id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
55,300 | hoyce/passport-cas-kth | index.js | stripGatewayAuthenticationParameter | function stripGatewayAuthenticationParameter(aUrl) {
if (aUrl.query && aUrl.query.useGateway) {
delete aUrl.query.useGateway;
}
if (aUrl.query.nextUrl) {
var theNextUrl = decodeURIComponent(aUrl.query.nextUrl);
aUrl.query.nextUrl = decodeURIComponent(theNextUrl);
}
var theUrl = url.format(aUrl);
return theUrl;
} | javascript | function stripGatewayAuthenticationParameter(aUrl) {
if (aUrl.query && aUrl.query.useGateway) {
delete aUrl.query.useGateway;
}
if (aUrl.query.nextUrl) {
var theNextUrl = decodeURIComponent(aUrl.query.nextUrl);
aUrl.query.nextUrl = decodeURIComponent(theNextUrl);
}
var theUrl = url.format(aUrl);
return theUrl;
} | [
"function",
"stripGatewayAuthenticationParameter",
"(",
"aUrl",
")",
"{",
"if",
"(",
"aUrl",
".",
"query",
"&&",
"aUrl",
".",
"query",
".",
"useGateway",
")",
"{",
"delete",
"aUrl",
".",
"query",
".",
"useGateway",
";",
"}",
"if",
"(",
"aUrl",
".",
"query",
".",
"nextUrl",
")",
"{",
"var",
"theNextUrl",
"=",
"decodeURIComponent",
"(",
"aUrl",
".",
"query",
".",
"nextUrl",
")",
";",
"aUrl",
".",
"query",
".",
"nextUrl",
"=",
"decodeURIComponent",
"(",
"theNextUrl",
")",
";",
"}",
"var",
"theUrl",
"=",
"url",
".",
"format",
"(",
"aUrl",
")",
";",
"return",
"theUrl",
";",
"}"
] | If a gateway query parameter is added, remove it. | [
"If",
"a",
"gateway",
"query",
"parameter",
"is",
"added",
"remove",
"it",
"."
] | 56bcc5324c0332008cfde37023ed05a22bdf1eb3 | https://github.com/hoyce/passport-cas-kth/blob/56bcc5324c0332008cfde37023ed05a22bdf1eb3/index.js#L167-L178 |
55,301 | lucidogen/lucy-live | index.js | function ( h )
{ getData ( h, true )
.then
( function ( data )
{ if ( h.readValue == data )
{ // same. ignore
}
else
{ // console.log ( `onChangedPath ( "${h.path}" ) ` )
h.evalValue = null
h.readValue = data
// reload
let callbacks = h.callbacks
for ( let i = callbacks.length-1; i >= 0; --i )
{ let clbk = callbacks [ i ]
clbk.handler ( h, clbk.callback )
}
}
}
)
} | javascript | function ( h )
{ getData ( h, true )
.then
( function ( data )
{ if ( h.readValue == data )
{ // same. ignore
}
else
{ // console.log ( `onChangedPath ( "${h.path}" ) ` )
h.evalValue = null
h.readValue = data
// reload
let callbacks = h.callbacks
for ( let i = callbacks.length-1; i >= 0; --i )
{ let clbk = callbacks [ i ]
clbk.handler ( h, clbk.callback )
}
}
}
)
} | [
"function",
"(",
"h",
")",
"{",
"getData",
"(",
"h",
",",
"true",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"h",
".",
"readValue",
"==",
"data",
")",
"{",
"// same. ignore",
"}",
"else",
"{",
"// console.log ( `onChangedPath ( \"${h.path}\" ) ` )",
"h",
".",
"evalValue",
"=",
"null",
"h",
".",
"readValue",
"=",
"data",
"// reload",
"let",
"callbacks",
"=",
"h",
".",
"callbacks",
"for",
"(",
"let",
"i",
"=",
"callbacks",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"let",
"clbk",
"=",
"callbacks",
"[",
"i",
"]",
"clbk",
".",
"handler",
"(",
"h",
",",
"clbk",
".",
"callback",
")",
"}",
"}",
"}",
")",
"}"
] | If we change 'onChangedPath' to not read file content to detect file changes, we need to change the HANDLERS to use getData and adapt cache code accordingly. | [
"If",
"we",
"change",
"onChangedPath",
"to",
"not",
"read",
"file",
"content",
"to",
"detect",
"file",
"changes",
"we",
"need",
"to",
"change",
"the",
"HANDLERS",
"to",
"use",
"getData",
"and",
"adapt",
"cache",
"code",
"accordingly",
"."
] | 86924af74b23190e5753f5e1447719bb1def8151 | https://github.com/lucidogen/lucy-live/blob/86924af74b23190e5753f5e1447719bb1def8151/index.js#L89-L109 |
|
55,302 | lucidogen/lucy-live | index.js | function ( path, base )
{ let filename
let start = path.substr ( 0, 2 )
if ( path.charAt ( 0 ) === '/' )
{ // absolute path
filename = path
}
else if ( start == './' || start == '..' || path == '.' )
{ filename = lpath.resolve ( base, path )
}
else
{ // funky node_modules path not supported
throw new Error
( `Cannot watch path '${ path }' ( not a relative or absolute path ) ` )
}
return filename
} | javascript | function ( path, base )
{ let filename
let start = path.substr ( 0, 2 )
if ( path.charAt ( 0 ) === '/' )
{ // absolute path
filename = path
}
else if ( start == './' || start == '..' || path == '.' )
{ filename = lpath.resolve ( base, path )
}
else
{ // funky node_modules path not supported
throw new Error
( `Cannot watch path '${ path }' ( not a relative or absolute path ) ` )
}
return filename
} | [
"function",
"(",
"path",
",",
"base",
")",
"{",
"let",
"filename",
"let",
"start",
"=",
"path",
".",
"substr",
"(",
"0",
",",
"2",
")",
"if",
"(",
"path",
".",
"charAt",
"(",
"0",
")",
"===",
"'/'",
")",
"{",
"// absolute path",
"filename",
"=",
"path",
"}",
"else",
"if",
"(",
"start",
"==",
"'./'",
"||",
"start",
"==",
"'..'",
"||",
"path",
"==",
"'.'",
")",
"{",
"filename",
"=",
"lpath",
".",
"resolve",
"(",
"base",
",",
"path",
")",
"}",
"else",
"{",
"// funky node_modules path not supported",
"throw",
"new",
"Error",
"(",
"`",
"${",
"path",
"}",
"`",
")",
"}",
"return",
"filename",
"}"
] | Used by watch. Not full resolution. | [
"Used",
"by",
"watch",
".",
"Not",
"full",
"resolution",
"."
] | 86924af74b23190e5753f5e1447719bb1def8151 | https://github.com/lucidogen/lucy-live/blob/86924af74b23190e5753f5e1447719bb1def8151/index.js#L423-L439 |
|
55,303 | lucidogen/lucy-live | index.js | function ( path, base )
{ let start = path.substr ( 0, 2 )
let paths
if ( start != './' && start != '..' )
{ // absolute or funky node_modules require
paths = module.paths
}
else
{ paths = [ base ]
}
let filename = findPath ( path, paths )
if ( !filename )
{ throw new Error ( `Cannot find path '${ path }'` )
}
return filename
} | javascript | function ( path, base )
{ let start = path.substr ( 0, 2 )
let paths
if ( start != './' && start != '..' )
{ // absolute or funky node_modules require
paths = module.paths
}
else
{ paths = [ base ]
}
let filename = findPath ( path, paths )
if ( !filename )
{ throw new Error ( `Cannot find path '${ path }'` )
}
return filename
} | [
"function",
"(",
"path",
",",
"base",
")",
"{",
"let",
"start",
"=",
"path",
".",
"substr",
"(",
"0",
",",
"2",
")",
"let",
"paths",
"if",
"(",
"start",
"!=",
"'./'",
"&&",
"start",
"!=",
"'..'",
")",
"{",
"// absolute or funky node_modules require",
"paths",
"=",
"module",
".",
"paths",
"}",
"else",
"{",
"paths",
"=",
"[",
"base",
"]",
"}",
"let",
"filename",
"=",
"findPath",
"(",
"path",
",",
"paths",
")",
"if",
"(",
"!",
"filename",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"path",
"}",
"`",
")",
"}",
"return",
"filename",
"}"
] | Used by require | [
"Used",
"by",
"require"
] | 86924af74b23190e5753f5e1447719bb1def8151 | https://github.com/lucidogen/lucy-live/blob/86924af74b23190e5753f5e1447719bb1def8151/index.js#L442-L457 |
|
55,304 | mgesmundo/authorify-client | lib/mixin/WithContent.js | function(date) {
if (_.isDate(date)) {
this._date = date.toSerialNumber();
} else if (_.isNumber(date)) {
this._date = date;
} else {
throw new CError('wrong date type').log();
}
} | javascript | function(date) {
if (_.isDate(date)) {
this._date = date.toSerialNumber();
} else if (_.isNumber(date)) {
this._date = date;
} else {
throw new CError('wrong date type').log();
}
} | [
"function",
"(",
"date",
")",
"{",
"if",
"(",
"_",
".",
"isDate",
"(",
"date",
")",
")",
"{",
"this",
".",
"_date",
"=",
"date",
".",
"toSerialNumber",
"(",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isNumber",
"(",
"date",
")",
")",
"{",
"this",
".",
"_date",
"=",
"date",
";",
"}",
"else",
"{",
"throw",
"new",
"CError",
"(",
"'wrong date type'",
")",
".",
"log",
"(",
")",
";",
"}",
"}"
] | Set the date
@param {Date/Integer} date The date as date or number of milliseconds. The date is anyhow saved as integer. | [
"Set",
"the",
"date"
] | 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/mixin/WithContent.js#L39-L47 |
|
55,305 | mgesmundo/authorify-client | lib/mixin/WithContent.js | function(password) {
// empty password not allowed
if (password) {
var hmac = forge.hmac.create();
hmac.start('sha256', SECRET);
hmac.update(password);
this._password = password;
this._passwordHash = hmac.digest().toHex();
}
} | javascript | function(password) {
// empty password not allowed
if (password) {
var hmac = forge.hmac.create();
hmac.start('sha256', SECRET);
hmac.update(password);
this._password = password;
this._passwordHash = hmac.digest().toHex();
}
} | [
"function",
"(",
"password",
")",
"{",
"// empty password not allowed",
"if",
"(",
"password",
")",
"{",
"var",
"hmac",
"=",
"forge",
".",
"hmac",
".",
"create",
"(",
")",
";",
"hmac",
".",
"start",
"(",
"'sha256'",
",",
"SECRET",
")",
";",
"hmac",
".",
"update",
"(",
"password",
")",
";",
"this",
".",
"_password",
"=",
"password",
";",
"this",
".",
"_passwordHash",
"=",
"hmac",
".",
"digest",
"(",
")",
".",
"toHex",
"(",
")",
";",
"}",
"}"
] | Set the password for interactive login
@param {String} password The password for the login | [
"Set",
"the",
"password",
"for",
"interactive",
"login"
] | 39fb57db897eaa49b76444ff62bbc0ccedc7ee16 | https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/mixin/WithContent.js#L135-L144 |
|
55,306 | cli-kit/cli-property | lib/find.js | find | function find(key, target, opts) {
opts = opts || {};
var path = []
, o = target, i, k, p
, re = opts.re = opts.re || /\./
, parts = key.split(re);
for(i =0;i < parts.length;i++) {
k = parts[i];
p = o;
if(opts.create && o[k] === undefined) o[k] = {};
o = o[k];
path.push(k);
if(!o) break;
}
return {key: k, value: o, parent: p, path: path.join('.')};
} | javascript | function find(key, target, opts) {
opts = opts || {};
var path = []
, o = target, i, k, p
, re = opts.re = opts.re || /\./
, parts = key.split(re);
for(i =0;i < parts.length;i++) {
k = parts[i];
p = o;
if(opts.create && o[k] === undefined) o[k] = {};
o = o[k];
path.push(k);
if(!o) break;
}
return {key: k, value: o, parent: p, path: path.join('.')};
} | [
"function",
"find",
"(",
"key",
",",
"target",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"path",
"=",
"[",
"]",
",",
"o",
"=",
"target",
",",
"i",
",",
"k",
",",
"p",
",",
"re",
"=",
"opts",
".",
"re",
"=",
"opts",
".",
"re",
"||",
"/",
"\\.",
"/",
",",
"parts",
"=",
"key",
".",
"split",
"(",
"re",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"parts",
".",
"length",
";",
"i",
"++",
")",
"{",
"k",
"=",
"parts",
"[",
"i",
"]",
";",
"p",
"=",
"o",
";",
"if",
"(",
"opts",
".",
"create",
"&&",
"o",
"[",
"k",
"]",
"===",
"undefined",
")",
"o",
"[",
"k",
"]",
"=",
"{",
"}",
";",
"o",
"=",
"o",
"[",
"k",
"]",
";",
"path",
".",
"push",
"(",
"k",
")",
";",
"if",
"(",
"!",
"o",
")",
"break",
";",
"}",
"return",
"{",
"key",
":",
"k",
",",
"value",
":",
"o",
",",
"parent",
":",
"p",
",",
"path",
":",
"path",
".",
"join",
"(",
"'.'",
")",
"}",
";",
"}"
] | Accept a string dot delimited key and attempt to lookup the
property on a target object.
Returns an object containing the fields:
1. key - The name of the property on the parent.
2. value - The property value.
3. parent - The parent object.
4. path - A string dot delimited path to the object.
@param key String dot delimited property reference.
@param target The target object.
@param opts Processing opts.
@param opts.re An alternative regular
expression used to split the key.
@param opts.create Create objects for each
part in the path. | [
"Accept",
"a",
"string",
"dot",
"delimited",
"key",
"and",
"attempt",
"to",
"lookup",
"the",
"property",
"on",
"a",
"target",
"object",
"."
] | de6f727af1f8fc1f613fe42200c5e070aa6b0b21 | https://github.com/cli-kit/cli-property/blob/de6f727af1f8fc1f613fe42200c5e070aa6b0b21/lib/find.js#L20-L35 |
55,307 | hitchyjs/odem | lib/utility/string.js | camelToSnake | function camelToSnake( string ) {
return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "_" + match.toLocaleLowerCase() );
} | javascript | function camelToSnake( string ) {
return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "_" + match.toLocaleLowerCase() );
} | [
"function",
"camelToSnake",
"(",
"string",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"ptnCamel",
",",
"(",
"all",
",",
"predecessor",
",",
"match",
")",
"=>",
"predecessor",
"+",
"\"_\"",
"+",
"match",
".",
"toLocaleLowerCase",
"(",
")",
")",
";",
"}"
] | Converts string from camelCase to snake_case.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"camelCase",
"to",
"snake_case",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L40-L42 |
55,308 | hitchyjs/odem | lib/utility/string.js | camelToKebab | function camelToKebab( string ) {
return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "-" + match.toLocaleLowerCase() );
} | javascript | function camelToKebab( string ) {
return string.replace( ptnCamel, ( all, predecessor, match ) => predecessor + "-" + match.toLocaleLowerCase() );
} | [
"function",
"camelToKebab",
"(",
"string",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"ptnCamel",
",",
"(",
"all",
",",
"predecessor",
",",
"match",
")",
"=>",
"predecessor",
"+",
"\"-\"",
"+",
"match",
".",
"toLocaleLowerCase",
"(",
")",
")",
";",
"}"
] | Converts string from camelCase to kebab-case.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"camelCase",
"to",
"kebab",
"-",
"case",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L50-L52 |
55,309 | hitchyjs/odem | lib/utility/string.js | snakeToCamel | function snakeToCamel( string ) {
return string.replace( ptnSnake, ( all, predecessor, match ) => predecessor + match.toLocaleUpperCase() );
} | javascript | function snakeToCamel( string ) {
return string.replace( ptnSnake, ( all, predecessor, match ) => predecessor + match.toLocaleUpperCase() );
} | [
"function",
"snakeToCamel",
"(",
"string",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"ptnSnake",
",",
"(",
"all",
",",
"predecessor",
",",
"match",
")",
"=>",
"predecessor",
"+",
"match",
".",
"toLocaleUpperCase",
"(",
")",
")",
";",
"}"
] | Converts string from snake_case to camelCase.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"snake_case",
"to",
"camelCase",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L60-L62 |
55,310 | hitchyjs/odem | lib/utility/string.js | snakeToKebab | function snakeToKebab( string ) {
return string.replace( ptnSnake, ( all, predecessor, match ) => predecessor + "-" + match );
} | javascript | function snakeToKebab( string ) {
return string.replace( ptnSnake, ( all, predecessor, match ) => predecessor + "-" + match );
} | [
"function",
"snakeToKebab",
"(",
"string",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"ptnSnake",
",",
"(",
"all",
",",
"predecessor",
",",
"match",
")",
"=>",
"predecessor",
"+",
"\"-\"",
"+",
"match",
")",
";",
"}"
] | Converts string from snake_case to kebab-case.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"snake_case",
"to",
"kebab",
"-",
"case",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L70-L72 |
55,311 | hitchyjs/odem | lib/utility/string.js | kebabToCamel | function kebabToCamel( string ) {
return string.replace( ptnKebab, ( all, predecessor, match ) => predecessor + match.toLocaleUpperCase() );
} | javascript | function kebabToCamel( string ) {
return string.replace( ptnKebab, ( all, predecessor, match ) => predecessor + match.toLocaleUpperCase() );
} | [
"function",
"kebabToCamel",
"(",
"string",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"ptnKebab",
",",
"(",
"all",
",",
"predecessor",
",",
"match",
")",
"=>",
"predecessor",
"+",
"match",
".",
"toLocaleUpperCase",
"(",
")",
")",
";",
"}"
] | Converts string from kebab-case to camelCase.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"kebab",
"-",
"case",
"to",
"camelCase",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L80-L82 |
55,312 | hitchyjs/odem | lib/utility/string.js | kebabToPascal | function kebabToPascal( string ) {
const camel = kebabToCamel( string );
return camel.slice( 0, 1 ).toUpperCase() + camel.slice( 1 );
} | javascript | function kebabToPascal( string ) {
const camel = kebabToCamel( string );
return camel.slice( 0, 1 ).toUpperCase() + camel.slice( 1 );
} | [
"function",
"kebabToPascal",
"(",
"string",
")",
"{",
"const",
"camel",
"=",
"kebabToCamel",
"(",
"string",
")",
";",
"return",
"camel",
".",
"slice",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"camel",
".",
"slice",
"(",
"1",
")",
";",
"}"
] | Converts string from kebab-case to PascalCase.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"kebab",
"-",
"case",
"to",
"PascalCase",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L90-L94 |
55,313 | hitchyjs/odem | lib/utility/string.js | kebabToSnake | function kebabToSnake( string ) {
return string.replace( ptnKebab, ( all, predecessor, match ) => predecessor + "_" + match );
} | javascript | function kebabToSnake( string ) {
return string.replace( ptnKebab, ( all, predecessor, match ) => predecessor + "_" + match );
} | [
"function",
"kebabToSnake",
"(",
"string",
")",
"{",
"return",
"string",
".",
"replace",
"(",
"ptnKebab",
",",
"(",
"all",
",",
"predecessor",
",",
"match",
")",
"=>",
"predecessor",
"+",
"\"_\"",
"+",
"match",
")",
";",
"}"
] | Converts string from kebab-case to snake_case.
@param {string} string string to convert
@returns {string} converted string | [
"Converts",
"string",
"from",
"kebab",
"-",
"case",
"to",
"snake_case",
"."
] | 28f3dc31cc3314f9109d2cac1f5f7e20dad6521b | https://github.com/hitchyjs/odem/blob/28f3dc31cc3314f9109d2cac1f5f7e20dad6521b/lib/utility/string.js#L102-L104 |
55,314 | TribeMedia/tribemedia-kurento-client-core | lib/complexTypes/CodecConfiguration.js | CodecConfiguration | function CodecConfiguration(codecConfigurationDict){
if(!(this instanceof CodecConfiguration))
return new CodecConfiguration(codecConfigurationDict)
// Check codecConfigurationDict has the required fields
checkType('String', 'codecConfigurationDict.name', codecConfigurationDict.name, {required: true});
checkType('String', 'codecConfigurationDict.properties', codecConfigurationDict.properties);
// Init parent class
CodecConfiguration.super_.call(this, codecConfigurationDict)
// Set object properties
Object.defineProperties(this, {
name: {
writable: true,
enumerable: true,
value: codecConfigurationDict.name
},
properties: {
writable: true,
enumerable: true,
value: codecConfigurationDict.properties
}
})
} | javascript | function CodecConfiguration(codecConfigurationDict){
if(!(this instanceof CodecConfiguration))
return new CodecConfiguration(codecConfigurationDict)
// Check codecConfigurationDict has the required fields
checkType('String', 'codecConfigurationDict.name', codecConfigurationDict.name, {required: true});
checkType('String', 'codecConfigurationDict.properties', codecConfigurationDict.properties);
// Init parent class
CodecConfiguration.super_.call(this, codecConfigurationDict)
// Set object properties
Object.defineProperties(this, {
name: {
writable: true,
enumerable: true,
value: codecConfigurationDict.name
},
properties: {
writable: true,
enumerable: true,
value: codecConfigurationDict.properties
}
})
} | [
"function",
"CodecConfiguration",
"(",
"codecConfigurationDict",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"CodecConfiguration",
")",
")",
"return",
"new",
"CodecConfiguration",
"(",
"codecConfigurationDict",
")",
"// Check codecConfigurationDict has the required fields",
"checkType",
"(",
"'String'",
",",
"'codecConfigurationDict.name'",
",",
"codecConfigurationDict",
".",
"name",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"checkType",
"(",
"'String'",
",",
"'codecConfigurationDict.properties'",
",",
"codecConfigurationDict",
".",
"properties",
")",
";",
"// Init parent class",
"CodecConfiguration",
".",
"super_",
".",
"call",
"(",
"this",
",",
"codecConfigurationDict",
")",
"// Set object properties",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"name",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"codecConfigurationDict",
".",
"name",
"}",
",",
"properties",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"codecConfigurationDict",
".",
"properties",
"}",
"}",
")",
"}"
] | Defines specific configuration for codecs
@constructor module:core/complexTypes.CodecConfiguration
@property {external:String} name
Name of the codec defined as <encoding name>/<clock rate>[/<encoding
parameters>]
@property {external:String} properties
String used for tuning codec properties | [
"Defines",
"specific",
"configuration",
"for",
"codecs"
] | de4c0094644aae91320e330f9cea418a3ac55468 | https://github.com/TribeMedia/tribemedia-kurento-client-core/blob/de4c0094644aae91320e330f9cea418a3ac55468/lib/complexTypes/CodecConfiguration.js#L38-L62 |
55,315 | AndreasMadsen/drugged | handlers/default.js | DefaultHandle | function DefaultHandle(done, req, res, parsedUrl) {
this.res = res;
this.res.once('error', this.error.bind(this));
this.req = req;
this.req.once('error', this.error.bind(this));
this.url = parsedUrl;
// If this is the actual constructor call done now
if (this.constructor === DefaultHandle) done(null);
} | javascript | function DefaultHandle(done, req, res, parsedUrl) {
this.res = res;
this.res.once('error', this.error.bind(this));
this.req = req;
this.req.once('error', this.error.bind(this));
this.url = parsedUrl;
// If this is the actual constructor call done now
if (this.constructor === DefaultHandle) done(null);
} | [
"function",
"DefaultHandle",
"(",
"done",
",",
"req",
",",
"res",
",",
"parsedUrl",
")",
"{",
"this",
".",
"res",
"=",
"res",
";",
"this",
".",
"res",
".",
"once",
"(",
"'error'",
",",
"this",
".",
"error",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"req",
"=",
"req",
";",
"this",
".",
"req",
".",
"once",
"(",
"'error'",
",",
"this",
".",
"error",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"url",
"=",
"parsedUrl",
";",
"// If this is the actual constructor call done now",
"if",
"(",
"this",
".",
"constructor",
"===",
"DefaultHandle",
")",
"done",
"(",
"null",
")",
";",
"}"
] | Supper simple request container | [
"Supper",
"simple",
"request",
"container"
] | 2ba5e9a9e87dd43a6754f711a125da13c58da68b | https://github.com/AndreasMadsen/drugged/blob/2ba5e9a9e87dd43a6754f711a125da13c58da68b/handlers/default.js#L4-L13 |
55,316 | tmpvar/varargs | varargs.js | varargs | function varargs(args) {
var argl = args.length;
var arga;
if (!Array.isArray(args)) {
arga = new Array(argl);
for (var i = 0; i < argl; i++) {
arga[i] = args[i];
}
}
return arga;
} | javascript | function varargs(args) {
var argl = args.length;
var arga;
if (!Array.isArray(args)) {
arga = new Array(argl);
for (var i = 0; i < argl; i++) {
arga[i] = args[i];
}
}
return arga;
} | [
"function",
"varargs",
"(",
"args",
")",
"{",
"var",
"argl",
"=",
"args",
".",
"length",
";",
"var",
"arga",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"args",
")",
")",
"{",
"arga",
"=",
"new",
"Array",
"(",
"argl",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"argl",
";",
"i",
"++",
")",
"{",
"arga",
"[",
"i",
"]",
"=",
"args",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"arga",
";",
"}"
] | args is an 'arguments' object | [
"args",
"is",
"an",
"arguments",
"object"
] | 27ff831850302bb41bde6b34eba940094eca6730 | https://github.com/tmpvar/varargs/blob/27ff831850302bb41bde6b34eba940094eca6730/varargs.js#L4-L17 |
55,317 | MrRaindrop/cubicbezier | build/cubicbezier.debug.js | solveCurveX | function solveCurveX(x) {
var t2 = x,
derivative,
x2;
// https://trac.webkit.org/browser/trunk/Source/WebCore/platform/animation
// First try a few iterations of Newton's method -- normally very fast.
// http://en.wikipedia.org/wiki/Newton's_method
for (var i = 0; i < 8; i++) {
// f(t)-x=0
x2 = sampleCurveX(t2) - x;
if (Math.abs(x2) < ZERO_LIMIT) {
return t2;
}
derivative = sampleCurveDerivativeX(t2);
// == 0, failure
if (Math.abs(derivative) < ZERO_LIMIT) {
break;
}
t2 -= x2 / derivative;
}
// Fall back to the bisection method for reliability.
// bisection
// http://en.wikipedia.org/wiki/Bisection_method
var t1 = 1,
t0 = 0;
t2 = x;
while (t1 > t0) {
x2 = sampleCurveX(t2) - x;
if (Math.abs(x2) < ZERO_LIMIT) {
return t2;
}
if (x2 > 0) {
t1 = t2;
} else {
t0 = t2;
}
t2 = (t1 + t0) / 2;
}
// Failure
return t2;
} | javascript | function solveCurveX(x) {
var t2 = x,
derivative,
x2;
// https://trac.webkit.org/browser/trunk/Source/WebCore/platform/animation
// First try a few iterations of Newton's method -- normally very fast.
// http://en.wikipedia.org/wiki/Newton's_method
for (var i = 0; i < 8; i++) {
// f(t)-x=0
x2 = sampleCurveX(t2) - x;
if (Math.abs(x2) < ZERO_LIMIT) {
return t2;
}
derivative = sampleCurveDerivativeX(t2);
// == 0, failure
if (Math.abs(derivative) < ZERO_LIMIT) {
break;
}
t2 -= x2 / derivative;
}
// Fall back to the bisection method for reliability.
// bisection
// http://en.wikipedia.org/wiki/Bisection_method
var t1 = 1,
t0 = 0;
t2 = x;
while (t1 > t0) {
x2 = sampleCurveX(t2) - x;
if (Math.abs(x2) < ZERO_LIMIT) {
return t2;
}
if (x2 > 0) {
t1 = t2;
} else {
t0 = t2;
}
t2 = (t1 + t0) / 2;
}
// Failure
return t2;
} | [
"function",
"solveCurveX",
"(",
"x",
")",
"{",
"var",
"t2",
"=",
"x",
",",
"derivative",
",",
"x2",
";",
"// https://trac.webkit.org/browser/trunk/Source/WebCore/platform/animation",
"// First try a few iterations of Newton's method -- normally very fast.",
"// http://en.wikipedia.org/wiki/Newton's_method",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"8",
";",
"i",
"++",
")",
"{",
"// f(t)-x=0",
"x2",
"=",
"sampleCurveX",
"(",
"t2",
")",
"-",
"x",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"x2",
")",
"<",
"ZERO_LIMIT",
")",
"{",
"return",
"t2",
";",
"}",
"derivative",
"=",
"sampleCurveDerivativeX",
"(",
"t2",
")",
";",
"// == 0, failure",
"if",
"(",
"Math",
".",
"abs",
"(",
"derivative",
")",
"<",
"ZERO_LIMIT",
")",
"{",
"break",
";",
"}",
"t2",
"-=",
"x2",
"/",
"derivative",
";",
"}",
"// Fall back to the bisection method for reliability.",
"// bisection",
"// http://en.wikipedia.org/wiki/Bisection_method",
"var",
"t1",
"=",
"1",
",",
"t0",
"=",
"0",
";",
"t2",
"=",
"x",
";",
"while",
"(",
"t1",
">",
"t0",
")",
"{",
"x2",
"=",
"sampleCurveX",
"(",
"t2",
")",
"-",
"x",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"x2",
")",
"<",
"ZERO_LIMIT",
")",
"{",
"return",
"t2",
";",
"}",
"if",
"(",
"x2",
">",
"0",
")",
"{",
"t1",
"=",
"t2",
";",
"}",
"else",
"{",
"t0",
"=",
"t2",
";",
"}",
"t2",
"=",
"(",
"t1",
"+",
"t0",
")",
"/",
"2",
";",
"}",
"// Failure",
"return",
"t2",
";",
"}"
] | Given an x value, find a parametric value it came from. | [
"Given",
"an",
"x",
"value",
"find",
"a",
"parametric",
"value",
"it",
"came",
"from",
"."
] | 4d70f21a8890799aef1bcd7165f2dce50efe3221 | https://github.com/MrRaindrop/cubicbezier/blob/4d70f21a8890799aef1bcd7165f2dce50efe3221/build/cubicbezier.debug.js#L29-L72 |
55,318 | AndreasMadsen/immortal | lib/monitor.js | function (name) {
return function (state) {
// Write to output stream
var time = new Date();
self.write(messages[name][state].replace('{pid}', self.pid[name]));
self.write('=== Time: ' + time.toString());
};
} | javascript | function (name) {
return function (state) {
// Write to output stream
var time = new Date();
self.write(messages[name][state].replace('{pid}', self.pid[name]));
self.write('=== Time: ' + time.toString());
};
} | [
"function",
"(",
"name",
")",
"{",
"return",
"function",
"(",
"state",
")",
"{",
"// Write to output stream",
"var",
"time",
"=",
"new",
"Date",
"(",
")",
";",
"self",
".",
"write",
"(",
"messages",
"[",
"name",
"]",
"[",
"state",
"]",
".",
"replace",
"(",
"'{pid}'",
",",
"self",
".",
"pid",
"[",
"name",
"]",
")",
")",
";",
"self",
".",
"write",
"(",
"'=== Time: '",
"+",
"time",
".",
"toString",
"(",
")",
")",
";",
"}",
";",
"}"
] | will write the message given in the message object and write the current time and date. | [
"will",
"write",
"the",
"message",
"given",
"in",
"the",
"message",
"object",
"and",
"write",
"the",
"current",
"time",
"and",
"date",
"."
] | c1ab5a4287a543fdfd980604a9e9927d663a9ef2 | https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/monitor.js#L84-L91 |
|
55,319 | ltoussaint/node-bootstrap-core | routers/exactPath.js | ExactPath | function ExactPath() {
/**
* Uri to action::method mapping
* @type {Object}
*/
var mapping = {};
/**
* Resolve uri
* @param request
* @returns {*}
*/
this.resolve = function (request) {
var uri = request.url.split('?')[0];
if (mapping[request.method] && mapping[request.method][uri]) {
return decode.call(this, mapping[request.method][uri]);
}
return null;
};
/**
* Add a route mapping
* @param method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.addRoute = function (method, uri, callback) {
method = method.toUpperCase();
if (!mapping[method]) {
mapping[method] = {};
}
mapping[method][uri] = callback;
return this;
};
/**
* Add route mapping for get http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.get = function (uri, callback) {
return this.addRoute('GET', uri, callback);
};
/**
* Add route mapping for post http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.post = function (uri, callback) {
return this.addRoute('POST', uri, callback);
};
/**
* Add route mapping for put http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.put = function (uri, callback) {
return this.addRoute('PUT', uri, callback);
};
/**
* Add route mapping for delete http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.delete = function (uri, callback) {
return this.addRoute('DELETE', uri, callback);
};
return this;
/**
* Decode callback
* @param callback
* @returns {*}
*/
function decode(callback) {
if (typeof callback == 'function') {
return callback;
} else {
var split = callback.split('::');
var action = split[0];
var method = split[1] || 'index';
return {
action: action,
method: method,
arguments: []
};
}
}
} | javascript | function ExactPath() {
/**
* Uri to action::method mapping
* @type {Object}
*/
var mapping = {};
/**
* Resolve uri
* @param request
* @returns {*}
*/
this.resolve = function (request) {
var uri = request.url.split('?')[0];
if (mapping[request.method] && mapping[request.method][uri]) {
return decode.call(this, mapping[request.method][uri]);
}
return null;
};
/**
* Add a route mapping
* @param method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.addRoute = function (method, uri, callback) {
method = method.toUpperCase();
if (!mapping[method]) {
mapping[method] = {};
}
mapping[method][uri] = callback;
return this;
};
/**
* Add route mapping for get http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.get = function (uri, callback) {
return this.addRoute('GET', uri, callback);
};
/**
* Add route mapping for post http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.post = function (uri, callback) {
return this.addRoute('POST', uri, callback);
};
/**
* Add route mapping for put http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.put = function (uri, callback) {
return this.addRoute('PUT', uri, callback);
};
/**
* Add route mapping for delete http method
* @param uri
* @param callback
* @returns {ExactPath}
*/
this.delete = function (uri, callback) {
return this.addRoute('DELETE', uri, callback);
};
return this;
/**
* Decode callback
* @param callback
* @returns {*}
*/
function decode(callback) {
if (typeof callback == 'function') {
return callback;
} else {
var split = callback.split('::');
var action = split[0];
var method = split[1] || 'index';
return {
action: action,
method: method,
arguments: []
};
}
}
} | [
"function",
"ExactPath",
"(",
")",
"{",
"/**\n * Uri to action::method mapping\n * @type {Object}\n */",
"var",
"mapping",
"=",
"{",
"}",
";",
"/**\n * Resolve uri\n * @param request\n * @returns {*}\n */",
"this",
".",
"resolve",
"=",
"function",
"(",
"request",
")",
"{",
"var",
"uri",
"=",
"request",
".",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"mapping",
"[",
"request",
".",
"method",
"]",
"&&",
"mapping",
"[",
"request",
".",
"method",
"]",
"[",
"uri",
"]",
")",
"{",
"return",
"decode",
".",
"call",
"(",
"this",
",",
"mapping",
"[",
"request",
".",
"method",
"]",
"[",
"uri",
"]",
")",
";",
"}",
"return",
"null",
";",
"}",
";",
"/**\n * Add a route mapping\n * @param method\n * @param uri\n * @param callback\n * @returns {ExactPath}\n */",
"this",
".",
"addRoute",
"=",
"function",
"(",
"method",
",",
"uri",
",",
"callback",
")",
"{",
"method",
"=",
"method",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"!",
"mapping",
"[",
"method",
"]",
")",
"{",
"mapping",
"[",
"method",
"]",
"=",
"{",
"}",
";",
"}",
"mapping",
"[",
"method",
"]",
"[",
"uri",
"]",
"=",
"callback",
";",
"return",
"this",
";",
"}",
";",
"/**\n * Add route mapping for get http method\n * @param uri\n * @param callback\n * @returns {ExactPath}\n */",
"this",
".",
"get",
"=",
"function",
"(",
"uri",
",",
"callback",
")",
"{",
"return",
"this",
".",
"addRoute",
"(",
"'GET'",
",",
"uri",
",",
"callback",
")",
";",
"}",
";",
"/**\n * Add route mapping for post http method\n * @param uri\n * @param callback\n * @returns {ExactPath}\n */",
"this",
".",
"post",
"=",
"function",
"(",
"uri",
",",
"callback",
")",
"{",
"return",
"this",
".",
"addRoute",
"(",
"'POST'",
",",
"uri",
",",
"callback",
")",
";",
"}",
";",
"/**\n * Add route mapping for put http method\n * @param uri\n * @param callback\n * @returns {ExactPath}\n */",
"this",
".",
"put",
"=",
"function",
"(",
"uri",
",",
"callback",
")",
"{",
"return",
"this",
".",
"addRoute",
"(",
"'PUT'",
",",
"uri",
",",
"callback",
")",
";",
"}",
";",
"/**\n * Add route mapping for delete http method\n * @param uri\n * @param callback\n * @returns {ExactPath}\n */",
"this",
".",
"delete",
"=",
"function",
"(",
"uri",
",",
"callback",
")",
"{",
"return",
"this",
".",
"addRoute",
"(",
"'DELETE'",
",",
"uri",
",",
"callback",
")",
";",
"}",
";",
"return",
"this",
";",
"/**\n * Decode callback\n * @param callback\n * @returns {*}\n */",
"function",
"decode",
"(",
"callback",
")",
"{",
"if",
"(",
"typeof",
"callback",
"==",
"'function'",
")",
"{",
"return",
"callback",
";",
"}",
"else",
"{",
"var",
"split",
"=",
"callback",
".",
"split",
"(",
"'::'",
")",
";",
"var",
"action",
"=",
"split",
"[",
"0",
"]",
";",
"var",
"method",
"=",
"split",
"[",
"1",
"]",
"||",
"'index'",
";",
"return",
"{",
"action",
":",
"action",
",",
"method",
":",
"method",
",",
"arguments",
":",
"[",
"]",
"}",
";",
"}",
"}",
"}"
] | Simple router which will map exact url pathname to a callback
@returns {ExactPath}
@constructor | [
"Simple",
"router",
"which",
"will",
"map",
"exact",
"url",
"pathname",
"to",
"a",
"callback"
] | b083b320900ed068007e58af2249825b8da24c79 | https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/routers/exactPath.js#L8-L107 |
55,320 | MoNoApps/uf | utils/zugmaschine.js | function(config){
this.options = {
hostname : config.url,
port : 443,
path : '', //override
method : '', //override
auth : config.user + ':' + config.passwd,
headers : config.headers
};
} | javascript | function(config){
this.options = {
hostname : config.url,
port : 443,
path : '', //override
method : '', //override
auth : config.user + ':' + config.passwd,
headers : config.headers
};
} | [
"function",
"(",
"config",
")",
"{",
"this",
".",
"options",
"=",
"{",
"hostname",
":",
"config",
".",
"url",
",",
"port",
":",
"443",
",",
"path",
":",
"''",
",",
"//override",
"method",
":",
"''",
",",
"//override",
"auth",
":",
"config",
".",
"user",
"+",
"':'",
"+",
"config",
".",
"passwd",
",",
"headers",
":",
"config",
".",
"headers",
"}",
";",
"}"
] | The Tracktor object.
This object uses https and send the request to unfuddle API. | [
"The",
"Tracktor",
"object",
".",
"This",
"object",
"uses",
"https",
"and",
"send",
"the",
"request",
"to",
"unfuddle",
"API",
"."
] | cc65386de47acce4aa6fc44ef18219d03944f6c3 | https://github.com/MoNoApps/uf/blob/cc65386de47acce4aa6fc44ef18219d03944f6c3/utils/zugmaschine.js#L7-L16 |
|
55,321 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/wireprotocol/3_2_support.js | decorateWithSessionsData | function decorateWithSessionsData(command, session, options) {
if (!session) {
return;
}
// first apply non-transaction-specific sessions data
const serverSession = session.serverSession;
const inTransaction = session.inTransaction() || isTransactionCommand(command);
const isRetryableWrite = options.willRetryWrite;
if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) {
command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber);
}
// now attempt to apply transaction-specific sessions data
if (!inTransaction) {
if (session.transaction.state !== TxnState.NO_TRANSACTION) {
session.transaction.transition(TxnState.NO_TRANSACTION);
}
// for causal consistency
if (session.supports.causalConsistency && session.operationTime) {
command.readConcern = command.readConcern || {};
Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
}
return;
}
if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) {
return new MongoError(
`Read preference in a transaction must be primary, not: ${options.readPreference.mode}`
);
}
// `autocommit` must always be false to differentiate from retryable writes
command.autocommit = false;
if (session.transaction.state === TxnState.STARTING_TRANSACTION) {
session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS);
command.startTransaction = true;
const readConcern =
session.transaction.options.readConcern || session.clientOptions.readConcern;
if (readConcern) {
command.readConcern = readConcern;
}
if (session.supports.causalConsistency && session.operationTime) {
command.readConcern = command.readConcern || {};
Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
}
}
} | javascript | function decorateWithSessionsData(command, session, options) {
if (!session) {
return;
}
// first apply non-transaction-specific sessions data
const serverSession = session.serverSession;
const inTransaction = session.inTransaction() || isTransactionCommand(command);
const isRetryableWrite = options.willRetryWrite;
if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) {
command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber);
}
// now attempt to apply transaction-specific sessions data
if (!inTransaction) {
if (session.transaction.state !== TxnState.NO_TRANSACTION) {
session.transaction.transition(TxnState.NO_TRANSACTION);
}
// for causal consistency
if (session.supports.causalConsistency && session.operationTime) {
command.readConcern = command.readConcern || {};
Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
}
return;
}
if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) {
return new MongoError(
`Read preference in a transaction must be primary, not: ${options.readPreference.mode}`
);
}
// `autocommit` must always be false to differentiate from retryable writes
command.autocommit = false;
if (session.transaction.state === TxnState.STARTING_TRANSACTION) {
session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS);
command.startTransaction = true;
const readConcern =
session.transaction.options.readConcern || session.clientOptions.readConcern;
if (readConcern) {
command.readConcern = readConcern;
}
if (session.supports.causalConsistency && session.operationTime) {
command.readConcern = command.readConcern || {};
Object.assign(command.readConcern, { afterClusterTime: session.operationTime });
}
}
} | [
"function",
"decorateWithSessionsData",
"(",
"command",
",",
"session",
",",
"options",
")",
"{",
"if",
"(",
"!",
"session",
")",
"{",
"return",
";",
"}",
"// first apply non-transaction-specific sessions data",
"const",
"serverSession",
"=",
"session",
".",
"serverSession",
";",
"const",
"inTransaction",
"=",
"session",
".",
"inTransaction",
"(",
")",
"||",
"isTransactionCommand",
"(",
"command",
")",
";",
"const",
"isRetryableWrite",
"=",
"options",
".",
"willRetryWrite",
";",
"if",
"(",
"serverSession",
".",
"txnNumber",
"&&",
"(",
"isRetryableWrite",
"||",
"inTransaction",
")",
")",
"{",
"command",
".",
"txnNumber",
"=",
"BSON",
".",
"Long",
".",
"fromNumber",
"(",
"serverSession",
".",
"txnNumber",
")",
";",
"}",
"// now attempt to apply transaction-specific sessions data",
"if",
"(",
"!",
"inTransaction",
")",
"{",
"if",
"(",
"session",
".",
"transaction",
".",
"state",
"!==",
"TxnState",
".",
"NO_TRANSACTION",
")",
"{",
"session",
".",
"transaction",
".",
"transition",
"(",
"TxnState",
".",
"NO_TRANSACTION",
")",
";",
"}",
"// for causal consistency",
"if",
"(",
"session",
".",
"supports",
".",
"causalConsistency",
"&&",
"session",
".",
"operationTime",
")",
"{",
"command",
".",
"readConcern",
"=",
"command",
".",
"readConcern",
"||",
"{",
"}",
";",
"Object",
".",
"assign",
"(",
"command",
".",
"readConcern",
",",
"{",
"afterClusterTime",
":",
"session",
".",
"operationTime",
"}",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"options",
".",
"readPreference",
"&&",
"!",
"options",
".",
"readPreference",
".",
"equals",
"(",
"ReadPreference",
".",
"primary",
")",
")",
"{",
"return",
"new",
"MongoError",
"(",
"`",
"${",
"options",
".",
"readPreference",
".",
"mode",
"}",
"`",
")",
";",
"}",
"// `autocommit` must always be false to differentiate from retryable writes",
"command",
".",
"autocommit",
"=",
"false",
";",
"if",
"(",
"session",
".",
"transaction",
".",
"state",
"===",
"TxnState",
".",
"STARTING_TRANSACTION",
")",
"{",
"session",
".",
"transaction",
".",
"transition",
"(",
"TxnState",
".",
"TRANSACTION_IN_PROGRESS",
")",
";",
"command",
".",
"startTransaction",
"=",
"true",
";",
"const",
"readConcern",
"=",
"session",
".",
"transaction",
".",
"options",
".",
"readConcern",
"||",
"session",
".",
"clientOptions",
".",
"readConcern",
";",
"if",
"(",
"readConcern",
")",
"{",
"command",
".",
"readConcern",
"=",
"readConcern",
";",
"}",
"if",
"(",
"session",
".",
"supports",
".",
"causalConsistency",
"&&",
"session",
".",
"operationTime",
")",
"{",
"command",
".",
"readConcern",
"=",
"command",
".",
"readConcern",
"||",
"{",
"}",
";",
"Object",
".",
"assign",
"(",
"command",
".",
"readConcern",
",",
"{",
"afterClusterTime",
":",
"session",
".",
"operationTime",
"}",
")",
";",
"}",
"}",
"}"
] | Optionally decorate a command with sessions specific keys
@param {Object} command the command to decorate
@param {ClientSession} session the session tracking transaction state
@param {Object} [options] Optional settings passed to calling operation
@param {Function} [callback] Optional callback passed from calling operation
@return {MongoError|null} An error, if some error condition was met | [
"Optionally",
"decorate",
"a",
"command",
"with",
"sessions",
"specific",
"keys"
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/wireprotocol/3_2_support.js#L28-L81 |
55,322 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/wireprotocol/3_2_support.js | executeWrite | function executeWrite(pool, bson, type, opsField, ns, ops, options, callback) {
if (ops.length === 0) throw new MongoError('insert must contain at least one document');
if (typeof options === 'function') {
callback = options;
options = {};
options = options || {};
}
// Split the ns up to get db and collection
const p = ns.split('.');
const d = p.shift();
// Options
const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;
const writeConcern = options.writeConcern;
// return skeleton
const writeCommand = {};
writeCommand[type] = p.join('.');
writeCommand[opsField] = ops;
writeCommand.ordered = ordered;
// Did we specify a write concern
if (writeConcern && Object.keys(writeConcern).length > 0) {
writeCommand.writeConcern = writeConcern;
}
// If we have collation passed in
if (options.collation) {
for (let i = 0; i < writeCommand[opsField].length; i++) {
if (!writeCommand[opsField][i].collation) {
writeCommand[opsField][i].collation = options.collation;
}
}
}
// Do we have bypassDocumentValidation set, then enable it on the write command
if (options.bypassDocumentValidation === true) {
writeCommand.bypassDocumentValidation = options.bypassDocumentValidation;
}
// optionally decorate command with transactions data
const err = decorateWithSessionsData(writeCommand, options.session, options, callback);
if (err) {
return callback(err, null);
}
// Options object
const opts = { command: true };
if (typeof options.session !== 'undefined') opts.session = options.session;
const queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 };
if (type === 'insert') queryOptions.checkKeys = true;
if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys;
// Ensure we support serialization of functions
if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions;
// Do not serialize the undefined fields
if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined;
try {
// Create write command
const cmd = new Query(bson, `${d}.$cmd`, writeCommand, queryOptions);
// Execute command
pool.write(cmd, opts, callback);
} catch (err) {
callback(err);
}
} | javascript | function executeWrite(pool, bson, type, opsField, ns, ops, options, callback) {
if (ops.length === 0) throw new MongoError('insert must contain at least one document');
if (typeof options === 'function') {
callback = options;
options = {};
options = options || {};
}
// Split the ns up to get db and collection
const p = ns.split('.');
const d = p.shift();
// Options
const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;
const writeConcern = options.writeConcern;
// return skeleton
const writeCommand = {};
writeCommand[type] = p.join('.');
writeCommand[opsField] = ops;
writeCommand.ordered = ordered;
// Did we specify a write concern
if (writeConcern && Object.keys(writeConcern).length > 0) {
writeCommand.writeConcern = writeConcern;
}
// If we have collation passed in
if (options.collation) {
for (let i = 0; i < writeCommand[opsField].length; i++) {
if (!writeCommand[opsField][i].collation) {
writeCommand[opsField][i].collation = options.collation;
}
}
}
// Do we have bypassDocumentValidation set, then enable it on the write command
if (options.bypassDocumentValidation === true) {
writeCommand.bypassDocumentValidation = options.bypassDocumentValidation;
}
// optionally decorate command with transactions data
const err = decorateWithSessionsData(writeCommand, options.session, options, callback);
if (err) {
return callback(err, null);
}
// Options object
const opts = { command: true };
if (typeof options.session !== 'undefined') opts.session = options.session;
const queryOptions = { checkKeys: false, numberToSkip: 0, numberToReturn: 1 };
if (type === 'insert') queryOptions.checkKeys = true;
if (typeof options.checkKeys === 'boolean') queryOptions.checkKeys = options.checkKeys;
// Ensure we support serialization of functions
if (options.serializeFunctions) queryOptions.serializeFunctions = options.serializeFunctions;
// Do not serialize the undefined fields
if (options.ignoreUndefined) queryOptions.ignoreUndefined = options.ignoreUndefined;
try {
// Create write command
const cmd = new Query(bson, `${d}.$cmd`, writeCommand, queryOptions);
// Execute command
pool.write(cmd, opts, callback);
} catch (err) {
callback(err);
}
} | [
"function",
"executeWrite",
"(",
"pool",
",",
"bson",
",",
"type",
",",
"opsField",
",",
"ns",
",",
"ops",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"ops",
".",
"length",
"===",
"0",
")",
"throw",
"new",
"MongoError",
"(",
"'insert must contain at least one document'",
")",
";",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"callback",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"}",
"// Split the ns up to get db and collection",
"const",
"p",
"=",
"ns",
".",
"split",
"(",
"'.'",
")",
";",
"const",
"d",
"=",
"p",
".",
"shift",
"(",
")",
";",
"// Options",
"const",
"ordered",
"=",
"typeof",
"options",
".",
"ordered",
"===",
"'boolean'",
"?",
"options",
".",
"ordered",
":",
"true",
";",
"const",
"writeConcern",
"=",
"options",
".",
"writeConcern",
";",
"// return skeleton",
"const",
"writeCommand",
"=",
"{",
"}",
";",
"writeCommand",
"[",
"type",
"]",
"=",
"p",
".",
"join",
"(",
"'.'",
")",
";",
"writeCommand",
"[",
"opsField",
"]",
"=",
"ops",
";",
"writeCommand",
".",
"ordered",
"=",
"ordered",
";",
"// Did we specify a write concern",
"if",
"(",
"writeConcern",
"&&",
"Object",
".",
"keys",
"(",
"writeConcern",
")",
".",
"length",
">",
"0",
")",
"{",
"writeCommand",
".",
"writeConcern",
"=",
"writeConcern",
";",
"}",
"// If we have collation passed in",
"if",
"(",
"options",
".",
"collation",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"writeCommand",
"[",
"opsField",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"writeCommand",
"[",
"opsField",
"]",
"[",
"i",
"]",
".",
"collation",
")",
"{",
"writeCommand",
"[",
"opsField",
"]",
"[",
"i",
"]",
".",
"collation",
"=",
"options",
".",
"collation",
";",
"}",
"}",
"}",
"// Do we have bypassDocumentValidation set, then enable it on the write command",
"if",
"(",
"options",
".",
"bypassDocumentValidation",
"===",
"true",
")",
"{",
"writeCommand",
".",
"bypassDocumentValidation",
"=",
"options",
".",
"bypassDocumentValidation",
";",
"}",
"// optionally decorate command with transactions data",
"const",
"err",
"=",
"decorateWithSessionsData",
"(",
"writeCommand",
",",
"options",
".",
"session",
",",
"options",
",",
"callback",
")",
";",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
"// Options object",
"const",
"opts",
"=",
"{",
"command",
":",
"true",
"}",
";",
"if",
"(",
"typeof",
"options",
".",
"session",
"!==",
"'undefined'",
")",
"opts",
".",
"session",
"=",
"options",
".",
"session",
";",
"const",
"queryOptions",
"=",
"{",
"checkKeys",
":",
"false",
",",
"numberToSkip",
":",
"0",
",",
"numberToReturn",
":",
"1",
"}",
";",
"if",
"(",
"type",
"===",
"'insert'",
")",
"queryOptions",
".",
"checkKeys",
"=",
"true",
";",
"if",
"(",
"typeof",
"options",
".",
"checkKeys",
"===",
"'boolean'",
")",
"queryOptions",
".",
"checkKeys",
"=",
"options",
".",
"checkKeys",
";",
"// Ensure we support serialization of functions",
"if",
"(",
"options",
".",
"serializeFunctions",
")",
"queryOptions",
".",
"serializeFunctions",
"=",
"options",
".",
"serializeFunctions",
";",
"// Do not serialize the undefined fields",
"if",
"(",
"options",
".",
"ignoreUndefined",
")",
"queryOptions",
".",
"ignoreUndefined",
"=",
"options",
".",
"ignoreUndefined",
";",
"try",
"{",
"// Create write command",
"const",
"cmd",
"=",
"new",
"Query",
"(",
"bson",
",",
"`",
"${",
"d",
"}",
"`",
",",
"writeCommand",
",",
"queryOptions",
")",
";",
"// Execute command",
"pool",
".",
"write",
"(",
"cmd",
",",
"opts",
",",
"callback",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"}"
] | Execute a write operation | [
"Execute",
"a",
"write",
"operation"
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/wireprotocol/3_2_support.js#L85-L151 |
55,323 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/wireprotocol/3_2_support.js | killCursorCallback | function killCursorCallback(err, result) {
if (err) {
if (typeof callback !== 'function') return;
return callback(err);
}
// Result
const r = result.message;
// If we have a timed out query or a cursor that was killed
if ((r.responseFlags & (1 << 0)) !== 0) {
if (typeof callback !== 'function') return;
return callback(new MongoNetworkError('cursor killed or timed out'), null);
}
if (!Array.isArray(r.documents) || r.documents.length === 0) {
if (typeof callback !== 'function') return;
return callback(
new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`)
);
}
// Return the result
if (typeof callback === 'function') {
callback(null, r.documents[0]);
}
} | javascript | function killCursorCallback(err, result) {
if (err) {
if (typeof callback !== 'function') return;
return callback(err);
}
// Result
const r = result.message;
// If we have a timed out query or a cursor that was killed
if ((r.responseFlags & (1 << 0)) !== 0) {
if (typeof callback !== 'function') return;
return callback(new MongoNetworkError('cursor killed or timed out'), null);
}
if (!Array.isArray(r.documents) || r.documents.length === 0) {
if (typeof callback !== 'function') return;
return callback(
new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`)
);
}
// Return the result
if (typeof callback === 'function') {
callback(null, r.documents[0]);
}
} | [
"function",
"killCursorCallback",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"return",
";",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"// Result",
"const",
"r",
"=",
"result",
".",
"message",
";",
"// If we have a timed out query or a cursor that was killed",
"if",
"(",
"(",
"r",
".",
"responseFlags",
"&",
"(",
"1",
"<<",
"0",
")",
")",
"!==",
"0",
")",
"{",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"return",
";",
"return",
"callback",
"(",
"new",
"MongoNetworkError",
"(",
"'cursor killed or timed out'",
")",
",",
"null",
")",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"r",
".",
"documents",
")",
"||",
"r",
".",
"documents",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"return",
";",
"return",
"callback",
"(",
"new",
"MongoError",
"(",
"`",
"${",
"cursorId",
"}",
"`",
")",
")",
";",
"}",
"// Return the result",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"callback",
"(",
"null",
",",
"r",
".",
"documents",
"[",
"0",
"]",
")",
";",
"}",
"}"
] | Kill cursor callback | [
"Kill",
"cursor",
"callback"
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/wireprotocol/3_2_support.js#L190-L215 |
55,324 | tdeekens/grunt-voguesy | tasks/voguesy.js | function(dependencies) {
var _dependencies = dependencies || {};
var _numberOfOudatedPackages = Object.keys(_dependencies).length;
var _minor = semver.allMinor(dependencies, 'latest');
var _major = semver.allMajor(dependencies, 'latest');
var _patch = semver.allPatch(dependencies, 'latest`');
var _passing = (
options['up-to-dateness'].number >= _numberOfOudatedPackages &&
_major.passing === true &&
_minor.passing === true &&
_patch.passing === true
);
return {
passing: _passing,
outdated: _.merge(_major.outdated, _minor.outdated, _patch.outdated)
};
} | javascript | function(dependencies) {
var _dependencies = dependencies || {};
var _numberOfOudatedPackages = Object.keys(_dependencies).length;
var _minor = semver.allMinor(dependencies, 'latest');
var _major = semver.allMajor(dependencies, 'latest');
var _patch = semver.allPatch(dependencies, 'latest`');
var _passing = (
options['up-to-dateness'].number >= _numberOfOudatedPackages &&
_major.passing === true &&
_minor.passing === true &&
_patch.passing === true
);
return {
passing: _passing,
outdated: _.merge(_major.outdated, _minor.outdated, _patch.outdated)
};
} | [
"function",
"(",
"dependencies",
")",
"{",
"var",
"_dependencies",
"=",
"dependencies",
"||",
"{",
"}",
";",
"var",
"_numberOfOudatedPackages",
"=",
"Object",
".",
"keys",
"(",
"_dependencies",
")",
".",
"length",
";",
"var",
"_minor",
"=",
"semver",
".",
"allMinor",
"(",
"dependencies",
",",
"'latest'",
")",
";",
"var",
"_major",
"=",
"semver",
".",
"allMajor",
"(",
"dependencies",
",",
"'latest'",
")",
";",
"var",
"_patch",
"=",
"semver",
".",
"allPatch",
"(",
"dependencies",
",",
"'latest`'",
")",
";",
"var",
"_passing",
"=",
"(",
"options",
"[",
"'up-to-dateness'",
"]",
".",
"number",
">=",
"_numberOfOudatedPackages",
"&&",
"_major",
".",
"passing",
"===",
"true",
"&&",
"_minor",
".",
"passing",
"===",
"true",
"&&",
"_patch",
".",
"passing",
"===",
"true",
")",
";",
"return",
"{",
"passing",
":",
"_passing",
",",
"outdated",
":",
"_",
".",
"merge",
"(",
"_major",
".",
"outdated",
",",
"_minor",
".",
"outdated",
",",
"_patch",
".",
"outdated",
")",
"}",
";",
"}"
] | Helper function to avoid code repetition | [
"Helper",
"function",
"to",
"avoid",
"code",
"repetition"
] | 914eb487385bf76c1fa5105a3ef8c98d9cce2263 | https://github.com/tdeekens/grunt-voguesy/blob/914eb487385bf76c1fa5105a3ef8c98d9cce2263/tasks/voguesy.js#L45-L62 |
|
55,325 | m3co/router3 | src/router3.js | resolve_ | function resolve_(element, resolve) {
// if element is a fragment, it will load everything
// up to child element
if (element.MaterialFragment) {
element.MaterialFragment.loaded.then(() => {
slice.call(element.querySelectorAll(selClass))
.forEach(element => componentHandler.upgradeElement(element));
resolve();
});
} else {
element.addEventListener('load', resolve, { once: true });
}
} | javascript | function resolve_(element, resolve) {
// if element is a fragment, it will load everything
// up to child element
if (element.MaterialFragment) {
element.MaterialFragment.loaded.then(() => {
slice.call(element.querySelectorAll(selClass))
.forEach(element => componentHandler.upgradeElement(element));
resolve();
});
} else {
element.addEventListener('load', resolve, { once: true });
}
} | [
"function",
"resolve_",
"(",
"element",
",",
"resolve",
")",
"{",
"// if element is a fragment, it will load everything",
"// up to child element",
"if",
"(",
"element",
".",
"MaterialFragment",
")",
"{",
"element",
".",
"MaterialFragment",
".",
"loaded",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"slice",
".",
"call",
"(",
"element",
".",
"querySelectorAll",
"(",
"selClass",
")",
")",
".",
"forEach",
"(",
"element",
"=>",
"componentHandler",
".",
"upgradeElement",
"(",
"element",
")",
")",
";",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"element",
".",
"addEventListener",
"(",
"'load'",
",",
"resolve",
",",
"{",
"once",
":",
"true",
"}",
")",
";",
"}",
"}"
] | Resolve and upgrade any router element present in element
@param {HTMLElement} element - The element to upgrade/resolve.
@param {Function} resolve - The function to resolve the Promise.
@private | [
"Resolve",
"and",
"upgrade",
"any",
"router",
"element",
"present",
"in",
"element"
] | 8d148bfce50fe7aff4a0952298e0ade50184c1f7 | https://github.com/m3co/router3/blob/8d148bfce50fe7aff4a0952298e0ade50184c1f7/src/router3.js#L54-L66 |
55,326 | m3co/router3 | src/router3.js | hashchange_ | function hashchange_(e) {
if (counterLastMatch > 1) {
counterLastMatch = 0;
throw new Error(`Cannot go back to last matched hash ${e.oldURL}`);
}
// Look for all router3 elements in order
Promise.all(slice
.call(document.querySelectorAll(selClass))
.map(element => {
/**
* link router3 with fragment
* (This process should be decoupled...)
*/
return new Promise(resolve => {
let fragments = slice.call(element.querySelectorAll('.mdl-fragment'));
if (element.classList.contains('mdl-fragment')) {
resolve_(element, resolve);
} else {
// if there's at least one child fragment, then load all fragments
// and resolve their promises
Promise.all(fragments.map(fragment => {
return new Promise(resolve => resolve_(fragment, resolve));
})).then(resolve);
}
});
})
).then(() => {
// when everything was loaded...
let match = slice
.call(document.querySelectorAll(selClass))
.map(element => route_(element,
e && e.newURL ? e.newURL : window.location.href, lastMatch))
.find(result => result);
if (match) {
stateRevert = false;
lastMatch = match;
counterLastMatch = 0;
} else {
let newHash = window.location.hash || '';
if (newHash !== '') {
stateRevert = true;
counterLastMatch++;
window.location.hash = e && e.oldURL ? e.oldURL.split('#')[1] : '';
setTimeout(() => {
throw new Error(`Cannot navigate to ${newHash.slice(1)}`);
});
}
}
});
} | javascript | function hashchange_(e) {
if (counterLastMatch > 1) {
counterLastMatch = 0;
throw new Error(`Cannot go back to last matched hash ${e.oldURL}`);
}
// Look for all router3 elements in order
Promise.all(slice
.call(document.querySelectorAll(selClass))
.map(element => {
/**
* link router3 with fragment
* (This process should be decoupled...)
*/
return new Promise(resolve => {
let fragments = slice.call(element.querySelectorAll('.mdl-fragment'));
if (element.classList.contains('mdl-fragment')) {
resolve_(element, resolve);
} else {
// if there's at least one child fragment, then load all fragments
// and resolve their promises
Promise.all(fragments.map(fragment => {
return new Promise(resolve => resolve_(fragment, resolve));
})).then(resolve);
}
});
})
).then(() => {
// when everything was loaded...
let match = slice
.call(document.querySelectorAll(selClass))
.map(element => route_(element,
e && e.newURL ? e.newURL : window.location.href, lastMatch))
.find(result => result);
if (match) {
stateRevert = false;
lastMatch = match;
counterLastMatch = 0;
} else {
let newHash = window.location.hash || '';
if (newHash !== '') {
stateRevert = true;
counterLastMatch++;
window.location.hash = e && e.oldURL ? e.oldURL.split('#')[1] : '';
setTimeout(() => {
throw new Error(`Cannot navigate to ${newHash.slice(1)}`);
});
}
}
});
} | [
"function",
"hashchange_",
"(",
"e",
")",
"{",
"if",
"(",
"counterLastMatch",
">",
"1",
")",
"{",
"counterLastMatch",
"=",
"0",
";",
"throw",
"new",
"Error",
"(",
"`",
"${",
"e",
".",
"oldURL",
"}",
"`",
")",
";",
"}",
"// Look for all router3 elements in order",
"Promise",
".",
"all",
"(",
"slice",
".",
"call",
"(",
"document",
".",
"querySelectorAll",
"(",
"selClass",
")",
")",
".",
"map",
"(",
"element",
"=>",
"{",
"/**\n * link router3 with fragment\n * (This process should be decoupled...)\n */",
"return",
"new",
"Promise",
"(",
"resolve",
"=>",
"{",
"let",
"fragments",
"=",
"slice",
".",
"call",
"(",
"element",
".",
"querySelectorAll",
"(",
"'.mdl-fragment'",
")",
")",
";",
"if",
"(",
"element",
".",
"classList",
".",
"contains",
"(",
"'mdl-fragment'",
")",
")",
"{",
"resolve_",
"(",
"element",
",",
"resolve",
")",
";",
"}",
"else",
"{",
"// if there's at least one child fragment, then load all fragments",
"// and resolve their promises",
"Promise",
".",
"all",
"(",
"fragments",
".",
"map",
"(",
"fragment",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"resolve",
"=>",
"resolve_",
"(",
"fragment",
",",
"resolve",
")",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"resolve",
")",
";",
"}",
"}",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"// when everything was loaded...",
"let",
"match",
"=",
"slice",
".",
"call",
"(",
"document",
".",
"querySelectorAll",
"(",
"selClass",
")",
")",
".",
"map",
"(",
"element",
"=>",
"route_",
"(",
"element",
",",
"e",
"&&",
"e",
".",
"newURL",
"?",
"e",
".",
"newURL",
":",
"window",
".",
"location",
".",
"href",
",",
"lastMatch",
")",
")",
".",
"find",
"(",
"result",
"=>",
"result",
")",
";",
"if",
"(",
"match",
")",
"{",
"stateRevert",
"=",
"false",
";",
"lastMatch",
"=",
"match",
";",
"counterLastMatch",
"=",
"0",
";",
"}",
"else",
"{",
"let",
"newHash",
"=",
"window",
".",
"location",
".",
"hash",
"||",
"''",
";",
"if",
"(",
"newHash",
"!==",
"''",
")",
"{",
"stateRevert",
"=",
"true",
";",
"counterLastMatch",
"++",
";",
"window",
".",
"location",
".",
"hash",
"=",
"e",
"&&",
"e",
".",
"oldURL",
"?",
"e",
".",
"oldURL",
".",
"split",
"(",
"'#'",
")",
"[",
"1",
"]",
":",
"''",
";",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"newHash",
".",
"slice",
"(",
"1",
")",
"}",
"`",
")",
";",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Hash Change handler that also is executed when
load event has been dispatched
@private | [
"Hash",
"Change",
"handler",
"that",
"also",
"is",
"executed",
"when",
"load",
"event",
"has",
"been",
"dispatched"
] | 8d148bfce50fe7aff4a0952298e0ade50184c1f7 | https://github.com/m3co/router3/blob/8d148bfce50fe7aff4a0952298e0ade50184c1f7/src/router3.js#L74-L123 |
55,327 | m3co/router3 | src/router3.js | hide_ | function hide_(element) {
if (!element.hidden) {
element.hidden = true;
element.style.visibility = 'hidden';
element.style.height = '0px';
element.style.width = '0px';
/**
* Dispatch hide event if URL's fragment matches with a route
* and router.hidden = true
*
* @event MaterialRouter3#hide
* @type {CustomEvent}
* @property {HTMLElement} router - The router that dispatches
* this event
*/
element.dispatchEvent(new CustomEvent('hide', {
detail: {
router: element
}
}));
}
return true;
} | javascript | function hide_(element) {
if (!element.hidden) {
element.hidden = true;
element.style.visibility = 'hidden';
element.style.height = '0px';
element.style.width = '0px';
/**
* Dispatch hide event if URL's fragment matches with a route
* and router.hidden = true
*
* @event MaterialRouter3#hide
* @type {CustomEvent}
* @property {HTMLElement} router - The router that dispatches
* this event
*/
element.dispatchEvent(new CustomEvent('hide', {
detail: {
router: element
}
}));
}
return true;
} | [
"function",
"hide_",
"(",
"element",
")",
"{",
"if",
"(",
"!",
"element",
".",
"hidden",
")",
"{",
"element",
".",
"hidden",
"=",
"true",
";",
"element",
".",
"style",
".",
"visibility",
"=",
"'hidden'",
";",
"element",
".",
"style",
".",
"height",
"=",
"'0px'",
";",
"element",
".",
"style",
".",
"width",
"=",
"'0px'",
";",
"/**\n * Dispatch hide event if URL's fragment matches with a route\n * and router.hidden = true\n *\n * @event MaterialRouter3#hide\n * @type {CustomEvent}\n * @property {HTMLElement} router - The router that dispatches\n * this event\n */",
"element",
".",
"dispatchEvent",
"(",
"new",
"CustomEvent",
"(",
"'hide'",
",",
"{",
"detail",
":",
"{",
"router",
":",
"element",
"}",
"}",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Hide element and dispatch hide event
@param {HTMLElement} element - The element
@private | [
"Hide",
"element",
"and",
"dispatch",
"hide",
"event"
] | 8d148bfce50fe7aff4a0952298e0ade50184c1f7 | https://github.com/m3co/router3/blob/8d148bfce50fe7aff4a0952298e0ade50184c1f7/src/router3.js#L196-L219 |
55,328 | m3co/router3 | src/router3.js | dispatchShow_ | function dispatchShow_(element, detail) {
/**
* Dispatch show event if URL's fragment matches with a route
*
* @event MaterialRouter3#show
* @type {CustomEvent}
* @property {HTMLElement} router - The router that dispatches
* this event
* @property {String} param1
* @property {String} param2
* @property {String} ...
* @property {String} paramN - The values extracted
* from the URL's fragment. These params go in order of appearance
* from left to right.
*/
element.dispatchEvent(new CustomEvent('show', {
bubbles: true,
detail: detail
}));
} | javascript | function dispatchShow_(element, detail) {
/**
* Dispatch show event if URL's fragment matches with a route
*
* @event MaterialRouter3#show
* @type {CustomEvent}
* @property {HTMLElement} router - The router that dispatches
* this event
* @property {String} param1
* @property {String} param2
* @property {String} ...
* @property {String} paramN - The values extracted
* from the URL's fragment. These params go in order of appearance
* from left to right.
*/
element.dispatchEvent(new CustomEvent('show', {
bubbles: true,
detail: detail
}));
} | [
"function",
"dispatchShow_",
"(",
"element",
",",
"detail",
")",
"{",
"/**\n * Dispatch show event if URL's fragment matches with a route\n *\n * @event MaterialRouter3#show\n * @type {CustomEvent}\n * @property {HTMLElement} router - The router that dispatches\n * this event\n * @property {String} param1\n * @property {String} param2\n * @property {String} ...\n * @property {String} paramN - The values extracted\n * from the URL's fragment. These params go in order of appearance\n * from left to right.\n */",
"element",
".",
"dispatchEvent",
"(",
"new",
"CustomEvent",
"(",
"'show'",
",",
"{",
"bubbles",
":",
"true",
",",
"detail",
":",
"detail",
"}",
")",
")",
";",
"}"
] | Dispatch show event
@param {HTMLElement} element - The element
@param {Object} detail - The extracted params
@private | [
"Dispatch",
"show",
"event"
] | 8d148bfce50fe7aff4a0952298e0ade50184c1f7 | https://github.com/m3co/router3/blob/8d148bfce50fe7aff4a0952298e0ade50184c1f7/src/router3.js#L228-L248 |
55,329 | m3co/router3 | src/router3.js | unhide_ | function unhide_(element) {
if (element.hidden) {
element.hidden = false;
element.style.visibility = 'visible';
element.style.height = null;
element.style.width = null;
/**
* Dispatch unhide even if URL's fragment matches with a route
* and router.hidden = false
*
* @event MaterialRouter3#unhide
* @type {CustomEvent}
* @property {HTMLElement} router - The router that dispatches
* this event
*/
element.dispatchEvent(new CustomEvent('unhide', {
detail: {
router: element
}
}));
}
return true;
} | javascript | function unhide_(element) {
if (element.hidden) {
element.hidden = false;
element.style.visibility = 'visible';
element.style.height = null;
element.style.width = null;
/**
* Dispatch unhide even if URL's fragment matches with a route
* and router.hidden = false
*
* @event MaterialRouter3#unhide
* @type {CustomEvent}
* @property {HTMLElement} router - The router that dispatches
* this event
*/
element.dispatchEvent(new CustomEvent('unhide', {
detail: {
router: element
}
}));
}
return true;
} | [
"function",
"unhide_",
"(",
"element",
")",
"{",
"if",
"(",
"element",
".",
"hidden",
")",
"{",
"element",
".",
"hidden",
"=",
"false",
";",
"element",
".",
"style",
".",
"visibility",
"=",
"'visible'",
";",
"element",
".",
"style",
".",
"height",
"=",
"null",
";",
"element",
".",
"style",
".",
"width",
"=",
"null",
";",
"/**\n * Dispatch unhide even if URL's fragment matches with a route\n * and router.hidden = false\n *\n * @event MaterialRouter3#unhide\n * @type {CustomEvent}\n * @property {HTMLElement} router - The router that dispatches\n * this event\n */",
"element",
".",
"dispatchEvent",
"(",
"new",
"CustomEvent",
"(",
"'unhide'",
",",
"{",
"detail",
":",
"{",
"router",
":",
"element",
"}",
"}",
")",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Unhide element and dispatch unhide event
@param {HTMLElement} element - The element
@private | [
"Unhide",
"element",
"and",
"dispatch",
"unhide",
"event"
] | 8d148bfce50fe7aff4a0952298e0ade50184c1f7 | https://github.com/m3co/router3/blob/8d148bfce50fe7aff4a0952298e0ade50184c1f7/src/router3.js#L256-L279 |
55,330 | m3co/router3 | src/router3.js | match_ | function match_(newHash, parents, hashes) {
parents.push(parents[hashes.length].parentElement.closest(selClass));
hashes.push(parents[hashes.length].getAttribute('hash'));
if (parents[hashes.length]) {
return match_(newHash, parents, hashes);
} else {
return hashes.slice(0, hashes.length).reverse().join('/');
}
} | javascript | function match_(newHash, parents, hashes) {
parents.push(parents[hashes.length].parentElement.closest(selClass));
hashes.push(parents[hashes.length].getAttribute('hash'));
if (parents[hashes.length]) {
return match_(newHash, parents, hashes);
} else {
return hashes.slice(0, hashes.length).reverse().join('/');
}
} | [
"function",
"match_",
"(",
"newHash",
",",
"parents",
",",
"hashes",
")",
"{",
"parents",
".",
"push",
"(",
"parents",
"[",
"hashes",
".",
"length",
"]",
".",
"parentElement",
".",
"closest",
"(",
"selClass",
")",
")",
";",
"hashes",
".",
"push",
"(",
"parents",
"[",
"hashes",
".",
"length",
"]",
".",
"getAttribute",
"(",
"'hash'",
")",
")",
";",
"if",
"(",
"parents",
"[",
"hashes",
".",
"length",
"]",
")",
"{",
"return",
"match_",
"(",
"newHash",
",",
"parents",
",",
"hashes",
")",
";",
"}",
"else",
"{",
"return",
"hashes",
".",
"slice",
"(",
"0",
",",
"hashes",
".",
"length",
")",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"}"
] | Match to chain-hash
@param {String} newHash - The new hash to navigate
@param {Array} parents - The array of pushed parents
@param {Array} hashes - The array of pushed hashes
@private | [
"Match",
"to",
"chain",
"-",
"hash"
] | 8d148bfce50fe7aff4a0952298e0ade50184c1f7 | https://github.com/m3co/router3/blob/8d148bfce50fe7aff4a0952298e0ade50184c1f7/src/router3.js#L289-L298 |
55,331 | muttr/libmuttr | lib/client.js | Client | function Client(identity) {
if (!(this instanceof Client)) {
return new Client(identity);
}
assert(identity instanceof Identity, 'Invalid identity supplied');
this._identity = identity;
this._podhost = utils.getPodHostFromUserID(this._identity.userID);
this._baseUrl = 'https://' + this._podhost;
this._pubkey = this._identity._publicKeyArmored;
} | javascript | function Client(identity) {
if (!(this instanceof Client)) {
return new Client(identity);
}
assert(identity instanceof Identity, 'Invalid identity supplied');
this._identity = identity;
this._podhost = utils.getPodHostFromUserID(this._identity.userID);
this._baseUrl = 'https://' + this._podhost;
this._pubkey = this._identity._publicKeyArmored;
} | [
"function",
"Client",
"(",
"identity",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Client",
")",
")",
"{",
"return",
"new",
"Client",
"(",
"identity",
")",
";",
"}",
"assert",
"(",
"identity",
"instanceof",
"Identity",
",",
"'Invalid identity supplied'",
")",
";",
"this",
".",
"_identity",
"=",
"identity",
";",
"this",
".",
"_podhost",
"=",
"utils",
".",
"getPodHostFromUserID",
"(",
"this",
".",
"_identity",
".",
"userID",
")",
";",
"this",
".",
"_baseUrl",
"=",
"'https://'",
"+",
"this",
".",
"_podhost",
";",
"this",
".",
"_pubkey",
"=",
"this",
".",
"_identity",
".",
"_publicKeyArmored",
";",
"}"
] | HTTPS API Client for MuttrPods
@constructor
@param {object} identity | [
"HTTPS",
"API",
"Client",
"for",
"MuttrPods"
] | 2e4fda9cb2b47b8febe30585f54196d39d79e2e5 | https://github.com/muttr/libmuttr/blob/2e4fda9cb2b47b8febe30585f54196d39d79e2e5/lib/client.js#L25-L36 |
55,332 | Gozala/signalize | core.js | ender | function ender(input) {
return signal(function(next) {
var pending = 0
var state = null
return spawn(input, function(item) {
state = item === START ? (pending = pending + 1,
state) :
item === END ? (pending = pending - 1,
pending ? state : next(item)) :
next(item)
return state
})
})
} | javascript | function ender(input) {
return signal(function(next) {
var pending = 0
var state = null
return spawn(input, function(item) {
state = item === START ? (pending = pending + 1,
state) :
item === END ? (pending = pending - 1,
pending ? state : next(item)) :
next(item)
return state
})
})
} | [
"function",
"ender",
"(",
"input",
")",
"{",
"return",
"signal",
"(",
"function",
"(",
"next",
")",
"{",
"var",
"pending",
"=",
"0",
"var",
"state",
"=",
"null",
"return",
"spawn",
"(",
"input",
",",
"function",
"(",
"item",
")",
"{",
"state",
"=",
"item",
"===",
"START",
"?",
"(",
"pending",
"=",
"pending",
"+",
"1",
",",
"state",
")",
":",
"item",
"===",
"END",
"?",
"(",
"pending",
"=",
"pending",
"-",
"1",
",",
"pending",
"?",
"state",
":",
"next",
"(",
"item",
")",
")",
":",
"next",
"(",
"item",
")",
"return",
"state",
"}",
")",
"}",
")",
"}"
] | Takes input that represents groups wrapped in `START` and `END` items and returns input that contains all items, but `START` & `END` except the last `END`. | [
"Takes",
"input",
"that",
"represents",
"groups",
"wrapped",
"in",
"START",
"and",
"END",
"items",
"and",
"returns",
"input",
"that",
"contains",
"all",
"items",
"but",
"START",
"&",
"END",
"except",
"the",
"last",
"END",
"."
] | 4fcde5d5580b157425045fe32ab09c62f213522b | https://github.com/Gozala/signalize/blob/4fcde5d5580b157425045fe32ab09c62f213522b/core.js#L330-L343 |
55,333 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb/lib/operations/collection_ops.js | bulkWrite | function bulkWrite(coll, operations, options, callback) {
// Add ignoreUndfined
if (coll.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = coll.s.options.ignoreUndefined;
}
// Create the bulk operation
const bulk =
options.ordered === true || options.ordered == null
? coll.initializeOrderedBulkOp(options)
: coll.initializeUnorderedBulkOp(options);
// Do we have a collation
let collation = false;
// for each op go through and add to the bulk
try {
for (let i = 0; i < operations.length; i++) {
// Get the operation type
const key = Object.keys(operations[i])[0];
// Check if we have a collation
if (operations[i][key].collation) {
collation = true;
}
// Pass to the raw bulk
bulk.raw(operations[i]);
}
} catch (err) {
return callback(err, null);
}
// Final options for retryable writes and write concern
let finalOptions = Object.assign({}, options);
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
const capabilities = coll.s.topology.capabilities();
// Did the user pass in a collation, check if our write server supports it
if (collation && capabilities && !capabilities.commandsTakeCollation) {
return callback(new MongoError('server/primary/mongos does not support collation'));
}
// Execute the bulk
bulk.execute(writeCon, finalOptions, (err, r) => {
// We have connection level error
if (!r && err) {
return callback(err, null);
}
r.insertedCount = r.nInserted;
r.matchedCount = r.nMatched;
r.modifiedCount = r.nModified || 0;
r.deletedCount = r.nRemoved;
r.upsertedCount = r.getUpsertedIds().length;
r.upsertedIds = {};
r.insertedIds = {};
// Update the n
r.n = r.insertedCount;
// Inserted documents
const inserted = r.getInsertedIds();
// Map inserted ids
for (let i = 0; i < inserted.length; i++) {
r.insertedIds[inserted[i].index] = inserted[i]._id;
}
// Upserted documents
const upserted = r.getUpsertedIds();
// Map upserted ids
for (let i = 0; i < upserted.length; i++) {
r.upsertedIds[upserted[i].index] = upserted[i]._id;
}
// Return the results
callback(null, r);
});
} | javascript | function bulkWrite(coll, operations, options, callback) {
// Add ignoreUndfined
if (coll.s.options.ignoreUndefined) {
options = Object.assign({}, options);
options.ignoreUndefined = coll.s.options.ignoreUndefined;
}
// Create the bulk operation
const bulk =
options.ordered === true || options.ordered == null
? coll.initializeOrderedBulkOp(options)
: coll.initializeUnorderedBulkOp(options);
// Do we have a collation
let collation = false;
// for each op go through and add to the bulk
try {
for (let i = 0; i < operations.length; i++) {
// Get the operation type
const key = Object.keys(operations[i])[0];
// Check if we have a collation
if (operations[i][key].collation) {
collation = true;
}
// Pass to the raw bulk
bulk.raw(operations[i]);
}
} catch (err) {
return callback(err, null);
}
// Final options for retryable writes and write concern
let finalOptions = Object.assign({}, options);
finalOptions = applyRetryableWrites(finalOptions, coll.s.db);
finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options);
const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
const capabilities = coll.s.topology.capabilities();
// Did the user pass in a collation, check if our write server supports it
if (collation && capabilities && !capabilities.commandsTakeCollation) {
return callback(new MongoError('server/primary/mongos does not support collation'));
}
// Execute the bulk
bulk.execute(writeCon, finalOptions, (err, r) => {
// We have connection level error
if (!r && err) {
return callback(err, null);
}
r.insertedCount = r.nInserted;
r.matchedCount = r.nMatched;
r.modifiedCount = r.nModified || 0;
r.deletedCount = r.nRemoved;
r.upsertedCount = r.getUpsertedIds().length;
r.upsertedIds = {};
r.insertedIds = {};
// Update the n
r.n = r.insertedCount;
// Inserted documents
const inserted = r.getInsertedIds();
// Map inserted ids
for (let i = 0; i < inserted.length; i++) {
r.insertedIds[inserted[i].index] = inserted[i]._id;
}
// Upserted documents
const upserted = r.getUpsertedIds();
// Map upserted ids
for (let i = 0; i < upserted.length; i++) {
r.upsertedIds[upserted[i].index] = upserted[i]._id;
}
// Return the results
callback(null, r);
});
} | [
"function",
"bulkWrite",
"(",
"coll",
",",
"operations",
",",
"options",
",",
"callback",
")",
"{",
"// Add ignoreUndfined",
"if",
"(",
"coll",
".",
"s",
".",
"options",
".",
"ignoreUndefined",
")",
"{",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"options",
".",
"ignoreUndefined",
"=",
"coll",
".",
"s",
".",
"options",
".",
"ignoreUndefined",
";",
"}",
"// Create the bulk operation",
"const",
"bulk",
"=",
"options",
".",
"ordered",
"===",
"true",
"||",
"options",
".",
"ordered",
"==",
"null",
"?",
"coll",
".",
"initializeOrderedBulkOp",
"(",
"options",
")",
":",
"coll",
".",
"initializeUnorderedBulkOp",
"(",
"options",
")",
";",
"// Do we have a collation",
"let",
"collation",
"=",
"false",
";",
"// for each op go through and add to the bulk",
"try",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"operations",
".",
"length",
";",
"i",
"++",
")",
"{",
"// Get the operation type",
"const",
"key",
"=",
"Object",
".",
"keys",
"(",
"operations",
"[",
"i",
"]",
")",
"[",
"0",
"]",
";",
"// Check if we have a collation",
"if",
"(",
"operations",
"[",
"i",
"]",
"[",
"key",
"]",
".",
"collation",
")",
"{",
"collation",
"=",
"true",
";",
"}",
"// Pass to the raw bulk",
"bulk",
".",
"raw",
"(",
"operations",
"[",
"i",
"]",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
"// Final options for retryable writes and write concern",
"let",
"finalOptions",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"finalOptions",
"=",
"applyRetryableWrites",
"(",
"finalOptions",
",",
"coll",
".",
"s",
".",
"db",
")",
";",
"finalOptions",
"=",
"applyWriteConcern",
"(",
"finalOptions",
",",
"{",
"db",
":",
"coll",
".",
"s",
".",
"db",
",",
"collection",
":",
"coll",
"}",
",",
"options",
")",
";",
"const",
"writeCon",
"=",
"finalOptions",
".",
"writeConcern",
"?",
"finalOptions",
".",
"writeConcern",
":",
"{",
"}",
";",
"const",
"capabilities",
"=",
"coll",
".",
"s",
".",
"topology",
".",
"capabilities",
"(",
")",
";",
"// Did the user pass in a collation, check if our write server supports it",
"if",
"(",
"collation",
"&&",
"capabilities",
"&&",
"!",
"capabilities",
".",
"commandsTakeCollation",
")",
"{",
"return",
"callback",
"(",
"new",
"MongoError",
"(",
"'server/primary/mongos does not support collation'",
")",
")",
";",
"}",
"// Execute the bulk",
"bulk",
".",
"execute",
"(",
"writeCon",
",",
"finalOptions",
",",
"(",
"err",
",",
"r",
")",
"=>",
"{",
"// We have connection level error",
"if",
"(",
"!",
"r",
"&&",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
",",
"null",
")",
";",
"}",
"r",
".",
"insertedCount",
"=",
"r",
".",
"nInserted",
";",
"r",
".",
"matchedCount",
"=",
"r",
".",
"nMatched",
";",
"r",
".",
"modifiedCount",
"=",
"r",
".",
"nModified",
"||",
"0",
";",
"r",
".",
"deletedCount",
"=",
"r",
".",
"nRemoved",
";",
"r",
".",
"upsertedCount",
"=",
"r",
".",
"getUpsertedIds",
"(",
")",
".",
"length",
";",
"r",
".",
"upsertedIds",
"=",
"{",
"}",
";",
"r",
".",
"insertedIds",
"=",
"{",
"}",
";",
"// Update the n",
"r",
".",
"n",
"=",
"r",
".",
"insertedCount",
";",
"// Inserted documents",
"const",
"inserted",
"=",
"r",
".",
"getInsertedIds",
"(",
")",
";",
"// Map inserted ids",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"inserted",
".",
"length",
";",
"i",
"++",
")",
"{",
"r",
".",
"insertedIds",
"[",
"inserted",
"[",
"i",
"]",
".",
"index",
"]",
"=",
"inserted",
"[",
"i",
"]",
".",
"_id",
";",
"}",
"// Upserted documents",
"const",
"upserted",
"=",
"r",
".",
"getUpsertedIds",
"(",
")",
";",
"// Map upserted ids",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"upserted",
".",
"length",
";",
"i",
"++",
")",
"{",
"r",
".",
"upsertedIds",
"[",
"upserted",
"[",
"i",
"]",
".",
"index",
"]",
"=",
"upserted",
"[",
"i",
"]",
".",
"_id",
";",
"}",
"// Return the results",
"callback",
"(",
"null",
",",
"r",
")",
";",
"}",
")",
";",
"}"
] | Perform a bulkWrite operation. See Collection.prototype.bulkWrite for more information.
@method
@param {Collection} a Collection instance.
@param {object[]} operations Bulk operations to perform.
@param {object} [options] Optional settings. See Collection.prototype.bulkWrite for a list of options.
@param {Collection~bulkWriteOpCallback} [callback] The command result callback | [
"Perform",
"a",
"bulkWrite",
"operation",
".",
"See",
"Collection",
".",
"prototype",
".",
"bulkWrite",
"for",
"more",
"information",
"."
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/collection_ops.js#L68-L149 |
55,334 | Industryswarm/isnode-mod-data | lib/mongodb/mongodb/lib/operations/collection_ops.js | rename | function rename(coll, newName, options, callback) {
const Collection = require('../collection');
// Check the collection name
checkCollectionName(newName);
// Build the command
const renameCollection = `${coll.s.dbName}.${coll.s.name}`;
const toCollection = `${coll.s.dbName}.${newName}`;
const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false;
const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget };
// Decorate command with writeConcern if supported
applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options);
// Execute against admin
executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => {
if (err) return handleCallback(callback, err, null);
// We have an error
if (doc.errmsg) return handleCallback(callback, toError(doc), null);
try {
return handleCallback(
callback,
null,
new Collection(
coll.s.db,
coll.s.topology,
coll.s.dbName,
newName,
coll.s.pkFactory,
coll.s.options
)
);
} catch (err) {
return handleCallback(callback, toError(err), null);
}
});
} | javascript | function rename(coll, newName, options, callback) {
const Collection = require('../collection');
// Check the collection name
checkCollectionName(newName);
// Build the command
const renameCollection = `${coll.s.dbName}.${coll.s.name}`;
const toCollection = `${coll.s.dbName}.${newName}`;
const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false;
const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget };
// Decorate command with writeConcern if supported
applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options);
// Execute against admin
executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => {
if (err) return handleCallback(callback, err, null);
// We have an error
if (doc.errmsg) return handleCallback(callback, toError(doc), null);
try {
return handleCallback(
callback,
null,
new Collection(
coll.s.db,
coll.s.topology,
coll.s.dbName,
newName,
coll.s.pkFactory,
coll.s.options
)
);
} catch (err) {
return handleCallback(callback, toError(err), null);
}
});
} | [
"function",
"rename",
"(",
"coll",
",",
"newName",
",",
"options",
",",
"callback",
")",
"{",
"const",
"Collection",
"=",
"require",
"(",
"'../collection'",
")",
";",
"// Check the collection name",
"checkCollectionName",
"(",
"newName",
")",
";",
"// Build the command",
"const",
"renameCollection",
"=",
"`",
"${",
"coll",
".",
"s",
".",
"dbName",
"}",
"${",
"coll",
".",
"s",
".",
"name",
"}",
"`",
";",
"const",
"toCollection",
"=",
"`",
"${",
"coll",
".",
"s",
".",
"dbName",
"}",
"${",
"newName",
"}",
"`",
";",
"const",
"dropTarget",
"=",
"typeof",
"options",
".",
"dropTarget",
"===",
"'boolean'",
"?",
"options",
".",
"dropTarget",
":",
"false",
";",
"const",
"cmd",
"=",
"{",
"renameCollection",
":",
"renameCollection",
",",
"to",
":",
"toCollection",
",",
"dropTarget",
":",
"dropTarget",
"}",
";",
"// Decorate command with writeConcern if supported",
"applyWriteConcern",
"(",
"cmd",
",",
"{",
"db",
":",
"coll",
".",
"s",
".",
"db",
",",
"collection",
":",
"coll",
"}",
",",
"options",
")",
";",
"// Execute against admin",
"executeDbAdminCommand",
"(",
"coll",
".",
"s",
".",
"db",
".",
"admin",
"(",
")",
".",
"s",
".",
"db",
",",
"cmd",
",",
"options",
",",
"(",
"err",
",",
"doc",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"handleCallback",
"(",
"callback",
",",
"err",
",",
"null",
")",
";",
"// We have an error",
"if",
"(",
"doc",
".",
"errmsg",
")",
"return",
"handleCallback",
"(",
"callback",
",",
"toError",
"(",
"doc",
")",
",",
"null",
")",
";",
"try",
"{",
"return",
"handleCallback",
"(",
"callback",
",",
"null",
",",
"new",
"Collection",
"(",
"coll",
".",
"s",
".",
"db",
",",
"coll",
".",
"s",
".",
"topology",
",",
"coll",
".",
"s",
".",
"dbName",
",",
"newName",
",",
"coll",
".",
"s",
".",
"pkFactory",
",",
"coll",
".",
"s",
".",
"options",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"handleCallback",
"(",
"callback",
",",
"toError",
"(",
"err",
")",
",",
"null",
")",
";",
"}",
"}",
")",
";",
"}"
] | Rename the collection.
@method
@param {Collection} a Collection instance.
@param {string} newName New name of of the collection.
@param {object} [options] Optional settings. See Collection.prototype.rename for a list of options.
@param {Collection~collectionResultCallback} [callback] The results callback | [
"Rename",
"the",
"collection",
"."
] | 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/collection_ops.js#L1206-L1241 |
55,335 | smbape/node-sem-lib | lib/sem-lib.js | toPositiveInt | function toPositiveInt(num, _default) {
if (isNumeric(num)) {
num = parseInt(num, 10);
} else {
return _default;
}
if (num < 0) {
return _default;
}
return num;
} | javascript | function toPositiveInt(num, _default) {
if (isNumeric(num)) {
num = parseInt(num, 10);
} else {
return _default;
}
if (num < 0) {
return _default;
}
return num;
} | [
"function",
"toPositiveInt",
"(",
"num",
",",
"_default",
")",
"{",
"if",
"(",
"isNumeric",
"(",
"num",
")",
")",
"{",
"num",
"=",
"parseInt",
"(",
"num",
",",
"10",
")",
";",
"}",
"else",
"{",
"return",
"_default",
";",
"}",
"if",
"(",
"num",
"<",
"0",
")",
"{",
"return",
"_default",
";",
"}",
"return",
"num",
";",
"}"
] | Value of parsed interger or default value if not a number or < 0
@param {Any} num value to parse
@param {Interger} _default default value
@return {Interger} parsing result | [
"Value",
"of",
"parsed",
"interger",
"or",
"default",
"value",
"if",
"not",
"a",
"number",
"or",
"<",
"0"
] | 81651c9c1b998ccf219dfd92d93d6a0f8f0c684b | https://github.com/smbape/node-sem-lib/blob/81651c9c1b998ccf219dfd92d93d6a0f8f0c684b/lib/sem-lib.js#L78-L89 |
55,336 | benzhou1/iod | lib/schema.js | validateIODActions | function validateIODActions(IOD, IODOpts) {
// Validate IOD action schema
var actionErr = validateAction(IOD, IODOpts.action, IODOpts.params)
if (actionErr) return actionErr
// Validate IOD action required inputs
var inputErr = validateActionInputs(IOD, IODOpts)
if (inputErr) return inputErr
// Validate IOD action parameter pairs
var pairErr = validateParamPairs(IOD, IODOpts)
if (pairErr) return pairErr
} | javascript | function validateIODActions(IOD, IODOpts) {
// Validate IOD action schema
var actionErr = validateAction(IOD, IODOpts.action, IODOpts.params)
if (actionErr) return actionErr
// Validate IOD action required inputs
var inputErr = validateActionInputs(IOD, IODOpts)
if (inputErr) return inputErr
// Validate IOD action parameter pairs
var pairErr = validateParamPairs(IOD, IODOpts)
if (pairErr) return pairErr
} | [
"function",
"validateIODActions",
"(",
"IOD",
",",
"IODOpts",
")",
"{",
"// Validate IOD action schema",
"var",
"actionErr",
"=",
"validateAction",
"(",
"IOD",
",",
"IODOpts",
".",
"action",
",",
"IODOpts",
".",
"params",
")",
"if",
"(",
"actionErr",
")",
"return",
"actionErr",
"// Validate IOD action required inputs",
"var",
"inputErr",
"=",
"validateActionInputs",
"(",
"IOD",
",",
"IODOpts",
")",
"if",
"(",
"inputErr",
")",
"return",
"inputErr",
"// Validate IOD action parameter pairs",
"var",
"pairErr",
"=",
"validateParamPairs",
"(",
"IOD",
",",
"IODOpts",
")",
"if",
"(",
"pairErr",
")",
"return",
"pairErr",
"}"
] | Validates IOD action schema along with their required inputs.
@param {IOD} IOD - IOD object
@param {Object} IODOpts - IOD options object
@returns {Object | null} - Schema errors | [
"Validates",
"IOD",
"action",
"schema",
"along",
"with",
"their",
"required",
"inputs",
"."
] | a346628f9bc5e4420e4d00e8f21c4cb268b6237c | https://github.com/benzhou1/iod/blob/a346628f9bc5e4420e4d00e8f21c4cb268b6237c/lib/schema.js#L255-L267 |
55,337 | benzhou1/iod | lib/schema.js | validateIODJob | function validateIODJob(IOD, IODOpts) {
var job = IODOpts.job
var errors = []
_.each(job.actions, function(action) {
// Validate every IOD action in job
var err = validateAction(IOD, action.name, action.params)
if (err) return errors.push({
action: action.name,
error: err
})
// Validate every IOD action required inputs in job
var inputErr = validateActionInputs(IOD, {
action: action.name,
params: action.params
})
if (inputErr) return errors.push({
action: action.name,
error: inputErr
})
// Validate every IOD action parameter pairs in job
var pairErr = validateParamPairs(IOD, {
action: action.name,
params: action.params
})
if (pairErr) return errors.push({
action: action.name,
error: pairErr
})
})
if (errors.length) return errors
} | javascript | function validateIODJob(IOD, IODOpts) {
var job = IODOpts.job
var errors = []
_.each(job.actions, function(action) {
// Validate every IOD action in job
var err = validateAction(IOD, action.name, action.params)
if (err) return errors.push({
action: action.name,
error: err
})
// Validate every IOD action required inputs in job
var inputErr = validateActionInputs(IOD, {
action: action.name,
params: action.params
})
if (inputErr) return errors.push({
action: action.name,
error: inputErr
})
// Validate every IOD action parameter pairs in job
var pairErr = validateParamPairs(IOD, {
action: action.name,
params: action.params
})
if (pairErr) return errors.push({
action: action.name,
error: pairErr
})
})
if (errors.length) return errors
} | [
"function",
"validateIODJob",
"(",
"IOD",
",",
"IODOpts",
")",
"{",
"var",
"job",
"=",
"IODOpts",
".",
"job",
"var",
"errors",
"=",
"[",
"]",
"_",
".",
"each",
"(",
"job",
".",
"actions",
",",
"function",
"(",
"action",
")",
"{",
"// Validate every IOD action in job",
"var",
"err",
"=",
"validateAction",
"(",
"IOD",
",",
"action",
".",
"name",
",",
"action",
".",
"params",
")",
"if",
"(",
"err",
")",
"return",
"errors",
".",
"push",
"(",
"{",
"action",
":",
"action",
".",
"name",
",",
"error",
":",
"err",
"}",
")",
"// Validate every IOD action required inputs in job",
"var",
"inputErr",
"=",
"validateActionInputs",
"(",
"IOD",
",",
"{",
"action",
":",
"action",
".",
"name",
",",
"params",
":",
"action",
".",
"params",
"}",
")",
"if",
"(",
"inputErr",
")",
"return",
"errors",
".",
"push",
"(",
"{",
"action",
":",
"action",
".",
"name",
",",
"error",
":",
"inputErr",
"}",
")",
"// Validate every IOD action parameter pairs in job",
"var",
"pairErr",
"=",
"validateParamPairs",
"(",
"IOD",
",",
"{",
"action",
":",
"action",
".",
"name",
",",
"params",
":",
"action",
".",
"params",
"}",
")",
"if",
"(",
"pairErr",
")",
"return",
"errors",
".",
"push",
"(",
"{",
"action",
":",
"action",
".",
"name",
",",
"error",
":",
"pairErr",
"}",
")",
"}",
")",
"if",
"(",
"errors",
".",
"length",
")",
"return",
"errors",
"}"
] | Validates IOD action schema for every action in job, along with their required inputs.
@param {IOD} IOD - IOD object
@param {Object} IODOpts - IOD options object
@returns {Object | null} - Schema errors | [
"Validates",
"IOD",
"action",
"schema",
"for",
"every",
"action",
"in",
"job",
"along",
"with",
"their",
"required",
"inputs",
"."
] | a346628f9bc5e4420e4d00e8f21c4cb268b6237c | https://github.com/benzhou1/iod/blob/a346628f9bc5e4420e4d00e8f21c4cb268b6237c/lib/schema.js#L276-L310 |
55,338 | Miramac/dir-util | lib/creator.js | create | function create(options, cb) {
options.force = (options.force) ? options.force : false;
options.preserve = (options.preserve) ? options.preserve : true;
options.password = getPwHash(options.password);
console.log('Gernerating directories with folling options:\n', options, '\n');
if(options.test) {return;}
//create directory
if(options.force || !fs.existsSync(options.dest)) {
wrench.mkdirSyncRecursive(options.dest);
wrench.copyDirSyncRecursive(options.src, options.dest, { preserve: options.preserve });
}
if(options.files.length) {
_.each(options.files, function(file) {
fs.exists(path.join(options.dest,options.pwfile), function(exists) {
if(!exists || options.force || file.force) {
fs.writeFile(path.join(options.dest,strReplace(file.name, options)), strReplace(file.data, options), function(err){
if(err) {throw err;}
});
}
});
});
}
//Search and replace
replace(options.dest, {
filters: ['index\.php$', '\.htaccess']
, type: 'replace'
, values: [{
user: options.user
, root: options.root
, project: options.project
, title: options.title
, userDir: options.userDir
, pwfile: options.pwfile
}]
}, function(err, data) {
if(cb) {
cb(err, data);
}
});
} | javascript | function create(options, cb) {
options.force = (options.force) ? options.force : false;
options.preserve = (options.preserve) ? options.preserve : true;
options.password = getPwHash(options.password);
console.log('Gernerating directories with folling options:\n', options, '\n');
if(options.test) {return;}
//create directory
if(options.force || !fs.existsSync(options.dest)) {
wrench.mkdirSyncRecursive(options.dest);
wrench.copyDirSyncRecursive(options.src, options.dest, { preserve: options.preserve });
}
if(options.files.length) {
_.each(options.files, function(file) {
fs.exists(path.join(options.dest,options.pwfile), function(exists) {
if(!exists || options.force || file.force) {
fs.writeFile(path.join(options.dest,strReplace(file.name, options)), strReplace(file.data, options), function(err){
if(err) {throw err;}
});
}
});
});
}
//Search and replace
replace(options.dest, {
filters: ['index\.php$', '\.htaccess']
, type: 'replace'
, values: [{
user: options.user
, root: options.root
, project: options.project
, title: options.title
, userDir: options.userDir
, pwfile: options.pwfile
}]
}, function(err, data) {
if(cb) {
cb(err, data);
}
});
} | [
"function",
"create",
"(",
"options",
",",
"cb",
")",
"{",
"options",
".",
"force",
"=",
"(",
"options",
".",
"force",
")",
"?",
"options",
".",
"force",
":",
"false",
";",
"options",
".",
"preserve",
"=",
"(",
"options",
".",
"preserve",
")",
"?",
"options",
".",
"preserve",
":",
"true",
";",
"options",
".",
"password",
"=",
"getPwHash",
"(",
"options",
".",
"password",
")",
";",
"console",
".",
"log",
"(",
"'Gernerating directories with folling options:\\n'",
",",
"options",
",",
"'\\n'",
")",
";",
"if",
"(",
"options",
".",
"test",
")",
"{",
"return",
";",
"}",
"//create directory",
"if",
"(",
"options",
".",
"force",
"||",
"!",
"fs",
".",
"existsSync",
"(",
"options",
".",
"dest",
")",
")",
"{",
"wrench",
".",
"mkdirSyncRecursive",
"(",
"options",
".",
"dest",
")",
";",
"wrench",
".",
"copyDirSyncRecursive",
"(",
"options",
".",
"src",
",",
"options",
".",
"dest",
",",
"{",
"preserve",
":",
"options",
".",
"preserve",
"}",
")",
";",
"}",
"if",
"(",
"options",
".",
"files",
".",
"length",
")",
"{",
"_",
".",
"each",
"(",
"options",
".",
"files",
",",
"function",
"(",
"file",
")",
"{",
"fs",
".",
"exists",
"(",
"path",
".",
"join",
"(",
"options",
".",
"dest",
",",
"options",
".",
"pwfile",
")",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
"||",
"options",
".",
"force",
"||",
"file",
".",
"force",
")",
"{",
"fs",
".",
"writeFile",
"(",
"path",
".",
"join",
"(",
"options",
".",
"dest",
",",
"strReplace",
"(",
"file",
".",
"name",
",",
"options",
")",
")",
",",
"strReplace",
"(",
"file",
".",
"data",
",",
"options",
")",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
"//Search and replace ",
"replace",
"(",
"options",
".",
"dest",
",",
"{",
"filters",
":",
"[",
"'index\\.php$'",
",",
"'\\.htaccess'",
"]",
",",
"type",
":",
"'replace'",
",",
"values",
":",
"[",
"{",
"user",
":",
"options",
".",
"user",
",",
"root",
":",
"options",
".",
"root",
",",
"project",
":",
"options",
".",
"project",
",",
"title",
":",
"options",
".",
"title",
",",
"userDir",
":",
"options",
".",
"userDir",
",",
"pwfile",
":",
"options",
".",
"pwfile",
"}",
"]",
"}",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"cb",
")",
"{",
"cb",
"(",
"err",
",",
"data",
")",
";",
"}",
"}",
")",
";",
"}"
] | Used to create user directory with htacces password-file from a template folder. Will need a rework for more generic functionality...
Deep copy src to the dest
Search and replace in dest | [
"Used",
"to",
"create",
"user",
"directory",
"with",
"htacces",
"password",
"-",
"file",
"from",
"a",
"template",
"folder",
".",
"Will",
"need",
"a",
"rework",
"for",
"more",
"generic",
"functionality",
"..."
] | 2ffb6fce91e1540b29d924b38225c161a8e646ef | https://github.com/Miramac/dir-util/blob/2ffb6fce91e1540b29d924b38225c161a8e646ef/lib/creator.js#L19-L59 |
55,339 | Miramac/dir-util | lib/creator.js | replace | function replace(root, options, callback) {
analyser.readDir(root, options, function(err, files) {
files = _.flatten(files);
_.each(files, function(file){
fs.readFile(file, 'UTF-8', function(err, data) {
if(err) {throw err;}
var i, value;
for(i=0; i<options.values.length; i++) {
value = options.values[i];
if(value === Object(value)) {
for(var key in value) {
if(value.hasOwnProperty(key)) {
data = data.replace(new RegExp('{{'+key+'}}','g'), value[key]);
}
}
}
fs.writeFile(file, data);
}
});
});
if(callback) {
callback(err, files);
}
});
} | javascript | function replace(root, options, callback) {
analyser.readDir(root, options, function(err, files) {
files = _.flatten(files);
_.each(files, function(file){
fs.readFile(file, 'UTF-8', function(err, data) {
if(err) {throw err;}
var i, value;
for(i=0; i<options.values.length; i++) {
value = options.values[i];
if(value === Object(value)) {
for(var key in value) {
if(value.hasOwnProperty(key)) {
data = data.replace(new RegExp('{{'+key+'}}','g'), value[key]);
}
}
}
fs.writeFile(file, data);
}
});
});
if(callback) {
callback(err, files);
}
});
} | [
"function",
"replace",
"(",
"root",
",",
"options",
",",
"callback",
")",
"{",
"analyser",
".",
"readDir",
"(",
"root",
",",
"options",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"files",
"=",
"_",
".",
"flatten",
"(",
"files",
")",
";",
"_",
".",
"each",
"(",
"files",
",",
"function",
"(",
"file",
")",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"'UTF-8'",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"var",
"i",
",",
"value",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"values",
".",
"length",
";",
"i",
"++",
")",
"{",
"value",
"=",
"options",
".",
"values",
"[",
"i",
"]",
";",
"if",
"(",
"value",
"===",
"Object",
"(",
"value",
")",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"value",
")",
"{",
"if",
"(",
"value",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"data",
"=",
"data",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'{{'",
"+",
"key",
"+",
"'}}'",
",",
"'g'",
")",
",",
"value",
"[",
"key",
"]",
")",
";",
"}",
"}",
"}",
"fs",
".",
"writeFile",
"(",
"file",
",",
"data",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
",",
"files",
")",
";",
"}",
"}",
")",
";",
"}"
] | search and replace in files file | [
"search",
"and",
"replace",
"in",
"files",
"file"
] | 2ffb6fce91e1540b29d924b38225c161a8e646ef | https://github.com/Miramac/dir-util/blob/2ffb6fce91e1540b29d924b38225c161a8e646ef/lib/creator.js#L75-L99 |
55,340 | calaverastech/grunt-pkgbuild | tasks/pkgbuild.js | abs_path | function abs_path(file, cwd) {
if(!file || file.length === 0) {
return null;
}
function get_path(p) {
var dir = grunt.file.isPathAbsolute(p) ? "" : (cwd || ".");
return path.join(dir, p);
}
if(_.isArray(file)) {
return _.map(file, function(p) {
return get_path(p);
});
} else {
return get_path(file);
}
} | javascript | function abs_path(file, cwd) {
if(!file || file.length === 0) {
return null;
}
function get_path(p) {
var dir = grunt.file.isPathAbsolute(p) ? "" : (cwd || ".");
return path.join(dir, p);
}
if(_.isArray(file)) {
return _.map(file, function(p) {
return get_path(p);
});
} else {
return get_path(file);
}
} | [
"function",
"abs_path",
"(",
"file",
",",
"cwd",
")",
"{",
"if",
"(",
"!",
"file",
"||",
"file",
".",
"length",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"function",
"get_path",
"(",
"p",
")",
"{",
"var",
"dir",
"=",
"grunt",
".",
"file",
".",
"isPathAbsolute",
"(",
"p",
")",
"?",
"\"\"",
":",
"(",
"cwd",
"||",
"\".\"",
")",
";",
"return",
"path",
".",
"join",
"(",
"dir",
",",
"p",
")",
";",
"}",
"if",
"(",
"_",
".",
"isArray",
"(",
"file",
")",
")",
"{",
"return",
"_",
".",
"map",
"(",
"file",
",",
"function",
"(",
"p",
")",
"{",
"return",
"get_path",
"(",
"p",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"get_path",
"(",
"file",
")",
";",
"}",
"}"
] | get absolute path | [
"get",
"absolute",
"path"
] | f1414516a0cffc1d7d7c0fa63861d3acbef054bd | https://github.com/calaverastech/grunt-pkgbuild/blob/f1414516a0cffc1d7d7c0fa63861d3acbef054bd/tasks/pkgbuild.js#L147-L164 |
55,341 | peteromano/jetrunner | example/vendor/mocha/lib/ms.js | format | function format(ms) {
if (ms == d) return Math.round(ms / d) + ' day';
if (ms > d) return Math.round(ms / d) + ' days';
if (ms == h) return Math.round(ms / h) + ' hour';
if (ms > h) return Math.round(ms / h) + ' hours';
if (ms == m) return Math.round(ms / m) + ' minute';
if (ms > m) return Math.round(ms / m) + ' minutes';
if (ms == s) return Math.round(ms / s) + ' second';
if (ms > s) return Math.round(ms / s) + ' seconds';
return ms + ' ms';
} | javascript | function format(ms) {
if (ms == d) return Math.round(ms / d) + ' day';
if (ms > d) return Math.round(ms / d) + ' days';
if (ms == h) return Math.round(ms / h) + ' hour';
if (ms > h) return Math.round(ms / h) + ' hours';
if (ms == m) return Math.round(ms / m) + ' minute';
if (ms > m) return Math.round(ms / m) + ' minutes';
if (ms == s) return Math.round(ms / s) + ' second';
if (ms > s) return Math.round(ms / s) + ' seconds';
return ms + ' ms';
} | [
"function",
"format",
"(",
"ms",
")",
"{",
"if",
"(",
"ms",
"==",
"d",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"d",
")",
"+",
"' day'",
";",
"if",
"(",
"ms",
">",
"d",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"d",
")",
"+",
"' days'",
";",
"if",
"(",
"ms",
"==",
"h",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"h",
")",
"+",
"' hour'",
";",
"if",
"(",
"ms",
">",
"h",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"h",
")",
"+",
"' hours'",
";",
"if",
"(",
"ms",
"==",
"m",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"m",
")",
"+",
"' minute'",
";",
"if",
"(",
"ms",
">",
"m",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"m",
")",
"+",
"' minutes'",
";",
"if",
"(",
"ms",
"==",
"s",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"s",
")",
"+",
"' second'",
";",
"if",
"(",
"ms",
">",
"s",
")",
"return",
"Math",
".",
"round",
"(",
"ms",
"/",
"s",
")",
"+",
"' seconds'",
";",
"return",
"ms",
"+",
"' ms'",
";",
"}"
] | Format the given `ms`.
@param {Number} ms
@return {String}
@api public | [
"Format",
"the",
"given",
"ms",
"."
] | 1882e0ee83d31fe1c799b42848c8c1357a62c995 | https://github.com/peteromano/jetrunner/blob/1882e0ee83d31fe1c799b42848c8c1357a62c995/example/vendor/mocha/lib/ms.js#L71-L81 |
55,342 | christophercrouzet/pillr | lib/components/render_page.js | getPartials | function getPartials(file, sourcePath, templates, customPartialName, callback) {
const { partials } = templates;
if (file.meta.customLayout === undefined) {
async.nextTick(callback, null, partials);
return;
}
const customLayoutPath = path.join(
sourcePath,
path.resolve(path.sep, file.meta.filePath.dir, file.meta.customLayout)
);
read(customLayoutPath, ReadMode.UTF8, (error, data) => {
if (error) {
console.error(`${file.path}: Could not load the custom layout`);
async.nextTick(callback, error);
return;
}
const customPartials = { [customPartialName]: data };
async.nextTick(callback, null, Object.assign({}, partials, customPartials));
});
} | javascript | function getPartials(file, sourcePath, templates, customPartialName, callback) {
const { partials } = templates;
if (file.meta.customLayout === undefined) {
async.nextTick(callback, null, partials);
return;
}
const customLayoutPath = path.join(
sourcePath,
path.resolve(path.sep, file.meta.filePath.dir, file.meta.customLayout)
);
read(customLayoutPath, ReadMode.UTF8, (error, data) => {
if (error) {
console.error(`${file.path}: Could not load the custom layout`);
async.nextTick(callback, error);
return;
}
const customPartials = { [customPartialName]: data };
async.nextTick(callback, null, Object.assign({}, partials, customPartials));
});
} | [
"function",
"getPartials",
"(",
"file",
",",
"sourcePath",
",",
"templates",
",",
"customPartialName",
",",
"callback",
")",
"{",
"const",
"{",
"partials",
"}",
"=",
"templates",
";",
"if",
"(",
"file",
".",
"meta",
".",
"customLayout",
"===",
"undefined",
")",
"{",
"async",
".",
"nextTick",
"(",
"callback",
",",
"null",
",",
"partials",
")",
";",
"return",
";",
"}",
"const",
"customLayoutPath",
"=",
"path",
".",
"join",
"(",
"sourcePath",
",",
"path",
".",
"resolve",
"(",
"path",
".",
"sep",
",",
"file",
".",
"meta",
".",
"filePath",
".",
"dir",
",",
"file",
".",
"meta",
".",
"customLayout",
")",
")",
";",
"read",
"(",
"customLayoutPath",
",",
"ReadMode",
".",
"UTF8",
",",
"(",
"error",
",",
"data",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"file",
".",
"path",
"}",
"`",
")",
";",
"async",
".",
"nextTick",
"(",
"callback",
",",
"error",
")",
";",
"return",
";",
"}",
"const",
"customPartials",
"=",
"{",
"[",
"customPartialName",
"]",
":",
"data",
"}",
";",
"async",
".",
"nextTick",
"(",
"callback",
",",
"null",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"partials",
",",
"customPartials",
")",
")",
";",
"}",
")",
";",
"}"
] | Retrieve the template partials. | [
"Retrieve",
"the",
"template",
"partials",
"."
] | 411ccd344a03478776c4e8d2e2f9bdc45dc8ee45 | https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/components/render_page.js#L12-L33 |
55,343 | christophercrouzet/pillr | lib/components/render_page.js | render | function render(file, layout, context, partials, callback) {
try {
const data = mustache.render(layout, context, partials);
async.nextTick(callback, null, data);
} catch (error) {
console.error(`${file.path}: Could not render the layout`);
async.nextTick(callback, error);
}
} | javascript | function render(file, layout, context, partials, callback) {
try {
const data = mustache.render(layout, context, partials);
async.nextTick(callback, null, data);
} catch (error) {
console.error(`${file.path}: Could not render the layout`);
async.nextTick(callback, error);
}
} | [
"function",
"render",
"(",
"file",
",",
"layout",
",",
"context",
",",
"partials",
",",
"callback",
")",
"{",
"try",
"{",
"const",
"data",
"=",
"mustache",
".",
"render",
"(",
"layout",
",",
"context",
",",
"partials",
")",
";",
"async",
".",
"nextTick",
"(",
"callback",
",",
"null",
",",
"data",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"file",
".",
"path",
"}",
"`",
")",
";",
"async",
".",
"nextTick",
"(",
"callback",
",",
"error",
")",
";",
"}",
"}"
] | Render the page. | [
"Render",
"the",
"page",
"."
] | 411ccd344a03478776c4e8d2e2f9bdc45dc8ee45 | https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/components/render_page.js#L36-L44 |
55,344 | christophercrouzet/pillr | lib/components/render_page.js | wrapFunctions | function wrapFunctions(fns, file, files) {
return Object.entries(fns)
.reduce((obj1, [groupName, group]) => {
return Object.assign(obj1, {
[groupName]: Object.entries(group)
.reduce((obj2, [fnName, fn]) => {
return Object.assign(obj2, { [fnName]: fn(file, files) });
}, {})
});
}, {});
} | javascript | function wrapFunctions(fns, file, files) {
return Object.entries(fns)
.reduce((obj1, [groupName, group]) => {
return Object.assign(obj1, {
[groupName]: Object.entries(group)
.reduce((obj2, [fnName, fn]) => {
return Object.assign(obj2, { [fnName]: fn(file, files) });
}, {})
});
}, {});
} | [
"function",
"wrapFunctions",
"(",
"fns",
",",
"file",
",",
"files",
")",
"{",
"return",
"Object",
".",
"entries",
"(",
"fns",
")",
".",
"reduce",
"(",
"(",
"obj1",
",",
"[",
"groupName",
",",
"group",
"]",
")",
"=>",
"{",
"return",
"Object",
".",
"assign",
"(",
"obj1",
",",
"{",
"[",
"groupName",
"]",
":",
"Object",
".",
"entries",
"(",
"group",
")",
".",
"reduce",
"(",
"(",
"obj2",
",",
"[",
"fnName",
",",
"fn",
"]",
")",
"=>",
"{",
"return",
"Object",
".",
"assign",
"(",
"obj2",
",",
"{",
"[",
"fnName",
"]",
":",
"fn",
"(",
"file",
",",
"files",
")",
"}",
")",
";",
"}",
",",
"{",
"}",
")",
"}",
")",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] | Wrap the template functions to pass them the current file. | [
"Wrap",
"the",
"template",
"functions",
"to",
"pass",
"them",
"the",
"current",
"file",
"."
] | 411ccd344a03478776c4e8d2e2f9bdc45dc8ee45 | https://github.com/christophercrouzet/pillr/blob/411ccd344a03478776c4e8d2e2f9bdc45dc8ee45/lib/components/render_page.js#L48-L58 |
55,345 | huafu/ember-dev-fixtures | private/utils/dev-fixtures/module.js | function (fullPath, autoDefine) {
if (!this.instances[fullPath]) {
this.instances[fullPath] = DevFixturesModule.create({
fullPath: fullPath,
autoDefine: Boolean(autoDefine)
});
}
return this.instances[fullPath];
} | javascript | function (fullPath, autoDefine) {
if (!this.instances[fullPath]) {
this.instances[fullPath] = DevFixturesModule.create({
fullPath: fullPath,
autoDefine: Boolean(autoDefine)
});
}
return this.instances[fullPath];
} | [
"function",
"(",
"fullPath",
",",
"autoDefine",
")",
"{",
"if",
"(",
"!",
"this",
".",
"instances",
"[",
"fullPath",
"]",
")",
"{",
"this",
".",
"instances",
"[",
"fullPath",
"]",
"=",
"DevFixturesModule",
".",
"create",
"(",
"{",
"fullPath",
":",
"fullPath",
",",
"autoDefine",
":",
"Boolean",
"(",
"autoDefine",
")",
"}",
")",
";",
"}",
"return",
"this",
".",
"instances",
"[",
"fullPath",
"]",
";",
"}"
] | Get the instance of the module for the given full path
@method for
@param {string} fullPath
@param {boolean} autoDefine
@return {DevFixturesModule} | [
"Get",
"the",
"instance",
"of",
"the",
"module",
"for",
"the",
"given",
"full",
"path"
] | 811ed4d339c2dc840d5b297b5b244726cf1339ca | https://github.com/huafu/ember-dev-fixtures/blob/811ed4d339c2dc840d5b297b5b244726cf1339ca/private/utils/dev-fixtures/module.js#L143-L151 |
|
55,346 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( obj ) {
var clone;
// Array.
if ( obj && ( obj instanceof Array ) ) {
clone = [];
for ( var i = 0; i < obj.length; i++ )
clone[ i ] = CKEDITOR.tools.clone( obj[ i ] );
return clone;
}
// "Static" types.
if ( obj === null || ( typeof( obj ) != 'object' ) || ( obj instanceof String ) || ( obj instanceof Number ) || ( obj instanceof Boolean ) || ( obj instanceof Date ) || ( obj instanceof RegExp ) )
return obj;
// DOM objects and window.
if ( obj.nodeType || obj.window === obj )
return obj;
// Objects.
clone = new obj.constructor();
for ( var propertyName in obj ) {
var property = obj[ propertyName ];
clone[ propertyName ] = CKEDITOR.tools.clone( property );
}
return clone;
} | javascript | function( obj ) {
var clone;
// Array.
if ( obj && ( obj instanceof Array ) ) {
clone = [];
for ( var i = 0; i < obj.length; i++ )
clone[ i ] = CKEDITOR.tools.clone( obj[ i ] );
return clone;
}
// "Static" types.
if ( obj === null || ( typeof( obj ) != 'object' ) || ( obj instanceof String ) || ( obj instanceof Number ) || ( obj instanceof Boolean ) || ( obj instanceof Date ) || ( obj instanceof RegExp ) )
return obj;
// DOM objects and window.
if ( obj.nodeType || obj.window === obj )
return obj;
// Objects.
clone = new obj.constructor();
for ( var propertyName in obj ) {
var property = obj[ propertyName ];
clone[ propertyName ] = CKEDITOR.tools.clone( property );
}
return clone;
} | [
"function",
"(",
"obj",
")",
"{",
"var",
"clone",
";",
"// Array.",
"if",
"(",
"obj",
"&&",
"(",
"obj",
"instanceof",
"Array",
")",
")",
"{",
"clone",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"obj",
".",
"length",
";",
"i",
"++",
")",
"clone",
"[",
"i",
"]",
"=",
"CKEDITOR",
".",
"tools",
".",
"clone",
"(",
"obj",
"[",
"i",
"]",
")",
";",
"return",
"clone",
";",
"}",
"// \"Static\" types.",
"if",
"(",
"obj",
"===",
"null",
"||",
"(",
"typeof",
"(",
"obj",
")",
"!=",
"'object'",
")",
"||",
"(",
"obj",
"instanceof",
"String",
")",
"||",
"(",
"obj",
"instanceof",
"Number",
")",
"||",
"(",
"obj",
"instanceof",
"Boolean",
")",
"||",
"(",
"obj",
"instanceof",
"Date",
")",
"||",
"(",
"obj",
"instanceof",
"RegExp",
")",
")",
"return",
"obj",
";",
"// DOM objects and window.",
"if",
"(",
"obj",
".",
"nodeType",
"||",
"obj",
".",
"window",
"===",
"obj",
")",
"return",
"obj",
";",
"// Objects.",
"clone",
"=",
"new",
"obj",
".",
"constructor",
"(",
")",
";",
"for",
"(",
"var",
"propertyName",
"in",
"obj",
")",
"{",
"var",
"property",
"=",
"obj",
"[",
"propertyName",
"]",
";",
"clone",
"[",
"propertyName",
"]",
"=",
"CKEDITOR",
".",
"tools",
".",
"clone",
"(",
"property",
")",
";",
"}",
"return",
"clone",
";",
"}"
] | Creates a deep copy of an object.
**Note**: Recursive references are not supported.
var obj = {
name: 'John',
cars: {
Mercedes: { color: 'blue' },
Porsche: { color: 'red' }
}
};
var clone = CKEDITOR.tools.clone( obj );
clone.name = 'Paul';
clone.cars.Porsche.color = 'silver';
alert( obj.name ); // 'John'
alert( clone.name ); // 'Paul'
alert( obj.cars.Porsche.color ); // 'red'
alert( clone.cars.Porsche.color ); // 'silver'
@param {Object} object The object to be cloned.
@returns {Object} The object clone. | [
"Creates",
"a",
"deep",
"copy",
"of",
"an",
"object",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L95-L125 |
|
55,347 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( str, keepCase ) {
return str.charAt( 0 ).toUpperCase() + ( keepCase ? str.slice( 1 ) : str.slice( 1 ).toLowerCase() );
} | javascript | function( str, keepCase ) {
return str.charAt( 0 ).toUpperCase() + ( keepCase ? str.slice( 1 ) : str.slice( 1 ).toLowerCase() );
} | [
"function",
"(",
"str",
",",
"keepCase",
")",
"{",
"return",
"str",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"(",
"keepCase",
"?",
"str",
".",
"slice",
"(",
"1",
")",
":",
"str",
".",
"slice",
"(",
"1",
")",
".",
"toLowerCase",
"(",
")",
")",
";",
"}"
] | Turns the first letter of a string to upper-case.
@param {String} str
@param {Boolean} [keepCase] Keep the case of 2nd to last letter.
@returns {String} | [
"Turns",
"the",
"first",
"letter",
"of",
"a",
"string",
"to",
"upper",
"-",
"case",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L134-L136 |
|
55,348 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( property, value, asString ) {
if ( asString )
return cssVendorPrefix + property + ':' + value + ';' + property + ':' + value;
var ret = {};
ret[ property ] = value;
ret[ cssVendorPrefix + property ] = value;
return ret;
} | javascript | function( property, value, asString ) {
if ( asString )
return cssVendorPrefix + property + ':' + value + ';' + property + ':' + value;
var ret = {};
ret[ property ] = value;
ret[ cssVendorPrefix + property ] = value;
return ret;
} | [
"function",
"(",
"property",
",",
"value",
",",
"asString",
")",
"{",
"if",
"(",
"asString",
")",
"return",
"cssVendorPrefix",
"+",
"property",
"+",
"':'",
"+",
"value",
"+",
"';'",
"+",
"property",
"+",
"':'",
"+",
"value",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"ret",
"[",
"property",
"]",
"=",
"value",
";",
"ret",
"[",
"cssVendorPrefix",
"+",
"property",
"]",
"=",
"value",
";",
"return",
"ret",
";",
"}"
] | Generates an object or a string containing vendor-specific and vendor-free CSS properties.
CKEDITOR.tools.cssVendorPrefix( 'border-radius', '0', true );
// On Firefox: '-moz-border-radius:0;border-radius:0'
// On Chrome: '-webkit-border-radius:0;border-radius:0'
@param {String} property The CSS property name.
@param {String} value The CSS value.
@param {Boolean} [asString=false] If `true`, then the returned value will be a CSS string.
@returns {Object/String} The object containing CSS properties or its stringified version. | [
"Generates",
"an",
"object",
"or",
"a",
"string",
"containing",
"vendor",
"-",
"specific",
"and",
"vendor",
"-",
"free",
"CSS",
"properties",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L267-L276 |
|
55,349 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( originalFunction, functionBuilder ) {
var newFn = functionBuilder( originalFunction );
newFn.prototype = originalFunction.prototype;
return newFn;
} | javascript | function( originalFunction, functionBuilder ) {
var newFn = functionBuilder( originalFunction );
newFn.prototype = originalFunction.prototype;
return newFn;
} | [
"function",
"(",
"originalFunction",
",",
"functionBuilder",
")",
"{",
"var",
"newFn",
"=",
"functionBuilder",
"(",
"originalFunction",
")",
";",
"newFn",
".",
"prototype",
"=",
"originalFunction",
".",
"prototype",
";",
"return",
"newFn",
";",
"}"
] | Creates a function override.
var obj = {
myFunction: function( name ) {
alert( 'Name: ' + name );
}
};
obj.myFunction = CKEDITOR.tools.override( obj.myFunction, function( myFunctionOriginal ) {
return function( name ) {
alert( 'Overriden name: ' + name );
myFunctionOriginal.call( this, name );
};
} );
@param {Function} originalFunction The function to be overridden.
@param {Function} functionBuilder A function that returns the new
function. The original function reference will be passed to this function.
@returns {Function} The new function. | [
"Creates",
"a",
"function",
"override",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L429-L433 |
|
55,350 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( styleText, nativeNormalize ) {
var props = [],
name,
parsedProps = CKEDITOR.tools.parseCssText( styleText, true, nativeNormalize );
for ( name in parsedProps )
props.push( name + ':' + parsedProps[ name ] );
props.sort();
return props.length ? ( props.join( ';' ) + ';' ) : '';
} | javascript | function( styleText, nativeNormalize ) {
var props = [],
name,
parsedProps = CKEDITOR.tools.parseCssText( styleText, true, nativeNormalize );
for ( name in parsedProps )
props.push( name + ':' + parsedProps[ name ] );
props.sort();
return props.length ? ( props.join( ';' ) + ';' ) : '';
} | [
"function",
"(",
"styleText",
",",
"nativeNormalize",
")",
"{",
"var",
"props",
"=",
"[",
"]",
",",
"name",
",",
"parsedProps",
"=",
"CKEDITOR",
".",
"tools",
".",
"parseCssText",
"(",
"styleText",
",",
"true",
",",
"nativeNormalize",
")",
";",
"for",
"(",
"name",
"in",
"parsedProps",
")",
"props",
".",
"push",
"(",
"name",
"+",
"':'",
"+",
"parsedProps",
"[",
"name",
"]",
")",
";",
"props",
".",
"sort",
"(",
")",
";",
"return",
"props",
".",
"length",
"?",
"(",
"props",
".",
"join",
"(",
"';'",
")",
"+",
"';'",
")",
":",
"''",
";",
"}"
] | Normalizes CSS data in order to avoid differences in the style attribute.
@param {String} styleText The style data to be normalized.
@param {Boolean} [nativeNormalize=false] Parse the data using the browser.
@returns {String} The normalized value. | [
"Normalizes",
"CSS",
"data",
"in",
"order",
"to",
"avoid",
"differences",
"in",
"the",
"style",
"attribute",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L840-L851 |
|
55,351 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( styleText, normalize, nativeNormalize ) {
var retval = {};
if ( nativeNormalize ) {
// Injects the style in a temporary span object, so the browser parses it,
// retrieving its final format.
var temp = new CKEDITOR.dom.element( 'span' );
temp.setAttribute( 'style', styleText );
styleText = CKEDITOR.tools.convertRgbToHex( temp.getAttribute( 'style' ) || '' );
}
// IE will leave a single semicolon when failed to parse the style text. (#3891)
if ( !styleText || styleText == ';' )
return retval;
styleText.replace( /"/g, '"' ).replace( /\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value ) {
if ( normalize ) {
name = name.toLowerCase();
// Normalize font-family property, ignore quotes and being case insensitive. (#7322)
// http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property
if ( name == 'font-family' )
value = value.toLowerCase().replace( /["']/g, '' ).replace( /\s*,\s*/g, ',' );
value = CKEDITOR.tools.trim( value );
}
retval[ name ] = value;
} );
return retval;
} | javascript | function( styleText, normalize, nativeNormalize ) {
var retval = {};
if ( nativeNormalize ) {
// Injects the style in a temporary span object, so the browser parses it,
// retrieving its final format.
var temp = new CKEDITOR.dom.element( 'span' );
temp.setAttribute( 'style', styleText );
styleText = CKEDITOR.tools.convertRgbToHex( temp.getAttribute( 'style' ) || '' );
}
// IE will leave a single semicolon when failed to parse the style text. (#3891)
if ( !styleText || styleText == ';' )
return retval;
styleText.replace( /"/g, '"' ).replace( /\s*([^:;\s]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value ) {
if ( normalize ) {
name = name.toLowerCase();
// Normalize font-family property, ignore quotes and being case insensitive. (#7322)
// http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property
if ( name == 'font-family' )
value = value.toLowerCase().replace( /["']/g, '' ).replace( /\s*,\s*/g, ',' );
value = CKEDITOR.tools.trim( value );
}
retval[ name ] = value;
} );
return retval;
} | [
"function",
"(",
"styleText",
",",
"normalize",
",",
"nativeNormalize",
")",
"{",
"var",
"retval",
"=",
"{",
"}",
";",
"if",
"(",
"nativeNormalize",
")",
"{",
"// Injects the style in a temporary span object, so the browser parses it,",
"// retrieving its final format.",
"var",
"temp",
"=",
"new",
"CKEDITOR",
".",
"dom",
".",
"element",
"(",
"'span'",
")",
";",
"temp",
".",
"setAttribute",
"(",
"'style'",
",",
"styleText",
")",
";",
"styleText",
"=",
"CKEDITOR",
".",
"tools",
".",
"convertRgbToHex",
"(",
"temp",
".",
"getAttribute",
"(",
"'style'",
")",
"||",
"''",
")",
";",
"}",
"// IE will leave a single semicolon when failed to parse the style text. (#3891)",
"if",
"(",
"!",
"styleText",
"||",
"styleText",
"==",
"';'",
")",
"return",
"retval",
";",
"styleText",
".",
"replace",
"(",
"/",
""",
"/",
"g",
",",
"'\"'",
")",
".",
"replace",
"(",
"/",
"\\s*([^:;\\s]+)\\s*:\\s*([^;]+)\\s*(?=;|$)",
"/",
"g",
",",
"function",
"(",
"match",
",",
"name",
",",
"value",
")",
"{",
"if",
"(",
"normalize",
")",
"{",
"name",
"=",
"name",
".",
"toLowerCase",
"(",
")",
";",
"// Normalize font-family property, ignore quotes and being case insensitive. (#7322)",
"// http://www.w3.org/TR/css3-fonts/#font-family-the-font-family-property",
"if",
"(",
"name",
"==",
"'font-family'",
")",
"value",
"=",
"value",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"[\"']",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
"\\s*,\\s*",
"/",
"g",
",",
"','",
")",
";",
"value",
"=",
"CKEDITOR",
".",
"tools",
".",
"trim",
"(",
"value",
")",
";",
"}",
"retval",
"[",
"name",
"]",
"=",
"value",
";",
"}",
")",
";",
"return",
"retval",
";",
"}"
] | Turns inline style text properties into one hash.
@param {String} styleText The style data to be parsed.
@param {Boolean} [normalize=false] Normalize properties and values
(e.g. trim spaces, convert to lower case).
@param {Boolean} [nativeNormalize=false] Parse the data using the browser.
@returns {Object} The object containing parsed properties. | [
"Turns",
"inline",
"style",
"text",
"properties",
"into",
"one",
"hash",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L878-L906 |
|
55,352 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( styles, sort ) {
var name,
stylesArr = [];
for ( name in styles )
stylesArr.push( name + ':' + styles[ name ] );
if ( sort )
stylesArr.sort();
return stylesArr.join( '; ' );
} | javascript | function( styles, sort ) {
var name,
stylesArr = [];
for ( name in styles )
stylesArr.push( name + ':' + styles[ name ] );
if ( sort )
stylesArr.sort();
return stylesArr.join( '; ' );
} | [
"function",
"(",
"styles",
",",
"sort",
")",
"{",
"var",
"name",
",",
"stylesArr",
"=",
"[",
"]",
";",
"for",
"(",
"name",
"in",
"styles",
")",
"stylesArr",
".",
"push",
"(",
"name",
"+",
"':'",
"+",
"styles",
"[",
"name",
"]",
")",
";",
"if",
"(",
"sort",
")",
"stylesArr",
".",
"sort",
"(",
")",
";",
"return",
"stylesArr",
".",
"join",
"(",
"'; '",
")",
";",
"}"
] | Serializes the `style name => value` hash to a style text.
var styleObj = CKEDITOR.tools.parseCssText( 'color: red; border: none' );
console.log( styleObj.color ); // -> 'red'
CKEDITOR.tools.writeCssText( styleObj ); // -> 'color:red; border:none'
CKEDITOR.tools.writeCssText( styleObj, true ); // -> 'border:none; color:red'
@since 4.1
@param {Object} styles The object contaning style properties.
@param {Boolean} [sort] Whether to sort CSS properties.
@returns {String} The serialized style text. | [
"Serializes",
"the",
"style",
"name",
"=",
">",
"value",
"hash",
"to",
"a",
"style",
"text",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L921-L932 |
|
55,353 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( left, right, onlyLeft ) {
var name;
if ( !left && !right )
return true;
if ( !left || !right )
return false;
for ( name in left ) {
if ( left[ name ] != right[ name ] )
return false;
}
if ( !onlyLeft ) {
for ( name in right ) {
if ( left[ name ] != right[ name ] )
return false;
}
}
return true;
} | javascript | function( left, right, onlyLeft ) {
var name;
if ( !left && !right )
return true;
if ( !left || !right )
return false;
for ( name in left ) {
if ( left[ name ] != right[ name ] )
return false;
}
if ( !onlyLeft ) {
for ( name in right ) {
if ( left[ name ] != right[ name ] )
return false;
}
}
return true;
} | [
"function",
"(",
"left",
",",
"right",
",",
"onlyLeft",
")",
"{",
"var",
"name",
";",
"if",
"(",
"!",
"left",
"&&",
"!",
"right",
")",
"return",
"true",
";",
"if",
"(",
"!",
"left",
"||",
"!",
"right",
")",
"return",
"false",
";",
"for",
"(",
"name",
"in",
"left",
")",
"{",
"if",
"(",
"left",
"[",
"name",
"]",
"!=",
"right",
"[",
"name",
"]",
")",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"onlyLeft",
")",
"{",
"for",
"(",
"name",
"in",
"right",
")",
"{",
"if",
"(",
"left",
"[",
"name",
"]",
"!=",
"right",
"[",
"name",
"]",
")",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Compares two objects.
**Note:** This method performs shallow, non-strict comparison.
@since 4.1
@param {Object} left
@param {Object} right
@param {Boolean} [onlyLeft] Check only the properties that are present in the `left` object.
@returns {Boolean} Whether objects are identical. | [
"Compares",
"two",
"objects",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L945-L967 |
|
55,354 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( arr, fillWith ) {
var obj = {};
if ( arguments.length == 1 )
fillWith = true;
for ( var i = 0, l = arr.length; i < l; ++i )
obj[ arr[ i ] ] = fillWith;
return obj;
} | javascript | function( arr, fillWith ) {
var obj = {};
if ( arguments.length == 1 )
fillWith = true;
for ( var i = 0, l = arr.length; i < l; ++i )
obj[ arr[ i ] ] = fillWith;
return obj;
} | [
"function",
"(",
"arr",
",",
"fillWith",
")",
"{",
"var",
"obj",
"=",
"{",
"}",
";",
"if",
"(",
"arguments",
".",
"length",
"==",
"1",
")",
"fillWith",
"=",
"true",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"obj",
"[",
"arr",
"[",
"i",
"]",
"]",
"=",
"fillWith",
";",
"return",
"obj",
";",
"}"
] | Converts an array to an object by rewriting array items
to object properties.
var arr = [ 'foo', 'bar', 'foo' ];
console.log( CKEDITOR.tools.convertArrayToObject( arr ) );
// -> { foo: true, bar: true }
console.log( CKEDITOR.tools.convertArrayToObject( arr, 1 ) );
// -> { foo: 1, bar: 1 }
@since 4.1
@param {Array} arr The array to be converted to an object.
@param [fillWith=true] Set each property of an object to `fillWith` value. | [
"Converts",
"an",
"array",
"to",
"an",
"object",
"by",
"rewriting",
"array",
"items",
"to",
"object",
"properties",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L1001-L1011 |
|
55,355 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function() {
var domain;
while ( 1 ) {
try {
// Try to access the parent document. It throws
// "access denied" if restricted by the "Same Origin" policy.
domain = window.parent.document.domain;
break;
} catch ( e ) {
// Calculate the value to set to document.domain.
domain = domain ?
// If it is not the first pass, strip one part of the
// name. E.g. "test.example.com" => "example.com"
domain.replace( /.+?(?:\.|$)/, '' ) :
// In the first pass, we'll handle the
// "document.domain = document.domain" case.
document.domain;
// Stop here if there is no more domain parts available.
if ( !domain )
break;
document.domain = domain;
}
}
return !!domain;
} | javascript | function() {
var domain;
while ( 1 ) {
try {
// Try to access the parent document. It throws
// "access denied" if restricted by the "Same Origin" policy.
domain = window.parent.document.domain;
break;
} catch ( e ) {
// Calculate the value to set to document.domain.
domain = domain ?
// If it is not the first pass, strip one part of the
// name. E.g. "test.example.com" => "example.com"
domain.replace( /.+?(?:\.|$)/, '' ) :
// In the first pass, we'll handle the
// "document.domain = document.domain" case.
document.domain;
// Stop here if there is no more domain parts available.
if ( !domain )
break;
document.domain = domain;
}
}
return !!domain;
} | [
"function",
"(",
")",
"{",
"var",
"domain",
";",
"while",
"(",
"1",
")",
"{",
"try",
"{",
"// Try to access the parent document. It throws",
"// \"access denied\" if restricted by the \"Same Origin\" policy.",
"domain",
"=",
"window",
".",
"parent",
".",
"document",
".",
"domain",
";",
"break",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Calculate the value to set to document.domain.",
"domain",
"=",
"domain",
"?",
"// If it is not the first pass, strip one part of the",
"// name. E.g. \"test.example.com\" => \"example.com\"",
"domain",
".",
"replace",
"(",
"/",
".+?(?:\\.|$)",
"/",
",",
"''",
")",
":",
"// In the first pass, we'll handle the",
"// \"document.domain = document.domain\" case.",
"document",
".",
"domain",
";",
"// Stop here if there is no more domain parts available.",
"if",
"(",
"!",
"domain",
")",
"break",
";",
"document",
".",
"domain",
"=",
"domain",
";",
"}",
"}",
"return",
"!",
"!",
"domain",
";",
"}"
] | Tries to fix the `document.domain` of the current document to match the
parent window domain, avoiding "Same Origin" policy issues.
This is an Internet Explorer only requirement.
@since 4.1.2
@returns {Boolean} `true` if the current domain is already good or if
it has been fixed successfully. | [
"Tries",
"to",
"fix",
"the",
"document",
".",
"domain",
"of",
"the",
"current",
"document",
"to",
"match",
"the",
"parent",
"window",
"domain",
"avoiding",
"Same",
"Origin",
"policy",
"issues",
".",
"This",
"is",
"an",
"Internet",
"Explorer",
"only",
"requirement",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L1022-L1052 |
|
55,356 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/tools.js | function( arr, regexp ) {
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( arr[ i ].match( regexp ) )
return true;
}
return false;
} | javascript | function( arr, regexp ) {
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( arr[ i ].match( regexp ) )
return true;
}
return false;
} | [
"function",
"(",
"arr",
",",
"regexp",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"if",
"(",
"arr",
"[",
"i",
"]",
".",
"match",
"(",
"regexp",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Checks if any of the `arr` items match the provided regular expression.
@param {Array} arr The array whose items will be checked.
@param {RegExp} regexp The regular expression.
@returns {Boolean} Returns `true` for the first occurrence of the search pattern.
@since 4.4 | [
"Checks",
"if",
"any",
"of",
"the",
"arr",
"items",
"match",
"the",
"provided",
"regular",
"expression",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/tools.js#L1152-L1158 |
|
55,357 | nick-thompson/capp | index.js | loadDocument | function loadDocument (directory, callback) {
var docPath = path.resolve(directory, '_design.js')
fs.stat(docPath, function (err, stat) {
if (err) return callback.call(null, err);
if (stat.isFile()) {
var document = require(docPath);
return callback.call(null, null, document);
}
return callback.call(null, new Error('No _design.js file found!'));
});
} | javascript | function loadDocument (directory, callback) {
var docPath = path.resolve(directory, '_design.js')
fs.stat(docPath, function (err, stat) {
if (err) return callback.call(null, err);
if (stat.isFile()) {
var document = require(docPath);
return callback.call(null, null, document);
}
return callback.call(null, new Error('No _design.js file found!'));
});
} | [
"function",
"loadDocument",
"(",
"directory",
",",
"callback",
")",
"{",
"var",
"docPath",
"=",
"path",
".",
"resolve",
"(",
"directory",
",",
"'_design.js'",
")",
"fs",
".",
"stat",
"(",
"docPath",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
".",
"call",
"(",
"null",
",",
"err",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"var",
"document",
"=",
"require",
"(",
"docPath",
")",
";",
"return",
"callback",
".",
"call",
"(",
"null",
",",
"null",
",",
"document",
")",
";",
"}",
"return",
"callback",
".",
"call",
"(",
"null",
",",
"new",
"Error",
"(",
"'No _design.js file found!'",
")",
")",
";",
"}",
")",
";",
"}"
] | Load a design document from the _design.js directive
within a specified directory.
@param {string} directory
@param {function} callback (err, document) | [
"Load",
"a",
"design",
"document",
"from",
"the",
"_design",
".",
"js",
"directive",
"within",
"a",
"specified",
"directory",
"."
] | 3df2193d7b464b0440224f658128fded8bff8c88 | https://github.com/nick-thompson/capp/blob/3df2193d7b464b0440224f658128fded8bff8c88/index.js#L25-L35 |
55,358 | nick-thompson/capp | index.js | loadAttachments | function loadAttachments (doc, directory, callback) {
doc._attachments = doc._attachments || {};
glob('**/*', { cwd: directory }, function (err, files) {
async.each(files, function (file, done) {
if (file.indexOf('_') === 0) return done();
fs.stat(path.join(directory, file), function (err, stat) {
if (err) return done(err);
if (stat.isFile()) {
fs.readFile(path.join(directory, file), function (err, data) {
if (err) return done(err);
var ext = file.split('.').pop()
doc._attachments[file] = {}
doc._attachments[file]['content_type'] = lookup(ext);
doc._attachments[file]['data'] = data.toString('base64');
done();
});
} else {
done();
}
});
}, function (err) {
callback.call(null, err, doc);
});
});
} | javascript | function loadAttachments (doc, directory, callback) {
doc._attachments = doc._attachments || {};
glob('**/*', { cwd: directory }, function (err, files) {
async.each(files, function (file, done) {
if (file.indexOf('_') === 0) return done();
fs.stat(path.join(directory, file), function (err, stat) {
if (err) return done(err);
if (stat.isFile()) {
fs.readFile(path.join(directory, file), function (err, data) {
if (err) return done(err);
var ext = file.split('.').pop()
doc._attachments[file] = {}
doc._attachments[file]['content_type'] = lookup(ext);
doc._attachments[file]['data'] = data.toString('base64');
done();
});
} else {
done();
}
});
}, function (err) {
callback.call(null, err, doc);
});
});
} | [
"function",
"loadAttachments",
"(",
"doc",
",",
"directory",
",",
"callback",
")",
"{",
"doc",
".",
"_attachments",
"=",
"doc",
".",
"_attachments",
"||",
"{",
"}",
";",
"glob",
"(",
"'**/*'",
",",
"{",
"cwd",
":",
"directory",
"}",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"async",
".",
"each",
"(",
"files",
",",
"function",
"(",
"file",
",",
"done",
")",
"{",
"if",
"(",
"file",
".",
"indexOf",
"(",
"'_'",
")",
"===",
"0",
")",
"return",
"done",
"(",
")",
";",
"fs",
".",
"stat",
"(",
"path",
".",
"join",
"(",
"directory",
",",
"file",
")",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
")",
"{",
"fs",
".",
"readFile",
"(",
"path",
".",
"join",
"(",
"directory",
",",
"file",
")",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"var",
"ext",
"=",
"file",
".",
"split",
"(",
"'.'",
")",
".",
"pop",
"(",
")",
"doc",
".",
"_attachments",
"[",
"file",
"]",
"=",
"{",
"}",
"doc",
".",
"_attachments",
"[",
"file",
"]",
"[",
"'content_type'",
"]",
"=",
"lookup",
"(",
"ext",
")",
";",
"doc",
".",
"_attachments",
"[",
"file",
"]",
"[",
"'data'",
"]",
"=",
"data",
".",
"toString",
"(",
"'base64'",
")",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"done",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"callback",
".",
"call",
"(",
"null",
",",
"err",
",",
"doc",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Recursively load attachments from a directory onto
a design document.
@param {object} doc design document
@param {string} directory path to the attachments directory
@param {function} callback (err, document) | [
"Recursively",
"load",
"attachments",
"from",
"a",
"directory",
"onto",
"a",
"design",
"document",
"."
] | 3df2193d7b464b0440224f658128fded8bff8c88 | https://github.com/nick-thompson/capp/blob/3df2193d7b464b0440224f658128fded8bff8c88/index.js#L47-L71 |
55,359 | nick-thompson/capp | index.js | push | function push (directory, uri, callback) {
var db = nano(uri);
loadDocument(directory, function (err, doc) {
if (err) return callback.call(null, err);
loadAttachments(doc, directory, function (err, doc) {
if (err) return callback.call(null, err);
db.get(doc._id, function (err, body) {
if (err && err.reason !== "missing") return callback.call(null, err);
if (body && body._rev) {
doc._rev = body._rev;
}
db.insert(doc, doc._id, callback);
});
});
});
} | javascript | function push (directory, uri, callback) {
var db = nano(uri);
loadDocument(directory, function (err, doc) {
if (err) return callback.call(null, err);
loadAttachments(doc, directory, function (err, doc) {
if (err) return callback.call(null, err);
db.get(doc._id, function (err, body) {
if (err && err.reason !== "missing") return callback.call(null, err);
if (body && body._rev) {
doc._rev = body._rev;
}
db.insert(doc, doc._id, callback);
});
});
});
} | [
"function",
"push",
"(",
"directory",
",",
"uri",
",",
"callback",
")",
"{",
"var",
"db",
"=",
"nano",
"(",
"uri",
")",
";",
"loadDocument",
"(",
"directory",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
".",
"call",
"(",
"null",
",",
"err",
")",
";",
"loadAttachments",
"(",
"doc",
",",
"directory",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
".",
"call",
"(",
"null",
",",
"err",
")",
";",
"db",
".",
"get",
"(",
"doc",
".",
"_id",
",",
"function",
"(",
"err",
",",
"body",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"reason",
"!==",
"\"missing\"",
")",
"return",
"callback",
".",
"call",
"(",
"null",
",",
"err",
")",
";",
"if",
"(",
"body",
"&&",
"body",
".",
"_rev",
")",
"{",
"doc",
".",
"_rev",
"=",
"body",
".",
"_rev",
";",
"}",
"db",
".",
"insert",
"(",
"doc",
",",
"doc",
".",
"_id",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Build a design document from the specified directory
and push it to a Couch at the specified uri.
@param {string} directory
@param {string} uri
@param {function} callback (err, responseBody) | [
"Build",
"a",
"design",
"document",
"from",
"the",
"specified",
"directory",
"and",
"push",
"it",
"to",
"a",
"Couch",
"at",
"the",
"specified",
"uri",
"."
] | 3df2193d7b464b0440224f658128fded8bff8c88 | https://github.com/nick-thompson/capp/blob/3df2193d7b464b0440224f658128fded8bff8c88/index.js#L82-L97 |
55,360 | nick-thompson/capp | index.js | init | function init (directory, callback) {
var source = path.join(__dirname, 'template');
ncp(source, directory, callback);
} | javascript | function init (directory, callback) {
var source = path.join(__dirname, 'template');
ncp(source, directory, callback);
} | [
"function",
"init",
"(",
"directory",
",",
"callback",
")",
"{",
"var",
"source",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'template'",
")",
";",
"ncp",
"(",
"source",
",",
"directory",
",",
"callback",
")",
";",
"}"
] | Initialize a boilerplate CouchApp in the specified directory.
@param {string} directory
@param {function} callback (err) | [
"Initialize",
"a",
"boilerplate",
"CouchApp",
"in",
"the",
"specified",
"directory",
"."
] | 3df2193d7b464b0440224f658128fded8bff8c88 | https://github.com/nick-thompson/capp/blob/3df2193d7b464b0440224f658128fded8bff8c88/index.js#L106-L109 |
55,361 | queicherius/generic-checkmark-reporter | src/index.js | start | function start (outputFunction) {
startTime = new Date()
failures = []
count = 0
stats = {success: 0, failure: 0, skipped: 0}
log = outputFunction || log
} | javascript | function start (outputFunction) {
startTime = new Date()
failures = []
count = 0
stats = {success: 0, failure: 0, skipped: 0}
log = outputFunction || log
} | [
"function",
"start",
"(",
"outputFunction",
")",
"{",
"startTime",
"=",
"new",
"Date",
"(",
")",
"failures",
"=",
"[",
"]",
"count",
"=",
"0",
"stats",
"=",
"{",
"success",
":",
"0",
",",
"failure",
":",
"0",
",",
"skipped",
":",
"0",
"}",
"log",
"=",
"outputFunction",
"||",
"log",
"}"
] | Function to call at the start of the test run, resets all variables | [
"Function",
"to",
"call",
"at",
"the",
"start",
"of",
"the",
"test",
"run",
"resets",
"all",
"variables"
] | ded2db7a82e71ca4beb52e2599a73a5e5a0e9687 | https://github.com/queicherius/generic-checkmark-reporter/blob/ded2db7a82e71ca4beb52e2599a73a5e5a0e9687/src/index.js#L17-L23 |
55,362 | queicherius/generic-checkmark-reporter | src/index.js | result | function result (type, error) {
if (count % 40 === 0) {
log('\n ')
}
count++
stats[type]++
log(SYMBOLS[type] + ' ')
if (type === 'failure') {
failures.push(error)
}
} | javascript | function result (type, error) {
if (count % 40 === 0) {
log('\n ')
}
count++
stats[type]++
log(SYMBOLS[type] + ' ')
if (type === 'failure') {
failures.push(error)
}
} | [
"function",
"result",
"(",
"type",
",",
"error",
")",
"{",
"if",
"(",
"count",
"%",
"40",
"===",
"0",
")",
"{",
"log",
"(",
"'\\n '",
")",
"}",
"count",
"++",
"stats",
"[",
"type",
"]",
"++",
"log",
"(",
"SYMBOLS",
"[",
"type",
"]",
"+",
"' '",
")",
"if",
"(",
"type",
"===",
"'failure'",
")",
"{",
"failures",
".",
"push",
"(",
"error",
")",
"}",
"}"
] | Function to call to report a single spec result | [
"Function",
"to",
"call",
"to",
"report",
"a",
"single",
"spec",
"result"
] | ded2db7a82e71ca4beb52e2599a73a5e5a0e9687 | https://github.com/queicherius/generic-checkmark-reporter/blob/ded2db7a82e71ca4beb52e2599a73a5e5a0e9687/src/index.js#L26-L38 |
55,363 | queicherius/generic-checkmark-reporter | src/index.js | end | function end () {
var diff = new Date() - startTime
log('\n\n')
log(' ' + SYMBOLS.success + ' ' + (stats.success + ' passing ').green)
log(('(' + diff + 'ms)').grey)
if (stats.skipped) {
log('\n ' + SYMBOLS.skipped + ' ' + (stats.skipped + ' pending').cyan)
}
if (stats.failure) {
log('\n ' + SYMBOLS.failure + ' ' + (stats.failure + ' failing').red)
// Log all accumulated errors
log('\n\n')
failures.forEach(logError)
}
log('\n\n')
} | javascript | function end () {
var diff = new Date() - startTime
log('\n\n')
log(' ' + SYMBOLS.success + ' ' + (stats.success + ' passing ').green)
log(('(' + diff + 'ms)').grey)
if (stats.skipped) {
log('\n ' + SYMBOLS.skipped + ' ' + (stats.skipped + ' pending').cyan)
}
if (stats.failure) {
log('\n ' + SYMBOLS.failure + ' ' + (stats.failure + ' failing').red)
// Log all accumulated errors
log('\n\n')
failures.forEach(logError)
}
log('\n\n')
} | [
"function",
"end",
"(",
")",
"{",
"var",
"diff",
"=",
"new",
"Date",
"(",
")",
"-",
"startTime",
"log",
"(",
"'\\n\\n'",
")",
"log",
"(",
"' '",
"+",
"SYMBOLS",
".",
"success",
"+",
"' '",
"+",
"(",
"stats",
".",
"success",
"+",
"' passing '",
")",
".",
"green",
")",
"log",
"(",
"(",
"'('",
"+",
"diff",
"+",
"'ms)'",
")",
".",
"grey",
")",
"if",
"(",
"stats",
".",
"skipped",
")",
"{",
"log",
"(",
"'\\n '",
"+",
"SYMBOLS",
".",
"skipped",
"+",
"' '",
"+",
"(",
"stats",
".",
"skipped",
"+",
"' pending'",
")",
".",
"cyan",
")",
"}",
"if",
"(",
"stats",
".",
"failure",
")",
"{",
"log",
"(",
"'\\n '",
"+",
"SYMBOLS",
".",
"failure",
"+",
"' '",
"+",
"(",
"stats",
".",
"failure",
"+",
"' failing'",
")",
".",
"red",
")",
"// Log all accumulated errors",
"log",
"(",
"'\\n\\n'",
")",
"failures",
".",
"forEach",
"(",
"logError",
")",
"}",
"log",
"(",
"'\\n\\n'",
")",
"}"
] | Function to call to report end results | [
"Function",
"to",
"call",
"to",
"report",
"end",
"results"
] | ded2db7a82e71ca4beb52e2599a73a5e5a0e9687 | https://github.com/queicherius/generic-checkmark-reporter/blob/ded2db7a82e71ca4beb52e2599a73a5e5a0e9687/src/index.js#L41-L61 |
55,364 | queicherius/generic-checkmark-reporter | src/index.js | logError | function logError (failure, index) {
index = index + 1
if (index > 1) {
log('\n\n')
}
log(' ' + index + ') ' + failure.description + ': ')
if (failure.environment) {
log(('(' + failure.environment + ')').grey)
}
log('\n\n')
// Log the actual error message / stack trace / diffs
var intend = 4 + String(index).length
var error = formatError(failure.error, intend)
if (!_empty(error.message)) {
log(error.message + '\n')
}
if (!_empty(error.stack)) {
log('\n' + error.stack.grey + '\n')
}
} | javascript | function logError (failure, index) {
index = index + 1
if (index > 1) {
log('\n\n')
}
log(' ' + index + ') ' + failure.description + ': ')
if (failure.environment) {
log(('(' + failure.environment + ')').grey)
}
log('\n\n')
// Log the actual error message / stack trace / diffs
var intend = 4 + String(index).length
var error = formatError(failure.error, intend)
if (!_empty(error.message)) {
log(error.message + '\n')
}
if (!_empty(error.stack)) {
log('\n' + error.stack.grey + '\n')
}
} | [
"function",
"logError",
"(",
"failure",
",",
"index",
")",
"{",
"index",
"=",
"index",
"+",
"1",
"if",
"(",
"index",
">",
"1",
")",
"{",
"log",
"(",
"'\\n\\n'",
")",
"}",
"log",
"(",
"' '",
"+",
"index",
"+",
"') '",
"+",
"failure",
".",
"description",
"+",
"': '",
")",
"if",
"(",
"failure",
".",
"environment",
")",
"{",
"log",
"(",
"(",
"'('",
"+",
"failure",
".",
"environment",
"+",
"')'",
")",
".",
"grey",
")",
"}",
"log",
"(",
"'\\n\\n'",
")",
"// Log the actual error message / stack trace / diffs",
"var",
"intend",
"=",
"4",
"+",
"String",
"(",
"index",
")",
".",
"length",
"var",
"error",
"=",
"formatError",
"(",
"failure",
".",
"error",
",",
"intend",
")",
"if",
"(",
"!",
"_empty",
"(",
"error",
".",
"message",
")",
")",
"{",
"log",
"(",
"error",
".",
"message",
"+",
"'\\n'",
")",
"}",
"if",
"(",
"!",
"_empty",
"(",
"error",
".",
"stack",
")",
")",
"{",
"log",
"(",
"'\\n'",
"+",
"error",
".",
"stack",
".",
"grey",
"+",
"'\\n'",
")",
"}",
"}"
] | Log a single error | [
"Log",
"a",
"single",
"error"
] | ded2db7a82e71ca4beb52e2599a73a5e5a0e9687 | https://github.com/queicherius/generic-checkmark-reporter/blob/ded2db7a82e71ca4beb52e2599a73a5e5a0e9687/src/index.js#L64-L90 |
55,365 | queicherius/generic-checkmark-reporter | src/index.js | intendLines | function intendLines (string, trim, intend) {
var intendStr = new Array(intend + 1).join(' ')
return string
.split('\n')
.map(function (s) {
return trim ? s.trim() : s
})
.join('\n')
.replace(/^/gm, intendStr)
} | javascript | function intendLines (string, trim, intend) {
var intendStr = new Array(intend + 1).join(' ')
return string
.split('\n')
.map(function (s) {
return trim ? s.trim() : s
})
.join('\n')
.replace(/^/gm, intendStr)
} | [
"function",
"intendLines",
"(",
"string",
",",
"trim",
",",
"intend",
")",
"{",
"var",
"intendStr",
"=",
"new",
"Array",
"(",
"intend",
"+",
"1",
")",
".",
"join",
"(",
"' '",
")",
"return",
"string",
".",
"split",
"(",
"'\\n'",
")",
".",
"map",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"trim",
"?",
"s",
".",
"trim",
"(",
")",
":",
"s",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
".",
"replace",
"(",
"/",
"^",
"/",
"gm",
",",
"intendStr",
")",
"}"
] | Intend every line of a string | [
"Intend",
"every",
"line",
"of",
"a",
"string"
] | ded2db7a82e71ca4beb52e2599a73a5e5a0e9687 | https://github.com/queicherius/generic-checkmark-reporter/blob/ded2db7a82e71ca4beb52e2599a73a5e5a0e9687/src/index.js#L153-L163 |
55,366 | vkiding/jud-vue-framework | index.js | registerComponents | function registerComponents (newComponents) {
var config = Vue$2.config;
var newConfig = {};
if (Array.isArray(newComponents)) {
newComponents.forEach(function (component) {
if (!component) {
return
}
if (typeof component === 'string') {
components[component] = true;
newConfig[component] = true;
} else if (typeof component === 'object' && typeof component.type === 'string') {
components[component.type] = component;
newConfig[component.type] = true;
}
});
var oldIsReservedTag = config.isReservedTag;
config.isReservedTag = function (name) {
return newConfig[name] || oldIsReservedTag(name)
};
}
} | javascript | function registerComponents (newComponents) {
var config = Vue$2.config;
var newConfig = {};
if (Array.isArray(newComponents)) {
newComponents.forEach(function (component) {
if (!component) {
return
}
if (typeof component === 'string') {
components[component] = true;
newConfig[component] = true;
} else if (typeof component === 'object' && typeof component.type === 'string') {
components[component.type] = component;
newConfig[component.type] = true;
}
});
var oldIsReservedTag = config.isReservedTag;
config.isReservedTag = function (name) {
return newConfig[name] || oldIsReservedTag(name)
};
}
} | [
"function",
"registerComponents",
"(",
"newComponents",
")",
"{",
"var",
"config",
"=",
"Vue$2",
".",
"config",
";",
"var",
"newConfig",
"=",
"{",
"}",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"newComponents",
")",
")",
"{",
"newComponents",
".",
"forEach",
"(",
"function",
"(",
"component",
")",
"{",
"if",
"(",
"!",
"component",
")",
"{",
"return",
"}",
"if",
"(",
"typeof",
"component",
"===",
"'string'",
")",
"{",
"components",
"[",
"component",
"]",
"=",
"true",
";",
"newConfig",
"[",
"component",
"]",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"typeof",
"component",
"===",
"'object'",
"&&",
"typeof",
"component",
".",
"type",
"===",
"'string'",
")",
"{",
"components",
"[",
"component",
".",
"type",
"]",
"=",
"component",
";",
"newConfig",
"[",
"component",
".",
"type",
"]",
"=",
"true",
";",
"}",
"}",
")",
";",
"var",
"oldIsReservedTag",
"=",
"config",
".",
"isReservedTag",
";",
"config",
".",
"isReservedTag",
"=",
"function",
"(",
"name",
")",
"{",
"return",
"newConfig",
"[",
"name",
"]",
"||",
"oldIsReservedTag",
"(",
"name",
")",
"}",
";",
"}",
"}"
] | Register native components information.
@param {array} newComponents | [
"Register",
"native",
"components",
"information",
"."
] | 1be5034f4cf3fc7dbba6beae78d92028efea52d0 | https://github.com/vkiding/jud-vue-framework/blob/1be5034f4cf3fc7dbba6beae78d92028efea52d0/index.js#L5018-L5039 |
55,367 | travism/solid-logger-js | lib/adapters/file.js | ensureLogsRotated | function ensureLogsRotated(stats){
// TODO: other writes should wait until this is done
var today = new Date(),
modifiedDate = new Date(stats.mtime),
archivedFileName;
if(!_logDatesMatch(today, modifiedDate)){
archivedFileName = _createRotatedLogName(this.config.path, modifiedDate);
console.log('Log file modified previous to today, archiving to: ' + archivedFileName);
return fs.renameAsync(this.config.path, archivedFileName)
.bind(this)
.then(this.createEmptyFile);
}
} | javascript | function ensureLogsRotated(stats){
// TODO: other writes should wait until this is done
var today = new Date(),
modifiedDate = new Date(stats.mtime),
archivedFileName;
if(!_logDatesMatch(today, modifiedDate)){
archivedFileName = _createRotatedLogName(this.config.path, modifiedDate);
console.log('Log file modified previous to today, archiving to: ' + archivedFileName);
return fs.renameAsync(this.config.path, archivedFileName)
.bind(this)
.then(this.createEmptyFile);
}
} | [
"function",
"ensureLogsRotated",
"(",
"stats",
")",
"{",
"// TODO: other writes should wait until this is done",
"var",
"today",
"=",
"new",
"Date",
"(",
")",
",",
"modifiedDate",
"=",
"new",
"Date",
"(",
"stats",
".",
"mtime",
")",
",",
"archivedFileName",
";",
"if",
"(",
"!",
"_logDatesMatch",
"(",
"today",
",",
"modifiedDate",
")",
")",
"{",
"archivedFileName",
"=",
"_createRotatedLogName",
"(",
"this",
".",
"config",
".",
"path",
",",
"modifiedDate",
")",
";",
"console",
".",
"log",
"(",
"'Log file modified previous to today, archiving to: '",
"+",
"archivedFileName",
")",
";",
"return",
"fs",
".",
"renameAsync",
"(",
"this",
".",
"config",
".",
"path",
",",
"archivedFileName",
")",
".",
"bind",
"(",
"this",
")",
".",
"then",
"(",
"this",
".",
"createEmptyFile",
")",
";",
"}",
"}"
] | Method will look at the stats of a file and if it was modified on a date that was not today then it will
rename it to it's modfied date so we can start fresh daily.
@param stats Stats of a file
@returns {string} Status of rotation ('datematches' - do nothing, 'logrotated' - change detected rename file) | [
"Method",
"will",
"look",
"at",
"the",
"stats",
"of",
"a",
"file",
"and",
"if",
"it",
"was",
"modified",
"on",
"a",
"date",
"that",
"was",
"not",
"today",
"then",
"it",
"will",
"rename",
"it",
"to",
"it",
"s",
"modfied",
"date",
"so",
"we",
"can",
"start",
"fresh",
"daily",
"."
] | e5287dcfc680fcfa3eb449dd29bc8c92106184a9 | https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/adapters/file.js#L139-L153 |
55,368 | travism/solid-logger-js | lib/adapters/file.js | _logDatesMatch | function _logDatesMatch(d1, d2){
return ((d1.getFullYear()===d2.getFullYear())&&(d1.getMonth()===d2.getMonth())&&(d1.getDate()===d2.getDate()));
} | javascript | function _logDatesMatch(d1, d2){
return ((d1.getFullYear()===d2.getFullYear())&&(d1.getMonth()===d2.getMonth())&&(d1.getDate()===d2.getDate()));
} | [
"function",
"_logDatesMatch",
"(",
"d1",
",",
"d2",
")",
"{",
"return",
"(",
"(",
"d1",
".",
"getFullYear",
"(",
")",
"===",
"d2",
".",
"getFullYear",
"(",
")",
")",
"&&",
"(",
"d1",
".",
"getMonth",
"(",
")",
"===",
"d2",
".",
"getMonth",
"(",
")",
")",
"&&",
"(",
"d1",
".",
"getDate",
"(",
")",
"===",
"d2",
".",
"getDate",
"(",
")",
")",
")",
";",
"}"
] | Internal utility method that will tell me if the date from the existing log file matches todays Date
@param d1 1st date to compare
@param d2 2nd date to compare
@returns {boolean} | [
"Internal",
"utility",
"method",
"that",
"will",
"tell",
"me",
"if",
"the",
"date",
"from",
"the",
"existing",
"log",
"file",
"matches",
"todays",
"Date"
] | e5287dcfc680fcfa3eb449dd29bc8c92106184a9 | https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/adapters/file.js#L184-L186 |
55,369 | travism/solid-logger-js | lib/adapters/file.js | _createRotatedLogName | function _createRotatedLogName(logPath, modifiedDate){
var logName = logPath,
suffixIdx = logPath.lastIndexOf('.'),
suffix = '';
if(suffixIdx > -1){
suffix = logName.substr(suffixIdx, logName.length);
logName = logName.replace(
suffix, ('.' +
modifiedDate.getFullYear() +
'-' + (modifiedDate.getMonth() + 1) +
'-' + modifiedDate.getDate()
) + suffix
);
}
else {
logName = logName +
('.' + modifiedDate.getFullYear() + '-' + (modifiedDate.getMonth() + 1) + '-' + modifiedDate.getDate());
}
return logName;
} | javascript | function _createRotatedLogName(logPath, modifiedDate){
var logName = logPath,
suffixIdx = logPath.lastIndexOf('.'),
suffix = '';
if(suffixIdx > -1){
suffix = logName.substr(suffixIdx, logName.length);
logName = logName.replace(
suffix, ('.' +
modifiedDate.getFullYear() +
'-' + (modifiedDate.getMonth() + 1) +
'-' + modifiedDate.getDate()
) + suffix
);
}
else {
logName = logName +
('.' + modifiedDate.getFullYear() + '-' + (modifiedDate.getMonth() + 1) + '-' + modifiedDate.getDate());
}
return logName;
} | [
"function",
"_createRotatedLogName",
"(",
"logPath",
",",
"modifiedDate",
")",
"{",
"var",
"logName",
"=",
"logPath",
",",
"suffixIdx",
"=",
"logPath",
".",
"lastIndexOf",
"(",
"'.'",
")",
",",
"suffix",
"=",
"''",
";",
"if",
"(",
"suffixIdx",
">",
"-",
"1",
")",
"{",
"suffix",
"=",
"logName",
".",
"substr",
"(",
"suffixIdx",
",",
"logName",
".",
"length",
")",
";",
"logName",
"=",
"logName",
".",
"replace",
"(",
"suffix",
",",
"(",
"'.'",
"+",
"modifiedDate",
".",
"getFullYear",
"(",
")",
"+",
"'-'",
"+",
"(",
"modifiedDate",
".",
"getMonth",
"(",
")",
"+",
"1",
")",
"+",
"'-'",
"+",
"modifiedDate",
".",
"getDate",
"(",
")",
")",
"+",
"suffix",
")",
";",
"}",
"else",
"{",
"logName",
"=",
"logName",
"+",
"(",
"'.'",
"+",
"modifiedDate",
".",
"getFullYear",
"(",
")",
"+",
"'-'",
"+",
"(",
"modifiedDate",
".",
"getMonth",
"(",
")",
"+",
"1",
")",
"+",
"'-'",
"+",
"modifiedDate",
".",
"getDate",
"(",
")",
")",
";",
"}",
"return",
"logName",
";",
"}"
] | Method that will take the passed in logPath and recreate the path with a modified file name. So if a file
was modified on a previous day and a new log is coming in on the current day, then we want to rename the
old log file with the date in the name.
@param logPath Path of current log file
@param modifiedDate Last file modified date
@returns {string} New file path for previous log | [
"Method",
"that",
"will",
"take",
"the",
"passed",
"in",
"logPath",
"and",
"recreate",
"the",
"path",
"with",
"a",
"modified",
"file",
"name",
".",
"So",
"if",
"a",
"file",
"was",
"modified",
"on",
"a",
"previous",
"day",
"and",
"a",
"new",
"log",
"is",
"coming",
"in",
"on",
"the",
"current",
"day",
"then",
"we",
"want",
"to",
"rename",
"the",
"old",
"log",
"file",
"with",
"the",
"date",
"in",
"the",
"name",
"."
] | e5287dcfc680fcfa3eb449dd29bc8c92106184a9 | https://github.com/travism/solid-logger-js/blob/e5287dcfc680fcfa3eb449dd29bc8c92106184a9/lib/adapters/file.js#L196-L217 |
55,370 | DannyNemer/dantil | dantil.js | getStackTraceArray | function getStackTraceArray() {
var origStackTraceLimit = Error.stackTraceLimit
var origPrepareStackTrace = Error.prepareStackTrace
// Collect all stack frames.
Error.stackTraceLimit = Infinity
// Get a structured stack trace as an `Array` of `CallSite` objects, each of which represents a stack frame, with frames for native Node functions and this file removed.
Error.prepareStackTrace = function (error, structuredStackTrace) {
return structuredStackTrace.filter(function (frame) {
var filePath = frame.getFileName()
// Skip frames from within this module (i.e., `dantil`).
if (filePath === __filename) {
return false
}
// Skip frames for native Node functions (e.g., `require()`).
if (!/\//.test(filePath)) {
return false
}
return true
})
}
// Collect the stack trace.
var stack = Error().stack
// Restore stack trace configuration after collecting stack trace.
Error.stackTraceLimit = origStackTraceLimit
Error.prepareStackTrace = origPrepareStackTrace
return stack
} | javascript | function getStackTraceArray() {
var origStackTraceLimit = Error.stackTraceLimit
var origPrepareStackTrace = Error.prepareStackTrace
// Collect all stack frames.
Error.stackTraceLimit = Infinity
// Get a structured stack trace as an `Array` of `CallSite` objects, each of which represents a stack frame, with frames for native Node functions and this file removed.
Error.prepareStackTrace = function (error, structuredStackTrace) {
return structuredStackTrace.filter(function (frame) {
var filePath = frame.getFileName()
// Skip frames from within this module (i.e., `dantil`).
if (filePath === __filename) {
return false
}
// Skip frames for native Node functions (e.g., `require()`).
if (!/\//.test(filePath)) {
return false
}
return true
})
}
// Collect the stack trace.
var stack = Error().stack
// Restore stack trace configuration after collecting stack trace.
Error.stackTraceLimit = origStackTraceLimit
Error.prepareStackTrace = origPrepareStackTrace
return stack
} | [
"function",
"getStackTraceArray",
"(",
")",
"{",
"var",
"origStackTraceLimit",
"=",
"Error",
".",
"stackTraceLimit",
"var",
"origPrepareStackTrace",
"=",
"Error",
".",
"prepareStackTrace",
"// Collect all stack frames.",
"Error",
".",
"stackTraceLimit",
"=",
"Infinity",
"// Get a structured stack trace as an `Array` of `CallSite` objects, each of which represents a stack frame, with frames for native Node functions and this file removed.",
"Error",
".",
"prepareStackTrace",
"=",
"function",
"(",
"error",
",",
"structuredStackTrace",
")",
"{",
"return",
"structuredStackTrace",
".",
"filter",
"(",
"function",
"(",
"frame",
")",
"{",
"var",
"filePath",
"=",
"frame",
".",
"getFileName",
"(",
")",
"// Skip frames from within this module (i.e., `dantil`).",
"if",
"(",
"filePath",
"===",
"__filename",
")",
"{",
"return",
"false",
"}",
"// Skip frames for native Node functions (e.g., `require()`).",
"if",
"(",
"!",
"/",
"\\/",
"/",
".",
"test",
"(",
"filePath",
")",
")",
"{",
"return",
"false",
"}",
"return",
"true",
"}",
")",
"}",
"// Collect the stack trace.",
"var",
"stack",
"=",
"Error",
"(",
")",
".",
"stack",
"// Restore stack trace configuration after collecting stack trace.",
"Error",
".",
"stackTraceLimit",
"=",
"origStackTraceLimit",
"Error",
".",
"prepareStackTrace",
"=",
"origPrepareStackTrace",
"return",
"stack",
"}"
] | Gets the structured stack trace as an array of `CallSite` objects, excluding the stack frames for this module and native Node functions.
@private
@static
@returns {CallSite[]} Returns the structured stack trace. | [
"Gets",
"the",
"structured",
"stack",
"trace",
"as",
"an",
"array",
"of",
"CallSite",
"objects",
"excluding",
"the",
"stack",
"frames",
"for",
"this",
"module",
"and",
"native",
"Node",
"functions",
"."
] | dbccccc61d59111b71e7333a60092a93b573fdac | https://github.com/DannyNemer/dantil/blob/dbccccc61d59111b71e7333a60092a93b573fdac/dantil.js#L322-L356 |
55,371 | DannyNemer/dantil | dantil.js | writeToProcessStream | function writeToProcessStream(processStreamName, string) {
var writableStream = process[processStreamName]
if (writableStream) {
writableStream.write(string + '\n')
} else {
throw new Error('Unrecognized process stream: ' + exports.stylize(processStreamName))
}
} | javascript | function writeToProcessStream(processStreamName, string) {
var writableStream = process[processStreamName]
if (writableStream) {
writableStream.write(string + '\n')
} else {
throw new Error('Unrecognized process stream: ' + exports.stylize(processStreamName))
}
} | [
"function",
"writeToProcessStream",
"(",
"processStreamName",
",",
"string",
")",
"{",
"var",
"writableStream",
"=",
"process",
"[",
"processStreamName",
"]",
"if",
"(",
"writableStream",
")",
"{",
"writableStream",
".",
"write",
"(",
"string",
"+",
"'\\n'",
")",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Unrecognized process stream: '",
"+",
"exports",
".",
"stylize",
"(",
"processStreamName",
")",
")",
"}",
"}"
] | Writes `string` with a trailing newline to `processStreamName`.
@private
@static
@param {string} processStreamName The name of the writable process stream (e.g., `stout`, `stderr`).
@param {string} string The string to print. | [
"Writes",
"string",
"with",
"a",
"trailing",
"newline",
"to",
"processStreamName",
"."
] | dbccccc61d59111b71e7333a60092a93b573fdac | https://github.com/DannyNemer/dantil/blob/dbccccc61d59111b71e7333a60092a93b573fdac/dantil.js#L864-L871 |
55,372 | DannyNemer/dantil | dantil.js | prettify | function prettify(args, options) {
if (!options) {
options = {}
}
var stylizeOptions = {
// Number of times to recurse while formatting; defaults to 2.
depth: options.depth,
// Format in color if the terminal supports color.
colors: exports.colors.supportsColor,
}
// Use `RegExp()` to get correct `reMultiLined.source`.
var reMultiLined = RegExp('\n', 'g')
var reWhitespaceOnly = /^\s+$/
var indent = ' '
var prevArgIsSeperateLine = false
var argsArray = Array.prototype.slice.call(args)
// Remove any leading newline characters in the first argument, and prepend them to the remainder of the formatted arguments instead of including the characters in the indentation of each argument (as occurs with other whitespace characters in the first argument).
var firstArg = argsArray[0]
var leadingNewlines = ''
if (/^\n+/.test(firstArg)) {
var lastNewlineIdx = firstArg.lastIndexOf('\n')
if (lastNewlineIdx === firstArg.length - 1) {
argsArray.shift()
} else {
argsArray[0] = firstArg.slice(lastNewlineIdx + 1)
firstArg = firstArg.slice(0, lastNewlineIdx + 1)
}
leadingNewlines = firstArg
}
return leadingNewlines + argsArray.reduce(function (formattedArgs, arg, i, args) {
var argIsString = typeof arg === 'string'
// Parse numbers passed as string for styling.
if (argIsString && /^\S+$/.test(arg) && !isNaN(arg)) {
arg = parseFloat(arg)
argIsString = false
}
// Do not stylize strings passed as arguments (i.e., not `Object` properties). This also preserves any already-stylized arguments.
var formattedArg = !options.stylizeStings && argIsString ? arg : exports.stylize(arg, stylizeOptions)
if (i === 0) {
// Extend indent for remaining arguments with the first argument's leading whitespace, if any.
if (argIsString) {
// Get the substring of leading whitespace characters from the start of the string, up to the first non-whitespace character, if any.
var firstNonWhitespaceIndex = arg.search(/[^\s]/)
arg = arg.slice(0, firstNonWhitespaceIndex === -1 ? arg.length : firstNonWhitespaceIndex)
// JavaScript will not properly indent if '\t' is appended to spaces (i.e., reverse order as here).
// If the first argument is entirely whitespace, indent all remaining arguments with that whitespace.
indent = reWhitespaceOnly.test(formattedArg) ? arg : arg + indent
// If first argument is entirely whitespace, exclude from output because it serves only to set indentation of all remaining arguments.
if (reWhitespaceOnly.test(formattedArg)) {
// Force the next argument to be pushed to `formattedArgs` to avoid concatenating with `undefined` (because `formattedArgs` remains empty).
prevArgIsSeperateLine = true
} else {
formattedArgs.push(formattedArg)
}
} else {
formattedArgs.push(formattedArg)
if (arg instanceof Object) {
// Do not indent remaining arguments if the first argument is of a complex type.
indent = ''
// Format the complex type on a separate line.
prevArgIsSeperateLine = true
}
}
} else if (arg instanceof Object && (!Array.isArray(arg) || reMultiLined.test(formattedArg) || args[0] instanceof Object)) {
// Format plain `Object`s, `Array`s with multi-line string representations, and `Array`s when the first argument is of a complex type on separate lines.
formattedArgs.push(indent + formattedArg.replace(reMultiLined, reMultiLined.source + indent))
prevArgIsSeperateLine = true
} else if (prevArgIsSeperateLine) {
// Format anything that follows a multi-line string representations on a new line.
formattedArgs.push(indent + formattedArg)
prevArgIsSeperateLine = false
} else {
// Concatenate all consecutive primitive data types.
formattedArgs[formattedArgs.length - 1] += ' ' + formattedArg
}
return formattedArgs
}, []).join('\n')
} | javascript | function prettify(args, options) {
if (!options) {
options = {}
}
var stylizeOptions = {
// Number of times to recurse while formatting; defaults to 2.
depth: options.depth,
// Format in color if the terminal supports color.
colors: exports.colors.supportsColor,
}
// Use `RegExp()` to get correct `reMultiLined.source`.
var reMultiLined = RegExp('\n', 'g')
var reWhitespaceOnly = /^\s+$/
var indent = ' '
var prevArgIsSeperateLine = false
var argsArray = Array.prototype.slice.call(args)
// Remove any leading newline characters in the first argument, and prepend them to the remainder of the formatted arguments instead of including the characters in the indentation of each argument (as occurs with other whitespace characters in the first argument).
var firstArg = argsArray[0]
var leadingNewlines = ''
if (/^\n+/.test(firstArg)) {
var lastNewlineIdx = firstArg.lastIndexOf('\n')
if (lastNewlineIdx === firstArg.length - 1) {
argsArray.shift()
} else {
argsArray[0] = firstArg.slice(lastNewlineIdx + 1)
firstArg = firstArg.slice(0, lastNewlineIdx + 1)
}
leadingNewlines = firstArg
}
return leadingNewlines + argsArray.reduce(function (formattedArgs, arg, i, args) {
var argIsString = typeof arg === 'string'
// Parse numbers passed as string for styling.
if (argIsString && /^\S+$/.test(arg) && !isNaN(arg)) {
arg = parseFloat(arg)
argIsString = false
}
// Do not stylize strings passed as arguments (i.e., not `Object` properties). This also preserves any already-stylized arguments.
var formattedArg = !options.stylizeStings && argIsString ? arg : exports.stylize(arg, stylizeOptions)
if (i === 0) {
// Extend indent for remaining arguments with the first argument's leading whitespace, if any.
if (argIsString) {
// Get the substring of leading whitespace characters from the start of the string, up to the first non-whitespace character, if any.
var firstNonWhitespaceIndex = arg.search(/[^\s]/)
arg = arg.slice(0, firstNonWhitespaceIndex === -1 ? arg.length : firstNonWhitespaceIndex)
// JavaScript will not properly indent if '\t' is appended to spaces (i.e., reverse order as here).
// If the first argument is entirely whitespace, indent all remaining arguments with that whitespace.
indent = reWhitespaceOnly.test(formattedArg) ? arg : arg + indent
// If first argument is entirely whitespace, exclude from output because it serves only to set indentation of all remaining arguments.
if (reWhitespaceOnly.test(formattedArg)) {
// Force the next argument to be pushed to `formattedArgs` to avoid concatenating with `undefined` (because `formattedArgs` remains empty).
prevArgIsSeperateLine = true
} else {
formattedArgs.push(formattedArg)
}
} else {
formattedArgs.push(formattedArg)
if (arg instanceof Object) {
// Do not indent remaining arguments if the first argument is of a complex type.
indent = ''
// Format the complex type on a separate line.
prevArgIsSeperateLine = true
}
}
} else if (arg instanceof Object && (!Array.isArray(arg) || reMultiLined.test(formattedArg) || args[0] instanceof Object)) {
// Format plain `Object`s, `Array`s with multi-line string representations, and `Array`s when the first argument is of a complex type on separate lines.
formattedArgs.push(indent + formattedArg.replace(reMultiLined, reMultiLined.source + indent))
prevArgIsSeperateLine = true
} else if (prevArgIsSeperateLine) {
// Format anything that follows a multi-line string representations on a new line.
formattedArgs.push(indent + formattedArg)
prevArgIsSeperateLine = false
} else {
// Concatenate all consecutive primitive data types.
formattedArgs[formattedArgs.length - 1] += ' ' + formattedArg
}
return formattedArgs
}, []).join('\n')
} | [
"function",
"prettify",
"(",
"args",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
"}",
"var",
"stylizeOptions",
"=",
"{",
"// Number of times to recurse while formatting; defaults to 2.",
"depth",
":",
"options",
".",
"depth",
",",
"// Format in color if the terminal supports color.",
"colors",
":",
"exports",
".",
"colors",
".",
"supportsColor",
",",
"}",
"// Use `RegExp()` to get correct `reMultiLined.source`.",
"var",
"reMultiLined",
"=",
"RegExp",
"(",
"'\\n'",
",",
"'g'",
")",
"var",
"reWhitespaceOnly",
"=",
"/",
"^\\s+$",
"/",
"var",
"indent",
"=",
"' '",
"var",
"prevArgIsSeperateLine",
"=",
"false",
"var",
"argsArray",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
")",
"// Remove any leading newline characters in the first argument, and prepend them to the remainder of the formatted arguments instead of including the characters in the indentation of each argument (as occurs with other whitespace characters in the first argument).",
"var",
"firstArg",
"=",
"argsArray",
"[",
"0",
"]",
"var",
"leadingNewlines",
"=",
"''",
"if",
"(",
"/",
"^\\n+",
"/",
".",
"test",
"(",
"firstArg",
")",
")",
"{",
"var",
"lastNewlineIdx",
"=",
"firstArg",
".",
"lastIndexOf",
"(",
"'\\n'",
")",
"if",
"(",
"lastNewlineIdx",
"===",
"firstArg",
".",
"length",
"-",
"1",
")",
"{",
"argsArray",
".",
"shift",
"(",
")",
"}",
"else",
"{",
"argsArray",
"[",
"0",
"]",
"=",
"firstArg",
".",
"slice",
"(",
"lastNewlineIdx",
"+",
"1",
")",
"firstArg",
"=",
"firstArg",
".",
"slice",
"(",
"0",
",",
"lastNewlineIdx",
"+",
"1",
")",
"}",
"leadingNewlines",
"=",
"firstArg",
"}",
"return",
"leadingNewlines",
"+",
"argsArray",
".",
"reduce",
"(",
"function",
"(",
"formattedArgs",
",",
"arg",
",",
"i",
",",
"args",
")",
"{",
"var",
"argIsString",
"=",
"typeof",
"arg",
"===",
"'string'",
"// Parse numbers passed as string for styling.",
"if",
"(",
"argIsString",
"&&",
"/",
"^\\S+$",
"/",
".",
"test",
"(",
"arg",
")",
"&&",
"!",
"isNaN",
"(",
"arg",
")",
")",
"{",
"arg",
"=",
"parseFloat",
"(",
"arg",
")",
"argIsString",
"=",
"false",
"}",
"// Do not stylize strings passed as arguments (i.e., not `Object` properties). This also preserves any already-stylized arguments.",
"var",
"formattedArg",
"=",
"!",
"options",
".",
"stylizeStings",
"&&",
"argIsString",
"?",
"arg",
":",
"exports",
".",
"stylize",
"(",
"arg",
",",
"stylizeOptions",
")",
"if",
"(",
"i",
"===",
"0",
")",
"{",
"// Extend indent for remaining arguments with the first argument's leading whitespace, if any.",
"if",
"(",
"argIsString",
")",
"{",
"// Get the substring of leading whitespace characters from the start of the string, up to the first non-whitespace character, if any.",
"var",
"firstNonWhitespaceIndex",
"=",
"arg",
".",
"search",
"(",
"/",
"[^\\s]",
"/",
")",
"arg",
"=",
"arg",
".",
"slice",
"(",
"0",
",",
"firstNonWhitespaceIndex",
"===",
"-",
"1",
"?",
"arg",
".",
"length",
":",
"firstNonWhitespaceIndex",
")",
"// JavaScript will not properly indent if '\\t' is appended to spaces (i.e., reverse order as here).",
"// If the first argument is entirely whitespace, indent all remaining arguments with that whitespace.",
"indent",
"=",
"reWhitespaceOnly",
".",
"test",
"(",
"formattedArg",
")",
"?",
"arg",
":",
"arg",
"+",
"indent",
"// If first argument is entirely whitespace, exclude from output because it serves only to set indentation of all remaining arguments.",
"if",
"(",
"reWhitespaceOnly",
".",
"test",
"(",
"formattedArg",
")",
")",
"{",
"// Force the next argument to be pushed to `formattedArgs` to avoid concatenating with `undefined` (because `formattedArgs` remains empty).",
"prevArgIsSeperateLine",
"=",
"true",
"}",
"else",
"{",
"formattedArgs",
".",
"push",
"(",
"formattedArg",
")",
"}",
"}",
"else",
"{",
"formattedArgs",
".",
"push",
"(",
"formattedArg",
")",
"if",
"(",
"arg",
"instanceof",
"Object",
")",
"{",
"// Do not indent remaining arguments if the first argument is of a complex type.",
"indent",
"=",
"''",
"// Format the complex type on a separate line.",
"prevArgIsSeperateLine",
"=",
"true",
"}",
"}",
"}",
"else",
"if",
"(",
"arg",
"instanceof",
"Object",
"&&",
"(",
"!",
"Array",
".",
"isArray",
"(",
"arg",
")",
"||",
"reMultiLined",
".",
"test",
"(",
"formattedArg",
")",
"||",
"args",
"[",
"0",
"]",
"instanceof",
"Object",
")",
")",
"{",
"// Format plain `Object`s, `Array`s with multi-line string representations, and `Array`s when the first argument is of a complex type on separate lines.",
"formattedArgs",
".",
"push",
"(",
"indent",
"+",
"formattedArg",
".",
"replace",
"(",
"reMultiLined",
",",
"reMultiLined",
".",
"source",
"+",
"indent",
")",
")",
"prevArgIsSeperateLine",
"=",
"true",
"}",
"else",
"if",
"(",
"prevArgIsSeperateLine",
")",
"{",
"// Format anything that follows a multi-line string representations on a new line.",
"formattedArgs",
".",
"push",
"(",
"indent",
"+",
"formattedArg",
")",
"prevArgIsSeperateLine",
"=",
"false",
"}",
"else",
"{",
"// Concatenate all consecutive primitive data types.",
"formattedArgs",
"[",
"formattedArgs",
".",
"length",
"-",
"1",
"]",
"+=",
"' '",
"+",
"formattedArg",
"}",
"return",
"formattedArgs",
"}",
",",
"[",
"]",
")",
".",
"join",
"(",
"'\\n'",
")",
"}"
] | Formats the provided values and objects in color for pretty-printing, recursing `options.depth` times while formatting objects.
Formats plain `Object` and `Array` instances with multi-line string representations on separate lines. Concatenates and formats all other consecutive values on the same line.
If the first argument is of a complex type (e.g., `Object`, `Array`), left-aligns all remaining lines. Otherwise, equally indents each line after the first line, if any. If the first argument has leading whitespace (or is entirely whitespace), prepends all remaining arguments with the same whitespace (as indentation) excluding newline characters.
@private
@static
@param {Array} args The values and objects to format.
@param {Object} [options] The options object.
@param {number} [options.depth=2] The number of times to recurse while formating `args`. Pass `null` to recurse indefinitely.
@param {number} [options.stylizeStings=false] Specify stylizing strings in `args`. This does not apply to `Object` properties.
@returns {string} Returns the formatted string. | [
"Formats",
"the",
"provided",
"values",
"and",
"objects",
"in",
"color",
"for",
"pretty",
"-",
"printing",
"recursing",
"options",
".",
"depth",
"times",
"while",
"formatting",
"objects",
"."
] | dbccccc61d59111b71e7333a60092a93b573fdac | https://github.com/DannyNemer/dantil/blob/dbccccc61d59111b71e7333a60092a93b573fdac/dantil.js#L888-L979 |
55,373 | DannyNemer/dantil | dantil.js | stringifyStackFrame | function stringifyStackFrame(stackFrame, label) {
var frameString = stackFrame.toString()
// Colorize function name (or `label`, if provided).
var lastSpaceIndex = frameString.lastIndexOf(' ')
if (lastSpaceIndex !== -1) {
return exports.colors.cyan(label || frameString.slice(0, lastSpaceIndex)) + frameString.slice(lastSpaceIndex)
}
// If there is no leading function, method, or type name (e.g., then root Node call: "node.js:405:3"), and `label` was provided.
if (label) {
return exports.colors.cyan(label) + ' ' + frameString
}
return frameString
} | javascript | function stringifyStackFrame(stackFrame, label) {
var frameString = stackFrame.toString()
// Colorize function name (or `label`, if provided).
var lastSpaceIndex = frameString.lastIndexOf(' ')
if (lastSpaceIndex !== -1) {
return exports.colors.cyan(label || frameString.slice(0, lastSpaceIndex)) + frameString.slice(lastSpaceIndex)
}
// If there is no leading function, method, or type name (e.g., then root Node call: "node.js:405:3"), and `label` was provided.
if (label) {
return exports.colors.cyan(label) + ' ' + frameString
}
return frameString
} | [
"function",
"stringifyStackFrame",
"(",
"stackFrame",
",",
"label",
")",
"{",
"var",
"frameString",
"=",
"stackFrame",
".",
"toString",
"(",
")",
"// Colorize function name (or `label`, if provided).",
"var",
"lastSpaceIndex",
"=",
"frameString",
".",
"lastIndexOf",
"(",
"' '",
")",
"if",
"(",
"lastSpaceIndex",
"!==",
"-",
"1",
")",
"{",
"return",
"exports",
".",
"colors",
".",
"cyan",
"(",
"label",
"||",
"frameString",
".",
"slice",
"(",
"0",
",",
"lastSpaceIndex",
")",
")",
"+",
"frameString",
".",
"slice",
"(",
"lastSpaceIndex",
")",
"}",
"// If there is no leading function, method, or type name (e.g., then root Node call: \"node.js:405:3\"), and `label` was provided.",
"if",
"(",
"label",
")",
"{",
"return",
"exports",
".",
"colors",
".",
"cyan",
"(",
"label",
")",
"+",
"' '",
"+",
"frameString",
"}",
"return",
"frameString",
"}"
] | Stringifies and colorizes the function name in `stackFrame`. If provided, `label` substitutes the function name in the `stackFrame` string representation.
@private
@static
@param {CallSite} stackFrame The stack frame to stringify and stylize.
@param {string} [label] The label that substitutes the function name in the `stackFrame` string representation.
@returns {string} Returns the stylized string representation of `stackFrame`. | [
"Stringifies",
"and",
"colorizes",
"the",
"function",
"name",
"in",
"stackFrame",
".",
"If",
"provided",
"label",
"substitutes",
"the",
"function",
"name",
"in",
"the",
"stackFrame",
"string",
"representation",
"."
] | dbccccc61d59111b71e7333a60092a93b573fdac | https://github.com/DannyNemer/dantil/blob/dbccccc61d59111b71e7333a60092a93b573fdac/dantil.js#L1431-L1446 |
55,374 | AndreasMadsen/immortal | lib/helpers.js | ProcessWatcher | function ProcessWatcher(pid, parent) {
var self = this;
this.dead = false;
// check first if process is alive
if (exports.alive(pid) === false) {
process.nextTick(function () {
self.dead = true;
self.emit('dead');
});
return self;
}
// use disconnect to detect parent death
if (parent && exports.support.disconnect) {
var listen = function() {
self.dead = true;
self.stop();
self.emit('dead');
}
parent.once('disconnect', listen);
this.stop = parent.removeListener.bind(null, 'disconnect', listen);
this.on('newListener', function (eventName) {
if (eventName !== 'cycle') return;
process.nextTick(function () {
self.emit('cycle');
});
});
return self;
}
// fallback to an setInterval try/catch check
var timer = setInterval(function () {
if (exports.alive(pid) === false) {
self.dead = true;
self.stop();
self.emit('dead');
}
self.emit('cycle');
});
this.stop = clearInterval.bind(null, timer);
} | javascript | function ProcessWatcher(pid, parent) {
var self = this;
this.dead = false;
// check first if process is alive
if (exports.alive(pid) === false) {
process.nextTick(function () {
self.dead = true;
self.emit('dead');
});
return self;
}
// use disconnect to detect parent death
if (parent && exports.support.disconnect) {
var listen = function() {
self.dead = true;
self.stop();
self.emit('dead');
}
parent.once('disconnect', listen);
this.stop = parent.removeListener.bind(null, 'disconnect', listen);
this.on('newListener', function (eventName) {
if (eventName !== 'cycle') return;
process.nextTick(function () {
self.emit('cycle');
});
});
return self;
}
// fallback to an setInterval try/catch check
var timer = setInterval(function () {
if (exports.alive(pid) === false) {
self.dead = true;
self.stop();
self.emit('dead');
}
self.emit('cycle');
});
this.stop = clearInterval.bind(null, timer);
} | [
"function",
"ProcessWatcher",
"(",
"pid",
",",
"parent",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"dead",
"=",
"false",
";",
"// check first if process is alive",
"if",
"(",
"exports",
".",
"alive",
"(",
"pid",
")",
"===",
"false",
")",
"{",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"self",
".",
"dead",
"=",
"true",
";",
"self",
".",
"emit",
"(",
"'dead'",
")",
";",
"}",
")",
";",
"return",
"self",
";",
"}",
"// use disconnect to detect parent death",
"if",
"(",
"parent",
"&&",
"exports",
".",
"support",
".",
"disconnect",
")",
"{",
"var",
"listen",
"=",
"function",
"(",
")",
"{",
"self",
".",
"dead",
"=",
"true",
";",
"self",
".",
"stop",
"(",
")",
";",
"self",
".",
"emit",
"(",
"'dead'",
")",
";",
"}",
"parent",
".",
"once",
"(",
"'disconnect'",
",",
"listen",
")",
";",
"this",
".",
"stop",
"=",
"parent",
".",
"removeListener",
".",
"bind",
"(",
"null",
",",
"'disconnect'",
",",
"listen",
")",
";",
"this",
".",
"on",
"(",
"'newListener'",
",",
"function",
"(",
"eventName",
")",
"{",
"if",
"(",
"eventName",
"!==",
"'cycle'",
")",
"return",
";",
"process",
".",
"nextTick",
"(",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"'cycle'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"self",
";",
"}",
"// fallback to an setInterval try/catch check",
"var",
"timer",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"exports",
".",
"alive",
"(",
"pid",
")",
"===",
"false",
")",
"{",
"self",
".",
"dead",
"=",
"true",
";",
"self",
".",
"stop",
"(",
")",
";",
"self",
".",
"emit",
"(",
"'dead'",
")",
";",
"}",
"self",
".",
"emit",
"(",
"'cycle'",
")",
";",
"}",
")",
";",
"this",
".",
"stop",
"=",
"clearInterval",
".",
"bind",
"(",
"null",
",",
"timer",
")",
";",
"}"
] | continusely check if process alive and execute callback when the process is missing | [
"continusely",
"check",
"if",
"process",
"alive",
"and",
"execute",
"callback",
"when",
"the",
"process",
"is",
"missing"
] | c1ab5a4287a543fdfd980604a9e9927d663a9ef2 | https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/helpers.js#L90-L136 |
55,375 | PsychoLlama/panic-manager | src/Manager.js | validate | function validate (config) {
/** Make sure the config object was passed. */
if (!config) {
throw new TypeError('Missing configuration object.');
}
/** Make sure the panic url is provided. */
if (typeof config.panic !== 'string') {
throw new TypeError('Panic server URL "config.panic" not provided.');
}
/** Make sure config.clients is an array. */
if (isArray(config.clients) === false) {
throw new TypeError('"config.clients" is not an array.');
}
var str = JSON.stringify;
/** Validate the client objects. */
config.clients.forEach(function (client) {
if (!client) {
throw new Error('Client "' + client + '" is not an object.');
}
if (!client.type) {
throw new Error('Missing client.type attribute: ' + str(client));
}
});
} | javascript | function validate (config) {
/** Make sure the config object was passed. */
if (!config) {
throw new TypeError('Missing configuration object.');
}
/** Make sure the panic url is provided. */
if (typeof config.panic !== 'string') {
throw new TypeError('Panic server URL "config.panic" not provided.');
}
/** Make sure config.clients is an array. */
if (isArray(config.clients) === false) {
throw new TypeError('"config.clients" is not an array.');
}
var str = JSON.stringify;
/** Validate the client objects. */
config.clients.forEach(function (client) {
if (!client) {
throw new Error('Client "' + client + '" is not an object.');
}
if (!client.type) {
throw new Error('Missing client.type attribute: ' + str(client));
}
});
} | [
"function",
"validate",
"(",
"config",
")",
"{",
"/** Make sure the config object was passed. */",
"if",
"(",
"!",
"config",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Missing configuration object.'",
")",
";",
"}",
"/** Make sure the panic url is provided. */",
"if",
"(",
"typeof",
"config",
".",
"panic",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Panic server URL \"config.panic\" not provided.'",
")",
";",
"}",
"/** Make sure config.clients is an array. */",
"if",
"(",
"isArray",
"(",
"config",
".",
"clients",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'\"config.clients\" is not an array.'",
")",
";",
"}",
"var",
"str",
"=",
"JSON",
".",
"stringify",
";",
"/** Validate the client objects. */",
"config",
".",
"clients",
".",
"forEach",
"(",
"function",
"(",
"client",
")",
"{",
"if",
"(",
"!",
"client",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Client \"'",
"+",
"client",
"+",
"'\" is not an object.'",
")",
";",
"}",
"if",
"(",
"!",
"client",
".",
"type",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Missing client.type attribute: '",
"+",
"str",
"(",
"client",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Validate a config object.
@throws {TypeError} - Reports any missing inputs.
@param {Object} config - The configuration object.
@returns {undefined} | [
"Validate",
"a",
"config",
"object",
"."
] | d68c8c918994a5b93647bd7965e364d6ddc411de | https://github.com/PsychoLlama/panic-manager/blob/d68c8c918994a5b93647bd7965e364d6ddc411de/src/Manager.js#L14-L43 |
55,376 | PsychoLlama/panic-manager | src/Manager.js | Manager | function Manager (remote) {
/** Allow usage without `new`. */
if (!(this instanceof Manager)) {
return new Manager(remote);
}
/**
* @property {Boolean} isRemote
* Whether the manager is remote.
*/
this.isRemote = false;
/**
* @property {Socket} socket
* A socket.io instance, or `null` if using locally.
*/
this.socket = null;
/** If only using locally, stop here. */
if (!remote) {
return this;
}
/** If it's a URL, connect to it. */
if (typeof remote === 'string') {
this.isRemote = true;
/** Automatically postfix the manager scope. */
var url = remote + '/panic-manager';
/** Connect to the remote manager. */
this.socket = socket.client(url);
return this;
}
/** Listen for /panic-manager connections. */
var server = socket.server(remote).of('/panic-manager');
/** Listen for connections. */
server.on('connection', function (socket) {
/** Listen for start commands. */
socket.on('start', function (config) {
spawn(config);
});
});
this.socket = server;
} | javascript | function Manager (remote) {
/** Allow usage without `new`. */
if (!(this instanceof Manager)) {
return new Manager(remote);
}
/**
* @property {Boolean} isRemote
* Whether the manager is remote.
*/
this.isRemote = false;
/**
* @property {Socket} socket
* A socket.io instance, or `null` if using locally.
*/
this.socket = null;
/** If only using locally, stop here. */
if (!remote) {
return this;
}
/** If it's a URL, connect to it. */
if (typeof remote === 'string') {
this.isRemote = true;
/** Automatically postfix the manager scope. */
var url = remote + '/panic-manager';
/** Connect to the remote manager. */
this.socket = socket.client(url);
return this;
}
/** Listen for /panic-manager connections. */
var server = socket.server(remote).of('/panic-manager');
/** Listen for connections. */
server.on('connection', function (socket) {
/** Listen for start commands. */
socket.on('start', function (config) {
spawn(config);
});
});
this.socket = server;
} | [
"function",
"Manager",
"(",
"remote",
")",
"{",
"/** Allow usage without `new`. */",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Manager",
")",
")",
"{",
"return",
"new",
"Manager",
"(",
"remote",
")",
";",
"}",
"/**\n\t * @property {Boolean} isRemote\n\t * Whether the manager is remote.\n\t */",
"this",
".",
"isRemote",
"=",
"false",
";",
"/**\n\t * @property {Socket} socket\n\t * A socket.io instance, or `null` if using locally.\n\t */",
"this",
".",
"socket",
"=",
"null",
";",
"/** If only using locally, stop here. */",
"if",
"(",
"!",
"remote",
")",
"{",
"return",
"this",
";",
"}",
"/** If it's a URL, connect to it. */",
"if",
"(",
"typeof",
"remote",
"===",
"'string'",
")",
"{",
"this",
".",
"isRemote",
"=",
"true",
";",
"/** Automatically postfix the manager scope. */",
"var",
"url",
"=",
"remote",
"+",
"'/panic-manager'",
";",
"/** Connect to the remote manager. */",
"this",
".",
"socket",
"=",
"socket",
".",
"client",
"(",
"url",
")",
";",
"return",
"this",
";",
"}",
"/** Listen for /panic-manager connections. */",
"var",
"server",
"=",
"socket",
".",
"server",
"(",
"remote",
")",
".",
"of",
"(",
"'/panic-manager'",
")",
";",
"/** Listen for connections. */",
"server",
".",
"on",
"(",
"'connection'",
",",
"function",
"(",
"socket",
")",
"{",
"/** Listen for start commands. */",
"socket",
".",
"on",
"(",
"'start'",
",",
"function",
"(",
"config",
")",
"{",
"spawn",
"(",
"config",
")",
";",
"}",
")",
";",
"}",
")",
";",
"this",
".",
"socket",
"=",
"server",
";",
"}"
] | Manage panic clients in bulk, either locally or remotely.
@class Manager
@param {Mixed} remote - Either an http.Server to attach to,
a URL to connect to, or `undefined` if there is no remote. | [
"Manage",
"panic",
"clients",
"in",
"bulk",
"either",
"locally",
"or",
"remotely",
"."
] | d68c8c918994a5b93647bd7965e364d6ddc411de | https://github.com/PsychoLlama/panic-manager/blob/d68c8c918994a5b93647bd7965e364d6ddc411de/src/Manager.js#L52-L104 |
55,377 | doowb/recent | index.js | recent | function recent(views, options) {
options = options || {};
var prop = options.prop || 'data.date';
var limit = options.limit || 10;
var res = {};
for (var key in views) {
if (views.hasOwnProperty(key)) {
var date = createdDate(key, views[key], prop);
res[date] = res[date] || [];
res[date].push(key);
}
}
var keys = Object.keys(res).sort();
var len = keys.length;
var num = 0;
var acc = {};
while (len-- && num < limit) {
var arr = res[keys[len]];
for (var j = 0; j < arr.length; j++) {
var key = arr[j];
acc[key] = views[key];
num++;
if (num > limit) break;
}
}
return acc;
} | javascript | function recent(views, options) {
options = options || {};
var prop = options.prop || 'data.date';
var limit = options.limit || 10;
var res = {};
for (var key in views) {
if (views.hasOwnProperty(key)) {
var date = createdDate(key, views[key], prop);
res[date] = res[date] || [];
res[date].push(key);
}
}
var keys = Object.keys(res).sort();
var len = keys.length;
var num = 0;
var acc = {};
while (len-- && num < limit) {
var arr = res[keys[len]];
for (var j = 0; j < arr.length; j++) {
var key = arr[j];
acc[key] = views[key];
num++;
if (num > limit) break;
}
}
return acc;
} | [
"function",
"recent",
"(",
"views",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"prop",
"=",
"options",
".",
"prop",
"||",
"'data.date'",
";",
"var",
"limit",
"=",
"options",
".",
"limit",
"||",
"10",
";",
"var",
"res",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"views",
")",
"{",
"if",
"(",
"views",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"var",
"date",
"=",
"createdDate",
"(",
"key",
",",
"views",
"[",
"key",
"]",
",",
"prop",
")",
";",
"res",
"[",
"date",
"]",
"=",
"res",
"[",
"date",
"]",
"||",
"[",
"]",
";",
"res",
"[",
"date",
"]",
".",
"push",
"(",
"key",
")",
";",
"}",
"}",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"res",
")",
".",
"sort",
"(",
")",
";",
"var",
"len",
"=",
"keys",
".",
"length",
";",
"var",
"num",
"=",
"0",
";",
"var",
"acc",
"=",
"{",
"}",
";",
"while",
"(",
"len",
"--",
"&&",
"num",
"<",
"limit",
")",
"{",
"var",
"arr",
"=",
"res",
"[",
"keys",
"[",
"len",
"]",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"arr",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"key",
"=",
"arr",
"[",
"j",
"]",
";",
"acc",
"[",
"key",
"]",
"=",
"views",
"[",
"key",
"]",
";",
"num",
"++",
";",
"if",
"(",
"num",
">",
"limit",
")",
"break",
";",
"}",
"}",
"return",
"acc",
";",
"}"
] | Return the most recent items on an object.
```
var top10 = recent(posts);
```
@param {Object} `views` Object hash of items.
@param {Object} `options` Options to determine limit and property to sort on.
@return {Object} Object of most recent items.
@api public | [
"Return",
"the",
"most",
"recent",
"items",
"on",
"an",
"object",
"."
] | 7858a521be1d8f78c3cf37f058aef1d8a5b6414a | https://github.com/doowb/recent/blob/7858a521be1d8f78c3cf37f058aef1d8a5b6414a/index.js#L25-L55 |
55,378 | doowb/recent | index.js | createdDate | function createdDate(key, value, prop) {
var val = prop ? get(value, prop) : value;
var str = val || key;
var re = /^(\d{4})-(\d{2})-(\d{2})/;
var m = re.exec(str);
if (!m) return null;
return String(m[1]) + String(m[2]) + String(m[3]);
} | javascript | function createdDate(key, value, prop) {
var val = prop ? get(value, prop) : value;
var str = val || key;
var re = /^(\d{4})-(\d{2})-(\d{2})/;
var m = re.exec(str);
if (!m) return null;
return String(m[1]) + String(m[2]) + String(m[3]);
} | [
"function",
"createdDate",
"(",
"key",
",",
"value",
",",
"prop",
")",
"{",
"var",
"val",
"=",
"prop",
"?",
"get",
"(",
"value",
",",
"prop",
")",
":",
"value",
";",
"var",
"str",
"=",
"val",
"||",
"key",
";",
"var",
"re",
"=",
"/",
"^(\\d{4})-(\\d{2})-(\\d{2})",
"/",
";",
"var",
"m",
"=",
"re",
".",
"exec",
"(",
"str",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
"null",
";",
"return",
"String",
"(",
"m",
"[",
"1",
"]",
")",
"+",
"String",
"(",
"m",
"[",
"2",
"]",
")",
"+",
"String",
"(",
"m",
"[",
"3",
"]",
")",
";",
"}"
] | Get the date from a specified property or key.
@param {String} `key` Key used as the fallback when the property is not on the value.
@param {Object} `value` Object to use when finding the property.
@param {String} `prop` Property string to use to get the date.
@return {String} Date string in the format `YYYYMMDD` (e.g. 20150618) | [
"Get",
"the",
"date",
"from",
"a",
"specified",
"property",
"or",
"key",
"."
] | 7858a521be1d8f78c3cf37f058aef1d8a5b6414a | https://github.com/doowb/recent/blob/7858a521be1d8f78c3cf37f058aef1d8a5b6414a/index.js#L66-L74 |
55,379 | AndreasMadsen/immortal | src/setup.js | printError | function printError(error) {
process.stderr.write(red);
console.error(error.trace);
process.stderr.write(yellow);
console.error('an error occurred, please file an issue');
process.stderr.write(reset);
process.exit(1);
} | javascript | function printError(error) {
process.stderr.write(red);
console.error(error.trace);
process.stderr.write(yellow);
console.error('an error occurred, please file an issue');
process.stderr.write(reset);
process.exit(1);
} | [
"function",
"printError",
"(",
"error",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"red",
")",
";",
"console",
".",
"error",
"(",
"error",
".",
"trace",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"yellow",
")",
";",
"console",
".",
"error",
"(",
"'an error occurred, please file an issue'",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"reset",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}"
] | print error text | [
"print",
"error",
"text"
] | c1ab5a4287a543fdfd980604a9e9927d663a9ef2 | https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/src/setup.js#L61-L68 |
55,380 | Nichejs/Seminarjs | private/lib/core/routes.js | routes | function routes(app) {
this.app = app;
var seminarjs = this;
app.get('/version', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({
'name': seminarjs.get('name'),
'seminarjsVersion': seminarjs.version
}));
});
return this;
} | javascript | function routes(app) {
this.app = app;
var seminarjs = this;
app.get('/version', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({
'name': seminarjs.get('name'),
'seminarjsVersion': seminarjs.version
}));
});
return this;
} | [
"function",
"routes",
"(",
"app",
")",
"{",
"this",
".",
"app",
"=",
"app",
";",
"var",
"seminarjs",
"=",
"this",
";",
"app",
".",
"get",
"(",
"'/version'",
",",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
";",
"res",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"'name'",
":",
"seminarjs",
".",
"get",
"(",
"'name'",
")",
",",
"'seminarjsVersion'",
":",
"seminarjs",
".",
"version",
"}",
")",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Adds bindings for the seminarjs routes
####Example:
var app = express();
app.configure(...); // configuration settings
app.use(...); // middleware, routes, etc. should come before seminarjs is initialised
seminarjs.routes(app);
@param {Express()} app
@api public | [
"Adds",
"bindings",
"for",
"the",
"seminarjs",
"routes"
] | 53c4c1d5c33ffbf6320b10f25679bf181cbf853e | https://github.com/Nichejs/Seminarjs/blob/53c4c1d5c33ffbf6320b10f25679bf181cbf853e/private/lib/core/routes.js#L15-L30 |
55,381 | sitegui/constant-equals | bench.js | getSimiliarString | function getSimiliarString(base, relation) {
var length = Math.round(base.length * relation),
r = '',
i, str
do {
str = getRandomString(base.length - length)
} while (str && str[0] === base[length])
for (i = 0; i < length; i++) {
r += base[i] // substr(...) seems to be optimized
}
return r + str
} | javascript | function getSimiliarString(base, relation) {
var length = Math.round(base.length * relation),
r = '',
i, str
do {
str = getRandomString(base.length - length)
} while (str && str[0] === base[length])
for (i = 0; i < length; i++) {
r += base[i] // substr(...) seems to be optimized
}
return r + str
} | [
"function",
"getSimiliarString",
"(",
"base",
",",
"relation",
")",
"{",
"var",
"length",
"=",
"Math",
".",
"round",
"(",
"base",
".",
"length",
"*",
"relation",
")",
",",
"r",
"=",
"''",
",",
"i",
",",
"str",
"do",
"{",
"str",
"=",
"getRandomString",
"(",
"base",
".",
"length",
"-",
"length",
")",
"}",
"while",
"(",
"str",
"&&",
"str",
"[",
"0",
"]",
"===",
"base",
"[",
"length",
"]",
")",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"r",
"+=",
"base",
"[",
"i",
"]",
"// substr(...) seems to be optimized",
"}",
"return",
"r",
"+",
"str",
"}"
] | Generate another string that has the same prefix and length as another one
@param {string} base
@param {number} relation A number from 0 (not equal at all) to 1 (equal strings)
@param {string} | [
"Generate",
"another",
"string",
"that",
"has",
"the",
"same",
"prefix",
"and",
"length",
"as",
"another",
"one"
] | c7e87815854250de3c76b5eea59dfd2586dd6a95 | https://github.com/sitegui/constant-equals/blob/c7e87815854250de3c76b5eea59dfd2586dd6a95/bench.js#L33-L44 |
55,382 | sitegui/constant-equals | bench.js | compare | function compare(a, b, n) {
var n2 = n,
then = Date.now()
while (n2--) {
a === b
}
return (Date.now() - then) * 1e6 / n
} | javascript | function compare(a, b, n) {
var n2 = n,
then = Date.now()
while (n2--) {
a === b
}
return (Date.now() - then) * 1e6 / n
} | [
"function",
"compare",
"(",
"a",
",",
"b",
",",
"n",
")",
"{",
"var",
"n2",
"=",
"n",
",",
"then",
"=",
"Date",
".",
"now",
"(",
")",
"while",
"(",
"n2",
"--",
")",
"{",
"a",
"===",
"b",
"}",
"return",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"then",
")",
"*",
"1e6",
"/",
"n",
"}"
] | Compute a==b n times
@param {string} a
@param {string} b
@param {number} n
@returns {number} The time per comparison (in ns) | [
"Compute",
"a",
"==",
"b",
"n",
"times"
] | c7e87815854250de3c76b5eea59dfd2586dd6a95 | https://github.com/sitegui/constant-equals/blob/c7e87815854250de3c76b5eea59dfd2586dd6a95/bench.js#L53-L60 |
55,383 | sitegui/constant-equals | bench.js | constantCompare | function constantCompare(a, b, n) {
var n2 = n,
then = Date.now(),
eq = false,
len, i
while (n2--) {
len = Math.max(a.length, b.length)
for (i = 0; i < len; i++) {
if (a.length >= i && b.length >= i && a[i] !== b[i]) {
eq = false
}
}
}
return (Date.now() - then) * 1e6 / n
} | javascript | function constantCompare(a, b, n) {
var n2 = n,
then = Date.now(),
eq = false,
len, i
while (n2--) {
len = Math.max(a.length, b.length)
for (i = 0; i < len; i++) {
if (a.length >= i && b.length >= i && a[i] !== b[i]) {
eq = false
}
}
}
return (Date.now() - then) * 1e6 / n
} | [
"function",
"constantCompare",
"(",
"a",
",",
"b",
",",
"n",
")",
"{",
"var",
"n2",
"=",
"n",
",",
"then",
"=",
"Date",
".",
"now",
"(",
")",
",",
"eq",
"=",
"false",
",",
"len",
",",
"i",
"while",
"(",
"n2",
"--",
")",
"{",
"len",
"=",
"Math",
".",
"max",
"(",
"a",
".",
"length",
",",
"b",
".",
"length",
")",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"a",
".",
"length",
">=",
"i",
"&&",
"b",
".",
"length",
">=",
"i",
"&&",
"a",
"[",
"i",
"]",
"!==",
"b",
"[",
"i",
"]",
")",
"{",
"eq",
"=",
"false",
"}",
"}",
"}",
"return",
"(",
"Date",
".",
"now",
"(",
")",
"-",
"then",
")",
"*",
"1e6",
"/",
"n",
"}"
] | Compute a==b n times with a constant algorithm
@param {string} a
@param {string} b
@param {number} n
@returns {number} The time per comparison (in ns) | [
"Compute",
"a",
"==",
"b",
"n",
"times",
"with",
"a",
"constant",
"algorithm"
] | c7e87815854250de3c76b5eea59dfd2586dd6a95 | https://github.com/sitegui/constant-equals/blob/c7e87815854250de3c76b5eea59dfd2586dd6a95/bench.js#L69-L83 |
55,384 | sitegui/constant-equals | bench.js | stat | function stat(fn, n) {
var n2 = n,
times = [],
sum = 0,
t, avg, median
while (n2--) {
t = fn()
sum += t
times.push(t)
}
avg = sum / n
times.sort(function (a, b) {
return a - b
})
median = times[Math.floor(times.length / 2)]
if (times.length % 2 === 0) {
median = (median + times[times.length / 2 - 1]) / 2
}
return {
avg: avg,
median: median
}
} | javascript | function stat(fn, n) {
var n2 = n,
times = [],
sum = 0,
t, avg, median
while (n2--) {
t = fn()
sum += t
times.push(t)
}
avg = sum / n
times.sort(function (a, b) {
return a - b
})
median = times[Math.floor(times.length / 2)]
if (times.length % 2 === 0) {
median = (median + times[times.length / 2 - 1]) / 2
}
return {
avg: avg,
median: median
}
} | [
"function",
"stat",
"(",
"fn",
",",
"n",
")",
"{",
"var",
"n2",
"=",
"n",
",",
"times",
"=",
"[",
"]",
",",
"sum",
"=",
"0",
",",
"t",
",",
"avg",
",",
"median",
"while",
"(",
"n2",
"--",
")",
"{",
"t",
"=",
"fn",
"(",
")",
"sum",
"+=",
"t",
"times",
".",
"push",
"(",
"t",
")",
"}",
"avg",
"=",
"sum",
"/",
"n",
"times",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"-",
"b",
"}",
")",
"median",
"=",
"times",
"[",
"Math",
".",
"floor",
"(",
"times",
".",
"length",
"/",
"2",
")",
"]",
"if",
"(",
"times",
".",
"length",
"%",
"2",
"===",
"0",
")",
"{",
"median",
"=",
"(",
"median",
"+",
"times",
"[",
"times",
".",
"length",
"/",
"2",
"-",
"1",
"]",
")",
"/",
"2",
"}",
"return",
"{",
"avg",
":",
"avg",
",",
"median",
":",
"median",
"}",
"}"
] | Make a statistical experiment on fn
@param {Function} fn A function that receives nothing and returns a number
@param {number} n Number of probes to takes
@returns {{avg: number, median: number}} | [
"Make",
"a",
"statistical",
"experiment",
"on",
"fn"
] | c7e87815854250de3c76b5eea59dfd2586dd6a95 | https://github.com/sitegui/constant-equals/blob/c7e87815854250de3c76b5eea59dfd2586dd6a95/bench.js#L91-L113 |
55,385 | antonycourtney/tabli-core | lib/js/components/util.js | merge | function merge() {
var res = {};
for (var i = 0; i < arguments.length; i++) {
if (arguments[i]) {
Object.assign(res, arguments[i]);
} else {
if (typeof arguments[i] === 'undefined') {
throw new Error('m(): argument ' + i + ' undefined');
}
}
}
return res;
} | javascript | function merge() {
var res = {};
for (var i = 0; i < arguments.length; i++) {
if (arguments[i]) {
Object.assign(res, arguments[i]);
} else {
if (typeof arguments[i] === 'undefined') {
throw new Error('m(): argument ' + i + ' undefined');
}
}
}
return res;
} | [
"function",
"merge",
"(",
")",
"{",
"var",
"res",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"arguments",
"[",
"i",
"]",
")",
"{",
"Object",
".",
"assign",
"(",
"res",
",",
"arguments",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"if",
"(",
"typeof",
"arguments",
"[",
"i",
"]",
"===",
"'undefined'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'m(): argument '",
"+",
"i",
"+",
"' undefined'",
")",
";",
"}",
"}",
"}",
"return",
"res",
";",
"}"
] | Object merge operator from the original css-in-js presentation | [
"Object",
"merge",
"operator",
"from",
"the",
"original",
"css",
"-",
"in",
"-",
"js",
"presentation"
] | 76cc540891421bc6c8bdcf00f277ebb6e716fdd9 | https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/components/util.js#L11-L24 |
55,386 | huang-xiao-jian/gulp-publish | index.js | publish | function publish(opts) {
// stream options
var defaults = {
enableResolve: false,
directory: './build',
debug: false
};
var options = utils.shallowMerge(opts, defaults);
return through(function(file, enc, callback) {
if (file.isNull()) return callback(null, file);
// emit error event when pass stream
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN, 'Streams are not supported!'));
return callback();
}
// resolve the HTML files
var blocks = utils.getSplitBlock(file.contents.toString());
var result = utils.resolveSourceToDestiny(blocks, options);
file.contents = new Buffer(result);
// resolve the files linked by tag script and link
if (options.enableResolve) {
var fileSource = utils.getBlockFileSource(blocks);
utils.resolveFileSource(fileSource, options);
}
callback(null, file);
});
} | javascript | function publish(opts) {
// stream options
var defaults = {
enableResolve: false,
directory: './build',
debug: false
};
var options = utils.shallowMerge(opts, defaults);
return through(function(file, enc, callback) {
if (file.isNull()) return callback(null, file);
// emit error event when pass stream
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN, 'Streams are not supported!'));
return callback();
}
// resolve the HTML files
var blocks = utils.getSplitBlock(file.contents.toString());
var result = utils.resolveSourceToDestiny(blocks, options);
file.contents = new Buffer(result);
// resolve the files linked by tag script and link
if (options.enableResolve) {
var fileSource = utils.getBlockFileSource(blocks);
utils.resolveFileSource(fileSource, options);
}
callback(null, file);
});
} | [
"function",
"publish",
"(",
"opts",
")",
"{",
"// stream options",
"var",
"defaults",
"=",
"{",
"enableResolve",
":",
"false",
",",
"directory",
":",
"'./build'",
",",
"debug",
":",
"false",
"}",
";",
"var",
"options",
"=",
"utils",
".",
"shallowMerge",
"(",
"opts",
",",
"defaults",
")",
";",
"return",
"through",
"(",
"function",
"(",
"file",
",",
"enc",
",",
"callback",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"return",
"callback",
"(",
"null",
",",
"file",
")",
";",
"// emit error event when pass stream",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"gutil",
".",
"PluginError",
"(",
"PLUGIN",
",",
"'Streams are not supported!'",
")",
")",
";",
"return",
"callback",
"(",
")",
";",
"}",
"// resolve the HTML files",
"var",
"blocks",
"=",
"utils",
".",
"getSplitBlock",
"(",
"file",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"var",
"result",
"=",
"utils",
".",
"resolveSourceToDestiny",
"(",
"blocks",
",",
"options",
")",
";",
"file",
".",
"contents",
"=",
"new",
"Buffer",
"(",
"result",
")",
";",
"// resolve the files linked by tag script and link",
"if",
"(",
"options",
".",
"enableResolve",
")",
"{",
"var",
"fileSource",
"=",
"utils",
".",
"getBlockFileSource",
"(",
"blocks",
")",
";",
"utils",
".",
"resolveFileSource",
"(",
"fileSource",
",",
"options",
")",
";",
"}",
"callback",
"(",
"null",
",",
"file",
")",
";",
"}",
")",
";",
"}"
] | Return transform stream which resolve HTML files.
@param {object} opts - stream options
@returns {Stream} | [
"Return",
"transform",
"stream",
"which",
"resolve",
"HTML",
"files",
"."
] | a093c21c523becfe6869fda170efd1cca459c225 | https://github.com/huang-xiao-jian/gulp-publish/blob/a093c21c523becfe6869fda170efd1cca459c225/index.js#L22-L53 |
55,387 | ConnorWiseman/pga | index.js | multiple | function multiple(pool, fn, queries, callback) {
let queryObjects = queries.map(query => {
if (typeof query === 'string') {
return { text: query, values: [] };
}
return Object.assign({ values: [] }, query);
});
if (callback && typeof callback === 'function') {
return fn(pool, queryObjects, callback);
}
return new Promise((resolve, reject) => {
fn(pool, queryObjects, (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
});
} | javascript | function multiple(pool, fn, queries, callback) {
let queryObjects = queries.map(query => {
if (typeof query === 'string') {
return { text: query, values: [] };
}
return Object.assign({ values: [] }, query);
});
if (callback && typeof callback === 'function') {
return fn(pool, queryObjects, callback);
}
return new Promise((resolve, reject) => {
fn(pool, queryObjects, (error, result) => {
if (error) {
return reject(error);
}
resolve(result);
});
});
} | [
"function",
"multiple",
"(",
"pool",
",",
"fn",
",",
"queries",
",",
"callback",
")",
"{",
"let",
"queryObjects",
"=",
"queries",
".",
"map",
"(",
"query",
"=>",
"{",
"if",
"(",
"typeof",
"query",
"===",
"'string'",
")",
"{",
"return",
"{",
"text",
":",
"query",
",",
"values",
":",
"[",
"]",
"}",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"values",
":",
"[",
"]",
"}",
",",
"query",
")",
";",
"}",
")",
";",
"if",
"(",
"callback",
"&&",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"return",
"fn",
"(",
"pool",
",",
"queryObjects",
",",
"callback",
")",
";",
"}",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"fn",
"(",
"pool",
",",
"queryObjects",
",",
"(",
"error",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"reject",
"(",
"error",
")",
";",
"}",
"resolve",
"(",
"result",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Using the specified connection pool, performs the specified function using
a series of queries and a user-defined callback function.
@param {BoundPool} pool
@param {Function} fn
@param {Array.<Object>} queries
@param {Function} callback
@return {Promise}
@private | [
"Using",
"the",
"specified",
"connection",
"pool",
"performs",
"the",
"specified",
"function",
"using",
"a",
"series",
"of",
"queries",
"and",
"a",
"user",
"-",
"defined",
"callback",
"function",
"."
] | 5a186e1039ffe467f40755c6eae0f5deb38e7b41 | https://github.com/ConnorWiseman/pga/blob/5a186e1039ffe467f40755c6eae0f5deb38e7b41/index.js#L22-L44 |
55,388 | ConnorWiseman/pga | index.js | normalize | function normalize(args) {
let result = {
queries: null,
callback: null
};
if (args.length === 1 && Array.isArray(args[0])) {
result.queries = args[0];
} else if (args.length === 2 && Array.isArray(args[0])) {
result.queries = args[0];
if (typeof args[1] === 'function') {
result.callback = args[1];
}
} else {
result.queries = args;
if (typeof result.queries[result.queries.length - 1] === 'function') {
result.callback = result.queries.pop();
}
}
return result;
} | javascript | function normalize(args) {
let result = {
queries: null,
callback: null
};
if (args.length === 1 && Array.isArray(args[0])) {
result.queries = args[0];
} else if (args.length === 2 && Array.isArray(args[0])) {
result.queries = args[0];
if (typeof args[1] === 'function') {
result.callback = args[1];
}
} else {
result.queries = args;
if (typeof result.queries[result.queries.length - 1] === 'function') {
result.callback = result.queries.pop();
}
}
return result;
} | [
"function",
"normalize",
"(",
"args",
")",
"{",
"let",
"result",
"=",
"{",
"queries",
":",
"null",
",",
"callback",
":",
"null",
"}",
";",
"if",
"(",
"args",
".",
"length",
"===",
"1",
"&&",
"Array",
".",
"isArray",
"(",
"args",
"[",
"0",
"]",
")",
")",
"{",
"result",
".",
"queries",
"=",
"args",
"[",
"0",
"]",
";",
"}",
"else",
"if",
"(",
"args",
".",
"length",
"===",
"2",
"&&",
"Array",
".",
"isArray",
"(",
"args",
"[",
"0",
"]",
")",
")",
"{",
"result",
".",
"queries",
"=",
"args",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"args",
"[",
"1",
"]",
"===",
"'function'",
")",
"{",
"result",
".",
"callback",
"=",
"args",
"[",
"1",
"]",
";",
"}",
"}",
"else",
"{",
"result",
".",
"queries",
"=",
"args",
";",
"if",
"(",
"typeof",
"result",
".",
"queries",
"[",
"result",
".",
"queries",
".",
"length",
"-",
"1",
"]",
"===",
"'function'",
")",
"{",
"result",
".",
"callback",
"=",
"result",
".",
"queries",
".",
"pop",
"(",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Normalizes arguments passed to any of the pga methods that handle multiple
queries- parallel or transact.
@param {Array} args [description]
@return {Object}
@private | [
"Normalizes",
"arguments",
"passed",
"to",
"any",
"of",
"the",
"pga",
"methods",
"that",
"handle",
"multiple",
"queries",
"-",
"parallel",
"or",
"transact",
"."
] | 5a186e1039ffe467f40755c6eae0f5deb38e7b41 | https://github.com/ConnorWiseman/pga/blob/5a186e1039ffe467f40755c6eae0f5deb38e7b41/index.js#L54-L77 |
55,389 | ConnorWiseman/pga | index.js | performParallel | function performParallel(pool, queries, callback) {
let count = 0,
results = new Array(queries.length);
queries.forEach((query, index) => {
pool.query(query, (error, result) => {
if (error) {
return callback(error, results);
}
results[index] = result;
if (++count === queries.length) {
return callback(null, results);
}
});
});
} | javascript | function performParallel(pool, queries, callback) {
let count = 0,
results = new Array(queries.length);
queries.forEach((query, index) => {
pool.query(query, (error, result) => {
if (error) {
return callback(error, results);
}
results[index] = result;
if (++count === queries.length) {
return callback(null, results);
}
});
});
} | [
"function",
"performParallel",
"(",
"pool",
",",
"queries",
",",
"callback",
")",
"{",
"let",
"count",
"=",
"0",
",",
"results",
"=",
"new",
"Array",
"(",
"queries",
".",
"length",
")",
";",
"queries",
".",
"forEach",
"(",
"(",
"query",
",",
"index",
")",
"=>",
"{",
"pool",
".",
"query",
"(",
"query",
",",
"(",
"error",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
",",
"results",
")",
";",
"}",
"results",
"[",
"index",
"]",
"=",
"result",
";",
"if",
"(",
"++",
"count",
"===",
"queries",
".",
"length",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Using the specified connection pool, performs a series of specified queries
in parallel, executing a specified callback function once all queries have
successfully completed.
@param {BoundPool} pool
@param {Array.<Object>} queries
@param {Function} callback
@private | [
"Using",
"the",
"specified",
"connection",
"pool",
"performs",
"a",
"series",
"of",
"specified",
"queries",
"in",
"parallel",
"executing",
"a",
"specified",
"callback",
"function",
"once",
"all",
"queries",
"have",
"successfully",
"completed",
"."
] | 5a186e1039ffe467f40755c6eae0f5deb38e7b41 | https://github.com/ConnorWiseman/pga/blob/5a186e1039ffe467f40755c6eae0f5deb38e7b41/index.js#L89-L106 |
55,390 | ConnorWiseman/pga | index.js | performTransaction | function performTransaction(pool, queries, callback) {
pool.connect((error, client, done) => {
if (error) {
done(client);
return callback(error, null);
}
client.query('BEGIN', error => {
if (error) {
return rollback(client, done, error, callback);
}
sequence(queries, (results, current, next) => {
let query = current.text,
params = current.values;
client.query(query, params, (error, result) => {
if (error) {
return rollback(client, done, error, callback);
}
results.push(result);
next();
});
}, (results) => {
client.query('COMMIT', error => {
if (error) {
return rollback(client, done, error, callback);
}
done(client);
return callback(null, results);
});
});
});
});
} | javascript | function performTransaction(pool, queries, callback) {
pool.connect((error, client, done) => {
if (error) {
done(client);
return callback(error, null);
}
client.query('BEGIN', error => {
if (error) {
return rollback(client, done, error, callback);
}
sequence(queries, (results, current, next) => {
let query = current.text,
params = current.values;
client.query(query, params, (error, result) => {
if (error) {
return rollback(client, done, error, callback);
}
results.push(result);
next();
});
}, (results) => {
client.query('COMMIT', error => {
if (error) {
return rollback(client, done, error, callback);
}
done(client);
return callback(null, results);
});
});
});
});
} | [
"function",
"performTransaction",
"(",
"pool",
",",
"queries",
",",
"callback",
")",
"{",
"pool",
".",
"connect",
"(",
"(",
"error",
",",
"client",
",",
"done",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"done",
"(",
"client",
")",
";",
"return",
"callback",
"(",
"error",
",",
"null",
")",
";",
"}",
"client",
".",
"query",
"(",
"'BEGIN'",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"rollback",
"(",
"client",
",",
"done",
",",
"error",
",",
"callback",
")",
";",
"}",
"sequence",
"(",
"queries",
",",
"(",
"results",
",",
"current",
",",
"next",
")",
"=>",
"{",
"let",
"query",
"=",
"current",
".",
"text",
",",
"params",
"=",
"current",
".",
"values",
";",
"client",
".",
"query",
"(",
"query",
",",
"params",
",",
"(",
"error",
",",
"result",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"rollback",
"(",
"client",
",",
"done",
",",
"error",
",",
"callback",
")",
";",
"}",
"results",
".",
"push",
"(",
"result",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"(",
"results",
")",
"=>",
"{",
"client",
".",
"query",
"(",
"'COMMIT'",
",",
"error",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"rollback",
"(",
"client",
",",
"done",
",",
"error",
",",
"callback",
")",
";",
"}",
"done",
"(",
"client",
")",
";",
"return",
"callback",
"(",
"null",
",",
"results",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Using the specified connection pool, performs a series of specified queries
using any specified parameters in sequence, finally executing a specified
callback function with any error or result. Will automatically rollback the
transaction if it fails and commit if it succeeds.
@param {BoundPool} pool
@param {Array.<Object>} queries
@param {Function} callback
@private | [
"Using",
"the",
"specified",
"connection",
"pool",
"performs",
"a",
"series",
"of",
"specified",
"queries",
"using",
"any",
"specified",
"parameters",
"in",
"sequence",
"finally",
"executing",
"a",
"specified",
"callback",
"function",
"with",
"any",
"error",
"or",
"result",
".",
"Will",
"automatically",
"rollback",
"the",
"transaction",
"if",
"it",
"fails",
"and",
"commit",
"if",
"it",
"succeeds",
"."
] | 5a186e1039ffe467f40755c6eae0f5deb38e7b41 | https://github.com/ConnorWiseman/pga/blob/5a186e1039ffe467f40755c6eae0f5deb38e7b41/index.js#L119-L155 |
55,391 | ConnorWiseman/pga | index.js | rollback | function rollback(client, done, error, callback) {
client.query('ROLLBACK', rollbackError => {
done(rollbackError);
return callback(rollbackError || error, null);
});
} | javascript | function rollback(client, done, error, callback) {
client.query('ROLLBACK', rollbackError => {
done(rollbackError);
return callback(rollbackError || error, null);
});
} | [
"function",
"rollback",
"(",
"client",
",",
"done",
",",
"error",
",",
"callback",
")",
"{",
"client",
".",
"query",
"(",
"'ROLLBACK'",
",",
"rollbackError",
"=>",
"{",
"done",
"(",
"rollbackError",
")",
";",
"return",
"callback",
"(",
"rollbackError",
"||",
"error",
",",
"null",
")",
";",
"}",
")",
";",
"}"
] | Rolls back any failed transaction.
@param {Client} client
@param {Function} done
@param {Error} error
@param {Function} callback
@private | [
"Rolls",
"back",
"any",
"failed",
"transaction",
"."
] | 5a186e1039ffe467f40755c6eae0f5deb38e7b41 | https://github.com/ConnorWiseman/pga/blob/5a186e1039ffe467f40755c6eae0f5deb38e7b41/index.js#L166-L171 |
55,392 | cli-kit/cli-property | lib/flatten.js | flatten | function flatten(source, opts) {
opts = opts || {};
var delimiter = opts.delimiter = opts.delimiter || '.';
var o = {};
function iterate(source, parts) {
var k, v;
parts = parts || [];
for(k in source) {
v = source[k];
if(v && typeof v === 'object' && Object.keys(v).length) {
iterate(v, parts.concat(k));
}else{
o[parts.concat(k).join(delimiter)] = v;
}
}
}
iterate(source);
return o;
} | javascript | function flatten(source, opts) {
opts = opts || {};
var delimiter = opts.delimiter = opts.delimiter || '.';
var o = {};
function iterate(source, parts) {
var k, v;
parts = parts || [];
for(k in source) {
v = source[k];
if(v && typeof v === 'object' && Object.keys(v).length) {
iterate(v, parts.concat(k));
}else{
o[parts.concat(k).join(delimiter)] = v;
}
}
}
iterate(source);
return o;
} | [
"function",
"flatten",
"(",
"source",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"delimiter",
"=",
"opts",
".",
"delimiter",
"=",
"opts",
".",
"delimiter",
"||",
"'.'",
";",
"var",
"o",
"=",
"{",
"}",
";",
"function",
"iterate",
"(",
"source",
",",
"parts",
")",
"{",
"var",
"k",
",",
"v",
";",
"parts",
"=",
"parts",
"||",
"[",
"]",
";",
"for",
"(",
"k",
"in",
"source",
")",
"{",
"v",
"=",
"source",
"[",
"k",
"]",
";",
"if",
"(",
"v",
"&&",
"typeof",
"v",
"===",
"'object'",
"&&",
"Object",
".",
"keys",
"(",
"v",
")",
".",
"length",
")",
"{",
"iterate",
"(",
"v",
",",
"parts",
".",
"concat",
"(",
"k",
")",
")",
";",
"}",
"else",
"{",
"o",
"[",
"parts",
".",
"concat",
"(",
"k",
")",
".",
"join",
"(",
"delimiter",
")",
"]",
"=",
"v",
";",
"}",
"}",
"}",
"iterate",
"(",
"source",
")",
";",
"return",
"o",
";",
"}"
] | Flatten an object joining keys on a dot delimiter.
Returns the transformed object.
@param source The source object to transform.
@param opts Processing options.
@param opts.delimiter The string to join keys on. | [
"Flatten",
"an",
"object",
"joining",
"keys",
"on",
"a",
"dot",
"delimiter",
"."
] | de6f727af1f8fc1f613fe42200c5e070aa6b0b21 | https://github.com/cli-kit/cli-property/blob/de6f727af1f8fc1f613fe42200c5e070aa6b0b21/lib/flatten.js#L10-L28 |
55,393 | Ragnarokkr/grunt-bumpx | tasks/bump.js | isValidLevel | function isValidLevel ( level ) {
return reLevel.test( level ) || isFunction( level ) || Array.isArray( level );
} | javascript | function isValidLevel ( level ) {
return reLevel.test( level ) || isFunction( level ) || Array.isArray( level );
} | [
"function",
"isValidLevel",
"(",
"level",
")",
"{",
"return",
"reLevel",
".",
"test",
"(",
"level",
")",
"||",
"isFunction",
"(",
"level",
")",
"||",
"Array",
".",
"isArray",
"(",
"level",
")",
";",
"}"
] | To be valid, a `level` must be one of the values into `supportedLevels`, a function, or an array of functions. | [
"To",
"be",
"valid",
"a",
"level",
"must",
"be",
"one",
"of",
"the",
"values",
"into",
"supportedLevels",
"a",
"function",
"or",
"an",
"array",
"of",
"functions",
"."
] | 24b2f6730d35b9cea7b31c74cf709f501add67f8 | https://github.com/Ragnarokkr/grunt-bumpx/blob/24b2f6730d35b9cea7b31c74cf709f501add67f8/tasks/bump.js#L75-L77 |
55,394 | Ragnarokkr/grunt-bumpx | tasks/bump.js | printMsg | function printMsg ( msgId, data ) {
var outputFn;
if ( messages.hasOwnProperty( msgId) ) {
switch ( msgId.match( /^[A-Z]+/ )[0] ) {
case 'INFO':
outputFn = grunt.log.writeln;
break;
case 'VERBOSE':
outputFn = grunt.verbose.writeln;
break;
case 'DEBUG':
outputFn = grunt.log.debug;
break;
default:
outputFn = grunt.fail.warn;
} // switch
outputFn( grunt.template.process( messages[ msgId ], { data: data } ) );
}
} | javascript | function printMsg ( msgId, data ) {
var outputFn;
if ( messages.hasOwnProperty( msgId) ) {
switch ( msgId.match( /^[A-Z]+/ )[0] ) {
case 'INFO':
outputFn = grunt.log.writeln;
break;
case 'VERBOSE':
outputFn = grunt.verbose.writeln;
break;
case 'DEBUG':
outputFn = grunt.log.debug;
break;
default:
outputFn = grunt.fail.warn;
} // switch
outputFn( grunt.template.process( messages[ msgId ], { data: data } ) );
}
} | [
"function",
"printMsg",
"(",
"msgId",
",",
"data",
")",
"{",
"var",
"outputFn",
";",
"if",
"(",
"messages",
".",
"hasOwnProperty",
"(",
"msgId",
")",
")",
"{",
"switch",
"(",
"msgId",
".",
"match",
"(",
"/",
"^[A-Z]+",
"/",
")",
"[",
"0",
"]",
")",
"{",
"case",
"'INFO'",
":",
"outputFn",
"=",
"grunt",
".",
"log",
".",
"writeln",
";",
"break",
";",
"case",
"'VERBOSE'",
":",
"outputFn",
"=",
"grunt",
".",
"verbose",
".",
"writeln",
";",
"break",
";",
"case",
"'DEBUG'",
":",
"outputFn",
"=",
"grunt",
".",
"log",
".",
"debug",
";",
"break",
";",
"default",
":",
"outputFn",
"=",
"grunt",
".",
"fail",
".",
"warn",
";",
"}",
"// switch",
"outputFn",
"(",
"grunt",
".",
"template",
".",
"process",
"(",
"messages",
"[",
"msgId",
"]",
",",
"{",
"data",
":",
"data",
"}",
")",
")",
";",
"}",
"}"
] | Prints out a message according to the type of message ID. | [
"Prints",
"out",
"a",
"message",
"according",
"to",
"the",
"type",
"of",
"message",
"ID",
"."
] | 24b2f6730d35b9cea7b31c74cf709f501add67f8 | https://github.com/Ragnarokkr/grunt-bumpx/blob/24b2f6730d35b9cea7b31c74cf709f501add67f8/tasks/bump.js#L84-L107 |
55,395 | jimf/checkstyle-formatter | index.js | formatMessage | function formatMessage (message) {
return '<error' +
attr(message, 'line') +
attr(message, 'column') +
attr(message, 'severity') +
attr(message, 'message') +
('source' in message ? attr(message, 'source') : '') +
' />'
} | javascript | function formatMessage (message) {
return '<error' +
attr(message, 'line') +
attr(message, 'column') +
attr(message, 'severity') +
attr(message, 'message') +
('source' in message ? attr(message, 'source') : '') +
' />'
} | [
"function",
"formatMessage",
"(",
"message",
")",
"{",
"return",
"'<error'",
"+",
"attr",
"(",
"message",
",",
"'line'",
")",
"+",
"attr",
"(",
"message",
",",
"'column'",
")",
"+",
"attr",
"(",
"message",
",",
"'severity'",
")",
"+",
"attr",
"(",
"message",
",",
"'message'",
")",
"+",
"(",
"'source'",
"in",
"message",
"?",
"attr",
"(",
"message",
",",
"'source'",
")",
":",
"''",
")",
"+",
"' />'",
"}"
] | Format error line.
@param {object} message Message object to format
@return {string} | [
"Format",
"error",
"line",
"."
] | d4ce7e332552b4ec46cd90e9f1c2e08e19f0b832 | https://github.com/jimf/checkstyle-formatter/blob/d4ce7e332552b4ec46cd90e9f1c2e08e19f0b832/index.js#L25-L33 |
55,396 | jimf/checkstyle-formatter | index.js | formatResult | function formatResult (result) {
return [
'<file name="' + result.filename + '">',
result.messages.map(formatMessage).join('\n'),
'</file>'
].join('\n')
} | javascript | function formatResult (result) {
return [
'<file name="' + result.filename + '">',
result.messages.map(formatMessage).join('\n'),
'</file>'
].join('\n')
} | [
"function",
"formatResult",
"(",
"result",
")",
"{",
"return",
"[",
"'<file name=\"'",
"+",
"result",
".",
"filename",
"+",
"'\">'",
",",
"result",
".",
"messages",
".",
"map",
"(",
"formatMessage",
")",
".",
"join",
"(",
"'\\n'",
")",
",",
"'</file>'",
"]",
".",
"join",
"(",
"'\\n'",
")",
"}"
] | Format results for a single file.
@param {object} result Results for a single file
@param {string} result.filename Filename for these results
@param {object[]} result.messages Warnings/errors for file
@return {string} XML representation for file and results | [
"Format",
"results",
"for",
"a",
"single",
"file",
"."
] | d4ce7e332552b4ec46cd90e9f1c2e08e19f0b832 | https://github.com/jimf/checkstyle-formatter/blob/d4ce7e332552b4ec46cd90e9f1c2e08e19f0b832/index.js#L43-L49 |
55,397 | piranna/easy-coveralls | index.js | restoreLib | function restoreLib(err1)
{
fs.move(ORIG, LIB, {clobber: true}, function(err2)
{
callback(err1 || err2)
})
} | javascript | function restoreLib(err1)
{
fs.move(ORIG, LIB, {clobber: true}, function(err2)
{
callback(err1 || err2)
})
} | [
"function",
"restoreLib",
"(",
"err1",
")",
"{",
"fs",
".",
"move",
"(",
"ORIG",
",",
"LIB",
",",
"{",
"clobber",
":",
"true",
"}",
",",
"function",
"(",
"err2",
")",
"{",
"callback",
"(",
"err1",
"||",
"err2",
")",
"}",
")",
"}"
] | Restore original not-instrumented library | [
"Restore",
"original",
"not",
"-",
"instrumented",
"library"
] | c4e67d769365e3decbf6b48deea48644196ce1cc | https://github.com/piranna/easy-coveralls/blob/c4e67d769365e3decbf6b48deea48644196ce1cc/index.js#L48-L54 |
55,398 | phun-ky/patsy | lib/patsy.js | function(chunk) {
var patsy = this;
chunk = chunk.trim();
if(chunk == 'exit'){
this.scripture.print('[King Arthur]'.magenta + ': On second thought, let\'s not go to Camelot, it\'s a silly place. I am leaving you behind squire!\n');
program.prompt('[Patsy]'.cyan + ': Sire, do you really want to leave me here all alone? [Y/n] (enter for yes): ', function(proceed){
// Did he answer yes? (or DEFAULT)
if (( proceed.search(/yes|y|j|ja/g) !== -1 ) ||
(( proceed.trim() === '' ))) {
util.print('[King Arthur]'.magenta + ': I hold your oath fullfilled!\n');
patsy.die();
}
// Did he answer no?
else if( proceed.search(/no|n|nei/g) !== -1 ) {
util.print('[King Arthur]'.magenta + ': No, I am just pulling your leg mate! \n');
util.print('[Patsy]'.cyan + ': <shrugs> \n');
}
// No valid input
else {
util.print('[King Arthur]'.magenta + ': I can\'t do that!? It\'s to silly! I\'m leaving, come Patsy! <sound of two half coconuts banging together fading out..>\n');
process.exit();
}
});
} else if(chunk == 'test') {
this.scripture.print('[Patsy]'.yellow + ': Running tests!\n');
this.runTests();
}
} | javascript | function(chunk) {
var patsy = this;
chunk = chunk.trim();
if(chunk == 'exit'){
this.scripture.print('[King Arthur]'.magenta + ': On second thought, let\'s not go to Camelot, it\'s a silly place. I am leaving you behind squire!\n');
program.prompt('[Patsy]'.cyan + ': Sire, do you really want to leave me here all alone? [Y/n] (enter for yes): ', function(proceed){
// Did he answer yes? (or DEFAULT)
if (( proceed.search(/yes|y|j|ja/g) !== -1 ) ||
(( proceed.trim() === '' ))) {
util.print('[King Arthur]'.magenta + ': I hold your oath fullfilled!\n');
patsy.die();
}
// Did he answer no?
else if( proceed.search(/no|n|nei/g) !== -1 ) {
util.print('[King Arthur]'.magenta + ': No, I am just pulling your leg mate! \n');
util.print('[Patsy]'.cyan + ': <shrugs> \n');
}
// No valid input
else {
util.print('[King Arthur]'.magenta + ': I can\'t do that!? It\'s to silly! I\'m leaving, come Patsy! <sound of two half coconuts banging together fading out..>\n');
process.exit();
}
});
} else if(chunk == 'test') {
this.scripture.print('[Patsy]'.yellow + ': Running tests!\n');
this.runTests();
}
} | [
"function",
"(",
"chunk",
")",
"{",
"var",
"patsy",
"=",
"this",
";",
"chunk",
"=",
"chunk",
".",
"trim",
"(",
")",
";",
"if",
"(",
"chunk",
"==",
"'exit'",
")",
"{",
"this",
".",
"scripture",
".",
"print",
"(",
"'[King Arthur]'",
".",
"magenta",
"+",
"': On second thought, let\\'s not go to Camelot, it\\'s a silly place. I am leaving you behind squire!\\n'",
")",
";",
"program",
".",
"prompt",
"(",
"'[Patsy]'",
".",
"cyan",
"+",
"': Sire, do you really want to leave me here all alone? [Y/n] (enter for yes): '",
",",
"function",
"(",
"proceed",
")",
"{",
"// Did he answer yes? (or DEFAULT)",
"if",
"(",
"(",
"proceed",
".",
"search",
"(",
"/",
"yes|y|j|ja",
"/",
"g",
")",
"!==",
"-",
"1",
")",
"||",
"(",
"(",
"proceed",
".",
"trim",
"(",
")",
"===",
"''",
")",
")",
")",
"{",
"util",
".",
"print",
"(",
"'[King Arthur]'",
".",
"magenta",
"+",
"': I hold your oath fullfilled!\\n'",
")",
";",
"patsy",
".",
"die",
"(",
")",
";",
"}",
"// Did he answer no?",
"else",
"if",
"(",
"proceed",
".",
"search",
"(",
"/",
"no|n|nei",
"/",
"g",
")",
"!==",
"-",
"1",
")",
"{",
"util",
".",
"print",
"(",
"'[King Arthur]'",
".",
"magenta",
"+",
"': No, I am just pulling your leg mate! \\n'",
")",
";",
"util",
".",
"print",
"(",
"'[Patsy]'",
".",
"cyan",
"+",
"': <shrugs> \\n'",
")",
";",
"}",
"// No valid input",
"else",
"{",
"util",
".",
"print",
"(",
"'[King Arthur]'",
".",
"magenta",
"+",
"': I can\\'t do that!? It\\'s to silly! I\\'m leaving, come Patsy! <sound of two half coconuts banging together fading out..>\\n'",
")",
";",
"process",
".",
"exit",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"chunk",
"==",
"'test'",
")",
"{",
"this",
".",
"scripture",
".",
"print",
"(",
"'[Patsy]'",
".",
"yellow",
"+",
"': Running tests!\\n'",
")",
";",
"this",
".",
"runTests",
"(",
")",
";",
"}",
"}"
] | Function to check current input from stdin
@param String chunk
@calls this.die | [
"Function",
"to",
"check",
"current",
"input",
"from",
"stdin"
] | b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5 | https://github.com/phun-ky/patsy/blob/b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5/lib/patsy.js#L245-L291 |
|
55,399 | phun-ky/patsy | lib/patsy.js | function(relativeProjectPath, relative){
var src = [];
var complete_path;
var patsy = this;
if(patsy.utils.isArray(relative)){
// For each path, check if path is negated, if it is, remove negation
relative.forEach(function(_path){
if(patsy.utils.isPathNegated(_path)){
_path = _path.slice(1);
complete_path = '!' + relativeProjectPath + _path;
} else {
complete_path = relativeProjectPath + _path;
}
src.push(path.normalize(complete_path));
});
} else {
if(patsy.utils.isPathNegated(relative)){
var _path = relative.slice(1);
complete_path = '!' + relativeProjectPath + _path;
} else {
complete_path = relativeProjectPath + relative;
}
src = path.normalize(complete_path);
}
return src;
} | javascript | function(relativeProjectPath, relative){
var src = [];
var complete_path;
var patsy = this;
if(patsy.utils.isArray(relative)){
// For each path, check if path is negated, if it is, remove negation
relative.forEach(function(_path){
if(patsy.utils.isPathNegated(_path)){
_path = _path.slice(1);
complete_path = '!' + relativeProjectPath + _path;
} else {
complete_path = relativeProjectPath + _path;
}
src.push(path.normalize(complete_path));
});
} else {
if(patsy.utils.isPathNegated(relative)){
var _path = relative.slice(1);
complete_path = '!' + relativeProjectPath + _path;
} else {
complete_path = relativeProjectPath + relative;
}
src = path.normalize(complete_path);
}
return src;
} | [
"function",
"(",
"relativeProjectPath",
",",
"relative",
")",
"{",
"var",
"src",
"=",
"[",
"]",
";",
"var",
"complete_path",
";",
"var",
"patsy",
"=",
"this",
";",
"if",
"(",
"patsy",
".",
"utils",
".",
"isArray",
"(",
"relative",
")",
")",
"{",
"// For each path, check if path is negated, if it is, remove negation",
"relative",
".",
"forEach",
"(",
"function",
"(",
"_path",
")",
"{",
"if",
"(",
"patsy",
".",
"utils",
".",
"isPathNegated",
"(",
"_path",
")",
")",
"{",
"_path",
"=",
"_path",
".",
"slice",
"(",
"1",
")",
";",
"complete_path",
"=",
"'!'",
"+",
"relativeProjectPath",
"+",
"_path",
";",
"}",
"else",
"{",
"complete_path",
"=",
"relativeProjectPath",
"+",
"_path",
";",
"}",
"src",
".",
"push",
"(",
"path",
".",
"normalize",
"(",
"complete_path",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"patsy",
".",
"utils",
".",
"isPathNegated",
"(",
"relative",
")",
")",
"{",
"var",
"_path",
"=",
"relative",
".",
"slice",
"(",
"1",
")",
";",
"complete_path",
"=",
"'!'",
"+",
"relativeProjectPath",
"+",
"_path",
";",
"}",
"else",
"{",
"complete_path",
"=",
"relativeProjectPath",
"+",
"relative",
";",
"}",
"src",
"=",
"path",
".",
"normalize",
"(",
"complete_path",
")",
";",
"}",
"return",
"src",
";",
"}"
] | Update relative paths
@param String relativeProjectPah
@param String|Array relative | [
"Update",
"relative",
"paths"
] | b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5 | https://github.com/phun-ky/patsy/blob/b2bf3e6c72e17c38d9b2cf2fa4306478fc3858a5/lib/patsy.js#L723-L762 |
Subsets and Splits