id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
10,100
PlatziDev/pulse-editor
src/utils/set-selection-range.js
setSelectionRange
function setSelectionRange (selection = false, field) { if (!selection) return null if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } if (typeof field !== 'object') { throw new TypeError('The field must be an object.') } if (field.setSelectionRange) { field.setSelectionRange( selection.start, selection.end ) return null } if (!field.createTextRange) return null const range = field.createTextRange() range.collapse(true) range.moveStart('character', selection.end) range.moveEnd('character', selection.end) range.select() return null }
javascript
function setSelectionRange (selection = false, field) { if (!selection) return null if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } if (typeof field !== 'object') { throw new TypeError('The field must be an object.') } if (field.setSelectionRange) { field.setSelectionRange( selection.start, selection.end ) return null } if (!field.createTextRange) return null const range = field.createTextRange() range.collapse(true) range.moveStart('character', selection.end) range.moveEnd('character', selection.end) range.select() return null }
[ "function", "setSelectionRange", "(", "selection", "=", "false", ",", "field", ")", "{", "if", "(", "!", "selection", ")", "return", "null", "if", "(", "typeof", "selection", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'The selection must be an object.'", ")", "}", "if", "(", "typeof", "selection", ".", "start", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection start value must be a number.'", ")", "}", "if", "(", "typeof", "selection", ".", "end", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection end value must be a number.'", ")", "}", "if", "(", "typeof", "field", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'The field must be an object.'", ")", "}", "if", "(", "field", ".", "setSelectionRange", ")", "{", "field", ".", "setSelectionRange", "(", "selection", ".", "start", ",", "selection", ".", "end", ")", "return", "null", "}", "if", "(", "!", "field", ".", "createTextRange", ")", "return", "null", "const", "range", "=", "field", ".", "createTextRange", "(", ")", "range", ".", "collapse", "(", "true", ")", "range", ".", "moveStart", "(", "'character'", ",", "selection", ".", "end", ")", "range", ".", "moveEnd", "(", "'character'", ",", "selection", ".", "end", ")", "range", ".", "select", "(", ")", "return", "null", "}" ]
Set the content selection range in the given field input @param {Boolean} [selection=false] The selections positions @param {Element} field The DOMNode field
[ "Set", "the", "content", "selection", "range", "in", "the", "given", "field", "input" ]
897bc0e91b365e305c06c038f0192a21e5f5fe4a
https://github.com/PlatziDev/pulse-editor/blob/897bc0e91b365e305c06c038f0192a21e5f5fe4a/src/utils/set-selection-range.js#L6-L43
10,101
PlatziDev/pulse-editor
src/utils/create-change-event.js
createChangeEvent
function createChangeEvent (selected, selection, markdown, native, html) { if (typeof selected !== 'string') { throw new TypeError('The selected content value must be a string.') } if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } if (typeof markdown !== 'string') { throw new TypeError('The markdown content value must be a string.') } if (typeof native !== 'object') { throw new TypeError('The native event must be an object.') } if (typeof html !== 'string') { throw new TypeError('The html content value must be a string.') } return { selected, selection, markdown, native, html } }
javascript
function createChangeEvent (selected, selection, markdown, native, html) { if (typeof selected !== 'string') { throw new TypeError('The selected content value must be a string.') } if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } if (typeof markdown !== 'string') { throw new TypeError('The markdown content value must be a string.') } if (typeof native !== 'object') { throw new TypeError('The native event must be an object.') } if (typeof html !== 'string') { throw new TypeError('The html content value must be a string.') } return { selected, selection, markdown, native, html } }
[ "function", "createChangeEvent", "(", "selected", ",", "selection", ",", "markdown", ",", "native", ",", "html", ")", "{", "if", "(", "typeof", "selected", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The selected content value must be a string.'", ")", "}", "if", "(", "typeof", "selection", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'The selection must be an object.'", ")", "}", "if", "(", "typeof", "selection", ".", "start", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection start value must be a number.'", ")", "}", "if", "(", "typeof", "selection", ".", "end", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection end value must be a number.'", ")", "}", "if", "(", "typeof", "markdown", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The markdown content value must be a string.'", ")", "}", "if", "(", "typeof", "native", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'The native event must be an object.'", ")", "}", "if", "(", "typeof", "html", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The html content value must be a string.'", ")", "}", "return", "{", "selected", ",", "selection", ",", "markdown", ",", "native", ",", "html", "}", "}" ]
Create a ChangeEvent object @param {string} selected The selected text @param {SelectionType} selection The selection position @param {string} markdown The current value @param {Object} native The native triggered DOM event @param {string} html The parsed value as HTML @return {ChangeEventType} The ChangeEvent object
[ "Create", "a", "ChangeEvent", "object" ]
897bc0e91b365e305c06c038f0192a21e5f5fe4a
https://github.com/PlatziDev/pulse-editor/blob/897bc0e91b365e305c06c038f0192a21e5f5fe4a/src/utils/create-change-event.js#L10-L46
10,102
PlatziDev/pulse-editor
src/utils/update-content.js
updateContent
function updateContent (content, selection, updated) { if (typeof content !== 'string') { throw new TypeError('The content value must be a string.') } if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } if (typeof updated !== 'string') { throw new TypeError('The updated content value must be a string.') } return content.slice(0, selection.start) + updated + content.slice(selection.end) }
javascript
function updateContent (content, selection, updated) { if (typeof content !== 'string') { throw new TypeError('The content value must be a string.') } if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } if (typeof updated !== 'string') { throw new TypeError('The updated content value must be a string.') } return content.slice(0, selection.start) + updated + content.slice(selection.end) }
[ "function", "updateContent", "(", "content", ",", "selection", ",", "updated", ")", "{", "if", "(", "typeof", "content", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The content value must be a string.'", ")", "}", "if", "(", "typeof", "selection", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'The selection must be an object.'", ")", "}", "if", "(", "typeof", "selection", ".", "start", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection start value must be a number.'", ")", "}", "if", "(", "typeof", "selection", ".", "end", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection end value must be a number.'", ")", "}", "if", "(", "typeof", "updated", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The updated content value must be a string.'", ")", "}", "return", "content", ".", "slice", "(", "0", ",", "selection", ".", "start", ")", "+", "updated", "+", "content", ".", "slice", "(", "selection", ".", "end", ")", "}" ]
Update the selected content with the updated content in the given full content @param {string} content The full content string @param {SelectionType} selection The selections positions @param {string} updated The update slice of content @return {string} The final updated content string
[ "Update", "the", "selected", "content", "with", "the", "updated", "content", "in", "the", "given", "full", "content" ]
897bc0e91b365e305c06c038f0192a21e5f5fe4a
https://github.com/PlatziDev/pulse-editor/blob/897bc0e91b365e305c06c038f0192a21e5f5fe4a/src/utils/update-content.js#L8-L30
10,103
PlatziDev/pulse-editor
src/utils/get-selected.js
getSelected
function getSelected (content, selection) { if (typeof content !== 'string') { throw new TypeError('The content must be a string.') } if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } return content.slice(selection.start, selection.end) }
javascript
function getSelected (content, selection) { if (typeof content !== 'string') { throw new TypeError('The content must be a string.') } if (typeof selection !== 'object') { throw new TypeError('The selection must be an object.') } if (typeof selection.start !== 'number') { throw new TypeError('The selection start value must be a number.') } if (typeof selection.end !== 'number') { throw new TypeError('The selection end value must be a number.') } return content.slice(selection.start, selection.end) }
[ "function", "getSelected", "(", "content", ",", "selection", ")", "{", "if", "(", "typeof", "content", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'The content must be a string.'", ")", "}", "if", "(", "typeof", "selection", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'The selection must be an object.'", ")", "}", "if", "(", "typeof", "selection", ".", "start", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection start value must be a number.'", ")", "}", "if", "(", "typeof", "selection", ".", "end", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'The selection end value must be a number.'", ")", "}", "return", "content", ".", "slice", "(", "selection", ".", "start", ",", "selection", ".", "end", ")", "}" ]
Get the piece of content selected from a full content stringa and the selections positios @param {string} content The full content string @param {SelectionType} selection The selections positions @return {string} The sliced string
[ "Get", "the", "piece", "of", "content", "selected", "from", "a", "full", "content", "stringa", "and", "the", "selections", "positios" ]
897bc0e91b365e305c06c038f0192a21e5f5fe4a
https://github.com/PlatziDev/pulse-editor/blob/897bc0e91b365e305c06c038f0192a21e5f5fe4a/src/utils/get-selected.js#L8-L26
10,104
PlatziDev/pulse-editor
src/buttons/base.js
BaseButton
function BaseButton (props) { return ( <button {...props} className={props.className} onClick={props.onClick} name={props.name} disabled={props.disabled} type='button' children={props.children} /> ) }
javascript
function BaseButton (props) { return ( <button {...props} className={props.className} onClick={props.onClick} name={props.name} disabled={props.disabled} type='button' children={props.children} /> ) }
[ "function", "BaseButton", "(", "props", ")", "{", "return", "(", "<", "button", "{", "...", "props", "}", "className", "=", "{", "props", ".", "className", "}", "onClick", "=", "{", "props", ".", "onClick", "}", "name", "=", "{", "props", ".", "name", "}", "disabled", "=", "{", "props", ".", "disabled", "}", "type", "=", "'button'", "children", "=", "{", "props", ".", "children", "}", "/", ">", ")", "}" ]
The basic button without any functionality @param {Object} props The base button props
[ "The", "basic", "button", "without", "any", "functionality" ]
897bc0e91b365e305c06c038f0192a21e5f5fe4a
https://github.com/PlatziDev/pulse-editor/blob/897bc0e91b365e305c06c038f0192a21e5f5fe4a/src/buttons/base.js#L10-L22
10,105
uber/tchannel-node
request-handler.js
RequestCallbackHandler
function RequestCallbackHandler(callback, thisp) { var self = this; self.callback = callback; self.thisp = thisp || self; }
javascript
function RequestCallbackHandler(callback, thisp) { var self = this; self.callback = callback; self.thisp = thisp || self; }
[ "function", "RequestCallbackHandler", "(", "callback", ",", "thisp", ")", "{", "var", "self", "=", "this", ";", "self", ".", "callback", "=", "callback", ";", "self", ".", "thisp", "=", "thisp", "||", "self", ";", "}" ]
The non-streamed request handler is only for the cases where neither the request or response can have streams. In this case, a req.stream indicates that the request is fragmented across multiple frames.
[ "The", "non", "-", "streamed", "request", "handler", "is", "only", "for", "the", "cases", "where", "neither", "the", "request", "or", "response", "can", "have", "streams", ".", "In", "this", "case", "a", "req", ".", "stream", "indicates", "that", "the", "request", "is", "fragmented", "across", "multiple", "frames", "." ]
d13525e0e157402726c91f05c788ce56dafbe3eb
https://github.com/uber/tchannel-node/blob/d13525e0e157402726c91f05c788ce56dafbe3eb/request-handler.js#L46-L50
10,106
uber/tchannel-node
request-handler.js
StreamedRequestCallbackHandler
function StreamedRequestCallbackHandler(callback, thisp) { var self = this; self.callback = callback; self.thisp = thisp || self; }
javascript
function StreamedRequestCallbackHandler(callback, thisp) { var self = this; self.callback = callback; self.thisp = thisp || self; }
[ "function", "StreamedRequestCallbackHandler", "(", "callback", ",", "thisp", ")", "{", "var", "self", "=", "this", ";", "self", ".", "callback", "=", "callback", ";", "self", ".", "thisp", "=", "thisp", "||", "self", ";", "}" ]
The streamed request handler is for cases where the handler function elects to deal with whether req.streamed and whether res.streamed. req.streamed may indicated either a streaming request or a fragmented request and the handler must distinguish the cases.
[ "The", "streamed", "request", "handler", "is", "for", "cases", "where", "the", "handler", "function", "elects", "to", "deal", "with", "whether", "req", ".", "streamed", "and", "whether", "res", ".", "streamed", ".", "req", ".", "streamed", "may", "indicated", "either", "a", "streaming", "request", "or", "a", "fragmented", "request", "and", "the", "handler", "must", "distinguish", "the", "cases", "." ]
d13525e0e157402726c91f05c788ce56dafbe3eb
https://github.com/uber/tchannel-node/blob/d13525e0e157402726c91f05c788ce56dafbe3eb/request-handler.js#L86-L90
10,107
uber/tchannel-node
v2/call.js
allocifyPoolFn
function allocifyPoolFn(fn, ResultCons) { return allocFn; function allocFn(arg1, arg2, arg3) { return fn(new ResultCons(), arg1, arg2, arg3); } }
javascript
function allocifyPoolFn(fn, ResultCons) { return allocFn; function allocFn(arg1, arg2, arg3) { return fn(new ResultCons(), arg1, arg2, arg3); } }
[ "function", "allocifyPoolFn", "(", "fn", ",", "ResultCons", ")", "{", "return", "allocFn", ";", "function", "allocFn", "(", "arg1", ",", "arg2", ",", "arg3", ")", "{", "return", "fn", "(", "new", "ResultCons", "(", ")", ",", "arg1", ",", "arg2", ",", "arg3", ")", ";", "}", "}" ]
Calls a pooled function and conveniently allocates a response object for it
[ "Calls", "a", "pooled", "function", "and", "conveniently", "allocates", "a", "response", "object", "for", "it" ]
d13525e0e157402726c91f05c788ce56dafbe3eb
https://github.com/uber/tchannel-node/blob/d13525e0e157402726c91f05c788ce56dafbe3eb/v2/call.js#L74-L80
10,108
uber/tchannel-node
benchmarks/compare.js
descStats
function descStats(sample) { var S = [].concat(sample); S.sort(function sortOrder(a, b) { return a - b; }); var N = S.length; var q1 = S[Math.floor(0.25 * N)]; var q2 = S[Math.floor(0.50 * N)]; var q3 = S[Math.floor(0.70 * N)]; var iqr = q3 - q1; var tol = 3 * iqr / 2; var hi = q3 + tol; var whiIndex = N; while (--whiIndex > 0) { if (S[whiIndex] <= hi) { break; } } var whiPct = (whiIndex + 1) / N; var whi = S[whiIndex]; return { min: S[0], max: S[N - 1], q1: q1, q2: q2, q3: q3, hi: hi, whi: whi, whiPct: whiPct }; }
javascript
function descStats(sample) { var S = [].concat(sample); S.sort(function sortOrder(a, b) { return a - b; }); var N = S.length; var q1 = S[Math.floor(0.25 * N)]; var q2 = S[Math.floor(0.50 * N)]; var q3 = S[Math.floor(0.70 * N)]; var iqr = q3 - q1; var tol = 3 * iqr / 2; var hi = q3 + tol; var whiIndex = N; while (--whiIndex > 0) { if (S[whiIndex] <= hi) { break; } } var whiPct = (whiIndex + 1) / N; var whi = S[whiIndex]; return { min: S[0], max: S[N - 1], q1: q1, q2: q2, q3: q3, hi: hi, whi: whi, whiPct: whiPct }; }
[ "function", "descStats", "(", "sample", ")", "{", "var", "S", "=", "[", "]", ".", "concat", "(", "sample", ")", ";", "S", ".", "sort", "(", "function", "sortOrder", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", ")", ";", "var", "N", "=", "S", ".", "length", ";", "var", "q1", "=", "S", "[", "Math", ".", "floor", "(", "0.25", "*", "N", ")", "]", ";", "var", "q2", "=", "S", "[", "Math", ".", "floor", "(", "0.50", "*", "N", ")", "]", ";", "var", "q3", "=", "S", "[", "Math", ".", "floor", "(", "0.70", "*", "N", ")", "]", ";", "var", "iqr", "=", "q3", "-", "q1", ";", "var", "tol", "=", "3", "*", "iqr", "/", "2", ";", "var", "hi", "=", "q3", "+", "tol", ";", "var", "whiIndex", "=", "N", ";", "while", "(", "--", "whiIndex", ">", "0", ")", "{", "if", "(", "S", "[", "whiIndex", "]", "<=", "hi", ")", "{", "break", ";", "}", "}", "var", "whiPct", "=", "(", "whiIndex", "+", "1", ")", "/", "N", ";", "var", "whi", "=", "S", "[", "whiIndex", "]", ";", "return", "{", "min", ":", "S", "[", "0", "]", ",", "max", ":", "S", "[", "N", "-", "1", "]", ",", "q1", ":", "q1", ",", "q2", ":", "q2", ",", "q3", ":", "q3", ",", "hi", ":", "hi", ",", "whi", ":", "whi", ",", "whiPct", ":", "whiPct", "}", ";", "}" ]
return basic descriptive stats of some numerical sample
[ "return", "basic", "descriptive", "stats", "of", "some", "numerical", "sample" ]
d13525e0e157402726c91f05c788ce56dafbe3eb
https://github.com/uber/tchannel-node/blob/d13525e0e157402726c91f05c788ce56dafbe3eb/benchmarks/compare.js#L108-L138
10,109
apigee-127/sway
lib/types/parameter.js
Parameter
function Parameter (opOrPathObject, definition, definitionFullyResolved, pathToDefinition) { // Assign local properties this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.pathToDefinition = pathToDefinition; this.ptr = JsonRefs.pathToPtr(pathToDefinition); if (_.has(opOrPathObject, 'consumes')) { this.operationObject = opOrPathObject; this.pathObject = opOrPathObject.pathObject; } else { this.operationObject = undefined; this.pathObject = opOrPathObject; } // Assign local properties from the OpenAPI Parameter Object definition _.assign(this, definitionFullyResolved); if (_.isUndefined(this.schema)) { this.schema = helpers.computeParameterSchema(definitionFullyResolved); } this.pathObject.apiDefinition._debug(' %s%s (in: %s) at %s', _.isUndefined(this.operationObject) ? '' : ' ', definitionFullyResolved.name, definitionFullyResolved.in, this.ptr); }
javascript
function Parameter (opOrPathObject, definition, definitionFullyResolved, pathToDefinition) { // Assign local properties this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.pathToDefinition = pathToDefinition; this.ptr = JsonRefs.pathToPtr(pathToDefinition); if (_.has(opOrPathObject, 'consumes')) { this.operationObject = opOrPathObject; this.pathObject = opOrPathObject.pathObject; } else { this.operationObject = undefined; this.pathObject = opOrPathObject; } // Assign local properties from the OpenAPI Parameter Object definition _.assign(this, definitionFullyResolved); if (_.isUndefined(this.schema)) { this.schema = helpers.computeParameterSchema(definitionFullyResolved); } this.pathObject.apiDefinition._debug(' %s%s (in: %s) at %s', _.isUndefined(this.operationObject) ? '' : ' ', definitionFullyResolved.name, definitionFullyResolved.in, this.ptr); }
[ "function", "Parameter", "(", "opOrPathObject", ",", "definition", ",", "definitionFullyResolved", ",", "pathToDefinition", ")", "{", "// Assign local properties", "this", ".", "definition", "=", "definition", ";", "this", ".", "definitionFullyResolved", "=", "definitionFullyResolved", ";", "this", ".", "pathToDefinition", "=", "pathToDefinition", ";", "this", ".", "ptr", "=", "JsonRefs", ".", "pathToPtr", "(", "pathToDefinition", ")", ";", "if", "(", "_", ".", "has", "(", "opOrPathObject", ",", "'consumes'", ")", ")", "{", "this", ".", "operationObject", "=", "opOrPathObject", ";", "this", ".", "pathObject", "=", "opOrPathObject", ".", "pathObject", ";", "}", "else", "{", "this", ".", "operationObject", "=", "undefined", ";", "this", ".", "pathObject", "=", "opOrPathObject", ";", "}", "// Assign local properties from the OpenAPI Parameter Object definition", "_", ".", "assign", "(", "this", ",", "definitionFullyResolved", ")", ";", "if", "(", "_", ".", "isUndefined", "(", "this", ".", "schema", ")", ")", "{", "this", ".", "schema", "=", "helpers", ".", "computeParameterSchema", "(", "definitionFullyResolved", ")", ";", "}", "this", ".", "pathObject", ".", "apiDefinition", ".", "_debug", "(", "' %s%s (in: %s) at %s'", ",", "_", ".", "isUndefined", "(", "this", ".", "operationObject", ")", "?", "''", ":", "' '", ",", "definitionFullyResolved", ".", "name", ",", "definitionFullyResolved", ".", "in", ",", "this", ".", "ptr", ")", ";", "}" ]
The OpenAPI Parameter object. **Note:** Do not use directly. **Extra Properties:** Other than the documented properties, this object also exposes all properties of the [OpenAPI Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameterObject). @param {module:sway.Operation|module:sway.Path} opOrPathObject - The `Operation` or `Path` object @param {object} definition - The parameter definition *(The raw parameter definition __after__ remote references were resolved)* @param {object} definitionFullyResolved - The parameter definition with all of its resolvable references resolved @param {string[]} pathToDefinition - The path segments to the parameter definition @property {object} definition - The parameter definition *(The raw parameter definition __after__ remote references were resolved)* @property {object} definitionFullyResolved - The parameter definition with all of its resolvable references resolved @property {module:sway.Operation} operationObject - The `Operation` object the parameter belongs to *(Can be `undefined` for path-level parameters)* @property {module:sway.Path} pathObject - The `Path` object the parameter belongs to @property {string[]} pathToDefinition - The path segments to the parameter definition @property {string} ptr - The JSON Pointer to the parameter definition @property {object} schema - The JSON Schema for the parameter *(For non-body parameters, this is a computed value)* @constructor @memberof module:sway
[ "The", "OpenAPI", "Parameter", "object", "." ]
e9ad6e81af41f526567e9d5a0f150e59e429e513
https://github.com/apigee-127/sway/blob/e9ad6e81af41f526567e9d5a0f150e59e429e513/lib/types/parameter.js#L61-L88
10,110
apigee-127/sway
lib/validation/validators.js
validateStructure
function validateStructure (apiDefinition) { var results = helpers.validateAgainstSchema(helpers.getJSONSchemaValidator(), swaggerSchema, apiDefinition.definitionFullyResolved); // Make complex JSON Schema validation errors easier to understand (Issue 15) results.errors = results.errors.map(function (error) { var defType = ['additionalProperties', 'items'].indexOf(error.path[error.path.length - 1]) > -1 ? 'schema' : error.path[error.path.length - 2]; if (['ANY_OF_MISSING', 'ONE_OF_MISSING'].indexOf(error.code) > -1) { switch (defType) { case 'parameters': defType = 'parameter'; break; case 'responses': defType = 'response'; break; case 'schema': defType += ' ' + error.path[error.path.length - 1]; // no default } error.message = 'Not a valid ' + defType + ' definition'; } return error; }); // Treat invalid/missing references as structural errors _.each(apiDefinition.references, function (refDetails, refPtr) { var refPath = JsonRefs.pathFromPtr(refPtr); var err; if (refDetails.missing) { err = { code: 'UNRESOLVABLE_REFERENCE', message: 'Reference could not be resolved: ' + refDetails.uri, path: refPath.concat('$ref') }; if (_.has(refDetails, 'error')) { err.error = refDetails.error; } results.errors.push(err); } else if (refDetails.type === 'invalid') { results.errors.push({ code: 'INVALID_REFERENCE', message: refDetails.error || 'Invalid JSON Reference', path: refPath.concat('$ref') }); } else if (_.has(refDetails, 'warning')) { // json-refs only creates warnings for JSON References with superfluous properties which will be ignored results.warnings.push({ code: 'EXTRA_REFERENCE_PROPERTIES', message: refDetails.warning, path: refPath }); } }); return results; }
javascript
function validateStructure (apiDefinition) { var results = helpers.validateAgainstSchema(helpers.getJSONSchemaValidator(), swaggerSchema, apiDefinition.definitionFullyResolved); // Make complex JSON Schema validation errors easier to understand (Issue 15) results.errors = results.errors.map(function (error) { var defType = ['additionalProperties', 'items'].indexOf(error.path[error.path.length - 1]) > -1 ? 'schema' : error.path[error.path.length - 2]; if (['ANY_OF_MISSING', 'ONE_OF_MISSING'].indexOf(error.code) > -1) { switch (defType) { case 'parameters': defType = 'parameter'; break; case 'responses': defType = 'response'; break; case 'schema': defType += ' ' + error.path[error.path.length - 1]; // no default } error.message = 'Not a valid ' + defType + ' definition'; } return error; }); // Treat invalid/missing references as structural errors _.each(apiDefinition.references, function (refDetails, refPtr) { var refPath = JsonRefs.pathFromPtr(refPtr); var err; if (refDetails.missing) { err = { code: 'UNRESOLVABLE_REFERENCE', message: 'Reference could not be resolved: ' + refDetails.uri, path: refPath.concat('$ref') }; if (_.has(refDetails, 'error')) { err.error = refDetails.error; } results.errors.push(err); } else if (refDetails.type === 'invalid') { results.errors.push({ code: 'INVALID_REFERENCE', message: refDetails.error || 'Invalid JSON Reference', path: refPath.concat('$ref') }); } else if (_.has(refDetails, 'warning')) { // json-refs only creates warnings for JSON References with superfluous properties which will be ignored results.warnings.push({ code: 'EXTRA_REFERENCE_PROPERTIES', message: refDetails.warning, path: refPath }); } }); return results; }
[ "function", "validateStructure", "(", "apiDefinition", ")", "{", "var", "results", "=", "helpers", ".", "validateAgainstSchema", "(", "helpers", ".", "getJSONSchemaValidator", "(", ")", ",", "swaggerSchema", ",", "apiDefinition", ".", "definitionFullyResolved", ")", ";", "// Make complex JSON Schema validation errors easier to understand (Issue 15)", "results", ".", "errors", "=", "results", ".", "errors", ".", "map", "(", "function", "(", "error", ")", "{", "var", "defType", "=", "[", "'additionalProperties'", ",", "'items'", "]", ".", "indexOf", "(", "error", ".", "path", "[", "error", ".", "path", ".", "length", "-", "1", "]", ")", ">", "-", "1", "?", "'schema'", ":", "error", ".", "path", "[", "error", ".", "path", ".", "length", "-", "2", "]", ";", "if", "(", "[", "'ANY_OF_MISSING'", ",", "'ONE_OF_MISSING'", "]", ".", "indexOf", "(", "error", ".", "code", ")", ">", "-", "1", ")", "{", "switch", "(", "defType", ")", "{", "case", "'parameters'", ":", "defType", "=", "'parameter'", ";", "break", ";", "case", "'responses'", ":", "defType", "=", "'response'", ";", "break", ";", "case", "'schema'", ":", "defType", "+=", "' '", "+", "error", ".", "path", "[", "error", ".", "path", ".", "length", "-", "1", "]", ";", "// no default", "}", "error", ".", "message", "=", "'Not a valid '", "+", "defType", "+", "' definition'", ";", "}", "return", "error", ";", "}", ")", ";", "// Treat invalid/missing references as structural errors", "_", ".", "each", "(", "apiDefinition", ".", "references", ",", "function", "(", "refDetails", ",", "refPtr", ")", "{", "var", "refPath", "=", "JsonRefs", ".", "pathFromPtr", "(", "refPtr", ")", ";", "var", "err", ";", "if", "(", "refDetails", ".", "missing", ")", "{", "err", "=", "{", "code", ":", "'UNRESOLVABLE_REFERENCE'", ",", "message", ":", "'Reference could not be resolved: '", "+", "refDetails", ".", "uri", ",", "path", ":", "refPath", ".", "concat", "(", "'$ref'", ")", "}", ";", "if", "(", "_", ".", "has", "(", "refDetails", ",", "'error'", ")", ")", "{", "err", ".", "error", "=", "refDetails", ".", "error", ";", "}", "results", ".", "errors", ".", "push", "(", "err", ")", ";", "}", "else", "if", "(", "refDetails", ".", "type", "===", "'invalid'", ")", "{", "results", ".", "errors", ".", "push", "(", "{", "code", ":", "'INVALID_REFERENCE'", ",", "message", ":", "refDetails", ".", "error", "||", "'Invalid JSON Reference'", ",", "path", ":", "refPath", ".", "concat", "(", "'$ref'", ")", "}", ")", ";", "}", "else", "if", "(", "_", ".", "has", "(", "refDetails", ",", "'warning'", ")", ")", "{", "// json-refs only creates warnings for JSON References with superfluous properties which will be ignored", "results", ".", "warnings", ".", "push", "(", "{", "code", ":", "'EXTRA_REFERENCE_PROPERTIES'", ",", "message", ":", "refDetails", ".", "warning", ",", "path", ":", "refPath", "}", ")", ";", "}", "}", ")", ";", "return", "results", ";", "}" ]
Validates the resolved OpenAPI Definition against the OpenAPI 3.x JSON Schema. @param {ApiDefinition} apiDefinition - The `ApiDefinition` object @returns {object} Object containing the errors and warnings of the validation
[ "Validates", "the", "resolved", "OpenAPI", "Definition", "against", "the", "OpenAPI", "3", ".", "x", "JSON", "Schema", "." ]
e9ad6e81af41f526567e9d5a0f150e59e429e513
https://github.com/apigee-127/sway/blob/e9ad6e81af41f526567e9d5a0f150e59e429e513/lib/validation/validators.js#L107-L174
10,111
apigee-127/sway
lib/types/api-definition.js
ApiDefinition
function ApiDefinition (definition, definitionRemotesResolved, definitionFullyResolved, references, options) { var that = this; debug('Creating ApiDefinition from %s', _.isString(options.definition) ? options.definition : 'the provided OpenAPI definition'); // Assign this so other object can use it this._debug = debug; // Assign local properties this.customFormats = {}; this.customFormatGenerators = {}; this.customValidators = []; this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.definitionRemotesResolved = definitionRemotesResolved; this.documentationUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md'; this.options = options; this.references = references; this.version = '2.0'; // Assign local properties from the OpenAPI Object definition _.assign(this, definition); // Register custom formats _.each(options.customFormats, _.bind(ApiDefinition.prototype.registerFormat, this)); // Register custom formats _.each(options.customFormatGenerators, _.bind(ApiDefinition.prototype.registerFormatGenerator, this)); // Register custom validators _.each(options.customValidators, _.bind(ApiDefinition.prototype.registerValidator, this)); debug(' Paths:'); // Create the Path objects this.pathObjects = _.map(definitionFullyResolved.paths, function (pathDef, path) { return new Path(that, path, _.get(definitionRemotesResolved, ['paths', path]), pathDef, ['paths', path]); }); }
javascript
function ApiDefinition (definition, definitionRemotesResolved, definitionFullyResolved, references, options) { var that = this; debug('Creating ApiDefinition from %s', _.isString(options.definition) ? options.definition : 'the provided OpenAPI definition'); // Assign this so other object can use it this._debug = debug; // Assign local properties this.customFormats = {}; this.customFormatGenerators = {}; this.customValidators = []; this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.definitionRemotesResolved = definitionRemotesResolved; this.documentationUrl = 'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md'; this.options = options; this.references = references; this.version = '2.0'; // Assign local properties from the OpenAPI Object definition _.assign(this, definition); // Register custom formats _.each(options.customFormats, _.bind(ApiDefinition.prototype.registerFormat, this)); // Register custom formats _.each(options.customFormatGenerators, _.bind(ApiDefinition.prototype.registerFormatGenerator, this)); // Register custom validators _.each(options.customValidators, _.bind(ApiDefinition.prototype.registerValidator, this)); debug(' Paths:'); // Create the Path objects this.pathObjects = _.map(definitionFullyResolved.paths, function (pathDef, path) { return new Path(that, path, _.get(definitionRemotesResolved, ['paths', path]), pathDef, ['paths', path]); }); }
[ "function", "ApiDefinition", "(", "definition", ",", "definitionRemotesResolved", ",", "definitionFullyResolved", ",", "references", ",", "options", ")", "{", "var", "that", "=", "this", ";", "debug", "(", "'Creating ApiDefinition from %s'", ",", "_", ".", "isString", "(", "options", ".", "definition", ")", "?", "options", ".", "definition", ":", "'the provided OpenAPI definition'", ")", ";", "// Assign this so other object can use it", "this", ".", "_debug", "=", "debug", ";", "// Assign local properties", "this", ".", "customFormats", "=", "{", "}", ";", "this", ".", "customFormatGenerators", "=", "{", "}", ";", "this", ".", "customValidators", "=", "[", "]", ";", "this", ".", "definition", "=", "definition", ";", "this", ".", "definitionFullyResolved", "=", "definitionFullyResolved", ";", "this", ".", "definitionRemotesResolved", "=", "definitionRemotesResolved", ";", "this", ".", "documentationUrl", "=", "'https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md'", ";", "this", ".", "options", "=", "options", ";", "this", ".", "references", "=", "references", ";", "this", ".", "version", "=", "'2.0'", ";", "// Assign local properties from the OpenAPI Object definition", "_", ".", "assign", "(", "this", ",", "definition", ")", ";", "// Register custom formats", "_", ".", "each", "(", "options", ".", "customFormats", ",", "_", ".", "bind", "(", "ApiDefinition", ".", "prototype", ".", "registerFormat", ",", "this", ")", ")", ";", "// Register custom formats", "_", ".", "each", "(", "options", ".", "customFormatGenerators", ",", "_", ".", "bind", "(", "ApiDefinition", ".", "prototype", ".", "registerFormatGenerator", ",", "this", ")", ")", ";", "// Register custom validators", "_", ".", "each", "(", "options", ".", "customValidators", ",", "_", ".", "bind", "(", "ApiDefinition", ".", "prototype", ".", "registerValidator", ",", "this", ")", ")", ";", "debug", "(", "' Paths:'", ")", ";", "// Create the Path objects", "this", ".", "pathObjects", "=", "_", ".", "map", "(", "definitionFullyResolved", ".", "paths", ",", "function", "(", "pathDef", ",", "path", ")", "{", "return", "new", "Path", "(", "that", ",", "path", ",", "_", ".", "get", "(", "definitionRemotesResolved", ",", "[", "'paths'", ",", "path", "]", ")", ",", "pathDef", ",", "[", "'paths'", ",", "path", "]", ")", ";", "}", ")", ";", "}" ]
The OpenAPI Definition object. **Note:** Do not use directly. **Extra Properties:** Other than the documented properties, this object also exposes all properties of the [OpenAPI Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#openapi-object). @param {object} definition - The original OpenAPI definition @param {object} definitionRemotesResolved - The OpenAPI definition with all of its remote references resolved @param {object} definitionFullyResolved - The OpenAPI definition with all of its references resolved @param {object} references - The location and resolution of the resolved references in the OpenAPI definition @param {object} options - The options passed to ApiDefinition.create @property {object} customFormats - The key/value pair of custom formats *(The keys are the format name and the values are async functions. See [ZSchema Custom Formats](https://github.com/zaggino/z-schema#register-a-custom-format))* @property {object} customFormatGenerators - The key/value pair of custom format generators *(The keys are the format name and the values are functions. See [json-schema-mocker Custom Format](https://github.com/json-schema-faker/json-schema-faker#custom-formats))* @property {module:sway.DocumentValidationFunction[]} customValidators - The array of custom validators @property {object} definition - The original OpenAPI definition @property {object} definitionRemotesResolved - The OpenAPI definition with only its remote references resolved *(This means all references to external/remote documents are replaced with its dereferenced value but all local references are left unresolved.)* @property {object} definitionFullyResolved - The OpenAPI definition with all of its resolvable references resolved *(This means that all resolvable references are replaced with their dereferenced value.)* @property {string} documentationUrl - The URL to the OpenAPI documentation @property {module:sway.Path[]} pathObjects - The unique `Path` objects @property {object} options - The options passed to the constructor @property {object} references - The reference metadata *(See [JsonRefs~ResolvedRefDetails](https://github.com/whitlockjc/json-refs/blob/master/docs/API.md#module_JsonRefs..ResolvedRefDetails))* @property {string} version - The OpenAPI version @constructor @memberof module:sway
[ "The", "OpenAPI", "Definition", "object", "." ]
e9ad6e81af41f526567e9d5a0f150e59e429e513
https://github.com/apigee-127/sway/blob/e9ad6e81af41f526567e9d5a0f150e59e429e513/lib/types/api-definition.js#L69-L112
10,112
apigee-127/sway
lib/types/path.js
Path
function Path (apiDefinition, path, definition, definitionFullyResolved, pathToDefinition) { var basePathPrefix = apiDefinition.definitionFullyResolved.basePath || '/'; var that = this; var sanitizedPath; // TODO: We could/should refactor this to use the path module // Remove trailing slash from the basePathPrefix so we do not end up with double slashes if (basePathPrefix.charAt(basePathPrefix.length - 1) === '/') { basePathPrefix = basePathPrefix.substring(0, basePathPrefix.length - 1); } // Converts OpenAPI parameters to Express-style parameters, and also escapes all path-to-regexp special characters // // @see: https://github.com/pillarjs/path-to-regexp/issues/76#issuecomment-219085357 sanitizedPath = basePathPrefix + path.replace('(', '\\(') // path-to-regexp .replace(')', '\\)') // path-to-regexp .replace(':', '\\:') // path-to-regexp .replace('*', '\\*') // path-to-regexp .replace('+', '\\+') // path-to-regexp .replace('?', '\\?') // path-to-regexp .replace(/\{/g, ':') // OpenAPI -> Express-style .replace(/\}/g, ''); // OpenAPI -> Express-style // Assign local properties this.apiDefinition = apiDefinition; this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.path = path; this.pathToDefinition = pathToDefinition; this.ptr = JsonRefs.pathToPtr(pathToDefinition); this.regexp = pathToRegexp(sanitizedPath, {sensitive: true}); // Assign local properties from the OpenAPI Path Object definition _.assign(this, definitionFullyResolved); this._debug = this.apiDefinition._debug; this._debug(' %s', this.path); this.parameterObjects = _.map(definitionFullyResolved.parameters, function (paramDef, index) { var pPath = pathToDefinition.concat(['parameters', index.toString()]); return new Parameter(that, _.get(apiDefinition.definitionRemotesResolved, pPath), paramDef, pPath); }); this._debug(' Operations:'); this.operationObjects = _.reduce(definitionFullyResolved, function (operations, operationDef, method) { var oPath = pathToDefinition.concat(method); if (supportedHttpMethods.indexOf(method) > -1) { operations.push(new Operation(that, method, _.get(apiDefinition.definitionRemotesResolved, oPath), operationDef, oPath)); } return operations; }, []); }
javascript
function Path (apiDefinition, path, definition, definitionFullyResolved, pathToDefinition) { var basePathPrefix = apiDefinition.definitionFullyResolved.basePath || '/'; var that = this; var sanitizedPath; // TODO: We could/should refactor this to use the path module // Remove trailing slash from the basePathPrefix so we do not end up with double slashes if (basePathPrefix.charAt(basePathPrefix.length - 1) === '/') { basePathPrefix = basePathPrefix.substring(0, basePathPrefix.length - 1); } // Converts OpenAPI parameters to Express-style parameters, and also escapes all path-to-regexp special characters // // @see: https://github.com/pillarjs/path-to-regexp/issues/76#issuecomment-219085357 sanitizedPath = basePathPrefix + path.replace('(', '\\(') // path-to-regexp .replace(')', '\\)') // path-to-regexp .replace(':', '\\:') // path-to-regexp .replace('*', '\\*') // path-to-regexp .replace('+', '\\+') // path-to-regexp .replace('?', '\\?') // path-to-regexp .replace(/\{/g, ':') // OpenAPI -> Express-style .replace(/\}/g, ''); // OpenAPI -> Express-style // Assign local properties this.apiDefinition = apiDefinition; this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.path = path; this.pathToDefinition = pathToDefinition; this.ptr = JsonRefs.pathToPtr(pathToDefinition); this.regexp = pathToRegexp(sanitizedPath, {sensitive: true}); // Assign local properties from the OpenAPI Path Object definition _.assign(this, definitionFullyResolved); this._debug = this.apiDefinition._debug; this._debug(' %s', this.path); this.parameterObjects = _.map(definitionFullyResolved.parameters, function (paramDef, index) { var pPath = pathToDefinition.concat(['parameters', index.toString()]); return new Parameter(that, _.get(apiDefinition.definitionRemotesResolved, pPath), paramDef, pPath); }); this._debug(' Operations:'); this.operationObjects = _.reduce(definitionFullyResolved, function (operations, operationDef, method) { var oPath = pathToDefinition.concat(method); if (supportedHttpMethods.indexOf(method) > -1) { operations.push(new Operation(that, method, _.get(apiDefinition.definitionRemotesResolved, oPath), operationDef, oPath)); } return operations; }, []); }
[ "function", "Path", "(", "apiDefinition", ",", "path", ",", "definition", ",", "definitionFullyResolved", ",", "pathToDefinition", ")", "{", "var", "basePathPrefix", "=", "apiDefinition", ".", "definitionFullyResolved", ".", "basePath", "||", "'/'", ";", "var", "that", "=", "this", ";", "var", "sanitizedPath", ";", "// TODO: We could/should refactor this to use the path module", "// Remove trailing slash from the basePathPrefix so we do not end up with double slashes", "if", "(", "basePathPrefix", ".", "charAt", "(", "basePathPrefix", ".", "length", "-", "1", ")", "===", "'/'", ")", "{", "basePathPrefix", "=", "basePathPrefix", ".", "substring", "(", "0", ",", "basePathPrefix", ".", "length", "-", "1", ")", ";", "}", "// Converts OpenAPI parameters to Express-style parameters, and also escapes all path-to-regexp special characters", "//", "// @see: https://github.com/pillarjs/path-to-regexp/issues/76#issuecomment-219085357", "sanitizedPath", "=", "basePathPrefix", "+", "path", ".", "replace", "(", "'('", ",", "'\\\\('", ")", "// path-to-regexp", ".", "replace", "(", "')'", ",", "'\\\\)'", ")", "// path-to-regexp", ".", "replace", "(", "':'", ",", "'\\\\:'", ")", "// path-to-regexp", ".", "replace", "(", "'*'", ",", "'\\\\*'", ")", "// path-to-regexp", ".", "replace", "(", "'+'", ",", "'\\\\+'", ")", "// path-to-regexp", ".", "replace", "(", "'?'", ",", "'\\\\?'", ")", "// path-to-regexp", ".", "replace", "(", "/", "\\{", "/", "g", ",", "':'", ")", "// OpenAPI -> Express-style", ".", "replace", "(", "/", "\\}", "/", "g", ",", "''", ")", ";", "// OpenAPI -> Express-style", "// Assign local properties", "this", ".", "apiDefinition", "=", "apiDefinition", ";", "this", ".", "definition", "=", "definition", ";", "this", ".", "definitionFullyResolved", "=", "definitionFullyResolved", ";", "this", ".", "path", "=", "path", ";", "this", ".", "pathToDefinition", "=", "pathToDefinition", ";", "this", ".", "ptr", "=", "JsonRefs", ".", "pathToPtr", "(", "pathToDefinition", ")", ";", "this", ".", "regexp", "=", "pathToRegexp", "(", "sanitizedPath", ",", "{", "sensitive", ":", "true", "}", ")", ";", "// Assign local properties from the OpenAPI Path Object definition", "_", ".", "assign", "(", "this", ",", "definitionFullyResolved", ")", ";", "this", ".", "_debug", "=", "this", ".", "apiDefinition", ".", "_debug", ";", "this", ".", "_debug", "(", "' %s'", ",", "this", ".", "path", ")", ";", "this", ".", "parameterObjects", "=", "_", ".", "map", "(", "definitionFullyResolved", ".", "parameters", ",", "function", "(", "paramDef", ",", "index", ")", "{", "var", "pPath", "=", "pathToDefinition", ".", "concat", "(", "[", "'parameters'", ",", "index", ".", "toString", "(", ")", "]", ")", ";", "return", "new", "Parameter", "(", "that", ",", "_", ".", "get", "(", "apiDefinition", ".", "definitionRemotesResolved", ",", "pPath", ")", ",", "paramDef", ",", "pPath", ")", ";", "}", ")", ";", "this", ".", "_debug", "(", "' Operations:'", ")", ";", "this", ".", "operationObjects", "=", "_", ".", "reduce", "(", "definitionFullyResolved", ",", "function", "(", "operations", ",", "operationDef", ",", "method", ")", "{", "var", "oPath", "=", "pathToDefinition", ".", "concat", "(", "method", ")", ";", "if", "(", "supportedHttpMethods", ".", "indexOf", "(", "method", ")", ">", "-", "1", ")", "{", "operations", ".", "push", "(", "new", "Operation", "(", "that", ",", "method", ",", "_", ".", "get", "(", "apiDefinition", ".", "definitionRemotesResolved", ",", "oPath", ")", ",", "operationDef", ",", "oPath", ")", ")", ";", "}", "return", "operations", ";", "}", ",", "[", "]", ")", ";", "}" ]
The Path object. **Note:** Do not use directly. **Extra Properties:** Other than the documented properties, this object also exposes all properties of the [OpenAPI Path Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathItemObject). @param {module:sway.ApiDefinition} apiDefinition - The `ApiDefinition` object @param {string} path - The path string @param {object} definition - The path definition *(The raw path definition __after__ remote references were resolved)* @param {object} definitionFullyResolved - The path definition with all of its resolvable references resolved @param {string[]} pathToDefinition - The path segments to the path definition @property {module:sway.ApiDefinition} apiDefinition - The `ApiDefinition` object @property {object} definition - The path definition *(The raw path definition __after__ remote references were resolved)* @property {object} definitionFullyResolved - The path definition with all of its resolvable references resolved @property {module:sway.Operation[]} operationObjects - The `Operation` objects @property {module:sway.Parameter[]} parameterObjects - The path-level `Parameter` objects @property {string} path - The path string @property {string[]} pathToDefinition - The path segments to the path definition @property {ptr} ptr - The JSON Pointer to the path @property {regexp} regexp - The `RegExp` used to match request paths against this path @constructor @memberof module:sway
[ "The", "Path", "object", "." ]
e9ad6e81af41f526567e9d5a0f150e59e429e513
https://github.com/apigee-127/sway/blob/e9ad6e81af41f526567e9d5a0f150e59e429e513/lib/types/path.js#L64-L124
10,113
apigee-127/sway
lib/types/response.js
Response
function Response (operationObject, statusCode, definition, definitionFullyResolved, pathToDefinition) { // Assign local properties this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.operationObject = operationObject; this.pathToDefinition = pathToDefinition; this.ptr = JsonRefs.pathToPtr(pathToDefinition); this.statusCode = statusCode; // Assign local properties from the OpenAPI Response Object definition _.assign(this, definitionFullyResolved); this.operationObject.pathObject.apiDefinition._debug(' %s at %s', statusCode, this.ptr); }
javascript
function Response (operationObject, statusCode, definition, definitionFullyResolved, pathToDefinition) { // Assign local properties this.definition = definition; this.definitionFullyResolved = definitionFullyResolved; this.operationObject = operationObject; this.pathToDefinition = pathToDefinition; this.ptr = JsonRefs.pathToPtr(pathToDefinition); this.statusCode = statusCode; // Assign local properties from the OpenAPI Response Object definition _.assign(this, definitionFullyResolved); this.operationObject.pathObject.apiDefinition._debug(' %s at %s', statusCode, this.ptr); }
[ "function", "Response", "(", "operationObject", ",", "statusCode", ",", "definition", ",", "definitionFullyResolved", ",", "pathToDefinition", ")", "{", "// Assign local properties", "this", ".", "definition", "=", "definition", ";", "this", ".", "definitionFullyResolved", "=", "definitionFullyResolved", ";", "this", ".", "operationObject", "=", "operationObject", ";", "this", ".", "pathToDefinition", "=", "pathToDefinition", ";", "this", ".", "ptr", "=", "JsonRefs", ".", "pathToPtr", "(", "pathToDefinition", ")", ";", "this", ".", "statusCode", "=", "statusCode", ";", "// Assign local properties from the OpenAPI Response Object definition", "_", ".", "assign", "(", "this", ",", "definitionFullyResolved", ")", ";", "this", ".", "operationObject", ".", "pathObject", ".", "apiDefinition", ".", "_debug", "(", "' %s at %s'", ",", "statusCode", ",", "this", ".", "ptr", ")", ";", "}" ]
The OpenAPI Response object. **Note:** Do not use directly. **Extra Properties:** Other than the documented properties, this object also exposes all properties of the [OpenAPI Response Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject). @param {module:sway.Operation} operationObject - The `Operation` object @param {string} statusCode - The status code @param {object} definition - The response definition *(The raw response definition __after__ remote references were resolved)* @param {object} definitionFullyResolved - The response definition with all of its resolvable references resolved @param {string[]} pathToDefinition - The path segments to the path definition @property {object} definition - The response definition *(The raw responsedefinition __after__ remote references were resolved)* @property {object} definitionFullyResolved - The response definition with all of its resolvable references resolved @property {module:sway.Operation} operationObject - The Operation object @property {string[]} pathToDefinition - The path segments to the path definition @property {string} ptr - The JSON Pointer to the response definition @property {string} statusCode - The status code @constructor @memberof module:sway
[ "The", "OpenAPI", "Response", "object", "." ]
e9ad6e81af41f526567e9d5a0f150e59e429e513
https://github.com/apigee-127/sway/blob/e9ad6e81af41f526567e9d5a0f150e59e429e513/lib/types/response.js#L60-L73
10,114
adaltas/node-nikita
packages/core/lib/misc/conditions.js
function({options}, succeed, skip) { return each(options.if_exec).call((cmd, next) => { this.log({ message: `Nikita \`if_exec\`: ${cmd}`, level: 'DEBUG', module: 'nikita/misc/conditions' }); return this.system.execute({ cmd: cmd, relax: true, stderr_log: false, stdin_log: false, stdout_log: false }, function(err, {code}) { this.log({ message: `Nikita \`if_exec\`: code is "${code}"`, level: 'INFO', module: 'nikita/misc/conditions' }); if (code === 0) { return next(); } else { return skip(); } }); }).next(succeed); }
javascript
function({options}, succeed, skip) { return each(options.if_exec).call((cmd, next) => { this.log({ message: `Nikita \`if_exec\`: ${cmd}`, level: 'DEBUG', module: 'nikita/misc/conditions' }); return this.system.execute({ cmd: cmd, relax: true, stderr_log: false, stdin_log: false, stdout_log: false }, function(err, {code}) { this.log({ message: `Nikita \`if_exec\`: code is "${code}"`, level: 'INFO', module: 'nikita/misc/conditions' }); if (code === 0) { return next(); } else { return skip(); } }); }).next(succeed); }
[ "function", "(", "{", "options", "}", ",", "succeed", ",", "skip", ")", "{", "return", "each", "(", "options", ".", "if_exec", ")", ".", "call", "(", "(", "cmd", ",", "next", ")", "=>", "{", "this", ".", "log", "(", "{", "message", ":", "`", "\\`", "\\`", "${", "cmd", "}", "`", ",", "level", ":", "'DEBUG'", ",", "module", ":", "'nikita/misc/conditions'", "}", ")", ";", "return", "this", ".", "system", ".", "execute", "(", "{", "cmd", ":", "cmd", ",", "relax", ":", "true", ",", "stderr_log", ":", "false", ",", "stdin_log", ":", "false", ",", "stdout_log", ":", "false", "}", ",", "function", "(", "err", ",", "{", "code", "}", ")", "{", "this", ".", "log", "(", "{", "message", ":", "`", "\\`", "\\`", "${", "code", "}", "`", ",", "level", ":", "'INFO'", ",", "module", ":", "'nikita/misc/conditions'", "}", ")", ";", "if", "(", "code", "===", "0", ")", "{", "return", "next", "(", ")", ";", "}", "else", "{", "return", "skip", "(", ")", ";", "}", "}", ")", ";", "}", ")", ".", "next", "(", "succeed", ")", ";", "}" ]
The callback `succeed` is called if all the provided command were executed successfully otherwise the callback `skip` is called.
[ "The", "callback", "succeed", "is", "called", "if", "all", "the", "provided", "command", "were", "executed", "successfully", "otherwise", "the", "callback", "skip", "is", "called", "." ]
35c4b249da7f3fe3550f1679989d7795969fe6a6
https://github.com/adaltas/node-nikita/blob/35c4b249da7f3fe3550f1679989d7795969fe6a6/packages/core/lib/misc/conditions.js#L207-L233
10,115
adaltas/node-nikita
packages/core/lib/misc/conditions.js
function({options}, succeed, skip) { // Default to `options.target` if "true" if (typeof options.if_exists === 'boolean' && options.target) { options.if_exists = options.if_exists ? [options.target] : null; } return each(options.if_exists).call((if_exists, next) => { return this.fs.exists({ target: if_exists }, (err, {exists}) => { if (exists) { this.log({ message: `File exists ${if_exists}, continuing`, level: 'DEBUG', module: 'nikita/misc/conditions' }); return next(); } else { this.log({ message: `File doesnt exists ${if_exists}, skipping`, level: 'INFO', module: 'nikita/misc/conditions' }); return skip(); } }); }).next(succeed); }
javascript
function({options}, succeed, skip) { // Default to `options.target` if "true" if (typeof options.if_exists === 'boolean' && options.target) { options.if_exists = options.if_exists ? [options.target] : null; } return each(options.if_exists).call((if_exists, next) => { return this.fs.exists({ target: if_exists }, (err, {exists}) => { if (exists) { this.log({ message: `File exists ${if_exists}, continuing`, level: 'DEBUG', module: 'nikita/misc/conditions' }); return next(); } else { this.log({ message: `File doesnt exists ${if_exists}, skipping`, level: 'INFO', module: 'nikita/misc/conditions' }); return skip(); } }); }).next(succeed); }
[ "function", "(", "{", "options", "}", ",", "succeed", ",", "skip", ")", "{", "// Default to `options.target` if \"true\"", "if", "(", "typeof", "options", ".", "if_exists", "===", "'boolean'", "&&", "options", ".", "target", ")", "{", "options", ".", "if_exists", "=", "options", ".", "if_exists", "?", "[", "options", ".", "target", "]", ":", "null", ";", "}", "return", "each", "(", "options", ".", "if_exists", ")", ".", "call", "(", "(", "if_exists", ",", "next", ")", "=>", "{", "return", "this", ".", "fs", ".", "exists", "(", "{", "target", ":", "if_exists", "}", ",", "(", "err", ",", "{", "exists", "}", ")", "=>", "{", "if", "(", "exists", ")", "{", "this", ".", "log", "(", "{", "message", ":", "`", "${", "if_exists", "}", "`", ",", "level", ":", "'DEBUG'", ",", "module", ":", "'nikita/misc/conditions'", "}", ")", ";", "return", "next", "(", ")", ";", "}", "else", "{", "this", ".", "log", "(", "{", "message", ":", "`", "${", "if_exists", "}", "`", ",", "level", ":", "'INFO'", ",", "module", ":", "'nikita/misc/conditions'", "}", ")", ";", "return", "skip", "(", ")", ";", "}", "}", ")", ";", "}", ")", ".", "next", "(", "succeed", ")", ";", "}" ]
The callback `succeed` is called if all the provided paths exists otherwise the callback `skip` is called.
[ "The", "callback", "succeed", "is", "called", "if", "all", "the", "provided", "paths", "exists", "otherwise", "the", "callback", "skip", "is", "called", "." ]
35c4b249da7f3fe3550f1679989d7795969fe6a6
https://github.com/adaltas/node-nikita/blob/35c4b249da7f3fe3550f1679989d7795969fe6a6/packages/core/lib/misc/conditions.js#L442-L468
10,116
adaltas/node-nikita
packages/core/lib/misc/conditions.js
function({options}, succeed, skip) { // Default to `options.target` if "true" if (typeof options.unless_exists === 'boolean' && options.target) { options.unless_exists = options.unless_exists ? [options.target] : null; } return each(options.unless_exists).call((unless_exists, next) => { return this.fs.exists({ target: unless_exists }, (err, {exists}) => { if (exists) { this.log({ message: `File exists ${unless_exists}, skipping`, level: 'INFO', module: 'nikita/misc/conditions' }); return skip(); } else { this.log({ message: `File doesnt exists ${unless_exists}, continuing`, level: 'DEBUG', module: 'nikita/misc/conditions' }); return next(); } }); }).next(succeed); }
javascript
function({options}, succeed, skip) { // Default to `options.target` if "true" if (typeof options.unless_exists === 'boolean' && options.target) { options.unless_exists = options.unless_exists ? [options.target] : null; } return each(options.unless_exists).call((unless_exists, next) => { return this.fs.exists({ target: unless_exists }, (err, {exists}) => { if (exists) { this.log({ message: `File exists ${unless_exists}, skipping`, level: 'INFO', module: 'nikita/misc/conditions' }); return skip(); } else { this.log({ message: `File doesnt exists ${unless_exists}, continuing`, level: 'DEBUG', module: 'nikita/misc/conditions' }); return next(); } }); }).next(succeed); }
[ "function", "(", "{", "options", "}", ",", "succeed", ",", "skip", ")", "{", "// Default to `options.target` if \"true\"", "if", "(", "typeof", "options", ".", "unless_exists", "===", "'boolean'", "&&", "options", ".", "target", ")", "{", "options", ".", "unless_exists", "=", "options", ".", "unless_exists", "?", "[", "options", ".", "target", "]", ":", "null", ";", "}", "return", "each", "(", "options", ".", "unless_exists", ")", ".", "call", "(", "(", "unless_exists", ",", "next", ")", "=>", "{", "return", "this", ".", "fs", ".", "exists", "(", "{", "target", ":", "unless_exists", "}", ",", "(", "err", ",", "{", "exists", "}", ")", "=>", "{", "if", "(", "exists", ")", "{", "this", ".", "log", "(", "{", "message", ":", "`", "${", "unless_exists", "}", "`", ",", "level", ":", "'INFO'", ",", "module", ":", "'nikita/misc/conditions'", "}", ")", ";", "return", "skip", "(", ")", ";", "}", "else", "{", "this", ".", "log", "(", "{", "message", ":", "`", "${", "unless_exists", "}", "`", ",", "level", ":", "'DEBUG'", ",", "module", ":", "'nikita/misc/conditions'", "}", ")", ";", "return", "next", "(", ")", ";", "}", "}", ")", ";", "}", ")", ".", "next", "(", "succeed", ")", ";", "}" ]
The callback `succeed` is called if none of the provided paths exists otherwise the callback `skip` is called.
[ "The", "callback", "succeed", "is", "called", "if", "none", "of", "the", "provided", "paths", "exists", "otherwise", "the", "callback", "skip", "is", "called", "." ]
35c4b249da7f3fe3550f1679989d7795969fe6a6
https://github.com/adaltas/node-nikita/blob/35c4b249da7f3fe3550f1679989d7795969fe6a6/packages/core/lib/misc/conditions.js#L478-L504
10,117
adaltas/node-nikita
packages/core/lib/misc/conditions.js
function({options}, succeed, skip) { var ssh; // SSH connection ssh = this.ssh(options.ssh); return each(options.should_exist).call(function(should_exist, next) { return fs.exists(ssh, should_exist, function(err, exists) { if (exists) { return next(); } else { return next(Error(`File does not exist: ${should_exist}`)); } }); }).error(skip).next(succeed); }
javascript
function({options}, succeed, skip) { var ssh; // SSH connection ssh = this.ssh(options.ssh); return each(options.should_exist).call(function(should_exist, next) { return fs.exists(ssh, should_exist, function(err, exists) { if (exists) { return next(); } else { return next(Error(`File does not exist: ${should_exist}`)); } }); }).error(skip).next(succeed); }
[ "function", "(", "{", "options", "}", ",", "succeed", ",", "skip", ")", "{", "var", "ssh", ";", "// SSH connection", "ssh", "=", "this", ".", "ssh", "(", "options", ".", "ssh", ")", ";", "return", "each", "(", "options", ".", "should_exist", ")", ".", "call", "(", "function", "(", "should_exist", ",", "next", ")", "{", "return", "fs", ".", "exists", "(", "ssh", ",", "should_exist", ",", "function", "(", "err", ",", "exists", ")", "{", "if", "(", "exists", ")", "{", "return", "next", "(", ")", ";", "}", "else", "{", "return", "next", "(", "Error", "(", "`", "${", "should_exist", "}", "`", ")", ")", ";", "}", "}", ")", ";", "}", ")", ".", "error", "(", "skip", ")", ".", "next", "(", "succeed", ")", ";", "}" ]
The callback `succeed` is called if all of the provided paths exists otherwise the callback `skip` is called with an error.
[ "The", "callback", "succeed", "is", "called", "if", "all", "of", "the", "provided", "paths", "exists", "otherwise", "the", "callback", "skip", "is", "called", "with", "an", "error", "." ]
35c4b249da7f3fe3550f1679989d7795969fe6a6
https://github.com/adaltas/node-nikita/blob/35c4b249da7f3fe3550f1679989d7795969fe6a6/packages/core/lib/misc/conditions.js#L513-L526
10,118
adaltas/node-nikita
packages/core/lib/misc/ini.js
function(content, undefinedOnly) { var k, v; for (k in content) { v = content[k]; if (v && typeof v === 'object') { content[k] = module.exports.clean(v, undefinedOnly); continue; } if (typeof v === 'undefined') { delete content[k]; } if (!undefinedOnly && v === null) { delete content[k]; } } return content; }
javascript
function(content, undefinedOnly) { var k, v; for (k in content) { v = content[k]; if (v && typeof v === 'object') { content[k] = module.exports.clean(v, undefinedOnly); continue; } if (typeof v === 'undefined') { delete content[k]; } if (!undefinedOnly && v === null) { delete content[k]; } } return content; }
[ "function", "(", "content", ",", "undefinedOnly", ")", "{", "var", "k", ",", "v", ";", "for", "(", "k", "in", "content", ")", "{", "v", "=", "content", "[", "k", "]", ";", "if", "(", "v", "&&", "typeof", "v", "===", "'object'", ")", "{", "content", "[", "k", "]", "=", "module", ".", "exports", ".", "clean", "(", "v", ",", "undefinedOnly", ")", ";", "continue", ";", "}", "if", "(", "typeof", "v", "===", "'undefined'", ")", "{", "delete", "content", "[", "k", "]", ";", "}", "if", "(", "!", "undefinedOnly", "&&", "v", "===", "null", ")", "{", "delete", "content", "[", "k", "]", ";", "}", "}", "return", "content", ";", "}" ]
Remove undefined and null values
[ "Remove", "undefined", "and", "null", "values" ]
35c4b249da7f3fe3550f1679989d7795969fe6a6
https://github.com/adaltas/node-nikita/blob/35c4b249da7f3fe3550f1679989d7795969fe6a6/packages/core/lib/misc/ini.js#L11-L27
10,119
adaltas/node-nikita
packages/core/lib/misc/ini.js
function(obj, section, options = {}) { var children, dotSplit, out, safe; if (arguments.length === 2) { options = section; section = void 0; } if (options.separator == null) { options.separator = ' = '; } if (options.eol == null) { options.eol = !options.ssh && process.platform === "win32" ? "\r\n" : "\n"; } if (options.escape == null) { options.escape = true; } safe = module.exports.safe; dotSplit = module.exports.dotSplit; children = []; out = ""; Object.keys(obj).forEach(function(k, _, __) { var val; val = obj[k]; if (val && Array.isArray(val)) { return val.forEach(function(item) { return out += safe(`${k}[]`) + options.separator + safe(item) + options.eol; }); } else if (val && typeof val === "object") { return children.push(k); } else if (typeof val === 'boolean') { if (val === true) { return out += safe(k) + options.eol; } else { } } else { // disregard false value return out += safe(k) + options.separator + safe(val) + options.eol; } }); if (section && out.length) { out = "[" + safe(section) + "]" + options.eol + out; } children.forEach((k, _, __) => { var child, nk; // escape the section name dot as some daemon could not parse it nk = options.escape ? dotSplit(k).join('\\.') : k; child = module.exports.stringify(obj[k], (section ? section + "." : "") + nk, options); if (out.length && child.length) { out += options.eol; } return out += child; }); return out; }
javascript
function(obj, section, options = {}) { var children, dotSplit, out, safe; if (arguments.length === 2) { options = section; section = void 0; } if (options.separator == null) { options.separator = ' = '; } if (options.eol == null) { options.eol = !options.ssh && process.platform === "win32" ? "\r\n" : "\n"; } if (options.escape == null) { options.escape = true; } safe = module.exports.safe; dotSplit = module.exports.dotSplit; children = []; out = ""; Object.keys(obj).forEach(function(k, _, __) { var val; val = obj[k]; if (val && Array.isArray(val)) { return val.forEach(function(item) { return out += safe(`${k}[]`) + options.separator + safe(item) + options.eol; }); } else if (val && typeof val === "object") { return children.push(k); } else if (typeof val === 'boolean') { if (val === true) { return out += safe(k) + options.eol; } else { } } else { // disregard false value return out += safe(k) + options.separator + safe(val) + options.eol; } }); if (section && out.length) { out = "[" + safe(section) + "]" + options.eol + out; } children.forEach((k, _, __) => { var child, nk; // escape the section name dot as some daemon could not parse it nk = options.escape ? dotSplit(k).join('\\.') : k; child = module.exports.stringify(obj[k], (section ? section + "." : "") + nk, options); if (out.length && child.length) { out += options.eol; } return out += child; }); return out; }
[ "function", "(", "obj", ",", "section", ",", "options", "=", "{", "}", ")", "{", "var", "children", ",", "dotSplit", ",", "out", ",", "safe", ";", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "options", "=", "section", ";", "section", "=", "void", "0", ";", "}", "if", "(", "options", ".", "separator", "==", "null", ")", "{", "options", ".", "separator", "=", "' = '", ";", "}", "if", "(", "options", ".", "eol", "==", "null", ")", "{", "options", ".", "eol", "=", "!", "options", ".", "ssh", "&&", "process", ".", "platform", "===", "\"win32\"", "?", "\"\\r\\n\"", ":", "\"\\n\"", ";", "}", "if", "(", "options", ".", "escape", "==", "null", ")", "{", "options", ".", "escape", "=", "true", ";", "}", "safe", "=", "module", ".", "exports", ".", "safe", ";", "dotSplit", "=", "module", ".", "exports", ".", "dotSplit", ";", "children", "=", "[", "]", ";", "out", "=", "\"\"", ";", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "k", ",", "_", ",", "__", ")", "{", "var", "val", ";", "val", "=", "obj", "[", "k", "]", ";", "if", "(", "val", "&&", "Array", ".", "isArray", "(", "val", ")", ")", "{", "return", "val", ".", "forEach", "(", "function", "(", "item", ")", "{", "return", "out", "+=", "safe", "(", "`", "${", "k", "}", "`", ")", "+", "options", ".", "separator", "+", "safe", "(", "item", ")", "+", "options", ".", "eol", ";", "}", ")", ";", "}", "else", "if", "(", "val", "&&", "typeof", "val", "===", "\"object\"", ")", "{", "return", "children", ".", "push", "(", "k", ")", ";", "}", "else", "if", "(", "typeof", "val", "===", "'boolean'", ")", "{", "if", "(", "val", "===", "true", ")", "{", "return", "out", "+=", "safe", "(", "k", ")", "+", "options", ".", "eol", ";", "}", "else", "{", "}", "}", "else", "{", "// disregard false value", "return", "out", "+=", "safe", "(", "k", ")", "+", "options", ".", "separator", "+", "safe", "(", "val", ")", "+", "options", ".", "eol", ";", "}", "}", ")", ";", "if", "(", "section", "&&", "out", ".", "length", ")", "{", "out", "=", "\"[\"", "+", "safe", "(", "section", ")", "+", "\"]\"", "+", "options", ".", "eol", "+", "out", ";", "}", "children", ".", "forEach", "(", "(", "k", ",", "_", ",", "__", ")", "=>", "{", "var", "child", ",", "nk", ";", "// escape the section name dot as some daemon could not parse it", "nk", "=", "options", ".", "escape", "?", "dotSplit", "(", "k", ")", ".", "join", "(", "'\\\\.'", ")", ":", "k", ";", "child", "=", "module", ".", "exports", ".", "stringify", "(", "obj", "[", "k", "]", ",", "(", "section", "?", "section", "+", "\".\"", ":", "\"\"", ")", "+", "nk", ",", "options", ")", ";", "if", "(", "out", ".", "length", "&&", "child", ".", "length", ")", "{", "out", "+=", "options", ".", "eol", ";", "}", "return", "out", "+=", "child", ";", "}", ")", ";", "return", "out", ";", "}" ]
same as ini parse but transform value which are true and type of true as '' to be user by stringify_single_key
[ "same", "as", "ini", "parse", "but", "transform", "value", "which", "are", "true", "and", "type", "of", "true", "as", "to", "be", "user", "by", "stringify_single_key" ]
35c4b249da7f3fe3550f1679989d7795969fe6a6
https://github.com/adaltas/node-nikita/blob/35c4b249da7f3fe3550f1679989d7795969fe6a6/packages/core/lib/misc/ini.js#L262-L315
10,120
proj4js/mgrs
mgrs.js
encode
function encode(utm, accuracy) { // prepend with leading zeroes const seasting = '00000' + utm.easting, snorthing = '00000' + utm.northing; return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy); }
javascript
function encode(utm, accuracy) { // prepend with leading zeroes const seasting = '00000' + utm.easting, snorthing = '00000' + utm.northing; return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy); }
[ "function", "encode", "(", "utm", ",", "accuracy", ")", "{", "// prepend with leading zeroes", "const", "seasting", "=", "'00000'", "+", "utm", ".", "easting", ",", "snorthing", "=", "'00000'", "+", "utm", ".", "northing", ";", "return", "utm", ".", "zoneNumber", "+", "utm", ".", "zoneLetter", "+", "get100kID", "(", "utm", ".", "easting", ",", "utm", ".", "northing", ",", "utm", ".", "zoneNumber", ")", "+", "seasting", ".", "substr", "(", "seasting", ".", "length", "-", "5", ",", "accuracy", ")", "+", "snorthing", ".", "substr", "(", "snorthing", ".", "length", "-", "5", ",", "accuracy", ")", ";", "}" ]
Encodes a UTM location as MGRS string. @private @param {object} utm An object literal with easting, northing, zoneLetter, zoneNumber @param {number} accuracy Accuracy in digits (1-5). @return {string} MGRS string for the given UTM location.
[ "Encodes", "a", "UTM", "location", "as", "MGRS", "string", "." ]
1780ee78d247425ea73ddb2730849c54bae9f34c
https://github.com/proj4js/mgrs/blob/1780ee78d247425ea73ddb2730849c54bae9f34c/mgrs.js#L327-L333
10,121
proj4js/mgrs
mgrs.js
get100kID
function get100kID(easting, northing, zoneNumber) { const setParm = get100kSetForZone(zoneNumber); const setColumn = Math.floor(easting / 100000); const setRow = Math.floor(northing / 100000) % 20; return getLetter100kID(setColumn, setRow, setParm); }
javascript
function get100kID(easting, northing, zoneNumber) { const setParm = get100kSetForZone(zoneNumber); const setColumn = Math.floor(easting / 100000); const setRow = Math.floor(northing / 100000) % 20; return getLetter100kID(setColumn, setRow, setParm); }
[ "function", "get100kID", "(", "easting", ",", "northing", ",", "zoneNumber", ")", "{", "const", "setParm", "=", "get100kSetForZone", "(", "zoneNumber", ")", ";", "const", "setColumn", "=", "Math", ".", "floor", "(", "easting", "/", "100000", ")", ";", "const", "setRow", "=", "Math", ".", "floor", "(", "northing", "/", "100000", ")", "%", "20", ";", "return", "getLetter100kID", "(", "setColumn", ",", "setRow", ",", "setParm", ")", ";", "}" ]
Get the two letter 100k designator for a given UTM easting, northing and zone number value. @private @param {number} easting @param {number} northing @param {number} zoneNumber @return {string} the two letter 100k designator for the given UTM location.
[ "Get", "the", "two", "letter", "100k", "designator", "for", "a", "given", "UTM", "easting", "northing", "and", "zone", "number", "value", "." ]
1780ee78d247425ea73ddb2730849c54bae9f34c
https://github.com/proj4js/mgrs/blob/1780ee78d247425ea73ddb2730849c54bae9f34c/mgrs.js#L345-L350
10,122
libp2p/js-libp2p-circuit
src/circuit/utils.js
getB58String
function getB58String (peer) { let b58Id = null if (multiaddr.isMultiaddr(peer)) { const relayMa = multiaddr(peer) b58Id = relayMa.getPeerId() } else if (PeerInfo.isPeerInfo(peer)) { b58Id = peer.id.toB58String() } return b58Id }
javascript
function getB58String (peer) { let b58Id = null if (multiaddr.isMultiaddr(peer)) { const relayMa = multiaddr(peer) b58Id = relayMa.getPeerId() } else if (PeerInfo.isPeerInfo(peer)) { b58Id = peer.id.toB58String() } return b58Id }
[ "function", "getB58String", "(", "peer", ")", "{", "let", "b58Id", "=", "null", "if", "(", "multiaddr", ".", "isMultiaddr", "(", "peer", ")", ")", "{", "const", "relayMa", "=", "multiaddr", "(", "peer", ")", "b58Id", "=", "relayMa", ".", "getPeerId", "(", ")", "}", "else", "if", "(", "PeerInfo", ".", "isPeerInfo", "(", "peer", ")", ")", "{", "b58Id", "=", "peer", ".", "id", ".", "toB58String", "(", ")", "}", "return", "b58Id", "}" ]
Get b58 string from multiaddr or peerinfo @param {Multiaddr|PeerInfo} peer @return {*}
[ "Get", "b58", "string", "from", "multiaddr", "or", "peerinfo" ]
ed35c767f8fa525560dea20e8bf663d45743361f
https://github.com/libp2p/js-libp2p-circuit/blob/ed35c767f8fa525560dea20e8bf663d45743361f/src/circuit/utils.js#L15-L25
10,123
libp2p/js-libp2p-circuit
src/circuit/utils.js
peerInfoFromMa
function peerInfoFromMa (peer) { let p // PeerInfo if (PeerInfo.isPeerInfo(peer)) { p = peer // Multiaddr instance (not string) } else if (multiaddr.isMultiaddr(peer)) { const peerIdB58Str = peer.getPeerId() try { p = swarm._peerBook.get(peerIdB58Str) } catch (err) { p = new PeerInfo(PeerId.createFromB58String(peerIdB58Str)) } p.multiaddrs.add(peer) // PeerId } else if (PeerId.isPeerId(peer)) { const peerIdB58Str = peer.toB58String() p = swarm._peerBook.has(peerIdB58Str) ? swarm._peerBook.get(peerIdB58Str) : peer } return p }
javascript
function peerInfoFromMa (peer) { let p // PeerInfo if (PeerInfo.isPeerInfo(peer)) { p = peer // Multiaddr instance (not string) } else if (multiaddr.isMultiaddr(peer)) { const peerIdB58Str = peer.getPeerId() try { p = swarm._peerBook.get(peerIdB58Str) } catch (err) { p = new PeerInfo(PeerId.createFromB58String(peerIdB58Str)) } p.multiaddrs.add(peer) // PeerId } else if (PeerId.isPeerId(peer)) { const peerIdB58Str = peer.toB58String() p = swarm._peerBook.has(peerIdB58Str) ? swarm._peerBook.get(peerIdB58Str) : peer } return p }
[ "function", "peerInfoFromMa", "(", "peer", ")", "{", "let", "p", "// PeerInfo", "if", "(", "PeerInfo", ".", "isPeerInfo", "(", "peer", ")", ")", "{", "p", "=", "peer", "// Multiaddr instance (not string)", "}", "else", "if", "(", "multiaddr", ".", "isMultiaddr", "(", "peer", ")", ")", "{", "const", "peerIdB58Str", "=", "peer", ".", "getPeerId", "(", ")", "try", "{", "p", "=", "swarm", ".", "_peerBook", ".", "get", "(", "peerIdB58Str", ")", "}", "catch", "(", "err", ")", "{", "p", "=", "new", "PeerInfo", "(", "PeerId", ".", "createFromB58String", "(", "peerIdB58Str", ")", ")", "}", "p", ".", "multiaddrs", ".", "add", "(", "peer", ")", "// PeerId", "}", "else", "if", "(", "PeerId", ".", "isPeerId", "(", "peer", ")", ")", "{", "const", "peerIdB58Str", "=", "peer", ".", "toB58String", "(", ")", "p", "=", "swarm", ".", "_peerBook", ".", "has", "(", "peerIdB58Str", ")", "?", "swarm", ".", "_peerBook", ".", "get", "(", "peerIdB58Str", ")", ":", "peer", "}", "return", "p", "}" ]
Helper to make a peer info from a multiaddrs @param {Multiaddr|PeerInfo|PeerId} ma @param {Swarm} swarm @return {PeerInfo} @private TODO: this is ripped off of libp2p, should probably be a generally available util function
[ "Helper", "to", "make", "a", "peer", "info", "from", "a", "multiaddrs" ]
ed35c767f8fa525560dea20e8bf663d45743361f
https://github.com/libp2p/js-libp2p-circuit/blob/ed35c767f8fa525560dea20e8bf663d45743361f/src/circuit/utils.js#L36-L57
10,124
libp2p/js-libp2p-circuit
src/circuit/utils.js
writeResponse
function writeResponse (streamHandler, status, cb) { cb = cb || (() => {}) streamHandler.write(proto.CircuitRelay.encode({ type: proto.CircuitRelay.Type.STATUS, code: status })) return cb() }
javascript
function writeResponse (streamHandler, status, cb) { cb = cb || (() => {}) streamHandler.write(proto.CircuitRelay.encode({ type: proto.CircuitRelay.Type.STATUS, code: status })) return cb() }
[ "function", "writeResponse", "(", "streamHandler", ",", "status", ",", "cb", ")", "{", "cb", "=", "cb", "||", "(", "(", ")", "=>", "{", "}", ")", "streamHandler", ".", "write", "(", "proto", ".", "CircuitRelay", ".", "encode", "(", "{", "type", ":", "proto", ".", "CircuitRelay", ".", "Type", ".", "STATUS", ",", "code", ":", "status", "}", ")", ")", "return", "cb", "(", ")", "}" ]
Write a response @param {StreamHandler} streamHandler @param {CircuitRelay.Status} status @param {Function} cb @returns {*}
[ "Write", "a", "response" ]
ed35c767f8fa525560dea20e8bf663d45743361f
https://github.com/libp2p/js-libp2p-circuit/blob/ed35c767f8fa525560dea20e8bf663d45743361f/src/circuit/utils.js#L78-L85
10,125
googleapis/gaxios
samples/quickstart.js
quickstart
async function quickstart() { const url = 'https://www.googleapis.com/discovery/v1/apis/'; const res = await request({url}); console.log(`status: ${res.status}`); console.log(`data:`); console.log(res.data); }
javascript
async function quickstart() { const url = 'https://www.googleapis.com/discovery/v1/apis/'; const res = await request({url}); console.log(`status: ${res.status}`); console.log(`data:`); console.log(res.data); }
[ "async", "function", "quickstart", "(", ")", "{", "const", "url", "=", "'https://www.googleapis.com/discovery/v1/apis/'", ";", "const", "res", "=", "await", "request", "(", "{", "url", "}", ")", ";", "console", ".", "log", "(", "`", "${", "res", ".", "status", "}", "`", ")", ";", "console", ".", "log", "(", "`", "`", ")", ";", "console", ".", "log", "(", "res", ".", "data", ")", ";", "}" ]
Perform a simple `GET` request to a JSON API.
[ "Perform", "a", "simple", "GET", "request", "to", "a", "JSON", "API", "." ]
076afae4b37c02747908a01509266b5fee926d47
https://github.com/googleapis/gaxios/blob/076afae4b37c02747908a01509266b5fee926d47/samples/quickstart.js#L23-L29
10,126
enketo/enketo-core
src/js/widgets-controller.js
disable
function disable( group ) { widgets.forEach( Widget => { const els = _getElements( group, Widget.selector ); new Collection( els ).disable( Widget ); } ); }
javascript
function disable( group ) { widgets.forEach( Widget => { const els = _getElements( group, Widget.selector ); new Collection( els ).disable( Widget ); } ); }
[ "function", "disable", "(", "group", ")", "{", "widgets", ".", "forEach", "(", "Widget", "=>", "{", "const", "els", "=", "_getElements", "(", "group", ",", "Widget", ".", "selector", ")", ";", "new", "Collection", "(", "els", ")", ".", "disable", "(", "Widget", ")", ";", "}", ")", ";", "}" ]
Disables widgets, if they aren't disabled already when the branch was disabled by the controller. In most widgets, this function will do nothing because all fieldsets, inputs, textareas and selects will get the disabled attribute automatically when the branch element provided as parameter becomes irrelevant. @param { Element } group The element inside which all widgets need to be disabled.
[ "Disables", "widgets", "if", "they", "aren", "t", "disabled", "already", "when", "the", "branch", "was", "disabled", "by", "the", "controller", ".", "In", "most", "widgets", "this", "function", "will", "do", "nothing", "because", "all", "fieldsets", "inputs", "textareas", "and", "selects", "will", "get", "the", "disabled", "attribute", "automatically", "when", "the", "branch", "element", "provided", "as", "parameter", "becomes", "irrelevant", "." ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/widgets-controller.js#L57-L62
10,127
enketo/enketo-core
src/js/widgets-controller.js
_getElements
function _getElements( group, selector ) { if ( selector ) { if ( selector === 'form' ) { return [ formHtml ]; } // e.g. if the widget selector starts at .question level (e.g. ".or-appearance-draw input") if ( group.classList.contains( 'question' ) ) { return [ ...group.querySelectorAll( 'input:not(.ignore), select:not(.ignore), textarea:not(.ignore)' ) ] .filter( el => el.matches( selector ) ); } return [ ...group.querySelectorAll( selector ) ]; } return []; }
javascript
function _getElements( group, selector ) { if ( selector ) { if ( selector === 'form' ) { return [ formHtml ]; } // e.g. if the widget selector starts at .question level (e.g. ".or-appearance-draw input") if ( group.classList.contains( 'question' ) ) { return [ ...group.querySelectorAll( 'input:not(.ignore), select:not(.ignore), textarea:not(.ignore)' ) ] .filter( el => el.matches( selector ) ); } return [ ...group.querySelectorAll( selector ) ]; } return []; }
[ "function", "_getElements", "(", "group", ",", "selector", ")", "{", "if", "(", "selector", ")", "{", "if", "(", "selector", "===", "'form'", ")", "{", "return", "[", "formHtml", "]", ";", "}", "// e.g. if the widget selector starts at .question level (e.g. \".or-appearance-draw input\")", "if", "(", "group", ".", "classList", ".", "contains", "(", "'question'", ")", ")", "{", "return", "[", "...", "group", ".", "querySelectorAll", "(", "'input:not(.ignore), select:not(.ignore), textarea:not(.ignore)'", ")", "]", ".", "filter", "(", "el", "=>", "el", ".", "matches", "(", "selector", ")", ")", ";", "}", "return", "[", "...", "group", ".", "querySelectorAll", "(", "selector", ")", "]", ";", "}", "return", "[", "]", ";", "}" ]
Returns the elements on which to apply the widget @param {Element} group a jQuery-wrapped element @param {string} selector if the selector is null, the form element will be returned @return {jQuery} a jQuery collection
[ "Returns", "the", "elements", "on", "which", "to", "apply", "the", "widget" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/widgets-controller.js#L71-L85
10,128
enketo/enketo-core
src/js/print.js
setDpi
function setDpi() { const dpiO = {}; const e = document.body.appendChild( document.createElement( 'DIV' ) ); e.style.width = '1in'; e.style.padding = '0'; dpiO.v = e.offsetWidth; e.parentNode.removeChild( e ); dpi = dpiO.v; }
javascript
function setDpi() { const dpiO = {}; const e = document.body.appendChild( document.createElement( 'DIV' ) ); e.style.width = '1in'; e.style.padding = '0'; dpiO.v = e.offsetWidth; e.parentNode.removeChild( e ); dpi = dpiO.v; }
[ "function", "setDpi", "(", ")", "{", "const", "dpiO", "=", "{", "}", ";", "const", "e", "=", "document", ".", "body", ".", "appendChild", "(", "document", ".", "createElement", "(", "'DIV'", ")", ")", ";", "e", ".", "style", ".", "width", "=", "'1in'", ";", "e", ".", "style", ".", "padding", "=", "'0'", ";", "dpiO", ".", "v", "=", "e", ".", "offsetWidth", ";", "e", ".", "parentNode", ".", "removeChild", "(", "e", ")", ";", "dpi", "=", "dpiO", ".", "v", ";", "}" ]
Calculates the dots per inch and sets the dpi property
[ "Calculates", "the", "dots", "per", "inch", "and", "sets", "the", "dpi", "property" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/print.js#L19-L27
10,129
enketo/enketo-core
src/js/print.js
getPrintStyleSheet
function getPrintStyleSheet() { let sheet; // document.styleSheets is an Object not an Array! for ( const i in document.styleSheets ) { if ( document.styleSheets.hasOwnProperty( i ) ) { sheet = document.styleSheets[ i ]; if ( sheet.media.mediaText === 'print' ) { return sheet; } } } return null; }
javascript
function getPrintStyleSheet() { let sheet; // document.styleSheets is an Object not an Array! for ( const i in document.styleSheets ) { if ( document.styleSheets.hasOwnProperty( i ) ) { sheet = document.styleSheets[ i ]; if ( sheet.media.mediaText === 'print' ) { return sheet; } } } return null; }
[ "function", "getPrintStyleSheet", "(", ")", "{", "let", "sheet", ";", "// document.styleSheets is an Object not an Array!", "for", "(", "const", "i", "in", "document", ".", "styleSheets", ")", "{", "if", "(", "document", ".", "styleSheets", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "sheet", "=", "document", ".", "styleSheets", "[", "i", "]", ";", "if", "(", "sheet", ".", "media", ".", "mediaText", "===", "'print'", ")", "{", "return", "sheet", ";", "}", "}", "}", "return", "null", ";", "}" ]
Gets print stylesheets @return {Element} [description]
[ "Gets", "print", "stylesheets" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/print.js#L33-L45
10,130
enketo/enketo-core
src/js/print.js
styleToAll
function styleToAll() { // sometimes, setStylesheet fails upon loading printStyleSheet = printStyleSheet || getPrintStyleSheet(); $printStyleSheetLink = $printStyleSheetLink || getPrintStyleSheetLink(); // Chrome: printStyleSheet.media.mediaText = 'all'; // Firefox: $printStyleSheetLink.attr( 'media', 'all' ); return !!printStyleSheet; }
javascript
function styleToAll() { // sometimes, setStylesheet fails upon loading printStyleSheet = printStyleSheet || getPrintStyleSheet(); $printStyleSheetLink = $printStyleSheetLink || getPrintStyleSheetLink(); // Chrome: printStyleSheet.media.mediaText = 'all'; // Firefox: $printStyleSheetLink.attr( 'media', 'all' ); return !!printStyleSheet; }
[ "function", "styleToAll", "(", ")", "{", "// sometimes, setStylesheet fails upon loading", "printStyleSheet", "=", "printStyleSheet", "||", "getPrintStyleSheet", "(", ")", ";", "$printStyleSheetLink", "=", "$printStyleSheetLink", "||", "getPrintStyleSheetLink", "(", ")", ";", "// Chrome:", "printStyleSheet", ".", "media", ".", "mediaText", "=", "'all'", ";", "// Firefox:", "$printStyleSheetLink", ".", "attr", "(", "'media'", ",", "'all'", ")", ";", "return", "!", "!", "printStyleSheet", ";", "}" ]
Applies the print stylesheet to the current view by changing stylesheets media property to 'all'
[ "Applies", "the", "print", "stylesheet", "to", "the", "current", "view", "by", "changing", "stylesheets", "media", "property", "to", "all" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/print.js#L54-L63
10,131
enketo/enketo-core
src/js/fake-translator.js
t
function t( key, options ) { let str = ''; let target = SOURCE_STRINGS; // crude string getter key.split( '.' ).forEach( part => { target = target ? target[ part ] : ''; str = target; } ); // crude interpolator options = options || {}; str = str.replace( /__([^_]+)__/, ( match, p1 ) => options[ p1 ] ); // Enable line below to switch to fake Arabic, very useful for testing RTL // var AR = 'العربية '; return str.split( '' ).map( function( char, i ) { return AR[ i % AR.length ];} ).join( '' ); return str; }
javascript
function t( key, options ) { let str = ''; let target = SOURCE_STRINGS; // crude string getter key.split( '.' ).forEach( part => { target = target ? target[ part ] : ''; str = target; } ); // crude interpolator options = options || {}; str = str.replace( /__([^_]+)__/, ( match, p1 ) => options[ p1 ] ); // Enable line below to switch to fake Arabic, very useful for testing RTL // var AR = 'العربية '; return str.split( '' ).map( function( char, i ) { return AR[ i % AR.length ];} ).join( '' ); return str; }
[ "function", "t", "(", "key", ",", "options", ")", "{", "let", "str", "=", "''", ";", "let", "target", "=", "SOURCE_STRINGS", ";", "// crude string getter", "key", ".", "split", "(", "'.'", ")", ".", "forEach", "(", "part", "=>", "{", "target", "=", "target", "?", "target", "[", "part", "]", ":", "''", ";", "str", "=", "target", ";", "}", ")", ";", "// crude interpolator", "options", "=", "options", "||", "{", "}", ";", "str", "=", "str", ".", "replace", "(", "/", "__([^_]+)__", "/", ",", "(", "match", ",", "p1", ")", "=>", "options", "[", "p1", "]", ")", ";", "// Enable line below to switch to fake Arabic, very useful for testing RTL", "// var AR = 'العربية '; return str.split( '' ).map( function( char, i ) { return AR[ i % AR.length ];} ).join( '' );", "return", "str", ";", "}" ]
Add keys from XSL stylesheets manually so i18next-parser will detect them. t('constraint.invalid'); t('constraint.required'); Meant to be replaced by a real translator in the app that consumes enketo-core @param {String} key translation key @param {*} key translation options @return {String} translation output
[ "Add", "keys", "from", "XSL", "stylesheets", "manually", "so", "i18next", "-", "parser", "will", "detect", "them", "." ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/fake-translator.js#L95-L111
10,132
enketo/enketo-core
app.js
initializeForm
function initializeForm() { form = new Form( 'form.or:eq(0)', { modelStr: modelStr }, { arcGis: { basemaps: [ 'streets', 'topo', 'satellite', 'osm' ], webMapId: 'f2e9b762544945f390ca4ac3671cfa72', hasZ: true }, 'clearIrrelevantImmediately': true } ); // for debugging window.form = form; //initialize form and check for load errors loadErrors = form.init(); if ( loadErrors.length > 0 ) { window.alert( 'loadErrors: ' + loadErrors.join( ', ' ) ); } }
javascript
function initializeForm() { form = new Form( 'form.or:eq(0)', { modelStr: modelStr }, { arcGis: { basemaps: [ 'streets', 'topo', 'satellite', 'osm' ], webMapId: 'f2e9b762544945f390ca4ac3671cfa72', hasZ: true }, 'clearIrrelevantImmediately': true } ); // for debugging window.form = form; //initialize form and check for load errors loadErrors = form.init(); if ( loadErrors.length > 0 ) { window.alert( 'loadErrors: ' + loadErrors.join( ', ' ) ); } }
[ "function", "initializeForm", "(", ")", "{", "form", "=", "new", "Form", "(", "'form.or:eq(0)'", ",", "{", "modelStr", ":", "modelStr", "}", ",", "{", "arcGis", ":", "{", "basemaps", ":", "[", "'streets'", ",", "'topo'", ",", "'satellite'", ",", "'osm'", "]", ",", "webMapId", ":", "'f2e9b762544945f390ca4ac3671cfa72'", ",", "hasZ", ":", "true", "}", ",", "'clearIrrelevantImmediately'", ":", "true", "}", ")", ";", "// for debugging", "window", ".", "form", "=", "form", ";", "//initialize form and check for load errors", "loadErrors", "=", "form", ".", "init", "(", ")", ";", "if", "(", "loadErrors", ".", "length", ">", "0", ")", "{", "window", ".", "alert", "(", "'loadErrors: '", "+", "loadErrors", ".", "join", "(", "', '", ")", ")", ";", "}", "}" ]
initialize the form
[ "initialize", "the", "form" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/app.js#L64-L82
10,133
enketo/enketo-core
app.js
getURLParameter
function getURLParameter( name ) { return decodeURI( ( new RegExp( name + '=' + '(.+?)(&|$)' ).exec( location.search ) || [ null, null ] )[ 1 ] ); }
javascript
function getURLParameter( name ) { return decodeURI( ( new RegExp( name + '=' + '(.+?)(&|$)' ).exec( location.search ) || [ null, null ] )[ 1 ] ); }
[ "function", "getURLParameter", "(", "name", ")", "{", "return", "decodeURI", "(", "(", "new", "RegExp", "(", "name", "+", "'='", "+", "'(.+?)(&|$)'", ")", ".", "exec", "(", "location", ".", "search", ")", "||", "[", "null", ",", "null", "]", ")", "[", "1", "]", ")", ";", "}" ]
get query string parameter
[ "get", "query", "string", "parameter" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/app.js#L85-L89
10,134
enketo/enketo-core
src/js/translated-error.js
TranslatedError
function TranslatedError( message, translationKey, translationOptions ) { this.message = message; this.translationKey = translationKey; this.translationOptions = translationOptions; }
javascript
function TranslatedError( message, translationKey, translationOptions ) { this.message = message; this.translationKey = translationKey; this.translationOptions = translationOptions; }
[ "function", "TranslatedError", "(", "message", ",", "translationKey", ",", "translationOptions", ")", "{", "this", ".", "message", "=", "message", ";", "this", ".", "translationKey", "=", "translationKey", ";", "this", ".", "translationOptions", "=", "translationOptions", ";", "}" ]
Error to be translated
[ "Error", "to", "be", "translated" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/translated-error.js#L2-L6
10,135
enketo/enketo-core
src/js/utils.js
parseFunctionFromExpression
function parseFunctionFromExpression( expr, func ) { let index; let result; let openBrackets; let start; let argStart; let args; const findFunc = new RegExp( `${func}\\s*\\(`, 'g' ); const results = []; if ( !expr || !func ) { return results; } while ( ( result = findFunc.exec( expr ) ) !== null ) { openBrackets = 1; args = []; start = result.index; argStart = findFunc.lastIndex; index = argStart - 1; while ( openBrackets !== 0 && index < expr.length ) { index++; if ( expr[ index ] === '(' ) { openBrackets++; } else if ( expr[ index ] === ')' ) { openBrackets--; } else if ( expr[ index ] === ',' && openBrackets === 1 ) { args.push( expr.substring( argStart, index ).trim() ); argStart = index + 1; } } // add last argument if ( argStart < index ) { args.push( expr.substring( argStart, index ).trim() ); } // add [ 'function( a ,b)', ['a','b'] ] to result array results.push( [ expr.substring( start, index + 1 ), args ] ); } return results; }
javascript
function parseFunctionFromExpression( expr, func ) { let index; let result; let openBrackets; let start; let argStart; let args; const findFunc = new RegExp( `${func}\\s*\\(`, 'g' ); const results = []; if ( !expr || !func ) { return results; } while ( ( result = findFunc.exec( expr ) ) !== null ) { openBrackets = 1; args = []; start = result.index; argStart = findFunc.lastIndex; index = argStart - 1; while ( openBrackets !== 0 && index < expr.length ) { index++; if ( expr[ index ] === '(' ) { openBrackets++; } else if ( expr[ index ] === ')' ) { openBrackets--; } else if ( expr[ index ] === ',' && openBrackets === 1 ) { args.push( expr.substring( argStart, index ).trim() ); argStart = index + 1; } } // add last argument if ( argStart < index ) { args.push( expr.substring( argStart, index ).trim() ); } // add [ 'function( a ,b)', ['a','b'] ] to result array results.push( [ expr.substring( start, index + 1 ), args ] ); } return results; }
[ "function", "parseFunctionFromExpression", "(", "expr", ",", "func", ")", "{", "let", "index", ";", "let", "result", ";", "let", "openBrackets", ";", "let", "start", ";", "let", "argStart", ";", "let", "args", ";", "const", "findFunc", "=", "new", "RegExp", "(", "`", "${", "func", "}", "\\\\", "\\\\", "`", ",", "'g'", ")", ";", "const", "results", "=", "[", "]", ";", "if", "(", "!", "expr", "||", "!", "func", ")", "{", "return", "results", ";", "}", "while", "(", "(", "result", "=", "findFunc", ".", "exec", "(", "expr", ")", ")", "!==", "null", ")", "{", "openBrackets", "=", "1", ";", "args", "=", "[", "]", ";", "start", "=", "result", ".", "index", ";", "argStart", "=", "findFunc", ".", "lastIndex", ";", "index", "=", "argStart", "-", "1", ";", "while", "(", "openBrackets", "!==", "0", "&&", "index", "<", "expr", ".", "length", ")", "{", "index", "++", ";", "if", "(", "expr", "[", "index", "]", "===", "'('", ")", "{", "openBrackets", "++", ";", "}", "else", "if", "(", "expr", "[", "index", "]", "===", "')'", ")", "{", "openBrackets", "--", ";", "}", "else", "if", "(", "expr", "[", "index", "]", "===", "','", "&&", "openBrackets", "===", "1", ")", "{", "args", ".", "push", "(", "expr", ".", "substring", "(", "argStart", ",", "index", ")", ".", "trim", "(", ")", ")", ";", "argStart", "=", "index", "+", "1", ";", "}", "}", "// add last argument", "if", "(", "argStart", "<", "index", ")", "{", "args", ".", "push", "(", "expr", ".", "substring", "(", "argStart", ",", "index", ")", ".", "trim", "(", ")", ")", ";", "}", "// add [ 'function( a ,b)', ['a','b'] ] to result array", "results", ".", "push", "(", "[", "expr", ".", "substring", "(", "start", ",", "index", "+", "1", ")", ",", "args", "]", ")", ";", "}", "return", "results", ";", "}" ]
Parses an Expression to extract all function calls and theirs argument arrays. @param {String} expr The expression to search @param {String} func The function name to search for @return {<String, <String*>>} The result array, where each result is an array containing the function call and array of arguments.
[ "Parses", "an", "Expression", "to", "extract", "all", "function", "calls", "and", "theirs", "argument", "arrays", "." ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/utils.js#L11-L52
10,136
enketo/enketo-core
src/js/utils.js
toArray
function toArray( list ) { const array = []; // iterate backwards ensuring that length is an UInt32 for ( let i = list.length >>> 0; i--; ) { array[ i ] = list[ i ]; } return array; }
javascript
function toArray( list ) { const array = []; // iterate backwards ensuring that length is an UInt32 for ( let i = list.length >>> 0; i--; ) { array[ i ] = list[ i ]; } return array; }
[ "function", "toArray", "(", "list", ")", "{", "const", "array", "=", "[", "]", ";", "// iterate backwards ensuring that length is an UInt32", "for", "(", "let", "i", "=", "list", ".", "length", ">>>", "0", ";", "i", "--", ";", ")", "{", "array", "[", "i", "]", "=", "list", "[", "i", "]", ";", "}", "return", "array", ";", "}" ]
Converts NodeLists or DOMtokenLists to an array @param {[type]} list [description] @return {[type]} [description]
[ "Converts", "NodeLists", "or", "DOMtokenLists", "to", "an", "array" ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/utils.js#L85-L92
10,137
enketo/enketo-core
src/js/utils.js
updateDownloadLink
function updateDownloadLink( anchor, objectUrl, fileName ) { if ( window.updateDownloadLinkIe11 ) { return window.updateDownloadLinkIe11( ...arguments ); } anchor.setAttribute( 'href', objectUrl || '' ); anchor.setAttribute( 'download', fileName || '' ); }
javascript
function updateDownloadLink( anchor, objectUrl, fileName ) { if ( window.updateDownloadLinkIe11 ) { return window.updateDownloadLinkIe11( ...arguments ); } anchor.setAttribute( 'href', objectUrl || '' ); anchor.setAttribute( 'download', fileName || '' ); }
[ "function", "updateDownloadLink", "(", "anchor", ",", "objectUrl", ",", "fileName", ")", "{", "if", "(", "window", ".", "updateDownloadLinkIe11", ")", "{", "return", "window", ".", "updateDownloadLinkIe11", "(", "...", "arguments", ")", ";", "}", "anchor", ".", "setAttribute", "(", "'href'", ",", "objectUrl", "||", "''", ")", ";", "anchor", ".", "setAttribute", "(", "'download'", ",", "fileName", "||", "''", ")", ";", "}" ]
Update a HTML anchor to serve as a download or reset it if an empty objectUrl is provided. @param {HTMLElement} anchor the anchor element @param {*} objectUrl the objectUrl to download @param {*} fileName the filename of the file
[ "Update", "a", "HTML", "anchor", "to", "serve", "as", "a", "download", "or", "reset", "it", "if", "an", "empty", "objectUrl", "is", "provided", "." ]
b47a98dd5c4ace2410424efa706c96de43e2e6a2
https://github.com/enketo/enketo-core/blob/b47a98dd5c4ace2410424efa706c96de43e2e6a2/src/js/utils.js#L163-L169
10,138
namics/stylelint-bem-namics
index.js
getValidSyntax
function getValidSyntax(className, namespaces) { const parsedClassName = parseClassName(className, namespaces); // Try to guess the namespaces or use the first one let validSyntax = parsedClassName.namespace || namespaces[0] || ''; if (parsedClassName.helper) { validSyntax += `${parsedClassName.helper}-`; } if (parsedClassName.pattern) { validSyntax += `${parsedClassName.pattern}-`; } else if (validPatternPrefixes.length) { validSyntax += '[prefix]-'; } validSyntax += '[block]'; if (className.indexOf('__') !== -1) { validSyntax += '__[element]'; } if (validHelperPrefixes.indexOf(parsedClassName.helper) !== -1) { validSyntax += `--[${parsedClassName.helper}]`; } else if (className.indexOf('--') !== -1) { validSyntax += '--[modifier]'; } return validSyntax; }
javascript
function getValidSyntax(className, namespaces) { const parsedClassName = parseClassName(className, namespaces); // Try to guess the namespaces or use the first one let validSyntax = parsedClassName.namespace || namespaces[0] || ''; if (parsedClassName.helper) { validSyntax += `${parsedClassName.helper}-`; } if (parsedClassName.pattern) { validSyntax += `${parsedClassName.pattern}-`; } else if (validPatternPrefixes.length) { validSyntax += '[prefix]-'; } validSyntax += '[block]'; if (className.indexOf('__') !== -1) { validSyntax += '__[element]'; } if (validHelperPrefixes.indexOf(parsedClassName.helper) !== -1) { validSyntax += `--[${parsedClassName.helper}]`; } else if (className.indexOf('--') !== -1) { validSyntax += '--[modifier]'; } return validSyntax; }
[ "function", "getValidSyntax", "(", "className", ",", "namespaces", ")", "{", "const", "parsedClassName", "=", "parseClassName", "(", "className", ",", "namespaces", ")", ";", "// Try to guess the namespaces or use the first one", "let", "validSyntax", "=", "parsedClassName", ".", "namespace", "||", "namespaces", "[", "0", "]", "||", "''", ";", "if", "(", "parsedClassName", ".", "helper", ")", "{", "validSyntax", "+=", "`", "${", "parsedClassName", ".", "helper", "}", "`", ";", "}", "if", "(", "parsedClassName", ".", "pattern", ")", "{", "validSyntax", "+=", "`", "${", "parsedClassName", ".", "pattern", "}", "`", ";", "}", "else", "if", "(", "validPatternPrefixes", ".", "length", ")", "{", "validSyntax", "+=", "'[prefix]-'", ";", "}", "validSyntax", "+=", "'[block]'", ";", "if", "(", "className", ".", "indexOf", "(", "'__'", ")", "!==", "-", "1", ")", "{", "validSyntax", "+=", "'__[element]'", ";", "}", "if", "(", "validHelperPrefixes", ".", "indexOf", "(", "parsedClassName", ".", "helper", ")", "!==", "-", "1", ")", "{", "validSyntax", "+=", "`", "${", "parsedClassName", ".", "helper", "}", "`", ";", "}", "else", "if", "(", "className", ".", "indexOf", "(", "'--'", ")", "!==", "-", "1", ")", "{", "validSyntax", "+=", "'--[modifier]'", ";", "}", "return", "validSyntax", ";", "}" ]
Helper for error messages to tell the correct syntax @param {string} className the class name @param {string[]} namespaces (optional) namespace @returns {string} valid syntax
[ "Helper", "for", "error", "messages", "to", "tell", "the", "correct", "syntax" ]
83deeb7871a49604b51b12bb48c0ac4186851a57
https://github.com/namics/stylelint-bem-namics/blob/83deeb7871a49604b51b12bb48c0ac4186851a57/index.js#L90-L112
10,139
i18next/react-i18next
react-i18next.js
pushTextNode
function pushTextNode(list, html, level, start, ignoreWhitespace) { // calculate correct end of the content slice in case there's // no tag after the text node. var end = html.indexOf('<', start); var content = html.slice(start, end === -1 ? undefined : end); // if a node is nothing but whitespace, collapse it as the spec states: // https://www.w3.org/TR/html4/struct/text.html#h-9.1 if (/^\s*$/.test(content)) { content = ' '; } // don't add whitespace-only text nodes if they would be trailing text nodes // or if they would be leading whitespace-only text nodes: // * end > -1 indicates this is not a trailing text node // * leading node is when level is -1 and list has length 0 if (!ignoreWhitespace && end > -1 && level + list.length >= 0 || content !== ' ') { list.push({ type: 'text', content: content }); } }
javascript
function pushTextNode(list, html, level, start, ignoreWhitespace) { // calculate correct end of the content slice in case there's // no tag after the text node. var end = html.indexOf('<', start); var content = html.slice(start, end === -1 ? undefined : end); // if a node is nothing but whitespace, collapse it as the spec states: // https://www.w3.org/TR/html4/struct/text.html#h-9.1 if (/^\s*$/.test(content)) { content = ' '; } // don't add whitespace-only text nodes if they would be trailing text nodes // or if they would be leading whitespace-only text nodes: // * end > -1 indicates this is not a trailing text node // * leading node is when level is -1 and list has length 0 if (!ignoreWhitespace && end > -1 && level + list.length >= 0 || content !== ' ') { list.push({ type: 'text', content: content }); } }
[ "function", "pushTextNode", "(", "list", ",", "html", ",", "level", ",", "start", ",", "ignoreWhitespace", ")", "{", "// calculate correct end of the content slice in case there's", "// no tag after the text node.", "var", "end", "=", "html", ".", "indexOf", "(", "'<'", ",", "start", ")", ";", "var", "content", "=", "html", ".", "slice", "(", "start", ",", "end", "===", "-", "1", "?", "undefined", ":", "end", ")", ";", "// if a node is nothing but whitespace, collapse it as the spec states:", "// https://www.w3.org/TR/html4/struct/text.html#h-9.1", "if", "(", "/", "^\\s*$", "/", ".", "test", "(", "content", ")", ")", "{", "content", "=", "' '", ";", "}", "// don't add whitespace-only text nodes if they would be trailing text nodes", "// or if they would be leading whitespace-only text nodes:", "// * end > -1 indicates this is not a trailing text node", "// * leading node is when level is -1 and list has length 0", "if", "(", "!", "ignoreWhitespace", "&&", "end", ">", "-", "1", "&&", "level", "+", "list", ".", "length", ">=", "0", "||", "content", "!==", "' '", ")", "{", "list", ".", "push", "(", "{", "type", ":", "'text'", ",", "content", ":", "content", "}", ")", ";", "}", "}" ]
common logic for pushing a child node onto a list
[ "common", "logic", "for", "pushing", "a", "child", "node", "onto", "a", "list" ]
8d1e5d469f78498c8f62bb4c7ceed58362c47d70
https://github.com/i18next/react-i18next/blob/8d1e5d469f78498c8f62bb4c7ceed58362c47d70/react-i18next.js#L195-L216
10,140
i18next/react-i18next
example/locize/src/App.js
Page
function Page() { const { t, i18n } = useTranslation(); const changeLanguage = lng => { i18n.changeLanguage(lng); }; return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <Welcome /> </div> <div className="App-intro"> <div> <button onClick={() => changeLanguage('de')}>de</button> <button onClick={() => changeLanguage('en')}>en</button> </div> <MyComponent /> </div> <div>{t('description.part2')}</div> </div> ); }
javascript
function Page() { const { t, i18n } = useTranslation(); const changeLanguage = lng => { i18n.changeLanguage(lng); }; return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <Welcome /> </div> <div className="App-intro"> <div> <button onClick={() => changeLanguage('de')}>de</button> <button onClick={() => changeLanguage('en')}>en</button> </div> <MyComponent /> </div> <div>{t('description.part2')}</div> </div> ); }
[ "function", "Page", "(", ")", "{", "const", "{", "t", ",", "i18n", "}", "=", "useTranslation", "(", ")", ";", "const", "changeLanguage", "=", "lng", "=>", "{", "i18n", ".", "changeLanguage", "(", "lng", ")", ";", "}", ";", "return", "(", "<", "div", "className", "=", "\"App\"", ">", "\n ", "<", "div", "className", "=", "\"App-header\"", ">", "\n ", "<", "img", "src", "=", "{", "logo", "}", "className", "=", "\"App-logo\"", "alt", "=", "\"logo\"", "/", ">", "\n ", "<", "Welcome", "/", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "div", "className", "=", "\"App-intro\"", ">", "\n ", "<", "div", ">", "\n ", "<", "button", "onClick", "=", "{", "(", ")", "=>", "changeLanguage", "(", "'de'", ")", "}", ">", "de", "<", "/", "button", ">", "\n ", "<", "button", "onClick", "=", "{", "(", ")", "=>", "changeLanguage", "(", "'en'", ")", "}", ">", "en", "<", "/", "button", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "MyComponent", "/", ">", "\n ", "<", "/", "div", ">", "\n ", "<", "div", ">", "{", "t", "(", "'description.part2'", ")", "}", "<", "/", "div", ">", "\n ", "<", "/", "div", ">", ")", ";", "}" ]
page uses the hook
[ "page", "uses", "the", "hook" ]
8d1e5d469f78498c8f62bb4c7ceed58362c47d70
https://github.com/i18next/react-i18next/blob/8d1e5d469f78498c8f62bb4c7ceed58362c47d70/example/locize/src/App.js#L25-L48
10,141
wycats/handlebars.js
spec/precompiler.js
mockRequireUglify
function mockRequireUglify(loadError, callback) { var Module = require('module'); var _resolveFilename = Module._resolveFilename; delete require.cache[require.resolve('uglify-js')]; delete require.cache[require.resolve('../dist/cjs/precompiler')]; Module._resolveFilename = function(request, mod) { if (request === 'uglify-js') { throw loadError; } return _resolveFilename.call(this, request, mod); }; try { callback(); } finally { Module._resolveFilename = _resolveFilename; delete require.cache[require.resolve('uglify-js')]; delete require.cache[require.resolve('../dist/cjs/precompiler')]; } }
javascript
function mockRequireUglify(loadError, callback) { var Module = require('module'); var _resolveFilename = Module._resolveFilename; delete require.cache[require.resolve('uglify-js')]; delete require.cache[require.resolve('../dist/cjs/precompiler')]; Module._resolveFilename = function(request, mod) { if (request === 'uglify-js') { throw loadError; } return _resolveFilename.call(this, request, mod); }; try { callback(); } finally { Module._resolveFilename = _resolveFilename; delete require.cache[require.resolve('uglify-js')]; delete require.cache[require.resolve('../dist/cjs/precompiler')]; } }
[ "function", "mockRequireUglify", "(", "loadError", ",", "callback", ")", "{", "var", "Module", "=", "require", "(", "'module'", ")", ";", "var", "_resolveFilename", "=", "Module", ".", "_resolveFilename", ";", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "'uglify-js'", ")", "]", ";", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "'../dist/cjs/precompiler'", ")", "]", ";", "Module", ".", "_resolveFilename", "=", "function", "(", "request", ",", "mod", ")", "{", "if", "(", "request", "===", "'uglify-js'", ")", "{", "throw", "loadError", ";", "}", "return", "_resolveFilename", ".", "call", "(", "this", ",", "request", ",", "mod", ")", ";", "}", ";", "try", "{", "callback", "(", ")", ";", "}", "finally", "{", "Module", ".", "_resolveFilename", "=", "_resolveFilename", ";", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "'uglify-js'", ")", "]", ";", "delete", "require", ".", "cache", "[", "require", ".", "resolve", "(", "'../dist/cjs/precompiler'", ")", "]", ";", "}", "}" ]
Mock the Module.prototype.require-function such that an error is thrown, when "uglify-js" is loaded. The function cleans up its mess when "callback" is finished @param {Error} loadError the error that should be thrown if uglify is loaded @param {function} callback a callback-function to run when the mock is active.
[ "Mock", "the", "Module", ".", "prototype", ".", "require", "-", "function", "such", "that", "an", "error", "is", "thrown", "when", "uglify", "-", "js", "is", "loaded", "." ]
3ce4425056998c1db921d7b6c0662b843acb593b
https://github.com/wycats/handlebars.js/blob/3ce4425056998c1db921d7b6c0662b843acb593b/spec/precompiler.js#L39-L57
10,142
wycats/handlebars.js
lib/precompiler.js
minify
function minify(output, sourceMapFile) { try { // Try to resolve uglify-js in order to see if it does exist require.resolve('uglify-js'); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { // Something else seems to be wrong throw e; } // it does not exist! console.error('Code minimization is disabled due to missing uglify-js dependency'); return output; } return require('uglify-js').minify(output.code, { sourceMap: { content: output.map, url: sourceMapFile } }); }
javascript
function minify(output, sourceMapFile) { try { // Try to resolve uglify-js in order to see if it does exist require.resolve('uglify-js'); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { // Something else seems to be wrong throw e; } // it does not exist! console.error('Code minimization is disabled due to missing uglify-js dependency'); return output; } return require('uglify-js').minify(output.code, { sourceMap: { content: output.map, url: sourceMapFile } }); }
[ "function", "minify", "(", "output", ",", "sourceMapFile", ")", "{", "try", "{", "// Try to resolve uglify-js in order to see if it does exist", "require", ".", "resolve", "(", "'uglify-js'", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "!==", "'MODULE_NOT_FOUND'", ")", "{", "// Something else seems to be wrong", "throw", "e", ";", "}", "// it does not exist!", "console", ".", "error", "(", "'Code minimization is disabled due to missing uglify-js dependency'", ")", ";", "return", "output", ";", "}", "return", "require", "(", "'uglify-js'", ")", ".", "minify", "(", "output", ".", "code", ",", "{", "sourceMap", ":", "{", "content", ":", "output", ".", "map", ",", "url", ":", "sourceMapFile", "}", "}", ")", ";", "}" ]
Run uglify to minify the compiled template, if uglify exists in the dependencies. We are using `require` instead of `import` here, because es6-modules do not allow dynamic imports and uglify-js is an optional dependency. Since we are inside NodeJS here, this should not be a problem. @param {string} output the compiled template @param {string} sourceMapFile the file to write the source map to.
[ "Run", "uglify", "to", "minify", "the", "compiled", "template", "if", "uglify", "exists", "in", "the", "dependencies", "." ]
3ce4425056998c1db921d7b6c0662b843acb593b
https://github.com/wycats/handlebars.js/blob/3ce4425056998c1db921d7b6c0662b843acb593b/lib/precompiler.js#L279-L298
10,143
wycats/handlebars.js
lib/handlebars/compiler/visitor.js
function(node, name) { let value = this.accept(node[name]); if (this.mutating) { // Hacky sanity check: This may have a few false positives for type for the helper // methods but will generally do the right thing without a lot of overhead. if (value && !Visitor.prototype[value.type]) { throw new Exception('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type); } node[name] = value; } }
javascript
function(node, name) { let value = this.accept(node[name]); if (this.mutating) { // Hacky sanity check: This may have a few false positives for type for the helper // methods but will generally do the right thing without a lot of overhead. if (value && !Visitor.prototype[value.type]) { throw new Exception('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type); } node[name] = value; } }
[ "function", "(", "node", ",", "name", ")", "{", "let", "value", "=", "this", ".", "accept", "(", "node", "[", "name", "]", ")", ";", "if", "(", "this", ".", "mutating", ")", "{", "// Hacky sanity check: This may have a few false positives for type for the helper", "// methods but will generally do the right thing without a lot of overhead.", "if", "(", "value", "&&", "!", "Visitor", ".", "prototype", "[", "value", ".", "type", "]", ")", "{", "throw", "new", "Exception", "(", "'Unexpected node type \"'", "+", "value", ".", "type", "+", "'\" found when accepting '", "+", "name", "+", "' on '", "+", "node", ".", "type", ")", ";", "}", "node", "[", "name", "]", "=", "value", ";", "}", "}" ]
Visits a given value. If mutating, will replace the value if necessary.
[ "Visits", "a", "given", "value", ".", "If", "mutating", "will", "replace", "the", "value", "if", "necessary", "." ]
3ce4425056998c1db921d7b6c0662b843acb593b
https://github.com/wycats/handlebars.js/blob/3ce4425056998c1db921d7b6c0662b843acb593b/lib/handlebars/compiler/visitor.js#L12-L22
10,144
wycats/handlebars.js
lib/handlebars/compiler/visitor.js
function(node, name) { this.acceptKey(node, name); if (!node[name]) { throw new Exception(node.type + ' requires ' + name); } }
javascript
function(node, name) { this.acceptKey(node, name); if (!node[name]) { throw new Exception(node.type + ' requires ' + name); } }
[ "function", "(", "node", ",", "name", ")", "{", "this", ".", "acceptKey", "(", "node", ",", "name", ")", ";", "if", "(", "!", "node", "[", "name", "]", ")", "{", "throw", "new", "Exception", "(", "node", ".", "type", "+", "' requires '", "+", "name", ")", ";", "}", "}" ]
Performs an accept operation with added sanity check to ensure required keys are not removed.
[ "Performs", "an", "accept", "operation", "with", "added", "sanity", "check", "to", "ensure", "required", "keys", "are", "not", "removed", "." ]
3ce4425056998c1db921d7b6c0662b843acb593b
https://github.com/wycats/handlebars.js/blob/3ce4425056998c1db921d7b6c0662b843acb593b/lib/handlebars/compiler/visitor.js#L26-L32
10,145
facebook/regenerator
packages/regenerator-transform/src/visit.js
shouldRegenerate
function shouldRegenerate(node, state) { if (node.generator) { if (node.async) { // Async generator return state.opts.asyncGenerators !== false; } else { // Plain generator return state.opts.generators !== false; } } else if (node.async) { // Async function return state.opts.async !== false; } else { // Not a generator or async function. return false; } }
javascript
function shouldRegenerate(node, state) { if (node.generator) { if (node.async) { // Async generator return state.opts.asyncGenerators !== false; } else { // Plain generator return state.opts.generators !== false; } } else if (node.async) { // Async function return state.opts.async !== false; } else { // Not a generator or async function. return false; } }
[ "function", "shouldRegenerate", "(", "node", ",", "state", ")", "{", "if", "(", "node", ".", "generator", ")", "{", "if", "(", "node", ".", "async", ")", "{", "// Async generator", "return", "state", ".", "opts", ".", "asyncGenerators", "!==", "false", ";", "}", "else", "{", "// Plain generator", "return", "state", ".", "opts", ".", "generators", "!==", "false", ";", "}", "}", "else", "if", "(", "node", ".", "async", ")", "{", "// Async function", "return", "state", ".", "opts", ".", "async", "!==", "false", ";", "}", "else", "{", "// Not a generator or async function.", "return", "false", ";", "}", "}" ]
Check if a node should be transformed by regenerator
[ "Check", "if", "a", "node", "should", "be", "transformed", "by", "regenerator" ]
d4ccc3ba278753c7c37e2db2147834007b9075b1
https://github.com/facebook/regenerator/blob/d4ccc3ba278753c7c37e2db2147834007b9075b1/packages/regenerator-transform/src/visit.js#L202-L218
10,146
facebook/regenerator
packages/regenerator-transform/src/visit.js
getOuterFnExpr
function getOuterFnExpr(funPath) { const t = util.getTypes(); let node = funPath.node; t.assertFunction(node); if (!node.id) { // Default-exported function declarations, and function expressions may not // have a name to reference, so we explicitly add one. node.id = funPath.scope.parent.generateUidIdentifier("callee"); } if (node.generator && // Non-generator functions don't need to be marked. t.isFunctionDeclaration(node)) { // Return the identifier returned by runtime.mark(<node.id>). return getMarkedFunctionId(funPath); } return t.clone(node.id); }
javascript
function getOuterFnExpr(funPath) { const t = util.getTypes(); let node = funPath.node; t.assertFunction(node); if (!node.id) { // Default-exported function declarations, and function expressions may not // have a name to reference, so we explicitly add one. node.id = funPath.scope.parent.generateUidIdentifier("callee"); } if (node.generator && // Non-generator functions don't need to be marked. t.isFunctionDeclaration(node)) { // Return the identifier returned by runtime.mark(<node.id>). return getMarkedFunctionId(funPath); } return t.clone(node.id); }
[ "function", "getOuterFnExpr", "(", "funPath", ")", "{", "const", "t", "=", "util", ".", "getTypes", "(", ")", ";", "let", "node", "=", "funPath", ".", "node", ";", "t", ".", "assertFunction", "(", "node", ")", ";", "if", "(", "!", "node", ".", "id", ")", "{", "// Default-exported function declarations, and function expressions may not", "// have a name to reference, so we explicitly add one.", "node", ".", "id", "=", "funPath", ".", "scope", ".", "parent", ".", "generateUidIdentifier", "(", "\"callee\"", ")", ";", "}", "if", "(", "node", ".", "generator", "&&", "// Non-generator functions don't need to be marked.", "t", ".", "isFunctionDeclaration", "(", "node", ")", ")", "{", "// Return the identifier returned by runtime.mark(<node.id>).", "return", "getMarkedFunctionId", "(", "funPath", ")", ";", "}", "return", "t", ".", "clone", "(", "node", ".", "id", ")", ";", "}" ]
Given a NodePath for a Function, return an Expression node that can be used to refer reliably to the function object from inside the function. This expression is essentially a replacement for arguments.callee, with the key advantage that it works in strict mode.
[ "Given", "a", "NodePath", "for", "a", "Function", "return", "an", "Expression", "node", "that", "can", "be", "used", "to", "refer", "reliably", "to", "the", "function", "object", "from", "inside", "the", "function", ".", "This", "expression", "is", "essentially", "a", "replacement", "for", "arguments", ".", "callee", "with", "the", "key", "advantage", "that", "it", "works", "in", "strict", "mode", "." ]
d4ccc3ba278753c7c37e2db2147834007b9075b1
https://github.com/facebook/regenerator/blob/d4ccc3ba278753c7c37e2db2147834007b9075b1/packages/regenerator-transform/src/visit.js#L224-L242
10,147
facebook/regenerator
packages/regenerator-transform/src/emit.js
explodeViaTempVar
function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { assert.ok( !ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?" ); let result = self.explodeExpression(childPath, ignoreChildResult); if (ignoreChildResult) { // Side effects already emitted above. } else if (tempVar || (hasLeapingChildren && !t.isLiteral(result))) { // If tempVar was provided, then the result will always be assigned // to it, even if the result does not otherwise need to be assigned // to a temporary variable. When no tempVar is provided, we have // the flexibility to decide whether a temporary variable is really // necessary. Unfortunately, in general, a temporary variable is // required whenever any child contains a yield expression, since it // is difficult to prove (at all, let alone efficiently) whether // this result would evaluate to the same value before and after the // yield (see #206). One narrow case where we can prove it doesn't // matter (and thus we do not need a temporary variable) is when the // result in question is a Literal value. result = self.emitAssign( tempVar || self.makeTempVar(), result ); } return result; }
javascript
function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { assert.ok( !ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?" ); let result = self.explodeExpression(childPath, ignoreChildResult); if (ignoreChildResult) { // Side effects already emitted above. } else if (tempVar || (hasLeapingChildren && !t.isLiteral(result))) { // If tempVar was provided, then the result will always be assigned // to it, even if the result does not otherwise need to be assigned // to a temporary variable. When no tempVar is provided, we have // the flexibility to decide whether a temporary variable is really // necessary. Unfortunately, in general, a temporary variable is // required whenever any child contains a yield expression, since it // is difficult to prove (at all, let alone efficiently) whether // this result would evaluate to the same value before and after the // yield (see #206). One narrow case where we can prove it doesn't // matter (and thus we do not need a temporary variable) is when the // result in question is a Literal value. result = self.emitAssign( tempVar || self.makeTempVar(), result ); } return result; }
[ "function", "explodeViaTempVar", "(", "tempVar", ",", "childPath", ",", "ignoreChildResult", ")", "{", "assert", ".", "ok", "(", "!", "ignoreChildResult", "||", "!", "tempVar", ",", "\"Ignoring the result of a child expression but forcing it to \"", "+", "\"be assigned to a temporary variable?\"", ")", ";", "let", "result", "=", "self", ".", "explodeExpression", "(", "childPath", ",", "ignoreChildResult", ")", ";", "if", "(", "ignoreChildResult", ")", "{", "// Side effects already emitted above.", "}", "else", "if", "(", "tempVar", "||", "(", "hasLeapingChildren", "&&", "!", "t", ".", "isLiteral", "(", "result", ")", ")", ")", "{", "// If tempVar was provided, then the result will always be assigned", "// to it, even if the result does not otherwise need to be assigned", "// to a temporary variable. When no tempVar is provided, we have", "// the flexibility to decide whether a temporary variable is really", "// necessary. Unfortunately, in general, a temporary variable is", "// required whenever any child contains a yield expression, since it", "// is difficult to prove (at all, let alone efficiently) whether", "// this result would evaluate to the same value before and after the", "// yield (see #206). One narrow case where we can prove it doesn't", "// matter (and thus we do not need a temporary variable) is when the", "// result in question is a Literal value.", "result", "=", "self", ".", "emitAssign", "(", "tempVar", "||", "self", ".", "makeTempVar", "(", ")", ",", "result", ")", ";", "}", "return", "result", ";", "}" ]
In order to save the rest of explodeExpression from a combinatorial trainwreck of special cases, explodeViaTempVar is responsible for deciding when a subexpression needs to be "exploded," which is my very technical term for emitting the subexpression as an assignment to a temporary variable and the substituting the temporary variable for the original subexpression. Think of exploded view diagrams, not Michael Bay movies. The point of exploding subexpressions is to control the precise order in which the generated code realizes the side effects of those subexpressions.
[ "In", "order", "to", "save", "the", "rest", "of", "explodeExpression", "from", "a", "combinatorial", "trainwreck", "of", "special", "cases", "explodeViaTempVar", "is", "responsible", "for", "deciding", "when", "a", "subexpression", "needs", "to", "be", "exploded", "which", "is", "my", "very", "technical", "term", "for", "emitting", "the", "subexpression", "as", "an", "assignment", "to", "a", "temporary", "variable", "and", "the", "substituting", "the", "temporary", "variable", "for", "the", "original", "subexpression", ".", "Think", "of", "exploded", "view", "diagrams", "not", "Michael", "Bay", "movies", ".", "The", "point", "of", "exploding", "subexpressions", "is", "to", "control", "the", "precise", "order", "in", "which", "the", "generated", "code", "realizes", "the", "side", "effects", "of", "those", "subexpressions", "." ]
d4ccc3ba278753c7c37e2db2147834007b9075b1
https://github.com/facebook/regenerator/blob/d4ccc3ba278753c7c37e2db2147834007b9075b1/packages/regenerator-transform/src/emit.js#L946-L977
10,148
willmcpo/body-scroll-lock
lib/bodyScrollLock.js
allowTouchMove
function allowTouchMove(el) { return locks.some(function (lock) { if (lock.options.allowTouchMove && lock.options.allowTouchMove(el)) { return true; } return false; }); }
javascript
function allowTouchMove(el) { return locks.some(function (lock) { if (lock.options.allowTouchMove && lock.options.allowTouchMove(el)) { return true; } return false; }); }
[ "function", "allowTouchMove", "(", "el", ")", "{", "return", "locks", ".", "some", "(", "function", "(", "lock", ")", "{", "if", "(", "lock", ".", "options", ".", "allowTouchMove", "&&", "lock", ".", "options", ".", "allowTouchMove", "(", "el", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "}" ]
returns true if `el` should be allowed to receive touchmove events
[ "returns", "true", "if", "el", "should", "be", "allowed", "to", "receive", "touchmove", "events" ]
0e65e5fc9018b84975440b92ac84669f21ea5b3b
https://github.com/willmcpo/body-scroll-lock/blob/0e65e5fc9018b84975440b92ac84669f21ea5b3b/lib/bodyScrollLock.js#L59-L67
10,149
benmosher/eslint-plugin-import
src/rules/no-useless-path-segments.js
toRelativePath
function toRelativePath(relativePath) { const stripped = relativePath.replace(/\/$/g, '') // Remove trailing / return /^((\.\.)|(\.))($|\/)/.test(stripped) ? stripped : `./${stripped}` }
javascript
function toRelativePath(relativePath) { const stripped = relativePath.replace(/\/$/g, '') // Remove trailing / return /^((\.\.)|(\.))($|\/)/.test(stripped) ? stripped : `./${stripped}` }
[ "function", "toRelativePath", "(", "relativePath", ")", "{", "const", "stripped", "=", "relativePath", ".", "replace", "(", "/", "\\/$", "/", "g", ",", "''", ")", "// Remove trailing /", "return", "/", "^((\\.\\.)|(\\.))($|\\/)", "/", ".", "test", "(", "stripped", ")", "?", "stripped", ":", "`", "${", "stripped", "}", "`", "}" ]
convert a potentially relative path from node utils into a true relative path. ../ -> .. ./ -> . .foo/bar -> ./.foo/bar ..foo/bar -> ./..foo/bar foo/bar -> ./foo/bar @param relativePath {string} relative posix path potentially missing leading './' @returns {string} relative posix path that always starts with a ./
[ "convert", "a", "potentially", "relative", "path", "from", "node", "utils", "into", "a", "true", "relative", "path", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/no-useless-path-segments.js#L25-L29
10,150
benmosher/eslint-plugin-import
src/rules/no-duplicates.js
getDefaultImportName
function getDefaultImportName(node) { const defaultSpecifier = node.specifiers .find(specifier => specifier.type === 'ImportDefaultSpecifier') return defaultSpecifier != null ? defaultSpecifier.local.name : undefined }
javascript
function getDefaultImportName(node) { const defaultSpecifier = node.specifiers .find(specifier => specifier.type === 'ImportDefaultSpecifier') return defaultSpecifier != null ? defaultSpecifier.local.name : undefined }
[ "function", "getDefaultImportName", "(", "node", ")", "{", "const", "defaultSpecifier", "=", "node", ".", "specifiers", ".", "find", "(", "specifier", "=>", "specifier", ".", "type", "===", "'ImportDefaultSpecifier'", ")", "return", "defaultSpecifier", "!=", "null", "?", "defaultSpecifier", ".", "local", ".", "name", ":", "undefined", "}" ]
Get the name of the default import of `node`, if any.
[ "Get", "the", "name", "of", "the", "default", "import", "of", "node", "if", "any", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/no-duplicates.js#L167-L171
10,151
benmosher/eslint-plugin-import
src/rules/no-duplicates.js
hasNamespace
function hasNamespace(node) { const specifiers = node.specifiers .filter(specifier => specifier.type === 'ImportNamespaceSpecifier') return specifiers.length > 0 }
javascript
function hasNamespace(node) { const specifiers = node.specifiers .filter(specifier => specifier.type === 'ImportNamespaceSpecifier') return specifiers.length > 0 }
[ "function", "hasNamespace", "(", "node", ")", "{", "const", "specifiers", "=", "node", ".", "specifiers", ".", "filter", "(", "specifier", "=>", "specifier", ".", "type", "===", "'ImportNamespaceSpecifier'", ")", "return", "specifiers", ".", "length", ">", "0", "}" ]
Checks whether `node` has a namespace import.
[ "Checks", "whether", "node", "has", "a", "namespace", "import", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/no-duplicates.js#L174-L178
10,152
benmosher/eslint-plugin-import
src/rules/no-duplicates.js
hasSpecifiers
function hasSpecifiers(node) { const specifiers = node.specifiers .filter(specifier => specifier.type === 'ImportSpecifier') return specifiers.length > 0 }
javascript
function hasSpecifiers(node) { const specifiers = node.specifiers .filter(specifier => specifier.type === 'ImportSpecifier') return specifiers.length > 0 }
[ "function", "hasSpecifiers", "(", "node", ")", "{", "const", "specifiers", "=", "node", ".", "specifiers", ".", "filter", "(", "specifier", "=>", "specifier", ".", "type", "===", "'ImportSpecifier'", ")", "return", "specifiers", ".", "length", ">", "0", "}" ]
Checks whether `node` has any non-default specifiers.
[ "Checks", "whether", "node", "has", "any", "non", "-", "default", "specifiers", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/no-duplicates.js#L181-L185
10,153
benmosher/eslint-plugin-import
src/rules/no-duplicates.js
hasProblematicComments
function hasProblematicComments(node, sourceCode) { return ( hasCommentBefore(node, sourceCode) || hasCommentAfter(node, sourceCode) || hasCommentInsideNonSpecifiers(node, sourceCode) ) }
javascript
function hasProblematicComments(node, sourceCode) { return ( hasCommentBefore(node, sourceCode) || hasCommentAfter(node, sourceCode) || hasCommentInsideNonSpecifiers(node, sourceCode) ) }
[ "function", "hasProblematicComments", "(", "node", ",", "sourceCode", ")", "{", "return", "(", "hasCommentBefore", "(", "node", ",", "sourceCode", ")", "||", "hasCommentAfter", "(", "node", ",", "sourceCode", ")", "||", "hasCommentInsideNonSpecifiers", "(", "node", ",", "sourceCode", ")", ")", "}" ]
It's not obvious what the user wants to do with comments associated with duplicate imports, so skip imports with comments when autofixing.
[ "It", "s", "not", "obvious", "what", "the", "user", "wants", "to", "do", "with", "comments", "associated", "with", "duplicate", "imports", "so", "skip", "imports", "with", "comments", "when", "autofixing", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/no-duplicates.js#L189-L195
10,154
benmosher/eslint-plugin-import
utils/module-require.js
createModule
function createModule(filename) { const mod = new Module(filename) mod.filename = filename mod.paths = Module._nodeModulePaths(path.dirname(filename)) return mod }
javascript
function createModule(filename) { const mod = new Module(filename) mod.filename = filename mod.paths = Module._nodeModulePaths(path.dirname(filename)) return mod }
[ "function", "createModule", "(", "filename", ")", "{", "const", "mod", "=", "new", "Module", "(", "filename", ")", "mod", ".", "filename", "=", "filename", "mod", ".", "paths", "=", "Module", ".", "_nodeModulePaths", "(", "path", ".", "dirname", "(", "filename", ")", ")", "return", "mod", "}" ]
borrowed from babel-eslint
[ "borrowed", "from", "babel", "-", "eslint" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/utils/module-require.js#L8-L13
10,155
benmosher/eslint-plugin-import
src/rules/namespace.js
function ({ body }) { function processBodyStatement(declaration) { if (declaration.type !== 'ImportDeclaration') return if (declaration.specifiers.length === 0) return const imports = Exports.get(declaration.source.value, context) if (imports == null) return null if (imports.errors.length) { imports.reportErrors(context, declaration) return } for (const specifier of declaration.specifiers) { switch (specifier.type) { case 'ImportNamespaceSpecifier': if (!imports.size) { context.report(specifier, `No exported names found in module '${declaration.source.value}'.`) } namespaces.set(specifier.local.name, imports) break case 'ImportDefaultSpecifier': case 'ImportSpecifier': { const meta = imports.get( // default to 'default' for default http://i.imgur.com/nj6qAWy.jpg specifier.imported ? specifier.imported.name : 'default') if (!meta || !meta.namespace) break namespaces.set(specifier.local.name, meta.namespace) break } } } } body.forEach(processBodyStatement) }
javascript
function ({ body }) { function processBodyStatement(declaration) { if (declaration.type !== 'ImportDeclaration') return if (declaration.specifiers.length === 0) return const imports = Exports.get(declaration.source.value, context) if (imports == null) return null if (imports.errors.length) { imports.reportErrors(context, declaration) return } for (const specifier of declaration.specifiers) { switch (specifier.type) { case 'ImportNamespaceSpecifier': if (!imports.size) { context.report(specifier, `No exported names found in module '${declaration.source.value}'.`) } namespaces.set(specifier.local.name, imports) break case 'ImportDefaultSpecifier': case 'ImportSpecifier': { const meta = imports.get( // default to 'default' for default http://i.imgur.com/nj6qAWy.jpg specifier.imported ? specifier.imported.name : 'default') if (!meta || !meta.namespace) break namespaces.set(specifier.local.name, meta.namespace) break } } } } body.forEach(processBodyStatement) }
[ "function", "(", "{", "body", "}", ")", "{", "function", "processBodyStatement", "(", "declaration", ")", "{", "if", "(", "declaration", ".", "type", "!==", "'ImportDeclaration'", ")", "return", "if", "(", "declaration", ".", "specifiers", ".", "length", "===", "0", ")", "return", "const", "imports", "=", "Exports", ".", "get", "(", "declaration", ".", "source", ".", "value", ",", "context", ")", "if", "(", "imports", "==", "null", ")", "return", "null", "if", "(", "imports", ".", "errors", ".", "length", ")", "{", "imports", ".", "reportErrors", "(", "context", ",", "declaration", ")", "return", "}", "for", "(", "const", "specifier", "of", "declaration", ".", "specifiers", ")", "{", "switch", "(", "specifier", ".", "type", ")", "{", "case", "'ImportNamespaceSpecifier'", ":", "if", "(", "!", "imports", ".", "size", ")", "{", "context", ".", "report", "(", "specifier", ",", "`", "${", "declaration", ".", "source", ".", "value", "}", "`", ")", "}", "namespaces", ".", "set", "(", "specifier", ".", "local", ".", "name", ",", "imports", ")", "break", "case", "'ImportDefaultSpecifier'", ":", "case", "'ImportSpecifier'", ":", "{", "const", "meta", "=", "imports", ".", "get", "(", "// default to 'default' for default http://i.imgur.com/nj6qAWy.jpg", "specifier", ".", "imported", "?", "specifier", ".", "imported", ".", "name", ":", "'default'", ")", "if", "(", "!", "meta", "||", "!", "meta", ".", "namespace", ")", "break", "namespaces", ".", "set", "(", "specifier", ".", "local", ".", "name", ",", "meta", ".", "namespace", ")", "break", "}", "}", "}", "}", "body", ".", "forEach", "(", "processBodyStatement", ")", "}" ]
pick up all imports at body entry time, to properly respect hoisting
[ "pick", "up", "all", "imports", "at", "body", "entry", "time", "to", "properly", "respect", "hoisting" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/namespace.js#L48-L84
10,156
benmosher/eslint-plugin-import
src/rules/namespace.js
function (namespace) { var declaration = importDeclaration(context) var imports = Exports.get(declaration.source.value, context) if (imports == null) return null if (imports.errors.length) { imports.reportErrors(context, declaration) return } if (!imports.size) { context.report(namespace, `No exported names found in module '${declaration.source.value}'.`) } }
javascript
function (namespace) { var declaration = importDeclaration(context) var imports = Exports.get(declaration.source.value, context) if (imports == null) return null if (imports.errors.length) { imports.reportErrors(context, declaration) return } if (!imports.size) { context.report(namespace, `No exported names found in module '${declaration.source.value}'.`) } }
[ "function", "(", "namespace", ")", "{", "var", "declaration", "=", "importDeclaration", "(", "context", ")", "var", "imports", "=", "Exports", ".", "get", "(", "declaration", ".", "source", ".", "value", ",", "context", ")", "if", "(", "imports", "==", "null", ")", "return", "null", "if", "(", "imports", ".", "errors", ".", "length", ")", "{", "imports", ".", "reportErrors", "(", "context", ",", "declaration", ")", "return", "}", "if", "(", "!", "imports", ".", "size", ")", "{", "context", ".", "report", "(", "namespace", ",", "`", "${", "declaration", ".", "source", ".", "value", "}", "`", ")", "}", "}" ]
same as above, but does not add names to local map
[ "same", "as", "above", "but", "does", "not", "add", "names", "to", "local", "map" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/namespace.js#L87-L102
10,157
benmosher/eslint-plugin-import
utils/moduleVisitor.js
checkCommon
function checkCommon(call) { if (call.callee.type !== 'Identifier') return if (call.callee.name !== 'require') return if (call.arguments.length !== 1) return const modulePath = call.arguments[0] if (modulePath.type !== 'Literal') return if (typeof modulePath.value !== 'string') return checkSourceValue(modulePath, call) }
javascript
function checkCommon(call) { if (call.callee.type !== 'Identifier') return if (call.callee.name !== 'require') return if (call.arguments.length !== 1) return const modulePath = call.arguments[0] if (modulePath.type !== 'Literal') return if (typeof modulePath.value !== 'string') return checkSourceValue(modulePath, call) }
[ "function", "checkCommon", "(", "call", ")", "{", "if", "(", "call", ".", "callee", ".", "type", "!==", "'Identifier'", ")", "return", "if", "(", "call", ".", "callee", ".", "name", "!==", "'require'", ")", "return", "if", "(", "call", ".", "arguments", ".", "length", "!==", "1", ")", "return", "const", "modulePath", "=", "call", ".", "arguments", "[", "0", "]", "if", "(", "modulePath", ".", "type", "!==", "'Literal'", ")", "return", "if", "(", "typeof", "modulePath", ".", "value", "!==", "'string'", ")", "return", "checkSourceValue", "(", "modulePath", ",", "call", ")", "}" ]
for CommonJS `require` calls adapted from @mctep: http://git.io/v4rAu
[ "for", "CommonJS", "require", "calls", "adapted", "from" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/utils/moduleVisitor.js#L51-L61
10,158
benmosher/eslint-plugin-import
utils/moduleVisitor.js
makeOptionsSchema
function makeOptionsSchema(additionalProperties) { const base = { 'type': 'object', 'properties': { 'commonjs': { 'type': 'boolean' }, 'amd': { 'type': 'boolean' }, 'esmodule': { 'type': 'boolean' }, 'ignore': { 'type': 'array', 'minItems': 1, 'items': { 'type': 'string' }, 'uniqueItems': true, }, }, 'additionalProperties': false, } if (additionalProperties){ for (let key in additionalProperties) { base.properties[key] = additionalProperties[key] } } return base }
javascript
function makeOptionsSchema(additionalProperties) { const base = { 'type': 'object', 'properties': { 'commonjs': { 'type': 'boolean' }, 'amd': { 'type': 'boolean' }, 'esmodule': { 'type': 'boolean' }, 'ignore': { 'type': 'array', 'minItems': 1, 'items': { 'type': 'string' }, 'uniqueItems': true, }, }, 'additionalProperties': false, } if (additionalProperties){ for (let key in additionalProperties) { base.properties[key] = additionalProperties[key] } } return base }
[ "function", "makeOptionsSchema", "(", "additionalProperties", ")", "{", "const", "base", "=", "{", "'type'", ":", "'object'", ",", "'properties'", ":", "{", "'commonjs'", ":", "{", "'type'", ":", "'boolean'", "}", ",", "'amd'", ":", "{", "'type'", ":", "'boolean'", "}", ",", "'esmodule'", ":", "{", "'type'", ":", "'boolean'", "}", ",", "'ignore'", ":", "{", "'type'", ":", "'array'", ",", "'minItems'", ":", "1", ",", "'items'", ":", "{", "'type'", ":", "'string'", "}", ",", "'uniqueItems'", ":", "true", ",", "}", ",", "}", ",", "'additionalProperties'", ":", "false", ",", "}", "if", "(", "additionalProperties", ")", "{", "for", "(", "let", "key", "in", "additionalProperties", ")", "{", "base", ".", "properties", "[", "key", "]", "=", "additionalProperties", "[", "key", "]", "}", "}", "return", "base", "}" ]
make an options schema for the module visitor, optionally adding extra fields.
[ "make", "an", "options", "schema", "for", "the", "module", "visitor", "optionally", "adding", "extra", "fields", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/utils/moduleVisitor.js#L109-L133
10,159
benmosher/eslint-plugin-import
src/rules/order.js
reverse
function reverse(array) { return array.map(function (v) { return { name: v.name, rank: -v.rank, node: v.node, } }).reverse() }
javascript
function reverse(array) { return array.map(function (v) { return { name: v.name, rank: -v.rank, node: v.node, } }).reverse() }
[ "function", "reverse", "(", "array", ")", "{", "return", "array", ".", "map", "(", "function", "(", "v", ")", "{", "return", "{", "name", ":", "v", ".", "name", ",", "rank", ":", "-", "v", ".", "rank", ",", "node", ":", "v", ".", "node", ",", "}", "}", ")", ".", "reverse", "(", ")", "}" ]
REPORTING AND FIXING
[ "REPORTING", "AND", "FIXING" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/order.js#L11-L19
10,160
benmosher/eslint-plugin-import
src/rules/no-internal-modules.js
isReachViolation
function isReachViolation(importPath) { const steps = normalizeSep(importPath) .split('/') .reduce((acc, step) => { if (!step || step === '.') { return acc } else if (step === '..') { return acc.slice(0, -1) } else { return acc.concat(step) } }, []) const nonScopeSteps = steps.filter(step => step.indexOf('@') !== 0) if (nonScopeSteps.length <= 1) return false // before trying to resolve, see if the raw import (with relative // segments resolved) matches an allowed pattern const justSteps = steps.join('/') if (reachingAllowed(justSteps) || reachingAllowed(`/${justSteps}`)) return false // if the import statement doesn't match directly, try to match the // resolved path if the import is resolvable const resolved = resolve(importPath, context) if (!resolved || reachingAllowed(normalizeSep(resolved))) return false // this import was not allowed by the allowed paths, and reaches // so it is a violation return true }
javascript
function isReachViolation(importPath) { const steps = normalizeSep(importPath) .split('/') .reduce((acc, step) => { if (!step || step === '.') { return acc } else if (step === '..') { return acc.slice(0, -1) } else { return acc.concat(step) } }, []) const nonScopeSteps = steps.filter(step => step.indexOf('@') !== 0) if (nonScopeSteps.length <= 1) return false // before trying to resolve, see if the raw import (with relative // segments resolved) matches an allowed pattern const justSteps = steps.join('/') if (reachingAllowed(justSteps) || reachingAllowed(`/${justSteps}`)) return false // if the import statement doesn't match directly, try to match the // resolved path if the import is resolvable const resolved = resolve(importPath, context) if (!resolved || reachingAllowed(normalizeSep(resolved))) return false // this import was not allowed by the allowed paths, and reaches // so it is a violation return true }
[ "function", "isReachViolation", "(", "importPath", ")", "{", "const", "steps", "=", "normalizeSep", "(", "importPath", ")", ".", "split", "(", "'/'", ")", ".", "reduce", "(", "(", "acc", ",", "step", ")", "=>", "{", "if", "(", "!", "step", "||", "step", "===", "'.'", ")", "{", "return", "acc", "}", "else", "if", "(", "step", "===", "'..'", ")", "{", "return", "acc", ".", "slice", "(", "0", ",", "-", "1", ")", "}", "else", "{", "return", "acc", ".", "concat", "(", "step", ")", "}", "}", ",", "[", "]", ")", "const", "nonScopeSteps", "=", "steps", ".", "filter", "(", "step", "=>", "step", ".", "indexOf", "(", "'@'", ")", "!==", "0", ")", "if", "(", "nonScopeSteps", ".", "length", "<=", "1", ")", "return", "false", "// before trying to resolve, see if the raw import (with relative", "// segments resolved) matches an allowed pattern", "const", "justSteps", "=", "steps", ".", "join", "(", "'/'", ")", "if", "(", "reachingAllowed", "(", "justSteps", ")", "||", "reachingAllowed", "(", "`", "${", "justSteps", "}", "`", ")", ")", "return", "false", "// if the import statement doesn't match directly, try to match the", "// resolved path if the import is resolvable", "const", "resolved", "=", "resolve", "(", "importPath", ",", "context", ")", "if", "(", "!", "resolved", "||", "reachingAllowed", "(", "normalizeSep", "(", "resolved", ")", ")", ")", "return", "false", "// this import was not allowed by the allowed paths, and reaches", "// so it is a violation", "return", "true", "}" ]
find a directory that is being reached into, but which shouldn't be
[ "find", "a", "directory", "that", "is", "being", "reached", "into", "but", "which", "shouldn", "t", "be" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/rules/no-internal-modules.js#L47-L76
10,161
benmosher/eslint-plugin-import
src/ExportMap.js
captureDoc
function captureDoc(source, docStyleParsers, ...nodes) { const metadata = {} // 'some' short-circuits on first 'true' nodes.some(n => { try { let leadingComments // n.leadingComments is legacy `attachComments` behavior if ('leadingComments' in n) { leadingComments = n.leadingComments } else if (n.range) { leadingComments = source.getCommentsBefore(n) } if (!leadingComments || leadingComments.length === 0) return false for (let name in docStyleParsers) { const doc = docStyleParsers[name](leadingComments) if (doc) { metadata.doc = doc } } return true } catch (err) { return false } }) return metadata }
javascript
function captureDoc(source, docStyleParsers, ...nodes) { const metadata = {} // 'some' short-circuits on first 'true' nodes.some(n => { try { let leadingComments // n.leadingComments is legacy `attachComments` behavior if ('leadingComments' in n) { leadingComments = n.leadingComments } else if (n.range) { leadingComments = source.getCommentsBefore(n) } if (!leadingComments || leadingComments.length === 0) return false for (let name in docStyleParsers) { const doc = docStyleParsers[name](leadingComments) if (doc) { metadata.doc = doc } } return true } catch (err) { return false } }) return metadata }
[ "function", "captureDoc", "(", "source", ",", "docStyleParsers", ",", "...", "nodes", ")", "{", "const", "metadata", "=", "{", "}", "// 'some' short-circuits on first 'true'", "nodes", ".", "some", "(", "n", "=>", "{", "try", "{", "let", "leadingComments", "// n.leadingComments is legacy `attachComments` behavior", "if", "(", "'leadingComments'", "in", "n", ")", "{", "leadingComments", "=", "n", ".", "leadingComments", "}", "else", "if", "(", "n", ".", "range", ")", "{", "leadingComments", "=", "source", ".", "getCommentsBefore", "(", "n", ")", "}", "if", "(", "!", "leadingComments", "||", "leadingComments", ".", "length", "===", "0", ")", "return", "false", "for", "(", "let", "name", "in", "docStyleParsers", ")", "{", "const", "doc", "=", "docStyleParsers", "[", "name", "]", "(", "leadingComments", ")", "if", "(", "doc", ")", "{", "metadata", ".", "doc", "=", "doc", "}", "}", "return", "true", "}", "catch", "(", "err", ")", "{", "return", "false", "}", "}", ")", "return", "metadata", "}" ]
parse docs from the first node that has leading comments
[ "parse", "docs", "from", "the", "first", "node", "that", "has", "leading", "comments" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/ExportMap.js#L196-L228
10,162
benmosher/eslint-plugin-import
src/ExportMap.js
captureJsDoc
function captureJsDoc(comments) { let doc // capture XSDoc comments.forEach(comment => { // skip non-block comments if (comment.type !== 'Block') return try { doc = doctrine.parse(comment.value, { unwrap: true }) } catch (err) { /* don't care, for now? maybe add to `errors?` */ } }) return doc }
javascript
function captureJsDoc(comments) { let doc // capture XSDoc comments.forEach(comment => { // skip non-block comments if (comment.type !== 'Block') return try { doc = doctrine.parse(comment.value, { unwrap: true }) } catch (err) { /* don't care, for now? maybe add to `errors?` */ } }) return doc }
[ "function", "captureJsDoc", "(", "comments", ")", "{", "let", "doc", "// capture XSDoc", "comments", ".", "forEach", "(", "comment", "=>", "{", "// skip non-block comments", "if", "(", "comment", ".", "type", "!==", "'Block'", ")", "return", "try", "{", "doc", "=", "doctrine", ".", "parse", "(", "comment", ".", "value", ",", "{", "unwrap", ":", "true", "}", ")", "}", "catch", "(", "err", ")", "{", "/* don't care, for now? maybe add to `errors?` */", "}", "}", ")", "return", "doc", "}" ]
parse JSDoc from leading comments @param {...[type]} comments [description] @return {{doc: object}}
[ "parse", "JSDoc", "from", "leading", "comments" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/ExportMap.js#L240-L255
10,163
benmosher/eslint-plugin-import
src/ExportMap.js
captureTomDoc
function captureTomDoc(comments) { // collect lines up to first paragraph break const lines = [] for (let i = 0; i < comments.length; i++) { const comment = comments[i] if (comment.value.match(/^\s*$/)) break lines.push(comment.value.trim()) } // return doctrine-like object const statusMatch = lines.join(' ').match(/^(Public|Internal|Deprecated):\s*(.+)/) if (statusMatch) { return { description: statusMatch[2], tags: [{ title: statusMatch[1].toLowerCase(), description: statusMatch[2], }], } } }
javascript
function captureTomDoc(comments) { // collect lines up to first paragraph break const lines = [] for (let i = 0; i < comments.length; i++) { const comment = comments[i] if (comment.value.match(/^\s*$/)) break lines.push(comment.value.trim()) } // return doctrine-like object const statusMatch = lines.join(' ').match(/^(Public|Internal|Deprecated):\s*(.+)/) if (statusMatch) { return { description: statusMatch[2], tags: [{ title: statusMatch[1].toLowerCase(), description: statusMatch[2], }], } } }
[ "function", "captureTomDoc", "(", "comments", ")", "{", "// collect lines up to first paragraph break", "const", "lines", "=", "[", "]", "for", "(", "let", "i", "=", "0", ";", "i", "<", "comments", ".", "length", ";", "i", "++", ")", "{", "const", "comment", "=", "comments", "[", "i", "]", "if", "(", "comment", ".", "value", ".", "match", "(", "/", "^\\s*$", "/", ")", ")", "break", "lines", ".", "push", "(", "comment", ".", "value", ".", "trim", "(", ")", ")", "}", "// return doctrine-like object", "const", "statusMatch", "=", "lines", ".", "join", "(", "' '", ")", ".", "match", "(", "/", "^(Public|Internal|Deprecated):\\s*(.+)", "/", ")", "if", "(", "statusMatch", ")", "{", "return", "{", "description", ":", "statusMatch", "[", "2", "]", ",", "tags", ":", "[", "{", "title", ":", "statusMatch", "[", "1", "]", ".", "toLowerCase", "(", ")", ",", "description", ":", "statusMatch", "[", "2", "]", ",", "}", "]", ",", "}", "}", "}" ]
parse TomDoc section from comments
[ "parse", "TomDoc", "section", "from", "comments" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/ExportMap.js#L260-L280
10,164
benmosher/eslint-plugin-import
src/ExportMap.js
childContext
function childContext(path, context) { const { settings, parserOptions, parserPath } = context return { settings, parserOptions, parserPath, path, } }
javascript
function childContext(path, context) { const { settings, parserOptions, parserPath } = context return { settings, parserOptions, parserPath, path, } }
[ "function", "childContext", "(", "path", ",", "context", ")", "{", "const", "{", "settings", ",", "parserOptions", ",", "parserPath", "}", "=", "context", "return", "{", "settings", ",", "parserOptions", ",", "parserPath", ",", "path", ",", "}", "}" ]
don't hold full context object in memory, just grab what we need.
[ "don", "t", "hold", "full", "context", "object", "in", "memory", "just", "grab", "what", "we", "need", "." ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/ExportMap.js#L562-L570
10,165
benmosher/eslint-plugin-import
src/ExportMap.js
makeSourceCode
function makeSourceCode(text, ast) { if (SourceCode.length > 1) { // ESLint 3 return new SourceCode(text, ast) } else { // ESLint 4, 5 return new SourceCode({ text, ast }) } }
javascript
function makeSourceCode(text, ast) { if (SourceCode.length > 1) { // ESLint 3 return new SourceCode(text, ast) } else { // ESLint 4, 5 return new SourceCode({ text, ast }) } }
[ "function", "makeSourceCode", "(", "text", ",", "ast", ")", "{", "if", "(", "SourceCode", ".", "length", ">", "1", ")", "{", "// ESLint 3", "return", "new", "SourceCode", "(", "text", ",", "ast", ")", "}", "else", "{", "// ESLint 4, 5", "return", "new", "SourceCode", "(", "{", "text", ",", "ast", "}", ")", "}", "}" ]
sometimes legacy support isn't _that_ hard... right?
[ "sometimes", "legacy", "support", "isn", "t", "_that_", "hard", "...", "right?" ]
1edbbd03ec636469328ad59da922ed7edc8cd36d
https://github.com/benmosher/eslint-plugin-import/blob/1edbbd03ec636469328ad59da922ed7edc8cd36d/src/ExportMap.js#L576-L584
10,166
jprichardson/node-fs-extra
lib/copy-sync/copy-sync.js
isSrcSubdir
function isSrcSubdir (src, dest) { const srcArray = path.resolve(src).split(path.sep) const destArray = path.resolve(dest).split(path.sep) return srcArray.reduce((acc, current, i) => acc && destArray[i] === current, true) }
javascript
function isSrcSubdir (src, dest) { const srcArray = path.resolve(src).split(path.sep) const destArray = path.resolve(dest).split(path.sep) return srcArray.reduce((acc, current, i) => acc && destArray[i] === current, true) }
[ "function", "isSrcSubdir", "(", "src", ",", "dest", ")", "{", "const", "srcArray", "=", "path", ".", "resolve", "(", "src", ")", ".", "split", "(", "path", ".", "sep", ")", "const", "destArray", "=", "path", ".", "resolve", "(", "dest", ")", ".", "split", "(", "path", ".", "sep", ")", "return", "srcArray", ".", "reduce", "(", "(", "acc", ",", "current", ",", "i", ")", "=>", "acc", "&&", "destArray", "[", "i", "]", "===", "current", ",", "true", ")", "}" ]
return true if dest is a subdir of src, otherwise false.
[ "return", "true", "if", "dest", "is", "a", "subdir", "of", "src", "otherwise", "false", "." ]
8e0879110fbdd597c36602fe3b81ef03a4b3ec7a
https://github.com/jprichardson/node-fs-extra/blob/8e0879110fbdd597c36602fe3b81ef03a4b3ec7a/lib/copy-sync/copy-sync.js#L164-L168
10,167
jprichardson/node-fs-extra
lib/mkdirs/win32.js
getRootPath
function getRootPath (p) { p = path.normalize(path.resolve(p)).split(path.sep) if (p.length > 0) return p[0] return null }
javascript
function getRootPath (p) { p = path.normalize(path.resolve(p)).split(path.sep) if (p.length > 0) return p[0] return null }
[ "function", "getRootPath", "(", "p", ")", "{", "p", "=", "path", ".", "normalize", "(", "path", ".", "resolve", "(", "p", ")", ")", ".", "split", "(", "path", ".", "sep", ")", "if", "(", "p", ".", "length", ">", "0", ")", "return", "p", "[", "0", "]", "return", "null", "}" ]
get drive on windows
[ "get", "drive", "on", "windows" ]
8e0879110fbdd597c36602fe3b81ef03a4b3ec7a
https://github.com/jprichardson/node-fs-extra/blob/8e0879110fbdd597c36602fe3b81ef03a4b3ec7a/lib/mkdirs/win32.js#L6-L10
10,168
jprichardson/node-fs-extra
lib/remove/rimraf.js
rimraf_
function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === 'ENOENT') { return cb(null) } // Windows can EPERM on stat. Life is suffering. if (er && er.code === 'EPERM' && isWindows) { return fixWinEPERM(p, options, er, cb) } if (st && st.isDirectory()) { return rmdir(p, options, er, cb) } options.unlink(p, er => { if (er) { if (er.code === 'ENOENT') { return cb(null) } if (er.code === 'EPERM') { return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) } if (er.code === 'EISDIR') { return rmdir(p, options, er, cb) } } return cb(er) }) }) }
javascript
function rimraf_ (p, options, cb) { assert(p) assert(options) assert(typeof cb === 'function') // sunos lets the root user unlink directories, which is... weird. // so we have to lstat here and make sure it's not a dir. options.lstat(p, (er, st) => { if (er && er.code === 'ENOENT') { return cb(null) } // Windows can EPERM on stat. Life is suffering. if (er && er.code === 'EPERM' && isWindows) { return fixWinEPERM(p, options, er, cb) } if (st && st.isDirectory()) { return rmdir(p, options, er, cb) } options.unlink(p, er => { if (er) { if (er.code === 'ENOENT') { return cb(null) } if (er.code === 'EPERM') { return (isWindows) ? fixWinEPERM(p, options, er, cb) : rmdir(p, options, er, cb) } if (er.code === 'EISDIR') { return rmdir(p, options, er, cb) } } return cb(er) }) }) }
[ "function", "rimraf_", "(", "p", ",", "options", ",", "cb", ")", "{", "assert", "(", "p", ")", "assert", "(", "options", ")", "assert", "(", "typeof", "cb", "===", "'function'", ")", "// sunos lets the root user unlink directories, which is... weird.", "// so we have to lstat here and make sure it's not a dir.", "options", ".", "lstat", "(", "p", ",", "(", "er", ",", "st", ")", "=>", "{", "if", "(", "er", "&&", "er", ".", "code", "===", "'ENOENT'", ")", "{", "return", "cb", "(", "null", ")", "}", "// Windows can EPERM on stat. Life is suffering.", "if", "(", "er", "&&", "er", ".", "code", "===", "'EPERM'", "&&", "isWindows", ")", "{", "return", "fixWinEPERM", "(", "p", ",", "options", ",", "er", ",", "cb", ")", "}", "if", "(", "st", "&&", "st", ".", "isDirectory", "(", ")", ")", "{", "return", "rmdir", "(", "p", ",", "options", ",", "er", ",", "cb", ")", "}", "options", ".", "unlink", "(", "p", ",", "er", "=>", "{", "if", "(", "er", ")", "{", "if", "(", "er", ".", "code", "===", "'ENOENT'", ")", "{", "return", "cb", "(", "null", ")", "}", "if", "(", "er", ".", "code", "===", "'EPERM'", ")", "{", "return", "(", "isWindows", ")", "?", "fixWinEPERM", "(", "p", ",", "options", ",", "er", ",", "cb", ")", ":", "rmdir", "(", "p", ",", "options", ",", "er", ",", "cb", ")", "}", "if", "(", "er", ".", "code", "===", "'EISDIR'", ")", "{", "return", "rmdir", "(", "p", ",", "options", ",", "er", ",", "cb", ")", "}", "}", "return", "cb", "(", "er", ")", "}", ")", "}", ")", "}" ]
Two possible strategies. 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR Both result in an extra syscall when you guess wrong. However, there are likely far more normal files in the world than directories. This is based on the assumption that a the average number of files per directory is >= 1. If anyone ever complains about this, then I guess the strategy could be made configurable somehow. But until then, YAGNI.
[ "Two", "possible", "strategies", ".", "1", ".", "Assume", "it", "s", "a", "file", ".", "unlink", "it", "then", "do", "the", "dir", "stuff", "on", "EPERM", "or", "EISDIR", "2", ".", "Assume", "it", "s", "a", "directory", ".", "readdir", "then", "do", "the", "file", "stuff", "on", "ENOTDIR", "Both", "result", "in", "an", "extra", "syscall", "when", "you", "guess", "wrong", ".", "However", "there", "are", "likely", "far", "more", "normal", "files", "in", "the", "world", "than", "directories", ".", "This", "is", "based", "on", "the", "assumption", "that", "a", "the", "average", "number", "of", "files", "per", "directory", "is", ">", "=", "1", ".", "If", "anyone", "ever", "complains", "about", "this", "then", "I", "guess", "the", "strategy", "could", "be", "made", "configurable", "somehow", ".", "But", "until", "then", "YAGNI", "." ]
8e0879110fbdd597c36602fe3b81ef03a4b3ec7a
https://github.com/jprichardson/node-fs-extra/blob/8e0879110fbdd597c36602fe3b81ef03a4b3ec7a/lib/remove/rimraf.js#L72-L110
10,169
jprichardson/node-fs-extra
lib/move-sync/index.js
isSrcSubdir
function isSrcSubdir (src, dest) { try { return fs.statSync(src).isDirectory() && src !== dest && dest.indexOf(src) > -1 && dest.split(path.dirname(src) + path.sep)[1].split(path.sep)[0] === path.basename(src) } catch (e) { return false } }
javascript
function isSrcSubdir (src, dest) { try { return fs.statSync(src).isDirectory() && src !== dest && dest.indexOf(src) > -1 && dest.split(path.dirname(src) + path.sep)[1].split(path.sep)[0] === path.basename(src) } catch (e) { return false } }
[ "function", "isSrcSubdir", "(", "src", ",", "dest", ")", "{", "try", "{", "return", "fs", ".", "statSync", "(", "src", ")", ".", "isDirectory", "(", ")", "&&", "src", "!==", "dest", "&&", "dest", ".", "indexOf", "(", "src", ")", ">", "-", "1", "&&", "dest", ".", "split", "(", "path", ".", "dirname", "(", "src", ")", "+", "path", ".", "sep", ")", "[", "1", "]", ".", "split", "(", "path", ".", "sep", ")", "[", "0", "]", "===", "path", ".", "basename", "(", "src", ")", "}", "catch", "(", "e", ")", "{", "return", "false", "}", "}" ]
return true if dest is a subdir of src, otherwise false. extract dest base dir and check if that is the same as src basename
[ "return", "true", "if", "dest", "is", "a", "subdir", "of", "src", "otherwise", "false", ".", "extract", "dest", "base", "dir", "and", "check", "if", "that", "is", "the", "same", "as", "src", "basename" ]
8e0879110fbdd597c36602fe3b81ef03a4b3ec7a
https://github.com/jprichardson/node-fs-extra/blob/8e0879110fbdd597c36602fe3b81ef03a4b3ec7a/lib/move-sync/index.js#L104-L113
10,170
gpbl/react-day-picker
lib/src/ModifiersUtils.js
dayMatchesModifier
function dayMatchesModifier(day, modifier) { if (!modifier) { return false; } var arr = Array.isArray(modifier) ? modifier : [modifier]; return arr.some(function (mod) { if (!mod) { return false; } if (mod instanceof Date) { return (0, _DateUtils.isSameDay)(day, mod); } if ((0, _Helpers.isRangeOfDates)(mod)) { return (0, _DateUtils.isDayInRange)(day, mod); } if (mod.after && mod.before && (0, _DateUtils.isDayAfter)(mod.before, mod.after)) { return (0, _DateUtils.isDayAfter)(day, mod.after) && (0, _DateUtils.isDayBefore)(day, mod.before); } if (mod.after && mod.before && ((0, _DateUtils.isDayAfter)(mod.after, mod.before) || (0, _DateUtils.isSameDay)(mod.after, mod.before))) { return (0, _DateUtils.isDayAfter)(day, mod.after) || (0, _DateUtils.isDayBefore)(day, mod.before); } if (mod.after) { return (0, _DateUtils.isDayAfter)(day, mod.after); } if (mod.before) { return (0, _DateUtils.isDayBefore)(day, mod.before); } if (mod.daysOfWeek) { return mod.daysOfWeek.some(function (dayOfWeek) { return day.getDay() === dayOfWeek; }); } if (typeof mod === 'function') { return mod(day); } return false; }); }
javascript
function dayMatchesModifier(day, modifier) { if (!modifier) { return false; } var arr = Array.isArray(modifier) ? modifier : [modifier]; return arr.some(function (mod) { if (!mod) { return false; } if (mod instanceof Date) { return (0, _DateUtils.isSameDay)(day, mod); } if ((0, _Helpers.isRangeOfDates)(mod)) { return (0, _DateUtils.isDayInRange)(day, mod); } if (mod.after && mod.before && (0, _DateUtils.isDayAfter)(mod.before, mod.after)) { return (0, _DateUtils.isDayAfter)(day, mod.after) && (0, _DateUtils.isDayBefore)(day, mod.before); } if (mod.after && mod.before && ((0, _DateUtils.isDayAfter)(mod.after, mod.before) || (0, _DateUtils.isSameDay)(mod.after, mod.before))) { return (0, _DateUtils.isDayAfter)(day, mod.after) || (0, _DateUtils.isDayBefore)(day, mod.before); } if (mod.after) { return (0, _DateUtils.isDayAfter)(day, mod.after); } if (mod.before) { return (0, _DateUtils.isDayBefore)(day, mod.before); } if (mod.daysOfWeek) { return mod.daysOfWeek.some(function (dayOfWeek) { return day.getDay() === dayOfWeek; }); } if (typeof mod === 'function') { return mod(day); } return false; }); }
[ "function", "dayMatchesModifier", "(", "day", ",", "modifier", ")", "{", "if", "(", "!", "modifier", ")", "{", "return", "false", ";", "}", "var", "arr", "=", "Array", ".", "isArray", "(", "modifier", ")", "?", "modifier", ":", "[", "modifier", "]", ";", "return", "arr", ".", "some", "(", "function", "(", "mod", ")", "{", "if", "(", "!", "mod", ")", "{", "return", "false", ";", "}", "if", "(", "mod", "instanceof", "Date", ")", "{", "return", "(", "0", ",", "_DateUtils", ".", "isSameDay", ")", "(", "day", ",", "mod", ")", ";", "}", "if", "(", "(", "0", ",", "_Helpers", ".", "isRangeOfDates", ")", "(", "mod", ")", ")", "{", "return", "(", "0", ",", "_DateUtils", ".", "isDayInRange", ")", "(", "day", ",", "mod", ")", ";", "}", "if", "(", "mod", ".", "after", "&&", "mod", ".", "before", "&&", "(", "0", ",", "_DateUtils", ".", "isDayAfter", ")", "(", "mod", ".", "before", ",", "mod", ".", "after", ")", ")", "{", "return", "(", "0", ",", "_DateUtils", ".", "isDayAfter", ")", "(", "day", ",", "mod", ".", "after", ")", "&&", "(", "0", ",", "_DateUtils", ".", "isDayBefore", ")", "(", "day", ",", "mod", ".", "before", ")", ";", "}", "if", "(", "mod", ".", "after", "&&", "mod", ".", "before", "&&", "(", "(", "0", ",", "_DateUtils", ".", "isDayAfter", ")", "(", "mod", ".", "after", ",", "mod", ".", "before", ")", "||", "(", "0", ",", "_DateUtils", ".", "isSameDay", ")", "(", "mod", ".", "after", ",", "mod", ".", "before", ")", ")", ")", "{", "return", "(", "0", ",", "_DateUtils", ".", "isDayAfter", ")", "(", "day", ",", "mod", ".", "after", ")", "||", "(", "0", ",", "_DateUtils", ".", "isDayBefore", ")", "(", "day", ",", "mod", ".", "before", ")", ";", "}", "if", "(", "mod", ".", "after", ")", "{", "return", "(", "0", ",", "_DateUtils", ".", "isDayAfter", ")", "(", "day", ",", "mod", ".", "after", ")", ";", "}", "if", "(", "mod", ".", "before", ")", "{", "return", "(", "0", ",", "_DateUtils", ".", "isDayBefore", ")", "(", "day", ",", "mod", ".", "before", ")", ";", "}", "if", "(", "mod", ".", "daysOfWeek", ")", "{", "return", "mod", ".", "daysOfWeek", ".", "some", "(", "function", "(", "dayOfWeek", ")", "{", "return", "day", ".", "getDay", "(", ")", "===", "dayOfWeek", ";", "}", ")", ";", "}", "if", "(", "typeof", "mod", "===", "'function'", ")", "{", "return", "mod", "(", "day", ")", ";", "}", "return", "false", ";", "}", ")", ";", "}" ]
Return `true` if a date matches the specified modifier. @export @param {Date} day @param {Any} modifier @return {Boolean}
[ "Return", "true", "if", "a", "date", "matches", "the", "specified", "modifier", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/ModifiersUtils.js#L21-L58
10,171
gpbl/react-day-picker
lib/src/ModifiersUtils.js
getModifiersForDay
function getModifiersForDay(day) { var modifiersObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return Object.keys(modifiersObj).reduce(function (modifiers, modifierName) { var value = modifiersObj[modifierName]; if (dayMatchesModifier(day, value)) { modifiers.push(modifierName); } return modifiers; }, []); }
javascript
function getModifiersForDay(day) { var modifiersObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return Object.keys(modifiersObj).reduce(function (modifiers, modifierName) { var value = modifiersObj[modifierName]; if (dayMatchesModifier(day, value)) { modifiers.push(modifierName); } return modifiers; }, []); }
[ "function", "getModifiersForDay", "(", "day", ")", "{", "var", "modifiersObj", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ";", "return", "Object", ".", "keys", "(", "modifiersObj", ")", ".", "reduce", "(", "function", "(", "modifiers", ",", "modifierName", ")", "{", "var", "value", "=", "modifiersObj", "[", "modifierName", "]", ";", "if", "(", "dayMatchesModifier", "(", "day", ",", "value", ")", ")", "{", "modifiers", ".", "push", "(", "modifierName", ")", ";", "}", "return", "modifiers", ";", "}", ",", "[", "]", ")", ";", "}" ]
Return the modifiers matching the given day for the given object of modifiers. @export @param {Date} day @param {Object} [modifiersObj={}] @return {Array}
[ "Return", "the", "modifiers", "matching", "the", "given", "day", "for", "the", "given", "object", "of", "modifiers", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/ModifiersUtils.js#L69-L79
10,172
gpbl/react-day-picker
lib/src/DateUtils.js
addMonths
function addMonths(d, n) { var newDate = clone(d); newDate.setMonth(d.getMonth() + n); return newDate; }
javascript
function addMonths(d, n) { var newDate = clone(d); newDate.setMonth(d.getMonth() + n); return newDate; }
[ "function", "addMonths", "(", "d", ",", "n", ")", "{", "var", "newDate", "=", "clone", "(", "d", ")", ";", "newDate", ".", "setMonth", "(", "d", ".", "getMonth", "(", ")", "+", "n", ")", ";", "return", "newDate", ";", "}" ]
Return `d` as a new date with `n` months added. @export @param {[type]} d @param {[type]} n
[ "Return", "d", "as", "a", "new", "date", "with", "n", "months", "added", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L48-L52
10,173
gpbl/react-day-picker
lib/src/DateUtils.js
isSameDay
function isSameDay(d1, d2) { if (!d1 || !d2) { return false; } return d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear(); }
javascript
function isSameDay(d1, d2) { if (!d1 || !d2) { return false; } return d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear(); }
[ "function", "isSameDay", "(", "d1", ",", "d2", ")", "{", "if", "(", "!", "d1", "||", "!", "d2", ")", "{", "return", "false", ";", "}", "return", "d1", ".", "getDate", "(", ")", "===", "d2", ".", "getDate", "(", ")", "&&", "d1", ".", "getMonth", "(", ")", "===", "d2", ".", "getMonth", "(", ")", "&&", "d1", ".", "getFullYear", "(", ")", "===", "d2", ".", "getFullYear", "(", ")", ";", "}" ]
Return `true` if two dates are the same day, ignoring the time. @export @param {Date} d1 @param {Date} d2 @return {Boolean}
[ "Return", "true", "if", "two", "dates", "are", "the", "same", "day", "ignoring", "the", "time", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L62-L67
10,174
gpbl/react-day-picker
lib/src/DateUtils.js
isSameMonth
function isSameMonth(d1, d2) { if (!d1 || !d2) { return false; } return d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear(); }
javascript
function isSameMonth(d1, d2) { if (!d1 || !d2) { return false; } return d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear(); }
[ "function", "isSameMonth", "(", "d1", ",", "d2", ")", "{", "if", "(", "!", "d1", "||", "!", "d2", ")", "{", "return", "false", ";", "}", "return", "d1", ".", "getMonth", "(", ")", "===", "d2", ".", "getMonth", "(", ")", "&&", "d1", ".", "getFullYear", "(", ")", "===", "d2", ".", "getFullYear", "(", ")", ";", "}" ]
Return `true` if two dates fall in the same month. @export @param {Date} d1 @param {Date} d2 @return {Boolean}
[ "Return", "true", "if", "two", "dates", "fall", "in", "the", "same", "month", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L77-L82
10,175
gpbl/react-day-picker
lib/src/DateUtils.js
isDayBefore
function isDayBefore(d1, d2) { var day1 = clone(d1).setHours(0, 0, 0, 0); var day2 = clone(d2).setHours(0, 0, 0, 0); return day1 < day2; }
javascript
function isDayBefore(d1, d2) { var day1 = clone(d1).setHours(0, 0, 0, 0); var day2 = clone(d2).setHours(0, 0, 0, 0); return day1 < day2; }
[ "function", "isDayBefore", "(", "d1", ",", "d2", ")", "{", "var", "day1", "=", "clone", "(", "d1", ")", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "var", "day2", "=", "clone", "(", "d2", ")", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "return", "day1", "<", "day2", ";", "}" ]
Returns `true` if the first day is before the second day. @export @param {Date} d1 @param {Date} d2 @returns {Boolean}
[ "Returns", "true", "if", "the", "first", "day", "is", "before", "the", "second", "day", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L92-L96
10,176
gpbl/react-day-picker
lib/src/DateUtils.js
isDayAfter
function isDayAfter(d1, d2) { var day1 = clone(d1).setHours(0, 0, 0, 0); var day2 = clone(d2).setHours(0, 0, 0, 0); return day1 > day2; }
javascript
function isDayAfter(d1, d2) { var day1 = clone(d1).setHours(0, 0, 0, 0); var day2 = clone(d2).setHours(0, 0, 0, 0); return day1 > day2; }
[ "function", "isDayAfter", "(", "d1", ",", "d2", ")", "{", "var", "day1", "=", "clone", "(", "d1", ")", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "var", "day2", "=", "clone", "(", "d2", ")", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "return", "day1", ">", "day2", ";", "}" ]
Returns `true` if the first day is after the second day. @export @param {Date} d1 @param {Date} d2 @returns {Boolean}
[ "Returns", "true", "if", "the", "first", "day", "is", "after", "the", "second", "day", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L106-L110
10,177
gpbl/react-day-picker
lib/src/DateUtils.js
isDayBetween
function isDayBetween(d, d1, d2) { var date = clone(d); date.setHours(0, 0, 0, 0); return isDayAfter(date, d1) && isDayBefore(date, d2) || isDayAfter(date, d2) && isDayBefore(date, d1); }
javascript
function isDayBetween(d, d1, d2) { var date = clone(d); date.setHours(0, 0, 0, 0); return isDayAfter(date, d1) && isDayBefore(date, d2) || isDayAfter(date, d2) && isDayBefore(date, d1); }
[ "function", "isDayBetween", "(", "d", ",", "d1", ",", "d2", ")", "{", "var", "date", "=", "clone", "(", "d", ")", ";", "date", ".", "setHours", "(", "0", ",", "0", ",", "0", ",", "0", ")", ";", "return", "isDayAfter", "(", "date", ",", "d1", ")", "&&", "isDayBefore", "(", "date", ",", "d2", ")", "||", "isDayAfter", "(", "date", ",", "d2", ")", "&&", "isDayBefore", "(", "date", ",", "d1", ")", ";", "}" ]
Return `true` if day `d` is between days `d1` and `d2`, without including them. @export @param {Date} d @param {Date} d1 @param {Date} d2 @return {Boolean}
[ "Return", "true", "if", "day", "d", "is", "between", "days", "d1", "and", "d2", "without", "including", "them", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L150-L154
10,178
gpbl/react-day-picker
lib/src/DateUtils.js
addDayToRange
function addDayToRange(day) { var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { from: null, to: null }; var from = range.from, to = range.to; if (!from) { from = day; } else if (from && to && isSameDay(from, to) && isSameDay(day, from)) { from = null; to = null; } else if (to && isDayBefore(day, from)) { from = day; } else if (to && isSameDay(day, to)) { from = day; to = day; } else { to = day; if (isDayBefore(to, from)) { to = from; from = day; } } return { from: from, to: to }; }
javascript
function addDayToRange(day) { var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { from: null, to: null }; var from = range.from, to = range.to; if (!from) { from = day; } else if (from && to && isSameDay(from, to) && isSameDay(day, from)) { from = null; to = null; } else if (to && isDayBefore(day, from)) { from = day; } else if (to && isSameDay(day, to)) { from = day; to = day; } else { to = day; if (isDayBefore(to, from)) { to = from; from = day; } } return { from: from, to: to }; }
[ "function", "addDayToRange", "(", "day", ")", "{", "var", "range", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "from", ":", "null", ",", "to", ":", "null", "}", ";", "var", "from", "=", "range", ".", "from", ",", "to", "=", "range", ".", "to", ";", "if", "(", "!", "from", ")", "{", "from", "=", "day", ";", "}", "else", "if", "(", "from", "&&", "to", "&&", "isSameDay", "(", "from", ",", "to", ")", "&&", "isSameDay", "(", "day", ",", "from", ")", ")", "{", "from", "=", "null", ";", "to", "=", "null", ";", "}", "else", "if", "(", "to", "&&", "isDayBefore", "(", "day", ",", "from", ")", ")", "{", "from", "=", "day", ";", "}", "else", "if", "(", "to", "&&", "isSameDay", "(", "day", ",", "to", ")", ")", "{", "from", "=", "day", ";", "to", "=", "day", ";", "}", "else", "{", "to", "=", "day", ";", "if", "(", "isDayBefore", "(", "to", ",", "from", ")", ")", "{", "to", "=", "from", ";", "from", "=", "day", ";", "}", "}", "return", "{", "from", ":", "from", ",", "to", ":", "to", "}", ";", "}" ]
Add a day to a range and return a new range. A range is an object with `from` and `to` days. @export @param {Date} day @param {Object} range @return {Object} Returns a new range object
[ "Add", "a", "day", "to", "a", "range", "and", "return", "a", "new", "range", ".", "A", "range", "is", "an", "object", "with", "from", "and", "to", "days", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L165-L189
10,179
gpbl/react-day-picker
lib/src/DateUtils.js
isDayInRange
function isDayInRange(day, range) { var from = range.from, to = range.to; return from && isSameDay(day, from) || to && isSameDay(day, to) || from && to && isDayBetween(day, from, to); }
javascript
function isDayInRange(day, range) { var from = range.from, to = range.to; return from && isSameDay(day, from) || to && isSameDay(day, to) || from && to && isDayBetween(day, from, to); }
[ "function", "isDayInRange", "(", "day", ",", "range", ")", "{", "var", "from", "=", "range", ".", "from", ",", "to", "=", "range", ".", "to", ";", "return", "from", "&&", "isSameDay", "(", "day", ",", "from", ")", "||", "to", "&&", "isSameDay", "(", "day", ",", "to", ")", "||", "from", "&&", "to", "&&", "isDayBetween", "(", "day", ",", "from", ",", "to", ")", ";", "}" ]
Return `true` if a day is included in a range of days. @export @param {Date} day @param {Object} range @return {Boolean}
[ "Return", "true", "if", "a", "day", "is", "included", "in", "a", "range", "of", "days", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DateUtils.js#L199-L204
10,180
gpbl/react-day-picker
lib/src/DayPickerInput.js
OverlayComponent
function OverlayComponent(_ref) { var input = _ref.input, selectedDay = _ref.selectedDay, month = _ref.month, children = _ref.children, classNames = _ref.classNames, props = _objectWithoutProperties(_ref, ['input', 'selectedDay', 'month', 'children', 'classNames']); return _react2.default.createElement( 'div', _extends({ className: classNames.overlayWrapper }, props), _react2.default.createElement( 'div', { className: classNames.overlay }, children ) ); }
javascript
function OverlayComponent(_ref) { var input = _ref.input, selectedDay = _ref.selectedDay, month = _ref.month, children = _ref.children, classNames = _ref.classNames, props = _objectWithoutProperties(_ref, ['input', 'selectedDay', 'month', 'children', 'classNames']); return _react2.default.createElement( 'div', _extends({ className: classNames.overlayWrapper }, props), _react2.default.createElement( 'div', { className: classNames.overlay }, children ) ); }
[ "function", "OverlayComponent", "(", "_ref", ")", "{", "var", "input", "=", "_ref", ".", "input", ",", "selectedDay", "=", "_ref", ".", "selectedDay", ",", "month", "=", "_ref", ".", "month", ",", "children", "=", "_ref", ".", "children", ",", "classNames", "=", "_ref", ".", "classNames", ",", "props", "=", "_objectWithoutProperties", "(", "_ref", ",", "[", "'input'", ",", "'selectedDay'", ",", "'month'", ",", "'children'", ",", "'classNames'", "]", ")", ";", "return", "_react2", ".", "default", ".", "createElement", "(", "'div'", ",", "_extends", "(", "{", "className", ":", "classNames", ".", "overlayWrapper", "}", ",", "props", ")", ",", "_react2", ".", "default", ".", "createElement", "(", "'div'", ",", "{", "className", ":", "classNames", ".", "overlay", "}", ",", "children", ")", ")", ";", "}" ]
The default component used as Overlay. @param {Object} props
[ "The", "default", "component", "used", "as", "Overlay", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DayPickerInput.js#L54-L71
10,181
gpbl/react-day-picker
lib/src/DayPickerInput.js
defaultFormat
function defaultFormat(d) { if ((0, _DateUtils.isDate)(d)) { var year = d.getFullYear(); var month = '' + (d.getMonth() + 1); var day = '' + d.getDate(); return year + '-' + month + '-' + day; } return ''; }
javascript
function defaultFormat(d) { if ((0, _DateUtils.isDate)(d)) { var year = d.getFullYear(); var month = '' + (d.getMonth() + 1); var day = '' + d.getDate(); return year + '-' + month + '-' + day; } return ''; }
[ "function", "defaultFormat", "(", "d", ")", "{", "if", "(", "(", "0", ",", "_DateUtils", ".", "isDate", ")", "(", "d", ")", ")", "{", "var", "year", "=", "d", ".", "getFullYear", "(", ")", ";", "var", "month", "=", "''", "+", "(", "d", ".", "getMonth", "(", ")", "+", "1", ")", ";", "var", "day", "=", "''", "+", "d", ".", "getDate", "(", ")", ";", "return", "year", "+", "'-'", "+", "month", "+", "'-'", "+", "day", ";", "}", "return", "''", ";", "}" ]
The default function used to format a Date to String, passed to the `format` prop. @param {Date} d @return {String}
[ "The", "default", "function", "used", "to", "format", "a", "Date", "to", "String", "passed", "to", "the", "format", "prop", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DayPickerInput.js#L87-L95
10,182
gpbl/react-day-picker
lib/src/DayPickerInput.js
defaultParse
function defaultParse(str) { if (typeof str !== 'string') { return undefined; } var split = str.split('-'); if (split.length !== 3) { return undefined; } var year = parseInt(split[0], 10); var month = parseInt(split[1], 10) - 1; var day = parseInt(split[2], 10); if (isNaN(year) || String(year).length > 4 || isNaN(month) || isNaN(day) || day <= 0 || day > 31 || month < 0 || month >= 12) { return undefined; } return new Date(year, month, day); }
javascript
function defaultParse(str) { if (typeof str !== 'string') { return undefined; } var split = str.split('-'); if (split.length !== 3) { return undefined; } var year = parseInt(split[0], 10); var month = parseInt(split[1], 10) - 1; var day = parseInt(split[2], 10); if (isNaN(year) || String(year).length > 4 || isNaN(month) || isNaN(day) || day <= 0 || day > 31 || month < 0 || month >= 12) { return undefined; } return new Date(year, month, day); }
[ "function", "defaultParse", "(", "str", ")", "{", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "return", "undefined", ";", "}", "var", "split", "=", "str", ".", "split", "(", "'-'", ")", ";", "if", "(", "split", ".", "length", "!==", "3", ")", "{", "return", "undefined", ";", "}", "var", "year", "=", "parseInt", "(", "split", "[", "0", "]", ",", "10", ")", ";", "var", "month", "=", "parseInt", "(", "split", "[", "1", "]", ",", "10", ")", "-", "1", ";", "var", "day", "=", "parseInt", "(", "split", "[", "2", "]", ",", "10", ")", ";", "if", "(", "isNaN", "(", "year", ")", "||", "String", "(", "year", ")", ".", "length", ">", "4", "||", "isNaN", "(", "month", ")", "||", "isNaN", "(", "day", ")", "||", "day", "<=", "0", "||", "day", ">", "31", "||", "month", "<", "0", "||", "month", ">=", "12", ")", "{", "return", "undefined", ";", "}", "return", "new", "Date", "(", "year", ",", "month", ",", "day", ")", ";", "}" ]
The default function used to parse a String as Date, passed to the `parse` prop. @param {String} str @return {Date}
[ "The", "default", "function", "used", "to", "parse", "a", "String", "as", "Date", "passed", "to", "the", "parse", "prop", "." ]
421af9f56b1b07ed58f864678b3bbb8617cdaff7
https://github.com/gpbl/react-day-picker/blob/421af9f56b1b07ed58f864678b3bbb8617cdaff7/lib/src/DayPickerInput.js#L103-L119
10,183
davidjbradshaw/iframe-resizer
js/iframeResizer.contentWindow.js
throttle
function throttle(func) { var context, args, result, timeout = null, previous = 0, later = function() { previous = getNow() timeout = null result = func.apply(context, args) if (!timeout) { // eslint-disable-next-line no-multi-assign context = args = null } } return function() { var now = getNow() if (!previous) { previous = now } var remaining = throttledTimer - (now - previous) context = this args = arguments if (remaining <= 0 || remaining > throttledTimer) { if (timeout) { clearTimeout(timeout) timeout = null } previous = now result = func.apply(context, args) if (!timeout) { // eslint-disable-next-line no-multi-assign context = args = null } } else if (!timeout) { timeout = setTimeout(later, remaining) } return result } }
javascript
function throttle(func) { var context, args, result, timeout = null, previous = 0, later = function() { previous = getNow() timeout = null result = func.apply(context, args) if (!timeout) { // eslint-disable-next-line no-multi-assign context = args = null } } return function() { var now = getNow() if (!previous) { previous = now } var remaining = throttledTimer - (now - previous) context = this args = arguments if (remaining <= 0 || remaining > throttledTimer) { if (timeout) { clearTimeout(timeout) timeout = null } previous = now result = func.apply(context, args) if (!timeout) { // eslint-disable-next-line no-multi-assign context = args = null } } else if (!timeout) { timeout = setTimeout(later, remaining) } return result } }
[ "function", "throttle", "(", "func", ")", "{", "var", "context", ",", "args", ",", "result", ",", "timeout", "=", "null", ",", "previous", "=", "0", ",", "later", "=", "function", "(", ")", "{", "previous", "=", "getNow", "(", ")", "timeout", "=", "null", "result", "=", "func", ".", "apply", "(", "context", ",", "args", ")", "if", "(", "!", "timeout", ")", "{", "// eslint-disable-next-line no-multi-assign", "context", "=", "args", "=", "null", "}", "}", "return", "function", "(", ")", "{", "var", "now", "=", "getNow", "(", ")", "if", "(", "!", "previous", ")", "{", "previous", "=", "now", "}", "var", "remaining", "=", "throttledTimer", "-", "(", "now", "-", "previous", ")", "context", "=", "this", "args", "=", "arguments", "if", "(", "remaining", "<=", "0", "||", "remaining", ">", "throttledTimer", ")", "{", "if", "(", "timeout", ")", "{", "clearTimeout", "(", "timeout", ")", "timeout", "=", "null", "}", "previous", "=", "now", "result", "=", "func", ".", "apply", "(", "context", ",", "args", ")", "if", "(", "!", "timeout", ")", "{", "// eslint-disable-next-line no-multi-assign", "context", "=", "args", "=", "null", "}", "}", "else", "if", "(", "!", "timeout", ")", "{", "timeout", "=", "setTimeout", "(", "later", ",", "remaining", ")", "}", "return", "result", "}", "}" ]
Based on underscore.js
[ "Based", "on", "underscore", ".", "js" ]
772f24df77444aff5e6520ce31bf93111c70f0b3
https://github.com/davidjbradshaw/iframe-resizer/blob/772f24df77444aff5e6520ce31bf93111c70f0b3/js/iframeResizer.contentWindow.js#L106-L153
10,184
davidjbradshaw/iframe-resizer
js/iframeResizer.contentWindow.js
getComputedStyle
function getComputedStyle(prop, el) { var retVal = 0 el = el || document.body // Not testable in phantonJS retVal = document.defaultView.getComputedStyle(el, null) retVal = null !== retVal ? retVal[prop] : 0 return parseInt(retVal, base) }
javascript
function getComputedStyle(prop, el) { var retVal = 0 el = el || document.body // Not testable in phantonJS retVal = document.defaultView.getComputedStyle(el, null) retVal = null !== retVal ? retVal[prop] : 0 return parseInt(retVal, base) }
[ "function", "getComputedStyle", "(", "prop", ",", "el", ")", "{", "var", "retVal", "=", "0", "el", "=", "el", "||", "document", ".", "body", "// Not testable in phantonJS", "retVal", "=", "document", ".", "defaultView", ".", "getComputedStyle", "(", "el", ",", "null", ")", "retVal", "=", "null", "!==", "retVal", "?", "retVal", "[", "prop", "]", ":", "0", "return", "parseInt", "(", "retVal", ",", "base", ")", "}" ]
document.documentElement.offsetHeight is not reliable, so we have to jump through hoops to get a better value.
[ "document", ".", "documentElement", ".", "offsetHeight", "is", "not", "reliable", "so", "we", "have", "to", "jump", "through", "hoops", "to", "get", "a", "better", "value", "." ]
772f24df77444aff5e6520ce31bf93111c70f0b3
https://github.com/davidjbradshaw/iframe-resizer/blob/772f24df77444aff5e6520ce31bf93111c70f0b3/js/iframeResizer.contentWindow.js#L853-L861
10,185
davidjbradshaw/iframe-resizer
js/iframeResizer.js
setupBodyMarginValues
function setupBodyMarginValues() { if ( 'number' === typeof (settings[iframeId] && settings[iframeId].bodyMargin) || '0' === (settings[iframeId] && settings[iframeId].bodyMargin) ) { settings[iframeId].bodyMarginV1 = settings[iframeId].bodyMargin settings[iframeId].bodyMargin = '' + settings[iframeId].bodyMargin + 'px' } }
javascript
function setupBodyMarginValues() { if ( 'number' === typeof (settings[iframeId] && settings[iframeId].bodyMargin) || '0' === (settings[iframeId] && settings[iframeId].bodyMargin) ) { settings[iframeId].bodyMarginV1 = settings[iframeId].bodyMargin settings[iframeId].bodyMargin = '' + settings[iframeId].bodyMargin + 'px' } }
[ "function", "setupBodyMarginValues", "(", ")", "{", "if", "(", "'number'", "===", "typeof", "(", "settings", "[", "iframeId", "]", "&&", "settings", "[", "iframeId", "]", ".", "bodyMargin", ")", "||", "'0'", "===", "(", "settings", "[", "iframeId", "]", "&&", "settings", "[", "iframeId", "]", ".", "bodyMargin", ")", ")", "{", "settings", "[", "iframeId", "]", ".", "bodyMarginV1", "=", "settings", "[", "iframeId", "]", ".", "bodyMargin", "settings", "[", "iframeId", "]", ".", "bodyMargin", "=", "''", "+", "settings", "[", "iframeId", "]", ".", "bodyMargin", "+", "'px'", "}", "}" ]
The V1 iFrame script expects an int, where as in V2 expects a CSS string value such as '1px 3em', so if we have an int for V2, set V1=V2 and then convert V2 to a string PX value.
[ "The", "V1", "iFrame", "script", "expects", "an", "int", "where", "as", "in", "V2", "expects", "a", "CSS", "string", "value", "such", "as", "1px", "3em", "so", "if", "we", "have", "an", "int", "for", "V2", "set", "V1", "=", "V2", "and", "then", "convert", "V2", "to", "a", "string", "PX", "value", "." ]
772f24df77444aff5e6520ce31bf93111c70f0b3
https://github.com/davidjbradshaw/iframe-resizer/blob/772f24df77444aff5e6520ce31bf93111c70f0b3/js/iframeResizer.js#L939-L949
10,186
davidjbradshaw/iframe-resizer
js/iframeResizer.js
init
function init(msg) { function iFrameLoaded() { trigger('iFrame.onload', msg, iframe, undefined, true) checkReset() } function createDestroyObserver(MutationObserver) { if (!iframe.parentNode) { return } var destroyObserver = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { var removedNodes = Array.prototype.slice.call(mutation.removedNodes) // Transform NodeList into an Array removedNodes.forEach(function(removedNode) { if (removedNode === iframe) { closeIFrame(iframe) } }) }) }) destroyObserver.observe(iframe.parentNode, { childList: true }) } var MutationObserver = getMutationObserver() if (MutationObserver) { createDestroyObserver(MutationObserver) } addEventListener(iframe, 'load', iFrameLoaded) trigger('init', msg, iframe, undefined, true) }
javascript
function init(msg) { function iFrameLoaded() { trigger('iFrame.onload', msg, iframe, undefined, true) checkReset() } function createDestroyObserver(MutationObserver) { if (!iframe.parentNode) { return } var destroyObserver = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { var removedNodes = Array.prototype.slice.call(mutation.removedNodes) // Transform NodeList into an Array removedNodes.forEach(function(removedNode) { if (removedNode === iframe) { closeIFrame(iframe) } }) }) }) destroyObserver.observe(iframe.parentNode, { childList: true }) } var MutationObserver = getMutationObserver() if (MutationObserver) { createDestroyObserver(MutationObserver) } addEventListener(iframe, 'load', iFrameLoaded) trigger('init', msg, iframe, undefined, true) }
[ "function", "init", "(", "msg", ")", "{", "function", "iFrameLoaded", "(", ")", "{", "trigger", "(", "'iFrame.onload'", ",", "msg", ",", "iframe", ",", "undefined", ",", "true", ")", "checkReset", "(", ")", "}", "function", "createDestroyObserver", "(", "MutationObserver", ")", "{", "if", "(", "!", "iframe", ".", "parentNode", ")", "{", "return", "}", "var", "destroyObserver", "=", "new", "MutationObserver", "(", "function", "(", "mutations", ")", "{", "mutations", ".", "forEach", "(", "function", "(", "mutation", ")", "{", "var", "removedNodes", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "mutation", ".", "removedNodes", ")", "// Transform NodeList into an Array", "removedNodes", ".", "forEach", "(", "function", "(", "removedNode", ")", "{", "if", "(", "removedNode", "===", "iframe", ")", "{", "closeIFrame", "(", "iframe", ")", "}", "}", ")", "}", ")", "}", ")", "destroyObserver", ".", "observe", "(", "iframe", ".", "parentNode", ",", "{", "childList", ":", "true", "}", ")", "}", "var", "MutationObserver", "=", "getMutationObserver", "(", ")", "if", "(", "MutationObserver", ")", "{", "createDestroyObserver", "(", "MutationObserver", ")", "}", "addEventListener", "(", "iframe", ",", "'load'", ",", "iFrameLoaded", ")", "trigger", "(", "'init'", ",", "msg", ",", "iframe", ",", "undefined", ",", "true", ")", "}" ]
We have to call trigger twice, as we can not be sure if all iframes have completed loading when this code runs. The event listener also catches the page changing in the iFrame.
[ "We", "have", "to", "call", "trigger", "twice", "as", "we", "can", "not", "be", "sure", "if", "all", "iframes", "have", "completed", "loading", "when", "this", "code", "runs", ".", "The", "event", "listener", "also", "catches", "the", "page", "changing", "in", "the", "iFrame", "." ]
772f24df77444aff5e6520ce31bf93111c70f0b3
https://github.com/davidjbradshaw/iframe-resizer/blob/772f24df77444aff5e6520ce31bf93111c70f0b3/js/iframeResizer.js#L1007-L1040
10,187
karma-runner/karma
lib/middleware/proxy.js
createProxyHandler
function createProxyHandler (proxies, urlRoot) { if (!proxies.length) { const nullProxy = (request, response, next) => next() nullProxy.upgrade = () => {} return nullProxy } function createProxy (request, response, next) { const proxyRecord = proxies.find((p) => request.url.startsWith(p.path)) if (proxyRecord) { log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`) request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl) proxyRecord.proxy.web(request, response) } else { return next() } } createProxy.upgrade = function (request, socket, head) { // special-case karma's route to avoid upgrading it if (request.url.startsWith(urlRoot)) { log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`) return } const proxyRecord = proxies.find((p) => request.url.startsWith(p.path)) if (proxyRecord) { log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`) request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl) proxyRecord.proxy.ws(request, socket, head) } } return createProxy }
javascript
function createProxyHandler (proxies, urlRoot) { if (!proxies.length) { const nullProxy = (request, response, next) => next() nullProxy.upgrade = () => {} return nullProxy } function createProxy (request, response, next) { const proxyRecord = proxies.find((p) => request.url.startsWith(p.path)) if (proxyRecord) { log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`) request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl) proxyRecord.proxy.web(request, response) } else { return next() } } createProxy.upgrade = function (request, socket, head) { // special-case karma's route to avoid upgrading it if (request.url.startsWith(urlRoot)) { log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`) return } const proxyRecord = proxies.find((p) => request.url.startsWith(p.path)) if (proxyRecord) { log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`) request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl) proxyRecord.proxy.ws(request, socket, head) } } return createProxy }
[ "function", "createProxyHandler", "(", "proxies", ",", "urlRoot", ")", "{", "if", "(", "!", "proxies", ".", "length", ")", "{", "const", "nullProxy", "=", "(", "request", ",", "response", ",", "next", ")", "=>", "next", "(", ")", "nullProxy", ".", "upgrade", "=", "(", ")", "=>", "{", "}", "return", "nullProxy", "}", "function", "createProxy", "(", "request", ",", "response", ",", "next", ")", "{", "const", "proxyRecord", "=", "proxies", ".", "find", "(", "(", "p", ")", "=>", "request", ".", "url", ".", "startsWith", "(", "p", ".", "path", ")", ")", "if", "(", "proxyRecord", ")", "{", "log", ".", "debug", "(", "`", "${", "request", ".", "url", "}", "${", "proxyRecord", ".", "host", "}", "${", "proxyRecord", ".", "port", "}", "`", ")", "request", ".", "url", "=", "request", ".", "url", ".", "replace", "(", "proxyRecord", ".", "path", ",", "proxyRecord", ".", "baseUrl", ")", "proxyRecord", ".", "proxy", ".", "web", "(", "request", ",", "response", ")", "}", "else", "{", "return", "next", "(", ")", "}", "}", "createProxy", ".", "upgrade", "=", "function", "(", "request", ",", "socket", ",", "head", ")", "{", "// special-case karma's route to avoid upgrading it", "if", "(", "request", ".", "url", ".", "startsWith", "(", "urlRoot", ")", ")", "{", "log", ".", "debug", "(", "`", "${", "request", ".", "url", "}", "`", ")", "return", "}", "const", "proxyRecord", "=", "proxies", ".", "find", "(", "(", "p", ")", "=>", "request", ".", "url", ".", "startsWith", "(", "p", ".", "path", ")", ")", "if", "(", "proxyRecord", ")", "{", "log", ".", "debug", "(", "`", "${", "request", ".", "url", "}", "${", "proxyRecord", ".", "host", "}", "${", "proxyRecord", ".", "port", "}", "`", ")", "request", ".", "url", "=", "request", ".", "url", ".", "replace", "(", "proxyRecord", ".", "path", ",", "proxyRecord", ".", "baseUrl", ")", "proxyRecord", ".", "proxy", ".", "ws", "(", "request", ",", "socket", ",", "head", ")", "}", "}", "return", "createProxy", "}" ]
Returns a handler which understands the proxies and its redirects, along with the proxy to use @param proxies An array of proxy record objects @param urlRoot The URL root that karma is mounted on @return {Function} handler function
[ "Returns", "a", "handler", "which", "understands", "the", "proxies", "and", "its", "redirects", "along", "with", "the", "proxy", "to", "use" ]
fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e
https://github.com/karma-runner/karma/blob/fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e/lib/middleware/proxy.js#L78-L112
10,188
karma-runner/karma
lib/middleware/source_files.js
createSourceFilesMiddleware
function createSourceFilesMiddleware (filesPromise, serveFile, basePath, urlRoot) { return function (request, response, next) { const requestedFilePath = composeUrl(request.url, basePath, urlRoot) // When a path contains HTML-encoded characters (e.g %2F used by Jenkins for branches with /) const requestedFilePathUnescaped = composeUrl(querystring.unescape(request.url), basePath, urlRoot) request.pause() log.debug(`Requesting ${request.url}`) log.debug(`Fetching ${requestedFilePath}`) return filesPromise.then(function (files) { // TODO(vojta): change served to be a map rather then an array const file = findByPath(files.served, requestedFilePath) || findByPath(files.served, requestedFilePathUnescaped) const rangeHeader = request.headers['range'] if (file) { const acceptEncodingHeader = request.headers['accept-encoding'] const matchedEncoding = Object.keys(file.encodings).find( (encoding) => new RegExp(`(^|.*, ?)${encoding}(,|$)`).test(acceptEncodingHeader) ) const content = file.encodings[matchedEncoding] || file.content serveFile(file.contentPath || file.path, rangeHeader, response, function () { if (/\?\w+/.test(request.url)) { common.setHeavyCacheHeaders(response) // files with timestamps - cache one year, rely on timestamps } else { common.setNoCacheHeaders(response) // without timestamps - no cache (debug) } if (matchedEncoding) { response.setHeader('Content-Encoding', matchedEncoding) } }, content, file.doNotCache) } else { next() } request.resume() }) } }
javascript
function createSourceFilesMiddleware (filesPromise, serveFile, basePath, urlRoot) { return function (request, response, next) { const requestedFilePath = composeUrl(request.url, basePath, urlRoot) // When a path contains HTML-encoded characters (e.g %2F used by Jenkins for branches with /) const requestedFilePathUnescaped = composeUrl(querystring.unescape(request.url), basePath, urlRoot) request.pause() log.debug(`Requesting ${request.url}`) log.debug(`Fetching ${requestedFilePath}`) return filesPromise.then(function (files) { // TODO(vojta): change served to be a map rather then an array const file = findByPath(files.served, requestedFilePath) || findByPath(files.served, requestedFilePathUnescaped) const rangeHeader = request.headers['range'] if (file) { const acceptEncodingHeader = request.headers['accept-encoding'] const matchedEncoding = Object.keys(file.encodings).find( (encoding) => new RegExp(`(^|.*, ?)${encoding}(,|$)`).test(acceptEncodingHeader) ) const content = file.encodings[matchedEncoding] || file.content serveFile(file.contentPath || file.path, rangeHeader, response, function () { if (/\?\w+/.test(request.url)) { common.setHeavyCacheHeaders(response) // files with timestamps - cache one year, rely on timestamps } else { common.setNoCacheHeaders(response) // without timestamps - no cache (debug) } if (matchedEncoding) { response.setHeader('Content-Encoding', matchedEncoding) } }, content, file.doNotCache) } else { next() } request.resume() }) } }
[ "function", "createSourceFilesMiddleware", "(", "filesPromise", ",", "serveFile", ",", "basePath", ",", "urlRoot", ")", "{", "return", "function", "(", "request", ",", "response", ",", "next", ")", "{", "const", "requestedFilePath", "=", "composeUrl", "(", "request", ".", "url", ",", "basePath", ",", "urlRoot", ")", "// When a path contains HTML-encoded characters (e.g %2F used by Jenkins for branches with /)", "const", "requestedFilePathUnescaped", "=", "composeUrl", "(", "querystring", ".", "unescape", "(", "request", ".", "url", ")", ",", "basePath", ",", "urlRoot", ")", "request", ".", "pause", "(", ")", "log", ".", "debug", "(", "`", "${", "request", ".", "url", "}", "`", ")", "log", ".", "debug", "(", "`", "${", "requestedFilePath", "}", "`", ")", "return", "filesPromise", ".", "then", "(", "function", "(", "files", ")", "{", "// TODO(vojta): change served to be a map rather then an array", "const", "file", "=", "findByPath", "(", "files", ".", "served", ",", "requestedFilePath", ")", "||", "findByPath", "(", "files", ".", "served", ",", "requestedFilePathUnescaped", ")", "const", "rangeHeader", "=", "request", ".", "headers", "[", "'range'", "]", "if", "(", "file", ")", "{", "const", "acceptEncodingHeader", "=", "request", ".", "headers", "[", "'accept-encoding'", "]", "const", "matchedEncoding", "=", "Object", ".", "keys", "(", "file", ".", "encodings", ")", ".", "find", "(", "(", "encoding", ")", "=>", "new", "RegExp", "(", "`", "${", "encoding", "}", "`", ")", ".", "test", "(", "acceptEncodingHeader", ")", ")", "const", "content", "=", "file", ".", "encodings", "[", "matchedEncoding", "]", "||", "file", ".", "content", "serveFile", "(", "file", ".", "contentPath", "||", "file", ".", "path", ",", "rangeHeader", ",", "response", ",", "function", "(", ")", "{", "if", "(", "/", "\\?\\w+", "/", ".", "test", "(", "request", ".", "url", ")", ")", "{", "common", ".", "setHeavyCacheHeaders", "(", "response", ")", "// files with timestamps - cache one year, rely on timestamps", "}", "else", "{", "common", ".", "setNoCacheHeaders", "(", "response", ")", "// without timestamps - no cache (debug)", "}", "if", "(", "matchedEncoding", ")", "{", "response", ".", "setHeader", "(", "'Content-Encoding'", ",", "matchedEncoding", ")", "}", "}", ",", "content", ",", "file", ".", "doNotCache", ")", "}", "else", "{", "next", "(", ")", "}", "request", ".", "resume", "(", ")", "}", ")", "}", "}" ]
Source Files middleware is responsible for serving all the source files under the test.
[ "Source", "Files", "middleware", "is", "responsible", "for", "serving", "all", "the", "source", "files", "under", "the", "test", "." ]
fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e
https://github.com/karma-runner/karma/blob/fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e/lib/middleware/source_files.js#L21-L61
10,189
karma-runner/karma
lib/web-server.js
createReadFilePromise
function createReadFilePromise () { return (filepath) => { return new Promise((resolve, reject) => { fs.readFile(filepath, 'utf8', function (error, data) { if (error) { reject(new Error(`Cannot read ${filepath}, got: ${error}`)) } else if (!data) { reject(new Error(`No content at ${filepath}`)) } else { resolve(data.split('\n')) } }) }) } }
javascript
function createReadFilePromise () { return (filepath) => { return new Promise((resolve, reject) => { fs.readFile(filepath, 'utf8', function (error, data) { if (error) { reject(new Error(`Cannot read ${filepath}, got: ${error}`)) } else if (!data) { reject(new Error(`No content at ${filepath}`)) } else { resolve(data.split('\n')) } }) }) } }
[ "function", "createReadFilePromise", "(", ")", "{", "return", "(", "filepath", ")", "=>", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readFile", "(", "filepath", ",", "'utf8'", ",", "function", "(", "error", ",", "data", ")", "{", "if", "(", "error", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "filepath", "}", "${", "error", "}", "`", ")", ")", "}", "else", "if", "(", "!", "data", ")", "{", "reject", "(", "new", "Error", "(", "`", "${", "filepath", "}", "`", ")", ")", "}", "else", "{", "resolve", "(", "data", ".", "split", "(", "'\\n'", ")", ")", "}", "}", ")", "}", ")", "}", "}" ]
Bind the filesystem into the injectable file reader function
[ "Bind", "the", "filesystem", "into", "the", "injectable", "file", "reader", "function" ]
fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e
https://github.com/karma-runner/karma/blob/fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e/lib/web-server.js#L43-L57
10,190
karma-runner/karma
lib/launchers/capture_timeout.js
CaptureTimeoutLauncher
function CaptureTimeoutLauncher (timer, captureTimeout) { if (!captureTimeout) { return } let pendingTimeoutId = null this.on('start', () => { pendingTimeoutId = timer.setTimeout(() => { pendingTimeoutId = null if (this.state !== this.STATE_BEING_CAPTURED) { return } log.warn(`${this.name} have not captured in ${captureTimeout} ms, killing.`) this.error = 'timeout' this.kill() }, captureTimeout) }) this.on('done', () => { if (pendingTimeoutId) { timer.clearTimeout(pendingTimeoutId) pendingTimeoutId = null } }) }
javascript
function CaptureTimeoutLauncher (timer, captureTimeout) { if (!captureTimeout) { return } let pendingTimeoutId = null this.on('start', () => { pendingTimeoutId = timer.setTimeout(() => { pendingTimeoutId = null if (this.state !== this.STATE_BEING_CAPTURED) { return } log.warn(`${this.name} have not captured in ${captureTimeout} ms, killing.`) this.error = 'timeout' this.kill() }, captureTimeout) }) this.on('done', () => { if (pendingTimeoutId) { timer.clearTimeout(pendingTimeoutId) pendingTimeoutId = null } }) }
[ "function", "CaptureTimeoutLauncher", "(", "timer", ",", "captureTimeout", ")", "{", "if", "(", "!", "captureTimeout", ")", "{", "return", "}", "let", "pendingTimeoutId", "=", "null", "this", ".", "on", "(", "'start'", ",", "(", ")", "=>", "{", "pendingTimeoutId", "=", "timer", ".", "setTimeout", "(", "(", ")", "=>", "{", "pendingTimeoutId", "=", "null", "if", "(", "this", ".", "state", "!==", "this", ".", "STATE_BEING_CAPTURED", ")", "{", "return", "}", "log", ".", "warn", "(", "`", "${", "this", ".", "name", "}", "${", "captureTimeout", "}", "`", ")", "this", ".", "error", "=", "'timeout'", "this", ".", "kill", "(", ")", "}", ",", "captureTimeout", ")", "}", ")", "this", ".", "on", "(", "'done'", ",", "(", ")", "=>", "{", "if", "(", "pendingTimeoutId", ")", "{", "timer", ".", "clearTimeout", "(", "pendingTimeoutId", ")", "pendingTimeoutId", "=", "null", "}", "}", ")", "}" ]
Kill browser if it does not capture in given `captureTimeout`.
[ "Kill", "browser", "if", "it", "does", "not", "capture", "in", "given", "captureTimeout", "." ]
fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e
https://github.com/karma-runner/karma/blob/fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e/lib/launchers/capture_timeout.js#L6-L32
10,191
karma-runner/karma
lib/launchers/base.js
BaseLauncher
function BaseLauncher (id, emitter) { if (this.start) { return } // TODO(vojta): figure out how to do inheritance with DI Object.keys(EventEmitter.prototype).forEach(function (method) { this[method] = EventEmitter.prototype[method] }, this) this.bind = KarmaEventEmitter.prototype.bind.bind(this) this.emitAsync = KarmaEventEmitter.prototype.emitAsync.bind(this) this.id = id this._state = null Object.defineProperty(this, 'state', { get: () => { return this._state }, set: (toState) => { log.debug(`${this._state} -> ${toState}`) this._state = toState } }) this.error = null let killingPromise let previousUrl this.start = function (url) { previousUrl = url this.error = null this.state = BEING_CAPTURED this.emit('start', url + '?id=' + this.id + (helper.isDefined(this.displayName) ? '&displayName=' + encodeURIComponent(this.displayName) : '')) } this.kill = function () { // Already killed, or being killed. if (killingPromise) { return killingPromise } killingPromise = this.emitAsync('kill').then(() => { this.state = FINISHED }) this.state = BEING_KILLED return killingPromise } this.forceKill = function () { this.kill() this.state = BEING_FORCE_KILLED return killingPromise } this.restart = function () { if (this.state === BEING_FORCE_KILLED) { return } if (!killingPromise) { killingPromise = this.emitAsync('kill') } killingPromise.then(() => { if (this.state === BEING_FORCE_KILLED) { this.state = FINISHED } else { killingPromise = null log.debug(`Restarting ${this.name}`) this.start(previousUrl) } }) this.state = RESTARTING } this.markCaptured = function () { if (this.state === BEING_CAPTURED) { this.state = CAPTURED } } this.isCaptured = function () { return this.state === CAPTURED } this.toString = function () { return this.name } this._done = function (error) { killingPromise = killingPromise || Promise.resolve() this.error = this.error || error this.emit('done') if (this.error && this.state !== BEING_FORCE_KILLED && this.state !== RESTARTING) { emitter.emit('browser_process_failure', this) } this.state = FINISHED } this.STATE_BEING_CAPTURED = BEING_CAPTURED this.STATE_CAPTURED = CAPTURED this.STATE_BEING_KILLED = BEING_KILLED this.STATE_FINISHED = FINISHED this.STATE_RESTARTING = RESTARTING this.STATE_BEING_FORCE_KILLED = BEING_FORCE_KILLED }
javascript
function BaseLauncher (id, emitter) { if (this.start) { return } // TODO(vojta): figure out how to do inheritance with DI Object.keys(EventEmitter.prototype).forEach(function (method) { this[method] = EventEmitter.prototype[method] }, this) this.bind = KarmaEventEmitter.prototype.bind.bind(this) this.emitAsync = KarmaEventEmitter.prototype.emitAsync.bind(this) this.id = id this._state = null Object.defineProperty(this, 'state', { get: () => { return this._state }, set: (toState) => { log.debug(`${this._state} -> ${toState}`) this._state = toState } }) this.error = null let killingPromise let previousUrl this.start = function (url) { previousUrl = url this.error = null this.state = BEING_CAPTURED this.emit('start', url + '?id=' + this.id + (helper.isDefined(this.displayName) ? '&displayName=' + encodeURIComponent(this.displayName) : '')) } this.kill = function () { // Already killed, or being killed. if (killingPromise) { return killingPromise } killingPromise = this.emitAsync('kill').then(() => { this.state = FINISHED }) this.state = BEING_KILLED return killingPromise } this.forceKill = function () { this.kill() this.state = BEING_FORCE_KILLED return killingPromise } this.restart = function () { if (this.state === BEING_FORCE_KILLED) { return } if (!killingPromise) { killingPromise = this.emitAsync('kill') } killingPromise.then(() => { if (this.state === BEING_FORCE_KILLED) { this.state = FINISHED } else { killingPromise = null log.debug(`Restarting ${this.name}`) this.start(previousUrl) } }) this.state = RESTARTING } this.markCaptured = function () { if (this.state === BEING_CAPTURED) { this.state = CAPTURED } } this.isCaptured = function () { return this.state === CAPTURED } this.toString = function () { return this.name } this._done = function (error) { killingPromise = killingPromise || Promise.resolve() this.error = this.error || error this.emit('done') if (this.error && this.state !== BEING_FORCE_KILLED && this.state !== RESTARTING) { emitter.emit('browser_process_failure', this) } this.state = FINISHED } this.STATE_BEING_CAPTURED = BEING_CAPTURED this.STATE_CAPTURED = CAPTURED this.STATE_BEING_KILLED = BEING_KILLED this.STATE_FINISHED = FINISHED this.STATE_RESTARTING = RESTARTING this.STATE_BEING_FORCE_KILLED = BEING_FORCE_KILLED }
[ "function", "BaseLauncher", "(", "id", ",", "emitter", ")", "{", "if", "(", "this", ".", "start", ")", "{", "return", "}", "// TODO(vojta): figure out how to do inheritance with DI", "Object", ".", "keys", "(", "EventEmitter", ".", "prototype", ")", ".", "forEach", "(", "function", "(", "method", ")", "{", "this", "[", "method", "]", "=", "EventEmitter", ".", "prototype", "[", "method", "]", "}", ",", "this", ")", "this", ".", "bind", "=", "KarmaEventEmitter", ".", "prototype", ".", "bind", ".", "bind", "(", "this", ")", "this", ".", "emitAsync", "=", "KarmaEventEmitter", ".", "prototype", ".", "emitAsync", ".", "bind", "(", "this", ")", "this", ".", "id", "=", "id", "this", ".", "_state", "=", "null", "Object", ".", "defineProperty", "(", "this", ",", "'state'", ",", "{", "get", ":", "(", ")", "=>", "{", "return", "this", ".", "_state", "}", ",", "set", ":", "(", "toState", ")", "=>", "{", "log", ".", "debug", "(", "`", "${", "this", ".", "_state", "}", "${", "toState", "}", "`", ")", "this", ".", "_state", "=", "toState", "}", "}", ")", "this", ".", "error", "=", "null", "let", "killingPromise", "let", "previousUrl", "this", ".", "start", "=", "function", "(", "url", ")", "{", "previousUrl", "=", "url", "this", ".", "error", "=", "null", "this", ".", "state", "=", "BEING_CAPTURED", "this", ".", "emit", "(", "'start'", ",", "url", "+", "'?id='", "+", "this", ".", "id", "+", "(", "helper", ".", "isDefined", "(", "this", ".", "displayName", ")", "?", "'&displayName='", "+", "encodeURIComponent", "(", "this", ".", "displayName", ")", ":", "''", ")", ")", "}", "this", ".", "kill", "=", "function", "(", ")", "{", "// Already killed, or being killed.", "if", "(", "killingPromise", ")", "{", "return", "killingPromise", "}", "killingPromise", "=", "this", ".", "emitAsync", "(", "'kill'", ")", ".", "then", "(", "(", ")", "=>", "{", "this", ".", "state", "=", "FINISHED", "}", ")", "this", ".", "state", "=", "BEING_KILLED", "return", "killingPromise", "}", "this", ".", "forceKill", "=", "function", "(", ")", "{", "this", ".", "kill", "(", ")", "this", ".", "state", "=", "BEING_FORCE_KILLED", "return", "killingPromise", "}", "this", ".", "restart", "=", "function", "(", ")", "{", "if", "(", "this", ".", "state", "===", "BEING_FORCE_KILLED", ")", "{", "return", "}", "if", "(", "!", "killingPromise", ")", "{", "killingPromise", "=", "this", ".", "emitAsync", "(", "'kill'", ")", "}", "killingPromise", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "this", ".", "state", "===", "BEING_FORCE_KILLED", ")", "{", "this", ".", "state", "=", "FINISHED", "}", "else", "{", "killingPromise", "=", "null", "log", ".", "debug", "(", "`", "${", "this", ".", "name", "}", "`", ")", "this", ".", "start", "(", "previousUrl", ")", "}", "}", ")", "this", ".", "state", "=", "RESTARTING", "}", "this", ".", "markCaptured", "=", "function", "(", ")", "{", "if", "(", "this", ".", "state", "===", "BEING_CAPTURED", ")", "{", "this", ".", "state", "=", "CAPTURED", "}", "}", "this", ".", "isCaptured", "=", "function", "(", ")", "{", "return", "this", ".", "state", "===", "CAPTURED", "}", "this", ".", "toString", "=", "function", "(", ")", "{", "return", "this", ".", "name", "}", "this", ".", "_done", "=", "function", "(", "error", ")", "{", "killingPromise", "=", "killingPromise", "||", "Promise", ".", "resolve", "(", ")", "this", ".", "error", "=", "this", ".", "error", "||", "error", "this", ".", "emit", "(", "'done'", ")", "if", "(", "this", ".", "error", "&&", "this", ".", "state", "!==", "BEING_FORCE_KILLED", "&&", "this", ".", "state", "!==", "RESTARTING", ")", "{", "emitter", ".", "emit", "(", "'browser_process_failure'", ",", "this", ")", "}", "this", ".", "state", "=", "FINISHED", "}", "this", ".", "STATE_BEING_CAPTURED", "=", "BEING_CAPTURED", "this", ".", "STATE_CAPTURED", "=", "CAPTURED", "this", ".", "STATE_BEING_KILLED", "=", "BEING_KILLED", "this", ".", "STATE_FINISHED", "=", "FINISHED", "this", ".", "STATE_RESTARTING", "=", "RESTARTING", "this", ".", "STATE_BEING_FORCE_KILLED", "=", "BEING_FORCE_KILLED", "}" ]
Base launcher that any custom launcher extends.
[ "Base", "launcher", "that", "any", "custom", "launcher", "extends", "." ]
fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e
https://github.com/karma-runner/karma/blob/fe9a1dd13b5eb3969f9e08acbce020e2a382fd9e/lib/launchers/base.js#L18-L133
10,192
kimmobrunfeldt/progressbar.js
Gruntfile.js
groupToElements
function groupToElements(array, n) { var lists = _.groupBy(array, function(element, index){ return Math.floor(index / n); }); return _.toArray(lists); }
javascript
function groupToElements(array, n) { var lists = _.groupBy(array, function(element, index){ return Math.floor(index / n); }); return _.toArray(lists); }
[ "function", "groupToElements", "(", "array", ",", "n", ")", "{", "var", "lists", "=", "_", ".", "groupBy", "(", "array", ",", "function", "(", "element", ",", "index", ")", "{", "return", "Math", ".", "floor", "(", "index", "/", "n", ")", ";", "}", ")", ";", "return", "_", ".", "toArray", "(", "lists", ")", ";", "}" ]
Split array to smaller arrays containing n elements at max
[ "Split", "array", "to", "smaller", "arrays", "containing", "n", "elements", "at", "max" ]
cebeb0786a331de9e2083e416d191c5181047e53
https://github.com/kimmobrunfeldt/progressbar.js/blob/cebeb0786a331de9e2083e416d191c5181047e53/Gruntfile.js#L6-L12
10,193
kimmobrunfeldt/progressbar.js
src/utils.js
extend
function extend(destination, source, recursive) { destination = destination || {}; source = source || {}; recursive = recursive || false; for (var attrName in source) { if (source.hasOwnProperty(attrName)) { var destVal = destination[attrName]; var sourceVal = source[attrName]; if (recursive && isObject(destVal) && isObject(sourceVal)) { destination[attrName] = extend(destVal, sourceVal, recursive); } else { destination[attrName] = sourceVal; } } } return destination; }
javascript
function extend(destination, source, recursive) { destination = destination || {}; source = source || {}; recursive = recursive || false; for (var attrName in source) { if (source.hasOwnProperty(attrName)) { var destVal = destination[attrName]; var sourceVal = source[attrName]; if (recursive && isObject(destVal) && isObject(sourceVal)) { destination[attrName] = extend(destVal, sourceVal, recursive); } else { destination[attrName] = sourceVal; } } } return destination; }
[ "function", "extend", "(", "destination", ",", "source", ",", "recursive", ")", "{", "destination", "=", "destination", "||", "{", "}", ";", "source", "=", "source", "||", "{", "}", ";", "recursive", "=", "recursive", "||", "false", ";", "for", "(", "var", "attrName", "in", "source", ")", "{", "if", "(", "source", ".", "hasOwnProperty", "(", "attrName", ")", ")", "{", "var", "destVal", "=", "destination", "[", "attrName", "]", ";", "var", "sourceVal", "=", "source", "[", "attrName", "]", ";", "if", "(", "recursive", "&&", "isObject", "(", "destVal", ")", "&&", "isObject", "(", "sourceVal", ")", ")", "{", "destination", "[", "attrName", "]", "=", "extend", "(", "destVal", ",", "sourceVal", ",", "recursive", ")", ";", "}", "else", "{", "destination", "[", "attrName", "]", "=", "sourceVal", ";", "}", "}", "}", "return", "destination", ";", "}" ]
Copy all attributes from source object to destination object. destination object is mutated.
[ "Copy", "all", "attributes", "from", "source", "object", "to", "destination", "object", ".", "destination", "object", "is", "mutated", "." ]
cebeb0786a331de9e2083e416d191c5181047e53
https://github.com/kimmobrunfeldt/progressbar.js/blob/cebeb0786a331de9e2083e416d191c5181047e53/src/utils.js#L8-L26
10,194
prescottprue/react-redux-firebase
src/actions/auth.js
createProfileWatchErrorHandler
function createProfileWatchErrorHandler(dispatch, firebase) { const { config: { onProfileListenerError, logErrors } } = firebase._ return function handleProfileError(err) { if (logErrors) { // eslint-disable-next-line no-console console.error(`Error with profile listener: ${err.message || ''}`, err) } if (isFunction(onProfileListenerError)) { const factoryResult = onProfileListenerError(err, firebase) // Return factoryResult if it is a promise if (isFunction(factoryResult.then)) { return factoryResult } } return Promise.reject(err) } }
javascript
function createProfileWatchErrorHandler(dispatch, firebase) { const { config: { onProfileListenerError, logErrors } } = firebase._ return function handleProfileError(err) { if (logErrors) { // eslint-disable-next-line no-console console.error(`Error with profile listener: ${err.message || ''}`, err) } if (isFunction(onProfileListenerError)) { const factoryResult = onProfileListenerError(err, firebase) // Return factoryResult if it is a promise if (isFunction(factoryResult.then)) { return factoryResult } } return Promise.reject(err) } }
[ "function", "createProfileWatchErrorHandler", "(", "dispatch", ",", "firebase", ")", "{", "const", "{", "config", ":", "{", "onProfileListenerError", ",", "logErrors", "}", "}", "=", "firebase", ".", "_", "return", "function", "handleProfileError", "(", "err", ")", "{", "if", "(", "logErrors", ")", "{", "// eslint-disable-next-line no-console", "console", ".", "error", "(", "`", "${", "err", ".", "message", "||", "''", "}", "`", ",", "err", ")", "}", "if", "(", "isFunction", "(", "onProfileListenerError", ")", ")", "{", "const", "factoryResult", "=", "onProfileListenerError", "(", "err", ",", "firebase", ")", "// Return factoryResult if it is a promise", "if", "(", "isFunction", "(", "factoryResult", ".", "then", ")", ")", "{", "return", "factoryResult", "}", "}", "return", "Promise", ".", "reject", "(", "err", ")", "}", "}" ]
Creates a function for handling errors from profile watcher. Used for both RTDB and Firestore. @param {Function} dispatch - Action dispatch function @param {Object} firebase - Internal firebase object @return {Function} Profile watch error handler function @private
[ "Creates", "a", "function", "for", "handling", "errors", "from", "profile", "watcher", ".", "Used", "for", "both", "RTDB", "and", "Firestore", "." ]
de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c
https://github.com/prescottprue/react-redux-firebase/blob/de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c/src/actions/auth.js#L151-L167
10,195
prescottprue/react-redux-firebase
bin/api-docs-upload.js
runCommand
function runCommand(cmd) { return exec(cmd).catch(err => Promise.reject( err.message && err.message.indexOf('not found') !== -1 ? new Error(`${cmd.split(' ')[0]} must be installed to upload`) : err ) ) }
javascript
function runCommand(cmd) { return exec(cmd).catch(err => Promise.reject( err.message && err.message.indexOf('not found') !== -1 ? new Error(`${cmd.split(' ')[0]} must be installed to upload`) : err ) ) }
[ "function", "runCommand", "(", "cmd", ")", "{", "return", "exec", "(", "cmd", ")", ".", "catch", "(", "err", "=>", "Promise", ".", "reject", "(", "err", ".", "message", "&&", "err", ".", "message", ".", "indexOf", "(", "'not found'", ")", "!==", "-", "1", "?", "new", "Error", "(", "`", "${", "cmd", ".", "split", "(", "' '", ")", "[", "0", "]", "}", "`", ")", ":", "err", ")", ")", "}" ]
Run shell command with error handling. @param {String} cmd - Command to run @return {Promise} Resolves with stdout of running command @private
[ "Run", "shell", "command", "with", "error", "handling", "." ]
de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c
https://github.com/prescottprue/react-redux-firebase/blob/de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c/bin/api-docs-upload.js#L26-L34
10,196
prescottprue/react-redux-firebase
bin/api-docs-upload.js
uploadList
function uploadList(files) { return Promise.all( files.map(file => upload(file) .then(({ uploadPath, output }) => { console.log(`Successfully uploaded: ${uploadPath}`) // eslint-disable-line no-console return output }) .catch(err => { console.log('Error uploading:', err.message || err) // eslint-disable-line no-console return Promise.reject(err) }) ) ) }
javascript
function uploadList(files) { return Promise.all( files.map(file => upload(file) .then(({ uploadPath, output }) => { console.log(`Successfully uploaded: ${uploadPath}`) // eslint-disable-line no-console return output }) .catch(err => { console.log('Error uploading:', err.message || err) // eslint-disable-line no-console return Promise.reject(err) }) ) ) }
[ "function", "uploadList", "(", "files", ")", "{", "return", "Promise", ".", "all", "(", "files", ".", "map", "(", "file", "=>", "upload", "(", "file", ")", ".", "then", "(", "(", "{", "uploadPath", ",", "output", "}", ")", "=>", "{", "console", ".", "log", "(", "`", "${", "uploadPath", "}", "`", ")", "// eslint-disable-line no-console", "return", "output", "}", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "log", "(", "'Error uploading:'", ",", "err", ".", "message", "||", "err", ")", "// eslint-disable-line no-console", "return", "Promise", ".", "reject", "(", "err", ")", "}", ")", ")", ")", "}" ]
Upload list of files or folders to Google Cloud Storage @param {Array} files - List of files/folders to upload @return {Promise} Resolves with an array of upload results @private
[ "Upload", "list", "of", "files", "or", "folders", "to", "Google", "Cloud", "Storage" ]
de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c
https://github.com/prescottprue/react-redux-firebase/blob/de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c/bin/api-docs-upload.js#L61-L75
10,197
prescottprue/react-redux-firebase
src/utils/storage.js
createUploadMetaResponseHandler
function createUploadMetaResponseHandler({ fileData, firebase, uploadTaskSnapshot, downloadURL }) { /** * Converts upload meta data snapshot into an object (handling both * RTDB and Firestore) * @param {Object} metaDataSnapshot - Snapshot from metadata upload (from * RTDB or Firestore) * @return {Object} Upload result including snapshot, key, File */ return function uploadResultFromSnap(metaDataSnapshot) { const { useFirestoreForStorageMeta } = firebase._.config const result = { snapshot: metaDataSnapshot, key: metaDataSnapshot.key || metaDataSnapshot.id, File: fileData, metaDataSnapshot, uploadTaskSnapshot, // Support legacy method uploadTaskSnaphot: uploadTaskSnapshot, createdAt: useFirestoreForStorageMeta ? firebase.firestore.FieldValue.serverTimestamp() : firebase.database.ServerValue.TIMESTAMP } // Attach id if it exists (Firestore) if (metaDataSnapshot.id) { result.id = metaDataSnapshot.id } // Attach downloadURL if it exists if (downloadURL) { result.downloadURL = downloadURL } return result } }
javascript
function createUploadMetaResponseHandler({ fileData, firebase, uploadTaskSnapshot, downloadURL }) { /** * Converts upload meta data snapshot into an object (handling both * RTDB and Firestore) * @param {Object} metaDataSnapshot - Snapshot from metadata upload (from * RTDB or Firestore) * @return {Object} Upload result including snapshot, key, File */ return function uploadResultFromSnap(metaDataSnapshot) { const { useFirestoreForStorageMeta } = firebase._.config const result = { snapshot: metaDataSnapshot, key: metaDataSnapshot.key || metaDataSnapshot.id, File: fileData, metaDataSnapshot, uploadTaskSnapshot, // Support legacy method uploadTaskSnaphot: uploadTaskSnapshot, createdAt: useFirestoreForStorageMeta ? firebase.firestore.FieldValue.serverTimestamp() : firebase.database.ServerValue.TIMESTAMP } // Attach id if it exists (Firestore) if (metaDataSnapshot.id) { result.id = metaDataSnapshot.id } // Attach downloadURL if it exists if (downloadURL) { result.downloadURL = downloadURL } return result } }
[ "function", "createUploadMetaResponseHandler", "(", "{", "fileData", ",", "firebase", ",", "uploadTaskSnapshot", ",", "downloadURL", "}", ")", "{", "/**\n * Converts upload meta data snapshot into an object (handling both\n * RTDB and Firestore)\n * @param {Object} metaDataSnapshot - Snapshot from metadata upload (from\n * RTDB or Firestore)\n * @return {Object} Upload result including snapshot, key, File\n */", "return", "function", "uploadResultFromSnap", "(", "metaDataSnapshot", ")", "{", "const", "{", "useFirestoreForStorageMeta", "}", "=", "firebase", ".", "_", ".", "config", "const", "result", "=", "{", "snapshot", ":", "metaDataSnapshot", ",", "key", ":", "metaDataSnapshot", ".", "key", "||", "metaDataSnapshot", ".", "id", ",", "File", ":", "fileData", ",", "metaDataSnapshot", ",", "uploadTaskSnapshot", ",", "// Support legacy method", "uploadTaskSnaphot", ":", "uploadTaskSnapshot", ",", "createdAt", ":", "useFirestoreForStorageMeta", "?", "firebase", ".", "firestore", ".", "FieldValue", ".", "serverTimestamp", "(", ")", ":", "firebase", ".", "database", ".", "ServerValue", ".", "TIMESTAMP", "}", "// Attach id if it exists (Firestore)", "if", "(", "metaDataSnapshot", ".", "id", ")", "{", "result", ".", "id", "=", "metaDataSnapshot", ".", "id", "}", "// Attach downloadURL if it exists", "if", "(", "downloadURL", ")", "{", "result", ".", "downloadURL", "=", "downloadURL", "}", "return", "result", "}", "}" ]
Create a function to handle response from upload. @param {Object} fileData - File data which was uploaded @param {Object} uploadTaskSnapshot - Snapshot from storage upload task @return {Function} Function for handling upload result
[ "Create", "a", "function", "to", "handle", "response", "from", "upload", "." ]
de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c
https://github.com/prescottprue/react-redux-firebase/blob/de32c8e46f7f99b3e8d3afbbc9f8518ee15e0a5c/src/utils/storage.js#L49-L86
10,198
SSENSE/vue-carousel
docs/public/js/common.js
initMobileMenu
function initMobileMenu () { var mobileBar = document.getElementById('mobile-bar') var sidebar = document.querySelector('.sidebar') var menuButton = mobileBar.querySelector('.menu-button') menuButton.addEventListener('click', function () { sidebar.classList.toggle('open') }) document.body.addEventListener('click', function (e) { if (e.target !== menuButton && !sidebar.contains(e.target)) { sidebar.classList.remove('open') } }) }
javascript
function initMobileMenu () { var mobileBar = document.getElementById('mobile-bar') var sidebar = document.querySelector('.sidebar') var menuButton = mobileBar.querySelector('.menu-button') menuButton.addEventListener('click', function () { sidebar.classList.toggle('open') }) document.body.addEventListener('click', function (e) { if (e.target !== menuButton && !sidebar.contains(e.target)) { sidebar.classList.remove('open') } }) }
[ "function", "initMobileMenu", "(", ")", "{", "var", "mobileBar", "=", "document", ".", "getElementById", "(", "'mobile-bar'", ")", "var", "sidebar", "=", "document", ".", "querySelector", "(", "'.sidebar'", ")", "var", "menuButton", "=", "mobileBar", ".", "querySelector", "(", "'.menu-button'", ")", "menuButton", ".", "addEventListener", "(", "'click'", ",", "function", "(", ")", "{", "sidebar", ".", "classList", ".", "toggle", "(", "'open'", ")", "}", ")", "document", ".", "body", ".", "addEventListener", "(", "'click'", ",", "function", "(", "e", ")", "{", "if", "(", "e", ".", "target", "!==", "menuButton", "&&", "!", "sidebar", ".", "contains", "(", "e", ".", "target", ")", ")", "{", "sidebar", ".", "classList", ".", "remove", "(", "'open'", ")", "}", "}", ")", "}" ]
Mobile burger menu button for toggling sidebar
[ "Mobile", "burger", "menu", "button", "for", "toggling", "sidebar" ]
7c8e213e6773100b7cfad19b3ee88feebd777970
https://github.com/SSENSE/vue-carousel/blob/7c8e213e6773100b7cfad19b3ee88feebd777970/docs/public/js/common.js#L80-L94
10,199
SSENSE/vue-carousel
docs/public/js/common.js
initVersionSelect
function initVersionSelect () { // version select var versionSelect = document.querySelector('.version-select') versionSelect && versionSelect.addEventListener('change', function (e) { var version = e.target.value var section = window.location.pathname.match(/\/v\d\/(\w+?)\//)[1] if (version === 'SELF') return window.location.assign( 'http://' + version + (version && '.') + 'vuejs.org/' + section + '/' ) }) }
javascript
function initVersionSelect () { // version select var versionSelect = document.querySelector('.version-select') versionSelect && versionSelect.addEventListener('change', function (e) { var version = e.target.value var section = window.location.pathname.match(/\/v\d\/(\w+?)\//)[1] if (version === 'SELF') return window.location.assign( 'http://' + version + (version && '.') + 'vuejs.org/' + section + '/' ) }) }
[ "function", "initVersionSelect", "(", ")", "{", "// version select", "var", "versionSelect", "=", "document", ".", "querySelector", "(", "'.version-select'", ")", "versionSelect", "&&", "versionSelect", ".", "addEventListener", "(", "'change'", ",", "function", "(", "e", ")", "{", "var", "version", "=", "e", ".", "target", ".", "value", "var", "section", "=", "window", ".", "location", ".", "pathname", ".", "match", "(", "/", "\\/v\\d\\/(\\w+?)\\/", "/", ")", "[", "1", "]", "if", "(", "version", "===", "'SELF'", ")", "return", "window", ".", "location", ".", "assign", "(", "'http://'", "+", "version", "+", "(", "version", "&&", "'.'", ")", "+", "'vuejs.org/'", "+", "section", "+", "'/'", ")", "}", ")", "}" ]
Doc version select
[ "Doc", "version", "select" ]
7c8e213e6773100b7cfad19b3ee88feebd777970
https://github.com/SSENSE/vue-carousel/blob/7c8e213e6773100b7cfad19b3ee88feebd777970/docs/public/js/common.js#L100-L114