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 |
---|---|---|---|---|---|---|---|---|---|---|---|
jurca/szn-options | szn-options.js | updateExistingItems | function updateExistingItems(groupUi) {
let itemUi = groupUi.firstElementChild
while (itemUi) {
updateItem(itemUi)
itemUi = itemUi.nextElementSibling
}
} | javascript | function updateExistingItems(groupUi) {
let itemUi = groupUi.firstElementChild
while (itemUi) {
updateItem(itemUi)
itemUi = itemUi.nextElementSibling
}
} | [
"function",
"updateExistingItems",
"(",
"groupUi",
")",
"{",
"let",
"itemUi",
"=",
"groupUi",
".",
"firstElementChild",
"while",
"(",
"itemUi",
")",
"{",
"updateItem",
"(",
"itemUi",
")",
"itemUi",
"=",
"itemUi",
".",
"nextElementSibling",
"}",
"}"
]
| Updates all items in the provided UI container to reflect the current state of their associated options.
@param {Element} groupUi The element containing the elements representing the UIs of the options. | [
"Updates",
"all",
"items",
"in",
"the",
"provided",
"UI",
"container",
"to",
"reflect",
"the",
"current",
"state",
"of",
"their",
"associated",
"options",
"."
]
| dc1c2e1f74e25d78643904389cdbaaf48a20b52e | https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L494-L500 | train |
jurca/szn-options | szn-options.js | addMissingItems | function addMissingItems(groupUi, options) {
let nextItemUi = groupUi.firstElementChild
let nextOption = options.firstElementChild
while (nextOption) {
if (!nextItemUi || nextItemUi._option !== nextOption) {
const newItemUi = document.createElement('szn-')
newItemUi._option = nextOption
newItemUi.setAttribute('data-szn-options--' + (nextOption.tagName === 'OPTGROUP' ? 'optgroup' : 'option'), '')
updateItem(newItemUi)
groupUi.insertBefore(newItemUi, nextItemUi)
} else {
nextItemUi = nextItemUi && nextItemUi.nextElementSibling
}
nextOption = nextOption.nextElementSibling
}
} | javascript | function addMissingItems(groupUi, options) {
let nextItemUi = groupUi.firstElementChild
let nextOption = options.firstElementChild
while (nextOption) {
if (!nextItemUi || nextItemUi._option !== nextOption) {
const newItemUi = document.createElement('szn-')
newItemUi._option = nextOption
newItemUi.setAttribute('data-szn-options--' + (nextOption.tagName === 'OPTGROUP' ? 'optgroup' : 'option'), '')
updateItem(newItemUi)
groupUi.insertBefore(newItemUi, nextItemUi)
} else {
nextItemUi = nextItemUi && nextItemUi.nextElementSibling
}
nextOption = nextOption.nextElementSibling
}
} | [
"function",
"addMissingItems",
"(",
"groupUi",
",",
"options",
")",
"{",
"let",
"nextItemUi",
"=",
"groupUi",
".",
"firstElementChild",
"let",
"nextOption",
"=",
"options",
".",
"firstElementChild",
"while",
"(",
"nextOption",
")",
"{",
"if",
"(",
"!",
"nextItemUi",
"||",
"nextItemUi",
".",
"_option",
"!==",
"nextOption",
")",
"{",
"const",
"newItemUi",
"=",
"document",
".",
"createElement",
"(",
"'szn-'",
")",
"newItemUi",
".",
"_option",
"=",
"nextOption",
"newItemUi",
".",
"setAttribute",
"(",
"'data-szn-options--'",
"+",
"(",
"nextOption",
".",
"tagName",
"===",
"'OPTGROUP'",
"?",
"'optgroup'",
":",
"'option'",
")",
",",
"''",
")",
"updateItem",
"(",
"newItemUi",
")",
"groupUi",
".",
"insertBefore",
"(",
"newItemUi",
",",
"nextItemUi",
")",
"}",
"else",
"{",
"nextItemUi",
"=",
"nextItemUi",
"&&",
"nextItemUi",
".",
"nextElementSibling",
"}",
"nextOption",
"=",
"nextOption",
".",
"nextElementSibling",
"}",
"}"
]
| Adds the options present in the options container missing the UI into the UI, while preserving the order of the
options. Option groups are added recursively.
@param {Element} groupUi The element containing the UIs of the options. The new options will be inserted into this
element's children.
@param {HTMLElement} options An element containing the <code>option</code> and <code>optgroup</code> elements that
the UI reflects. | [
"Adds",
"the",
"options",
"present",
"in",
"the",
"options",
"container",
"missing",
"the",
"UI",
"into",
"the",
"UI",
"while",
"preserving",
"the",
"order",
"of",
"the",
"options",
".",
"Option",
"groups",
"are",
"added",
"recursively",
"."
]
| dc1c2e1f74e25d78643904389cdbaaf48a20b52e | https://github.com/jurca/szn-options/blob/dc1c2e1f74e25d78643904389cdbaaf48a20b52e/szn-options.js#L548-L564 | train |
iAdramelk/css-url-edit | lib/css-url-edit.js | _collectURLs | function _collectURLs ( token ) {
var elem, isArrayElem;
if ( Array.isArray( token ) ) {
for ( var i = 0; i < token.length; i++ ) {
elem = token[ i ];
isArrayElem = Array.isArray( elem );
if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) {
urls.push( elem );
} else if ( isArrayElem ) {
_collectURLs( elem );
}
}
}
} | javascript | function _collectURLs ( token ) {
var elem, isArrayElem;
if ( Array.isArray( token ) ) {
for ( var i = 0; i < token.length; i++ ) {
elem = token[ i ];
isArrayElem = Array.isArray( elem );
if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) {
urls.push( elem );
} else if ( isArrayElem ) {
_collectURLs( elem );
}
}
}
} | [
"function",
"_collectURLs",
"(",
"token",
")",
"{",
"var",
"elem",
",",
"isArrayElem",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"token",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"token",
".",
"length",
";",
"i",
"++",
")",
"{",
"elem",
"=",
"token",
"[",
"i",
"]",
";",
"isArrayElem",
"=",
"Array",
".",
"isArray",
"(",
"elem",
")",
";",
"if",
"(",
"isArrayElem",
"&&",
"(",
"elem",
"[",
"0",
"]",
"===",
"'uri'",
")",
")",
"{",
"urls",
".",
"push",
"(",
"elem",
")",
";",
"}",
"else",
"if",
"(",
"isArrayElem",
")",
"{",
"_collectURLs",
"(",
"elem",
")",
";",
"}",
"}",
"}",
"}"
]
| collection of urls to work with
Generates initial document tree.
@private | [
"collection",
"of",
"urls",
"to",
"work",
"with",
"Generates",
"initial",
"document",
"tree",
"."
]
| 7cbff3b449db5e343a0fe071df138f95468fa60d | https://github.com/iAdramelk/css-url-edit/blob/7cbff3b449db5e343a0fe071df138f95468fa60d/lib/css-url-edit.js#L35-L60 | train |
iAdramelk/css-url-edit | lib/css-url-edit.js | function ( mask ) {
if ( mask && ( mask instanceof RegExp ) !== true ) {
throw { type: 'getURLs', message: 'First argument must be RegExp' };
}
return urls.map( function ( value ) {
return _getURLValue( value );
} ).filter( function ( value, pos, self ) {
var unique = self.indexOf( value ) === pos;
if ( mask && unique ) {
return mask.test( value );
} else {
return unique;
}
} );
} | javascript | function ( mask ) {
if ( mask && ( mask instanceof RegExp ) !== true ) {
throw { type: 'getURLs', message: 'First argument must be RegExp' };
}
return urls.map( function ( value ) {
return _getURLValue( value );
} ).filter( function ( value, pos, self ) {
var unique = self.indexOf( value ) === pos;
if ( mask && unique ) {
return mask.test( value );
} else {
return unique;
}
} );
} | [
"function",
"(",
"mask",
")",
"{",
"if",
"(",
"mask",
"&&",
"(",
"mask",
"instanceof",
"RegExp",
")",
"!==",
"true",
")",
"{",
"throw",
"{",
"type",
":",
"'getURLs'",
",",
"message",
":",
"'First argument must be RegExp'",
"}",
";",
"}",
"return",
"urls",
".",
"map",
"(",
"function",
"(",
"value",
")",
"{",
"return",
"_getURLValue",
"(",
"value",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"value",
",",
"pos",
",",
"self",
")",
"{",
"var",
"unique",
"=",
"self",
".",
"indexOf",
"(",
"value",
")",
"===",
"pos",
";",
"if",
"(",
"mask",
"&&",
"unique",
")",
"{",
"return",
"mask",
".",
"test",
"(",
"value",
")",
";",
"}",
"else",
"{",
"return",
"unique",
";",
"}",
"}",
")",
";",
"}"
]
| Returns list of unique URLs in css document.
@param {regexp} mask RegExp to test URLs against.
@return {array} Array of matchet URLs. | [
"Returns",
"list",
"of",
"unique",
"URLs",
"in",
"css",
"document",
"."
]
| 7cbff3b449db5e343a0fe071df138f95468fa60d | https://github.com/iAdramelk/css-url-edit/blob/7cbff3b449db5e343a0fe071df138f95468fa60d/lib/css-url-edit.js#L105-L133 | train |
|
iAdramelk/css-url-edit | lib/css-url-edit.js | function ( from_value, to_value ) {
var type;
if ( from_value instanceof RegExp ) {
type = 'RegExp';
} else if ( typeof from_value === 'string' ) {
type = 'String';
} else {
throw { type: 'changeURLContent', message: 'First argument must be RegExp of String' };
}
if ( to_value === undefined ) {
to_value = "";
} else if( typeof to_value !== 'string' ) {
throw { type: 'changeURLContent', message: 'Second argument must be String' };
}
urls.filter( function ( value ) {
if ( type === "RegExp" ) {
return from_value.test( _getURLValue( value ) );
} else {
return _getURLValue( value ).indexOf( from_value ) !== -1;
}
} ).forEach( function ( value ) {
var new_value = _getURLValue( value ).replace( from_value, to_value );
_setURLValue( value, new_value );
} );
} | javascript | function ( from_value, to_value ) {
var type;
if ( from_value instanceof RegExp ) {
type = 'RegExp';
} else if ( typeof from_value === 'string' ) {
type = 'String';
} else {
throw { type: 'changeURLContent', message: 'First argument must be RegExp of String' };
}
if ( to_value === undefined ) {
to_value = "";
} else if( typeof to_value !== 'string' ) {
throw { type: 'changeURLContent', message: 'Second argument must be String' };
}
urls.filter( function ( value ) {
if ( type === "RegExp" ) {
return from_value.test( _getURLValue( value ) );
} else {
return _getURLValue( value ).indexOf( from_value ) !== -1;
}
} ).forEach( function ( value ) {
var new_value = _getURLValue( value ).replace( from_value, to_value );
_setURLValue( value, new_value );
} );
} | [
"function",
"(",
"from_value",
",",
"to_value",
")",
"{",
"var",
"type",
";",
"if",
"(",
"from_value",
"instanceof",
"RegExp",
")",
"{",
"type",
"=",
"'RegExp'",
";",
"}",
"else",
"if",
"(",
"typeof",
"from_value",
"===",
"'string'",
")",
"{",
"type",
"=",
"'String'",
";",
"}",
"else",
"{",
"throw",
"{",
"type",
":",
"'changeURLContent'",
",",
"message",
":",
"'First argument must be RegExp of String'",
"}",
";",
"}",
"if",
"(",
"to_value",
"===",
"undefined",
")",
"{",
"to_value",
"=",
"\"\"",
";",
"}",
"else",
"if",
"(",
"typeof",
"to_value",
"!==",
"'string'",
")",
"{",
"throw",
"{",
"type",
":",
"'changeURLContent'",
",",
"message",
":",
"'Second argument must be String'",
"}",
";",
"}",
"urls",
".",
"filter",
"(",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"type",
"===",
"\"RegExp\"",
")",
"{",
"return",
"from_value",
".",
"test",
"(",
"_getURLValue",
"(",
"value",
")",
")",
";",
"}",
"else",
"{",
"return",
"_getURLValue",
"(",
"value",
")",
".",
"indexOf",
"(",
"from_value",
")",
"!==",
"-",
"1",
";",
"}",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"value",
")",
"{",
"var",
"new_value",
"=",
"_getURLValue",
"(",
"value",
")",
".",
"replace",
"(",
"from_value",
",",
"to_value",
")",
";",
"_setURLValue",
"(",
"value",
",",
"new_value",
")",
";",
"}",
")",
";",
"}"
]
| Replace content of every URL matching RegExp with new content.
@param {regexp|string} or from_value Mask to select urls with.
@param {string} to_value Rule to apply on found items. | [
"Replace",
"content",
"of",
"every",
"URL",
"matching",
"RegExp",
"with",
"new",
"content",
"."
]
| 7cbff3b449db5e343a0fe071df138f95468fa60d | https://github.com/iAdramelk/css-url-edit/blob/7cbff3b449db5e343a0fe071df138f95468fa60d/lib/css-url-edit.js#L179-L226 | train |
|
sydneystockholm/blog.md | lib/blog.js | Blog | function Blog(loader, options) {
this.slugs = {};
this.ids = {};
this.posts = [];
this.length = 0;
options = options || {};
if (typeof loader === 'string') {
loader = new FileSystemLoader(loader, options);
} else if (Array.isArray(loader)) {
loader = new ArrayLoader(loader);
}
var self = this;
loader.on('error', function (err) {
self.emit('error', err);
});
loader.on('load', this.onLoad.bind(this));
loader.on('new_post', this.onNewPost.bind(this));
loader.on('updated_post', this.onUpdatedPost.bind(this));
loader.on('removed_post', this.onRemovedPost.bind(this));
} | javascript | function Blog(loader, options) {
this.slugs = {};
this.ids = {};
this.posts = [];
this.length = 0;
options = options || {};
if (typeof loader === 'string') {
loader = new FileSystemLoader(loader, options);
} else if (Array.isArray(loader)) {
loader = new ArrayLoader(loader);
}
var self = this;
loader.on('error', function (err) {
self.emit('error', err);
});
loader.on('load', this.onLoad.bind(this));
loader.on('new_post', this.onNewPost.bind(this));
loader.on('updated_post', this.onUpdatedPost.bind(this));
loader.on('removed_post', this.onRemovedPost.bind(this));
} | [
"function",
"Blog",
"(",
"loader",
",",
"options",
")",
"{",
"this",
".",
"slugs",
"=",
"{",
"}",
";",
"this",
".",
"ids",
"=",
"{",
"}",
";",
"this",
".",
"posts",
"=",
"[",
"]",
";",
"this",
".",
"length",
"=",
"0",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"typeof",
"loader",
"===",
"'string'",
")",
"{",
"loader",
"=",
"new",
"FileSystemLoader",
"(",
"loader",
",",
"options",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"loader",
")",
")",
"{",
"loader",
"=",
"new",
"ArrayLoader",
"(",
"loader",
")",
";",
"}",
"var",
"self",
"=",
"this",
";",
"loader",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
")",
";",
"loader",
".",
"on",
"(",
"'load'",
",",
"this",
".",
"onLoad",
".",
"bind",
"(",
"this",
")",
")",
";",
"loader",
".",
"on",
"(",
"'new_post'",
",",
"this",
".",
"onNewPost",
".",
"bind",
"(",
"this",
")",
")",
";",
"loader",
".",
"on",
"(",
"'updated_post'",
",",
"this",
".",
"onUpdatedPost",
".",
"bind",
"(",
"this",
")",
")",
";",
"loader",
".",
"on",
"(",
"'removed_post'",
",",
"this",
".",
"onRemovedPost",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Create a new blog.
@param {Loader|Array|String} loader
@param {Object} options (optional) | [
"Create",
"a",
"new",
"blog",
"."
]
| 0b145fa1620cbe8b7296eb242241ee93223db9f9 | https://github.com/sydneystockholm/blog.md/blob/0b145fa1620cbe8b7296eb242241ee93223db9f9/lib/blog.js#L16-L35 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/dom/text.js | function( offset ) {
// Saved the children count and text length beforehand.
var parent = this.$.parentNode,
count = parent.childNodes.length,
length = this.getLength();
var doc = this.getDocument();
var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc );
if ( parent.childNodes.length == count )
{
// If the offset is after the last char, IE creates the text node
// on split, but don't include it into the DOM. So, we have to do
// that manually here.
if ( offset >= length )
{
retval = doc.createText( '' );
retval.insertAfter( this );
}
else
{
// IE BUG: IE8+ does not update the childNodes array in DOM after splitText(),
// we need to make some DOM changes to make it update. (#3436)
var workaround = doc.createText( '' );
workaround.insertAfter( retval );
workaround.remove();
}
}
return retval;
} | javascript | function( offset ) {
// Saved the children count and text length beforehand.
var parent = this.$.parentNode,
count = parent.childNodes.length,
length = this.getLength();
var doc = this.getDocument();
var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc );
if ( parent.childNodes.length == count )
{
// If the offset is after the last char, IE creates the text node
// on split, but don't include it into the DOM. So, we have to do
// that manually here.
if ( offset >= length )
{
retval = doc.createText( '' );
retval.insertAfter( this );
}
else
{
// IE BUG: IE8+ does not update the childNodes array in DOM after splitText(),
// we need to make some DOM changes to make it update. (#3436)
var workaround = doc.createText( '' );
workaround.insertAfter( retval );
workaround.remove();
}
}
return retval;
} | [
"function",
"(",
"offset",
")",
"{",
"var",
"parent",
"=",
"this",
".",
"$",
".",
"parentNode",
",",
"count",
"=",
"parent",
".",
"childNodes",
".",
"length",
",",
"length",
"=",
"this",
".",
"getLength",
"(",
")",
";",
"var",
"doc",
"=",
"this",
".",
"getDocument",
"(",
")",
";",
"var",
"retval",
"=",
"new",
"CKEDITOR",
".",
"dom",
".",
"text",
"(",
"this",
".",
"$",
".",
"splitText",
"(",
"offset",
")",
",",
"doc",
")",
";",
"if",
"(",
"parent",
".",
"childNodes",
".",
"length",
"==",
"count",
")",
"{",
"if",
"(",
"offset",
">=",
"length",
")",
"{",
"retval",
"=",
"doc",
".",
"createText",
"(",
"''",
")",
";",
"retval",
".",
"insertAfter",
"(",
"this",
")",
";",
"}",
"else",
"{",
"var",
"workaround",
"=",
"doc",
".",
"createText",
"(",
"''",
")",
";",
"workaround",
".",
"insertAfter",
"(",
"retval",
")",
";",
"workaround",
".",
"remove",
"(",
")",
";",
"}",
"}",
"return",
"retval",
";",
"}"
]
| Breaks this text node into two nodes at the specified offset,
keeping both in the tree as siblings. This node then only contains
all the content up to the offset point. A new text node, which is
inserted as the next sibling of this node, contains all the content
at and after the offset point. When the offset is equal to the
length of this node, the new node has no data.
@param {Number} The position at which to split, starting from zero.
@returns {CKEDITOR.dom.text} The new text node. | [
"Breaks",
"this",
"text",
"node",
"into",
"two",
"nodes",
"at",
"the",
"specified",
"offset",
"keeping",
"both",
"in",
"the",
"tree",
"as",
"siblings",
".",
"This",
"node",
"then",
"only",
"contains",
"all",
"the",
"content",
"up",
"to",
"the",
"offset",
"point",
".",
"A",
"new",
"text",
"node",
"which",
"is",
"inserted",
"as",
"the",
"next",
"sibling",
"of",
"this",
"node",
"contains",
"all",
"the",
"content",
"at",
"and",
"after",
"the",
"offset",
"point",
".",
"When",
"the",
"offset",
"is",
"equal",
"to",
"the",
"length",
"of",
"this",
"node",
"the",
"new",
"node",
"has",
"no",
"data",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/text.js#L90-L121 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/dom/text.js | function( indexA, indexB ) {
// We need the following check due to a Firefox bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=458886
if ( typeof indexB != 'number' )
return this.$.nodeValue.substr( indexA );
else
return this.$.nodeValue.substring( indexA, indexB );
} | javascript | function( indexA, indexB ) {
// We need the following check due to a Firefox bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=458886
if ( typeof indexB != 'number' )
return this.$.nodeValue.substr( indexA );
else
return this.$.nodeValue.substring( indexA, indexB );
} | [
"function",
"(",
"indexA",
",",
"indexB",
")",
"{",
"if",
"(",
"typeof",
"indexB",
"!=",
"'number'",
")",
"return",
"this",
".",
"$",
".",
"nodeValue",
".",
"substr",
"(",
"indexA",
")",
";",
"else",
"return",
"this",
".",
"$",
".",
"nodeValue",
".",
"substring",
"(",
"indexA",
",",
"indexB",
")",
";",
"}"
]
| Extracts characters from indexA up to but not including `indexB`.
@param {Number} indexA An integer between `0` and one less than the
length of the text.
@param {Number} [indexB] An integer between `0` and the length of the
string. If omitted, extracts characters to the end of the text. | [
"Extracts",
"characters",
"from",
"indexA",
"up",
"to",
"but",
"not",
"including",
"indexB",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/text.js#L131-L138 | train |
|
zeustrismegistus/dformat | dformat.js | setTypeValueFromInstance | function setTypeValueFromInstance(node)
{
var val = node.instance;
if(val === undefined)
{
node.type = "undefined";
node.value = "undefined";
}
else if(val === null)
{
node.type = "null";
node.value = "null";
}
else
{
var valType = typeof val;
if(valType === "boolean")
{
node.type = "boolean";
node.value = val.toString();
}
else if (valType === "number")
{
node.type = "number";
node.value = val.toString();
}
else if (valType === "string")
{
node.type = "string";
node.value = val;
}
else if (valType === "symbol")
{
node.type = "symbol";
node.value = val.toString();
}
else if(valType === "function")
{
node.type = "function";
node.value = val.toString();
}
else if(val instanceof Date)
{
node.type = "date";
node.value = val.getTime().toString();
}
else if(val instanceof Array)
{
node.type = "array";
}
else if(jsmeta.isEmpty(val))
{
node.type = "empty";
node.value = "empty";
}
else
{
node.type = "object";
}
}
} | javascript | function setTypeValueFromInstance(node)
{
var val = node.instance;
if(val === undefined)
{
node.type = "undefined";
node.value = "undefined";
}
else if(val === null)
{
node.type = "null";
node.value = "null";
}
else
{
var valType = typeof val;
if(valType === "boolean")
{
node.type = "boolean";
node.value = val.toString();
}
else if (valType === "number")
{
node.type = "number";
node.value = val.toString();
}
else if (valType === "string")
{
node.type = "string";
node.value = val;
}
else if (valType === "symbol")
{
node.type = "symbol";
node.value = val.toString();
}
else if(valType === "function")
{
node.type = "function";
node.value = val.toString();
}
else if(val instanceof Date)
{
node.type = "date";
node.value = val.getTime().toString();
}
else if(val instanceof Array)
{
node.type = "array";
}
else if(jsmeta.isEmpty(val))
{
node.type = "empty";
node.value = "empty";
}
else
{
node.type = "object";
}
}
} | [
"function",
"setTypeValueFromInstance",
"(",
"node",
")",
"{",
"var",
"val",
"=",
"node",
".",
"instance",
";",
"if",
"(",
"val",
"===",
"undefined",
")",
"{",
"node",
".",
"type",
"=",
"\"undefined\"",
";",
"node",
".",
"value",
"=",
"\"undefined\"",
";",
"}",
"else",
"if",
"(",
"val",
"===",
"null",
")",
"{",
"node",
".",
"type",
"=",
"\"null\"",
";",
"node",
".",
"value",
"=",
"\"null\"",
";",
"}",
"else",
"{",
"var",
"valType",
"=",
"typeof",
"val",
";",
"if",
"(",
"valType",
"===",
"\"boolean\"",
")",
"{",
"node",
".",
"type",
"=",
"\"boolean\"",
";",
"node",
".",
"value",
"=",
"val",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"valType",
"===",
"\"number\"",
")",
"{",
"node",
".",
"type",
"=",
"\"number\"",
";",
"node",
".",
"value",
"=",
"val",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"valType",
"===",
"\"string\"",
")",
"{",
"node",
".",
"type",
"=",
"\"string\"",
";",
"node",
".",
"value",
"=",
"val",
";",
"}",
"else",
"if",
"(",
"valType",
"===",
"\"symbol\"",
")",
"{",
"node",
".",
"type",
"=",
"\"symbol\"",
";",
"node",
".",
"value",
"=",
"val",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"valType",
"===",
"\"function\"",
")",
"{",
"node",
".",
"type",
"=",
"\"function\"",
";",
"node",
".",
"value",
"=",
"val",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"val",
"instanceof",
"Date",
")",
"{",
"node",
".",
"type",
"=",
"\"date\"",
";",
"node",
".",
"value",
"=",
"val",
".",
"getTime",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"else",
"if",
"(",
"val",
"instanceof",
"Array",
")",
"{",
"node",
".",
"type",
"=",
"\"array\"",
";",
"}",
"else",
"if",
"(",
"jsmeta",
".",
"isEmpty",
"(",
"val",
")",
")",
"{",
"node",
".",
"type",
"=",
"\"empty\"",
";",
"node",
".",
"value",
"=",
"\"empty\"",
";",
"}",
"else",
"{",
"node",
".",
"type",
"=",
"\"object\"",
";",
"}",
"}",
"}"
]
| hydrates type and value properties from a value | [
"hydrates",
"type",
"and",
"value",
"properties",
"from",
"a",
"value"
]
| 8f2b90a3dfd4ae440530f695558f7dfd51cd54c4 | https://github.com/zeustrismegistus/dformat/blob/8f2b90a3dfd4ae440530f695558f7dfd51cd54c4/dformat.js#L221-L282 | train |
zeustrismegistus/dformat | dformat.js | setInstanceFromTypeValue | function setInstanceFromTypeValue(node)
{
if(node.type == "undefined")
{
node.instance = undefined;
}
else if(node.type === "boolean")
{
node.instance = Boolean(node.value);
}
else if (node.type === "number")
{
node.instance = Number(node.value);
}
else if (node.type === "string")
{
node.instance = node.value;
}
else if (node.type === "symbol")
{
node.instance = Symbol(node.value);
}
else if(node.type === "function")
{
var fn;
eval("fn = " + node.value);
node.instance = fn;
}
else if(node.type === "null")
{
node.instance = null;
}
else if(node.type === "date")
{
node.instance = new Date(Number(node.value))
}
else if(node.type === "array")
{
node.instance = [];
}
else if(node.type === "empty")
{
node.instance = {};
}
else
{
/* $lab:coverage:off$ */
if(node.type !== "object")
throw new Error("object expected");
/* $lab:coverage:on$ */
node.instance = {};
}
} | javascript | function setInstanceFromTypeValue(node)
{
if(node.type == "undefined")
{
node.instance = undefined;
}
else if(node.type === "boolean")
{
node.instance = Boolean(node.value);
}
else if (node.type === "number")
{
node.instance = Number(node.value);
}
else if (node.type === "string")
{
node.instance = node.value;
}
else if (node.type === "symbol")
{
node.instance = Symbol(node.value);
}
else if(node.type === "function")
{
var fn;
eval("fn = " + node.value);
node.instance = fn;
}
else if(node.type === "null")
{
node.instance = null;
}
else if(node.type === "date")
{
node.instance = new Date(Number(node.value))
}
else if(node.type === "array")
{
node.instance = [];
}
else if(node.type === "empty")
{
node.instance = {};
}
else
{
/* $lab:coverage:off$ */
if(node.type !== "object")
throw new Error("object expected");
/* $lab:coverage:on$ */
node.instance = {};
}
} | [
"function",
"setInstanceFromTypeValue",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"==",
"\"undefined\"",
")",
"{",
"node",
".",
"instance",
"=",
"undefined",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"boolean\"",
")",
"{",
"node",
".",
"instance",
"=",
"Boolean",
"(",
"node",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"number\"",
")",
"{",
"node",
".",
"instance",
"=",
"Number",
"(",
"node",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"string\"",
")",
"{",
"node",
".",
"instance",
"=",
"node",
".",
"value",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"symbol\"",
")",
"{",
"node",
".",
"instance",
"=",
"Symbol",
"(",
"node",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"function\"",
")",
"{",
"var",
"fn",
";",
"eval",
"(",
"\"fn = \"",
"+",
"node",
".",
"value",
")",
";",
"node",
".",
"instance",
"=",
"fn",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"null\"",
")",
"{",
"node",
".",
"instance",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"date\"",
")",
"{",
"node",
".",
"instance",
"=",
"new",
"Date",
"(",
"Number",
"(",
"node",
".",
"value",
")",
")",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"array\"",
")",
"{",
"node",
".",
"instance",
"=",
"[",
"]",
";",
"}",
"else",
"if",
"(",
"node",
".",
"type",
"===",
"\"empty\"",
")",
"{",
"node",
".",
"instance",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"if",
"(",
"node",
".",
"type",
"!==",
"\"object\"",
")",
"throw",
"new",
"Error",
"(",
"\"object expected\"",
")",
";",
"node",
".",
"instance",
"=",
"{",
"}",
";",
"}",
"}"
]
| does the reverse of setTypeValue | [
"does",
"the",
"reverse",
"of",
"setTypeValue"
]
| 8f2b90a3dfd4ae440530f695558f7dfd51cd54c4 | https://github.com/zeustrismegistus/dformat/blob/8f2b90a3dfd4ae440530f695558f7dfd51cd54c4/dformat.js#L285-L339 | train |
saebekassebil/erroneous | lib/erroneous.js | ErroneousError | function ErroneousError(e, additional) {
additional = additional || {};
this.line = e.lineno || e.lineNumber || additional.lineno;
this.file = e.filename || e.fileName || additional.filename;
this.msg = e.message || additional.message;
this.time = e.timestamp || additional.timestamp || Date.now();
this.type = (this.parseMessage(this.msg) || e.type || e.name).toLowerCase();
// If it's a DOM node, let's figure out which
if (e.target) {
this.target = this.getTargetIdentifier(e.target);
if (e.target.nodeName) {
this.type = 'resource';
if (e.target.href) {
this.file = e.target.href;
} else if (e.target.src) {
this.file = e.target.src;
}
}
}
// Parse the stack if any
this.stack = e.stack;
this.parseStack(e.stack);
} | javascript | function ErroneousError(e, additional) {
additional = additional || {};
this.line = e.lineno || e.lineNumber || additional.lineno;
this.file = e.filename || e.fileName || additional.filename;
this.msg = e.message || additional.message;
this.time = e.timestamp || additional.timestamp || Date.now();
this.type = (this.parseMessage(this.msg) || e.type || e.name).toLowerCase();
// If it's a DOM node, let's figure out which
if (e.target) {
this.target = this.getTargetIdentifier(e.target);
if (e.target.nodeName) {
this.type = 'resource';
if (e.target.href) {
this.file = e.target.href;
} else if (e.target.src) {
this.file = e.target.src;
}
}
}
// Parse the stack if any
this.stack = e.stack;
this.parseStack(e.stack);
} | [
"function",
"ErroneousError",
"(",
"e",
",",
"additional",
")",
"{",
"additional",
"=",
"additional",
"||",
"{",
"}",
";",
"this",
".",
"line",
"=",
"e",
".",
"lineno",
"||",
"e",
".",
"lineNumber",
"||",
"additional",
".",
"lineno",
";",
"this",
".",
"file",
"=",
"e",
".",
"filename",
"||",
"e",
".",
"fileName",
"||",
"additional",
".",
"filename",
";",
"this",
".",
"msg",
"=",
"e",
".",
"message",
"||",
"additional",
".",
"message",
";",
"this",
".",
"time",
"=",
"e",
".",
"timestamp",
"||",
"additional",
".",
"timestamp",
"||",
"Date",
".",
"now",
"(",
")",
";",
"this",
".",
"type",
"=",
"(",
"this",
".",
"parseMessage",
"(",
"this",
".",
"msg",
")",
"||",
"e",
".",
"type",
"||",
"e",
".",
"name",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"e",
".",
"target",
")",
"{",
"this",
".",
"target",
"=",
"this",
".",
"getTargetIdentifier",
"(",
"e",
".",
"target",
")",
";",
"if",
"(",
"e",
".",
"target",
".",
"nodeName",
")",
"{",
"this",
".",
"type",
"=",
"'resource'",
";",
"if",
"(",
"e",
".",
"target",
".",
"href",
")",
"{",
"this",
".",
"file",
"=",
"e",
".",
"target",
".",
"href",
";",
"}",
"else",
"if",
"(",
"e",
".",
"target",
".",
"src",
")",
"{",
"this",
".",
"file",
"=",
"e",
".",
"target",
".",
"src",
";",
"}",
"}",
"}",
"this",
".",
"stack",
"=",
"e",
".",
"stack",
";",
"this",
".",
"parseStack",
"(",
"e",
".",
"stack",
")",
";",
"}"
]
| Object for storing error details
Only used internally | [
"Object",
"for",
"storing",
"error",
"details",
"Only",
"used",
"internally"
]
| 05a104db15373bd302202ec544e65a4d8bd5ce02 | https://github.com/saebekassebil/erroneous/blob/05a104db15373bd302202ec544e65a4d8bd5ce02/lib/erroneous.js#L13-L38 | train |
Pocketbrain/native-ads-web-ad-library | src/ads/adBuilder.js | _replaceMacros | function _replaceMacros(s, macros, obj) {
var regex = null;
for (var i = 0; i < macros.length; i++) {
var macro = macros[i];
regex = new RegExp(macro.macro, "g");
s = s.replace(regex, obj[macro.prop]);
}
return s;
} | javascript | function _replaceMacros(s, macros, obj) {
var regex = null;
for (var i = 0; i < macros.length; i++) {
var macro = macros[i];
regex = new RegExp(macro.macro, "g");
s = s.replace(regex, obj[macro.prop]);
}
return s;
} | [
"function",
"_replaceMacros",
"(",
"s",
",",
"macros",
",",
"obj",
")",
"{",
"var",
"regex",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"macros",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"macro",
"=",
"macros",
"[",
"i",
"]",
";",
"regex",
"=",
"new",
"RegExp",
"(",
"macro",
".",
"macro",
",",
"\"g\"",
")",
";",
"s",
"=",
"s",
".",
"replace",
"(",
"regex",
",",
"obj",
"[",
"macro",
".",
"prop",
"]",
")",
";",
"}",
"return",
"s",
";",
"}"
]
| Replaces macros in a string with the properties of an object
@param s The string to replace the macros in
@param macros The macros to replace the string with
@param obj the object to get the macro properties from
@returns {String} - The string with the macros replaced
@private | [
"Replaces",
"macros",
"in",
"a",
"string",
"with",
"the",
"properties",
"of",
"an",
"object"
]
| aafee1c42e0569ee77f334fc2c4eb71eb146957e | https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/ads/adBuilder.js#L70-L80 | train |
AndiDittrich/Node.async-magic | lib/series.js | series | async function series(resolvers){
// buffer
const results = [];
// run resolvers in series
for (const r of resolvers){
results.push(await r.resolve());
}
// return results
return results;
} | javascript | async function series(resolvers){
// buffer
const results = [];
// run resolvers in series
for (const r of resolvers){
results.push(await r.resolve());
}
// return results
return results;
} | [
"async",
"function",
"series",
"(",
"resolvers",
")",
"{",
"const",
"results",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"r",
"of",
"resolvers",
")",
"{",
"results",
".",
"push",
"(",
"await",
"r",
".",
"resolve",
"(",
")",
")",
";",
"}",
"return",
"results",
";",
"}"
]
| resolves multiple promises in series | [
"resolves",
"multiple",
"promises",
"in",
"series"
]
| 0c41dd27d8f7539bb24034bc23ce870f5f8a10b3 | https://github.com/AndiDittrich/Node.async-magic/blob/0c41dd27d8f7539bb24034bc23ce870f5f8a10b3/lib/series.js#L2-L13 | train |
ikondrat/franky | src/etc/components.js | function (componentDescription) {
var i = components.length,
app;
// Old-school declaration
// > franky.Component.extend({
// id: 'hello',
// init: function () {
// console.log('hello');
// }
// });
if (franky.isObject(componentDescription)) {
app = franky.beget(franky.ComponentBase, componentDescription);
// Short form declaration
// > franky.Component.extend('hello', function () {
// console.log('hello');
// });
} else if (franky.isString(componentDescription) && franky.isFunction(arguments[1])) {
app = franky.beget(franky.ComponentBase, {
id: componentDescription,
init: arguments[1]
});
// Dependencies injection form declaration
// > franky.Component.extend('hello', ['$logger', function ($logger) {
// $logger.say('hello');
// }]);
} else if (franky.isString(componentDescription) && franky.isArray(arguments[1])) {
var args = arguments[1];
app = franky.beget(franky.ComponentBase, {
id: componentDescription,
init: function () {
var deps = franky.filter(args, function (item) {
return franky.isString(item);
});
deps = franky.map(deps, function (serviceName) {
if (!services[serviceName]) {
throw new Error('Service ' + serviceName + ' hasnt defined');
}
return services[serviceName]();
});
var defs = franky.filter(args, function (item) {
return franky.isFunction(item);
});
if (defs.length > 1) {
throw new Error('Too much declaration functions');
}
defs[0].apply(this, deps);
}
});
} else {
throw new Error('Unknown definition structure, try to use extend("yourName", function() { ... init code ... })');
}
if (!app.id) {
franky.error('extend method expects id field in description object');
}
components.push(app);
// fill index
componentsIndex[app.id] = i;
return components[i];
} | javascript | function (componentDescription) {
var i = components.length,
app;
// Old-school declaration
// > franky.Component.extend({
// id: 'hello',
// init: function () {
// console.log('hello');
// }
// });
if (franky.isObject(componentDescription)) {
app = franky.beget(franky.ComponentBase, componentDescription);
// Short form declaration
// > franky.Component.extend('hello', function () {
// console.log('hello');
// });
} else if (franky.isString(componentDescription) && franky.isFunction(arguments[1])) {
app = franky.beget(franky.ComponentBase, {
id: componentDescription,
init: arguments[1]
});
// Dependencies injection form declaration
// > franky.Component.extend('hello', ['$logger', function ($logger) {
// $logger.say('hello');
// }]);
} else if (franky.isString(componentDescription) && franky.isArray(arguments[1])) {
var args = arguments[1];
app = franky.beget(franky.ComponentBase, {
id: componentDescription,
init: function () {
var deps = franky.filter(args, function (item) {
return franky.isString(item);
});
deps = franky.map(deps, function (serviceName) {
if (!services[serviceName]) {
throw new Error('Service ' + serviceName + ' hasnt defined');
}
return services[serviceName]();
});
var defs = franky.filter(args, function (item) {
return franky.isFunction(item);
});
if (defs.length > 1) {
throw new Error('Too much declaration functions');
}
defs[0].apply(this, deps);
}
});
} else {
throw new Error('Unknown definition structure, try to use extend("yourName", function() { ... init code ... })');
}
if (!app.id) {
franky.error('extend method expects id field in description object');
}
components.push(app);
// fill index
componentsIndex[app.id] = i;
return components[i];
} | [
"function",
"(",
"componentDescription",
")",
"{",
"var",
"i",
"=",
"components",
".",
"length",
",",
"app",
";",
"if",
"(",
"franky",
".",
"isObject",
"(",
"componentDescription",
")",
")",
"{",
"app",
"=",
"franky",
".",
"beget",
"(",
"franky",
".",
"ComponentBase",
",",
"componentDescription",
")",
";",
"}",
"else",
"if",
"(",
"franky",
".",
"isString",
"(",
"componentDescription",
")",
"&&",
"franky",
".",
"isFunction",
"(",
"arguments",
"[",
"1",
"]",
")",
")",
"{",
"app",
"=",
"franky",
".",
"beget",
"(",
"franky",
".",
"ComponentBase",
",",
"{",
"id",
":",
"componentDescription",
",",
"init",
":",
"arguments",
"[",
"1",
"]",
"}",
")",
";",
"}",
"else",
"if",
"(",
"franky",
".",
"isString",
"(",
"componentDescription",
")",
"&&",
"franky",
".",
"isArray",
"(",
"arguments",
"[",
"1",
"]",
")",
")",
"{",
"var",
"args",
"=",
"arguments",
"[",
"1",
"]",
";",
"app",
"=",
"franky",
".",
"beget",
"(",
"franky",
".",
"ComponentBase",
",",
"{",
"id",
":",
"componentDescription",
",",
"init",
":",
"function",
"(",
")",
"{",
"var",
"deps",
"=",
"franky",
".",
"filter",
"(",
"args",
",",
"function",
"(",
"item",
")",
"{",
"return",
"franky",
".",
"isString",
"(",
"item",
")",
";",
"}",
")",
";",
"deps",
"=",
"franky",
".",
"map",
"(",
"deps",
",",
"function",
"(",
"serviceName",
")",
"{",
"if",
"(",
"!",
"services",
"[",
"serviceName",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Service '",
"+",
"serviceName",
"+",
"' hasnt defined'",
")",
";",
"}",
"return",
"services",
"[",
"serviceName",
"]",
"(",
")",
";",
"}",
")",
";",
"var",
"defs",
"=",
"franky",
".",
"filter",
"(",
"args",
",",
"function",
"(",
"item",
")",
"{",
"return",
"franky",
".",
"isFunction",
"(",
"item",
")",
";",
"}",
")",
";",
"if",
"(",
"defs",
".",
"length",
">",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Too much declaration functions'",
")",
";",
"}",
"defs",
"[",
"0",
"]",
".",
"apply",
"(",
"this",
",",
"deps",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown definition structure, try to use extend(\"yourName\", function() { ... init code ... })'",
")",
";",
"}",
"if",
"(",
"!",
"app",
".",
"id",
")",
"{",
"franky",
".",
"error",
"(",
"'extend method expects id field in description object'",
")",
";",
"}",
"components",
".",
"push",
"(",
"app",
")",
";",
"componentsIndex",
"[",
"app",
".",
"id",
"]",
"=",
"i",
";",
"return",
"components",
"[",
"i",
"]",
";",
"}"
]
| Cornerstone of Component moodule - method for creating new components | [
"Cornerstone",
"of",
"Component",
"moodule",
"-",
"method",
"for",
"creating",
"new",
"components"
]
| 6a7368891f39620a225e37c4a56d2bf99644c3e7 | https://github.com/ikondrat/franky/blob/6a7368891f39620a225e37c4a56d2bf99644c3e7/src/etc/components.js#L37-L100 | train |
|
craiglonsdale/repohelper | lib/pullRequests.js | getPRsForRepo | function getPRsForRepo(repo) {
print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug);
return new Promise((resolve, reject) => {
github.pullRequests.getAll({
user: repo.owner.login,
repo: repo.name,
state: 'open'
}, (err, prs) => {
if (err) {
return reject(err);
}
return resolve(prs.filter((pr) => {
return pr && pr.head;
}));
});
});
} | javascript | function getPRsForRepo(repo) {
print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug);
return new Promise((resolve, reject) => {
github.pullRequests.getAll({
user: repo.owner.login,
repo: repo.name,
state: 'open'
}, (err, prs) => {
if (err) {
return reject(err);
}
return resolve(prs.filter((pr) => {
return pr && pr.head;
}));
});
});
} | [
"function",
"getPRsForRepo",
"(",
"repo",
")",
"{",
"print",
"(",
"[",
"'Fetching PRs for '",
",",
"clc",
".",
"yellow",
".",
"bold",
"(",
"`",
"${",
"repo",
".",
"owner",
".",
"login",
"}",
"${",
"repo",
".",
"name",
"}",
"`",
")",
"]",
",",
"debug",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"github",
".",
"pullRequests",
".",
"getAll",
"(",
"{",
"user",
":",
"repo",
".",
"owner",
".",
"login",
",",
"repo",
":",
"repo",
".",
"name",
",",
"state",
":",
"'open'",
"}",
",",
"(",
"err",
",",
"prs",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"return",
"resolve",
"(",
"prs",
".",
"filter",
"(",
"(",
"pr",
")",
"=>",
"{",
"return",
"pr",
"&&",
"pr",
".",
"head",
";",
"}",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Fetch open pull requests for a single repository
@param {Object} repo Repository metadata
@return {Promise} Resolves to a list of pull requests | [
"Fetch",
"open",
"pull",
"requests",
"for",
"a",
"single",
"repository"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L71-L87 | train |
craiglonsdale/repohelper | lib/pullRequests.js | populateLabelsForPR | function populateLabelsForPR(pr) {
print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
return new Promise((resolve) => {
github.issues.getIssueLabels({
user: pr.base.user.login,
repo: pr.base.repo.name,
number: pr.number
}, function (err, labels) {
if (err && debug) {
print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug);
}
if (labels && labels.length > 0) {
pr.labels = labels.map((label) => {
return {
name: label.name,
color: label.color
};
});
}
return resolve(pr);
});
});
} | javascript | function populateLabelsForPR(pr) {
print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
return new Promise((resolve) => {
github.issues.getIssueLabels({
user: pr.base.user.login,
repo: pr.base.repo.name,
number: pr.number
}, function (err, labels) {
if (err && debug) {
print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug);
}
if (labels && labels.length > 0) {
pr.labels = labels.map((label) => {
return {
name: label.name,
color: label.color
};
});
}
return resolve(pr);
});
});
} | [
"function",
"populateLabelsForPR",
"(",
"pr",
")",
"{",
"print",
"(",
"[",
"'Get labels for PR '",
",",
"clc",
".",
"yellow",
".",
"bold",
"(",
"`",
"${",
"pr",
".",
"head",
".",
"user",
".",
"login",
"}",
"${",
"pr",
".",
"head",
".",
"repo",
".",
"name",
"}",
"${",
"pr",
".",
"number",
"}",
"`",
")",
"]",
",",
"debug",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
")",
"=>",
"{",
"github",
".",
"issues",
".",
"getIssueLabels",
"(",
"{",
"user",
":",
"pr",
".",
"base",
".",
"user",
".",
"login",
",",
"repo",
":",
"pr",
".",
"base",
".",
"repo",
".",
"name",
",",
"number",
":",
"pr",
".",
"number",
"}",
",",
"function",
"(",
"err",
",",
"labels",
")",
"{",
"if",
"(",
"err",
"&&",
"debug",
")",
"{",
"print",
"(",
"[",
"'Error fetching labels for PR '",
",",
"clc",
".",
"red",
".",
"bold",
"`",
"${",
"pr",
".",
"base",
".",
"user",
".",
"login",
"}",
"${",
"pr",
".",
"base",
".",
"repo",
".",
"name",
"}",
"${",
"pr",
".",
"number",
"}",
"`",
"]",
",",
"debug",
")",
";",
"}",
"if",
"(",
"labels",
"&&",
"labels",
".",
"length",
">",
"0",
")",
"{",
"pr",
".",
"labels",
"=",
"labels",
".",
"map",
"(",
"(",
"label",
")",
"=>",
"{",
"return",
"{",
"name",
":",
"label",
".",
"name",
",",
"color",
":",
"label",
".",
"color",
"}",
";",
"}",
")",
";",
"}",
"return",
"resolve",
"(",
"pr",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Fetch a list of labels for a single pull-request
@param {Object} pr Pull-request metadata
@return {Promise} Resolves to an array of labels | [
"Fetch",
"a",
"list",
"of",
"labels",
"for",
"a",
"single",
"pull",
"-",
"request"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L94-L116 | train |
craiglonsdale/repohelper | lib/pullRequests.js | getLabels | function getLabels(prs) {
return Promise.all(prs.reduce((flattenedPRs, pr) => {
if (pr) {
return flattenedPRs.concat(pr);
}
}, []).map(populateLabelsForPR));
} | javascript | function getLabels(prs) {
return Promise.all(prs.reduce((flattenedPRs, pr) => {
if (pr) {
return flattenedPRs.concat(pr);
}
}, []).map(populateLabelsForPR));
} | [
"function",
"getLabels",
"(",
"prs",
")",
"{",
"return",
"Promise",
".",
"all",
"(",
"prs",
".",
"reduce",
"(",
"(",
"flattenedPRs",
",",
"pr",
")",
"=>",
"{",
"if",
"(",
"pr",
")",
"{",
"return",
"flattenedPRs",
".",
"concat",
"(",
"pr",
")",
";",
"}",
"}",
",",
"[",
"]",
")",
".",
"map",
"(",
"populateLabelsForPR",
")",
")",
";",
"}"
]
| Fetch labels for a list of pull-requests
@param {Array} repos List of pull-requests
@return {Promise} Resolves to an array of PRs containing labels | [
"Fetch",
"labels",
"for",
"a",
"list",
"of",
"pull",
"-",
"requests"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L123-L129 | train |
craiglonsdale/repohelper | lib/pullRequests.js | analyzePatch | function analyzePatch(patch) {
const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => {
if (currentLine.match(/^[-+]/)) {
return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, ''));
}
return reducedPatch;
}, []);
return {
lines: patchLines.length,
chars: patchLines.join('').length
};
} | javascript | function analyzePatch(patch) {
const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => {
if (currentLine.match(/^[-+]/)) {
return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, ''));
}
return reducedPatch;
}, []);
return {
lines: patchLines.length,
chars: patchLines.join('').length
};
} | [
"function",
"analyzePatch",
"(",
"patch",
")",
"{",
"const",
"patchLines",
"=",
"patch",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"reduce",
";",
"(",
"(",
"reducedPatch",
",",
"currentLine",
")",
"=>",
"{",
"if",
"(",
"currentLine",
".",
"match",
"(",
"/",
"^[-+]",
"/",
")",
")",
"{",
"return",
"reducedPatch",
".",
"concat",
"(",
"currentLine",
".",
"replace",
"(",
"/",
"^[-+]+\\s*",
"/",
",",
"''",
")",
")",
";",
"}",
"return",
"reducedPatch",
";",
"}",
",",
"[",
"]",
")",
"}"
]
| Reduce a patch down to just changed lines
@param {String} patch The complete patch with surrounding context
@return {Object} Stats about the changed lines | [
"Reduce",
"a",
"patch",
"down",
"to",
"just",
"changed",
"lines"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L148-L159 | train |
craiglonsdale/repohelper | lib/pullRequests.js | extractDiffData | function extractDiffData(diff) {
print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug);
return {
user: diff.user,
repo: diff.repo,
title: diff.title,
number: diff.number,
link: diff.link,
createdAt: diff.createdAt,
updatedAt: diff.updatedAt,
labels: diff.labels,
aheadBy: diff.ahead_by,
behindBy: diff.behind_by,
status: diff.status,
totalCommits: diff.total_commits,
author: {
login: diff.merge_base_commit.author ? diff.merge_base_commit.author.login : 'Unknown',
avatarUrl: diff.merge_base_commit.author ? diff.merge_base_commit.author.avatar_url : '',
},
files: diff.files.map((file) => {
return {
filename: file.filename,
status: file.status,
additions: file.additions,
deletions: file.deletions,
changes: file.changes,
patch: analyzePatch(file.patch || '')
};
})
};
} | javascript | function extractDiffData(diff) {
print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug);
return {
user: diff.user,
repo: diff.repo,
title: diff.title,
number: diff.number,
link: diff.link,
createdAt: diff.createdAt,
updatedAt: diff.updatedAt,
labels: diff.labels,
aheadBy: diff.ahead_by,
behindBy: diff.behind_by,
status: diff.status,
totalCommits: diff.total_commits,
author: {
login: diff.merge_base_commit.author ? diff.merge_base_commit.author.login : 'Unknown',
avatarUrl: diff.merge_base_commit.author ? diff.merge_base_commit.author.avatar_url : '',
},
files: diff.files.map((file) => {
return {
filename: file.filename,
status: file.status,
additions: file.additions,
deletions: file.deletions,
changes: file.changes,
patch: analyzePatch(file.patch || '')
};
})
};
} | [
"function",
"extractDiffData",
"(",
"diff",
")",
"{",
"print",
"(",
"[",
"'Extract diff for '",
",",
"clc",
".",
"yellow",
".",
"bold",
"(",
"`",
"${",
"diff",
".",
"user",
"}",
"${",
"diff",
".",
"repo",
"}",
"${",
"diff",
".",
"number",
"}",
"`",
")",
",",
"clc",
".",
"white",
".",
"italic",
"(",
"`",
"${",
"diff",
".",
"title",
"}",
"`",
")",
"]",
",",
"debug",
")",
";",
"return",
"{",
"user",
":",
"diff",
".",
"user",
",",
"repo",
":",
"diff",
".",
"repo",
",",
"title",
":",
"diff",
".",
"title",
",",
"number",
":",
"diff",
".",
"number",
",",
"link",
":",
"diff",
".",
"link",
",",
"createdAt",
":",
"diff",
".",
"createdAt",
",",
"updatedAt",
":",
"diff",
".",
"updatedAt",
",",
"labels",
":",
"diff",
".",
"labels",
",",
"aheadBy",
":",
"diff",
".",
"ahead_by",
",",
"behindBy",
":",
"diff",
".",
"behind_by",
",",
"status",
":",
"diff",
".",
"status",
",",
"totalCommits",
":",
"diff",
".",
"total_commits",
",",
"author",
":",
"{",
"login",
":",
"diff",
".",
"merge_base_commit",
".",
"author",
"?",
"diff",
".",
"merge_base_commit",
".",
"author",
".",
"login",
":",
"'Unknown'",
",",
"avatarUrl",
":",
"diff",
".",
"merge_base_commit",
".",
"author",
"?",
"diff",
".",
"merge_base_commit",
".",
"author",
".",
"avatar_url",
":",
"''",
",",
"}",
",",
"files",
":",
"diff",
".",
"files",
".",
"map",
"(",
"(",
"file",
")",
"=>",
"{",
"return",
"{",
"filename",
":",
"file",
".",
"filename",
",",
"status",
":",
"file",
".",
"status",
",",
"additions",
":",
"file",
".",
"additions",
",",
"deletions",
":",
"file",
".",
"deletions",
",",
"changes",
":",
"file",
".",
"changes",
",",
"patch",
":",
"analyzePatch",
"(",
"file",
".",
"patch",
"||",
"''",
")",
"}",
";",
"}",
")",
"}",
";",
"}"
]
| Refine a complete diff down to its useful information
@param {Object} diff Too much information about a diff
@return {Object} Just enough information about a diff | [
"Refine",
"a",
"complete",
"diff",
"down",
"to",
"its",
"useful",
"information"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L166-L196 | train |
craiglonsdale/repohelper | lib/pullRequests.js | getDiffForPR | function getDiffForPR(pr) {
print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
return new Promise((resolve) => {
github.repos.compareCommits({
user: pr.head.user.login,
repo: pr.head.repo.name,
head: pr.head.ref,
base: pr.base.ref
}, (err, diff) => {
if (err && debug) {
print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
}
diff.user = pr.head.user.login;
diff.repo = pr.head.repo.name;
diff.title = pr.title;
diff.number = pr.number;
diff.link = pr._links.html.href;
diff.createdAt = pr.created_at;
diff.createdAt = pr.updated_at;
diff.labels = pr.labels;
return resolve(extractDiffData(diff));
});
});
} | javascript | function getDiffForPR(pr) {
print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
return new Promise((resolve) => {
github.repos.compareCommits({
user: pr.head.user.login,
repo: pr.head.repo.name,
head: pr.head.ref,
base: pr.base.ref
}, (err, diff) => {
if (err && debug) {
print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
}
diff.user = pr.head.user.login;
diff.repo = pr.head.repo.name;
diff.title = pr.title;
diff.number = pr.number;
diff.link = pr._links.html.href;
diff.createdAt = pr.created_at;
diff.createdAt = pr.updated_at;
diff.labels = pr.labels;
return resolve(extractDiffData(diff));
});
});
} | [
"function",
"getDiffForPR",
"(",
"pr",
")",
"{",
"print",
"(",
"[",
"'Get diff for PR '",
",",
"clc",
".",
"yellow",
".",
"bold",
"(",
"`",
"${",
"pr",
".",
"head",
".",
"user",
".",
"login",
"}",
"${",
"pr",
".",
"head",
".",
"repo",
".",
"name",
"}",
"${",
"pr",
".",
"number",
"}",
"`",
")",
"]",
",",
"debug",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
")",
"=>",
"{",
"github",
".",
"repos",
".",
"compareCommits",
"(",
"{",
"user",
":",
"pr",
".",
"head",
".",
"user",
".",
"login",
",",
"repo",
":",
"pr",
".",
"head",
".",
"repo",
".",
"name",
",",
"head",
":",
"pr",
".",
"head",
".",
"ref",
",",
"base",
":",
"pr",
".",
"base",
".",
"ref",
"}",
",",
"(",
"err",
",",
"diff",
")",
"=>",
"{",
"if",
"(",
"err",
"&&",
"debug",
")",
"{",
"print",
"(",
"[",
"'Error fetching diffs for PR '",
",",
"clc",
".",
"red",
".",
"bold",
"`",
"${",
"pr",
".",
"head",
".",
"user",
".",
"login",
"}",
"${",
"pr",
".",
"head",
".",
"repo",
".",
"name",
"}",
"${",
"pr",
".",
"number",
"}",
"`",
"]",
",",
"debug",
")",
";",
"}",
"diff",
".",
"user",
"=",
"pr",
".",
"head",
".",
"user",
".",
"login",
";",
"diff",
".",
"repo",
"=",
"pr",
".",
"head",
".",
"repo",
".",
"name",
";",
"diff",
".",
"title",
"=",
"pr",
".",
"title",
";",
"diff",
".",
"number",
"=",
"pr",
".",
"number",
";",
"diff",
".",
"link",
"=",
"pr",
".",
"_links",
".",
"html",
".",
"href",
";",
"diff",
".",
"createdAt",
"=",
"pr",
".",
"created_at",
";",
"diff",
".",
"createdAt",
"=",
"pr",
".",
"updated_at",
";",
"diff",
".",
"labels",
"=",
"pr",
".",
"labels",
";",
"return",
"resolve",
"(",
"extractDiffData",
"(",
"diff",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Fetch the diff for a single pull-request
@param {Object} pr Pull-request metadata
@return {Promise} Resolves to an array of labels | [
"Fetch",
"the",
"diff",
"for",
"a",
"single",
"pull",
"-",
"request"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L203-L226 | train |
craiglonsdale/repohelper | lib/pullRequests.js | getDiffs | function getDiffs(prs) {
print('Fetching diffs', debug);
return Promise.all(prs.reduce((flattenedPRs, pr) => {
if (pr) {
return flattenedPRs.concat(pr);
}
}, []).map(getDiffForPR));
} | javascript | function getDiffs(prs) {
print('Fetching diffs', debug);
return Promise.all(prs.reduce((flattenedPRs, pr) => {
if (pr) {
return flattenedPRs.concat(pr);
}
}, []).map(getDiffForPR));
} | [
"function",
"getDiffs",
"(",
"prs",
")",
"{",
"print",
"(",
"'Fetching diffs'",
",",
"debug",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"prs",
".",
"reduce",
"(",
"(",
"flattenedPRs",
",",
"pr",
")",
"=>",
"{",
"if",
"(",
"pr",
")",
"{",
"return",
"flattenedPRs",
".",
"concat",
"(",
"pr",
")",
";",
"}",
"}",
",",
"[",
"]",
")",
".",
"map",
"(",
"getDiffForPR",
")",
")",
";",
"}"
]
| Fetch diffs for a list of pull-requests
@param {Array} repos List of pull-requests
@return {Promise} Resolves to an array of PRs containing diff infomation | [
"Fetch",
"diffs",
"for",
"a",
"list",
"of",
"pull",
"-",
"requests"
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L233-L240 | train |
craiglonsdale/repohelper | lib/pullRequests.js | getOpenPRs | function getOpenPRs(auth, repo, debugEnabled) {
setDebugMode(debugEnabled);
return authenticate(auth)
.then(function () {
return getPRsForRepo(repo)
.then(getLabels, handleError('getPRs'))
.then(getDiffs, handleError('getLabels'));
}, handleError('authenticate'));
} | javascript | function getOpenPRs(auth, repo, debugEnabled) {
setDebugMode(debugEnabled);
return authenticate(auth)
.then(function () {
return getPRsForRepo(repo)
.then(getLabels, handleError('getPRs'))
.then(getDiffs, handleError('getLabels'));
}, handleError('authenticate'));
} | [
"function",
"getOpenPRs",
"(",
"auth",
",",
"repo",
",",
"debugEnabled",
")",
"{",
"setDebugMode",
"(",
"debugEnabled",
")",
";",
"return",
"authenticate",
"(",
"auth",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"getPRsForRepo",
"(",
"repo",
")",
".",
"then",
"(",
"getLabels",
",",
"handleError",
"(",
"'getPRs'",
")",
")",
".",
"then",
"(",
"getDiffs",
",",
"handleError",
"(",
"'getLabels'",
")",
")",
";",
"}",
",",
"handleError",
"(",
"'authenticate'",
")",
")",
";",
"}"
]
| Get a list of all open pull requests.
@param {Object} auth Credentials containing an auth token
@param {Object} repo The repo from which to get the Open PRs
@param {Boolean} debugEnabled Set the debug state
@return {Promise} Resolves to a list of all open pull-requests | [
"Get",
"a",
"list",
"of",
"all",
"open",
"pull",
"requests",
"."
]
| 9685a71e0d2cfc78df76280b9b1a8e66d0001587 | https://github.com/craiglonsdale/repohelper/blob/9685a71e0d2cfc78df76280b9b1a8e66d0001587/lib/pullRequests.js#L249-L257 | train |
IonicaBizau/double-last | lib/index.js | DoubleLast | function DoubleLast(input, letters) {
var last = LastChar(input);
if (!letters || ~letters.indexOf(last)) {
return input + last;
}
return input;
} | javascript | function DoubleLast(input, letters) {
var last = LastChar(input);
if (!letters || ~letters.indexOf(last)) {
return input + last;
}
return input;
} | [
"function",
"DoubleLast",
"(",
"input",
",",
"letters",
")",
"{",
"var",
"last",
"=",
"LastChar",
"(",
"input",
")",
";",
"if",
"(",
"!",
"letters",
"||",
"~",
"letters",
".",
"indexOf",
"(",
"last",
")",
")",
"{",
"return",
"input",
"+",
"last",
";",
"}",
"return",
"input",
";",
"}"
]
| DoubleLast
Doubles the last letter.
@name DoubleLast
@function
@param {String} input The input string.
@param {Array} letters An array of letters: if the last letter of the input
is not found in this list, it will *not* be doubled.
@return {String} The modified string. | [
"DoubleLast",
"Doubles",
"the",
"last",
"letter",
"."
]
| e3de121d5c71dbfe075077797b2361efd00dd24e | https://github.com/IonicaBizau/double-last/blob/e3de121d5c71dbfe075077797b2361efd00dd24e/lib/index.js#L15-L21 | train |
rranauro/boxspringjs | backbone.boxspring.js | function(err, data, response) {
// call the 'response' callback, if provided using 'node' style callback pattern
if (options.complete) {
options.complete.call(model, err, data, response, options);
}
// trigger any event listeners for "complete"
model.trigger('complete', err, data, response, options);
} | javascript | function(err, data, response) {
// call the 'response' callback, if provided using 'node' style callback pattern
if (options.complete) {
options.complete.call(model, err, data, response, options);
}
// trigger any event listeners for "complete"
model.trigger('complete', err, data, response, options);
} | [
"function",
"(",
"err",
",",
"data",
",",
"response",
")",
"{",
"if",
"(",
"options",
".",
"complete",
")",
"{",
"options",
".",
"complete",
".",
"call",
"(",
"model",
",",
"err",
",",
"data",
",",
"response",
",",
"options",
")",
";",
"}",
"model",
".",
"trigger",
"(",
"'complete'",
",",
"err",
",",
"data",
",",
"response",
",",
"options",
")",
";",
"}"
]
| complete call back | [
"complete",
"call",
"back"
]
| 43fd13ae45ba5b16ba9144084b96748a1cd8c0ea | https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/backbone.boxspring.js#L34-L43 | train |
|
Industryswarm/isnode-mod-data | lib/mongodb/mongodb/lib/bulk/common.js | handleMongoWriteConcernError | function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) {
mergeBatchResults(ordered, batch, bulkResult, null, err.result);
const wrappedWriteConcernError = new WriteConcernError({
errmsg: err.result.writeConcernError.errmsg,
code: err.result.writeConcernError.result
});
return handleCallback(
callback,
new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
null
);
} | javascript | function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) {
mergeBatchResults(ordered, batch, bulkResult, null, err.result);
const wrappedWriteConcernError = new WriteConcernError({
errmsg: err.result.writeConcernError.errmsg,
code: err.result.writeConcernError.result
});
return handleCallback(
callback,
new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
null
);
} | [
"function",
"handleMongoWriteConcernError",
"(",
"batch",
",",
"bulkResult",
",",
"ordered",
",",
"err",
",",
"callback",
")",
"{",
"mergeBatchResults",
"(",
"ordered",
",",
"batch",
",",
"bulkResult",
",",
"null",
",",
"err",
".",
"result",
")",
";",
"const",
"wrappedWriteConcernError",
"=",
"new",
"WriteConcernError",
"(",
"{",
"errmsg",
":",
"err",
".",
"result",
".",
"writeConcernError",
".",
"errmsg",
",",
"code",
":",
"err",
".",
"result",
".",
"writeConcernError",
".",
"result",
"}",
")",
";",
"return",
"handleCallback",
"(",
"callback",
",",
"new",
"BulkWriteError",
"(",
"toError",
"(",
"wrappedWriteConcernError",
")",
",",
"new",
"BulkWriteResult",
"(",
"bulkResult",
")",
")",
",",
"null",
")",
";",
"}"
]
| handles write concern error
@param {object} batch
@param {object} bulkResult
@param {boolean} ordered
@param {WriteConcernError} err
@param {function} callback | [
"handles",
"write",
"concern",
"error"
]
| 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/bulk/common.js#L496-L508 | train |
huafu/ember-dev-fixtures | private/utils/dev-fixtures/fixtures.js | recordCursor | function recordCursor(records, id) {
var record;
id = coerceId(id);
for (var i = 0, len = records.length; i < len; i++) {
record = records[i];
if (coerceId(record.id) === id) {
return {record: record, index: i};
}
}
} | javascript | function recordCursor(records, id) {
var record;
id = coerceId(id);
for (var i = 0, len = records.length; i < len; i++) {
record = records[i];
if (coerceId(record.id) === id) {
return {record: record, index: i};
}
}
} | [
"function",
"recordCursor",
"(",
"records",
",",
"id",
")",
"{",
"var",
"record",
";",
"id",
"=",
"coerceId",
"(",
"id",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"records",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"record",
"=",
"records",
"[",
"i",
"]",
";",
"if",
"(",
"coerceId",
"(",
"record",
".",
"id",
")",
"===",
"id",
")",
"{",
"return",
"{",
"record",
":",
"record",
",",
"index",
":",
"i",
"}",
";",
"}",
"}",
"}"
]
| Get the cursor of a record for a given ID
@function recordCursor
@param {Array} records
@param {string|number} id
@return {{record: Object, index: number}} | [
"Get",
"the",
"cursor",
"of",
"a",
"record",
"for",
"a",
"given",
"ID"
]
| 811ed4d339c2dc840d5b297b5b244726cf1339ca | https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/fixtures.js#L38-L47 | train |
huafu/ember-dev-fixtures | private/utils/dev-fixtures/fixtures.js | function (overlayName, modelName) {
var key = (overlayName || BASE_OVERLAY) + '#' + modelName;
if (!this.instances[key]) {
this.instances[key] = DevFixturesFixtures.create({
modelName: modelName,
overlayName: overlayName
});
}
return this.instances[key];
} | javascript | function (overlayName, modelName) {
var key = (overlayName || BASE_OVERLAY) + '#' + modelName;
if (!this.instances[key]) {
this.instances[key] = DevFixturesFixtures.create({
modelName: modelName,
overlayName: overlayName
});
}
return this.instances[key];
} | [
"function",
"(",
"overlayName",
",",
"modelName",
")",
"{",
"var",
"key",
"=",
"(",
"overlayName",
"||",
"BASE_OVERLAY",
")",
"+",
"'#'",
"+",
"modelName",
";",
"if",
"(",
"!",
"this",
".",
"instances",
"[",
"key",
"]",
")",
"{",
"this",
".",
"instances",
"[",
"key",
"]",
"=",
"DevFixturesFixtures",
".",
"create",
"(",
"{",
"modelName",
":",
"modelName",
",",
"overlayName",
":",
"overlayName",
"}",
")",
";",
"}",
"return",
"this",
".",
"instances",
"[",
"key",
"]",
";",
"}"
]
| Get the instance for given overlay name and model name
@method for
@param {string} overlayName
@param {string} modelName
@return {DevFixturesFixtures} | [
"Get",
"the",
"instance",
"for",
"given",
"overlay",
"name",
"and",
"model",
"name"
]
| 811ed4d339c2dc840d5b297b5b244726cf1339ca | https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/fixtures.js#L263-L272 | train |
|
AndreasMadsen/drugged | drugged.js | Router | function Router(HandleConstructor) {
if (!(this instanceof Router)) return new Router(HandleConstructor);
this.Handle = DefaultHandle;
this.router = new HttpHash();
this.collections = new Map();
this.attachMethods = [];
} | javascript | function Router(HandleConstructor) {
if (!(this instanceof Router)) return new Router(HandleConstructor);
this.Handle = DefaultHandle;
this.router = new HttpHash();
this.collections = new Map();
this.attachMethods = [];
} | [
"function",
"Router",
"(",
"HandleConstructor",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Router",
")",
")",
"return",
"new",
"Router",
"(",
"HandleConstructor",
")",
";",
"this",
".",
"Handle",
"=",
"DefaultHandle",
";",
"this",
".",
"router",
"=",
"new",
"HttpHash",
"(",
")",
";",
"this",
".",
"collections",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"attachMethods",
"=",
"[",
"]",
";",
"}"
]
| API for creating routes and dispatching requests | [
"API",
"for",
"creating",
"routes",
"and",
"dispatching",
"requests"
]
| 2ba5e9a9e87dd43a6754f711a125da13c58da68b | https://github.com/AndreasMadsen/drugged/blob/2ba5e9a9e87dd43a6754f711a125da13c58da68b/drugged.js#L50-L57 | train |
AndreasMadsen/drugged | drugged.js | done | function done(err) {
if (err) return handle.error(err);
// Evaluate all the attach methods
for (const attachMethod of self.attachMethods) {
attachMethod.call(handle);
}
// No match found, send 404
if (match.handler === null) {
err = new Error('Not Found');
err.statusCode = 404;
return handle.error(err);
}
// match found, relay to HandlerCollection
match.handler(req.method, handle, match.params, match.splat);
} | javascript | function done(err) {
if (err) return handle.error(err);
// Evaluate all the attach methods
for (const attachMethod of self.attachMethods) {
attachMethod.call(handle);
}
// No match found, send 404
if (match.handler === null) {
err = new Error('Not Found');
err.statusCode = 404;
return handle.error(err);
}
// match found, relay to HandlerCollection
match.handler(req.method, handle, match.params, match.splat);
} | [
"function",
"done",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handle",
".",
"error",
"(",
"err",
")",
";",
"for",
"(",
"const",
"attachMethod",
"of",
"self",
".",
"attachMethods",
")",
"{",
"attachMethod",
".",
"call",
"(",
"handle",
")",
";",
"}",
"if",
"(",
"match",
".",
"handler",
"===",
"null",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"'Not Found'",
")",
";",
"err",
".",
"statusCode",
"=",
"404",
";",
"return",
"handle",
".",
"error",
"(",
"err",
")",
";",
"}",
"match",
".",
"handler",
"(",
"req",
".",
"method",
",",
"handle",
",",
"match",
".",
"params",
",",
"match",
".",
"splat",
")",
";",
"}"
]
| The handle constructor is done | [
"The",
"handle",
"constructor",
"is",
"done"
]
| 2ba5e9a9e87dd43a6754f711a125da13c58da68b | https://github.com/AndreasMadsen/drugged/blob/2ba5e9a9e87dd43a6754f711a125da13c58da68b/drugged.js#L139-L156 | train |
skazska/marking-codes | v0-hash.js | vsHash | function vsHash(text) {
let codes = [];
let pos = 0;
let partPos = 0;
for (let i = 0; i < text.length; i++) {
if (!codes[pos]) codes[pos]=[];
let code = decodeCharCode2Int36(text.charCodeAt(i));
if (code !== null) {
codes[pos][partPos] = code;
partPos += 1;
}
if (partPos === LEN) {
partPos = 0;
pos += 1;
}
}
if (partPos) {
for (let i = 0; i < LEN - partPos; i++) {
codes[pos].push(0);
}
}
return [codes.reduce((result, code) => {
result = result ^ code.reduce((r, v, i) => {
return r + v * Math.pow(36, i);
}, 0);
return result;
}, 0)];
} | javascript | function vsHash(text) {
let codes = [];
let pos = 0;
let partPos = 0;
for (let i = 0; i < text.length; i++) {
if (!codes[pos]) codes[pos]=[];
let code = decodeCharCode2Int36(text.charCodeAt(i));
if (code !== null) {
codes[pos][partPos] = code;
partPos += 1;
}
if (partPos === LEN) {
partPos = 0;
pos += 1;
}
}
if (partPos) {
for (let i = 0; i < LEN - partPos; i++) {
codes[pos].push(0);
}
}
return [codes.reduce((result, code) => {
result = result ^ code.reduce((r, v, i) => {
return r + v * Math.pow(36, i);
}, 0);
return result;
}, 0)];
} | [
"function",
"vsHash",
"(",
"text",
")",
"{",
"let",
"codes",
"=",
"[",
"]",
";",
"let",
"pos",
"=",
"0",
";",
"let",
"partPos",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"text",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"codes",
"[",
"pos",
"]",
")",
"codes",
"[",
"pos",
"]",
"=",
"[",
"]",
";",
"let",
"code",
"=",
"decodeCharCode2Int36",
"(",
"text",
".",
"charCodeAt",
"(",
"i",
")",
")",
";",
"if",
"(",
"code",
"!==",
"null",
")",
"{",
"codes",
"[",
"pos",
"]",
"[",
"partPos",
"]",
"=",
"code",
";",
"partPos",
"+=",
"1",
";",
"}",
"if",
"(",
"partPos",
"===",
"LEN",
")",
"{",
"partPos",
"=",
"0",
";",
"pos",
"+=",
"1",
";",
"}",
"}",
"if",
"(",
"partPos",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"LEN",
"-",
"partPos",
";",
"i",
"++",
")",
"{",
"codes",
"[",
"pos",
"]",
".",
"push",
"(",
"0",
")",
";",
"}",
"}",
"return",
"[",
"codes",
".",
"reduce",
"(",
"(",
"result",
",",
"code",
")",
"=>",
"{",
"result",
"=",
"result",
"^",
"code",
".",
"reduce",
"(",
"(",
"r",
",",
"v",
",",
"i",
")",
"=>",
"{",
"return",
"r",
"+",
"v",
"*",
"Math",
".",
"pow",
"(",
"36",
",",
"i",
")",
";",
"}",
",",
"0",
")",
";",
"return",
"result",
";",
"}",
",",
"0",
")",
"]",
";",
"}"
]
| hashes string value
@param text
@returns {Array} | [
"hashes",
"string",
"value"
]
| 64c81c39db3dd8a8b17b0bf5e66e4da04d13a846 | https://github.com/skazska/marking-codes/blob/64c81c39db3dd8a8b17b0bf5e66e4da04d13a846/v0-hash.js#L73-L102 | train |
fvanwijk/jasmine-mox-matchers | src/jasmine-mox-matchers.js | getResult | function getResult(matcherName, pass, ...messageWithPlaceholderValues) {
const formattedMessage = format.apply(this, messageWithPlaceholderValues);
messages[matcherName] = formattedMessage; // Save {not} message for later use
return {
pass,
message: formattedMessage.replace(' {not}', pass ? ' not' : '')
};
} | javascript | function getResult(matcherName, pass, ...messageWithPlaceholderValues) {
const formattedMessage = format.apply(this, messageWithPlaceholderValues);
messages[matcherName] = formattedMessage; // Save {not} message for later use
return {
pass,
message: formattedMessage.replace(' {not}', pass ? ' not' : '')
};
} | [
"function",
"getResult",
"(",
"matcherName",
",",
"pass",
",",
"...",
"messageWithPlaceholderValues",
")",
"{",
"const",
"formattedMessage",
"=",
"format",
".",
"apply",
"(",
"this",
",",
"messageWithPlaceholderValues",
")",
";",
"messages",
"[",
"matcherName",
"]",
"=",
"formattedMessage",
";",
"return",
"{",
"pass",
",",
"message",
":",
"formattedMessage",
".",
"replace",
"(",
"' {not}'",
",",
"pass",
"?",
"' not'",
":",
"''",
")",
"}",
";",
"}"
]
| Create a jasmine 2 matcher result
@param {string} matcherName
@param {Boolean} pass
@param {...string} message
@returns {{pass: boolean, message: string}} | [
"Create",
"a",
"jasmine",
"2",
"matcher",
"result"
]
| 99230a8665deef2ffbb69f013bedbcc80fa59a8e | https://github.com/fvanwijk/jasmine-mox-matchers/blob/99230a8665deef2ffbb69f013bedbcc80fa59a8e/src/jasmine-mox-matchers.js#L37-L44 | train |
fvanwijk/jasmine-mox-matchers | src/jasmine-mox-matchers.js | createPromiseWith | function createPromiseWith(actual, expected, verb) {
assertPromise(actual);
const success = jasmine.createSpy('Promise success callback');
const failure = jasmine.createSpy('Promise failure callback');
actual.then(success, failure);
createScope().$digest();
const spy = verb === 'resolved' ? success : failure;
let pass = false;
let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`;
if (isJasmine2 ? spy.calls.any() : spy.calls.length) {
const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0];
if (angular.isFunction(expected)) {
expected(actualResult);
pass = true;
} else {
pass = angular.equals(actualResult, expected);
}
message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \
${jasmine.pp(actualResult)}`;
}
return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message);
} | javascript | function createPromiseWith(actual, expected, verb) {
assertPromise(actual);
const success = jasmine.createSpy('Promise success callback');
const failure = jasmine.createSpy('Promise failure callback');
actual.then(success, failure);
createScope().$digest();
const spy = verb === 'resolved' ? success : failure;
let pass = false;
let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`;
if (isJasmine2 ? spy.calls.any() : spy.calls.length) {
const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0];
if (angular.isFunction(expected)) {
expected(actualResult);
pass = true;
} else {
pass = angular.equals(actualResult, expected);
}
message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \
${jasmine.pp(actualResult)}`;
}
return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message);
} | [
"function",
"createPromiseWith",
"(",
"actual",
",",
"expected",
",",
"verb",
")",
"{",
"assertPromise",
"(",
"actual",
")",
";",
"const",
"success",
"=",
"jasmine",
".",
"createSpy",
"(",
"'Promise success callback'",
")",
";",
"const",
"failure",
"=",
"jasmine",
".",
"createSpy",
"(",
"'Promise failure callback'",
")",
";",
"actual",
".",
"then",
"(",
"success",
",",
"failure",
")",
";",
"createScope",
"(",
")",
".",
"$digest",
"(",
")",
";",
"const",
"spy",
"=",
"verb",
"===",
"'resolved'",
"?",
"success",
":",
"failure",
";",
"let",
"pass",
"=",
"false",
";",
"let",
"message",
"=",
"`",
"${",
"verb",
"}",
"${",
"jasmine",
".",
"pp",
"(",
"expected",
")",
"}",
"${",
"verb",
"}",
"`",
";",
"if",
"(",
"isJasmine2",
"?",
"spy",
".",
"calls",
".",
"any",
"(",
")",
":",
"spy",
".",
"calls",
".",
"length",
")",
"{",
"const",
"actualResult",
"=",
"isJasmine2",
"?",
"spy",
".",
"calls",
".",
"mostRecent",
"(",
")",
".",
"args",
"[",
"0",
"]",
":",
"spy",
".",
"mostRecentCall",
".",
"args",
"[",
"0",
"]",
";",
"if",
"(",
"angular",
".",
"isFunction",
"(",
"expected",
")",
")",
"{",
"expected",
"(",
"actualResult",
")",
";",
"pass",
"=",
"true",
";",
"}",
"else",
"{",
"pass",
"=",
"angular",
".",
"equals",
"(",
"actualResult",
",",
"expected",
")",
";",
"}",
"message",
"=",
"`",
"${",
"verb",
"}",
"${",
"jasmine",
".",
"pp",
"(",
"expected",
")",
"}",
"${",
"verb",
"}",
"\\",
"${",
"jasmine",
".",
"pp",
"(",
"actualResult",
")",
"}",
"`",
";",
"}",
"return",
"getResult",
"(",
"`",
"${",
"verb",
"===",
"'resolved'",
"?",
"'Resolve'",
":",
"'Reject'",
"}",
"`",
",",
"pass",
",",
"message",
")",
";",
"}"
]
| Helper function to create returns for to...With matchers
@param {*} actual the test subject
@param {*} expected value to match against
@param {string} verb 'rejected' or 'resolved'
@returns {boolean} | [
"Helper",
"function",
"to",
"create",
"returns",
"for",
"to",
"...",
"With",
"matchers"
]
| 99230a8665deef2ffbb69f013bedbcc80fa59a8e | https://github.com/fvanwijk/jasmine-mox-matchers/blob/99230a8665deef2ffbb69f013bedbcc80fa59a8e/src/jasmine-mox-matchers.js#L78-L104 | train |
jeremyckahn/bezierizer | dist/bezierizer.js | Bezierizer | function Bezierizer (container) {
this.$el = $(container);
this.$el.append($(HTML_TEMPLATE));
this._$canvasContainer = this.$el.find('.bezierizer-canvas-container');
this._$canvas = this._$canvasContainer.find('canvas');
this._$handleContainer = this.$el.find('.bezierizer-handle-container');
this._$handles = this._$handleContainer.find('.bezierizer-handle');
this._ctx = this._$canvas[0].getContext('2d');
this._$canvas[0].height = this._$canvas.height();
this._$canvas[0].width = this._$canvas.width();
this._$handles.dragon({
within: this._$handleContainer
});
this._points = {};
this.setHandlePositions({
x1: 0.25
,y1: 0.5
,x2: 0.75
,y2: 0.5
});
this._initBindings();
} | javascript | function Bezierizer (container) {
this.$el = $(container);
this.$el.append($(HTML_TEMPLATE));
this._$canvasContainer = this.$el.find('.bezierizer-canvas-container');
this._$canvas = this._$canvasContainer.find('canvas');
this._$handleContainer = this.$el.find('.bezierizer-handle-container');
this._$handles = this._$handleContainer.find('.bezierizer-handle');
this._ctx = this._$canvas[0].getContext('2d');
this._$canvas[0].height = this._$canvas.height();
this._$canvas[0].width = this._$canvas.width();
this._$handles.dragon({
within: this._$handleContainer
});
this._points = {};
this.setHandlePositions({
x1: 0.25
,y1: 0.5
,x2: 0.75
,y2: 0.5
});
this._initBindings();
} | [
"function",
"Bezierizer",
"(",
"container",
")",
"{",
"this",
".",
"$el",
"=",
"$",
"(",
"container",
")",
";",
"this",
".",
"$el",
".",
"append",
"(",
"$",
"(",
"HTML_TEMPLATE",
")",
")",
";",
"this",
".",
"_$canvasContainer",
"=",
"this",
".",
"$el",
".",
"find",
"(",
"'.bezierizer-canvas-container'",
")",
";",
"this",
".",
"_$canvas",
"=",
"this",
".",
"_$canvasContainer",
".",
"find",
"(",
"'canvas'",
")",
";",
"this",
".",
"_$handleContainer",
"=",
"this",
".",
"$el",
".",
"find",
"(",
"'.bezierizer-handle-container'",
")",
";",
"this",
".",
"_$handles",
"=",
"this",
".",
"_$handleContainer",
".",
"find",
"(",
"'.bezierizer-handle'",
")",
";",
"this",
".",
"_ctx",
"=",
"this",
".",
"_$canvas",
"[",
"0",
"]",
".",
"getContext",
"(",
"'2d'",
")",
";",
"this",
".",
"_$canvas",
"[",
"0",
"]",
".",
"height",
"=",
"this",
".",
"_$canvas",
".",
"height",
"(",
")",
";",
"this",
".",
"_$canvas",
"[",
"0",
"]",
".",
"width",
"=",
"this",
".",
"_$canvas",
".",
"width",
"(",
")",
";",
"this",
".",
"_$handles",
".",
"dragon",
"(",
"{",
"within",
":",
"this",
".",
"_$handleContainer",
"}",
")",
";",
"this",
".",
"_points",
"=",
"{",
"}",
";",
"this",
".",
"setHandlePositions",
"(",
"{",
"x1",
":",
"0.25",
",",
"y1",
":",
"0.5",
",",
"x2",
":",
"0.75",
",",
"y2",
":",
"0.5",
"}",
")",
";",
"this",
".",
"_initBindings",
"(",
")",
";",
"}"
]
| Creates a Bezierizer widget and inserts it into the DOM.
@param {Element} container The container element to insert the Bezierizer widget into.
@constructor | [
"Creates",
"a",
"Bezierizer",
"widget",
"and",
"inserts",
"it",
"into",
"the",
"DOM",
"."
]
| f1886b556279875bbb0da5051f7b716727b28768 | https://github.com/jeremyckahn/bezierizer/blob/f1886b556279875bbb0da5051f7b716727b28768/dist/bezierizer.js#L47-L73 | train |
StefanoMagrassi/gulp-tracer | lib/renderer.js | function() {
if (cache.styles) {
return cache.styles;
}
cache.styles = {};
cache.styles[CONSTS.LOG] = chalk.white;
cache.styles[CONSTS.INFO] = chalk.cyan;
cache.styles[CONSTS.SUCCESS] = chalk.bold.green;
cache.styles[CONSTS.WARN] = chalk.yellow;
cache.styles[CONSTS.ERROR] = chalk.bold.red;
return cache.styles;
} | javascript | function() {
if (cache.styles) {
return cache.styles;
}
cache.styles = {};
cache.styles[CONSTS.LOG] = chalk.white;
cache.styles[CONSTS.INFO] = chalk.cyan;
cache.styles[CONSTS.SUCCESS] = chalk.bold.green;
cache.styles[CONSTS.WARN] = chalk.yellow;
cache.styles[CONSTS.ERROR] = chalk.bold.red;
return cache.styles;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"cache",
".",
"styles",
")",
"{",
"return",
"cache",
".",
"styles",
";",
"}",
"cache",
".",
"styles",
"=",
"{",
"}",
";",
"cache",
".",
"styles",
"[",
"CONSTS",
".",
"LOG",
"]",
"=",
"chalk",
".",
"white",
";",
"cache",
".",
"styles",
"[",
"CONSTS",
".",
"INFO",
"]",
"=",
"chalk",
".",
"cyan",
";",
"cache",
".",
"styles",
"[",
"CONSTS",
".",
"SUCCESS",
"]",
"=",
"chalk",
".",
"bold",
".",
"green",
";",
"cache",
".",
"styles",
"[",
"CONSTS",
".",
"WARN",
"]",
"=",
"chalk",
".",
"yellow",
";",
"cache",
".",
"styles",
"[",
"CONSTS",
".",
"ERROR",
"]",
"=",
"chalk",
".",
"bold",
".",
"red",
";",
"return",
"cache",
".",
"styles",
";",
"}"
]
| Gets the chalk styles from cache, creating cache object if it doesn't exist.
@return {object} | [
"Gets",
"the",
"chalk",
"styles",
"from",
"cache",
"creating",
"cache",
"object",
"if",
"it",
"doesn",
"t",
"exist",
"."
]
| 11839f916b0fa39260178678332a795215a17b16 | https://github.com/StefanoMagrassi/gulp-tracer/blob/11839f916b0fa39260178678332a795215a17b16/lib/renderer.js#L32-L45 | train |
|
StefanoMagrassi/gulp-tracer | lib/renderer.js | function(type) {
var t = '[' + type.toUpperCase() + ']';
return utils.filler(t, utils.longestKey(CONSTS, 2));
} | javascript | function(type) {
var t = '[' + type.toUpperCase() + ']';
return utils.filler(t, utils.longestKey(CONSTS, 2));
} | [
"function",
"(",
"type",
")",
"{",
"var",
"t",
"=",
"'['",
"+",
"type",
".",
"toUpperCase",
"(",
")",
"+",
"']'",
";",
"return",
"utils",
".",
"filler",
"(",
"t",
",",
"utils",
".",
"longestKey",
"(",
"CONSTS",
",",
"2",
")",
")",
";",
"}"
]
| Renders type tag column.
@param {string} type
@return {string} | [
"Renders",
"type",
"tag",
"column",
"."
]
| 11839f916b0fa39260178678332a795215a17b16 | https://github.com/StefanoMagrassi/gulp-tracer/blob/11839f916b0fa39260178678332a795215a17b16/lib/renderer.js#L71-L75 | train |
|
StefanoMagrassi/gulp-tracer | lib/renderer.js | function(type, messages) {
if (type !== CONSTS.LOG) {
messages.unshift(tag(type));
}
return messages.map(styles.bind(null, type));
} | javascript | function(type, messages) {
if (type !== CONSTS.LOG) {
messages.unshift(tag(type));
}
return messages.map(styles.bind(null, type));
} | [
"function",
"(",
"type",
",",
"messages",
")",
"{",
"if",
"(",
"type",
"!==",
"CONSTS",
".",
"LOG",
")",
"{",
"messages",
".",
"unshift",
"(",
"tag",
"(",
"type",
")",
")",
";",
"}",
"return",
"messages",
".",
"map",
"(",
"styles",
".",
"bind",
"(",
"null",
",",
"type",
")",
")",
";",
"}"
]
| Remaps messages applying styles.
@param {string} type
@param {array} messages
@return {array} | [
"Remaps",
"messages",
"applying",
"styles",
"."
]
| 11839f916b0fa39260178678332a795215a17b16 | https://github.com/StefanoMagrassi/gulp-tracer/blob/11839f916b0fa39260178678332a795215a17b16/lib/renderer.js#L83-L89 | train |
|
SamPlacette/charon | index.js | detectErrors | function detectErrors (err, responseSpec, next) {
var callbackErr;
if (err) {
callbackErr = err;
}
else {
var status = responseSpec.statusCode;
if (status == 403) {
callbackErr = new Charon.RequestForbiddenError(responseSpec);
}
else if (status == 404) {
callbackErr = new Charon.ResourceNotFoundError(responseSpec);
}
else if (status == 409) {
callbackErr = new Charon.ResourceConflictError(responseSpec);
}
else if (status >= 400 && status <= 499) {
// 4xx error
callbackErr = new Charon.ConsumerError(responseSpec);
}
else if (status >= 500 && status <= 599) {
// 5xx error
callbackErr = new Charon.ServiceError(responseSpec);
}
else if (! (status >= 200 && status <= 299)) {
// not sure what this is, but it's not successful
callbackErr = new Charon.RuntimeError('Unrecognized HTTP status code', responseSpec);
}
}
this.invokeNext(callbackErr, responseSpec, next);
} | javascript | function detectErrors (err, responseSpec, next) {
var callbackErr;
if (err) {
callbackErr = err;
}
else {
var status = responseSpec.statusCode;
if (status == 403) {
callbackErr = new Charon.RequestForbiddenError(responseSpec);
}
else if (status == 404) {
callbackErr = new Charon.ResourceNotFoundError(responseSpec);
}
else if (status == 409) {
callbackErr = new Charon.ResourceConflictError(responseSpec);
}
else if (status >= 400 && status <= 499) {
// 4xx error
callbackErr = new Charon.ConsumerError(responseSpec);
}
else if (status >= 500 && status <= 599) {
// 5xx error
callbackErr = new Charon.ServiceError(responseSpec);
}
else if (! (status >= 200 && status <= 299)) {
// not sure what this is, but it's not successful
callbackErr = new Charon.RuntimeError('Unrecognized HTTP status code', responseSpec);
}
}
this.invokeNext(callbackErr, responseSpec, next);
} | [
"function",
"detectErrors",
"(",
"err",
",",
"responseSpec",
",",
"next",
")",
"{",
"var",
"callbackErr",
";",
"if",
"(",
"err",
")",
"{",
"callbackErr",
"=",
"err",
";",
"}",
"else",
"{",
"var",
"status",
"=",
"responseSpec",
".",
"statusCode",
";",
"if",
"(",
"status",
"==",
"403",
")",
"{",
"callbackErr",
"=",
"new",
"Charon",
".",
"RequestForbiddenError",
"(",
"responseSpec",
")",
";",
"}",
"else",
"if",
"(",
"status",
"==",
"404",
")",
"{",
"callbackErr",
"=",
"new",
"Charon",
".",
"ResourceNotFoundError",
"(",
"responseSpec",
")",
";",
"}",
"else",
"if",
"(",
"status",
"==",
"409",
")",
"{",
"callbackErr",
"=",
"new",
"Charon",
".",
"ResourceConflictError",
"(",
"responseSpec",
")",
";",
"}",
"else",
"if",
"(",
"status",
">=",
"400",
"&&",
"status",
"<=",
"499",
")",
"{",
"callbackErr",
"=",
"new",
"Charon",
".",
"ConsumerError",
"(",
"responseSpec",
")",
";",
"}",
"else",
"if",
"(",
"status",
">=",
"500",
"&&",
"status",
"<=",
"599",
")",
"{",
"callbackErr",
"=",
"new",
"Charon",
".",
"ServiceError",
"(",
"responseSpec",
")",
";",
"}",
"else",
"if",
"(",
"!",
"(",
"status",
">=",
"200",
"&&",
"status",
"<=",
"299",
")",
")",
"{",
"callbackErr",
"=",
"new",
"Charon",
".",
"RuntimeError",
"(",
"'Unrecognized HTTP status code'",
",",
"responseSpec",
")",
";",
"}",
"}",
"this",
".",
"invokeNext",
"(",
"callbackErr",
",",
"responseSpec",
",",
"next",
")",
";",
"}"
]
| A response middleware function. Attempts to detect errors in the ``responseSpec`` and create appropriate error instances to pass to the ``next`` callback as necessary. This logic should be common for most APIs, but it may be overidden by the integrator if so desired. | [
"A",
"response",
"middleware",
"function",
".",
"Attempts",
"to",
"detect",
"errors",
"in",
"the",
"responseSpec",
"and",
"create",
"appropriate",
"error",
"instances",
"to",
"pass",
"to",
"the",
"next",
"callback",
"as",
"necessary",
".",
"This",
"logic",
"should",
"be",
"common",
"for",
"most",
"APIs",
"but",
"it",
"may",
"be",
"overidden",
"by",
"the",
"integrator",
"if",
"so",
"desired",
"."
]
| c88bba7c2cd082b8fa90d02e82d0ffc2726c3558 | https://github.com/SamPlacette/charon/blob/c88bba7c2cd082b8fa90d02e82d0ffc2726c3558/index.js#L190-L220 | train |
SamPlacette/charon | index.js | parseResource | function parseResource (err, responseSpec, next) {
var resource = responseSpec ? responseSpec.body : undefined;
this.invokeNext(err, resource, next);
} | javascript | function parseResource (err, responseSpec, next) {
var resource = responseSpec ? responseSpec.body : undefined;
this.invokeNext(err, resource, next);
} | [
"function",
"parseResource",
"(",
"err",
",",
"responseSpec",
",",
"next",
")",
"{",
"var",
"resource",
"=",
"responseSpec",
"?",
"responseSpec",
".",
"body",
":",
"undefined",
";",
"this",
".",
"invokeNext",
"(",
"err",
",",
"resource",
",",
"next",
")",
";",
"}"
]
| default resource parser. Executes after all callback wrappers. Responsible for parsing the resource from the response and passing ``err``, ``resource`` to the next callback. | [
"default",
"resource",
"parser",
".",
"Executes",
"after",
"all",
"callback",
"wrappers",
".",
"Responsible",
"for",
"parsing",
"the",
"resource",
"from",
"the",
"response",
"and",
"passing",
"err",
"resource",
"to",
"the",
"next",
"callback",
"."
]
| c88bba7c2cd082b8fa90d02e82d0ffc2726c3558 | https://github.com/SamPlacette/charon/blob/c88bba7c2cd082b8fa90d02e82d0ffc2726c3558/index.js#L369-L372 | train |
SamPlacette/charon | index.js | function (propertyName) {
var value = this.client[propertyName];
if (! _.isUndefined(this[propertyName])) {
// pass, defer to resource manager prototype properties
}
else if (_.isFunction(value)) {
// copy functions (including the error ctors) by direct reference
this[propertyName] = value;
}
else if (_.contains(this.client.serviceCallParams, propertyName)) {
// default service call params which are not function values are proxied
// via getter functions
this[propertyName] = function () { return this.client[propertyName]; };
}
// all other properties are assumed to be client configuration, and
// should be accessed by referencing the ``client`` instance property.
} | javascript | function (propertyName) {
var value = this.client[propertyName];
if (! _.isUndefined(this[propertyName])) {
// pass, defer to resource manager prototype properties
}
else if (_.isFunction(value)) {
// copy functions (including the error ctors) by direct reference
this[propertyName] = value;
}
else if (_.contains(this.client.serviceCallParams, propertyName)) {
// default service call params which are not function values are proxied
// via getter functions
this[propertyName] = function () { return this.client[propertyName]; };
}
// all other properties are assumed to be client configuration, and
// should be accessed by referencing the ``client`` instance property.
} | [
"function",
"(",
"propertyName",
")",
"{",
"var",
"value",
"=",
"this",
".",
"client",
"[",
"propertyName",
"]",
";",
"if",
"(",
"!",
"_",
".",
"isUndefined",
"(",
"this",
"[",
"propertyName",
"]",
")",
")",
"{",
"}",
"else",
"if",
"(",
"_",
".",
"isFunction",
"(",
"value",
")",
")",
"{",
"this",
"[",
"propertyName",
"]",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"_",
".",
"contains",
"(",
"this",
".",
"client",
".",
"serviceCallParams",
",",
"propertyName",
")",
")",
"{",
"this",
"[",
"propertyName",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"client",
"[",
"propertyName",
"]",
";",
"}",
";",
"}",
"}"
]
| links a single property from the client (identified by ``propertyName`` to ``this`` instance | [
"links",
"a",
"single",
"property",
"from",
"the",
"client",
"(",
"identified",
"by",
"propertyName",
"to",
"this",
"instance"
]
| c88bba7c2cd082b8fa90d02e82d0ffc2726c3558 | https://github.com/SamPlacette/charon/blob/c88bba7c2cd082b8fa90d02e82d0ffc2726c3558/index.js#L410-L426 | train |
|
melvincarvalho/rdf-shell | lib/ls.js | ls | function ls(uri, callback) {
if (!uri) {
callback(new Error('uri is required'))
}
util.getAll(uri, function(err, val) {
var res = {}
for (var i=0; i<val.length; i++) {
if (val[i].predicate.uri === 'http://www.w3.org/ns/ldp#contains') {
if (! res[val[i].object.uri]) res[val[i].object.uri] = {}
res[val[i].object.uri].contains = val[i].object.uri
}
if (val[i].predicate.uri === 'http://www.w3.org/ns/posix/stat#mtime') {
if (! res[val[i].subject.uri]) res[val[i].subject.uri] = {}
res[val[i].subject.uri].mtime = val[i].object.value
}
}
var arr =[]
for( var k in res ) {
if (res.hasOwnProperty(k)) {
if (k && res[k] && res[k].mtime && res[k].contains) {
arr.push({ file : res[k].contains, mtime : res[k].mtime })
}
}
}
arr = arr.sort(function(a, b){
if (a.mtime < b.mtime) return -1
if (a.mtime > b.mtime) return 1
return 0
})
var ret = []
for (i=0; i<arr.length; i++) {
ret.push(arr[i].file)
}
callback(null, ret)
})
} | javascript | function ls(uri, callback) {
if (!uri) {
callback(new Error('uri is required'))
}
util.getAll(uri, function(err, val) {
var res = {}
for (var i=0; i<val.length; i++) {
if (val[i].predicate.uri === 'http://www.w3.org/ns/ldp#contains') {
if (! res[val[i].object.uri]) res[val[i].object.uri] = {}
res[val[i].object.uri].contains = val[i].object.uri
}
if (val[i].predicate.uri === 'http://www.w3.org/ns/posix/stat#mtime') {
if (! res[val[i].subject.uri]) res[val[i].subject.uri] = {}
res[val[i].subject.uri].mtime = val[i].object.value
}
}
var arr =[]
for( var k in res ) {
if (res.hasOwnProperty(k)) {
if (k && res[k] && res[k].mtime && res[k].contains) {
arr.push({ file : res[k].contains, mtime : res[k].mtime })
}
}
}
arr = arr.sort(function(a, b){
if (a.mtime < b.mtime) return -1
if (a.mtime > b.mtime) return 1
return 0
})
var ret = []
for (i=0; i<arr.length; i++) {
ret.push(arr[i].file)
}
callback(null, ret)
})
} | [
"function",
"ls",
"(",
"uri",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"uri",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'uri is required'",
")",
")",
"}",
"util",
".",
"getAll",
"(",
"uri",
",",
"function",
"(",
"err",
",",
"val",
")",
"{",
"var",
"res",
"=",
"{",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"val",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"val",
"[",
"i",
"]",
".",
"predicate",
".",
"uri",
"===",
"'http://www.w3.org/ns/ldp#contains'",
")",
"{",
"if",
"(",
"!",
"res",
"[",
"val",
"[",
"i",
"]",
".",
"object",
".",
"uri",
"]",
")",
"res",
"[",
"val",
"[",
"i",
"]",
".",
"object",
".",
"uri",
"]",
"=",
"{",
"}",
"res",
"[",
"val",
"[",
"i",
"]",
".",
"object",
".",
"uri",
"]",
".",
"contains",
"=",
"val",
"[",
"i",
"]",
".",
"object",
".",
"uri",
"}",
"if",
"(",
"val",
"[",
"i",
"]",
".",
"predicate",
".",
"uri",
"===",
"'http://www.w3.org/ns/posix/stat#mtime'",
")",
"{",
"if",
"(",
"!",
"res",
"[",
"val",
"[",
"i",
"]",
".",
"subject",
".",
"uri",
"]",
")",
"res",
"[",
"val",
"[",
"i",
"]",
".",
"subject",
".",
"uri",
"]",
"=",
"{",
"}",
"res",
"[",
"val",
"[",
"i",
"]",
".",
"subject",
".",
"uri",
"]",
".",
"mtime",
"=",
"val",
"[",
"i",
"]",
".",
"object",
".",
"value",
"}",
"}",
"var",
"arr",
"=",
"[",
"]",
"for",
"(",
"var",
"k",
"in",
"res",
")",
"{",
"if",
"(",
"res",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"{",
"if",
"(",
"k",
"&&",
"res",
"[",
"k",
"]",
"&&",
"res",
"[",
"k",
"]",
".",
"mtime",
"&&",
"res",
"[",
"k",
"]",
".",
"contains",
")",
"{",
"arr",
".",
"push",
"(",
"{",
"file",
":",
"res",
"[",
"k",
"]",
".",
"contains",
",",
"mtime",
":",
"res",
"[",
"k",
"]",
".",
"mtime",
"}",
")",
"}",
"}",
"}",
"arr",
"=",
"arr",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"mtime",
"<",
"b",
".",
"mtime",
")",
"return",
"-",
"1",
"if",
"(",
"a",
".",
"mtime",
">",
"b",
".",
"mtime",
")",
"return",
"1",
"return",
"0",
"}",
")",
"var",
"ret",
"=",
"[",
"]",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"ret",
".",
"push",
"(",
"arr",
"[",
"i",
"]",
".",
"file",
")",
"}",
"callback",
"(",
"null",
",",
"ret",
")",
"}",
")",
"}"
]
| get the contents of a container as an array
@param {[type]} argv [description]
@param {Function} callback [description]
@return {[type]} [description] | [
"get",
"the",
"contents",
"of",
"a",
"container",
"as",
"an",
"array"
]
| bf2015f6f333855e69a18ce3ec9e917bbddfb425 | https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/ls.js#L11-L51 | train |
huafu/ember-dev-fixtures | private/utils/dev-fixtures/overlay.js | function (name) {
name = name || BASE_OVERLAY;
if (!this.instances[name]) {
this.instances[name] = DevFixturesOverlay.create({name: name});
}
return this.instances[name];
} | javascript | function (name) {
name = name || BASE_OVERLAY;
if (!this.instances[name]) {
this.instances[name] = DevFixturesOverlay.create({name: name});
}
return this.instances[name];
} | [
"function",
"(",
"name",
")",
"{",
"name",
"=",
"name",
"||",
"BASE_OVERLAY",
";",
"if",
"(",
"!",
"this",
".",
"instances",
"[",
"name",
"]",
")",
"{",
"this",
".",
"instances",
"[",
"name",
"]",
"=",
"DevFixturesOverlay",
".",
"create",
"(",
"{",
"name",
":",
"name",
"}",
")",
";",
"}",
"return",
"this",
".",
"instances",
"[",
"name",
"]",
";",
"}"
]
| Get the singleton instance for the given overlay name
@method for
@param {string} name
@return {DevFixturesOverlay} | [
"Get",
"the",
"singleton",
"instance",
"for",
"the",
"given",
"overlay",
"name"
]
| 811ed4d339c2dc840d5b297b5b244726cf1339ca | https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/overlay.js#L197-L203 | train |
|
RnbWd/parse-browserify | lib/op.js | function(json) {
var decoder = Parse.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
} | javascript | function(json) {
var decoder = Parse.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
} | [
"function",
"(",
"json",
")",
"{",
"var",
"decoder",
"=",
"Parse",
".",
"Op",
".",
"_opDecoderMap",
"[",
"json",
".",
"__op",
"]",
";",
"if",
"(",
"decoder",
")",
"{",
"return",
"decoder",
"(",
"json",
")",
";",
"}",
"else",
"{",
"return",
"undefined",
";",
"}",
"}"
]
| Converts a json object into an instance of a subclass of Parse.Op. | [
"Converts",
"a",
"json",
"object",
"into",
"an",
"instance",
"of",
"a",
"subclass",
"of",
"Parse",
".",
"Op",
"."
]
| c19c1b798e4010a552e130b1a9ce3b5d084dc101 | https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/op.js#L45-L52 | train |
|
RnbWd/parse-browserify | lib/op.js | function() {
var self = this;
return _.map(this.relationsToRemove, function(objectId) {
var object = Parse.Object._create(self._targetClassName);
object.id = objectId;
return object;
});
} | javascript | function() {
var self = this;
return _.map(this.relationsToRemove, function(objectId) {
var object = Parse.Object._create(self._targetClassName);
object.id = objectId;
return object;
});
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"return",
"_",
".",
"map",
"(",
"this",
".",
"relationsToRemove",
",",
"function",
"(",
"objectId",
")",
"{",
"var",
"object",
"=",
"Parse",
".",
"Object",
".",
"_create",
"(",
"self",
".",
"_targetClassName",
")",
";",
"object",
".",
"id",
"=",
"objectId",
";",
"return",
"object",
";",
"}",
")",
";",
"}"
]
| Returns an array of unfetched Parse.Object that are being removed from
the relation.
@return {Array} | [
"Returns",
"an",
"array",
"of",
"unfetched",
"Parse",
".",
"Object",
"that",
"are",
"being",
"removed",
"from",
"the",
"relation",
"."
]
| c19c1b798e4010a552e130b1a9ce3b5d084dc101 | https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/op.js#L434-L441 | train |
|
RnbWd/parse-browserify | lib/op.js | function() {
var adds = null;
var removes = null;
var self = this;
var idToPointer = function(id) {
return { __type: 'Pointer',
className: self._targetClassName,
objectId: id };
};
var pointers = null;
if (this.relationsToAdd.length > 0) {
pointers = _.map(this.relationsToAdd, idToPointer);
adds = { "__op": "AddRelation", "objects": pointers };
}
if (this.relationsToRemove.length > 0) {
pointers = _.map(this.relationsToRemove, idToPointer);
removes = { "__op": "RemoveRelation", "objects": pointers };
}
if (adds && removes) {
return { "__op": "Batch", "ops": [adds, removes]};
}
return adds || removes || {};
} | javascript | function() {
var adds = null;
var removes = null;
var self = this;
var idToPointer = function(id) {
return { __type: 'Pointer',
className: self._targetClassName,
objectId: id };
};
var pointers = null;
if (this.relationsToAdd.length > 0) {
pointers = _.map(this.relationsToAdd, idToPointer);
adds = { "__op": "AddRelation", "objects": pointers };
}
if (this.relationsToRemove.length > 0) {
pointers = _.map(this.relationsToRemove, idToPointer);
removes = { "__op": "RemoveRelation", "objects": pointers };
}
if (adds && removes) {
return { "__op": "Batch", "ops": [adds, removes]};
}
return adds || removes || {};
} | [
"function",
"(",
")",
"{",
"var",
"adds",
"=",
"null",
";",
"var",
"removes",
"=",
"null",
";",
"var",
"self",
"=",
"this",
";",
"var",
"idToPointer",
"=",
"function",
"(",
"id",
")",
"{",
"return",
"{",
"__type",
":",
"'Pointer'",
",",
"className",
":",
"self",
".",
"_targetClassName",
",",
"objectId",
":",
"id",
"}",
";",
"}",
";",
"var",
"pointers",
"=",
"null",
";",
"if",
"(",
"this",
".",
"relationsToAdd",
".",
"length",
">",
"0",
")",
"{",
"pointers",
"=",
"_",
".",
"map",
"(",
"this",
".",
"relationsToAdd",
",",
"idToPointer",
")",
";",
"adds",
"=",
"{",
"\"__op\"",
":",
"\"AddRelation\"",
",",
"\"objects\"",
":",
"pointers",
"}",
";",
"}",
"if",
"(",
"this",
".",
"relationsToRemove",
".",
"length",
">",
"0",
")",
"{",
"pointers",
"=",
"_",
".",
"map",
"(",
"this",
".",
"relationsToRemove",
",",
"idToPointer",
")",
";",
"removes",
"=",
"{",
"\"__op\"",
":",
"\"RemoveRelation\"",
",",
"\"objects\"",
":",
"pointers",
"}",
";",
"}",
"if",
"(",
"adds",
"&&",
"removes",
")",
"{",
"return",
"{",
"\"__op\"",
":",
"\"Batch\"",
",",
"\"ops\"",
":",
"[",
"adds",
",",
"removes",
"]",
"}",
";",
"}",
"return",
"adds",
"||",
"removes",
"||",
"{",
"}",
";",
"}"
]
| Returns a JSON version of the operation suitable for sending to Parse.
@return {Object} | [
"Returns",
"a",
"JSON",
"version",
"of",
"the",
"operation",
"suitable",
"for",
"sending",
"to",
"Parse",
"."
]
| c19c1b798e4010a552e130b1a9ce3b5d084dc101 | https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/op.js#L447-L472 | train |
|
sdgluck/serialise-request | index.js | blobToString | function blobToString (blob) {
return blobUtil
.blobToArrayBuffer(blob)
.then(function (buffer) {
return String.fromCharCode.apply(null, new Uint16Array(buffer))
})
} | javascript | function blobToString (blob) {
return blobUtil
.blobToArrayBuffer(blob)
.then(function (buffer) {
return String.fromCharCode.apply(null, new Uint16Array(buffer))
})
} | [
"function",
"blobToString",
"(",
"blob",
")",
"{",
"return",
"blobUtil",
".",
"blobToArrayBuffer",
"(",
"blob",
")",
".",
"then",
"(",
"function",
"(",
"buffer",
")",
"{",
"return",
"String",
".",
"fromCharCode",
".",
"apply",
"(",
"null",
",",
"new",
"Uint16Array",
"(",
"buffer",
")",
")",
"}",
")",
"}"
]
| Turn a Blob into a String.
@param {Blob} blob
@returns {Promise} | [
"Turn",
"a",
"Blob",
"into",
"a",
"String",
"."
]
| c0e108729bbe92cc05152d29ed32e7f7a7fffb82 | https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L28-L34 | train |
sdgluck/serialise-request | index.js | remakeBody | function remakeBody (body, bodyType) {
return blobUtil
.base64StringToBlob(body)
.then(function (blob) {
switch (bodyType) {
case BodyTypes.ARRAY_BUFFER:
return blobUtil.blobToArrayBuffer(blob)
case BodyTypes.BLOB:
return blob
case BodyTypes.FORM_DATA:
throw new Error('Cannot make FormData from serialised Request')
case BodyTypes.JSON:
return blobToString(blob)
.then(function (str) {
return JSON.parse(str)
})
case BodyTypes.TEXT:
return blobToString(blob)
default:
throw new Error('Unknown requested body type "' + bodyType + '"')
}
})
} | javascript | function remakeBody (body, bodyType) {
return blobUtil
.base64StringToBlob(body)
.then(function (blob) {
switch (bodyType) {
case BodyTypes.ARRAY_BUFFER:
return blobUtil.blobToArrayBuffer(blob)
case BodyTypes.BLOB:
return blob
case BodyTypes.FORM_DATA:
throw new Error('Cannot make FormData from serialised Request')
case BodyTypes.JSON:
return blobToString(blob)
.then(function (str) {
return JSON.parse(str)
})
case BodyTypes.TEXT:
return blobToString(blob)
default:
throw new Error('Unknown requested body type "' + bodyType + '"')
}
})
} | [
"function",
"remakeBody",
"(",
"body",
",",
"bodyType",
")",
"{",
"return",
"blobUtil",
".",
"base64StringToBlob",
"(",
"body",
")",
".",
"then",
"(",
"function",
"(",
"blob",
")",
"{",
"switch",
"(",
"bodyType",
")",
"{",
"case",
"BodyTypes",
".",
"ARRAY_BUFFER",
":",
"return",
"blobUtil",
".",
"blobToArrayBuffer",
"(",
"blob",
")",
"case",
"BodyTypes",
".",
"BLOB",
":",
"return",
"blob",
"case",
"BodyTypes",
".",
"FORM_DATA",
":",
"throw",
"new",
"Error",
"(",
"'Cannot make FormData from serialised Request'",
")",
"case",
"BodyTypes",
".",
"JSON",
":",
"return",
"blobToString",
"(",
"blob",
")",
".",
"then",
"(",
"function",
"(",
"str",
")",
"{",
"return",
"JSON",
".",
"parse",
"(",
"str",
")",
"}",
")",
"case",
"BodyTypes",
".",
"TEXT",
":",
"return",
"blobToString",
"(",
"blob",
")",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Unknown requested body type \"'",
"+",
"bodyType",
"+",
"'\"'",
")",
"}",
"}",
")",
"}"
]
| Deserialise the body of a Request.
@param {String} body
@param {String} bodyType
@returns {Promise} | [
"Deserialise",
"the",
"body",
"of",
"a",
"Request",
"."
]
| c0e108729bbe92cc05152d29ed32e7f7a7fffb82 | https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L42-L64 | train |
sdgluck/serialise-request | index.js | serialiseRequest | function serialiseRequest (request, toObject) {
if (!(request instanceof Request)) {
throw new Error('Expecting request to be instance of Request')
}
var headers = []
var headerNames = request.headers.keys()
for (var i = 0; i < headerNames.length; i++) {
var headerName = headerNames[i]
headers[headerName] = request.headers.get(headerName)
}
var serialised = {
method: request.method,
url: request.url,
headers: headers,
context: request.context,
referrer: request.referrer,
mode: request.mode,
credentials: request.credentials,
redirect: request.redirect,
integrity: request.integrity,
cache: request.cache,
bodyUsed: request.bodyUsed
}
return request
.blob()
.then(blobUtil.blobToBase64String)
.then(function (base64) {
serialised.__body = base64
return toObject
? serialised
: JSON.stringify(serialised)
})
} | javascript | function serialiseRequest (request, toObject) {
if (!(request instanceof Request)) {
throw new Error('Expecting request to be instance of Request')
}
var headers = []
var headerNames = request.headers.keys()
for (var i = 0; i < headerNames.length; i++) {
var headerName = headerNames[i]
headers[headerName] = request.headers.get(headerName)
}
var serialised = {
method: request.method,
url: request.url,
headers: headers,
context: request.context,
referrer: request.referrer,
mode: request.mode,
credentials: request.credentials,
redirect: request.redirect,
integrity: request.integrity,
cache: request.cache,
bodyUsed: request.bodyUsed
}
return request
.blob()
.then(blobUtil.blobToBase64String)
.then(function (base64) {
serialised.__body = base64
return toObject
? serialised
: JSON.stringify(serialised)
})
} | [
"function",
"serialiseRequest",
"(",
"request",
",",
"toObject",
")",
"{",
"if",
"(",
"!",
"(",
"request",
"instanceof",
"Request",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Expecting request to be instance of Request'",
")",
"}",
"var",
"headers",
"=",
"[",
"]",
"var",
"headerNames",
"=",
"request",
".",
"headers",
".",
"keys",
"(",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"headerNames",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"headerName",
"=",
"headerNames",
"[",
"i",
"]",
"headers",
"[",
"headerName",
"]",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"headerName",
")",
"}",
"var",
"serialised",
"=",
"{",
"method",
":",
"request",
".",
"method",
",",
"url",
":",
"request",
".",
"url",
",",
"headers",
":",
"headers",
",",
"context",
":",
"request",
".",
"context",
",",
"referrer",
":",
"request",
".",
"referrer",
",",
"mode",
":",
"request",
".",
"mode",
",",
"credentials",
":",
"request",
".",
"credentials",
",",
"redirect",
":",
"request",
".",
"redirect",
",",
"integrity",
":",
"request",
".",
"integrity",
",",
"cache",
":",
"request",
".",
"cache",
",",
"bodyUsed",
":",
"request",
".",
"bodyUsed",
"}",
"return",
"request",
".",
"blob",
"(",
")",
".",
"then",
"(",
"blobUtil",
".",
"blobToBase64String",
")",
".",
"then",
"(",
"function",
"(",
"base64",
")",
"{",
"serialised",
".",
"__body",
"=",
"base64",
"return",
"toObject",
"?",
"serialised",
":",
"JSON",
".",
"stringify",
"(",
"serialised",
")",
"}",
")",
"}"
]
| Serialise a Request to a string or object.
@param {Request} request
@param {Boolean} [toObject] serialise to an object
@returns {Promise} | [
"Serialise",
"a",
"Request",
"to",
"a",
"string",
"or",
"object",
"."
]
| c0e108729bbe92cc05152d29ed32e7f7a7fffb82 | https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L72-L107 | train |
sdgluck/serialise-request | index.js | deserialiseRequest | function deserialiseRequest (serialised) {
var options
var url
if (typeof serialised === 'string') {
options = JSON.parse(serialised)
url = options.url
} else if (typeof serialised === 'object') {
options = serialised
url = options.url
} else {
throw new Error('Expecting serialised request to be a string or object')
}
const request = new Request(url, options)
const properties = {
context: {
enumerable: true,
value: options.context
}
}
const methods = Object.keys(BodyTypes).reduce(function (obj, key) {
const methodName = BodyMethods[key]
obj[methodName] = {
enumerable: true,
value: function () {
if (request.bodyUsed) {
return Promise.reject(new TypeError('Already used'))
}
request.bodyUsed = true
return Promise.resolve(remakeBody(options.__body, key))
}
}
return obj
}, properties)
Object.defineProperties(request, methods)
return request
} | javascript | function deserialiseRequest (serialised) {
var options
var url
if (typeof serialised === 'string') {
options = JSON.parse(serialised)
url = options.url
} else if (typeof serialised === 'object') {
options = serialised
url = options.url
} else {
throw new Error('Expecting serialised request to be a string or object')
}
const request = new Request(url, options)
const properties = {
context: {
enumerable: true,
value: options.context
}
}
const methods = Object.keys(BodyTypes).reduce(function (obj, key) {
const methodName = BodyMethods[key]
obj[methodName] = {
enumerable: true,
value: function () {
if (request.bodyUsed) {
return Promise.reject(new TypeError('Already used'))
}
request.bodyUsed = true
return Promise.resolve(remakeBody(options.__body, key))
}
}
return obj
}, properties)
Object.defineProperties(request, methods)
return request
} | [
"function",
"deserialiseRequest",
"(",
"serialised",
")",
"{",
"var",
"options",
"var",
"url",
"if",
"(",
"typeof",
"serialised",
"===",
"'string'",
")",
"{",
"options",
"=",
"JSON",
".",
"parse",
"(",
"serialised",
")",
"url",
"=",
"options",
".",
"url",
"}",
"else",
"if",
"(",
"typeof",
"serialised",
"===",
"'object'",
")",
"{",
"options",
"=",
"serialised",
"url",
"=",
"options",
".",
"url",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Expecting serialised request to be a string or object'",
")",
"}",
"const",
"request",
"=",
"new",
"Request",
"(",
"url",
",",
"options",
")",
"const",
"properties",
"=",
"{",
"context",
":",
"{",
"enumerable",
":",
"true",
",",
"value",
":",
"options",
".",
"context",
"}",
"}",
"const",
"methods",
"=",
"Object",
".",
"keys",
"(",
"BodyTypes",
")",
".",
"reduce",
"(",
"function",
"(",
"obj",
",",
"key",
")",
"{",
"const",
"methodName",
"=",
"BodyMethods",
"[",
"key",
"]",
"obj",
"[",
"methodName",
"]",
"=",
"{",
"enumerable",
":",
"true",
",",
"value",
":",
"function",
"(",
")",
"{",
"if",
"(",
"request",
".",
"bodyUsed",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"TypeError",
"(",
"'Already used'",
")",
")",
"}",
"request",
".",
"bodyUsed",
"=",
"true",
"return",
"Promise",
".",
"resolve",
"(",
"remakeBody",
"(",
"options",
".",
"__body",
",",
"key",
")",
")",
"}",
"}",
"return",
"obj",
"}",
",",
"properties",
")",
"Object",
".",
"defineProperties",
"(",
"request",
",",
"methods",
")",
"return",
"request",
"}"
]
| Deserialise a Request from a string or object.
@param {Object|String} serialised
@returns {Request} | [
"Deserialise",
"a",
"Request",
"from",
"a",
"string",
"or",
"object",
"."
]
| c0e108729bbe92cc05152d29ed32e7f7a7fffb82 | https://github.com/sdgluck/serialise-request/blob/c0e108729bbe92cc05152d29ed32e7f7a7fffb82/index.js#L114-L155 | train |
TJkrusinski/buzzfeed-headlines | lib/scraper.js | scrapePage | function scrapePage(cb, pages, links) {
links = links || [];
pages = pages || basePages.slice();
var url = pages.pop();
jsdom.env({
url: url,
scripts: ['http://code.jquery.com/jquery.js'],
done: function(err, window){
if (err) return cb(err);
_getLinks(window, links);
if (!pages.length) return cb(null, links);
scrapePage(cb, pages, links);
}
});
} | javascript | function scrapePage(cb, pages, links) {
links = links || [];
pages = pages || basePages.slice();
var url = pages.pop();
jsdom.env({
url: url,
scripts: ['http://code.jquery.com/jquery.js'],
done: function(err, window){
if (err) return cb(err);
_getLinks(window, links);
if (!pages.length) return cb(null, links);
scrapePage(cb, pages, links);
}
});
} | [
"function",
"scrapePage",
"(",
"cb",
",",
"pages",
",",
"links",
")",
"{",
"links",
"=",
"links",
"||",
"[",
"]",
";",
"pages",
"=",
"pages",
"||",
"basePages",
".",
"slice",
"(",
")",
";",
"var",
"url",
"=",
"pages",
".",
"pop",
"(",
")",
";",
"jsdom",
".",
"env",
"(",
"{",
"url",
":",
"url",
",",
"scripts",
":",
"[",
"'http://code.jquery.com/jquery.js'",
"]",
",",
"done",
":",
"function",
"(",
"err",
",",
"window",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"_getLinks",
"(",
"window",
",",
"links",
")",
";",
"if",
"(",
"!",
"pages",
".",
"length",
")",
"return",
"cb",
"(",
"null",
",",
"links",
")",
";",
"scrapePage",
"(",
"cb",
",",
"pages",
",",
"links",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Scrape a page
@param {Function} cb
@param {Number} pages - max number of pages
@param {String} links - the links accumulated thus far
@return undefined
@api public | [
"Scrape",
"a",
"page"
]
| 542f6a81c56a3bb57da3a7f5b391da0788f76e5e | https://github.com/TJkrusinski/buzzfeed-headlines/blob/542f6a81c56a3bb57da3a7f5b391da0788f76e5e/lib/scraper.js#L29-L45 | train |
TJkrusinski/buzzfeed-headlines | lib/scraper.js | _getLinks | function _getLinks (window, links) {
var $ = window.$;
$('a.lede__link').each(function(){
var text = $(this).text().trim();
if (!text) return;
links.push(text);
});
} | javascript | function _getLinks (window, links) {
var $ = window.$;
$('a.lede__link').each(function(){
var text = $(this).text().trim();
if (!text) return;
links.push(text);
});
} | [
"function",
"_getLinks",
"(",
"window",
",",
"links",
")",
"{",
"var",
"$",
"=",
"window",
".",
"$",
";",
"$",
"(",
"'a.lede__link'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"text",
"=",
"$",
"(",
"this",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"!",
"text",
")",
"return",
";",
"links",
".",
"push",
"(",
"text",
")",
";",
"}",
")",
";",
"}"
]
| Get article links from the page
@param {Object} window - jsdom `window` object
@param {Array} links - array of headline links
@api private | [
"Get",
"article",
"links",
"from",
"the",
"page"
]
| 542f6a81c56a3bb57da3a7f5b391da0788f76e5e | https://github.com/TJkrusinski/buzzfeed-headlines/blob/542f6a81c56a3bb57da3a7f5b391da0788f76e5e/lib/scraper.js#L56-L64 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | generateRandomClientId | function generateRandomClientId() {
var length = 22;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
} | javascript | function generateRandomClientId() {
var length = 22;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
} | [
"function",
"generateRandomClientId",
"(",
")",
"{",
"var",
"length",
"=",
"22",
";",
"var",
"chars",
"=",
"'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'",
";",
"var",
"result",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"length",
";",
"i",
">",
"0",
";",
"--",
"i",
")",
"{",
"result",
"+=",
"chars",
"[",
"Math",
".",
"round",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"(",
"chars",
".",
"length",
"-",
"1",
")",
")",
"]",
";",
"}",
"return",
"result",
";",
"}"
]
| Helper function that generates a random client ID | [
"Helper",
"function",
"that",
"generates",
"a",
"random",
"client",
"ID"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L30-L38 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | connectBrowser | function connectBrowser (subscriptions, backlog, host, done_cb, secure) {
// Associate the right port
var websocket_uri;
if(secure == true) {
websocket_uri ='wss://' + host + ':1885/mqtt';
}
else {
websocket_uri ='ws://' + host + ':1884/mqtt';
}
// Create client
var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId());
// Register callback for connection lost
client.onConnectionLost = function() {
// TODO try to reconnect
};
// Register callback for received message
client.onMessageArrived = function (message) {
// Execute all the appropriate callbacks:
// the ones specific to this channel with a single parameter (message)
// the ones associated to a wildcard channel, with two parameters (message and channel)
var cbs = findCallbacks(subscriptions, message.destinationName);
if (cbs!==undefined) {
cbs.forEach(function(cb) {
if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1)
cb(message.payloadString);
else
cb(message.payloadString, message.destinationName);
});
}
};
// Connect
client.connect({onSuccess: function() {
// Execute optional done callback passing true
if (done_cb!==undefined)
done_cb(true);
// Execute the backlog of operations performed while the client wasn't connected
backlog.forEach(function(e) {
e.op.apply(this, e.params);
});
},
onFailure: function() {
// Execute optional done callback passing false
if (done_cb!==undefined)
done_cb(false);
else
console.error('There was a problem initializing nutella.');
}});
return client;
} | javascript | function connectBrowser (subscriptions, backlog, host, done_cb, secure) {
// Associate the right port
var websocket_uri;
if(secure == true) {
websocket_uri ='wss://' + host + ':1885/mqtt';
}
else {
websocket_uri ='ws://' + host + ':1884/mqtt';
}
// Create client
var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId());
// Register callback for connection lost
client.onConnectionLost = function() {
// TODO try to reconnect
};
// Register callback for received message
client.onMessageArrived = function (message) {
// Execute all the appropriate callbacks:
// the ones specific to this channel with a single parameter (message)
// the ones associated to a wildcard channel, with two parameters (message and channel)
var cbs = findCallbacks(subscriptions, message.destinationName);
if (cbs!==undefined) {
cbs.forEach(function(cb) {
if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1)
cb(message.payloadString);
else
cb(message.payloadString, message.destinationName);
});
}
};
// Connect
client.connect({onSuccess: function() {
// Execute optional done callback passing true
if (done_cb!==undefined)
done_cb(true);
// Execute the backlog of operations performed while the client wasn't connected
backlog.forEach(function(e) {
e.op.apply(this, e.params);
});
},
onFailure: function() {
// Execute optional done callback passing false
if (done_cb!==undefined)
done_cb(false);
else
console.error('There was a problem initializing nutella.');
}});
return client;
} | [
"function",
"connectBrowser",
"(",
"subscriptions",
",",
"backlog",
",",
"host",
",",
"done_cb",
",",
"secure",
")",
"{",
"var",
"websocket_uri",
";",
"if",
"(",
"secure",
"==",
"true",
")",
"{",
"websocket_uri",
"=",
"'wss://'",
"+",
"host",
"+",
"':1885/mqtt'",
";",
"}",
"else",
"{",
"websocket_uri",
"=",
"'ws://'",
"+",
"host",
"+",
"':1884/mqtt'",
";",
"}",
"var",
"client",
"=",
"new",
"mqtt_lib",
".",
"Client",
"(",
"websocket_uri",
",",
"generateRandomClientId",
"(",
")",
")",
";",
"client",
".",
"onConnectionLost",
"=",
"function",
"(",
")",
"{",
"}",
";",
"client",
".",
"onMessageArrived",
"=",
"function",
"(",
"message",
")",
"{",
"var",
"cbs",
"=",
"findCallbacks",
"(",
"subscriptions",
",",
"message",
".",
"destinationName",
")",
";",
"if",
"(",
"cbs",
"!==",
"undefined",
")",
"{",
"cbs",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"subscriptions",
")",
".",
"indexOf",
"(",
"message",
".",
"destinationName",
")",
"!==",
"-",
"1",
")",
"cb",
"(",
"message",
".",
"payloadString",
")",
";",
"else",
"cb",
"(",
"message",
".",
"payloadString",
",",
"message",
".",
"destinationName",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"client",
".",
"connect",
"(",
"{",
"onSuccess",
":",
"function",
"(",
")",
"{",
"if",
"(",
"done_cb",
"!==",
"undefined",
")",
"done_cb",
"(",
"true",
")",
";",
"backlog",
".",
"forEach",
"(",
"function",
"(",
"e",
")",
"{",
"e",
".",
"op",
".",
"apply",
"(",
"this",
",",
"e",
".",
"params",
")",
";",
"}",
")",
";",
"}",
",",
"onFailure",
":",
"function",
"(",
")",
"{",
"if",
"(",
"done_cb",
"!==",
"undefined",
")",
"done_cb",
"(",
"false",
")",
";",
"else",
"console",
".",
"error",
"(",
"'There was a problem initializing nutella.'",
")",
";",
"}",
"}",
")",
";",
"return",
"client",
";",
"}"
]
| Helper function that connects the MQTT client in the browser | [
"Helper",
"function",
"that",
"connects",
"the",
"MQTT",
"client",
"in",
"the",
"browser"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L43-L93 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | subscribeBrowser | function subscribeBrowser (client, subscriptions, backlog, channel, callback, done_callback) {
if ( addToBacklog(client, backlog, subscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return;
if (subscriptions[channel]===undefined) {
subscriptions[channel] = [callback];
client.subscribe(channel, {qos: 0, onSuccess: function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}});
} else {
subscriptions[channel].push(callback);
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}
} | javascript | function subscribeBrowser (client, subscriptions, backlog, channel, callback, done_callback) {
if ( addToBacklog(client, backlog, subscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return;
if (subscriptions[channel]===undefined) {
subscriptions[channel] = [callback];
client.subscribe(channel, {qos: 0, onSuccess: function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}});
} else {
subscriptions[channel].push(callback);
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}
} | [
"function",
"subscribeBrowser",
"(",
"client",
",",
"subscriptions",
",",
"backlog",
",",
"channel",
",",
"callback",
",",
"done_callback",
")",
"{",
"if",
"(",
"addToBacklog",
"(",
"client",
",",
"backlog",
",",
"subscribeBrowser",
",",
"[",
"client",
",",
"subscriptions",
",",
"backlog",
",",
"channel",
",",
"callback",
",",
"done_callback",
"]",
")",
")",
"return",
";",
"if",
"(",
"subscriptions",
"[",
"channel",
"]",
"===",
"undefined",
")",
"{",
"subscriptions",
"[",
"channel",
"]",
"=",
"[",
"callback",
"]",
";",
"client",
".",
"subscribe",
"(",
"channel",
",",
"{",
"qos",
":",
"0",
",",
"onSuccess",
":",
"function",
"(",
")",
"{",
"if",
"(",
"done_callback",
"!==",
"undefined",
")",
"done_callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"subscriptions",
"[",
"channel",
"]",
".",
"push",
"(",
"callback",
")",
";",
"if",
"(",
"done_callback",
"!==",
"undefined",
")",
"done_callback",
"(",
")",
";",
"}",
"}"
]
| Helper function that subscribes to a channel in the browser | [
"Helper",
"function",
"that",
"subscribes",
"to",
"a",
"channel",
"in",
"the",
"browser"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L122-L135 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | function(client, subscriptions, backlog, channel, callback, done_callback) {
if ( addToBacklog(client, backlog, unsubscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return;
if (subscriptions[channel]===undefined)
return;
subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
if (subscriptions[channel].length===0) {
delete subscriptions[channel];
client.unsubscribe(channel, {onSuccess : function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}});
}
} | javascript | function(client, subscriptions, backlog, channel, callback, done_callback) {
if ( addToBacklog(client, backlog, unsubscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return;
if (subscriptions[channel]===undefined)
return;
subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
if (subscriptions[channel].length===0) {
delete subscriptions[channel];
client.unsubscribe(channel, {onSuccess : function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}});
}
} | [
"function",
"(",
"client",
",",
"subscriptions",
",",
"backlog",
",",
"channel",
",",
"callback",
",",
"done_callback",
")",
"{",
"if",
"(",
"addToBacklog",
"(",
"client",
",",
"backlog",
",",
"unsubscribeBrowser",
",",
"[",
"client",
",",
"subscriptions",
",",
"backlog",
",",
"channel",
",",
"callback",
",",
"done_callback",
"]",
")",
")",
"return",
";",
"if",
"(",
"subscriptions",
"[",
"channel",
"]",
"===",
"undefined",
")",
"return",
";",
"subscriptions",
"[",
"channel",
"]",
".",
"splice",
"(",
"subscriptions",
"[",
"channel",
"]",
".",
"indexOf",
"(",
"callback",
")",
",",
"1",
")",
";",
"if",
"(",
"subscriptions",
"[",
"channel",
"]",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"subscriptions",
"[",
"channel",
"]",
";",
"client",
".",
"unsubscribe",
"(",
"channel",
",",
"{",
"onSuccess",
":",
"function",
"(",
")",
"{",
"if",
"(",
"done_callback",
"!==",
"undefined",
")",
"done_callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Helper function that unsubscribes from a channel in the browser | [
"Helper",
"function",
"that",
"unsubscribes",
"from",
"a",
"channel",
"in",
"the",
"browser"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L156-L168 | train |
|
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | function (client, backlog, channel, message) {
if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return;
message = new mqtt_lib.Message(message);
message.destinationName = channel;
client.send(message);
} | javascript | function (client, backlog, channel, message) {
if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return;
message = new mqtt_lib.Message(message);
message.destinationName = channel;
client.send(message);
} | [
"function",
"(",
"client",
",",
"backlog",
",",
"channel",
",",
"message",
")",
"{",
"if",
"(",
"addToBacklog",
"(",
"client",
",",
"backlog",
",",
"publishBrowser",
",",
"[",
"client",
",",
"backlog",
",",
"channel",
",",
"message",
"]",
")",
")",
"return",
";",
"message",
"=",
"new",
"mqtt_lib",
".",
"Message",
"(",
"message",
")",
";",
"message",
".",
"destinationName",
"=",
"channel",
";",
"client",
".",
"send",
"(",
"message",
")",
";",
"}"
]
| Helper function that publishes to a channel in the browser | [
"Helper",
"function",
"that",
"publishes",
"to",
"a",
"channel",
"in",
"the",
"browser"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L195-L200 | train |
|
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | findCallbacks | function findCallbacks (subscriptions, channel) {
// First try to see if a callback for the exact channel exists
if(Object.keys(subscriptions).indexOf(channel)!==-1)
return subscriptions[channel];
// If it doesn't then let's try to see if the channel matches a wildcard callback
var pattern = matchesWildcard(subscriptions, channel);
if (pattern!== undefined) {
return subscriptions[pattern];
}
// If there's no exact match or wildcard we have to return undefined
return undefined;
} | javascript | function findCallbacks (subscriptions, channel) {
// First try to see if a callback for the exact channel exists
if(Object.keys(subscriptions).indexOf(channel)!==-1)
return subscriptions[channel];
// If it doesn't then let's try to see if the channel matches a wildcard callback
var pattern = matchesWildcard(subscriptions, channel);
if (pattern!== undefined) {
return subscriptions[pattern];
}
// If there's no exact match or wildcard we have to return undefined
return undefined;
} | [
"function",
"findCallbacks",
"(",
"subscriptions",
",",
"channel",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"subscriptions",
")",
".",
"indexOf",
"(",
"channel",
")",
"!==",
"-",
"1",
")",
"return",
"subscriptions",
"[",
"channel",
"]",
";",
"var",
"pattern",
"=",
"matchesWildcard",
"(",
"subscriptions",
",",
"channel",
")",
";",
"if",
"(",
"pattern",
"!==",
"undefined",
")",
"{",
"return",
"subscriptions",
"[",
"pattern",
"]",
";",
"}",
"return",
"undefined",
";",
"}"
]
| Helper function that selects the right callback when a message is received | [
"Helper",
"function",
"that",
"selects",
"the",
"right",
"callback",
"when",
"a",
"message",
"is",
"received"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L233-L244 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | matchesWildcard | function matchesWildcard (subscriptions, channel) {
var i;
var subs = Object.keys(subscriptions);
for (i=0; i < subs.length; i++) {
if (matchesFilter(subs[i], channel)) {
return subs[i];
}
}
return undefined;
} | javascript | function matchesWildcard (subscriptions, channel) {
var i;
var subs = Object.keys(subscriptions);
for (i=0; i < subs.length; i++) {
if (matchesFilter(subs[i], channel)) {
return subs[i];
}
}
return undefined;
} | [
"function",
"matchesWildcard",
"(",
"subscriptions",
",",
"channel",
")",
"{",
"var",
"i",
";",
"var",
"subs",
"=",
"Object",
".",
"keys",
"(",
"subscriptions",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"subs",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"matchesFilter",
"(",
"subs",
"[",
"i",
"]",
",",
"channel",
")",
")",
"{",
"return",
"subs",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"undefined",
";",
"}"
]
| Helper function that tries to match a channel with each subscription it returns undefined if no match is found | [
"Helper",
"function",
"that",
"tries",
"to",
"match",
"a",
"channel",
"with",
"each",
"subscription",
"it",
"returns",
"undefined",
"if",
"no",
"match",
"is",
"found"
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L251-L260 | train |
nutella-framework/nutella_lib.js | src/simple-mqtt-client/client-browser.js | addToBacklog | function addToBacklog (client, backlog, method, parameters) {
if (!client.isConnected() ) {
backlog.push({
op : method,
params : parameters
});
return true;
}
return false;
} | javascript | function addToBacklog (client, backlog, method, parameters) {
if (!client.isConnected() ) {
backlog.push({
op : method,
params : parameters
});
return true;
}
return false;
} | [
"function",
"addToBacklog",
"(",
"client",
",",
"backlog",
",",
"method",
",",
"parameters",
")",
"{",
"if",
"(",
"!",
"client",
".",
"isConnected",
"(",
")",
")",
"{",
"backlog",
".",
"push",
"(",
"{",
"op",
":",
"method",
",",
"params",
":",
"parameters",
"}",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Helper method that queues operations into the backlog. This method is used to make `connect` "synchronous" by queueing up operations on the client until it is connected. @param {string} method - the method that needs to be added to the backlog @param {Array} parameters - parameters to the method being added to the backlog @returns {boolean} true if the method was successfully added, false otherwise | [
"Helper",
"method",
"that",
"queues",
"operations",
"into",
"the",
"backlog",
".",
"This",
"method",
"is",
"used",
"to",
"make",
"connect",
"synchronous",
"by",
"queueing",
"up",
"operations",
"on",
"the",
"client",
"until",
"it",
"is",
"connected",
"."
]
| b3a3406a407e2a1ada6edcc503b70991f9cb249b | https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/simple-mqtt-client/client-browser.js#L295-L304 | train |
thlorenz/snippetify | examples/snippetify-self-parsable.js | printParsableCode | function printParsableCode(snippets) {
// prints all lines, some of which were fixed to make them parsable
var lines = snippets
.map(function (x) { return '[ ' + x.code + ' ]'; });
console.log(lines.join('\n'));
} | javascript | function printParsableCode(snippets) {
// prints all lines, some of which were fixed to make them parsable
var lines = snippets
.map(function (x) { return '[ ' + x.code + ' ]'; });
console.log(lines.join('\n'));
} | [
"function",
"printParsableCode",
"(",
"snippets",
")",
"{",
"var",
"lines",
"=",
"snippets",
".",
"map",
"(",
"function",
"(",
"x",
")",
"{",
"return",
"'[ '",
"+",
"x",
".",
"code",
"+",
"' ]'",
";",
"}",
")",
";",
"console",
".",
"log",
"(",
"lines",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"}"
]
| This meaningless comment will be a separate snippet since it is parsable on its own | [
"This",
"meaningless",
"comment",
"will",
"be",
"a",
"separate",
"snippet",
"since",
"it",
"is",
"parsable",
"on",
"its",
"own"
]
| cc5795b155955c15c78ead01d10d72ee44fab846 | https://github.com/thlorenz/snippetify/blob/cc5795b155955c15c78ead01d10d72ee44fab846/examples/snippetify-self-parsable.js#L8-L14 | train |
LuiseteMola/wraps-cache | dist/index.js | configure | function configure(cacheType, conf) {
// Check for custom logging functions on cache (debug)
if (conf && conf.logger) {
logger_1.configureLogger(conf.logger);
logger_1.logger.info('Custom cache logger configured');
}
if (cacheType)
exports.cache = cacheType;
} | javascript | function configure(cacheType, conf) {
// Check for custom logging functions on cache (debug)
if (conf && conf.logger) {
logger_1.configureLogger(conf.logger);
logger_1.logger.info('Custom cache logger configured');
}
if (cacheType)
exports.cache = cacheType;
} | [
"function",
"configure",
"(",
"cacheType",
",",
"conf",
")",
"{",
"if",
"(",
"conf",
"&&",
"conf",
".",
"logger",
")",
"{",
"logger_1",
".",
"configureLogger",
"(",
"conf",
".",
"logger",
")",
";",
"logger_1",
".",
"logger",
".",
"info",
"(",
"'Custom cache logger configured'",
")",
";",
"}",
"if",
"(",
"cacheType",
")",
"exports",
".",
"cache",
"=",
"cacheType",
";",
"}"
]
| Cache middleware configuration | [
"Cache",
"middleware",
"configuration"
]
| b43973a4d48e4223c08ec4aae05f3f8267112f16 | https://github.com/LuiseteMola/wraps-cache/blob/b43973a4d48e4223c08ec4aae05f3f8267112f16/dist/index.js#L10-L18 | train |
ugate/releasebot | Gruntfile.js | Tasks | function Tasks() {
this.tasks = [];
this.add = function(task) {
var commit = grunt.config.get('releasebot.commit');
if (commit.skipTaskCheck(task)) {
grunt.log.writeln('Skipping "' + task + '" task');
return false;
}
// grunt.log.writeln('Queuing "' + task + '" task');
return this.tasks.push(task);
};
} | javascript | function Tasks() {
this.tasks = [];
this.add = function(task) {
var commit = grunt.config.get('releasebot.commit');
if (commit.skipTaskCheck(task)) {
grunt.log.writeln('Skipping "' + task + '" task');
return false;
}
// grunt.log.writeln('Queuing "' + task + '" task');
return this.tasks.push(task);
};
} | [
"function",
"Tasks",
"(",
")",
"{",
"this",
".",
"tasks",
"=",
"[",
"]",
";",
"this",
".",
"add",
"=",
"function",
"(",
"task",
")",
"{",
"var",
"commit",
"=",
"grunt",
".",
"config",
".",
"get",
"(",
"'releasebot.commit'",
")",
";",
"if",
"(",
"commit",
".",
"skipTaskCheck",
"(",
"task",
")",
")",
"{",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Skipping \"'",
"+",
"task",
"+",
"'\" task'",
")",
";",
"return",
"false",
";",
"}",
"return",
"this",
".",
"tasks",
".",
"push",
"(",
"task",
")",
";",
"}",
";",
"}"
]
| Task array that takes into account possible skip options
@constructor | [
"Task",
"array",
"that",
"takes",
"into",
"account",
"possible",
"skip",
"options"
]
| 1a2ff42796e77f47f9590992c014fee461aad80b | https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/Gruntfile.js#L140-L151 | train |
kuhnza/node-tubesio | lib/tubesio/utils.js | Args | function Args() {
if (argv._.length >= 1) {
try {
// Attempt to parse 1st argument as JSON string
_.extend(this, JSON.parse(argv._[0]));
} catch (err) {
// Pass, we must be in the console so don't worry about it
}
}
} | javascript | function Args() {
if (argv._.length >= 1) {
try {
// Attempt to parse 1st argument as JSON string
_.extend(this, JSON.parse(argv._[0]));
} catch (err) {
// Pass, we must be in the console so don't worry about it
}
}
} | [
"function",
"Args",
"(",
")",
"{",
"if",
"(",
"argv",
".",
"_",
".",
"length",
">=",
"1",
")",
"{",
"try",
"{",
"_",
".",
"extend",
"(",
"this",
",",
"JSON",
".",
"parse",
"(",
"argv",
".",
"_",
"[",
"0",
"]",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"}"
]
| All functions, include conflict, will be available through _.str object
Argument parser object. | [
"All",
"functions",
"include",
"conflict",
"will",
"be",
"available",
"through",
"_",
".",
"str",
"object",
"Argument",
"parser",
"object",
"."
]
| 198d005de764480485fe038d1832ccb0f6e0596e | https://github.com/kuhnza/node-tubesio/blob/198d005de764480485fe038d1832ccb0f6e0596e/lib/tubesio/utils.js#L27-L36 | train |
kuhnza/node-tubesio | lib/tubesio/utils.js | getLastResult | function getLastResult() {
if (argv._.length >= 2) {
try {
return JSON.parse(argv._[1]);
} catch (err) {
// pass
}
}
return null;
} | javascript | function getLastResult() {
if (argv._.length >= 2) {
try {
return JSON.parse(argv._[1]);
} catch (err) {
// pass
}
}
return null;
} | [
"function",
"getLastResult",
"(",
")",
"{",
"if",
"(",
"argv",
".",
"_",
".",
"length",
">=",
"2",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"argv",
".",
"_",
"[",
"1",
"]",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}",
"return",
"null",
";",
"}"
]
| Parse last results if present. | [
"Parse",
"last",
"results",
"if",
"present",
"."
]
| 198d005de764480485fe038d1832ccb0f6e0596e | https://github.com/kuhnza/node-tubesio/blob/198d005de764480485fe038d1832ccb0f6e0596e/lib/tubesio/utils.js#L54-L64 | train |
kuhnza/node-tubesio | lib/tubesio/utils.js | EStoreScraper | function EStoreScraper() {
_.defaults(this, {
logger: new logging.Logger(),
cookieJar: new CookieJar(),
maxConcurrency: 10,
startPage: '',
agent: new http.Agent()
});
this.agent.maxSockets = this.maxConcurrency;
this.products = [];
this.waiting = 0;
} | javascript | function EStoreScraper() {
_.defaults(this, {
logger: new logging.Logger(),
cookieJar: new CookieJar(),
maxConcurrency: 10,
startPage: '',
agent: new http.Agent()
});
this.agent.maxSockets = this.maxConcurrency;
this.products = [];
this.waiting = 0;
} | [
"function",
"EStoreScraper",
"(",
")",
"{",
"_",
".",
"defaults",
"(",
"this",
",",
"{",
"logger",
":",
"new",
"logging",
".",
"Logger",
"(",
")",
",",
"cookieJar",
":",
"new",
"CookieJar",
"(",
")",
",",
"maxConcurrency",
":",
"10",
",",
"startPage",
":",
"''",
",",
"agent",
":",
"new",
"http",
".",
"Agent",
"(",
")",
"}",
")",
";",
"this",
".",
"agent",
".",
"maxSockets",
"=",
"this",
".",
"maxConcurrency",
";",
"this",
".",
"products",
"=",
"[",
"]",
";",
"this",
".",
"waiting",
"=",
"0",
";",
"}"
]
| General purpose e-commerce store scraper shell. | [
"General",
"purpose",
"e",
"-",
"commerce",
"store",
"scraper",
"shell",
"."
]
| 198d005de764480485fe038d1832ccb0f6e0596e | https://github.com/kuhnza/node-tubesio/blob/198d005de764480485fe038d1832ccb0f6e0596e/lib/tubesio/utils.js#L72-L84 | train |
andreruffert/closest-number | index.js | closestNumber | function closestNumber(arr, num) {
return arr.reduce((prev, curr) => (Math.abs(curr - num) < Math.abs(prev - num)) ? curr : prev);
} | javascript | function closestNumber(arr, num) {
return arr.reduce((prev, curr) => (Math.abs(curr - num) < Math.abs(prev - num)) ? curr : prev);
} | [
"function",
"closestNumber",
"(",
"arr",
",",
"num",
")",
"{",
"return",
"arr",
".",
"reduce",
"(",
"(",
"prev",
",",
"curr",
")",
"=>",
"(",
"Math",
".",
"abs",
"(",
"curr",
"-",
"num",
")",
"<",
"Math",
".",
"abs",
"(",
"prev",
"-",
"num",
")",
")",
"?",
"curr",
":",
"prev",
")",
";",
"}"
]
| Returns the closest number out of an array
@param {Array} arr
@param {Number} num
@return {Number} | [
"Returns",
"the",
"closest",
"number",
"out",
"of",
"an",
"array"
]
| 5dcf1497d7fa6b05ed4cd80f05ad4fccc5edb1ed | https://github.com/andreruffert/closest-number/blob/5dcf1497d7fa6b05ed4cd80f05ad4fccc5edb1ed/index.js#L7-L9 | train |
Augmentedjs/augmented | scripts/core/augmented.js | function(source, type) {
var out = null;
switch(type) {
case Augmented.Utility.TransformerType.xString:
if (typeof source === 'object') {
out = JSON.stringify(source);
} else {
out = String(source);
}
break;
case Augmented.Utility.TransformerType.xInteger:
out = parseInt(source);
break;
case Augmented.Utility.TransformerType.xNumber:
out = Number(source);
break;
case Augmented.Utility.TransformerType.xBoolean:
out = Boolean(source);
break;
case Augmented.Utility.TransformerType.xArray:
if (!Array.isArray(source)) {
out = [];
out[0] = source;
} else {
out = source;
}
break;
case Augmented.Utility.TransformerType.xObject:
if (typeof source !== 'object') {
out = {};
out[source] = source;
} else {
out = source;
}
break;
}
return out;
} | javascript | function(source, type) {
var out = null;
switch(type) {
case Augmented.Utility.TransformerType.xString:
if (typeof source === 'object') {
out = JSON.stringify(source);
} else {
out = String(source);
}
break;
case Augmented.Utility.TransformerType.xInteger:
out = parseInt(source);
break;
case Augmented.Utility.TransformerType.xNumber:
out = Number(source);
break;
case Augmented.Utility.TransformerType.xBoolean:
out = Boolean(source);
break;
case Augmented.Utility.TransformerType.xArray:
if (!Array.isArray(source)) {
out = [];
out[0] = source;
} else {
out = source;
}
break;
case Augmented.Utility.TransformerType.xObject:
if (typeof source !== 'object') {
out = {};
out[source] = source;
} else {
out = source;
}
break;
}
return out;
} | [
"function",
"(",
"source",
",",
"type",
")",
"{",
"var",
"out",
"=",
"null",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xString",
":",
"if",
"(",
"typeof",
"source",
"===",
"'object'",
")",
"{",
"out",
"=",
"JSON",
".",
"stringify",
"(",
"source",
")",
";",
"}",
"else",
"{",
"out",
"=",
"String",
"(",
"source",
")",
";",
"}",
"break",
";",
"case",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xInteger",
":",
"out",
"=",
"parseInt",
"(",
"source",
")",
";",
"break",
";",
"case",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xNumber",
":",
"out",
"=",
"Number",
"(",
"source",
")",
";",
"break",
";",
"case",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xBoolean",
":",
"out",
"=",
"Boolean",
"(",
"source",
")",
";",
"break",
";",
"case",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xArray",
":",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"source",
")",
")",
"{",
"out",
"=",
"[",
"]",
";",
"out",
"[",
"0",
"]",
"=",
"source",
";",
"}",
"else",
"{",
"out",
"=",
"source",
";",
"}",
"break",
";",
"case",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xObject",
":",
"if",
"(",
"typeof",
"source",
"!==",
"'object'",
")",
"{",
"out",
"=",
"{",
"}",
";",
"out",
"[",
"source",
"]",
"=",
"source",
";",
"}",
"else",
"{",
"out",
"=",
"source",
";",
"}",
"break",
";",
"}",
"return",
"out",
";",
"}"
]
| Transform an object, primitive, or array to another object, primitive, or array
@method transform
@param {object} source Source primitive to transform
@param {Augmented.Utility.TransformerType} type Type to transform to
@memberof Augmented.Utility.Transformer
@returns {object} returns a transformed object or primitive | [
"Transform",
"an",
"object",
"primitive",
"or",
"array",
"to",
"another",
"object",
"primitive",
"or",
"array"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L613-L650 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(source) {
if (source === null) {
return Augmented.Utility.TransformerType.xNull;
} else if (typeof source === 'string') {
return Augmented.Utility.TransformerType.xString;
} else if (typeof source === 'number') {
return Augmented.Utility.TransformerType.xNumber;
} else if (typeof source === 'boolean') {
return Augmented.Utility.TransformerType.xBoolean;
} else if (Array.isArray(source)) {
return Augmented.Utility.TransformerType.xArray;
} else if (typeof source === 'object') {
return Augmented.Utility.TransformerType.xObject;
}
} | javascript | function(source) {
if (source === null) {
return Augmented.Utility.TransformerType.xNull;
} else if (typeof source === 'string') {
return Augmented.Utility.TransformerType.xString;
} else if (typeof source === 'number') {
return Augmented.Utility.TransformerType.xNumber;
} else if (typeof source === 'boolean') {
return Augmented.Utility.TransformerType.xBoolean;
} else if (Array.isArray(source)) {
return Augmented.Utility.TransformerType.xArray;
} else if (typeof source === 'object') {
return Augmented.Utility.TransformerType.xObject;
}
} | [
"function",
"(",
"source",
")",
"{",
"if",
"(",
"source",
"===",
"null",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xNull",
";",
"}",
"else",
"if",
"(",
"typeof",
"source",
"===",
"'string'",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xString",
";",
"}",
"else",
"if",
"(",
"typeof",
"source",
"===",
"'number'",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xNumber",
";",
"}",
"else",
"if",
"(",
"typeof",
"source",
"===",
"'boolean'",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xBoolean",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"source",
")",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xArray",
";",
"}",
"else",
"if",
"(",
"typeof",
"source",
"===",
"'object'",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"TransformerType",
".",
"xObject",
";",
"}",
"}"
]
| Returns a Augmented.Utility.TransformerType of a passed object
@method isType
@memberof Augmented.Utility.Transformer
@param {object} source The source primitive
@returns {Augmented.Utility.TransformerType} type of source as Augmented.Utility.TransformerType | [
"Returns",
"a",
"Augmented",
".",
"Utility",
".",
"TransformerType",
"of",
"a",
"passed",
"object"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L658-L672 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(type, level) {
if (type === Augmented.Logger.Type.console) {
return new consoleLogger(level);
} else if (type === Augmented.Logger.Type.colorConsole) {
return new colorConsoleLogger(level);
} else if (type === Augmented.Logger.Type.rest) {
return new restLogger(level);
}
} | javascript | function(type, level) {
if (type === Augmented.Logger.Type.console) {
return new consoleLogger(level);
} else if (type === Augmented.Logger.Type.colorConsole) {
return new colorConsoleLogger(level);
} else if (type === Augmented.Logger.Type.rest) {
return new restLogger(level);
}
} | [
"function",
"(",
"type",
",",
"level",
")",
"{",
"if",
"(",
"type",
"===",
"Augmented",
".",
"Logger",
".",
"Type",
".",
"console",
")",
"{",
"return",
"new",
"consoleLogger",
"(",
"level",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"Augmented",
".",
"Logger",
".",
"Type",
".",
"colorConsole",
")",
"{",
"return",
"new",
"colorConsoleLogger",
"(",
"level",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"Augmented",
".",
"Logger",
".",
"Type",
".",
"rest",
")",
"{",
"return",
"new",
"restLogger",
"(",
"level",
")",
";",
"}",
"}"
]
| getLogger - get an instance of a logger
@method getLogger
@param {Augmented.Logger.Type} type Type of logger instance
@param {Augmented.Logger.Level} level Level to set the logger to
@memberof Augmented.Logger.LoggerFactory
@returns {Augmented.Logger.abstractLogger} logger Instance of a logger by istance type
@example Augmented.Logger.LoggerFactory.getLogger(Augmented.Logger.Type.console, Augmented.Logger.Level.debug); | [
"getLogger",
"-",
"get",
"an",
"instance",
"of",
"a",
"logger"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L1280-L1288 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(username, password) {
var c = null;
Augmented.ajax({
url: this.uri,
method: "GET",
user: username,
password: password,
success: function(data, status) {
var p = new principal({
fullName: data.fullName,
id: data.id,
login: data.login,
email: data.email
});
c = new securityContext(p, data.permissions);
},
failure: function(data, status) {
// TODO: Bundle this perhaps
throw new Error("Failed to authenticate with response of - " + status);
}
});
return c;
} | javascript | function(username, password) {
var c = null;
Augmented.ajax({
url: this.uri,
method: "GET",
user: username,
password: password,
success: function(data, status) {
var p = new principal({
fullName: data.fullName,
id: data.id,
login: data.login,
email: data.email
});
c = new securityContext(p, data.permissions);
},
failure: function(data, status) {
// TODO: Bundle this perhaps
throw new Error("Failed to authenticate with response of - " + status);
}
});
return c;
} | [
"function",
"(",
"username",
",",
"password",
")",
"{",
"var",
"c",
"=",
"null",
";",
"Augmented",
".",
"ajax",
"(",
"{",
"url",
":",
"this",
".",
"uri",
",",
"method",
":",
"\"GET\"",
",",
"user",
":",
"username",
",",
"password",
":",
"password",
",",
"success",
":",
"function",
"(",
"data",
",",
"status",
")",
"{",
"var",
"p",
"=",
"new",
"principal",
"(",
"{",
"fullName",
":",
"data",
".",
"fullName",
",",
"id",
":",
"data",
".",
"id",
",",
"login",
":",
"data",
".",
"login",
",",
"email",
":",
"data",
".",
"email",
"}",
")",
";",
"c",
"=",
"new",
"securityContext",
"(",
"p",
",",
"data",
".",
"permissions",
")",
";",
"}",
",",
"failure",
":",
"function",
"(",
"data",
",",
"status",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Failed to authenticate with response of - \"",
"+",
"status",
")",
";",
"}",
"}",
")",
";",
"return",
"c",
";",
"}"
]
| authenticate the user
@method authenticate
@param {string} username The name of the user (login)
@param {string} password The password for the user (not stored)
@returns {Augmented.Security.Context} Returns a security context or null is case of failure
@memberof Augmented.Security.Client.ACL
@throws Error Failed to authenticate | [
"authenticate",
"the",
"user"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L1794-L1816 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(clientType) {
if (clientType === Augmented.Security.ClientType.OAUTH2) {
return new Augmented.Security.Client.OAUTH2Client();
} else if (clientType === Augmented.Security.ClientType.ACL) {
return new Augmented.Security.Client.ACLClient();
}
return null;
} | javascript | function(clientType) {
if (clientType === Augmented.Security.ClientType.OAUTH2) {
return new Augmented.Security.Client.OAUTH2Client();
} else if (clientType === Augmented.Security.ClientType.ACL) {
return new Augmented.Security.Client.ACLClient();
}
return null;
} | [
"function",
"(",
"clientType",
")",
"{",
"if",
"(",
"clientType",
"===",
"Augmented",
".",
"Security",
".",
"ClientType",
".",
"OAUTH2",
")",
"{",
"return",
"new",
"Augmented",
".",
"Security",
".",
"Client",
".",
"OAUTH2Client",
"(",
")",
";",
"}",
"else",
"if",
"(",
"clientType",
"===",
"Augmented",
".",
"Security",
".",
"ClientType",
".",
"ACL",
")",
"{",
"return",
"new",
"Augmented",
".",
"Security",
".",
"Client",
".",
"ACLClient",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
]
| Get an instance of a security client
@method getSecurityClient
@param {Augmented.Security.ClientType} clientType The Client Type to return
@returns {Augmented.Security.Client} Returns a security client instance
@memberof Augmented.Security.AuthenticationFactory | [
"Get",
"an",
"instance",
"of",
"a",
"security",
"client"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L1834-L1841 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(message) {
var key = "";
if (message) {
var x = message.level &&
(key += message.level, message.kind &&
(key += this.delimiter + message.kind, message.rule &&
(key += this.delimiter + message.rule, message.values.title &&
(key += this.delimiter + message.values.title))));
}
return (key) ? key : "";
} | javascript | function(message) {
var key = "";
if (message) {
var x = message.level &&
(key += message.level, message.kind &&
(key += this.delimiter + message.kind, message.rule &&
(key += this.delimiter + message.rule, message.values.title &&
(key += this.delimiter + message.values.title))));
}
return (key) ? key : "";
} | [
"function",
"(",
"message",
")",
"{",
"var",
"key",
"=",
"\"\"",
";",
"if",
"(",
"message",
")",
"{",
"var",
"x",
"=",
"message",
".",
"level",
"&&",
"(",
"key",
"+=",
"message",
".",
"level",
",",
"message",
".",
"kind",
"&&",
"(",
"key",
"+=",
"this",
".",
"delimiter",
"+",
"message",
".",
"kind",
",",
"message",
".",
"rule",
"&&",
"(",
"key",
"+=",
"this",
".",
"delimiter",
"+",
"message",
".",
"rule",
",",
"message",
".",
"values",
".",
"title",
"&&",
"(",
"key",
"+=",
"this",
".",
"delimiter",
"+",
"message",
".",
"values",
".",
"title",
")",
")",
")",
")",
";",
"}",
"return",
"(",
"key",
")",
"?",
"key",
":",
"\"\"",
";",
"}"
]
| Format a key for a message
@function format
@param {message} message The message to format
@memberof Augmented.Utility.MessageKeyFormatter
@returns The key to lookup in a bundle | [
"Format",
"a",
"key",
"for",
"a",
"message"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L3553-L3563 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function() {
var myValidator;
if (myValidator === undefined) {
myValidator = new Validator();
}
/**
* Returns if the framework supports validation
* @method supportsValidation
* @returns {boolean} Returns true if the framework supports validation
* @memberof Augmented.ValidationFramework
*/
this.supportsValidation = function() {
return (myValidator !== null);
};
/**
* Registers a schema to the Framework
* @method registerSchema
* @param {string} identity The identity of the schema
* @param {object} schema The JSON schema
* @memberof Augmented.ValidationFramework
*/
this.registerSchema = function(identity, schema) {
myValidator.addSchema(identity, schema);
};
/**
* Gets a schema
* @method getSchema
* @param {string} identity The identity of the schema
* @returns {object} The JSON schema
* @memberof Augmented.ValidationFramework
*/
this.getSchema = function(identity) {
return myValidator.getSchema(identity);
};
/**
* Gets all schemas
* @method getSchemas
* @returns {array} all JSON schemas
* @memberof Augmented.ValidationFramework
*/
this.getSchemas = function() {
return myValidator.getSchemaMap();
};
/**
* Clears all schemas
* @method clearSchemas
* @memberof Augmented.ValidationFramework
*/
this.clearSchemas = function() {
myValidator.dropSchemas();
};
/**
* Validates data via a schema
* @method validate
* @param {object} data The data to validate
* @param {object} The JSON schema
* @returns {object} Returns the validation object
* @memberof Augmented.ValidationFramework
*/
this.validate = function(data, schema) {
return myValidator.validateMultiple(data, schema);
};
/**
* Validates data via a schema
* @method getValidationMessages
* @returns {array} Returns the validation messages
* @memberof Augmented.ValidationFramework
*/
this.getValidationMessages = function() {
return myValidator.error;
};
this.generateSchema = function(model) {
if (model && model instanceof Augmented.Model) {
return Augmented.Utility.SchemaGenerator(model.toJSON());
}
return Augmented.Utility.SchemaGenerator(model);
};
} | javascript | function() {
var myValidator;
if (myValidator === undefined) {
myValidator = new Validator();
}
/**
* Returns if the framework supports validation
* @method supportsValidation
* @returns {boolean} Returns true if the framework supports validation
* @memberof Augmented.ValidationFramework
*/
this.supportsValidation = function() {
return (myValidator !== null);
};
/**
* Registers a schema to the Framework
* @method registerSchema
* @param {string} identity The identity of the schema
* @param {object} schema The JSON schema
* @memberof Augmented.ValidationFramework
*/
this.registerSchema = function(identity, schema) {
myValidator.addSchema(identity, schema);
};
/**
* Gets a schema
* @method getSchema
* @param {string} identity The identity of the schema
* @returns {object} The JSON schema
* @memberof Augmented.ValidationFramework
*/
this.getSchema = function(identity) {
return myValidator.getSchema(identity);
};
/**
* Gets all schemas
* @method getSchemas
* @returns {array} all JSON schemas
* @memberof Augmented.ValidationFramework
*/
this.getSchemas = function() {
return myValidator.getSchemaMap();
};
/**
* Clears all schemas
* @method clearSchemas
* @memberof Augmented.ValidationFramework
*/
this.clearSchemas = function() {
myValidator.dropSchemas();
};
/**
* Validates data via a schema
* @method validate
* @param {object} data The data to validate
* @param {object} The JSON schema
* @returns {object} Returns the validation object
* @memberof Augmented.ValidationFramework
*/
this.validate = function(data, schema) {
return myValidator.validateMultiple(data, schema);
};
/**
* Validates data via a schema
* @method getValidationMessages
* @returns {array} Returns the validation messages
* @memberof Augmented.ValidationFramework
*/
this.getValidationMessages = function() {
return myValidator.error;
};
this.generateSchema = function(model) {
if (model && model instanceof Augmented.Model) {
return Augmented.Utility.SchemaGenerator(model.toJSON());
}
return Augmented.Utility.SchemaGenerator(model);
};
} | [
"function",
"(",
")",
"{",
"var",
"myValidator",
";",
"if",
"(",
"myValidator",
"===",
"undefined",
")",
"{",
"myValidator",
"=",
"new",
"Validator",
"(",
")",
";",
"}",
"this",
".",
"supportsValidation",
"=",
"function",
"(",
")",
"{",
"return",
"(",
"myValidator",
"!==",
"null",
")",
";",
"}",
";",
"this",
".",
"registerSchema",
"=",
"function",
"(",
"identity",
",",
"schema",
")",
"{",
"myValidator",
".",
"addSchema",
"(",
"identity",
",",
"schema",
")",
";",
"}",
";",
"this",
".",
"getSchema",
"=",
"function",
"(",
"identity",
")",
"{",
"return",
"myValidator",
".",
"getSchema",
"(",
"identity",
")",
";",
"}",
";",
"this",
".",
"getSchemas",
"=",
"function",
"(",
")",
"{",
"return",
"myValidator",
".",
"getSchemaMap",
"(",
")",
";",
"}",
";",
"this",
".",
"clearSchemas",
"=",
"function",
"(",
")",
"{",
"myValidator",
".",
"dropSchemas",
"(",
")",
";",
"}",
";",
"this",
".",
"validate",
"=",
"function",
"(",
"data",
",",
"schema",
")",
"{",
"return",
"myValidator",
".",
"validateMultiple",
"(",
"data",
",",
"schema",
")",
";",
"}",
";",
"this",
".",
"getValidationMessages",
"=",
"function",
"(",
")",
"{",
"return",
"myValidator",
".",
"error",
";",
"}",
";",
"this",
".",
"generateSchema",
"=",
"function",
"(",
"model",
")",
"{",
"if",
"(",
"model",
"&&",
"model",
"instanceof",
"Augmented",
".",
"Model",
")",
"{",
"return",
"Augmented",
".",
"Utility",
".",
"SchemaGenerator",
"(",
"model",
".",
"toJSON",
"(",
")",
")",
";",
"}",
"return",
"Augmented",
".",
"Utility",
".",
"SchemaGenerator",
"(",
"model",
")",
";",
"}",
";",
"}"
]
| Augmented.ValidationFramework -
The Validation Framework Base Wrapper Class.
Provides abstraction for base validation build-in library
@constructor Augmented.ValidationFramework
@memberof Augmented | [
"Augmented",
".",
"ValidationFramework",
"-",
"The",
"Validation",
"Framework",
"Base",
"Wrapper",
"Class",
".",
"Provides",
"abstraction",
"for",
"base",
"validation",
"build",
"-",
"in",
"library"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L3611-L3690 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function() {
if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) {
// validate from Validator
this.validationMessages = Augmented.ValidationFramework.validate(this.toJSON(), this.schema);
} else {
this.validationMessages.valid = true;
}
return this.validationMessages;
} | javascript | function() {
if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) {
// validate from Validator
this.validationMessages = Augmented.ValidationFramework.validate(this.toJSON(), this.schema);
} else {
this.validationMessages.valid = true;
}
return this.validationMessages;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"supportsValidation",
"(",
")",
"&&",
"Augmented",
".",
"ValidationFramework",
".",
"supportsValidation",
"(",
")",
")",
"{",
"this",
".",
"validationMessages",
"=",
"Augmented",
".",
"ValidationFramework",
".",
"validate",
"(",
"this",
".",
"toJSON",
"(",
")",
",",
"this",
".",
"schema",
")",
";",
"}",
"else",
"{",
"this",
".",
"validationMessages",
".",
"valid",
"=",
"true",
";",
"}",
"return",
"this",
".",
"validationMessages",
";",
"}"
]
| Validates the model
@method validate
@memberof Augmented.Model
@returns {array} Returns array of messages from validation | [
"Validates",
"the",
"model"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L3757-L3765 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function() {
const messages = [];
if (this.validationMessages && this.validationMessages.errors) {
const l = this.validationMessages.errors.length;
var i = 0;
for (i = 0; i < l; i++) {
messages.push(this.validationMessages.errors[i].message + " from " + this.validationMessages.errors[i].dataPath);
}
}
return messages;
} | javascript | function() {
const messages = [];
if (this.validationMessages && this.validationMessages.errors) {
const l = this.validationMessages.errors.length;
var i = 0;
for (i = 0; i < l; i++) {
messages.push(this.validationMessages.errors[i].message + " from " + this.validationMessages.errors[i].dataPath);
}
}
return messages;
} | [
"function",
"(",
")",
"{",
"const",
"messages",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"validationMessages",
"&&",
"this",
".",
"validationMessages",
".",
"errors",
")",
"{",
"const",
"l",
"=",
"this",
".",
"validationMessages",
".",
"errors",
".",
"length",
";",
"var",
"i",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"messages",
".",
"push",
"(",
"this",
".",
"validationMessages",
".",
"errors",
"[",
"i",
"]",
".",
"message",
"+",
"\" from \"",
"+",
"this",
".",
"validationMessages",
".",
"errors",
"[",
"i",
"]",
".",
"dataPath",
")",
";",
"}",
"}",
"return",
"messages",
";",
"}"
]
| Gets the validation messages only in an array
@method getValidationMessages
@memberof Augmented.Model
@returns {array} Returns array of messages from validation | [
"Gets",
"the",
"validation",
"messages",
"only",
"in",
"an",
"array"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L3772-L3782 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(method, model, options) {
if (!options) {
options = {};
}
if (this.crossOrigin === true) {
options.crossDomain = true;
}
if (!options.xhrFields) {
options.xhrFields = {
withCredentials: true
};
}
if (this.mock) {
options.mock = this.mock;
}
return Augmented.sync(method, model, options);
} | javascript | function(method, model, options) {
if (!options) {
options = {};
}
if (this.crossOrigin === true) {
options.crossDomain = true;
}
if (!options.xhrFields) {
options.xhrFields = {
withCredentials: true
};
}
if (this.mock) {
options.mock = this.mock;
}
return Augmented.sync(method, model, options);
} | [
"function",
"(",
"method",
",",
"model",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"this",
".",
"crossOrigin",
"===",
"true",
")",
"{",
"options",
".",
"crossDomain",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"options",
".",
"xhrFields",
")",
"{",
"options",
".",
"xhrFields",
"=",
"{",
"withCredentials",
":",
"true",
"}",
";",
"}",
"if",
"(",
"this",
".",
"mock",
")",
"{",
"options",
".",
"mock",
"=",
"this",
".",
"mock",
";",
"}",
"return",
"Augmented",
".",
"sync",
"(",
"method",
",",
"model",
",",
"options",
")",
";",
"}"
]
| Model.sync - Sync model data to bound REST call
@method sync
@memberof Augmented.Model | [
"Model",
".",
"sync",
"-",
"Sync",
"model",
"data",
"to",
"bound",
"REST",
"call"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L3794-L3812 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function() {
if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) {
// validate from Validator
var messages = [];
this.validationMessages.messages = messages;
this.validationMessages.valid = true;
var a = this.toJSON(), i = 0, l = a.length;
//logger.debug("AUGMENTED: Collection Validate: Beginning with " + l + " models.");
for (i = 0; i < l; i++) {
messages[i] = Augmented.ValidationFramework.validate(a[i], this.schema);
if (!messages[i].valid) {
this.validationMessages.valid = false;
}
}
//logger.debug("AUGMENTED: Collection Validate: Completed isValid " + this.validationMessages.valid);
} else {
this.validationMessages.valid = true;
}
return this.validationMessages;
} | javascript | function() {
if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) {
// validate from Validator
var messages = [];
this.validationMessages.messages = messages;
this.validationMessages.valid = true;
var a = this.toJSON(), i = 0, l = a.length;
//logger.debug("AUGMENTED: Collection Validate: Beginning with " + l + " models.");
for (i = 0; i < l; i++) {
messages[i] = Augmented.ValidationFramework.validate(a[i], this.schema);
if (!messages[i].valid) {
this.validationMessages.valid = false;
}
}
//logger.debug("AUGMENTED: Collection Validate: Completed isValid " + this.validationMessages.valid);
} else {
this.validationMessages.valid = true;
}
return this.validationMessages;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"supportsValidation",
"(",
")",
"&&",
"Augmented",
".",
"ValidationFramework",
".",
"supportsValidation",
"(",
")",
")",
"{",
"var",
"messages",
"=",
"[",
"]",
";",
"this",
".",
"validationMessages",
".",
"messages",
"=",
"messages",
";",
"this",
".",
"validationMessages",
".",
"valid",
"=",
"true",
";",
"var",
"a",
"=",
"this",
".",
"toJSON",
"(",
")",
",",
"i",
"=",
"0",
",",
"l",
"=",
"a",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"messages",
"[",
"i",
"]",
"=",
"Augmented",
".",
"ValidationFramework",
".",
"validate",
"(",
"a",
"[",
"i",
"]",
",",
"this",
".",
"schema",
")",
";",
"if",
"(",
"!",
"messages",
"[",
"i",
"]",
".",
"valid",
")",
"{",
"this",
".",
"validationMessages",
".",
"valid",
"=",
"false",
";",
"}",
"}",
"}",
"else",
"{",
"this",
".",
"validationMessages",
".",
"valid",
"=",
"true",
";",
"}",
"return",
"this",
".",
"validationMessages",
";",
"}"
]
| Validates the collection
@method validate
@memberof Augmented.Collection
@returns {array} Returns array of message from validation | [
"Validates",
"the",
"collection"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L3946-L3967 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(key) {
if (key) {
var data = this.toJSON();
if (data) {
var sorted = Augmented.Utility.Sort(data, key);
this.reset(sorted);
}
}
} | javascript | function(key) {
if (key) {
var data = this.toJSON();
if (data) {
var sorted = Augmented.Utility.Sort(data, key);
this.reset(sorted);
}
}
} | [
"function",
"(",
"key",
")",
"{",
"if",
"(",
"key",
")",
"{",
"var",
"data",
"=",
"this",
".",
"toJSON",
"(",
")",
";",
"if",
"(",
"data",
")",
"{",
"var",
"sorted",
"=",
"Augmented",
".",
"Utility",
".",
"Sort",
"(",
"data",
",",
"key",
")",
";",
"this",
".",
"reset",
"(",
"sorted",
")",
";",
"}",
"}",
"}"
]
| sortByKey - Sorts the collection by a property key
@method sortByKey
@param {object} key The key to sort by
@memberof Augmented.Collection | [
"sortByKey",
"-",
"Sorts",
"the",
"collection",
"by",
"a",
"property",
"key"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4029-L4037 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(options) {
options = (options) ? options : {};
var data = (options.data || {});
var p = this.paginationConfiguration;
var d = {};
d[p.currentPageParam] = this.currentPage;
d[p.pageSizeParam] = this.pageSize;
options.data = d;
var xhr = Augmented.Collection.prototype.fetch.call(this, options);
// TODO: parse header links to sync up vars
return xhr;
} | javascript | function(options) {
options = (options) ? options : {};
var data = (options.data || {});
var p = this.paginationConfiguration;
var d = {};
d[p.currentPageParam] = this.currentPage;
d[p.pageSizeParam] = this.pageSize;
options.data = d;
var xhr = Augmented.Collection.prototype.fetch.call(this, options);
// TODO: parse header links to sync up vars
return xhr;
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"(",
"options",
")",
"?",
"options",
":",
"{",
"}",
";",
"var",
"data",
"=",
"(",
"options",
".",
"data",
"||",
"{",
"}",
")",
";",
"var",
"p",
"=",
"this",
".",
"paginationConfiguration",
";",
"var",
"d",
"=",
"{",
"}",
";",
"d",
"[",
"p",
".",
"currentPageParam",
"]",
"=",
"this",
".",
"currentPage",
";",
"d",
"[",
"p",
".",
"pageSizeParam",
"]",
"=",
"this",
".",
"pageSize",
";",
"options",
".",
"data",
"=",
"d",
";",
"var",
"xhr",
"=",
"Augmented",
".",
"Collection",
".",
"prototype",
".",
"fetch",
".",
"call",
"(",
"this",
",",
"options",
")",
";",
"return",
"xhr",
";",
"}"
]
| Collection.fetch - rewritten fetch method from Backbone.Collection.fetch
@method fetch
@memberof Augmented.PaginatedCollection
@borrows Collection.fetch | [
"Collection",
".",
"fetch",
"-",
"rewritten",
"fetch",
"method",
"from",
"Backbone",
".",
"Collection",
".",
"fetch"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4147-L4162 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(apiType, data) {
var arg = (data) ? data : {};
var collection = null;
if (!apiType) {
apiType = paginationAPIType.github;
}
if (apiType === paginationAPIType.github) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "page",
pageSizeParam: "per_page"
});
} else if (apiType === paginationAPIType.solr) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "start",
pageSizeParam: "rows"
});
} else if (apiType === paginationAPIType.database) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "offset",
pageSizeParam: "limit"
});
}
return collection;
} | javascript | function(apiType, data) {
var arg = (data) ? data : {};
var collection = null;
if (!apiType) {
apiType = paginationAPIType.github;
}
if (apiType === paginationAPIType.github) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "page",
pageSizeParam: "per_page"
});
} else if (apiType === paginationAPIType.solr) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "start",
pageSizeParam: "rows"
});
} else if (apiType === paginationAPIType.database) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "offset",
pageSizeParam: "limit"
});
}
return collection;
} | [
"function",
"(",
"apiType",
",",
"data",
")",
"{",
"var",
"arg",
"=",
"(",
"data",
")",
"?",
"data",
":",
"{",
"}",
";",
"var",
"collection",
"=",
"null",
";",
"if",
"(",
"!",
"apiType",
")",
"{",
"apiType",
"=",
"paginationAPIType",
".",
"github",
";",
"}",
"if",
"(",
"apiType",
"===",
"paginationAPIType",
".",
"github",
")",
"{",
"collection",
"=",
"new",
"paginatedCollection",
"(",
"arg",
")",
";",
"collection",
".",
"setPaginationConfiguration",
"(",
"{",
"currentPageParam",
":",
"\"page\"",
",",
"pageSizeParam",
":",
"\"per_page\"",
"}",
")",
";",
"}",
"else",
"if",
"(",
"apiType",
"===",
"paginationAPIType",
".",
"solr",
")",
"{",
"collection",
"=",
"new",
"paginatedCollection",
"(",
"arg",
")",
";",
"collection",
".",
"setPaginationConfiguration",
"(",
"{",
"currentPageParam",
":",
"\"start\"",
",",
"pageSizeParam",
":",
"\"rows\"",
"}",
")",
";",
"}",
"else",
"if",
"(",
"apiType",
"===",
"paginationAPIType",
".",
"database",
")",
"{",
"collection",
"=",
"new",
"paginatedCollection",
"(",
"arg",
")",
";",
"collection",
".",
"setPaginationConfiguration",
"(",
"{",
"currentPageParam",
":",
"\"offset\"",
",",
"pageSizeParam",
":",
"\"limit\"",
"}",
")",
";",
"}",
"return",
"collection",
";",
"}"
]
| Get a pagination collection of type
@method getPaginatedCollection
@memberof Augmented.PaginationFactory
@param {Augmented.PaginationFactory.type} apiType The API type to return an instance of
@param {object} args Collection arguments | [
"Get",
"a",
"pagination",
"collection",
"of",
"type"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4254-L4281 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(permission, negative) {
if (!negative) {
negative = false;
}
if (permission !== null && !Array.isArray(permission)) {
var p = (negative) ? this.permissions.exclude : this.permissions.include;
p.push(permission);
}
} | javascript | function(permission, negative) {
if (!negative) {
negative = false;
}
if (permission !== null && !Array.isArray(permission)) {
var p = (negative) ? this.permissions.exclude : this.permissions.include;
p.push(permission);
}
} | [
"function",
"(",
"permission",
",",
"negative",
")",
"{",
"if",
"(",
"!",
"negative",
")",
"{",
"negative",
"=",
"false",
";",
"}",
"if",
"(",
"permission",
"!==",
"null",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"permission",
")",
")",
"{",
"var",
"p",
"=",
"(",
"negative",
")",
"?",
"this",
".",
"permissions",
".",
"exclude",
":",
"this",
".",
"permissions",
".",
"include",
";",
"p",
".",
"push",
"(",
"permission",
")",
";",
"}",
"}"
]
| Adds a permission to the view
@method addPermission
@param {string} permission The permission to add
@param {boolean} negative Flag to set a nagative permission (optional)
@memberof Augmented.View | [
"Adds",
"a",
"permission",
"to",
"the",
"view"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4388-L4396 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(permission, negative) {
if (!negative) {
negative = false;
}
if (permission !== null && !Array.isArray(permission)) {
var p = (negative) ? this.permissions.exclude : this.permissions.include;
p.splice((p.indexOf(permission)), 1);
}
} | javascript | function(permission, negative) {
if (!negative) {
negative = false;
}
if (permission !== null && !Array.isArray(permission)) {
var p = (negative) ? this.permissions.exclude : this.permissions.include;
p.splice((p.indexOf(permission)), 1);
}
} | [
"function",
"(",
"permission",
",",
"negative",
")",
"{",
"if",
"(",
"!",
"negative",
")",
"{",
"negative",
"=",
"false",
";",
"}",
"if",
"(",
"permission",
"!==",
"null",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"permission",
")",
")",
"{",
"var",
"p",
"=",
"(",
"negative",
")",
"?",
"this",
".",
"permissions",
".",
"exclude",
":",
"this",
".",
"permissions",
".",
"include",
";",
"p",
".",
"splice",
"(",
"(",
"p",
".",
"indexOf",
"(",
"permission",
")",
")",
",",
"1",
")",
";",
"}",
"}"
]
| Removes a permission to the view
@method removePermission
@param {string} permission The permission to remove
@param {boolean} negative Flag to set a nagative permission (optional)
@memberof Augmented.View | [
"Removes",
"a",
"permission",
"to",
"the",
"view"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4404-L4412 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(permissions, negative) {
if (!negative) {
negative = false;
}
if (permissions !== null && Array.isArray(permissions)) {
if (negative) {
this.permissions.exclude = permissions;
} else {
this.permissions.include = permissions;
}
}
} | javascript | function(permissions, negative) {
if (!negative) {
negative = false;
}
if (permissions !== null && Array.isArray(permissions)) {
if (negative) {
this.permissions.exclude = permissions;
} else {
this.permissions.include = permissions;
}
}
} | [
"function",
"(",
"permissions",
",",
"negative",
")",
"{",
"if",
"(",
"!",
"negative",
")",
"{",
"negative",
"=",
"false",
";",
"}",
"if",
"(",
"permissions",
"!==",
"null",
"&&",
"Array",
".",
"isArray",
"(",
"permissions",
")",
")",
"{",
"if",
"(",
"negative",
")",
"{",
"this",
".",
"permissions",
".",
"exclude",
"=",
"permissions",
";",
"}",
"else",
"{",
"this",
".",
"permissions",
".",
"include",
"=",
"permissions",
";",
"}",
"}",
"}"
]
| Sets the permissions to the view
@method setPermissions
@param {array} permissions The permissions to set
@param {boolean} negative Flag to set a nagative permission (optional)
@memberof Augmented.View | [
"Sets",
"the",
"permissions",
"to",
"the",
"view"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4420-L4431 | train |
|
Augmentedjs/augmented | scripts/core/augmented.js | function(match, negative) {
if (!negative) {
negative = false;
}
var p = (negative) ? this.permissions.exclude : this.permissions.include;
return (p.indexOf(match) !== -1);
} | javascript | function(match, negative) {
if (!negative) {
negative = false;
}
var p = (negative) ? this.permissions.exclude : this.permissions.include;
return (p.indexOf(match) !== -1);
} | [
"function",
"(",
"match",
",",
"negative",
")",
"{",
"if",
"(",
"!",
"negative",
")",
"{",
"negative",
"=",
"false",
";",
"}",
"var",
"p",
"=",
"(",
"negative",
")",
"?",
"this",
".",
"permissions",
".",
"exclude",
":",
"this",
".",
"permissions",
".",
"include",
";",
"return",
"(",
"p",
".",
"indexOf",
"(",
"match",
")",
"!==",
"-",
"1",
")",
";",
"}"
]
| Matches a permission in the view
@method matchesPermission
@param {string} match The permissions to match
@param {boolean} negative Flag to set a nagative permission (optional)
@returns {boolean} Returns true if the match exists
@memberof Augmented.View | [
"Matches",
"a",
"permission",
"in",
"the",
"view"
]
| 430567d411ab9e77953232bb600c08080ed33146 | https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/core/augmented.js#L4466-L4472 | train |
|
kaelzhang/node-mix2 | index.js | mix | function mix (r, s, or, cl) {
if (!s || !r) {
return r;
}
var i = 0,
c, len;
or = or || arguments.length === 2;
if (cl && (len = cl.length)) {
for (; i < len; i++) {
c = cl[i];
if ((c in s) && (or || !(c in r))) {
r[c] = s[c];
}
}
} else {
for (c in s) {
if (or || !(c in r)) {
r[c] = s[c];
}
}
}
return r;
} | javascript | function mix (r, s, or, cl) {
if (!s || !r) {
return r;
}
var i = 0,
c, len;
or = or || arguments.length === 2;
if (cl && (len = cl.length)) {
for (; i < len; i++) {
c = cl[i];
if ((c in s) && (or || !(c in r))) {
r[c] = s[c];
}
}
} else {
for (c in s) {
if (or || !(c in r)) {
r[c] = s[c];
}
}
}
return r;
} | [
"function",
"mix",
"(",
"r",
",",
"s",
",",
"or",
",",
"cl",
")",
"{",
"if",
"(",
"!",
"s",
"||",
"!",
"r",
")",
"{",
"return",
"r",
";",
"}",
"var",
"i",
"=",
"0",
",",
"c",
",",
"len",
";",
"or",
"=",
"or",
"||",
"arguments",
".",
"length",
"===",
"2",
";",
"if",
"(",
"cl",
"&&",
"(",
"len",
"=",
"cl",
".",
"length",
")",
")",
"{",
"for",
"(",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"c",
"=",
"cl",
"[",
"i",
"]",
";",
"if",
"(",
"(",
"c",
"in",
"s",
")",
"&&",
"(",
"or",
"||",
"!",
"(",
"c",
"in",
"r",
")",
")",
")",
"{",
"r",
"[",
"c",
"]",
"=",
"s",
"[",
"c",
"]",
";",
"}",
"}",
"}",
"else",
"{",
"for",
"(",
"c",
"in",
"s",
")",
"{",
"if",
"(",
"or",
"||",
"!",
"(",
"c",
"in",
"r",
")",
")",
"{",
"r",
"[",
"c",
"]",
"=",
"s",
"[",
"c",
"]",
";",
"}",
"}",
"}",
"return",
"r",
";",
"}"
]
| copy all properties in the supplier to the receiver @param r {Object} receiver @param s {Object} supplier @param or {boolean=} whether override the existing property in the receiver @param cl {(Array.<string>)=} copy list, an array of selected properties | [
"copy",
"all",
"properties",
"in",
"the",
"supplier",
"to",
"the",
"receiver"
]
| 23490e0bb671664cbfa7aa6033e364560878bbe3 | https://github.com/kaelzhang/node-mix2/blob/23490e0bb671664cbfa7aa6033e364560878bbe3/index.js#L11-L36 | train |
jmchilton/pyre-to-regexp | index.js | pyre | function pyre(pattern, namedCaptures) {
pattern = String(pattern || '').trim();
// populate namedCaptures array and removed named captures from the `pattern`
namedCaptures = namedCaptures == undefined ? [] : namedCaptures;
var numGroups = 0;
pattern = replaceCaptureGroups(pattern, function (group) {
if (/^\(\?P[<]/.test(group)) {
// Python-style "named capture"
// It is possible to name a subpattern using the syntax (?P<name>pattern).
// This subpattern will then be indexed in the matches array by its normal
// numeric position and also by name.
var match = /^\(\?P[<]([^>]+)[>]([^\)]+)\)$/.exec(group);
if (namedCaptures) namedCaptures[numGroups] = match[1];
numGroups++;
return '(' + match[2] + ')';
} else if ('(?:' === group.substring(0, 3)) {
// non-capture group, leave untouched
return group;
} else {
// regular capture, leave untouched
numGroups++;
return group;
}
});
var regexp = new RegExp(pattern);
regexp.pyreReplace = function(source, replacement) {
var jsReplacement = pyreReplacement(replacement, namedCaptures);
return source.replace(this, jsReplacement);
}
return regexp;
} | javascript | function pyre(pattern, namedCaptures) {
pattern = String(pattern || '').trim();
// populate namedCaptures array and removed named captures from the `pattern`
namedCaptures = namedCaptures == undefined ? [] : namedCaptures;
var numGroups = 0;
pattern = replaceCaptureGroups(pattern, function (group) {
if (/^\(\?P[<]/.test(group)) {
// Python-style "named capture"
// It is possible to name a subpattern using the syntax (?P<name>pattern).
// This subpattern will then be indexed in the matches array by its normal
// numeric position and also by name.
var match = /^\(\?P[<]([^>]+)[>]([^\)]+)\)$/.exec(group);
if (namedCaptures) namedCaptures[numGroups] = match[1];
numGroups++;
return '(' + match[2] + ')';
} else if ('(?:' === group.substring(0, 3)) {
// non-capture group, leave untouched
return group;
} else {
// regular capture, leave untouched
numGroups++;
return group;
}
});
var regexp = new RegExp(pattern);
regexp.pyreReplace = function(source, replacement) {
var jsReplacement = pyreReplacement(replacement, namedCaptures);
return source.replace(this, jsReplacement);
}
return regexp;
} | [
"function",
"pyre",
"(",
"pattern",
",",
"namedCaptures",
")",
"{",
"pattern",
"=",
"String",
"(",
"pattern",
"||",
"''",
")",
".",
"trim",
"(",
")",
";",
"namedCaptures",
"=",
"namedCaptures",
"==",
"undefined",
"?",
"[",
"]",
":",
"namedCaptures",
";",
"var",
"numGroups",
"=",
"0",
";",
"pattern",
"=",
"replaceCaptureGroups",
"(",
"pattern",
",",
"function",
"(",
"group",
")",
"{",
"if",
"(",
"/",
"^\\(\\?P[<]",
"/",
".",
"test",
"(",
"group",
")",
")",
"{",
"var",
"match",
"=",
"/",
"^\\(\\?P[<]([^>]+)[>]([^\\)]+)\\)$",
"/",
".",
"exec",
"(",
"group",
")",
";",
"if",
"(",
"namedCaptures",
")",
"namedCaptures",
"[",
"numGroups",
"]",
"=",
"match",
"[",
"1",
"]",
";",
"numGroups",
"++",
";",
"return",
"'('",
"+",
"match",
"[",
"2",
"]",
"+",
"')'",
";",
"}",
"else",
"if",
"(",
"'(?:'",
"===",
"group",
".",
"substring",
"(",
"0",
",",
"3",
")",
")",
"{",
"return",
"group",
";",
"}",
"else",
"{",
"numGroups",
"++",
";",
"return",
"group",
";",
"}",
"}",
")",
";",
"var",
"regexp",
"=",
"new",
"RegExp",
"(",
"pattern",
")",
";",
"regexp",
".",
"pyreReplace",
"=",
"function",
"(",
"source",
",",
"replacement",
")",
"{",
"var",
"jsReplacement",
"=",
"pyreReplacement",
"(",
"replacement",
",",
"namedCaptures",
")",
";",
"return",
"source",
".",
"replace",
"(",
"this",
",",
"jsReplacement",
")",
";",
"}",
"return",
"regexp",
";",
"}"
]
| Returns a JavaScript RegExp instance from the given Python-like string.
An empty array may be passsed in as the second argument, which will be
populated with the "named capture group" names as Strings in the Array,
once the RegExp has been returned.
@param {String} pattern - Python-like regexp string to compile to a JS RegExp
@return {RegExp} returns a JavaScript RegExp instance from the given `pattern`
@public | [
"Returns",
"a",
"JavaScript",
"RegExp",
"instance",
"from",
"the",
"given",
"Python",
"-",
"like",
"string",
"."
]
| 1adc49fee33096c8d93dfcd26d13b3600c425ce0 | https://github.com/jmchilton/pyre-to-regexp/blob/1adc49fee33096c8d93dfcd26d13b3600c425ce0/index.js#L18-L50 | train |
kaelzhang/neuron-module-bundler | lib/unwrap.js | unwrapAst | function unwrapAst (ast, prefix, suffix) {
let fake_code = `${prefix}\nlet ${LONG_AND_WEIRED_STRING}\n${suffix}`
let fake_ast = babylon.parse(fake_code, {
sourceType: 'module'
})
let selected_node
let selected_index
traverse(fake_ast, {
enter: function (node, parent) {
// removes the loc info of fake ast
if (node.loc) {
node.loc = null
}
if (node.type !== 'BlockStatement') {
return
}
// find the index of LONG_AND_WEIRED_STRING
let index = node.body.findIndex(n => {
if (node.type !== 'VariableDeclaration') {
return
}
if (
access(n, [
'declarations', 0,
'id',
'name'
]) === LONG_AND_WEIRED_STRING
) {
return true
}
})
if (!~index) {
return
}
selected_node = node
selected_index = index
}
})
if (selected_node) {
selected_node.body.splice(selected_index, 1)
selected_node.body.push(...ast.program.body)
}
return fake_ast
} | javascript | function unwrapAst (ast, prefix, suffix) {
let fake_code = `${prefix}\nlet ${LONG_AND_WEIRED_STRING}\n${suffix}`
let fake_ast = babylon.parse(fake_code, {
sourceType: 'module'
})
let selected_node
let selected_index
traverse(fake_ast, {
enter: function (node, parent) {
// removes the loc info of fake ast
if (node.loc) {
node.loc = null
}
if (node.type !== 'BlockStatement') {
return
}
// find the index of LONG_AND_WEIRED_STRING
let index = node.body.findIndex(n => {
if (node.type !== 'VariableDeclaration') {
return
}
if (
access(n, [
'declarations', 0,
'id',
'name'
]) === LONG_AND_WEIRED_STRING
) {
return true
}
})
if (!~index) {
return
}
selected_node = node
selected_index = index
}
})
if (selected_node) {
selected_node.body.splice(selected_index, 1)
selected_node.body.push(...ast.program.body)
}
return fake_ast
} | [
"function",
"unwrapAst",
"(",
"ast",
",",
"prefix",
",",
"suffix",
")",
"{",
"let",
"fake_code",
"=",
"`",
"${",
"prefix",
"}",
"\\n",
"${",
"LONG_AND_WEIRED_STRING",
"}",
"\\n",
"${",
"suffix",
"}",
"`",
"let",
"fake_ast",
"=",
"babylon",
".",
"parse",
"(",
"fake_code",
",",
"{",
"sourceType",
":",
"'module'",
"}",
")",
"let",
"selected_node",
"let",
"selected_index",
"traverse",
"(",
"fake_ast",
",",
"{",
"enter",
":",
"function",
"(",
"node",
",",
"parent",
")",
"{",
"if",
"(",
"node",
".",
"loc",
")",
"{",
"node",
".",
"loc",
"=",
"null",
"}",
"if",
"(",
"node",
".",
"type",
"!==",
"'BlockStatement'",
")",
"{",
"return",
"}",
"let",
"index",
"=",
"node",
".",
"body",
".",
"findIndex",
"(",
"n",
"=>",
"{",
"if",
"(",
"node",
".",
"type",
"!==",
"'VariableDeclaration'",
")",
"{",
"return",
"}",
"if",
"(",
"access",
"(",
"n",
",",
"[",
"'declarations'",
",",
"0",
",",
"'id'",
",",
"'name'",
"]",
")",
"===",
"LONG_AND_WEIRED_STRING",
")",
"{",
"return",
"true",
"}",
"}",
")",
"if",
"(",
"!",
"~",
"index",
")",
"{",
"return",
"}",
"selected_node",
"=",
"node",
"selected_index",
"=",
"index",
"}",
"}",
")",
"if",
"(",
"selected_node",
")",
"{",
"selected_node",
".",
"body",
".",
"splice",
"(",
"selected_index",
",",
"1",
")",
"selected_node",
".",
"body",
".",
"push",
"(",
"...",
"ast",
".",
"program",
".",
"body",
")",
"}",
"return",
"fake_ast",
"}"
]
| Based on the situation that neuron wrappings are always functions with no statements within the bodies or statements at the beginning of function bodies | [
"Based",
"on",
"the",
"situation",
"that",
"neuron",
"wrappings",
"are",
"always",
"functions",
"with",
"no",
"statements",
"within",
"the",
"bodies",
"or",
"statements",
"at",
"the",
"beginning",
"of",
"function",
"bodies"
]
| ddf458a80c8e973d0312f800a83293345d073e11 | https://github.com/kaelzhang/neuron-module-bundler/blob/ddf458a80c8e973d0312f800a83293345d073e11/lib/unwrap.js#L54-L105 | train |
raincatcher-beta/raincatcher-sync | lib/client/mediator-subscribers/index.js | function(datasetId) {
if (syncSubscribers && datasetId && syncSubscribers[datasetId]) {
syncSubscribers[datasetId].unsubscribeAll();
delete syncSubscribers[datasetId];
}
} | javascript | function(datasetId) {
if (syncSubscribers && datasetId && syncSubscribers[datasetId]) {
syncSubscribers[datasetId].unsubscribeAll();
delete syncSubscribers[datasetId];
}
} | [
"function",
"(",
"datasetId",
")",
"{",
"if",
"(",
"syncSubscribers",
"&&",
"datasetId",
"&&",
"syncSubscribers",
"[",
"datasetId",
"]",
")",
"{",
"syncSubscribers",
"[",
"datasetId",
"]",
".",
"unsubscribeAll",
"(",
")",
";",
"delete",
"syncSubscribers",
"[",
"datasetId",
"]",
";",
"}",
"}"
]
| Removing any subscribers for a specific data set
@param {string} datasetId - The identifier for the data set. | [
"Removing",
"any",
"subscribers",
"for",
"a",
"specific",
"data",
"set"
]
| a51eeb8fdea30a6afdcd0587019bd1148bf30468 | https://github.com/raincatcher-beta/raincatcher-sync/blob/a51eeb8fdea30a6afdcd0587019bd1148bf30468/lib/client/mediator-subscribers/index.js#L64-L69 | train |
|
sendanor/nor-api-profile | src/validity.js | create_message | function create_message(req, data) {
debug.assert(data).is('object');
if(!is.uuid(data.$id)) {
data.$id = require('node-uuid').v4();
}
req.session.client.messages[data.$id] = data;
} | javascript | function create_message(req, data) {
debug.assert(data).is('object');
if(!is.uuid(data.$id)) {
data.$id = require('node-uuid').v4();
}
req.session.client.messages[data.$id] = data;
} | [
"function",
"create_message",
"(",
"req",
",",
"data",
")",
"{",
"debug",
".",
"assert",
"(",
"data",
")",
".",
"is",
"(",
"'object'",
")",
";",
"if",
"(",
"!",
"is",
".",
"uuid",
"(",
"data",
".",
"$id",
")",
")",
"{",
"data",
".",
"$id",
"=",
"require",
"(",
"'node-uuid'",
")",
".",
"v4",
"(",
")",
";",
"}",
"req",
".",
"session",
".",
"client",
".",
"messages",
"[",
"data",
".",
"$id",
"]",
"=",
"data",
";",
"}"
]
| Add a message
@fixme This code should be from session.js somehow | [
"Add",
"a",
"message"
]
| 5938f8b0c8e3c27062856f2d70e98d20fa78af8f | https://github.com/sendanor/nor-api-profile/blob/5938f8b0c8e3c27062856f2d70e98d20fa78af8f/src/validity.js#L200-L206 | train |
alexindigo/multibundle | bundler.js | hookStdout | function hookStdout(callback)
{
process.stdout._oWrite = process.stdout.write;
// take control
process.stdout.write = function(string, encoding, fd)
{
callback(string, encoding, fd);
};
// reverse it
return function()
{
process.stdout.write = process.stdout._oWrite;
};
} | javascript | function hookStdout(callback)
{
process.stdout._oWrite = process.stdout.write;
// take control
process.stdout.write = function(string, encoding, fd)
{
callback(string, encoding, fd);
};
// reverse it
return function()
{
process.stdout.write = process.stdout._oWrite;
};
} | [
"function",
"hookStdout",
"(",
"callback",
")",
"{",
"process",
".",
"stdout",
".",
"_oWrite",
"=",
"process",
".",
"stdout",
".",
"write",
";",
"process",
".",
"stdout",
".",
"write",
"=",
"function",
"(",
"string",
",",
"encoding",
",",
"fd",
")",
"{",
"callback",
"(",
"string",
",",
"encoding",
",",
"fd",
")",
";",
"}",
";",
"return",
"function",
"(",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"=",
"process",
".",
"stdout",
".",
"_oWrite",
";",
"}",
";",
"}"
]
| Hooks into stdout stream
to snitch on passed data
@param {function} callback - invoked on each passing chunk
@returns {function} - snitching-cancel function | [
"Hooks",
"into",
"stdout",
"stream",
"to",
"snitch",
"on",
"passed",
"data"
]
| 3eac4c590600cc71cd8dc18119187cc73c9175bb | https://github.com/alexindigo/multibundle/blob/3eac4c590600cc71cd8dc18119187cc73c9175bb/bundler.js#L46-L61 | train |
EyalAr/fume | lib/fume.js | Fume | function Fume(sources, config) {
config = config || {};
config.nameTagPrefix = config.nameTagPrefix || NAME_TAG_PREFIX;
config.preferTagPrefix = config.preferTagPrefix || PREFER_TAG_PREFIX;
config.amdTagPrefix = config.amdTagPrefix || AMD_TAG_PREFIX;
config.cjsTagPrefix = config.cjsTagPrefix || CJS_TAG_PREFIX;
this.config = config;
var nameTagRe = new RegExp(
"^.*?" +
this.config.nameTagPrefix +
"\\s*(\\w+)\\W*$"
),
preferTagRe = new RegExp(
"^.*?" +
this.config.preferTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
),
amdTagRe = new RegExp(
"^.*?" +
this.config.amdTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
),
cjsTagRe = new RegExp(
"^.*?" +
this.config.cjsTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
);
// parse the sources and get needed information
sources.forEach(function (source) {
source.dir = path.dirname(source.path);
source.tree = parse(source.code);
source.factory = source.tree.body[0];
source.amdMaps = {};
source.cjsMaps = {};
source.preferMaps = {};
if (source.factory.type !== 'FunctionDeclaration')
throw Error("Expected a factory function at '" +
source.path + "'");
source.args = source.factory.params;
// get comment lines before the factory function:
var m = source.code.match(cmtLinesRe);
// this RegExp should always match
if (!m) throw Error("Unable to parse pre-factory annotation");
var cLines = m[1].split(/[\n\r]/);
// extract annotation from the comment lines:
cLines.forEach(function (line) {
// attempt to detect the factory name:
// first try:
// the parse tree doesn't include comments, so we need to look
// at the source. a simple regex to detect the @name tag
// anywhere before the factory function:
var m = line.match(nameTagRe);
if (m) source.name = m[1];
// second try:
// if name tag isn't specified, take the function's name:
source.name = source.name || source.factory.id.name;
// check if this name is already taken by another factory:
if (sources.some(function (other) {
return other !== source &&
other.dir === source.dir &&
other.name === source.name;
}))
throw Error(
"Factory path '" +
path.join(source.dir, source.name) +
"' cannot be specified more than once"
);
// detect prefer mapping:
m = line.match(preferTagRe);
if (m) source.preferMaps[m[1]] = m[2];
// detect AMD mapping:
m = line.match(amdTagRe);
if (m) source.amdMaps[m[1]] = m[2];
// detect CJS mapping:
m = line.match(cjsTagRe);
if (m) source.cjsMaps[m[1]] = m[2];
});
});
// detect sibling dependencies
sources.forEach(function (source) {
source.factory.params.forEach(function (param) {
// find the siblings which can qualify as this dependency
param.candidatePaths = sources.filter(function (other) {
return other !== source && other.name === param.name;
}).map(function (other) {
return other.path;
});
});
});
return sources.reduce(function (p, e, i, o) {
p[e.path] = new Factory(e);
return p;
}, {});
} | javascript | function Fume(sources, config) {
config = config || {};
config.nameTagPrefix = config.nameTagPrefix || NAME_TAG_PREFIX;
config.preferTagPrefix = config.preferTagPrefix || PREFER_TAG_PREFIX;
config.amdTagPrefix = config.amdTagPrefix || AMD_TAG_PREFIX;
config.cjsTagPrefix = config.cjsTagPrefix || CJS_TAG_PREFIX;
this.config = config;
var nameTagRe = new RegExp(
"^.*?" +
this.config.nameTagPrefix +
"\\s*(\\w+)\\W*$"
),
preferTagRe = new RegExp(
"^.*?" +
this.config.preferTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
),
amdTagRe = new RegExp(
"^.*?" +
this.config.amdTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
),
cjsTagRe = new RegExp(
"^.*?" +
this.config.cjsTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
);
// parse the sources and get needed information
sources.forEach(function (source) {
source.dir = path.dirname(source.path);
source.tree = parse(source.code);
source.factory = source.tree.body[0];
source.amdMaps = {};
source.cjsMaps = {};
source.preferMaps = {};
if (source.factory.type !== 'FunctionDeclaration')
throw Error("Expected a factory function at '" +
source.path + "'");
source.args = source.factory.params;
// get comment lines before the factory function:
var m = source.code.match(cmtLinesRe);
// this RegExp should always match
if (!m) throw Error("Unable to parse pre-factory annotation");
var cLines = m[1].split(/[\n\r]/);
// extract annotation from the comment lines:
cLines.forEach(function (line) {
// attempt to detect the factory name:
// first try:
// the parse tree doesn't include comments, so we need to look
// at the source. a simple regex to detect the @name tag
// anywhere before the factory function:
var m = line.match(nameTagRe);
if (m) source.name = m[1];
// second try:
// if name tag isn't specified, take the function's name:
source.name = source.name || source.factory.id.name;
// check if this name is already taken by another factory:
if (sources.some(function (other) {
return other !== source &&
other.dir === source.dir &&
other.name === source.name;
}))
throw Error(
"Factory path '" +
path.join(source.dir, source.name) +
"' cannot be specified more than once"
);
// detect prefer mapping:
m = line.match(preferTagRe);
if (m) source.preferMaps[m[1]] = m[2];
// detect AMD mapping:
m = line.match(amdTagRe);
if (m) source.amdMaps[m[1]] = m[2];
// detect CJS mapping:
m = line.match(cjsTagRe);
if (m) source.cjsMaps[m[1]] = m[2];
});
});
// detect sibling dependencies
sources.forEach(function (source) {
source.factory.params.forEach(function (param) {
// find the siblings which can qualify as this dependency
param.candidatePaths = sources.filter(function (other) {
return other !== source && other.name === param.name;
}).map(function (other) {
return other.path;
});
});
});
return sources.reduce(function (p, e, i, o) {
p[e.path] = new Factory(e);
return p;
}, {});
} | [
"function",
"Fume",
"(",
"sources",
",",
"config",
")",
"{",
"config",
"=",
"config",
"||",
"{",
"}",
";",
"config",
".",
"nameTagPrefix",
"=",
"config",
".",
"nameTagPrefix",
"||",
"NAME_TAG_PREFIX",
";",
"config",
".",
"preferTagPrefix",
"=",
"config",
".",
"preferTagPrefix",
"||",
"PREFER_TAG_PREFIX",
";",
"config",
".",
"amdTagPrefix",
"=",
"config",
".",
"amdTagPrefix",
"||",
"AMD_TAG_PREFIX",
";",
"config",
".",
"cjsTagPrefix",
"=",
"config",
".",
"cjsTagPrefix",
"||",
"CJS_TAG_PREFIX",
";",
"this",
".",
"config",
"=",
"config",
";",
"var",
"nameTagRe",
"=",
"new",
"RegExp",
"(",
"\"^.*?\"",
"+",
"this",
".",
"config",
".",
"nameTagPrefix",
"+",
"\"\\\\s*(\\\\w+)\\\\W*$\"",
")",
",",
"\\\\",
",",
"\\\\",
",",
"\\\\",
";",
"preferTagRe",
"=",
"new",
"RegExp",
"(",
"\"^.*?\"",
"+",
"this",
".",
"config",
".",
"preferTagPrefix",
"+",
"\"\\\\s*(\\\\S+)\\\\s+(\\\\S+)\\\\W*$\"",
")",
"\\\\",
"\\\\",
"}"
]
| Parse the list of sources | [
"Parse",
"the",
"list",
"of",
"sources"
]
| 66f555d39b9cee18bbdf7a0a565919247163a227 | https://github.com/EyalAr/fume/blob/66f555d39b9cee18bbdf7a0a565919247163a227/lib/fume.js#L52-L169 | train |
EyalAr/fume | lib/fume.js | amdWrap | function amdWrap(factoryCode, deps) {
var deps = deps.map(function (dep) {
return "'" + dep + "'";
});
return AMD_TEMPLATE.START +
deps.join(',') +
AMD_TEMPLATE.MIDDLE +
factoryCode +
AMD_TEMPLATE.END;
} | javascript | function amdWrap(factoryCode, deps) {
var deps = deps.map(function (dep) {
return "'" + dep + "'";
});
return AMD_TEMPLATE.START +
deps.join(',') +
AMD_TEMPLATE.MIDDLE +
factoryCode +
AMD_TEMPLATE.END;
} | [
"function",
"amdWrap",
"(",
"factoryCode",
",",
"deps",
")",
"{",
"var",
"deps",
"=",
"deps",
".",
"map",
"(",
"function",
"(",
"dep",
")",
"{",
"return",
"\"'\"",
"+",
"dep",
"+",
"\"'\"",
";",
"}",
")",
";",
"return",
"AMD_TEMPLATE",
".",
"START",
"+",
"deps",
".",
"join",
"(",
"','",
")",
"+",
"AMD_TEMPLATE",
".",
"MIDDLE",
"+",
"factoryCode",
"+",
"AMD_TEMPLATE",
".",
"END",
";",
"}"
]
| Wrap a factory with an AMD loader. | [
"Wrap",
"a",
"factory",
"with",
"an",
"AMD",
"loader",
"."
]
| 66f555d39b9cee18bbdf7a0a565919247163a227 | https://github.com/EyalAr/fume/blob/66f555d39b9cee18bbdf7a0a565919247163a227/lib/fume.js#L276-L285 | train |
EyalAr/fume | lib/fume.js | cjsWrap | function cjsWrap(factoryCode, deps) {
var requires = deps.map(function (dep) {
return "require('" + dep + "')";
});
return CJS_TEMPLATE.START +
factoryCode +
CJS_TEMPLATE.MIDDLE +
requires.join(',') +
CJS_TEMPLATE.END;
} | javascript | function cjsWrap(factoryCode, deps) {
var requires = deps.map(function (dep) {
return "require('" + dep + "')";
});
return CJS_TEMPLATE.START +
factoryCode +
CJS_TEMPLATE.MIDDLE +
requires.join(',') +
CJS_TEMPLATE.END;
} | [
"function",
"cjsWrap",
"(",
"factoryCode",
",",
"deps",
")",
"{",
"var",
"requires",
"=",
"deps",
".",
"map",
"(",
"function",
"(",
"dep",
")",
"{",
"return",
"\"require('\"",
"+",
"dep",
"+",
"\"')\"",
";",
"}",
")",
";",
"return",
"CJS_TEMPLATE",
".",
"START",
"+",
"factoryCode",
"+",
"CJS_TEMPLATE",
".",
"MIDDLE",
"+",
"requires",
".",
"join",
"(",
"','",
")",
"+",
"CJS_TEMPLATE",
".",
"END",
";",
"}"
]
| Wrap a factory with a CJS loader. | [
"Wrap",
"a",
"factory",
"with",
"a",
"CJS",
"loader",
"."
]
| 66f555d39b9cee18bbdf7a0a565919247163a227 | https://github.com/EyalAr/fume/blob/66f555d39b9cee18bbdf7a0a565919247163a227/lib/fume.js#L290-L299 | train |
bmustiata/tsdlocal | tasks/tsdlocal.js | ensureFolderExists | function ensureFolderExists(file) {
var folderName = path.dirname(file);
if (fs.existsSync(folderName)) {
return;
}
try {
mkdirp.sync(folderName);
}
catch (e) {
console.log(colors.red("Unable to create parent folders for: " + file), e);
}
} | javascript | function ensureFolderExists(file) {
var folderName = path.dirname(file);
if (fs.existsSync(folderName)) {
return;
}
try {
mkdirp.sync(folderName);
}
catch (e) {
console.log(colors.red("Unable to create parent folders for: " + file), e);
}
} | [
"function",
"ensureFolderExists",
"(",
"file",
")",
"{",
"var",
"folderName",
"=",
"path",
".",
"dirname",
"(",
"file",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"folderName",
")",
")",
"{",
"return",
";",
"}",
"try",
"{",
"mkdirp",
".",
"sync",
"(",
"folderName",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"colors",
".",
"red",
"(",
"\"Unable to create parent folders for: \"",
"+",
"file",
")",
",",
"e",
")",
";",
"}",
"}"
]
| Ensures the parent folders for the given file name exists. | [
"Ensures",
"the",
"parent",
"folders",
"for",
"the",
"given",
"file",
"name",
"exists",
"."
]
| 584bc9974337e54eb30897f1a9b2417210e6b968 | https://github.com/bmustiata/tsdlocal/blob/584bc9974337e54eb30897f1a9b2417210e6b968/tasks/tsdlocal.js#L103-L114 | train |
camshaft/node-env-builder | index.js | mergeTypes | function mergeTypes(env, types, conf, ENV, fn) {
fetch(conf, 'types', function(err, layout) {
if (err) return fn(err);
debug('# TYPES');
var batch = new Batch();
batch.concurrency(1);
types.forEach(function(type) {
batch.push(function(cb) {
debug(type);
mergeConf(env, layout, type, ENV, cb);
});
});
batch.end(fn);
});
} | javascript | function mergeTypes(env, types, conf, ENV, fn) {
fetch(conf, 'types', function(err, layout) {
if (err) return fn(err);
debug('# TYPES');
var batch = new Batch();
batch.concurrency(1);
types.forEach(function(type) {
batch.push(function(cb) {
debug(type);
mergeConf(env, layout, type, ENV, cb);
});
});
batch.end(fn);
});
} | [
"function",
"mergeTypes",
"(",
"env",
",",
"types",
",",
"conf",
",",
"ENV",
",",
"fn",
")",
"{",
"fetch",
"(",
"conf",
",",
"'types'",
",",
"function",
"(",
"err",
",",
"layout",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"debug",
"(",
"'# TYPES'",
")",
";",
"var",
"batch",
"=",
"new",
"Batch",
"(",
")",
";",
"batch",
".",
"concurrency",
"(",
"1",
")",
";",
"types",
".",
"forEach",
"(",
"function",
"(",
"type",
")",
"{",
"batch",
".",
"push",
"(",
"function",
"(",
"cb",
")",
"{",
"debug",
"(",
"type",
")",
";",
"mergeConf",
"(",
"env",
",",
"layout",
",",
"type",
",",
"ENV",
",",
"cb",
")",
";",
"}",
")",
";",
"}",
")",
";",
"batch",
".",
"end",
"(",
"fn",
")",
";",
"}",
")",
";",
"}"
]
| Merge types into ENV
@param {String} env
@param {Array} types
@param {Object} conf
@param {Object} ENV
@param {Function} fn | [
"Merge",
"types",
"into",
"ENV"
]
| b9ae640bbfbccccaebcfa19ec65392da042a49e9 | https://github.com/camshaft/node-env-builder/blob/b9ae640bbfbccccaebcfa19ec65392da042a49e9/index.js#L54-L72 | train |
camshaft/node-env-builder | index.js | mergeApp | function mergeApp(env, app, conf, ENV, fn) {
fetch(conf, 'apps', function(err, apps) {
if (err) return fn(err);
debug('# APP');
debug(app);
mergeConf(env, apps, app, ENV, fn);
});
} | javascript | function mergeApp(env, app, conf, ENV, fn) {
fetch(conf, 'apps', function(err, apps) {
if (err) return fn(err);
debug('# APP');
debug(app);
mergeConf(env, apps, app, ENV, fn);
});
} | [
"function",
"mergeApp",
"(",
"env",
",",
"app",
",",
"conf",
",",
"ENV",
",",
"fn",
")",
"{",
"fetch",
"(",
"conf",
",",
"'apps'",
",",
"function",
"(",
"err",
",",
"apps",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"debug",
"(",
"'# APP'",
")",
";",
"debug",
"(",
"app",
")",
";",
"mergeConf",
"(",
"env",
",",
"apps",
",",
"app",
",",
"ENV",
",",
"fn",
")",
";",
"}",
")",
";",
"}"
]
| Merge app into ENV
@param {String} env
@param {String} app
@param {Object} conf
@param {Object} ENV
@param {Function} fn | [
"Merge",
"app",
"into",
"ENV"
]
| b9ae640bbfbccccaebcfa19ec65392da042a49e9 | https://github.com/camshaft/node-env-builder/blob/b9ae640bbfbccccaebcfa19ec65392da042a49e9/index.js#L84-L91 | train |
camshaft/node-env-builder | index.js | mergeConf | function mergeConf(env, conf, key, ENV, fn) {
fetch(conf, key, function(err, layout) {
if (err) return fn(err);
fetch(layout, 'default', function(err, defaults) {
if (err) return fn(err);
debug(' default', defaults);
merge(ENV, defaults);
debug(' ', ENV);
fetch(layout, env, function(err, envs) {
if (err) return fn(err);
debug(' ' + env, envs);
merge(ENV, envs);
debug(' ', ENV);
fn();
});
});
});
} | javascript | function mergeConf(env, conf, key, ENV, fn) {
fetch(conf, key, function(err, layout) {
if (err) return fn(err);
fetch(layout, 'default', function(err, defaults) {
if (err) return fn(err);
debug(' default', defaults);
merge(ENV, defaults);
debug(' ', ENV);
fetch(layout, env, function(err, envs) {
if (err) return fn(err);
debug(' ' + env, envs);
merge(ENV, envs);
debug(' ', ENV);
fn();
});
});
});
} | [
"function",
"mergeConf",
"(",
"env",
",",
"conf",
",",
"key",
",",
"ENV",
",",
"fn",
")",
"{",
"fetch",
"(",
"conf",
",",
"key",
",",
"function",
"(",
"err",
",",
"layout",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"fetch",
"(",
"layout",
",",
"'default'",
",",
"function",
"(",
"err",
",",
"defaults",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"debug",
"(",
"' default'",
",",
"defaults",
")",
";",
"merge",
"(",
"ENV",
",",
"defaults",
")",
";",
"debug",
"(",
"' '",
",",
"ENV",
")",
";",
"fetch",
"(",
"layout",
",",
"env",
",",
"function",
"(",
"err",
",",
"envs",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"debug",
"(",
"' '",
"+",
"env",
",",
"envs",
")",
";",
"merge",
"(",
"ENV",
",",
"envs",
")",
";",
"debug",
"(",
"' '",
",",
"ENV",
")",
";",
"fn",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Merge conf into ENV
@param {String} env
@param {Object} conf
@param {String} key
@param {Object} ENV
@param {Function} fn | [
"Merge",
"conf",
"into",
"ENV"
]
| b9ae640bbfbccccaebcfa19ec65392da042a49e9 | https://github.com/camshaft/node-env-builder/blob/b9ae640bbfbccccaebcfa19ec65392da042a49e9/index.js#L103-L125 | train |
camshaft/node-env-builder | index.js | fetch | function fetch(conf, key, fn) {
getKey(conf, key, function(err, layout) {
if (err) return fn(err);
get(layout, fn);
});
} | javascript | function fetch(conf, key, fn) {
getKey(conf, key, function(err, layout) {
if (err) return fn(err);
get(layout, fn);
});
} | [
"function",
"fetch",
"(",
"conf",
",",
"key",
",",
"fn",
")",
"{",
"getKey",
"(",
"conf",
",",
"key",
",",
"function",
"(",
"err",
",",
"layout",
")",
"{",
"if",
"(",
"err",
")",
"return",
"fn",
"(",
"err",
")",
";",
"get",
"(",
"layout",
",",
"fn",
")",
";",
"}",
")",
";",
"}"
]
| Fetch an object by key
@param {Object} conf
@param {String} key
@param {Function} fn | [
"Fetch",
"an",
"object",
"by",
"key"
]
| b9ae640bbfbccccaebcfa19ec65392da042a49e9 | https://github.com/camshaft/node-env-builder/blob/b9ae640bbfbccccaebcfa19ec65392da042a49e9/index.js#L135-L140 | train |
camshaft/node-env-builder | index.js | get | function get(obj, fn) {
if (typeof obj === 'object') return fn(null, obj);
if (typeof obj === 'undefined') return fn(null, {});
if (typeof obj !== 'function') return fn(new Error('cannot read conf:\n' + obj));
if (obj.length === 1) return obj(fn);
var val;
try {
val = obj();
} catch(err) {
return fn(err);
}
fn(null, val);
} | javascript | function get(obj, fn) {
if (typeof obj === 'object') return fn(null, obj);
if (typeof obj === 'undefined') return fn(null, {});
if (typeof obj !== 'function') return fn(new Error('cannot read conf:\n' + obj));
if (obj.length === 1) return obj(fn);
var val;
try {
val = obj();
} catch(err) {
return fn(err);
}
fn(null, val);
} | [
"function",
"get",
"(",
"obj",
",",
"fn",
")",
"{",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
")",
"return",
"fn",
"(",
"null",
",",
"obj",
")",
";",
"if",
"(",
"typeof",
"obj",
"===",
"'undefined'",
")",
"return",
"fn",
"(",
"null",
",",
"{",
"}",
")",
";",
"if",
"(",
"typeof",
"obj",
"!==",
"'function'",
")",
"return",
"fn",
"(",
"new",
"Error",
"(",
"'cannot read conf:\\n'",
"+",
"\\n",
")",
")",
";",
"obj",
"if",
"(",
"obj",
".",
"length",
"===",
"1",
")",
"return",
"obj",
"(",
"fn",
")",
";",
"var",
"val",
";",
"try",
"{",
"val",
"=",
"obj",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"fn",
"(",
"err",
")",
";",
"}",
"}"
]
| Lazily evaluate the value
@param {Any} obj
@param {Function} fn | [
"Lazily",
"evaluate",
"the",
"value"
]
| b9ae640bbfbccccaebcfa19ec65392da042a49e9 | https://github.com/camshaft/node-env-builder/blob/b9ae640bbfbccccaebcfa19ec65392da042a49e9/index.js#L171-L183 | train |
puranjayjain/gulp-replace-frommap | index.js | getIndexOf | function getIndexOf(string, find) {
// if regex then do it regex way
if(XRegExp.isRegExp(find)) {
return string.search(find);
} else {
// normal way
return string.indexOf(find);
}
} | javascript | function getIndexOf(string, find) {
// if regex then do it regex way
if(XRegExp.isRegExp(find)) {
return string.search(find);
} else {
// normal way
return string.indexOf(find);
}
} | [
"function",
"getIndexOf",
"(",
"string",
",",
"find",
")",
"{",
"if",
"(",
"XRegExp",
".",
"isRegExp",
"(",
"find",
")",
")",
"{",
"return",
"string",
".",
"search",
"(",
"find",
")",
";",
"}",
"else",
"{",
"return",
"string",
".",
"indexOf",
"(",
"find",
")",
";",
"}",
"}"
]
| get index of using regex or normal way -1 other wise | [
"get",
"index",
"of",
"using",
"regex",
"or",
"normal",
"way",
"-",
"1",
"other",
"wise"
]
| def6b6345ebf5341e46ddfe05d7d09974180c718 | https://github.com/puranjayjain/gulp-replace-frommap/blob/def6b6345ebf5341e46ddfe05d7d09974180c718/index.js#L112-L120 | train |
puranjayjain/gulp-replace-frommap | index.js | getStringWithLength | function getStringWithLength(string, find) {
let obj;
// if regex then do it regex way
if(XRegExp.isRegExp(find)) {
obj = {
textValue: XRegExp.replace(string, find, '$1', 'one'),
textLength: XRegExp.match(string, /class/g, 'one')
.length
};
return;
} else {
obj = {
textValue: find,
textLength: find.length
};
}
return obj;
} | javascript | function getStringWithLength(string, find) {
let obj;
// if regex then do it regex way
if(XRegExp.isRegExp(find)) {
obj = {
textValue: XRegExp.replace(string, find, '$1', 'one'),
textLength: XRegExp.match(string, /class/g, 'one')
.length
};
return;
} else {
obj = {
textValue: find,
textLength: find.length
};
}
return obj;
} | [
"function",
"getStringWithLength",
"(",
"string",
",",
"find",
")",
"{",
"let",
"obj",
";",
"if",
"(",
"XRegExp",
".",
"isRegExp",
"(",
"find",
")",
")",
"{",
"obj",
"=",
"{",
"textValue",
":",
"XRegExp",
".",
"replace",
"(",
"string",
",",
"find",
",",
"'$1'",
",",
"'one'",
")",
",",
"textLength",
":",
"XRegExp",
".",
"match",
"(",
"string",
",",
"/",
"class",
"/",
"g",
",",
"'one'",
")",
".",
"length",
"}",
";",
"return",
";",
"}",
"else",
"{",
"obj",
"=",
"{",
"textValue",
":",
"find",
",",
"textLength",
":",
"find",
".",
"length",
"}",
";",
"}",
"return",
"obj",
";",
"}"
]
| get the full matched regex string or the string itself along with it's length | [
"get",
"the",
"full",
"matched",
"regex",
"string",
"or",
"the",
"string",
"itself",
"along",
"with",
"it",
"s",
"length"
]
| def6b6345ebf5341e46ddfe05d7d09974180c718 | https://github.com/puranjayjain/gulp-replace-frommap/blob/def6b6345ebf5341e46ddfe05d7d09974180c718/index.js#L123-L140 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.