repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
robertblackwell/yake | src/yake/cli_args.js | ParseWithConfig | function ParseWithConfig(config, argv)
{
const debug = false;
const parser = dashdash.createParser({ options : config });
const helpText = parser.help({ includeEnv : true }).trimRight();
try
{
const opts = parser.parse(argv, 2);
const innerOptions = parser.options;
const keyValues = {};
/**
* From opts build a key/value object consting ONLY of the options keys and no extra stuff
* Note that dashdash puts a bunch of other stuff in opts.
* AND then wrap the keyValue object in a CliOptions object for returing
*/
innerOptions.forEach((element) =>
{
const k = element.key;
if (debug) debugLog(`loop k: ${k} v: ${opts[k]}`);
const v = (opts.hasOwnProperty(k)) ? opts[k] : undefined;
keyValues[k] = v;
});
/**
* @NOTE - the next two variables are temporary and disappear when the function is complete
* so there is no need to copy them
*/
const cliOptions = CliOptions(keyValues);
const cliArgs = CliArguments(opts._args);
if (debug) debugLog(util.inspect(cliOptions.getOptions()));
return [cliOptions, cliArgs, helpText];
}
catch (e)
{
debugger;
console.log(e.stack);
raiseError(`Command Line Parser found an error: ${e.message}`);
console.error('Command Line Parser found an error: %s', e.message);
process.exit(1);
}
} | javascript | function ParseWithConfig(config, argv)
{
const debug = false;
const parser = dashdash.createParser({ options : config });
const helpText = parser.help({ includeEnv : true }).trimRight();
try
{
const opts = parser.parse(argv, 2);
const innerOptions = parser.options;
const keyValues = {};
/**
* From opts build a key/value object consting ONLY of the options keys and no extra stuff
* Note that dashdash puts a bunch of other stuff in opts.
* AND then wrap the keyValue object in a CliOptions object for returing
*/
innerOptions.forEach((element) =>
{
const k = element.key;
if (debug) debugLog(`loop k: ${k} v: ${opts[k]}`);
const v = (opts.hasOwnProperty(k)) ? opts[k] : undefined;
keyValues[k] = v;
});
/**
* @NOTE - the next two variables are temporary and disappear when the function is complete
* so there is no need to copy them
*/
const cliOptions = CliOptions(keyValues);
const cliArgs = CliArguments(opts._args);
if (debug) debugLog(util.inspect(cliOptions.getOptions()));
return [cliOptions, cliArgs, helpText];
}
catch (e)
{
debugger;
console.log(e.stack);
raiseError(`Command Line Parser found an error: ${e.message}`);
console.error('Command Line Parser found an error: %s', e.message);
process.exit(1);
}
} | [
"function",
"ParseWithConfig",
"(",
"config",
",",
"argv",
")",
"{",
"const",
"debug",
"=",
"false",
";",
"const",
"parser",
"=",
"dashdash",
".",
"createParser",
"(",
"{",
"options",
":",
"config",
"}",
")",
";",
"const",
"helpText",
"=",
"parser",
".",
"help",
"(",
"{",
"includeEnv",
":",
"true",
"}",
")",
".",
"trimRight",
"(",
")",
";",
"try",
"{",
"const",
"opts",
"=",
"parser",
".",
"parse",
"(",
"argv",
",",
"2",
")",
";",
"const",
"innerOptions",
"=",
"parser",
".",
"options",
";",
"const",
"keyValues",
"=",
"{",
"}",
";",
"innerOptions",
".",
"forEach",
"(",
"(",
"element",
")",
"=>",
"{",
"const",
"k",
"=",
"element",
".",
"key",
";",
"if",
"(",
"debug",
")",
"debugLog",
"(",
"`",
"${",
"k",
"}",
"${",
"opts",
"[",
"k",
"]",
"}",
"`",
")",
";",
"const",
"v",
"=",
"(",
"opts",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"?",
"opts",
"[",
"k",
"]",
":",
"undefined",
";",
"keyValues",
"[",
"k",
"]",
"=",
"v",
";",
"}",
")",
";",
"const",
"cliOptions",
"=",
"CliOptions",
"(",
"keyValues",
")",
";",
"const",
"cliArgs",
"=",
"CliArguments",
"(",
"opts",
".",
"_args",
")",
";",
"if",
"(",
"debug",
")",
"debugLog",
"(",
"util",
".",
"inspect",
"(",
"cliOptions",
".",
"getOptions",
"(",
")",
")",
")",
";",
"return",
"[",
"cliOptions",
",",
"cliArgs",
",",
"helpText",
"]",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debugger",
";",
"console",
".",
"log",
"(",
"e",
".",
"stack",
")",
";",
"raiseError",
"(",
"`",
"${",
"e",
".",
"message",
"}",
"`",
")",
";",
"console",
".",
"error",
"(",
"'Command Line Parser found an error: %s'",
",",
"e",
".",
"message",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
]
| ParseWithConfig - A function that parses an array of command line options and arguments
@param {object} config The configuration
@param {array} argv an array of things like command line options and arguments
@return {array} of CliOptions, CliAruments} returns 2 values via an array.length = 2 | [
"ParseWithConfig",
"-",
"A",
"function",
"that",
"parses",
"an",
"array",
"of",
"command",
"line",
"options",
"and",
"arguments"
]
| 172b02e29303fb718bac88bbda9b85749c57169c | https://github.com/robertblackwell/yake/blob/172b02e29303fb718bac88bbda9b85749c57169c/src/yake/cli_args.js#L295-L340 | train |
pierrec/node-atok-parser | lib/helpers.js | hasEscapeFirst | function hasEscapeFirst (data, offset) {
isBuffer = (!isQuiet && typeof data !== 'string')
escaped = (this.prev.idx > 0)
return escaped
? ( escapeOffset = offset - escLength, -1 )
//HACK to bypass the trimLeft/trimRight properties
: ( this.prev.prev.length = leftLength + 1, atok.offset--, 1 )
} | javascript | function hasEscapeFirst (data, offset) {
isBuffer = (!isQuiet && typeof data !== 'string')
escaped = (this.prev.idx > 0)
return escaped
? ( escapeOffset = offset - escLength, -1 )
//HACK to bypass the trimLeft/trimRight properties
: ( this.prev.prev.length = leftLength + 1, atok.offset--, 1 )
} | [
"function",
"hasEscapeFirst",
"(",
"data",
",",
"offset",
")",
"{",
"isBuffer",
"=",
"(",
"!",
"isQuiet",
"&&",
"typeof",
"data",
"!==",
"'string'",
")",
"escaped",
"=",
"(",
"this",
".",
"prev",
".",
"idx",
">",
"0",
")",
"return",
"escaped",
"?",
"(",
"escapeOffset",
"=",
"offset",
"-",
"escLength",
",",
"-",
"1",
")",
":",
"(",
"this",
".",
"prev",
".",
"prev",
".",
"length",
"=",
"leftLength",
"+",
"1",
",",
"atok",
".",
"offset",
"--",
",",
"1",
")",
"}"
]
| Make the rule fail if an escape char was found | [
"Make",
"the",
"rule",
"fail",
"if",
"an",
"escape",
"char",
"was",
"found"
]
| 414d39904dff73ffdde049212076c14ca40aa20b | https://github.com/pierrec/node-atok-parser/blob/414d39904dff73ffdde049212076c14ca40aa20b/lib/helpers.js#L774-L782 | train |
vitorleal/say-something | lib/say-something.js | function (config) {
'use strict';
//If is not instance of SaySomething return a new instance
if (false === (this instanceof SaySomething)) {
return new SaySomething(config);
}
events.EventEmitter.call(this);
this.defaults = {
language: 'en'
};
//Extend default with the config object
_.extend(this.defaults, config);
return this;
} | javascript | function (config) {
'use strict';
//If is not instance of SaySomething return a new instance
if (false === (this instanceof SaySomething)) {
return new SaySomething(config);
}
events.EventEmitter.call(this);
this.defaults = {
language: 'en'
};
//Extend default with the config object
_.extend(this.defaults, config);
return this;
} | [
"function",
"(",
"config",
")",
"{",
"'use strict'",
";",
"if",
"(",
"false",
"===",
"(",
"this",
"instanceof",
"SaySomething",
")",
")",
"{",
"return",
"new",
"SaySomething",
"(",
"config",
")",
";",
"}",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"defaults",
"=",
"{",
"language",
":",
"'en'",
"}",
";",
"_",
".",
"extend",
"(",
"this",
".",
"defaults",
",",
"config",
")",
";",
"return",
"this",
";",
"}"
]
| Creates an instance of the SaySomething object.
@class
@param config {object} - configuration object.
@param config.language {string} - OPTIONAL (dafault 'en').
@extends EventEmitter
@fires taliking - will be emitted when talking something.
@fires done - will be emitted after say something.
@example
```js
var SaySomething = require('say-something'),
saySomething = new SaySomething({
language: 'pt-br' //default language is 'en'
});
``` | [
"Creates",
"an",
"instance",
"of",
"the",
"SaySomething",
"object",
"."
]
| e197c520dcfa44d267a30f6c10fed521b830e8e1 | https://github.com/vitorleal/say-something/blob/e197c520dcfa44d267a30f6c10fed521b830e8e1/lib/say-something.js#L25-L43 | train |
|
byu-oit/sans-server-swagger | bin/middleware.js | executeController | function executeController(server, controller, req, res) {
try {
const promise = controller.call(server, req, res);
if (promise && typeof promise.catch === 'function') {
promise.catch(function(err) {
res.status(500).send(err);
});
}
} catch (err) {
res.send(err);
}
} | javascript | function executeController(server, controller, req, res) {
try {
const promise = controller.call(server, req, res);
if (promise && typeof promise.catch === 'function') {
promise.catch(function(err) {
res.status(500).send(err);
});
}
} catch (err) {
res.send(err);
}
} | [
"function",
"executeController",
"(",
"server",
",",
"controller",
",",
"req",
",",
"res",
")",
"{",
"try",
"{",
"const",
"promise",
"=",
"controller",
".",
"call",
"(",
"server",
",",
"req",
",",
"res",
")",
";",
"if",
"(",
"promise",
"&&",
"typeof",
"promise",
".",
"catch",
"===",
"'function'",
")",
"{",
"promise",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"res",
".",
"status",
"(",
"500",
")",
".",
"send",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"res",
".",
"send",
"(",
"err",
")",
";",
"}",
"}"
]
| Safely execute a controller.
@param server
@param controller
@param req
@param res | [
"Safely",
"execute",
"a",
"controller",
"."
]
| 455e76b8d65451e606e3c7894ff08affbeb447f1 | https://github.com/byu-oit/sans-server-swagger/blob/455e76b8d65451e606e3c7894ff08affbeb447f1/bin/middleware.js#L311-L322 | train |
byu-oit/sans-server-swagger | bin/middleware.js | findMatchingExample | function findMatchingExample(req, code, type) {
const swagger = req.swagger.root;
const responses = req.swagger.rel.responses;
// if no responses then exit
const responseKeys = responses && typeof responses === 'object' ? Object.keys(responses) : [];
if (responseKeys.length === 0) return { code: 501, type: undefined };
// get first code if not provided
if (arguments.length < 1) code = responseKeys[0];
// validate that responses exist
const responseSchema = responses[code];
if (!responseSchema) return { code: 501, type: undefined };
const examples = responses[code].examples;
const accept = type ?
type :
req.headers.hasOwnProperty('accept')
? req.headers.accept
: Array.isArray(swagger.produces) && swagger.produces.length > 0
? swagger.produces[0]
: examples && Object.keys(examples)[0];
// check if there are examples
const keys = examples ? Object.keys(examples) : [];
const typesLength = keys.length;
if (typesLength === 0) return { code: 501, type: undefined };
// if anything is accepted then return first example
if (accept === '*') return { code: code, type: keys[0] };
// determine what types and subtypes are supported by examples
const types = keys.map(key => {
const ar = key.split('/');
return { type: ar[0] || '*', subtype: ar[1] || '*' };
});
// find all the types that the client accepts
const accepts = accept.split(/,\s*/);
const length = accepts.length;
for (let i = 0; i < length; i++) {
// remove variable from type and separate type and subtype
const item = accepts[i].split(';')[0];
const parts = item.split('/');
const a = {
type: parts[0] || '*',
subtype: parts[1] || '*'
};
// look for a match between types and accepts
for (let j = 0; j < typesLength; j++) {
const t = types[j];
if ((t.type === '*' || a.type === '*' || a.type === t.type) &&
(t.subtype === '*' || a.subtype === '*' || a.subtype === t.subtype)) return { code: code, type: keys[j] };
}
}
return { code: 406, type: undefined };
} | javascript | function findMatchingExample(req, code, type) {
const swagger = req.swagger.root;
const responses = req.swagger.rel.responses;
// if no responses then exit
const responseKeys = responses && typeof responses === 'object' ? Object.keys(responses) : [];
if (responseKeys.length === 0) return { code: 501, type: undefined };
// get first code if not provided
if (arguments.length < 1) code = responseKeys[0];
// validate that responses exist
const responseSchema = responses[code];
if (!responseSchema) return { code: 501, type: undefined };
const examples = responses[code].examples;
const accept = type ?
type :
req.headers.hasOwnProperty('accept')
? req.headers.accept
: Array.isArray(swagger.produces) && swagger.produces.length > 0
? swagger.produces[0]
: examples && Object.keys(examples)[0];
// check if there are examples
const keys = examples ? Object.keys(examples) : [];
const typesLength = keys.length;
if (typesLength === 0) return { code: 501, type: undefined };
// if anything is accepted then return first example
if (accept === '*') return { code: code, type: keys[0] };
// determine what types and subtypes are supported by examples
const types = keys.map(key => {
const ar = key.split('/');
return { type: ar[0] || '*', subtype: ar[1] || '*' };
});
// find all the types that the client accepts
const accepts = accept.split(/,\s*/);
const length = accepts.length;
for (let i = 0; i < length; i++) {
// remove variable from type and separate type and subtype
const item = accepts[i].split(';')[0];
const parts = item.split('/');
const a = {
type: parts[0] || '*',
subtype: parts[1] || '*'
};
// look for a match between types and accepts
for (let j = 0; j < typesLength; j++) {
const t = types[j];
if ((t.type === '*' || a.type === '*' || a.type === t.type) &&
(t.subtype === '*' || a.subtype === '*' || a.subtype === t.subtype)) return { code: code, type: keys[j] };
}
}
return { code: 406, type: undefined };
} | [
"function",
"findMatchingExample",
"(",
"req",
",",
"code",
",",
"type",
")",
"{",
"const",
"swagger",
"=",
"req",
".",
"swagger",
".",
"root",
";",
"const",
"responses",
"=",
"req",
".",
"swagger",
".",
"rel",
".",
"responses",
";",
"const",
"responseKeys",
"=",
"responses",
"&&",
"typeof",
"responses",
"===",
"'object'",
"?",
"Object",
".",
"keys",
"(",
"responses",
")",
":",
"[",
"]",
";",
"if",
"(",
"responseKeys",
".",
"length",
"===",
"0",
")",
"return",
"{",
"code",
":",
"501",
",",
"type",
":",
"undefined",
"}",
";",
"if",
"(",
"arguments",
".",
"length",
"<",
"1",
")",
"code",
"=",
"responseKeys",
"[",
"0",
"]",
";",
"const",
"responseSchema",
"=",
"responses",
"[",
"code",
"]",
";",
"if",
"(",
"!",
"responseSchema",
")",
"return",
"{",
"code",
":",
"501",
",",
"type",
":",
"undefined",
"}",
";",
"const",
"examples",
"=",
"responses",
"[",
"code",
"]",
".",
"examples",
";",
"const",
"accept",
"=",
"type",
"?",
"type",
":",
"req",
".",
"headers",
".",
"hasOwnProperty",
"(",
"'accept'",
")",
"?",
"req",
".",
"headers",
".",
"accept",
":",
"Array",
".",
"isArray",
"(",
"swagger",
".",
"produces",
")",
"&&",
"swagger",
".",
"produces",
".",
"length",
">",
"0",
"?",
"swagger",
".",
"produces",
"[",
"0",
"]",
":",
"examples",
"&&",
"Object",
".",
"keys",
"(",
"examples",
")",
"[",
"0",
"]",
";",
"const",
"keys",
"=",
"examples",
"?",
"Object",
".",
"keys",
"(",
"examples",
")",
":",
"[",
"]",
";",
"const",
"typesLength",
"=",
"keys",
".",
"length",
";",
"if",
"(",
"typesLength",
"===",
"0",
")",
"return",
"{",
"code",
":",
"501",
",",
"type",
":",
"undefined",
"}",
";",
"if",
"(",
"accept",
"===",
"'*'",
")",
"return",
"{",
"code",
":",
"code",
",",
"type",
":",
"keys",
"[",
"0",
"]",
"}",
";",
"const",
"types",
"=",
"keys",
".",
"map",
"(",
"key",
"=>",
"{",
"const",
"ar",
"=",
"key",
".",
"split",
"(",
"'/'",
")",
";",
"return",
"{",
"type",
":",
"ar",
"[",
"0",
"]",
"||",
"'*'",
",",
"subtype",
":",
"ar",
"[",
"1",
"]",
"||",
"'*'",
"}",
";",
"}",
")",
";",
"const",
"accepts",
"=",
"accept",
".",
"split",
"(",
"/",
",\\s*",
"/",
")",
";",
"const",
"length",
"=",
"accepts",
".",
"length",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"const",
"item",
"=",
"accepts",
"[",
"i",
"]",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
";",
"const",
"parts",
"=",
"item",
".",
"split",
"(",
"'/'",
")",
";",
"const",
"a",
"=",
"{",
"type",
":",
"parts",
"[",
"0",
"]",
"||",
"'*'",
",",
"subtype",
":",
"parts",
"[",
"1",
"]",
"||",
"'*'",
"}",
";",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"typesLength",
";",
"j",
"++",
")",
"{",
"const",
"t",
"=",
"types",
"[",
"j",
"]",
";",
"if",
"(",
"(",
"t",
".",
"type",
"===",
"'*'",
"||",
"a",
".",
"type",
"===",
"'*'",
"||",
"a",
".",
"type",
"===",
"t",
".",
"type",
")",
"&&",
"(",
"t",
".",
"subtype",
"===",
"'*'",
"||",
"a",
".",
"subtype",
"===",
"'*'",
"||",
"a",
".",
"subtype",
"===",
"t",
".",
"subtype",
")",
")",
"return",
"{",
"code",
":",
"code",
",",
"type",
":",
"keys",
"[",
"j",
"]",
"}",
";",
"}",
"}",
"return",
"{",
"code",
":",
"406",
",",
"type",
":",
"undefined",
"}",
";",
"}"
]
| Look through swagger examples and find a match based on the accept content type
@param {object} req
@param {string|number} [code]
@param {string} [type]
@returns {{ code: number, type: string|undefined }} | [
"Look",
"through",
"swagger",
"examples",
"and",
"find",
"a",
"match",
"based",
"on",
"the",
"accept",
"content",
"type"
]
| 455e76b8d65451e606e3c7894ff08affbeb447f1 | https://github.com/byu-oit/sans-server-swagger/blob/455e76b8d65451e606e3c7894ff08affbeb447f1/bin/middleware.js#L331-L391 | train |
byu-oit/sans-server-swagger | bin/middleware.js | loadController | function loadController(controllersDirectory, controller, development) {
const filePath = path.resolve(controllersDirectory, controller);
try {
return require(filePath);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf("Cannot find module '" + filePath + "'") === 0 && development) {
console.error('Cannot find controller: ' + filePath);
return null;
} else {
throw e;
}
}
} | javascript | function loadController(controllersDirectory, controller, development) {
const filePath = path.resolve(controllersDirectory, controller);
try {
return require(filePath);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND' && e.message.indexOf("Cannot find module '" + filePath + "'") === 0 && development) {
console.error('Cannot find controller: ' + filePath);
return null;
} else {
throw e;
}
}
} | [
"function",
"loadController",
"(",
"controllersDirectory",
",",
"controller",
",",
"development",
")",
"{",
"const",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"controllersDirectory",
",",
"controller",
")",
";",
"try",
"{",
"return",
"require",
"(",
"filePath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"===",
"'MODULE_NOT_FOUND'",
"&&",
"e",
".",
"message",
".",
"indexOf",
"(",
"\"Cannot find module '\"",
"+",
"filePath",
"+",
"\"'\"",
")",
"===",
"0",
"&&",
"development",
")",
"{",
"console",
".",
"error",
"(",
"'Cannot find controller: '",
"+",
"filePath",
")",
";",
"return",
"null",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
"}"
]
| Attempt to load a node module as a controller.
@param {string} controllersDirectory
@param {string} controller
@param {boolean} development
@returns {*} | [
"Attempt",
"to",
"load",
"a",
"node",
"module",
"as",
"a",
"controller",
"."
]
| 455e76b8d65451e606e3c7894ff08affbeb447f1 | https://github.com/byu-oit/sans-server-swagger/blob/455e76b8d65451e606e3c7894ff08affbeb447f1/bin/middleware.js#L400-L412 | train |
niallo/deadlift | lib/heroku.js | full_uri_encode | function full_uri_encode(string) {
string = encodeURIComponent(string);
string = string.replace(/\./g, '%2E');
return(string);
} | javascript | function full_uri_encode(string) {
string = encodeURIComponent(string);
string = string.replace(/\./g, '%2E');
return(string);
} | [
"function",
"full_uri_encode",
"(",
"string",
")",
"{",
"string",
"=",
"encodeURIComponent",
"(",
"string",
")",
";",
"string",
"=",
"string",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"'%2E'",
")",
";",
"return",
"(",
"string",
")",
";",
"}"
]
| Special Heroku URI encoding. Used for key deletes. | [
"Special",
"Heroku",
"URI",
"encoding",
".",
"Used",
"for",
"key",
"deletes",
"."
]
| ff37d4eeccc326ec5e1390394585f6ac10bcc703 | https://github.com/niallo/deadlift/blob/ff37d4eeccc326ec5e1390394585f6ac10bcc703/lib/heroku.js#L97-L101 | train |
niallo/deadlift | lib/heroku.js | function(err, privkey, pubkey) {
if (err) throw err;
this.pubkey = pubkey;
this.privkey = privkey;
this.user_host_field = pubkey.split(' ')[2].trim();
console.log("Adding Heroku SSH keypair via API");
add_ssh_key(api_key, pubkey, this);
} | javascript | function(err, privkey, pubkey) {
if (err) throw err;
this.pubkey = pubkey;
this.privkey = privkey;
this.user_host_field = pubkey.split(' ')[2].trim();
console.log("Adding Heroku SSH keypair via API");
add_ssh_key(api_key, pubkey, this);
} | [
"function",
"(",
"err",
",",
"privkey",
",",
"pubkey",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"this",
".",
"pubkey",
"=",
"pubkey",
";",
"this",
".",
"privkey",
"=",
"privkey",
";",
"this",
".",
"user_host_field",
"=",
"pubkey",
".",
"split",
"(",
"' '",
")",
"[",
"2",
"]",
".",
"trim",
"(",
")",
";",
"console",
".",
"log",
"(",
"\"Adding Heroku SSH keypair via API\"",
")",
";",
"add_ssh_key",
"(",
"api_key",
",",
"pubkey",
",",
"this",
")",
";",
"}"
]
| Add keypair to Heroku account | [
"Add",
"keypair",
"to",
"Heroku",
"account"
]
| ff37d4eeccc326ec5e1390394585f6ac10bcc703 | https://github.com/niallo/deadlift/blob/ff37d4eeccc326ec5e1390394585f6ac10bcc703/lib/heroku.js#L139-L146 | train |
|
niallo/deadlift | lib/heroku.js | function(err, r, b) {
if (err) throw err;
try {
fs.unlink(keyname, this.parallel());
fs.unlink(keyname + ".pub", this.parallel());
} catch(e) {
// do nothing
};
console.log("Heroku SSH keypair deleted from local FS");
callback(err, this.privkey, this.pubkey, this.user_host_field);
} | javascript | function(err, r, b) {
if (err) throw err;
try {
fs.unlink(keyname, this.parallel());
fs.unlink(keyname + ".pub", this.parallel());
} catch(e) {
// do nothing
};
console.log("Heroku SSH keypair deleted from local FS");
callback(err, this.privkey, this.pubkey, this.user_host_field);
} | [
"function",
"(",
"err",
",",
"r",
",",
"b",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"try",
"{",
"fs",
".",
"unlink",
"(",
"keyname",
",",
"this",
".",
"parallel",
"(",
")",
")",
";",
"fs",
".",
"unlink",
"(",
"keyname",
"+",
"\".pub\"",
",",
"this",
".",
"parallel",
"(",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
";",
"console",
".",
"log",
"(",
"\"Heroku SSH keypair deleted from local FS\"",
")",
";",
"callback",
"(",
"err",
",",
"this",
".",
"privkey",
",",
"this",
".",
"pubkey",
",",
"this",
".",
"user_host_field",
")",
";",
"}"
]
| SSH key has been added, unlink files | [
"SSH",
"key",
"has",
"been",
"added",
"unlink",
"files"
]
| ff37d4eeccc326ec5e1390394585f6ac10bcc703 | https://github.com/niallo/deadlift/blob/ff37d4eeccc326ec5e1390394585f6ac10bcc703/lib/heroku.js#L148-L158 | train |
|
GrabarzUndPartner/gp-module-base | install.js | preparePackage | function preparePackage() {
var ignoreFiles = ['package.json', 'README.md', 'LICENSE.md', '.gitignore', '.npmignore'];
var ignoreCopyFiles = [];
var copyRecursiveSync = function(src, dest) {
var exists = fs.existsSync(src);
var stats = exists && fs.statSync(src);
var isDirectory = exists && stats.isDirectory();
if (exists && isDirectory) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).forEach(function(filename) {
copyRecursiveSync(upath.join(src, filename),
upath.join(dest, filename));
});
} else {
if (ignoreCopyFiles.indexOf(upath.basename(src)) === -1) {
fs.linkSync(src, dest);
}
}
};
var srcPkg = upath.join(process.cwd(), 'src');
if (fs.existsSync(srcPkg)) {
fs.readdirSync(process.cwd()).forEach(function(filename) {
var curPath = upath.join(process.cwd(), filename);
if (ignoreFiles.indexOf(upath.basename(curPath)) === -1 && fs.statSync(curPath).isFile()) {
fs.unlinkSync(curPath);
}
});
copyRecursiveSync(srcPkg, process.cwd());
}
deleteFolderRecursive(srcPkg);
deleteFolderRecursive(upath.join(process.cwd(), 'test'));
deleteFolderRecursive(upath.join(process.cwd(), 'env'));
} | javascript | function preparePackage() {
var ignoreFiles = ['package.json', 'README.md', 'LICENSE.md', '.gitignore', '.npmignore'];
var ignoreCopyFiles = [];
var copyRecursiveSync = function(src, dest) {
var exists = fs.existsSync(src);
var stats = exists && fs.statSync(src);
var isDirectory = exists && stats.isDirectory();
if (exists && isDirectory) {
if (!fs.existsSync(dest)) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).forEach(function(filename) {
copyRecursiveSync(upath.join(src, filename),
upath.join(dest, filename));
});
} else {
if (ignoreCopyFiles.indexOf(upath.basename(src)) === -1) {
fs.linkSync(src, dest);
}
}
};
var srcPkg = upath.join(process.cwd(), 'src');
if (fs.existsSync(srcPkg)) {
fs.readdirSync(process.cwd()).forEach(function(filename) {
var curPath = upath.join(process.cwd(), filename);
if (ignoreFiles.indexOf(upath.basename(curPath)) === -1 && fs.statSync(curPath).isFile()) {
fs.unlinkSync(curPath);
}
});
copyRecursiveSync(srcPkg, process.cwd());
}
deleteFolderRecursive(srcPkg);
deleteFolderRecursive(upath.join(process.cwd(), 'test'));
deleteFolderRecursive(upath.join(process.cwd(), 'env'));
} | [
"function",
"preparePackage",
"(",
")",
"{",
"var",
"ignoreFiles",
"=",
"[",
"'package.json'",
",",
"'README.md'",
",",
"'LICENSE.md'",
",",
"'.gitignore'",
",",
"'.npmignore'",
"]",
";",
"var",
"ignoreCopyFiles",
"=",
"[",
"]",
";",
"var",
"copyRecursiveSync",
"=",
"function",
"(",
"src",
",",
"dest",
")",
"{",
"var",
"exists",
"=",
"fs",
".",
"existsSync",
"(",
"src",
")",
";",
"var",
"stats",
"=",
"exists",
"&&",
"fs",
".",
"statSync",
"(",
"src",
")",
";",
"var",
"isDirectory",
"=",
"exists",
"&&",
"stats",
".",
"isDirectory",
"(",
")",
";",
"if",
"(",
"exists",
"&&",
"isDirectory",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dest",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"dest",
")",
";",
"}",
"fs",
".",
"readdirSync",
"(",
"src",
")",
".",
"forEach",
"(",
"function",
"(",
"filename",
")",
"{",
"copyRecursiveSync",
"(",
"upath",
".",
"join",
"(",
"src",
",",
"filename",
")",
",",
"upath",
".",
"join",
"(",
"dest",
",",
"filename",
")",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"if",
"(",
"ignoreCopyFiles",
".",
"indexOf",
"(",
"upath",
".",
"basename",
"(",
"src",
")",
")",
"===",
"-",
"1",
")",
"{",
"fs",
".",
"linkSync",
"(",
"src",
",",
"dest",
")",
";",
"}",
"}",
"}",
";",
"var",
"srcPkg",
"=",
"upath",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'src'",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"srcPkg",
")",
")",
"{",
"fs",
".",
"readdirSync",
"(",
"process",
".",
"cwd",
"(",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"filename",
")",
"{",
"var",
"curPath",
"=",
"upath",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"filename",
")",
";",
"if",
"(",
"ignoreFiles",
".",
"indexOf",
"(",
"upath",
".",
"basename",
"(",
"curPath",
")",
")",
"===",
"-",
"1",
"&&",
"fs",
".",
"statSync",
"(",
"curPath",
")",
".",
"isFile",
"(",
")",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"curPath",
")",
";",
"}",
"}",
")",
";",
"copyRecursiveSync",
"(",
"srcPkg",
",",
"process",
".",
"cwd",
"(",
")",
")",
";",
"}",
"deleteFolderRecursive",
"(",
"srcPkg",
")",
";",
"deleteFolderRecursive",
"(",
"upath",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'test'",
")",
")",
";",
"deleteFolderRecursive",
"(",
"upath",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'env'",
")",
")",
";",
"}"
]
| Clean package root and exclude src | [
"Clean",
"package",
"root",
"and",
"exclude",
"src"
]
| d255cf6cfec7d783b591dc6f5c4ef60ce913013c | https://github.com/GrabarzUndPartner/gp-module-base/blob/d255cf6cfec7d783b591dc6f5c4ef60ce913013c/install.js#L23-L57 | train |
jhermsmeier/node-bloodline | bloodline.js | describe | function describe( object ) {
return Object.getOwnPropertyNames( object )
.reduce( function( desc, key ) {
desc[ key ] = Object.getOwnPropertyDescriptor( object, key )
return desc
}, Object.create( null ))
} | javascript | function describe( object ) {
return Object.getOwnPropertyNames( object )
.reduce( function( desc, key ) {
desc[ key ] = Object.getOwnPropertyDescriptor( object, key )
return desc
}, Object.create( null ))
} | [
"function",
"describe",
"(",
"object",
")",
"{",
"return",
"Object",
".",
"getOwnPropertyNames",
"(",
"object",
")",
".",
"reduce",
"(",
"function",
"(",
"desc",
",",
"key",
")",
"{",
"desc",
"[",
"key",
"]",
"=",
"Object",
".",
"getOwnPropertyDescriptor",
"(",
"object",
",",
"key",
")",
"return",
"desc",
"}",
",",
"Object",
".",
"create",
"(",
"null",
")",
")",
"}"
]
| Retrieves an object's description
@param {Object} object
@return {Object} description | [
"Retrieves",
"an",
"object",
"s",
"description"
]
| a789250ca2f4d2dc7f3f653aaf784197ea3b3aeb | https://github.com/jhermsmeier/node-bloodline/blob/a789250ca2f4d2dc7f3f653aaf784197ea3b3aeb/bloodline.js#L6-L12 | train |
jhermsmeier/node-bloodline | bloodline.js | inherit | function inherit( ctor, sctor ) {
ctor.prototype = Object.create(
sctor.prototype,
describe( ctor.prototype )
)
} | javascript | function inherit( ctor, sctor ) {
ctor.prototype = Object.create(
sctor.prototype,
describe( ctor.prototype )
)
} | [
"function",
"inherit",
"(",
"ctor",
",",
"sctor",
")",
"{",
"ctor",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"sctor",
".",
"prototype",
",",
"describe",
"(",
"ctor",
".",
"prototype",
")",
")",
"}"
]
| Inherits from sctor to ctor
@param {Function} ctor
@param {Function} sctor
@return {Object} | [
"Inherits",
"from",
"sctor",
"to",
"ctor"
]
| a789250ca2f4d2dc7f3f653aaf784197ea3b3aeb | https://github.com/jhermsmeier/node-bloodline/blob/a789250ca2f4d2dc7f3f653aaf784197ea3b3aeb/bloodline.js#L20-L25 | train |
tsunammis/command-asker.js | lib/command-asker.js | CommandAsker | function CommandAsker(questions, options) {
options = options || {};
if (!_.isArray(questions)) {
throw "there are no questions available :'(";
}
this.questions = questions;
this.response = {};
this.cli = readline.createInterface({
input: process.stdin,
output: process.stdout
});
this.askCallback = null;
this.errorMsg = options.errorMsg || clc.xterm(160);
this.currentQuestion = 0;
} | javascript | function CommandAsker(questions, options) {
options = options || {};
if (!_.isArray(questions)) {
throw "there are no questions available :'(";
}
this.questions = questions;
this.response = {};
this.cli = readline.createInterface({
input: process.stdin,
output: process.stdout
});
this.askCallback = null;
this.errorMsg = options.errorMsg || clc.xterm(160);
this.currentQuestion = 0;
} | [
"function",
"CommandAsker",
"(",
"questions",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"questions",
")",
")",
"{",
"throw",
"\"there are no questions available :'(\"",
";",
"}",
"this",
".",
"questions",
"=",
"questions",
";",
"this",
".",
"response",
"=",
"{",
"}",
";",
"this",
".",
"cli",
"=",
"readline",
".",
"createInterface",
"(",
"{",
"input",
":",
"process",
".",
"stdin",
",",
"output",
":",
"process",
".",
"stdout",
"}",
")",
";",
"this",
".",
"askCallback",
"=",
"null",
";",
"this",
".",
"errorMsg",
"=",
"options",
".",
"errorMsg",
"||",
"clc",
".",
"xterm",
"(",
"160",
")",
";",
"this",
".",
"currentQuestion",
"=",
"0",
";",
"}"
]
| Create new asker
@constructor | [
"Create",
"new",
"asker"
]
| e157862cdb37fba4b89a0b98c25dc9037a64e1a9 | https://github.com/tsunammis/command-asker.js/blob/e157862cdb37fba4b89a0b98c25dc9037a64e1a9/lib/command-asker.js#L21-L37 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | function( editor ) {
// Backward compatibility.
if ( editor instanceof CKEDITOR.dom.document )
return applyStyleOnSelection.call( this, editor.getSelection() );
if ( this.checkApplicable( editor.elementPath(), editor ) ) {
var initialEnterMode = this._.enterMode;
// See comment in removeStyle.
if ( !initialEnterMode )
this._.enterMode = editor.activeEnterMode;
applyStyleOnSelection.call( this, editor.getSelection(), 0, editor );
this._.enterMode = initialEnterMode;
}
} | javascript | function( editor ) {
// Backward compatibility.
if ( editor instanceof CKEDITOR.dom.document )
return applyStyleOnSelection.call( this, editor.getSelection() );
if ( this.checkApplicable( editor.elementPath(), editor ) ) {
var initialEnterMode = this._.enterMode;
// See comment in removeStyle.
if ( !initialEnterMode )
this._.enterMode = editor.activeEnterMode;
applyStyleOnSelection.call( this, editor.getSelection(), 0, editor );
this._.enterMode = initialEnterMode;
}
} | [
"function",
"(",
"editor",
")",
"{",
"if",
"(",
"editor",
"instanceof",
"CKEDITOR",
".",
"dom",
".",
"document",
")",
"return",
"applyStyleOnSelection",
".",
"call",
"(",
"this",
",",
"editor",
".",
"getSelection",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"checkApplicable",
"(",
"editor",
".",
"elementPath",
"(",
")",
",",
"editor",
")",
")",
"{",
"var",
"initialEnterMode",
"=",
"this",
".",
"_",
".",
"enterMode",
";",
"if",
"(",
"!",
"initialEnterMode",
")",
"this",
".",
"_",
".",
"enterMode",
"=",
"editor",
".",
"activeEnterMode",
";",
"applyStyleOnSelection",
".",
"call",
"(",
"this",
",",
"editor",
".",
"getSelection",
"(",
")",
",",
"0",
",",
"editor",
")",
";",
"this",
".",
"_",
".",
"enterMode",
"=",
"initialEnterMode",
";",
"}",
"}"
]
| Applies the style on the editor's current selection.
Before the style is applied, the method checks if the {@link #checkApplicable style is applicable}.
**Note:** The recommended way of applying the style is by using the
{@link CKEDITOR.editor#applyStyle} method, which is a shorthand for this method.
@param {CKEDITOR.editor/CKEDITOR.dom.document} editor The editor instance in which
the style will be applied.
A {@link CKEDITOR.dom.document} instance is accepted for backward compatibility
reasons, although since CKEditor 4.4 this type of argument is deprecated. Read more about
the signature change in the {@link CKEDITOR.style} documentation. | [
"Applies",
"the",
"style",
"on",
"the",
"editor",
"s",
"current",
"selection",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L199-L213 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | function( elementPath, editor, filter ) {
// Backward compatibility.
if ( editor && editor instanceof CKEDITOR.filter )
filter = editor;
if ( filter && !filter.check( this ) )
return false;
switch ( this.type ) {
case CKEDITOR.STYLE_OBJECT:
return !!elementPath.contains( this.element );
case CKEDITOR.STYLE_BLOCK:
return !!elementPath.blockLimit.getDtd()[ this.element ];
}
return true;
} | javascript | function( elementPath, editor, filter ) {
// Backward compatibility.
if ( editor && editor instanceof CKEDITOR.filter )
filter = editor;
if ( filter && !filter.check( this ) )
return false;
switch ( this.type ) {
case CKEDITOR.STYLE_OBJECT:
return !!elementPath.contains( this.element );
case CKEDITOR.STYLE_BLOCK:
return !!elementPath.blockLimit.getDtd()[ this.element ];
}
return true;
} | [
"function",
"(",
"elementPath",
",",
"editor",
",",
"filter",
")",
"{",
"if",
"(",
"editor",
"&&",
"editor",
"instanceof",
"CKEDITOR",
".",
"filter",
")",
"filter",
"=",
"editor",
";",
"if",
"(",
"filter",
"&&",
"!",
"filter",
".",
"check",
"(",
"this",
")",
")",
"return",
"false",
";",
"switch",
"(",
"this",
".",
"type",
")",
"{",
"case",
"CKEDITOR",
".",
"STYLE_OBJECT",
":",
"return",
"!",
"!",
"elementPath",
".",
"contains",
"(",
"this",
".",
"element",
")",
";",
"case",
"CKEDITOR",
".",
"STYLE_BLOCK",
":",
"return",
"!",
"!",
"elementPath",
".",
"blockLimit",
".",
"getDtd",
"(",
")",
"[",
"this",
".",
"element",
"]",
";",
"}",
"return",
"true",
";",
"}"
]
| Whether this style can be applied at the specified elements path.
@param {CKEDITOR.dom.elementPath} elementPath The elements path to
check the style against.
@param {CKEDITOR.editor} editor The editor instance. Required argument since
CKEditor 4.4. The style system will work without it, but it is highly
recommended to provide it for integration with all features. Read more about
the signature change in the {@link CKEDITOR.style} documentation.
@param {CKEDITOR.filter} [filter] If defined, the style will be
checked against this filter as well.
@returns {Boolean} `true` if this style can be applied at the elements path. | [
"Whether",
"this",
"style",
"can",
"be",
"applied",
"at",
"the",
"specified",
"elements",
"path",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L365-L381 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | function( element, fullMatch ) {
var def = this._.definition;
if ( !element || !def.ignoreReadonly && element.isReadOnly() )
return false;
var attribs,
name = element.getName();
// If the element name is the same as the style name.
if ( typeof this.element == 'string' ? name == this.element : name in this.element ) {
// If no attributes are defined in the element.
if ( !fullMatch && !element.hasAttributes() )
return true;
attribs = getAttributesForComparison( def );
if ( attribs._length ) {
for ( var attName in attribs ) {
if ( attName == '_length' )
continue;
var elementAttr = element.getAttribute( attName ) || '';
// Special treatment for 'style' attribute is required.
if ( attName == 'style' ? compareCssText( attribs[ attName ], elementAttr ) : attribs[ attName ] == elementAttr ) {
if ( !fullMatch )
return true;
} else if ( fullMatch ) {
return false;
}
}
if ( fullMatch )
return true;
} else {
return true;
}
}
return false;
} | javascript | function( element, fullMatch ) {
var def = this._.definition;
if ( !element || !def.ignoreReadonly && element.isReadOnly() )
return false;
var attribs,
name = element.getName();
// If the element name is the same as the style name.
if ( typeof this.element == 'string' ? name == this.element : name in this.element ) {
// If no attributes are defined in the element.
if ( !fullMatch && !element.hasAttributes() )
return true;
attribs = getAttributesForComparison( def );
if ( attribs._length ) {
for ( var attName in attribs ) {
if ( attName == '_length' )
continue;
var elementAttr = element.getAttribute( attName ) || '';
// Special treatment for 'style' attribute is required.
if ( attName == 'style' ? compareCssText( attribs[ attName ], elementAttr ) : attribs[ attName ] == elementAttr ) {
if ( !fullMatch )
return true;
} else if ( fullMatch ) {
return false;
}
}
if ( fullMatch )
return true;
} else {
return true;
}
}
return false;
} | [
"function",
"(",
"element",
",",
"fullMatch",
")",
"{",
"var",
"def",
"=",
"this",
".",
"_",
".",
"definition",
";",
"if",
"(",
"!",
"element",
"||",
"!",
"def",
".",
"ignoreReadonly",
"&&",
"element",
".",
"isReadOnly",
"(",
")",
")",
"return",
"false",
";",
"var",
"attribs",
",",
"name",
"=",
"element",
".",
"getName",
"(",
")",
";",
"if",
"(",
"typeof",
"this",
".",
"element",
"==",
"'string'",
"?",
"name",
"==",
"this",
".",
"element",
":",
"name",
"in",
"this",
".",
"element",
")",
"{",
"if",
"(",
"!",
"fullMatch",
"&&",
"!",
"element",
".",
"hasAttributes",
"(",
")",
")",
"return",
"true",
";",
"attribs",
"=",
"getAttributesForComparison",
"(",
"def",
")",
";",
"if",
"(",
"attribs",
".",
"_length",
")",
"{",
"for",
"(",
"var",
"attName",
"in",
"attribs",
")",
"{",
"if",
"(",
"attName",
"==",
"'_length'",
")",
"continue",
";",
"var",
"elementAttr",
"=",
"element",
".",
"getAttribute",
"(",
"attName",
")",
"||",
"''",
";",
"if",
"(",
"attName",
"==",
"'style'",
"?",
"compareCssText",
"(",
"attribs",
"[",
"attName",
"]",
",",
"elementAttr",
")",
":",
"attribs",
"[",
"attName",
"]",
"==",
"elementAttr",
")",
"{",
"if",
"(",
"!",
"fullMatch",
")",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"fullMatch",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"fullMatch",
")",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
]
| Checks if the element matches the current style definition.
@param {CKEDITOR.dom.element} element
@param {Boolean} fullMatch
@param {CKEDITOR.editor} editor The editor instance. Required argument since
CKEditor 4.4. The style system will work without it, but it is highly
recommended to provide it for integration with all features. Read more about
the signature change in the {@link CKEDITOR.style} documentation.
@returns {Boolean} | [
"Checks",
"if",
"the",
"element",
"matches",
"the",
"current",
"style",
"definition",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L394-L434 | train |
|
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | checkIfNodeCanBeChildOfStyle | function checkIfNodeCanBeChildOfStyle( def, currentNode, lastNode, nodeName, dtd, nodeIsNoStyle, nodeIsReadonly, includeReadonly ) {
// Style can be applied to text node.
if ( !nodeName )
return 1;
// Style definitely cannot be applied if DTD or data-nostyle do not allow.
if ( !dtd[ nodeName ] || nodeIsNoStyle )
return 0;
// Non-editable element cannot be styled is we shouldn't include readonly elements.
if ( nodeIsReadonly && !includeReadonly )
return 0;
// Check that we haven't passed lastNode yet and that style's childRule allows this style on current element.
return checkPositionAndRule( currentNode, lastNode, def, posPrecedingIdenticalContained );
} | javascript | function checkIfNodeCanBeChildOfStyle( def, currentNode, lastNode, nodeName, dtd, nodeIsNoStyle, nodeIsReadonly, includeReadonly ) {
// Style can be applied to text node.
if ( !nodeName )
return 1;
// Style definitely cannot be applied if DTD or data-nostyle do not allow.
if ( !dtd[ nodeName ] || nodeIsNoStyle )
return 0;
// Non-editable element cannot be styled is we shouldn't include readonly elements.
if ( nodeIsReadonly && !includeReadonly )
return 0;
// Check that we haven't passed lastNode yet and that style's childRule allows this style on current element.
return checkPositionAndRule( currentNode, lastNode, def, posPrecedingIdenticalContained );
} | [
"function",
"checkIfNodeCanBeChildOfStyle",
"(",
"def",
",",
"currentNode",
",",
"lastNode",
",",
"nodeName",
",",
"dtd",
",",
"nodeIsNoStyle",
",",
"nodeIsReadonly",
",",
"includeReadonly",
")",
"{",
"if",
"(",
"!",
"nodeName",
")",
"return",
"1",
";",
"if",
"(",
"!",
"dtd",
"[",
"nodeName",
"]",
"||",
"nodeIsNoStyle",
")",
"return",
"0",
";",
"if",
"(",
"nodeIsReadonly",
"&&",
"!",
"includeReadonly",
")",
"return",
"0",
";",
"return",
"checkPositionAndRule",
"(",
"currentNode",
",",
"lastNode",
",",
"def",
",",
"posPrecedingIdenticalContained",
")",
";",
"}"
]
| Checks if the current node can be a child of the style element. | [
"Checks",
"if",
"the",
"current",
"node",
"can",
"be",
"a",
"child",
"of",
"the",
"style",
"element",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L753-L768 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | checkIfStyleCanBeChildOf | function checkIfStyleCanBeChildOf( def, currentParent, elementName, isUnknownElement ) {
return currentParent &&
( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement ) &&
( !def.parentRule || def.parentRule( currentParent ) );
} | javascript | function checkIfStyleCanBeChildOf( def, currentParent, elementName, isUnknownElement ) {
return currentParent &&
( ( currentParent.getDtd() || CKEDITOR.dtd.span )[ elementName ] || isUnknownElement ) &&
( !def.parentRule || def.parentRule( currentParent ) );
} | [
"function",
"checkIfStyleCanBeChildOf",
"(",
"def",
",",
"currentParent",
",",
"elementName",
",",
"isUnknownElement",
")",
"{",
"return",
"currentParent",
"&&",
"(",
"(",
"currentParent",
".",
"getDtd",
"(",
")",
"||",
"CKEDITOR",
".",
"dtd",
".",
"span",
")",
"[",
"elementName",
"]",
"||",
"isUnknownElement",
")",
"&&",
"(",
"!",
"def",
".",
"parentRule",
"||",
"def",
".",
"parentRule",
"(",
"currentParent",
")",
")",
";",
"}"
]
| Check if the style element can be a child of the current node parent or if the element is not defined in the DTD. | [
"Check",
"if",
"the",
"style",
"element",
"can",
"be",
"a",
"child",
"of",
"the",
"current",
"node",
"parent",
"or",
"if",
"the",
"element",
"is",
"not",
"defined",
"in",
"the",
"DTD",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L772-L776 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | checkPositionAndRule | function checkPositionAndRule( nodeA, nodeB, def, posBitFlags ) {
return ( nodeA.getPosition( nodeB ) | posBitFlags ) == posBitFlags &&
( !def.childRule || def.childRule( nodeA ) );
} | javascript | function checkPositionAndRule( nodeA, nodeB, def, posBitFlags ) {
return ( nodeA.getPosition( nodeB ) | posBitFlags ) == posBitFlags &&
( !def.childRule || def.childRule( nodeA ) );
} | [
"function",
"checkPositionAndRule",
"(",
"nodeA",
",",
"nodeB",
",",
"def",
",",
"posBitFlags",
")",
"{",
"return",
"(",
"nodeA",
".",
"getPosition",
"(",
"nodeB",
")",
"|",
"posBitFlags",
")",
"==",
"posBitFlags",
"&&",
"(",
"!",
"def",
".",
"childRule",
"||",
"def",
".",
"childRule",
"(",
"nodeA",
")",
")",
";",
"}"
]
| Checks if position is a subset of posBitFlags and that nodeA fulfills style def rule. | [
"Checks",
"if",
"position",
"is",
"a",
"subset",
"of",
"posBitFlags",
"and",
"that",
"nodeA",
"fulfills",
"style",
"def",
"rule",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L791-L794 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | applyStyleOnNestedEditables | function applyStyleOnNestedEditables( editablesContainer ) {
var editables = findNestedEditables( editablesContainer ),
editable,
l = editables.length,
i = 0,
range = l && new CKEDITOR.dom.range( editablesContainer.getDocument() );
for ( ; i < l; ++i ) {
editable = editables[ i ];
// Check if style is allowed by this editable's ACF.
if ( checkIfAllowedInEditable( editable, this ) ) {
range.selectNodeContents( editable );
applyInlineStyle.call( this, range );
}
}
} | javascript | function applyStyleOnNestedEditables( editablesContainer ) {
var editables = findNestedEditables( editablesContainer ),
editable,
l = editables.length,
i = 0,
range = l && new CKEDITOR.dom.range( editablesContainer.getDocument() );
for ( ; i < l; ++i ) {
editable = editables[ i ];
// Check if style is allowed by this editable's ACF.
if ( checkIfAllowedInEditable( editable, this ) ) {
range.selectNodeContents( editable );
applyInlineStyle.call( this, range );
}
}
} | [
"function",
"applyStyleOnNestedEditables",
"(",
"editablesContainer",
")",
"{",
"var",
"editables",
"=",
"findNestedEditables",
"(",
"editablesContainer",
")",
",",
"editable",
",",
"l",
"=",
"editables",
".",
"length",
",",
"i",
"=",
"0",
",",
"range",
"=",
"l",
"&&",
"new",
"CKEDITOR",
".",
"dom",
".",
"range",
"(",
"editablesContainer",
".",
"getDocument",
"(",
")",
")",
";",
"for",
"(",
";",
"i",
"<",
"l",
";",
"++",
"i",
")",
"{",
"editable",
"=",
"editables",
"[",
"i",
"]",
";",
"if",
"(",
"checkIfAllowedInEditable",
"(",
"editable",
",",
"this",
")",
")",
"{",
"range",
".",
"selectNodeContents",
"(",
"editable",
")",
";",
"applyInlineStyle",
".",
"call",
"(",
"this",
",",
"range",
")",
";",
"}",
"}",
"}"
]
| Apply style to nested editables inside editablesContainer. @param {CKEDITOR.dom.element} editablesContainer @context CKEDITOR.style | [
"Apply",
"style",
"to",
"nested",
"editables",
"inside",
"editablesContainer",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L1187-L1202 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | checkIfAllowedInEditable | function checkIfAllowedInEditable( editable, style ) {
var filter = CKEDITOR.filter.instances[ editable.data( 'cke-filter' ) ];
return filter ? filter.check( style ) : 1;
} | javascript | function checkIfAllowedInEditable( editable, style ) {
var filter = CKEDITOR.filter.instances[ editable.data( 'cke-filter' ) ];
return filter ? filter.check( style ) : 1;
} | [
"function",
"checkIfAllowedInEditable",
"(",
"editable",
",",
"style",
")",
"{",
"var",
"filter",
"=",
"CKEDITOR",
".",
"filter",
".",
"instances",
"[",
"editable",
".",
"data",
"(",
"'cke-filter'",
")",
"]",
";",
"return",
"filter",
"?",
"filter",
".",
"check",
"(",
"style",
")",
":",
"1",
";",
"}"
]
| Checks if style is allowed in this editable. | [
"Checks",
"if",
"style",
"is",
"allowed",
"in",
"this",
"editable",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L1220-L1224 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | toPre | function toPre( block, newBlock ) {
var bogus = block.getBogus();
bogus && bogus.remove();
// First trim the block content.
var preHtml = block.getHtml();
// 1. Trim head/tail spaces, they're not visible.
preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
// 2. Delete ANSI whitespaces immediately before and after <BR> because
// they are not visible.
preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
// 3. Compress other ANSI whitespaces since they're only visible as one
// single space previously.
// 4. Convert to spaces since is no longer needed in <PRE>.
preHtml = preHtml.replace( /([ \t\n\r]+| )/g, ' ' );
// 5. Convert any <BR /> to \n. This must not be done earlier because
// the \n would then get compressed.
preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
// Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
if ( CKEDITOR.env.ie ) {
var temp = block.getDocument().createElement( 'div' );
temp.append( newBlock );
newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
newBlock.copyAttributes( temp.getFirst() );
newBlock = temp.getFirst().remove();
} else {
newBlock.setHtml( preHtml );
}
return newBlock;
} | javascript | function toPre( block, newBlock ) {
var bogus = block.getBogus();
bogus && bogus.remove();
// First trim the block content.
var preHtml = block.getHtml();
// 1. Trim head/tail spaces, they're not visible.
preHtml = replace( preHtml, /(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '' );
// 2. Delete ANSI whitespaces immediately before and after <BR> because
// they are not visible.
preHtml = preHtml.replace( /[ \t\r\n]*(<br[^>]*>)[ \t\r\n]*/gi, '$1' );
// 3. Compress other ANSI whitespaces since they're only visible as one
// single space previously.
// 4. Convert to spaces since is no longer needed in <PRE>.
preHtml = preHtml.replace( /([ \t\n\r]+| )/g, ' ' );
// 5. Convert any <BR /> to \n. This must not be done earlier because
// the \n would then get compressed.
preHtml = preHtml.replace( /<br\b[^>]*>/gi, '\n' );
// Krugle: IE normalizes innerHTML to <pre>, breaking whitespaces.
if ( CKEDITOR.env.ie ) {
var temp = block.getDocument().createElement( 'div' );
temp.append( newBlock );
newBlock.$.outerHTML = '<pre>' + preHtml + '</pre>';
newBlock.copyAttributes( temp.getFirst() );
newBlock = temp.getFirst().remove();
} else {
newBlock.setHtml( preHtml );
}
return newBlock;
} | [
"function",
"toPre",
"(",
"block",
",",
"newBlock",
")",
"{",
"var",
"bogus",
"=",
"block",
".",
"getBogus",
"(",
")",
";",
"bogus",
"&&",
"bogus",
".",
"remove",
"(",
")",
";",
"var",
"preHtml",
"=",
"block",
".",
"getHtml",
"(",
")",
";",
"preHtml",
"=",
"replace",
"(",
"preHtml",
",",
"/",
"(?:^[ \\t\\n\\r]+)|(?:[ \\t\\n\\r]+$)",
"/",
"g",
",",
"''",
")",
";",
"preHtml",
"=",
"preHtml",
".",
"replace",
"(",
"/",
"[ \\t\\r\\n]*(<br[^>]*>)[ \\t\\r\\n]*",
"/",
"gi",
",",
"'$1'",
")",
";",
"preHtml",
"=",
"preHtml",
".",
"replace",
"(",
"/",
"([ \\t\\n\\r]+| )",
"/",
"g",
",",
"' '",
")",
";",
"preHtml",
"=",
"preHtml",
".",
"replace",
"(",
"/",
"<br\\b[^>]*>",
"/",
"gi",
",",
"'\\n'",
")",
";",
"\\n",
"if",
"(",
"CKEDITOR",
".",
"env",
".",
"ie",
")",
"{",
"var",
"temp",
"=",
"block",
".",
"getDocument",
"(",
")",
".",
"createElement",
"(",
"'div'",
")",
";",
"temp",
".",
"append",
"(",
"newBlock",
")",
";",
"newBlock",
".",
"$",
".",
"outerHTML",
"=",
"'<pre>'",
"+",
"preHtml",
"+",
"'</pre>'",
";",
"newBlock",
".",
"copyAttributes",
"(",
"temp",
".",
"getFirst",
"(",
")",
")",
";",
"newBlock",
"=",
"temp",
".",
"getFirst",
"(",
")",
".",
"remove",
"(",
")",
";",
"}",
"else",
"{",
"newBlock",
".",
"setHtml",
"(",
"preHtml",
")",
";",
"}",
"}"
]
| Converting from a non-PRE block to a PRE block in formatting operations. | [
"Converting",
"from",
"a",
"non",
"-",
"PRE",
"block",
"to",
"a",
"PRE",
"block",
"in",
"formatting",
"operations",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L1454-L1486 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | getAttributesForComparison | function getAttributesForComparison( styleDefinition ) {
// If we have already computed it, just return it.
var attribs = styleDefinition._AC;
if ( attribs )
return attribs;
attribs = {};
var length = 0;
// Loop through all defined attributes.
var styleAttribs = styleDefinition.attributes;
if ( styleAttribs ) {
for ( var styleAtt in styleAttribs ) {
length++;
attribs[ styleAtt ] = styleAttribs[ styleAtt ];
}
}
// Includes the style definitions.
var styleText = CKEDITOR.style.getStyleText( styleDefinition );
if ( styleText ) {
if ( !attribs.style )
length++;
attribs.style = styleText;
}
// Appends the "length" information to the object.
attribs._length = length;
// Return it, saving it to the next request.
return ( styleDefinition._AC = attribs );
} | javascript | function getAttributesForComparison( styleDefinition ) {
// If we have already computed it, just return it.
var attribs = styleDefinition._AC;
if ( attribs )
return attribs;
attribs = {};
var length = 0;
// Loop through all defined attributes.
var styleAttribs = styleDefinition.attributes;
if ( styleAttribs ) {
for ( var styleAtt in styleAttribs ) {
length++;
attribs[ styleAtt ] = styleAttribs[ styleAtt ];
}
}
// Includes the style definitions.
var styleText = CKEDITOR.style.getStyleText( styleDefinition );
if ( styleText ) {
if ( !attribs.style )
length++;
attribs.style = styleText;
}
// Appends the "length" information to the object.
attribs._length = length;
// Return it, saving it to the next request.
return ( styleDefinition._AC = attribs );
} | [
"function",
"getAttributesForComparison",
"(",
"styleDefinition",
")",
"{",
"var",
"attribs",
"=",
"styleDefinition",
".",
"_AC",
";",
"if",
"(",
"attribs",
")",
"return",
"attribs",
";",
"attribs",
"=",
"{",
"}",
";",
"var",
"length",
"=",
"0",
";",
"var",
"styleAttribs",
"=",
"styleDefinition",
".",
"attributes",
";",
"if",
"(",
"styleAttribs",
")",
"{",
"for",
"(",
"var",
"styleAtt",
"in",
"styleAttribs",
")",
"{",
"length",
"++",
";",
"attribs",
"[",
"styleAtt",
"]",
"=",
"styleAttribs",
"[",
"styleAtt",
"]",
";",
"}",
"}",
"var",
"styleText",
"=",
"CKEDITOR",
".",
"style",
".",
"getStyleText",
"(",
"styleDefinition",
")",
";",
"if",
"(",
"styleText",
")",
"{",
"if",
"(",
"!",
"attribs",
".",
"style",
")",
"length",
"++",
";",
"attribs",
".",
"style",
"=",
"styleText",
";",
"}",
"attribs",
".",
"_length",
"=",
"length",
";",
"return",
"(",
"styleDefinition",
".",
"_AC",
"=",
"attribs",
")",
";",
"}"
]
| Returns an object that can be used for style matching comparison. Attributes names and values are all lowercased, and the styles get merged with the style attribute. | [
"Returns",
"an",
"object",
"that",
"can",
"be",
"used",
"for",
"style",
"matching",
"comparison",
".",
"Attributes",
"names",
"and",
"values",
"are",
"all",
"lowercased",
"and",
"the",
"styles",
"get",
"merged",
"with",
"the",
"style",
"attribute",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L1690-L1722 | train |
skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/style.js | function( callback ) {
if ( !this._.stylesDefinitions ) {
var editor = this,
// Respect the backwards compatible definition entry
configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet;
// The false value means that none styles should be loaded.
if ( configStyleSet === false ) {
callback( null );
return;
}
// #5352 Allow to define the styles directly in the config object
if ( configStyleSet instanceof Array ) {
editor._.stylesDefinitions = configStyleSet;
callback( configStyleSet );
return;
}
// Default value is 'default'.
if ( !configStyleSet )
configStyleSet = 'default';
var partsStylesSet = configStyleSet.split( ':' ),
styleSetName = partsStylesSet[ 0 ],
externalPath = partsStylesSet[ 1 ];
CKEDITOR.stylesSet.addExternal( styleSetName, externalPath ? partsStylesSet.slice( 1 ).join( ':' ) : CKEDITOR.getUrl( 'styles.js' ), '' );
CKEDITOR.stylesSet.load( styleSetName, function( stylesSet ) {
editor._.stylesDefinitions = stylesSet[ styleSetName ];
callback( editor._.stylesDefinitions );
} );
} else {
callback( this._.stylesDefinitions );
}
} | javascript | function( callback ) {
if ( !this._.stylesDefinitions ) {
var editor = this,
// Respect the backwards compatible definition entry
configStyleSet = editor.config.stylesCombo_stylesSet || editor.config.stylesSet;
// The false value means that none styles should be loaded.
if ( configStyleSet === false ) {
callback( null );
return;
}
// #5352 Allow to define the styles directly in the config object
if ( configStyleSet instanceof Array ) {
editor._.stylesDefinitions = configStyleSet;
callback( configStyleSet );
return;
}
// Default value is 'default'.
if ( !configStyleSet )
configStyleSet = 'default';
var partsStylesSet = configStyleSet.split( ':' ),
styleSetName = partsStylesSet[ 0 ],
externalPath = partsStylesSet[ 1 ];
CKEDITOR.stylesSet.addExternal( styleSetName, externalPath ? partsStylesSet.slice( 1 ).join( ':' ) : CKEDITOR.getUrl( 'styles.js' ), '' );
CKEDITOR.stylesSet.load( styleSetName, function( stylesSet ) {
editor._.stylesDefinitions = stylesSet[ styleSetName ];
callback( editor._.stylesDefinitions );
} );
} else {
callback( this._.stylesDefinitions );
}
} | [
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_",
".",
"stylesDefinitions",
")",
"{",
"var",
"editor",
"=",
"this",
",",
"configStyleSet",
"=",
"editor",
".",
"config",
".",
"stylesCombo_stylesSet",
"||",
"editor",
".",
"config",
".",
"stylesSet",
";",
"if",
"(",
"configStyleSet",
"===",
"false",
")",
"{",
"callback",
"(",
"null",
")",
";",
"return",
";",
"}",
"if",
"(",
"configStyleSet",
"instanceof",
"Array",
")",
"{",
"editor",
".",
"_",
".",
"stylesDefinitions",
"=",
"configStyleSet",
";",
"callback",
"(",
"configStyleSet",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"configStyleSet",
")",
"configStyleSet",
"=",
"'default'",
";",
"var",
"partsStylesSet",
"=",
"configStyleSet",
".",
"split",
"(",
"':'",
")",
",",
"styleSetName",
"=",
"partsStylesSet",
"[",
"0",
"]",
",",
"externalPath",
"=",
"partsStylesSet",
"[",
"1",
"]",
";",
"CKEDITOR",
".",
"stylesSet",
".",
"addExternal",
"(",
"styleSetName",
",",
"externalPath",
"?",
"partsStylesSet",
".",
"slice",
"(",
"1",
")",
".",
"join",
"(",
"':'",
")",
":",
"CKEDITOR",
".",
"getUrl",
"(",
"'styles.js'",
")",
",",
"''",
")",
";",
"CKEDITOR",
".",
"stylesSet",
".",
"load",
"(",
"styleSetName",
",",
"function",
"(",
"stylesSet",
")",
"{",
"editor",
".",
"_",
".",
"stylesDefinitions",
"=",
"stylesSet",
"[",
"styleSetName",
"]",
";",
"callback",
"(",
"editor",
".",
"_",
".",
"stylesDefinitions",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"this",
".",
"_",
".",
"stylesDefinitions",
")",
";",
"}",
"}"
]
| Gets the current `stylesSet` for this instance.
editor.getStylesSet( function( stylesDefinitions ) {} );
See also {@link CKEDITOR.editor#stylesSet} event.
@member CKEDITOR.editor
@param {Function} callback The function to be called with the styles data. | [
"Gets",
"the",
"current",
"stylesSet",
"for",
"this",
"instance",
"."
]
| 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/style.js#L1977-L2013 | train |
|
nknapp/m-io | fs.js | walk | function walk (directoryPath, filter, collector) {
var defer = Q.defer()
fs.stat(directoryPath, function (err, stat) {
if (err) {
if (err.code === 'ENOENT') {
// Like q-io/fs, return an empty array, if the directory does not exist
return defer.resolve([])
}
return defer.reject(err)
}
// Call filter to get result, "true" if no filter is set
var filterResult = !filter || filter(directoryPath, stat)
if (filterResult) {
collector.push(directoryPath)
}
// false/true => iterate directory
if (stat.isDirectory() && filterResult !== null) {
fs.readdir(directoryPath, function (err, filenames) {
if (err) {
return defer.reject(err)
}
var paths = filenames.map(function (name) {
return path.join(directoryPath, name)
})
// Walk all files/subdirs
Q.all(paths.map(function (filepath) {
return walk(filepath, filter, collector)
}))
.then(function () {
defer.fulfill(collector)
})
})
} else {
// No recursive call with a file
defer.fulfill(collector)
}
})
return defer.promise
} | javascript | function walk (directoryPath, filter, collector) {
var defer = Q.defer()
fs.stat(directoryPath, function (err, stat) {
if (err) {
if (err.code === 'ENOENT') {
// Like q-io/fs, return an empty array, if the directory does not exist
return defer.resolve([])
}
return defer.reject(err)
}
// Call filter to get result, "true" if no filter is set
var filterResult = !filter || filter(directoryPath, stat)
if (filterResult) {
collector.push(directoryPath)
}
// false/true => iterate directory
if (stat.isDirectory() && filterResult !== null) {
fs.readdir(directoryPath, function (err, filenames) {
if (err) {
return defer.reject(err)
}
var paths = filenames.map(function (name) {
return path.join(directoryPath, name)
})
// Walk all files/subdirs
Q.all(paths.map(function (filepath) {
return walk(filepath, filter, collector)
}))
.then(function () {
defer.fulfill(collector)
})
})
} else {
// No recursive call with a file
defer.fulfill(collector)
}
})
return defer.promise
} | [
"function",
"walk",
"(",
"directoryPath",
",",
"filter",
",",
"collector",
")",
"{",
"var",
"defer",
"=",
"Q",
".",
"defer",
"(",
")",
"fs",
".",
"stat",
"(",
"directoryPath",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"return",
"defer",
".",
"resolve",
"(",
"[",
"]",
")",
"}",
"return",
"defer",
".",
"reject",
"(",
"err",
")",
"}",
"var",
"filterResult",
"=",
"!",
"filter",
"||",
"filter",
"(",
"directoryPath",
",",
"stat",
")",
"if",
"(",
"filterResult",
")",
"{",
"collector",
".",
"push",
"(",
"directoryPath",
")",
"}",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
"&&",
"filterResult",
"!==",
"null",
")",
"{",
"fs",
".",
"readdir",
"(",
"directoryPath",
",",
"function",
"(",
"err",
",",
"filenames",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"defer",
".",
"reject",
"(",
"err",
")",
"}",
"var",
"paths",
"=",
"filenames",
".",
"map",
"(",
"function",
"(",
"name",
")",
"{",
"return",
"path",
".",
"join",
"(",
"directoryPath",
",",
"name",
")",
"}",
")",
"Q",
".",
"all",
"(",
"paths",
".",
"map",
"(",
"function",
"(",
"filepath",
")",
"{",
"return",
"walk",
"(",
"filepath",
",",
"filter",
",",
"collector",
")",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"defer",
".",
"fulfill",
"(",
"collector",
")",
"}",
")",
"}",
")",
"}",
"else",
"{",
"defer",
".",
"fulfill",
"(",
"collector",
")",
"}",
"}",
")",
"return",
"defer",
".",
"promise",
"}"
]
| Walk a directory tree, collect paths of files in an Array and return a Promise for the fulfilled action
@param {string} directoryPath the base path
@param {function(string,fs.Stats):boolean} filter a function that returns true, false or null to show that a file
should be included or ignored and that a directory should be ignored completely (null)
@param {string[]} collector array to collect the filenames into
@private
@returns {Promise<string[]>} a promise for the collector, that is fulfilled after traversal | [
"Walk",
"a",
"directory",
"tree",
"collect",
"paths",
"of",
"files",
"in",
"an",
"Array",
"and",
"return",
"a",
"Promise",
"for",
"the",
"fulfilled",
"action"
]
| c2bcb22d49ef9d13e3601703f57824b954862bed | https://github.com/nknapp/m-io/blob/c2bcb22d49ef9d13e3601703f57824b954862bed/fs.js#L165-L203 | train |
ethul/connect-uglify-js | lib/middleware.js | doesEscapeRoot | function doesEscapeRoot(root,file) {
if (file.indexOf(path.normalize(root+"/")) === 0) return just(file);
else return nothing();
} | javascript | function doesEscapeRoot(root,file) {
if (file.indexOf(path.normalize(root+"/")) === 0) return just(file);
else return nothing();
} | [
"function",
"doesEscapeRoot",
"(",
"root",
",",
"file",
")",
"{",
"if",
"(",
"file",
".",
"indexOf",
"(",
"path",
".",
"normalize",
"(",
"root",
"+",
"\"/\"",
")",
")",
"===",
"0",
")",
"return",
"just",
"(",
"file",
")",
";",
"else",
"return",
"nothing",
"(",
")",
";",
"}"
]
| The computed path for the requested file should always have the root as the prefix. When it does not, that means the computed request path is pointing outside of the root, which could be malicious. | [
"The",
"computed",
"path",
"for",
"the",
"requested",
"file",
"should",
"always",
"have",
"the",
"root",
"as",
"the",
"prefix",
".",
"When",
"it",
"does",
"not",
"that",
"means",
"the",
"computed",
"request",
"path",
"is",
"pointing",
"outside",
"of",
"the",
"root",
"which",
"could",
"be",
"malicious",
"."
]
| 3e6caa3098a099ec3d007d17a37d54ec6c30e798 | https://github.com/ethul/connect-uglify-js/blob/3e6caa3098a099ec3d007d17a37d54ec6c30e798/lib/middleware.js#L71-L74 | train |
ethul/connect-uglify-js | lib/middleware.js | httpOk | function httpOk(response,isHead,body) {
response.setHeader(HTTP_CONTENT_TYPE,MIME_TYPE_JAVASCRIPT);
response.setHeader(HTTP_CONTENT_LENGTH,body.length);
response.statusCode = HTTP_OK;
if (isHead) response.end();
else response.end(body);
} | javascript | function httpOk(response,isHead,body) {
response.setHeader(HTTP_CONTENT_TYPE,MIME_TYPE_JAVASCRIPT);
response.setHeader(HTTP_CONTENT_LENGTH,body.length);
response.statusCode = HTTP_OK;
if (isHead) response.end();
else response.end(body);
} | [
"function",
"httpOk",
"(",
"response",
",",
"isHead",
",",
"body",
")",
"{",
"response",
".",
"setHeader",
"(",
"HTTP_CONTENT_TYPE",
",",
"MIME_TYPE_JAVASCRIPT",
")",
";",
"response",
".",
"setHeader",
"(",
"HTTP_CONTENT_LENGTH",
",",
"body",
".",
"length",
")",
";",
"response",
".",
"statusCode",
"=",
"HTTP_OK",
";",
"if",
"(",
"isHead",
")",
"response",
".",
"end",
"(",
")",
";",
"else",
"response",
".",
"end",
"(",
"body",
")",
";",
"}"
]
| Helper method to response with an HTTP ok with a body, when the isHead is true then no body is returned | [
"Helper",
"method",
"to",
"response",
"with",
"an",
"HTTP",
"ok",
"with",
"a",
"body",
"when",
"the",
"isHead",
"is",
"true",
"then",
"no",
"body",
"is",
"returned"
]
| 3e6caa3098a099ec3d007d17a37d54ec6c30e798 | https://github.com/ethul/connect-uglify-js/blob/3e6caa3098a099ec3d007d17a37d54ec6c30e798/lib/middleware.js#L114-L120 | train |
tracker1/mssql-ng | src/connections/close.js | closeConnection | function closeConnection(options) {
//no options, close/delete all connection references
if (!options) {
try {
mssql.close();
} catch(err){}
//create list to track items to close
let closeList = [];
//iterate through each connection
for (let key in promises) {
//if there's a close method (connection match), add it to the list
if (promises[key] && typeof promises[key].close === 'function') closeList.push(promises[key]);
}
//iterate through list and close each connection
closeList.forEach((item)=>item.close());
}
//either a connection promise, or a connection
if (options._mssqlngKey && typeof options.close === 'function') return options.close();
//match against connection options
let key = stringify(options || {});
if (connections[key]) connections[key].close();
if (promises[key]) promises[key].then((conn)=>conn.close()).catch(()=>{ delete promises[key]; delete connections[key] });
} | javascript | function closeConnection(options) {
//no options, close/delete all connection references
if (!options) {
try {
mssql.close();
} catch(err){}
//create list to track items to close
let closeList = [];
//iterate through each connection
for (let key in promises) {
//if there's a close method (connection match), add it to the list
if (promises[key] && typeof promises[key].close === 'function') closeList.push(promises[key]);
}
//iterate through list and close each connection
closeList.forEach((item)=>item.close());
}
//either a connection promise, or a connection
if (options._mssqlngKey && typeof options.close === 'function') return options.close();
//match against connection options
let key = stringify(options || {});
if (connections[key]) connections[key].close();
if (promises[key]) promises[key].then((conn)=>conn.close()).catch(()=>{ delete promises[key]; delete connections[key] });
} | [
"function",
"closeConnection",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"try",
"{",
"mssql",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"let",
"closeList",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"key",
"in",
"promises",
")",
"{",
"if",
"(",
"promises",
"[",
"key",
"]",
"&&",
"typeof",
"promises",
"[",
"key",
"]",
".",
"close",
"===",
"'function'",
")",
"closeList",
".",
"push",
"(",
"promises",
"[",
"key",
"]",
")",
";",
"}",
"closeList",
".",
"forEach",
"(",
"(",
"item",
")",
"=>",
"item",
".",
"close",
"(",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"_mssqlngKey",
"&&",
"typeof",
"options",
".",
"close",
"===",
"'function'",
")",
"return",
"options",
".",
"close",
"(",
")",
";",
"let",
"key",
"=",
"stringify",
"(",
"options",
"||",
"{",
"}",
")",
";",
"if",
"(",
"connections",
"[",
"key",
"]",
")",
"connections",
"[",
"key",
"]",
".",
"close",
"(",
")",
";",
"if",
"(",
"promises",
"[",
"key",
"]",
")",
"promises",
"[",
"key",
"]",
".",
"then",
"(",
"(",
"conn",
")",
"=>",
"conn",
".",
"close",
"(",
")",
")",
".",
"catch",
"(",
"(",
")",
"=>",
"{",
"delete",
"promises",
"[",
"key",
"]",
";",
"delete",
"connections",
"[",
"key",
"]",
"}",
")",
";",
"}"
]
| close a specific connection, if no options specified, deletes all connections | [
"close",
"a",
"specific",
"connection",
"if",
"no",
"options",
"specified",
"deletes",
"all",
"connections"
]
| 7f32135d33f9b8324fdd94656136cae4087464ce | https://github.com/tracker1/mssql-ng/blob/7f32135d33f9b8324fdd94656136cae4087464ce/src/connections/close.js#L8-L35 | train |
dominictarr/kiddb | index.js | function (_data, cb) {
if(!db.data) return cb(new Error('kiddb not open'))
if(!writing) return db._update(_data, cb)
db.__data = _data
qcb.push(cb)
onWrote = function () {
onWrote = null
var cbs = qcb; qcb = []
var _data = db.__data
db.__data = null
db.update(_data, function (err) {
cbs.forEach(function (cb) {
cb(err)
})
})
}
} | javascript | function (_data, cb) {
if(!db.data) return cb(new Error('kiddb not open'))
if(!writing) return db._update(_data, cb)
db.__data = _data
qcb.push(cb)
onWrote = function () {
onWrote = null
var cbs = qcb; qcb = []
var _data = db.__data
db.__data = null
db.update(_data, function (err) {
cbs.forEach(function (cb) {
cb(err)
})
})
}
} | [
"function",
"(",
"_data",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"db",
".",
"data",
")",
"return",
"cb",
"(",
"new",
"Error",
"(",
"'kiddb not open'",
")",
")",
"if",
"(",
"!",
"writing",
")",
"return",
"db",
".",
"_update",
"(",
"_data",
",",
"cb",
")",
"db",
".",
"__data",
"=",
"_data",
"qcb",
".",
"push",
"(",
"cb",
")",
"onWrote",
"=",
"function",
"(",
")",
"{",
"onWrote",
"=",
"null",
"var",
"cbs",
"=",
"qcb",
";",
"qcb",
"=",
"[",
"]",
"var",
"_data",
"=",
"db",
".",
"__data",
"db",
".",
"__data",
"=",
"null",
"db",
".",
"update",
"(",
"_data",
",",
"function",
"(",
"err",
")",
"{",
"cbs",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"cb",
"(",
"err",
")",
"}",
")",
"}",
")",
"}",
"}"
]
| instead of doing a concurrent write, queue the new writes. these can probably be merged together, and then a bunch will succeed at once. if you contrived your benchmark the right way, this could look like really great performance! | [
"instead",
"of",
"doing",
"a",
"concurrent",
"write",
"queue",
"the",
"new",
"writes",
".",
"these",
"can",
"probably",
"be",
"merged",
"together",
"and",
"then",
"a",
"bunch",
"will",
"succeed",
"at",
"once",
".",
"if",
"you",
"contrived",
"your",
"benchmark",
"the",
"right",
"way",
"this",
"could",
"look",
"like",
"really",
"great",
"performance!"
]
| 63d81daf6a0a9a941be6e70f87e7a45094592535 | https://github.com/dominictarr/kiddb/blob/63d81daf6a0a9a941be6e70f87e7a45094592535/index.js#L82-L98 | train |
|
dominictarr/kiddb | index.js | function (key, cb) {
if(!db.data) return cb(new Error('kiddb not open'))
if(db.data[key]) cb(null, db.data[key])
else cb(new Error('not found'))
} | javascript | function (key, cb) {
if(!db.data) return cb(new Error('kiddb not open'))
if(db.data[key]) cb(null, db.data[key])
else cb(new Error('not found'))
} | [
"function",
"(",
"key",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"db",
".",
"data",
")",
"return",
"cb",
"(",
"new",
"Error",
"(",
"'kiddb not open'",
")",
")",
"if",
"(",
"db",
".",
"data",
"[",
"key",
"]",
")",
"cb",
"(",
"null",
",",
"db",
".",
"data",
"[",
"key",
"]",
")",
"else",
"cb",
"(",
"new",
"Error",
"(",
"'not found'",
")",
")",
"}"
]
| following is a bunch of stuff to make give the leveldown api... | [
"following",
"is",
"a",
"bunch",
"of",
"stuff",
"to",
"make",
"give",
"the",
"leveldown",
"api",
"..."
]
| 63d81daf6a0a9a941be6e70f87e7a45094592535 | https://github.com/dominictarr/kiddb/blob/63d81daf6a0a9a941be6e70f87e7a45094592535/index.js#L102-L106 | train |
|
SpringRoll/grunt-springroll-download | tasks/springroll.js | downloadArchive | function downloadArchive(id, call, options, done)
{
grunt.log.write('Downloading '.gray + id.yellow + ' ... '.gray);
request(call, function(err, response, body)
{
if (err) return done(err);
var result = JSON.parse(body);
if (!result.success)
{
return done(result.error + ' with game "' + id + '"');
}
if (options.json)
{
grunt.log.write('Writing json ... '.gray);
var writeStream = fs.createWriteStream(path.join(options.dest, id + '.json'));
writeStream.write(JSON.stringify(result.data, null, options.debug ? "\t":""));
writeStream.end();
}
grunt.log.write('Installing ... '.gray);
this.get(result.data.url).run(function(err, files)
{
if (err)
{
return done('Unable to download archive for game "' + id + '"');
}
grunt.log.writeln('Done.'.green);
done(null, files);
});
}
.bind(this));
} | javascript | function downloadArchive(id, call, options, done)
{
grunt.log.write('Downloading '.gray + id.yellow + ' ... '.gray);
request(call, function(err, response, body)
{
if (err) return done(err);
var result = JSON.parse(body);
if (!result.success)
{
return done(result.error + ' with game "' + id + '"');
}
if (options.json)
{
grunt.log.write('Writing json ... '.gray);
var writeStream = fs.createWriteStream(path.join(options.dest, id + '.json'));
writeStream.write(JSON.stringify(result.data, null, options.debug ? "\t":""));
writeStream.end();
}
grunt.log.write('Installing ... '.gray);
this.get(result.data.url).run(function(err, files)
{
if (err)
{
return done('Unable to download archive for game "' + id + '"');
}
grunt.log.writeln('Done.'.green);
done(null, files);
});
}
.bind(this));
} | [
"function",
"downloadArchive",
"(",
"id",
",",
"call",
",",
"options",
",",
"done",
")",
"{",
"grunt",
".",
"log",
".",
"write",
"(",
"'Downloading '",
".",
"gray",
"+",
"id",
".",
"yellow",
"+",
"' ... '",
".",
"gray",
")",
";",
"request",
"(",
"call",
",",
"function",
"(",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"var",
"result",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"if",
"(",
"!",
"result",
".",
"success",
")",
"{",
"return",
"done",
"(",
"result",
".",
"error",
"+",
"' with game \"'",
"+",
"id",
"+",
"'\"'",
")",
";",
"}",
"if",
"(",
"options",
".",
"json",
")",
"{",
"grunt",
".",
"log",
".",
"write",
"(",
"'Writing json ... '",
".",
"gray",
")",
";",
"var",
"writeStream",
"=",
"fs",
".",
"createWriteStream",
"(",
"path",
".",
"join",
"(",
"options",
".",
"dest",
",",
"id",
"+",
"'.json'",
")",
")",
";",
"writeStream",
".",
"write",
"(",
"JSON",
".",
"stringify",
"(",
"result",
".",
"data",
",",
"null",
",",
"options",
".",
"debug",
"?",
"\"\\t\"",
":",
"\\t",
")",
")",
";",
"\"\"",
"}",
"writeStream",
".",
"end",
"(",
")",
";",
"grunt",
".",
"log",
".",
"write",
"(",
"'Installing ... '",
".",
"gray",
")",
";",
"}",
".",
"this",
".",
"get",
"(",
"result",
".",
"data",
".",
"url",
")",
".",
"run",
"(",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"'Unable to download archive for game \"'",
"+",
"id",
"+",
"'\"'",
")",
";",
"}",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'Done.'",
".",
"green",
")",
";",
"done",
"(",
"null",
",",
"files",
")",
";",
"}",
")",
";",
"bind",
")",
";",
"}"
]
| Handle the request | [
"Handle",
"the",
"request"
]
| af59b2254866010e3ac0e0a53bda4b8202deae02 | https://github.com/SpringRoll/grunt-springroll-download/blob/af59b2254866010e3ac0e0a53bda4b8202deae02/tasks/springroll.js#L143-L180 | train |
bammoo/grunt-assets-version-replace | tasks/index.js | function(dest, src) {
if(src.indexOf('.js') > -1) {
return dest + src.replace('.js','.' + tsPrefix + newTS + '.js');
}
else {
return dest + src.replace('.css','.' + tsPrefix + newTS + '.css');
}
} | javascript | function(dest, src) {
if(src.indexOf('.js') > -1) {
return dest + src.replace('.js','.' + tsPrefix + newTS + '.js');
}
else {
return dest + src.replace('.css','.' + tsPrefix + newTS + '.css');
}
} | [
"function",
"(",
"dest",
",",
"src",
")",
"{",
"if",
"(",
"src",
".",
"indexOf",
"(",
"'.js'",
")",
">",
"-",
"1",
")",
"{",
"return",
"dest",
"+",
"src",
".",
"replace",
"(",
"'.js'",
",",
"'.'",
"+",
"tsPrefix",
"+",
"newTS",
"+",
"'.js'",
")",
";",
"}",
"else",
"{",
"return",
"dest",
"+",
"src",
".",
"replace",
"(",
"'.css'",
",",
"'.'",
"+",
"tsPrefix",
"+",
"newTS",
"+",
"'.css'",
")",
";",
"}",
"}"
]
| Add rename function to copy task config | [
"Add",
"rename",
"function",
"to",
"copy",
"task",
"config"
]
| 7fe9fd6c6301ec0cc2ebdceec99f2e89a87210b5 | https://github.com/bammoo/grunt-assets-version-replace/blob/7fe9fd6c6301ec0cc2ebdceec99f2e89a87210b5/tasks/index.js#L70-L77 | train |
|
NiklasGollenstede/regexpx | index.js | isEscapeingAt | function isEscapeingAt(string, index) {
if (index === 0) { return false; }
let i = index - 1;
while (
i >= 0 && string[i] === '\\'
) { --i; }
return (index - i) % 2 === 0;
} | javascript | function isEscapeingAt(string, index) {
if (index === 0) { return false; }
let i = index - 1;
while (
i >= 0 && string[i] === '\\'
) { --i; }
return (index - i) % 2 === 0;
} | [
"function",
"isEscapeingAt",
"(",
"string",
",",
"index",
")",
"{",
"if",
"(",
"index",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"let",
"i",
"=",
"index",
"-",
"1",
";",
"while",
"(",
"i",
">=",
"0",
"&&",
"string",
"[",
"i",
"]",
"===",
"'\\\\'",
")",
"\\\\",
"{",
"--",
"i",
";",
"}",
"}"
]
| checks whether the string is escaping the char at index | [
"checks",
"whether",
"the",
"string",
"is",
"escaping",
"the",
"char",
"at",
"index"
]
| f0ef06cbab75345963c31a5a05d024de8e22ed9d | https://github.com/NiklasGollenstede/regexpx/blob/f0ef06cbab75345963c31a5a05d024de8e22ed9d/index.js#L120-L127 | train |
wilmoore/json-parse.js | index.js | parse | function parse (defaultValue, data) {
try {
return JSON.parse(data)
} catch (error) {
if (defaultValue === null || defaultValue === undefined) {
throw error
} else {
return defaultValue
}
}
} | javascript | function parse (defaultValue, data) {
try {
return JSON.parse(data)
} catch (error) {
if (defaultValue === null || defaultValue === undefined) {
throw error
} else {
return defaultValue
}
}
} | [
"function",
"parse",
"(",
"defaultValue",
",",
"data",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"data",
")",
"}",
"catch",
"(",
"error",
")",
"{",
"if",
"(",
"defaultValue",
"===",
"null",
"||",
"defaultValue",
"===",
"undefined",
")",
"{",
"throw",
"error",
"}",
"else",
"{",
"return",
"defaultValue",
"}",
"}",
"}"
]
| Curried function that calls `JSON.parse` on provided input returning either
the parsed JSON or the specified default value if the data fails to parse as
valid JSON instead of throwing a `SyntaxError`.
@param {*} defaultValue
Default value to return if given data does not parse as valid JSON.
@param {*} data
Data to parse as JSON.
@return {*}
JavaScript value corresponding to parsed data. | [
"Curried",
"function",
"that",
"calls",
"JSON",
".",
"parse",
"on",
"provided",
"input",
"returning",
"either",
"the",
"parsed",
"JSON",
"or",
"the",
"specified",
"default",
"value",
"if",
"the",
"data",
"fails",
"to",
"parse",
"as",
"valid",
"JSON",
"instead",
"of",
"throwing",
"a",
"SyntaxError",
"."
]
| 143631ea04bcaecdc5e3e336edcb56e065158c29 | https://github.com/wilmoore/json-parse.js/blob/143631ea04bcaecdc5e3e336edcb56e065158c29/index.js#L30-L40 | train |
adoyle-h/config-sp | src/config.js | load | function load(fromPath, relativePaths, opts) {
opts = opts || {};
var ignores = opts.ignores || [];
if (typeof ignores === 'string') ignores = [ignores];
var conf = {};
relativePaths.forEach(function(relativePath) {
var path = Path.resolve(fromPath, relativePath);
var config = loadFile(path, ignores);
extend(conf, config);
});
if (conf.get === undefined) {
bindGetMethod(conf);
} else {
throw new Error('`get` property cannot be the root key of config');
}
return conf;
} | javascript | function load(fromPath, relativePaths, opts) {
opts = opts || {};
var ignores = opts.ignores || [];
if (typeof ignores === 'string') ignores = [ignores];
var conf = {};
relativePaths.forEach(function(relativePath) {
var path = Path.resolve(fromPath, relativePath);
var config = loadFile(path, ignores);
extend(conf, config);
});
if (conf.get === undefined) {
bindGetMethod(conf);
} else {
throw new Error('`get` property cannot be the root key of config');
}
return conf;
} | [
"function",
"load",
"(",
"fromPath",
",",
"relativePaths",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"ignores",
"=",
"opts",
".",
"ignores",
"||",
"[",
"]",
";",
"if",
"(",
"typeof",
"ignores",
"===",
"'string'",
")",
"ignores",
"=",
"[",
"ignores",
"]",
";",
"var",
"conf",
"=",
"{",
"}",
";",
"relativePaths",
".",
"forEach",
"(",
"function",
"(",
"relativePath",
")",
"{",
"var",
"path",
"=",
"Path",
".",
"resolve",
"(",
"fromPath",
",",
"relativePath",
")",
";",
"var",
"config",
"=",
"loadFile",
"(",
"path",
",",
"ignores",
")",
";",
"extend",
"(",
"conf",
",",
"config",
")",
";",
"}",
")",
";",
"if",
"(",
"conf",
".",
"get",
"===",
"undefined",
")",
"{",
"bindGetMethod",
"(",
"conf",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'`get` property cannot be the root key of config'",
")",
";",
"}",
"return",
"conf",
";",
"}"
]
| Load your config files.
You could invoke the `load` function many times. Each returned config is independent and not affected by each other.
@example
// Assume that there are two files 'test/config/default.js', 'test/config/local.js',
// and the codes in 'test/config/index.js':
load(__dirname, ['default.js', 'local.js']);
@param {String} fromPath A absolute path to sub-config folder.
@param {String[]} relativePaths The paths of config files, which relative to `fromPath`.
The latter item will overwrite the former recursively.
@param {Object} [opts]
@param {String|String[]} [opts.ignores] Filenames that allowed missing when loading these files.
@return {Object} The final config object.
@throws Throw an error if the files of relativePaths are missing.
You could set `CONFIG_SP_LOAD_FILE_MISSING` environment variable for toleration
@method load | [
"Load",
"your",
"config",
"files",
"."
]
| cdfefc1b1c292d834b1144695bb284f0e26a6a77 | https://github.com/adoyle-h/config-sp/blob/cdfefc1b1c292d834b1144695bb284f0e26a6a77/src/config.js#L71-L90 | train |
adoyle-h/config-sp | src/config.js | create | function create() {
var args = Array.prototype.slice.call(arguments);
var conf = {};
args.forEach(function(config) {
extend(conf, config);
});
if (conf.get === undefined) {
bindGetMethod(conf);
} else {
throw new Error('`get` property cannot be the root key of config');
}
return conf;
} | javascript | function create() {
var args = Array.prototype.slice.call(arguments);
var conf = {};
args.forEach(function(config) {
extend(conf, config);
});
if (conf.get === undefined) {
bindGetMethod(conf);
} else {
throw new Error('`get` property cannot be the root key of config');
}
return conf;
} | [
"function",
"create",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"conf",
"=",
"{",
"}",
";",
"args",
".",
"forEach",
"(",
"function",
"(",
"config",
")",
"{",
"extend",
"(",
"conf",
",",
"config",
")",
";",
"}",
")",
";",
"if",
"(",
"conf",
".",
"get",
"===",
"undefined",
")",
"{",
"bindGetMethod",
"(",
"conf",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'`get` property cannot be the root key of config'",
")",
";",
"}",
"return",
"conf",
";",
"}"
]
| create a config with multi objects.
The latter object will overwrite the former recursively.
@example
create({a: 1, b: 2}, {a: 0, c: 3}); // => {a: 0, b: 2, c: 3}
@param {Object...} source a set of config objects.
@return {Object} The final config object.
@method create | [
"create",
"a",
"config",
"with",
"multi",
"objects",
"."
]
| cdfefc1b1c292d834b1144695bb284f0e26a6a77 | https://github.com/adoyle-h/config-sp/blob/cdfefc1b1c292d834b1144695bb284f0e26a6a77/src/config.js#L106-L121 | train |
nachos/settings-file | lib/index.js | SettingsFile | function SettingsFile(app, options) {
if (!app) {
throw new TypeError('SettingsFile must accept an app name');
}
else if (typeof app !== 'string') {
throw new TypeError('SettingsFile app name must be a string');
}
debug('initialize new settings file for app: %s', app);
this._app = app;
this._path = nachosHome('data', app + '.json');
debug('resolved path is %s', this._path);
this._options = defaults(options, {
globalDefaults: {},
instanceDefaults: {}
});
} | javascript | function SettingsFile(app, options) {
if (!app) {
throw new TypeError('SettingsFile must accept an app name');
}
else if (typeof app !== 'string') {
throw new TypeError('SettingsFile app name must be a string');
}
debug('initialize new settings file for app: %s', app);
this._app = app;
this._path = nachosHome('data', app + '.json');
debug('resolved path is %s', this._path);
this._options = defaults(options, {
globalDefaults: {},
instanceDefaults: {}
});
} | [
"function",
"SettingsFile",
"(",
"app",
",",
"options",
")",
"{",
"if",
"(",
"!",
"app",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'SettingsFile must accept an app name'",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"app",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'SettingsFile app name must be a string'",
")",
";",
"}",
"debug",
"(",
"'initialize new settings file for app: %s'",
",",
"app",
")",
";",
"this",
".",
"_app",
"=",
"app",
";",
"this",
".",
"_path",
"=",
"nachosHome",
"(",
"'data'",
",",
"app",
"+",
"'.json'",
")",
";",
"debug",
"(",
"'resolved path is %s'",
",",
"this",
".",
"_path",
")",
";",
"this",
".",
"_options",
"=",
"defaults",
"(",
"options",
",",
"{",
"globalDefaults",
":",
"{",
"}",
",",
"instanceDefaults",
":",
"{",
"}",
"}",
")",
";",
"}"
]
| Nachos settings file
@param {String} app The name of the app
@param {Object} options Optional templates for global and instance settings
@constructor | [
"Nachos",
"settings",
"file"
]
| d31e6d7db3f5b48cf6fb042507119e3488285e92 | https://github.com/nachos/settings-file/blob/d31e6d7db3f5b48cf6fb042507119e3488285e92/lib/index.js#L23-L39 | train |
nachos/settings-file | lib/index.js | function (content) {
var fileContent = self._readFileSync();
fileContent.instances = fileContent.instances || {};
fileContent.instances[this._id] = content;
self._writeFileSync(fileContent);
} | javascript | function (content) {
var fileContent = self._readFileSync();
fileContent.instances = fileContent.instances || {};
fileContent.instances[this._id] = content;
self._writeFileSync(fileContent);
} | [
"function",
"(",
"content",
")",
"{",
"var",
"fileContent",
"=",
"self",
".",
"_readFileSync",
"(",
")",
";",
"fileContent",
".",
"instances",
"=",
"fileContent",
".",
"instances",
"||",
"{",
"}",
";",
"fileContent",
".",
"instances",
"[",
"this",
".",
"_id",
"]",
"=",
"content",
";",
"self",
".",
"_writeFileSync",
"(",
"fileContent",
")",
";",
"}"
]
| Save the instance settings
@param {Object} content The instance settings | [
"Save",
"the",
"instance",
"settings"
]
| d31e6d7db3f5b48cf6fb042507119e3488285e92 | https://github.com/nachos/settings-file/blob/d31e6d7db3f5b48cf6fb042507119e3488285e92/lib/index.js#L293-L299 | train |
|
PrinceNebulon/github-api-promise | src/teams/teams.js | function(id, params) {
return req.standardRequest(`${config.host}/teams/${id}/teams?${req.assembleQueryParams(params,
['page'])}`);
} | javascript | function(id, params) {
return req.standardRequest(`${config.host}/teams/${id}/teams?${req.assembleQueryParams(params,
['page'])}`);
} | [
"function",
"(",
"id",
",",
"params",
")",
"{",
"return",
"req",
".",
"standardRequest",
"(",
"`",
"${",
"config",
".",
"host",
"}",
"${",
"id",
"}",
"${",
"req",
".",
"assembleQueryParams",
"(",
"params",
",",
"[",
"'page'",
"]",
")",
"}",
"`",
")",
";",
"}"
]
| List child teams
At this time, the hellcat-preview media type is required to use this endpoint.
@see {@link https://developer.github.com/v3/teams/#list-child-teams}
@param {string} id - The team ID
@param {object} params - An object of parameters for the request
@param {int} params.page - The page of results to retrieve
@return {object} team data | [
"List",
"child",
"teams"
]
| 990cb2cce19b53f54d9243002fde47428f24e7cc | https://github.com/PrinceNebulon/github-api-promise/blob/990cb2cce19b53f54d9243002fde47428f24e7cc/src/teams/teams.js#L147-L150 | train |
|
PrinceNebulon/github-api-promise | src/teams/teams.js | function(id, projectId, body) {
return req.standardRequest(`${config.host}/teams/${id}/projects/${projectId}`, 'put', body);
} | javascript | function(id, projectId, body) {
return req.standardRequest(`${config.host}/teams/${id}/projects/${projectId}`, 'put', body);
} | [
"function",
"(",
"id",
",",
"projectId",
",",
"body",
")",
"{",
"return",
"req",
".",
"standardRequest",
"(",
"`",
"${",
"config",
".",
"host",
"}",
"${",
"id",
"}",
"${",
"projectId",
"}",
"`",
",",
"'put'",
",",
"body",
")",
";",
"}"
]
| Add or update team project
Adds an organization project to a team. To add a project to a team or update the team's permission on a project, the authenticated user must have admin permissions for the project. The project and team must be part of the same organization.
@see {@link https://developer.github.com/v3/teams/#add-or-update-team-project}
@param {string} id - The team ID
@param {string} projectId - The project ID
@param {object} body - The request body
@param {string} body.permission - The permission to grant to the team for this project. Can be one of:
* `read` - team members can read, but not write to or administer this project.
* `write` - team members can read and write, but not administer this project.
* `admin` - team members can read, write and administer this project.
Default: the team's `permission` attribute will be used to determine what permission to grant the team on this project. Note that, if you choose not to pass any parameters, you'll need to set `Content-Length` to zero when calling out to this endpoint. For more information, see "HTTP verbs."
**Note**: If you pass the `hellcat-preview` media type, you can promote—but not demote—a `permission` attribute inherited from a parent team.
@return {nothing} | [
"Add",
"or",
"update",
"team",
"project"
]
| 990cb2cce19b53f54d9243002fde47428f24e7cc | https://github.com/PrinceNebulon/github-api-promise/blob/990cb2cce19b53f54d9243002fde47428f24e7cc/src/teams/teams.js#L302-L304 | train |
|
jasonpincin/pharos-tree | index.js | createStream | function createStream (options) {
options = options || {}
var stream = through2.obj(function transform (chunk, encoding, cb) {
stream.push(options.objectMode ? chunk : JSON.stringify(chunk)+'\n')
cb()
})
stream.close = function close () {
setImmediate(function () {
stream.push(null)
changes.unpipe(stream)
})
numStreams--
}
changes.pipe(stream)
numStreams++
return stream
} | javascript | function createStream (options) {
options = options || {}
var stream = through2.obj(function transform (chunk, encoding, cb) {
stream.push(options.objectMode ? chunk : JSON.stringify(chunk)+'\n')
cb()
})
stream.close = function close () {
setImmediate(function () {
stream.push(null)
changes.unpipe(stream)
})
numStreams--
}
changes.pipe(stream)
numStreams++
return stream
} | [
"function",
"createStream",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
"var",
"stream",
"=",
"through2",
".",
"obj",
"(",
"function",
"transform",
"(",
"chunk",
",",
"encoding",
",",
"cb",
")",
"{",
"stream",
".",
"push",
"(",
"options",
".",
"objectMode",
"?",
"chunk",
":",
"JSON",
".",
"stringify",
"(",
"chunk",
")",
"+",
"'\\n'",
")",
"\\n",
"}",
")",
"cb",
"(",
")",
"stream",
".",
"close",
"=",
"function",
"close",
"(",
")",
"{",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"stream",
".",
"push",
"(",
"null",
")",
"changes",
".",
"unpipe",
"(",
"stream",
")",
"}",
")",
"numStreams",
"--",
"}",
"changes",
".",
"pipe",
"(",
"stream",
")",
"numStreams",
"++",
"}"
]
| create stream of changes | [
"create",
"stream",
"of",
"changes"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L20-L37 | train |
jasonpincin/pharos-tree | index.js | feed | function feed(op, pnode) {
if (numStreams > 0) {
changes.push({op:op, pnode:pnode.toJSON()})
}
} | javascript | function feed(op, pnode) {
if (numStreams > 0) {
changes.push({op:op, pnode:pnode.toJSON()})
}
} | [
"function",
"feed",
"(",
"op",
",",
"pnode",
")",
"{",
"if",
"(",
"numStreams",
">",
"0",
")",
"{",
"changes",
".",
"push",
"(",
"{",
"op",
":",
"op",
",",
"pnode",
":",
"pnode",
".",
"toJSON",
"(",
")",
"}",
")",
"}",
"}"
]
| feed change streams | [
"feed",
"change",
"streams"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L39-L43 | train |
jasonpincin/pharos-tree | index.js | setPnodeData | function setPnodeData (pnode, value) {
if (!pnode.exists) {
pnode._data = value
persistPnode(pnode)
}
else if (pnode._data !== value) {
pnode._data = value
incTransaction()
incPnodeVersion(pnode)
feed('change', pnode)
}
return pnode
} | javascript | function setPnodeData (pnode, value) {
if (!pnode.exists) {
pnode._data = value
persistPnode(pnode)
}
else if (pnode._data !== value) {
pnode._data = value
incTransaction()
incPnodeVersion(pnode)
feed('change', pnode)
}
return pnode
} | [
"function",
"setPnodeData",
"(",
"pnode",
",",
"value",
")",
"{",
"if",
"(",
"!",
"pnode",
".",
"exists",
")",
"{",
"pnode",
".",
"_data",
"=",
"value",
"persistPnode",
"(",
"pnode",
")",
"}",
"else",
"if",
"(",
"pnode",
".",
"_data",
"!==",
"value",
")",
"{",
"pnode",
".",
"_data",
"=",
"value",
"incTransaction",
"(",
")",
"incPnodeVersion",
"(",
"pnode",
")",
"feed",
"(",
"'change'",
",",
"pnode",
")",
"}",
"return",
"pnode",
"}"
]
| set pnode data | [
"set",
"pnode",
"data"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L80-L92 | train |
jasonpincin/pharos-tree | index.js | unsetPnodeData | function unsetPnodeData (pnode) {
if (pnode.hasOwnProperty('_data') && pnode._data !== undefined) {
pnode._data = undefined
incTransaction()
incPnodeVersion(pnode)
feed('change', pnode)
}
return pnode
} | javascript | function unsetPnodeData (pnode) {
if (pnode.hasOwnProperty('_data') && pnode._data !== undefined) {
pnode._data = undefined
incTransaction()
incPnodeVersion(pnode)
feed('change', pnode)
}
return pnode
} | [
"function",
"unsetPnodeData",
"(",
"pnode",
")",
"{",
"if",
"(",
"pnode",
".",
"hasOwnProperty",
"(",
"'_data'",
")",
"&&",
"pnode",
".",
"_data",
"!==",
"undefined",
")",
"{",
"pnode",
".",
"_data",
"=",
"undefined",
"incTransaction",
"(",
")",
"incPnodeVersion",
"(",
"pnode",
")",
"feed",
"(",
"'change'",
",",
"pnode",
")",
"}",
"return",
"pnode",
"}"
]
| unset pnode data | [
"unset",
"pnode",
"data"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L94-L102 | train |
jasonpincin/pharos-tree | index.js | incPnodeVersion | function incPnodeVersion (pnode) {
pnode._version = pnode._version ? pnode._version + 1 : 1
pnode._mtxid = ptree.txid
pnode._mtime = new Date
if (!pnode._ctxid) pnode._ctxid = pnode._mtxid
if (!pnode._ctime) pnode._ctime = pnode._mtime
return pnode
} | javascript | function incPnodeVersion (pnode) {
pnode._version = pnode._version ? pnode._version + 1 : 1
pnode._mtxid = ptree.txid
pnode._mtime = new Date
if (!pnode._ctxid) pnode._ctxid = pnode._mtxid
if (!pnode._ctime) pnode._ctime = pnode._mtime
return pnode
} | [
"function",
"incPnodeVersion",
"(",
"pnode",
")",
"{",
"pnode",
".",
"_version",
"=",
"pnode",
".",
"_version",
"?",
"pnode",
".",
"_version",
"+",
"1",
":",
"1",
"pnode",
".",
"_mtxid",
"=",
"ptree",
".",
"txid",
"pnode",
".",
"_mtime",
"=",
"new",
"Date",
"if",
"(",
"!",
"pnode",
".",
"_ctxid",
")",
"pnode",
".",
"_ctxid",
"=",
"pnode",
".",
"_mtxid",
"if",
"(",
"!",
"pnode",
".",
"_ctime",
")",
"pnode",
".",
"_ctime",
"=",
"pnode",
".",
"_mtime",
"return",
"pnode",
"}"
]
| increment pnode version | [
"increment",
"pnode",
"version"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L104-L111 | train |
jasonpincin/pharos-tree | index.js | incChildrenVersion | function incChildrenVersion (pnode) {
if (pnode && pnode._childrenVersion) pnode._childrenVersion++
else pnode._childrenVersion = 1
return pnode
} | javascript | function incChildrenVersion (pnode) {
if (pnode && pnode._childrenVersion) pnode._childrenVersion++
else pnode._childrenVersion = 1
return pnode
} | [
"function",
"incChildrenVersion",
"(",
"pnode",
")",
"{",
"if",
"(",
"pnode",
"&&",
"pnode",
".",
"_childrenVersion",
")",
"pnode",
".",
"_childrenVersion",
"++",
"else",
"pnode",
".",
"_childrenVersion",
"=",
"1",
"return",
"pnode",
"}"
]
| incrememnt childrenVersion of pnode | [
"incrememnt",
"childrenVersion",
"of",
"pnode"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L113-L117 | train |
jasonpincin/pharos-tree | index.js | addChild | function addChild(parent, child) {
parent._children.push(child)
incChildrenVersion(parent)
return parent
} | javascript | function addChild(parent, child) {
parent._children.push(child)
incChildrenVersion(parent)
return parent
} | [
"function",
"addChild",
"(",
"parent",
",",
"child",
")",
"{",
"parent",
".",
"_children",
".",
"push",
"(",
"child",
")",
"incChildrenVersion",
"(",
"parent",
")",
"return",
"parent",
"}"
]
| add child to pnode | [
"add",
"child",
"to",
"pnode"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L125-L129 | train |
jasonpincin/pharos-tree | index.js | removeChild | function removeChild(parent, child) {
var parentChildIdx = parent._children.indexOf(child)
parent._children.splice(parentChildIdx, 1)
incChildrenVersion(parent)
return parent
} | javascript | function removeChild(parent, child) {
var parentChildIdx = parent._children.indexOf(child)
parent._children.splice(parentChildIdx, 1)
incChildrenVersion(parent)
return parent
} | [
"function",
"removeChild",
"(",
"parent",
",",
"child",
")",
"{",
"var",
"parentChildIdx",
"=",
"parent",
".",
"_children",
".",
"indexOf",
"(",
"child",
")",
"parent",
".",
"_children",
".",
"splice",
"(",
"parentChildIdx",
",",
"1",
")",
"incChildrenVersion",
"(",
"parent",
")",
"return",
"parent",
"}"
]
| remove child from pnode | [
"remove",
"child",
"from",
"pnode"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L131-L136 | train |
jasonpincin/pharos-tree | index.js | pnodeParents | function pnodeParents (pnode) {
if (!pnode.valid) return undefined
var parentPaths = parents(pnode.path),
list = []
for (var i = 0; i < parentPaths.length; i++) list.push( ptree(parentPaths[i]) )
return list
} | javascript | function pnodeParents (pnode) {
if (!pnode.valid) return undefined
var parentPaths = parents(pnode.path),
list = []
for (var i = 0; i < parentPaths.length; i++) list.push( ptree(parentPaths[i]) )
return list
} | [
"function",
"pnodeParents",
"(",
"pnode",
")",
"{",
"if",
"(",
"!",
"pnode",
".",
"valid",
")",
"return",
"undefined",
"var",
"parentPaths",
"=",
"parents",
"(",
"pnode",
".",
"path",
")",
",",
"list",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"parentPaths",
".",
"length",
";",
"i",
"++",
")",
"list",
".",
"push",
"(",
"ptree",
"(",
"parentPaths",
"[",
"i",
"]",
")",
")",
"return",
"list",
"}"
]
| get all parents of a pnoce | [
"get",
"all",
"parents",
"of",
"a",
"pnoce"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L138-L144 | train |
jasonpincin/pharos-tree | index.js | pnodeParent | function pnodeParent (pnode) {
if (!pnode.valid) return undefined
var parentPath = parents.immediate(pnode.path)
return parentPath ? ptree(parentPath) : null
} | javascript | function pnodeParent (pnode) {
if (!pnode.valid) return undefined
var parentPath = parents.immediate(pnode.path)
return parentPath ? ptree(parentPath) : null
} | [
"function",
"pnodeParent",
"(",
"pnode",
")",
"{",
"if",
"(",
"!",
"pnode",
".",
"valid",
")",
"return",
"undefined",
"var",
"parentPath",
"=",
"parents",
".",
"immediate",
"(",
"pnode",
".",
"path",
")",
"return",
"parentPath",
"?",
"ptree",
"(",
"parentPath",
")",
":",
"null",
"}"
]
| get immediate parent of pnode | [
"get",
"immediate",
"parent",
"of",
"pnode"
]
| c0988800d6ffbcbfee153c4f07c194979f5e4f43 | https://github.com/jasonpincin/pharos-tree/blob/c0988800d6ffbcbfee153c4f07c194979f5e4f43/index.js#L146-L150 | train |
wilmoore/parameters-named.js | index.js | parameters | function parameters (spec) {
var defs = {}
var envs = {}
return function (params) {
init(spec, defs, envs)
var opts = cat(defs, envs, params)
var errs = []
def(opts, spec, errs)
req(opts, spec, errs)
val(opts, spec, errs)
return {
error: errs.length ? errs[0] : null,
errors: errs,
params: opts
}
}
} | javascript | function parameters (spec) {
var defs = {}
var envs = {}
return function (params) {
init(spec, defs, envs)
var opts = cat(defs, envs, params)
var errs = []
def(opts, spec, errs)
req(opts, spec, errs)
val(opts, spec, errs)
return {
error: errs.length ? errs[0] : null,
errors: errs,
params: opts
}
}
} | [
"function",
"parameters",
"(",
"spec",
")",
"{",
"var",
"defs",
"=",
"{",
"}",
"var",
"envs",
"=",
"{",
"}",
"return",
"function",
"(",
"params",
")",
"{",
"init",
"(",
"spec",
",",
"defs",
",",
"envs",
")",
"var",
"opts",
"=",
"cat",
"(",
"defs",
",",
"envs",
",",
"params",
")",
"var",
"errs",
"=",
"[",
"]",
"def",
"(",
"opts",
",",
"spec",
",",
"errs",
")",
"req",
"(",
"opts",
",",
"spec",
",",
"errs",
")",
"val",
"(",
"opts",
",",
"spec",
",",
"errs",
")",
"return",
"{",
"error",
":",
"errs",
".",
"length",
"?",
"errs",
"[",
"0",
"]",
":",
"null",
",",
"errors",
":",
"errs",
",",
"params",
":",
"opts",
"}",
"}",
"}"
]
| Named parameters supporting default value, validation, and environment variables.
@param {String} string
string literal.
@return {String}
string literal. | [
"Named",
"parameters",
"supporting",
"default",
"value",
"validation",
"and",
"environment",
"variables",
"."
]
| d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2 | https://github.com/wilmoore/parameters-named.js/blob/d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2/index.js#L28-L47 | train |
wilmoore/parameters-named.js | index.js | init | function init (spec, defs, envs) {
for (var key in spec || {}) {
if (spec[key].def) defs[key] = spec[key].def
if (has(spec[key].env)) envs[key] = get(spec[key].env)
}
} | javascript | function init (spec, defs, envs) {
for (var key in spec || {}) {
if (spec[key].def) defs[key] = spec[key].def
if (has(spec[key].env)) envs[key] = get(spec[key].env)
}
} | [
"function",
"init",
"(",
"spec",
",",
"defs",
",",
"envs",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"spec",
"||",
"{",
"}",
")",
"{",
"if",
"(",
"spec",
"[",
"key",
"]",
".",
"def",
")",
"defs",
"[",
"key",
"]",
"=",
"spec",
"[",
"key",
"]",
".",
"def",
"if",
"(",
"has",
"(",
"spec",
"[",
"key",
"]",
".",
"env",
")",
")",
"envs",
"[",
"key",
"]",
"=",
"get",
"(",
"spec",
"[",
"key",
"]",
".",
"env",
")",
"}",
"}"
]
| Initialize defaults and environment variables.
@param {String} spec
Parameters definition object.
@param {Object} defs
Default values container.
@param {String} spec
Environment values container. | [
"Initialize",
"defaults",
"and",
"environment",
"variables",
"."
]
| d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2 | https://github.com/wilmoore/parameters-named.js/blob/d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2/index.js#L62-L67 | train |
wilmoore/parameters-named.js | index.js | def | function def (params, spec, errs) {
for (var key in params) {
if (!spec.hasOwnProperty(key)) defError(key, errs)
}
} | javascript | function def (params, spec, errs) {
for (var key in params) {
if (!spec.hasOwnProperty(key)) defError(key, errs)
}
} | [
"function",
"def",
"(",
"params",
",",
"spec",
",",
"errs",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"params",
")",
"{",
"if",
"(",
"!",
"spec",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"defError",
"(",
"key",
",",
"errs",
")",
"}",
"}"
]
| Ensure that parameter is defined.
@param {Object} params
Parameters value object.
@param {String} spec
Parameters definition object.
@param {Array} errs
Errors list. | [
"Ensure",
"that",
"parameter",
"is",
"defined",
"."
]
| d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2 | https://github.com/wilmoore/parameters-named.js/blob/d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2/index.js#L82-L86 | train |
wilmoore/parameters-named.js | index.js | req | function req (params, spec, errs) {
for (var key in spec) {
if (spec[key].req && !params.hasOwnProperty(key)) reqError(key, errs)
}
} | javascript | function req (params, spec, errs) {
for (var key in spec) {
if (spec[key].req && !params.hasOwnProperty(key)) reqError(key, errs)
}
} | [
"function",
"req",
"(",
"params",
",",
"spec",
",",
"errs",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"spec",
")",
"{",
"if",
"(",
"spec",
"[",
"key",
"]",
".",
"req",
"&&",
"!",
"params",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"reqError",
"(",
"key",
",",
"errs",
")",
"}",
"}"
]
| Ensure that required keys are set.
@param {Object} params
Parameters value object.
@param {String} spec
Parameters definition object.
@param {Array} errs
Errors list. | [
"Ensure",
"that",
"required",
"keys",
"are",
"set",
"."
]
| d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2 | https://github.com/wilmoore/parameters-named.js/blob/d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2/index.js#L115-L119 | train |
wilmoore/parameters-named.js | index.js | val | function val (params, spec, errs) {
for (var key in params) {
if (key in spec && isFunction(spec[key].val) && !spec[key].val(params[key])) valError(key, errs)
}
} | javascript | function val (params, spec, errs) {
for (var key in params) {
if (key in spec && isFunction(spec[key].val) && !spec[key].val(params[key])) valError(key, errs)
}
} | [
"function",
"val",
"(",
"params",
",",
"spec",
",",
"errs",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"params",
")",
"{",
"if",
"(",
"key",
"in",
"spec",
"&&",
"isFunction",
"(",
"spec",
"[",
"key",
"]",
".",
"val",
")",
"&&",
"!",
"spec",
"[",
"key",
"]",
".",
"val",
"(",
"params",
"[",
"key",
"]",
")",
")",
"valError",
"(",
"key",
",",
"errs",
")",
"}",
"}"
]
| Ensure that validation predicates pass.
@param {Object} params
Parameters value object.
@param {String} spec
Parameters definition object.
@param {Array} errs
Errors list. | [
"Ensure",
"that",
"validation",
"predicates",
"pass",
"."
]
| d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2 | https://github.com/wilmoore/parameters-named.js/blob/d4201cd97b986ac2a24910d9f1d3c5c6f35dd5b2/index.js#L148-L152 | train |
clusterpoint/nodejs-client-api | lib/connection.js | header | function header(length) {
var res = [0x09, 0x09, 0x00, 0x00];
res.push((length & 0x000000FF) >> 0);
res.push((length & 0x0000FF00) >> 8);
res.push((length & 0x00FF0000) >> 16);
res.push((length & 0xFF000000) >> 24);
return new Buffer(res);
} | javascript | function header(length) {
var res = [0x09, 0x09, 0x00, 0x00];
res.push((length & 0x000000FF) >> 0);
res.push((length & 0x0000FF00) >> 8);
res.push((length & 0x00FF0000) >> 16);
res.push((length & 0xFF000000) >> 24);
return new Buffer(res);
} | [
"function",
"header",
"(",
"length",
")",
"{",
"var",
"res",
"=",
"[",
"0x09",
",",
"0x09",
",",
"0x00",
",",
"0x00",
"]",
";",
"res",
".",
"push",
"(",
"(",
"length",
"&",
"0x000000FF",
")",
">>",
"0",
")",
";",
"res",
".",
"push",
"(",
"(",
"length",
"&",
"0x0000FF00",
")",
">>",
"8",
")",
";",
"res",
".",
"push",
"(",
"(",
"length",
"&",
"0x00FF0000",
")",
">>",
"16",
")",
";",
"res",
".",
"push",
"(",
"(",
"length",
"&",
"0xFF000000",
")",
">>",
"24",
")",
";",
"return",
"new",
"Buffer",
"(",
"res",
")",
";",
"}"
]
| Creates header for clusterpoint messages
@param {Integer} length
@return {Buffer} | [
"Creates",
"header",
"for",
"clusterpoint",
"messages"
]
| ca9322eab3d11f7cc43ce0e6f6e2403f5b3712a0 | https://github.com/clusterpoint/nodejs-client-api/blob/ca9322eab3d11f7cc43ce0e6f6e2403f5b3712a0/lib/connection.js#L192-L199 | train |
AndreasMadsen/immortal | lib/executables/daemon.js | function (emit) {
ipc.send({
cmd : 'setup',
emit: emit,
daemon: process.pid,
message: errorBuffer === "" ? null : errorBuffer
});
} | javascript | function (emit) {
ipc.send({
cmd : 'setup',
emit: emit,
daemon: process.pid,
message: errorBuffer === "" ? null : errorBuffer
});
} | [
"function",
"(",
"emit",
")",
"{",
"ipc",
".",
"send",
"(",
"{",
"cmd",
":",
"'setup'",
",",
"emit",
":",
"emit",
",",
"daemon",
":",
"process",
".",
"pid",
",",
"message",
":",
"errorBuffer",
"===",
"\"\"",
"?",
"null",
":",
"errorBuffer",
"}",
")",
";",
"}"
]
| this function will setup a new pump as a daemon | [
"this",
"function",
"will",
"setup",
"a",
"new",
"pump",
"as",
"a",
"daemon"
]
| c1ab5a4287a543fdfd980604a9e9927d663a9ef2 | https://github.com/AndreasMadsen/immortal/blob/c1ab5a4287a543fdfd980604a9e9927d663a9ef2/lib/executables/daemon.js#L43-L50 | train |
|
overlookmotel/ejs-extra | lib/index.js | resolveObjectName | function resolveObjectName(view){
return cache[view] || (cache[view] = view
.split('/')
.slice(-1)[0]
.split('.')[0]
.replace(/^_/, '')
.replace(/[^a-zA-Z0-9 ]+/g, ' ')
.split(/ +/).map(function(word, i){
return i ? word[0].toUpperCase() + word.substr(1) : word;
}).join(''));
} | javascript | function resolveObjectName(view){
return cache[view] || (cache[view] = view
.split('/')
.slice(-1)[0]
.split('.')[0]
.replace(/^_/, '')
.replace(/[^a-zA-Z0-9 ]+/g, ' ')
.split(/ +/).map(function(word, i){
return i ? word[0].toUpperCase() + word.substr(1) : word;
}).join(''));
} | [
"function",
"resolveObjectName",
"(",
"view",
")",
"{",
"return",
"cache",
"[",
"view",
"]",
"||",
"(",
"cache",
"[",
"view",
"]",
"=",
"view",
".",
"split",
"(",
"'/'",
")",
".",
"slice",
"(",
"-",
"1",
")",
"[",
"0",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
".",
"replace",
"(",
"/",
"^_",
"/",
",",
"''",
")",
".",
"replace",
"(",
"/",
"[^a-zA-Z0-9 ]+",
"/",
"g",
",",
"' '",
")",
".",
"split",
"(",
"/",
" +",
"/",
")",
".",
"map",
"(",
"function",
"(",
"word",
",",
"i",
")",
"{",
"return",
"i",
"?",
"word",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
"+",
"word",
".",
"substr",
"(",
"1",
")",
":",
"word",
";",
"}",
")",
".",
"join",
"(",
"''",
")",
")",
";",
"}"
]
| Resolve partial object name from the view path.
Examples:
"user.ejs" becomes "user"
"forum thread.ejs" becomes "forumThread"
"forum/thread/post.ejs" becomes "post"
"blog-post.ejs" becomes "blogPost"
@return {String}
@api private | [
"Resolve",
"partial",
"object",
"name",
"from",
"the",
"view",
"path",
"."
]
| 0bda55152b174f1a990f4a04787a41676b1430d1 | https://github.com/overlookmotel/ejs-extra/blob/0bda55152b174f1a990f4a04787a41676b1430d1/lib/index.js#L160-L170 | train |
overlookmotel/ejs-extra | lib/index.js | block | function block(name, html) {
// bound to the blocks object in renderFile
var blk = this[name];
if (!blk) {
// always create, so if we request a
// non-existent block we'll get a new one
blk = this[name] = new Block();
}
if (html) {
blk.append(html);
}
return blk;
} | javascript | function block(name, html) {
// bound to the blocks object in renderFile
var blk = this[name];
if (!blk) {
// always create, so if we request a
// non-existent block we'll get a new one
blk = this[name] = new Block();
}
if (html) {
blk.append(html);
}
return blk;
} | [
"function",
"block",
"(",
"name",
",",
"html",
")",
"{",
"var",
"blk",
"=",
"this",
"[",
"name",
"]",
";",
"if",
"(",
"!",
"blk",
")",
"{",
"blk",
"=",
"this",
"[",
"name",
"]",
"=",
"new",
"Block",
"(",
")",
";",
"}",
"if",
"(",
"html",
")",
"{",
"blk",
".",
"append",
"(",
"html",
")",
";",
"}",
"return",
"blk",
";",
"}"
]
| Return the block with the given name, create it if necessary.
Optionally append the given html to the block.
The returned Block can append, prepend or replace the block,
as well as render it when included in a parent template.
@param {String} name
@param {String} html
@return {Block}
@api private | [
"Return",
"the",
"block",
"with",
"the",
"given",
"name",
"create",
"it",
"if",
"necessary",
".",
"Optionally",
"append",
"the",
"given",
"html",
"to",
"the",
"block",
"."
]
| 0bda55152b174f1a990f4a04787a41676b1430d1 | https://github.com/overlookmotel/ejs-extra/blob/0bda55152b174f1a990f4a04787a41676b1430d1/lib/index.js#L427-L439 | train |
overlookmotel/ejs-extra | lib/index.js | script | function script(path, type) {
if (path) {
var html = '<script src="'+path+'"'+(type ? 'type="'+type+'"' : '')+'></script>';
if (this.html.indexOf(html) == -1) this.append(html);
}
return this;
} | javascript | function script(path, type) {
if (path) {
var html = '<script src="'+path+'"'+(type ? 'type="'+type+'"' : '')+'></script>';
if (this.html.indexOf(html) == -1) this.append(html);
}
return this;
} | [
"function",
"script",
"(",
"path",
",",
"type",
")",
"{",
"if",
"(",
"path",
")",
"{",
"var",
"html",
"=",
"'<script src=\"'",
"+",
"path",
"+",
"'\"'",
"+",
"(",
"type",
"?",
"'type=\"'",
"+",
"type",
"+",
"'\"'",
":",
"''",
")",
"+",
"'></script>'",
";",
"if",
"(",
"this",
".",
"html",
".",
"indexOf",
"(",
"html",
")",
"==",
"-",
"1",
")",
"this",
".",
"append",
"(",
"html",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| bound to scripts Block in renderFile | [
"bound",
"to",
"scripts",
"Block",
"in",
"renderFile"
]
| 0bda55152b174f1a990f4a04787a41676b1430d1 | https://github.com/overlookmotel/ejs-extra/blob/0bda55152b174f1a990f4a04787a41676b1430d1/lib/index.js#L442-L448 | train |
overlookmotel/ejs-extra | lib/index.js | stylesheet | function stylesheet(path, media) {
if (path) {
var html = '<link rel="stylesheet" href="'+path+'"'+(media ? 'media="'+media+'"' : '')+' />';
if (this.html.indexOf(html) == -1) this.append(html);
}
return this;
} | javascript | function stylesheet(path, media) {
if (path) {
var html = '<link rel="stylesheet" href="'+path+'"'+(media ? 'media="'+media+'"' : '')+' />';
if (this.html.indexOf(html) == -1) this.append(html);
}
return this;
} | [
"function",
"stylesheet",
"(",
"path",
",",
"media",
")",
"{",
"if",
"(",
"path",
")",
"{",
"var",
"html",
"=",
"'<link rel=\"stylesheet\" href=\"'",
"+",
"path",
"+",
"'\"'",
"+",
"(",
"media",
"?",
"'media=\"'",
"+",
"media",
"+",
"'\"'",
":",
"''",
")",
"+",
"' />'",
";",
"if",
"(",
"this",
".",
"html",
".",
"indexOf",
"(",
"html",
")",
"==",
"-",
"1",
")",
"this",
".",
"append",
"(",
"html",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| bound to stylesheets Block in renderFile | [
"bound",
"to",
"stylesheets",
"Block",
"in",
"renderFile"
]
| 0bda55152b174f1a990f4a04787a41676b1430d1 | https://github.com/overlookmotel/ejs-extra/blob/0bda55152b174f1a990f4a04787a41676b1430d1/lib/index.js#L451-L457 | train |
Pocketbrain/native-ads-web-ad-library | src/ads/insertAds.js | insertAds | function insertAds(adUnit, ads, adLoadedCallback) {
var adContainers = page.getAdContainers(adUnit);
if (!adContainers.length) {
logger.error("No ad containers could be found. stopping insertion for adUnit " + adUnit.name);
return []; //Ad can't be inserted
}
var adBuilder = new AdBuilder(ads);
var beforeElement;
var insertedAdElements = [];
for (var i = 0; i < adContainers.length; i++) {
var adContainer = adContainers[i];
while ((beforeElement = adContainer.getNextElement()) !== null) {
var adToInsert = adBuilder.createAdUnit(adUnit, adContainer.containerElement);
if (adToInsert === null) {
//we ran out of ads.
break;
}
insertedAdElements.push(adToInsert);
beforeElement.parentNode.insertBefore(adToInsert, beforeElement.nextSibling);
// var elementDisplay = adToInsert.style.display || "block";
//TODO: Why are we defaulting to block here?
// adToInsert.style.display = elementDisplay;
handleImageLoad(adToInsert, adLoadedCallback);
}
}
return insertedAdElements;
} | javascript | function insertAds(adUnit, ads, adLoadedCallback) {
var adContainers = page.getAdContainers(adUnit);
if (!adContainers.length) {
logger.error("No ad containers could be found. stopping insertion for adUnit " + adUnit.name);
return []; //Ad can't be inserted
}
var adBuilder = new AdBuilder(ads);
var beforeElement;
var insertedAdElements = [];
for (var i = 0; i < adContainers.length; i++) {
var adContainer = adContainers[i];
while ((beforeElement = adContainer.getNextElement()) !== null) {
var adToInsert = adBuilder.createAdUnit(adUnit, adContainer.containerElement);
if (adToInsert === null) {
//we ran out of ads.
break;
}
insertedAdElements.push(adToInsert);
beforeElement.parentNode.insertBefore(adToInsert, beforeElement.nextSibling);
// var elementDisplay = adToInsert.style.display || "block";
//TODO: Why are we defaulting to block here?
// adToInsert.style.display = elementDisplay;
handleImageLoad(adToInsert, adLoadedCallback);
}
}
return insertedAdElements;
} | [
"function",
"insertAds",
"(",
"adUnit",
",",
"ads",
",",
"adLoadedCallback",
")",
"{",
"var",
"adContainers",
"=",
"page",
".",
"getAdContainers",
"(",
"adUnit",
")",
";",
"if",
"(",
"!",
"adContainers",
".",
"length",
")",
"{",
"logger",
".",
"error",
"(",
"\"No ad containers could be found. stopping insertion for adUnit \"",
"+",
"adUnit",
".",
"name",
")",
";",
"return",
"[",
"]",
";",
"}",
"var",
"adBuilder",
"=",
"new",
"AdBuilder",
"(",
"ads",
")",
";",
"var",
"beforeElement",
";",
"var",
"insertedAdElements",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"adContainers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"adContainer",
"=",
"adContainers",
"[",
"i",
"]",
";",
"while",
"(",
"(",
"beforeElement",
"=",
"adContainer",
".",
"getNextElement",
"(",
")",
")",
"!==",
"null",
")",
"{",
"var",
"adToInsert",
"=",
"adBuilder",
".",
"createAdUnit",
"(",
"adUnit",
",",
"adContainer",
".",
"containerElement",
")",
";",
"if",
"(",
"adToInsert",
"===",
"null",
")",
"{",
"break",
";",
"}",
"insertedAdElements",
".",
"push",
"(",
"adToInsert",
")",
";",
"beforeElement",
".",
"parentNode",
".",
"insertBefore",
"(",
"adToInsert",
",",
"beforeElement",
".",
"nextSibling",
")",
";",
"handleImageLoad",
"(",
"adToInsert",
",",
"adLoadedCallback",
")",
";",
"}",
"}",
"return",
"insertedAdElements",
";",
"}"
]
| Insert advertisements for the given ad unit on the page
@param adUnit - The ad unit to insert advertisements for
@param ads - Array of ads retrieved from OfferEngine
@param adLoadedCallback - Callback to execute when the ads are fully loaded
@returns {Array} | [
"Insert",
"advertisements",
"for",
"the",
"given",
"ad",
"unit",
"on",
"the",
"page"
]
| aafee1c42e0569ee77f334fc2c4eb71eb146957e | https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/ads/insertAds.js#L17-L50 | train |
Pocketbrain/native-ads-web-ad-library | src/ads/insertAds.js | handleImageLoad | function handleImageLoad(adElement, adLoadedCallback) {
var adImage = adElement.querySelector("img");
if (adImage) {
(function (adToInsert, adImage) {
adImage.onload = function () {
adLoadedCallback(adToInsert, true);
};
})(adElement, adImage);
} else {
adLoadedCallback(adElement, false);
}
} | javascript | function handleImageLoad(adElement, adLoadedCallback) {
var adImage = adElement.querySelector("img");
if (adImage) {
(function (adToInsert, adImage) {
adImage.onload = function () {
adLoadedCallback(adToInsert, true);
};
})(adElement, adImage);
} else {
adLoadedCallback(adElement, false);
}
} | [
"function",
"handleImageLoad",
"(",
"adElement",
",",
"adLoadedCallback",
")",
"{",
"var",
"adImage",
"=",
"adElement",
".",
"querySelector",
"(",
"\"img\"",
")",
";",
"if",
"(",
"adImage",
")",
"{",
"(",
"function",
"(",
"adToInsert",
",",
"adImage",
")",
"{",
"adImage",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"adLoadedCallback",
"(",
"adToInsert",
",",
"true",
")",
";",
"}",
";",
"}",
")",
"(",
"adElement",
",",
"adImage",
")",
";",
"}",
"else",
"{",
"adLoadedCallback",
"(",
"adElement",
",",
"false",
")",
";",
"}",
"}"
]
| Add an event handler to the onload of ad images.
@param adElement - The HTML element of the advertisement
@param adLoadedCallback - Callback to execute when ads are loaded | [
"Add",
"an",
"event",
"handler",
"to",
"the",
"onload",
"of",
"ad",
"images",
"."
]
| aafee1c42e0569ee77f334fc2c4eb71eb146957e | https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/ads/insertAds.js#L57-L68 | train |
shkuznetsov/machinegun | index.js | function (powder) {
var callback = function (err) {
shooting--;
if (err) {
// Only emit error if a listener exists
// This is mainly to prevent silent errors in promises
if (machinegun.listenerCount('error')) machinegun.emit('error', err);
if (opt.giveUpOnError) machinegun.giveUp(err);
}
trigger();
};
var primer = function () {
var maybeThenable = powder(callback);
if (maybeThenable && (typeof maybeThenable.then == 'function')) {
maybeThenable.then(callback.bind(null, null), function (err) { callback(err || new Error()); });
}
};
this.shoot = function () {
shooting++;
process.nextTick(primer);
};
} | javascript | function (powder) {
var callback = function (err) {
shooting--;
if (err) {
// Only emit error if a listener exists
// This is mainly to prevent silent errors in promises
if (machinegun.listenerCount('error')) machinegun.emit('error', err);
if (opt.giveUpOnError) machinegun.giveUp(err);
}
trigger();
};
var primer = function () {
var maybeThenable = powder(callback);
if (maybeThenable && (typeof maybeThenable.then == 'function')) {
maybeThenable.then(callback.bind(null, null), function (err) { callback(err || new Error()); });
}
};
this.shoot = function () {
shooting++;
process.nextTick(primer);
};
} | [
"function",
"(",
"powder",
")",
"{",
"var",
"callback",
"=",
"function",
"(",
"err",
")",
"{",
"shooting",
"--",
";",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"machinegun",
".",
"listenerCount",
"(",
"'error'",
")",
")",
"machinegun",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"if",
"(",
"opt",
".",
"giveUpOnError",
")",
"machinegun",
".",
"giveUp",
"(",
"err",
")",
";",
"}",
"trigger",
"(",
")",
";",
"}",
";",
"var",
"primer",
"=",
"function",
"(",
")",
"{",
"var",
"maybeThenable",
"=",
"powder",
"(",
"callback",
")",
";",
"if",
"(",
"maybeThenable",
"&&",
"(",
"typeof",
"maybeThenable",
".",
"then",
"==",
"'function'",
")",
")",
"{",
"maybeThenable",
".",
"then",
"(",
"callback",
".",
"bind",
"(",
"null",
",",
"null",
")",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
"||",
"new",
"Error",
"(",
")",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"this",
".",
"shoot",
"=",
"function",
"(",
")",
"{",
"shooting",
"++",
";",
"process",
".",
"nextTick",
"(",
"primer",
")",
";",
"}",
";",
"}"
]
| Primer function wrapper class Used mainly to contextualise callback | [
"Primer",
"function",
"wrapper",
"class",
"Used",
"mainly",
"to",
"contextualise",
"callback"
]
| a9d342300dca7a7701a7f3954fe63bf88e206634 | https://github.com/shkuznetsov/machinegun/blob/a9d342300dca7a7701a7f3954fe63bf88e206634/index.js#L21-L42 | train |
|
hakovala/node-fse-promise | index.js | callPromise | function callPromise(fn, args) {
return new Promise((resolve, reject) => {
// promisified callback
function callback(err,other) {
// check if the 'err' is boolean, if so then this is a 'exists' callback special case
if (err && (typeof err !== 'boolean')) return reject(err);
// convert arguments to proper array, ignoring error argument
let args = Array.prototype.slice.call(arguments, 1);
// if arguments length is one or more resolve arguments as array,
// otherwise resolve the argument as is.
return resolve(args.length < 2 ? args[0] : args);
}
fn.apply(null, args.concat([callback]));
});
} | javascript | function callPromise(fn, args) {
return new Promise((resolve, reject) => {
// promisified callback
function callback(err,other) {
// check if the 'err' is boolean, if so then this is a 'exists' callback special case
if (err && (typeof err !== 'boolean')) return reject(err);
// convert arguments to proper array, ignoring error argument
let args = Array.prototype.slice.call(arguments, 1);
// if arguments length is one or more resolve arguments as array,
// otherwise resolve the argument as is.
return resolve(args.length < 2 ? args[0] : args);
}
fn.apply(null, args.concat([callback]));
});
} | [
"function",
"callPromise",
"(",
"fn",
",",
"args",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"function",
"callback",
"(",
"err",
",",
"other",
")",
"{",
"if",
"(",
"err",
"&&",
"(",
"typeof",
"err",
"!==",
"'boolean'",
")",
")",
"return",
"reject",
"(",
"err",
")",
";",
"let",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"return",
"resolve",
"(",
"args",
".",
"length",
"<",
"2",
"?",
"args",
"[",
"0",
"]",
":",
"args",
")",
";",
"}",
"fn",
".",
"apply",
"(",
"null",
",",
"args",
".",
"concat",
"(",
"[",
"callback",
"]",
")",
")",
";",
"}",
")",
";",
"}"
]
| Call method with promises | [
"Call",
"method",
"with",
"promises"
]
| 0171cd2927f4daad8c33ed99e1e46b53a7e24b90 | https://github.com/hakovala/node-fse-promise/blob/0171cd2927f4daad8c33ed99e1e46b53a7e24b90/index.js#L82-L96 | train |
hakovala/node-fse-promise | index.js | makePromise | function makePromise(fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
if (hasCallback(args)) {
// argument list has callback, so call method with callback
return callCallback(fn, args);
} else {
// no callback, call method with promises
return callPromise(fn, args);
}
}
} | javascript | function makePromise(fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
if (hasCallback(args)) {
// argument list has callback, so call method with callback
return callCallback(fn, args);
} else {
// no callback, call method with promises
return callPromise(fn, args);
}
}
} | [
"function",
"makePromise",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"if",
"(",
"hasCallback",
"(",
"args",
")",
")",
"{",
"return",
"callCallback",
"(",
"fn",
",",
"args",
")",
";",
"}",
"else",
"{",
"return",
"callPromise",
"(",
"fn",
",",
"args",
")",
";",
"}",
"}",
"}"
]
| Wrap method to handle both callbacks and promises | [
"Wrap",
"method",
"to",
"handle",
"both",
"callbacks",
"and",
"promises"
]
| 0171cd2927f4daad8c33ed99e1e46b53a7e24b90 | https://github.com/hakovala/node-fse-promise/blob/0171cd2927f4daad8c33ed99e1e46b53a7e24b90/index.js#L101-L112 | train |
mheadd/phl-property | index.js | standardizeAddress | function standardizeAddress(address, callback) {
var url = address_url + encodeURIComponent(address) + '?format=json';
request(url, function(err, resp, body) {
var error = resp.statusCode != 200 ? new Error('Unable to standardize address') : err;
callback(error, body);
});
} | javascript | function standardizeAddress(address, callback) {
var url = address_url + encodeURIComponent(address) + '?format=json';
request(url, function(err, resp, body) {
var error = resp.statusCode != 200 ? new Error('Unable to standardize address') : err;
callback(error, body);
});
} | [
"function",
"standardizeAddress",
"(",
"address",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"address_url",
"+",
"encodeURIComponent",
"(",
"address",
")",
"+",
"'?format=json'",
";",
"request",
"(",
"url",
",",
"function",
"(",
"err",
",",
"resp",
",",
"body",
")",
"{",
"var",
"error",
"=",
"resp",
".",
"statusCode",
"!=",
"200",
"?",
"new",
"Error",
"(",
"'Unable to standardize address'",
")",
":",
"err",
";",
"callback",
"(",
"error",
",",
"body",
")",
";",
"}",
")",
";",
"}"
]
| Standardize address and location information for a property. | [
"Standardize",
"address",
"and",
"location",
"information",
"for",
"a",
"property",
"."
]
| d94abe26cd9ec11a94320ccee42a6abb2e08d49e | https://github.com/mheadd/phl-property/blob/d94abe26cd9ec11a94320ccee42a6abb2e08d49e/index.js#L30-L36 | train |
mheadd/phl-property | index.js | getAddressDetails | function getAddressDetails(body, callback) {
var addresses = JSON.parse(body).addresses
if(addresses.length == 0) {
callback(new Error('No property information for that address'), null);
}
else {
var url = property_url + encodeURIComponent(addresses[0].standardizedAddress);
request(url, function(err, resp, body) {
callback(err, body);
});
}
} | javascript | function getAddressDetails(body, callback) {
var addresses = JSON.parse(body).addresses
if(addresses.length == 0) {
callback(new Error('No property information for that address'), null);
}
else {
var url = property_url + encodeURIComponent(addresses[0].standardizedAddress);
request(url, function(err, resp, body) {
callback(err, body);
});
}
} | [
"function",
"getAddressDetails",
"(",
"body",
",",
"callback",
")",
"{",
"var",
"addresses",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
".",
"addresses",
"if",
"(",
"addresses",
".",
"length",
"==",
"0",
")",
"{",
"callback",
"(",
"new",
"Error",
"(",
"'No property information for that address'",
")",
",",
"null",
")",
";",
"}",
"else",
"{",
"var",
"url",
"=",
"property_url",
"+",
"encodeURIComponent",
"(",
"addresses",
"[",
"0",
"]",
".",
"standardizedAddress",
")",
";",
"request",
"(",
"url",
",",
"function",
"(",
"err",
",",
"resp",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
")",
";",
"}",
")",
";",
"}",
"}"
]
| Get property details for an address. | [
"Get",
"property",
"details",
"for",
"an",
"address",
"."
]
| d94abe26cd9ec11a94320ccee42a6abb2e08d49e | https://github.com/mheadd/phl-property/blob/d94abe26cd9ec11a94320ccee42a6abb2e08d49e/index.js#L39-L50 | train |
verbose/verb-reflinks | index.js | isValidPackageName | function isValidPackageName(name) {
const stats = validateName(name);
return stats.validForNewPackages === true
&& stats.validForOldPackages === true;
} | javascript | function isValidPackageName(name) {
const stats = validateName(name);
return stats.validForNewPackages === true
&& stats.validForOldPackages === true;
} | [
"function",
"isValidPackageName",
"(",
"name",
")",
"{",
"const",
"stats",
"=",
"validateName",
"(",
"name",
")",
";",
"return",
"stats",
".",
"validForNewPackages",
"===",
"true",
"&&",
"stats",
".",
"validForOldPackages",
"===",
"true",
";",
"}"
]
| Returns true if the given name is a valid npm package name | [
"Returns",
"true",
"if",
"the",
"given",
"name",
"is",
"a",
"valid",
"npm",
"package",
"name"
]
| 89ee1e55a1385d6de03af9af97c28042de4e3b37 | https://github.com/verbose/verb-reflinks/blob/89ee1e55a1385d6de03af9af97c28042de4e3b37/index.js#L124-L128 | train |
Pocketbrain/native-ads-web-ad-library | src/device/deviceDetector.js | isValidPlatform | function isValidPlatform() {
if (appSettings.overrides && appSettings.overrides.platform) {
return true; //If a platform override is set, it's always valid
}
return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
} | javascript | function isValidPlatform() {
if (appSettings.overrides && appSettings.overrides.platform) {
return true; //If a platform override is set, it's always valid
}
return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
} | [
"function",
"isValidPlatform",
"(",
")",
"{",
"if",
"(",
"appSettings",
".",
"overrides",
"&&",
"appSettings",
".",
"overrides",
".",
"platform",
")",
"{",
"return",
"true",
";",
"}",
"return",
"/",
"iPhone|iPad|iPod|Android",
"/",
"i",
".",
"test",
"(",
"navigator",
".",
"userAgent",
")",
";",
"}"
]
| Check if the platform the user is currently visiting the page with is valid for
the ad library to run
@returns {boolean} | [
"Check",
"if",
"the",
"platform",
"the",
"user",
"is",
"currently",
"visiting",
"the",
"page",
"with",
"is",
"valid",
"for",
"the",
"ad",
"library",
"to",
"run"
]
| aafee1c42e0569ee77f334fc2c4eb71eb146957e | https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/device/deviceDetector.js#L14-L19 | train |
Pocketbrain/native-ads-web-ad-library | src/device/deviceDetector.js | detectFormFactor | function detectFormFactor() {
var viewPortWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var displaySettings = appSettings.displaySettings; //convenience variable
var formFactor;
if (viewPortWidth >= displaySettings.mobile.minWidth && viewPortWidth <= displaySettings.mobile.maxWidth) {
formFactor = DeviceEnumerations.formFactor.smartPhone;
} else if (viewPortWidth >= displaySettings.tablet.minWidth && viewPortWidth <= displaySettings.tablet.maxWidth) {
formFactor = DeviceEnumerations.formFactor.tablet;
} else {
formFactor = DeviceEnumerations.formFactor.desktop;
}
return formFactor;
} | javascript | function detectFormFactor() {
var viewPortWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var displaySettings = appSettings.displaySettings; //convenience variable
var formFactor;
if (viewPortWidth >= displaySettings.mobile.minWidth && viewPortWidth <= displaySettings.mobile.maxWidth) {
formFactor = DeviceEnumerations.formFactor.smartPhone;
} else if (viewPortWidth >= displaySettings.tablet.minWidth && viewPortWidth <= displaySettings.tablet.maxWidth) {
formFactor = DeviceEnumerations.formFactor.tablet;
} else {
formFactor = DeviceEnumerations.formFactor.desktop;
}
return formFactor;
} | [
"function",
"detectFormFactor",
"(",
")",
"{",
"var",
"viewPortWidth",
"=",
"Math",
".",
"max",
"(",
"document",
".",
"documentElement",
".",
"clientWidth",
",",
"window",
".",
"innerWidth",
"||",
"0",
")",
";",
"var",
"displaySettings",
"=",
"appSettings",
".",
"displaySettings",
";",
"var",
"formFactor",
";",
"if",
"(",
"viewPortWidth",
">=",
"displaySettings",
".",
"mobile",
".",
"minWidth",
"&&",
"viewPortWidth",
"<=",
"displaySettings",
".",
"mobile",
".",
"maxWidth",
")",
"{",
"formFactor",
"=",
"DeviceEnumerations",
".",
"formFactor",
".",
"smartPhone",
";",
"}",
"else",
"if",
"(",
"viewPortWidth",
">=",
"displaySettings",
".",
"tablet",
".",
"minWidth",
"&&",
"viewPortWidth",
"<=",
"displaySettings",
".",
"tablet",
".",
"maxWidth",
")",
"{",
"formFactor",
"=",
"DeviceEnumerations",
".",
"formFactor",
".",
"tablet",
";",
"}",
"else",
"{",
"formFactor",
"=",
"DeviceEnumerations",
".",
"formFactor",
".",
"desktop",
";",
"}",
"return",
"formFactor",
";",
"}"
]
| Detects the device form factor based on the ViewPort and the deviceWidths in AppSettings
The test_old is done based on the viewport, because it is already validated that a device is Android or iOS
@returns {*} the form factor of the device
@private | [
"Detects",
"the",
"device",
"form",
"factor",
"based",
"on",
"the",
"ViewPort",
"and",
"the",
"deviceWidths",
"in",
"AppSettings",
"The",
"test_old",
"is",
"done",
"based",
"on",
"the",
"viewport",
"because",
"it",
"is",
"already",
"validated",
"that",
"a",
"device",
"is",
"Android",
"or",
"iOS"
]
| aafee1c42e0569ee77f334fc2c4eb71eb146957e | https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/device/deviceDetector.js#L27-L42 | train |
smallhadroncollider/grunt-jspm | tasks/jspm.js | function () {
var pkgJson = grunt.file.readJSON("package.json");
if (pkgJson.jspm && pkgJson.jspm.directories && pkgJson.jspm.directories.baseURL) {
return pkgJson.jspm.directories.baseURL;
}
return "";
} | javascript | function () {
var pkgJson = grunt.file.readJSON("package.json");
if (pkgJson.jspm && pkgJson.jspm.directories && pkgJson.jspm.directories.baseURL) {
return pkgJson.jspm.directories.baseURL;
}
return "";
} | [
"function",
"(",
")",
"{",
"var",
"pkgJson",
"=",
"grunt",
".",
"file",
".",
"readJSON",
"(",
"\"package.json\"",
")",
";",
"if",
"(",
"pkgJson",
".",
"jspm",
"&&",
"pkgJson",
".",
"jspm",
".",
"directories",
"&&",
"pkgJson",
".",
"jspm",
".",
"directories",
".",
"baseURL",
")",
"{",
"return",
"pkgJson",
".",
"jspm",
".",
"directories",
".",
"baseURL",
";",
"}",
"return",
"\"\"",
";",
"}"
]
| Geth the JSPM baseURL from package.json | [
"Geth",
"the",
"JSPM",
"baseURL",
"from",
"package",
".",
"json"
]
| 45c02eedef0f1a578a379631891e0ef13406786e | https://github.com/smallhadroncollider/grunt-jspm/blob/45c02eedef0f1a578a379631891e0ef13406786e/tasks/jspm.js#L11-L19 | train |
|
apflieger/grunt-csstree | lib/csstree.js | function(treeRoot) {
var stat = fs.statSync(treeRoot);
if (stat.isDirectory()) {
return buildTree(treeRoot);
} else {
throw new Error("path: " + treeRoot + " is not a directory");
}
} | javascript | function(treeRoot) {
var stat = fs.statSync(treeRoot);
if (stat.isDirectory()) {
return buildTree(treeRoot);
} else {
throw new Error("path: " + treeRoot + " is not a directory");
}
} | [
"function",
"(",
"treeRoot",
")",
"{",
"var",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"treeRoot",
")",
";",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
"buildTree",
"(",
"treeRoot",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"path: \"",
"+",
"treeRoot",
"+",
"\" is not a directory\"",
")",
";",
"}",
"}"
]
| Crawl the given directory and build the tree object model for further use | [
"Crawl",
"the",
"given",
"directory",
"and",
"build",
"the",
"tree",
"object",
"model",
"for",
"further",
"use"
]
| a1844eb22acc7359116ab1fa9bf1004a6512a2b2 | https://github.com/apflieger/grunt-csstree/blob/a1844eb22acc7359116ab1fa9bf1004a6512a2b2/lib/csstree.js#L76-L83 | train |
|
apflieger/grunt-csstree | lib/csstree.js | function(tree, options) {
if (!options) {
options = {
ext: '.css',
importFormat: null, // to be initialized just bellow
encoding: 'utf-8'
};
}
if (!options.ext) {
options.ext = '.css';
}
if (!options.importFormat) {
if (options.ext === '.css') {
options.importFormat = function(path) {
return '@import "' + path + '";';
};
} else if (options.ext === '.less') {
options.importFormat = function(path) {
return '@import (less) "' + path + '";';
};
}
}
if (!options.encoding) {
options.encoding = 'utf-8';
}
generate(tree, null, options);
} | javascript | function(tree, options) {
if (!options) {
options = {
ext: '.css',
importFormat: null, // to be initialized just bellow
encoding: 'utf-8'
};
}
if (!options.ext) {
options.ext = '.css';
}
if (!options.importFormat) {
if (options.ext === '.css') {
options.importFormat = function(path) {
return '@import "' + path + '";';
};
} else if (options.ext === '.less') {
options.importFormat = function(path) {
return '@import (less) "' + path + '";';
};
}
}
if (!options.encoding) {
options.encoding = 'utf-8';
}
generate(tree, null, options);
} | [
"function",
"(",
"tree",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"ext",
":",
"'.css'",
",",
"importFormat",
":",
"null",
",",
"encoding",
":",
"'utf-8'",
"}",
";",
"}",
"if",
"(",
"!",
"options",
".",
"ext",
")",
"{",
"options",
".",
"ext",
"=",
"'.css'",
";",
"}",
"if",
"(",
"!",
"options",
".",
"importFormat",
")",
"{",
"if",
"(",
"options",
".",
"ext",
"===",
"'.css'",
")",
"{",
"options",
".",
"importFormat",
"=",
"function",
"(",
"path",
")",
"{",
"return",
"'@import \"'",
"+",
"path",
"+",
"'\";'",
";",
"}",
";",
"}",
"else",
"if",
"(",
"options",
".",
"ext",
"===",
"'.less'",
")",
"{",
"options",
".",
"importFormat",
"=",
"function",
"(",
"path",
")",
"{",
"return",
"'@import (less) \"'",
"+",
"path",
"+",
"'\";'",
";",
"}",
";",
"}",
"}",
"if",
"(",
"!",
"options",
".",
"encoding",
")",
"{",
"options",
".",
"encoding",
"=",
"'utf-8'",
";",
"}",
"generate",
"(",
"tree",
",",
"null",
",",
"options",
")",
";",
"}"
]
| Generate the files that contains @import rules on the given tree | [
"Generate",
"the",
"files",
"that",
"contains"
]
| a1844eb22acc7359116ab1fa9bf1004a6512a2b2 | https://github.com/apflieger/grunt-csstree/blob/a1844eb22acc7359116ab1fa9bf1004a6512a2b2/lib/csstree.js#L85-L115 | train |
|
intervolga/bemjson-loader | lib/validate-bemdecl.js | validateBemDecl | function validateBemDecl(bemDecl, fileName) {
let errors = [];
bemDecl.forEach((decl) => {
errors = errors.concat(validateBemDeclItem(decl, fileName));
});
return errors;
} | javascript | function validateBemDecl(bemDecl, fileName) {
let errors = [];
bemDecl.forEach((decl) => {
errors = errors.concat(validateBemDeclItem(decl, fileName));
});
return errors;
} | [
"function",
"validateBemDecl",
"(",
"bemDecl",
",",
"fileName",
")",
"{",
"let",
"errors",
"=",
"[",
"]",
";",
"bemDecl",
".",
"forEach",
"(",
"(",
"decl",
")",
"=>",
"{",
"errors",
"=",
"errors",
".",
"concat",
"(",
"validateBemDeclItem",
"(",
"decl",
",",
"fileName",
")",
")",
";",
"}",
")",
";",
"return",
"errors",
";",
"}"
]
| Validate BEM declarations
@param {Array} bemDecl
@param {String} fileName
@return {Array} of validation errors | [
"Validate",
"BEM",
"declarations"
]
| c4ff680ee07ab939d400f241859fe608411fd8de | https://github.com/intervolga/bemjson-loader/blob/c4ff680ee07ab939d400f241859fe608411fd8de/lib/validate-bemdecl.js#L8-L16 | train |
intervolga/bemjson-loader | lib/validate-bemdecl.js | validateBemDeclItem | function validateBemDeclItem(decl, fileName) {
let errors = [];
Object.keys(decl).forEach((key) => {
const val = decl[key];
if (val === '[object Object]') {
errors.push(new Error('Error in BemJson ' + fileName +
' produced wrong BemDecl ' + JSON.stringify(decl, null, 2)));
}
});
return errors;
} | javascript | function validateBemDeclItem(decl, fileName) {
let errors = [];
Object.keys(decl).forEach((key) => {
const val = decl[key];
if (val === '[object Object]') {
errors.push(new Error('Error in BemJson ' + fileName +
' produced wrong BemDecl ' + JSON.stringify(decl, null, 2)));
}
});
return errors;
} | [
"function",
"validateBemDeclItem",
"(",
"decl",
",",
"fileName",
")",
"{",
"let",
"errors",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"decl",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"const",
"val",
"=",
"decl",
"[",
"key",
"]",
";",
"if",
"(",
"val",
"===",
"'[object Object]'",
")",
"{",
"errors",
".",
"push",
"(",
"new",
"Error",
"(",
"'Error in BemJson '",
"+",
"fileName",
"+",
"' produced wrong BemDecl '",
"+",
"JSON",
".",
"stringify",
"(",
"decl",
",",
"null",
",",
"2",
")",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"errors",
";",
"}"
]
| Validate single BEM declaration
@param {Object} decl
@param {String} fileName
@return {Array} of validation errors | [
"Validate",
"single",
"BEM",
"declaration"
]
| c4ff680ee07ab939d400f241859fe608411fd8de | https://github.com/intervolga/bemjson-loader/blob/c4ff680ee07ab939d400f241859fe608411fd8de/lib/validate-bemdecl.js#L25-L37 | train |
royriojas/simplessy | compile-less.js | _getToken | function _getToken( /*klass, klass1, klass2*/ ) {
if ( !tokens ) {
throw new Error( 'no tokens found' );
}
var _args = [ ].slice.call( arguments ).join( ' ' ).split( ' ' );
var _result = _args.map( function ( klass ) {
var token = tokens[ klass ];
if ( !token ) {
throw new Error( 'no token found for ' + klass );
}
return token;
} ).join( ' ' );
return _result;
} | javascript | function _getToken( /*klass, klass1, klass2*/ ) {
if ( !tokens ) {
throw new Error( 'no tokens found' );
}
var _args = [ ].slice.call( arguments ).join( ' ' ).split( ' ' );
var _result = _args.map( function ( klass ) {
var token = tokens[ klass ];
if ( !token ) {
throw new Error( 'no token found for ' + klass );
}
return token;
} ).join( ' ' );
return _result;
} | [
"function",
"_getToken",
"(",
")",
"{",
"if",
"(",
"!",
"tokens",
")",
"{",
"throw",
"new",
"Error",
"(",
"'no tokens found'",
")",
";",
"}",
"var",
"_args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"join",
"(",
"' '",
")",
".",
"split",
"(",
"' '",
")",
";",
"var",
"_result",
"=",
"_args",
".",
"map",
"(",
"function",
"(",
"klass",
")",
"{",
"var",
"token",
"=",
"tokens",
"[",
"klass",
"]",
";",
"if",
"(",
"!",
"token",
")",
"{",
"throw",
"new",
"Error",
"(",
"'no token found for '",
"+",
"klass",
")",
";",
"}",
"return",
"token",
";",
"}",
")",
".",
"join",
"(",
"' '",
")",
";",
"return",
"_result",
";",
"}"
]
| be careful here, this function is defined like this for ease of use, but this is going to actually be serialized inside the output of the transform so tokens inside this function, refer to the tokens variable declared in the transformed code | [
"be",
"careful",
"here",
"this",
"function",
"is",
"defined",
"like",
"this",
"for",
"ease",
"of",
"use",
"but",
"this",
"is",
"going",
"to",
"actually",
"be",
"serialized",
"inside",
"the",
"output",
"of",
"the",
"transform",
"so",
"tokens",
"inside",
"this",
"function",
"refer",
"to",
"the",
"tokens",
"variable",
"declared",
"in",
"the",
"transformed",
"code"
]
| ac6c7af664c846bcfb23099ca5f6841335f833ae | https://github.com/royriojas/simplessy/blob/ac6c7af664c846bcfb23099ca5f6841335f833ae/compile-less.js#L58-L76 | train |
Chapabu/gulp-holograph | src/index.js | handleBuffer | function handleBuffer (file, encoding, cb) {
const config = configParser(String(file.contents));
holograph.holograph(config);
return cb(null, file);
} | javascript | function handleBuffer (file, encoding, cb) {
const config = configParser(String(file.contents));
holograph.holograph(config);
return cb(null, file);
} | [
"function",
"handleBuffer",
"(",
"file",
",",
"encoding",
",",
"cb",
")",
"{",
"const",
"config",
"=",
"configParser",
"(",
"String",
"(",
"file",
".",
"contents",
")",
")",
";",
"holograph",
".",
"holograph",
"(",
"config",
")",
";",
"return",
"cb",
"(",
"null",
",",
"file",
")",
";",
"}"
]
| Run Hologram when given a buffer.
@param {Object} file A Vinyl file.
@param {String} encoding The file encoding.
@param {Function} cb Called after hologram has run.
@returns {Function} Executed callback. | [
"Run",
"Hologram",
"when",
"given",
"a",
"buffer",
"."
]
| 182dc177efd593956abf31d3a402f2d02daa95a5 | https://github.com/Chapabu/gulp-holograph/blob/182dc177efd593956abf31d3a402f2d02daa95a5/src/index.js#L20-L24 | train |
Chapabu/gulp-holograph | src/index.js | handleStream | function handleStream (file, encoding, cb) {
let config = '';
file.contents.on('data', chunk => {
config += chunk;
});
file.contents.on('end', () => {
config = configParser(config);
holograph.holograph(config);
return cb(null, file);
});
} | javascript | function handleStream (file, encoding, cb) {
let config = '';
file.contents.on('data', chunk => {
config += chunk;
});
file.contents.on('end', () => {
config = configParser(config);
holograph.holograph(config);
return cb(null, file);
});
} | [
"function",
"handleStream",
"(",
"file",
",",
"encoding",
",",
"cb",
")",
"{",
"let",
"config",
"=",
"''",
";",
"file",
".",
"contents",
".",
"on",
"(",
"'data'",
",",
"chunk",
"=>",
"{",
"config",
"+=",
"chunk",
";",
"}",
")",
";",
"file",
".",
"contents",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"config",
"=",
"configParser",
"(",
"config",
")",
";",
"holograph",
".",
"holograph",
"(",
"config",
")",
";",
"return",
"cb",
"(",
"null",
",",
"file",
")",
";",
"}",
")",
";",
"}"
]
| Run Hologram when given a stream.
@param {Object} file A Vinyl file.
@param {String} encoding The file encoding.
@param {Function} cb Called after hologram has run.
@returns {Function} Executed callback. | [
"Run",
"Hologram",
"when",
"given",
"a",
"stream",
"."
]
| 182dc177efd593956abf31d3a402f2d02daa95a5 | https://github.com/Chapabu/gulp-holograph/blob/182dc177efd593956abf31d3a402f2d02daa95a5/src/index.js#L34-L48 | train |
Chapabu/gulp-holograph | src/index.js | gulpHolograph | function gulpHolograph () {
return through.obj(function (file, encoding, cb) {
// Handle any non-supported types.
// This covers directories and symlinks as well, as they have to be null.
if (file.isNull()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'No file contents.'));
}
// Handle buffers.
if (file.isBuffer()) {
handleBuffer(file, encoding, cb);
}
// Handle streams.
if (file.isStream()) {
handleStream(file, encoding, cb);
}
});
} | javascript | function gulpHolograph () {
return through.obj(function (file, encoding, cb) {
// Handle any non-supported types.
// This covers directories and symlinks as well, as they have to be null.
if (file.isNull()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'No file contents.'));
}
// Handle buffers.
if (file.isBuffer()) {
handleBuffer(file, encoding, cb);
}
// Handle streams.
if (file.isStream()) {
handleStream(file, encoding, cb);
}
});
} | [
"function",
"gulpHolograph",
"(",
")",
"{",
"return",
"through",
".",
"obj",
"(",
"function",
"(",
"file",
",",
"encoding",
",",
"cb",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"{",
"this",
".",
"emit",
"(",
"'error'",
",",
"new",
"PluginError",
"(",
"PLUGIN_NAME",
",",
"'No file contents.'",
")",
")",
";",
"}",
"if",
"(",
"file",
".",
"isBuffer",
"(",
")",
")",
"{",
"handleBuffer",
"(",
"file",
",",
"encoding",
",",
"cb",
")",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"handleStream",
"(",
"file",
",",
"encoding",
",",
"cb",
")",
";",
"}",
"}",
")",
";",
"}"
]
| The actual plugin. Runs Holograph with a provided config file.
@returns {Object} A through2 stream. | [
"The",
"actual",
"plugin",
".",
"Runs",
"Holograph",
"with",
"a",
"provided",
"config",
"file",
"."
]
| 182dc177efd593956abf31d3a402f2d02daa95a5 | https://github.com/Chapabu/gulp-holograph/blob/182dc177efd593956abf31d3a402f2d02daa95a5/src/index.js#L55-L77 | train |
ianmuninio/jmodel | lib/error.js | JModelError | function JModelError(obj) {
this.message = obj['message'];
this.propertyName = obj['propertyName'];
Error.call(this);
Error.captureStackTrace(this, this.constructor);
} | javascript | function JModelError(obj) {
this.message = obj['message'];
this.propertyName = obj['propertyName'];
Error.call(this);
Error.captureStackTrace(this, this.constructor);
} | [
"function",
"JModelError",
"(",
"obj",
")",
"{",
"this",
".",
"message",
"=",
"obj",
"[",
"'message'",
"]",
";",
"this",
".",
"propertyName",
"=",
"obj",
"[",
"'propertyName'",
"]",
";",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"}"
]
| JModel Error Class
@param {Object} obj
@returns {JModelError} | [
"JModel",
"Error",
"Class"
]
| c118bfc46596f59445604acc43b01ad2b04c31ef | https://github.com/ianmuninio/jmodel/blob/c118bfc46596f59445604acc43b01ad2b04c31ef/lib/error.js#L14-L20 | train |
weisjohn/jsonload | index.js | normalize | function normalize(filepath) {
// resolve to an absolute ppath
if (!path.isAbsolute || !path.isAbsolute(filepath))
filepath = path.resolve(path.dirname(module.parent.filename), filepath);
// tack .json on the end if need be
if (!/\.json$/.test(filepath))
filepath = filepath + '.json';
return filepath;
} | javascript | function normalize(filepath) {
// resolve to an absolute ppath
if (!path.isAbsolute || !path.isAbsolute(filepath))
filepath = path.resolve(path.dirname(module.parent.filename), filepath);
// tack .json on the end if need be
if (!/\.json$/.test(filepath))
filepath = filepath + '.json';
return filepath;
} | [
"function",
"normalize",
"(",
"filepath",
")",
"{",
"if",
"(",
"!",
"path",
".",
"isAbsolute",
"||",
"!",
"path",
".",
"isAbsolute",
"(",
"filepath",
")",
")",
"filepath",
"=",
"path",
".",
"resolve",
"(",
"path",
".",
"dirname",
"(",
"module",
".",
"parent",
".",
"filename",
")",
",",
"filepath",
")",
";",
"if",
"(",
"!",
"/",
"\\.json$",
"/",
".",
"test",
"(",
"filepath",
")",
")",
"filepath",
"=",
"filepath",
"+",
"'.json'",
";",
"return",
"filepath",
";",
"}"
]
| clean up paths for convenient loading | [
"clean",
"up",
"paths",
"for",
"convenient",
"loading"
]
| 53ad101bc32c766c75bf93616a805ab67edaa9ef | https://github.com/weisjohn/jsonload/blob/53ad101bc32c766c75bf93616a805ab67edaa9ef/index.js#L6-L17 | train |
weisjohn/jsonload | index.js | parse | function parse(contents, retained, parser) {
var errors = [], data = [], lines = 0;
// optional parser
if (!parser) parser = JSON;
// process each line of the file
contents.toString().split('\n').forEach(function(line) {
if (!line) return;
lines++;
try {
data.push(parser.parse(line));
} catch (e) {
e.line = line;
errors.push(e);
}
});
// if no errors/data, don't return an empty array
var ret = {};
if (errors.length) ret.errors = errors;
if (data.length) ret.data = data;
// if every line failed, probably not line-delimited
if (errors.length == lines) ret.errors = retained;
return ret;
} | javascript | function parse(contents, retained, parser) {
var errors = [], data = [], lines = 0;
// optional parser
if (!parser) parser = JSON;
// process each line of the file
contents.toString().split('\n').forEach(function(line) {
if (!line) return;
lines++;
try {
data.push(parser.parse(line));
} catch (e) {
e.line = line;
errors.push(e);
}
});
// if no errors/data, don't return an empty array
var ret = {};
if (errors.length) ret.errors = errors;
if (data.length) ret.data = data;
// if every line failed, probably not line-delimited
if (errors.length == lines) ret.errors = retained;
return ret;
} | [
"function",
"parse",
"(",
"contents",
",",
"retained",
",",
"parser",
")",
"{",
"var",
"errors",
"=",
"[",
"]",
",",
"data",
"=",
"[",
"]",
",",
"lines",
"=",
"0",
";",
"if",
"(",
"!",
"parser",
")",
"parser",
"=",
"JSON",
";",
"contents",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"forEach",
";",
"(",
"function",
"(",
"line",
")",
"{",
"if",
"(",
"!",
"line",
")",
"return",
";",
"lines",
"++",
";",
"try",
"{",
"data",
".",
"push",
"(",
"parser",
".",
"parse",
"(",
"line",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"e",
".",
"line",
"=",
"line",
";",
"errors",
".",
"push",
"(",
"e",
")",
";",
"}",
"}",
")",
"var",
"ret",
"=",
"{",
"}",
";",
"if",
"(",
"errors",
".",
"length",
")",
"ret",
".",
"errors",
"=",
"errors",
";",
"if",
"(",
"data",
".",
"length",
")",
"ret",
".",
"data",
"=",
"data",
";",
"if",
"(",
"errors",
".",
"length",
"==",
"lines",
")",
"ret",
".",
"errors",
"=",
"retained",
";",
"}"
]
| process line-delimited files | [
"process",
"line",
"-",
"delimited",
"files"
]
| 53ad101bc32c766c75bf93616a805ab67edaa9ef | https://github.com/weisjohn/jsonload/blob/53ad101bc32c766c75bf93616a805ab67edaa9ef/index.js#L20-L47 | train |
AgronKabashi/trastpiler | lib/trastpiler.js | createTranspiler | function createTranspiler ({ mappers = {}, initialScopeData } = {}) {
const config = {
scope: createScope(initialScopeData),
mappers
};
return (config.decoratedTranspile = transpile.bind(null, config));
} | javascript | function createTranspiler ({ mappers = {}, initialScopeData } = {}) {
const config = {
scope: createScope(initialScopeData),
mappers
};
return (config.decoratedTranspile = transpile.bind(null, config));
} | [
"function",
"createTranspiler",
"(",
"{",
"mappers",
"=",
"{",
"}",
",",
"initialScopeData",
"}",
"=",
"{",
"}",
")",
"{",
"const",
"config",
"=",
"{",
"scope",
":",
"createScope",
"(",
"initialScopeData",
")",
",",
"mappers",
"}",
";",
"return",
"(",
"config",
".",
"decoratedTranspile",
"=",
"transpile",
".",
"bind",
"(",
"null",
",",
"config",
")",
")",
";",
"}"
]
| eslint-disable-line no-use-before-define | [
"eslint",
"-",
"disable",
"-",
"line",
"no",
"-",
"use",
"-",
"before",
"-",
"define"
]
| 6bbebda1290aa2aaf9dfe6c286777aa20bfe56c5 | https://github.com/AgronKabashi/trastpiler/blob/6bbebda1290aa2aaf9dfe6c286777aa20bfe56c5/lib/trastpiler.js#L53-L60 | train |
ltoussaint/node-bootstrap-core | routers/matchPath.js | MatchPath | function MatchPath() {
var defaultAction = 'welcome',
defaultMethod = 'index';
/**
* Resolve uri
* @param request
* @returns {*}
*/
this.resolve = function (request) {
var action = defaultAction;
var method = defaultMethod;
if ('/' != request.url) {
var uriComponents = request.url.split('?')[0].substr(1).split('/');
if (uriComponents.length > 1) {
method = uriComponents.pop();
action = uriComponents.join('/');
} else if (uriComponents.length == 1) {
action = uriComponents[0];
}
}
return {
action: action,
method: method,
arguments: []
};
};
/**
* Set default action
* @param action
* @returns {MatchPath}
*/
this.setDefaultAction = function (action) {
defaultAction = action;
return this;
};
/**
* Set default method
* @param method
* @returns {MatchPath}
*/
this.setDefaultMethod = function (method) {
defaultMethod = method;
return this;
};
return this;
} | javascript | function MatchPath() {
var defaultAction = 'welcome',
defaultMethod = 'index';
/**
* Resolve uri
* @param request
* @returns {*}
*/
this.resolve = function (request) {
var action = defaultAction;
var method = defaultMethod;
if ('/' != request.url) {
var uriComponents = request.url.split('?')[0].substr(1).split('/');
if (uriComponents.length > 1) {
method = uriComponents.pop();
action = uriComponents.join('/');
} else if (uriComponents.length == 1) {
action = uriComponents[0];
}
}
return {
action: action,
method: method,
arguments: []
};
};
/**
* Set default action
* @param action
* @returns {MatchPath}
*/
this.setDefaultAction = function (action) {
defaultAction = action;
return this;
};
/**
* Set default method
* @param method
* @returns {MatchPath}
*/
this.setDefaultMethod = function (method) {
defaultMethod = method;
return this;
};
return this;
} | [
"function",
"MatchPath",
"(",
")",
"{",
"var",
"defaultAction",
"=",
"'welcome'",
",",
"defaultMethod",
"=",
"'index'",
";",
"this",
".",
"resolve",
"=",
"function",
"(",
"request",
")",
"{",
"var",
"action",
"=",
"defaultAction",
";",
"var",
"method",
"=",
"defaultMethod",
";",
"if",
"(",
"'/'",
"!=",
"request",
".",
"url",
")",
"{",
"var",
"uriComponents",
"=",
"request",
".",
"url",
".",
"split",
"(",
"'?'",
")",
"[",
"0",
"]",
".",
"substr",
"(",
"1",
")",
".",
"split",
"(",
"'/'",
")",
";",
"if",
"(",
"uriComponents",
".",
"length",
">",
"1",
")",
"{",
"method",
"=",
"uriComponents",
".",
"pop",
"(",
")",
";",
"action",
"=",
"uriComponents",
".",
"join",
"(",
"'/'",
")",
";",
"}",
"else",
"if",
"(",
"uriComponents",
".",
"length",
"==",
"1",
")",
"{",
"action",
"=",
"uriComponents",
"[",
"0",
"]",
";",
"}",
"}",
"return",
"{",
"action",
":",
"action",
",",
"method",
":",
"method",
",",
"arguments",
":",
"[",
"]",
"}",
";",
"}",
";",
"this",
".",
"setDefaultAction",
"=",
"function",
"(",
"action",
")",
"{",
"defaultAction",
"=",
"action",
";",
"return",
"this",
";",
"}",
";",
"this",
".",
"setDefaultMethod",
"=",
"function",
"(",
"method",
")",
"{",
"defaultMethod",
"=",
"method",
";",
"return",
"this",
";",
"}",
";",
"return",
"this",
";",
"}"
]
| Simple router which will match url pathname with an action
@returns {MatchPath}
@constructor | [
"Simple",
"router",
"which",
"will",
"match",
"url",
"pathname",
"with",
"an",
"action"
]
| b083b320900ed068007e58af2249825b8da24c79 | https://github.com/ltoussaint/node-bootstrap-core/blob/b083b320900ed068007e58af2249825b8da24c79/routers/matchPath.js#L8-L60 | train |
twolfson/grunt-init-init | src/init/resolveTemplateFiles.js | resolveTemplateFiles | function resolveTemplateFiles(name) {
// Create paths for resolving
var customFile = customDir + '/' + name + '.js',
customTemplateDir = customDir + '/' + name + '/**/*',
stdFile = stdDir + '/' + name + '.js',
stdTemplateDir = stdDir + '/' + name + '/**/*';
// Grab any and all files
var customFiles = expandFiles(customFile).concat(expandFiles(customTemplateDir)),
stdFiles = expandFiles(stdFile).concat(expandFiles(stdTemplateDir));
// Generate a hash of files
var fileMap = {};
// Iterate over the customFiles
customFiles.forEach(function (file) {
// Extract the relative path of the file
var relPath = path.relative(customDir, file);
// Save the relative path
fileMap[relPath] = file;
});
// Iterate over the stdFiles
stdFiles.forEach(function (file) {
// Extract the relative path of the file
var relPath = path.relative(stdDir, file),
overrideExists = fileMap[relPath];
// If it does not exist, save it
if (!overrideExists) {
fileMap[relPath] = file;
}
});
// Return the fileMap
return fileMap;
} | javascript | function resolveTemplateFiles(name) {
// Create paths for resolving
var customFile = customDir + '/' + name + '.js',
customTemplateDir = customDir + '/' + name + '/**/*',
stdFile = stdDir + '/' + name + '.js',
stdTemplateDir = stdDir + '/' + name + '/**/*';
// Grab any and all files
var customFiles = expandFiles(customFile).concat(expandFiles(customTemplateDir)),
stdFiles = expandFiles(stdFile).concat(expandFiles(stdTemplateDir));
// Generate a hash of files
var fileMap = {};
// Iterate over the customFiles
customFiles.forEach(function (file) {
// Extract the relative path of the file
var relPath = path.relative(customDir, file);
// Save the relative path
fileMap[relPath] = file;
});
// Iterate over the stdFiles
stdFiles.forEach(function (file) {
// Extract the relative path of the file
var relPath = path.relative(stdDir, file),
overrideExists = fileMap[relPath];
// If it does not exist, save it
if (!overrideExists) {
fileMap[relPath] = file;
}
});
// Return the fileMap
return fileMap;
} | [
"function",
"resolveTemplateFiles",
"(",
"name",
")",
"{",
"var",
"customFile",
"=",
"customDir",
"+",
"'/'",
"+",
"name",
"+",
"'.js'",
",",
"customTemplateDir",
"=",
"customDir",
"+",
"'/'",
"+",
"name",
"+",
"'/**/*'",
",",
"stdFile",
"=",
"stdDir",
"+",
"'/'",
"+",
"name",
"+",
"'.js'",
",",
"stdTemplateDir",
"=",
"stdDir",
"+",
"'/'",
"+",
"name",
"+",
"'/**/*'",
";",
"var",
"customFiles",
"=",
"expandFiles",
"(",
"customFile",
")",
".",
"concat",
"(",
"expandFiles",
"(",
"customTemplateDir",
")",
")",
",",
"stdFiles",
"=",
"expandFiles",
"(",
"stdFile",
")",
".",
"concat",
"(",
"expandFiles",
"(",
"stdTemplateDir",
")",
")",
";",
"var",
"fileMap",
"=",
"{",
"}",
";",
"customFiles",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"relPath",
"=",
"path",
".",
"relative",
"(",
"customDir",
",",
"file",
")",
";",
"fileMap",
"[",
"relPath",
"]",
"=",
"file",
";",
"}",
")",
";",
"stdFiles",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"relPath",
"=",
"path",
".",
"relative",
"(",
"stdDir",
",",
"file",
")",
",",
"overrideExists",
"=",
"fileMap",
"[",
"relPath",
"]",
";",
"if",
"(",
"!",
"overrideExists",
")",
"{",
"fileMap",
"[",
"relPath",
"]",
"=",
"file",
";",
"}",
"}",
")",
";",
"return",
"fileMap",
";",
"}"
]
| Define a helper to find custom and standard template files | [
"Define",
"a",
"helper",
"to",
"find",
"custom",
"and",
"standard",
"template",
"files"
]
| 2dd3d063f06213c4ca086ec5b220759067ecd567 | https://github.com/twolfson/grunt-init-init/blob/2dd3d063f06213c4ca086ec5b220759067ecd567/src/init/resolveTemplateFiles.js#L9-L46 | train |
pinyin/outline | vendor/transformation-matrix/rotate.js | rotate | function rotate(angle, cx, cy) {
var cosAngle = cos(angle);
var sinAngle = sin(angle);
var rotationMatrix = {
a: cosAngle, c: -sinAngle, e: 0,
b: sinAngle, d: cosAngle, f: 0
};
if ((0, _utils.isUndefined)(cx) || (0, _utils.isUndefined)(cy)) {
return rotationMatrix;
}
return (0, _transform.transform)([(0, _translate.translate)(cx, cy), rotationMatrix, (0, _translate.translate)(-cx, -cy)]);
} | javascript | function rotate(angle, cx, cy) {
var cosAngle = cos(angle);
var sinAngle = sin(angle);
var rotationMatrix = {
a: cosAngle, c: -sinAngle, e: 0,
b: sinAngle, d: cosAngle, f: 0
};
if ((0, _utils.isUndefined)(cx) || (0, _utils.isUndefined)(cy)) {
return rotationMatrix;
}
return (0, _transform.transform)([(0, _translate.translate)(cx, cy), rotationMatrix, (0, _translate.translate)(-cx, -cy)]);
} | [
"function",
"rotate",
"(",
"angle",
",",
"cx",
",",
"cy",
")",
"{",
"var",
"cosAngle",
"=",
"cos",
"(",
"angle",
")",
";",
"var",
"sinAngle",
"=",
"sin",
"(",
"angle",
")",
";",
"var",
"rotationMatrix",
"=",
"{",
"a",
":",
"cosAngle",
",",
"c",
":",
"-",
"sinAngle",
",",
"e",
":",
"0",
",",
"b",
":",
"sinAngle",
",",
"d",
":",
"cosAngle",
",",
"f",
":",
"0",
"}",
";",
"if",
"(",
"(",
"0",
",",
"_utils",
".",
"isUndefined",
")",
"(",
"cx",
")",
"||",
"(",
"0",
",",
"_utils",
".",
"isUndefined",
")",
"(",
"cy",
")",
")",
"{",
"return",
"rotationMatrix",
";",
"}",
"return",
"(",
"0",
",",
"_transform",
".",
"transform",
")",
"(",
"[",
"(",
"0",
",",
"_translate",
".",
"translate",
")",
"(",
"cx",
",",
"cy",
")",
",",
"rotationMatrix",
",",
"(",
"0",
",",
"_translate",
".",
"translate",
")",
"(",
"-",
"cx",
",",
"-",
"cy",
")",
"]",
")",
";",
"}"
]
| Calculate a rotation matrix
@param angle Angle in radians
@param [cx] If (cx,cy) are supplied the rotate is about this point
@param [cy] If (cx,cy) are supplied the rotate is about this point
@returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix * | [
"Calculate",
"a",
"rotation",
"matrix"
]
| e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/rotate.js#L27-L39 | train |
pinyin/outline | vendor/transformation-matrix/rotate.js | rotateDEG | function rotateDEG(angle) {
var cx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var cy = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return rotate(angle * PI / 180, cx, cy);
} | javascript | function rotateDEG(angle) {
var cx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var cy = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
return rotate(angle * PI / 180, cx, cy);
} | [
"function",
"rotateDEG",
"(",
"angle",
")",
"{",
"var",
"cx",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"undefined",
";",
"var",
"cy",
"=",
"arguments",
".",
"length",
">",
"2",
"&&",
"arguments",
"[",
"2",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"2",
"]",
":",
"undefined",
";",
"return",
"rotate",
"(",
"angle",
"*",
"PI",
"/",
"180",
",",
"cx",
",",
"cy",
")",
";",
"}"
]
| Calculate a rotation matrix with a DEG angle
@param angle Angle in degree
@param [cx] If (cx,cy) are supplied the rotate is about this point
@param [cy] If (cx,cy) are supplied the rotate is about this point
@returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix | [
"Calculate",
"a",
"rotation",
"matrix",
"with",
"a",
"DEG",
"angle"
]
| e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/rotate.js#L48-L53 | train |
vnykmshr/proc-utils | lib/proc.js | reload | function reload(args) {
if (args !== undefined) {
if (args.l !== undefined) {
fs.closeSync(1);
fs.openSync(args.l, 'a+');
}
if (args.e !== undefined) {
fs.closeSync(2);
fs.openSync(args.e, 'a+');
}
}
} | javascript | function reload(args) {
if (args !== undefined) {
if (args.l !== undefined) {
fs.closeSync(1);
fs.openSync(args.l, 'a+');
}
if (args.e !== undefined) {
fs.closeSync(2);
fs.openSync(args.e, 'a+');
}
}
} | [
"function",
"reload",
"(",
"args",
")",
"{",
"if",
"(",
"args",
"!==",
"undefined",
")",
"{",
"if",
"(",
"args",
".",
"l",
"!==",
"undefined",
")",
"{",
"fs",
".",
"closeSync",
"(",
"1",
")",
";",
"fs",
".",
"openSync",
"(",
"args",
".",
"l",
",",
"'a+'",
")",
";",
"}",
"if",
"(",
"args",
".",
"e",
"!==",
"undefined",
")",
"{",
"fs",
".",
"closeSync",
"(",
"2",
")",
";",
"fs",
".",
"openSync",
"(",
"args",
".",
"e",
",",
"'a+'",
")",
";",
"}",
"}",
"}"
]
| Close the standard output and error descriptors
and redirect them to the specified files provided
in the argument | [
"Close",
"the",
"standard",
"output",
"and",
"error",
"descriptors",
"and",
"redirect",
"them",
"to",
"the",
"specified",
"files",
"provided",
"in",
"the",
"argument"
]
| cae3b96a9cd6689a3e5cfedfefef3718c1e4839c | https://github.com/vnykmshr/proc-utils/blob/cae3b96a9cd6689a3e5cfedfefef3718c1e4839c/lib/proc.js#L17-L29 | train |
vnykmshr/proc-utils | lib/proc.js | setupHandlers | function setupHandlers() {
function terminate(err) {
util.log('Uncaught Error: ' + err.message);
console.log(err.stack);
if (proc.shutdownHook) {
proc.shutdownHook(err, gracefulShutdown);
}
}
process.on('uncaughtException', terminate);
process.addListener('SIGINT', gracefulShutdown);
process.addListener('SIGHUP', function () {
util.log('RECIEVED SIGHUP signal, reloading log files...');
reload(argv);
});
} | javascript | function setupHandlers() {
function terminate(err) {
util.log('Uncaught Error: ' + err.message);
console.log(err.stack);
if (proc.shutdownHook) {
proc.shutdownHook(err, gracefulShutdown);
}
}
process.on('uncaughtException', terminate);
process.addListener('SIGINT', gracefulShutdown);
process.addListener('SIGHUP', function () {
util.log('RECIEVED SIGHUP signal, reloading log files...');
reload(argv);
});
} | [
"function",
"setupHandlers",
"(",
")",
"{",
"function",
"terminate",
"(",
"err",
")",
"{",
"util",
".",
"log",
"(",
"'Uncaught Error: '",
"+",
"err",
".",
"message",
")",
";",
"console",
".",
"log",
"(",
"err",
".",
"stack",
")",
";",
"if",
"(",
"proc",
".",
"shutdownHook",
")",
"{",
"proc",
".",
"shutdownHook",
"(",
"err",
",",
"gracefulShutdown",
")",
";",
"}",
"}",
"process",
".",
"on",
"(",
"'uncaughtException'",
",",
"terminate",
")",
";",
"process",
".",
"addListener",
"(",
"'SIGINT'",
",",
"gracefulShutdown",
")",
";",
"process",
".",
"addListener",
"(",
"'SIGHUP'",
",",
"function",
"(",
")",
"{",
"util",
".",
"log",
"(",
"'RECIEVED SIGHUP signal, reloading log files...'",
")",
";",
"reload",
"(",
"argv",
")",
";",
"}",
")",
";",
"}"
]
| Reopen logfiles on SIGHUP
Exit on uncaught exceptions | [
"Reopen",
"logfiles",
"on",
"SIGHUP",
"Exit",
"on",
"uncaught",
"exceptions"
]
| cae3b96a9cd6689a3e5cfedfefef3718c1e4839c | https://github.com/vnykmshr/proc-utils/blob/cae3b96a9cd6689a3e5cfedfefef3718c1e4839c/lib/proc.js#L56-L75 | train |
JohnnieFucker/dreamix-admin | lib/consoleService.js | enableCommand | function enableCommand(consoleService, moduleId, msg, cb) {
if (!moduleId) {
logger.error(`fail to enable admin module for ${moduleId}`);
cb('empty moduleId');
return;
}
const modules = consoleService.modules;
if (!modules[moduleId]) {
cb(null, protocol.PRO_FAIL);
return;
}
if (consoleService.master) {
consoleService.enable(moduleId);
consoleService.agent.notifyCommand('enable', moduleId, msg);
cb(null, protocol.PRO_OK);
} else {
consoleService.enable(moduleId);
cb(null, protocol.PRO_OK);
}
} | javascript | function enableCommand(consoleService, moduleId, msg, cb) {
if (!moduleId) {
logger.error(`fail to enable admin module for ${moduleId}`);
cb('empty moduleId');
return;
}
const modules = consoleService.modules;
if (!modules[moduleId]) {
cb(null, protocol.PRO_FAIL);
return;
}
if (consoleService.master) {
consoleService.enable(moduleId);
consoleService.agent.notifyCommand('enable', moduleId, msg);
cb(null, protocol.PRO_OK);
} else {
consoleService.enable(moduleId);
cb(null, protocol.PRO_OK);
}
} | [
"function",
"enableCommand",
"(",
"consoleService",
",",
"moduleId",
",",
"msg",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"moduleId",
")",
"{",
"logger",
".",
"error",
"(",
"`",
"${",
"moduleId",
"}",
"`",
")",
";",
"cb",
"(",
"'empty moduleId'",
")",
";",
"return",
";",
"}",
"const",
"modules",
"=",
"consoleService",
".",
"modules",
";",
"if",
"(",
"!",
"modules",
"[",
"moduleId",
"]",
")",
"{",
"cb",
"(",
"null",
",",
"protocol",
".",
"PRO_FAIL",
")",
";",
"return",
";",
"}",
"if",
"(",
"consoleService",
".",
"master",
")",
"{",
"consoleService",
".",
"enable",
"(",
"moduleId",
")",
";",
"consoleService",
".",
"agent",
".",
"notifyCommand",
"(",
"'enable'",
",",
"moduleId",
",",
"msg",
")",
";",
"cb",
"(",
"null",
",",
"protocol",
".",
"PRO_OK",
")",
";",
"}",
"else",
"{",
"consoleService",
".",
"enable",
"(",
"moduleId",
")",
";",
"cb",
"(",
"null",
",",
"protocol",
".",
"PRO_OK",
")",
";",
"}",
"}"
]
| enable module in current server | [
"enable",
"module",
"in",
"current",
"server"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/consoleService.js#L35-L56 | train |
JohnnieFucker/dreamix-admin | lib/consoleService.js | registerRecord | function registerRecord(service, moduleId, module) {
const record = {
moduleId: moduleId,
module: module,
enable: false
};
if (module.type && module.interval) {
if (!service.master && record.module.type === 'push' || service.master && record.module.type !== 'push') {// eslint-disable-line
// push for monitor or pull for master(default)
record.delay = module.delay || 0;
record.interval = module.interval || 1;
// normalize the arguments
if (record.delay < 0) {
record.delay = 0;
}
if (record.interval < 0) {
record.interval = 1;
}
record.interval = Math.ceil(record.interval);
record.delay *= MS_OF_SECOND;
record.interval *= MS_OF_SECOND;
record.schedule = true;
}
}
return record;
} | javascript | function registerRecord(service, moduleId, module) {
const record = {
moduleId: moduleId,
module: module,
enable: false
};
if (module.type && module.interval) {
if (!service.master && record.module.type === 'push' || service.master && record.module.type !== 'push') {// eslint-disable-line
// push for monitor or pull for master(default)
record.delay = module.delay || 0;
record.interval = module.interval || 1;
// normalize the arguments
if (record.delay < 0) {
record.delay = 0;
}
if (record.interval < 0) {
record.interval = 1;
}
record.interval = Math.ceil(record.interval);
record.delay *= MS_OF_SECOND;
record.interval *= MS_OF_SECOND;
record.schedule = true;
}
}
return record;
} | [
"function",
"registerRecord",
"(",
"service",
",",
"moduleId",
",",
"module",
")",
"{",
"const",
"record",
"=",
"{",
"moduleId",
":",
"moduleId",
",",
"module",
":",
"module",
",",
"enable",
":",
"false",
"}",
";",
"if",
"(",
"module",
".",
"type",
"&&",
"module",
".",
"interval",
")",
"{",
"if",
"(",
"!",
"service",
".",
"master",
"&&",
"record",
".",
"module",
".",
"type",
"===",
"'push'",
"||",
"service",
".",
"master",
"&&",
"record",
".",
"module",
".",
"type",
"!==",
"'push'",
")",
"{",
"record",
".",
"delay",
"=",
"module",
".",
"delay",
"||",
"0",
";",
"record",
".",
"interval",
"=",
"module",
".",
"interval",
"||",
"1",
";",
"if",
"(",
"record",
".",
"delay",
"<",
"0",
")",
"{",
"record",
".",
"delay",
"=",
"0",
";",
"}",
"if",
"(",
"record",
".",
"interval",
"<",
"0",
")",
"{",
"record",
".",
"interval",
"=",
"1",
";",
"}",
"record",
".",
"interval",
"=",
"Math",
".",
"ceil",
"(",
"record",
".",
"interval",
")",
";",
"record",
".",
"delay",
"*=",
"MS_OF_SECOND",
";",
"record",
".",
"interval",
"*=",
"MS_OF_SECOND",
";",
"record",
".",
"schedule",
"=",
"true",
";",
"}",
"}",
"return",
"record",
";",
"}"
]
| register a module service
@param {Object} service consoleService object
@param {String} moduleId adminConsole id/name
@param {Object} module module object
@api private | [
"register",
"a",
"module",
"service"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/consoleService.js#L93-L120 | train |
JohnnieFucker/dreamix-admin | lib/consoleService.js | addToSchedule | function addToSchedule(service, record) {
if (record && record.schedule) {
record.jobId = schedule.scheduleJob({
start: Date.now() + record.delay,
period: record.interval
},
doScheduleJob, {
service: service,
record: record
});
}
} | javascript | function addToSchedule(service, record) {
if (record && record.schedule) {
record.jobId = schedule.scheduleJob({
start: Date.now() + record.delay,
period: record.interval
},
doScheduleJob, {
service: service,
record: record
});
}
} | [
"function",
"addToSchedule",
"(",
"service",
",",
"record",
")",
"{",
"if",
"(",
"record",
"&&",
"record",
".",
"schedule",
")",
"{",
"record",
".",
"jobId",
"=",
"schedule",
".",
"scheduleJob",
"(",
"{",
"start",
":",
"Date",
".",
"now",
"(",
")",
"+",
"record",
".",
"delay",
",",
"period",
":",
"record",
".",
"interval",
"}",
",",
"doScheduleJob",
",",
"{",
"service",
":",
"service",
",",
"record",
":",
"record",
"}",
")",
";",
"}",
"}"
]
| schedule console module
@param {Object} service consoleService object
@param {Object} record module object
@api private | [
"schedule",
"console",
"module"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/consoleService.js#L153-L164 | train |
JohnnieFucker/dreamix-admin | lib/consoleService.js | exportEvent | function exportEvent(outer, inner, event) {
inner.on(event, (...args) => {
args.unshift(event);
outer.emit(...args);
});
} | javascript | function exportEvent(outer, inner, event) {
inner.on(event, (...args) => {
args.unshift(event);
outer.emit(...args);
});
} | [
"function",
"exportEvent",
"(",
"outer",
",",
"inner",
",",
"event",
")",
"{",
"inner",
".",
"on",
"(",
"event",
",",
"(",
"...",
"args",
")",
"=>",
"{",
"args",
".",
"unshift",
"(",
"event",
")",
";",
"outer",
".",
"emit",
"(",
"...",
"args",
")",
";",
"}",
")",
";",
"}"
]
| export closure function out
@param {Function} outer outer function
@param {Function} inner inner function
@param {object} event
@api private | [
"export",
"closure",
"function",
"out"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/consoleService.js#L174-L179 | train |
fladi/sails-generate-avahi | templates/hook.template.js | add_group | function add_group() {
server.EntryGroupNew(function(err, path) {
if (err) {
sails.log.error('DBus: Could not call org.freedesktop.Avahi.Server.EntryGroupNew');
return;
}
service.getInterface(
path,
avahi.DBUS_INTERFACE_ENTRY_GROUP.value,
function (
err,
newGroup
) {
group = newGroup;
add_service();
}
)
});
} | javascript | function add_group() {
server.EntryGroupNew(function(err, path) {
if (err) {
sails.log.error('DBus: Could not call org.freedesktop.Avahi.Server.EntryGroupNew');
return;
}
service.getInterface(
path,
avahi.DBUS_INTERFACE_ENTRY_GROUP.value,
function (
err,
newGroup
) {
group = newGroup;
add_service();
}
)
});
} | [
"function",
"add_group",
"(",
")",
"{",
"server",
".",
"EntryGroupNew",
"(",
"function",
"(",
"err",
",",
"path",
")",
"{",
"if",
"(",
"err",
")",
"{",
"sails",
".",
"log",
".",
"error",
"(",
"'DBus: Could not call org.freedesktop.Avahi.Server.EntryGroupNew'",
")",
";",
"return",
";",
"}",
"service",
".",
"getInterface",
"(",
"path",
",",
"avahi",
".",
"DBUS_INTERFACE_ENTRY_GROUP",
".",
"value",
",",
"function",
"(",
"err",
",",
"newGroup",
")",
"{",
"group",
"=",
"newGroup",
";",
"add_service",
"(",
")",
";",
"}",
")",
"}",
")",
";",
"}"
]
| Add a new EntryGroup for our service. | [
"Add",
"a",
"new",
"EntryGroup",
"for",
"our",
"service",
"."
]
| 09f66f30d9301ad7078a3b4e95f3b3c7f3b6d337 | https://github.com/fladi/sails-generate-avahi/blob/09f66f30d9301ad7078a3b4e95f3b3c7f3b6d337/templates/hook.template.js#L41-L59 | train |
fladi/sails-generate-avahi | templates/hook.template.js | add_service | function add_service() {
// Default configuration. Overrides can be defined in `config/avahi.js`.
sails.log.info('Publishing service ' + config.name + ' (' + config.type + ') on port '+ config.port);
group.AddService(
avahi.IF_UNSPEC.value,
avahi.PROTO_INET.value,
0,
config.name,
config.type,
config.domain,
config.host,
config.port,
'',
function(err) {
if (err) {
sails.log.error('DBus: Could not call org.freedesktop.Avahi.EntryGroup.AddService');
return;
}
group.Commit();
}
);
} | javascript | function add_service() {
// Default configuration. Overrides can be defined in `config/avahi.js`.
sails.log.info('Publishing service ' + config.name + ' (' + config.type + ') on port '+ config.port);
group.AddService(
avahi.IF_UNSPEC.value,
avahi.PROTO_INET.value,
0,
config.name,
config.type,
config.domain,
config.host,
config.port,
'',
function(err) {
if (err) {
sails.log.error('DBus: Could not call org.freedesktop.Avahi.EntryGroup.AddService');
return;
}
group.Commit();
}
);
} | [
"function",
"add_service",
"(",
")",
"{",
"sails",
".",
"log",
".",
"info",
"(",
"'Publishing service '",
"+",
"config",
".",
"name",
"+",
"' ('",
"+",
"config",
".",
"type",
"+",
"') on port '",
"+",
"config",
".",
"port",
")",
";",
"group",
".",
"AddService",
"(",
"avahi",
".",
"IF_UNSPEC",
".",
"value",
",",
"avahi",
".",
"PROTO_INET",
".",
"value",
",",
"0",
",",
"config",
".",
"name",
",",
"config",
".",
"type",
",",
"config",
".",
"domain",
",",
"config",
".",
"host",
",",
"config",
".",
"port",
",",
"''",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"sails",
".",
"log",
".",
"error",
"(",
"'DBus: Could not call org.freedesktop.Avahi.EntryGroup.AddService'",
")",
";",
"return",
";",
"}",
"group",
".",
"Commit",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Add our service definition. | [
"Add",
"our",
"service",
"definition",
"."
]
| 09f66f30d9301ad7078a3b4e95f3b3c7f3b6d337 | https://github.com/fladi/sails-generate-avahi/blob/09f66f30d9301ad7078a3b4e95f3b3c7f3b6d337/templates/hook.template.js#L62-L84 | train |
vanjacosic/opbeat-js | src/opbeat.js | triggerEvent | function triggerEvent(eventType, options) {
var event, key;
options = options || {};
eventType = 'opbeat' + eventType.substr(0,1).toUpperCase() + eventType.substr(1);
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventType, true, true);
} else {
event = document.createEventObject();
event.eventType = eventType;
}
for (key in options) if (hasKey(options, key)) {
event[key] = options[key];
}
if (document.createEvent) {
// IE9 if standards
document.dispatchEvent(event);
} else {
// IE8 regardless of Quirks or Standards
// IE9 if quirks
try {
document.fireEvent('on' + event.eventType.toLowerCase(), event);
} catch(e) {}
}
} | javascript | function triggerEvent(eventType, options) {
var event, key;
options = options || {};
eventType = 'opbeat' + eventType.substr(0,1).toUpperCase() + eventType.substr(1);
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventType, true, true);
} else {
event = document.createEventObject();
event.eventType = eventType;
}
for (key in options) if (hasKey(options, key)) {
event[key] = options[key];
}
if (document.createEvent) {
// IE9 if standards
document.dispatchEvent(event);
} else {
// IE8 regardless of Quirks or Standards
// IE9 if quirks
try {
document.fireEvent('on' + event.eventType.toLowerCase(), event);
} catch(e) {}
}
} | [
"function",
"triggerEvent",
"(",
"eventType",
",",
"options",
")",
"{",
"var",
"event",
",",
"key",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"eventType",
"=",
"'opbeat'",
"+",
"eventType",
".",
"substr",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"eventType",
".",
"substr",
"(",
"1",
")",
";",
"if",
"(",
"document",
".",
"createEvent",
")",
"{",
"event",
"=",
"document",
".",
"createEvent",
"(",
"'HTMLEvents'",
")",
";",
"event",
".",
"initEvent",
"(",
"eventType",
",",
"true",
",",
"true",
")",
";",
"}",
"else",
"{",
"event",
"=",
"document",
".",
"createEventObject",
"(",
")",
";",
"event",
".",
"eventType",
"=",
"eventType",
";",
"}",
"for",
"(",
"key",
"in",
"options",
")",
"if",
"(",
"hasKey",
"(",
"options",
",",
"key",
")",
")",
"{",
"event",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
";",
"}",
"if",
"(",
"document",
".",
"createEvent",
")",
"{",
"document",
".",
"dispatchEvent",
"(",
"event",
")",
";",
"}",
"else",
"{",
"try",
"{",
"document",
".",
"fireEvent",
"(",
"'on'",
"+",
"event",
".",
"eventType",
".",
"toLowerCase",
"(",
")",
",",
"event",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"}"
]
| To be deprecated | [
"To",
"be",
"deprecated"
]
| 136065ff2f6cda0097c783e43ca3773da6dff3ed | https://github.com/vanjacosic/opbeat-js/blob/136065ff2f6cda0097c783e43ca3773da6dff3ed/src/opbeat.js#L308-L337 | train |
PrinceNebulon/github-api-promise | src/request-helpers.js | function(url, method = 'get', body = undefined) {
var deferred = Q.defer();
this.extendedRequest(url, method, body)
.then((res) => { deferred.resolve(res.body); })
.catch((err) => { deferred.reject(err); });
return deferred.promise;
} | javascript | function(url, method = 'get', body = undefined) {
var deferred = Q.defer();
this.extendedRequest(url, method, body)
.then((res) => { deferred.resolve(res.body); })
.catch((err) => { deferred.reject(err); });
return deferred.promise;
} | [
"function",
"(",
"url",
",",
"method",
"=",
"'get'",
",",
"body",
"=",
"undefined",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"this",
".",
"extendedRequest",
"(",
"url",
",",
"method",
",",
"body",
")",
".",
"then",
"(",
"(",
"res",
")",
"=>",
"{",
"deferred",
".",
"resolve",
"(",
"res",
".",
"body",
")",
";",
"}",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
]
| Returns only the response body | [
"Returns",
"only",
"the",
"response",
"body"
]
| 990cb2cce19b53f54d9243002fde47428f24e7cc | https://github.com/PrinceNebulon/github-api-promise/blob/990cb2cce19b53f54d9243002fde47428f24e7cc/src/request-helpers.js#L37-L45 | train |
|
mjhasbach/bower-package-url | lib/bowerPackageURL.js | bowerPackageURL | function bowerPackageURL(packageName, cb) {
if (typeof cb !== 'function') {
throw new TypeError('cb must be a function');
}
if (typeof packageName !== 'string') {
cb(new TypeError('packageName must be a string'));
return;
}
http.get('https://bower.herokuapp.com/packages/' + packageName)
.end(function(err, res) {
if (err && err.status === 404) {
err = new Error('Package ' + packageName + ' not found on Bower');
}
cb(err, res.body.url);
});
} | javascript | function bowerPackageURL(packageName, cb) {
if (typeof cb !== 'function') {
throw new TypeError('cb must be a function');
}
if (typeof packageName !== 'string') {
cb(new TypeError('packageName must be a string'));
return;
}
http.get('https://bower.herokuapp.com/packages/' + packageName)
.end(function(err, res) {
if (err && err.status === 404) {
err = new Error('Package ' + packageName + ' not found on Bower');
}
cb(err, res.body.url);
});
} | [
"function",
"bowerPackageURL",
"(",
"packageName",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'cb must be a function'",
")",
";",
"}",
"if",
"(",
"typeof",
"packageName",
"!==",
"'string'",
")",
"{",
"cb",
"(",
"new",
"TypeError",
"(",
"'packageName must be a string'",
")",
")",
";",
"return",
";",
"}",
"http",
".",
"get",
"(",
"'https://bower.herokuapp.com/packages/'",
"+",
"packageName",
")",
".",
"end",
"(",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"status",
"===",
"404",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"'Package '",
"+",
"packageName",
"+",
"' not found on Bower'",
")",
";",
"}",
"cb",
"(",
"err",
",",
"res",
".",
"body",
".",
"url",
")",
";",
"}",
")",
";",
"}"
]
| The bowerPackageURL callback
@callback bowerPackageURLCallback
@param {Object} err - An error object if an error occurred
@param {string} url - The repository URL associated with the provided bower package name
Get the repository URL associated with a bower package name
@alias module:bowerPackageURL
@param {string} packageName - A bower package name
@param {bowerPackageURLCallback} cb - A callback to be executed after the repository URL is collected
@example
bowerPackageURL('lodash', function(err, url) {
if (err) { console.error(err); }
console.log(url);
}); | [
"The",
"bowerPackageURL",
"callback"
]
| 5ed279cc7e685789ec73667ff6787ae85e368acc | https://github.com/mjhasbach/bower-package-url/blob/5ed279cc7e685789ec73667ff6787ae85e368acc/lib/bowerPackageURL.js#L26-L43 | train |
crokita/functionite | examples/example3.js | addPoints | function addPoints (x1, y1, x2, y2, cb) {
var xFinal = x1 + x2;
var yFinal = y1 + y2;
cb(xFinal, yFinal);
} | javascript | function addPoints (x1, y1, x2, y2, cb) {
var xFinal = x1 + x2;
var yFinal = y1 + y2;
cb(xFinal, yFinal);
} | [
"function",
"addPoints",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"cb",
")",
"{",
"var",
"xFinal",
"=",
"x1",
"+",
"x2",
";",
"var",
"yFinal",
"=",
"y1",
"+",
"y2",
";",
"cb",
"(",
"xFinal",
",",
"yFinal",
")",
";",
"}"
]
| this function takes the sum of two points, and returns the sum of x's and the sum of y's in a callback | [
"this",
"function",
"takes",
"the",
"sum",
"of",
"two",
"points",
"and",
"returns",
"the",
"sum",
"of",
"x",
"s",
"and",
"the",
"sum",
"of",
"y",
"s",
"in",
"a",
"callback"
]
| e5d52b3bded8eac6b42413208e1dc61e0741ae34 | https://github.com/crokita/functionite/blob/e5d52b3bded8eac6b42413208e1dc61e0741ae34/examples/example3.js#L16-L20 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.