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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
nknapp/promised-handlebars | lib/utils.js | mapValues | function mapValues (obj, mapFn) {
return Object.keys(obj).reduce(function (result, key) {
result[key] = mapFn(obj[key], key, obj)
return result
}, {})
} | javascript | function mapValues (obj, mapFn) {
return Object.keys(obj).reduce(function (result, key) {
result[key] = mapFn(obj[key], key, obj)
return result
}, {})
} | [
"function",
"mapValues",
"(",
"obj",
",",
"mapFn",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"key",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"mapFn",
"(",
"obj",
"[",
"key",
"]",
",",
"key",
",",
"obj",
")",
"return",
"result",
"}",
",",
"{",
"}",
")",
"}"
]
| Apply the mapFn to all values of the object and return a new object with the applied values
@param obj the input object
@param {function(any, string, object): any} mapFn the map function (receives the value, the key and the whole object as parameter)
@returns {object} an object with the same keys as the input object | [
"Apply",
"the",
"mapFn",
"to",
"all",
"values",
"of",
"the",
"object",
"and",
"return",
"a",
"new",
"object",
"with",
"the",
"applied",
"values"
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/lib/utils.js#L39-L44 | train |
nknapp/promised-handlebars | lib/utils.js | anyApplies | function anyApplies (array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return true
}
}
return false
} | javascript | function anyApplies (array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return true
}
}
return false
} | [
"function",
"anyApplies",
"(",
"array",
",",
"predicate",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"predicate",
"(",
"array",
"[",
"i",
"]",
")",
")",
"{",
"return",
"true",
"}",
"}",
"return",
"false",
"}"
]
| Check if the predicate is true for any element of the array
@param {Array} array
@param {function(any):boolean} predicate
@returns {boolean} | [
"Check",
"if",
"the",
"predicate",
"is",
"true",
"for",
"any",
"element",
"of",
"the",
"array"
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/lib/utils.js#L63-L70 | train |
nknapp/promised-handlebars | index.js | prepareAndResolveMarkers | function prepareAndResolveMarkers (fn, args) {
if (markers) {
// The Markers-object has already been created for this cycle of the event loop:
// Just run the wraped function
return fn.apply(this, args)
}
try {
// No Markers yet. This is the initial call or some call that occured during a promise resolution
// Create markers, apply the function and resolve placeholders (i.e. promises) created during the
// function execution
markers = new Markers(engine, options.placeholder)
var resultWithPlaceholders = fn.apply(this, args)
return markers.resolve(resultWithPlaceholders)
} finally {
// Reset promises for the next execution run
markers = null
}
} | javascript | function prepareAndResolveMarkers (fn, args) {
if (markers) {
// The Markers-object has already been created for this cycle of the event loop:
// Just run the wraped function
return fn.apply(this, args)
}
try {
// No Markers yet. This is the initial call or some call that occured during a promise resolution
// Create markers, apply the function and resolve placeholders (i.e. promises) created during the
// function execution
markers = new Markers(engine, options.placeholder)
var resultWithPlaceholders = fn.apply(this, args)
return markers.resolve(resultWithPlaceholders)
} finally {
// Reset promises for the next execution run
markers = null
}
} | [
"function",
"prepareAndResolveMarkers",
"(",
"fn",
",",
"args",
")",
"{",
"if",
"(",
"markers",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
"}",
"try",
"{",
"markers",
"=",
"new",
"Markers",
"(",
"engine",
",",
"options",
".",
"placeholder",
")",
"var",
"resultWithPlaceholders",
"=",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
"return",
"markers",
".",
"resolve",
"(",
"resultWithPlaceholders",
")",
"}",
"finally",
"{",
"markers",
"=",
"null",
"}",
"}"
]
| Wrapper for templates, partials and block-helper callbacks
1) the `markers` variable is initialized with a new instance of Markers
2) a promise is returned instead of a string
3) promise placeholder-values are replaced with the promise-results
in the returned promise | [
"Wrapper",
"for",
"templates",
"partials",
"and",
"block",
"-",
"helper",
"callbacks"
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/index.js#L88-L105 | train |
nknapp/promised-handlebars | lib/markers.js | Markers | function Markers (engine, prefix) {
/**
* This array stores the promises created in the current event-loop cycle
* @type {Promise[]}
*/
this.promiseStore = []
this.engine = engine
this.prefix = prefix
// one line from substack's quotemeta-package
var placeHolderRegexEscaped = String(this.prefix).replace(/(\W)/g, '\\$1')
this.regex = new RegExp(placeHolderRegexEscaped + '(\\d+)(>|>)', 'g')
} | javascript | function Markers (engine, prefix) {
/**
* This array stores the promises created in the current event-loop cycle
* @type {Promise[]}
*/
this.promiseStore = []
this.engine = engine
this.prefix = prefix
// one line from substack's quotemeta-package
var placeHolderRegexEscaped = String(this.prefix).replace(/(\W)/g, '\\$1')
this.regex = new RegExp(placeHolderRegexEscaped + '(\\d+)(>|>)', 'g')
} | [
"function",
"Markers",
"(",
"engine",
",",
"prefix",
")",
"{",
"this",
".",
"promiseStore",
"=",
"[",
"]",
"this",
".",
"engine",
"=",
"engine",
"this",
".",
"prefix",
"=",
"prefix",
"var",
"placeHolderRegexEscaped",
"=",
"String",
"(",
"this",
".",
"prefix",
")",
".",
"replace",
"(",
"/",
"(\\W)",
"/",
"g",
",",
"'\\\\$1'",
")",
"\\\\",
"}"
]
| A class the handles the creation and resolution of markers in the Handlebars output.
Markes are used as placeholders in the output string for promises returned by helpers.
They are replaced as soon as the promises are resolved.
@param {Handlebars} engine a Handlebars instance (needed for the `escapeExpression` function)
@param {string} prefix the prefix to identify placeholders (this prefix should never occur in the template).
@constructor | [
"A",
"class",
"the",
"handles",
"the",
"creation",
"and",
"resolution",
"of",
"markers",
"in",
"the",
"Handlebars",
"output",
".",
"Markes",
"are",
"used",
"as",
"placeholders",
"in",
"the",
"output",
"string",
"for",
"promises",
"returned",
"by",
"helpers",
".",
"They",
"are",
"replaced",
"as",
"soon",
"as",
"the",
"promises",
"are",
"resolved",
"."
]
| 2274dad8a2c7558a6747e274e85b1dd4d88dbac9 | https://github.com/nknapp/promised-handlebars/blob/2274dad8a2c7558a6747e274e85b1dd4d88dbac9/lib/markers.js#L29-L40 | train |
attila/savvior | src/Helpers.js | each | function each(collection, fn, scope) {
var i = 0,
cont;
for (i; i < collection.length; i++) {
cont = fn.call(scope, collection[i], i);
if (cont === false) {
break; //allow early exit
}
}
} | javascript | function each(collection, fn, scope) {
var i = 0,
cont;
for (i; i < collection.length; i++) {
cont = fn.call(scope, collection[i], i);
if (cont === false) {
break; //allow early exit
}
}
} | [
"function",
"each",
"(",
"collection",
",",
"fn",
",",
"scope",
")",
"{",
"var",
"i",
"=",
"0",
",",
"cont",
";",
"for",
"(",
"i",
";",
"i",
"<",
"collection",
".",
"length",
";",
"i",
"++",
")",
"{",
"cont",
"=",
"fn",
".",
"call",
"(",
"scope",
",",
"collection",
"[",
"i",
"]",
",",
"i",
")",
";",
"if",
"(",
"cont",
"===",
"false",
")",
"{",
"break",
";",
"}",
"}",
"}"
]
| Helper function for iterating over a collection
@param collection
@param fn
@param scope | [
"Helper",
"function",
"for",
"iterating",
"over",
"a",
"collection"
]
| 860e887756465acc2abf348ae7073e2d603f523f | https://github.com/attila/savvior/blob/860e887756465acc2abf348ae7073e2d603f523f/src/Helpers.js#L22-L32 | train |
attila/savvior | src/Grid.js | function(element) {
this.columns = null;
this.element = element;
this.filtered = document.createDocumentFragment();
this.status = false;
this.columnClasses = null;
} | javascript | function(element) {
this.columns = null;
this.element = element;
this.filtered = document.createDocumentFragment();
this.status = false;
this.columnClasses = null;
} | [
"function",
"(",
"element",
")",
"{",
"this",
".",
"columns",
"=",
"null",
";",
"this",
".",
"element",
"=",
"element",
";",
"this",
".",
"filtered",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"this",
".",
"status",
"=",
"false",
";",
"this",
".",
"columnClasses",
"=",
"null",
";",
"}"
]
| Implements the grid element and its internal manipulation features
@param {Object} Grid
@param {String} Grid.columns Stores the current number of columns
@param {Object} Grid.element Stores the DOM object of the grid element
@param {Boolean} Grid.status Pointer to maintain the Grid status
@constructor | [
"Implements",
"the",
"grid",
"element",
"and",
"its",
"internal",
"manipulation",
"features"
]
| 860e887756465acc2abf348ae7073e2d603f523f | https://github.com/attila/savvior/blob/860e887756465acc2abf348ae7073e2d603f523f/src/Grid.js#L10-L16 | train |
|
anseki/plain-overlay | plain-overlay.esm.js | setStyle | function setStyle(element, styleProps, savedStyleProps, propNames) {
var style = element.style;
(propNames || Object.keys(styleProps)).forEach(function (prop) {
if (styleProps[prop] != null) {
if (savedStyleProps && savedStyleProps[prop] == null) {
savedStyleProps[prop] = style[prop];
}
style[prop] = styleProps[prop];
styleProps[prop] = null;
}
});
return element;
} | javascript | function setStyle(element, styleProps, savedStyleProps, propNames) {
var style = element.style;
(propNames || Object.keys(styleProps)).forEach(function (prop) {
if (styleProps[prop] != null) {
if (savedStyleProps && savedStyleProps[prop] == null) {
savedStyleProps[prop] = style[prop];
}
style[prop] = styleProps[prop];
styleProps[prop] = null;
}
});
return element;
} | [
"function",
"setStyle",
"(",
"element",
",",
"styleProps",
",",
"savedStyleProps",
",",
"propNames",
")",
"{",
"var",
"style",
"=",
"element",
".",
"style",
";",
"(",
"propNames",
"||",
"Object",
".",
"keys",
"(",
"styleProps",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"if",
"(",
"styleProps",
"[",
"prop",
"]",
"!=",
"null",
")",
"{",
"if",
"(",
"savedStyleProps",
"&&",
"savedStyleProps",
"[",
"prop",
"]",
"==",
"null",
")",
"{",
"savedStyleProps",
"[",
"prop",
"]",
"=",
"style",
"[",
"prop",
"]",
";",
"}",
"style",
"[",
"prop",
"]",
"=",
"styleProps",
"[",
"prop",
"]",
";",
"styleProps",
"[",
"prop",
"]",
"=",
"null",
";",
"}",
"}",
")",
";",
"return",
"element",
";",
"}"
]
| Set style properties while saving current properties.
@param {Element} element - Target element.
@param {Object} styleProps - New style properties.
@param {(Object|null)} savedStyleProps - Current style properties holder.
@param {Array} [propNames] - Names of target properties.
@returns {Element} Target element itself. | [
"Set",
"style",
"properties",
"while",
"saving",
"current",
"properties",
"."
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/plain-overlay.esm.js#L105-L117 | train |
anseki/plain-overlay | plain-overlay.esm.js | getDocClientWH | function getDocClientWH(props) {
var elmTarget = props.elmTarget,
width = elmTarget.clientWidth,
height = elmTarget.clientHeight;
if (IS_TRIDENT || IS_EDGE) {
var targetBodyCmpStyle = props.window.getComputedStyle(props.elmTargetBody, ''),
wMode = targetBodyCmpStyle.writingMode || targetBodyCmpStyle['writing-mode'],
// Trident bug
direction = targetBodyCmpStyle.direction;
return wMode === 'tb-rl' || wMode === 'bt-rl' || wMode === 'tb-lr' || wMode === 'bt-lr' || IS_EDGE && (direction === 'ltr' && (wMode === 'vertical-rl' || wMode === 'vertical-lr') || direction === 'rtl' && (wMode === 'vertical-rl' || wMode === 'vertical-lr')) ? { width: height, height: width } : // interchange
{ width: width, height: height };
}
return { width: width, height: height };
} | javascript | function getDocClientWH(props) {
var elmTarget = props.elmTarget,
width = elmTarget.clientWidth,
height = elmTarget.clientHeight;
if (IS_TRIDENT || IS_EDGE) {
var targetBodyCmpStyle = props.window.getComputedStyle(props.elmTargetBody, ''),
wMode = targetBodyCmpStyle.writingMode || targetBodyCmpStyle['writing-mode'],
// Trident bug
direction = targetBodyCmpStyle.direction;
return wMode === 'tb-rl' || wMode === 'bt-rl' || wMode === 'tb-lr' || wMode === 'bt-lr' || IS_EDGE && (direction === 'ltr' && (wMode === 'vertical-rl' || wMode === 'vertical-lr') || direction === 'rtl' && (wMode === 'vertical-rl' || wMode === 'vertical-lr')) ? { width: height, height: width } : // interchange
{ width: width, height: height };
}
return { width: width, height: height };
} | [
"function",
"getDocClientWH",
"(",
"props",
")",
"{",
"var",
"elmTarget",
"=",
"props",
".",
"elmTarget",
",",
"width",
"=",
"elmTarget",
".",
"clientWidth",
",",
"height",
"=",
"elmTarget",
".",
"clientHeight",
";",
"if",
"(",
"IS_TRIDENT",
"||",
"IS_EDGE",
")",
"{",
"var",
"targetBodyCmpStyle",
"=",
"props",
".",
"window",
".",
"getComputedStyle",
"(",
"props",
".",
"elmTargetBody",
",",
"''",
")",
",",
"wMode",
"=",
"targetBodyCmpStyle",
".",
"writingMode",
"||",
"targetBodyCmpStyle",
"[",
"'writing-mode'",
"]",
",",
"direction",
"=",
"targetBodyCmpStyle",
".",
"direction",
";",
"return",
"wMode",
"===",
"'tb-rl'",
"||",
"wMode",
"===",
"'bt-rl'",
"||",
"wMode",
"===",
"'tb-lr'",
"||",
"wMode",
"===",
"'bt-lr'",
"||",
"IS_EDGE",
"&&",
"(",
"direction",
"===",
"'ltr'",
"&&",
"(",
"wMode",
"===",
"'vertical-rl'",
"||",
"wMode",
"===",
"'vertical-lr'",
")",
"||",
"direction",
"===",
"'rtl'",
"&&",
"(",
"wMode",
"===",
"'vertical-rl'",
"||",
"wMode",
"===",
"'vertical-lr'",
")",
")",
"?",
"{",
"width",
":",
"height",
",",
"height",
":",
"width",
"}",
":",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
"}",
";",
"}",
"return",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
"}",
";",
"}"
]
| Trident and Edge bug, width and height are interchanged. | [
"Trident",
"and",
"Edge",
"bug",
"width",
"and",
"height",
"are",
"interchanged",
"."
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/plain-overlay.esm.js#L238-L251 | train |
anseki/plain-overlay | plain-overlay.esm.js | nodeContainsSel | function nodeContainsSel(node, selection) {
var nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNode(node);
for (var i = 0; i < iLen; i++) {
var selRange = selection.getRangeAt(i);
if (selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 || selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return false;
}
}
return true;
} | javascript | function nodeContainsSel(node, selection) {
var nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNode(node);
for (var i = 0; i < iLen; i++) {
var selRange = selection.getRangeAt(i);
if (selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 || selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return false;
}
}
return true;
} | [
"function",
"nodeContainsSel",
"(",
"node",
",",
"selection",
")",
"{",
"var",
"nodeRange",
"=",
"node",
".",
"ownerDocument",
".",
"createRange",
"(",
")",
",",
"iLen",
"=",
"selection",
".",
"rangeCount",
";",
"nodeRange",
".",
"selectNode",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"iLen",
";",
"i",
"++",
")",
"{",
"var",
"selRange",
"=",
"selection",
".",
"getRangeAt",
"(",
"i",
")",
";",
"if",
"(",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"START_TO_START",
",",
"nodeRange",
")",
"<",
"0",
"||",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"END_TO_END",
",",
"nodeRange",
")",
">",
"0",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Indicates whether the selection is part of the node or not.
@param {Node} node - Target node.
@param {Selection} selection - The parsed selection.
@returns {boolean} `true` if all ranges of `selection` are part of `node`. | [
"Indicates",
"whether",
"the",
"selection",
"is",
"part",
"of",
"the",
"node",
"or",
"not",
"."
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/plain-overlay.esm.js#L342-L353 | train |
topliceanu/sum | sum.js | function (str) {
return _(str).chain()
.unescapeHTML()
.stripTags()
.clean()
.value()
.replace( matchJunk, '' )
.toLowerCase();
} | javascript | function (str) {
return _(str).chain()
.unescapeHTML()
.stripTags()
.clean()
.value()
.replace( matchJunk, '' )
.toLowerCase();
} | [
"function",
"(",
"str",
")",
"{",
"return",
"_",
"(",
"str",
")",
".",
"chain",
"(",
")",
".",
"unescapeHTML",
"(",
")",
".",
"stripTags",
"(",
")",
".",
"clean",
"(",
")",
".",
"value",
"(",
")",
".",
"replace",
"(",
"matchJunk",
",",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"}"
]
| Function used to clean sentences before splitting into words
@param {String} str
@return {String} | [
"Function",
"used",
"to",
"clean",
"sentences",
"before",
"splitting",
"into",
"words"
]
| b3f3195cfca95b1f690cb01aebfe7d2d59ce4890 | https://github.com/topliceanu/sum/blob/b3f3195cfca95b1f690cb01aebfe7d2d59ce4890/sum.js#L78-L86 | train |
|
anseki/plain-overlay | src/plain-overlay.js | selContainsNode | function selContainsNode(selection, node, partialContainment) {
const nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNodeContents(node);
for (let i = 0; i < iLen; i++) {
const selRange = selection.getRangeAt(i);
// Edge bug (Issue #7321753); getRangeAt returns empty (collapsed) range
// NOTE: It can not recover when the selection has multiple ranges.
if (!selRange.toString().length && selection.toString().length && iLen === 1) {
console.log('Edge bug (Issue #7321753)'); // [DEBUG/]
selRange.setStart(selection.anchorNode, selection.anchorOffset);
selRange.setEnd(selection.focusNode, selection.focusOffset);
// Edge doesn't throw when end is upper than start.
if (selRange.toString() !== selection.toString()) {
selRange.setStart(selection.focusNode, selection.focusOffset);
selRange.setEnd(selection.anchorNode, selection.anchorOffset);
if (selRange.toString() !== selection.toString()) {
throw new Error('Edge bug (Issue #7321753); Couldn\'t recover');
}
}
}
if (partialContainment
? selRange.compareBoundaryPoints(Range.START_TO_END, nodeRange) >= 0 &&
selRange.compareBoundaryPoints(Range.END_TO_START, nodeRange) <= 0 :
selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 &&
selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return true;
}
}
return false;
} | javascript | function selContainsNode(selection, node, partialContainment) {
const nodeRange = node.ownerDocument.createRange(),
iLen = selection.rangeCount;
nodeRange.selectNodeContents(node);
for (let i = 0; i < iLen; i++) {
const selRange = selection.getRangeAt(i);
// Edge bug (Issue #7321753); getRangeAt returns empty (collapsed) range
// NOTE: It can not recover when the selection has multiple ranges.
if (!selRange.toString().length && selection.toString().length && iLen === 1) {
console.log('Edge bug (Issue #7321753)'); // [DEBUG/]
selRange.setStart(selection.anchorNode, selection.anchorOffset);
selRange.setEnd(selection.focusNode, selection.focusOffset);
// Edge doesn't throw when end is upper than start.
if (selRange.toString() !== selection.toString()) {
selRange.setStart(selection.focusNode, selection.focusOffset);
selRange.setEnd(selection.anchorNode, selection.anchorOffset);
if (selRange.toString() !== selection.toString()) {
throw new Error('Edge bug (Issue #7321753); Couldn\'t recover');
}
}
}
if (partialContainment
? selRange.compareBoundaryPoints(Range.START_TO_END, nodeRange) >= 0 &&
selRange.compareBoundaryPoints(Range.END_TO_START, nodeRange) <= 0 :
selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 &&
selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) {
return true;
}
}
return false;
} | [
"function",
"selContainsNode",
"(",
"selection",
",",
"node",
",",
"partialContainment",
")",
"{",
"const",
"nodeRange",
"=",
"node",
".",
"ownerDocument",
".",
"createRange",
"(",
")",
",",
"iLen",
"=",
"selection",
".",
"rangeCount",
";",
"nodeRange",
".",
"selectNodeContents",
"(",
"node",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"iLen",
";",
"i",
"++",
")",
"{",
"const",
"selRange",
"=",
"selection",
".",
"getRangeAt",
"(",
"i",
")",
";",
"if",
"(",
"!",
"selRange",
".",
"toString",
"(",
")",
".",
"length",
"&&",
"selection",
".",
"toString",
"(",
")",
".",
"length",
"&&",
"iLen",
"===",
"1",
")",
"{",
"console",
".",
"log",
"(",
"'Edge bug (Issue #7321753)'",
")",
";",
"selRange",
".",
"setStart",
"(",
"selection",
".",
"anchorNode",
",",
"selection",
".",
"anchorOffset",
")",
";",
"selRange",
".",
"setEnd",
"(",
"selection",
".",
"focusNode",
",",
"selection",
".",
"focusOffset",
")",
";",
"if",
"(",
"selRange",
".",
"toString",
"(",
")",
"!==",
"selection",
".",
"toString",
"(",
")",
")",
"{",
"selRange",
".",
"setStart",
"(",
"selection",
".",
"focusNode",
",",
"selection",
".",
"focusOffset",
")",
";",
"selRange",
".",
"setEnd",
"(",
"selection",
".",
"anchorNode",
",",
"selection",
".",
"anchorOffset",
")",
";",
"if",
"(",
"selRange",
".",
"toString",
"(",
")",
"!==",
"selection",
".",
"toString",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Edge bug (Issue #7321753); Couldn\\'t recover'",
")",
";",
"}",
"}",
"}",
"\\'",
"}",
"if",
"(",
"partialContainment",
"?",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"START_TO_END",
",",
"nodeRange",
")",
">=",
"0",
"&&",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"END_TO_START",
",",
"nodeRange",
")",
"<=",
"0",
":",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"START_TO_START",
",",
"nodeRange",
")",
"<",
"0",
"&&",
"selRange",
".",
"compareBoundaryPoints",
"(",
"Range",
".",
"END_TO_END",
",",
"nodeRange",
")",
">",
"0",
")",
"{",
"return",
"true",
";",
"}",
"}"
]
| Selection.containsNode polyfill for Trident | [
"Selection",
".",
"containsNode",
"polyfill",
"for",
"Trident"
]
| 0d5db55507aeb2acaa641d0e59b2495c8c0152aa | https://github.com/anseki/plain-overlay/blob/0d5db55507aeb2acaa641d0e59b2495c8c0152aa/src/plain-overlay.js#L343-L373 | train |
clns/node-commit-msg | lib/nlp-parser.js | getMatchingParenthesis | function getMatchingParenthesis(string, startPos) {
var length = string.length;
var bracket = 1;
for (var i=startPos+1; i<=length; i++) {
if (string[i] == '(') {
bracket += 1;
} else if (string[i] == ')') {
bracket -= 1;
}
if (bracket == 0) {
return i;
}
}
} | javascript | function getMatchingParenthesis(string, startPos) {
var length = string.length;
var bracket = 1;
for (var i=startPos+1; i<=length; i++) {
if (string[i] == '(') {
bracket += 1;
} else if (string[i] == ')') {
bracket -= 1;
}
if (bracket == 0) {
return i;
}
}
} | [
"function",
"getMatchingParenthesis",
"(",
"string",
",",
"startPos",
")",
"{",
"var",
"length",
"=",
"string",
".",
"length",
";",
"var",
"bracket",
"=",
"1",
";",
"for",
"(",
"var",
"i",
"=",
"startPos",
"+",
"1",
";",
"i",
"<=",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"string",
"[",
"i",
"]",
"==",
"'('",
")",
"{",
"bracket",
"+=",
"1",
";",
"}",
"else",
"if",
"(",
"string",
"[",
"i",
"]",
"==",
"')'",
")",
"{",
"bracket",
"-=",
"1",
";",
"}",
"if",
"(",
"bracket",
"==",
"0",
")",
"{",
"return",
"i",
";",
"}",
"}",
"}"
]
| Find the position of a matching closing bracket for a string opening bracket | [
"Find",
"the",
"position",
"of",
"a",
"matching",
"closing",
"bracket",
"for",
"a",
"string",
"opening",
"bracket"
]
| 53108eca78f627e770d0d885e4ae0b4ddf87f141 | https://github.com/clns/node-commit-msg/blob/53108eca78f627e770d0d885e4ae0b4ddf87f141/lib/nlp-parser.js#L218-L231 | train |
Maheshkumar-Kakade/otp-generator | index.js | function (length, options) {
length = length || 10
var generateOptions = options || {}
generateOptions.digits = generateOptions.hasOwnProperty('digits') ? options.digits : true
generateOptions.alphabets = generateOptions.hasOwnProperty('alphabets') ? options.alphabets : true
generateOptions.upperCase = generateOptions.hasOwnProperty('upperCase') ? options.upperCase : true
generateOptions.specialChars = generateOptions.hasOwnProperty('specialChars') ? options.specialChars : true
var allowsChars = ((generateOptions.digits || '') && digits) +
((generateOptions.alphabets || '') && alphabets) +
((generateOptions.upperCase || '') && upperCase) +
((generateOptions.specialChars || '') && specialChars)
var password = ''
for (var index = 0; index < length; ++index) {
var charIndex = rand(0, allowsChars.length - 1)
password += allowsChars[charIndex]
}
return password
} | javascript | function (length, options) {
length = length || 10
var generateOptions = options || {}
generateOptions.digits = generateOptions.hasOwnProperty('digits') ? options.digits : true
generateOptions.alphabets = generateOptions.hasOwnProperty('alphabets') ? options.alphabets : true
generateOptions.upperCase = generateOptions.hasOwnProperty('upperCase') ? options.upperCase : true
generateOptions.specialChars = generateOptions.hasOwnProperty('specialChars') ? options.specialChars : true
var allowsChars = ((generateOptions.digits || '') && digits) +
((generateOptions.alphabets || '') && alphabets) +
((generateOptions.upperCase || '') && upperCase) +
((generateOptions.specialChars || '') && specialChars)
var password = ''
for (var index = 0; index < length; ++index) {
var charIndex = rand(0, allowsChars.length - 1)
password += allowsChars[charIndex]
}
return password
} | [
"function",
"(",
"length",
",",
"options",
")",
"{",
"length",
"=",
"length",
"||",
"10",
"var",
"generateOptions",
"=",
"options",
"||",
"{",
"}",
"generateOptions",
".",
"digits",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'digits'",
")",
"?",
"options",
".",
"digits",
":",
"true",
"generateOptions",
".",
"alphabets",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'alphabets'",
")",
"?",
"options",
".",
"alphabets",
":",
"true",
"generateOptions",
".",
"upperCase",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'upperCase'",
")",
"?",
"options",
".",
"upperCase",
":",
"true",
"generateOptions",
".",
"specialChars",
"=",
"generateOptions",
".",
"hasOwnProperty",
"(",
"'specialChars'",
")",
"?",
"options",
".",
"specialChars",
":",
"true",
"var",
"allowsChars",
"=",
"(",
"(",
"generateOptions",
".",
"digits",
"||",
"''",
")",
"&&",
"digits",
")",
"+",
"(",
"(",
"generateOptions",
".",
"alphabets",
"||",
"''",
")",
"&&",
"alphabets",
")",
"+",
"(",
"(",
"generateOptions",
".",
"upperCase",
"||",
"''",
")",
"&&",
"upperCase",
")",
"+",
"(",
"(",
"generateOptions",
".",
"specialChars",
"||",
"''",
")",
"&&",
"specialChars",
")",
"var",
"password",
"=",
"''",
"for",
"(",
"var",
"index",
"=",
"0",
";",
"index",
"<",
"length",
";",
"++",
"index",
")",
"{",
"var",
"charIndex",
"=",
"rand",
"(",
"0",
",",
"allowsChars",
".",
"length",
"-",
"1",
")",
"password",
"+=",
"allowsChars",
"[",
"charIndex",
"]",
"}",
"return",
"password",
"}"
]
| Generate OTP of the length
@param {number} length length of password.
@param {object} options
@param {boolean} options.digits Default: `true` true value includes digits in OTP
@param {boolean} options.alphabets Default: `true` true value includes alphabets in OTP
@param {boolean} options.upperCase Default: `true` true value includes upperCase in OTP
@param {boolean} options.specialChars Default: `true` true value includes specialChars in OTP | [
"Generate",
"OTP",
"of",
"the",
"length"
]
| 9d794ce1a2ae78c974ec5913588fe8043e9073ba | https://github.com/Maheshkumar-Kakade/otp-generator/blob/9d794ce1a2ae78c974ec5913588fe8043e9073ba/index.js#L24-L43 | train |
|
maxazan/angular-multiple-selection | multiple-selection.js | getSelectableElements | function getSelectableElements(element) {
var out = [];
var childs = element.children();
for (var i = 0; i < childs.length; i++) {
var child = angular.element(childs[i]);
if (child.scope().isSelectable) {
out.push(child);
} else {
if (child.scope().$id!=element.scope().$id && child.scope().isSelectableZone === true) {
} else {
out = out.concat(getSelectableElements(child));
}
}
}
return out;
} | javascript | function getSelectableElements(element) {
var out = [];
var childs = element.children();
for (var i = 0; i < childs.length; i++) {
var child = angular.element(childs[i]);
if (child.scope().isSelectable) {
out.push(child);
} else {
if (child.scope().$id!=element.scope().$id && child.scope().isSelectableZone === true) {
} else {
out = out.concat(getSelectableElements(child));
}
}
}
return out;
} | [
"function",
"getSelectableElements",
"(",
"element",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"var",
"childs",
"=",
"element",
".",
"children",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childs",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"child",
"=",
"angular",
".",
"element",
"(",
"childs",
"[",
"i",
"]",
")",
";",
"if",
"(",
"child",
".",
"scope",
"(",
")",
".",
"isSelectable",
")",
"{",
"out",
".",
"push",
"(",
"child",
")",
";",
"}",
"else",
"{",
"if",
"(",
"child",
".",
"scope",
"(",
")",
".",
"$id",
"!=",
"element",
".",
"scope",
"(",
")",
".",
"$id",
"&&",
"child",
".",
"scope",
"(",
")",
".",
"isSelectableZone",
"===",
"true",
")",
"{",
"}",
"else",
"{",
"out",
"=",
"out",
".",
"concat",
"(",
"getSelectableElements",
"(",
"child",
")",
")",
";",
"}",
"}",
"}",
"return",
"out",
";",
"}"
]
| Angular JS multiple-selection module
@author Maksym Pomazan
@version 0.0.3 | [
"Angular",
"JS",
"multiple",
"-",
"selection",
"module"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L6-L22 | train |
maxazan/angular-multiple-selection | multiple-selection.js | checkElementHitting | function checkElementHitting(box1, box2) {
return (box2.beginX <= box1.beginX && box1.beginX <= box2.endX || box1.beginX <= box2.beginX && box2.beginX <= box1.endX) &&
(box2.beginY <= box1.beginY && box1.beginY <= box2.endY || box1.beginY <= box2.beginY && box2.beginY <= box1.endY);
} | javascript | function checkElementHitting(box1, box2) {
return (box2.beginX <= box1.beginX && box1.beginX <= box2.endX || box1.beginX <= box2.beginX && box2.beginX <= box1.endX) &&
(box2.beginY <= box1.beginY && box1.beginY <= box2.endY || box1.beginY <= box2.beginY && box2.beginY <= box1.endY);
} | [
"function",
"checkElementHitting",
"(",
"box1",
",",
"box2",
")",
"{",
"return",
"(",
"box2",
".",
"beginX",
"<=",
"box1",
".",
"beginX",
"&&",
"box1",
".",
"beginX",
"<=",
"box2",
".",
"endX",
"||",
"box1",
".",
"beginX",
"<=",
"box2",
".",
"beginX",
"&&",
"box2",
".",
"beginX",
"<=",
"box1",
".",
"endX",
")",
"&&",
"(",
"box2",
".",
"beginY",
"<=",
"box1",
".",
"beginY",
"&&",
"box1",
".",
"beginY",
"<=",
"box2",
".",
"endY",
"||",
"box1",
".",
"beginY",
"<=",
"box2",
".",
"beginY",
"&&",
"box2",
".",
"beginY",
"<=",
"box1",
".",
"endY",
")",
";",
"}"
]
| Check that 2 boxes hitting
@param {Object} box1
@param {Object} box2
@return {Boolean} is hitting | [
"Check",
"that",
"2",
"boxes",
"hitting"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L99-L102 | train |
maxazan/angular-multiple-selection | multiple-selection.js | moveSelectionHelper | function moveSelectionHelper(hepler, startX, startY, endX, endY) {
var box = transformBox(startX, startY, endX, endY);
helper.css({
"top": box.beginY + "px",
"left": box.beginX + "px",
"width": (box.endX - box.beginX) + "px",
"height": (box.endY - box.beginY) + "px"
});
} | javascript | function moveSelectionHelper(hepler, startX, startY, endX, endY) {
var box = transformBox(startX, startY, endX, endY);
helper.css({
"top": box.beginY + "px",
"left": box.beginX + "px",
"width": (box.endX - box.beginX) + "px",
"height": (box.endY - box.beginY) + "px"
});
} | [
"function",
"moveSelectionHelper",
"(",
"hepler",
",",
"startX",
",",
"startY",
",",
"endX",
",",
"endY",
")",
"{",
"var",
"box",
"=",
"transformBox",
"(",
"startX",
",",
"startY",
",",
"endX",
",",
"endY",
")",
";",
"helper",
".",
"css",
"(",
"{",
"\"top\"",
":",
"box",
".",
"beginY",
"+",
"\"px\"",
",",
"\"left\"",
":",
"box",
".",
"beginX",
"+",
"\"px\"",
",",
"\"width\"",
":",
"(",
"box",
".",
"endX",
"-",
"box",
".",
"beginX",
")",
"+",
"\"px\"",
",",
"\"height\"",
":",
"(",
"box",
".",
"endY",
"-",
"box",
".",
"beginY",
")",
"+",
"\"px\"",
"}",
")",
";",
"}"
]
| Method move selection helper
@param {Element} hepler
@param {Number} startX
@param {Number} startY
@param {Number} endX
@param {Number} endY | [
"Method",
"move",
"selection",
"helper"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L143-L153 | train |
maxazan/angular-multiple-selection | multiple-selection.js | mousemove | function mousemove(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Move helper
moveSelectionHelper(helper, startX, startY, event.pageX, event.pageY);
// Check items is selecting
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (checkElementHitting(transformBox(offset(childs[i][0]).left, offset(childs[i][0]).top, offset(childs[i][0]).left + childs[i].prop('offsetWidth'), offset(childs[i][0]).top + childs[i].prop('offsetHeight')), transformBox(startX, startY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelecting === false) {
childs[i].scope().isSelecting = true;
childs[i].scope().$apply();
}
} else {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().$apply();
}
}
}
} | javascript | function mousemove(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Move helper
moveSelectionHelper(helper, startX, startY, event.pageX, event.pageY);
// Check items is selecting
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (checkElementHitting(transformBox(offset(childs[i][0]).left, offset(childs[i][0]).top, offset(childs[i][0]).left + childs[i].prop('offsetWidth'), offset(childs[i][0]).top + childs[i].prop('offsetHeight')), transformBox(startX, startY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelecting === false) {
childs[i].scope().isSelecting = true;
childs[i].scope().$apply();
}
} else {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().$apply();
}
}
}
} | [
"function",
"mousemove",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"moveSelectionHelper",
"(",
"helper",
",",
"startX",
",",
"startY",
",",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
")",
";",
"var",
"childs",
"=",
"getSelectableElements",
"(",
"element",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"checkElementHitting",
"(",
"transformBox",
"(",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"left",
",",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"top",
",",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"left",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetWidth'",
")",
",",
"offset",
"(",
"childs",
"[",
"i",
"]",
"[",
"0",
"]",
")",
".",
"top",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetHeight'",
")",
")",
",",
"transformBox",
"(",
"startX",
",",
"startY",
",",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
")",
")",
")",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"===",
"false",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"=",
"true",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"===",
"true",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"=",
"false",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"}",
"}",
"}"
]
| Method on Mouse Move
@param {Event} @event | [
"Method",
"on",
"Mouse",
"Move"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L160-L180 | train |
maxazan/angular-multiple-selection | multiple-selection.js | mouseup | function mouseup(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Remove helper
helper.remove();
// Change all selecting items to selected
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().isSelected = event.ctrlKey ? !childs[i].scope().isSelected : true;
childs[i].scope().$apply();
} else {
if (checkElementHitting(transformBox(childs[i].prop('offsetLeft'), childs[i].prop('offsetTop'), childs[i].prop('offsetLeft') + childs[i].prop('offsetWidth'), childs[i].prop('offsetTop') + childs[i].prop('offsetHeight')), transformBox(event.pageX, event.pageY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelected === false) {
childs[i].scope().isSelected = true;
childs[i].scope().$apply();
}
}
}
}
// Remove listeners
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
} | javascript | function mouseup(event) {
// Prevent default dragging of selected content
event.preventDefault();
// Remove helper
helper.remove();
// Change all selecting items to selected
var childs = getSelectableElements(element);
for (var i = 0; i < childs.length; i++) {
if (childs[i].scope().isSelecting === true) {
childs[i].scope().isSelecting = false;
childs[i].scope().isSelected = event.ctrlKey ? !childs[i].scope().isSelected : true;
childs[i].scope().$apply();
} else {
if (checkElementHitting(transformBox(childs[i].prop('offsetLeft'), childs[i].prop('offsetTop'), childs[i].prop('offsetLeft') + childs[i].prop('offsetWidth'), childs[i].prop('offsetTop') + childs[i].prop('offsetHeight')), transformBox(event.pageX, event.pageY, event.pageX, event.pageY))) {
if (childs[i].scope().isSelected === false) {
childs[i].scope().isSelected = true;
childs[i].scope().$apply();
}
}
}
}
// Remove listeners
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
} | [
"function",
"mouseup",
"(",
"event",
")",
"{",
"event",
".",
"preventDefault",
"(",
")",
";",
"helper",
".",
"remove",
"(",
")",
";",
"var",
"childs",
"=",
"getSelectableElements",
"(",
"element",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"===",
"true",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelecting",
"=",
"false",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
"=",
"event",
".",
"ctrlKey",
"?",
"!",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
":",
"true",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"checkElementHitting",
"(",
"transformBox",
"(",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetLeft'",
")",
",",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetTop'",
")",
",",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetLeft'",
")",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetWidth'",
")",
",",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetTop'",
")",
"+",
"childs",
"[",
"i",
"]",
".",
"prop",
"(",
"'offsetHeight'",
")",
")",
",",
"transformBox",
"(",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
",",
"event",
".",
"pageX",
",",
"event",
".",
"pageY",
")",
")",
")",
"{",
"if",
"(",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
"===",
"false",
")",
"{",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"isSelected",
"=",
"true",
";",
"childs",
"[",
"i",
"]",
".",
"scope",
"(",
")",
".",
"$apply",
"(",
")",
";",
"}",
"}",
"}",
"}",
"$document",
".",
"off",
"(",
"'mousemove'",
",",
"mousemove",
")",
";",
"$document",
".",
"off",
"(",
"'mouseup'",
",",
"mouseup",
")",
";",
"}"
]
| Event on Mouse up
@param {Event} event | [
"Event",
"on",
"Mouse",
"up"
]
| 86fe83d71449adf801fc9d5fa4c7b9a439637835 | https://github.com/maxazan/angular-multiple-selection/blob/86fe83d71449adf801fc9d5fa4c7b9a439637835/multiple-selection.js#L188-L214 | train |
clns/node-commit-msg | lib/commit-message.js | function(verb) {
var matches = verb.value.match(/^VB[^P\s]+ (\S+)$/);
if (matches) {
var index = s.indexOf(matches[1]);
this._log('Use imperative present tense, eg. "Fix bug" not ' +
'"Fixed bug" or "Fixes bug". To get it right ask yourself: "If applied, ' +
'this patch will <YOUR-COMMIT-MESSAGE-HERE>"',
cfg.imperativeVerbsInSubject.type, [1, index+1+this._colOffset]);
hasError = true;
return false; // stop loop
}
return true;
} | javascript | function(verb) {
var matches = verb.value.match(/^VB[^P\s]+ (\S+)$/);
if (matches) {
var index = s.indexOf(matches[1]);
this._log('Use imperative present tense, eg. "Fix bug" not ' +
'"Fixed bug" or "Fixes bug". To get it right ask yourself: "If applied, ' +
'this patch will <YOUR-COMMIT-MESSAGE-HERE>"',
cfg.imperativeVerbsInSubject.type, [1, index+1+this._colOffset]);
hasError = true;
return false; // stop loop
}
return true;
} | [
"function",
"(",
"verb",
")",
"{",
"var",
"matches",
"=",
"verb",
".",
"value",
".",
"match",
"(",
"/",
"^VB[^P\\s]+ (\\S+)$",
"/",
")",
";",
"if",
"(",
"matches",
")",
"{",
"var",
"index",
"=",
"s",
".",
"indexOf",
"(",
"matches",
"[",
"1",
"]",
")",
";",
"this",
".",
"_log",
"(",
"'Use imperative present tense, eg. \"Fix bug\" not '",
"+",
"'\"Fixed bug\" or \"Fixes bug\". To get it right ask yourself: \"If applied, '",
"+",
"'this patch will <YOUR-COMMIT-MESSAGE-HERE>\"'",
",",
"cfg",
".",
"imperativeVerbsInSubject",
".",
"type",
",",
"[",
"1",
",",
"index",
"+",
"1",
"+",
"this",
".",
"_colOffset",
"]",
")",
";",
"hasError",
"=",
"true",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| If the commit message is not a fragment and contains at least 1 verb, continue | [
"If",
"the",
"commit",
"message",
"is",
"not",
"a",
"fragment",
"and",
"contains",
"at",
"least",
"1",
"verb",
"continue"
]
| 53108eca78f627e770d0d885e4ae0b4ddf87f141 | https://github.com/clns/node-commit-msg/blob/53108eca78f627e770d0d885e4ae0b4ddf87f141/lib/commit-message.js#L357-L371 | train |
|
luckylooke/dragon | example/example.js | animate | function animate( dragon, itemElm, destElm, duration ) {
duration = duration || 2;
let getOffset = dragon.space.utils.getOffset
let itemOffset = getOffset( itemElm, true )
let destOffset = getOffset( destElm, true )
let startX = itemOffset.left + ( itemOffset.width / 2 )
let startY = itemOffset.top + ( itemOffset.height / 2 )
let destX = destOffset.left + ( destOffset.width / 2 )
let destY = destOffset.top + ( destOffset.height / 2 )
let distanceX = destX - startX
let distanceY = destY - startY
let steps = duration * 60
let i = 0
animationRunning = true;
let drag = dragon.grab( itemElm )
drag.start( itemOffset.width / 2, itemOffset.height / 2 )
let cb = () => {
drag.release();
animationRunning = false;
}
step( 16 )
function step( time ) {
// console.log( 'step', drag.x, drag.y );
if ( i < steps ) {
setTimeout( () => {
let ease = easeInOutQuadDiff( i++ / steps, i-- / steps )
let ease2 = easeInOutQuartDiff( i++ / steps, i / steps )
// console.log( 'step', distanceX * ease, distanceY * ease2 )
drag.drag( drag.x + distanceX * ease, drag.y + distanceY * ease2 )
step( time )
}, time )
return
}
else
drag.drag( destX, destY )
if ( cb )
setTimeout( cb, 500 )
}
} | javascript | function animate( dragon, itemElm, destElm, duration ) {
duration = duration || 2;
let getOffset = dragon.space.utils.getOffset
let itemOffset = getOffset( itemElm, true )
let destOffset = getOffset( destElm, true )
let startX = itemOffset.left + ( itemOffset.width / 2 )
let startY = itemOffset.top + ( itemOffset.height / 2 )
let destX = destOffset.left + ( destOffset.width / 2 )
let destY = destOffset.top + ( destOffset.height / 2 )
let distanceX = destX - startX
let distanceY = destY - startY
let steps = duration * 60
let i = 0
animationRunning = true;
let drag = dragon.grab( itemElm )
drag.start( itemOffset.width / 2, itemOffset.height / 2 )
let cb = () => {
drag.release();
animationRunning = false;
}
step( 16 )
function step( time ) {
// console.log( 'step', drag.x, drag.y );
if ( i < steps ) {
setTimeout( () => {
let ease = easeInOutQuadDiff( i++ / steps, i-- / steps )
let ease2 = easeInOutQuartDiff( i++ / steps, i / steps )
// console.log( 'step', distanceX * ease, distanceY * ease2 )
drag.drag( drag.x + distanceX * ease, drag.y + distanceY * ease2 )
step( time )
}, time )
return
}
else
drag.drag( destX, destY )
if ( cb )
setTimeout( cb, 500 )
}
} | [
"function",
"animate",
"(",
"dragon",
",",
"itemElm",
",",
"destElm",
",",
"duration",
")",
"{",
"duration",
"=",
"duration",
"||",
"2",
";",
"let",
"getOffset",
"=",
"dragon",
".",
"space",
".",
"utils",
".",
"getOffset",
"let",
"itemOffset",
"=",
"getOffset",
"(",
"itemElm",
",",
"true",
")",
"let",
"destOffset",
"=",
"getOffset",
"(",
"destElm",
",",
"true",
")",
"let",
"startX",
"=",
"itemOffset",
".",
"left",
"+",
"(",
"itemOffset",
".",
"width",
"/",
"2",
")",
"let",
"startY",
"=",
"itemOffset",
".",
"top",
"+",
"(",
"itemOffset",
".",
"height",
"/",
"2",
")",
"let",
"destX",
"=",
"destOffset",
".",
"left",
"+",
"(",
"destOffset",
".",
"width",
"/",
"2",
")",
"let",
"destY",
"=",
"destOffset",
".",
"top",
"+",
"(",
"destOffset",
".",
"height",
"/",
"2",
")",
"let",
"distanceX",
"=",
"destX",
"-",
"startX",
"let",
"distanceY",
"=",
"destY",
"-",
"startY",
"let",
"steps",
"=",
"duration",
"*",
"60",
"let",
"i",
"=",
"0",
"animationRunning",
"=",
"true",
";",
"let",
"drag",
"=",
"dragon",
".",
"grab",
"(",
"itemElm",
")",
"drag",
".",
"start",
"(",
"itemOffset",
".",
"width",
"/",
"2",
",",
"itemOffset",
".",
"height",
"/",
"2",
")",
"let",
"cb",
"=",
"(",
")",
"=>",
"{",
"drag",
".",
"release",
"(",
")",
";",
"animationRunning",
"=",
"false",
";",
"}",
"step",
"(",
"16",
")",
"function",
"step",
"(",
"time",
")",
"{",
"if",
"(",
"i",
"<",
"steps",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"let",
"ease",
"=",
"easeInOutQuadDiff",
"(",
"i",
"++",
"/",
"steps",
",",
"i",
"--",
"/",
"steps",
")",
"let",
"ease2",
"=",
"easeInOutQuartDiff",
"(",
"i",
"++",
"/",
"steps",
",",
"i",
"/",
"steps",
")",
"drag",
".",
"drag",
"(",
"drag",
".",
"x",
"+",
"distanceX",
"*",
"ease",
",",
"drag",
".",
"y",
"+",
"distanceY",
"*",
"ease2",
")",
"step",
"(",
"time",
")",
"}",
",",
"time",
")",
"return",
"}",
"else",
"drag",
".",
"drag",
"(",
"destX",
",",
"destY",
")",
"if",
"(",
"cb",
")",
"setTimeout",
"(",
"cb",
",",
"500",
")",
"}",
"}"
]
| duration in seconds! | [
"duration",
"in",
"seconds!"
]
| bb0c285967db04061fc75105aaa7ef62d2bd9d74 | https://github.com/luckylooke/dragon/blob/bb0c285967db04061fc75105aaa7ef62d2bd9d74/example/example.js#L32-L85 | train |
auduno/mosse | build/mosse.module.js | fft | function fft(re, im, inv) {
var d, h, ik, m, tmp, wr, wi, xr, xi,
n4 = _n >> 2;
// bit reversal
for(var l=0; l<_n; l++) {
m = _bitrev[l];
if(l < m) {
tmp = re[l];
re[l] = re[m];
re[m] = tmp;
tmp = im[l];
im[l] = im[m];
im[m] = tmp;
}
}
// butterfly operation
for(var k=1; k<_n; k<<=1) {
h = 0;
d = _n/(k << 1);
for(var j=0; j<k; j++) {
wr = _cstb[h + n4];
wi = inv*_cstb[h];
for(var i=j; i<_n; i+=(k<<1)) {
ik = i + k;
xr = wr*re[ik] + wi*im[ik];
xi = wr*im[ik] - wi*re[ik];
re[ik] = re[i] - xr;
re[i] += xr;
im[ik] = im[i] - xi;
im[i] += xi;
}
h += d;
}
}
} | javascript | function fft(re, im, inv) {
var d, h, ik, m, tmp, wr, wi, xr, xi,
n4 = _n >> 2;
// bit reversal
for(var l=0; l<_n; l++) {
m = _bitrev[l];
if(l < m) {
tmp = re[l];
re[l] = re[m];
re[m] = tmp;
tmp = im[l];
im[l] = im[m];
im[m] = tmp;
}
}
// butterfly operation
for(var k=1; k<_n; k<<=1) {
h = 0;
d = _n/(k << 1);
for(var j=0; j<k; j++) {
wr = _cstb[h + n4];
wi = inv*_cstb[h];
for(var i=j; i<_n; i+=(k<<1)) {
ik = i + k;
xr = wr*re[ik] + wi*im[ik];
xi = wr*im[ik] - wi*re[ik];
re[ik] = re[i] - xr;
re[i] += xr;
im[ik] = im[i] - xi;
im[i] += xi;
}
h += d;
}
}
} | [
"function",
"fft",
"(",
"re",
",",
"im",
",",
"inv",
")",
"{",
"var",
"d",
",",
"h",
",",
"ik",
",",
"m",
",",
"tmp",
",",
"wr",
",",
"wi",
",",
"xr",
",",
"xi",
",",
"n4",
"=",
"_n",
">>",
"2",
";",
"for",
"(",
"var",
"l",
"=",
"0",
";",
"l",
"<",
"_n",
";",
"l",
"++",
")",
"{",
"m",
"=",
"_bitrev",
"[",
"l",
"]",
";",
"if",
"(",
"l",
"<",
"m",
")",
"{",
"tmp",
"=",
"re",
"[",
"l",
"]",
";",
"re",
"[",
"l",
"]",
"=",
"re",
"[",
"m",
"]",
";",
"re",
"[",
"m",
"]",
"=",
"tmp",
";",
"tmp",
"=",
"im",
"[",
"l",
"]",
";",
"im",
"[",
"l",
"]",
"=",
"im",
"[",
"m",
"]",
";",
"im",
"[",
"m",
"]",
"=",
"tmp",
";",
"}",
"}",
"for",
"(",
"var",
"k",
"=",
"1",
";",
"k",
"<",
"_n",
";",
"k",
"<<=",
"1",
")",
"{",
"h",
"=",
"0",
";",
"d",
"=",
"_n",
"/",
"(",
"k",
"<<",
"1",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"k",
";",
"j",
"++",
")",
"{",
"wr",
"=",
"_cstb",
"[",
"h",
"+",
"n4",
"]",
";",
"wi",
"=",
"inv",
"*",
"_cstb",
"[",
"h",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"j",
";",
"i",
"<",
"_n",
";",
"i",
"+=",
"(",
"k",
"<<",
"1",
")",
")",
"{",
"ik",
"=",
"i",
"+",
"k",
";",
"xr",
"=",
"wr",
"*",
"re",
"[",
"ik",
"]",
"+",
"wi",
"*",
"im",
"[",
"ik",
"]",
";",
"xi",
"=",
"wr",
"*",
"im",
"[",
"ik",
"]",
"-",
"wi",
"*",
"re",
"[",
"ik",
"]",
";",
"re",
"[",
"ik",
"]",
"=",
"re",
"[",
"i",
"]",
"-",
"xr",
";",
"re",
"[",
"i",
"]",
"+=",
"xr",
";",
"im",
"[",
"ik",
"]",
"=",
"im",
"[",
"i",
"]",
"-",
"xi",
";",
"im",
"[",
"i",
"]",
"+=",
"xi",
";",
"}",
"h",
"+=",
"d",
";",
"}",
"}",
"}"
]
| core operation of FFT | [
"core",
"operation",
"of",
"FFT"
]
| 30b430aa091b271a884aae4211875777292304b2 | https://github.com/auduno/mosse/blob/30b430aa091b271a884aae4211875777292304b2/build/mosse.module.js#L107-L141 | train |
auduno/mosse | build/mosse.module.js | _makeBitReversal | function _makeBitReversal() {
var i = 0,
j = 0,
k = 0;
_bitrev[0] = 0;
while(++i < _n) {
k = _n >> 1;
while(k <= j) {
j -= k;
k >>= 1;
}
j += k;
_bitrev[i] = j;
}
} | javascript | function _makeBitReversal() {
var i = 0,
j = 0,
k = 0;
_bitrev[0] = 0;
while(++i < _n) {
k = _n >> 1;
while(k <= j) {
j -= k;
k >>= 1;
}
j += k;
_bitrev[i] = j;
}
} | [
"function",
"_makeBitReversal",
"(",
")",
"{",
"var",
"i",
"=",
"0",
",",
"j",
"=",
"0",
",",
"k",
"=",
"0",
";",
"_bitrev",
"[",
"0",
"]",
"=",
"0",
";",
"while",
"(",
"++",
"i",
"<",
"_n",
")",
"{",
"k",
"=",
"_n",
">>",
"1",
";",
"while",
"(",
"k",
"<=",
"j",
")",
"{",
"j",
"-=",
"k",
";",
"k",
">>=",
"1",
";",
"}",
"j",
"+=",
"k",
";",
"_bitrev",
"[",
"i",
"]",
"=",
"j",
";",
"}",
"}"
]
| make bit reversal table | [
"make",
"bit",
"reversal",
"table"
]
| 30b430aa091b271a884aae4211875777292304b2 | https://github.com/auduno/mosse/blob/30b430aa091b271a884aae4211875777292304b2/build/mosse.module.js#L162-L176 | train |
auduno/mosse | build/mosse.module.js | _makeCosSinTable | function _makeCosSinTable() {
var n2 = _n >> 1,
n4 = _n >> 2,
n8 = _n >> 3,
n2p4 = n2 + n4,
t = Math.sin(Math.PI/_n),
dc = 2*t*t,
ds = Math.sqrt(dc*(2 - dc)),
c = _cstb[n4] = 1,
s = _cstb[0] = 0;
t = 2*dc;
for(var i=1; i<n8; i++) {
c -= dc;
dc += t*c;
s += ds;
ds -= t*s;
_cstb[i] = s;
_cstb[n4 - i] = c;
}
if(n8 !== 0) {
_cstb[n8] = Math.sqrt(0.5);
}
for(var j=0; j<n4; j++) {
_cstb[n2 - j] = _cstb[j];
}
for(var k=0; k<n2p4; k++) {
_cstb[k + n2] = -_cstb[k];
}
} | javascript | function _makeCosSinTable() {
var n2 = _n >> 1,
n4 = _n >> 2,
n8 = _n >> 3,
n2p4 = n2 + n4,
t = Math.sin(Math.PI/_n),
dc = 2*t*t,
ds = Math.sqrt(dc*(2 - dc)),
c = _cstb[n4] = 1,
s = _cstb[0] = 0;
t = 2*dc;
for(var i=1; i<n8; i++) {
c -= dc;
dc += t*c;
s += ds;
ds -= t*s;
_cstb[i] = s;
_cstb[n4 - i] = c;
}
if(n8 !== 0) {
_cstb[n8] = Math.sqrt(0.5);
}
for(var j=0; j<n4; j++) {
_cstb[n2 - j] = _cstb[j];
}
for(var k=0; k<n2p4; k++) {
_cstb[k + n2] = -_cstb[k];
}
} | [
"function",
"_makeCosSinTable",
"(",
")",
"{",
"var",
"n2",
"=",
"_n",
">>",
"1",
",",
"n4",
"=",
"_n",
">>",
"2",
",",
"n8",
"=",
"_n",
">>",
"3",
",",
"n2p4",
"=",
"n2",
"+",
"n4",
",",
"t",
"=",
"Math",
".",
"sin",
"(",
"Math",
".",
"PI",
"/",
"_n",
")",
",",
"dc",
"=",
"2",
"*",
"t",
"*",
"t",
",",
"ds",
"=",
"Math",
".",
"sqrt",
"(",
"dc",
"*",
"(",
"2",
"-",
"dc",
")",
")",
",",
"c",
"=",
"_cstb",
"[",
"n4",
"]",
"=",
"1",
",",
"s",
"=",
"_cstb",
"[",
"0",
"]",
"=",
"0",
";",
"t",
"=",
"2",
"*",
"dc",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"n8",
";",
"i",
"++",
")",
"{",
"c",
"-=",
"dc",
";",
"dc",
"+=",
"t",
"*",
"c",
";",
"s",
"+=",
"ds",
";",
"ds",
"-=",
"t",
"*",
"s",
";",
"_cstb",
"[",
"i",
"]",
"=",
"s",
";",
"_cstb",
"[",
"n4",
"-",
"i",
"]",
"=",
"c",
";",
"}",
"if",
"(",
"n8",
"!==",
"0",
")",
"{",
"_cstb",
"[",
"n8",
"]",
"=",
"Math",
".",
"sqrt",
"(",
"0.5",
")",
";",
"}",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"n4",
";",
"j",
"++",
")",
"{",
"_cstb",
"[",
"n2",
"-",
"j",
"]",
"=",
"_cstb",
"[",
"j",
"]",
";",
"}",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"n2p4",
";",
"k",
"++",
")",
"{",
"_cstb",
"[",
"k",
"+",
"n2",
"]",
"=",
"-",
"_cstb",
"[",
"k",
"]",
";",
"}",
"}"
]
| make trigonometric function table | [
"make",
"trigonometric",
"function",
"table"
]
| 30b430aa091b271a884aae4211875777292304b2 | https://github.com/auduno/mosse/blob/30b430aa091b271a884aae4211875777292304b2/build/mosse.module.js#L179-L207 | train |
tjanczuk/wns | lib/wns.js | function (name, imageCount, textCount) {
// contains placeholder for optional binding attributes
// contains placeholder for each text and image payload
var template = '<binding template="' + name + '"%s>';
for (var i = 0; i < imageCount; i++)
template += '<image id="' + (i + 1) + '" src="%s" alt="%s"/>';
for (var i = 0; i < textCount; i++)
template += '<text id="' + (i + 1) + '">%s</text>';
template += '</binding>';
return template;
} | javascript | function (name, imageCount, textCount) {
// contains placeholder for optional binding attributes
// contains placeholder for each text and image payload
var template = '<binding template="' + name + '"%s>';
for (var i = 0; i < imageCount; i++)
template += '<image id="' + (i + 1) + '" src="%s" alt="%s"/>';
for (var i = 0; i < textCount; i++)
template += '<text id="' + (i + 1) + '">%s</text>';
template += '</binding>';
return template;
} | [
"function",
"(",
"name",
",",
"imageCount",
",",
"textCount",
")",
"{",
"var",
"template",
"=",
"'<binding template=\"'",
"+",
"name",
"+",
"'\"%s>'",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"imageCount",
";",
"i",
"++",
")",
"template",
"+=",
"'<image id=\"'",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'\" src=\"%s\" alt=\"%s\"/>'",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"textCount",
";",
"i",
"++",
")",
"template",
"+=",
"'<text id=\"'",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"'\">%s</text>'",
";",
"template",
"+=",
"'</binding>'",
";",
"return",
"template",
";",
"}"
]
| creates a toast or tile binding template given the name and a specific number of text and image elements | [
"creates",
"a",
"toast",
"or",
"tile",
"binding",
"template",
"given",
"the",
"name",
"and",
"a",
"specific",
"number",
"of",
"text",
"and",
"image",
"elements"
]
| bc5228c5337941b9309d041231dbac9e85673491 | https://github.com/tjanczuk/wns/blob/bc5228c5337941b9309d041231dbac9e85673491/lib/wns.js#L116-L127 | train |
|
yoshuawuyts/markdown-to-medium | bin/cli.js | usage | function usage (exitCode) {
const rs = fs.createReadStream(path.join(__dirname, '/usage.txt'))
const ws = process.stdout
rs.pipe(ws)
ws.on('finish', process.exit.bind(null, exitCode))
} | javascript | function usage (exitCode) {
const rs = fs.createReadStream(path.join(__dirname, '/usage.txt'))
const ws = process.stdout
rs.pipe(ws)
ws.on('finish', process.exit.bind(null, exitCode))
} | [
"function",
"usage",
"(",
"exitCode",
")",
"{",
"const",
"rs",
"=",
"fs",
".",
"createReadStream",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'/usage.txt'",
")",
")",
"const",
"ws",
"=",
"process",
".",
"stdout",
"rs",
".",
"pipe",
"(",
"ws",
")",
"ws",
".",
"on",
"(",
"'finish'",
",",
"process",
".",
"exit",
".",
"bind",
"(",
"null",
",",
"exitCode",
")",
")",
"}"
]
| print usage & exit num? -> null | [
"print",
"usage",
"&",
"exit",
"num?",
"-",
">",
"null"
]
| f03123b8e6a40ee164a6c10748c1155d3adc1848 | https://github.com/yoshuawuyts/markdown-to-medium/blob/f03123b8e6a40ee164a6c10748c1155d3adc1848/bin/cli.js#L59-L64 | train |
talyssonoc/jsT9 | dist/jst9.js | predict | function predict(word, amount) {
if (!word) {
return [];
}
amount = amount || this.config.maxAmount;
var currentWord = false;
var initialBranchResult = this._findInitialBranch(word);
if(!initialBranchResult) {
return [];
}
if (initialBranchResult.currentBranch.$ === true) {
currentWord = initialBranchResult.baseWord;
}
var predictedList = this._exploreBranch(initialBranchResult.baseWord, initialBranchResult.currentBranch);
if (currentWord) {
predictedList.push(currentWord);
}
predictedList.sort(this.config.sort);
return predictedList.slice(0, amount);
} | javascript | function predict(word, amount) {
if (!word) {
return [];
}
amount = amount || this.config.maxAmount;
var currentWord = false;
var initialBranchResult = this._findInitialBranch(word);
if(!initialBranchResult) {
return [];
}
if (initialBranchResult.currentBranch.$ === true) {
currentWord = initialBranchResult.baseWord;
}
var predictedList = this._exploreBranch(initialBranchResult.baseWord, initialBranchResult.currentBranch);
if (currentWord) {
predictedList.push(currentWord);
}
predictedList.sort(this.config.sort);
return predictedList.slice(0, amount);
} | [
"function",
"predict",
"(",
"word",
",",
"amount",
")",
"{",
"if",
"(",
"!",
"word",
")",
"{",
"return",
"[",
"]",
";",
"}",
"amount",
"=",
"amount",
"||",
"this",
".",
"config",
".",
"maxAmount",
";",
"var",
"currentWord",
"=",
"false",
";",
"var",
"initialBranchResult",
"=",
"this",
".",
"_findInitialBranch",
"(",
"word",
")",
";",
"if",
"(",
"!",
"initialBranchResult",
")",
"{",
"return",
"[",
"]",
";",
"}",
"if",
"(",
"initialBranchResult",
".",
"currentBranch",
".",
"$",
"===",
"true",
")",
"{",
"currentWord",
"=",
"initialBranchResult",
".",
"baseWord",
";",
"}",
"var",
"predictedList",
"=",
"this",
".",
"_exploreBranch",
"(",
"initialBranchResult",
".",
"baseWord",
",",
"initialBranchResult",
".",
"currentBranch",
")",
";",
"if",
"(",
"currentWord",
")",
"{",
"predictedList",
".",
"push",
"(",
"currentWord",
")",
";",
"}",
"predictedList",
".",
"sort",
"(",
"this",
".",
"config",
".",
"sort",
")",
";",
"return",
"predictedList",
".",
"slice",
"(",
"0",
",",
"amount",
")",
";",
"}"
]
| Predict the words, given the initial word
@param {String} word The initial word
@return {Array} The array of Strings with the predicted words | [
"Predict",
"the",
"words",
"given",
"the",
"initial",
"word"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L92-L121 | train |
talyssonoc/jsT9 | dist/jst9.js | addWord | function addWord(word) {
var branch = this.root;
var stopSearchOnCurrentBranch = false;
var newNode;
while (!stopSearchOnCurrentBranch) {
var wordContainsThePrefix = false;
var isCase3 = false;
var case2Result;
//Looks for how branch it should follow
for (var b in branch.branches) {
//Case 1: current node prefix == `word`
if(this._tryCase1(branch, word, b)) {
return;
}
//Case 2: `word` begins with current node prefix to add
//Cuts the word and goes to the next branch
case2Result = this._tryCase2(branch, word, b);
if(case2Result) {
word = case2Result.word;
branch = case2Result.branch;
wordContainsThePrefix = true;
break;
}
//Case 3: current node prefix begins with part of or whole `word`
if(this._tryCase3(branch, word, b)) {
isCase3 = stopSearchOnCurrentBranch = wordContainsThePrefix = true;
break;
}
}
//Case 4: current node prefix doesn't have intersection with `word`
if(this._tryCase4(branch, word, wordContainsThePrefix)) {
stopSearchOnCurrentBranch = true;
}
}
} | javascript | function addWord(word) {
var branch = this.root;
var stopSearchOnCurrentBranch = false;
var newNode;
while (!stopSearchOnCurrentBranch) {
var wordContainsThePrefix = false;
var isCase3 = false;
var case2Result;
//Looks for how branch it should follow
for (var b in branch.branches) {
//Case 1: current node prefix == `word`
if(this._tryCase1(branch, word, b)) {
return;
}
//Case 2: `word` begins with current node prefix to add
//Cuts the word and goes to the next branch
case2Result = this._tryCase2(branch, word, b);
if(case2Result) {
word = case2Result.word;
branch = case2Result.branch;
wordContainsThePrefix = true;
break;
}
//Case 3: current node prefix begins with part of or whole `word`
if(this._tryCase3(branch, word, b)) {
isCase3 = stopSearchOnCurrentBranch = wordContainsThePrefix = true;
break;
}
}
//Case 4: current node prefix doesn't have intersection with `word`
if(this._tryCase4(branch, word, wordContainsThePrefix)) {
stopSearchOnCurrentBranch = true;
}
}
} | [
"function",
"addWord",
"(",
"word",
")",
"{",
"var",
"branch",
"=",
"this",
".",
"root",
";",
"var",
"stopSearchOnCurrentBranch",
"=",
"false",
";",
"var",
"newNode",
";",
"while",
"(",
"!",
"stopSearchOnCurrentBranch",
")",
"{",
"var",
"wordContainsThePrefix",
"=",
"false",
";",
"var",
"isCase3",
"=",
"false",
";",
"var",
"case2Result",
";",
"for",
"(",
"var",
"b",
"in",
"branch",
".",
"branches",
")",
"{",
"if",
"(",
"this",
".",
"_tryCase1",
"(",
"branch",
",",
"word",
",",
"b",
")",
")",
"{",
"return",
";",
"}",
"case2Result",
"=",
"this",
".",
"_tryCase2",
"(",
"branch",
",",
"word",
",",
"b",
")",
";",
"if",
"(",
"case2Result",
")",
"{",
"word",
"=",
"case2Result",
".",
"word",
";",
"branch",
"=",
"case2Result",
".",
"branch",
";",
"wordContainsThePrefix",
"=",
"true",
";",
"break",
";",
"}",
"if",
"(",
"this",
".",
"_tryCase3",
"(",
"branch",
",",
"word",
",",
"b",
")",
")",
"{",
"isCase3",
"=",
"stopSearchOnCurrentBranch",
"=",
"wordContainsThePrefix",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"this",
".",
"_tryCase4",
"(",
"branch",
",",
"word",
",",
"wordContainsThePrefix",
")",
")",
"{",
"stopSearchOnCurrentBranch",
"=",
"true",
";",
"}",
"}",
"}"
]
| Add a new word to the tree
@param {String} word Word to be added to the tree | [
"Add",
"a",
"new",
"word",
"to",
"the",
"tree"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L227-L268 | train |
talyssonoc/jsT9 | dist/jst9.js | _exploreBranch | function _exploreBranch(baseWord, currentBranch) {
var predictedList = [];
for (var b in currentBranch.branches) { //For each branch forking from the branch
var prefix = currentBranch.branches[b].prefix; //Get the leading character of the current branch
if (currentBranch.branches[b].$ === true) { //If the current leaf ends a word, puts the word on the list
predictedList.push(baseWord + prefix);
}
//Recursively calls the function, passing the forking branches as parameter
var predictedWords = this._exploreBranch(baseWord + prefix, currentBranch.branches[b]);
predictedList = predictedList.concat(predictedWords);
}
return predictedList;
} | javascript | function _exploreBranch(baseWord, currentBranch) {
var predictedList = [];
for (var b in currentBranch.branches) { //For each branch forking from the branch
var prefix = currentBranch.branches[b].prefix; //Get the leading character of the current branch
if (currentBranch.branches[b].$ === true) { //If the current leaf ends a word, puts the word on the list
predictedList.push(baseWord + prefix);
}
//Recursively calls the function, passing the forking branches as parameter
var predictedWords = this._exploreBranch(baseWord + prefix, currentBranch.branches[b]);
predictedList = predictedList.concat(predictedWords);
}
return predictedList;
} | [
"function",
"_exploreBranch",
"(",
"baseWord",
",",
"currentBranch",
")",
"{",
"var",
"predictedList",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"b",
"in",
"currentBranch",
".",
"branches",
")",
"{",
"var",
"prefix",
"=",
"currentBranch",
".",
"branches",
"[",
"b",
"]",
".",
"prefix",
";",
"if",
"(",
"currentBranch",
".",
"branches",
"[",
"b",
"]",
".",
"$",
"===",
"true",
")",
"{",
"predictedList",
".",
"push",
"(",
"baseWord",
"+",
"prefix",
")",
";",
"}",
"var",
"predictedWords",
"=",
"this",
".",
"_exploreBranch",
"(",
"baseWord",
"+",
"prefix",
",",
"currentBranch",
".",
"branches",
"[",
"b",
"]",
")",
";",
"predictedList",
"=",
"predictedList",
".",
"concat",
"(",
"predictedWords",
")",
";",
"}",
"return",
"predictedList",
";",
"}"
]
| Looks for the words that contain the word passed as parameter
@param {String} baseWord The base to look for
@param {Object} currentBranch The begining branch
@return {Array} List of predicted words | [
"Looks",
"for",
"the",
"words",
"that",
"contain",
"the",
"word",
"passed",
"as",
"parameter"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L362-L379 | train |
talyssonoc/jsT9 | dist/jst9.js | _getWordList | function _getWordList(_wordList, callback) {
if(Array.isArray(_wordList)) {
callback(_wordList);
} else if ((typeof _wordList) === 'string') {
this._fetchWordList(_wordList, callback);
} else {
console.error((typeof _wordList) + ' variable is not supported as data source');
callback([]);
}
} | javascript | function _getWordList(_wordList, callback) {
if(Array.isArray(_wordList)) {
callback(_wordList);
} else if ((typeof _wordList) === 'string') {
this._fetchWordList(_wordList, callback);
} else {
console.error((typeof _wordList) + ' variable is not supported as data source');
callback([]);
}
} | [
"function",
"_getWordList",
"(",
"_wordList",
",",
"callback",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"_wordList",
")",
")",
"{",
"callback",
"(",
"_wordList",
")",
";",
"}",
"else",
"if",
"(",
"(",
"typeof",
"_wordList",
")",
"===",
"'string'",
")",
"{",
"this",
".",
"_fetchWordList",
"(",
"_wordList",
",",
"callback",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"(",
"typeof",
"_wordList",
")",
"+",
"' variable is not supported as data source'",
")",
";",
"callback",
"(",
"[",
"]",
")",
";",
"}",
"}"
]
| Returns the word list base on config
@param {Array|String}
@param {Function}
@return {Array} | [
"Returns",
"the",
"word",
"list",
"base",
"on",
"config"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L387-L402 | train |
talyssonoc/jsT9 | dist/jst9.js | _fetchWordList | function _fetchWordList(path, callback) {
var words = [];
axios.get(path)
.then(function(response) {
var jsonData = response.data;
if(response.responseType === 'text') {
jsonData = JSON.parse(jsonData);
}
if(Array.isArray(jsonData.words)) {
words = jsonData.words;
}
callback(words);
}.bind(this))
.catch(function(error) {
callback(words);
}.bind(this));
} | javascript | function _fetchWordList(path, callback) {
var words = [];
axios.get(path)
.then(function(response) {
var jsonData = response.data;
if(response.responseType === 'text') {
jsonData = JSON.parse(jsonData);
}
if(Array.isArray(jsonData.words)) {
words = jsonData.words;
}
callback(words);
}.bind(this))
.catch(function(error) {
callback(words);
}.bind(this));
} | [
"function",
"_fetchWordList",
"(",
"path",
",",
"callback",
")",
"{",
"var",
"words",
"=",
"[",
"]",
";",
"axios",
".",
"get",
"(",
"path",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"var",
"jsonData",
"=",
"response",
".",
"data",
";",
"if",
"(",
"response",
".",
"responseType",
"===",
"'text'",
")",
"{",
"jsonData",
"=",
"JSON",
".",
"parse",
"(",
"jsonData",
")",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"jsonData",
".",
"words",
")",
")",
"{",
"words",
"=",
"jsonData",
".",
"words",
";",
"}",
"callback",
"(",
"words",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
".",
"catch",
"(",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"words",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Fetches the word list from an address
@param {String} path Path of a JSON file with an array called 'words' with the word list
@return {Array} Word list extracted from the given path | [
"Fetches",
"the",
"word",
"list",
"from",
"an",
"address"
]
| 9e19d5941c3f937569285595ae5be449e15a3afa | https://github.com/talyssonoc/jsT9/blob/9e19d5941c3f937569285595ae5be449e15a3afa/dist/jst9.js#L409-L430 | train |
yoshuawuyts/markdown-to-medium | index.js | main | function main (options, done) {
const token = options.token
const filename = options.filename
assert.equal(typeof token, 'string', 'markdown-to-medium: token should be a string')
const client = new medium.MediumClient({
clientId: token,
clientSecret: token
})
client.setAccessToken(token)
var src
try {
src = fs.readFileSync(filename, 'utf8')
} catch (e) {
throw new Error('Could not read file ' + filename)
}
const matter = frontMatter(src)
let title = options.title || matter.attributes.title
const tags = (options.tags && options.tags.split(',')) || matter.attributes.tags
const publication = options.publication || matter.attributes.publication
const canonicalUrl = options.canonicalUrl || matter.attributes.canonicalUrl || ''
const license = checkLicense(options.license || matter.attributes.license)
var content = `
# ${title}
${matter.body}
`
if (!title && getTitle(src)) {
title = getTitle(src).text
content = matter.body
}
if (canonicalUrl.length) {
content += `
*Cross-posted from [${canonicalUrl}](${canonicalUrl}).*
`
}
client.getUser((err, user) => {
if (err) {
throw new Error(err)
}
console.log(`Authenticated as ${user.username}`.blue)
const options = {
userId: user.id,
title,
tags,
content,
canonicalUrl,
license,
contentFormat: 'markdown',
publishStatus: 'draft'
}
const successMsg = `Draft post "${title}" published to Medium.com`.green
if (publication) {
client.getPublicationsForUser({userId: user.id}, (err, publications) => {
if (err) {
throw new Error(err)
}
const myPub = publications.filter((val) => { return val.name === publication })
if (myPub.length === 0) {
throw new Error('No publication by that name!')
}
client.createPostInPublication(Object.assign(options, {publicationId: myPub[0].id}), (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
})
} else {
client.createPost(options, (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
}
})
} | javascript | function main (options, done) {
const token = options.token
const filename = options.filename
assert.equal(typeof token, 'string', 'markdown-to-medium: token should be a string')
const client = new medium.MediumClient({
clientId: token,
clientSecret: token
})
client.setAccessToken(token)
var src
try {
src = fs.readFileSync(filename, 'utf8')
} catch (e) {
throw new Error('Could not read file ' + filename)
}
const matter = frontMatter(src)
let title = options.title || matter.attributes.title
const tags = (options.tags && options.tags.split(',')) || matter.attributes.tags
const publication = options.publication || matter.attributes.publication
const canonicalUrl = options.canonicalUrl || matter.attributes.canonicalUrl || ''
const license = checkLicense(options.license || matter.attributes.license)
var content = `
# ${title}
${matter.body}
`
if (!title && getTitle(src)) {
title = getTitle(src).text
content = matter.body
}
if (canonicalUrl.length) {
content += `
*Cross-posted from [${canonicalUrl}](${canonicalUrl}).*
`
}
client.getUser((err, user) => {
if (err) {
throw new Error(err)
}
console.log(`Authenticated as ${user.username}`.blue)
const options = {
userId: user.id,
title,
tags,
content,
canonicalUrl,
license,
contentFormat: 'markdown',
publishStatus: 'draft'
}
const successMsg = `Draft post "${title}" published to Medium.com`.green
if (publication) {
client.getPublicationsForUser({userId: user.id}, (err, publications) => {
if (err) {
throw new Error(err)
}
const myPub = publications.filter((val) => { return val.name === publication })
if (myPub.length === 0) {
throw new Error('No publication by that name!')
}
client.createPostInPublication(Object.assign(options, {publicationId: myPub[0].id}), (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
})
} else {
client.createPost(options, (err, post) => {
if (err) {
throw new Error(err)
}
console.log(successMsg)
open(post.url)
})
}
})
} | [
"function",
"main",
"(",
"options",
",",
"done",
")",
"{",
"const",
"token",
"=",
"options",
".",
"token",
"const",
"filename",
"=",
"options",
".",
"filename",
"assert",
".",
"equal",
"(",
"typeof",
"token",
",",
"'string'",
",",
"'markdown-to-medium: token should be a string'",
")",
"const",
"client",
"=",
"new",
"medium",
".",
"MediumClient",
"(",
"{",
"clientId",
":",
"token",
",",
"clientSecret",
":",
"token",
"}",
")",
"client",
".",
"setAccessToken",
"(",
"token",
")",
"var",
"src",
"try",
"{",
"src",
"=",
"fs",
".",
"readFileSync",
"(",
"filename",
",",
"'utf8'",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Could not read file '",
"+",
"filename",
")",
"}",
"const",
"matter",
"=",
"frontMatter",
"(",
"src",
")",
"let",
"title",
"=",
"options",
".",
"title",
"||",
"matter",
".",
"attributes",
".",
"title",
"const",
"tags",
"=",
"(",
"options",
".",
"tags",
"&&",
"options",
".",
"tags",
".",
"split",
"(",
"','",
")",
")",
"||",
"matter",
".",
"attributes",
".",
"tags",
"const",
"publication",
"=",
"options",
".",
"publication",
"||",
"matter",
".",
"attributes",
".",
"publication",
"const",
"canonicalUrl",
"=",
"options",
".",
"canonicalUrl",
"||",
"matter",
".",
"attributes",
".",
"canonicalUrl",
"||",
"''",
"const",
"license",
"=",
"checkLicense",
"(",
"options",
".",
"license",
"||",
"matter",
".",
"attributes",
".",
"license",
")",
"var",
"content",
"=",
"`",
"${",
"title",
"}",
"${",
"matter",
".",
"body",
"}",
"`",
"if",
"(",
"!",
"title",
"&&",
"getTitle",
"(",
"src",
")",
")",
"{",
"title",
"=",
"getTitle",
"(",
"src",
")",
".",
"text",
"content",
"=",
"matter",
".",
"body",
"}",
"if",
"(",
"canonicalUrl",
".",
"length",
")",
"{",
"content",
"+=",
"`",
"${",
"canonicalUrl",
"}",
"${",
"canonicalUrl",
"}",
"`",
"}",
"client",
".",
"getUser",
"(",
"(",
"err",
",",
"user",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"`",
"${",
"user",
".",
"username",
"}",
"`",
".",
"blue",
")",
"const",
"options",
"=",
"{",
"userId",
":",
"user",
".",
"id",
",",
"title",
",",
"tags",
",",
"content",
",",
"canonicalUrl",
",",
"license",
",",
"contentFormat",
":",
"'markdown'",
",",
"publishStatus",
":",
"'draft'",
"}",
"const",
"successMsg",
"=",
"`",
"${",
"title",
"}",
"`",
".",
"green",
"if",
"(",
"publication",
")",
"{",
"client",
".",
"getPublicationsForUser",
"(",
"{",
"userId",
":",
"user",
".",
"id",
"}",
",",
"(",
"err",
",",
"publications",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"const",
"myPub",
"=",
"publications",
".",
"filter",
"(",
"(",
"val",
")",
"=>",
"{",
"return",
"val",
".",
"name",
"===",
"publication",
"}",
")",
"if",
"(",
"myPub",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No publication by that name!'",
")",
"}",
"client",
".",
"createPostInPublication",
"(",
"Object",
".",
"assign",
"(",
"options",
",",
"{",
"publicationId",
":",
"myPub",
"[",
"0",
"]",
".",
"id",
"}",
")",
",",
"(",
"err",
",",
"post",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"successMsg",
")",
"open",
"(",
"post",
".",
"url",
")",
"}",
")",
"}",
")",
"}",
"else",
"{",
"client",
".",
"createPost",
"(",
"options",
",",
"(",
"err",
",",
"post",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"err",
")",
"}",
"console",
".",
"log",
"(",
"successMsg",
")",
"open",
"(",
"post",
".",
"url",
")",
"}",
")",
"}",
"}",
")",
"}"
]
| publish a markdown file to medium | [
"publish",
"a",
"markdown",
"file",
"to",
"medium"
]
| f03123b8e6a40ee164a6c10748c1155d3adc1848 | https://github.com/yoshuawuyts/markdown-to-medium/blob/f03123b8e6a40ee164a6c10748c1155d3adc1848/index.js#L40-L133 | train |
meeDamian/country-emoji | src/lib.js | flag | function flag(input) {
if (!CODE_RE.test(input) || input === 'UK') {
input = nameToCode(input);
}
return codeToFlag(input);
} | javascript | function flag(input) {
if (!CODE_RE.test(input) || input === 'UK') {
input = nameToCode(input);
}
return codeToFlag(input);
} | [
"function",
"flag",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"CODE_RE",
".",
"test",
"(",
"input",
")",
"||",
"input",
"===",
"'UK'",
")",
"{",
"input",
"=",
"nameToCode",
"(",
"input",
")",
";",
"}",
"return",
"codeToFlag",
"(",
"input",
")",
";",
"}"
]
| Takes either code or full name | [
"Takes",
"either",
"code",
"or",
"full",
"name"
]
| 6e2c490c2c038882280ee17866ec689c05af3544 | https://github.com/meeDamian/country-emoji/blob/6e2c490c2c038882280ee17866ec689c05af3544/src/lib.js#L133-L139 | train |
meeDamian/country-emoji | src/lib.js | name | function name(input) {
if (FLAG_RE.test(input)) {
input = flagToCode(input);
}
return codeToName(input);
} | javascript | function name(input) {
if (FLAG_RE.test(input)) {
input = flagToCode(input);
}
return codeToName(input);
} | [
"function",
"name",
"(",
"input",
")",
"{",
"if",
"(",
"FLAG_RE",
".",
"test",
"(",
"input",
")",
")",
"{",
"input",
"=",
"flagToCode",
"(",
"input",
")",
";",
"}",
"return",
"codeToName",
"(",
"input",
")",
";",
"}"
]
| Takes either emoji or code | [
"Takes",
"either",
"emoji",
"or",
"code"
]
| 6e2c490c2c038882280ee17866ec689c05af3544 | https://github.com/meeDamian/country-emoji/blob/6e2c490c2c038882280ee17866ec689c05af3544/src/lib.js#L142-L148 | train |
mweststrate/nscript | lib/index.js | runScriptFile | function runScriptFile(scriptFile) {
//node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away!
scriptArgs = scriptArgs.slice(scriptArgs.indexOf(scriptFile) + 1);
if (shell.verbose())
console.warn("Starting nscript " + scriptFile + scriptArgs.join(" "));
runNscriptFunction(require(path.resolve(process.cwd(), scriptFile))); //nscript scripts should always export a single function that is the main
} | javascript | function runScriptFile(scriptFile) {
//node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away!
scriptArgs = scriptArgs.slice(scriptArgs.indexOf(scriptFile) + 1);
if (shell.verbose())
console.warn("Starting nscript " + scriptFile + scriptArgs.join(" "));
runNscriptFunction(require(path.resolve(process.cwd(), scriptFile))); //nscript scripts should always export a single function that is the main
} | [
"function",
"runScriptFile",
"(",
"scriptFile",
")",
"{",
"scriptArgs",
"=",
"scriptArgs",
".",
"slice",
"(",
"scriptArgs",
".",
"indexOf",
"(",
"scriptFile",
")",
"+",
"1",
")",
";",
"if",
"(",
"shell",
".",
"verbose",
"(",
")",
")",
"console",
".",
"warn",
"(",
"\"Starting nscript \"",
"+",
"scriptFile",
"+",
"scriptArgs",
".",
"join",
"(",
"\" \"",
")",
")",
";",
"runNscriptFunction",
"(",
"require",
"(",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"scriptFile",
")",
")",
")",
";",
"}"
]
| Runs a file that contains a nscript script
@param {string} scriptFile | [
"Runs",
"a",
"file",
"that",
"contains",
"a",
"nscript",
"script"
]
| 0a02d17bb3ab00d2d5830151ab20771f0366baba | https://github.com/mweststrate/nscript/blob/0a02d17bb3ab00d2d5830151ab20771f0366baba/lib/index.js#L147-L154 | train |
julienetie/mimetic | src/initialize-mimetic-partial.js | initializeMimeticPartial | function initializeMimeticPartial(
document,
getRootREMValue,
// CSSUnitsToPixels,
setRootFontSize,
resizilla,
) {
// A resize object to store MIMETIC's resizilla's requirements.
const resize = {};
/**
* The intializeMimetic function.
* @param {object} config - The API parameters.
*/
function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
}
/**
* Remove both event listeners set via resizilla.
*/
initalizeMimeticFinal.prototype.kill = () => resize.resizilla.destroy();
/**
* Re-instate resizilla.
*/
initalizeMimeticFinal.prototype.revive = function revive() {
resize.resizilla = resizilla(() => {
setRootFontSize(resize.settings, resize.setRootFontSizeScope);
}, resize.scaleDelay, false);
};
return initalizeMimeticFinal;
} | javascript | function initializeMimeticPartial(
document,
getRootREMValue,
// CSSUnitsToPixels,
setRootFontSize,
resizilla,
) {
// A resize object to store MIMETIC's resizilla's requirements.
const resize = {};
/**
* The intializeMimetic function.
* @param {object} config - The API parameters.
*/
function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
}
/**
* Remove both event listeners set via resizilla.
*/
initalizeMimeticFinal.prototype.kill = () => resize.resizilla.destroy();
/**
* Re-instate resizilla.
*/
initalizeMimeticFinal.prototype.revive = function revive() {
resize.resizilla = resizilla(() => {
setRootFontSize(resize.settings, resize.setRootFontSizeScope);
}, resize.scaleDelay, false);
};
return initalizeMimeticFinal;
} | [
"function",
"initializeMimeticPartial",
"(",
"document",
",",
"getRootREMValue",
",",
"setRootFontSize",
",",
"resizilla",
",",
")",
"{",
"const",
"resize",
"=",
"{",
"}",
";",
"function",
"initalizeMimeticFinal",
"(",
"config",
")",
"{",
"const",
"{",
"scaleDelay",
",",
"}",
"=",
"config",
";",
"resize",
".",
"scaleDelay",
"=",
"scaleDelay",
";",
"const",
"rootFontSize",
"=",
"getRootREMValue",
"(",
"document",
")",
";",
"const",
"settings",
"=",
"Object",
".",
"assign",
"(",
"{",
"initialOuterHeight",
":",
"window",
".",
"outerHeight",
",",
"initialOuterWidth",
":",
"window",
".",
"outerWidth",
",",
"rootFontSize",
",",
"}",
",",
"config",
")",
";",
"resize",
".",
"settings",
"=",
"settings",
";",
"const",
"setRootFontSizeScope",
"=",
"(",
")",
"=>",
"setRootFontSize",
"(",
"settings",
")",
";",
"resize",
".",
"setRootFontSizeScope",
"=",
"setRootFontSizeScope",
";",
"setRootFontSizeScope",
"(",
")",
";",
"resize",
".",
"resizilla",
"=",
"resizilla",
"(",
"(",
")",
"=>",
"{",
"setRootFontSize",
"(",
"settings",
",",
"setRootFontSizeScope",
")",
";",
"}",
",",
"scaleDelay",
",",
"false",
")",
";",
"}",
"initalizeMimeticFinal",
".",
"prototype",
".",
"kill",
"=",
"(",
")",
"=>",
"resize",
".",
"resizilla",
".",
"destroy",
"(",
")",
";",
"initalizeMimeticFinal",
".",
"prototype",
".",
"revive",
"=",
"function",
"revive",
"(",
")",
"{",
"resize",
".",
"resizilla",
"=",
"resizilla",
"(",
"(",
")",
"=>",
"{",
"setRootFontSize",
"(",
"resize",
".",
"settings",
",",
"resize",
".",
"setRootFontSizeScope",
")",
";",
"}",
",",
"resize",
".",
"scaleDelay",
",",
"false",
")",
";",
"}",
";",
"return",
"initalizeMimeticFinal",
";",
"}"
]
| Sets up intializeMimetic via partial application.
@param {Function} document.
@param {Function} getRootREMValue - Gets the root font-size in REM units.
@param {Function} CSSUnitsToPixels - Converts any CSS units to pixels.
@param {Function} setRootFontSize - Sets the new root font size.
@param {Function} resizilla - Calls handler on window resize and orientationchange events. | [
"Sets",
"up",
"intializeMimetic",
"via",
"partial",
"application",
"."
]
| fc4c794e8b5063aa0d9f5145c59a797adca0d984 | https://github.com/julienetie/mimetic/blob/fc4c794e8b5063aa0d9f5145c59a797adca0d984/src/initialize-mimetic-partial.js#L9-L90 | train |
julienetie/mimetic | src/initialize-mimetic-partial.js | initalizeMimeticFinal | function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
} | javascript | function initalizeMimeticFinal(config) {
// Destructured API parameters.
const {
scaleDelay,
} = config;
// Store the scaleDelay for kill and revive.
resize.scaleDelay = scaleDelay;
// The intial root font size.
const rootFontSize = getRootREMValue(document);
// // mobileWidth in pixels.
// const mobileWidthPX = CSSUnitsToPixels(mobileWidth);
// Cut off width in pixels.
// const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth);
// Provide parameters to setRootFontSize. @TODO remove config, only use what is needed.
const settings = Object.assign({
initialOuterHeight: window.outerHeight,
initialOuterWidth: window.outerWidth,
rootFontSize,
// mobileWidthPX,
// cutOffWidthPX,
}, config);
// Store the settings for kill and revive.
resize.settings = settings;
// Immediately set the root font size according to MIMETIC.
const setRootFontSizeScope = () => setRootFontSize(settings);
resize.setRootFontSizeScope = setRootFontSizeScope;
setRootFontSizeScope();
// On window resize set the root font size according to MIMETIC.
resize.resizilla = resizilla(() => {
setRootFontSize(settings, setRootFontSizeScope);
}, scaleDelay, false);
} | [
"function",
"initalizeMimeticFinal",
"(",
"config",
")",
"{",
"const",
"{",
"scaleDelay",
",",
"}",
"=",
"config",
";",
"resize",
".",
"scaleDelay",
"=",
"scaleDelay",
";",
"const",
"rootFontSize",
"=",
"getRootREMValue",
"(",
"document",
")",
";",
"const",
"settings",
"=",
"Object",
".",
"assign",
"(",
"{",
"initialOuterHeight",
":",
"window",
".",
"outerHeight",
",",
"initialOuterWidth",
":",
"window",
".",
"outerWidth",
",",
"rootFontSize",
",",
"}",
",",
"config",
")",
";",
"resize",
".",
"settings",
"=",
"settings",
";",
"const",
"setRootFontSizeScope",
"=",
"(",
")",
"=>",
"setRootFontSize",
"(",
"settings",
")",
";",
"resize",
".",
"setRootFontSizeScope",
"=",
"setRootFontSizeScope",
";",
"setRootFontSizeScope",
"(",
")",
";",
"resize",
".",
"resizilla",
"=",
"resizilla",
"(",
"(",
")",
"=>",
"{",
"setRootFontSize",
"(",
"settings",
",",
"setRootFontSizeScope",
")",
";",
"}",
",",
"scaleDelay",
",",
"false",
")",
";",
"}"
]
| The intializeMimetic function.
@param {object} config - The API parameters. | [
"The",
"intializeMimetic",
"function",
"."
]
| fc4c794e8b5063aa0d9f5145c59a797adca0d984 | https://github.com/julienetie/mimetic/blob/fc4c794e8b5063aa0d9f5145c59a797adca0d984/src/initialize-mimetic-partial.js#L24-L71 | train |
capaj/socket.io-rpc | main.js | RPCserver | function RPCserver () {
var server
if (typeof arguments[0] === 'number') {
server = require('http').createServer()
server.listen.apply(server, arguments)
} else {
server = arguments[0]
}
var io = socketIO(server, arguments[1])
var rpcServer = {
io: io.of('/rpc'),
/**
* @param toExtendWith {Object}
*/
expose: function (toExtendWith) {
if (typeof toExtendWith !== 'object') {
throw new TypeError('object expected as first argument')
}
Object.extend(tree, toExtendWith)
},
server: server
}
var tree = {}
rpcServer.io.on('connect', function (socket) {
socketEventHandlers(socket, tree, 'server')
})
return rpcServer
} | javascript | function RPCserver () {
var server
if (typeof arguments[0] === 'number') {
server = require('http').createServer()
server.listen.apply(server, arguments)
} else {
server = arguments[0]
}
var io = socketIO(server, arguments[1])
var rpcServer = {
io: io.of('/rpc'),
/**
* @param toExtendWith {Object}
*/
expose: function (toExtendWith) {
if (typeof toExtendWith !== 'object') {
throw new TypeError('object expected as first argument')
}
Object.extend(tree, toExtendWith)
},
server: server
}
var tree = {}
rpcServer.io.on('connect', function (socket) {
socketEventHandlers(socket, tree, 'server')
})
return rpcServer
} | [
"function",
"RPCserver",
"(",
")",
"{",
"var",
"server",
"if",
"(",
"typeof",
"arguments",
"[",
"0",
"]",
"===",
"'number'",
")",
"{",
"server",
"=",
"require",
"(",
"'http'",
")",
".",
"createServer",
"(",
")",
"server",
".",
"listen",
".",
"apply",
"(",
"server",
",",
"arguments",
")",
"}",
"else",
"{",
"server",
"=",
"arguments",
"[",
"0",
"]",
"}",
"var",
"io",
"=",
"socketIO",
"(",
"server",
",",
"arguments",
"[",
"1",
"]",
")",
"var",
"rpcServer",
"=",
"{",
"io",
":",
"io",
".",
"of",
"(",
"'/rpc'",
")",
",",
"expose",
":",
"function",
"(",
"toExtendWith",
")",
"{",
"if",
"(",
"typeof",
"toExtendWith",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'object expected as first argument'",
")",
"}",
"Object",
".",
"extend",
"(",
"tree",
",",
"toExtendWith",
")",
"}",
",",
"server",
":",
"server",
"}",
"var",
"tree",
"=",
"{",
"}",
"rpcServer",
".",
"io",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
"socket",
")",
"{",
"socketEventHandlers",
"(",
"socket",
",",
"tree",
",",
"'server'",
")",
"}",
")",
"return",
"rpcServer",
"}"
]
| Shares the same signature as express.js listen method, because it passes arguments to it when first argument is number
@param {Number|Object} port or http server
@param {String} [hostname]
@param {Function} [Callback]
@returns {{expose: Function, loadClientChannel: Function, channel: Object}} rpc backend instance | [
"Shares",
"the",
"same",
"signature",
"as",
"express",
".",
"js",
"listen",
"method",
"because",
"it",
"passes",
"arguments",
"to",
"it",
"when",
"first",
"argument",
"is",
"number"
]
| 1474b50beb2b8d8ed5b5c09f87b971bf0e00f874 | https://github.com/capaj/socket.io-rpc/blob/1474b50beb2b8d8ed5b5c09f87b971bf0e00f874/main.js#L12-L42 | train |
basarevych/dynamic-table | node/adapter/array.js | checkFilter | function checkFilter(filter, type, test, real) {
if (type == Table.TYPE_DATETIME) {
if (typeof real != 'object')
real = new Date(real * 1000);
if (filter == Table.FILTER_BETWEEN
&& Array.isArray(test) && test.length == 2) {
test = [
test[0] ? moment.unix(test[0]) : null,
test[1] ? moment.unix(test[1]) : null,
];
} else if (filter != Table.FILTER_BETWEEN) {
test = moment.unix(test);
} else {
return null;
}
} else {
if (filter == Table.FILTER_BETWEEN) {
if (!Array.isArray(test) || test.length != 2)
return null;
}
}
switch (filter) {
case Table.FILTER_LIKE:
return real !== null && real.indexOf(test) != -1;
case Table.FILTER_EQUAL:
return real !== null && test == real;
case Table.FILTER_BETWEEN:
if (real === null)
return false;
if (test[0] !== null && real < test[0])
return false;
if (test[1] !== null && real > test[1])
return false;
return true;
case Table.FILTER_NULL:
return real === null;
default:
throw new Error("Unknown filter: " + filter);
}
return false;
} | javascript | function checkFilter(filter, type, test, real) {
if (type == Table.TYPE_DATETIME) {
if (typeof real != 'object')
real = new Date(real * 1000);
if (filter == Table.FILTER_BETWEEN
&& Array.isArray(test) && test.length == 2) {
test = [
test[0] ? moment.unix(test[0]) : null,
test[1] ? moment.unix(test[1]) : null,
];
} else if (filter != Table.FILTER_BETWEEN) {
test = moment.unix(test);
} else {
return null;
}
} else {
if (filter == Table.FILTER_BETWEEN) {
if (!Array.isArray(test) || test.length != 2)
return null;
}
}
switch (filter) {
case Table.FILTER_LIKE:
return real !== null && real.indexOf(test) != -1;
case Table.FILTER_EQUAL:
return real !== null && test == real;
case Table.FILTER_BETWEEN:
if (real === null)
return false;
if (test[0] !== null && real < test[0])
return false;
if (test[1] !== null && real > test[1])
return false;
return true;
case Table.FILTER_NULL:
return real === null;
default:
throw new Error("Unknown filter: " + filter);
}
return false;
} | [
"function",
"checkFilter",
"(",
"filter",
",",
"type",
",",
"test",
",",
"real",
")",
"{",
"if",
"(",
"type",
"==",
"Table",
".",
"TYPE_DATETIME",
")",
"{",
"if",
"(",
"typeof",
"real",
"!=",
"'object'",
")",
"real",
"=",
"new",
"Date",
"(",
"real",
"*",
"1000",
")",
";",
"if",
"(",
"filter",
"==",
"Table",
".",
"FILTER_BETWEEN",
"&&",
"Array",
".",
"isArray",
"(",
"test",
")",
"&&",
"test",
".",
"length",
"==",
"2",
")",
"{",
"test",
"=",
"[",
"test",
"[",
"0",
"]",
"?",
"moment",
".",
"unix",
"(",
"test",
"[",
"0",
"]",
")",
":",
"null",
",",
"test",
"[",
"1",
"]",
"?",
"moment",
".",
"unix",
"(",
"test",
"[",
"1",
"]",
")",
":",
"null",
",",
"]",
";",
"}",
"else",
"if",
"(",
"filter",
"!=",
"Table",
".",
"FILTER_BETWEEN",
")",
"{",
"test",
"=",
"moment",
".",
"unix",
"(",
"test",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"filter",
"==",
"Table",
".",
"FILTER_BETWEEN",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"test",
")",
"||",
"test",
".",
"length",
"!=",
"2",
")",
"return",
"null",
";",
"}",
"}",
"switch",
"(",
"filter",
")",
"{",
"case",
"Table",
".",
"FILTER_LIKE",
":",
"return",
"real",
"!==",
"null",
"&&",
"real",
".",
"indexOf",
"(",
"test",
")",
"!=",
"-",
"1",
";",
"case",
"Table",
".",
"FILTER_EQUAL",
":",
"return",
"real",
"!==",
"null",
"&&",
"test",
"==",
"real",
";",
"case",
"Table",
".",
"FILTER_BETWEEN",
":",
"if",
"(",
"real",
"===",
"null",
")",
"return",
"false",
";",
"if",
"(",
"test",
"[",
"0",
"]",
"!==",
"null",
"&&",
"real",
"<",
"test",
"[",
"0",
"]",
")",
"return",
"false",
";",
"if",
"(",
"test",
"[",
"1",
"]",
"!==",
"null",
"&&",
"real",
">",
"test",
"[",
"1",
"]",
")",
"return",
"false",
";",
"return",
"true",
";",
"case",
"Table",
".",
"FILTER_NULL",
":",
"return",
"real",
"===",
"null",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"\"Unknown filter: \"",
"+",
"filter",
")",
";",
"}",
"return",
"false",
";",
"}"
]
| Check and apply filter
@param {string} filter
@param {string} type
@param {*} test
@param {*} real | [
"Check",
"and",
"apply",
"filter"
]
| 227eafab0d4dafabe0d2ceaa881ab3befe994d9c | https://github.com/basarevych/dynamic-table/blob/227eafab0d4dafabe0d2ceaa881ab3befe994d9c/node/adapter/array.js#L239-L281 | train |
hareko/js-merge-xml | example.js | function(evt, id, fnc) {
var elem = $(id);
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evt, fnc, false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent('on' + evt, fnc);
}
else { // No much to do
elem[evt] = fnc;
}
} | javascript | function(evt, id, fnc) {
var elem = $(id);
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evt, fnc, false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent('on' + evt, fnc);
}
else { // No much to do
elem[evt] = fnc;
}
} | [
"function",
"(",
"evt",
",",
"id",
",",
"fnc",
")",
"{",
"var",
"elem",
"=",
"$",
"(",
"id",
")",
";",
"if",
"(",
"elem",
".",
"addEventListener",
")",
"elem",
".",
"addEventListener",
"(",
"evt",
",",
"fnc",
",",
"false",
")",
";",
"else",
"if",
"(",
"elem",
".",
"attachEvent",
")",
"{",
"elem",
".",
"attachEvent",
"(",
"'on'",
"+",
"evt",
",",
"fnc",
")",
";",
"}",
"else",
"{",
"elem",
"[",
"evt",
"]",
"=",
"fnc",
";",
"}",
"}"
]
| add event handler
@param {string} evt
@param {string} id
@param {function} fnc | [
"add",
"event",
"handler"
]
| 65d42764daeac152bda5a4a389a9ba108e4d26cd | https://github.com/hareko/js-merge-xml/blob/65d42764daeac152bda5a4a389a9ba108e4d26cd/example.js#L28-L38 | train |
|
hareko/js-merge-xml | example.js | function(evt) {
$('output').innerHTML = '';
$('result').innerHTML = '';
oMX.Init(); /* begin with new objects */
fls = [];
var cnt = 0;
var files = evt.target.files; /* FileList object */
for (var i = 0; i < files.length; i++) { /* loop the selected files */
var reader = new FileReader();
reader.onload = function(file) {
fls[cnt + 1] = oMX.AddFile(file) ? true : false; /* get a file */
var c = $('result').innerHTML;
if (c !== '') {
c += ', ';
}
$('result').innerHTML = c + fls[cnt];
cnt += 2;
};
fls.push(files[i].name, null);
reader.readAsText(files[i]);
}
} | javascript | function(evt) {
$('output').innerHTML = '';
$('result').innerHTML = '';
oMX.Init(); /* begin with new objects */
fls = [];
var cnt = 0;
var files = evt.target.files; /* FileList object */
for (var i = 0; i < files.length; i++) { /* loop the selected files */
var reader = new FileReader();
reader.onload = function(file) {
fls[cnt + 1] = oMX.AddFile(file) ? true : false; /* get a file */
var c = $('result').innerHTML;
if (c !== '') {
c += ', ';
}
$('result').innerHTML = c + fls[cnt];
cnt += 2;
};
fls.push(files[i].name, null);
reader.readAsText(files[i]);
}
} | [
"function",
"(",
"evt",
")",
"{",
"$",
"(",
"'output'",
")",
".",
"innerHTML",
"=",
"''",
";",
"$",
"(",
"'result'",
")",
".",
"innerHTML",
"=",
"''",
";",
"oMX",
".",
"Init",
"(",
")",
";",
"fls",
"=",
"[",
"]",
";",
"var",
"cnt",
"=",
"0",
";",
"var",
"files",
"=",
"evt",
".",
"target",
".",
"files",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"reader",
"=",
"new",
"FileReader",
"(",
")",
";",
"reader",
".",
"onload",
"=",
"function",
"(",
"file",
")",
"{",
"fls",
"[",
"cnt",
"+",
"1",
"]",
"=",
"oMX",
".",
"AddFile",
"(",
"file",
")",
"?",
"true",
":",
"false",
";",
"var",
"c",
"=",
"$",
"(",
"'result'",
")",
".",
"innerHTML",
";",
"if",
"(",
"c",
"!==",
"''",
")",
"{",
"c",
"+=",
"', '",
";",
"}",
"$",
"(",
"'result'",
")",
".",
"innerHTML",
"=",
"c",
"+",
"fls",
"[",
"cnt",
"]",
";",
"cnt",
"+=",
"2",
";",
"}",
";",
"fls",
".",
"push",
"(",
"files",
"[",
"i",
"]",
".",
"name",
",",
"null",
")",
";",
"reader",
".",
"readAsText",
"(",
"files",
"[",
"i",
"]",
")",
";",
"}",
"}"
]
| FileList objects handler
@param {object} evt | [
"FileList",
"objects",
"handler"
]
| 65d42764daeac152bda5a4a389a9ba108e4d26cd | https://github.com/hareko/js-merge-xml/blob/65d42764daeac152bda5a4a389a9ba108e4d26cd/example.js#L44-L65 | train |
|
ryanhornberger/nunjucks-html-loader | index.js | function(searchPaths, sourceFoundCallback) {
this.sourceFoundCallback = sourceFoundCallback;
if(searchPaths) {
searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
// For windows, convert to forward slashes
this.searchPaths = searchPaths.map(path.normalize);
}
else {
this.searchPaths = ['.'];
}
} | javascript | function(searchPaths, sourceFoundCallback) {
this.sourceFoundCallback = sourceFoundCallback;
if(searchPaths) {
searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
// For windows, convert to forward slashes
this.searchPaths = searchPaths.map(path.normalize);
}
else {
this.searchPaths = ['.'];
}
} | [
"function",
"(",
"searchPaths",
",",
"sourceFoundCallback",
")",
"{",
"this",
".",
"sourceFoundCallback",
"=",
"sourceFoundCallback",
";",
"if",
"(",
"searchPaths",
")",
"{",
"searchPaths",
"=",
"Array",
".",
"isArray",
"(",
"searchPaths",
")",
"?",
"searchPaths",
":",
"[",
"searchPaths",
"]",
";",
"this",
".",
"searchPaths",
"=",
"searchPaths",
".",
"map",
"(",
"path",
".",
"normalize",
")",
";",
"}",
"else",
"{",
"this",
".",
"searchPaths",
"=",
"[",
"'.'",
"]",
";",
"}",
"}"
]
| Based off of the Nunjucks 'FileSystemLoader' | [
"Based",
"off",
"of",
"the",
"Nunjucks",
"FileSystemLoader"
]
| df04de862aa86c6d590fa93174a0fa58eaaf06a0 | https://github.com/ryanhornberger/nunjucks-html-loader/blob/df04de862aa86c6d590fa93174a0fa58eaaf06a0/index.js#L9-L19 | train |
|
jasontbradshaw/tailing-stream | tailing-stream.js | function (preserveExistingProperties) {
var result = undefined;
for (var i = 1; i < arguments.length; i++) {
obj = arguments[i];
// set initial result object to the first argument given
if (!result) {
result = obj;
continue;
}
for (prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// preserve preexisting child properties if specified
if (preserveExistingProperties &&
Object.prototype.hasOwnProperty.call(result, prop)) {
continue;
}
result[prop] = obj[prop];
}
}
}
return result;
} | javascript | function (preserveExistingProperties) {
var result = undefined;
for (var i = 1; i < arguments.length; i++) {
obj = arguments[i];
// set initial result object to the first argument given
if (!result) {
result = obj;
continue;
}
for (prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// preserve preexisting child properties if specified
if (preserveExistingProperties &&
Object.prototype.hasOwnProperty.call(result, prop)) {
continue;
}
result[prop] = obj[prop];
}
}
}
return result;
} | [
"function",
"(",
"preserveExistingProperties",
")",
"{",
"var",
"result",
"=",
"undefined",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"obj",
"=",
"arguments",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"result",
")",
"{",
"result",
"=",
"obj",
";",
"continue",
";",
"}",
"for",
"(",
"prop",
"in",
"obj",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"obj",
",",
"prop",
")",
")",
"{",
"if",
"(",
"preserveExistingProperties",
"&&",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"result",
",",
"prop",
")",
")",
"{",
"continue",
";",
"}",
"result",
"[",
"prop",
"]",
"=",
"obj",
"[",
"prop",
"]",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
]
| copy properties from right-most args to left-most | [
"copy",
"properties",
"from",
"right",
"-",
"most",
"args",
"to",
"left",
"-",
"most"
]
| c4f30353718efb86d6539ce5a142dfa9cf72c27b | https://github.com/jasontbradshaw/tailing-stream/blob/c4f30353718efb86d6539ce5a142dfa9cf72c27b/tailing-stream.js#L5-L29 | train |
|
liamcurry/gql | packages/gql-merge/dist/index.js | mergeAst | function mergeAst(schemaAst) {
var typeDefs = {};
// Go through the AST and extract/merge type definitions.
var editedAst = (0, _language.visit)(schemaAst, {
enter: function enter(node) {
var nodeName = node.name ? node.name.value : null;
// Don't transform TypeDefinitions directly
if (!nodeName || !node.kind.endsWith('TypeDefinition')) {
return;
}
var oldNode = typeDefs[nodeName];
if (!oldNode) {
// First time seeing this type so just store the value.
typeDefs[nodeName] = node;
return null;
}
// This type is defined multiple times, so merge the fields and values.
var concatProps = ['fields', 'values', 'types'];
concatProps.forEach(function (propName) {
if (node[propName] && oldNode[propName]) {
node[propName] = oldNode[propName].concat(node[propName]);
}
});
typeDefs[nodeName] = node;
return null;
}
});
var remainingNodesStr = (0, _gqlFormat.formatAst)(editedAst);
var typeDefsStr = (0, _values2.default)(typeDefs).map(_gqlFormat.formatAst).join('\n');
var fullSchemaStr = remainingNodesStr + '\n\n' + typeDefsStr;
return (0, _gqlFormat.formatString)(fullSchemaStr);
} | javascript | function mergeAst(schemaAst) {
var typeDefs = {};
// Go through the AST and extract/merge type definitions.
var editedAst = (0, _language.visit)(schemaAst, {
enter: function enter(node) {
var nodeName = node.name ? node.name.value : null;
// Don't transform TypeDefinitions directly
if (!nodeName || !node.kind.endsWith('TypeDefinition')) {
return;
}
var oldNode = typeDefs[nodeName];
if (!oldNode) {
// First time seeing this type so just store the value.
typeDefs[nodeName] = node;
return null;
}
// This type is defined multiple times, so merge the fields and values.
var concatProps = ['fields', 'values', 'types'];
concatProps.forEach(function (propName) {
if (node[propName] && oldNode[propName]) {
node[propName] = oldNode[propName].concat(node[propName]);
}
});
typeDefs[nodeName] = node;
return null;
}
});
var remainingNodesStr = (0, _gqlFormat.formatAst)(editedAst);
var typeDefsStr = (0, _values2.default)(typeDefs).map(_gqlFormat.formatAst).join('\n');
var fullSchemaStr = remainingNodesStr + '\n\n' + typeDefsStr;
return (0, _gqlFormat.formatString)(fullSchemaStr);
} | [
"function",
"mergeAst",
"(",
"schemaAst",
")",
"{",
"var",
"typeDefs",
"=",
"{",
"}",
";",
"var",
"editedAst",
"=",
"(",
"0",
",",
"_language",
".",
"visit",
")",
"(",
"schemaAst",
",",
"{",
"enter",
":",
"function",
"enter",
"(",
"node",
")",
"{",
"var",
"nodeName",
"=",
"node",
".",
"name",
"?",
"node",
".",
"name",
".",
"value",
":",
"null",
";",
"if",
"(",
"!",
"nodeName",
"||",
"!",
"node",
".",
"kind",
".",
"endsWith",
"(",
"'TypeDefinition'",
")",
")",
"{",
"return",
";",
"}",
"var",
"oldNode",
"=",
"typeDefs",
"[",
"nodeName",
"]",
";",
"if",
"(",
"!",
"oldNode",
")",
"{",
"typeDefs",
"[",
"nodeName",
"]",
"=",
"node",
";",
"return",
"null",
";",
"}",
"var",
"concatProps",
"=",
"[",
"'fields'",
",",
"'values'",
",",
"'types'",
"]",
";",
"concatProps",
".",
"forEach",
"(",
"function",
"(",
"propName",
")",
"{",
"if",
"(",
"node",
"[",
"propName",
"]",
"&&",
"oldNode",
"[",
"propName",
"]",
")",
"{",
"node",
"[",
"propName",
"]",
"=",
"oldNode",
"[",
"propName",
"]",
".",
"concat",
"(",
"node",
"[",
"propName",
"]",
")",
";",
"}",
"}",
")",
";",
"typeDefs",
"[",
"nodeName",
"]",
"=",
"node",
";",
"return",
"null",
";",
"}",
"}",
")",
";",
"var",
"remainingNodesStr",
"=",
"(",
"0",
",",
"_gqlFormat",
".",
"formatAst",
")",
"(",
"editedAst",
")",
";",
"var",
"typeDefsStr",
"=",
"(",
"0",
",",
"_values2",
".",
"default",
")",
"(",
"typeDefs",
")",
".",
"map",
"(",
"_gqlFormat",
".",
"formatAst",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"\\n",
"var",
"fullSchemaStr",
"=",
"remainingNodesStr",
"+",
"'\\n\\n'",
"+",
"\\n",
";",
"}"
]
| Merges duplicate definitions in a single GraphQL abstract-syntax tree
@param {Document} schemaAst - The GraphQL AST.
@return {string} The resulting merged GraphQL string. | [
"Merges",
"duplicate",
"definitions",
"in",
"a",
"single",
"GraphQL",
"abstract",
"-",
"syntax",
"tree"
]
| 0a28f69cc80084d648a95d1ea24a834d737235f6 | https://github.com/liamcurry/gql/blob/0a28f69cc80084d648a95d1ea24a834d737235f6/packages/gql-merge/dist/index.js#L272-L311 | train |
gribnoysup/setup-polly-jest | src/setupJasmine.js | getRecordingName | function getRecordingName(spec, suite) {
const descriptions = [spec.description];
while (suite) {
suite.description && descriptions.push(suite.description);
suite = suite.parentSuite;
}
return descriptions.reverse().join('/');
} | javascript | function getRecordingName(spec, suite) {
const descriptions = [spec.description];
while (suite) {
suite.description && descriptions.push(suite.description);
suite = suite.parentSuite;
}
return descriptions.reverse().join('/');
} | [
"function",
"getRecordingName",
"(",
"spec",
",",
"suite",
")",
"{",
"const",
"descriptions",
"=",
"[",
"spec",
".",
"description",
"]",
";",
"while",
"(",
"suite",
")",
"{",
"suite",
".",
"description",
"&&",
"descriptions",
".",
"push",
"(",
"suite",
".",
"description",
")",
";",
"suite",
"=",
"suite",
".",
"parentSuite",
";",
"}",
"return",
"descriptions",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}"
]
| Get full spec description, starting from the top
suite
@param {Object} spec Current spec
@param {Object} suite Current spec parent suite
@returns {string} Full spec description (e.g. "suite/should do something") | [
"Get",
"full",
"spec",
"description",
"starting",
"from",
"the",
"top",
"suite"
]
| 8c0acedca7f84a788f80974460893605f335a946 | https://github.com/gribnoysup/setup-polly-jest/blob/8c0acedca7f84a788f80974460893605f335a946/src/setupJasmine.js#L29-L38 | train |
gribnoysup/setup-polly-jest | src/setupJasmine.js | findSuiteRec | function findSuiteRec(suite, findFn) {
if (findFn(suite)) return suite;
for (const child of suite.children || []) {
const result = findSuiteRec(child, findFn);
if (result !== null) {
return result;
}
}
return null;
} | javascript | function findSuiteRec(suite, findFn) {
if (findFn(suite)) return suite;
for (const child of suite.children || []) {
const result = findSuiteRec(child, findFn);
if (result !== null) {
return result;
}
}
return null;
} | [
"function",
"findSuiteRec",
"(",
"suite",
",",
"findFn",
")",
"{",
"if",
"(",
"findFn",
"(",
"suite",
")",
")",
"return",
"suite",
";",
"for",
"(",
"const",
"child",
"of",
"suite",
".",
"children",
"||",
"[",
"]",
")",
"{",
"const",
"result",
"=",
"findSuiteRec",
"(",
"child",
",",
"findFn",
")",
";",
"if",
"(",
"result",
"!==",
"null",
")",
"{",
"return",
"result",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Recursively go through suite and its children
and return the first that matches the findFn
condition
@param {Object} suite Starting point
@param {Function} findFn Find function
@returns {?Object} Matching suite or null | [
"Recursively",
"go",
"through",
"suite",
"and",
"its",
"children",
"and",
"return",
"the",
"first",
"that",
"matches",
"the",
"findFn",
"condition"
]
| 8c0acedca7f84a788f80974460893605f335a946 | https://github.com/gribnoysup/setup-polly-jest/blob/8c0acedca7f84a788f80974460893605f335a946/src/setupJasmine.js#L50-L62 | train |
fex-team/fis3-hook-amd | amd.js | strSplice | function strSplice(str, index, count, add) {
return str.slice(0, index) + add + str.slice(index + count);
} | javascript | function strSplice(str, index, count, add) {
return str.slice(0, index) + add + str.slice(index + count);
} | [
"function",
"strSplice",
"(",
"str",
",",
"index",
",",
"count",
",",
"add",
")",
"{",
"return",
"str",
".",
"slice",
"(",
"0",
",",
"index",
")",
"+",
"add",
"+",
"str",
".",
"slice",
"(",
"index",
"+",
"count",
")",
";",
"}"
]
| like array.splice | [
"like",
"array",
".",
"splice"
]
| 2edda3eab5e14a8720f36255cecefe813404e5e9 | https://github.com/fex-team/fis3-hook-amd/blob/2edda3eab5e14a8720f36255cecefe813404e5e9/amd.js#L818-L820 | train |
liamcurry/gql | packages/gql-format/dist/index.js | SchemaDefinition | function SchemaDefinition(_ref24) {
var directives = _ref24.directives,
operationTypes = _ref24.operationTypes;
return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
} | javascript | function SchemaDefinition(_ref24) {
var directives = _ref24.directives,
operationTypes = _ref24.operationTypes;
return join(['schema', join(directives, ' '), block(operationTypes)], ' ');
} | [
"function",
"SchemaDefinition",
"(",
"_ref24",
")",
"{",
"var",
"directives",
"=",
"_ref24",
".",
"directives",
",",
"operationTypes",
"=",
"_ref24",
".",
"operationTypes",
";",
"return",
"join",
"(",
"[",
"'schema'",
",",
"join",
"(",
"directives",
",",
"' '",
")",
",",
"block",
"(",
"operationTypes",
")",
"]",
",",
"' '",
")",
";",
"}"
]
| Type System Definitions | [
"Type",
"System",
"Definitions"
]
| 0a28f69cc80084d648a95d1ea24a834d737235f6 | https://github.com/liamcurry/gql/blob/0a28f69cc80084d648a95d1ea24a834d737235f6/packages/gql-format/dist/index.js#L438-L442 | train |
liamcurry/gql | packages/gql-format/dist/index.js | join | function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
} | javascript | function join(maybeArray, separator) {
return maybeArray ? maybeArray.filter(function (x) {
return x;
}).join(separator || '') : '';
} | [
"function",
"join",
"(",
"maybeArray",
",",
"separator",
")",
"{",
"return",
"maybeArray",
"?",
"maybeArray",
".",
"filter",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"x",
";",
"}",
")",
".",
"join",
"(",
"separator",
"||",
"''",
")",
":",
"''",
";",
"}"
]
| Given maybeArray, print an empty string if it is null or empty, otherwise
print all items together separated by separator if provided | [
"Given",
"maybeArray",
"print",
"an",
"empty",
"string",
"if",
"it",
"is",
"null",
"or",
"empty",
"otherwise",
"print",
"all",
"items",
"together",
"separated",
"by",
"separator",
"if",
"provided"
]
| 0a28f69cc80084d648a95d1ea24a834d737235f6 | https://github.com/liamcurry/gql/blob/0a28f69cc80084d648a95d1ea24a834d737235f6/packages/gql-format/dist/index.js#L546-L550 | train |
FamilySearch/fs-js-lite | src/xhrHandler.js | createResponse | function createResponse(xhr, request){
// XHR header processing borrowed from jQuery
var responseHeaders = {}, match;
while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
return {
statusCode: xhr.status,
statusText: xhr.statusText,
headers: responseHeaders,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: xhr.responseText,
retries: 0,
throttled: false
};
} | javascript | function createResponse(xhr, request){
// XHR header processing borrowed from jQuery
var responseHeaders = {}, match;
while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
return {
statusCode: xhr.status,
statusText: xhr.statusText,
headers: responseHeaders,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: xhr.responseText,
retries: 0,
throttled: false
};
} | [
"function",
"createResponse",
"(",
"xhr",
",",
"request",
")",
"{",
"var",
"responseHeaders",
"=",
"{",
"}",
",",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"headersRegex",
".",
"exec",
"(",
"xhr",
".",
"getAllResponseHeaders",
"(",
")",
")",
")",
")",
"{",
"responseHeaders",
"[",
"match",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"match",
"[",
"2",
"]",
";",
"}",
"return",
"{",
"statusCode",
":",
"xhr",
".",
"status",
",",
"statusText",
":",
"xhr",
".",
"statusText",
",",
"headers",
":",
"responseHeaders",
",",
"originalUrl",
":",
"request",
".",
"url",
",",
"effectiveUrl",
":",
"request",
".",
"url",
",",
"redirected",
":",
"false",
",",
"requestMethod",
":",
"request",
".",
"method",
",",
"requestHeaders",
":",
"request",
".",
"headers",
",",
"body",
":",
"xhr",
".",
"responseText",
",",
"retries",
":",
"0",
",",
"throttled",
":",
"false",
"}",
";",
"}"
]
| Convert an XHR response to a standard response object
@param {XMLHttpRequest} xhr
@param {Object} request {url, method, headers, retries}
@return {Object} response | [
"Convert",
"an",
"XHR",
"response",
"to",
"a",
"standard",
"response",
"object"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/xhrHandler.js#L51-L72 | train |
FamilySearch/fs-js-lite | src/FamilySearch.js | function(options){
// Set the default options
this.appKey = '';
this.environment = 'integration';
this.redirectUri = '';
this.tokenCookie = 'FS_AUTH_TOKEN';
this.maxThrottledRetries = 10;
this.saveAccessToken = false;
this.accessToken = '';
this.jwt = '';
this.middleware = {
request: [
requestMiddleware.url,
requestMiddleware.defaultAcceptHeader,
requestMiddleware.authorizationHeader,
requestMiddleware.disableAutomaticRedirects,
requestMiddleware.body
],
response: [
responseMiddleware.redirect,
responseMiddleware.throttling,
responseMiddleware.json
]
};
// Process options
this.config(options);
} | javascript | function(options){
// Set the default options
this.appKey = '';
this.environment = 'integration';
this.redirectUri = '';
this.tokenCookie = 'FS_AUTH_TOKEN';
this.maxThrottledRetries = 10;
this.saveAccessToken = false;
this.accessToken = '';
this.jwt = '';
this.middleware = {
request: [
requestMiddleware.url,
requestMiddleware.defaultAcceptHeader,
requestMiddleware.authorizationHeader,
requestMiddleware.disableAutomaticRedirects,
requestMiddleware.body
],
response: [
responseMiddleware.redirect,
responseMiddleware.throttling,
responseMiddleware.json
]
};
// Process options
this.config(options);
} | [
"function",
"(",
"options",
")",
"{",
"this",
".",
"appKey",
"=",
"''",
";",
"this",
".",
"environment",
"=",
"'integration'",
";",
"this",
".",
"redirectUri",
"=",
"''",
";",
"this",
".",
"tokenCookie",
"=",
"'FS_AUTH_TOKEN'",
";",
"this",
".",
"maxThrottledRetries",
"=",
"10",
";",
"this",
".",
"saveAccessToken",
"=",
"false",
";",
"this",
".",
"accessToken",
"=",
"''",
";",
"this",
".",
"jwt",
"=",
"''",
";",
"this",
".",
"middleware",
"=",
"{",
"request",
":",
"[",
"requestMiddleware",
".",
"url",
",",
"requestMiddleware",
".",
"defaultAcceptHeader",
",",
"requestMiddleware",
".",
"authorizationHeader",
",",
"requestMiddleware",
".",
"disableAutomaticRedirects",
",",
"requestMiddleware",
".",
"body",
"]",
",",
"response",
":",
"[",
"responseMiddleware",
".",
"redirect",
",",
"responseMiddleware",
".",
"throttling",
",",
"responseMiddleware",
".",
"json",
"]",
"}",
";",
"this",
".",
"config",
"(",
"options",
")",
";",
"}"
]
| Create an instance of the FamilySearch SDK Client
@param {Object} options See a description of the possible options in the docs for config(). | [
"Create",
"an",
"instance",
"of",
"the",
"FamilySearch",
"SDK",
"Client"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/FamilySearch.js#L13-L41 | train |
|
philipwalton/private-parts | index.js | createKey | function createKey(factory){
// Create the factory based on the type of object passed.
factory = typeof factory == 'function'
? factory
: createBound(factory);
// Store is used to map public objects to private objects.
var store = new WeakMap();
// Seen is used to track existing private objects.
var seen = new WeakMap();
/**
* An accessor function to get private instances from the store.
* @param {Object} key The public object that is associated with a private
* object in the store.
*/
return function(key) {
if (typeof key != 'object') return;
var value = store.get(key);
if (!value) {
// Make sure key isn't already the private instance of some existing key.
// This check helps prevent accidental double privatizing.
if (seen.has(key)) {
value = key;
} else {
value = factory(key);
store.set(key, value);
seen.set(value, true);
}
}
return value;
};
} | javascript | function createKey(factory){
// Create the factory based on the type of object passed.
factory = typeof factory == 'function'
? factory
: createBound(factory);
// Store is used to map public objects to private objects.
var store = new WeakMap();
// Seen is used to track existing private objects.
var seen = new WeakMap();
/**
* An accessor function to get private instances from the store.
* @param {Object} key The public object that is associated with a private
* object in the store.
*/
return function(key) {
if (typeof key != 'object') return;
var value = store.get(key);
if (!value) {
// Make sure key isn't already the private instance of some existing key.
// This check helps prevent accidental double privatizing.
if (seen.has(key)) {
value = key;
} else {
value = factory(key);
store.set(key, value);
seen.set(value, true);
}
}
return value;
};
} | [
"function",
"createKey",
"(",
"factory",
")",
"{",
"factory",
"=",
"typeof",
"factory",
"==",
"'function'",
"?",
"factory",
":",
"createBound",
"(",
"factory",
")",
";",
"var",
"store",
"=",
"new",
"WeakMap",
"(",
")",
";",
"var",
"seen",
"=",
"new",
"WeakMap",
"(",
")",
";",
"return",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"typeof",
"key",
"!=",
"'object'",
")",
"return",
";",
"var",
"value",
"=",
"store",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"!",
"value",
")",
"{",
"if",
"(",
"seen",
".",
"has",
"(",
"key",
")",
")",
"{",
"value",
"=",
"key",
";",
"}",
"else",
"{",
"value",
"=",
"factory",
"(",
"key",
")",
";",
"store",
".",
"set",
"(",
"key",
",",
"value",
")",
";",
"seen",
".",
"set",
"(",
"value",
",",
"true",
")",
";",
"}",
"}",
"return",
"value",
";",
"}",
";",
"}"
]
| A function that returns a function that allows you to associate
a public object with its private counterpart.
@param {Function|Object} factory An optional argument that, is present, will
be used to create new objects in the store.
If factory is a function, it will be invoked with the key as an argument
and the return value will be the private instance.
If factory is an object, the private instance will be a new object with
factory as it's prototype. | [
"A",
"function",
"that",
"returns",
"a",
"function",
"that",
"allows",
"you",
"to",
"associate",
"a",
"public",
"object",
"with",
"its",
"private",
"counterpart",
"."
]
| 710d42f35c6c31267ba865af3470b4a08ce1fdd9 | https://github.com/philipwalton/private-parts/blob/710d42f35c6c31267ba865af3470b4a08ce1fdd9/index.js#L11-L46 | train |
FamilySearch/fs-js-lite | docs/console.js | makeRequest | function makeRequest(){
output('Sending the request...');
var options = {
method: $method.value,
headers: {
Accept: document.getElementById('accept').value
},
followRedirect: $followRedirect.checked
};
if(options.method === 'POST'){
options.body = $requestBody.value;
}
client.request($url.value, options, function(error, response){
if(error){
genericError();
} else {
displayResponse(response);
if(response.statusCode === 401){
$authStatus.classList.remove('loggedin');
$tokenDisplay.value = '';
} else {
$authStatus.classList.add('loggedin');
$tokenDisplay.value = 'Bearer ' + client.getAccessToken();
}
}
});
} | javascript | function makeRequest(){
output('Sending the request...');
var options = {
method: $method.value,
headers: {
Accept: document.getElementById('accept').value
},
followRedirect: $followRedirect.checked
};
if(options.method === 'POST'){
options.body = $requestBody.value;
}
client.request($url.value, options, function(error, response){
if(error){
genericError();
} else {
displayResponse(response);
if(response.statusCode === 401){
$authStatus.classList.remove('loggedin');
$tokenDisplay.value = '';
} else {
$authStatus.classList.add('loggedin');
$tokenDisplay.value = 'Bearer ' + client.getAccessToken();
}
}
});
} | [
"function",
"makeRequest",
"(",
")",
"{",
"output",
"(",
"'Sending the request...'",
")",
";",
"var",
"options",
"=",
"{",
"method",
":",
"$method",
".",
"value",
",",
"headers",
":",
"{",
"Accept",
":",
"document",
".",
"getElementById",
"(",
"'accept'",
")",
".",
"value",
"}",
",",
"followRedirect",
":",
"$followRedirect",
".",
"checked",
"}",
";",
"if",
"(",
"options",
".",
"method",
"===",
"'POST'",
")",
"{",
"options",
".",
"body",
"=",
"$requestBody",
".",
"value",
";",
"}",
"client",
".",
"request",
"(",
"$url",
".",
"value",
",",
"options",
",",
"function",
"(",
"error",
",",
"response",
")",
"{",
"if",
"(",
"error",
")",
"{",
"genericError",
"(",
")",
";",
"}",
"else",
"{",
"displayResponse",
"(",
"response",
")",
";",
"if",
"(",
"response",
".",
"statusCode",
"===",
"401",
")",
"{",
"$authStatus",
".",
"classList",
".",
"remove",
"(",
"'loggedin'",
")",
";",
"$tokenDisplay",
".",
"value",
"=",
"''",
";",
"}",
"else",
"{",
"$authStatus",
".",
"classList",
".",
"add",
"(",
"'loggedin'",
")",
";",
"$tokenDisplay",
".",
"value",
"=",
"'Bearer '",
"+",
"client",
".",
"getAccessToken",
"(",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Send a request to the API and display the response | [
"Send",
"a",
"request",
"to",
"the",
"API",
"and",
"display",
"the",
"response"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L63-L91 | train |
FamilySearch/fs-js-lite | docs/console.js | displayResponse | function displayResponse(response){
// Gather and display HTTP response data
var lines = [
response.statusCode + ' ' + response.statusText,
headersToString(response.headers)
];
if(response.data){
lines.push('');
lines.push(prettyPrint(response.data));
}
output(lines.join('\n'));
// Attach listeners to links so that clicking a link will auto-populate
// the url field
Array.from($output.querySelectorAll('.link')).forEach(function(link){
link.addEventListener('click', function(){
// Remove leading and trailing "
$url.value = link.innerHTML.slice(1,-1);
window.scrollTo(0, 0);
});
});
} | javascript | function displayResponse(response){
// Gather and display HTTP response data
var lines = [
response.statusCode + ' ' + response.statusText,
headersToString(response.headers)
];
if(response.data){
lines.push('');
lines.push(prettyPrint(response.data));
}
output(lines.join('\n'));
// Attach listeners to links so that clicking a link will auto-populate
// the url field
Array.from($output.querySelectorAll('.link')).forEach(function(link){
link.addEventListener('click', function(){
// Remove leading and trailing "
$url.value = link.innerHTML.slice(1,-1);
window.scrollTo(0, 0);
});
});
} | [
"function",
"displayResponse",
"(",
"response",
")",
"{",
"var",
"lines",
"=",
"[",
"response",
".",
"statusCode",
"+",
"' '",
"+",
"response",
".",
"statusText",
",",
"headersToString",
"(",
"response",
".",
"headers",
")",
"]",
";",
"if",
"(",
"response",
".",
"data",
")",
"{",
"lines",
".",
"push",
"(",
"''",
")",
";",
"lines",
".",
"push",
"(",
"prettyPrint",
"(",
"response",
".",
"data",
")",
")",
";",
"}",
"output",
"(",
"lines",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"\\n",
"}"
]
| Display an API response
@param {Object} response | [
"Display",
"an",
"API",
"response"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L105-L127 | train |
FamilySearch/fs-js-lite | docs/console.js | headersToString | function headersToString(headers){
var lines = [];
for(var name in headers){
lines.push(name + ': ' + headers[name]);
}
return lines.join('\n');
} | javascript | function headersToString(headers){
var lines = [];
for(var name in headers){
lines.push(name + ': ' + headers[name]);
}
return lines.join('\n');
} | [
"function",
"headersToString",
"(",
"headers",
")",
"{",
"var",
"lines",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"name",
"in",
"headers",
")",
"{",
"lines",
".",
"push",
"(",
"name",
"+",
"': '",
"+",
"headers",
"[",
"name",
"]",
")",
";",
"}",
"return",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
]
| Convert a headers map into a multi-line string
@param {Object} headers
@return {String} | [
"Convert",
"a",
"headers",
"map",
"into",
"a",
"multi",
"-",
"line",
"string"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L135-L141 | train |
FamilySearch/fs-js-lite | docs/console.js | syntaxHighlight | function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number',
url = false;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
if(match.indexOf('"https://') === 0){
// url = true;
cls += ' link';
}
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
var html = '<span class="' + cls + '">' + match + '</span>';
if(url){
html = '<a href>' + html + '</a>';
}
return html;
});
} | javascript | function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number',
url = false;
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
if(match.indexOf('"https://') === 0){
// url = true;
cls += ' link';
}
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
var html = '<span class="' + cls + '">' + match + '</span>';
if(url){
html = '<a href>' + html + '</a>';
}
return html;
});
} | [
"function",
"syntaxHighlight",
"(",
"json",
")",
"{",
"json",
"=",
"json",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"'&'",
")",
".",
"replace",
"(",
"/",
"<",
"/",
"g",
",",
"'<'",
")",
".",
"replace",
"(",
"/",
">",
"/",
"g",
",",
"'>'",
")",
";",
"return",
"json",
".",
"replace",
"(",
"/",
"(\"(\\\\u[a-zA-Z0-9]{4}|\\\\[^u]|[^\\\\\"])*\"(\\s*:)?|\\b(true|false|null)\\b|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)",
"/",
"g",
",",
"function",
"(",
"match",
")",
"{",
"var",
"cls",
"=",
"'number'",
",",
"url",
"=",
"false",
";",
"if",
"(",
"/",
"^\"",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"if",
"(",
"/",
":$",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"cls",
"=",
"'key'",
";",
"}",
"else",
"{",
"cls",
"=",
"'string'",
";",
"if",
"(",
"match",
".",
"indexOf",
"(",
"'\"https://'",
")",
"===",
"0",
")",
"{",
"cls",
"+=",
"' link'",
";",
"}",
"}",
"}",
"else",
"if",
"(",
"/",
"true|false",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"cls",
"=",
"'boolean'",
";",
"}",
"else",
"if",
"(",
"/",
"null",
"/",
".",
"test",
"(",
"match",
")",
")",
"{",
"cls",
"=",
"'null'",
";",
"}",
"var",
"html",
"=",
"'<span class=\"'",
"+",
"cls",
"+",
"'\">'",
"+",
"match",
"+",
"'</span>'",
";",
"if",
"(",
"url",
")",
"{",
"html",
"=",
"'<a href>'",
"+",
"html",
"+",
"'</a>'",
";",
"}",
"return",
"html",
";",
"}",
")",
";",
"}"
]
| Parse a JSON string and wrap data in spans to enable syntax highlighting.
http://stackoverflow.com/a/7220510
@param {String} JSON string
@returns {String} | [
"Parse",
"a",
"JSON",
"string",
"and",
"wrap",
"data",
"in",
"spans",
"to",
"enable",
"syntax",
"highlighting",
"."
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/docs/console.js#L170-L196 | train |
JamesMGreene/currentExecutingScript | src/main.js | getScriptFromUrl | function getScriptFromUrl(url, eligibleScripts) {
var i,
script = null;
eligibleScripts = eligibleScripts || scripts;
if (typeof url === "string" && url) {
for (i = eligibleScripts.length; i--; ) {
if (eligibleScripts[i].src === url) {
// NOTE: Could check if the same script URL is used by more than one `script` element
// here... but let's not. That would yield less useful results in "loose" detection. ;)
script = eligibleScripts[i];
break;
}
}
}
return script;
} | javascript | function getScriptFromUrl(url, eligibleScripts) {
var i,
script = null;
eligibleScripts = eligibleScripts || scripts;
if (typeof url === "string" && url) {
for (i = eligibleScripts.length; i--; ) {
if (eligibleScripts[i].src === url) {
// NOTE: Could check if the same script URL is used by more than one `script` element
// here... but let's not. That would yield less useful results in "loose" detection. ;)
script = eligibleScripts[i];
break;
}
}
}
return script;
} | [
"function",
"getScriptFromUrl",
"(",
"url",
",",
"eligibleScripts",
")",
"{",
"var",
"i",
",",
"script",
"=",
"null",
";",
"eligibleScripts",
"=",
"eligibleScripts",
"||",
"scripts",
";",
"if",
"(",
"typeof",
"url",
"===",
"\"string\"",
"&&",
"url",
")",
"{",
"for",
"(",
"i",
"=",
"eligibleScripts",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"if",
"(",
"eligibleScripts",
"[",
"i",
"]",
".",
"src",
"===",
"url",
")",
"{",
"script",
"=",
"eligibleScripts",
"[",
"i",
"]",
";",
"break",
";",
"}",
"}",
"}",
"return",
"script",
";",
"}"
]
| Get script object based on the `src` URL | [
"Get",
"script",
"object",
"based",
"on",
"the",
"src",
"URL"
]
| cfb5905463a6cc80f95d0d64721db269524c2ac9 | https://github.com/JamesMGreene/currentExecutingScript/blob/cfb5905463a6cc80f95d0d64721db269524c2ac9/src/main.js#L52-L69 | train |
JamesMGreene/currentExecutingScript | src/main.js | getSoleInlineScript | function getSoleInlineScript(eligibleScripts) {
var i, len,
script = null;
eligibleScripts = eligibleScripts || scripts;
for (i = 0, len = eligibleScripts.length; i < len; i++) {
if (!eligibleScripts[i].hasAttribute("src")) {
if (script) {
script = null;
break;
}
script = eligibleScripts[i];
}
}
return script;
} | javascript | function getSoleInlineScript(eligibleScripts) {
var i, len,
script = null;
eligibleScripts = eligibleScripts || scripts;
for (i = 0, len = eligibleScripts.length; i < len; i++) {
if (!eligibleScripts[i].hasAttribute("src")) {
if (script) {
script = null;
break;
}
script = eligibleScripts[i];
}
}
return script;
} | [
"function",
"getSoleInlineScript",
"(",
"eligibleScripts",
")",
"{",
"var",
"i",
",",
"len",
",",
"script",
"=",
"null",
";",
"eligibleScripts",
"=",
"eligibleScripts",
"||",
"scripts",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"eligibleScripts",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"eligibleScripts",
"[",
"i",
"]",
".",
"hasAttribute",
"(",
"\"src\"",
")",
")",
"{",
"if",
"(",
"script",
")",
"{",
"script",
"=",
"null",
";",
"break",
";",
"}",
"script",
"=",
"eligibleScripts",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"script",
";",
"}"
]
| If there is only a single inline script on the page, return it; otherwise `null` | [
"If",
"there",
"is",
"only",
"a",
"single",
"inline",
"script",
"on",
"the",
"page",
"return",
"it",
";",
"otherwise",
"null"
]
| cfb5905463a6cc80f95d0d64721db269524c2ac9 | https://github.com/JamesMGreene/currentExecutingScript/blob/cfb5905463a6cc80f95d0d64721db269524c2ac9/src/main.js#L100-L114 | train |
JamesMGreene/currentExecutingScript | src/main.js | getScriptUrlFromStack | function getScriptUrlFromStack(stack, skipStackDepth) {
var matches, remainingStack,
url = null,
ignoreMessage = typeof skipStackDepth === "number";
skipStackDepth = ignoreMessage ? Math.round(skipStackDepth) : 0;
if (typeof stack === "string" && stack) {
if (ignoreMessage) {
matches = stack.match(/(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
else {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=data:text\/javascript|blob|http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (!(matches && matches[1])) {
matches = stack.match(/\)@(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
}
if (matches && matches[1]) {
if (skipStackDepth > 0) {
remainingStack = stack.slice(stack.indexOf(matches[0]) + matches[0].length);
url = getScriptUrlFromStack(remainingStack, (skipStackDepth - 1));
}
else {
url = matches[1];
}
}
// TODO: Handle more edge cases!
// Fixes #1
// See https://github.com/JamesMGreene/currentExecutingScript/issues/1
// ???
}
return url;
} | javascript | function getScriptUrlFromStack(stack, skipStackDepth) {
var matches, remainingStack,
url = null,
ignoreMessage = typeof skipStackDepth === "number";
skipStackDepth = ignoreMessage ? Math.round(skipStackDepth) : 0;
if (typeof stack === "string" && stack) {
if (ignoreMessage) {
matches = stack.match(/(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
else {
matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=data:text\/javascript|blob|http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
if (!(matches && matches[1])) {
matches = stack.match(/\)@(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
}
}
if (matches && matches[1]) {
if (skipStackDepth > 0) {
remainingStack = stack.slice(stack.indexOf(matches[0]) + matches[0].length);
url = getScriptUrlFromStack(remainingStack, (skipStackDepth - 1));
}
else {
url = matches[1];
}
}
// TODO: Handle more edge cases!
// Fixes #1
// See https://github.com/JamesMGreene/currentExecutingScript/issues/1
// ???
}
return url;
} | [
"function",
"getScriptUrlFromStack",
"(",
"stack",
",",
"skipStackDepth",
")",
"{",
"var",
"matches",
",",
"remainingStack",
",",
"url",
"=",
"null",
",",
"ignoreMessage",
"=",
"typeof",
"skipStackDepth",
"===",
"\"number\"",
";",
"skipStackDepth",
"=",
"ignoreMessage",
"?",
"Math",
".",
"round",
"(",
"skipStackDepth",
")",
":",
"0",
";",
"if",
"(",
"typeof",
"stack",
"===",
"\"string\"",
"&&",
"stack",
")",
"{",
"if",
"(",
"ignoreMessage",
")",
"{",
"matches",
"=",
"stack",
".",
"match",
"(",
"/",
"(data:text\\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\\/\\/[\\/]?.+?\\/[^:\\)]*?)(?::\\d+)(?::\\d+)?",
"/",
")",
";",
"}",
"else",
"{",
"matches",
"=",
"stack",
".",
"match",
"(",
"/",
"^(?:|[^:@]*@|.+\\)@(?=data:text\\/javascript|blob|http[s]?|file)|.+?\\s+(?: at |@)(?:[^:\\(]+ )*[\\(]?)(data:text\\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\\/\\/[\\/]?.+?\\/[^:\\)]*?)(?::\\d+)(?::\\d+)?",
"/",
")",
";",
"if",
"(",
"!",
"(",
"matches",
"&&",
"matches",
"[",
"1",
"]",
")",
")",
"{",
"matches",
"=",
"stack",
".",
"match",
"(",
"/",
"\\)@(data:text\\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\\/\\/[\\/]?.+?\\/[^:\\)]*?)(?::\\d+)(?::\\d+)?",
"/",
")",
";",
"}",
"}",
"if",
"(",
"matches",
"&&",
"matches",
"[",
"1",
"]",
")",
"{",
"if",
"(",
"skipStackDepth",
">",
"0",
")",
"{",
"remainingStack",
"=",
"stack",
".",
"slice",
"(",
"stack",
".",
"indexOf",
"(",
"matches",
"[",
"0",
"]",
")",
"+",
"matches",
"[",
"0",
"]",
".",
"length",
")",
";",
"url",
"=",
"getScriptUrlFromStack",
"(",
"remainingStack",
",",
"(",
"skipStackDepth",
"-",
"1",
")",
")",
";",
"}",
"else",
"{",
"url",
"=",
"matches",
"[",
"1",
"]",
";",
"}",
"}",
"}",
"return",
"url",
";",
"}"
]
| Get the currently executing script URL from an Error stack trace | [
"Get",
"the",
"currently",
"executing",
"script",
"URL",
"from",
"an",
"Error",
"stack",
"trace"
]
| cfb5905463a6cc80f95d0d64721db269524c2ac9 | https://github.com/JamesMGreene/currentExecutingScript/blob/cfb5905463a6cc80f95d0d64721db269524c2ac9/src/main.js#L117-L152 | train |
FamilySearch/fs-js-lite | src/nodeHandler.js | createResponse | function createResponse(request, response, body){
return {
statusCode: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: body,
retries: 0,
throttled: false
};
} | javascript | function createResponse(request, response, body){
return {
statusCode: response.statusCode,
statusText: response.statusMessage,
headers: response.headers,
originalUrl: request.url,
effectiveUrl: request.url,
redirected: false,
requestMethod: request.method,
requestHeaders: request.headers,
body: body,
retries: 0,
throttled: false
};
} | [
"function",
"createResponse",
"(",
"request",
",",
"response",
",",
"body",
")",
"{",
"return",
"{",
"statusCode",
":",
"response",
".",
"statusCode",
",",
"statusText",
":",
"response",
".",
"statusMessage",
",",
"headers",
":",
"response",
".",
"headers",
",",
"originalUrl",
":",
"request",
".",
"url",
",",
"effectiveUrl",
":",
"request",
".",
"url",
",",
"redirected",
":",
"false",
",",
"requestMethod",
":",
"request",
".",
"method",
",",
"requestHeaders",
":",
"request",
".",
"headers",
",",
"body",
":",
"body",
",",
"retries",
":",
"0",
",",
"throttled",
":",
"false",
"}",
";",
"}"
]
| Convert an node response to a standard sdk response object
@param {Object} request {url, method, headers, retries}
@param {http.IncomingMessage} response
@param {String} body
@return {Object} response | [
"Convert",
"an",
"node",
"response",
"to",
"a",
"standard",
"sdk",
"response",
"object"
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/nodeHandler.js#L33-L47 | train |
Soreine/draft-js-simpledecorator | index.js | callback | function callback (start, end, props) {
if (props === undefined) {
props = {};
}
key = blockKey + KEY_SEPARATOR + decorationId;
decorated[blockKey][decorationId] = props;
decorateRange(decorations, start, end, key);
decorationId++;
} | javascript | function callback (start, end, props) {
if (props === undefined) {
props = {};
}
key = blockKey + KEY_SEPARATOR + decorationId;
decorated[blockKey][decorationId] = props;
decorateRange(decorations, start, end, key);
decorationId++;
} | [
"function",
"callback",
"(",
"start",
",",
"end",
",",
"props",
")",
"{",
"if",
"(",
"props",
"===",
"undefined",
")",
"{",
"props",
"=",
"{",
"}",
";",
"}",
"key",
"=",
"blockKey",
"+",
"KEY_SEPARATOR",
"+",
"decorationId",
";",
"decorated",
"[",
"blockKey",
"]",
"[",
"decorationId",
"]",
"=",
"props",
";",
"decorateRange",
"(",
"decorations",
",",
"start",
",",
"end",
",",
"key",
")",
";",
"decorationId",
"++",
";",
"}"
]
| Apply a decoration to given range, with given props | [
"Apply",
"a",
"decoration",
"to",
"given",
"range",
"with",
"given",
"props"
]
| 436fe513f7d97322cfbf7c779050d539948ab65d | https://github.com/Soreine/draft-js-simpledecorator/blob/436fe513f7d97322cfbf7c779050d539948ab65d/index.js#L24-L32 | train |
mrbar42/trixion | src/polyfill/promise.js | handleThenable | function handleThenable(promise, value) {
var done, then;
// Attempt to get the `then` method from the thenable (if it is a thenable)
try {
if (! (then = utils.thenable(value))) {
return false;
}
} catch (err) {
rejectPromise(promise, err);
return true;
}
// Ensure that the promise did not attempt to fulfill with itself
if (promise === value) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return true;
}
try {
// Wait for the thenable to fulfill/reject before moving on
then.call(value,
function(subValue) {
if (! done) {
done = true;
// Once again look for circular promise resolution
if (value === subValue) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return;
}
resolvePromise(promise, subValue);
}
},
function(subValue) {
if (! done) {
done = true;
rejectPromise(promise, subValue);
}
}
);
} catch (err) {
if (! done) {
done = true;
rejectPromise(promise, err);
}
}
return true;
} | javascript | function handleThenable(promise, value) {
var done, then;
// Attempt to get the `then` method from the thenable (if it is a thenable)
try {
if (! (then = utils.thenable(value))) {
return false;
}
} catch (err) {
rejectPromise(promise, err);
return true;
}
// Ensure that the promise did not attempt to fulfill with itself
if (promise === value) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return true;
}
try {
// Wait for the thenable to fulfill/reject before moving on
then.call(value,
function(subValue) {
if (! done) {
done = true;
// Once again look for circular promise resolution
if (value === subValue) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return;
}
resolvePromise(promise, subValue);
}
},
function(subValue) {
if (! done) {
done = true;
rejectPromise(promise, subValue);
}
}
);
} catch (err) {
if (! done) {
done = true;
rejectPromise(promise, err);
}
}
return true;
} | [
"function",
"handleThenable",
"(",
"promise",
",",
"value",
")",
"{",
"var",
"done",
",",
"then",
";",
"try",
"{",
"if",
"(",
"!",
"(",
"then",
"=",
"utils",
".",
"thenable",
"(",
"value",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"rejectPromise",
"(",
"promise",
",",
"err",
")",
";",
"return",
"true",
";",
"}",
"if",
"(",
"promise",
"===",
"value",
")",
"{",
"rejectPromise",
"(",
"promise",
",",
"new",
"TypeError",
"(",
"'Circular resolution of promises'",
")",
")",
";",
"return",
"true",
";",
"}",
"try",
"{",
"then",
".",
"call",
"(",
"value",
",",
"function",
"(",
"subValue",
")",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"done",
"=",
"true",
";",
"if",
"(",
"value",
"===",
"subValue",
")",
"{",
"rejectPromise",
"(",
"promise",
",",
"new",
"TypeError",
"(",
"'Circular resolution of promises'",
")",
")",
";",
"return",
";",
"}",
"resolvePromise",
"(",
"promise",
",",
"subValue",
")",
";",
"}",
"}",
",",
"function",
"(",
"subValue",
")",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"done",
"=",
"true",
";",
"rejectPromise",
"(",
"promise",
",",
"subValue",
")",
";",
"}",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"done",
")",
"{",
"done",
"=",
"true",
";",
"rejectPromise",
"(",
"promise",
",",
"err",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| When a promise resolves with another thenable, this function handles delegating control and passing around values @param {child} the child promise that values will be passed to @param {value} the thenable value from the previous promise @return boolean | [
"When",
"a",
"promise",
"resolves",
"with",
"another",
"thenable",
"this",
"function",
"handles",
"delegating",
"control",
"and",
"passing",
"around",
"values"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L246-L298 | train |
mrbar42/trixion | src/polyfill/promise.js | fulfillPromise | function fulfillPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FULFILLED);
invokeFunctions(promise);
});
} | javascript | function fulfillPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FULFILLED);
invokeFunctions(promise);
});
} | [
"function",
"fulfillPromise",
"(",
"promise",
",",
"value",
")",
"{",
"if",
"(",
"promise",
".",
"state",
"!==",
"PENDING",
")",
"{",
"return",
";",
"}",
"setValue",
"(",
"promise",
",",
"value",
")",
";",
"setState",
"(",
"promise",
",",
"UNFULFILLED",
")",
";",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"setState",
"(",
"promise",
",",
"FULFILLED",
")",
";",
"invokeFunctions",
"(",
"promise",
")",
";",
"}",
")",
";",
"}"
]
| Fulfill the given promise @param {promise} the promise to resolve @param {value} the value of the promise @return void | [
"Fulfill",
"the",
"given",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L307-L317 | train |
mrbar42/trixion | src/polyfill/promise.js | rejectPromise | function rejectPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FAILED);
invokeFunctions(promise);
});
} | javascript | function rejectPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FAILED);
invokeFunctions(promise);
});
} | [
"function",
"rejectPromise",
"(",
"promise",
",",
"value",
")",
"{",
"if",
"(",
"promise",
".",
"state",
"!==",
"PENDING",
")",
"{",
"return",
";",
"}",
"setValue",
"(",
"promise",
",",
"value",
")",
";",
"setState",
"(",
"promise",
",",
"UNFULFILLED",
")",
";",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"setState",
"(",
"promise",
",",
"FAILED",
")",
";",
"invokeFunctions",
"(",
"promise",
")",
";",
"}",
")",
";",
"}"
]
| Reject the given promise @param {promise} the promise to reject @param {value} the value of the promise @return void | [
"Reject",
"the",
"given",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L326-L336 | train |
mrbar42/trixion | src/polyfill/promise.js | setState | function setState(promise, state) {
utils.defineProperty(promise, 'state', {
enumerable: false,
// According to the spec: If the state is UNFULFILLED (0), the state can be changed;
// If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we
// lock the property
configurable: (! state),
writable: false,
value: state
});
} | javascript | function setState(promise, state) {
utils.defineProperty(promise, 'state', {
enumerable: false,
// According to the spec: If the state is UNFULFILLED (0), the state can be changed;
// If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we
// lock the property
configurable: (! state),
writable: false,
value: state
});
} | [
"function",
"setState",
"(",
"promise",
",",
"state",
")",
"{",
"utils",
".",
"defineProperty",
"(",
"promise",
",",
"'state'",
",",
"{",
"enumerable",
":",
"false",
",",
"configurable",
":",
"(",
"!",
"state",
")",
",",
"writable",
":",
"false",
",",
"value",
":",
"state",
"}",
")",
";",
"}"
]
| Set the state of a promise @param {promise} the promise to modify @param {state} the new state @return void | [
"Set",
"the",
"state",
"of",
"a",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L345-L355 | train |
mrbar42/trixion | src/polyfill/promise.js | setValue | function setValue(promise, value) {
utils.defineProperty(promise, 'value', {
enumerable: false,
configurable: false,
writable: false,
value: value
});
} | javascript | function setValue(promise, value) {
utils.defineProperty(promise, 'value', {
enumerable: false,
configurable: false,
writable: false,
value: value
});
} | [
"function",
"setValue",
"(",
"promise",
",",
"value",
")",
"{",
"utils",
".",
"defineProperty",
"(",
"promise",
",",
"'value'",
",",
"{",
"enumerable",
":",
"false",
",",
"configurable",
":",
"false",
",",
"writable",
":",
"false",
",",
"value",
":",
"value",
"}",
")",
";",
"}"
]
| Set the value of a promise @param {promise} the promise to modify @param {value} the value to store @return void | [
"Set",
"the",
"value",
"of",
"a",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L364-L371 | train |
mrbar42/trixion | src/polyfill/promise.js | invokeFunctions | function invokeFunctions(promise) {
var funcs = promise.funcs;
for (var i = 0, c = funcs.length; i < c; i += 3) {
invokeFunction(promise, funcs[i], funcs[i + promise.state]);
}
// Empty out this list of functions as no one function will be called
// more than once, and we don't want to hold them in memory longer than needed
promise.funcs.length = 0;
} | javascript | function invokeFunctions(promise) {
var funcs = promise.funcs;
for (var i = 0, c = funcs.length; i < c; i += 3) {
invokeFunction(promise, funcs[i], funcs[i + promise.state]);
}
// Empty out this list of functions as no one function will be called
// more than once, and we don't want to hold them in memory longer than needed
promise.funcs.length = 0;
} | [
"function",
"invokeFunctions",
"(",
"promise",
")",
"{",
"var",
"funcs",
"=",
"promise",
".",
"funcs",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"c",
"=",
"funcs",
".",
"length",
";",
"i",
"<",
"c",
";",
"i",
"+=",
"3",
")",
"{",
"invokeFunction",
"(",
"promise",
",",
"funcs",
"[",
"i",
"]",
",",
"funcs",
"[",
"i",
"+",
"promise",
".",
"state",
"]",
")",
";",
"}",
"promise",
".",
"funcs",
".",
"length",
"=",
"0",
";",
"}"
]
| Invoke all existing functions queued up on the promise @param {promise} the promise to run functions for @return void | [
"Invoke",
"all",
"existing",
"functions",
"queued",
"up",
"on",
"the",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L379-L389 | train |
mrbar42/trixion | src/polyfill/promise.js | invokeFunction | function invokeFunction(promise, child, func) {
var value = promise.value;
var state = promise.state;
// If we have a function to run, run it
if (typeof func === 'function') {
try {
value = func(value);
} catch (err) {
rejectPromise(child, err);
return;
}
resolvePromise(child, value);
}
else if (state === FULFILLED) {
resolvePromise(child, value);
}
else if (state === FAILED) {
rejectPromise(child, value);
}
} | javascript | function invokeFunction(promise, child, func) {
var value = promise.value;
var state = promise.state;
// If we have a function to run, run it
if (typeof func === 'function') {
try {
value = func(value);
} catch (err) {
rejectPromise(child, err);
return;
}
resolvePromise(child, value);
}
else if (state === FULFILLED) {
resolvePromise(child, value);
}
else if (state === FAILED) {
rejectPromise(child, value);
}
} | [
"function",
"invokeFunction",
"(",
"promise",
",",
"child",
",",
"func",
")",
"{",
"var",
"value",
"=",
"promise",
".",
"value",
";",
"var",
"state",
"=",
"promise",
".",
"state",
";",
"if",
"(",
"typeof",
"func",
"===",
"'function'",
")",
"{",
"try",
"{",
"value",
"=",
"func",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"rejectPromise",
"(",
"child",
",",
"err",
")",
";",
"return",
";",
"}",
"resolvePromise",
"(",
"child",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"state",
"===",
"FULFILLED",
")",
"{",
"resolvePromise",
"(",
"child",
",",
"value",
")",
";",
"}",
"else",
"if",
"(",
"state",
"===",
"FAILED",
")",
"{",
"rejectPromise",
"(",
"child",
",",
"value",
")",
";",
"}",
"}"
]
| Invoke one specific function for the promise @param {promise} the promise the function belongs too (that .then was called on) @param {child} the promise return from the .then call; the next in line @param {func} the function to call @return void | [
"Invoke",
"one",
"specific",
"function",
"for",
"the",
"promise"
]
| 6ba7e17b137d737cad4877894456175c93be28ed | https://github.com/mrbar42/trixion/blob/6ba7e17b137d737cad4877894456175c93be28ed/src/polyfill/promise.js#L399-L422 | train |
savantly-net/ngx-graphexp | examples/app/main.bundle.js | function () {
// Existing active nodes
var allNodes = this.graphRoot.selectAll('g').filter('.active_node')
.data(this.nodeModels, function (n) {
return n.id;
});
return allNodes;
} | javascript | function () {
// Existing active nodes
var allNodes = this.graphRoot.selectAll('g').filter('.active_node')
.data(this.nodeModels, function (n) {
return n.id;
});
return allNodes;
} | [
"function",
"(",
")",
"{",
"var",
"allNodes",
"=",
"this",
".",
"graphRoot",
".",
"selectAll",
"(",
"'g'",
")",
".",
"filter",
"(",
"'.active_node'",
")",
".",
"data",
"(",
"this",
".",
"nodeModels",
",",
"function",
"(",
"n",
")",
"{",
"return",
"n",
".",
"id",
";",
"}",
")",
";",
"return",
"allNodes",
";",
"}"
]
| get all active nodes in the graph | [
"get",
"all",
"active",
"nodes",
"in",
"the",
"graph"
]
| f992861965dd935b45f78cb0c80c574a2cee5b13 | https://github.com/savantly-net/ngx-graphexp/blob/f992861965dd935b45f78cb0c80c574a2cee5b13/examples/app/main.bundle.js#L1250-L1257 | train |
|
FamilySearch/fs-js-lite | src/middleware/request/requestInterval.js | checkQueue | function checkQueue() {
if(!inInterval()) {
if(requestQueue.length) {
var next = requestQueue.shift();
sendRequest(next);
} else if(timer) {
clearInterval(timer); // No need to leave the timer running if we don't have any requests.
}
}
} | javascript | function checkQueue() {
if(!inInterval()) {
if(requestQueue.length) {
var next = requestQueue.shift();
sendRequest(next);
} else if(timer) {
clearInterval(timer); // No need to leave the timer running if we don't have any requests.
}
}
} | [
"function",
"checkQueue",
"(",
")",
"{",
"if",
"(",
"!",
"inInterval",
"(",
")",
")",
"{",
"if",
"(",
"requestQueue",
".",
"length",
")",
"{",
"var",
"next",
"=",
"requestQueue",
".",
"shift",
"(",
")",
";",
"sendRequest",
"(",
"next",
")",
";",
"}",
"else",
"if",
"(",
"timer",
")",
"{",
"clearInterval",
"(",
"timer",
")",
";",
"}",
"}",
"}"
]
| Check to see if we're ready to send any requests. | [
"Check",
"to",
"see",
"if",
"we",
"re",
"ready",
"to",
"send",
"any",
"requests",
"."
]
| 49a638196a3ff1121060cbd3d9c1f318c23bc0ab | https://github.com/FamilySearch/fs-js-lite/blob/49a638196a3ff1121060cbd3d9c1f318c23bc0ab/src/middleware/request/requestInterval.js#L38-L47 | train |
pazams/vivalid | lib/input.js | Input | function Input(el, validatorsNameOptionsTuples, onInputValidationResult, isBlurOnly) {
if (validInputTagNames.indexOf(el.nodeName.toLowerCase()) === -1) {
throw 'only operates on the following html tags: ' + validInputTagNames.toString();
}
this._el = el;
this._validatorsNameOptionsTuples = validatorsNameOptionsTuples;
this._onInputValidationResult = onInputValidationResult || defaultOnInputValidationResult;
this._isBlurOnly = isBlurOnly;
this._validators = buildValidators();
this._inputState = new InputState();
this._elName = el.nodeName.toLowerCase();
this._elType = el.type;
this._isKeyed = (this._elName === 'textarea' || keyStrokedInputTypes.indexOf(this._elType) > -1);
this._runValidatorsBounded = this._runValidators.bind(this);
this._initListeners();
function buildValidators() {
var result = [];
validatorsNameOptionsTuples.forEach(function(validatorsNameOptionsTuple) {
var validatorName = validatorsNameOptionsTuple[0];
var validatorOptions = validatorsNameOptionsTuple[1];
result.push({
name: validatorName,
run: validatorRepo.build(validatorName, validatorOptions)
});
});
return result;
}
/** The default {@link _internal.onInputValidationResult onInputValidationResult} used when {@link vivalid.Input} is initiated without a 3rd parameter
* @name defaultOnInputValidationResult
* @function
* @memberof! _internal
*/
function defaultOnInputValidationResult(el, validationsResult, validatorName, stateEnum) {
var errorDiv;
// for radio buttons and checkboxes: get the last element in group by name
if ((el.nodeName.toLowerCase() === 'input' && (el.type === 'radio' || el.type === 'checkbox'))) {
var getAllByName = el.parentNode.querySelectorAll('input[name="' + el.name + '"]');
el = getAllByName.item(getAllByName.length - 1);
}
if (validationsResult.stateEnum === stateEnum.invalid) {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.textContent = validationsResult.message;
} else {
appendNewErrorDiv(el, validationsResult.message);
}
el.style.borderStyle = "solid";
el.style.borderColor = "#ff0000";
$$.addClass(el, "vivalid-error-input");
} else {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.parentNode.removeChild(errorDiv);
el.style.borderStyle = "";
el.style.borderColor = "";
$$.removeClass(el, "vivalid-error-input");
}
}
function getExistingErrorDiv(el) {
if (el.nextElementSibling && el.nextElementSibling.className === "vivalid-error") {
return el.nextElementSibling;
}
}
function appendNewErrorDiv(el, message) {
errorDiv = document.createElement("DIV");
errorDiv.className = "vivalid-error";
errorDiv.style.color = "#ff0000";
var t = document.createTextNode(validationsResult.message);
errorDiv.appendChild(t);
el.parentNode.insertBefore(errorDiv, el.nextElementSibling);
}
}
} | javascript | function Input(el, validatorsNameOptionsTuples, onInputValidationResult, isBlurOnly) {
if (validInputTagNames.indexOf(el.nodeName.toLowerCase()) === -1) {
throw 'only operates on the following html tags: ' + validInputTagNames.toString();
}
this._el = el;
this._validatorsNameOptionsTuples = validatorsNameOptionsTuples;
this._onInputValidationResult = onInputValidationResult || defaultOnInputValidationResult;
this._isBlurOnly = isBlurOnly;
this._validators = buildValidators();
this._inputState = new InputState();
this._elName = el.nodeName.toLowerCase();
this._elType = el.type;
this._isKeyed = (this._elName === 'textarea' || keyStrokedInputTypes.indexOf(this._elType) > -1);
this._runValidatorsBounded = this._runValidators.bind(this);
this._initListeners();
function buildValidators() {
var result = [];
validatorsNameOptionsTuples.forEach(function(validatorsNameOptionsTuple) {
var validatorName = validatorsNameOptionsTuple[0];
var validatorOptions = validatorsNameOptionsTuple[1];
result.push({
name: validatorName,
run: validatorRepo.build(validatorName, validatorOptions)
});
});
return result;
}
/** The default {@link _internal.onInputValidationResult onInputValidationResult} used when {@link vivalid.Input} is initiated without a 3rd parameter
* @name defaultOnInputValidationResult
* @function
* @memberof! _internal
*/
function defaultOnInputValidationResult(el, validationsResult, validatorName, stateEnum) {
var errorDiv;
// for radio buttons and checkboxes: get the last element in group by name
if ((el.nodeName.toLowerCase() === 'input' && (el.type === 'radio' || el.type === 'checkbox'))) {
var getAllByName = el.parentNode.querySelectorAll('input[name="' + el.name + '"]');
el = getAllByName.item(getAllByName.length - 1);
}
if (validationsResult.stateEnum === stateEnum.invalid) {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.textContent = validationsResult.message;
} else {
appendNewErrorDiv(el, validationsResult.message);
}
el.style.borderStyle = "solid";
el.style.borderColor = "#ff0000";
$$.addClass(el, "vivalid-error-input");
} else {
errorDiv = getExistingErrorDiv(el);
if (errorDiv) {
errorDiv.parentNode.removeChild(errorDiv);
el.style.borderStyle = "";
el.style.borderColor = "";
$$.removeClass(el, "vivalid-error-input");
}
}
function getExistingErrorDiv(el) {
if (el.nextElementSibling && el.nextElementSibling.className === "vivalid-error") {
return el.nextElementSibling;
}
}
function appendNewErrorDiv(el, message) {
errorDiv = document.createElement("DIV");
errorDiv.className = "vivalid-error";
errorDiv.style.color = "#ff0000";
var t = document.createTextNode(validationsResult.message);
errorDiv.appendChild(t);
el.parentNode.insertBefore(errorDiv, el.nextElementSibling);
}
}
} | [
"function",
"Input",
"(",
"el",
",",
"validatorsNameOptionsTuples",
",",
"onInputValidationResult",
",",
"isBlurOnly",
")",
"{",
"if",
"(",
"validInputTagNames",
".",
"indexOf",
"(",
"el",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"'only operates on the following html tags: '",
"+",
"validInputTagNames",
".",
"toString",
"(",
")",
";",
"}",
"this",
".",
"_el",
"=",
"el",
";",
"this",
".",
"_validatorsNameOptionsTuples",
"=",
"validatorsNameOptionsTuples",
";",
"this",
".",
"_onInputValidationResult",
"=",
"onInputValidationResult",
"||",
"defaultOnInputValidationResult",
";",
"this",
".",
"_isBlurOnly",
"=",
"isBlurOnly",
";",
"this",
".",
"_validators",
"=",
"buildValidators",
"(",
")",
";",
"this",
".",
"_inputState",
"=",
"new",
"InputState",
"(",
")",
";",
"this",
".",
"_elName",
"=",
"el",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
";",
"this",
".",
"_elType",
"=",
"el",
".",
"type",
";",
"this",
".",
"_isKeyed",
"=",
"(",
"this",
".",
"_elName",
"===",
"'textarea'",
"||",
"keyStrokedInputTypes",
".",
"indexOf",
"(",
"this",
".",
"_elType",
")",
">",
"-",
"1",
")",
";",
"this",
".",
"_runValidatorsBounded",
"=",
"this",
".",
"_runValidators",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"_initListeners",
"(",
")",
";",
"function",
"buildValidators",
"(",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"validatorsNameOptionsTuples",
".",
"forEach",
"(",
"function",
"(",
"validatorsNameOptionsTuple",
")",
"{",
"var",
"validatorName",
"=",
"validatorsNameOptionsTuple",
"[",
"0",
"]",
";",
"var",
"validatorOptions",
"=",
"validatorsNameOptionsTuple",
"[",
"1",
"]",
";",
"result",
".",
"push",
"(",
"{",
"name",
":",
"validatorName",
",",
"run",
":",
"validatorRepo",
".",
"build",
"(",
"validatorName",
",",
"validatorOptions",
")",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
"function",
"defaultOnInputValidationResult",
"(",
"el",
",",
"validationsResult",
",",
"validatorName",
",",
"stateEnum",
")",
"{",
"var",
"errorDiv",
";",
"if",
"(",
"(",
"el",
".",
"nodeName",
".",
"toLowerCase",
"(",
")",
"===",
"'input'",
"&&",
"(",
"el",
".",
"type",
"===",
"'radio'",
"||",
"el",
".",
"type",
"===",
"'checkbox'",
")",
")",
")",
"{",
"var",
"getAllByName",
"=",
"el",
".",
"parentNode",
".",
"querySelectorAll",
"(",
"'input[name=\"'",
"+",
"el",
".",
"name",
"+",
"'\"]'",
")",
";",
"el",
"=",
"getAllByName",
".",
"item",
"(",
"getAllByName",
".",
"length",
"-",
"1",
")",
";",
"}",
"if",
"(",
"validationsResult",
".",
"stateEnum",
"===",
"stateEnum",
".",
"invalid",
")",
"{",
"errorDiv",
"=",
"getExistingErrorDiv",
"(",
"el",
")",
";",
"if",
"(",
"errorDiv",
")",
"{",
"errorDiv",
".",
"textContent",
"=",
"validationsResult",
".",
"message",
";",
"}",
"else",
"{",
"appendNewErrorDiv",
"(",
"el",
",",
"validationsResult",
".",
"message",
")",
";",
"}",
"el",
".",
"style",
".",
"borderStyle",
"=",
"\"solid\"",
";",
"el",
".",
"style",
".",
"borderColor",
"=",
"\"#ff0000\"",
";",
"$$",
".",
"addClass",
"(",
"el",
",",
"\"vivalid-error-input\"",
")",
";",
"}",
"else",
"{",
"errorDiv",
"=",
"getExistingErrorDiv",
"(",
"el",
")",
";",
"if",
"(",
"errorDiv",
")",
"{",
"errorDiv",
".",
"parentNode",
".",
"removeChild",
"(",
"errorDiv",
")",
";",
"el",
".",
"style",
".",
"borderStyle",
"=",
"\"\"",
";",
"el",
".",
"style",
".",
"borderColor",
"=",
"\"\"",
";",
"$$",
".",
"removeClass",
"(",
"el",
",",
"\"vivalid-error-input\"",
")",
";",
"}",
"}",
"function",
"getExistingErrorDiv",
"(",
"el",
")",
"{",
"if",
"(",
"el",
".",
"nextElementSibling",
"&&",
"el",
".",
"nextElementSibling",
".",
"className",
"===",
"\"vivalid-error\"",
")",
"{",
"return",
"el",
".",
"nextElementSibling",
";",
"}",
"}",
"function",
"appendNewErrorDiv",
"(",
"el",
",",
"message",
")",
"{",
"errorDiv",
"=",
"document",
".",
"createElement",
"(",
"\"DIV\"",
")",
";",
"errorDiv",
".",
"className",
"=",
"\"vivalid-error\"",
";",
"errorDiv",
".",
"style",
".",
"color",
"=",
"\"#ff0000\"",
";",
"var",
"t",
"=",
"document",
".",
"createTextNode",
"(",
"validationsResult",
".",
"message",
")",
";",
"errorDiv",
".",
"appendChild",
"(",
"t",
")",
";",
"el",
".",
"parentNode",
".",
"insertBefore",
"(",
"errorDiv",
",",
"el",
".",
"nextElementSibling",
")",
";",
"}",
"}",
"}"
]
| creates a new Input object wrapping around a DOM object.
@memberof! vivalid
@class
@example new Input(document.getElementById('Name'), [['required',{msg: 'custom required message'}],['max',{max: 10}]])
@param {HTMLElement} el the DOM object to wrap. For radios and checkboxes, pass only 1 element- the class will find it's siblings with the same name attribute.
@param {_internal.validatorsNameOptionsTuple[]} validatorsNameOptionsTuples <b> the order matters- the input's state is the first {@link _internal.validatorsNameOptionsTuple validatorsNameOptionsTuple} that evulates to a non-valid (pending or invalid) state. </b>
@param {function} [onInputValidationResult] Signature of {@link _internal.onInputValidationResult onInputValidationResult}. A function to handle an input state or message change. If not passed, {@link _internal.defaultOnInputValidationResult defaultOnInputValidationResult} will be used.
@param {boolean} isBlurOnly if true, doesn't not trigger validation on 'input' or 'change' events. | [
"creates",
"a",
"new",
"Input",
"object",
"wrapping",
"around",
"a",
"DOM",
"object",
"."
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/input.js#L21-L113 | train |
basic-web-components/basic-web-components | packages/basic-component-mixins/src/TimerSelectionMixin.js | selectNextWithWrap | function selectNextWithWrap(element) {
const items = element.items;
if (items && items.length > 0) {
if (element.selectedIndex == null || element.selectedIndex === items.length - 1) {
element.selectFirst();
} else {
element.selectNext();
}
}
} | javascript | function selectNextWithWrap(element) {
const items = element.items;
if (items && items.length > 0) {
if (element.selectedIndex == null || element.selectedIndex === items.length - 1) {
element.selectFirst();
} else {
element.selectNext();
}
}
} | [
"function",
"selectNextWithWrap",
"(",
"element",
")",
"{",
"const",
"items",
"=",
"element",
".",
"items",
";",
"if",
"(",
"items",
"&&",
"items",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"element",
".",
"selectedIndex",
"==",
"null",
"||",
"element",
".",
"selectedIndex",
"===",
"items",
".",
"length",
"-",
"1",
")",
"{",
"element",
".",
"selectFirst",
"(",
")",
";",
"}",
"else",
"{",
"element",
".",
"selectNext",
"(",
")",
";",
"}",
"}",
"}"
]
| Select the next item, wrapping to first item if necessary. | [
"Select",
"the",
"next",
"item",
"wrapping",
"to",
"first",
"item",
"if",
"necessary",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/TimerSelectionMixin.js#L155-L164 | train |
abdulhannanali/jest-nyan-reporter | helpers.js | printFailureMessages | function printFailureMessages(results) {
if (!results.numTotalTests || !results.numFailedTests) {
return;
}
console.log(color('bright fail', ` ${symbols.err} Failed Tests:`));
console.log('\n');
results.testResults.forEach(({failureMessage}) => {
if (failureMessage) {
console.log(failureMessage);
}
});
process.stdout.write('\n');
} | javascript | function printFailureMessages(results) {
if (!results.numTotalTests || !results.numFailedTests) {
return;
}
console.log(color('bright fail', ` ${symbols.err} Failed Tests:`));
console.log('\n');
results.testResults.forEach(({failureMessage}) => {
if (failureMessage) {
console.log(failureMessage);
}
});
process.stdout.write('\n');
} | [
"function",
"printFailureMessages",
"(",
"results",
")",
"{",
"if",
"(",
"!",
"results",
".",
"numTotalTests",
"||",
"!",
"results",
".",
"numFailedTests",
")",
"{",
"return",
";",
"}",
"console",
".",
"log",
"(",
"color",
"(",
"'bright fail'",
",",
"`",
"${",
"symbols",
".",
"err",
"}",
"`",
")",
")",
";",
"console",
".",
"log",
"(",
"'\\n'",
")",
";",
"\\n",
"results",
".",
"testResults",
".",
"forEach",
"(",
"(",
"{",
"failureMessage",
"}",
")",
"=>",
"{",
"if",
"(",
"failureMessage",
")",
"{",
"console",
".",
"log",
"(",
"failureMessage",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Prints failure messsages for the reporters to be displayed | [
"Prints",
"failure",
"messsages",
"for",
"the",
"reporters",
"to",
"be",
"displayed"
]
| 28f121bdb64a340655f3bc6151ff02b55c3d8fd7 | https://github.com/abdulhannanali/jest-nyan-reporter/blob/28f121bdb64a340655f3bc6151ff02b55c3d8fd7/helpers.js#L118-L133 | train |
basic-web-components/basic-web-components | Gruntfile.js | buildDocsList | function buildDocsList() {
const packagesWithoutBuiltDocs = [
'basic-component-mixins',
'basic-web-components'
];
const ary = allPackages.filter(item => {
return packagesWithoutBuiltDocs.indexOf(item) < 0;
}).map(item => {
return {
src: `packages/${item}/src/*.js`,
dest: `packages/${item}/README.md`};
});
return ary.concat(buildMixinsDocsList());
} | javascript | function buildDocsList() {
const packagesWithoutBuiltDocs = [
'basic-component-mixins',
'basic-web-components'
];
const ary = allPackages.filter(item => {
return packagesWithoutBuiltDocs.indexOf(item) < 0;
}).map(item => {
return {
src: `packages/${item}/src/*.js`,
dest: `packages/${item}/README.md`};
});
return ary.concat(buildMixinsDocsList());
} | [
"function",
"buildDocsList",
"(",
")",
"{",
"const",
"packagesWithoutBuiltDocs",
"=",
"[",
"'basic-component-mixins'",
",",
"'basic-web-components'",
"]",
";",
"const",
"ary",
"=",
"allPackages",
".",
"filter",
"(",
"item",
"=>",
"{",
"return",
"packagesWithoutBuiltDocs",
".",
"indexOf",
"(",
"item",
")",
"<",
"0",
";",
"}",
")",
".",
"map",
"(",
"item",
"=>",
"{",
"return",
"{",
"src",
":",
"`",
"${",
"item",
"}",
"`",
",",
"dest",
":",
"`",
"${",
"item",
"}",
"`",
"}",
";",
"}",
")",
";",
"return",
"ary",
".",
"concat",
"(",
"buildMixinsDocsList",
"(",
")",
")",
";",
"}"
]
| Build the global docsList array for use in building the package's README.md documentation | [
"Build",
"the",
"global",
"docsList",
"array",
"for",
"use",
"in",
"building",
"the",
"package",
"s",
"README",
".",
"md",
"documentation"
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/Gruntfile.js#L50-L64 | train |
basic-web-components/basic-web-components | Gruntfile.js | buildMixinsDocsList | function buildMixinsDocsList() {
return fs.readdirSync('packages/basic-component-mixins/src').filter(file => {
return file.indexOf('.js') == file.length - 3;
}).map(file => {
const fileRoot = file.replace('.js', '');
return {
src: `packages/basic-component-mixins/src/${file}`,
dest: `packages/basic-component-mixins/docs/${fileRoot}.md` };
});
} | javascript | function buildMixinsDocsList() {
return fs.readdirSync('packages/basic-component-mixins/src').filter(file => {
return file.indexOf('.js') == file.length - 3;
}).map(file => {
const fileRoot = file.replace('.js', '');
return {
src: `packages/basic-component-mixins/src/${file}`,
dest: `packages/basic-component-mixins/docs/${fileRoot}.md` };
});
} | [
"function",
"buildMixinsDocsList",
"(",
")",
"{",
"return",
"fs",
".",
"readdirSync",
"(",
"'packages/basic-component-mixins/src'",
")",
".",
"filter",
"(",
"file",
"=>",
"{",
"return",
"file",
".",
"indexOf",
"(",
"'.js'",
")",
"==",
"file",
".",
"length",
"-",
"3",
";",
"}",
")",
".",
"map",
"(",
"file",
"=>",
"{",
"const",
"fileRoot",
"=",
"file",
".",
"replace",
"(",
"'.js'",
",",
"''",
")",
";",
"return",
"{",
"src",
":",
"`",
"${",
"file",
"}",
"`",
",",
"dest",
":",
"`",
"${",
"fileRoot",
"}",
"`",
"}",
";",
"}",
")",
";",
"}"
]
| Build the portion of docsList that represents the individual source files within the basic-component-mixins directory. | [
"Build",
"the",
"portion",
"of",
"docsList",
"that",
"represents",
"the",
"individual",
"source",
"files",
"within",
"the",
"basic",
"-",
"component",
"-",
"mixins",
"directory",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/Gruntfile.js#L71-L80 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/custom-elements/src/custom-elements.js | _createElement | function _createElement(doc, tagName, options, callConstructor) {
const customElements = _customElements();
const element = options ? _origCreateElement.call(doc, tagName, options) :
_origCreateElement.call(doc, tagName);
const definition = customElements._definitions.get(tagName.toLowerCase());
if (definition) {
customElements._upgradeElement(element, definition, callConstructor);
}
customElements._observeRoot(element);
return element;
} | javascript | function _createElement(doc, tagName, options, callConstructor) {
const customElements = _customElements();
const element = options ? _origCreateElement.call(doc, tagName, options) :
_origCreateElement.call(doc, tagName);
const definition = customElements._definitions.get(tagName.toLowerCase());
if (definition) {
customElements._upgradeElement(element, definition, callConstructor);
}
customElements._observeRoot(element);
return element;
} | [
"function",
"_createElement",
"(",
"doc",
",",
"tagName",
",",
"options",
",",
"callConstructor",
")",
"{",
"const",
"customElements",
"=",
"_customElements",
"(",
")",
";",
"const",
"element",
"=",
"options",
"?",
"_origCreateElement",
".",
"call",
"(",
"doc",
",",
"tagName",
",",
"options",
")",
":",
"_origCreateElement",
".",
"call",
"(",
"doc",
",",
"tagName",
")",
";",
"const",
"definition",
"=",
"customElements",
".",
"_definitions",
".",
"get",
"(",
"tagName",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"definition",
")",
"{",
"customElements",
".",
"_upgradeElement",
"(",
"element",
",",
"definition",
",",
"callConstructor",
")",
";",
"}",
"customElements",
".",
"_observeRoot",
"(",
"element",
")",
";",
"return",
"element",
";",
"}"
]
| Creates a new element and upgrades it if it's a custom element.
@param {!Document} doc
@param {!string} tagName
@param {Object|undefined} options
@param {boolean} callConstructor whether or not to call the elements
constructor after upgrading. If an element is created by calling its
constructor, then `callConstructor` should be false to prevent double
initialization. | [
"Creates",
"a",
"new",
"element",
"and",
"upgrades",
"it",
"if",
"it",
"s",
"a",
"custom",
"element",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/custom-elements/src/custom-elements.js#L698-L708 | train |
micromatch/parse-glob | index.js | dotdir | function dotdir(base) {
if (base.indexOf('/.') !== -1) {
return true;
}
if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
return true;
}
return false;
} | javascript | function dotdir(base) {
if (base.indexOf('/.') !== -1) {
return true;
}
if (base.charAt(0) === '.' && base.charAt(1) !== '/') {
return true;
}
return false;
} | [
"function",
"dotdir",
"(",
"base",
")",
"{",
"if",
"(",
"base",
".",
"indexOf",
"(",
"'/.'",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"base",
".",
"charAt",
"(",
"0",
")",
"===",
"'.'",
"&&",
"base",
".",
"charAt",
"(",
"1",
")",
"!==",
"'/'",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Returns true if the glob matches dot-directories.
@param {Object} `tok` The tokens object
@param {Object} `path` The path object
@return {Object} | [
"Returns",
"true",
"if",
"the",
"glob",
"matches",
"dot",
"-",
"directories",
"."
]
| 9bfccb63acdeb3b1ed62035b3adef0e5081d8fc6 | https://github.com/micromatch/parse-glob/blob/9bfccb63acdeb3b1ed62035b3adef0e5081d8fc6/index.js#L111-L119 | train |
laardee/serverless-authentication | src/profile.js | formatAddress | function formatAddress(address) {
const result = address
if (result) {
result.formatted =
`${result.street_address}\n${result.postal_code} ${result.locality}\n${result.country}`
return result
}
return null
} | javascript | function formatAddress(address) {
const result = address
if (result) {
result.formatted =
`${result.street_address}\n${result.postal_code} ${result.locality}\n${result.country}`
return result
}
return null
} | [
"function",
"formatAddress",
"(",
"address",
")",
"{",
"const",
"result",
"=",
"address",
"if",
"(",
"result",
")",
"{",
"result",
".",
"formatted",
"=",
"`",
"${",
"result",
".",
"street_address",
"}",
"\\n",
"${",
"result",
".",
"postal_code",
"}",
"${",
"result",
".",
"locality",
"}",
"\\n",
"${",
"result",
".",
"country",
"}",
"`",
"return",
"result",
"}",
"return",
"null",
"}"
]
| Profile class that normalizes profile data fetched from authentication provider | [
"Profile",
"class",
"that",
"normalizes",
"profile",
"data",
"fetched",
"from",
"authentication",
"provider"
]
| 92026681c88020f0282939ec6f1b9a82da51f537 | https://github.com/laardee/serverless-authentication/blob/92026681c88020f0282939ec6f1b9a82da51f537/src/profile.js#L5-L13 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | arrayCopyChildNodes | function arrayCopyChildNodes(parent) {
var copy=[], i=0;
for (var n=parent.firstChild; n; n=n.nextSibling) {
copy[i++] = n;
}
return copy;
} | javascript | function arrayCopyChildNodes(parent) {
var copy=[], i=0;
for (var n=parent.firstChild; n; n=n.nextSibling) {
copy[i++] = n;
}
return copy;
} | [
"function",
"arrayCopyChildNodes",
"(",
"parent",
")",
"{",
"var",
"copy",
"=",
"[",
"]",
",",
"i",
"=",
"0",
";",
"for",
"(",
"var",
"n",
"=",
"parent",
".",
"firstChild",
";",
"n",
";",
"n",
"=",
"n",
".",
"nextSibling",
")",
"{",
"copy",
"[",
"i",
"++",
"]",
"=",
"n",
";",
"}",
"return",
"copy",
";",
"}"
]
| sad but faster than slice... | [
"sad",
"but",
"faster",
"than",
"slice",
"..."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L390-L396 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | saveChildNodes$1 | function saveChildNodes$1(node) {
if (!this.hasChildNodes(node)) {
node.__dom = node.__dom || {};
node.__dom.firstChild = node.firstChild;
node.__dom.lastChild = node.lastChild;
var c$ = node.__dom.childNodes = tree.arrayCopyChildNodes(node);
for (var i=0, n; (i<c$.length) && (n=c$[i]); i++) {
n.__dom = n.__dom || {};
n.__dom.parentNode = node;
n.__dom.nextSibling = c$[i+1] || null;
n.__dom.previousSibling = c$[i-1] || null;
common.patchNode(n);
}
}
} | javascript | function saveChildNodes$1(node) {
if (!this.hasChildNodes(node)) {
node.__dom = node.__dom || {};
node.__dom.firstChild = node.firstChild;
node.__dom.lastChild = node.lastChild;
var c$ = node.__dom.childNodes = tree.arrayCopyChildNodes(node);
for (var i=0, n; (i<c$.length) && (n=c$[i]); i++) {
n.__dom = n.__dom || {};
n.__dom.parentNode = node;
n.__dom.nextSibling = c$[i+1] || null;
n.__dom.previousSibling = c$[i-1] || null;
common.patchNode(n);
}
}
} | [
"function",
"saveChildNodes$1",
"(",
"node",
")",
"{",
"if",
"(",
"!",
"this",
".",
"hasChildNodes",
"(",
"node",
")",
")",
"{",
"node",
".",
"__dom",
"=",
"node",
".",
"__dom",
"||",
"{",
"}",
";",
"node",
".",
"__dom",
".",
"firstChild",
"=",
"node",
".",
"firstChild",
";",
"node",
".",
"__dom",
".",
"lastChild",
"=",
"node",
".",
"lastChild",
";",
"var",
"c$",
"=",
"node",
".",
"__dom",
".",
"childNodes",
"=",
"tree",
".",
"arrayCopyChildNodes",
"(",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
";",
"(",
"i",
"<",
"c$",
".",
"length",
")",
"&&",
"(",
"n",
"=",
"c$",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"n",
".",
"__dom",
"=",
"n",
".",
"__dom",
"||",
"{",
"}",
";",
"n",
".",
"__dom",
".",
"parentNode",
"=",
"node",
";",
"n",
".",
"__dom",
".",
"nextSibling",
"=",
"c$",
"[",
"i",
"+",
"1",
"]",
"||",
"null",
";",
"n",
".",
"__dom",
".",
"previousSibling",
"=",
"c$",
"[",
"i",
"-",
"1",
"]",
"||",
"null",
";",
"common",
".",
"patchNode",
"(",
"n",
")",
";",
"}",
"}",
"}"
]
| Capture the list of light children. It's important to do this before we start transforming the DOM into "rendered" state. Children may be added to this list dynamically. It will be treated as the source of truth for the light children of the element. This element's actual children will be treated as the rendered state once this function has been called. | [
"Capture",
"the",
"list",
"of",
"light",
"children",
".",
"It",
"s",
"important",
"to",
"do",
"this",
"before",
"we",
"start",
"transforming",
"the",
"DOM",
"into",
"rendered",
"state",
".",
"Children",
"may",
"be",
"added",
"to",
"this",
"list",
"dynamically",
".",
"It",
"will",
"be",
"treated",
"as",
"the",
"source",
"of",
"truth",
"for",
"the",
"light",
"children",
"of",
"the",
"element",
".",
"This",
"element",
"s",
"actual",
"children",
"will",
"be",
"treated",
"as",
"the",
"rendered",
"state",
"once",
"this",
"function",
"has",
"been",
"called",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L552-L566 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _elementNeedsDistribution | function _elementNeedsDistribution(element) {
var this$1 = this;
var c$ = tree.Logical.getChildNodes(element);
for (var i=0, c; i < c$.length; i++) {
c = c$[i];
if (this$1._distributor.isInsertionPoint(c)) {
return element.getRootNode();
}
}
} | javascript | function _elementNeedsDistribution(element) {
var this$1 = this;
var c$ = tree.Logical.getChildNodes(element);
for (var i=0, c; i < c$.length; i++) {
c = c$[i];
if (this$1._distributor.isInsertionPoint(c)) {
return element.getRootNode();
}
}
} | [
"function",
"_elementNeedsDistribution",
"(",
"element",
")",
"{",
"var",
"this$1",
"=",
"this",
";",
"var",
"c$",
"=",
"tree",
".",
"Logical",
".",
"getChildNodes",
"(",
"element",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"c",
";",
"i",
"<",
"c$",
".",
"length",
";",
"i",
"++",
")",
"{",
"c",
"=",
"c$",
"[",
"i",
"]",
";",
"if",
"(",
"this$1",
".",
"_distributor",
".",
"isInsertionPoint",
"(",
"c",
")",
")",
"{",
"return",
"element",
".",
"getRootNode",
"(",
")",
";",
"}",
"}",
"}"
]
| Return true if a host's children includes an insertion point that selects selectively | [
"Return",
"true",
"if",
"a",
"host",
"s",
"children",
"includes",
"an",
"insertion",
"point",
"that",
"selects",
"selectively"
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1233-L1243 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _composeTree | function _composeTree() {
var this$1 = this;
this._updateChildNodes(this.host, this._composeNode(this.host));
var p$ = this._insertionPoints || [];
for (var i=0, l=p$.length, p, parent; (i<l) && (p=p$[i]); i++) {
parent = tree.Logical.getParentNode(p);
if ((parent !== this$1.host) && (parent !== this$1)) {
this$1._updateChildNodes(parent, this$1._composeNode(parent));
}
}
} | javascript | function _composeTree() {
var this$1 = this;
this._updateChildNodes(this.host, this._composeNode(this.host));
var p$ = this._insertionPoints || [];
for (var i=0, l=p$.length, p, parent; (i<l) && (p=p$[i]); i++) {
parent = tree.Logical.getParentNode(p);
if ((parent !== this$1.host) && (parent !== this$1)) {
this$1._updateChildNodes(parent, this$1._composeNode(parent));
}
}
} | [
"function",
"_composeTree",
"(",
")",
"{",
"var",
"this$1",
"=",
"this",
";",
"this",
".",
"_updateChildNodes",
"(",
"this",
".",
"host",
",",
"this",
".",
"_composeNode",
"(",
"this",
".",
"host",
")",
")",
";",
"var",
"p$",
"=",
"this",
".",
"_insertionPoints",
"||",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"p$",
".",
"length",
",",
"p",
",",
"parent",
";",
"(",
"i",
"<",
"l",
")",
"&&",
"(",
"p",
"=",
"p$",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"parent",
"=",
"tree",
".",
"Logical",
".",
"getParentNode",
"(",
"p",
")",
";",
"if",
"(",
"(",
"parent",
"!==",
"this$1",
".",
"host",
")",
"&&",
"(",
"parent",
"!==",
"this$1",
")",
")",
"{",
"this$1",
".",
"_updateChildNodes",
"(",
"parent",
",",
"this$1",
".",
"_composeNode",
"(",
"parent",
")",
")",
";",
"}",
"}",
"}"
]
| Reify dom such that it is at its correct rendering position based on logical distribution. | [
"Reify",
"dom",
"such",
"that",
"it",
"is",
"at",
"its",
"correct",
"rendering",
"position",
"based",
"on",
"logical",
"distribution",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1339-L1350 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _composeNode | function _composeNode(node) {
var this$1 = this;
var children = [];
var c$ = tree.Logical.getChildNodes(node.shadyRoot || node);
for (var i = 0; i < c$.length; i++) {
var child = c$[i];
if (this$1._distributor.isInsertionPoint(child)) {
var distributedNodes = child._distributedNodes ||
(child._distributedNodes = []);
for (var j = 0; j < distributedNodes.length; j++) {
var distributedNode = distributedNodes[j];
if (this$1.isFinalDestination(child, distributedNode)) {
children.push(distributedNode);
}
}
} else {
children.push(child);
}
}
return children;
} | javascript | function _composeNode(node) {
var this$1 = this;
var children = [];
var c$ = tree.Logical.getChildNodes(node.shadyRoot || node);
for (var i = 0; i < c$.length; i++) {
var child = c$[i];
if (this$1._distributor.isInsertionPoint(child)) {
var distributedNodes = child._distributedNodes ||
(child._distributedNodes = []);
for (var j = 0; j < distributedNodes.length; j++) {
var distributedNode = distributedNodes[j];
if (this$1.isFinalDestination(child, distributedNode)) {
children.push(distributedNode);
}
}
} else {
children.push(child);
}
}
return children;
} | [
"function",
"_composeNode",
"(",
"node",
")",
"{",
"var",
"this$1",
"=",
"this",
";",
"var",
"children",
"=",
"[",
"]",
";",
"var",
"c$",
"=",
"tree",
".",
"Logical",
".",
"getChildNodes",
"(",
"node",
".",
"shadyRoot",
"||",
"node",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"c$",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"child",
"=",
"c$",
"[",
"i",
"]",
";",
"if",
"(",
"this$1",
".",
"_distributor",
".",
"isInsertionPoint",
"(",
"child",
")",
")",
"{",
"var",
"distributedNodes",
"=",
"child",
".",
"_distributedNodes",
"||",
"(",
"child",
".",
"_distributedNodes",
"=",
"[",
"]",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"distributedNodes",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"distributedNode",
"=",
"distributedNodes",
"[",
"j",
"]",
";",
"if",
"(",
"this$1",
".",
"isFinalDestination",
"(",
"child",
",",
"distributedNode",
")",
")",
"{",
"children",
".",
"push",
"(",
"distributedNode",
")",
";",
"}",
"}",
"}",
"else",
"{",
"children",
".",
"push",
"(",
"child",
")",
";",
"}",
"}",
"return",
"children",
";",
"}"
]
| Returns the list of nodes which should be rendered inside `node`. | [
"Returns",
"the",
"list",
"of",
"nodes",
"which",
"should",
"be",
"rendered",
"inside",
"node",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1353-L1374 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | _updateChildNodes | function _updateChildNodes(container, children) {
var composed = tree.Composed.getChildNodes(container);
var splices = calculateSplices(children, composed);
// process removals
for (var i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) {
for (var j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) {
// check if the node is still where we expect it is before trying
// to remove it; this can happen if we move a node and
// then schedule its previous host for distribution resulting in
// the node being removed here.
if (tree.Composed.getParentNode(n) === container) {
tree.Composed.removeChild(container, n);
}
composed.splice(s.index + d, 1);
}
d -= s.addedCount;
}
// process adds
for (var i$1=0, s$1, next; (i$1<splices.length) && (s$1=splices[i$1]); i$1++) { //eslint-disable-line no-redeclare
next = composed[s$1.index];
for (var j$1=s$1.index, n$1; j$1 < s$1.index + s$1.addedCount; j$1++) {
n$1 = children[j$1];
tree.Composed.insertBefore(container, n$1, next);
// TODO(sorvell): is this splice strictly needed?
composed.splice(j$1, 0, n$1);
}
}
} | javascript | function _updateChildNodes(container, children) {
var composed = tree.Composed.getChildNodes(container);
var splices = calculateSplices(children, composed);
// process removals
for (var i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) {
for (var j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) {
// check if the node is still where we expect it is before trying
// to remove it; this can happen if we move a node and
// then schedule its previous host for distribution resulting in
// the node being removed here.
if (tree.Composed.getParentNode(n) === container) {
tree.Composed.removeChild(container, n);
}
composed.splice(s.index + d, 1);
}
d -= s.addedCount;
}
// process adds
for (var i$1=0, s$1, next; (i$1<splices.length) && (s$1=splices[i$1]); i$1++) { //eslint-disable-line no-redeclare
next = composed[s$1.index];
for (var j$1=s$1.index, n$1; j$1 < s$1.index + s$1.addedCount; j$1++) {
n$1 = children[j$1];
tree.Composed.insertBefore(container, n$1, next);
// TODO(sorvell): is this splice strictly needed?
composed.splice(j$1, 0, n$1);
}
}
} | [
"function",
"_updateChildNodes",
"(",
"container",
",",
"children",
")",
"{",
"var",
"composed",
"=",
"tree",
".",
"Composed",
".",
"getChildNodes",
"(",
"container",
")",
";",
"var",
"splices",
"=",
"calculateSplices",
"(",
"children",
",",
"composed",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"d",
"=",
"0",
",",
"s",
";",
"(",
"i",
"<",
"splices",
".",
"length",
")",
"&&",
"(",
"s",
"=",
"splices",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"n",
";",
"(",
"j",
"<",
"s",
".",
"removed",
".",
"length",
")",
"&&",
"(",
"n",
"=",
"s",
".",
"removed",
"[",
"j",
"]",
")",
";",
"j",
"++",
")",
"{",
"if",
"(",
"tree",
".",
"Composed",
".",
"getParentNode",
"(",
"n",
")",
"===",
"container",
")",
"{",
"tree",
".",
"Composed",
".",
"removeChild",
"(",
"container",
",",
"n",
")",
";",
"}",
"composed",
".",
"splice",
"(",
"s",
".",
"index",
"+",
"d",
",",
"1",
")",
";",
"}",
"d",
"-=",
"s",
".",
"addedCount",
";",
"}",
"for",
"(",
"var",
"i$1",
"=",
"0",
",",
"s$1",
",",
"next",
";",
"(",
"i$1",
"<",
"splices",
".",
"length",
")",
"&&",
"(",
"s$1",
"=",
"splices",
"[",
"i$1",
"]",
")",
";",
"i$1",
"++",
")",
"{",
"next",
"=",
"composed",
"[",
"s$1",
".",
"index",
"]",
";",
"for",
"(",
"var",
"j$1",
"=",
"s$1",
".",
"index",
",",
"n$1",
";",
"j$1",
"<",
"s$1",
".",
"index",
"+",
"s$1",
".",
"addedCount",
";",
"j$1",
"++",
")",
"{",
"n$1",
"=",
"children",
"[",
"j$1",
"]",
";",
"tree",
".",
"Composed",
".",
"insertBefore",
"(",
"container",
",",
"n$1",
",",
"next",
")",
";",
"composed",
".",
"splice",
"(",
"j$1",
",",
"0",
",",
"n$1",
")",
";",
"}",
"}",
"}"
]
| Ensures that the rendered node list inside `container` is `children`. | [
"Ensures",
"that",
"the",
"rendered",
"node",
"list",
"inside",
"container",
"is",
"children",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1382-L1409 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | addNode | function addNode(container, node, ref_node) {
var ownerRoot = this.ownerShadyRootForNode(container);
if (ownerRoot) {
// optimization: special insertion point tracking
if (node.__noInsertionPoint && ownerRoot._clean) {
ownerRoot._skipUpdateInsertionPoints = true;
}
// note: we always need to see if an insertion point is added
// since this saves logical tree info; however, invalidation state
// needs
var ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot);
// invalidate insertion points IFF not already invalid!
if (ipAdded) {
ownerRoot._skipUpdateInsertionPoints = false;
}
}
if (tree.Logical.hasChildNodes(container)) {
tree.Logical.recordInsertBefore(node, container, ref_node);
}
// if not distributing and not adding to host, do a fast path addition
var handled = this._maybeDistribute(node, container, ownerRoot) ||
container.shadyRoot;
return handled;
} | javascript | function addNode(container, node, ref_node) {
var ownerRoot = this.ownerShadyRootForNode(container);
if (ownerRoot) {
// optimization: special insertion point tracking
if (node.__noInsertionPoint && ownerRoot._clean) {
ownerRoot._skipUpdateInsertionPoints = true;
}
// note: we always need to see if an insertion point is added
// since this saves logical tree info; however, invalidation state
// needs
var ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot);
// invalidate insertion points IFF not already invalid!
if (ipAdded) {
ownerRoot._skipUpdateInsertionPoints = false;
}
}
if (tree.Logical.hasChildNodes(container)) {
tree.Logical.recordInsertBefore(node, container, ref_node);
}
// if not distributing and not adding to host, do a fast path addition
var handled = this._maybeDistribute(node, container, ownerRoot) ||
container.shadyRoot;
return handled;
} | [
"function",
"addNode",
"(",
"container",
",",
"node",
",",
"ref_node",
")",
"{",
"var",
"ownerRoot",
"=",
"this",
".",
"ownerShadyRootForNode",
"(",
"container",
")",
";",
"if",
"(",
"ownerRoot",
")",
"{",
"if",
"(",
"node",
".",
"__noInsertionPoint",
"&&",
"ownerRoot",
".",
"_clean",
")",
"{",
"ownerRoot",
".",
"_skipUpdateInsertionPoints",
"=",
"true",
";",
"}",
"var",
"ipAdded",
"=",
"this",
".",
"_maybeAddInsertionPoint",
"(",
"node",
",",
"container",
",",
"ownerRoot",
")",
";",
"if",
"(",
"ipAdded",
")",
"{",
"ownerRoot",
".",
"_skipUpdateInsertionPoints",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"tree",
".",
"Logical",
".",
"hasChildNodes",
"(",
"container",
")",
")",
"{",
"tree",
".",
"Logical",
".",
"recordInsertBefore",
"(",
"node",
",",
"container",
",",
"ref_node",
")",
";",
"}",
"var",
"handled",
"=",
"this",
".",
"_maybeDistribute",
"(",
"node",
",",
"container",
",",
"ownerRoot",
")",
"||",
"container",
".",
"shadyRoot",
";",
"return",
"handled",
";",
"}"
]
| Try to add node. Record logical info, track insertion points, perform distribution iff needed. Return true if the add is handled. | [
"Try",
"to",
"add",
"node",
".",
"Record",
"logical",
"info",
"track",
"insertion",
"points",
"perform",
"distribution",
"iff",
"needed",
".",
"Return",
"true",
"if",
"the",
"add",
"is",
"handled",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L1605-L1628 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/shadydom.min.js | removeChild | function removeChild(node) {
if (tree.Logical.getParentNode(node) !== this) {
throw Error('The node to be removed is not a child of this node: ' +
node);
}
if (!mixinImpl.removeNode(node)) {
// if removing from a shadyRoot, remove form host instead
var container = isShadyRoot(this) ?
this.host :
this;
// not guaranteed to physically be in container; e.g.
// undistributed nodes.
var parent = tree.Composed.getParentNode(node);
if (container === parent) {
tree.Composed.removeChild(container, node);
}
}
mixinImpl._scheduleObserver(this, null, node);
return node;
} | javascript | function removeChild(node) {
if (tree.Logical.getParentNode(node) !== this) {
throw Error('The node to be removed is not a child of this node: ' +
node);
}
if (!mixinImpl.removeNode(node)) {
// if removing from a shadyRoot, remove form host instead
var container = isShadyRoot(this) ?
this.host :
this;
// not guaranteed to physically be in container; e.g.
// undistributed nodes.
var parent = tree.Composed.getParentNode(node);
if (container === parent) {
tree.Composed.removeChild(container, node);
}
}
mixinImpl._scheduleObserver(this, null, node);
return node;
} | [
"function",
"removeChild",
"(",
"node",
")",
"{",
"if",
"(",
"tree",
".",
"Logical",
".",
"getParentNode",
"(",
"node",
")",
"!==",
"this",
")",
"{",
"throw",
"Error",
"(",
"'The node to be removed is not a child of this node: '",
"+",
"node",
")",
";",
"}",
"if",
"(",
"!",
"mixinImpl",
".",
"removeNode",
"(",
"node",
")",
")",
"{",
"var",
"container",
"=",
"isShadyRoot",
"(",
"this",
")",
"?",
"this",
".",
"host",
":",
"this",
";",
"var",
"parent",
"=",
"tree",
".",
"Composed",
".",
"getParentNode",
"(",
"node",
")",
";",
"if",
"(",
"container",
"===",
"parent",
")",
"{",
"tree",
".",
"Composed",
".",
"removeChild",
"(",
"container",
",",
"node",
")",
";",
"}",
"}",
"mixinImpl",
".",
"_scheduleObserver",
"(",
"this",
",",
"null",
",",
"node",
")",
";",
"return",
"node",
";",
"}"
]
| Removes the given `node` from the element's `lightChildren`.
This method also performs dom composition. | [
"Removes",
"the",
"given",
"node",
"from",
"the",
"element",
"s",
"lightChildren",
".",
"This",
"method",
"also",
"performs",
"dom",
"composition",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/shadydom.min.js#L2059-L2078 | train |
catamphetamine/web-service | source/middleware/authentication.js | get_jwt_token | function get_jwt_token(ctx)
{
// Parses "Authorization: Bearer ${token}"
if (ctx.header.authorization)
{
const match = ctx.header.authorization.match(/^Bearer (.+)$/i)
if (match)
{
return match[1]
}
}
// (doesn't read cookies anymore to protect users from CSRF attacks)
// // Tries the "authentication" cookie
// if (ctx.cookies.get('authentication'))
// {
// return ctx.cookies.get('authentication')
// }
} | javascript | function get_jwt_token(ctx)
{
// Parses "Authorization: Bearer ${token}"
if (ctx.header.authorization)
{
const match = ctx.header.authorization.match(/^Bearer (.+)$/i)
if (match)
{
return match[1]
}
}
// (doesn't read cookies anymore to protect users from CSRF attacks)
// // Tries the "authentication" cookie
// if (ctx.cookies.get('authentication'))
// {
// return ctx.cookies.get('authentication')
// }
} | [
"function",
"get_jwt_token",
"(",
"ctx",
")",
"{",
"if",
"(",
"ctx",
".",
"header",
".",
"authorization",
")",
"{",
"const",
"match",
"=",
"ctx",
".",
"header",
".",
"authorization",
".",
"match",
"(",
"/",
"^Bearer (.+)$",
"/",
"i",
")",
"if",
"(",
"match",
")",
"{",
"return",
"match",
"[",
"1",
"]",
"}",
"}",
"}"
]
| Looks for JWT token inside HTTP Authorization header | [
"Looks",
"for",
"JWT",
"token",
"inside",
"HTTP",
"Authorization",
"header"
]
| e1eabaaf76bd109a2b2c48ad617ebdd9111409a1 | https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/authentication.js#L6-L25 | train |
catamphetamine/web-service | source/middleware/authentication.js | authenticate | async function authenticate({ options, keys, log })
{
// A little helper which can be called from routes
// as `ctx.role('administrator')`
// which will throw if the user isn't administrator.
// The `roles` are taken from JWT payload.
this.role = (...roles) =>
{
if (!this.user)
{
throw new errors.Unauthenticated()
}
for (const role of roles)
{
for (const user_role of this.user.roles)
{
if (user_role === role)
{
return true
}
}
}
throw new errors.Unauthorized(`One of the following roles is required: ${roles}`)
}
// Get JWT token from incoming HTTP request
let token = get_jwt_token(this)
// If no JWT token was found, then done
if (!token)
{
return
}
// JWT token (is now accessible from Koa's `ctx`)
this.accessToken = token
// Verify JWT token integrity
// by checking its signature using the supplied `keys`
let payload
for (const secret of keys)
{
try
{
payload = jwt.verify(token, secret)
break
}
catch (error)
{
// If authentication token expired
if (error.name === 'TokenExpiredError')
{
if (options.refreshAccessToken)
{
// If refreshing an access token fails
// then don't prevent the user from at least seeing a page
// therefore catching an error here.
try
{
token = await options.refreshAccessToken(this)
}
catch (error)
{
log.error(error)
}
if (token)
{
for (const secret of keys)
{
try
{
payload = jwt.verify(token, secret)
break
}
catch (error)
{
// Try another `secret`
if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
{
continue
}
// Some other non-JWT-related error
log.error(error)
break
}
}
}
}
if (payload)
{
break
}
throw new errors.Access_token_expired()
}
// Try another `secret`
if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
{
continue
}
// Some other non-JWT-related error.
// Shouldn't prevent the user from at least seeing a page
// therefore not rethrowing this error.
log.error(error)
break
}
}
// If JWT token signature was unable to be verified, then exit
if (!payload)
{
return
}
// If the access token isn't valid for access to this server
// (e.g. it's a "refresh token") then exit.
if (options.validateAccessToken)
{
if (!options.validateAccessToken(payload, this))
{
return
}
}
// Token payload can be accessed through `ctx`
this.accessTokenPayload = payload
// Fire "on user request" hook
if (options.onUserRequest)
{
options.onUserRequest(token, this)
}
// JWT token ID
const jwt_id = payload.jti
// `subject`
// (which is a user id)
const user_id = payload.sub
// // Optional JWT token validation (by id)
// // (for example, that it has not been revoked)
// if (validateToken)
// {
// // Can validate the token via a request to a database, for example.
// // Checks for `valid` property value inside the result object.
// // (There can possibly be other properties such as `reason`)
// const is_valid = (await validateToken(token, this)).valid
//
// // If the JWT token happens to be invalid
// // (expired or revoked, for example), then exit.
// if (!is_valid)
// {
// // this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked')
// return
// }
// }
// JWT token ID is now accessible via Koa's `ctx`
this.accessTokenId = jwt_id
// Extracts user data (description) from JWT token payload
// (`user` is now accessible via Koa's `ctx`)
this.user = options.userInfo ? options.userInfo(payload) : {}
// Sets user id
this.user.id = user_id
// Extra payload fields:
//
// 'iss' // Issuer
// 'sub' // Subject
// 'aud' // Audience
// 'exp' // Expiration time
// 'nbf' // Not before
// 'iat' // Issued at
// 'jti' // JWT ID
// JWT token payload is accessible via Koa's `ctx`
this.accessTokenPayload = payload
} | javascript | async function authenticate({ options, keys, log })
{
// A little helper which can be called from routes
// as `ctx.role('administrator')`
// which will throw if the user isn't administrator.
// The `roles` are taken from JWT payload.
this.role = (...roles) =>
{
if (!this.user)
{
throw new errors.Unauthenticated()
}
for (const role of roles)
{
for (const user_role of this.user.roles)
{
if (user_role === role)
{
return true
}
}
}
throw new errors.Unauthorized(`One of the following roles is required: ${roles}`)
}
// Get JWT token from incoming HTTP request
let token = get_jwt_token(this)
// If no JWT token was found, then done
if (!token)
{
return
}
// JWT token (is now accessible from Koa's `ctx`)
this.accessToken = token
// Verify JWT token integrity
// by checking its signature using the supplied `keys`
let payload
for (const secret of keys)
{
try
{
payload = jwt.verify(token, secret)
break
}
catch (error)
{
// If authentication token expired
if (error.name === 'TokenExpiredError')
{
if (options.refreshAccessToken)
{
// If refreshing an access token fails
// then don't prevent the user from at least seeing a page
// therefore catching an error here.
try
{
token = await options.refreshAccessToken(this)
}
catch (error)
{
log.error(error)
}
if (token)
{
for (const secret of keys)
{
try
{
payload = jwt.verify(token, secret)
break
}
catch (error)
{
// Try another `secret`
if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
{
continue
}
// Some other non-JWT-related error
log.error(error)
break
}
}
}
}
if (payload)
{
break
}
throw new errors.Access_token_expired()
}
// Try another `secret`
if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
{
continue
}
// Some other non-JWT-related error.
// Shouldn't prevent the user from at least seeing a page
// therefore not rethrowing this error.
log.error(error)
break
}
}
// If JWT token signature was unable to be verified, then exit
if (!payload)
{
return
}
// If the access token isn't valid for access to this server
// (e.g. it's a "refresh token") then exit.
if (options.validateAccessToken)
{
if (!options.validateAccessToken(payload, this))
{
return
}
}
// Token payload can be accessed through `ctx`
this.accessTokenPayload = payload
// Fire "on user request" hook
if (options.onUserRequest)
{
options.onUserRequest(token, this)
}
// JWT token ID
const jwt_id = payload.jti
// `subject`
// (which is a user id)
const user_id = payload.sub
// // Optional JWT token validation (by id)
// // (for example, that it has not been revoked)
// if (validateToken)
// {
// // Can validate the token via a request to a database, for example.
// // Checks for `valid` property value inside the result object.
// // (There can possibly be other properties such as `reason`)
// const is_valid = (await validateToken(token, this)).valid
//
// // If the JWT token happens to be invalid
// // (expired or revoked, for example), then exit.
// if (!is_valid)
// {
// // this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked')
// return
// }
// }
// JWT token ID is now accessible via Koa's `ctx`
this.accessTokenId = jwt_id
// Extracts user data (description) from JWT token payload
// (`user` is now accessible via Koa's `ctx`)
this.user = options.userInfo ? options.userInfo(payload) : {}
// Sets user id
this.user.id = user_id
// Extra payload fields:
//
// 'iss' // Issuer
// 'sub' // Subject
// 'aud' // Audience
// 'exp' // Expiration time
// 'nbf' // Not before
// 'iat' // Issued at
// 'jti' // JWT ID
// JWT token payload is accessible via Koa's `ctx`
this.accessTokenPayload = payload
} | [
"async",
"function",
"authenticate",
"(",
"{",
"options",
",",
"keys",
",",
"log",
"}",
")",
"{",
"this",
".",
"role",
"=",
"(",
"...",
"roles",
")",
"=>",
"{",
"if",
"(",
"!",
"this",
".",
"user",
")",
"{",
"throw",
"new",
"errors",
".",
"Unauthenticated",
"(",
")",
"}",
"for",
"(",
"const",
"role",
"of",
"roles",
")",
"{",
"for",
"(",
"const",
"user_role",
"of",
"this",
".",
"user",
".",
"roles",
")",
"{",
"if",
"(",
"user_role",
"===",
"role",
")",
"{",
"return",
"true",
"}",
"}",
"}",
"throw",
"new",
"errors",
".",
"Unauthorized",
"(",
"`",
"${",
"roles",
"}",
"`",
")",
"}",
"let",
"token",
"=",
"get_jwt_token",
"(",
"this",
")",
"if",
"(",
"!",
"token",
")",
"{",
"return",
"}",
"this",
".",
"accessToken",
"=",
"token",
"let",
"payload",
"for",
"(",
"const",
"secret",
"of",
"keys",
")",
"{",
"try",
"{",
"payload",
"=",
"jwt",
".",
"verify",
"(",
"token",
",",
"secret",
")",
"break",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"name",
"===",
"'TokenExpiredError'",
")",
"{",
"if",
"(",
"options",
".",
"refreshAccessToken",
")",
"{",
"try",
"{",
"token",
"=",
"await",
"options",
".",
"refreshAccessToken",
"(",
"this",
")",
"}",
"catch",
"(",
"error",
")",
"{",
"log",
".",
"error",
"(",
"error",
")",
"}",
"if",
"(",
"token",
")",
"{",
"for",
"(",
"const",
"secret",
"of",
"keys",
")",
"{",
"try",
"{",
"payload",
"=",
"jwt",
".",
"verify",
"(",
"token",
",",
"secret",
")",
"break",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"error",
".",
"name",
"===",
"'JsonWebTokenError'",
"&&",
"error",
".",
"message",
"===",
"'invalid signature'",
")",
"{",
"continue",
"}",
"log",
".",
"error",
"(",
"error",
")",
"break",
"}",
"}",
"}",
"}",
"if",
"(",
"payload",
")",
"{",
"break",
"}",
"throw",
"new",
"errors",
".",
"Access_token_expired",
"(",
")",
"}",
"if",
"(",
"error",
".",
"name",
"===",
"'JsonWebTokenError'",
"&&",
"error",
".",
"message",
"===",
"'invalid signature'",
")",
"{",
"continue",
"}",
"log",
".",
"error",
"(",
"error",
")",
"break",
"}",
"}",
"if",
"(",
"!",
"payload",
")",
"{",
"return",
"}",
"if",
"(",
"options",
".",
"validateAccessToken",
")",
"{",
"if",
"(",
"!",
"options",
".",
"validateAccessToken",
"(",
"payload",
",",
"this",
")",
")",
"{",
"return",
"}",
"}",
"this",
".",
"accessTokenPayload",
"=",
"payload",
"if",
"(",
"options",
".",
"onUserRequest",
")",
"{",
"options",
".",
"onUserRequest",
"(",
"token",
",",
"this",
")",
"}",
"const",
"jwt_id",
"=",
"payload",
".",
"jti",
"const",
"user_id",
"=",
"payload",
".",
"sub",
"this",
".",
"accessTokenId",
"=",
"jwt_id",
"this",
".",
"user",
"=",
"options",
".",
"userInfo",
"?",
"options",
".",
"userInfo",
"(",
"payload",
")",
":",
"{",
"}",
"this",
".",
"user",
".",
"id",
"=",
"user_id",
"this",
".",
"accessTokenPayload",
"=",
"payload",
"}"
]
| Looks for JWT token, and if it is found, sets some variables. | [
"Looks",
"for",
"JWT",
"token",
"and",
"if",
"it",
"is",
"found",
"sets",
"some",
"variables",
"."
]
| e1eabaaf76bd109a2b2c48ad617ebdd9111409a1 | https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/authentication.js#L28-L217 | train |
basic-web-components/basic-web-components | packages/basic-autosize-textarea/src/AutosizeTextarea.js | setMinimumHeight | function setMinimumHeight(element) {
const copyContainer = element.$.copyContainer;
const outerHeight = copyContainer.getBoundingClientRect().height;
const style = getComputedStyle(copyContainer);
const paddingTop = parseFloat(style.paddingTop);
const paddingBottom = parseFloat(style.paddingBottom);
const innerHeight = copyContainer.clientHeight - paddingTop - paddingBottom;
const bordersPlusPadding = outerHeight - innerHeight;
let minHeight = (element.minimumRows * element[lineHeightSymbol]) + bordersPlusPadding;
minHeight = Math.ceil(minHeight);
copyContainer.style.minHeight = minHeight + 'px';
} | javascript | function setMinimumHeight(element) {
const copyContainer = element.$.copyContainer;
const outerHeight = copyContainer.getBoundingClientRect().height;
const style = getComputedStyle(copyContainer);
const paddingTop = parseFloat(style.paddingTop);
const paddingBottom = parseFloat(style.paddingBottom);
const innerHeight = copyContainer.clientHeight - paddingTop - paddingBottom;
const bordersPlusPadding = outerHeight - innerHeight;
let minHeight = (element.minimumRows * element[lineHeightSymbol]) + bordersPlusPadding;
minHeight = Math.ceil(minHeight);
copyContainer.style.minHeight = minHeight + 'px';
} | [
"function",
"setMinimumHeight",
"(",
"element",
")",
"{",
"const",
"copyContainer",
"=",
"element",
".",
"$",
".",
"copyContainer",
";",
"const",
"outerHeight",
"=",
"copyContainer",
".",
"getBoundingClientRect",
"(",
")",
".",
"height",
";",
"const",
"style",
"=",
"getComputedStyle",
"(",
"copyContainer",
")",
";",
"const",
"paddingTop",
"=",
"parseFloat",
"(",
"style",
".",
"paddingTop",
")",
";",
"const",
"paddingBottom",
"=",
"parseFloat",
"(",
"style",
".",
"paddingBottom",
")",
";",
"const",
"innerHeight",
"=",
"copyContainer",
".",
"clientHeight",
"-",
"paddingTop",
"-",
"paddingBottom",
";",
"const",
"bordersPlusPadding",
"=",
"outerHeight",
"-",
"innerHeight",
";",
"let",
"minHeight",
"=",
"(",
"element",
".",
"minimumRows",
"*",
"element",
"[",
"lineHeightSymbol",
"]",
")",
"+",
"bordersPlusPadding",
";",
"minHeight",
"=",
"Math",
".",
"ceil",
"(",
"minHeight",
")",
";",
"copyContainer",
".",
"style",
".",
"minHeight",
"=",
"minHeight",
"+",
"'px'",
";",
"}"
]
| Setting the minimumRows attribute translates into setting the minimum height on the text copy container. | [
"Setting",
"the",
"minimumRows",
"attribute",
"translates",
"into",
"setting",
"the",
"minimum",
"height",
"on",
"the",
"text",
"copy",
"container",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-autosize-textarea/src/AutosizeTextarea.js#L332-L343 | train |
basic-web-components/basic-web-components | packages/basic-fade-overflow/src/FadeOverflow.js | extractRgbValues | function extractRgbValues(rgbString) {
const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/;
const match = rgbRegex.exec(rgbString);
if (match) {
return {
r: parseInt(match[1]),
g: parseInt(match[2]),
b: parseInt(match[3])
};
} else {
return null;
}
} | javascript | function extractRgbValues(rgbString) {
const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/;
const match = rgbRegex.exec(rgbString);
if (match) {
return {
r: parseInt(match[1]),
g: parseInt(match[2]),
b: parseInt(match[3])
};
} else {
return null;
}
} | [
"function",
"extractRgbValues",
"(",
"rgbString",
")",
"{",
"const",
"rgbRegex",
"=",
"/",
"rgba?\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*(?:,\\s*[\\d\\.]+\\s*)?\\)",
"/",
";",
"const",
"match",
"=",
"rgbRegex",
".",
"exec",
"(",
"rgbString",
")",
";",
"if",
"(",
"match",
")",
"{",
"return",
"{",
"r",
":",
"parseInt",
"(",
"match",
"[",
"1",
"]",
")",
",",
"g",
":",
"parseInt",
"(",
"match",
"[",
"2",
"]",
")",
",",
"b",
":",
"parseInt",
"(",
"match",
"[",
"3",
"]",
")",
"}",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
]
| Return the individual RGB values from a CSS color string. | [
"Return",
"the",
"individual",
"RGB",
"values",
"from",
"a",
"CSS",
"color",
"string",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-fade-overflow/src/FadeOverflow.js#L128-L140 | train |
basic-web-components/basic-web-components | packages/basic-component-mixins/src/ContentItemsMixin.js | filterAuxiliaryElements | function filterAuxiliaryElements(items) {
const auxiliaryTags = [
'link',
'script',
'style',
'template'
];
return [].filter.call(items, function(item) {
return !item.localName || auxiliaryTags.indexOf(item.localName) < 0;
});
} | javascript | function filterAuxiliaryElements(items) {
const auxiliaryTags = [
'link',
'script',
'style',
'template'
];
return [].filter.call(items, function(item) {
return !item.localName || auxiliaryTags.indexOf(item.localName) < 0;
});
} | [
"function",
"filterAuxiliaryElements",
"(",
"items",
")",
"{",
"const",
"auxiliaryTags",
"=",
"[",
"'link'",
",",
"'script'",
",",
"'style'",
",",
"'template'",
"]",
";",
"return",
"[",
"]",
".",
"filter",
".",
"call",
"(",
"items",
",",
"function",
"(",
"item",
")",
"{",
"return",
"!",
"item",
".",
"localName",
"||",
"auxiliaryTags",
".",
"indexOf",
"(",
"item",
".",
"localName",
")",
"<",
"0",
";",
"}",
")",
";",
"}"
]
| Return the given elements, filtering out auxiliary elements that aren't typically visible. Items which are not elements are returned as is. | [
"Return",
"the",
"given",
"elements",
"filtering",
"out",
"auxiliary",
"elements",
"that",
"aren",
"t",
"typically",
"visible",
".",
"Items",
"which",
"are",
"not",
"elements",
"are",
"returned",
"as",
"is",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/ContentItemsMixin.js#L140-L150 | train |
basic-web-components/basic-web-components | packages/basic-component-mixins/src/safeAttributes.js | setAttributeToElement | function setAttributeToElement(element, attributeName, value) {
if (value === null || typeof value === 'undefined') {
element.removeAttribute(attributeName);
} else {
const text = String(value);
// Avoid recursive attributeChangedCallback calls.
if (element.getAttribute(attributeName) !== text) {
element.setAttribute(attributeName, value);
}
}
} | javascript | function setAttributeToElement(element, attributeName, value) {
if (value === null || typeof value === 'undefined') {
element.removeAttribute(attributeName);
} else {
const text = String(value);
// Avoid recursive attributeChangedCallback calls.
if (element.getAttribute(attributeName) !== text) {
element.setAttribute(attributeName, value);
}
}
} | [
"function",
"setAttributeToElement",
"(",
"element",
",",
"attributeName",
",",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"null",
"||",
"typeof",
"value",
"===",
"'undefined'",
")",
"{",
"element",
".",
"removeAttribute",
"(",
"attributeName",
")",
";",
"}",
"else",
"{",
"const",
"text",
"=",
"String",
"(",
"value",
")",
";",
"if",
"(",
"element",
".",
"getAttribute",
"(",
"attributeName",
")",
"!==",
"text",
")",
"{",
"element",
".",
"setAttribute",
"(",
"attributeName",
",",
"value",
")",
";",
"}",
"}",
"}"
]
| Reflect the attribute to the given element. If the value is null, remove the attribute. | [
"Reflect",
"the",
"attribute",
"to",
"the",
"given",
"element",
".",
"If",
"the",
"value",
"is",
"null",
"remove",
"the",
"attribute",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/safeAttributes.js#L107-L117 | train |
basic-web-components/basic-web-components | packages/basic-component-mixins/src/renderArrayAsElements.js | renderArrayAsElements | function renderArrayAsElements(items, container, renderItem) {
// Create a new set of elements for the current items.
items.forEach((item, index) => {
const oldElement = container.childNodes[index];
const newElement = renderItem(item, oldElement);
if (newElement) {
if (!oldElement) {
container.appendChild(newElement);
} else if (newElement !== oldElement) {
container.replaceChild(newElement, oldElement);
}
}
});
// If the array shrank, remove the extra elements which are no longer needed.
while (container.childNodes.length > items.length) {
container.removeChild(container.childNodes[items.length]);
}
} | javascript | function renderArrayAsElements(items, container, renderItem) {
// Create a new set of elements for the current items.
items.forEach((item, index) => {
const oldElement = container.childNodes[index];
const newElement = renderItem(item, oldElement);
if (newElement) {
if (!oldElement) {
container.appendChild(newElement);
} else if (newElement !== oldElement) {
container.replaceChild(newElement, oldElement);
}
}
});
// If the array shrank, remove the extra elements which are no longer needed.
while (container.childNodes.length > items.length) {
container.removeChild(container.childNodes[items.length]);
}
} | [
"function",
"renderArrayAsElements",
"(",
"items",
",",
"container",
",",
"renderItem",
")",
"{",
"items",
".",
"forEach",
"(",
"(",
"item",
",",
"index",
")",
"=>",
"{",
"const",
"oldElement",
"=",
"container",
".",
"childNodes",
"[",
"index",
"]",
";",
"const",
"newElement",
"=",
"renderItem",
"(",
"item",
",",
"oldElement",
")",
";",
"if",
"(",
"newElement",
")",
"{",
"if",
"(",
"!",
"oldElement",
")",
"{",
"container",
".",
"appendChild",
"(",
"newElement",
")",
";",
"}",
"else",
"if",
"(",
"newElement",
"!==",
"oldElement",
")",
"{",
"container",
".",
"replaceChild",
"(",
"newElement",
",",
"oldElement",
")",
";",
"}",
"}",
"}",
")",
";",
"while",
"(",
"container",
".",
"childNodes",
".",
"length",
">",
"items",
".",
"length",
")",
"{",
"container",
".",
"removeChild",
"(",
"container",
".",
"childNodes",
"[",
"items",
".",
"length",
"]",
")",
";",
"}",
"}"
]
| Helper function for rendering an array of items as elements.
This is not a mixin, but a function components can use if they need to
generate a set of elements for the items in an array.
This function will reuse existing elements if possible. E.g., if it is called
to render an array of 4 items, and later called to render an array of 5
items, it can reuse the existing 4 items, creating just one new element.
Note, however, that this re-rendering is not automatic. If, after calling
this function, you manipulate the array you used, you must still call this
function again to re-render the array.
The `renderItem` parameter takes a function of two arguments: an item to
to render, and an existing element (if one exists) which can be repurposed to
render that item. If the latter argument is null, the `renderItem()` function
should create a new element and return it. The function should do the same
if the supplied existing element is not suitable for rendering the given
item; the returned element will be used to replace the existing one. If the
existing element *is* suitable, the function can simply update it and return
it as is.
Example: The following will render an array of strings in divs as children
of the `container` element:
let strings = ['a', 'b', 'c', ...];
let container = this.querySelector(...);
renderArrayAsElements(strings, container, (string, element) => {
if (!element) {
// No element exists yet, so create a new one.
element = document.createElement('div');
}
// Set/update the text content of the element.
element.textContent = string;
return element;
});
@param {Array} items - the items to render
@param {HTMLElement} container - the parent that will hold the elements
@param {function} renderItem - returns a new element for an item, or
repurposes an existing element for an item | [
"Helper",
"function",
"for",
"rendering",
"an",
"array",
"of",
"items",
"as",
"elements",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/renderArrayAsElements.js#L43-L61 | train |
catamphetamine/web-service | source/middleware/file upload.js | upload_file | async function upload_file(file, { upload_folder, log })
{
if (log)
{
log.debug(`Uploading: ${file.filename}`)
}
// Generate random unique filename
const file_name = await generate_unique_filename(upload_folder,
{
on_collision: (file_name) =>
{
log.info(`Generate unique file name: collision for "${file_name}". Taking another try.`)
}
})
// dot_extension: path.extname(file.filename)
const output_file = path.join(upload_folder, file_name)
// Write the file to disk
return await new Promise((resolve, reject) =>
{
// Ensure the `upload_folder` exists
// (just an extra precaution)
fs.ensureDir(upload_folder, (error) =>
{
if (error)
{
return reject(error)
}
// Open output file stream
const stream = fs.createWriteStream(output_file)
// Pipe file contents to disk
file.pipe(stream)
.on('finish', () => resolve(path.relative(upload_folder, output_file)))
.on('error', error => reject(error))
})
})
} | javascript | async function upload_file(file, { upload_folder, log })
{
if (log)
{
log.debug(`Uploading: ${file.filename}`)
}
// Generate random unique filename
const file_name = await generate_unique_filename(upload_folder,
{
on_collision: (file_name) =>
{
log.info(`Generate unique file name: collision for "${file_name}". Taking another try.`)
}
})
// dot_extension: path.extname(file.filename)
const output_file = path.join(upload_folder, file_name)
// Write the file to disk
return await new Promise((resolve, reject) =>
{
// Ensure the `upload_folder` exists
// (just an extra precaution)
fs.ensureDir(upload_folder, (error) =>
{
if (error)
{
return reject(error)
}
// Open output file stream
const stream = fs.createWriteStream(output_file)
// Pipe file contents to disk
file.pipe(stream)
.on('finish', () => resolve(path.relative(upload_folder, output_file)))
.on('error', error => reject(error))
})
})
} | [
"async",
"function",
"upload_file",
"(",
"file",
",",
"{",
"upload_folder",
",",
"log",
"}",
")",
"{",
"if",
"(",
"log",
")",
"{",
"log",
".",
"debug",
"(",
"`",
"${",
"file",
".",
"filename",
"}",
"`",
")",
"}",
"const",
"file_name",
"=",
"await",
"generate_unique_filename",
"(",
"upload_folder",
",",
"{",
"on_collision",
":",
"(",
"file_name",
")",
"=>",
"{",
"log",
".",
"info",
"(",
"`",
"${",
"file_name",
"}",
"`",
")",
"}",
"}",
")",
"const",
"output_file",
"=",
"path",
".",
"join",
"(",
"upload_folder",
",",
"file_name",
")",
"return",
"await",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fs",
".",
"ensureDir",
"(",
"upload_folder",
",",
"(",
"error",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"reject",
"(",
"error",
")",
"}",
"const",
"stream",
"=",
"fs",
".",
"createWriteStream",
"(",
"output_file",
")",
"file",
".",
"pipe",
"(",
"stream",
")",
".",
"on",
"(",
"'finish'",
",",
"(",
")",
"=>",
"resolve",
"(",
"path",
".",
"relative",
"(",
"upload_folder",
",",
"output_file",
")",
")",
")",
".",
"on",
"(",
"'error'",
",",
"error",
"=>",
"reject",
"(",
"error",
")",
")",
"}",
")",
"}",
")",
"}"
]
| Handles file upload. Takes a `file` busboy file object along with `upload_folder` option. Writes the `file` stream to `upload_folder` naming it with a randomly generated filename. Returns a Promise resolving to the randomly generated filename. | [
"Handles",
"file",
"upload",
".",
"Takes",
"a",
"file",
"busboy",
"file",
"object",
"along",
"with",
"upload_folder",
"option",
".",
"Writes",
"the",
"file",
"stream",
"to",
"upload_folder",
"naming",
"it",
"with",
"a",
"randomly",
"generated",
"filename",
".",
"Returns",
"a",
"Promise",
"resolving",
"to",
"the",
"randomly",
"generated",
"filename",
"."
]
| e1eabaaf76bd109a2b2c48ad617ebdd9111409a1 | https://github.com/catamphetamine/web-service/blob/e1eabaaf76bd109a2b2c48ad617ebdd9111409a1/source/middleware/file upload.js#L284-L325 | train |
basic-web-components/basic-web-components | packages/demos/bower_components/shadydom/src/tree.js | assertNative | function assertNative(element, property, tracked) {
let native = getNativeProperty(element, property);
if (native != tracked && element.__patched) {
window.console.warn('tracked', tracked, 'native', native);
}
return tracked;
} | javascript | function assertNative(element, property, tracked) {
let native = getNativeProperty(element, property);
if (native != tracked && element.__patched) {
window.console.warn('tracked', tracked, 'native', native);
}
return tracked;
} | [
"function",
"assertNative",
"(",
"element",
",",
"property",
",",
"tracked",
")",
"{",
"let",
"native",
"=",
"getNativeProperty",
"(",
"element",
",",
"property",
")",
";",
"if",
"(",
"native",
"!=",
"tracked",
"&&",
"element",
".",
"__patched",
")",
"{",
"window",
".",
"console",
".",
"warn",
"(",
"'tracked'",
",",
"tracked",
",",
"'native'",
",",
"native",
")",
";",
"}",
"return",
"tracked",
";",
"}"
]
| for testing... | [
"for",
"testing",
"..."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/demos/bower_components/shadydom/src/tree.js#L569-L575 | train |
pazams/vivalid | lib/validator-repo.js | build | function build(validatorName, validatorOptions) {
if (typeof validatorBuildersRepository[validatorName] !== 'function') {
throw validatorName + ' does not exists. use addValidatorBuilder to add a new validation rule';
}
return validatorBuildersRepository[validatorName](ValidationState, stateEnum, validatorOptions);
} | javascript | function build(validatorName, validatorOptions) {
if (typeof validatorBuildersRepository[validatorName] !== 'function') {
throw validatorName + ' does not exists. use addValidatorBuilder to add a new validation rule';
}
return validatorBuildersRepository[validatorName](ValidationState, stateEnum, validatorOptions);
} | [
"function",
"build",
"(",
"validatorName",
",",
"validatorOptions",
")",
"{",
"if",
"(",
"typeof",
"validatorBuildersRepository",
"[",
"validatorName",
"]",
"!==",
"'function'",
")",
"{",
"throw",
"validatorName",
"+",
"' does not exists. use addValidatorBuilder to add a new validation rule'",
";",
"}",
"return",
"validatorBuildersRepository",
"[",
"validatorName",
"]",
"(",
"ValidationState",
",",
"stateEnum",
",",
"validatorOptions",
")",
";",
"}"
]
| Adds validator builder. Use to create custom validation rules.
@memberof! vivalid.validatorRepo
@function
@private
@param {validatorName} name validator name.
@param {object} validatorOptions. | [
"Adds",
"validator",
"builder",
".",
"Use",
"to",
"create",
"custom",
"validation",
"rules",
"."
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/validator-repo.js#L27-L34 | train |
pazams/vivalid | lib/html-interface.js | addCallback | function addCallback(name, fn) {
if (typeof fn !== 'function') throw 'error while trying to add a custom callback: argument must be a function';
if (callbacks[name]) throw 'error while trying to add a custom callback: ' + name + ' already exists';
callbacks[name] = fn;
} | javascript | function addCallback(name, fn) {
if (typeof fn !== 'function') throw 'error while trying to add a custom callback: argument must be a function';
if (callbacks[name]) throw 'error while trying to add a custom callback: ' + name + ' already exists';
callbacks[name] = fn;
} | [
"function",
"addCallback",
"(",
"name",
",",
"fn",
")",
"{",
"if",
"(",
"typeof",
"fn",
"!==",
"'function'",
")",
"throw",
"'error while trying to add a custom callback: argument must be a function'",
";",
"if",
"(",
"callbacks",
"[",
"name",
"]",
")",
"throw",
"'error while trying to add a custom callback: '",
"+",
"name",
"+",
"' already exists'",
";",
"callbacks",
"[",
"name",
"]",
"=",
"fn",
";",
"}"
]
| Adds functional parameters, to be referenced at html data attributes.
@memberof! vivalid.htmlInterface
@function
@example vivalid.htmlInterface.addCallback('onValidationFailure', function(invalid,pending,valid){ alert('input group is invalid!: '+invalid+ ' invalid, ' +pending+' pending, and ' +valid+' valid ' ); });
@param {string} name
@param {function} fn | [
"Adds",
"functional",
"parameters",
"to",
"be",
"referenced",
"at",
"html",
"data",
"attributes",
"."
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L19-L23 | train |
pazams/vivalid | lib/html-interface.js | initGroup | function initGroup(groupElem) {
$$.ready(registerGroupFromDataAttribtues);
function registerGroupFromDataAttribtues() {
inputElems = $$.getElementsByTagNames(validInputTagNames, groupElem)
.filter(function(el) {
return $$.hasDataSet(el, 'vivalidTuples');
});
var vivalidGroup = createGroupFromDataAttribtues(groupElem, inputElems);
addToGroupNameDictionairy(groupElem, vivalidGroup);
}
} | javascript | function initGroup(groupElem) {
$$.ready(registerGroupFromDataAttribtues);
function registerGroupFromDataAttribtues() {
inputElems = $$.getElementsByTagNames(validInputTagNames, groupElem)
.filter(function(el) {
return $$.hasDataSet(el, 'vivalidTuples');
});
var vivalidGroup = createGroupFromDataAttribtues(groupElem, inputElems);
addToGroupNameDictionairy(groupElem, vivalidGroup);
}
} | [
"function",
"initGroup",
"(",
"groupElem",
")",
"{",
"$$",
".",
"ready",
"(",
"registerGroupFromDataAttribtues",
")",
";",
"function",
"registerGroupFromDataAttribtues",
"(",
")",
"{",
"inputElems",
"=",
"$$",
".",
"getElementsByTagNames",
"(",
"validInputTagNames",
",",
"groupElem",
")",
".",
"filter",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"$$",
".",
"hasDataSet",
"(",
"el",
",",
"'vivalidTuples'",
")",
";",
"}",
")",
";",
"var",
"vivalidGroup",
"=",
"createGroupFromDataAttribtues",
"(",
"groupElem",
",",
"inputElems",
")",
";",
"addToGroupNameDictionairy",
"(",
"groupElem",
",",
"vivalidGroup",
")",
";",
"}",
"}"
]
| Bootstraps a group by the group's DOM HTMLElement when using the html data attributes interface. Provides more control over vivalid.htmlInterface.init. Usefull when some of the elements are not present when DOMContentLoaded fires, but rather are appended at some later stage in the application flow.
@memberof! vivalid.htmlInterface
@function
@example vivalid.htmlInterface.initGroup(document.getElementById('FormId'));
@param {HTMLElement} groupElem | [
"Bootstraps",
"a",
"group",
"by",
"the",
"group",
"s",
"DOM",
"HTMLElement",
"when",
"using",
"the",
"html",
"data",
"attributes",
"interface",
".",
"Provides",
"more",
"control",
"over",
"vivalid",
".",
"htmlInterface",
".",
"init",
".",
"Usefull",
"when",
"some",
"of",
"the",
"elements",
"are",
"not",
"present",
"when",
"DOMContentLoaded",
"fires",
"but",
"rather",
"are",
"appended",
"at",
"some",
"later",
"stage",
"in",
"the",
"application",
"flow",
"."
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L32-L46 | train |
pazams/vivalid | lib/html-interface.js | initAll | function initAll() {
$$.ready(registerAllFromDataAttribtues);
function registerAllFromDataAttribtues() {
var _nextGroupId = 1;
// es6 map would have been nice here, but this lib is intended to run on es5 browsers. integrating Babel might work.
var groupIdToInputs = {};
var groupIdToGroup = {};
$$.getElementsByTagNames(validInputTagNames)
.filter(function(el) {
return $$.hasDataSet(el, 'vivalidTuples');
})
.forEach(function(el) {
addGroupInputs($$.getClosestParentByAttribute(el, 'vivalidGroup'), el);
});
for (var groupId in groupIdToInputs) {
var vivalidGroup = createGroupFromDataAttribtues(groupIdToGroup[groupId], groupIdToInputs[groupId]);
addToGroupNameDictionairy(groupIdToGroup[groupId], vivalidGroup);
}
function addGroupInputs(group, input) {
if (!group) {
throw 'an input validation is missing a group, input id: ' + input.id;
}
if (!group._groupId) group._groupId = _nextGroupId++;
if (!groupIdToInputs[group._groupId]) {
groupIdToInputs[group._groupId] = [];
groupIdToGroup[group._groupId] = group;
}
groupIdToInputs[group._groupId].push(input);
}
}
} | javascript | function initAll() {
$$.ready(registerAllFromDataAttribtues);
function registerAllFromDataAttribtues() {
var _nextGroupId = 1;
// es6 map would have been nice here, but this lib is intended to run on es5 browsers. integrating Babel might work.
var groupIdToInputs = {};
var groupIdToGroup = {};
$$.getElementsByTagNames(validInputTagNames)
.filter(function(el) {
return $$.hasDataSet(el, 'vivalidTuples');
})
.forEach(function(el) {
addGroupInputs($$.getClosestParentByAttribute(el, 'vivalidGroup'), el);
});
for (var groupId in groupIdToInputs) {
var vivalidGroup = createGroupFromDataAttribtues(groupIdToGroup[groupId], groupIdToInputs[groupId]);
addToGroupNameDictionairy(groupIdToGroup[groupId], vivalidGroup);
}
function addGroupInputs(group, input) {
if (!group) {
throw 'an input validation is missing a group, input id: ' + input.id;
}
if (!group._groupId) group._groupId = _nextGroupId++;
if (!groupIdToInputs[group._groupId]) {
groupIdToInputs[group._groupId] = [];
groupIdToGroup[group._groupId] = group;
}
groupIdToInputs[group._groupId].push(input);
}
}
} | [
"function",
"initAll",
"(",
")",
"{",
"$$",
".",
"ready",
"(",
"registerAllFromDataAttribtues",
")",
";",
"function",
"registerAllFromDataAttribtues",
"(",
")",
"{",
"var",
"_nextGroupId",
"=",
"1",
";",
"var",
"groupIdToInputs",
"=",
"{",
"}",
";",
"var",
"groupIdToGroup",
"=",
"{",
"}",
";",
"$$",
".",
"getElementsByTagNames",
"(",
"validInputTagNames",
")",
".",
"filter",
"(",
"function",
"(",
"el",
")",
"{",
"return",
"$$",
".",
"hasDataSet",
"(",
"el",
",",
"'vivalidTuples'",
")",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"el",
")",
"{",
"addGroupInputs",
"(",
"$$",
".",
"getClosestParentByAttribute",
"(",
"el",
",",
"'vivalidGroup'",
")",
",",
"el",
")",
";",
"}",
")",
";",
"for",
"(",
"var",
"groupId",
"in",
"groupIdToInputs",
")",
"{",
"var",
"vivalidGroup",
"=",
"createGroupFromDataAttribtues",
"(",
"groupIdToGroup",
"[",
"groupId",
"]",
",",
"groupIdToInputs",
"[",
"groupId",
"]",
")",
";",
"addToGroupNameDictionairy",
"(",
"groupIdToGroup",
"[",
"groupId",
"]",
",",
"vivalidGroup",
")",
";",
"}",
"function",
"addGroupInputs",
"(",
"group",
",",
"input",
")",
"{",
"if",
"(",
"!",
"group",
")",
"{",
"throw",
"'an input validation is missing a group, input id: '",
"+",
"input",
".",
"id",
";",
"}",
"if",
"(",
"!",
"group",
".",
"_groupId",
")",
"group",
".",
"_groupId",
"=",
"_nextGroupId",
"++",
";",
"if",
"(",
"!",
"groupIdToInputs",
"[",
"group",
".",
"_groupId",
"]",
")",
"{",
"groupIdToInputs",
"[",
"group",
".",
"_groupId",
"]",
"=",
"[",
"]",
";",
"groupIdToGroup",
"[",
"group",
".",
"_groupId",
"]",
"=",
"group",
";",
"}",
"groupIdToInputs",
"[",
"group",
".",
"_groupId",
"]",
".",
"push",
"(",
"input",
")",
";",
"}",
"}",
"}"
]
| Bootstraps all groups when using the html data attributes interface. Will work on all groups present at initial page load.
@memberof! vivalid.htmlInterface
@function
@example vivalid.htmlInterface.initAll(); | [
"Bootstraps",
"all",
"groups",
"when",
"using",
"the",
"html",
"data",
"attributes",
"interface",
".",
"Will",
"work",
"on",
"all",
"groups",
"present",
"at",
"initial",
"page",
"load",
"."
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L54-L97 | train |
pazams/vivalid | lib/html-interface.js | resetGroup | function resetGroup(groupName) {
var vivalidGroup = groupNameToVivalidGroup[groupName];
if (vivalidGroup) {
vivalidGroup.reset();
} else {
console.log('could not find group named ' + groupName);
}
} | javascript | function resetGroup(groupName) {
var vivalidGroup = groupNameToVivalidGroup[groupName];
if (vivalidGroup) {
vivalidGroup.reset();
} else {
console.log('could not find group named ' + groupName);
}
} | [
"function",
"resetGroup",
"(",
"groupName",
")",
"{",
"var",
"vivalidGroup",
"=",
"groupNameToVivalidGroup",
"[",
"groupName",
"]",
";",
"if",
"(",
"vivalidGroup",
")",
"{",
"vivalidGroup",
".",
"reset",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'could not find group named '",
"+",
"groupName",
")",
";",
"}",
"}"
]
| Allow's an application to reset the validations state and event listeners of a group
@memberof! vivalid.htmlInterface
@function
@example vivalid.htmlInterface.resetGroup('contactGroup');
@param {string} groupName | [
"Allow",
"s",
"an",
"application",
"to",
"reset",
"the",
"validations",
"state",
"and",
"event",
"listeners",
"of",
"a",
"group"
]
| dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f | https://github.com/pazams/vivalid/blob/dbcac4dd17f0f3c60e21d92f6561476cb1cc4a7f/lib/html-interface.js#L106-L116 | train |
basic-web-components/basic-web-components | packages/basic-component-mixins/src/KeyboardPrefixSelectionMixin.js | getIndexOfItemWithTextPrefix | function getIndexOfItemWithTextPrefix(element, prefix) {
const itemTextContents = getItemTextContents(element);
const prefixLength = prefix.length;
for (let i = 0; i < itemTextContents.length; i++) {
const itemTextContent = itemTextContents[i];
if (itemTextContent.substr(0, prefixLength) === prefix) {
return i;
}
}
return -1;
} | javascript | function getIndexOfItemWithTextPrefix(element, prefix) {
const itemTextContents = getItemTextContents(element);
const prefixLength = prefix.length;
for (let i = 0; i < itemTextContents.length; i++) {
const itemTextContent = itemTextContents[i];
if (itemTextContent.substr(0, prefixLength) === prefix) {
return i;
}
}
return -1;
} | [
"function",
"getIndexOfItemWithTextPrefix",
"(",
"element",
",",
"prefix",
")",
"{",
"const",
"itemTextContents",
"=",
"getItemTextContents",
"(",
"element",
")",
";",
"const",
"prefixLength",
"=",
"prefix",
".",
"length",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"itemTextContents",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"itemTextContent",
"=",
"itemTextContents",
"[",
"i",
"]",
";",
"if",
"(",
"itemTextContent",
".",
"substr",
"(",
"0",
",",
"prefixLength",
")",
"===",
"prefix",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
]
| Return the index of the first item with the given prefix, else -1. | [
"Return",
"the",
"index",
"of",
"the",
"first",
"item",
"with",
"the",
"given",
"prefix",
"else",
"-",
"1",
"."
]
| 1dd0e353da13e208777c022380c2d8056c041c0c | https://github.com/basic-web-components/basic-web-components/blob/1dd0e353da13e208777c022380c2d8056c041c0c/packages/basic-component-mixins/src/KeyboardPrefixSelectionMixin.js#L118-L128 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.