id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
50,600 | alexpods/ClazzJS | src/components/meta/Property/Type.js | function(value, params, property, fields, object) {
var that = this;
if (!_.isSimpleObject(value)) {
throw new Error('Value of property "' +
[property].concat(fields).join('.') +'" must be a simple object!');
}
if ('keys' in params) {
_.each(params.keys, function(key) {
if (-1 === params.keys.indexOf(key)) {
throw new Error('Unsupported hash key "' + key +
'" for property "' + [property].concat(fields).join('.') + '"!');
}
});
}
if ('element' in params) {
_.each(value, function(key) {
value[key] = that.apply(value[key], params.element, property, fields.concat(key), object);
}) ;
}
return value;
} | javascript | function(value, params, property, fields, object) {
var that = this;
if (!_.isSimpleObject(value)) {
throw new Error('Value of property "' +
[property].concat(fields).join('.') +'" must be a simple object!');
}
if ('keys' in params) {
_.each(params.keys, function(key) {
if (-1 === params.keys.indexOf(key)) {
throw new Error('Unsupported hash key "' + key +
'" for property "' + [property].concat(fields).join('.') + '"!');
}
});
}
if ('element' in params) {
_.each(value, function(key) {
value[key] = that.apply(value[key], params.element, property, fields.concat(key), object);
}) ;
}
return value;
} | [
"function",
"(",
"value",
",",
"params",
",",
"property",
",",
"fields",
",",
"object",
")",
"{",
"var",
"that",
"=",
"this",
";",
"if",
"(",
"!",
"_",
".",
"isSimpleObject",
"(",
"value",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Value of property \"'",
"+",
"[",
"property",
"]",
".",
"concat",
"(",
"fields",
")",
".",
"join",
"(",
"'.'",
")",
"+",
"'\" must be a simple object!'",
")",
";",
"}",
"if",
"(",
"'keys'",
"in",
"params",
")",
"{",
"_",
".",
"each",
"(",
"params",
".",
"keys",
",",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"-",
"1",
"===",
"params",
".",
"keys",
".",
"indexOf",
"(",
"key",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unsupported hash key \"'",
"+",
"key",
"+",
"'\" for property \"'",
"+",
"[",
"property",
"]",
".",
"concat",
"(",
"fields",
")",
".",
"join",
"(",
"'.'",
")",
"+",
"'\"!'",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"'element'",
"in",
"params",
")",
"{",
"_",
".",
"each",
"(",
"value",
",",
"function",
"(",
"key",
")",
"{",
"value",
"[",
"key",
"]",
"=",
"that",
".",
"apply",
"(",
"value",
"[",
"key",
"]",
",",
"params",
".",
"element",
",",
"property",
",",
"fields",
".",
"concat",
"(",
"key",
")",
",",
"object",
")",
";",
"}",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Hash property type
Check 'simple object' type of value, applies 'keys' and 'element' parameters
@param {*} value Property value
@param {object} params Property parameters
@param {string} property Property name
@param {array} fields Property fields
@param {object} object Object to which property belongs
@throws {Error} if property value does not a simple object
@throws {Error} if hash has unsupported keys
@returns {object} Processed property value
@this {metaProcessor} | [
"Hash",
"property",
"type",
"Check",
"simple",
"object",
"type",
"of",
"value",
"applies",
"keys",
"and",
"element",
"parameters"
] | 2f94496019669813c8246d48fcceb12a3e68a870 | https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/meta/Property/Type.js#L307-L330 |
|
50,601 | alexpods/ClazzJS | src/components/meta/Property/Type.js | function(value, params, property, fields, object) {
if (!_.isObject(value)) {
throw new Error('Value of property "' + property + '" must be an object!');
}
if ('instanceOf' in params) {
var instanceOf = params.instanceOf;
var clazzClazz = object.__isClazz ? object.__clazz : object.__clazz.__clazz;
if (_.isString(instanceOf)) {
instanceOf = clazzClazz.getNamespace().adjustPath(instanceOf);
if (!value.__clazz) {
instanceOf = clazzClazz(instanceOf);
}
}
if (value.__clazz ? !value.__clazz.__isSubclazzOf(instanceOf) : !(value instanceof instanceOf)) {
var className = instanceOf.__isClazz
? instanceOf.__name
: (_.isString(instanceOf) ? instanceOf : 'another');
throw new Error('Value of property "' + property +
'" must be instance of ' + className + ' clazz!');
}
}
return value;
} | javascript | function(value, params, property, fields, object) {
if (!_.isObject(value)) {
throw new Error('Value of property "' + property + '" must be an object!');
}
if ('instanceOf' in params) {
var instanceOf = params.instanceOf;
var clazzClazz = object.__isClazz ? object.__clazz : object.__clazz.__clazz;
if (_.isString(instanceOf)) {
instanceOf = clazzClazz.getNamespace().adjustPath(instanceOf);
if (!value.__clazz) {
instanceOf = clazzClazz(instanceOf);
}
}
if (value.__clazz ? !value.__clazz.__isSubclazzOf(instanceOf) : !(value instanceof instanceOf)) {
var className = instanceOf.__isClazz
? instanceOf.__name
: (_.isString(instanceOf) ? instanceOf : 'another');
throw new Error('Value of property "' + property +
'" must be instance of ' + className + ' clazz!');
}
}
return value;
} | [
"function",
"(",
"value",
",",
"params",
",",
"property",
",",
"fields",
",",
"object",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"value",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Value of property \"'",
"+",
"property",
"+",
"'\" must be an object!'",
")",
";",
"}",
"if",
"(",
"'instanceOf'",
"in",
"params",
")",
"{",
"var",
"instanceOf",
"=",
"params",
".",
"instanceOf",
";",
"var",
"clazzClazz",
"=",
"object",
".",
"__isClazz",
"?",
"object",
".",
"__clazz",
":",
"object",
".",
"__clazz",
".",
"__clazz",
";",
"if",
"(",
"_",
".",
"isString",
"(",
"instanceOf",
")",
")",
"{",
"instanceOf",
"=",
"clazzClazz",
".",
"getNamespace",
"(",
")",
".",
"adjustPath",
"(",
"instanceOf",
")",
";",
"if",
"(",
"!",
"value",
".",
"__clazz",
")",
"{",
"instanceOf",
"=",
"clazzClazz",
"(",
"instanceOf",
")",
";",
"}",
"}",
"if",
"(",
"value",
".",
"__clazz",
"?",
"!",
"value",
".",
"__clazz",
".",
"__isSubclazzOf",
"(",
"instanceOf",
")",
":",
"!",
"(",
"value",
"instanceof",
"instanceOf",
")",
")",
"{",
"var",
"className",
"=",
"instanceOf",
".",
"__isClazz",
"?",
"instanceOf",
".",
"__name",
":",
"(",
"_",
".",
"isString",
"(",
"instanceOf",
")",
"?",
"instanceOf",
":",
"'another'",
")",
";",
"throw",
"new",
"Error",
"(",
"'Value of property \"'",
"+",
"property",
"+",
"'\" must be instance of '",
"+",
"className",
"+",
"' clazz!'",
")",
";",
"}",
"}",
"return",
"value",
";",
"}"
] | Object property type
Check 'object' type of value, applies 'instanceOf' parameters
@param {*} value Property value
@param {object} params Property parameters
@param {string} property Property name
@param {array} fields Property fields
@param {object} object Object to which property belongs
@throws {Error} if property value does not an object
@throws {Error} if hash has unsupported keys
@returns {object} Processed property value
@this {metaProcessor} | [
"Object",
"property",
"type",
"Check",
"object",
"type",
"of",
"value",
"applies",
"instanceOf",
"parameters"
] | 2f94496019669813c8246d48fcceb12a3e68a870 | https://github.com/alexpods/ClazzJS/blob/2f94496019669813c8246d48fcceb12a3e68a870/src/components/meta/Property/Type.js#L349-L381 |
|
50,602 | Becklyn/becklyn-gulp | tasks/publish.js | removeExisting | function removeExisting ()
{
if (fs.existsSync("web/assets"))
{
var stat = fs.lstatSync("web/assets");
if (stat.isFile() || stat.isSymbolicLink())
{
fs.unlinkSync("web/assets");
}
else
{
wrench.rmdirSyncRecursive("web/assets");
}
}
} | javascript | function removeExisting ()
{
if (fs.existsSync("web/assets"))
{
var stat = fs.lstatSync("web/assets");
if (stat.isFile() || stat.isSymbolicLink())
{
fs.unlinkSync("web/assets");
}
else
{
wrench.rmdirSyncRecursive("web/assets");
}
}
} | [
"function",
"removeExisting",
"(",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"\"web/assets\"",
")",
")",
"{",
"var",
"stat",
"=",
"fs",
".",
"lstatSync",
"(",
"\"web/assets\"",
")",
";",
"if",
"(",
"stat",
".",
"isFile",
"(",
")",
"||",
"stat",
".",
"isSymbolicLink",
"(",
")",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"\"web/assets\"",
")",
";",
"}",
"else",
"{",
"wrench",
".",
"rmdirSyncRecursive",
"(",
"\"web/assets\"",
")",
";",
"}",
"}",
"}"
] | Removes the existing directory | [
"Removes",
"the",
"existing",
"directory"
] | 1c633378d561f07101f9db19ccd153617b8e0252 | https://github.com/Becklyn/becklyn-gulp/blob/1c633378d561f07101f9db19ccd153617b8e0252/tasks/publish.js#L14-L29 |
50,603 | wordijp/flexi-require | lib/internal/bower-utils.js | componentsHome | function componentsHome(workdir) {
var bowerrc = path.join(workdir, '.bowerrc'),
defaultHome = path.join(workdir, 'bower_components');
return (fs.existsSync(bowerrc) && require(bowerrc).directory) || defaultHome;
} | javascript | function componentsHome(workdir) {
var bowerrc = path.join(workdir, '.bowerrc'),
defaultHome = path.join(workdir, 'bower_components');
return (fs.existsSync(bowerrc) && require(bowerrc).directory) || defaultHome;
} | [
"function",
"componentsHome",
"(",
"workdir",
")",
"{",
"var",
"bowerrc",
"=",
"path",
".",
"join",
"(",
"workdir",
",",
"'.bowerrc'",
")",
",",
"defaultHome",
"=",
"path",
".",
"join",
"(",
"workdir",
",",
"'bower_components'",
")",
";",
"return",
"(",
"fs",
".",
"existsSync",
"(",
"bowerrc",
")",
"&&",
"require",
"(",
"bowerrc",
")",
".",
"directory",
")",
"||",
"defaultHome",
";",
"}"
] | determine bower components home dir, maybe need to get dir name from '.bowerrc' | [
"determine",
"bower",
"components",
"home",
"dir",
"maybe",
"need",
"to",
"get",
"dir",
"name",
"from",
".",
"bowerrc"
] | f62a7141fd97f4a5b47c9808a5c4a3349aeccb43 | https://github.com/wordijp/flexi-require/blob/f62a7141fd97f4a5b47c9808a5c4a3349aeccb43/lib/internal/bower-utils.js#L12-L16 |
50,604 | wordijp/flexi-require | lib/internal/bower-utils.js | componentName | function componentName(rawname) {
var name = rawname.split(':')[0],
index = name.replace('\\', '/').indexOf('/');
return (index > 0) ? name.substring(0, index) : name;
} | javascript | function componentName(rawname) {
var name = rawname.split(':')[0],
index = name.replace('\\', '/').indexOf('/');
return (index > 0) ? name.substring(0, index) : name;
} | [
"function",
"componentName",
"(",
"rawname",
")",
"{",
"var",
"name",
"=",
"rawname",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
",",
"index",
"=",
"name",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
".",
"indexOf",
"(",
"'/'",
")",
";",
"return",
"(",
"index",
">",
"0",
")",
"?",
"name",
".",
"substring",
"(",
"0",
",",
"index",
")",
":",
"name",
";",
"}"
] | extract component name from inputting rawname | [
"extract",
"component",
"name",
"from",
"inputting",
"rawname"
] | f62a7141fd97f4a5b47c9808a5c4a3349aeccb43 | https://github.com/wordijp/flexi-require/blob/f62a7141fd97f4a5b47c9808a5c4a3349aeccb43/lib/internal/bower-utils.js#L21-L25 |
50,605 | wordijp/flexi-require | lib/internal/bower-utils.js | componentNames | function componentNames(workdir) {
workdir = workdir || process.cwd();
try {
var bowerJson = require(path.join(workdir, 'bower.json'));
return _(Object.keys(bowerJson.dependencies || {}))
.union(Object.keys(bowerJson.devDependencies || {}))
.value();
} catch (ex) {
// not found bower
//console.warn(ex.message);
return [];
}
} | javascript | function componentNames(workdir) {
workdir = workdir || process.cwd();
try {
var bowerJson = require(path.join(workdir, 'bower.json'));
return _(Object.keys(bowerJson.dependencies || {}))
.union(Object.keys(bowerJson.devDependencies || {}))
.value();
} catch (ex) {
// not found bower
//console.warn(ex.message);
return [];
}
} | [
"function",
"componentNames",
"(",
"workdir",
")",
"{",
"workdir",
"=",
"workdir",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"try",
"{",
"var",
"bowerJson",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"workdir",
",",
"'bower.json'",
")",
")",
";",
"return",
"_",
"(",
"Object",
".",
"keys",
"(",
"bowerJson",
".",
"dependencies",
"||",
"{",
"}",
")",
")",
".",
"union",
"(",
"Object",
".",
"keys",
"(",
"bowerJson",
".",
"devDependencies",
"||",
"{",
"}",
")",
")",
".",
"value",
"(",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"// not found bower",
"//console.warn(ex.message);",
"return",
"[",
"]",
";",
"}",
"}"
] | get bower components names | [
"get",
"bower",
"components",
"names"
] | f62a7141fd97f4a5b47c9808a5c4a3349aeccb43 | https://github.com/wordijp/flexi-require/blob/f62a7141fd97f4a5b47c9808a5c4a3349aeccb43/lib/internal/bower-utils.js#L30-L42 |
50,606 | wordijp/flexi-require | lib/internal/bower-utils.js | resolve | function resolve(name, workdir) {
workdir = workdir || process.cwd();
var compName = componentName(name),
subname = name.substring(compName.length + 1),
basedir = path.join(componentsHome(workdir), compName),
bowerJson = require(path.join(basedir, 'bower.json'));
var mainfile = Array.isArray(bowerJson.main)
? bowerJson.main.filter(function(file) { return /\.js$/.test(file); })[0]
: bowerJson.main;
if (subname && subname.length > 0) {
var subpath = mainfile && path.join(basedir, mainfile, '..', subname);
if (subpath && (fs.existsSync(subpath) || fs.existsSync(subpath + '.js'))) {
return path.join(basedir, mainfile, '..', subname);
} else {
return path.join(basedir, subname);
}
} else {
if (mainfile) {
return path.join(basedir, mainfile);
} else {
if (fs.existsSync(path.join(basedir, "index.js"))) {
return path.join(basedir, "index.js");
} else {
return path.join(basedir, compName);
}
}
}
} | javascript | function resolve(name, workdir) {
workdir = workdir || process.cwd();
var compName = componentName(name),
subname = name.substring(compName.length + 1),
basedir = path.join(componentsHome(workdir), compName),
bowerJson = require(path.join(basedir, 'bower.json'));
var mainfile = Array.isArray(bowerJson.main)
? bowerJson.main.filter(function(file) { return /\.js$/.test(file); })[0]
: bowerJson.main;
if (subname && subname.length > 0) {
var subpath = mainfile && path.join(basedir, mainfile, '..', subname);
if (subpath && (fs.existsSync(subpath) || fs.existsSync(subpath + '.js'))) {
return path.join(basedir, mainfile, '..', subname);
} else {
return path.join(basedir, subname);
}
} else {
if (mainfile) {
return path.join(basedir, mainfile);
} else {
if (fs.existsSync(path.join(basedir, "index.js"))) {
return path.join(basedir, "index.js");
} else {
return path.join(basedir, compName);
}
}
}
} | [
"function",
"resolve",
"(",
"name",
",",
"workdir",
")",
"{",
"workdir",
"=",
"workdir",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"var",
"compName",
"=",
"componentName",
"(",
"name",
")",
",",
"subname",
"=",
"name",
".",
"substring",
"(",
"compName",
".",
"length",
"+",
"1",
")",
",",
"basedir",
"=",
"path",
".",
"join",
"(",
"componentsHome",
"(",
"workdir",
")",
",",
"compName",
")",
",",
"bowerJson",
"=",
"require",
"(",
"path",
".",
"join",
"(",
"basedir",
",",
"'bower.json'",
")",
")",
";",
"var",
"mainfile",
"=",
"Array",
".",
"isArray",
"(",
"bowerJson",
".",
"main",
")",
"?",
"bowerJson",
".",
"main",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"/",
"\\.js$",
"/",
".",
"test",
"(",
"file",
")",
";",
"}",
")",
"[",
"0",
"]",
":",
"bowerJson",
".",
"main",
";",
"if",
"(",
"subname",
"&&",
"subname",
".",
"length",
">",
"0",
")",
"{",
"var",
"subpath",
"=",
"mainfile",
"&&",
"path",
".",
"join",
"(",
"basedir",
",",
"mainfile",
",",
"'..'",
",",
"subname",
")",
";",
"if",
"(",
"subpath",
"&&",
"(",
"fs",
".",
"existsSync",
"(",
"subpath",
")",
"||",
"fs",
".",
"existsSync",
"(",
"subpath",
"+",
"'.js'",
")",
")",
")",
"{",
"return",
"path",
".",
"join",
"(",
"basedir",
",",
"mainfile",
",",
"'..'",
",",
"subname",
")",
";",
"}",
"else",
"{",
"return",
"path",
".",
"join",
"(",
"basedir",
",",
"subname",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"mainfile",
")",
"{",
"return",
"path",
".",
"join",
"(",
"basedir",
",",
"mainfile",
")",
";",
"}",
"else",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"basedir",
",",
"\"index.js\"",
")",
")",
")",
"{",
"return",
"path",
".",
"join",
"(",
"basedir",
",",
"\"index.js\"",
")",
";",
"}",
"else",
"{",
"return",
"path",
".",
"join",
"(",
"basedir",
",",
"compName",
")",
";",
"}",
"}",
"}",
"}"
] | resolve and return entry file's full path for specified component | [
"resolve",
"and",
"return",
"entry",
"file",
"s",
"full",
"path",
"for",
"specified",
"component"
] | f62a7141fd97f4a5b47c9808a5c4a3349aeccb43 | https://github.com/wordijp/flexi-require/blob/f62a7141fd97f4a5b47c9808a5c4a3349aeccb43/lib/internal/bower-utils.js#L48-L77 |
50,607 | wunderbyte/grunt-spiritual-dox | Gruntfile.js | uglify | function uglify(js) {
return ugli.minify(js, {
fromString: true,
mangle: false,
compress: {
warnings: false
}
}).code;
} | javascript | function uglify(js) {
return ugli.minify(js, {
fromString: true,
mangle: false,
compress: {
warnings: false
}
}).code;
} | [
"function",
"uglify",
"(",
"js",
")",
"{",
"return",
"ugli",
".",
"minify",
"(",
"js",
",",
"{",
"fromString",
":",
"true",
",",
"mangle",
":",
"false",
",",
"compress",
":",
"{",
"warnings",
":",
"false",
"}",
"}",
")",
".",
"code",
";",
"}"
] | Compute compressed source for file.
@param {String} filepath The file path
@returns {String} | [
"Compute",
"compressed",
"source",
"for",
"file",
"."
] | 5afcfe31ddbf7d654166aa15b938553b61de5811 | https://github.com/wunderbyte/grunt-spiritual-dox/blob/5afcfe31ddbf7d654166aa15b938553b61de5811/Gruntfile.js#L106-L114 |
50,608 | JohnnieFucker/dreamix-rpc | lib/rpc-client/failureProcess.js | failsafe | function failsafe(code, tracer, serverId, msg, opts, cb) { // eslint-disable-line
const self = this;
const retryTimes = opts.retryTimes || constants.DEFAULT_PARAM.FAILSAFE_RETRIES;
const retryConnectTime = opts.retryConnectTime || constants.DEFAULT_PARAM.FAILSAFE_CONNECT_TIME;
if (!tracer.retryTimes) {
tracer.retryTimes = 1;
} else {
tracer.retryTimes += 1;
}
switch (code) {
case constants.RPC_ERROR.SERVER_NOT_STARTED:
case constants.RPC_ERROR.NO_TRAGET_SERVER:
utils.invokeCallback(cb, new Error('rpc client is not started or cannot find remote server.'));
break;
case constants.RPC_ERROR.FAIL_CONNECT_SERVER:
if (tracer.retryTimes <= retryTimes) {
setTimeout(() => {
self.connect(tracer, serverId, cb);
}, retryConnectTime * tracer.retryTimes);
} else {
utils.invokeCallback(cb, new Error(`rpc client failed to connect to remote server: ${serverId}`));
}
break;
case constants.RPC_ERROR.FAIL_FIND_MAILBOX:
case constants.RPC_ERROR.FAIL_SEND_MESSAGE:
if (tracer.retryTimes <= retryTimes) {
setTimeout(() => {
self.dispatch.call(self, tracer, serverId, msg, opts, cb);
}, retryConnectTime * tracer.retryTimes);
} else {
utils.invokeCallback(cb, new Error(`rpc client failed to send message to remote server: ${serverId}`));
}
break;
case constants.RPC_ERROR.FILTER_ERROR:
utils.invokeCallback(cb, new Error('rpc client filter encounters error.'));
break;
default:
utils.invokeCallback(cb, new Error('rpc client unknown error.'));
}
} | javascript | function failsafe(code, tracer, serverId, msg, opts, cb) { // eslint-disable-line
const self = this;
const retryTimes = opts.retryTimes || constants.DEFAULT_PARAM.FAILSAFE_RETRIES;
const retryConnectTime = opts.retryConnectTime || constants.DEFAULT_PARAM.FAILSAFE_CONNECT_TIME;
if (!tracer.retryTimes) {
tracer.retryTimes = 1;
} else {
tracer.retryTimes += 1;
}
switch (code) {
case constants.RPC_ERROR.SERVER_NOT_STARTED:
case constants.RPC_ERROR.NO_TRAGET_SERVER:
utils.invokeCallback(cb, new Error('rpc client is not started or cannot find remote server.'));
break;
case constants.RPC_ERROR.FAIL_CONNECT_SERVER:
if (tracer.retryTimes <= retryTimes) {
setTimeout(() => {
self.connect(tracer, serverId, cb);
}, retryConnectTime * tracer.retryTimes);
} else {
utils.invokeCallback(cb, new Error(`rpc client failed to connect to remote server: ${serverId}`));
}
break;
case constants.RPC_ERROR.FAIL_FIND_MAILBOX:
case constants.RPC_ERROR.FAIL_SEND_MESSAGE:
if (tracer.retryTimes <= retryTimes) {
setTimeout(() => {
self.dispatch.call(self, tracer, serverId, msg, opts, cb);
}, retryConnectTime * tracer.retryTimes);
} else {
utils.invokeCallback(cb, new Error(`rpc client failed to send message to remote server: ${serverId}`));
}
break;
case constants.RPC_ERROR.FILTER_ERROR:
utils.invokeCallback(cb, new Error('rpc client filter encounters error.'));
break;
default:
utils.invokeCallback(cb, new Error('rpc client unknown error.'));
}
} | [
"function",
"failsafe",
"(",
"code",
",",
"tracer",
",",
"serverId",
",",
"msg",
",",
"opts",
",",
"cb",
")",
"{",
"// eslint-disable-line",
"const",
"self",
"=",
"this",
";",
"const",
"retryTimes",
"=",
"opts",
".",
"retryTimes",
"||",
"constants",
".",
"DEFAULT_PARAM",
".",
"FAILSAFE_RETRIES",
";",
"const",
"retryConnectTime",
"=",
"opts",
".",
"retryConnectTime",
"||",
"constants",
".",
"DEFAULT_PARAM",
".",
"FAILSAFE_CONNECT_TIME",
";",
"if",
"(",
"!",
"tracer",
".",
"retryTimes",
")",
"{",
"tracer",
".",
"retryTimes",
"=",
"1",
";",
"}",
"else",
"{",
"tracer",
".",
"retryTimes",
"+=",
"1",
";",
"}",
"switch",
"(",
"code",
")",
"{",
"case",
"constants",
".",
"RPC_ERROR",
".",
"SERVER_NOT_STARTED",
":",
"case",
"constants",
".",
"RPC_ERROR",
".",
"NO_TRAGET_SERVER",
":",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"new",
"Error",
"(",
"'rpc client is not started or cannot find remote server.'",
")",
")",
";",
"break",
";",
"case",
"constants",
".",
"RPC_ERROR",
".",
"FAIL_CONNECT_SERVER",
":",
"if",
"(",
"tracer",
".",
"retryTimes",
"<=",
"retryTimes",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"self",
".",
"connect",
"(",
"tracer",
",",
"serverId",
",",
"cb",
")",
";",
"}",
",",
"retryConnectTime",
"*",
"tracer",
".",
"retryTimes",
")",
";",
"}",
"else",
"{",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"new",
"Error",
"(",
"`",
"${",
"serverId",
"}",
"`",
")",
")",
";",
"}",
"break",
";",
"case",
"constants",
".",
"RPC_ERROR",
".",
"FAIL_FIND_MAILBOX",
":",
"case",
"constants",
".",
"RPC_ERROR",
".",
"FAIL_SEND_MESSAGE",
":",
"if",
"(",
"tracer",
".",
"retryTimes",
"<=",
"retryTimes",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"self",
".",
"dispatch",
".",
"call",
"(",
"self",
",",
"tracer",
",",
"serverId",
",",
"msg",
",",
"opts",
",",
"cb",
")",
";",
"}",
",",
"retryConnectTime",
"*",
"tracer",
".",
"retryTimes",
")",
";",
"}",
"else",
"{",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"new",
"Error",
"(",
"`",
"${",
"serverId",
"}",
"`",
")",
")",
";",
"}",
"break",
";",
"case",
"constants",
".",
"RPC_ERROR",
".",
"FILTER_ERROR",
":",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"new",
"Error",
"(",
"'rpc client filter encounters error.'",
")",
")",
";",
"break",
";",
"default",
":",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"new",
"Error",
"(",
"'rpc client unknown error.'",
")",
")",
";",
"}",
"}"
] | Failsafe rpc failure process.
@param code {Number} error code number.
@param tracer {Object} current rpc tracer.
@param serverId {String} rpc remote target server id.
@param msg {Object} rpc message.
@param opts {Object} rpc client options.
@param cb {Function} user rpc callback.
@api private | [
"Failsafe",
"rpc",
"failure",
"process",
"."
] | eb29e247214148c025456b2bb0542e1094fd2edb | https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/failureProcess.js#L54-L94 |
50,609 | tolokoban/ToloFrameWork | lib/boilerplate.preprocessor.js | process | function process( ctx, obj ) {
try {
if ( Array.isArray( obj ) ) return processArray( ctx, obj );
switch ( typeof obj ) {
case "string":
return processString( ctx, obj );
case "object":
return processObject( ctx, obj );
default:
return obj;
}
} catch ( ex ) {
fatal( ctx, ex );
}
} | javascript | function process( ctx, obj ) {
try {
if ( Array.isArray( obj ) ) return processArray( ctx, obj );
switch ( typeof obj ) {
case "string":
return processString( ctx, obj );
case "object":
return processObject( ctx, obj );
default:
return obj;
}
} catch ( ex ) {
fatal( ctx, ex );
}
} | [
"function",
"process",
"(",
"ctx",
",",
"obj",
")",
"{",
"try",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"obj",
")",
")",
"return",
"processArray",
"(",
"ctx",
",",
"obj",
")",
";",
"switch",
"(",
"typeof",
"obj",
")",
"{",
"case",
"\"string\"",
":",
"return",
"processString",
"(",
"ctx",
",",
"obj",
")",
";",
"case",
"\"object\"",
":",
"return",
"processObject",
"(",
"ctx",
",",
"obj",
")",
";",
"default",
":",
"return",
"obj",
";",
"}",
"}",
"catch",
"(",
"ex",
")",
"{",
"fatal",
"(",
"ctx",
",",
"ex",
")",
";",
"}",
"}"
] | Return a copy of `obj` after processing it. | [
"Return",
"a",
"copy",
"of",
"obj",
"after",
"processing",
"it",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/lib/boilerplate.preprocessor.js#L53-L67 |
50,610 | redisjs/jsr-server | lib/pubsub.js | PubSub | function PubSub(stats) {
// ref to statistics so they can be updated
// as subscriptions change
this._stats = stats;
// normal channels
this._channels = {};
// pattern channels
this._patterns = {};
this._count = {
channels: {
total: 0, // total number of channels
subscribers: 0, // total subscribers across all channels
},
patterns: {
total: 0, // total number of patterns
subscribers: 0, // total subscribers across all patterns
}
}
} | javascript | function PubSub(stats) {
// ref to statistics so they can be updated
// as subscriptions change
this._stats = stats;
// normal channels
this._channels = {};
// pattern channels
this._patterns = {};
this._count = {
channels: {
total: 0, // total number of channels
subscribers: 0, // total subscribers across all channels
},
patterns: {
total: 0, // total number of patterns
subscribers: 0, // total subscribers across all patterns
}
}
} | [
"function",
"PubSub",
"(",
"stats",
")",
"{",
"// ref to statistics so they can be updated",
"// as subscriptions change",
"this",
".",
"_stats",
"=",
"stats",
";",
"// normal channels",
"this",
".",
"_channels",
"=",
"{",
"}",
";",
"// pattern channels",
"this",
".",
"_patterns",
"=",
"{",
"}",
";",
"this",
".",
"_count",
"=",
"{",
"channels",
":",
"{",
"total",
":",
"0",
",",
"// total number of channels",
"subscribers",
":",
"0",
",",
"// total subscribers across all channels",
"}",
",",
"patterns",
":",
"{",
"total",
":",
"0",
",",
"// total number of patterns",
"subscribers",
":",
"0",
",",
"// total subscribers across all patterns",
"}",
"}",
"}"
] | Encapsulates the pubsub system.
Maps channel identifiers to arrays of client identifiers subscribed
to the given channel.
Clients are given a reference to the channels they are subscribed to,
this global subsystem is responsible for managing the client pubsub
references as well as the global references.
The global instance maps channels as keys on the objects which are arrays
of client identifiers, when a pubsub instance is assigned to a client the
channels and patterns are arrays of the client subscriptions. | [
"Encapsulates",
"the",
"pubsub",
"system",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/pubsub.js#L41-L63 |
50,611 | redisjs/jsr-server | lib/pubsub.js | getChannelList | function getChannelList(channels) {
var i
, channel
, list = [];
for(i = 0;i < channels.length;i++) {
channel = channels[i];
list.push(channel,
this._channels[channel] ? this._channels[channel].length : 0);
}
return list;
} | javascript | function getChannelList(channels) {
var i
, channel
, list = [];
for(i = 0;i < channels.length;i++) {
channel = channels[i];
list.push(channel,
this._channels[channel] ? this._channels[channel].length : 0);
}
return list;
} | [
"function",
"getChannelList",
"(",
"channels",
")",
"{",
"var",
"i",
",",
"channel",
",",
"list",
"=",
"[",
"]",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"channels",
".",
"length",
";",
"i",
"++",
")",
"{",
"channel",
"=",
"channels",
"[",
"i",
"]",
";",
"list",
".",
"push",
"(",
"channel",
",",
"this",
".",
"_channels",
"[",
"channel",
"]",
"?",
"this",
".",
"_channels",
"[",
"channel",
"]",
".",
"length",
":",
"0",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Get a multi bulk array reply of channels with subscriber counts.
Suitable for the PUBSUB NUMSUB [channel-1 channel-N] command.
@param channels The array of channels. | [
"Get",
"a",
"multi",
"bulk",
"array",
"reply",
"of",
"channels",
"with",
"subscriber",
"counts",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/pubsub.js#L127-L137 |
50,612 | redisjs/jsr-server | lib/pubsub.js | getChannels | function getChannels(pattern) {
if(!pattern) return Object.keys(this._channels);
var re = (pattern instanceof RegExp) ? pattern : Pattern.compile(pattern)
, k
, list = [];
for(k in this._channels) {
if(re.test(k)) {
list.push(k);
}
}
return list;
} | javascript | function getChannels(pattern) {
if(!pattern) return Object.keys(this._channels);
var re = (pattern instanceof RegExp) ? pattern : Pattern.compile(pattern)
, k
, list = [];
for(k in this._channels) {
if(re.test(k)) {
list.push(k);
}
}
return list;
} | [
"function",
"getChannels",
"(",
"pattern",
")",
"{",
"if",
"(",
"!",
"pattern",
")",
"return",
"Object",
".",
"keys",
"(",
"this",
".",
"_channels",
")",
";",
"var",
"re",
"=",
"(",
"pattern",
"instanceof",
"RegExp",
")",
"?",
"pattern",
":",
"Pattern",
".",
"compile",
"(",
"pattern",
")",
",",
"k",
",",
"list",
"=",
"[",
"]",
";",
"for",
"(",
"k",
"in",
"this",
".",
"_channels",
")",
"{",
"if",
"(",
"re",
".",
"test",
"(",
"k",
")",
")",
"{",
"list",
".",
"push",
"(",
"k",
")",
";",
"}",
"}",
"return",
"list",
";",
"}"
] | Get channels matching pattern not including pattern subscribers.
Suitable for the PUBSUB CHANNELS [pattern] command. | [
"Get",
"channels",
"matching",
"pattern",
"not",
"including",
"pattern",
"subscribers",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/pubsub.js#L144-L155 |
50,613 | redisjs/jsr-server | lib/pubsub.js | cleanup | function cleanup(client) {
if(client.pubsub
&& client.pubsub.channels
&& client.pubsub.patterns
&& !client.pubsub.channels.length
&& !client.pubsub.patterns.length) {
client.pubsub = null;
}
} | javascript | function cleanup(client) {
if(client.pubsub
&& client.pubsub.channels
&& client.pubsub.patterns
&& !client.pubsub.channels.length
&& !client.pubsub.patterns.length) {
client.pubsub = null;
}
} | [
"function",
"cleanup",
"(",
"client",
")",
"{",
"if",
"(",
"client",
".",
"pubsub",
"&&",
"client",
".",
"pubsub",
".",
"channels",
"&&",
"client",
".",
"pubsub",
".",
"patterns",
"&&",
"!",
"client",
".",
"pubsub",
".",
"channels",
".",
"length",
"&&",
"!",
"client",
".",
"pubsub",
".",
"patterns",
".",
"length",
")",
"{",
"client",
".",
"pubsub",
"=",
"null",
";",
"}",
"}"
] | Clean pubsub references on the client when it has no
more channels or patterns. | [
"Clean",
"pubsub",
"references",
"on",
"the",
"client",
"when",
"it",
"has",
"no",
"more",
"channels",
"or",
"patterns",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/pubsub.js#L386-L394 |
50,614 | bentomas/node-async-testing | lib/running.js | generateHelp | function generateHelp(flags) {
var max = 0;
for (var group in flags) {
for (var i = 0; i < flags[group].length; i++) {
var n = 2; // ' '
if (flags[group][i].longFlag) {
n += 2; // '--'
n += flags[group][i].longFlag.length;
}
if (flags[group][i].longFlag && flags[group][i].shortFlag) {
n += 2; // ', '
}
if (flags[group][i].shortFlag) {
n += 1; // '-'
n += flags[group][i].shortFlag.length;
}
if (n > max) {
max = n;
}
}
}
console.log('node-async-testing');
console.log('');
for (var group in flags) {
console.log(group+':');
for (var i = 0; i < flags[group].length; i++) {
var s = ' ';
if (flags[group][i].longFlag) {
s += '--' + flags[group][i].longFlag;
}
if (flags[group][i].longFlag && flags[group][i].shortFlag) {
s += ', ';
}
if (flags[group][i].shortFlag) {
for(var j = s.length+flags[group][i].shortFlag.length; j < max; j++) {
s += ' ';
}
s += '-' + flags[group][i].shortFlag;
}
if (flags[group][i].takesValue) {
s += ' <'+flags[group][i].takesValue+'>';
}
console.log(
s +
': ' +
flags[group][i].description +
(flags[group][i].options ? ' ('+flags[group][i].options.join(', ')+')' : '')
);
}
console.log('');
}
console.log('Any other arguments are interpreted as files to run');
} | javascript | function generateHelp(flags) {
var max = 0;
for (var group in flags) {
for (var i = 0; i < flags[group].length; i++) {
var n = 2; // ' '
if (flags[group][i].longFlag) {
n += 2; // '--'
n += flags[group][i].longFlag.length;
}
if (flags[group][i].longFlag && flags[group][i].shortFlag) {
n += 2; // ', '
}
if (flags[group][i].shortFlag) {
n += 1; // '-'
n += flags[group][i].shortFlag.length;
}
if (n > max) {
max = n;
}
}
}
console.log('node-async-testing');
console.log('');
for (var group in flags) {
console.log(group+':');
for (var i = 0; i < flags[group].length; i++) {
var s = ' ';
if (flags[group][i].longFlag) {
s += '--' + flags[group][i].longFlag;
}
if (flags[group][i].longFlag && flags[group][i].shortFlag) {
s += ', ';
}
if (flags[group][i].shortFlag) {
for(var j = s.length+flags[group][i].shortFlag.length; j < max; j++) {
s += ' ';
}
s += '-' + flags[group][i].shortFlag;
}
if (flags[group][i].takesValue) {
s += ' <'+flags[group][i].takesValue+'>';
}
console.log(
s +
': ' +
flags[group][i].description +
(flags[group][i].options ? ' ('+flags[group][i].options.join(', ')+')' : '')
);
}
console.log('');
}
console.log('Any other arguments are interpreted as files to run');
} | [
"function",
"generateHelp",
"(",
"flags",
")",
"{",
"var",
"max",
"=",
"0",
";",
"for",
"(",
"var",
"group",
"in",
"flags",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"flags",
"[",
"group",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"n",
"=",
"2",
";",
"// ' '",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"longFlag",
")",
"{",
"n",
"+=",
"2",
";",
"// '--'",
"n",
"+=",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"longFlag",
".",
"length",
";",
"}",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"longFlag",
"&&",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
")",
"{",
"n",
"+=",
"2",
";",
"// ', '",
"}",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
")",
"{",
"n",
"+=",
"1",
";",
"// '-'",
"n",
"+=",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
".",
"length",
";",
"}",
"if",
"(",
"n",
">",
"max",
")",
"{",
"max",
"=",
"n",
";",
"}",
"}",
"}",
"console",
".",
"log",
"(",
"'node-async-testing'",
")",
";",
"console",
".",
"log",
"(",
"''",
")",
";",
"for",
"(",
"var",
"group",
"in",
"flags",
")",
"{",
"console",
".",
"log",
"(",
"group",
"+",
"':'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"flags",
"[",
"group",
"]",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"s",
"=",
"' '",
";",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"longFlag",
")",
"{",
"s",
"+=",
"'--'",
"+",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"longFlag",
";",
"}",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"longFlag",
"&&",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
")",
"{",
"s",
"+=",
"', '",
";",
"}",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"s",
".",
"length",
"+",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
".",
"length",
";",
"j",
"<",
"max",
";",
"j",
"++",
")",
"{",
"s",
"+=",
"' '",
";",
"}",
"s",
"+=",
"'-'",
"+",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"shortFlag",
";",
"}",
"if",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"takesValue",
")",
"{",
"s",
"+=",
"' <'",
"+",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"takesValue",
"+",
"'>'",
";",
"}",
"console",
".",
"log",
"(",
"s",
"+",
"': '",
"+",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"description",
"+",
"(",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"options",
"?",
"' ('",
"+",
"flags",
"[",
"group",
"]",
"[",
"i",
"]",
".",
"options",
".",
"join",
"(",
"', '",
")",
"+",
"')'",
":",
"''",
")",
")",
";",
"}",
"console",
".",
"log",
"(",
"''",
")",
";",
"}",
"console",
".",
"log",
"(",
"'Any other arguments are interpreted as files to run'",
")",
";",
"}"
] | creates the help message for running this from the command line | [
"creates",
"the",
"help",
"message",
"for",
"running",
"this",
"from",
"the",
"command",
"line"
] | 82384ba4b8444e4659464bad661788827ea721aa | https://github.com/bentomas/node-async-testing/blob/82384ba4b8444e4659464bad661788827ea721aa/lib/running.js#L247-L302 |
50,615 | KapIT/observe-utils | lib/observe-utils.js | isPositiveFiniteInteger | function isPositiveFiniteInteger(value, errorMessage) {
value = Number(value);
if (isNaN(value) || !isFinite(value) || value < 0 || value % 1 !== 0) {
throw new RangeError(errorMessage.replace('$', value));
}
return value;
} | javascript | function isPositiveFiniteInteger(value, errorMessage) {
value = Number(value);
if (isNaN(value) || !isFinite(value) || value < 0 || value % 1 !== 0) {
throw new RangeError(errorMessage.replace('$', value));
}
return value;
} | [
"function",
"isPositiveFiniteInteger",
"(",
"value",
",",
"errorMessage",
")",
"{",
"value",
"=",
"Number",
"(",
"value",
")",
";",
"if",
"(",
"isNaN",
"(",
"value",
")",
"||",
"!",
"isFinite",
"(",
"value",
")",
"||",
"value",
"<",
"0",
"||",
"value",
"%",
"1",
"!==",
"0",
")",
"{",
"throw",
"new",
"RangeError",
"(",
"errorMessage",
".",
"replace",
"(",
"'$'",
",",
"value",
")",
")",
";",
"}",
"return",
"value",
";",
"}"
] | cast a value as number, and test if the obtained result is a positive finite integer, throw an error otherwise | [
"cast",
"a",
"value",
"as",
"number",
"and",
"test",
"if",
"the",
"obtained",
"result",
"is",
"a",
"positive",
"finite",
"integer",
"throw",
"an",
"error",
"otherwise"
] | 4a9d0140e2dfcb15e85f9d5951692045265fb391 | https://github.com/KapIT/observe-utils/blob/4a9d0140e2dfcb15e85f9d5951692045265fb391/lib/observe-utils.js#L82-L88 |
50,616 | KapIT/observe-utils | lib/observe-utils.js | defineObservableProperty | function defineObservableProperty(target, property, originalValue) {
//we store the value in an non-enumerable property with generated unique name
var internalPropName = '_' + (uidCounter++) + property;
if (target.hasOwnProperty(property)) {
Object.defineProperty(target, internalPropName, {
value: originalValue,
writable: true,
enumerable: false,
configurable: true
});
}
//then we create accessor method for our 'hidden' property,
// that dispatch changesRecords when the value is updated
Object.defineProperty(target, property, {
get: function () {
return this[internalPropName];
},
set: function (value) {
if (!sameValue(value, this[internalPropName])) {
var oldValue = this[internalPropName];
Object.defineProperty(this, internalPropName, {
value: value,
writable: true,
enumerable: false,
configurable: true
});
var notifier = Object.getNotifier(this);
notifier.notify({ type: 'update', name: property, oldValue: oldValue });
}
},
enumerable: true,
configurable: true
});
} | javascript | function defineObservableProperty(target, property, originalValue) {
//we store the value in an non-enumerable property with generated unique name
var internalPropName = '_' + (uidCounter++) + property;
if (target.hasOwnProperty(property)) {
Object.defineProperty(target, internalPropName, {
value: originalValue,
writable: true,
enumerable: false,
configurable: true
});
}
//then we create accessor method for our 'hidden' property,
// that dispatch changesRecords when the value is updated
Object.defineProperty(target, property, {
get: function () {
return this[internalPropName];
},
set: function (value) {
if (!sameValue(value, this[internalPropName])) {
var oldValue = this[internalPropName];
Object.defineProperty(this, internalPropName, {
value: value,
writable: true,
enumerable: false,
configurable: true
});
var notifier = Object.getNotifier(this);
notifier.notify({ type: 'update', name: property, oldValue: oldValue });
}
},
enumerable: true,
configurable: true
});
} | [
"function",
"defineObservableProperty",
"(",
"target",
",",
"property",
",",
"originalValue",
")",
"{",
"//we store the value in an non-enumerable property with generated unique name",
"var",
"internalPropName",
"=",
"'_'",
"+",
"(",
"uidCounter",
"++",
")",
"+",
"property",
";",
"if",
"(",
"target",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"target",
",",
"internalPropName",
",",
"{",
"value",
":",
"originalValue",
",",
"writable",
":",
"true",
",",
"enumerable",
":",
"false",
",",
"configurable",
":",
"true",
"}",
")",
";",
"}",
"//then we create accessor method for our 'hidden' property,",
"// that dispatch changesRecords when the value is updated",
"Object",
".",
"defineProperty",
"(",
"target",
",",
"property",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"this",
"[",
"internalPropName",
"]",
";",
"}",
",",
"set",
":",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"sameValue",
"(",
"value",
",",
"this",
"[",
"internalPropName",
"]",
")",
")",
"{",
"var",
"oldValue",
"=",
"this",
"[",
"internalPropName",
"]",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"internalPropName",
",",
"{",
"value",
":",
"value",
",",
"writable",
":",
"true",
",",
"enumerable",
":",
"false",
",",
"configurable",
":",
"true",
"}",
")",
";",
"var",
"notifier",
"=",
"Object",
".",
"getNotifier",
"(",
"this",
")",
";",
"notifier",
".",
"notify",
"(",
"{",
"type",
":",
"'update'",
",",
"name",
":",
"property",
",",
"oldValue",
":",
"oldValue",
"}",
")",
";",
"}",
"}",
",",
"enumerable",
":",
"true",
",",
"configurable",
":",
"true",
"}",
")",
";",
"}"
] | Define a property on an object that will call the Notifier.notify method when updated | [
"Define",
"a",
"property",
"on",
"an",
"object",
"that",
"will",
"call",
"the",
"Notifier",
".",
"notify",
"method",
"when",
"updated"
] | 4a9d0140e2dfcb15e85f9d5951692045265fb391 | https://github.com/KapIT/observe-utils/blob/4a9d0140e2dfcb15e85f9d5951692045265fb391/lib/observe-utils.js#L97-L133 |
50,617 | zthun/zbuildtools | src/karma/zkarma.js | createKarmaTypescriptConfig | function createKarmaTypescriptConfig(tsconfigJson, coverageDir) {
return {
tsconfig: tsconfigJson,
coverageOptions: {
instrumentation: !isDebug()
},
reports: {
'cobertura': {
directory: coverageDir,
subdirectory: 'cobertura',
filename: 'coverage.xml'
},
'html': {
directory: coverageDir,
subdirectory: '.'
},
'text-summary': null
}
};
} | javascript | function createKarmaTypescriptConfig(tsconfigJson, coverageDir) {
return {
tsconfig: tsconfigJson,
coverageOptions: {
instrumentation: !isDebug()
},
reports: {
'cobertura': {
directory: coverageDir,
subdirectory: 'cobertura',
filename: 'coverage.xml'
},
'html': {
directory: coverageDir,
subdirectory: '.'
},
'text-summary': null
}
};
} | [
"function",
"createKarmaTypescriptConfig",
"(",
"tsconfigJson",
",",
"coverageDir",
")",
"{",
"return",
"{",
"tsconfig",
":",
"tsconfigJson",
",",
"coverageOptions",
":",
"{",
"instrumentation",
":",
"!",
"isDebug",
"(",
")",
"}",
",",
"reports",
":",
"{",
"'cobertura'",
":",
"{",
"directory",
":",
"coverageDir",
",",
"subdirectory",
":",
"'cobertura'",
",",
"filename",
":",
"'coverage.xml'",
"}",
",",
"'html'",
":",
"{",
"directory",
":",
"coverageDir",
",",
"subdirectory",
":",
"'.'",
"}",
",",
"'text-summary'",
":",
"null",
"}",
"}",
";",
"}"
] | Creates an object that represents a karma typescript config object.
@param {String} tsconfigJson The relative path to the tsconfig.json file.
@param {String} coverageDir The coverage report directory.
@return {Object} The common options for a karma typescript configuration. | [
"Creates",
"an",
"object",
"that",
"represents",
"a",
"karma",
"typescript",
"config",
"object",
"."
] | f9b339fc3c3b8188638ccd17a96cb44d457bafd4 | https://github.com/zthun/zbuildtools/blob/f9b339fc3c3b8188638ccd17a96cb44d457bafd4/src/karma/zkarma.js#L39-L60 |
50,618 | igorski/zjslib | src/Sprite.js | Sprite | function Sprite( aElement, aProperties, aContent )
{
aProperties = aProperties || {};
var domElement = "div";
if ( aElement && typeof aElement !== "object" )
{
domElement = /** @type {string} */ ( aElement);
}
/* creates HTML element of requested tag type in the DOM */
if ( !aElement || typeof aElement === "string" )
{
this._element = document.createElement( domElement );
}
else
{
this._element = /** @type {Element} */ ( aElement );
}
Object.keys( aProperties ).forEach( function( key )
{
this._element.setAttribute( key, aProperties[ key ]);
}.bind( this ));
if ( aContent )
{
this.setContent( aContent );
}
this._children = [];
Inheritance.super( this );
this._eventHandler = new EventHandler(); // separate handler for DOM Events
} | javascript | function Sprite( aElement, aProperties, aContent )
{
aProperties = aProperties || {};
var domElement = "div";
if ( aElement && typeof aElement !== "object" )
{
domElement = /** @type {string} */ ( aElement);
}
/* creates HTML element of requested tag type in the DOM */
if ( !aElement || typeof aElement === "string" )
{
this._element = document.createElement( domElement );
}
else
{
this._element = /** @type {Element} */ ( aElement );
}
Object.keys( aProperties ).forEach( function( key )
{
this._element.setAttribute( key, aProperties[ key ]);
}.bind( this ));
if ( aContent )
{
this.setContent( aContent );
}
this._children = [];
Inheritance.super( this );
this._eventHandler = new EventHandler(); // separate handler for DOM Events
} | [
"function",
"Sprite",
"(",
"aElement",
",",
"aProperties",
",",
"aContent",
")",
"{",
"aProperties",
"=",
"aProperties",
"||",
"{",
"}",
";",
"var",
"domElement",
"=",
"\"div\"",
";",
"if",
"(",
"aElement",
"&&",
"typeof",
"aElement",
"!==",
"\"object\"",
")",
"{",
"domElement",
"=",
"/** @type {string} */",
"(",
"aElement",
")",
";",
"}",
"/* creates HTML element of requested tag type in the DOM */",
"if",
"(",
"!",
"aElement",
"||",
"typeof",
"aElement",
"===",
"\"string\"",
")",
"{",
"this",
".",
"_element",
"=",
"document",
".",
"createElement",
"(",
"domElement",
")",
";",
"}",
"else",
"{",
"this",
".",
"_element",
"=",
"/** @type {Element} */",
"(",
"aElement",
")",
";",
"}",
"Object",
".",
"keys",
"(",
"aProperties",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"this",
".",
"_element",
".",
"setAttribute",
"(",
"key",
",",
"aProperties",
"[",
"key",
"]",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"if",
"(",
"aContent",
")",
"{",
"this",
".",
"setContent",
"(",
"aContent",
")",
";",
"}",
"this",
".",
"_children",
"=",
"[",
"]",
";",
"Inheritance",
".",
"super",
"(",
"this",
")",
";",
"this",
".",
"_eventHandler",
"=",
"new",
"EventHandler",
"(",
")",
";",
"// separate handler for DOM Events",
"}"
] | A wrapper providing a convenient API to manage a DOM element, provides
Event handling and "display list"s
extends a basic EventTarget for dispatching events
@constructor
@param {string|Element|Node|Window|HTMLDocument=} aElement when String: this function will create an element in the
DOM with the String as tag name.
when HTMLElement: this function will bind the Sprite class to the existing
HTMLElement (for use when connecting existing HTML templates with the framework)
@param {Object=} aProperties optional properties for the HTML Element ( eg: id, class, etc. )
@param {string=} aContent optional body content of this Sprite (innerHTML)
@extends {EventDispatcher} | [
"A",
"wrapper",
"providing",
"a",
"convenient",
"API",
"to",
"manage",
"a",
"DOM",
"element",
"provides",
"Event",
"handling",
"and",
"display",
"list",
"s"
] | d3c3fd49862d21de4646af0403c03f31b1134b00 | https://github.com/igorski/zjslib/blob/d3c3fd49862d21de4646af0403c03f31b1134b00/src/Sprite.js#L50-L87 |
50,619 | igorski/zjslib | src/Sprite.js | function( e )
{
var event = new Event( aType );
event.target = self;
event.srcEvent = e;
aHandler( event );
} | javascript | function( e )
{
var event = new Event( aType );
event.target = self;
event.srcEvent = e;
aHandler( event );
} | [
"function",
"(",
"e",
")",
"{",
"var",
"event",
"=",
"new",
"Event",
"(",
"aType",
")",
";",
"event",
".",
"target",
"=",
"self",
";",
"event",
".",
"srcEvent",
"=",
"e",
";",
"aHandler",
"(",
"event",
")",
";",
"}"
] | wrap the callback invocation to reference the Sprite, NOT the DOM node as its target | [
"wrap",
"the",
"callback",
"invocation",
"to",
"reference",
"the",
"Sprite",
"NOT",
"the",
"DOM",
"node",
"as",
"its",
"target"
] | d3c3fd49862d21de4646af0403c03f31b1134b00 | https://github.com/igorski/zjslib/blob/d3c3fd49862d21de4646af0403c03f31b1134b00/src/Sprite.js#L180-L187 |
|
50,620 | magemello/gulp-license-check | index.js | checkHeaderFromStream | function checkHeaderFromStream(file, ctx) {
file.contents.pipe(es.wait(function (err, data) {
if (err) {
throw err;
}
var bufferFile = new File({
path: file.path,
contents: data
});
checkHeaderFromBuffer(bufferFile, ctx);
}));
} | javascript | function checkHeaderFromStream(file, ctx) {
file.contents.pipe(es.wait(function (err, data) {
if (err) {
throw err;
}
var bufferFile = new File({
path: file.path,
contents: data
});
checkHeaderFromBuffer(bufferFile, ctx);
}));
} | [
"function",
"checkHeaderFromStream",
"(",
"file",
",",
"ctx",
")",
"{",
"file",
".",
"contents",
".",
"pipe",
"(",
"es",
".",
"wait",
"(",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"var",
"bufferFile",
"=",
"new",
"File",
"(",
"{",
"path",
":",
"file",
".",
"path",
",",
"contents",
":",
"data",
"}",
")",
";",
"checkHeaderFromBuffer",
"(",
"bufferFile",
",",
"ctx",
")",
";",
"}",
")",
")",
";",
"}"
] | Check header from stream.
@param {object} file - current file from stream.
@param {object} ctx - context.
@returns {string[]} file in string[] format. | [
"Check",
"header",
"from",
"stream",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L59-L72 |
50,621 | magemello/gulp-license-check | index.js | checkHeaderFromBuffer | function checkHeaderFromBuffer(file, ctx) {
if (isLicenseHeaderPresent(file)) {
log(file.path, ctx);
} else {
error(file.path, ctx);
}
} | javascript | function checkHeaderFromBuffer(file, ctx) {
if (isLicenseHeaderPresent(file)) {
log(file.path, ctx);
} else {
error(file.path, ctx);
}
} | [
"function",
"checkHeaderFromBuffer",
"(",
"file",
",",
"ctx",
")",
"{",
"if",
"(",
"isLicenseHeaderPresent",
"(",
"file",
")",
")",
"{",
"log",
"(",
"file",
".",
"path",
",",
"ctx",
")",
";",
"}",
"else",
"{",
"error",
"(",
"file",
".",
"path",
",",
"ctx",
")",
";",
"}",
"}"
] | Check header from buffer.
@param {object} file - current file from buffer.
@param {object} ctx - context. | [
"Check",
"header",
"from",
"buffer",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L80-L86 |
50,622 | magemello/gulp-license-check | index.js | readLicenseHeaderFile | function readLicenseHeaderFile() {
if (licenseFileUtf8) {
return licenseFileUtf8;
}
if (fs.existsSync(licenseFilePath)) {
return fs.readFileSync(licenseFilePath, 'utf8').split(/\r?\n/);
}
throw new gutil.PluginError('gulp-license-check', new Error('The license header file doesn`t exist ' + licenseFilePath));
} | javascript | function readLicenseHeaderFile() {
if (licenseFileUtf8) {
return licenseFileUtf8;
}
if (fs.existsSync(licenseFilePath)) {
return fs.readFileSync(licenseFilePath, 'utf8').split(/\r?\n/);
}
throw new gutil.PluginError('gulp-license-check', new Error('The license header file doesn`t exist ' + licenseFilePath));
} | [
"function",
"readLicenseHeaderFile",
"(",
")",
"{",
"if",
"(",
"licenseFileUtf8",
")",
"{",
"return",
"licenseFileUtf8",
";",
"}",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"licenseFilePath",
")",
")",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"licenseFilePath",
",",
"'utf8'",
")",
".",
"split",
"(",
"/",
"\\r?\\n",
"/",
")",
";",
"}",
"throw",
"new",
"gutil",
".",
"PluginError",
"(",
"'gulp-license-check'",
",",
"new",
"Error",
"(",
"'The license header file doesn`t exist '",
"+",
"licenseFilePath",
")",
")",
";",
"}"
] | Read the file header path.
@returns {string[]} The license header template in sting[] format. | [
"Read",
"the",
"file",
"header",
"path",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L104-L114 |
50,623 | magemello/gulp-license-check | index.js | log | function log(filePath, ctx) {
if (isInfoLogActive) {
ctx.emit('log', {
msg: HEADER_PRESENT,
path: filePath
});
gutil.log(gutil.colors.green(HEADER_PRESENT), filePath);
}
} | javascript | function log(filePath, ctx) {
if (isInfoLogActive) {
ctx.emit('log', {
msg: HEADER_PRESENT,
path: filePath
});
gutil.log(gutil.colors.green(HEADER_PRESENT), filePath);
}
} | [
"function",
"log",
"(",
"filePath",
",",
"ctx",
")",
"{",
"if",
"(",
"isInfoLogActive",
")",
"{",
"ctx",
".",
"emit",
"(",
"'log'",
",",
"{",
"msg",
":",
"HEADER_PRESENT",
",",
"path",
":",
"filePath",
"}",
")",
";",
"gutil",
".",
"log",
"(",
"gutil",
".",
"colors",
".",
"green",
"(",
"HEADER_PRESENT",
")",
",",
"filePath",
")",
";",
"}",
"}"
] | Log util.
@param {string} filePath - file Path.
@param {object} ctx - context. | [
"Log",
"util",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L122-L130 |
50,624 | magemello/gulp-license-check | index.js | error | function error(filePath, ctx) {
if (isErrorBlocking) {
throw new gutil.PluginError('gulp-license-check', new Error('The following file doesn`t contain the license header ' + filePath));
} else {
logError(filePath, ctx);
}
} | javascript | function error(filePath, ctx) {
if (isErrorBlocking) {
throw new gutil.PluginError('gulp-license-check', new Error('The following file doesn`t contain the license header ' + filePath));
} else {
logError(filePath, ctx);
}
} | [
"function",
"error",
"(",
"filePath",
",",
"ctx",
")",
"{",
"if",
"(",
"isErrorBlocking",
")",
"{",
"throw",
"new",
"gutil",
".",
"PluginError",
"(",
"'gulp-license-check'",
",",
"new",
"Error",
"(",
"'The following file doesn`t contain the license header '",
"+",
"filePath",
")",
")",
";",
"}",
"else",
"{",
"logError",
"(",
"filePath",
",",
"ctx",
")",
";",
"}",
"}"
] | Manage error in case the header is not present.
@param {string} filePath - file Path.
@param {object} ctx - context. | [
"Manage",
"error",
"in",
"case",
"the",
"header",
"is",
"not",
"present",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L138-L144 |
50,625 | magemello/gulp-license-check | index.js | logError | function logError(filePath, ctx) {
if (isErrorLogActive) {
ctx.emit('log', {
msg: HEADER_NOT_PRESENT,
path: filePath
});
gutil.log(gutil.colors.red(HEADER_NOT_PRESENT), filePath);
}
} | javascript | function logError(filePath, ctx) {
if (isErrorLogActive) {
ctx.emit('log', {
msg: HEADER_NOT_PRESENT,
path: filePath
});
gutil.log(gutil.colors.red(HEADER_NOT_PRESENT), filePath);
}
} | [
"function",
"logError",
"(",
"filePath",
",",
"ctx",
")",
"{",
"if",
"(",
"isErrorLogActive",
")",
"{",
"ctx",
".",
"emit",
"(",
"'log'",
",",
"{",
"msg",
":",
"HEADER_NOT_PRESENT",
",",
"path",
":",
"filePath",
"}",
")",
";",
"gutil",
".",
"log",
"(",
"gutil",
".",
"colors",
".",
"red",
"(",
"HEADER_NOT_PRESENT",
")",
",",
"filePath",
")",
";",
"}",
"}"
] | Log error.
@param {string} filePath - file Path.
@param {object} ctx - context. | [
"Log",
"error",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L152-L160 |
50,626 | magemello/gulp-license-check | index.js | isLicenseHeaderPresent | function isLicenseHeaderPresent(currentFile) {
if (!isFileEmpty(currentFile.contents)) {
var currentFileUtf8 = readCurrentFile(currentFile),
licenseFileUtf8 = readLicenseHeaderFile(),
skipStrict = 0;
if(currentFileUtf8[0] === '"use strict";' ) {
skipStrict = 1;
}
for (var i = skipStrict; i < licenseFileUtf8.length; i++) {
if (currentFileUtf8[i + skipStrict] !== licenseFileUtf8[i]) {
return false;
}
}
}
return true;
} | javascript | function isLicenseHeaderPresent(currentFile) {
if (!isFileEmpty(currentFile.contents)) {
var currentFileUtf8 = readCurrentFile(currentFile),
licenseFileUtf8 = readLicenseHeaderFile(),
skipStrict = 0;
if(currentFileUtf8[0] === '"use strict";' ) {
skipStrict = 1;
}
for (var i = skipStrict; i < licenseFileUtf8.length; i++) {
if (currentFileUtf8[i + skipStrict] !== licenseFileUtf8[i]) {
return false;
}
}
}
return true;
} | [
"function",
"isLicenseHeaderPresent",
"(",
"currentFile",
")",
"{",
"if",
"(",
"!",
"isFileEmpty",
"(",
"currentFile",
".",
"contents",
")",
")",
"{",
"var",
"currentFileUtf8",
"=",
"readCurrentFile",
"(",
"currentFile",
")",
",",
"licenseFileUtf8",
"=",
"readLicenseHeaderFile",
"(",
")",
",",
"skipStrict",
"=",
"0",
";",
"if",
"(",
"currentFileUtf8",
"[",
"0",
"]",
"===",
"'\"use strict\";'",
")",
"{",
"skipStrict",
"=",
"1",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"skipStrict",
";",
"i",
"<",
"licenseFileUtf8",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"currentFileUtf8",
"[",
"i",
"+",
"skipStrict",
"]",
"!==",
"licenseFileUtf8",
"[",
"i",
"]",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] | Check if header is present.
@param {object} currentFile - file in string[] format.
@returns {boolean} dose match. | [
"Check",
"if",
"header",
"is",
"present",
"."
] | fbd547b989a90f7ea3bb41304868a03ec207f204 | https://github.com/magemello/gulp-license-check/blob/fbd547b989a90f7ea3bb41304868a03ec207f204/index.js#L169-L186 |
50,627 | calleboketoft/ng2-browser-storage | src/browser-storage/services/browser-storage.util.js | getConfigFromLS | function getConfigFromLS() {
var configStr = localStorage[getFullBSKey(browser_storage_config_1.browserStorageConfig.DB_CONFIG_KEY)];
if (typeof configStr === 'undefined') {
return null;
}
else {
return JSON.parse(configStr);
}
} | javascript | function getConfigFromLS() {
var configStr = localStorage[getFullBSKey(browser_storage_config_1.browserStorageConfig.DB_CONFIG_KEY)];
if (typeof configStr === 'undefined') {
return null;
}
else {
return JSON.parse(configStr);
}
} | [
"function",
"getConfigFromLS",
"(",
")",
"{",
"var",
"configStr",
"=",
"localStorage",
"[",
"getFullBSKey",
"(",
"browser_storage_config_1",
".",
"browserStorageConfig",
".",
"DB_CONFIG_KEY",
")",
"]",
";",
"if",
"(",
"typeof",
"configStr",
"===",
"'undefined'",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"return",
"JSON",
".",
"parse",
"(",
"configStr",
")",
";",
"}",
"}"
] | get config from browser storage and deserialize to JSON | [
"get",
"config",
"from",
"browser",
"storage",
"and",
"deserialize",
"to",
"JSON"
] | 7186096797957de62649bbb832a7c6b7d463d861 | https://github.com/calleboketoft/ng2-browser-storage/blob/7186096797957de62649bbb832a7c6b7d463d861/src/browser-storage/services/browser-storage.util.js#L5-L13 |
50,628 | calleboketoft/ng2-browser-storage | src/browser-storage/services/browser-storage.util.js | setConfigToLS | function setConfigToLS(configObj) {
var configStr = JSON.stringify(configObj);
window.localStorage[getFullBSKey(browser_storage_config_1.browserStorageConfig.DB_CONFIG_KEY)] = configStr;
} | javascript | function setConfigToLS(configObj) {
var configStr = JSON.stringify(configObj);
window.localStorage[getFullBSKey(browser_storage_config_1.browserStorageConfig.DB_CONFIG_KEY)] = configStr;
} | [
"function",
"setConfigToLS",
"(",
"configObj",
")",
"{",
"var",
"configStr",
"=",
"JSON",
".",
"stringify",
"(",
"configObj",
")",
";",
"window",
".",
"localStorage",
"[",
"getFullBSKey",
"(",
"browser_storage_config_1",
".",
"browserStorageConfig",
".",
"DB_CONFIG_KEY",
")",
"]",
"=",
"configStr",
";",
"}"
] | serialize config and save to browser storage | [
"serialize",
"config",
"and",
"save",
"to",
"browser",
"storage"
] | 7186096797957de62649bbb832a7c6b7d463d861 | https://github.com/calleboketoft/ng2-browser-storage/blob/7186096797957de62649bbb832a7c6b7d463d861/src/browser-storage/services/browser-storage.util.js#L16-L19 |
50,629 | calleboketoft/ng2-browser-storage | src/browser-storage/services/browser-storage.util.js | getInitialBrowserStorageState | function getInitialBrowserStorageState() {
var memorizedFile = getConfigFromLS()[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY];
return memorizedFile.map(function (memItem) {
var browserStorageValue = window[memItem.storageType]['getItem'](getFullBSKey(memItem.key));
if (browserStorageValue) {
return Object.assign({}, memItem, { value: browserStorageValue });
}
else {
return memItem;
}
});
} | javascript | function getInitialBrowserStorageState() {
var memorizedFile = getConfigFromLS()[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY];
return memorizedFile.map(function (memItem) {
var browserStorageValue = window[memItem.storageType]['getItem'](getFullBSKey(memItem.key));
if (browserStorageValue) {
return Object.assign({}, memItem, { value: browserStorageValue });
}
else {
return memItem;
}
});
} | [
"function",
"getInitialBrowserStorageState",
"(",
")",
"{",
"var",
"memorizedFile",
"=",
"getConfigFromLS",
"(",
")",
"[",
"browser_storage_config_1",
".",
"browserStorageConfig",
".",
"DB_INITIAL_KEY",
"]",
";",
"return",
"memorizedFile",
".",
"map",
"(",
"function",
"(",
"memItem",
")",
"{",
"var",
"browserStorageValue",
"=",
"window",
"[",
"memItem",
".",
"storageType",
"]",
"[",
"'getItem'",
"]",
"(",
"getFullBSKey",
"(",
"memItem",
".",
"key",
")",
")",
";",
"if",
"(",
"browserStorageValue",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"memItem",
",",
"{",
"value",
":",
"browserStorageValue",
"}",
")",
";",
"}",
"else",
"{",
"return",
"memItem",
";",
"}",
"}",
")",
";",
"}"
] | go through memorized file config and get all separate browser storage values from keys | [
"go",
"through",
"memorized",
"file",
"config",
"and",
"get",
"all",
"separate",
"browser",
"storage",
"values",
"from",
"keys"
] | 7186096797957de62649bbb832a7c6b7d463d861 | https://github.com/calleboketoft/ng2-browser-storage/blob/7186096797957de62649bbb832a7c6b7d463d861/src/browser-storage/services/browser-storage.util.js#L23-L34 |
50,630 | calleboketoft/ng2-browser-storage | src/browser-storage/services/browser-storage.util.js | initFromScratch | function initFromScratch(cbsConfigFromFile) {
cbsConfigFromFile.initialState.forEach(function (item) { return saveItemToBrowserStorage(item); });
return _a = {},
_a[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY] = cbsConfigFromFile.initialState,
_a;
var _a;
} | javascript | function initFromScratch(cbsConfigFromFile) {
cbsConfigFromFile.initialState.forEach(function (item) { return saveItemToBrowserStorage(item); });
return _a = {},
_a[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY] = cbsConfigFromFile.initialState,
_a;
var _a;
} | [
"function",
"initFromScratch",
"(",
"cbsConfigFromFile",
")",
"{",
"cbsConfigFromFile",
".",
"initialState",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"saveItemToBrowserStorage",
"(",
"item",
")",
";",
"}",
")",
";",
"return",
"_a",
"=",
"{",
"}",
",",
"_a",
"[",
"browser_storage_config_1",
".",
"browserStorageConfig",
".",
"DB_INITIAL_KEY",
"]",
"=",
"cbsConfigFromFile",
".",
"initialState",
",",
"_a",
";",
"var",
"_a",
";",
"}"
] | Initialize storage items from scratch | [
"Initialize",
"storage",
"items",
"from",
"scratch"
] | 7186096797957de62649bbb832a7c6b7d463d861 | https://github.com/calleboketoft/ng2-browser-storage/blob/7186096797957de62649bbb832a7c6b7d463d861/src/browser-storage/services/browser-storage.util.js#L55-L61 |
50,631 | calleboketoft/ng2-browser-storage | src/browser-storage/services/browser-storage.util.js | initExisting | function initExisting(cbsConfigFromFile, cbsConfigFromLS) {
// Restore items that have been manually removed by a user
restoreManuallyRemovedItems(cbsConfigFromLS);
var configFileDifferOptions = {
fileInitialState: cbsConfigFromFile.initialState,
memoryInitialState: cbsConfigFromLS[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY]
};
handleRemovedConfigItems(configFileDifferOptions);
handleAddedConfigItems(configFileDifferOptions);
handleUpdatedConfigItems(configFileDifferOptions);
} | javascript | function initExisting(cbsConfigFromFile, cbsConfigFromLS) {
// Restore items that have been manually removed by a user
restoreManuallyRemovedItems(cbsConfigFromLS);
var configFileDifferOptions = {
fileInitialState: cbsConfigFromFile.initialState,
memoryInitialState: cbsConfigFromLS[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY]
};
handleRemovedConfigItems(configFileDifferOptions);
handleAddedConfigItems(configFileDifferOptions);
handleUpdatedConfigItems(configFileDifferOptions);
} | [
"function",
"initExisting",
"(",
"cbsConfigFromFile",
",",
"cbsConfigFromLS",
")",
"{",
"// Restore items that have been manually removed by a user",
"restoreManuallyRemovedItems",
"(",
"cbsConfigFromLS",
")",
";",
"var",
"configFileDifferOptions",
"=",
"{",
"fileInitialState",
":",
"cbsConfigFromFile",
".",
"initialState",
",",
"memoryInitialState",
":",
"cbsConfigFromLS",
"[",
"browser_storage_config_1",
".",
"browserStorageConfig",
".",
"DB_INITIAL_KEY",
"]",
"}",
";",
"handleRemovedConfigItems",
"(",
"configFileDifferOptions",
")",
";",
"handleAddedConfigItems",
"(",
"configFileDifferOptions",
")",
";",
"handleUpdatedConfigItems",
"(",
"configFileDifferOptions",
")",
";",
"}"
] | Initialize storage items for existing config, handle any config file updates | [
"Initialize",
"storage",
"items",
"for",
"existing",
"config",
"handle",
"any",
"config",
"file",
"updates"
] | 7186096797957de62649bbb832a7c6b7d463d861 | https://github.com/calleboketoft/ng2-browser-storage/blob/7186096797957de62649bbb832a7c6b7d463d861/src/browser-storage/services/browser-storage.util.js#L63-L73 |
50,632 | calleboketoft/ng2-browser-storage | src/browser-storage/services/browser-storage.util.js | restoreManuallyRemovedItems | function restoreManuallyRemovedItems(cbsConfigFromLS) {
cbsConfigFromLS[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY].map(function (memoryItem) {
var storageItemValue = getItemValueFromBrowserStorage(memoryItem);
// the storage item has been removed, put back from memory object
if (typeof storageItemValue === 'undefined') {
saveItemToBrowserStorage(memoryItem);
}
});
} | javascript | function restoreManuallyRemovedItems(cbsConfigFromLS) {
cbsConfigFromLS[browser_storage_config_1.browserStorageConfig.DB_INITIAL_KEY].map(function (memoryItem) {
var storageItemValue = getItemValueFromBrowserStorage(memoryItem);
// the storage item has been removed, put back from memory object
if (typeof storageItemValue === 'undefined') {
saveItemToBrowserStorage(memoryItem);
}
});
} | [
"function",
"restoreManuallyRemovedItems",
"(",
"cbsConfigFromLS",
")",
"{",
"cbsConfigFromLS",
"[",
"browser_storage_config_1",
".",
"browserStorageConfig",
".",
"DB_INITIAL_KEY",
"]",
".",
"map",
"(",
"function",
"(",
"memoryItem",
")",
"{",
"var",
"storageItemValue",
"=",
"getItemValueFromBrowserStorage",
"(",
"memoryItem",
")",
";",
"// the storage item has been removed, put back from memory object",
"if",
"(",
"typeof",
"storageItemValue",
"===",
"'undefined'",
")",
"{",
"saveItemToBrowserStorage",
"(",
"memoryItem",
")",
";",
"}",
"}",
")",
";",
"}"
] | if an item has been manually removed from browser storage, restore it | [
"if",
"an",
"item",
"has",
"been",
"manually",
"removed",
"from",
"browser",
"storage",
"restore",
"it"
] | 7186096797957de62649bbb832a7c6b7d463d861 | https://github.com/calleboketoft/ng2-browser-storage/blob/7186096797957de62649bbb832a7c6b7d463d861/src/browser-storage/services/browser-storage.util.js#L75-L83 |
50,633 | blueflag/immutable-math | lib/transformations.js | percentBy | function percentBy(valueMapper) {
var valueSetter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return function (input) {
if (input.isEmpty()) {
return input;
}
var percents = input.map(valueMapper).update(percent());
if (!valueSetter) {
return percents;
}
return input.map(function (item, kk, iter) {
var value = percents.get(kk);
return valueSetter(item, value, kk, iter);
});
};
} | javascript | function percentBy(valueMapper) {
var valueSetter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
return function (input) {
if (input.isEmpty()) {
return input;
}
var percents = input.map(valueMapper).update(percent());
if (!valueSetter) {
return percents;
}
return input.map(function (item, kk, iter) {
var value = percents.get(kk);
return valueSetter(item, value, kk, iter);
});
};
} | [
"function",
"percentBy",
"(",
"valueMapper",
")",
"{",
"var",
"valueSetter",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"null",
";",
"return",
"function",
"(",
"input",
")",
"{",
"if",
"(",
"input",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"input",
";",
"}",
"var",
"percents",
"=",
"input",
".",
"map",
"(",
"valueMapper",
")",
".",
"update",
"(",
"percent",
"(",
")",
")",
";",
"if",
"(",
"!",
"valueSetter",
")",
"{",
"return",
"percents",
";",
"}",
"return",
"input",
".",
"map",
"(",
"function",
"(",
"item",
",",
"kk",
",",
"iter",
")",
"{",
"var",
"value",
"=",
"percents",
".",
"get",
"(",
"kk",
")",
";",
"return",
"valueSetter",
"(",
"item",
",",
"value",
",",
"kk",
",",
"iter",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Like `percent`, but also accepts a `valueMapper` function which allows you to process child properties.
@param {ValueMapper} valueMapper
@param {ValueSetter} valueSetter
@return {InputFunction} | [
"Like",
"percent",
"but",
"also",
"accepts",
"a",
"valueMapper",
"function",
"which",
"allows",
"you",
"to",
"process",
"child",
"properties",
"."
] | 64aba91517ce6836e0a3ebec2ba2b248408140f3 | https://github.com/blueflag/immutable-math/blob/64aba91517ce6836e0a3ebec2ba2b248408140f3/lib/transformations.js#L39-L56 |
50,634 | jamespdlynn/microjs | examples/game/lib/model/player.js | function(deltaTime){
var currentTime = new Date().getTime();
deltaTime = deltaTime || currentTime-this.lastUpdated;
//Ignore minor updates
if (deltaTime < 5){
return this;
}
deltaTime /= 1000; //convert to seconds
//Calculate deltas based on how much time has passed since last update
var data = this.attributes;
if (data.isAccelerating){
var deltaVelocity = this.ACCELERATION * deltaTime;
var deltaTime1 = 0;
//Calculate new velocities
var newVelocityX = data.velocityX + (Math.cos(data.angle) * deltaVelocity);
var newVelocityY = data.velocityY + (Math.sin(data.angle) * deltaVelocity);
//If velocities exceed maximums, we have to do some additional logic to calculate new positions
if (newVelocityX > this.MAX_VELOCITY_X || newVelocityX < -this.MAX_VELOCITY_X){
newVelocityX = (newVelocityX > 0) ? this.MAX_VELOCITY_X : -this.MAX_VELOCITY_X;
deltaTime1 = getTime(data.velocityX, newVelocityX, this.ACCELERATION);
data.posX += getDistance(data.velocityX, newVelocityX, deltaTime1) + (newVelocityX*(deltaTime-deltaTime1));
}
else{
data.posX += getDistance(data.velocityX, newVelocityX, deltaTime);
}
if (newVelocityY > this.MAX_VELOCITY_Y || newVelocityY < -this.MAX_VELOCITY_Y){
newVelocityY = (newVelocityY > 0) ? this.MAX_VELOCITY_Y : -this.MAX_VELOCITY_Y;
deltaTime1 = getTime(data.velocityY, newVelocityY, this.ACCELERATION);
data.posY += getDistance(data.velocityY, newVelocityY, deltaTime1) + (newVelocityY*(deltaTime-deltaTime1));
}else{
data.posY += getDistance(data.velocityY, newVelocityY, deltaTime);
}
data.velocityX = newVelocityX;
data.velocityY = newVelocityY;
}
else{
data.posX += data.velocityX * deltaTime;
data.posY += data.velocityY * deltaTime;
}
//Check to see if player has exceeded zone boundary, in which case send them to opposite side
var radius = this.SIZE/2;
var maxPosX = Constants.Zone.WIDTH+radius;
var maxPosY = Constants.Zone.HEIGHT+radius;
while (data.posX > maxPosX) data.posX -= maxPosX+radius;
while (data.posX < -radius) data.posX += maxPosX+radius;
while (data.posY > maxPosY) data.posY -= maxPosY+radius;
while (data.posY < -radius) data.posY += maxPosY+radius;
//Update last updated timestamp
this.lastUpdated = currentTime;
return this;
} | javascript | function(deltaTime){
var currentTime = new Date().getTime();
deltaTime = deltaTime || currentTime-this.lastUpdated;
//Ignore minor updates
if (deltaTime < 5){
return this;
}
deltaTime /= 1000; //convert to seconds
//Calculate deltas based on how much time has passed since last update
var data = this.attributes;
if (data.isAccelerating){
var deltaVelocity = this.ACCELERATION * deltaTime;
var deltaTime1 = 0;
//Calculate new velocities
var newVelocityX = data.velocityX + (Math.cos(data.angle) * deltaVelocity);
var newVelocityY = data.velocityY + (Math.sin(data.angle) * deltaVelocity);
//If velocities exceed maximums, we have to do some additional logic to calculate new positions
if (newVelocityX > this.MAX_VELOCITY_X || newVelocityX < -this.MAX_VELOCITY_X){
newVelocityX = (newVelocityX > 0) ? this.MAX_VELOCITY_X : -this.MAX_VELOCITY_X;
deltaTime1 = getTime(data.velocityX, newVelocityX, this.ACCELERATION);
data.posX += getDistance(data.velocityX, newVelocityX, deltaTime1) + (newVelocityX*(deltaTime-deltaTime1));
}
else{
data.posX += getDistance(data.velocityX, newVelocityX, deltaTime);
}
if (newVelocityY > this.MAX_VELOCITY_Y || newVelocityY < -this.MAX_VELOCITY_Y){
newVelocityY = (newVelocityY > 0) ? this.MAX_VELOCITY_Y : -this.MAX_VELOCITY_Y;
deltaTime1 = getTime(data.velocityY, newVelocityY, this.ACCELERATION);
data.posY += getDistance(data.velocityY, newVelocityY, deltaTime1) + (newVelocityY*(deltaTime-deltaTime1));
}else{
data.posY += getDistance(data.velocityY, newVelocityY, deltaTime);
}
data.velocityX = newVelocityX;
data.velocityY = newVelocityY;
}
else{
data.posX += data.velocityX * deltaTime;
data.posY += data.velocityY * deltaTime;
}
//Check to see if player has exceeded zone boundary, in which case send them to opposite side
var radius = this.SIZE/2;
var maxPosX = Constants.Zone.WIDTH+radius;
var maxPosY = Constants.Zone.HEIGHT+radius;
while (data.posX > maxPosX) data.posX -= maxPosX+radius;
while (data.posX < -radius) data.posX += maxPosX+radius;
while (data.posY > maxPosY) data.posY -= maxPosY+radius;
while (data.posY < -radius) data.posY += maxPosY+radius;
//Update last updated timestamp
this.lastUpdated = currentTime;
return this;
} | [
"function",
"(",
"deltaTime",
")",
"{",
"var",
"currentTime",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"deltaTime",
"=",
"deltaTime",
"||",
"currentTime",
"-",
"this",
".",
"lastUpdated",
";",
"//Ignore minor updates",
"if",
"(",
"deltaTime",
"<",
"5",
")",
"{",
"return",
"this",
";",
"}",
"deltaTime",
"/=",
"1000",
";",
"//convert to seconds",
"//Calculate deltas based on how much time has passed since last update",
"var",
"data",
"=",
"this",
".",
"attributes",
";",
"if",
"(",
"data",
".",
"isAccelerating",
")",
"{",
"var",
"deltaVelocity",
"=",
"this",
".",
"ACCELERATION",
"*",
"deltaTime",
";",
"var",
"deltaTime1",
"=",
"0",
";",
"//Calculate new velocities",
"var",
"newVelocityX",
"=",
"data",
".",
"velocityX",
"+",
"(",
"Math",
".",
"cos",
"(",
"data",
".",
"angle",
")",
"*",
"deltaVelocity",
")",
";",
"var",
"newVelocityY",
"=",
"data",
".",
"velocityY",
"+",
"(",
"Math",
".",
"sin",
"(",
"data",
".",
"angle",
")",
"*",
"deltaVelocity",
")",
";",
"//If velocities exceed maximums, we have to do some additional logic to calculate new positions",
"if",
"(",
"newVelocityX",
">",
"this",
".",
"MAX_VELOCITY_X",
"||",
"newVelocityX",
"<",
"-",
"this",
".",
"MAX_VELOCITY_X",
")",
"{",
"newVelocityX",
"=",
"(",
"newVelocityX",
">",
"0",
")",
"?",
"this",
".",
"MAX_VELOCITY_X",
":",
"-",
"this",
".",
"MAX_VELOCITY_X",
";",
"deltaTime1",
"=",
"getTime",
"(",
"data",
".",
"velocityX",
",",
"newVelocityX",
",",
"this",
".",
"ACCELERATION",
")",
";",
"data",
".",
"posX",
"+=",
"getDistance",
"(",
"data",
".",
"velocityX",
",",
"newVelocityX",
",",
"deltaTime1",
")",
"+",
"(",
"newVelocityX",
"*",
"(",
"deltaTime",
"-",
"deltaTime1",
")",
")",
";",
"}",
"else",
"{",
"data",
".",
"posX",
"+=",
"getDistance",
"(",
"data",
".",
"velocityX",
",",
"newVelocityX",
",",
"deltaTime",
")",
";",
"}",
"if",
"(",
"newVelocityY",
">",
"this",
".",
"MAX_VELOCITY_Y",
"||",
"newVelocityY",
"<",
"-",
"this",
".",
"MAX_VELOCITY_Y",
")",
"{",
"newVelocityY",
"=",
"(",
"newVelocityY",
">",
"0",
")",
"?",
"this",
".",
"MAX_VELOCITY_Y",
":",
"-",
"this",
".",
"MAX_VELOCITY_Y",
";",
"deltaTime1",
"=",
"getTime",
"(",
"data",
".",
"velocityY",
",",
"newVelocityY",
",",
"this",
".",
"ACCELERATION",
")",
";",
"data",
".",
"posY",
"+=",
"getDistance",
"(",
"data",
".",
"velocityY",
",",
"newVelocityY",
",",
"deltaTime1",
")",
"+",
"(",
"newVelocityY",
"*",
"(",
"deltaTime",
"-",
"deltaTime1",
")",
")",
";",
"}",
"else",
"{",
"data",
".",
"posY",
"+=",
"getDistance",
"(",
"data",
".",
"velocityY",
",",
"newVelocityY",
",",
"deltaTime",
")",
";",
"}",
"data",
".",
"velocityX",
"=",
"newVelocityX",
";",
"data",
".",
"velocityY",
"=",
"newVelocityY",
";",
"}",
"else",
"{",
"data",
".",
"posX",
"+=",
"data",
".",
"velocityX",
"*",
"deltaTime",
";",
"data",
".",
"posY",
"+=",
"data",
".",
"velocityY",
"*",
"deltaTime",
";",
"}",
"//Check to see if player has exceeded zone boundary, in which case send them to opposite side",
"var",
"radius",
"=",
"this",
".",
"SIZE",
"/",
"2",
";",
"var",
"maxPosX",
"=",
"Constants",
".",
"Zone",
".",
"WIDTH",
"+",
"radius",
";",
"var",
"maxPosY",
"=",
"Constants",
".",
"Zone",
".",
"HEIGHT",
"+",
"radius",
";",
"while",
"(",
"data",
".",
"posX",
">",
"maxPosX",
")",
"data",
".",
"posX",
"-=",
"maxPosX",
"+",
"radius",
";",
"while",
"(",
"data",
".",
"posX",
"<",
"-",
"radius",
")",
"data",
".",
"posX",
"+=",
"maxPosX",
"+",
"radius",
";",
"while",
"(",
"data",
".",
"posY",
">",
"maxPosY",
")",
"data",
".",
"posY",
"-=",
"maxPosY",
"+",
"radius",
";",
"while",
"(",
"data",
".",
"posY",
"<",
"-",
"radius",
")",
"data",
".",
"posY",
"+=",
"maxPosY",
"+",
"radius",
";",
"//Update last updated timestamp",
"this",
".",
"lastUpdated",
"=",
"currentTime",
";",
"return",
"this",
";",
"}"
] | Updates this player's velocity and position values
@param {number} [deltaTime] Time interval in milliseconds (by default uses the amount of time since function last called)
@returns {*} | [
"Updates",
"this",
"player",
"s",
"velocity",
"and",
"position",
"values"
] | 780a4074de84bcd74e3ae50d0ed64144b4474166 | https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/model/player.js#L73-L140 |
|
50,635 | jamespdlynn/microjs | examples/game/lib/model/player.js | function(posX, posY){
//Calculate the position deltas while account for zone boundaries
var zoneWidth = Constants.Zone.WIDTH;
var zoneHeight = Constants.Zone.HEIGHT;
var deltaX = posX - this.get("posX");
if (Math.abs(deltaX) > zoneWidth/2){
(posX < zoneWidth/2) ? deltaX += zoneWidth : deltaX -= zoneWidth;
}
var deltaY = posY - this.get("posY");
if (Math.abs(deltaY) > zoneHeight/2){
(posY < zoneHeight/2) ? deltaY += zoneHeight : deltaY -= zoneHeight;
}
var data = this.attributes;
//Update the velocities to move to the correct position by the next update
var interval = Constants.UPDATE_INTERVAL/1000;
data.velocityX += deltaX / interval;
data.velocityY += deltaY / interval;
//If these changes take us over the maximum velocities, update the constants to allow for it
this.MAX_VELOCITY_X = Math.max(data.velocityX, Constants.Player.MAX_VELOCITY_X);
this.MAX_VELOCITY_Y = Math.max(data.velocityY, Constants.Player.MAX_VELOCITY_Y);
return this;
} | javascript | function(posX, posY){
//Calculate the position deltas while account for zone boundaries
var zoneWidth = Constants.Zone.WIDTH;
var zoneHeight = Constants.Zone.HEIGHT;
var deltaX = posX - this.get("posX");
if (Math.abs(deltaX) > zoneWidth/2){
(posX < zoneWidth/2) ? deltaX += zoneWidth : deltaX -= zoneWidth;
}
var deltaY = posY - this.get("posY");
if (Math.abs(deltaY) > zoneHeight/2){
(posY < zoneHeight/2) ? deltaY += zoneHeight : deltaY -= zoneHeight;
}
var data = this.attributes;
//Update the velocities to move to the correct position by the next update
var interval = Constants.UPDATE_INTERVAL/1000;
data.velocityX += deltaX / interval;
data.velocityY += deltaY / interval;
//If these changes take us over the maximum velocities, update the constants to allow for it
this.MAX_VELOCITY_X = Math.max(data.velocityX, Constants.Player.MAX_VELOCITY_X);
this.MAX_VELOCITY_Y = Math.max(data.velocityY, Constants.Player.MAX_VELOCITY_Y);
return this;
} | [
"function",
"(",
"posX",
",",
"posY",
")",
"{",
"//Calculate the position deltas while account for zone boundaries",
"var",
"zoneWidth",
"=",
"Constants",
".",
"Zone",
".",
"WIDTH",
";",
"var",
"zoneHeight",
"=",
"Constants",
".",
"Zone",
".",
"HEIGHT",
";",
"var",
"deltaX",
"=",
"posX",
"-",
"this",
".",
"get",
"(",
"\"posX\"",
")",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"deltaX",
")",
">",
"zoneWidth",
"/",
"2",
")",
"{",
"(",
"posX",
"<",
"zoneWidth",
"/",
"2",
")",
"?",
"deltaX",
"+=",
"zoneWidth",
":",
"deltaX",
"-=",
"zoneWidth",
";",
"}",
"var",
"deltaY",
"=",
"posY",
"-",
"this",
".",
"get",
"(",
"\"posY\"",
")",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"deltaY",
")",
">",
"zoneHeight",
"/",
"2",
")",
"{",
"(",
"posY",
"<",
"zoneHeight",
"/",
"2",
")",
"?",
"deltaY",
"+=",
"zoneHeight",
":",
"deltaY",
"-=",
"zoneHeight",
";",
"}",
"var",
"data",
"=",
"this",
".",
"attributes",
";",
"//Update the velocities to move to the correct position by the next update",
"var",
"interval",
"=",
"Constants",
".",
"UPDATE_INTERVAL",
"/",
"1000",
";",
"data",
".",
"velocityX",
"+=",
"deltaX",
"/",
"interval",
";",
"data",
".",
"velocityY",
"+=",
"deltaY",
"/",
"interval",
";",
"//If these changes take us over the maximum velocities, update the constants to allow for it",
"this",
".",
"MAX_VELOCITY_X",
"=",
"Math",
".",
"max",
"(",
"data",
".",
"velocityX",
",",
"Constants",
".",
"Player",
".",
"MAX_VELOCITY_X",
")",
";",
"this",
".",
"MAX_VELOCITY_Y",
"=",
"Math",
".",
"max",
"(",
"data",
".",
"velocityY",
",",
"Constants",
".",
"Player",
".",
"MAX_VELOCITY_Y",
")",
";",
"return",
"this",
";",
"}"
] | Ease a player to a new position, by adding an auxiliary angle and velocity to update by.
This function can serve as a "dead reckoning algorithm" to smooth difference between positions on the client and server
@param {number} posX
@param {number} posY
@returns {*} | [
"Ease",
"a",
"player",
"to",
"a",
"new",
"position",
"by",
"adding",
"an",
"auxiliary",
"angle",
"and",
"velocity",
"to",
"update",
"by",
".",
"This",
"function",
"can",
"serve",
"as",
"a",
"dead",
"reckoning",
"algorithm",
"to",
"smooth",
"difference",
"between",
"positions",
"on",
"the",
"client",
"and",
"server"
] | 780a4074de84bcd74e3ae50d0ed64144b4474166 | https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/model/player.js#L149-L177 |
|
50,636 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | readFileSync | function readFileSync (fileName, options) {
verifyFileName (fileName);
var info = getFileInfo (fileName);
if (info.exists === false) {
var message1 = format (cc.MSG_DOES_NOT_EXIST, fileName);
throw new SafeFileError (cc.DOES_NOT_EXIST, message1);
}
if (info.isFile === false) {
var message2 = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message2);
}
// read data file
var data = null;
try {
data = fs.readFileSync (fileName, options);
} catch (e) {
var message3 = format (cc.MSG_READ_ERROR, fileName, e.message);
throw new SafeFileError (cc.READ_ERROR, message3);
}
// return data
return (data);
} | javascript | function readFileSync (fileName, options) {
verifyFileName (fileName);
var info = getFileInfo (fileName);
if (info.exists === false) {
var message1 = format (cc.MSG_DOES_NOT_EXIST, fileName);
throw new SafeFileError (cc.DOES_NOT_EXIST, message1);
}
if (info.isFile === false) {
var message2 = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message2);
}
// read data file
var data = null;
try {
data = fs.readFileSync (fileName, options);
} catch (e) {
var message3 = format (cc.MSG_READ_ERROR, fileName, e.message);
throw new SafeFileError (cc.READ_ERROR, message3);
}
// return data
return (data);
} | [
"function",
"readFileSync",
"(",
"fileName",
",",
"options",
")",
"{",
"verifyFileName",
"(",
"fileName",
")",
";",
"var",
"info",
"=",
"getFileInfo",
"(",
"fileName",
")",
";",
"if",
"(",
"info",
".",
"exists",
"===",
"false",
")",
"{",
"var",
"message1",
"=",
"format",
"(",
"cc",
".",
"MSG_DOES_NOT_EXIST",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"DOES_NOT_EXIST",
",",
"message1",
")",
";",
"}",
"if",
"(",
"info",
".",
"isFile",
"===",
"false",
")",
"{",
"var",
"message2",
"=",
"format",
"(",
"cc",
".",
"MSG_IS_NOT_A_FILE",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"IS_NOT_A_FILE",
",",
"message2",
")",
";",
"}",
"// read data file",
"var",
"data",
"=",
"null",
";",
"try",
"{",
"data",
"=",
"fs",
".",
"readFileSync",
"(",
"fileName",
",",
"options",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"message3",
"=",
"format",
"(",
"cc",
".",
"MSG_READ_ERROR",
",",
"fileName",
",",
"e",
".",
"message",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"READ_ERROR",
",",
"message3",
")",
";",
"}",
"// return data",
"return",
"(",
"data",
")",
";",
"}"
] | Read file.
@param {String} fileName File to read.
@returns {String} Data read from file.
@throws SafeFileError | [
"Read",
"file",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L23-L47 |
50,637 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | writeFileSync | function writeFileSync (fileName, data, options) {
verifyFileName (fileName);
var info = getFileInfo (fileName);
if ((info.exists === true) && (info.isFile === false)) {
var message1 = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message1);
}
// if content undefined or null, set data to empty string
if ((data === undefined) || (data === null)) {
data = "";
}
// write file content, throwing exception on error occurring
try {
fs.writeFileSync (fileName, data, options);
} catch (e) {
var message2 = format (cc.MSG_WRITE_ERROR, e.message);
throw new SafeFileError (cc.WRITE_ERROR, message2);
}
} | javascript | function writeFileSync (fileName, data, options) {
verifyFileName (fileName);
var info = getFileInfo (fileName);
if ((info.exists === true) && (info.isFile === false)) {
var message1 = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message1);
}
// if content undefined or null, set data to empty string
if ((data === undefined) || (data === null)) {
data = "";
}
// write file content, throwing exception on error occurring
try {
fs.writeFileSync (fileName, data, options);
} catch (e) {
var message2 = format (cc.MSG_WRITE_ERROR, e.message);
throw new SafeFileError (cc.WRITE_ERROR, message2);
}
} | [
"function",
"writeFileSync",
"(",
"fileName",
",",
"data",
",",
"options",
")",
"{",
"verifyFileName",
"(",
"fileName",
")",
";",
"var",
"info",
"=",
"getFileInfo",
"(",
"fileName",
")",
";",
"if",
"(",
"(",
"info",
".",
"exists",
"===",
"true",
")",
"&&",
"(",
"info",
".",
"isFile",
"===",
"false",
")",
")",
"{",
"var",
"message1",
"=",
"format",
"(",
"cc",
".",
"MSG_IS_NOT_A_FILE",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"IS_NOT_A_FILE",
",",
"message1",
")",
";",
"}",
"// if content undefined or null, set data to empty string",
"if",
"(",
"(",
"data",
"===",
"undefined",
")",
"||",
"(",
"data",
"===",
"null",
")",
")",
"{",
"data",
"=",
"\"\"",
";",
"}",
"// write file content, throwing exception on error occurring",
"try",
"{",
"fs",
".",
"writeFileSync",
"(",
"fileName",
",",
"data",
",",
"options",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"var",
"message2",
"=",
"format",
"(",
"cc",
".",
"MSG_WRITE_ERROR",
",",
"e",
".",
"message",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"WRITE_ERROR",
",",
"message2",
")",
";",
"}",
"}"
] | Write data to a file.
@param {String} fileName Name of file (path optional).
@param {String} data Data to write.
@throws SafeFileError | [
"Write",
"data",
"to",
"a",
"file",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L55-L76 |
50,638 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | safeGetState | function safeGetState (fileName) {
if ((fileName === undefined) || (fileName === null)) {
return (cc.INVALID_NAME);
}
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
return (cc.IS_NOT_A_FILE);
}
var state = getState (fileName);
return (state.status);
} | javascript | function safeGetState (fileName) {
if ((fileName === undefined) || (fileName === null)) {
return (cc.INVALID_NAME);
}
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
return (cc.IS_NOT_A_FILE);
}
var state = getState (fileName);
return (state.status);
} | [
"function",
"safeGetState",
"(",
"fileName",
")",
"{",
"if",
"(",
"(",
"fileName",
"===",
"undefined",
")",
"||",
"(",
"fileName",
"===",
"null",
")",
")",
"{",
"return",
"(",
"cc",
".",
"INVALID_NAME",
")",
";",
"}",
"// if fileName exists, verify it is a file",
"var",
"info",
"=",
"getFileInfo",
"(",
"fileName",
")",
";",
"if",
"(",
"(",
"info",
".",
"exists",
")",
"&&",
"(",
"info",
".",
"isFile",
"===",
"false",
")",
")",
"{",
"return",
"(",
"cc",
".",
"IS_NOT_A_FILE",
")",
";",
"}",
"var",
"state",
"=",
"getState",
"(",
"fileName",
")",
";",
"return",
"(",
"state",
".",
"status",
")",
";",
"}"
] | Get status of the file.
@param {String} file Name of base file.
@returns {Integer} SAFE_NORMAL, SAFE_AUTO_RECOVERABLE, SAFE_INTERVENE,
INVALID_NAME, IS_NOT_A_FILE, or DOES_NOT_EXIST | [
"Get",
"status",
"of",
"the",
"file",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L84-L96 |
50,639 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | safeRecover | function safeRecover (fileName) {
verifyFileName (fileName);
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
var message1 = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message1);
}
// get state, if doesn't exist throw error
var state = getState (fileName);
if (state.status === cc.DOES_NOT_EXIST) {
var message2 = format (cc.MSG_DOES_NOT_EXIST, fileName);
throw new SafeFileError (cc.DOES_NOT_EXIST, message2);
}
performRecovery (state, true);
} | javascript | function safeRecover (fileName) {
verifyFileName (fileName);
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
var message1 = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message1);
}
// get state, if doesn't exist throw error
var state = getState (fileName);
if (state.status === cc.DOES_NOT_EXIST) {
var message2 = format (cc.MSG_DOES_NOT_EXIST, fileName);
throw new SafeFileError (cc.DOES_NOT_EXIST, message2);
}
performRecovery (state, true);
} | [
"function",
"safeRecover",
"(",
"fileName",
")",
"{",
"verifyFileName",
"(",
"fileName",
")",
";",
"// if fileName exists, verify it is a file",
"var",
"info",
"=",
"getFileInfo",
"(",
"fileName",
")",
";",
"if",
"(",
"(",
"info",
".",
"exists",
")",
"&&",
"(",
"info",
".",
"isFile",
"===",
"false",
")",
")",
"{",
"var",
"message1",
"=",
"format",
"(",
"cc",
".",
"MSG_IS_NOT_A_FILE",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"IS_NOT_A_FILE",
",",
"message1",
")",
";",
"}",
"// get state, if doesn't exist throw error",
"var",
"state",
"=",
"getState",
"(",
"fileName",
")",
";",
"if",
"(",
"state",
".",
"status",
"===",
"cc",
".",
"DOES_NOT_EXIST",
")",
"{",
"var",
"message2",
"=",
"format",
"(",
"cc",
".",
"MSG_DOES_NOT_EXIST",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"DOES_NOT_EXIST",
",",
"message2",
")",
";",
"}",
"performRecovery",
"(",
"state",
",",
"true",
")",
";",
"}"
] | Initiate auto-recovery processing.
@param {String} fileName Name of base file
@throws SafeFileError | [
"Initiate",
"auto",
"-",
"recovery",
"processing",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L103-L121 |
50,640 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | safeReadFileSync | function safeReadFileSync (fileName, options) {
verifyFileName (fileName);
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
var message = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message);
}
// get state, if auto-recovery required, perform recovery
var state = getState (fileName);
if (state.status === cc.SAFE_RECOVERABLE) {
performRecovery (state, true);
}
// perform read on file
return (readFileSync (fileName, options));
} | javascript | function safeReadFileSync (fileName, options) {
verifyFileName (fileName);
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
var message = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message);
}
// get state, if auto-recovery required, perform recovery
var state = getState (fileName);
if (state.status === cc.SAFE_RECOVERABLE) {
performRecovery (state, true);
}
// perform read on file
return (readFileSync (fileName, options));
} | [
"function",
"safeReadFileSync",
"(",
"fileName",
",",
"options",
")",
"{",
"verifyFileName",
"(",
"fileName",
")",
";",
"// if fileName exists, verify it is a file",
"var",
"info",
"=",
"getFileInfo",
"(",
"fileName",
")",
";",
"if",
"(",
"(",
"info",
".",
"exists",
")",
"&&",
"(",
"info",
".",
"isFile",
"===",
"false",
")",
")",
"{",
"var",
"message",
"=",
"format",
"(",
"cc",
".",
"MSG_IS_NOT_A_FILE",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"IS_NOT_A_FILE",
",",
"message",
")",
";",
"}",
"// get state, if auto-recovery required, perform recovery",
"var",
"state",
"=",
"getState",
"(",
"fileName",
")",
";",
"if",
"(",
"state",
".",
"status",
"===",
"cc",
".",
"SAFE_RECOVERABLE",
")",
"{",
"performRecovery",
"(",
"state",
",",
"true",
")",
";",
"}",
"// perform read on file",
"return",
"(",
"readFileSync",
"(",
"fileName",
",",
"options",
")",
")",
";",
"}"
] | Read a file, performing recovery processing if necessary.
@param {String} file File to read.
@returns {String} Data read from file.
@throws SafeFileError | [
"Read",
"a",
"file",
"performing",
"recovery",
"processing",
"if",
"necessary",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L129-L147 |
50,641 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | safeWriteFileSync | function safeWriteFileSync (fileName, data, options) {
verifyFileName (fileName);
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
var message = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message);
}
// get current file system state, and auto-recover if necessary
var state = getState (fileName);
// store data in well defined ephemeral file to allow manual recovery
// If file already exists, remove it (failed prior recovery).
if (state.ephemeral.exists) {
fs.unlinkSync (state.ephemeral.name);
}
writeFileSync (state.ephemeral.name, data, options);
state.ephemeral.exists = true;
// if ready state file already exists, recover prior state
if (state.ready.exists) {
performRecovery (state, false);
}
fs.renameSync (state.ephemeral.name, state.ready.name);
// refresh state and process recovery to set file system state
state = getState (fileName);
performRecovery (state, true);
} | javascript | function safeWriteFileSync (fileName, data, options) {
verifyFileName (fileName);
// if fileName exists, verify it is a file
var info = getFileInfo (fileName);
if ((info.exists) && (info.isFile === false)) {
var message = format (cc.MSG_IS_NOT_A_FILE, fileName);
throw new SafeFileError (cc.IS_NOT_A_FILE, message);
}
// get current file system state, and auto-recover if necessary
var state = getState (fileName);
// store data in well defined ephemeral file to allow manual recovery
// If file already exists, remove it (failed prior recovery).
if (state.ephemeral.exists) {
fs.unlinkSync (state.ephemeral.name);
}
writeFileSync (state.ephemeral.name, data, options);
state.ephemeral.exists = true;
// if ready state file already exists, recover prior state
if (state.ready.exists) {
performRecovery (state, false);
}
fs.renameSync (state.ephemeral.name, state.ready.name);
// refresh state and process recovery to set file system state
state = getState (fileName);
performRecovery (state, true);
} | [
"function",
"safeWriteFileSync",
"(",
"fileName",
",",
"data",
",",
"options",
")",
"{",
"verifyFileName",
"(",
"fileName",
")",
";",
"// if fileName exists, verify it is a file",
"var",
"info",
"=",
"getFileInfo",
"(",
"fileName",
")",
";",
"if",
"(",
"(",
"info",
".",
"exists",
")",
"&&",
"(",
"info",
".",
"isFile",
"===",
"false",
")",
")",
"{",
"var",
"message",
"=",
"format",
"(",
"cc",
".",
"MSG_IS_NOT_A_FILE",
",",
"fileName",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"IS_NOT_A_FILE",
",",
"message",
")",
";",
"}",
"// get current file system state, and auto-recover if necessary",
"var",
"state",
"=",
"getState",
"(",
"fileName",
")",
";",
"// store data in well defined ephemeral file to allow manual recovery",
"// If file already exists, remove it (failed prior recovery).",
"if",
"(",
"state",
".",
"ephemeral",
".",
"exists",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"state",
".",
"ephemeral",
".",
"name",
")",
";",
"}",
"writeFileSync",
"(",
"state",
".",
"ephemeral",
".",
"name",
",",
"data",
",",
"options",
")",
";",
"state",
".",
"ephemeral",
".",
"exists",
"=",
"true",
";",
"// if ready state file already exists, recover prior state",
"if",
"(",
"state",
".",
"ready",
".",
"exists",
")",
"{",
"performRecovery",
"(",
"state",
",",
"false",
")",
";",
"}",
"fs",
".",
"renameSync",
"(",
"state",
".",
"ephemeral",
".",
"name",
",",
"state",
".",
"ready",
".",
"name",
")",
";",
"// refresh state and process recovery to set file system state",
"state",
"=",
"getState",
"(",
"fileName",
")",
";",
"performRecovery",
"(",
"state",
",",
"true",
")",
";",
"}"
] | Write data to a file using a recoverable process.
@param {String} fileName Name of file (path optional).
@param {String} data Data to write.
@throws SafeFileError | [
"Write",
"data",
"to",
"a",
"file",
"using",
"a",
"recoverable",
"process",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L155-L187 |
50,642 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | verifyFileName | function verifyFileName (fileName)
{
// if fileName undefined or null, throw exception
if ((fileName === undefined) || (fileName === null)) {
var message1 = format (cc.MSG_INVALID_NAME);
throw new SafeFileError (cc.INVALID_NAME, message1);
}
} | javascript | function verifyFileName (fileName)
{
// if fileName undefined or null, throw exception
if ((fileName === undefined) || (fileName === null)) {
var message1 = format (cc.MSG_INVALID_NAME);
throw new SafeFileError (cc.INVALID_NAME, message1);
}
} | [
"function",
"verifyFileName",
"(",
"fileName",
")",
"{",
"// if fileName undefined or null, throw exception",
"if",
"(",
"(",
"fileName",
"===",
"undefined",
")",
"||",
"(",
"fileName",
"===",
"null",
")",
")",
"{",
"var",
"message1",
"=",
"format",
"(",
"cc",
".",
"MSG_INVALID_NAME",
")",
";",
"throw",
"new",
"SafeFileError",
"(",
"cc",
".",
"INVALID_NAME",
",",
"message1",
")",
";",
"}",
"}"
] | Verify fileName parameter.
@param {String} fileName Name of file to verify.
@throws SafeFileError | [
"Verify",
"fileName",
"parameter",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L194-L201 |
50,643 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | getState | function getState (file) {
// collect state for all possible data and recovery files
var state = {};
state.ephemeral = getFileInfo (file + ".eph");
state.ready = getFileInfo (file + ".rdy");
state.base = getFileInfo (file);
state.backup = getFileInfo (file + ".bak");
state.tertiary = getFileInfo (file + ".bk2");
if (state.ephemeral.exists) {
state.status = cc.SAFE_INTERVENE;
} else if ((state.ready.exists) || (state.tertiary.exists)) {
state.status = cc.SAFE_RECOVERABLE;
} else if (state.base.exists) {
state.status = cc.SAFE_NORMAL;
} else {
if (state.backup.exists) {
state.status = cc.SAFE_RECOVERABLE;
} else {
state.status = cc.DOES_NOT_EXIST;
}
}
return (state);
} | javascript | function getState (file) {
// collect state for all possible data and recovery files
var state = {};
state.ephemeral = getFileInfo (file + ".eph");
state.ready = getFileInfo (file + ".rdy");
state.base = getFileInfo (file);
state.backup = getFileInfo (file + ".bak");
state.tertiary = getFileInfo (file + ".bk2");
if (state.ephemeral.exists) {
state.status = cc.SAFE_INTERVENE;
} else if ((state.ready.exists) || (state.tertiary.exists)) {
state.status = cc.SAFE_RECOVERABLE;
} else if (state.base.exists) {
state.status = cc.SAFE_NORMAL;
} else {
if (state.backup.exists) {
state.status = cc.SAFE_RECOVERABLE;
} else {
state.status = cc.DOES_NOT_EXIST;
}
}
return (state);
} | [
"function",
"getState",
"(",
"file",
")",
"{",
"// collect state for all possible data and recovery files",
"var",
"state",
"=",
"{",
"}",
";",
"state",
".",
"ephemeral",
"=",
"getFileInfo",
"(",
"file",
"+",
"\".eph\"",
")",
";",
"state",
".",
"ready",
"=",
"getFileInfo",
"(",
"file",
"+",
"\".rdy\"",
")",
";",
"state",
".",
"base",
"=",
"getFileInfo",
"(",
"file",
")",
";",
"state",
".",
"backup",
"=",
"getFileInfo",
"(",
"file",
"+",
"\".bak\"",
")",
";",
"state",
".",
"tertiary",
"=",
"getFileInfo",
"(",
"file",
"+",
"\".bk2\"",
")",
";",
"if",
"(",
"state",
".",
"ephemeral",
".",
"exists",
")",
"{",
"state",
".",
"status",
"=",
"cc",
".",
"SAFE_INTERVENE",
";",
"}",
"else",
"if",
"(",
"(",
"state",
".",
"ready",
".",
"exists",
")",
"||",
"(",
"state",
".",
"tertiary",
".",
"exists",
")",
")",
"{",
"state",
".",
"status",
"=",
"cc",
".",
"SAFE_RECOVERABLE",
";",
"}",
"else",
"if",
"(",
"state",
".",
"base",
".",
"exists",
")",
"{",
"state",
".",
"status",
"=",
"cc",
".",
"SAFE_NORMAL",
";",
"}",
"else",
"{",
"if",
"(",
"state",
".",
"backup",
".",
"exists",
")",
"{",
"state",
".",
"status",
"=",
"cc",
".",
"SAFE_RECOVERABLE",
";",
"}",
"else",
"{",
"state",
".",
"status",
"=",
"cc",
".",
"DOES_NOT_EXIST",
";",
"}",
"}",
"return",
"(",
"state",
")",
";",
"}"
] | Get state for file system entities.
@param {String} file Base file name.
@returns {Object} State object. | [
"Get",
"state",
"for",
"file",
"system",
"entities",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L208-L232 |
50,644 | usingjsonschema/ujs-safefile-nodejs | lib/safeFile.js | performRecovery | function performRecovery (state, removeEphemeral) {
// if ephemeral flag true, and ephemeral file exists, remove it
if ((removeEphemeral) && (state.ephemeral.exists)) {
fs.unlinkSync (state.ephemeral.name);
}
// if only backups exist, restore from backup
var baseAvailable = state.base.exists || state.ready.exists;
if (baseAvailable === false) {
if (state.tertiary.exists) {
if (state.backup.exists) {
fs.renameSync (state.backup.name, state.base.name);
fs.renameSync (state.tertiary.name, state.backup.name);
} else {
fs.renameSync (state.tertiary.name, state.base.name);
}
} else if (state.backup.exists) {
fs.renameSync (state.backup.name, state.base.name);
}
return;
}
// if tertiary state file exists, remove it
if (state.tertiary.exists) {
fs.unlinkSync (state.tertiary.name);
}
// if ready state file exists, update ready, base and backup files
if (state.ready.exists) {
var removeTertiary = false;
// if base and backup exist, rename to tertiary temporarily
if ((state.base.exists) && (state.backup.exists)) {
fs.renameSync (state.backup.name, state.tertiary.name);
removeTertiary = true;
}
// if base exists, rename to backup
if (state.base.exists) {
fs.renameSync (state.base.name, state.backup.name);
}
// place ready state file in base and delete temporary tertiary file
fs.renameSync (state.ready.name, state.base.name);
// if temporary tertiary created, remove it
if (removeTertiary) {
fs.unlinkSync (state.tertiary.name);
}
}
} | javascript | function performRecovery (state, removeEphemeral) {
// if ephemeral flag true, and ephemeral file exists, remove it
if ((removeEphemeral) && (state.ephemeral.exists)) {
fs.unlinkSync (state.ephemeral.name);
}
// if only backups exist, restore from backup
var baseAvailable = state.base.exists || state.ready.exists;
if (baseAvailable === false) {
if (state.tertiary.exists) {
if (state.backup.exists) {
fs.renameSync (state.backup.name, state.base.name);
fs.renameSync (state.tertiary.name, state.backup.name);
} else {
fs.renameSync (state.tertiary.name, state.base.name);
}
} else if (state.backup.exists) {
fs.renameSync (state.backup.name, state.base.name);
}
return;
}
// if tertiary state file exists, remove it
if (state.tertiary.exists) {
fs.unlinkSync (state.tertiary.name);
}
// if ready state file exists, update ready, base and backup files
if (state.ready.exists) {
var removeTertiary = false;
// if base and backup exist, rename to tertiary temporarily
if ((state.base.exists) && (state.backup.exists)) {
fs.renameSync (state.backup.name, state.tertiary.name);
removeTertiary = true;
}
// if base exists, rename to backup
if (state.base.exists) {
fs.renameSync (state.base.name, state.backup.name);
}
// place ready state file in base and delete temporary tertiary file
fs.renameSync (state.ready.name, state.base.name);
// if temporary tertiary created, remove it
if (removeTertiary) {
fs.unlinkSync (state.tertiary.name);
}
}
} | [
"function",
"performRecovery",
"(",
"state",
",",
"removeEphemeral",
")",
"{",
"// if ephemeral flag true, and ephemeral file exists, remove it",
"if",
"(",
"(",
"removeEphemeral",
")",
"&&",
"(",
"state",
".",
"ephemeral",
".",
"exists",
")",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"state",
".",
"ephemeral",
".",
"name",
")",
";",
"}",
"// if only backups exist, restore from backup",
"var",
"baseAvailable",
"=",
"state",
".",
"base",
".",
"exists",
"||",
"state",
".",
"ready",
".",
"exists",
";",
"if",
"(",
"baseAvailable",
"===",
"false",
")",
"{",
"if",
"(",
"state",
".",
"tertiary",
".",
"exists",
")",
"{",
"if",
"(",
"state",
".",
"backup",
".",
"exists",
")",
"{",
"fs",
".",
"renameSync",
"(",
"state",
".",
"backup",
".",
"name",
",",
"state",
".",
"base",
".",
"name",
")",
";",
"fs",
".",
"renameSync",
"(",
"state",
".",
"tertiary",
".",
"name",
",",
"state",
".",
"backup",
".",
"name",
")",
";",
"}",
"else",
"{",
"fs",
".",
"renameSync",
"(",
"state",
".",
"tertiary",
".",
"name",
",",
"state",
".",
"base",
".",
"name",
")",
";",
"}",
"}",
"else",
"if",
"(",
"state",
".",
"backup",
".",
"exists",
")",
"{",
"fs",
".",
"renameSync",
"(",
"state",
".",
"backup",
".",
"name",
",",
"state",
".",
"base",
".",
"name",
")",
";",
"}",
"return",
";",
"}",
"// if tertiary state file exists, remove it",
"if",
"(",
"state",
".",
"tertiary",
".",
"exists",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"state",
".",
"tertiary",
".",
"name",
")",
";",
"}",
"// if ready state file exists, update ready, base and backup files",
"if",
"(",
"state",
".",
"ready",
".",
"exists",
")",
"{",
"var",
"removeTertiary",
"=",
"false",
";",
"// if base and backup exist, rename to tertiary temporarily",
"if",
"(",
"(",
"state",
".",
"base",
".",
"exists",
")",
"&&",
"(",
"state",
".",
"backup",
".",
"exists",
")",
")",
"{",
"fs",
".",
"renameSync",
"(",
"state",
".",
"backup",
".",
"name",
",",
"state",
".",
"tertiary",
".",
"name",
")",
";",
"removeTertiary",
"=",
"true",
";",
"}",
"// if base exists, rename to backup",
"if",
"(",
"state",
".",
"base",
".",
"exists",
")",
"{",
"fs",
".",
"renameSync",
"(",
"state",
".",
"base",
".",
"name",
",",
"state",
".",
"backup",
".",
"name",
")",
";",
"}",
"// place ready state file in base and delete temporary tertiary file",
"fs",
".",
"renameSync",
"(",
"state",
".",
"ready",
".",
"name",
",",
"state",
".",
"base",
".",
"name",
")",
";",
"// if temporary tertiary created, remove it",
"if",
"(",
"removeTertiary",
")",
"{",
"fs",
".",
"unlinkSync",
"(",
"state",
".",
"tertiary",
".",
"name",
")",
";",
"}",
"}",
"}"
] | Evaluate save state, initiating recovery if necessary.
@param {Object} state State object with file names and existence flags | [
"Evaluate",
"save",
"state",
"initiating",
"recovery",
"if",
"necessary",
"."
] | 73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7 | https://github.com/usingjsonschema/ujs-safefile-nodejs/blob/73a50d0c74bb7c0f0b73a91312f10f7c3f78adb7/lib/safeFile.js#L260-L312 |
50,645 | SciSpike/yaktor-ui-angular1 | lib/parse.js | function (daString) {
// stop shouting
daString = daString.replace(/^([A-Z]*)$/, function (match, c) {
return (c ? c.toLowerCase() : '')
})
// prepare camels for _
daString = daString.replace(/([A-Z])/g, function (match, c) {
return (c ? '_' + c : '')
})
// convert to " "
daString = daString.replace(/(\-|_|\s)+(.)?/g, function (match, sep, c) {
return (c ? (sep ? ' ' : '') + c.toUpperCase() : '')
})
// capitalize
daString = daString.replace(/(.)/, function (match, c) {
return (c ? c.toUpperCase() : '')
})
// clean up
return daString.trim()
} | javascript | function (daString) {
// stop shouting
daString = daString.replace(/^([A-Z]*)$/, function (match, c) {
return (c ? c.toLowerCase() : '')
})
// prepare camels for _
daString = daString.replace(/([A-Z])/g, function (match, c) {
return (c ? '_' + c : '')
})
// convert to " "
daString = daString.replace(/(\-|_|\s)+(.)?/g, function (match, sep, c) {
return (c ? (sep ? ' ' : '') + c.toUpperCase() : '')
})
// capitalize
daString = daString.replace(/(.)/, function (match, c) {
return (c ? c.toUpperCase() : '')
})
// clean up
return daString.trim()
} | [
"function",
"(",
"daString",
")",
"{",
"// stop shouting",
"daString",
"=",
"daString",
".",
"replace",
"(",
"/",
"^([A-Z]*)$",
"/",
",",
"function",
"(",
"match",
",",
"c",
")",
"{",
"return",
"(",
"c",
"?",
"c",
".",
"toLowerCase",
"(",
")",
":",
"''",
")",
"}",
")",
"// prepare camels for _",
"daString",
"=",
"daString",
".",
"replace",
"(",
"/",
"([A-Z])",
"/",
"g",
",",
"function",
"(",
"match",
",",
"c",
")",
"{",
"return",
"(",
"c",
"?",
"'_'",
"+",
"c",
":",
"''",
")",
"}",
")",
"// convert to \" \"",
"daString",
"=",
"daString",
".",
"replace",
"(",
"/",
"(\\-|_|\\s)+(.)?",
"/",
"g",
",",
"function",
"(",
"match",
",",
"sep",
",",
"c",
")",
"{",
"return",
"(",
"c",
"?",
"(",
"sep",
"?",
"' '",
":",
"''",
")",
"+",
"c",
".",
"toUpperCase",
"(",
")",
":",
"''",
")",
"}",
")",
"// capitalize",
"daString",
"=",
"daString",
".",
"replace",
"(",
"/",
"(.)",
"/",
",",
"function",
"(",
"match",
",",
"c",
")",
"{",
"return",
"(",
"c",
"?",
"c",
".",
"toUpperCase",
"(",
")",
":",
"''",
")",
"}",
")",
"// clean up",
"return",
"daString",
".",
"trim",
"(",
")",
"}"
] | Generate a UI model based on a SciSpike generated state matrix. | [
"Generate",
"a",
"UI",
"model",
"based",
"on",
"a",
"SciSpike",
"generated",
"state",
"matrix",
"."
] | 35c29a18045a5f0f7eeedd3781f77a155ed5b017 | https://github.com/SciSpike/yaktor-ui-angular1/blob/35c29a18045a5f0f7eeedd3781f77a155ed5b017/lib/parse.js#L8-L27 |
|
50,646 | biggora/trinte-creator | app/bin/trinte.js | bootModel | function bootModel(trinte, schema, file) {
if (/\.js$/i.test(file)) {
var name = file.replace(/\.js$/i, '');
var modelDir = path.resolve(__dirname, '../app/models');
trinte.models[name] = require(modelDir + '/' + name)(schema);// Include the mongoose file
global[name] = trinte.models[name];
}
} | javascript | function bootModel(trinte, schema, file) {
if (/\.js$/i.test(file)) {
var name = file.replace(/\.js$/i, '');
var modelDir = path.resolve(__dirname, '../app/models');
trinte.models[name] = require(modelDir + '/' + name)(schema);// Include the mongoose file
global[name] = trinte.models[name];
}
} | [
"function",
"bootModel",
"(",
"trinte",
",",
"schema",
",",
"file",
")",
"{",
"if",
"(",
"/",
"\\.js$",
"/",
"i",
".",
"test",
"(",
"file",
")",
")",
"{",
"var",
"name",
"=",
"file",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
"i",
",",
"''",
")",
";",
"var",
"modelDir",
"=",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'../app/models'",
")",
";",
"trinte",
".",
"models",
"[",
"name",
"]",
"=",
"require",
"(",
"modelDir",
"+",
"'/'",
"+",
"name",
")",
"(",
"schema",
")",
";",
"// Include the mongoose file",
"global",
"[",
"name",
"]",
"=",
"trinte",
".",
"models",
"[",
"name",
"]",
";",
"}",
"}"
] | simplistic model support
@param {TrinteJS} trinte - trinte app descriptor.
@param {Schema} schema
@param {String} file | [
"simplistic",
"model",
"support"
] | fdd723405418967ca8a690867940863fd77e636b | https://github.com/biggora/trinte-creator/blob/fdd723405418967ca8a690867940863fd77e636b/app/bin/trinte.js#L39-L46 |
50,647 | mstrutt/node-match-media | main.js | convertUnit | function convertUnit (xUnit, mUnit, mVal) {
if (xUnit !== mUnit) {
if (mUnit === 'em') {
mVal = options.px_em_ratio * mVal;
}
if (xUnit === 'em') {
mVal = mVal/options.px_em_ratio;
}
}
return mVal;
} | javascript | function convertUnit (xUnit, mUnit, mVal) {
if (xUnit !== mUnit) {
if (mUnit === 'em') {
mVal = options.px_em_ratio * mVal;
}
if (xUnit === 'em') {
mVal = mVal/options.px_em_ratio;
}
}
return mVal;
} | [
"function",
"convertUnit",
"(",
"xUnit",
",",
"mUnit",
",",
"mVal",
")",
"{",
"if",
"(",
"xUnit",
"!==",
"mUnit",
")",
"{",
"if",
"(",
"mUnit",
"===",
"'em'",
")",
"{",
"mVal",
"=",
"options",
".",
"px_em_ratio",
"*",
"mVal",
";",
"}",
"if",
"(",
"xUnit",
"===",
"'em'",
")",
"{",
"mVal",
"=",
"mVal",
"/",
"options",
".",
"px_em_ratio",
";",
"}",
"}",
"return",
"mVal",
";",
"}"
] | checking for unit match and converting if needed | [
"checking",
"for",
"unit",
"match",
"and",
"converting",
"if",
"needed"
] | 6c239bfb6f154a6ac030ed9446b8fac0faa7e66a | https://github.com/mstrutt/node-match-media/blob/6c239bfb6f154a6ac030ed9446b8fac0faa7e66a/main.js#L11-L22 |
50,648 | tnantoka/LooseLeaf | lib/looseleaf.js | loadModules | function loadModules(dir, container, args) {
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
container[file] = {};
loadModules(filePath, container[file], args);
continue;
}
if (/.+\.js$/.test(file)) {
var name = file.replace(/\.js$/, '')
container[name] = require(filePath)(args, container);
}
}
} | javascript | function loadModules(dir, container, args) {
var files = fs.readdirSync(dir);
for (var i = 0; i < files.length; i++) {
var file = files[i];
var filePath = path.join(dir, file);
if (fs.statSync(filePath).isDirectory()) {
container[file] = {};
loadModules(filePath, container[file], args);
continue;
}
if (/.+\.js$/.test(file)) {
var name = file.replace(/\.js$/, '')
container[name] = require(filePath)(args, container);
}
}
} | [
"function",
"loadModules",
"(",
"dir",
",",
"container",
",",
"args",
")",
"{",
"var",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"dir",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"file",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"filePath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"container",
"[",
"file",
"]",
"=",
"{",
"}",
";",
"loadModules",
"(",
"filePath",
",",
"container",
"[",
"file",
"]",
",",
"args",
")",
";",
"continue",
";",
"}",
"if",
"(",
"/",
".+\\.js$",
"/",
".",
"test",
"(",
"file",
")",
")",
"{",
"var",
"name",
"=",
"file",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
",",
"''",
")",
"container",
"[",
"name",
"]",
"=",
"require",
"(",
"filePath",
")",
"(",
"args",
",",
"container",
")",
";",
"}",
"}",
"}"
] | Load and require js files to container obj from dir | [
"Load",
"and",
"require",
"js",
"files",
"to",
"container",
"obj",
"from",
"dir"
] | 0c6333977224d8f4ef7ad40415aa69e0ff76f7b5 | https://github.com/tnantoka/LooseLeaf/blob/0c6333977224d8f4ef7ad40415aa69e0ff76f7b5/lib/looseleaf.js#L92-L107 |
50,649 | mathieudutour/nplint | lib/cli-engine.js | loadPlugins | function loadPlugins(pluginNames) {
if (pluginNames) {
pluginNames.forEach(function(pluginName) {
var pluginNamespace = util.getNamespace(pluginName),
pluginNameWithoutNamespace = util.removeNameSpace(pluginName),
pluginNameWithoutPrefix = util.removePluginPrefix(pluginNameWithoutNamespace),
plugin;
if (!loadedPlugins[pluginNameWithoutPrefix]) {
plugin = require(pluginNamespace + util.PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix);
// if this plugin has rules, import them
if (plugin.rules) {
rules.import(plugin.rules, pluginNameWithoutPrefix);
}
loadedPlugins[pluginNameWithoutPrefix] = plugin;
}
});
}
} | javascript | function loadPlugins(pluginNames) {
if (pluginNames) {
pluginNames.forEach(function(pluginName) {
var pluginNamespace = util.getNamespace(pluginName),
pluginNameWithoutNamespace = util.removeNameSpace(pluginName),
pluginNameWithoutPrefix = util.removePluginPrefix(pluginNameWithoutNamespace),
plugin;
if (!loadedPlugins[pluginNameWithoutPrefix]) {
plugin = require(pluginNamespace + util.PLUGIN_NAME_PREFIX + pluginNameWithoutPrefix);
// if this plugin has rules, import them
if (plugin.rules) {
rules.import(plugin.rules, pluginNameWithoutPrefix);
}
loadedPlugins[pluginNameWithoutPrefix] = plugin;
}
});
}
} | [
"function",
"loadPlugins",
"(",
"pluginNames",
")",
"{",
"if",
"(",
"pluginNames",
")",
"{",
"pluginNames",
".",
"forEach",
"(",
"function",
"(",
"pluginName",
")",
"{",
"var",
"pluginNamespace",
"=",
"util",
".",
"getNamespace",
"(",
"pluginName",
")",
",",
"pluginNameWithoutNamespace",
"=",
"util",
".",
"removeNameSpace",
"(",
"pluginName",
")",
",",
"pluginNameWithoutPrefix",
"=",
"util",
".",
"removePluginPrefix",
"(",
"pluginNameWithoutNamespace",
")",
",",
"plugin",
";",
"if",
"(",
"!",
"loadedPlugins",
"[",
"pluginNameWithoutPrefix",
"]",
")",
"{",
"plugin",
"=",
"require",
"(",
"pluginNamespace",
"+",
"util",
".",
"PLUGIN_NAME_PREFIX",
"+",
"pluginNameWithoutPrefix",
")",
";",
"// if this plugin has rules, import them",
"if",
"(",
"plugin",
".",
"rules",
")",
"{",
"rules",
".",
"import",
"(",
"plugin",
".",
"rules",
",",
"pluginNameWithoutPrefix",
")",
";",
"}",
"loadedPlugins",
"[",
"pluginNameWithoutPrefix",
"]",
"=",
"plugin",
";",
"}",
"}",
")",
";",
"}",
"}"
] | Load the given plugins if they are not loaded already.
@param {string[]} pluginNames An array of plugin names which should be loaded.
@returns {void} | [
"Load",
"the",
"given",
"plugins",
"if",
"they",
"are",
"not",
"loaded",
"already",
"."
] | ef444abcc6dd08fb61d5fc8ce618598d4455e08e | https://github.com/mathieudutour/nplint/blob/ef444abcc6dd08fb61d5fc8ce618598d4455e08e/lib/cli-engine.js#L32-L52 |
50,650 | mathieudutour/nplint | lib/cli-engine.js | CLIEngine | function CLIEngine(options) {
/**
* Stored options for this instance
* @type {Object}
*/
this.options = assign(Object.create(defaultOptions), options || {});
// load in additional rules
if (this.options.rulePaths) {
this.options.rulePaths.forEach(function(rulesdir) {
rules.load(rulesdir);
});
}
} | javascript | function CLIEngine(options) {
/**
* Stored options for this instance
* @type {Object}
*/
this.options = assign(Object.create(defaultOptions), options || {});
// load in additional rules
if (this.options.rulePaths) {
this.options.rulePaths.forEach(function(rulesdir) {
rules.load(rulesdir);
});
}
} | [
"function",
"CLIEngine",
"(",
"options",
")",
"{",
"/**\n * Stored options for this instance\n * @type {Object}\n */",
"this",
".",
"options",
"=",
"assign",
"(",
"Object",
".",
"create",
"(",
"defaultOptions",
")",
",",
"options",
"||",
"{",
"}",
")",
";",
"// load in additional rules",
"if",
"(",
"this",
".",
"options",
".",
"rulePaths",
")",
"{",
"this",
".",
"options",
".",
"rulePaths",
".",
"forEach",
"(",
"function",
"(",
"rulesdir",
")",
"{",
"rules",
".",
"load",
"(",
"rulesdir",
")",
";",
"}",
")",
";",
"}",
"}"
] | Creates a new instance of the core CLI engine.
@param {CLIEngineOptions} options The options for this instance.
@constructor | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"core",
"CLI",
"engine",
"."
] | ef444abcc6dd08fb61d5fc8ce618598d4455e08e | https://github.com/mathieudutour/nplint/blob/ef444abcc6dd08fb61d5fc8ce618598d4455e08e/lib/cli-engine.js#L120-L134 |
50,651 | mathieudutour/nplint | lib/cli-engine.js | function(name, pluginobject) {
var pluginNameWithoutPrefix = util.removePluginPrefix(util.removeNameSpace(name));
if (pluginobject.rules) {
rules.import(pluginobject.rules, pluginNameWithoutPrefix);
}
loadedPlugins[pluginNameWithoutPrefix] = pluginobject;
} | javascript | function(name, pluginobject) {
var pluginNameWithoutPrefix = util.removePluginPrefix(util.removeNameSpace(name));
if (pluginobject.rules) {
rules.import(pluginobject.rules, pluginNameWithoutPrefix);
}
loadedPlugins[pluginNameWithoutPrefix] = pluginobject;
} | [
"function",
"(",
"name",
",",
"pluginobject",
")",
"{",
"var",
"pluginNameWithoutPrefix",
"=",
"util",
".",
"removePluginPrefix",
"(",
"util",
".",
"removeNameSpace",
"(",
"name",
")",
")",
";",
"if",
"(",
"pluginobject",
".",
"rules",
")",
"{",
"rules",
".",
"import",
"(",
"pluginobject",
".",
"rules",
",",
"pluginNameWithoutPrefix",
")",
";",
"}",
"loadedPlugins",
"[",
"pluginNameWithoutPrefix",
"]",
"=",
"pluginobject",
";",
"}"
] | Add a plugin by passing it's configuration
@param {string} name Name of the plugin.
@param {Object} pluginobject Plugin configuration object.
@returns {void} | [
"Add",
"a",
"plugin",
"by",
"passing",
"it",
"s",
"configuration"
] | ef444abcc6dd08fb61d5fc8ce618598d4455e08e | https://github.com/mathieudutour/nplint/blob/ef444abcc6dd08fb61d5fc8ce618598d4455e08e/lib/cli-engine.js#L206-L212 |
|
50,652 | mathieudutour/nplint | lib/cli-engine.js | function(directory) {
if (!this.packageJSONFinder) {
this.packageJSONFinder = new FileFinder(PACKAGE_FILENAME);
}
return this.packageJSONFinder.findInDirectoryOrParentsSync(directory || process.cwd());
} | javascript | function(directory) {
if (!this.packageJSONFinder) {
this.packageJSONFinder = new FileFinder(PACKAGE_FILENAME);
}
return this.packageJSONFinder.findInDirectoryOrParentsSync(directory || process.cwd());
} | [
"function",
"(",
"directory",
")",
"{",
"if",
"(",
"!",
"this",
".",
"packageJSONFinder",
")",
"{",
"this",
".",
"packageJSONFinder",
"=",
"new",
"FileFinder",
"(",
"PACKAGE_FILENAME",
")",
";",
"}",
"return",
"this",
".",
"packageJSONFinder",
".",
"findInDirectoryOrParentsSync",
"(",
"directory",
"||",
"process",
".",
"cwd",
"(",
")",
")",
";",
"}"
] | Find package.json from directory and parent directories.
@param {string} directory The directory to start searching from.
@returns {string[]} The paths of local config files found. | [
"Find",
"package",
".",
"json",
"from",
"directory",
"and",
"parent",
"directories",
"."
] | ef444abcc6dd08fb61d5fc8ce618598d4455e08e | https://github.com/mathieudutour/nplint/blob/ef444abcc6dd08fb61d5fc8ce618598d4455e08e/lib/cli-engine.js#L245-L251 |
|
50,653 | layoutmanager/layoutmanager | build/define.js | function(moduleName, deps, callback) {
//if (moduleName === "jquery/selector") { debugger; }
if (!deps && !callback) {
return;
}
// Allow deps to be optional.
if (!callback && typeof deps === "function") {
callback = deps;
deps = undefined;
}
// Ensure dependencies is never falsey.
deps = deps || [];
// Normalize the dependencies.
deps = deps.map(function(dep) {
if (dep.indexOf("./") === -1) {
return dep;
}
// Take off the last path.
var normalize = moduleName.split("/").slice(0, -1).join("/");
//console.log(normalize, dep, define.join(normalize, dep));
return define.join(normalize, dep);
});
// Attach to the module map.
define.map[moduleName] = {
moduleName: moduleName,
deps: deps,
callback: callback
};
} | javascript | function(moduleName, deps, callback) {
//if (moduleName === "jquery/selector") { debugger; }
if (!deps && !callback) {
return;
}
// Allow deps to be optional.
if (!callback && typeof deps === "function") {
callback = deps;
deps = undefined;
}
// Ensure dependencies is never falsey.
deps = deps || [];
// Normalize the dependencies.
deps = deps.map(function(dep) {
if (dep.indexOf("./") === -1) {
return dep;
}
// Take off the last path.
var normalize = moduleName.split("/").slice(0, -1).join("/");
//console.log(normalize, dep, define.join(normalize, dep));
return define.join(normalize, dep);
});
// Attach to the module map.
define.map[moduleName] = {
moduleName: moduleName,
deps: deps,
callback: callback
};
} | [
"function",
"(",
"moduleName",
",",
"deps",
",",
"callback",
")",
"{",
"//if (moduleName === \"jquery/selector\") { debugger; }",
"if",
"(",
"!",
"deps",
"&&",
"!",
"callback",
")",
"{",
"return",
";",
"}",
"// Allow deps to be optional.",
"if",
"(",
"!",
"callback",
"&&",
"typeof",
"deps",
"===",
"\"function\"",
")",
"{",
"callback",
"=",
"deps",
";",
"deps",
"=",
"undefined",
";",
"}",
"// Ensure dependencies is never falsey.",
"deps",
"=",
"deps",
"||",
"[",
"]",
";",
"// Normalize the dependencies.",
"deps",
"=",
"deps",
".",
"map",
"(",
"function",
"(",
"dep",
")",
"{",
"if",
"(",
"dep",
".",
"indexOf",
"(",
"\"./\"",
")",
"===",
"-",
"1",
")",
"{",
"return",
"dep",
";",
"}",
"// Take off the last path.",
"var",
"normalize",
"=",
"moduleName",
".",
"split",
"(",
"\"/\"",
")",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
".",
"join",
"(",
"\"/\"",
")",
";",
"//console.log(normalize, dep, define.join(normalize, dep));",
"return",
"define",
".",
"join",
"(",
"normalize",
",",
"dep",
")",
";",
"}",
")",
";",
"// Attach to the module map.",
"define",
".",
"map",
"[",
"moduleName",
"]",
"=",
"{",
"moduleName",
":",
"moduleName",
",",
"deps",
":",
"deps",
",",
"callback",
":",
"callback",
"}",
";",
"}"
] | Register modules first, but do not execute the callbacks until a matching `require` has been requested for this module. | [
"Register",
"modules",
"first",
"but",
"do",
"not",
"execute",
"the",
"callbacks",
"until",
"a",
"matching",
"require",
"has",
"been",
"requested",
"for",
"this",
"module",
"."
] | de01c901b570e3eb9f014bb43de7b363e5b22c99 | https://github.com/layoutmanager/layoutmanager/blob/de01c901b570e3eb9f014bb43de7b363e5b22c99/build/define.js#L6-L40 |
|
50,654 | Nazariglez/perenquen | lib/pixi/src/filters/shockwave/ShockwaveFilter.js | ShockwaveFilter | function ShockwaveFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/shockwave.frag', 'utf8'),
// custom uniforms
{
center: { type: 'v2', value: { x: 0.5, y: 0.5 } },
params: { type: 'v3', value: { x: 10, y: 0.8, z: 0.1 } },
time: { type: '1f', value: 0 }
}
);
} | javascript | function ShockwaveFilter()
{
core.AbstractFilter.call(this,
// vertex shader
null,
// fragment shader
fs.readFileSync(__dirname + '/shockwave.frag', 'utf8'),
// custom uniforms
{
center: { type: 'v2', value: { x: 0.5, y: 0.5 } },
params: { type: 'v3', value: { x: 10, y: 0.8, z: 0.1 } },
time: { type: '1f', value: 0 }
}
);
} | [
"function",
"ShockwaveFilter",
"(",
")",
"{",
"core",
".",
"AbstractFilter",
".",
"call",
"(",
"this",
",",
"// vertex shader",
"null",
",",
"// fragment shader",
"fs",
".",
"readFileSync",
"(",
"__dirname",
"+",
"'/shockwave.frag'",
",",
"'utf8'",
")",
",",
"// custom uniforms",
"{",
"center",
":",
"{",
"type",
":",
"'v2'",
",",
"value",
":",
"{",
"x",
":",
"0.5",
",",
"y",
":",
"0.5",
"}",
"}",
",",
"params",
":",
"{",
"type",
":",
"'v3'",
",",
"value",
":",
"{",
"x",
":",
"10",
",",
"y",
":",
"0.8",
",",
"z",
":",
"0.1",
"}",
"}",
",",
"time",
":",
"{",
"type",
":",
"'1f'",
",",
"value",
":",
"0",
"}",
"}",
")",
";",
"}"
] | The ColorMatrixFilter class lets you apply a 4x4 matrix transformation on the RGBA
color and alpha values of every pixel on your displayObject to produce a result
with a new set of RGBA color and alpha values. It's pretty powerful!
@class
@extends AbstractFilter
@memberof PIXI.filters | [
"The",
"ColorMatrixFilter",
"class",
"lets",
"you",
"apply",
"a",
"4x4",
"matrix",
"transformation",
"on",
"the",
"RGBA",
"color",
"and",
"alpha",
"values",
"of",
"every",
"pixel",
"on",
"your",
"displayObject",
"to",
"produce",
"a",
"result",
"with",
"a",
"new",
"set",
"of",
"RGBA",
"color",
"and",
"alpha",
"values",
".",
"It",
"s",
"pretty",
"powerful!"
] | e023964d05afeefebdcac4e2044819fdfa3899ae | https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/filters/shockwave/ShockwaveFilter.js#L14-L28 |
50,655 | canuc/ajaxs | ajaxs/index.js | getExtensionlessFilename | function getExtensionlessFilename( filename ) {
return filename.substr( 0, filename.length - path.extname( filename ).length);
} | javascript | function getExtensionlessFilename( filename ) {
return filename.substr( 0, filename.length - path.extname( filename ).length);
} | [
"function",
"getExtensionlessFilename",
"(",
"filename",
")",
"{",
"return",
"filename",
".",
"substr",
"(",
"0",
",",
"filename",
".",
"length",
"-",
"path",
".",
"extname",
"(",
"filename",
")",
".",
"length",
")",
";",
"}"
] | Synchronously retrieve the fixed filename.
@param { string } filename The filename to remove the extension from | [
"Synchronously",
"retrieve",
"the",
"fixed",
"filename",
"."
] | 3bea19efbff83d903a9b34ccd60ade9473a95690 | https://github.com/canuc/ajaxs/blob/3bea19efbff83d903a9b34ccd60ade9473a95690/ajaxs/index.js#L27-L29 |
50,656 | canuc/ajaxs | ajaxs/index.js | templateWithArgs | function templateWithArgs( apiDir, apiName, apiFuncName ) {
cacheAPIs[apiName] = {
reg: (RegularCacheClient
.replace(/%%api.root%%/g,apiDir)
.replace(/%%api.name%%/g,apiName)
.replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName))),
service: (ServiceCacheClient
.replace(/%%api.root%%/g,apiDir)
.replace(/%%api.name%%/g,apiName)
.replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName)))
}
} | javascript | function templateWithArgs( apiDir, apiName, apiFuncName ) {
cacheAPIs[apiName] = {
reg: (RegularCacheClient
.replace(/%%api.root%%/g,apiDir)
.replace(/%%api.name%%/g,apiName)
.replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName))),
service: (ServiceCacheClient
.replace(/%%api.root%%/g,apiDir)
.replace(/%%api.name%%/g,apiName)
.replace(/%%api.funcs%%/g,JSON.stringify(apiFuncName)))
}
} | [
"function",
"templateWithArgs",
"(",
"apiDir",
",",
"apiName",
",",
"apiFuncName",
")",
"{",
"cacheAPIs",
"[",
"apiName",
"]",
"=",
"{",
"reg",
":",
"(",
"RegularCacheClient",
".",
"replace",
"(",
"/",
"%%api.root%%",
"/",
"g",
",",
"apiDir",
")",
".",
"replace",
"(",
"/",
"%%api.name%%",
"/",
"g",
",",
"apiName",
")",
".",
"replace",
"(",
"/",
"%%api.funcs%%",
"/",
"g",
",",
"JSON",
".",
"stringify",
"(",
"apiFuncName",
")",
")",
")",
",",
"service",
":",
"(",
"ServiceCacheClient",
".",
"replace",
"(",
"/",
"%%api.root%%",
"/",
"g",
",",
"apiDir",
")",
".",
"replace",
"(",
"/",
"%%api.name%%",
"/",
"g",
",",
"apiName",
")",
".",
"replace",
"(",
"/",
"%%api.funcs%%",
"/",
"g",
",",
"JSON",
".",
"stringify",
"(",
"apiFuncName",
")",
")",
")",
"}",
"}"
] | Synchronously create a template | [
"Synchronously",
"create",
"a",
"template"
] | 3bea19efbff83d903a9b34ccd60ade9473a95690 | https://github.com/canuc/ajaxs/blob/3bea19efbff83d903a9b34ccd60ade9473a95690/ajaxs/index.js#L34-L46 |
50,657 | canuc/ajaxs | ajaxs/index.js | copyArgumentsArray | function copyArgumentsArray(args) {
var copy = [];
var index = 0;
for (var i in args) {
copy[index] = args[i];
index++;
}
return copy;
} | javascript | function copyArgumentsArray(args) {
var copy = [];
var index = 0;
for (var i in args) {
copy[index] = args[i];
index++;
}
return copy;
} | [
"function",
"copyArgumentsArray",
"(",
"args",
")",
"{",
"var",
"copy",
"=",
"[",
"]",
";",
"var",
"index",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"in",
"args",
")",
"{",
"copy",
"[",
"index",
"]",
"=",
"args",
"[",
"i",
"]",
";",
"index",
"++",
";",
"}",
"return",
"copy",
";",
"}"
] | Synchronously copy an arguments object array.
@internal
@param { object } args the objects array | [
"Synchronously",
"copy",
"an",
"arguments",
"object",
"array",
"."
] | 3bea19efbff83d903a9b34ccd60ade9473a95690 | https://github.com/canuc/ajaxs/blob/3bea19efbff83d903a9b34ccd60ade9473a95690/ajaxs/index.js#L53-L61 |
50,658 | canuc/ajaxs | ajaxs/index.js | readRawBody | function readRawBody(req,res,rawBodyCallback,callbackScope) {
if ( typeof req._body !== 'undefined' && req._body ) {
rawBodyCallback.call(callbackScope,req,res);
} else {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function() {
rawBodyCallback.call(callbackScope,req,res);
});
}
} | javascript | function readRawBody(req,res,rawBodyCallback,callbackScope) {
if ( typeof req._body !== 'undefined' && req._body ) {
rawBodyCallback.call(callbackScope,req,res);
} else {
req.rawBody = '';
req.setEncoding('utf8');
req.on('data', function(chunk) {
req.rawBody += chunk;
});
req.on('end', function() {
rawBodyCallback.call(callbackScope,req,res);
});
}
} | [
"function",
"readRawBody",
"(",
"req",
",",
"res",
",",
"rawBodyCallback",
",",
"callbackScope",
")",
"{",
"if",
"(",
"typeof",
"req",
".",
"_body",
"!==",
"'undefined'",
"&&",
"req",
".",
"_body",
")",
"{",
"rawBodyCallback",
".",
"call",
"(",
"callbackScope",
",",
"req",
",",
"res",
")",
";",
"}",
"else",
"{",
"req",
".",
"rawBody",
"=",
"''",
";",
"req",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"req",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"req",
".",
"rawBody",
"+=",
"chunk",
";",
"}",
")",
";",
"req",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"rawBodyCallback",
".",
"call",
"(",
"callbackScope",
",",
"req",
",",
"res",
")",
";",
"}",
")",
";",
"}",
"}"
] | Asynchronous call to read the raw body from the request that we have deemed,
as an API request.
NOTE: This function implements a workaround if the middleware is placed
after the body parser in the connect stack.
@internal
@param { object } req an expressjs http request object.
@param { object } res an expressjs http response object.
@param { function } rawBodyCallback a callback function once the body has been read.
@param { object } callback scopt | [
"Asynchronous",
"call",
"to",
"read",
"the",
"raw",
"body",
"from",
"the",
"request",
"that",
"we",
"have",
"deemed",
"as",
"an",
"API",
"request",
"."
] | 3bea19efbff83d903a9b34ccd60ade9473a95690 | https://github.com/canuc/ajaxs/blob/3bea19efbff83d903a9b34ccd60ade9473a95690/ajaxs/index.js#L119-L136 |
50,659 | redisjs/jsr-conf | lib/config-error.js | ConfigError | function ConfigError(lineno, line, file, err) {
this.name = ConfigError.name;
Error.call(this);
var fmt = '*** FATAL CONFIG FILE ERROR ***%s';
fmt += 'Reading the configuration file, at line %s%s';
fmt += '>>> %s%s';
fmt += err && err.message && !(err instanceof TypeDefError) ? err.message :
'Bad directive or wrong number of arguments';
this.message = util.format(fmt, EOL, lineno, EOL, line, EOL);
this.file = file;
this.err = err;
} | javascript | function ConfigError(lineno, line, file, err) {
this.name = ConfigError.name;
Error.call(this);
var fmt = '*** FATAL CONFIG FILE ERROR ***%s';
fmt += 'Reading the configuration file, at line %s%s';
fmt += '>>> %s%s';
fmt += err && err.message && !(err instanceof TypeDefError) ? err.message :
'Bad directive or wrong number of arguments';
this.message = util.format(fmt, EOL, lineno, EOL, line, EOL);
this.file = file;
this.err = err;
} | [
"function",
"ConfigError",
"(",
"lineno",
",",
"line",
",",
"file",
",",
"err",
")",
"{",
"this",
".",
"name",
"=",
"ConfigError",
".",
"name",
";",
"Error",
".",
"call",
"(",
"this",
")",
";",
"var",
"fmt",
"=",
"'*** FATAL CONFIG FILE ERROR ***%s'",
";",
"fmt",
"+=",
"'Reading the configuration file, at line %s%s'",
";",
"fmt",
"+=",
"'>>> %s%s'",
";",
"fmt",
"+=",
"err",
"&&",
"err",
".",
"message",
"&&",
"!",
"(",
"err",
"instanceof",
"TypeDefError",
")",
"?",
"err",
".",
"message",
":",
"'Bad directive or wrong number of arguments'",
";",
"this",
".",
"message",
"=",
"util",
".",
"format",
"(",
"fmt",
",",
"EOL",
",",
"lineno",
",",
"EOL",
",",
"line",
",",
"EOL",
")",
";",
"this",
".",
"file",
"=",
"file",
";",
"this",
".",
"err",
"=",
"err",
";",
"}"
] | Represents a configuration file error.
@param lineno The line number in the source file.
@param line The line that triggered the error.
@param file The configuration file being loaded.
@param err A source error containing more detail. | [
"Represents",
"a",
"configuration",
"file",
"error",
"."
] | 97c5e2e77e1601c879a62dfc2d500df537eaaddd | https://github.com/redisjs/jsr-conf/blob/97c5e2e77e1601c879a62dfc2d500df537eaaddd/lib/config-error.js#L13-L26 |
50,660 | jmjuanes/logty | lib/timestamp.js | function () {
let date = new Date();
let result = {};
let regex = /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d).\d\d\dZ/g;
let current = regex.exec(date.toJSON());
if (current === null || current.length < 7) {
return null;
}
for (let i = 0; i < 6; i++) {
//The first element is the full matched string
result[values[i]] = current[i + 1];
}
return result;
} | javascript | function () {
let date = new Date();
let result = {};
let regex = /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d).\d\d\dZ/g;
let current = regex.exec(date.toJSON());
if (current === null || current.length < 7) {
return null;
}
for (let i = 0; i < 6; i++) {
//The first element is the full matched string
result[values[i]] = current[i + 1];
}
return result;
} | [
"function",
"(",
")",
"{",
"let",
"date",
"=",
"new",
"Date",
"(",
")",
";",
"let",
"result",
"=",
"{",
"}",
";",
"let",
"regex",
"=",
"/",
"(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d).\\d\\d\\dZ",
"/",
"g",
";",
"let",
"current",
"=",
"regex",
".",
"exec",
"(",
"date",
".",
"toJSON",
"(",
")",
")",
";",
"if",
"(",
"current",
"===",
"null",
"||",
"current",
".",
"length",
"<",
"7",
")",
"{",
"return",
"null",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"6",
";",
"i",
"++",
")",
"{",
"//The first element is the full matched string",
"result",
"[",
"values",
"[",
"i",
"]",
"]",
"=",
"current",
"[",
"i",
"+",
"1",
"]",
";",
"}",
"return",
"result",
";",
"}"
] | Get the current time | [
"Get",
"the",
"current",
"time"
] | 47c4f9ea65f9443f54bd2ccb6a7277fb7c12201b | https://github.com/jmjuanes/logty/blob/47c4f9ea65f9443f54bd2ccb6a7277fb7c12201b/lib/timestamp.js#L10-L23 |
|
50,661 | MakerCollider/upm_mc | doxy/node/generators/jsdoc/generator.js | generateDocs | function generateDocs(specjs) {
var docs = GENERATE_MODULE(specjs.MODULE);
docs = _.reduce(specjs.METHODS, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec);
}, docs);
docs = _.reduce(specjs.ENUMS, function(memo, enumSpec, enumName) {
return memo += GENERATE_ENUM(enumName, enumSpec);
}, docs);
docs = _.reduce(specjs.CLASSES, function(memo, classSpec, parentClass) {
return _.reduce(classSpec.methods, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec, parentClass);
}, memo);
}, docs);
return docs;
} | javascript | function generateDocs(specjs) {
var docs = GENERATE_MODULE(specjs.MODULE);
docs = _.reduce(specjs.METHODS, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec);
}, docs);
docs = _.reduce(specjs.ENUMS, function(memo, enumSpec, enumName) {
return memo += GENERATE_ENUM(enumName, enumSpec);
}, docs);
docs = _.reduce(specjs.CLASSES, function(memo, classSpec, parentClass) {
return _.reduce(classSpec.methods, function(memo, methodSpec, methodName) {
return memo += GENERATE_METHOD(methodName, methodSpec, parentClass);
}, memo);
}, docs);
return docs;
} | [
"function",
"generateDocs",
"(",
"specjs",
")",
"{",
"var",
"docs",
"=",
"GENERATE_MODULE",
"(",
"specjs",
".",
"MODULE",
")",
";",
"docs",
"=",
"_",
".",
"reduce",
"(",
"specjs",
".",
"METHODS",
",",
"function",
"(",
"memo",
",",
"methodSpec",
",",
"methodName",
")",
"{",
"return",
"memo",
"+=",
"GENERATE_METHOD",
"(",
"methodName",
",",
"methodSpec",
")",
";",
"}",
",",
"docs",
")",
";",
"docs",
"=",
"_",
".",
"reduce",
"(",
"specjs",
".",
"ENUMS",
",",
"function",
"(",
"memo",
",",
"enumSpec",
",",
"enumName",
")",
"{",
"return",
"memo",
"+=",
"GENERATE_ENUM",
"(",
"enumName",
",",
"enumSpec",
")",
";",
"}",
",",
"docs",
")",
";",
"docs",
"=",
"_",
".",
"reduce",
"(",
"specjs",
".",
"CLASSES",
",",
"function",
"(",
"memo",
",",
"classSpec",
",",
"parentClass",
")",
"{",
"return",
"_",
".",
"reduce",
"(",
"classSpec",
".",
"methods",
",",
"function",
"(",
"memo",
",",
"methodSpec",
",",
"methodName",
")",
"{",
"return",
"memo",
"+=",
"GENERATE_METHOD",
"(",
"methodName",
",",
"methodSpec",
",",
"parentClass",
")",
";",
"}",
",",
"memo",
")",
";",
"}",
",",
"docs",
")",
";",
"return",
"docs",
";",
"}"
] | generate JSDoc-style documentation | [
"generate",
"JSDoc",
"-",
"style",
"documentation"
] | 525e775a17b85c30716c00435a2acb26bb198c12 | https://github.com/MakerCollider/upm_mc/blob/525e775a17b85c30716c00435a2acb26bb198c12/doxy/node/generators/jsdoc/generator.js#L30-L44 |
50,662 | jamespdlynn/microjs | examples/game/lib/server.js | function(buffer){
//Deserialize binary data into a JSON object
var data = micro.toJSON(buffer);
var type = data._type;
delete data._type;
switch (type)
{
case "Ping" :
var numPings = data.timestamps.length;
//Ping a minimum of number of times, before calculating the latency
if (numPings < MAX_PINGS){
ping(data);
}
else if (numPings == MAX_PINGS){
//Calculate this connections average latency and send it to the client
data.latency = calculateLatency(data.timestamps);
console.log(data.latency);
ping(data);
//If we haven't initialized yet, add this connection to the server zone
if (!initialized){
serverZone.add(connection);
initialized = true;
}
}
break;
case "PlayerUpdate":
//Set the player update id to the connection id to prevent clients from updating other players
data.id = connection.id;
serverZone.updatePlayer(data);
break;
default:
console.warn("Unexpected Schema Type Received: "+type);
break;
}
} | javascript | function(buffer){
//Deserialize binary data into a JSON object
var data = micro.toJSON(buffer);
var type = data._type;
delete data._type;
switch (type)
{
case "Ping" :
var numPings = data.timestamps.length;
//Ping a minimum of number of times, before calculating the latency
if (numPings < MAX_PINGS){
ping(data);
}
else if (numPings == MAX_PINGS){
//Calculate this connections average latency and send it to the client
data.latency = calculateLatency(data.timestamps);
console.log(data.latency);
ping(data);
//If we haven't initialized yet, add this connection to the server zone
if (!initialized){
serverZone.add(connection);
initialized = true;
}
}
break;
case "PlayerUpdate":
//Set the player update id to the connection id to prevent clients from updating other players
data.id = connection.id;
serverZone.updatePlayer(data);
break;
default:
console.warn("Unexpected Schema Type Received: "+type);
break;
}
} | [
"function",
"(",
"buffer",
")",
"{",
"//Deserialize binary data into a JSON object",
"var",
"data",
"=",
"micro",
".",
"toJSON",
"(",
"buffer",
")",
";",
"var",
"type",
"=",
"data",
".",
"_type",
";",
"delete",
"data",
".",
"_type",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"\"Ping\"",
":",
"var",
"numPings",
"=",
"data",
".",
"timestamps",
".",
"length",
";",
"//Ping a minimum of number of times, before calculating the latency",
"if",
"(",
"numPings",
"<",
"MAX_PINGS",
")",
"{",
"ping",
"(",
"data",
")",
";",
"}",
"else",
"if",
"(",
"numPings",
"==",
"MAX_PINGS",
")",
"{",
"//Calculate this connections average latency and send it to the client",
"data",
".",
"latency",
"=",
"calculateLatency",
"(",
"data",
".",
"timestamps",
")",
";",
"console",
".",
"log",
"(",
"data",
".",
"latency",
")",
";",
"ping",
"(",
"data",
")",
";",
"//If we haven't initialized yet, add this connection to the server zone",
"if",
"(",
"!",
"initialized",
")",
"{",
"serverZone",
".",
"add",
"(",
"connection",
")",
";",
"initialized",
"=",
"true",
";",
"}",
"}",
"break",
";",
"case",
"\"PlayerUpdate\"",
":",
"//Set the player update id to the connection id to prevent clients from updating other players",
"data",
".",
"id",
"=",
"connection",
".",
"id",
";",
"serverZone",
".",
"updatePlayer",
"(",
"data",
")",
";",
"break",
";",
"default",
":",
"console",
".",
"warn",
"(",
"\"Unexpected Schema Type Received: \"",
"+",
"type",
")",
";",
"break",
";",
"}",
"}"
] | Parse client sent binary data buffer | [
"Parse",
"client",
"sent",
"binary",
"data",
"buffer"
] | 780a4074de84bcd74e3ae50d0ed64144b4474166 | https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/server.js#L194-L235 |
|
50,663 | jamespdlynn/microjs | examples/game/lib/server.js | function(data){
data = data || {timestamps:[]};
data.timestamps.push(new Date().getTime());
send(connection, "Ping", data);
} | javascript | function(data){
data = data || {timestamps:[]};
data.timestamps.push(new Date().getTime());
send(connection, "Ping", data);
} | [
"function",
"(",
"data",
")",
"{",
"data",
"=",
"data",
"||",
"{",
"timestamps",
":",
"[",
"]",
"}",
";",
"data",
".",
"timestamps",
".",
"push",
"(",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
")",
";",
"send",
"(",
"connection",
",",
"\"Ping\"",
",",
"data",
")",
";",
"}"
] | Kick off the connection by pinging the client | [
"Kick",
"off",
"the",
"connection",
"by",
"pinging",
"the",
"client"
] | 780a4074de84bcd74e3ae50d0ed64144b4474166 | https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/server.js#L238-L242 |
|
50,664 | jamespdlynn/microjs | examples/game/lib/server.js | send | function send(conn,schemaName,json,byteLength){
var buffer = micro.toBinary(json, schemaName,byteLength);
if (FAKE_LATENCY){
setTimeout(function(){
conn.sendBytes(buffer);
},FAKE_LATENCY);
}else{
conn.sendBytes(buffer);
}
} | javascript | function send(conn,schemaName,json,byteLength){
var buffer = micro.toBinary(json, schemaName,byteLength);
if (FAKE_LATENCY){
setTimeout(function(){
conn.sendBytes(buffer);
},FAKE_LATENCY);
}else{
conn.sendBytes(buffer);
}
} | [
"function",
"send",
"(",
"conn",
",",
"schemaName",
",",
"json",
",",
"byteLength",
")",
"{",
"var",
"buffer",
"=",
"micro",
".",
"toBinary",
"(",
"json",
",",
"schemaName",
",",
"byteLength",
")",
";",
"if",
"(",
"FAKE_LATENCY",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"conn",
".",
"sendBytes",
"(",
"buffer",
")",
";",
"}",
",",
"FAKE_LATENCY",
")",
";",
"}",
"else",
"{",
"conn",
".",
"sendBytes",
"(",
"buffer",
")",
";",
"}",
"}"
] | Helper function that serializes a JSON data object according to a given schema,
and then sends it through a given client connection
@param {object} conn
@param {string} schemaName
@param {object} json
@param {number} [byteLength] | [
"Helper",
"function",
"that",
"serializes",
"a",
"JSON",
"data",
"object",
"according",
"to",
"a",
"given",
"schema",
"and",
"then",
"sends",
"it",
"through",
"a",
"given",
"client",
"connection"
] | 780a4074de84bcd74e3ae50d0ed64144b4474166 | https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/server.js#L259-L270 |
50,665 | jamespdlynn/microjs | examples/game/lib/server.js | calculateLatency | function calculateLatency(timestamps){
var length = timestamps.length,
sumLatency = 0;
for (var i = 1; i < length; i++){
sumLatency += (timestamps[i] - timestamps[i-1])/2;
}
return (sumLatency/(length-1));
} | javascript | function calculateLatency(timestamps){
var length = timestamps.length,
sumLatency = 0;
for (var i = 1; i < length; i++){
sumLatency += (timestamps[i] - timestamps[i-1])/2;
}
return (sumLatency/(length-1));
} | [
"function",
"calculateLatency",
"(",
"timestamps",
")",
"{",
"var",
"length",
"=",
"timestamps",
".",
"length",
",",
"sumLatency",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"sumLatency",
"+=",
"(",
"timestamps",
"[",
"i",
"]",
"-",
"timestamps",
"[",
"i",
"-",
"1",
"]",
")",
"/",
"2",
";",
"}",
"return",
"(",
"sumLatency",
"/",
"(",
"length",
"-",
"1",
")",
")",
";",
"}"
] | Helper function that calculates the latency by getting the average of all the ping timestamps differences
@param {Array.<number>} timestamps
@returns {number} | [
"Helper",
"function",
"that",
"calculates",
"the",
"latency",
"by",
"getting",
"the",
"average",
"of",
"all",
"the",
"ping",
"timestamps",
"differences"
] | 780a4074de84bcd74e3ae50d0ed64144b4474166 | https://github.com/jamespdlynn/microjs/blob/780a4074de84bcd74e3ae50d0ed64144b4474166/examples/game/lib/server.js#L278-L287 |
50,666 | macbre/tap-eater | lib/tap-eater.js | eat | function eat(stream, callback) {
if (!stream instanceof Stream) {
throw 'eat() accepts Stream only!';
}
this.callback = callback;
this.consumer = new TapConsumer();
this.report = {
pass: false,
skip: false,
fail: false,
total: false,
failures: [],
text: ''
};
// setup events
this.consumer.on('data', onData.bind(this));
this.consumer.on('end', onEnd.bind(this));
// consume the stream
stream.setEncoding('utf8');
stream.pipe(this.consumer);
// yum-yum!
} | javascript | function eat(stream, callback) {
if (!stream instanceof Stream) {
throw 'eat() accepts Stream only!';
}
this.callback = callback;
this.consumer = new TapConsumer();
this.report = {
pass: false,
skip: false,
fail: false,
total: false,
failures: [],
text: ''
};
// setup events
this.consumer.on('data', onData.bind(this));
this.consumer.on('end', onEnd.bind(this));
// consume the stream
stream.setEncoding('utf8');
stream.pipe(this.consumer);
// yum-yum!
} | [
"function",
"eat",
"(",
"stream",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"stream",
"instanceof",
"Stream",
")",
"{",
"throw",
"'eat() accepts Stream only!'",
";",
"}",
"this",
".",
"callback",
"=",
"callback",
";",
"this",
".",
"consumer",
"=",
"new",
"TapConsumer",
"(",
")",
";",
"this",
".",
"report",
"=",
"{",
"pass",
":",
"false",
",",
"skip",
":",
"false",
",",
"fail",
":",
"false",
",",
"total",
":",
"false",
",",
"failures",
":",
"[",
"]",
",",
"text",
":",
"''",
"}",
";",
"// setup events",
"this",
".",
"consumer",
".",
"on",
"(",
"'data'",
",",
"onData",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"consumer",
".",
"on",
"(",
"'end'",
",",
"onEnd",
".",
"bind",
"(",
"this",
")",
")",
";",
"// consume the stream",
"stream",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"stream",
".",
"pipe",
"(",
"this",
".",
"consumer",
")",
";",
"// yum-yum!",
"}"
] | consumes TAP data from given stream | [
"consumes",
"TAP",
"data",
"from",
"given",
"stream"
] | a4079972a021756ab1c58a433578d264305551ff | https://github.com/macbre/tap-eater/blob/a4079972a021756ab1c58a433578d264305551ff/lib/tap-eater.js#L102-L126 |
50,667 | gethuman/pancakes-recipe | middleware/mw.service.init.js | init | function init(ctx) {
var container = ctx.container;
// reactors can be initialized without a promise since just attaching event handlers
initReactors(container);
// adapters and services may be making database calls, so do with promises
return initAdapters(container)
.then(function () {
return initServices(container);
})
.then(function () {
return ctx;
});
} | javascript | function init(ctx) {
var container = ctx.container;
// reactors can be initialized without a promise since just attaching event handlers
initReactors(container);
// adapters and services may be making database calls, so do with promises
return initAdapters(container)
.then(function () {
return initServices(container);
})
.then(function () {
return ctx;
});
} | [
"function",
"init",
"(",
"ctx",
")",
"{",
"var",
"container",
"=",
"ctx",
".",
"container",
";",
"// reactors can be initialized without a promise since just attaching event handlers",
"initReactors",
"(",
"container",
")",
";",
"// adapters and services may be making database calls, so do with promises",
"return",
"initAdapters",
"(",
"container",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"initServices",
"(",
"container",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"ctx",
";",
"}",
")",
";",
"}"
] | Initialize all the reactors, adapters and services
@returns {Q} | [
"Initialize",
"all",
"the",
"reactors",
"adapters",
"and",
"services"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.service.init.js#L14-L28 |
50,668 | gethuman/pancakes-recipe | middleware/mw.service.init.js | reactHandler | function reactHandler(reactData) {
return function (eventData) {
// handler should always be run asynchronously
setTimeout(function () {
var payload = eventData.payload;
var inputData = payload.inputData;
var reactor = reactors[reactData.type + '.reactor'];
var matchesCriteria = objUtils.matchesCriteria(payload.data, reactData.criteria);
var fieldMissing = reactData.onFieldChange && reactData.onFieldChange.length &&
_.isEmpty(fakeblock.filter.getFieldsFromObj(inputData, reactData.onFieldChange));
if (!reactor) {
log.info('reactHandler does not exist: ' + JSON.stringify(reactData));
}
if (!reactor || !matchesCriteria || fieldMissing) {
//deferred.resolve();
return;
}
Q.fcall(function () {
reactor.react({
caller: payload.caller,
inputData: inputData,
data: payload.data,
context: payload.context,
reactData: reactData,
resourceName: eventData.name.resource,
methodName: eventData.name.method
});
}).catch(log.error);
});
};
} | javascript | function reactHandler(reactData) {
return function (eventData) {
// handler should always be run asynchronously
setTimeout(function () {
var payload = eventData.payload;
var inputData = payload.inputData;
var reactor = reactors[reactData.type + '.reactor'];
var matchesCriteria = objUtils.matchesCriteria(payload.data, reactData.criteria);
var fieldMissing = reactData.onFieldChange && reactData.onFieldChange.length &&
_.isEmpty(fakeblock.filter.getFieldsFromObj(inputData, reactData.onFieldChange));
if (!reactor) {
log.info('reactHandler does not exist: ' + JSON.stringify(reactData));
}
if (!reactor || !matchesCriteria || fieldMissing) {
//deferred.resolve();
return;
}
Q.fcall(function () {
reactor.react({
caller: payload.caller,
inputData: inputData,
data: payload.data,
context: payload.context,
reactData: reactData,
resourceName: eventData.name.resource,
methodName: eventData.name.method
});
}).catch(log.error);
});
};
} | [
"function",
"reactHandler",
"(",
"reactData",
")",
"{",
"return",
"function",
"(",
"eventData",
")",
"{",
"// handler should always be run asynchronously",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"var",
"payload",
"=",
"eventData",
".",
"payload",
";",
"var",
"inputData",
"=",
"payload",
".",
"inputData",
";",
"var",
"reactor",
"=",
"reactors",
"[",
"reactData",
".",
"type",
"+",
"'.reactor'",
"]",
";",
"var",
"matchesCriteria",
"=",
"objUtils",
".",
"matchesCriteria",
"(",
"payload",
".",
"data",
",",
"reactData",
".",
"criteria",
")",
";",
"var",
"fieldMissing",
"=",
"reactData",
".",
"onFieldChange",
"&&",
"reactData",
".",
"onFieldChange",
".",
"length",
"&&",
"_",
".",
"isEmpty",
"(",
"fakeblock",
".",
"filter",
".",
"getFieldsFromObj",
"(",
"inputData",
",",
"reactData",
".",
"onFieldChange",
")",
")",
";",
"if",
"(",
"!",
"reactor",
")",
"{",
"log",
".",
"info",
"(",
"'reactHandler does not exist: '",
"+",
"JSON",
".",
"stringify",
"(",
"reactData",
")",
")",
";",
"}",
"if",
"(",
"!",
"reactor",
"||",
"!",
"matchesCriteria",
"||",
"fieldMissing",
")",
"{",
"//deferred.resolve();",
"return",
";",
"}",
"Q",
".",
"fcall",
"(",
"function",
"(",
")",
"{",
"reactor",
".",
"react",
"(",
"{",
"caller",
":",
"payload",
".",
"caller",
",",
"inputData",
":",
"inputData",
",",
"data",
":",
"payload",
".",
"data",
",",
"context",
":",
"payload",
".",
"context",
",",
"reactData",
":",
"reactData",
",",
"resourceName",
":",
"eventData",
".",
"name",
".",
"resource",
",",
"methodName",
":",
"eventData",
".",
"name",
".",
"method",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"log",
".",
"error",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] | Get handler for a react event
@param reactData
@returns {Function} | [
"Get",
"handler",
"for",
"a",
"react",
"event"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.service.init.js#L35-L69 |
50,669 | gethuman/pancakes-recipe | middleware/mw.service.init.js | initReactors | function initReactors(container) {
var isBatch = container === 'batch';
// loop through each reactor and call init if it exists
_.each(reactors, function (reactor) {
if (reactor.init) {
reactor.init({ config: config, pancakes: pancakes });
}
});
// most reactors will be through the resource reactor definitions
_.each(resources, function (resource) { // loop through all the resources
_.each(resource.reactors, function (reactData) { // loop through reactors
if (isBatch && reactData.type === 'audit') { // don't do anything if audit for batch
return; // since audit not needed for batch
}
var eventTriggers = { // events that will trigger this propgation
resources: [resource.name],
adapters: reactData.trigger.adapters,
methods: reactData.trigger.methods
};
// add the event handler
eventBus.addHandlers(eventTriggers, reactHandler(reactData));
});
});
} | javascript | function initReactors(container) {
var isBatch = container === 'batch';
// loop through each reactor and call init if it exists
_.each(reactors, function (reactor) {
if (reactor.init) {
reactor.init({ config: config, pancakes: pancakes });
}
});
// most reactors will be through the resource reactor definitions
_.each(resources, function (resource) { // loop through all the resources
_.each(resource.reactors, function (reactData) { // loop through reactors
if (isBatch && reactData.type === 'audit') { // don't do anything if audit for batch
return; // since audit not needed for batch
}
var eventTriggers = { // events that will trigger this propgation
resources: [resource.name],
adapters: reactData.trigger.adapters,
methods: reactData.trigger.methods
};
// add the event handler
eventBus.addHandlers(eventTriggers, reactHandler(reactData));
});
});
} | [
"function",
"initReactors",
"(",
"container",
")",
"{",
"var",
"isBatch",
"=",
"container",
"===",
"'batch'",
";",
"// loop through each reactor and call init if it exists",
"_",
".",
"each",
"(",
"reactors",
",",
"function",
"(",
"reactor",
")",
"{",
"if",
"(",
"reactor",
".",
"init",
")",
"{",
"reactor",
".",
"init",
"(",
"{",
"config",
":",
"config",
",",
"pancakes",
":",
"pancakes",
"}",
")",
";",
"}",
"}",
")",
";",
"// most reactors will be through the resource reactor definitions",
"_",
".",
"each",
"(",
"resources",
",",
"function",
"(",
"resource",
")",
"{",
"// loop through all the resources",
"_",
".",
"each",
"(",
"resource",
".",
"reactors",
",",
"function",
"(",
"reactData",
")",
"{",
"// loop through reactors",
"if",
"(",
"isBatch",
"&&",
"reactData",
".",
"type",
"===",
"'audit'",
")",
"{",
"// don't do anything if audit for batch",
"return",
";",
"// since audit not needed for batch",
"}",
"var",
"eventTriggers",
"=",
"{",
"// events that will trigger this propgation",
"resources",
":",
"[",
"resource",
".",
"name",
"]",
",",
"adapters",
":",
"reactData",
".",
"trigger",
".",
"adapters",
",",
"methods",
":",
"reactData",
".",
"trigger",
".",
"methods",
"}",
";",
"// add the event handler",
"eventBus",
".",
"addHandlers",
"(",
"eventTriggers",
",",
"reactHandler",
"(",
"reactData",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Call all reactor init functions and attach reactors based
on reactor data within resource files.
@param container | [
"Call",
"all",
"reactor",
"init",
"functions",
"and",
"attach",
"reactors",
"based",
"on",
"reactor",
"data",
"within",
"resource",
"files",
"."
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.service.init.js#L76-L103 |
50,670 | gethuman/pancakes-recipe | middleware/mw.service.init.js | initAdapters | function initAdapters(container) {
var calls = [];
if (container === 'webserver') {
_.each(adapters, function (adapter) {
if (adapter.webInit) {
calls.push(adapter.webInit);
}
});
}
else {
_.each(adapters, function (adapter) {
if (adapter.init) {
calls.push(adapter.init);
}
});
}
return chainPromises(calls, config)
.then(function (returnConfig) {
if (returnConfig) {
return returnConfig;
}
else {
throw new Error('An adapter in the chain is not returning the config.');
}
});
} | javascript | function initAdapters(container) {
var calls = [];
if (container === 'webserver') {
_.each(adapters, function (adapter) {
if (adapter.webInit) {
calls.push(adapter.webInit);
}
});
}
else {
_.each(adapters, function (adapter) {
if (adapter.init) {
calls.push(adapter.init);
}
});
}
return chainPromises(calls, config)
.then(function (returnConfig) {
if (returnConfig) {
return returnConfig;
}
else {
throw new Error('An adapter in the chain is not returning the config.');
}
});
} | [
"function",
"initAdapters",
"(",
"container",
")",
"{",
"var",
"calls",
"=",
"[",
"]",
";",
"if",
"(",
"container",
"===",
"'webserver'",
")",
"{",
"_",
".",
"each",
"(",
"adapters",
",",
"function",
"(",
"adapter",
")",
"{",
"if",
"(",
"adapter",
".",
"webInit",
")",
"{",
"calls",
".",
"push",
"(",
"adapter",
".",
"webInit",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"_",
".",
"each",
"(",
"adapters",
",",
"function",
"(",
"adapter",
")",
"{",
"if",
"(",
"adapter",
".",
"init",
")",
"{",
"calls",
".",
"push",
"(",
"adapter",
".",
"init",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"chainPromises",
"(",
"calls",
",",
"config",
")",
".",
"then",
"(",
"function",
"(",
"returnConfig",
")",
"{",
"if",
"(",
"returnConfig",
")",
"{",
"return",
"returnConfig",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'An adapter in the chain is not returning the config.'",
")",
";",
"}",
"}",
")",
";",
"}"
] | Initialize the adapters as long as the container is no webserver
@param container
@returns {*} | [
"Initialize",
"the",
"adapters",
"as",
"long",
"as",
"the",
"container",
"is",
"no",
"webserver"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/middleware/mw.service.init.js#L111-L139 |
50,671 | derdesign/protos | lib/application.js | function() {
var args = [].slice.call(arguments, 0);
var workerMessage, done = 0;
var workerKeys = Object.keys(cluster.workers);
var nextWorker = function() {
if (workerKeys.length) {
done++;
cluster.workers[workerKeys.shift()].send(taskMessage.concat([args]));
} else {
app.log("Executed [%s] on %d workers", id, done);
app.removeListener('worker_message', workerMessage);
}
}
app.on('worker_message', workerMessage = function(msg) {
if (isMessageForMe(msg) && msg[3] === 'done') {
nextWorker()
}
});
nextWorker();
} | javascript | function() {
var args = [].slice.call(arguments, 0);
var workerMessage, done = 0;
var workerKeys = Object.keys(cluster.workers);
var nextWorker = function() {
if (workerKeys.length) {
done++;
cluster.workers[workerKeys.shift()].send(taskMessage.concat([args]));
} else {
app.log("Executed [%s] on %d workers", id, done);
app.removeListener('worker_message', workerMessage);
}
}
app.on('worker_message', workerMessage = function(msg) {
if (isMessageForMe(msg) && msg[3] === 'done') {
nextWorker()
}
});
nextWorker();
} | [
"function",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"var",
"workerMessage",
",",
"done",
"=",
"0",
";",
"var",
"workerKeys",
"=",
"Object",
".",
"keys",
"(",
"cluster",
".",
"workers",
")",
";",
"var",
"nextWorker",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"workerKeys",
".",
"length",
")",
"{",
"done",
"++",
";",
"cluster",
".",
"workers",
"[",
"workerKeys",
".",
"shift",
"(",
")",
"]",
".",
"send",
"(",
"taskMessage",
".",
"concat",
"(",
"[",
"args",
"]",
")",
")",
";",
"}",
"else",
"{",
"app",
".",
"log",
"(",
"\"Executed [%s] on %d workers\"",
",",
"id",
",",
"done",
")",
";",
"app",
".",
"removeListener",
"(",
"'worker_message'",
",",
"workerMessage",
")",
";",
"}",
"}",
"app",
".",
"on",
"(",
"'worker_message'",
",",
"workerMessage",
"=",
"function",
"(",
"msg",
")",
"{",
"if",
"(",
"isMessageForMe",
"(",
"msg",
")",
"&&",
"msg",
"[",
"3",
"]",
"===",
"'done'",
")",
"{",
"nextWorker",
"(",
")",
"}",
"}",
")",
";",
"nextWorker",
"(",
")",
";",
"}"
] | Master 1. Listen for worker messages and send task to all workers on receive Sends a message to all workers to run the task | [
"Master",
"1",
".",
"Listen",
"for",
"worker",
"messages",
"and",
"send",
"task",
"to",
"all",
"workers",
"on",
"receive",
"Sends",
"a",
"message",
"to",
"all",
"workers",
"to",
"run",
"the",
"task"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L489-L508 |
|
50,672 | derdesign/protos | lib/application.js | buildPartialView | function buildPartialView(path) {
var self = this;
var layoutPrefix = /^layout_/;
var p = pathModule.basename(path);
var pos = p.indexOf('.');
var ext = p.slice(pos+1);
if (ext in this.enginesByExtension) {
var engine = this.enginesByExtension[ext];
var func = engine.renderPartial(path);
var id = path
.replace(this.mvcpath + 'views/', '')
.replace('/partials/', '/')
.replace(/\/+/g, '_')
.replace(/[_\-]+/g, '_')
.replace(/^_+/g, '');
// Note: the layout_ prefix needs to be removed from the name because
// the slash from the path has been replaced with an underscore.
id = id.slice(0, id.indexOf('.')).toLowerCase().replace(layoutPrefix, '');
// Normalize views to remove duplicate chunks within the filename
// For example: dashboard/dashboard-test will be accessed as {{> dashboard_test}}
// The added benefit of this method is that it will remove all duplicate subsequent
// occurrences of the same chunk, regardless.
id = id.split('_').reduce(function(prev, current) {
if (prev[0] !== current) prev.unshift(current);
return prev;
}, []).reverse().join('_');
func.id = id;
this.views.partials[id] = func;
} else {
throw new Error(util.format("Unable to render %s: engine not loaded", this.relPath(path)));
}
} | javascript | function buildPartialView(path) {
var self = this;
var layoutPrefix = /^layout_/;
var p = pathModule.basename(path);
var pos = p.indexOf('.');
var ext = p.slice(pos+1);
if (ext in this.enginesByExtension) {
var engine = this.enginesByExtension[ext];
var func = engine.renderPartial(path);
var id = path
.replace(this.mvcpath + 'views/', '')
.replace('/partials/', '/')
.replace(/\/+/g, '_')
.replace(/[_\-]+/g, '_')
.replace(/^_+/g, '');
// Note: the layout_ prefix needs to be removed from the name because
// the slash from the path has been replaced with an underscore.
id = id.slice(0, id.indexOf('.')).toLowerCase().replace(layoutPrefix, '');
// Normalize views to remove duplicate chunks within the filename
// For example: dashboard/dashboard-test will be accessed as {{> dashboard_test}}
// The added benefit of this method is that it will remove all duplicate subsequent
// occurrences of the same chunk, regardless.
id = id.split('_').reduce(function(prev, current) {
if (prev[0] !== current) prev.unshift(current);
return prev;
}, []).reverse().join('_');
func.id = id;
this.views.partials[id] = func;
} else {
throw new Error(util.format("Unable to render %s: engine not loaded", this.relPath(path)));
}
} | [
"function",
"buildPartialView",
"(",
"path",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"layoutPrefix",
"=",
"/",
"^layout_",
"/",
";",
"var",
"p",
"=",
"pathModule",
".",
"basename",
"(",
"path",
")",
";",
"var",
"pos",
"=",
"p",
".",
"indexOf",
"(",
"'.'",
")",
";",
"var",
"ext",
"=",
"p",
".",
"slice",
"(",
"pos",
"+",
"1",
")",
";",
"if",
"(",
"ext",
"in",
"this",
".",
"enginesByExtension",
")",
"{",
"var",
"engine",
"=",
"this",
".",
"enginesByExtension",
"[",
"ext",
"]",
";",
"var",
"func",
"=",
"engine",
".",
"renderPartial",
"(",
"path",
")",
";",
"var",
"id",
"=",
"path",
".",
"replace",
"(",
"this",
".",
"mvcpath",
"+",
"'views/'",
",",
"''",
")",
".",
"replace",
"(",
"'/partials/'",
",",
"'/'",
")",
".",
"replace",
"(",
"/",
"\\/+",
"/",
"g",
",",
"'_'",
")",
".",
"replace",
"(",
"/",
"[_\\-]+",
"/",
"g",
",",
"'_'",
")",
".",
"replace",
"(",
"/",
"^_+",
"/",
"g",
",",
"''",
")",
";",
"// Note: the layout_ prefix needs to be removed from the name because",
"// the slash from the path has been replaced with an underscore.",
"id",
"=",
"id",
".",
"slice",
"(",
"0",
",",
"id",
".",
"indexOf",
"(",
"'.'",
")",
")",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"layoutPrefix",
",",
"''",
")",
";",
"// Normalize views to remove duplicate chunks within the filename",
"// For example: dashboard/dashboard-test will be accessed as {{> dashboard_test}}",
"// The added benefit of this method is that it will remove all duplicate subsequent",
"// occurrences of the same chunk, regardless.",
"id",
"=",
"id",
".",
"split",
"(",
"'_'",
")",
".",
"reduce",
"(",
"function",
"(",
"prev",
",",
"current",
")",
"{",
"if",
"(",
"prev",
"[",
"0",
"]",
"!==",
"current",
")",
"prev",
".",
"unshift",
"(",
"current",
")",
";",
"return",
"prev",
";",
"}",
",",
"[",
"]",
")",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"'_'",
")",
";",
"func",
".",
"id",
"=",
"id",
";",
"this",
".",
"views",
".",
"partials",
"[",
"id",
"]",
"=",
"func",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"\"Unable to render %s: engine not loaded\"",
",",
"this",
".",
"relPath",
"(",
"path",
")",
")",
")",
";",
"}",
"}"
] | Builds a partial view and caches its function | [
"Builds",
"a",
"partial",
"view",
"and",
"caches",
"its",
"function"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L1910-L1954 |
50,673 | derdesign/protos | lib/application.js | getDriverInstance | function getDriverInstance(driver, config) {
if (!(driver in protos.drivers)) throw new Error(util.format("The '%s' driver is not loaded. Load it with app.loadDrivers('%s')", driver, driver));
return new protos.drivers[driver](config || {});
} | javascript | function getDriverInstance(driver, config) {
if (!(driver in protos.drivers)) throw new Error(util.format("The '%s' driver is not loaded. Load it with app.loadDrivers('%s')", driver, driver));
return new protos.drivers[driver](config || {});
} | [
"function",
"getDriverInstance",
"(",
"driver",
",",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"driver",
"in",
"protos",
".",
"drivers",
")",
")",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"\"The '%s' driver is not loaded. Load it with app.loadDrivers('%s')\"",
",",
"driver",
",",
"driver",
")",
")",
";",
"return",
"new",
"protos",
".",
"drivers",
"[",
"driver",
"]",
"(",
"config",
"||",
"{",
"}",
")",
";",
"}"
] | Returns a new driver instance | [
"Returns",
"a",
"new",
"driver",
"instance"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L1958-L1961 |
50,674 | derdesign/protos | lib/application.js | getStorageInstance | function getStorageInstance(storage, config) {
if (!(storage in protos.storages)) throw new Error(util.format("The '%s' storage is not loaded. Load it with app.loadStorages('%s')", storage, storage));
return new protos.storages[storage](config || {});
} | javascript | function getStorageInstance(storage, config) {
if (!(storage in protos.storages)) throw new Error(util.format("The '%s' storage is not loaded. Load it with app.loadStorages('%s')", storage, storage));
return new protos.storages[storage](config || {});
} | [
"function",
"getStorageInstance",
"(",
"storage",
",",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"storage",
"in",
"protos",
".",
"storages",
")",
")",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"\"The '%s' storage is not loaded. Load it with app.loadStorages('%s')\"",
",",
"storage",
",",
"storage",
")",
")",
";",
"return",
"new",
"protos",
".",
"storages",
"[",
"storage",
"]",
"(",
"config",
"||",
"{",
"}",
")",
";",
"}"
] | Returns a new storage instance | [
"Returns",
"a",
"new",
"storage",
"instance"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L1965-L1968 |
50,675 | derdesign/protos | lib/application.js | loadControllers | function loadControllers() {
// Note: runs on app context
// Get controllers/
var cpath = this.mvcpath + 'controllers/',
files = protos.util.getFiles(cpath);
// Create controllers and attach to app
var controllerCtor = protos.lib.controller;
for (var controller, key, file, instance, className, Ctor, i=0; i < files.length; i++) {
file = files[i];
key = file.replace(this.regex.jsFile, '');
className = file.replace(this.regex.jsFile, '');
Ctor = protos.require(cpath + className, true); // Don't use module cache (allow reloading)
Ctor = createControllerFunction.call(this, Ctor);
instance = new Ctor(this);
instance.className = instance.constructor.name;
this.controllers[key.replace(/_controller$/, '')] = instance;
}
this.controller = this.controllers.main;
this.emit('controllers_loaded', this.controllers);
} | javascript | function loadControllers() {
// Note: runs on app context
// Get controllers/
var cpath = this.mvcpath + 'controllers/',
files = protos.util.getFiles(cpath);
// Create controllers and attach to app
var controllerCtor = protos.lib.controller;
for (var controller, key, file, instance, className, Ctor, i=0; i < files.length; i++) {
file = files[i];
key = file.replace(this.regex.jsFile, '');
className = file.replace(this.regex.jsFile, '');
Ctor = protos.require(cpath + className, true); // Don't use module cache (allow reloading)
Ctor = createControllerFunction.call(this, Ctor);
instance = new Ctor(this);
instance.className = instance.constructor.name;
this.controllers[key.replace(/_controller$/, '')] = instance;
}
this.controller = this.controllers.main;
this.emit('controllers_loaded', this.controllers);
} | [
"function",
"loadControllers",
"(",
")",
"{",
"// Note: runs on app context",
"// Get controllers/",
"var",
"cpath",
"=",
"this",
".",
"mvcpath",
"+",
"'controllers/'",
",",
"files",
"=",
"protos",
".",
"util",
".",
"getFiles",
"(",
"cpath",
")",
";",
"// Create controllers and attach to app",
"var",
"controllerCtor",
"=",
"protos",
".",
"lib",
".",
"controller",
";",
"for",
"(",
"var",
"controller",
",",
"key",
",",
"file",
",",
"instance",
",",
"className",
",",
"Ctor",
",",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"key",
"=",
"file",
".",
"replace",
"(",
"this",
".",
"regex",
".",
"jsFile",
",",
"''",
")",
";",
"className",
"=",
"file",
".",
"replace",
"(",
"this",
".",
"regex",
".",
"jsFile",
",",
"''",
")",
";",
"Ctor",
"=",
"protos",
".",
"require",
"(",
"cpath",
"+",
"className",
",",
"true",
")",
";",
"// Don't use module cache (allow reloading)",
"Ctor",
"=",
"createControllerFunction",
".",
"call",
"(",
"this",
",",
"Ctor",
")",
";",
"instance",
"=",
"new",
"Ctor",
"(",
"this",
")",
";",
"instance",
".",
"className",
"=",
"instance",
".",
"constructor",
".",
"name",
";",
"this",
".",
"controllers",
"[",
"key",
".",
"replace",
"(",
"/",
"_controller$",
"/",
",",
"''",
")",
"]",
"=",
"instance",
";",
"}",
"this",
".",
"controller",
"=",
"this",
".",
"controllers",
".",
"main",
";",
"this",
".",
"emit",
"(",
"'controllers_loaded'",
",",
"this",
".",
"controllers",
")",
";",
"}"
] | Loads controllers & routes | [
"Loads",
"controllers",
"&",
"routes"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L1972-L1997 |
50,676 | derdesign/protos | lib/application.js | processControllerHandlers | function processControllerHandlers() {
var self = this;
var jsFile = this.regex.jsFile;
var handlersPath = this.mvcpath + 'handlers';
var relPath = self.relPath(this.mvcpath) + 'handlers';
if (fs.existsSync(handlersPath)) {
fs.readdirSync(handlersPath).forEach(function(dirname) {
var dir = handlersPath + '/' + dirname;
var stat = fs.statSync(dir);
if (stat.isDirectory(dir)) {
var handlers = self.handlers[dirname] = {};
fileModule.walkSync(dir, function(dirPath, dirs, files) {
for (var path,hkey,callback,file,i=0; i < files.length; i++) {
file = files[i];
path = dirPath + '/' + file;
hkey = self.relPath(path, pathModule.basename(self.mvcpath) + '/handlers/' + dirname);
if (jsFile.test(file)) {
callback = protos.require(path, true); // Don't use module cache (allow reloading)
if (callback instanceof Function) {
handlers[hkey] = callback;
} else {
throw new Error(util.format("Expected a function for handler: %s/%s", dirname, file));
}
}
}
});
}
});
}
this.emit('handlers_loaded', self.handlers); // Emit regardless
} | javascript | function processControllerHandlers() {
var self = this;
var jsFile = this.regex.jsFile;
var handlersPath = this.mvcpath + 'handlers';
var relPath = self.relPath(this.mvcpath) + 'handlers';
if (fs.existsSync(handlersPath)) {
fs.readdirSync(handlersPath).forEach(function(dirname) {
var dir = handlersPath + '/' + dirname;
var stat = fs.statSync(dir);
if (stat.isDirectory(dir)) {
var handlers = self.handlers[dirname] = {};
fileModule.walkSync(dir, function(dirPath, dirs, files) {
for (var path,hkey,callback,file,i=0; i < files.length; i++) {
file = files[i];
path = dirPath + '/' + file;
hkey = self.relPath(path, pathModule.basename(self.mvcpath) + '/handlers/' + dirname);
if (jsFile.test(file)) {
callback = protos.require(path, true); // Don't use module cache (allow reloading)
if (callback instanceof Function) {
handlers[hkey] = callback;
} else {
throw new Error(util.format("Expected a function for handler: %s/%s", dirname, file));
}
}
}
});
}
});
}
this.emit('handlers_loaded', self.handlers); // Emit regardless
} | [
"function",
"processControllerHandlers",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"jsFile",
"=",
"this",
".",
"regex",
".",
"jsFile",
";",
"var",
"handlersPath",
"=",
"this",
".",
"mvcpath",
"+",
"'handlers'",
";",
"var",
"relPath",
"=",
"self",
".",
"relPath",
"(",
"this",
".",
"mvcpath",
")",
"+",
"'handlers'",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"handlersPath",
")",
")",
"{",
"fs",
".",
"readdirSync",
"(",
"handlersPath",
")",
".",
"forEach",
"(",
"function",
"(",
"dirname",
")",
"{",
"var",
"dir",
"=",
"handlersPath",
"+",
"'/'",
"+",
"dirname",
";",
"var",
"stat",
"=",
"fs",
".",
"statSync",
"(",
"dir",
")",
";",
"if",
"(",
"stat",
".",
"isDirectory",
"(",
"dir",
")",
")",
"{",
"var",
"handlers",
"=",
"self",
".",
"handlers",
"[",
"dirname",
"]",
"=",
"{",
"}",
";",
"fileModule",
".",
"walkSync",
"(",
"dir",
",",
"function",
"(",
"dirPath",
",",
"dirs",
",",
"files",
")",
"{",
"for",
"(",
"var",
"path",
",",
"hkey",
",",
"callback",
",",
"file",
",",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"path",
"=",
"dirPath",
"+",
"'/'",
"+",
"file",
";",
"hkey",
"=",
"self",
".",
"relPath",
"(",
"path",
",",
"pathModule",
".",
"basename",
"(",
"self",
".",
"mvcpath",
")",
"+",
"'/handlers/'",
"+",
"dirname",
")",
";",
"if",
"(",
"jsFile",
".",
"test",
"(",
"file",
")",
")",
"{",
"callback",
"=",
"protos",
".",
"require",
"(",
"path",
",",
"true",
")",
";",
"// Don't use module cache (allow reloading)",
"if",
"(",
"callback",
"instanceof",
"Function",
")",
"{",
"handlers",
"[",
"hkey",
"]",
"=",
"callback",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"\"Expected a function for handler: %s/%s\"",
",",
"dirname",
",",
"file",
")",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"this",
".",
"emit",
"(",
"'handlers_loaded'",
",",
"self",
".",
"handlers",
")",
";",
"// Emit regardless",
"}"
] | Processes controller handlers | [
"Processes",
"controller",
"handlers"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2001-L2041 |
50,677 | derdesign/protos | lib/application.js | parseConfig | function parseConfig() {
// Get main config
var p = this.path + '/config/',
files = protos.util.getFiles(p),
mainPos = files.indexOf('base.js'),
jsExt = protos.regex.jsFile,
configFile = this.path + '/config.js';
// If config.js is not present, use the one from skeleton to provide defaults.
var config = (fs.existsSync(configFile)) ? require(configFile) : protos.require('skeleton/config.js');
var baseConfig = (mainPos !== -1) ? require(this.path + '/config/base.js') : {};
_.extend(config, baseConfig);
// Extend with config files
for (var file,key,cfg,i=0; i < files.length; i++) {
if (i==mainPos) continue;
file = files[i];
key = file.replace(jsExt, '');
cfg = require(this.path + '/config/' + file);
if (typeof config[key] == 'object') _.extend(config[key], cfg);
else config[key] = cfg;
}
// Return merged configuration object
return config;
} | javascript | function parseConfig() {
// Get main config
var p = this.path + '/config/',
files = protos.util.getFiles(p),
mainPos = files.indexOf('base.js'),
jsExt = protos.regex.jsFile,
configFile = this.path + '/config.js';
// If config.js is not present, use the one from skeleton to provide defaults.
var config = (fs.existsSync(configFile)) ? require(configFile) : protos.require('skeleton/config.js');
var baseConfig = (mainPos !== -1) ? require(this.path + '/config/base.js') : {};
_.extend(config, baseConfig);
// Extend with config files
for (var file,key,cfg,i=0; i < files.length; i++) {
if (i==mainPos) continue;
file = files[i];
key = file.replace(jsExt, '');
cfg = require(this.path + '/config/' + file);
if (typeof config[key] == 'object') _.extend(config[key], cfg);
else config[key] = cfg;
}
// Return merged configuration object
return config;
} | [
"function",
"parseConfig",
"(",
")",
"{",
"// Get main config",
"var",
"p",
"=",
"this",
".",
"path",
"+",
"'/config/'",
",",
"files",
"=",
"protos",
".",
"util",
".",
"getFiles",
"(",
"p",
")",
",",
"mainPos",
"=",
"files",
".",
"indexOf",
"(",
"'base.js'",
")",
",",
"jsExt",
"=",
"protos",
".",
"regex",
".",
"jsFile",
",",
"configFile",
"=",
"this",
".",
"path",
"+",
"'/config.js'",
";",
"// If config.js is not present, use the one from skeleton to provide defaults.",
"var",
"config",
"=",
"(",
"fs",
".",
"existsSync",
"(",
"configFile",
")",
")",
"?",
"require",
"(",
"configFile",
")",
":",
"protos",
".",
"require",
"(",
"'skeleton/config.js'",
")",
";",
"var",
"baseConfig",
"=",
"(",
"mainPos",
"!==",
"-",
"1",
")",
"?",
"require",
"(",
"this",
".",
"path",
"+",
"'/config/base.js'",
")",
":",
"{",
"}",
";",
"_",
".",
"extend",
"(",
"config",
",",
"baseConfig",
")",
";",
"// Extend with config files",
"for",
"(",
"var",
"file",
",",
"key",
",",
"cfg",
",",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"==",
"mainPos",
")",
"continue",
";",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"key",
"=",
"file",
".",
"replace",
"(",
"jsExt",
",",
"''",
")",
";",
"cfg",
"=",
"require",
"(",
"this",
".",
"path",
"+",
"'/config/'",
"+",
"file",
")",
";",
"if",
"(",
"typeof",
"config",
"[",
"key",
"]",
"==",
"'object'",
")",
"_",
".",
"extend",
"(",
"config",
"[",
"key",
"]",
",",
"cfg",
")",
";",
"else",
"config",
"[",
"key",
"]",
"=",
"cfg",
";",
"}",
"// Return merged configuration object",
"return",
"config",
";",
"}"
] | Parses the application configuration | [
"Parses",
"the",
"application",
"configuration"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2045-L2074 |
50,678 | derdesign/protos | lib/application.js | watchPartial | function watchPartial(path, callback) {
// Don't watch partials again when reloading
if (this.watchPartials && RELOADING === false) {
var self = this;
self.debug('Watching Partial for changes: %s', self.relPath(path, 'app/views'));
var watcher = chokidar.watch(path, {interval: self.config.watchInterval || 100});
watcher.on('change', function() {
self.debug("Regeneraging view partial", self.relPath(path));
callback.call(self, path);
});
watcher.on('unlink', function() {
self.log(util.format("Stopped watching partial '%s' (renamed)", self.relPath(path)));
watcher.close();
});
watcher.on('error', function(err) {
self.log(util.format("Stopped watching partial '%s' (error)", self.relPath(path)));
self.log(err.stack);
watcher.close();
});
}
} | javascript | function watchPartial(path, callback) {
// Don't watch partials again when reloading
if (this.watchPartials && RELOADING === false) {
var self = this;
self.debug('Watching Partial for changes: %s', self.relPath(path, 'app/views'));
var watcher = chokidar.watch(path, {interval: self.config.watchInterval || 100});
watcher.on('change', function() {
self.debug("Regeneraging view partial", self.relPath(path));
callback.call(self, path);
});
watcher.on('unlink', function() {
self.log(util.format("Stopped watching partial '%s' (renamed)", self.relPath(path)));
watcher.close();
});
watcher.on('error', function(err) {
self.log(util.format("Stopped watching partial '%s' (error)", self.relPath(path)));
self.log(err.stack);
watcher.close();
});
}
} | [
"function",
"watchPartial",
"(",
"path",
",",
"callback",
")",
"{",
"// Don't watch partials again when reloading",
"if",
"(",
"this",
".",
"watchPartials",
"&&",
"RELOADING",
"===",
"false",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"debug",
"(",
"'Watching Partial for changes: %s'",
",",
"self",
".",
"relPath",
"(",
"path",
",",
"'app/views'",
")",
")",
";",
"var",
"watcher",
"=",
"chokidar",
".",
"watch",
"(",
"path",
",",
"{",
"interval",
":",
"self",
".",
"config",
".",
"watchInterval",
"||",
"100",
"}",
")",
";",
"watcher",
".",
"on",
"(",
"'change'",
",",
"function",
"(",
")",
"{",
"self",
".",
"debug",
"(",
"\"Regeneraging view partial\"",
",",
"self",
".",
"relPath",
"(",
"path",
")",
")",
";",
"callback",
".",
"call",
"(",
"self",
",",
"path",
")",
";",
"}",
")",
";",
"watcher",
".",
"on",
"(",
"'unlink'",
",",
"function",
"(",
")",
"{",
"self",
".",
"log",
"(",
"util",
".",
"format",
"(",
"\"Stopped watching partial '%s' (renamed)\"",
",",
"self",
".",
"relPath",
"(",
"path",
")",
")",
")",
";",
"watcher",
".",
"close",
"(",
")",
";",
"}",
")",
";",
"watcher",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"self",
".",
"log",
"(",
"util",
".",
"format",
"(",
"\"Stopped watching partial '%s' (error)\"",
",",
"self",
".",
"relPath",
"(",
"path",
")",
")",
")",
";",
"self",
".",
"log",
"(",
"err",
".",
"stack",
")",
";",
"watcher",
".",
"close",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] | Watches a view Partial for changes | [
"Watches",
"a",
"view",
"Partial",
"for",
"changes"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2078-L2107 |
50,679 | derdesign/protos | lib/application.js | parseDriverConfig | function parseDriverConfig() {
var cfg, def, x, y, z,
config = this.config.drivers,
drivers = this.drivers;
if (!config) config = this.config.drivers = {};
if (Object.keys(config).length === 0) return;
for (x in config) {
cfg = config[x];
if (x == 'default') { def = cfg; continue; }
for (y in cfg) {
if (typeof cfg[y] == 'object') {
if (typeof drivers[x] == 'undefined') drivers[x] = {};
drivers[x][y] = [x, cfg[y]];
} else {
drivers[x] = [x, cfg];
break;
}
}
}
} | javascript | function parseDriverConfig() {
var cfg, def, x, y, z,
config = this.config.drivers,
drivers = this.drivers;
if (!config) config = this.config.drivers = {};
if (Object.keys(config).length === 0) return;
for (x in config) {
cfg = config[x];
if (x == 'default') { def = cfg; continue; }
for (y in cfg) {
if (typeof cfg[y] == 'object') {
if (typeof drivers[x] == 'undefined') drivers[x] = {};
drivers[x][y] = [x, cfg[y]];
} else {
drivers[x] = [x, cfg];
break;
}
}
}
} | [
"function",
"parseDriverConfig",
"(",
")",
"{",
"var",
"cfg",
",",
"def",
",",
"x",
",",
"y",
",",
"z",
",",
"config",
"=",
"this",
".",
"config",
".",
"drivers",
",",
"drivers",
"=",
"this",
".",
"drivers",
";",
"if",
"(",
"!",
"config",
")",
"config",
"=",
"this",
".",
"config",
".",
"drivers",
"=",
"{",
"}",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"config",
")",
".",
"length",
"===",
"0",
")",
"return",
";",
"for",
"(",
"x",
"in",
"config",
")",
"{",
"cfg",
"=",
"config",
"[",
"x",
"]",
";",
"if",
"(",
"x",
"==",
"'default'",
")",
"{",
"def",
"=",
"cfg",
";",
"continue",
";",
"}",
"for",
"(",
"y",
"in",
"cfg",
")",
"{",
"if",
"(",
"typeof",
"cfg",
"[",
"y",
"]",
"==",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"drivers",
"[",
"x",
"]",
"==",
"'undefined'",
")",
"drivers",
"[",
"x",
"]",
"=",
"{",
"}",
";",
"drivers",
"[",
"x",
"]",
"[",
"y",
"]",
"=",
"[",
"x",
",",
"cfg",
"[",
"y",
"]",
"]",
";",
"}",
"else",
"{",
"drivers",
"[",
"x",
"]",
"=",
"[",
"x",
",",
"cfg",
"]",
";",
"break",
";",
"}",
"}",
"}",
"}"
] | Parses database drivers from config | [
"Parses",
"database",
"drivers",
"from",
"config"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2111-L2134 |
50,680 | derdesign/protos | lib/application.js | parseStorageConfig | function parseStorageConfig() {
var cfg, x, y, z,
config = this.config.storages,
storages = this.storages;
if (!config) config = this.config.storages = {};
if (Object.keys(config).length === 0) return;
for (x in config) {
cfg = config[x];
for (y in cfg) {
if (typeof cfg[y] == 'object') {
if (typeof storages[x] == 'undefined') storages[x] = {};
storages[x][y] = [x, cfg[y]];
} else {
storages[x] = [x, cfg];
break;
}
}
}
} | javascript | function parseStorageConfig() {
var cfg, x, y, z,
config = this.config.storages,
storages = this.storages;
if (!config) config = this.config.storages = {};
if (Object.keys(config).length === 0) return;
for (x in config) {
cfg = config[x];
for (y in cfg) {
if (typeof cfg[y] == 'object') {
if (typeof storages[x] == 'undefined') storages[x] = {};
storages[x][y] = [x, cfg[y]];
} else {
storages[x] = [x, cfg];
break;
}
}
}
} | [
"function",
"parseStorageConfig",
"(",
")",
"{",
"var",
"cfg",
",",
"x",
",",
"y",
",",
"z",
",",
"config",
"=",
"this",
".",
"config",
".",
"storages",
",",
"storages",
"=",
"this",
".",
"storages",
";",
"if",
"(",
"!",
"config",
")",
"config",
"=",
"this",
".",
"config",
".",
"storages",
"=",
"{",
"}",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"config",
")",
".",
"length",
"===",
"0",
")",
"return",
";",
"for",
"(",
"x",
"in",
"config",
")",
"{",
"cfg",
"=",
"config",
"[",
"x",
"]",
";",
"for",
"(",
"y",
"in",
"cfg",
")",
"{",
"if",
"(",
"typeof",
"cfg",
"[",
"y",
"]",
"==",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"storages",
"[",
"x",
"]",
"==",
"'undefined'",
")",
"storages",
"[",
"x",
"]",
"=",
"{",
"}",
";",
"storages",
"[",
"x",
"]",
"[",
"y",
"]",
"=",
"[",
"x",
",",
"cfg",
"[",
"y",
"]",
"]",
";",
"}",
"else",
"{",
"storages",
"[",
"x",
"]",
"=",
"[",
"x",
",",
"cfg",
"]",
";",
"break",
";",
"}",
"}",
"}",
"}"
] | Parses storages from config | [
"Parses",
"storages",
"from",
"config"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2138-L2159 |
50,681 | derdesign/protos | lib/application.js | loadAPI | function loadAPI() {
var apiPath = this.fullPath(this.paths.api);
if (fs.existsSync(apiPath) && fs.statSync(apiPath).isDirectory()) {
var files = protos.util.ls(apiPath, this.regex.jsFile);
files.forEach(function(file) {
var methods = protos.require(apiPath + "/" + file, true); // Don't use module cache (allow reloading)
_.extend(this.api, methods);
}, this);
}
this.emit('api_loaded', this.api);
} | javascript | function loadAPI() {
var apiPath = this.fullPath(this.paths.api);
if (fs.existsSync(apiPath) && fs.statSync(apiPath).isDirectory()) {
var files = protos.util.ls(apiPath, this.regex.jsFile);
files.forEach(function(file) {
var methods = protos.require(apiPath + "/" + file, true); // Don't use module cache (allow reloading)
_.extend(this.api, methods);
}, this);
}
this.emit('api_loaded', this.api);
} | [
"function",
"loadAPI",
"(",
")",
"{",
"var",
"apiPath",
"=",
"this",
".",
"fullPath",
"(",
"this",
".",
"paths",
".",
"api",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"apiPath",
")",
"&&",
"fs",
".",
"statSync",
"(",
"apiPath",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"var",
"files",
"=",
"protos",
".",
"util",
".",
"ls",
"(",
"apiPath",
",",
"this",
".",
"regex",
".",
"jsFile",
")",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"methods",
"=",
"protos",
".",
"require",
"(",
"apiPath",
"+",
"\"/\"",
"+",
"file",
",",
"true",
")",
";",
"// Don't use module cache (allow reloading)",
"_",
".",
"extend",
"(",
"this",
".",
"api",
",",
"methods",
")",
";",
"}",
",",
"this",
")",
";",
"}",
"this",
".",
"emit",
"(",
"'api_loaded'",
",",
"this",
".",
"api",
")",
";",
"}"
] | Loads the Application API | [
"Loads",
"the",
"Application",
"API"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2289-L2299 |
50,682 | derdesign/protos | lib/application.js | loadHooks | function loadHooks() {
var events = this._events;
var jsFile = /\.js$/i;
var hooksPath = this.fullPath('hook');
var loadedHooks = [];
if (fs.existsSync(hooksPath)) {
var files = protos.util.ls(hooksPath, jsFile);
for (var cb,idx,evt,file,len=files.length,i=0; i < len; i++) {
file = files[i];
evt = file.replace(jsFile, '');
loadedHooks.push(evt);
cb = protos.require(hooksPath + '/' + file, true);
if (cb instanceof Function) {
if (RELOADING) {
var origCb = this.hooks[evt];
if (origCb instanceof Function) {
// Hook was added previously
if (events[evt] instanceof Array) {
idx = events[evt].indexOf(origCb);
if (idx >= 0) {
// If old function is in events array, replace it
events[evt][idx] = this.hooks[evt] = cb;
} else {
// Otherwise, append to events array (add a new event handler)
events[evt].push(cb);
this.hooks[evt] = cb;
}
} else if (events[evt] instanceof Function) {
if (events[evt] === origCb) {
// If evt has only one callback, replace it
events[evt] = this.hooks[evt] = cb;
} else {
// Otherwise, create an array with the old and new events
events[evt] = [origCb, cb];
}
} // No else clause is needed here, it's either Function or Array
} else {
// This is a new event handler
this.hooks[evt] = cb;
this.on(evt, cb);
}
} else {
// Add the event handler normally
this.hooks[evt] = cb;
this.on(evt, cb);
}
}
}
}
// Remove any inexisting hooks
for (evt in this.hooks) {
if (loadedHooks.indexOf(evt) === -1) {
app.removeListener(evt, this.hooks[evt]);
delete this.hooks[evt];
}
}
} | javascript | function loadHooks() {
var events = this._events;
var jsFile = /\.js$/i;
var hooksPath = this.fullPath('hook');
var loadedHooks = [];
if (fs.existsSync(hooksPath)) {
var files = protos.util.ls(hooksPath, jsFile);
for (var cb,idx,evt,file,len=files.length,i=0; i < len; i++) {
file = files[i];
evt = file.replace(jsFile, '');
loadedHooks.push(evt);
cb = protos.require(hooksPath + '/' + file, true);
if (cb instanceof Function) {
if (RELOADING) {
var origCb = this.hooks[evt];
if (origCb instanceof Function) {
// Hook was added previously
if (events[evt] instanceof Array) {
idx = events[evt].indexOf(origCb);
if (idx >= 0) {
// If old function is in events array, replace it
events[evt][idx] = this.hooks[evt] = cb;
} else {
// Otherwise, append to events array (add a new event handler)
events[evt].push(cb);
this.hooks[evt] = cb;
}
} else if (events[evt] instanceof Function) {
if (events[evt] === origCb) {
// If evt has only one callback, replace it
events[evt] = this.hooks[evt] = cb;
} else {
// Otherwise, create an array with the old and new events
events[evt] = [origCb, cb];
}
} // No else clause is needed here, it's either Function or Array
} else {
// This is a new event handler
this.hooks[evt] = cb;
this.on(evt, cb);
}
} else {
// Add the event handler normally
this.hooks[evt] = cb;
this.on(evt, cb);
}
}
}
}
// Remove any inexisting hooks
for (evt in this.hooks) {
if (loadedHooks.indexOf(evt) === -1) {
app.removeListener(evt, this.hooks[evt]);
delete this.hooks[evt];
}
}
} | [
"function",
"loadHooks",
"(",
")",
"{",
"var",
"events",
"=",
"this",
".",
"_events",
";",
"var",
"jsFile",
"=",
"/",
"\\.js$",
"/",
"i",
";",
"var",
"hooksPath",
"=",
"this",
".",
"fullPath",
"(",
"'hook'",
")",
";",
"var",
"loadedHooks",
"=",
"[",
"]",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"hooksPath",
")",
")",
"{",
"var",
"files",
"=",
"protos",
".",
"util",
".",
"ls",
"(",
"hooksPath",
",",
"jsFile",
")",
";",
"for",
"(",
"var",
"cb",
",",
"idx",
",",
"evt",
",",
"file",
",",
"len",
"=",
"files",
".",
"length",
",",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"evt",
"=",
"file",
".",
"replace",
"(",
"jsFile",
",",
"''",
")",
";",
"loadedHooks",
".",
"push",
"(",
"evt",
")",
";",
"cb",
"=",
"protos",
".",
"require",
"(",
"hooksPath",
"+",
"'/'",
"+",
"file",
",",
"true",
")",
";",
"if",
"(",
"cb",
"instanceof",
"Function",
")",
"{",
"if",
"(",
"RELOADING",
")",
"{",
"var",
"origCb",
"=",
"this",
".",
"hooks",
"[",
"evt",
"]",
";",
"if",
"(",
"origCb",
"instanceof",
"Function",
")",
"{",
"// Hook was added previously",
"if",
"(",
"events",
"[",
"evt",
"]",
"instanceof",
"Array",
")",
"{",
"idx",
"=",
"events",
"[",
"evt",
"]",
".",
"indexOf",
"(",
"origCb",
")",
";",
"if",
"(",
"idx",
">=",
"0",
")",
"{",
"// If old function is in events array, replace it",
"events",
"[",
"evt",
"]",
"[",
"idx",
"]",
"=",
"this",
".",
"hooks",
"[",
"evt",
"]",
"=",
"cb",
";",
"}",
"else",
"{",
"// Otherwise, append to events array (add a new event handler)",
"events",
"[",
"evt",
"]",
".",
"push",
"(",
"cb",
")",
";",
"this",
".",
"hooks",
"[",
"evt",
"]",
"=",
"cb",
";",
"}",
"}",
"else",
"if",
"(",
"events",
"[",
"evt",
"]",
"instanceof",
"Function",
")",
"{",
"if",
"(",
"events",
"[",
"evt",
"]",
"===",
"origCb",
")",
"{",
"// If evt has only one callback, replace it",
"events",
"[",
"evt",
"]",
"=",
"this",
".",
"hooks",
"[",
"evt",
"]",
"=",
"cb",
";",
"}",
"else",
"{",
"// Otherwise, create an array with the old and new events",
"events",
"[",
"evt",
"]",
"=",
"[",
"origCb",
",",
"cb",
"]",
";",
"}",
"}",
"// No else clause is needed here, it's either Function or Array",
"}",
"else",
"{",
"// This is a new event handler",
"this",
".",
"hooks",
"[",
"evt",
"]",
"=",
"cb",
";",
"this",
".",
"on",
"(",
"evt",
",",
"cb",
")",
";",
"}",
"}",
"else",
"{",
"// Add the event handler normally",
"this",
".",
"hooks",
"[",
"evt",
"]",
"=",
"cb",
";",
"this",
".",
"on",
"(",
"evt",
",",
"cb",
")",
";",
"}",
"}",
"}",
"}",
"// Remove any inexisting hooks",
"for",
"(",
"evt",
"in",
"this",
".",
"hooks",
")",
"{",
"if",
"(",
"loadedHooks",
".",
"indexOf",
"(",
"evt",
")",
"===",
"-",
"1",
")",
"{",
"app",
".",
"removeListener",
"(",
"evt",
",",
"this",
".",
"hooks",
"[",
"evt",
"]",
")",
";",
"delete",
"this",
".",
"hooks",
"[",
"evt",
"]",
";",
"}",
"}",
"}"
] | Loads application hooks | [
"Loads",
"application",
"hooks"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2303-L2361 |
50,683 | derdesign/protos | lib/application.js | loadEngines | function loadEngines() {
// Initialize engine properties
this.enginesByExtension = {};
// Engine local variables
var exts = [];
var loadedEngines = this.loadedEngines = Object.keys(protos.engines);
if (loadedEngines.length > 0) {
// Get view engines
var engine, instance, engineProps = ['className', 'extensions'];
for (engine in protos.engines) {
instance = new protos.engines[engine]();
instance.className = instance.constructor.name;
protos.util.onlySetEnumerable(instance, engineProps);
this.engines[engine] = instance;
}
// Register engine extensions
for (var key in this.engines) {
engine = this.engines[key];
exts = exts.concat(engine.extensions);
for (var i=0; i < engine.extensions.length; i++) {
key = engine.extensions[i];
this.enginesByExtension[key] = engine;
}
}
// Set default view extension if not set
if (typeof this.config.viewExtensions.html == 'undefined') {
this.config.viewExtensions.html = 'ejs';
}
// Override engine extensions (from config)
var ext, extOverrides = this.config.viewExtensions;
for (ext in extOverrides) {
if (exts.indexOf(ext) == -1) exts.push(ext); // Register extension on `exts`
engine = this.engines[extOverrides[ext]]; // Get engine object
if (engine) {
engine.extensions.push(ext); // Add ext to engine extensions
this.enginesByExtension[ext] = engine; // Override engine extension
} else {
this.debug(util.format("Ignoring '%s' extension: the '%s' engine is not loaded"), ext, extOverrides[ext]);
}
}
// Set default template engine
this.defaultEngine = (this.engines.ejs || this.engines[loadedEngines[0]]);
// Add the engines regular expression
this.engineRegex = new RegExp('^(' + Object.keys(this.engines).join('|').replace(/\-/, '\\-') + ')$');
}
// Generate template file regex from registered template extensions
this.regex.templateFile = new RegExp('\\.(' + exts.join('|') + ')$');
this.templateExtensions = exts;
this.emit('engines_loaded', this.engines); // Emit regardless
} | javascript | function loadEngines() {
// Initialize engine properties
this.enginesByExtension = {};
// Engine local variables
var exts = [];
var loadedEngines = this.loadedEngines = Object.keys(protos.engines);
if (loadedEngines.length > 0) {
// Get view engines
var engine, instance, engineProps = ['className', 'extensions'];
for (engine in protos.engines) {
instance = new protos.engines[engine]();
instance.className = instance.constructor.name;
protos.util.onlySetEnumerable(instance, engineProps);
this.engines[engine] = instance;
}
// Register engine extensions
for (var key in this.engines) {
engine = this.engines[key];
exts = exts.concat(engine.extensions);
for (var i=0; i < engine.extensions.length; i++) {
key = engine.extensions[i];
this.enginesByExtension[key] = engine;
}
}
// Set default view extension if not set
if (typeof this.config.viewExtensions.html == 'undefined') {
this.config.viewExtensions.html = 'ejs';
}
// Override engine extensions (from config)
var ext, extOverrides = this.config.viewExtensions;
for (ext in extOverrides) {
if (exts.indexOf(ext) == -1) exts.push(ext); // Register extension on `exts`
engine = this.engines[extOverrides[ext]]; // Get engine object
if (engine) {
engine.extensions.push(ext); // Add ext to engine extensions
this.enginesByExtension[ext] = engine; // Override engine extension
} else {
this.debug(util.format("Ignoring '%s' extension: the '%s' engine is not loaded"), ext, extOverrides[ext]);
}
}
// Set default template engine
this.defaultEngine = (this.engines.ejs || this.engines[loadedEngines[0]]);
// Add the engines regular expression
this.engineRegex = new RegExp('^(' + Object.keys(this.engines).join('|').replace(/\-/, '\\-') + ')$');
}
// Generate template file regex from registered template extensions
this.regex.templateFile = new RegExp('\\.(' + exts.join('|') + ')$');
this.templateExtensions = exts;
this.emit('engines_loaded', this.engines); // Emit regardless
} | [
"function",
"loadEngines",
"(",
")",
"{",
"// Initialize engine properties",
"this",
".",
"enginesByExtension",
"=",
"{",
"}",
";",
"// Engine local variables",
"var",
"exts",
"=",
"[",
"]",
";",
"var",
"loadedEngines",
"=",
"this",
".",
"loadedEngines",
"=",
"Object",
".",
"keys",
"(",
"protos",
".",
"engines",
")",
";",
"if",
"(",
"loadedEngines",
".",
"length",
">",
"0",
")",
"{",
"// Get view engines",
"var",
"engine",
",",
"instance",
",",
"engineProps",
"=",
"[",
"'className'",
",",
"'extensions'",
"]",
";",
"for",
"(",
"engine",
"in",
"protos",
".",
"engines",
")",
"{",
"instance",
"=",
"new",
"protos",
".",
"engines",
"[",
"engine",
"]",
"(",
")",
";",
"instance",
".",
"className",
"=",
"instance",
".",
"constructor",
".",
"name",
";",
"protos",
".",
"util",
".",
"onlySetEnumerable",
"(",
"instance",
",",
"engineProps",
")",
";",
"this",
".",
"engines",
"[",
"engine",
"]",
"=",
"instance",
";",
"}",
"// Register engine extensions",
"for",
"(",
"var",
"key",
"in",
"this",
".",
"engines",
")",
"{",
"engine",
"=",
"this",
".",
"engines",
"[",
"key",
"]",
";",
"exts",
"=",
"exts",
".",
"concat",
"(",
"engine",
".",
"extensions",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"engine",
".",
"extensions",
".",
"length",
";",
"i",
"++",
")",
"{",
"key",
"=",
"engine",
".",
"extensions",
"[",
"i",
"]",
";",
"this",
".",
"enginesByExtension",
"[",
"key",
"]",
"=",
"engine",
";",
"}",
"}",
"// Set default view extension if not set",
"if",
"(",
"typeof",
"this",
".",
"config",
".",
"viewExtensions",
".",
"html",
"==",
"'undefined'",
")",
"{",
"this",
".",
"config",
".",
"viewExtensions",
".",
"html",
"=",
"'ejs'",
";",
"}",
"// Override engine extensions (from config)",
"var",
"ext",
",",
"extOverrides",
"=",
"this",
".",
"config",
".",
"viewExtensions",
";",
"for",
"(",
"ext",
"in",
"extOverrides",
")",
"{",
"if",
"(",
"exts",
".",
"indexOf",
"(",
"ext",
")",
"==",
"-",
"1",
")",
"exts",
".",
"push",
"(",
"ext",
")",
";",
"// Register extension on `exts`",
"engine",
"=",
"this",
".",
"engines",
"[",
"extOverrides",
"[",
"ext",
"]",
"]",
";",
"// Get engine object",
"if",
"(",
"engine",
")",
"{",
"engine",
".",
"extensions",
".",
"push",
"(",
"ext",
")",
";",
"// Add ext to engine extensions",
"this",
".",
"enginesByExtension",
"[",
"ext",
"]",
"=",
"engine",
";",
"// Override engine extension",
"}",
"else",
"{",
"this",
".",
"debug",
"(",
"util",
".",
"format",
"(",
"\"Ignoring '%s' extension: the '%s' engine is not loaded\"",
")",
",",
"ext",
",",
"extOverrides",
"[",
"ext",
"]",
")",
";",
"}",
"}",
"// Set default template engine",
"this",
".",
"defaultEngine",
"=",
"(",
"this",
".",
"engines",
".",
"ejs",
"||",
"this",
".",
"engines",
"[",
"loadedEngines",
"[",
"0",
"]",
"]",
")",
";",
"// Add the engines regular expression",
"this",
".",
"engineRegex",
"=",
"new",
"RegExp",
"(",
"'^('",
"+",
"Object",
".",
"keys",
"(",
"this",
".",
"engines",
")",
".",
"join",
"(",
"'|'",
")",
".",
"replace",
"(",
"/",
"\\-",
"/",
",",
"'\\\\-'",
")",
"+",
"')$'",
")",
";",
"}",
"// Generate template file regex from registered template extensions",
"this",
".",
"regex",
".",
"templateFile",
"=",
"new",
"RegExp",
"(",
"'\\\\.('",
"+",
"exts",
".",
"join",
"(",
"'|'",
")",
"+",
"')$'",
")",
";",
"this",
".",
"templateExtensions",
"=",
"exts",
";",
"this",
".",
"emit",
"(",
"'engines_loaded'",
",",
"this",
".",
"engines",
")",
";",
"// Emit regardless",
"}"
] | Loads view engines | [
"Loads",
"view",
"engines"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2365-L2428 |
50,684 | derdesign/protos | lib/application.js | buildTemplatePartial | function buildTemplatePartial(path) {
var tplDir = app.mvcpath + app.paths.templates;
var p = path.replace(tplDir, '');
var pos = p.indexOf('.');
var ext = p.slice(pos+1);
var tpl = p.slice(0,pos);
if (ext in this.enginesByExtension) {
var engine = this.enginesByExtension[ext];
var func = engine.renderPartial(path);
func.engine = engine;
func.ext = ext;
this.templates[tpl] = func;
} else {
throw new Error(util.format("Unable to render %s: engine not loaded", this.relPath(path)));
}
} | javascript | function buildTemplatePartial(path) {
var tplDir = app.mvcpath + app.paths.templates;
var p = path.replace(tplDir, '');
var pos = p.indexOf('.');
var ext = p.slice(pos+1);
var tpl = p.slice(0,pos);
if (ext in this.enginesByExtension) {
var engine = this.enginesByExtension[ext];
var func = engine.renderPartial(path);
func.engine = engine;
func.ext = ext;
this.templates[tpl] = func;
} else {
throw new Error(util.format("Unable to render %s: engine not loaded", this.relPath(path)));
}
} | [
"function",
"buildTemplatePartial",
"(",
"path",
")",
"{",
"var",
"tplDir",
"=",
"app",
".",
"mvcpath",
"+",
"app",
".",
"paths",
".",
"templates",
";",
"var",
"p",
"=",
"path",
".",
"replace",
"(",
"tplDir",
",",
"''",
")",
";",
"var",
"pos",
"=",
"p",
".",
"indexOf",
"(",
"'.'",
")",
";",
"var",
"ext",
"=",
"p",
".",
"slice",
"(",
"pos",
"+",
"1",
")",
";",
"var",
"tpl",
"=",
"p",
".",
"slice",
"(",
"0",
",",
"pos",
")",
";",
"if",
"(",
"ext",
"in",
"this",
".",
"enginesByExtension",
")",
"{",
"var",
"engine",
"=",
"this",
".",
"enginesByExtension",
"[",
"ext",
"]",
";",
"var",
"func",
"=",
"engine",
".",
"renderPartial",
"(",
"path",
")",
";",
"func",
".",
"engine",
"=",
"engine",
";",
"func",
".",
"ext",
"=",
"ext",
";",
"this",
".",
"templates",
"[",
"tpl",
"]",
"=",
"func",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"util",
".",
"format",
"(",
"\"Unable to render %s: engine not loaded\"",
",",
"this",
".",
"relPath",
"(",
"path",
")",
")",
")",
";",
"}",
"}"
] | Builds a template partial | [
"Builds",
"a",
"template",
"partial"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2542-L2566 |
50,685 | derdesign/protos | lib/application.js | setupViewPartials | function setupViewPartials() {
// Set view path association object
this.views.pathAsoc = {};
// Partial & template regexes
var self = this;
var exts = this.templateExtensions;
var partialRegex = new RegExp('\/views\/(.+)\/partials\/[a-zA-Z0-9-_]+\\.(' + exts.join('|') + ')$');
var templateRegex = new RegExp('\\.(' + exts.join('|') + ')$');
var layoutPath = this.mvcpath + 'views/' + this.paths.layout;
var viewsPath = this.mvcpath + 'views';
var partialPaths = [];
if (fs.existsSync(viewsPath)) {
fileModule.walkSync(viewsPath, function(dirPath, dirs, files) {
for (var path,file,i=0; i < files.length; i++) {
file = files[i];
path = dirPath + "/" + file;
if (partialRegex.test(path)) {
// Only build valid partial views
partialPaths.push(path);
buildPartialView.call(self, path);
watchPartial.call(self, path, buildPartialView);
} else if (templateRegex.test(file)) {
// Build partial views for everything inside app.paths.layout
if (path.indexOf(layoutPath) === 0) {
partialPaths.push(path);
buildPartialView.call(self, path);
watchPartial.call(self, path, buildPartialView);
}
// Only add valid templates to view associations
self.views.pathAsoc[self.relPath(path.replace(self.regex.templateFile, ''))] = path;
}
}
});
}
// Add Builtin Partials
var Helper = protos.lib.helper;
var builtinHelper = new Helper();
for (var m in builtinHelper) {
if (builtinHelper[m] instanceof Function) {
this.registerViewHelper(m, builtinHelper[m], builtinHelper);
}
}
// Helper Partials
Object.keys(this.helpers).forEach(function(alias) {
var m, method, hkey, helper = self.helpers[alias];
for (m in helper) {
if (helper[m] instanceof Function) {
method = helper[m];
hkey = (alias == 'main')
? util.format('%s', m)
: util.format('%s_%s', alias, m);
self.registerViewHelper(hkey, method, helper);
}
}
});
// Event when view partials are loaded
this.emit('view_partials_loaded', this.views.partials);
// Set shortcode context
// NOTE: Automatically resets on hot code loading, so it's good.
var shortcodeContext = this.__shortcodeContext = {};
// Only add shortcode filter to context if enabled on config
if (this.config.shortcodeFilter) {
// Register shortcodes from partials
var shortcode = self.shortcode;
var partials = self.views.partials;
Object.keys(this.views.partials).forEach(function(partial) {
if (partial[0] === '$') {
shortcodeContext[partial.replace(/^\$/, '#')] = self.views.partials[partial];
} else {
shortcodeContext[partial] = function(buf, params, locals) {
if (buf) params.content = buf; // Provide wrapped content in params.content
params.__proto__ = locals; // Set locals as prototype of params
return partials[partial].call(null, params); // Provide params to partial, which is passed as locals
}
}
});
this.addFilter('context', function(buf, locals) {
buf = this.shortcode.parse(buf, locals, shortcodeContext);
return buf;
});
}
// Event when view shortcodes are loaded
this.emit('view_shortcodes_loaded', shortcodeContext);
} | javascript | function setupViewPartials() {
// Set view path association object
this.views.pathAsoc = {};
// Partial & template regexes
var self = this;
var exts = this.templateExtensions;
var partialRegex = new RegExp('\/views\/(.+)\/partials\/[a-zA-Z0-9-_]+\\.(' + exts.join('|') + ')$');
var templateRegex = new RegExp('\\.(' + exts.join('|') + ')$');
var layoutPath = this.mvcpath + 'views/' + this.paths.layout;
var viewsPath = this.mvcpath + 'views';
var partialPaths = [];
if (fs.existsSync(viewsPath)) {
fileModule.walkSync(viewsPath, function(dirPath, dirs, files) {
for (var path,file,i=0; i < files.length; i++) {
file = files[i];
path = dirPath + "/" + file;
if (partialRegex.test(path)) {
// Only build valid partial views
partialPaths.push(path);
buildPartialView.call(self, path);
watchPartial.call(self, path, buildPartialView);
} else if (templateRegex.test(file)) {
// Build partial views for everything inside app.paths.layout
if (path.indexOf(layoutPath) === 0) {
partialPaths.push(path);
buildPartialView.call(self, path);
watchPartial.call(self, path, buildPartialView);
}
// Only add valid templates to view associations
self.views.pathAsoc[self.relPath(path.replace(self.regex.templateFile, ''))] = path;
}
}
});
}
// Add Builtin Partials
var Helper = protos.lib.helper;
var builtinHelper = new Helper();
for (var m in builtinHelper) {
if (builtinHelper[m] instanceof Function) {
this.registerViewHelper(m, builtinHelper[m], builtinHelper);
}
}
// Helper Partials
Object.keys(this.helpers).forEach(function(alias) {
var m, method, hkey, helper = self.helpers[alias];
for (m in helper) {
if (helper[m] instanceof Function) {
method = helper[m];
hkey = (alias == 'main')
? util.format('%s', m)
: util.format('%s_%s', alias, m);
self.registerViewHelper(hkey, method, helper);
}
}
});
// Event when view partials are loaded
this.emit('view_partials_loaded', this.views.partials);
// Set shortcode context
// NOTE: Automatically resets on hot code loading, so it's good.
var shortcodeContext = this.__shortcodeContext = {};
// Only add shortcode filter to context if enabled on config
if (this.config.shortcodeFilter) {
// Register shortcodes from partials
var shortcode = self.shortcode;
var partials = self.views.partials;
Object.keys(this.views.partials).forEach(function(partial) {
if (partial[0] === '$') {
shortcodeContext[partial.replace(/^\$/, '#')] = self.views.partials[partial];
} else {
shortcodeContext[partial] = function(buf, params, locals) {
if (buf) params.content = buf; // Provide wrapped content in params.content
params.__proto__ = locals; // Set locals as prototype of params
return partials[partial].call(null, params); // Provide params to partial, which is passed as locals
}
}
});
this.addFilter('context', function(buf, locals) {
buf = this.shortcode.parse(buf, locals, shortcodeContext);
return buf;
});
}
// Event when view shortcodes are loaded
this.emit('view_shortcodes_loaded', shortcodeContext);
} | [
"function",
"setupViewPartials",
"(",
")",
"{",
"// Set view path association object",
"this",
".",
"views",
".",
"pathAsoc",
"=",
"{",
"}",
";",
"// Partial & template regexes",
"var",
"self",
"=",
"this",
";",
"var",
"exts",
"=",
"this",
".",
"templateExtensions",
";",
"var",
"partialRegex",
"=",
"new",
"RegExp",
"(",
"'\\/views\\/(.+)\\/partials\\/[a-zA-Z0-9-_]+\\\\.('",
"+",
"exts",
".",
"join",
"(",
"'|'",
")",
"+",
"')$'",
")",
";",
"var",
"templateRegex",
"=",
"new",
"RegExp",
"(",
"'\\\\.('",
"+",
"exts",
".",
"join",
"(",
"'|'",
")",
"+",
"')$'",
")",
";",
"var",
"layoutPath",
"=",
"this",
".",
"mvcpath",
"+",
"'views/'",
"+",
"this",
".",
"paths",
".",
"layout",
";",
"var",
"viewsPath",
"=",
"this",
".",
"mvcpath",
"+",
"'views'",
";",
"var",
"partialPaths",
"=",
"[",
"]",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"viewsPath",
")",
")",
"{",
"fileModule",
".",
"walkSync",
"(",
"viewsPath",
",",
"function",
"(",
"dirPath",
",",
"dirs",
",",
"files",
")",
"{",
"for",
"(",
"var",
"path",
",",
"file",
",",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"path",
"=",
"dirPath",
"+",
"\"/\"",
"+",
"file",
";",
"if",
"(",
"partialRegex",
".",
"test",
"(",
"path",
")",
")",
"{",
"// Only build valid partial views",
"partialPaths",
".",
"push",
"(",
"path",
")",
";",
"buildPartialView",
".",
"call",
"(",
"self",
",",
"path",
")",
";",
"watchPartial",
".",
"call",
"(",
"self",
",",
"path",
",",
"buildPartialView",
")",
";",
"}",
"else",
"if",
"(",
"templateRegex",
".",
"test",
"(",
"file",
")",
")",
"{",
"// Build partial views for everything inside app.paths.layout",
"if",
"(",
"path",
".",
"indexOf",
"(",
"layoutPath",
")",
"===",
"0",
")",
"{",
"partialPaths",
".",
"push",
"(",
"path",
")",
";",
"buildPartialView",
".",
"call",
"(",
"self",
",",
"path",
")",
";",
"watchPartial",
".",
"call",
"(",
"self",
",",
"path",
",",
"buildPartialView",
")",
";",
"}",
"// Only add valid templates to view associations",
"self",
".",
"views",
".",
"pathAsoc",
"[",
"self",
".",
"relPath",
"(",
"path",
".",
"replace",
"(",
"self",
".",
"regex",
".",
"templateFile",
",",
"''",
")",
")",
"]",
"=",
"path",
";",
"}",
"}",
"}",
")",
";",
"}",
"// Add Builtin Partials",
"var",
"Helper",
"=",
"protos",
".",
"lib",
".",
"helper",
";",
"var",
"builtinHelper",
"=",
"new",
"Helper",
"(",
")",
";",
"for",
"(",
"var",
"m",
"in",
"builtinHelper",
")",
"{",
"if",
"(",
"builtinHelper",
"[",
"m",
"]",
"instanceof",
"Function",
")",
"{",
"this",
".",
"registerViewHelper",
"(",
"m",
",",
"builtinHelper",
"[",
"m",
"]",
",",
"builtinHelper",
")",
";",
"}",
"}",
"// Helper Partials",
"Object",
".",
"keys",
"(",
"this",
".",
"helpers",
")",
".",
"forEach",
"(",
"function",
"(",
"alias",
")",
"{",
"var",
"m",
",",
"method",
",",
"hkey",
",",
"helper",
"=",
"self",
".",
"helpers",
"[",
"alias",
"]",
";",
"for",
"(",
"m",
"in",
"helper",
")",
"{",
"if",
"(",
"helper",
"[",
"m",
"]",
"instanceof",
"Function",
")",
"{",
"method",
"=",
"helper",
"[",
"m",
"]",
";",
"hkey",
"=",
"(",
"alias",
"==",
"'main'",
")",
"?",
"util",
".",
"format",
"(",
"'%s'",
",",
"m",
")",
":",
"util",
".",
"format",
"(",
"'%s_%s'",
",",
"alias",
",",
"m",
")",
";",
"self",
".",
"registerViewHelper",
"(",
"hkey",
",",
"method",
",",
"helper",
")",
";",
"}",
"}",
"}",
")",
";",
"// Event when view partials are loaded",
"this",
".",
"emit",
"(",
"'view_partials_loaded'",
",",
"this",
".",
"views",
".",
"partials",
")",
";",
"// Set shortcode context",
"// NOTE: Automatically resets on hot code loading, so it's good.",
"var",
"shortcodeContext",
"=",
"this",
".",
"__shortcodeContext",
"=",
"{",
"}",
";",
"// Only add shortcode filter to context if enabled on config",
"if",
"(",
"this",
".",
"config",
".",
"shortcodeFilter",
")",
"{",
"// Register shortcodes from partials",
"var",
"shortcode",
"=",
"self",
".",
"shortcode",
";",
"var",
"partials",
"=",
"self",
".",
"views",
".",
"partials",
";",
"Object",
".",
"keys",
"(",
"this",
".",
"views",
".",
"partials",
")",
".",
"forEach",
"(",
"function",
"(",
"partial",
")",
"{",
"if",
"(",
"partial",
"[",
"0",
"]",
"===",
"'$'",
")",
"{",
"shortcodeContext",
"[",
"partial",
".",
"replace",
"(",
"/",
"^\\$",
"/",
",",
"'#'",
")",
"]",
"=",
"self",
".",
"views",
".",
"partials",
"[",
"partial",
"]",
";",
"}",
"else",
"{",
"shortcodeContext",
"[",
"partial",
"]",
"=",
"function",
"(",
"buf",
",",
"params",
",",
"locals",
")",
"{",
"if",
"(",
"buf",
")",
"params",
".",
"content",
"=",
"buf",
";",
"// Provide wrapped content in params.content",
"params",
".",
"__proto__",
"=",
"locals",
";",
"// Set locals as prototype of params",
"return",
"partials",
"[",
"partial",
"]",
".",
"call",
"(",
"null",
",",
"params",
")",
";",
"// Provide params to partial, which is passed as locals",
"}",
"}",
"}",
")",
";",
"this",
".",
"addFilter",
"(",
"'context'",
",",
"function",
"(",
"buf",
",",
"locals",
")",
"{",
"buf",
"=",
"this",
".",
"shortcode",
".",
"parse",
"(",
"buf",
",",
"locals",
",",
"shortcodeContext",
")",
";",
"return",
"buf",
";",
"}",
")",
";",
"}",
"// Event when view shortcodes are loaded",
"this",
".",
"emit",
"(",
"'view_shortcodes_loaded'",
",",
"shortcodeContext",
")",
";",
"}"
] | Configures View Partials | [
"Configures",
"View",
"Partials"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2570-L2688 |
50,686 | derdesign/protos | lib/application.js | createControllerFunction | function createControllerFunction(func) {
var Handlebars = protos.require('handlebars');
var context, newFunc, compile, source,
funcSrc = func.toString();
var code = funcSrc
.trim()
.replace(/^function\s+(.*?)(\s+)?\{(\s+)?/, '')
.replace(/(\s+)?\}$/, '');
// Get source file path
var alias = protos.lib.controller.prototype.getAlias(func.name),
srcFile = this.mvcpath + 'controllers/' + alias + '.js';
try {
source = fs.readFileSync(srcFile, 'utf-8');
} catch(e){
source = fs.readFileSync(srcFile.replace(/\.js$/, '_controller.js'), 'utf-8');
}
// Detect pre & post function code
var si = source.indexOf(funcSrc),
preFuncSrc = source.slice(0, si).trim(),
postFuncSrc = source.slice(si + funcSrc.length).trim();
// Controller code
var template = Handlebars.compile('\n\
with (locals) {\n\n\
function {{{name}}}(app) {\n\
this.filters = this.filters["{{{name}}}"] || [];\n\
}\n\n\
require("util").inherits({{{name}}}, protos.lib.controller);\n\n\
protos.extend({{{name}}}, protos.lib.controller);\n\n\
{{{name}}}.filter = {{{name}}}.prototype.filter;\n\
{{{name}}}.handler = {{{name}}}.prototype.handler;\n\n\
var __funKeys__ = Object.keys({{{name}}});\n\
\n\
(function() { \n\
{{{preFuncSrc}}}\n\n\
with(this) {\n\n\
{{{code}}}\n\
}\n\n\
{{{postFuncSrc}}}\n\n\
}).call({{{name}}});\n\n\
for (var key in {{{name}}}) {\n\
if (__funKeys__.indexOf(key) === -1) { \n\
{{{name}}}.prototype[key] = {{{name}}}[key];\n\
delete {{{name}}}[key];\n\
}\n\
}\n\
\n\
if (!{{{name}}}.prototype.authRequired) {\n\
{{{name}}}.prototype.authRequired = protos.lib.controller.prototype.authRequired;\n\
} else {\n\
{{{name}}}.prototype.authRequired = true; \n\
}\n\n\
return {{{name}}};\n\n\
}');
var fnCode = template({
name: func.name,
code: code,
preFuncSrc: preFuncSrc,
postFuncSrc: postFuncSrc,
});
// console.exit(fnCode);
/*jshint evil:true */
compile = new Function('locals', fnCode);
newFunc = compile({
app: this,
protos: protos,
module: {},
require: require,
console: console,
__dirname: this.mvcpath + 'controllers',
__filename: srcFile,
process: process
});
return newFunc;
} | javascript | function createControllerFunction(func) {
var Handlebars = protos.require('handlebars');
var context, newFunc, compile, source,
funcSrc = func.toString();
var code = funcSrc
.trim()
.replace(/^function\s+(.*?)(\s+)?\{(\s+)?/, '')
.replace(/(\s+)?\}$/, '');
// Get source file path
var alias = protos.lib.controller.prototype.getAlias(func.name),
srcFile = this.mvcpath + 'controllers/' + alias + '.js';
try {
source = fs.readFileSync(srcFile, 'utf-8');
} catch(e){
source = fs.readFileSync(srcFile.replace(/\.js$/, '_controller.js'), 'utf-8');
}
// Detect pre & post function code
var si = source.indexOf(funcSrc),
preFuncSrc = source.slice(0, si).trim(),
postFuncSrc = source.slice(si + funcSrc.length).trim();
// Controller code
var template = Handlebars.compile('\n\
with (locals) {\n\n\
function {{{name}}}(app) {\n\
this.filters = this.filters["{{{name}}}"] || [];\n\
}\n\n\
require("util").inherits({{{name}}}, protos.lib.controller);\n\n\
protos.extend({{{name}}}, protos.lib.controller);\n\n\
{{{name}}}.filter = {{{name}}}.prototype.filter;\n\
{{{name}}}.handler = {{{name}}}.prototype.handler;\n\n\
var __funKeys__ = Object.keys({{{name}}});\n\
\n\
(function() { \n\
{{{preFuncSrc}}}\n\n\
with(this) {\n\n\
{{{code}}}\n\
}\n\n\
{{{postFuncSrc}}}\n\n\
}).call({{{name}}});\n\n\
for (var key in {{{name}}}) {\n\
if (__funKeys__.indexOf(key) === -1) { \n\
{{{name}}}.prototype[key] = {{{name}}}[key];\n\
delete {{{name}}}[key];\n\
}\n\
}\n\
\n\
if (!{{{name}}}.prototype.authRequired) {\n\
{{{name}}}.prototype.authRequired = protos.lib.controller.prototype.authRequired;\n\
} else {\n\
{{{name}}}.prototype.authRequired = true; \n\
}\n\n\
return {{{name}}};\n\n\
}');
var fnCode = template({
name: func.name,
code: code,
preFuncSrc: preFuncSrc,
postFuncSrc: postFuncSrc,
});
// console.exit(fnCode);
/*jshint evil:true */
compile = new Function('locals', fnCode);
newFunc = compile({
app: this,
protos: protos,
module: {},
require: require,
console: console,
__dirname: this.mvcpath + 'controllers',
__filename: srcFile,
process: process
});
return newFunc;
} | [
"function",
"createControllerFunction",
"(",
"func",
")",
"{",
"var",
"Handlebars",
"=",
"protos",
".",
"require",
"(",
"'handlebars'",
")",
";",
"var",
"context",
",",
"newFunc",
",",
"compile",
",",
"source",
",",
"funcSrc",
"=",
"func",
".",
"toString",
"(",
")",
";",
"var",
"code",
"=",
"funcSrc",
".",
"trim",
"(",
")",
".",
"replace",
"(",
"/",
"^function\\s+(.*?)(\\s+)?\\{(\\s+)?",
"/",
",",
"''",
")",
".",
"replace",
"(",
"/",
"(\\s+)?\\}$",
"/",
",",
"''",
")",
";",
"// Get source file path",
"var",
"alias",
"=",
"protos",
".",
"lib",
".",
"controller",
".",
"prototype",
".",
"getAlias",
"(",
"func",
".",
"name",
")",
",",
"srcFile",
"=",
"this",
".",
"mvcpath",
"+",
"'controllers/'",
"+",
"alias",
"+",
"'.js'",
";",
"try",
"{",
"source",
"=",
"fs",
".",
"readFileSync",
"(",
"srcFile",
",",
"'utf-8'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"source",
"=",
"fs",
".",
"readFileSync",
"(",
"srcFile",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
",",
"'_controller.js'",
")",
",",
"'utf-8'",
")",
";",
"}",
"// Detect pre & post function code",
"var",
"si",
"=",
"source",
".",
"indexOf",
"(",
"funcSrc",
")",
",",
"preFuncSrc",
"=",
"source",
".",
"slice",
"(",
"0",
",",
"si",
")",
".",
"trim",
"(",
")",
",",
"postFuncSrc",
"=",
"source",
".",
"slice",
"(",
"si",
"+",
"funcSrc",
".",
"length",
")",
".",
"trim",
"(",
")",
";",
"// Controller code",
"var",
"template",
"=",
"Handlebars",
".",
"compile",
"(",
"'\\n\\\nwith (locals) {\\n\\n\\\nfunction {{{name}}}(app) {\\n\\\n this.filters = this.filters[\"{{{name}}}\"] || [];\\n\\\n}\\n\\n\\\nrequire(\"util\").inherits({{{name}}}, protos.lib.controller);\\n\\n\\\nprotos.extend({{{name}}}, protos.lib.controller);\\n\\n\\\n{{{name}}}.filter = {{{name}}}.prototype.filter;\\n\\\n{{{name}}}.handler = {{{name}}}.prototype.handler;\\n\\n\\\nvar __funKeys__ = Object.keys({{{name}}});\\n\\\n\\n\\\n(function() { \\n\\\n{{{preFuncSrc}}}\\n\\n\\\nwith(this) {\\n\\n\\\n {{{code}}}\\n\\\n}\\n\\n\\\n{{{postFuncSrc}}}\\n\\n\\\n}).call({{{name}}});\\n\\n\\\nfor (var key in {{{name}}}) {\\n\\\n if (__funKeys__.indexOf(key) === -1) { \\n\\\n {{{name}}}.prototype[key] = {{{name}}}[key];\\n\\\n delete {{{name}}}[key];\\n\\\n }\\n\\\n}\\n\\\n\\n\\\nif (!{{{name}}}.prototype.authRequired) {\\n\\\n {{{name}}}.prototype.authRequired = protos.lib.controller.prototype.authRequired;\\n\\\n} else {\\n\\\n {{{name}}}.prototype.authRequired = true; \\n\\\n}\\n\\n\\\nreturn {{{name}}};\\n\\n\\\n}'",
")",
";",
"var",
"fnCode",
"=",
"template",
"(",
"{",
"name",
":",
"func",
".",
"name",
",",
"code",
":",
"code",
",",
"preFuncSrc",
":",
"preFuncSrc",
",",
"postFuncSrc",
":",
"postFuncSrc",
",",
"}",
")",
";",
"// console.exit(fnCode);",
"/*jshint evil:true */",
"compile",
"=",
"new",
"Function",
"(",
"'locals'",
",",
"fnCode",
")",
";",
"newFunc",
"=",
"compile",
"(",
"{",
"app",
":",
"this",
",",
"protos",
":",
"protos",
",",
"module",
":",
"{",
"}",
",",
"require",
":",
"require",
",",
"console",
":",
"console",
",",
"__dirname",
":",
"this",
".",
"mvcpath",
"+",
"'controllers'",
",",
"__filename",
":",
"srcFile",
",",
"process",
":",
"process",
"}",
")",
";",
"return",
"newFunc",
";",
"}"
] | Converts a regular function into a controller constructor | [
"Converts",
"a",
"regular",
"function",
"into",
"a",
"controller",
"constructor"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/lib/application.js#L2692-L2777 |
50,687 | yefremov/aggregatejs | percentile.js | percentile | function percentile(array, k) {
var length = array.length;
if (length === 0) {
return 0;
}
if (typeof k !== 'number') {
throw new TypeError('k must be a number');
}
if (k <= 0) {
return array[0];
}
if (k >= 1) {
return array[length - 1];
}
array.sort(function (a, b) {
return a - b;
});
var index = (length - 1) * k;
var lower = Math.floor(index);
var upper = lower + 1;
var weight = index % 1;
if (upper >= length) {
return array[lower];
}
return array[lower] * (1 - weight) + array[upper] * weight;
} | javascript | function percentile(array, k) {
var length = array.length;
if (length === 0) {
return 0;
}
if (typeof k !== 'number') {
throw new TypeError('k must be a number');
}
if (k <= 0) {
return array[0];
}
if (k >= 1) {
return array[length - 1];
}
array.sort(function (a, b) {
return a - b;
});
var index = (length - 1) * k;
var lower = Math.floor(index);
var upper = lower + 1;
var weight = index % 1;
if (upper >= length) {
return array[lower];
}
return array[lower] * (1 - weight) + array[upper] * weight;
} | [
"function",
"percentile",
"(",
"array",
",",
"k",
")",
"{",
"var",
"length",
"=",
"array",
".",
"length",
";",
"if",
"(",
"length",
"===",
"0",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"typeof",
"k",
"!==",
"'number'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'k must be a number'",
")",
";",
"}",
"if",
"(",
"k",
"<=",
"0",
")",
"{",
"return",
"array",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"k",
">=",
"1",
")",
"{",
"return",
"array",
"[",
"length",
"-",
"1",
"]",
";",
"}",
"array",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
"-",
"b",
";",
"}",
")",
";",
"var",
"index",
"=",
"(",
"length",
"-",
"1",
")",
"*",
"k",
";",
"var",
"lower",
"=",
"Math",
".",
"floor",
"(",
"index",
")",
";",
"var",
"upper",
"=",
"lower",
"+",
"1",
";",
"var",
"weight",
"=",
"index",
"%",
"1",
";",
"if",
"(",
"upper",
">=",
"length",
")",
"{",
"return",
"array",
"[",
"lower",
"]",
";",
"}",
"return",
"array",
"[",
"lower",
"]",
"*",
"(",
"1",
"-",
"weight",
")",
"+",
"array",
"[",
"upper",
"]",
"*",
"weight",
";",
"}"
] | Returns the `k`-th percentile of values in `array`.
@param {Array} array Range of data that defines relative standing.
@param {number} k The percentile value that is between 0 through 1.
@return {number}
@example
percentile([100, -100, 150, -50, 100, 250], 0.25);
// => -12.5
percentile([100, -100, 150, -50, 100, 250], 0.50);
// => 100
percentile([100, -100, 150, -50, 100, 250], 0.95);
// => 225 | [
"Returns",
"the",
"k",
"-",
"th",
"percentile",
"of",
"values",
"in",
"array",
"."
] | 932b28a15a5707135e7095950000a838db409511 | https://github.com/yefremov/aggregatejs/blob/932b28a15a5707135e7095950000a838db409511/percentile.js#L26-L59 |
50,688 | lepisma/coelacanth | src.js | mergeObject | function mergeObject (oldObject, newObject) {
let oldCopy = Object.assign({}, oldObject)
function _merge (oo, no) {
for (let key in no) {
if (key in oo) {
// Follow structure of oo
if (oo[key] === Object(oo[key])) {
_merge(oo[key], no[key])
} else if (no[key] !== Object(no[key])) {
oo[key] = no[key]
}
} else {
// Plain assign
oo[key] = no[key]
}
}
return oo
}
return _merge(oldCopy, newObject)
} | javascript | function mergeObject (oldObject, newObject) {
let oldCopy = Object.assign({}, oldObject)
function _merge (oo, no) {
for (let key in no) {
if (key in oo) {
// Follow structure of oo
if (oo[key] === Object(oo[key])) {
_merge(oo[key], no[key])
} else if (no[key] !== Object(no[key])) {
oo[key] = no[key]
}
} else {
// Plain assign
oo[key] = no[key]
}
}
return oo
}
return _merge(oldCopy, newObject)
} | [
"function",
"mergeObject",
"(",
"oldObject",
",",
"newObject",
")",
"{",
"let",
"oldCopy",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"oldObject",
")",
"function",
"_merge",
"(",
"oo",
",",
"no",
")",
"{",
"for",
"(",
"let",
"key",
"in",
"no",
")",
"{",
"if",
"(",
"key",
"in",
"oo",
")",
"{",
"// Follow structure of oo",
"if",
"(",
"oo",
"[",
"key",
"]",
"===",
"Object",
"(",
"oo",
"[",
"key",
"]",
")",
")",
"{",
"_merge",
"(",
"oo",
"[",
"key",
"]",
",",
"no",
"[",
"key",
"]",
")",
"}",
"else",
"if",
"(",
"no",
"[",
"key",
"]",
"!==",
"Object",
"(",
"no",
"[",
"key",
"]",
")",
")",
"{",
"oo",
"[",
"key",
"]",
"=",
"no",
"[",
"key",
"]",
"}",
"}",
"else",
"{",
"// Plain assign",
"oo",
"[",
"key",
"]",
"=",
"no",
"[",
"key",
"]",
"}",
"}",
"return",
"oo",
"}",
"return",
"_merge",
"(",
"oldCopy",
",",
"newObject",
")",
"}"
] | Merge two objects with nested data | [
"Merge",
"two",
"objects",
"with",
"nested",
"data"
] | fdfa70dadafe5f74850eb1f8eba41ce7a9ac56a1 | https://github.com/lepisma/coelacanth/blob/fdfa70dadafe5f74850eb1f8eba41ce7a9ac56a1/src.js#L4-L25 |
50,689 | subfuzion/snapfinder-lib | main.js | connect | function connect(mongodbUri, callback) {
snapdb.connect(mongodbUri, function(err, client) {
if (err) return callback(err);
callback(null, client);
});
} | javascript | function connect(mongodbUri, callback) {
snapdb.connect(mongodbUri, function(err, client) {
if (err) return callback(err);
callback(null, client);
});
} | [
"function",
"connect",
"(",
"mongodbUri",
",",
"callback",
")",
"{",
"snapdb",
".",
"connect",
"(",
"mongodbUri",
",",
"function",
"(",
"err",
",",
"client",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"callback",
"(",
"null",
",",
"client",
")",
";",
"}",
")",
";",
"}"
] | Connect to the snapdb mongo database. | [
"Connect",
"to",
"the",
"snapdb",
"mongo",
"database",
"."
] | 121172f10a9ec64bc5f3d749fba97662b336caae | https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/main.js#L16-L21 |
50,690 | subfuzion/snapfinder-lib | main.js | findStoresInZip | function findStoresInZip(address, callback) {
geo.geocode(address, function(err, georesult) {
if (err) return callback(err);
snapdb.findStoresInZip(georesult.zip5, function(err, stores) {
if (err) return callback(err);
georesult.stores = stores;
return callback(null, georesult);
});
});
} | javascript | function findStoresInZip(address, callback) {
geo.geocode(address, function(err, georesult) {
if (err) return callback(err);
snapdb.findStoresInZip(georesult.zip5, function(err, stores) {
if (err) return callback(err);
georesult.stores = stores;
return callback(null, georesult);
});
});
} | [
"function",
"findStoresInZip",
"(",
"address",
",",
"callback",
")",
"{",
"geo",
".",
"geocode",
"(",
"address",
",",
"function",
"(",
"err",
",",
"georesult",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"snapdb",
".",
"findStoresInZip",
"(",
"georesult",
".",
"zip5",
",",
"function",
"(",
"err",
",",
"stores",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"georesult",
".",
"stores",
"=",
"stores",
";",
"return",
"callback",
"(",
"null",
",",
"georesult",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Find stores within a zip code.
@param address a valid address, address fragment, or pair of coordinates | [
"Find",
"stores",
"within",
"a",
"zip",
"code",
"."
] | 121172f10a9ec64bc5f3d749fba97662b336caae | https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/main.js#L66-L76 |
50,691 | subfuzion/snapfinder-lib | main.js | sortStoresByDistance | function sortStoresByDistance(location, stores) {
var i, s;
for (i = 0; i < stores.length; i++) {
s = stores[i];
s.distance = geo.getDistanceInMiles(location,
{ lat:s.latitude, lng:s.longitude });
}
stores.sort(function(a,b) { return a.distance - b.distance; });
return stores;
} | javascript | function sortStoresByDistance(location, stores) {
var i, s;
for (i = 0; i < stores.length; i++) {
s = stores[i];
s.distance = geo.getDistanceInMiles(location,
{ lat:s.latitude, lng:s.longitude });
}
stores.sort(function(a,b) { return a.distance - b.distance; });
return stores;
} | [
"function",
"sortStoresByDistance",
"(",
"location",
",",
"stores",
")",
"{",
"var",
"i",
",",
"s",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"stores",
".",
"length",
";",
"i",
"++",
")",
"{",
"s",
"=",
"stores",
"[",
"i",
"]",
";",
"s",
".",
"distance",
"=",
"geo",
".",
"getDistanceInMiles",
"(",
"location",
",",
"{",
"lat",
":",
"s",
".",
"latitude",
",",
"lng",
":",
"s",
".",
"longitude",
"}",
")",
";",
"}",
"stores",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"distance",
"-",
"b",
".",
"distance",
";",
"}",
")",
";",
"return",
"stores",
";",
"}"
] | Sorts the stores array in distance order from location, and also returns it.
@param location an object with lat and lng properties
@param stores an array of store objects | [
"Sorts",
"the",
"stores",
"array",
"in",
"distance",
"order",
"from",
"location",
"and",
"also",
"returns",
"it",
"."
] | 121172f10a9ec64bc5f3d749fba97662b336caae | https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/main.js#L83-L94 |
50,692 | peerigon/value | lib/value.js | setup | function setup(subject) {
context.subject = subject;
context.subjectType = null;
context.subjectConstructor = null;
context.isSet = false;
} | javascript | function setup(subject) {
context.subject = subject;
context.subjectType = null;
context.subjectConstructor = null;
context.isSet = false;
} | [
"function",
"setup",
"(",
"subject",
")",
"{",
"context",
".",
"subject",
"=",
"subject",
";",
"context",
".",
"subjectType",
"=",
"null",
";",
"context",
".",
"subjectConstructor",
"=",
"null",
";",
"context",
".",
"isSet",
"=",
"false",
";",
"}"
] | Resets all values of the context object.
@private
@param subject | [
"Resets",
"all",
"values",
"of",
"the",
"context",
"object",
"."
] | 5cdaad2c9c5d9431b0d123196571f1e708e42b40 | https://github.com/peerigon/value/blob/5cdaad2c9c5d9431b0d123196571f1e708e42b40/lib/value.js#L211-L216 |
50,693 | MaximTovstashev/brest | lib/utils/reject_fields.js | rejectFields | function rejectFields(result, fields) {
// If result is an array, then rejection rules are applied to each array entry
if (_.isArray(result)) {
return _.map(result, (single_entry) => _.omit(single_entry, fields));
}
return _.omit(result, fields);
} | javascript | function rejectFields(result, fields) {
// If result is an array, then rejection rules are applied to each array entry
if (_.isArray(result)) {
return _.map(result, (single_entry) => _.omit(single_entry, fields));
}
return _.omit(result, fields);
} | [
"function",
"rejectFields",
"(",
"result",
",",
"fields",
")",
"{",
"// If result is an array, then rejection rules are applied to each array entry",
"if",
"(",
"_",
".",
"isArray",
"(",
"result",
")",
")",
"{",
"return",
"_",
".",
"map",
"(",
"result",
",",
"(",
"single_entry",
")",
"=>",
"_",
".",
"omit",
"(",
"single_entry",
",",
"fields",
")",
")",
";",
"}",
"return",
"_",
".",
"omit",
"(",
"result",
",",
"fields",
")",
";",
"}"
] | Reject fields from result
@param result
@param fields
@return {*} | [
"Reject",
"fields",
"from",
"result"
] | 9b0bd6ee452e55b86cd01d1647f0dff460ad191f | https://github.com/MaximTovstashev/brest/blob/9b0bd6ee452e55b86cd01d1647f0dff460ad191f/lib/utils/reject_fields.js#L9-L15 |
50,694 | jonschlinkert/detect-conflicts | index.js | stringDiff | function stringDiff(existing, proposed, method) {
method = method || 'diffJson';
lazy.diff[method](existing, proposed).forEach(function (res) {
var color = utils.gray;
if (res.added) color = utils.green;
if (res.removed) color = utils.red;
process.stdout.write(color(res.value));
});
console.log('\n');
} | javascript | function stringDiff(existing, proposed, method) {
method = method || 'diffJson';
lazy.diff[method](existing, proposed).forEach(function (res) {
var color = utils.gray;
if (res.added) color = utils.green;
if (res.removed) color = utils.red;
process.stdout.write(color(res.value));
});
console.log('\n');
} | [
"function",
"stringDiff",
"(",
"existing",
",",
"proposed",
",",
"method",
")",
"{",
"method",
"=",
"method",
"||",
"'diffJson'",
";",
"lazy",
".",
"diff",
"[",
"method",
"]",
"(",
"existing",
",",
"proposed",
")",
".",
"forEach",
"(",
"function",
"(",
"res",
")",
"{",
"var",
"color",
"=",
"utils",
".",
"gray",
";",
"if",
"(",
"res",
".",
"added",
")",
"color",
"=",
"utils",
".",
"green",
";",
"if",
"(",
"res",
".",
"removed",
")",
"color",
"=",
"utils",
".",
"red",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"color",
"(",
"res",
".",
"value",
")",
")",
";",
"}",
")",
";",
"console",
".",
"log",
"(",
"'\\n'",
")",
";",
"}"
] | Show a diff comparison of the existing content versus the content
about to be written.
@param {String} `existing`
@param {String} `proposed`
@param {String} method Optionally pass a specific method name from the [diff] library to use for the diff.
@return {String} Visual diff comparison. | [
"Show",
"a",
"diff",
"comparison",
"of",
"the",
"existing",
"content",
"versus",
"the",
"content",
"about",
"to",
"be",
"written",
"."
] | 851acf9e57923eb791e9974ad92b4cba5c7fe44e | https://github.com/jonschlinkert/detect-conflicts/blob/851acf9e57923eb791e9974ad92b4cba5c7fe44e/index.js#L94-L103 |
50,695 | jonschlinkert/detect-conflicts | index.js | ask | function ask(file, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
opts = opts || {};
var prompt = lazy.inquirer.createPromptModule();
var fp = path.relative(process.cwd(), file.path);
var questions = {
name: 'action',
type: 'expand',
message: 'Overwrite `' + fp + '`?',
value: 'nothing',
choices: [{
key: 'n',
name: 'do not overwrite',
value: 'skip'
}, {
key: 'y',
name: 'overwrite',
value: 'write'
}, {
key: 'a',
name: 'overwrite this and all others',
value: 'force'
}, {
key: 'x',
name: 'abort',
value: 'abort'
}, {
key: 'd',
name: 'diff comparison between the current and new:',
value: 'diff'
}]
};
prompt([questions], function (answers) {
var msg = answers.action;
switch(answers.action) {
case 'skip':
cb(answers.action);
process.exit(0);
case 'abort':
msg = utils.red(utils.error) + ' Aborted. No action was taken.';
if (!opts.silent) console.log(msg);
cb(answers.action);
process.exit(0);
case 'diff':
var existing = opts.existing || fs.readFileSync(fp, 'utf8');
if (lazy.isBinary(existing) && typeof opts.binaryDiff === 'function') {
opts.binaryDiff(existing, file.contents);
} else {
stringDiff(existing, file.contents.toString());
}
return ask(file, opts, cb);
case 'force':
opts.force = true;
break;
case 'write':
msg = utils.green(utils.success) + ' file written to';
opts.force = true;
break;
default: {
msg = utils.red(utils.error) + utils.red(' Aborted.') + ' No action was taken.';
if (!opts.silent) console.log(msg);
cb(answers.action);
process.exit(0);
}
}
var rel = path.relative(process.cwd(), fp);
var filepath = utils[answers.action](rel);
if (!opts.silent) {
console.log(msg, filepath);
}
return cb(answers.action);
});
} | javascript | function ask(file, opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
opts = opts || {};
var prompt = lazy.inquirer.createPromptModule();
var fp = path.relative(process.cwd(), file.path);
var questions = {
name: 'action',
type: 'expand',
message: 'Overwrite `' + fp + '`?',
value: 'nothing',
choices: [{
key: 'n',
name: 'do not overwrite',
value: 'skip'
}, {
key: 'y',
name: 'overwrite',
value: 'write'
}, {
key: 'a',
name: 'overwrite this and all others',
value: 'force'
}, {
key: 'x',
name: 'abort',
value: 'abort'
}, {
key: 'd',
name: 'diff comparison between the current and new:',
value: 'diff'
}]
};
prompt([questions], function (answers) {
var msg = answers.action;
switch(answers.action) {
case 'skip':
cb(answers.action);
process.exit(0);
case 'abort':
msg = utils.red(utils.error) + ' Aborted. No action was taken.';
if (!opts.silent) console.log(msg);
cb(answers.action);
process.exit(0);
case 'diff':
var existing = opts.existing || fs.readFileSync(fp, 'utf8');
if (lazy.isBinary(existing) && typeof opts.binaryDiff === 'function') {
opts.binaryDiff(existing, file.contents);
} else {
stringDiff(existing, file.contents.toString());
}
return ask(file, opts, cb);
case 'force':
opts.force = true;
break;
case 'write':
msg = utils.green(utils.success) + ' file written to';
opts.force = true;
break;
default: {
msg = utils.red(utils.error) + utils.red(' Aborted.') + ' No action was taken.';
if (!opts.silent) console.log(msg);
cb(answers.action);
process.exit(0);
}
}
var rel = path.relative(process.cwd(), fp);
var filepath = utils[answers.action](rel);
if (!opts.silent) {
console.log(msg, filepath);
}
return cb(answers.action);
});
} | [
"function",
"ask",
"(",
"file",
",",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"cb",
"=",
"opts",
";",
"opts",
"=",
"{",
"}",
";",
"}",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"prompt",
"=",
"lazy",
".",
"inquirer",
".",
"createPromptModule",
"(",
")",
";",
"var",
"fp",
"=",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"file",
".",
"path",
")",
";",
"var",
"questions",
"=",
"{",
"name",
":",
"'action'",
",",
"type",
":",
"'expand'",
",",
"message",
":",
"'Overwrite `'",
"+",
"fp",
"+",
"'`?'",
",",
"value",
":",
"'nothing'",
",",
"choices",
":",
"[",
"{",
"key",
":",
"'n'",
",",
"name",
":",
"'do not overwrite'",
",",
"value",
":",
"'skip'",
"}",
",",
"{",
"key",
":",
"'y'",
",",
"name",
":",
"'overwrite'",
",",
"value",
":",
"'write'",
"}",
",",
"{",
"key",
":",
"'a'",
",",
"name",
":",
"'overwrite this and all others'",
",",
"value",
":",
"'force'",
"}",
",",
"{",
"key",
":",
"'x'",
",",
"name",
":",
"'abort'",
",",
"value",
":",
"'abort'",
"}",
",",
"{",
"key",
":",
"'d'",
",",
"name",
":",
"'diff comparison between the current and new:'",
",",
"value",
":",
"'diff'",
"}",
"]",
"}",
";",
"prompt",
"(",
"[",
"questions",
"]",
",",
"function",
"(",
"answers",
")",
"{",
"var",
"msg",
"=",
"answers",
".",
"action",
";",
"switch",
"(",
"answers",
".",
"action",
")",
"{",
"case",
"'skip'",
":",
"cb",
"(",
"answers",
".",
"action",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"case",
"'abort'",
":",
"msg",
"=",
"utils",
".",
"red",
"(",
"utils",
".",
"error",
")",
"+",
"' Aborted. No action was taken.'",
";",
"if",
"(",
"!",
"opts",
".",
"silent",
")",
"console",
".",
"log",
"(",
"msg",
")",
";",
"cb",
"(",
"answers",
".",
"action",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"case",
"'diff'",
":",
"var",
"existing",
"=",
"opts",
".",
"existing",
"||",
"fs",
".",
"readFileSync",
"(",
"fp",
",",
"'utf8'",
")",
";",
"if",
"(",
"lazy",
".",
"isBinary",
"(",
"existing",
")",
"&&",
"typeof",
"opts",
".",
"binaryDiff",
"===",
"'function'",
")",
"{",
"opts",
".",
"binaryDiff",
"(",
"existing",
",",
"file",
".",
"contents",
")",
";",
"}",
"else",
"{",
"stringDiff",
"(",
"existing",
",",
"file",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"ask",
"(",
"file",
",",
"opts",
",",
"cb",
")",
";",
"case",
"'force'",
":",
"opts",
".",
"force",
"=",
"true",
";",
"break",
";",
"case",
"'write'",
":",
"msg",
"=",
"utils",
".",
"green",
"(",
"utils",
".",
"success",
")",
"+",
"' file written to'",
";",
"opts",
".",
"force",
"=",
"true",
";",
"break",
";",
"default",
":",
"{",
"msg",
"=",
"utils",
".",
"red",
"(",
"utils",
".",
"error",
")",
"+",
"utils",
".",
"red",
"(",
"' Aborted.'",
")",
"+",
"' No action was taken.'",
";",
"if",
"(",
"!",
"opts",
".",
"silent",
")",
"console",
".",
"log",
"(",
"msg",
")",
";",
"cb",
"(",
"answers",
".",
"action",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
"}",
"var",
"rel",
"=",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"fp",
")",
";",
"var",
"filepath",
"=",
"utils",
"[",
"answers",
".",
"action",
"]",
"(",
"rel",
")",
";",
"if",
"(",
"!",
"opts",
".",
"silent",
")",
"{",
"console",
".",
"log",
"(",
"msg",
",",
"filepath",
")",
";",
"}",
"return",
"cb",
"(",
"answers",
".",
"action",
")",
";",
"}",
")",
";",
"}"
] | Prompt the user for feedback.
@param {Object} `file`
@param {Function} `cb` | [
"Prompt",
"the",
"user",
"for",
"feedback",
"."
] | 851acf9e57923eb791e9974ad92b4cba5c7fe44e | https://github.com/jonschlinkert/detect-conflicts/blob/851acf9e57923eb791e9974ad92b4cba5c7fe44e/index.js#L112-L196 |
50,696 | willemdewit/java.properties.js | lib/java.properties.js | splitEscaped | function splitEscaped(src, separator) {
let escapeFlag = false,
token = '',
result = [];
src.split('').forEach(letter => {
if (escapeFlag) {
token += letter;
escapeFlag = false;
} else if (letter === '\\') {
escapeFlag = true;
} else if (letter === separator) {
result.push(token);
token = '';
} else {
token += letter;
}
});
if (token.length > 0) {
result.push(token);
}
return result;
} | javascript | function splitEscaped(src, separator) {
let escapeFlag = false,
token = '',
result = [];
src.split('').forEach(letter => {
if (escapeFlag) {
token += letter;
escapeFlag = false;
} else if (letter === '\\') {
escapeFlag = true;
} else if (letter === separator) {
result.push(token);
token = '';
} else {
token += letter;
}
});
if (token.length > 0) {
result.push(token);
}
return result;
} | [
"function",
"splitEscaped",
"(",
"src",
",",
"separator",
")",
"{",
"let",
"escapeFlag",
"=",
"false",
",",
"token",
"=",
"''",
",",
"result",
"=",
"[",
"]",
";",
"src",
".",
"split",
"(",
"''",
")",
".",
"forEach",
"(",
"letter",
"=>",
"{",
"if",
"(",
"escapeFlag",
")",
"{",
"token",
"+=",
"letter",
";",
"escapeFlag",
"=",
"false",
";",
"}",
"else",
"if",
"(",
"letter",
"===",
"'\\\\'",
")",
"{",
"escapeFlag",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"letter",
"===",
"separator",
")",
"{",
"result",
".",
"push",
"(",
"token",
")",
";",
"token",
"=",
"''",
";",
"}",
"else",
"{",
"token",
"+=",
"letter",
";",
"}",
"}",
")",
";",
"if",
"(",
"token",
".",
"length",
">",
"0",
")",
"{",
"result",
".",
"push",
"(",
"token",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Split a string using a separator, if not preceded by a backslash.
For simplicity, this does not correctly handle two preceding backslashes
@param src {String} value to parse
@param separator {String} single character separator
@returns [] | [
"Split",
"a",
"string",
"using",
"a",
"separator",
"if",
"not",
"preceded",
"by",
"a",
"backslash",
".",
"For",
"simplicity",
"this",
"does",
"not",
"correctly",
"handle",
"two",
"preceding",
"backslashes"
] | dfd733f74e8bc0d196a7238caf92bdae07a80aa5 | https://github.com/willemdewit/java.properties.js/blob/dfd733f74e8bc0d196a7238caf92bdae07a80aa5/lib/java.properties.js#L33-L54 |
50,697 | willemdewit/java.properties.js | lib/java.properties.js | combineMultiLines | function combineMultiLines(lines) {
return lines.reduce((acc, cur) => {
const line = acc[acc.length - 1];
if (acc.length && isLineContinued(line)) {
acc[acc.length - 1] = line.replace(/\\$/, '');
acc[acc.length - 1] += cur;
} else {
acc.push(cur);
}
return acc;
}, []);
} | javascript | function combineMultiLines(lines) {
return lines.reduce((acc, cur) => {
const line = acc[acc.length - 1];
if (acc.length && isLineContinued(line)) {
acc[acc.length - 1] = line.replace(/\\$/, '');
acc[acc.length - 1] += cur;
} else {
acc.push(cur);
}
return acc;
}, []);
} | [
"function",
"combineMultiLines",
"(",
"lines",
")",
"{",
"return",
"lines",
".",
"reduce",
"(",
"(",
"acc",
",",
"cur",
")",
"=>",
"{",
"const",
"line",
"=",
"acc",
"[",
"acc",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"acc",
".",
"length",
"&&",
"isLineContinued",
"(",
"line",
")",
")",
"{",
"acc",
"[",
"acc",
".",
"length",
"-",
"1",
"]",
"=",
"line",
".",
"replace",
"(",
"/",
"\\\\$",
"/",
",",
"''",
")",
";",
"acc",
"[",
"acc",
".",
"length",
"-",
"1",
"]",
"+=",
"cur",
";",
"}",
"else",
"{",
"acc",
".",
"push",
"(",
"cur",
")",
";",
"}",
"return",
"acc",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Combines lines which end with a backslash with the next line
@param lines {String[]}
@returns {String[]} | [
"Combines",
"lines",
"which",
"end",
"with",
"a",
"backslash",
"with",
"the",
"next",
"line"
] | dfd733f74e8bc0d196a7238caf92bdae07a80aa5 | https://github.com/willemdewit/java.properties.js/blob/dfd733f74e8bc0d196a7238caf92bdae07a80aa5/lib/java.properties.js#L120-L131 |
50,698 | feedhenry/fh-mbaas-middleware | lib/util/mongo.js | createDb | function createDb(config, dbUser, dbUserPass, dbName, cb) {
log.logger.trace({user: dbUser, pwd: dbUserPass, name: dbName}, 'creating new datatbase');
var url = config.mongoUrl;
var admin = config.mongo.admin_auth.user;
var admin_pass = config.mongo.admin_auth.pass;
MongoClient.connect(url, function(err, db){
if (err) return handleError(null, err, 'cannot open mongodb connection', cb);
var targetDb = db.db(dbName);
targetDb.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err) {
if (err) return handleError(db, err, 'can not authenticate admin user', cb);
// update for mongodb3.2 - need to remove user first
targetDb.removeUser(dbUser, function(err) {
if(err){
log.logger.error(err, 'failed to remove user');
}
// add user to database
targetDb.addUser(dbUser, dbUserPass, function(err, user) {
if (err) return handleError(db, err, 'can not add user', cb);
log.logger.trace({user: user, database: dbName}, 'mongo added new user');
db.close();
return cb();
});
});
});
});
} | javascript | function createDb(config, dbUser, dbUserPass, dbName, cb) {
log.logger.trace({user: dbUser, pwd: dbUserPass, name: dbName}, 'creating new datatbase');
var url = config.mongoUrl;
var admin = config.mongo.admin_auth.user;
var admin_pass = config.mongo.admin_auth.pass;
MongoClient.connect(url, function(err, db){
if (err) return handleError(null, err, 'cannot open mongodb connection', cb);
var targetDb = db.db(dbName);
targetDb.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err) {
if (err) return handleError(db, err, 'can not authenticate admin user', cb);
// update for mongodb3.2 - need to remove user first
targetDb.removeUser(dbUser, function(err) {
if(err){
log.logger.error(err, 'failed to remove user');
}
// add user to database
targetDb.addUser(dbUser, dbUserPass, function(err, user) {
if (err) return handleError(db, err, 'can not add user', cb);
log.logger.trace({user: user, database: dbName}, 'mongo added new user');
db.close();
return cb();
});
});
});
});
} | [
"function",
"createDb",
"(",
"config",
",",
"dbUser",
",",
"dbUserPass",
",",
"dbName",
",",
"cb",
")",
"{",
"log",
".",
"logger",
".",
"trace",
"(",
"{",
"user",
":",
"dbUser",
",",
"pwd",
":",
"dbUserPass",
",",
"name",
":",
"dbName",
"}",
",",
"'creating new datatbase'",
")",
";",
"var",
"url",
"=",
"config",
".",
"mongoUrl",
";",
"var",
"admin",
"=",
"config",
".",
"mongo",
".",
"admin_auth",
".",
"user",
";",
"var",
"admin_pass",
"=",
"config",
".",
"mongo",
".",
"admin_auth",
".",
"pass",
";",
"MongoClient",
".",
"connect",
"(",
"url",
",",
"function",
"(",
"err",
",",
"db",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handleError",
"(",
"null",
",",
"err",
",",
"'cannot open mongodb connection'",
",",
"cb",
")",
";",
"var",
"targetDb",
"=",
"db",
".",
"db",
"(",
"dbName",
")",
";",
"targetDb",
".",
"authenticate",
"(",
"admin",
",",
"admin_pass",
",",
"{",
"'authSource'",
":",
"'admin'",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handleError",
"(",
"db",
",",
"err",
",",
"'can not authenticate admin user'",
",",
"cb",
")",
";",
"// update for mongodb3.2 - need to remove user first",
"targetDb",
".",
"removeUser",
"(",
"dbUser",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"logger",
".",
"error",
"(",
"err",
",",
"'failed to remove user'",
")",
";",
"}",
"// add user to database",
"targetDb",
".",
"addUser",
"(",
"dbUser",
",",
"dbUserPass",
",",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handleError",
"(",
"db",
",",
"err",
",",
"'can not add user'",
",",
"cb",
")",
";",
"log",
".",
"logger",
".",
"trace",
"(",
"{",
"user",
":",
"user",
",",
"database",
":",
"dbName",
"}",
",",
"'mongo added new user'",
")",
";",
"db",
".",
"close",
"(",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | create a database, including user name and pwd | [
"create",
"a",
"database",
"including",
"user",
"name",
"and",
"pwd"
] | f906e98efbb4b0963bf5137b34b5e0589ba24e69 | https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/mongo.js#L16-L44 |
50,699 | feedhenry/fh-mbaas-middleware | lib/util/mongo.js | dropDb | function dropDb(config, dbUser, dbName, cb){
log.logger.trace({user: dbUser, name: dbName}, 'drop database');
var url = config.mongoUrl;
var admin = config.mongo.admin_auth.user;
var admin_pass = config.mongo.admin_auth.pass;
MongoClient.connect(url, function(err, dbObj){
if (err) return handleError(null, err, 'cannot open mongodb connection', cb);
var dbToDrop = dbObj.db(dbName);
dbToDrop.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err){
if(err) return handleError(dbObj, err, 'can not authenticate admin user', cb);
dbToDrop.removeUser(dbUser, function(err){
if(err){
log.logger.error(err, 'failed to remove user');
}
dbToDrop.dropDatabase(function(err){
if(err) return handleError(dbObj, err, 'failed to drop database', cb);
dbObj.close();
return cb();
});
});
});
});
} | javascript | function dropDb(config, dbUser, dbName, cb){
log.logger.trace({user: dbUser, name: dbName}, 'drop database');
var url = config.mongoUrl;
var admin = config.mongo.admin_auth.user;
var admin_pass = config.mongo.admin_auth.pass;
MongoClient.connect(url, function(err, dbObj){
if (err) return handleError(null, err, 'cannot open mongodb connection', cb);
var dbToDrop = dbObj.db(dbName);
dbToDrop.authenticate(admin, admin_pass, {'authSource': 'admin'}, function(err){
if(err) return handleError(dbObj, err, 'can not authenticate admin user', cb);
dbToDrop.removeUser(dbUser, function(err){
if(err){
log.logger.error(err, 'failed to remove user');
}
dbToDrop.dropDatabase(function(err){
if(err) return handleError(dbObj, err, 'failed to drop database', cb);
dbObj.close();
return cb();
});
});
});
});
} | [
"function",
"dropDb",
"(",
"config",
",",
"dbUser",
",",
"dbName",
",",
"cb",
")",
"{",
"log",
".",
"logger",
".",
"trace",
"(",
"{",
"user",
":",
"dbUser",
",",
"name",
":",
"dbName",
"}",
",",
"'drop database'",
")",
";",
"var",
"url",
"=",
"config",
".",
"mongoUrl",
";",
"var",
"admin",
"=",
"config",
".",
"mongo",
".",
"admin_auth",
".",
"user",
";",
"var",
"admin_pass",
"=",
"config",
".",
"mongo",
".",
"admin_auth",
".",
"pass",
";",
"MongoClient",
".",
"connect",
"(",
"url",
",",
"function",
"(",
"err",
",",
"dbObj",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handleError",
"(",
"null",
",",
"err",
",",
"'cannot open mongodb connection'",
",",
"cb",
")",
";",
"var",
"dbToDrop",
"=",
"dbObj",
".",
"db",
"(",
"dbName",
")",
";",
"dbToDrop",
".",
"authenticate",
"(",
"admin",
",",
"admin_pass",
",",
"{",
"'authSource'",
":",
"'admin'",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handleError",
"(",
"dbObj",
",",
"err",
",",
"'can not authenticate admin user'",
",",
"cb",
")",
";",
"dbToDrop",
".",
"removeUser",
"(",
"dbUser",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"logger",
".",
"error",
"(",
"err",
",",
"'failed to remove user'",
")",
";",
"}",
"dbToDrop",
".",
"dropDatabase",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"handleError",
"(",
"dbObj",
",",
"err",
",",
"'failed to drop database'",
",",
"cb",
")",
";",
"dbObj",
".",
"close",
"(",
")",
";",
"return",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | drop a database | [
"drop",
"a",
"database"
] | f906e98efbb4b0963bf5137b34b5e0589ba24e69 | https://github.com/feedhenry/fh-mbaas-middleware/blob/f906e98efbb4b0963bf5137b34b5e0589ba24e69/lib/util/mongo.js#L47-L73 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.