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 list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 |
|---|---|---|---|---|---|---|---|---|---|---|---|
31,700 | feedhenry/fh-mbaas-express | lib/mbaas.js | resolvePermission | function resolvePermission(params) {
var dbPermissions = mBaaS.permission_map.db;
if (params.act && dbPermissions && dbPermissions[params.act]) {
params.requestedPermission = dbPermissions[params.act].requires;
}
} | javascript | function resolvePermission(params) {
var dbPermissions = mBaaS.permission_map.db;
if (params.act && dbPermissions && dbPermissions[params.act]) {
params.requestedPermission = dbPermissions[params.act].requires;
}
} | [
"function",
"resolvePermission",
"(",
"params",
")",
"{",
"var",
"dbPermissions",
"=",
"mBaaS",
".",
"permission_map",
".",
"db",
";",
"if",
"(",
"params",
".",
"act",
"&&",
"dbPermissions",
"&&",
"dbPermissions",
"[",
"params",
".",
"act",
"]",
")",
"{",
... | DB actions are bound to specific permissions. For example the `list` action
requires only read permissions while `update` requires write. Those permissions
are configured in the `permission-map` of fh-db. If the given action has a
permission set we will add that to the params, otherwise we ignore it.
@param params Request parameter object | [
"DB",
"actions",
"are",
"bound",
"to",
"specific",
"permissions",
".",
"For",
"example",
"the",
"list",
"action",
"requires",
"only",
"read",
"permissions",
"while",
"update",
"requires",
"write",
".",
"Those",
"permissions",
"are",
"configured",
"in",
"the",
... | 381c2a5842b49a4cbc4519d55b9a3c870b364d3c | https://github.com/feedhenry/fh-mbaas-express/blob/381c2a5842b49a4cbc4519d55b9a3c870b364d3c/lib/mbaas.js#L39-L44 |
31,701 | passabilities/backrest | lib/routing/buildRoutes.js | getFilterMethods | function getFilterMethods(type, controller, action) {
// Get all filters for the action.
let filters = getFilters(type, controller, action)
// Get filter method names to be skipped.
type = `skip${type[0].toUpperCase() + type.slice(1)}`
let skipFilterMethods = _.map(getFilters(type, controller, action), 'action')
// Remove filters that should be skipped.
filters = _.filter(filters, f => {
for(let method of skipFilterMethods)
if(method === f.action)
return false
return true
})
// Return final list of filter methods.
return _.map(filters, f => {
let { action } = f
action = typeof action === 'string' ? controller[action] : action
return action.bind(controller)
})
} | javascript | function getFilterMethods(type, controller, action) {
// Get all filters for the action.
let filters = getFilters(type, controller, action)
// Get filter method names to be skipped.
type = `skip${type[0].toUpperCase() + type.slice(1)}`
let skipFilterMethods = _.map(getFilters(type, controller, action), 'action')
// Remove filters that should be skipped.
filters = _.filter(filters, f => {
for(let method of skipFilterMethods)
if(method === f.action)
return false
return true
})
// Return final list of filter methods.
return _.map(filters, f => {
let { action } = f
action = typeof action === 'string' ? controller[action] : action
return action.bind(controller)
})
} | [
"function",
"getFilterMethods",
"(",
"type",
",",
"controller",
",",
"action",
")",
"{",
"// Get all filters for the action.",
"let",
"filters",
"=",
"getFilters",
"(",
"type",
",",
"controller",
",",
"action",
")",
"// Get filter method names to be skipped.",
"type",
... | Get list of filter methods to be applied to a specific action. | [
"Get",
"list",
"of",
"filter",
"methods",
"to",
"be",
"applied",
"to",
"a",
"specific",
"action",
"."
] | d44d417f199c4199a0f440b5c56ced19248de27a | https://github.com/passabilities/backrest/blob/d44d417f199c4199a0f440b5c56ced19248de27a/lib/routing/buildRoutes.js#L153-L174 |
31,702 | passabilities/backrest | lib/routing/buildRoutes.js | getFilters | function getFilters(type, controller, action) {
// User can set 'only' and 'except' rules on filters to be used on one
// or many action methods.
let useOptions = { only: true, except: false }
// Only return action filter methods that apply.
return _.filter(controller[`__${type}Filters`], filter => {
// An action must be defined in each filter.
if(!('action' in filter) || !filter.action)
throw new Error(`No action defined in filter for [${controller.constructor.name}.${type}: ${JSON.stringify(filter)}].`)
// Filter cannot contain both options.
let containsBoth = _.every(_.keys(useOptions), o => o in filter)
if(containsBoth)
throw new Error(`${type[0].toUpperCase() + type.slice(1)} filter cannot have both \'only\' and \'except\' keys.`)
let option = _.first(_.intersection(_.keys(useOptions), _.keys(filter)))
// If no option is defined, use for all actions.
if(!option)
return true
let useActions, use = useOptions[option]
useActions = typeof (useActions = filter[option]) === 'string' ? [useActions] : useActions
// Determine if filter can be used for this action.
for(let ua of useActions)
if(ua === action)
return use
return !use
})
} | javascript | function getFilters(type, controller, action) {
// User can set 'only' and 'except' rules on filters to be used on one
// or many action methods.
let useOptions = { only: true, except: false }
// Only return action filter methods that apply.
return _.filter(controller[`__${type}Filters`], filter => {
// An action must be defined in each filter.
if(!('action' in filter) || !filter.action)
throw new Error(`No action defined in filter for [${controller.constructor.name}.${type}: ${JSON.stringify(filter)}].`)
// Filter cannot contain both options.
let containsBoth = _.every(_.keys(useOptions), o => o in filter)
if(containsBoth)
throw new Error(`${type[0].toUpperCase() + type.slice(1)} filter cannot have both \'only\' and \'except\' keys.`)
let option = _.first(_.intersection(_.keys(useOptions), _.keys(filter)))
// If no option is defined, use for all actions.
if(!option)
return true
let useActions, use = useOptions[option]
useActions = typeof (useActions = filter[option]) === 'string' ? [useActions] : useActions
// Determine if filter can be used for this action.
for(let ua of useActions)
if(ua === action)
return use
return !use
})
} | [
"function",
"getFilters",
"(",
"type",
",",
"controller",
",",
"action",
")",
"{",
"// User can set 'only' and 'except' rules on filters to be used on one",
"// or many action methods.",
"let",
"useOptions",
"=",
"{",
"only",
":",
"true",
",",
"except",
":",
"false",
"}... | Get list of filters based on the type name to be applied to a specific action. | [
"Get",
"list",
"of",
"filters",
"based",
"on",
"the",
"type",
"name",
"to",
"be",
"applied",
"to",
"a",
"specific",
"action",
"."
] | d44d417f199c4199a0f440b5c56ced19248de27a | https://github.com/passabilities/backrest/blob/d44d417f199c4199a0f440b5c56ced19248de27a/lib/routing/buildRoutes.js#L177-L207 |
31,703 | tunnckoCoreLabs/charlike | src/index.js | charlike | async function charlike(settings = {}) {
const proj = settings.project;
if (!proj || (proj && typeof proj !== 'object')) {
throw new TypeError('expect `settings.project` to be an object');
}
const options = await makeDefaults(settings);
const { project, templates } = options;
const cfgDir = path.join(os.homedir(), '.config', 'charlike');
const tplDir = path.join(cfgDir, 'templates');
const templatesDir = templates ? path.resolve(templates) : null;
if (templatesDir && fs.existsSync(templatesDir)) {
project.templates = templatesDir;
} else if (fs.existsSync(cfgDir) && fs.existsSync(tplDir)) {
project.templates = tplDir;
} else {
project.templates = path.join(path.dirname(__dirname), 'templates');
}
if (!fs.existsSync(project.templates)) {
throw new Error(`source templates folder not exist: ${project.templates}`);
}
const locals = objectAssign({}, options.locals, { project });
const stream = fastGlob.stream('**/*', {
cwd: project.templates,
ignore: arrayify(null),
});
return new Promise((resolve, reject) => {
stream.on('error', reject);
stream.on('end', () => {
// Note: Seems to be called before really write to the optionsination directory.
// Stream are still fucking shit even in Node v10.
// Feels like nothing happend since v0.10.
// For proof, `process.exit` from inside the `.then` in the CLI,
// it will end/close the program before even create the options folder.
// One more proof: put one console.log in stream.on('data')
// and you will see that it still outputs even after calling the resolve()
resolve({ locals, project, dest: options.dest, options });
});
stream.on('data', async (filepath) => {
try {
const tplFilepath = path.join(project.templates, filepath);
const { body } = await jstransformer.renderFileAsync(
tplFilepath,
{ engine: options.engine },
locals,
);
const newFilepath = path
.join(options.dest, filepath)
.replace('_circleci', '.circleci');
const basename = path
.basename(newFilepath)
.replace(/^__/, '')
.replace(/^\$/, '')
.replace(/^_/, '.');
const fp = path.join(path.dirname(newFilepath), basename);
const fpDirname = path.dirname(fp);
if (!fs.existsSync(fpDirname)) {
await util.promisify(fs.mkdir)(fpDirname);
}
await util.promisify(fs.writeFile)(fp, body);
} catch (err) {
reject(err);
}
});
});
} | javascript | async function charlike(settings = {}) {
const proj = settings.project;
if (!proj || (proj && typeof proj !== 'object')) {
throw new TypeError('expect `settings.project` to be an object');
}
const options = await makeDefaults(settings);
const { project, templates } = options;
const cfgDir = path.join(os.homedir(), '.config', 'charlike');
const tplDir = path.join(cfgDir, 'templates');
const templatesDir = templates ? path.resolve(templates) : null;
if (templatesDir && fs.existsSync(templatesDir)) {
project.templates = templatesDir;
} else if (fs.existsSync(cfgDir) && fs.existsSync(tplDir)) {
project.templates = tplDir;
} else {
project.templates = path.join(path.dirname(__dirname), 'templates');
}
if (!fs.existsSync(project.templates)) {
throw new Error(`source templates folder not exist: ${project.templates}`);
}
const locals = objectAssign({}, options.locals, { project });
const stream = fastGlob.stream('**/*', {
cwd: project.templates,
ignore: arrayify(null),
});
return new Promise((resolve, reject) => {
stream.on('error', reject);
stream.on('end', () => {
// Note: Seems to be called before really write to the optionsination directory.
// Stream are still fucking shit even in Node v10.
// Feels like nothing happend since v0.10.
// For proof, `process.exit` from inside the `.then` in the CLI,
// it will end/close the program before even create the options folder.
// One more proof: put one console.log in stream.on('data')
// and you will see that it still outputs even after calling the resolve()
resolve({ locals, project, dest: options.dest, options });
});
stream.on('data', async (filepath) => {
try {
const tplFilepath = path.join(project.templates, filepath);
const { body } = await jstransformer.renderFileAsync(
tplFilepath,
{ engine: options.engine },
locals,
);
const newFilepath = path
.join(options.dest, filepath)
.replace('_circleci', '.circleci');
const basename = path
.basename(newFilepath)
.replace(/^__/, '')
.replace(/^\$/, '')
.replace(/^_/, '.');
const fp = path.join(path.dirname(newFilepath), basename);
const fpDirname = path.dirname(fp);
if (!fs.existsSync(fpDirname)) {
await util.promisify(fs.mkdir)(fpDirname);
}
await util.promisify(fs.writeFile)(fp, body);
} catch (err) {
reject(err);
}
});
});
} | [
"async",
"function",
"charlike",
"(",
"settings",
"=",
"{",
"}",
")",
"{",
"const",
"proj",
"=",
"settings",
".",
"project",
";",
"if",
"(",
"!",
"proj",
"||",
"(",
"proj",
"&&",
"typeof",
"proj",
"!==",
"'object'",
")",
")",
"{",
"throw",
"new",
"... | Generates a complete project using a set of templates.
You can define what _"templates"_ files to be used
by passing `settings.templates`, by default it uses [./templates](./templates)
folder from this repository root.
You can define project metadata in `settings.project` object, which should contain
`name`, `description` properties and also can contain `repo` and `dest`.
By default the destination folder is dynamically built from `settings.cwd` and `settings.project.name`,
but this behavior can be changed. If `settings.project.repo` is passed, then it will be used
instead of the `settings.project.name`.
To control the context of the templates, pass `settings.locals`. The default set of locals
includes `version` string and `project`, `author` and `license` objects.
@example
import charlike from 'charlike';
const settings = {
project: { name: 'foobar', description: 'Awesome project' },
cwd: '/home/charlike/code',
templates: '/home/charlike/config/.jsproject',
locals: {
foo: 'bar',
// some helper
toUpperCase: (val) => val.toUpperCase(),
},
};
// the `dest` will be `/home/charlike/code/foobar`
charlike(settings)
.then(({ dest }) => console.log(`Project generated to ${dest}`))
.catch((err) => console.error(`Error occures: ${err.message}; Sorry!`));
@name charlike
@param {object} settings the only required is `project` which should be an object
@param {object} settings.cwd working directory to create project to, defaults to `process.cwd()`
@param {object} settings.project should contain `name`, `description`, `repo` and `dest`
@param {object} settings.locals to pass more context to template files
@param {string} settings.engine for different template engine to be used in template files, default is `lodash`
@return {Promise<object>} if successful, will resolve to object like `{ locals, project, dest, options }`
@public | [
"Generates",
"a",
"complete",
"project",
"using",
"a",
"set",
"of",
"templates",
"."
] | a1278ff083b76f9e14f14ca25e6b5a467c9e20fa | https://github.com/tunnckoCoreLabs/charlike/blob/a1278ff083b76f9e14f14ca25e6b5a467c9e20fa/src/index.js#L62-L139 |
31,704 | Rhinostone/gina | core/router.js | function(request, params, route) {
var uRe = params.url.split(/\//)
, uRo = route.split(/\//)
, maxLen = uRo.length
, score = 0
, r = {}
, i = 0;
//attaching routing description for this request
request.routing = params; // can be retried in controller with: req.routing
if (uRe.length === uRo.length) {
for (; i<maxLen; ++i) {
if (uRe[i] === uRo[i]) {
++score
} else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) {
++score
}
}
}
r.past = (score === maxLen) ? true : false;
r.request = request;
return r
} | javascript | function(request, params, route) {
var uRe = params.url.split(/\//)
, uRo = route.split(/\//)
, maxLen = uRo.length
, score = 0
, r = {}
, i = 0;
//attaching routing description for this request
request.routing = params; // can be retried in controller with: req.routing
if (uRe.length === uRo.length) {
for (; i<maxLen; ++i) {
if (uRe[i] === uRo[i]) {
++score
} else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) {
++score
}
}
}
r.past = (score === maxLen) ? true : false;
r.request = request;
return r
} | [
"function",
"(",
"request",
",",
"params",
",",
"route",
")",
"{",
"var",
"uRe",
"=",
"params",
".",
"url",
".",
"split",
"(",
"/",
"\\/",
"/",
")",
",",
"uRo",
"=",
"route",
".",
"split",
"(",
"/",
"\\/",
"/",
")",
",",
"maxLen",
"=",
"uRo",
... | Parse routing for mathcing url
@param {object} request
@param {object} params
@param {string} route
@return | [
"Parse",
"routing",
"for",
"mathcing",
"url"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/router.js#L113-L138 | |
31,705 | cshum/ginga | index.js | wrapFn | function wrapFn (gen) {
if (!is.function(gen)) throw new Error('Middleware must be a function')
if (!is.generator(gen)) return gen
// wrap generator with raco
var fn = raco.wrap(gen)
return function (ctx, next) {
fn.call(this, ctx, next)
}
} | javascript | function wrapFn (gen) {
if (!is.function(gen)) throw new Error('Middleware must be a function')
if (!is.generator(gen)) return gen
// wrap generator with raco
var fn = raco.wrap(gen)
return function (ctx, next) {
fn.call(this, ctx, next)
}
} | [
"function",
"wrapFn",
"(",
"gen",
")",
"{",
"if",
"(",
"!",
"is",
".",
"function",
"(",
"gen",
")",
")",
"throw",
"new",
"Error",
"(",
"'Middleware must be a function'",
")",
"if",
"(",
"!",
"is",
".",
"generator",
"(",
"gen",
")",
")",
"return",
"ge... | wrap ginga middleware function | [
"wrap",
"ginga",
"middleware",
"function"
] | 6169297b1864d3779f4f09884fd9979a59052fb5 | https://github.com/cshum/ginga/blob/6169297b1864d3779f4f09884fd9979a59052fb5/index.js#L8-L17 |
31,706 | cshum/ginga | index.js | use | function use () {
// init hooks
if (!this.hasOwnProperty('_hooks')) {
this._hooks = {}
}
var args = Array.prototype.slice.call(arguments)
var i, j, l, m
var name = null
if (is.array(args[0])) {
// use(['a','b','c'], ...)
var arr = args.shift()
for (i = 0, l = arr.length; i < l; i++) {
use.apply(this, [arr[i]].concat(args))
}
return this
} else if (is.object(args[0]) && args[0]._hooks) {
// use(ginga)
var key
// concat hooks
for (key in args[0]._hooks) {
use.call(this, key, args[0]._hooks[key])
}
return this
}
// method name
if (is.string(args[0])) name = args.shift()
if (!name) throw new Error('Method name is not defined.')
if (!this._hooks[name]) this._hooks[name] = []
for (i = 0, l = args.length; i < l; i++) {
if (is.function(args[i])) {
this._hooks[name].push(wrapFn(args[i]))
} else if (is.array(args[i])) {
// use('a', [fn1, fn2, fn3])
for (j = 0, m = args[i].length; j < m; j++) {
use.call(this, name, args[i][j])
}
return this
} else {
throw new Error('Middleware must be a function')
}
}
return this
} | javascript | function use () {
// init hooks
if (!this.hasOwnProperty('_hooks')) {
this._hooks = {}
}
var args = Array.prototype.slice.call(arguments)
var i, j, l, m
var name = null
if (is.array(args[0])) {
// use(['a','b','c'], ...)
var arr = args.shift()
for (i = 0, l = arr.length; i < l; i++) {
use.apply(this, [arr[i]].concat(args))
}
return this
} else if (is.object(args[0]) && args[0]._hooks) {
// use(ginga)
var key
// concat hooks
for (key in args[0]._hooks) {
use.call(this, key, args[0]._hooks[key])
}
return this
}
// method name
if (is.string(args[0])) name = args.shift()
if (!name) throw new Error('Method name is not defined.')
if (!this._hooks[name]) this._hooks[name] = []
for (i = 0, l = args.length; i < l; i++) {
if (is.function(args[i])) {
this._hooks[name].push(wrapFn(args[i]))
} else if (is.array(args[i])) {
// use('a', [fn1, fn2, fn3])
for (j = 0, m = args[i].length; j < m; j++) {
use.call(this, name, args[i][j])
}
return this
} else {
throw new Error('Middleware must be a function')
}
}
return this
} | [
"function",
"use",
"(",
")",
"{",
"// init hooks",
"if",
"(",
"!",
"this",
".",
"hasOwnProperty",
"(",
"'_hooks'",
")",
")",
"{",
"this",
".",
"_hooks",
"=",
"{",
"}",
"}",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"... | ginga use method | [
"ginga",
"use",
"method"
] | 6169297b1864d3779f4f09884fd9979a59052fb5 | https://github.com/cshum/ginga/blob/6169297b1864d3779f4f09884fd9979a59052fb5/index.js#L20-L66 |
31,707 | cshum/ginga | index.js | define | function define () {
var args = Array.prototype.slice.call(arguments)
var i, l
var name = args.shift()
if (is.array(name)) {
name = args.shift()
for (i = 0, l = name.length; i < l; i++) {
define.apply(this, [name[i]].concat(args))
}
return this
}
if (!is.string(name)) throw new Error('Method name is not defined')
var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null
var pre = args.map(wrapFn)
// define scope method
this[name] = function () {
var args = Array.prototype.slice.call(arguments)
var self = this
var callback
if (is.function(args[args.length - 1])) callback = args.pop()
// init pipeline
var pipe = []
var obj = this
// prototype chain
while (obj) {
if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) {
pipe.unshift(obj._hooks[name])
}
obj = Object.getPrototypeOf(obj)
}
// pre middlewares
pipe.unshift(pre)
// invoke middleware
if (invoke) pipe.push(invoke)
pipe = flatten(pipe)
// context object and next triggerer
var ctx = new EventEmitter()
ctx.method = name
ctx.args = args
var index = 0
var size = pipe.length
function next (err, res) {
if (err || index === size) {
var args = Array.prototype.slice.call(arguments)
// callback when err or end of pipeline
if (callback) callback.apply(self, args)
args.unshift('end')
ctx.emit.apply(ctx, args)
} else if (index < size) {
var fn = pipe[index]
index++
var val = fn.call(self, ctx, next)
if (is.promise(val)) {
val.then(function (res) {
next(null, res)
}, function (err) {
next(err || new Error())
})
} else if (fn.length < 2) {
// args without next() & not promise, sync func
next(null, val)
}
}
}
if (callback) {
next()
} else {
// use promise if no callback
return new Promise(function (resolve, reject) {
callback = function (err, result) {
if (err) return reject(err)
resolve(result)
}
next()
})
}
}
return this
} | javascript | function define () {
var args = Array.prototype.slice.call(arguments)
var i, l
var name = args.shift()
if (is.array(name)) {
name = args.shift()
for (i = 0, l = name.length; i < l; i++) {
define.apply(this, [name[i]].concat(args))
}
return this
}
if (!is.string(name)) throw new Error('Method name is not defined')
var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null
var pre = args.map(wrapFn)
// define scope method
this[name] = function () {
var args = Array.prototype.slice.call(arguments)
var self = this
var callback
if (is.function(args[args.length - 1])) callback = args.pop()
// init pipeline
var pipe = []
var obj = this
// prototype chain
while (obj) {
if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) {
pipe.unshift(obj._hooks[name])
}
obj = Object.getPrototypeOf(obj)
}
// pre middlewares
pipe.unshift(pre)
// invoke middleware
if (invoke) pipe.push(invoke)
pipe = flatten(pipe)
// context object and next triggerer
var ctx = new EventEmitter()
ctx.method = name
ctx.args = args
var index = 0
var size = pipe.length
function next (err, res) {
if (err || index === size) {
var args = Array.prototype.slice.call(arguments)
// callback when err or end of pipeline
if (callback) callback.apply(self, args)
args.unshift('end')
ctx.emit.apply(ctx, args)
} else if (index < size) {
var fn = pipe[index]
index++
var val = fn.call(self, ctx, next)
if (is.promise(val)) {
val.then(function (res) {
next(null, res)
}, function (err) {
next(err || new Error())
})
} else if (fn.length < 2) {
// args without next() & not promise, sync func
next(null, val)
}
}
}
if (callback) {
next()
} else {
// use promise if no callback
return new Promise(function (resolve, reject) {
callback = function (err, result) {
if (err) return reject(err)
resolve(result)
}
next()
})
}
}
return this
} | [
"function",
"define",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
"var",
"i",
",",
"l",
"var",
"name",
"=",
"args",
".",
"shift",
"(",
")",
"if",
"(",
"is",
".",
"array",
"(",
... | ginga define method | [
"ginga",
"define",
"method"
] | 6169297b1864d3779f4f09884fd9979a59052fb5 | https://github.com/cshum/ginga/blob/6169297b1864d3779f4f09884fd9979a59052fb5/index.js#L69-L159 |
31,708 | Jack12816/greppy | lib/app/worker.js | function(callback) {
self.configureDatabases(function(err) {
if (err) {
process.exit(111);
return;
}
self.configureApplicationStack(
app, server, callback
);
});
} | javascript | function(callback) {
self.configureDatabases(function(err) {
if (err) {
process.exit(111);
return;
}
self.configureApplicationStack(
app, server, callback
);
});
} | [
"function",
"(",
"callback",
")",
"{",
"self",
".",
"configureDatabases",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"process",
".",
"exit",
"(",
"111",
")",
";",
"return",
";",
"}",
"self",
".",
"configureApplicationStack",
"("... | Configure database connections | [
"Configure",
"database",
"connections"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/app/worker.js#L454-L466 | |
31,709 | Kronos-Integration/kronos-interceptor-object-data-processor-row | lib/recordCheck/data-check-common.js | function (fieldDefinition, fieldName) {
const severity = propertyHelper.getSeverity(fieldDefinition, undefined, 'mandatory');
const isMandatoy = propertyHelper.getProperty(fieldDefinition, undefined, 'mandatory');
// const severity = fieldDefinition.severity;
// const isMandatoy = fieldDefinition.mandatory;
if (isMandatoy === true) {
/**
* Just check if for mandatory fields the value is given
* @param content the content hash to be validated.
*/
return function (content) {
// get the value from the content hash
const valueToCheck = content[fieldName];
// If the value is defined, we need to check it
if (valueToCheck === undefined || valueToCheck === null) {
return {
errorCode: 'MANDATORY_VALUE_MISSING',
severity: severity,
fieldName: fieldName
};
}
};
}
} | javascript | function (fieldDefinition, fieldName) {
const severity = propertyHelper.getSeverity(fieldDefinition, undefined, 'mandatory');
const isMandatoy = propertyHelper.getProperty(fieldDefinition, undefined, 'mandatory');
// const severity = fieldDefinition.severity;
// const isMandatoy = fieldDefinition.mandatory;
if (isMandatoy === true) {
/**
* Just check if for mandatory fields the value is given
* @param content the content hash to be validated.
*/
return function (content) {
// get the value from the content hash
const valueToCheck = content[fieldName];
// If the value is defined, we need to check it
if (valueToCheck === undefined || valueToCheck === null) {
return {
errorCode: 'MANDATORY_VALUE_MISSING',
severity: severity,
fieldName: fieldName
};
}
};
}
} | [
"function",
"(",
"fieldDefinition",
",",
"fieldName",
")",
"{",
"const",
"severity",
"=",
"propertyHelper",
".",
"getSeverity",
"(",
"fieldDefinition",
",",
"undefined",
",",
"'mandatory'",
")",
";",
"const",
"isMandatoy",
"=",
"propertyHelper",
".",
"getProperty"... | Creates the checks which are common to each file type
@param fieldDefinition The field_definition for this field.
@param fieldName The name of the current field | [
"Creates",
"the",
"checks",
"which",
"are",
"common",
"to",
"each",
"file",
"type"
] | 678a59b84dab4a9082377c90849a0d62d97a1ea4 | https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/recordCheck/data-check-common.js#L14-L41 | |
31,710 | vimlet/vimlet-commons | docs/release/framework/vcomet/vcomet.js | function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (
evt.type === "load" ||
readyRegExp.test((evt.currentTarget || evt.srcElement).readyState)
) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
} | javascript | function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (
evt.type === "load" ||
readyRegExp.test((evt.currentTarget || evt.srcElement).readyState)
) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
} | [
"function",
"(",
"evt",
")",
"{",
"//Using currentTarget instead of target for Firefox 2.0's sake. Not",
"//all old browsers will be supported, but this one was easy enough",
"//to support and still makes sense.",
"if",
"(",
"evt",
".",
"type",
"===",
"\"load\"",
"||",
"readyRegExp",... | callback for script loads, used to check status of loading.
@param {Event} evt the event from the browser for the script
that was loaded. | [
"callback",
"for",
"script",
"loads",
"used",
"to",
"check",
"status",
"of",
"loading",
"."
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/docs/release/framework/vcomet/vcomet.js#L2073-L2089 | |
31,711 | vimlet/vimlet-commons | docs/release/framework/vcomet/vcomet.js | function (attrName, oldVal, newVal) {
var property = vcomet.util.hyphenToCamelCase(attrName);
// The onAttributeChanged callback is triggered whether its observed or as a reflection of a property
if (el.__observeAttributes[attrName] || el.__reflectProperties[property]) {
vcomet.triggerAllCallbackEvents(el, config, "onAttributeChanged", [attrName, oldVal, newVal]);
}
// The onPropertyChanged callback is triggered when the attribute has changed and its reflect by a property
if (el.__reflectProperties[property]) {
el["__" + property] = newVal;
vcomet.triggerAllCallbackEvents(el, config, "onPropertyChanged", [property, oldVal, newVal]);
}
} | javascript | function (attrName, oldVal, newVal) {
var property = vcomet.util.hyphenToCamelCase(attrName);
// The onAttributeChanged callback is triggered whether its observed or as a reflection of a property
if (el.__observeAttributes[attrName] || el.__reflectProperties[property]) {
vcomet.triggerAllCallbackEvents(el, config, "onAttributeChanged", [attrName, oldVal, newVal]);
}
// The onPropertyChanged callback is triggered when the attribute has changed and its reflect by a property
if (el.__reflectProperties[property]) {
el["__" + property] = newVal;
vcomet.triggerAllCallbackEvents(el, config, "onPropertyChanged", [property, oldVal, newVal]);
}
} | [
"function",
"(",
"attrName",
",",
"oldVal",
",",
"newVal",
")",
"{",
"var",
"property",
"=",
"vcomet",
".",
"util",
".",
"hyphenToCamelCase",
"(",
"attrName",
")",
";",
"// The onAttributeChanged callback is triggered whether its observed or as a reflection of a property",
... | Callback to be triggered when the user calls to setAttribute | [
"Callback",
"to",
"be",
"triggered",
"when",
"the",
"user",
"calls",
"to",
"setAttribute"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/docs/release/framework/vcomet/vcomet.js#L4582-L4597 | |
31,712 | datacentricdesign/dcd-model | services/ThingService.js | createAccessPolicy | function createAccessPolicy(thingId) {
const thingPolicy = {
id: thingId + "-" + thingId + "-cru-policy",
effect: "allow",
actions: ["dcd:actions:create", "dcd:actions:read", "dcd:actions:update"],
subjects: ["dcd:things:" + thingId],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
"dcd:things:" + thingId + ":properties:<.*>"
]
};
logger.debug("Thing policy: " + JSON.stringify(thingPolicy));
return policies.create(thingPolicy);
} | javascript | function createAccessPolicy(thingId) {
const thingPolicy = {
id: thingId + "-" + thingId + "-cru-policy",
effect: "allow",
actions: ["dcd:actions:create", "dcd:actions:read", "dcd:actions:update"],
subjects: ["dcd:things:" + thingId],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
"dcd:things:" + thingId + ":properties:<.*>"
]
};
logger.debug("Thing policy: " + JSON.stringify(thingPolicy));
return policies.create(thingPolicy);
} | [
"function",
"createAccessPolicy",
"(",
"thingId",
")",
"{",
"const",
"thingPolicy",
"=",
"{",
"id",
":",
"thingId",
"+",
"\"-\"",
"+",
"thingId",
"+",
"\"-cru-policy\"",
",",
"effect",
":",
"\"allow\"",
",",
"actions",
":",
"[",
"\"dcd:actions:create\"",
",",
... | Generate an access policy for a thing.
@param thingId
@returns {Promise<>} | [
"Generate",
"an",
"access",
"policy",
"for",
"a",
"thing",
"."
] | 162b724bc965439fcd894cf23101b2f00dd02924 | https://github.com/datacentricdesign/dcd-model/blob/162b724bc965439fcd894cf23101b2f00dd02924/services/ThingService.js#L161-L175 |
31,713 | datacentricdesign/dcd-model | services/ThingService.js | createOwnerAccessPolicy | function createOwnerAccessPolicy(thingId, subject) {
const thingOwnerPolicy = {
id: thingId + "-" + subject + "-clrud-policy",
effect: "allow",
actions: [
"dcd:actions:create",
"dcd:actions:list",
"dcd:actions:read",
"dcd:actions:update",
"dcd:actions:delete"
],
subjects: [subject],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
"dcd:things:" + thingId + ":properties:<.*>"
]
};
return policies.create(thingOwnerPolicy);
} | javascript | function createOwnerAccessPolicy(thingId, subject) {
const thingOwnerPolicy = {
id: thingId + "-" + subject + "-clrud-policy",
effect: "allow",
actions: [
"dcd:actions:create",
"dcd:actions:list",
"dcd:actions:read",
"dcd:actions:update",
"dcd:actions:delete"
],
subjects: [subject],
resources: [
"dcd:things:" + thingId,
"dcd:things:" + thingId + ":properties",
"dcd:things:" + thingId + ":properties:<.*>"
]
};
return policies.create(thingOwnerPolicy);
} | [
"function",
"createOwnerAccessPolicy",
"(",
"thingId",
",",
"subject",
")",
"{",
"const",
"thingOwnerPolicy",
"=",
"{",
"id",
":",
"thingId",
"+",
"\"-\"",
"+",
"subject",
"+",
"\"-clrud-policy\"",
",",
"effect",
":",
"\"allow\"",
",",
"actions",
":",
"[",
"... | Generate an access policy for the owner of a thing.
@param thingId
@param subject
@returns {Promise<>} | [
"Generate",
"an",
"access",
"policy",
"for",
"the",
"owner",
"of",
"a",
"thing",
"."
] | 162b724bc965439fcd894cf23101b2f00dd02924 | https://github.com/datacentricdesign/dcd-model/blob/162b724bc965439fcd894cf23101b2f00dd02924/services/ThingService.js#L183-L202 |
31,714 | dowjones/distribucache | lib/decorators/PopulateInDecorator.js | PopulateInDecorator | function PopulateInDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populateIn: joi.number().integer().min(500).required(),
populateInAttempts: joi.number().integer().default(5),
pausePopulateIn: joi.number().integer().required(),
accessedAtThrottle: joi.number().integer().default(1000)
}));
this._store = this._getStore();
this._timer = this._store.createTimer();
this._timer.on('error', this._emitError);
this._timer.on('timeout', this._onTimeout.bind(this));
this.on('set:after', this.setTimeout.bind(this));
this.on('get:after', throttle(this.setAccessedAt.bind(this),
this._config.accessedAtThrottle));
} | javascript | function PopulateInDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populateIn: joi.number().integer().min(500).required(),
populateInAttempts: joi.number().integer().default(5),
pausePopulateIn: joi.number().integer().required(),
accessedAtThrottle: joi.number().integer().default(1000)
}));
this._store = this._getStore();
this._timer = this._store.createTimer();
this._timer.on('error', this._emitError);
this._timer.on('timeout', this._onTimeout.bind(this));
this.on('set:after', this.setTimeout.bind(this));
this.on('get:after', throttle(this.setAccessedAt.bind(this),
this._config.accessedAtThrottle));
} | [
"function",
"PopulateInDecorator",
"(",
"cache",
",",
"config",
")",
"{",
"BaseDecorator",
".",
"call",
"(",
"this",
",",
"cache",
",",
"config",
",",
"joi",
".",
"object",
"(",
")",
".",
"keys",
"(",
"{",
"populateIn",
":",
"joi",
".",
"number",
"(",
... | Auto-populating Redis-backed cache
@constructor
@param {Cache} cache
@param {Object} [config]
@param {String} [config.populateIn]
@param {String} [config.populateInAttempts]
@param {String} [config.pausePopulateIn]
@param {String} [config.accessedAtThrottle] | [
"Auto",
"-",
"populating",
"Redis",
"-",
"backed",
"cache"
] | ad79caee277771a6e49ee4a98c4983480cd89945 | https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/PopulateInDecorator.js#L22-L38 |
31,715 | kalamuna/metalsmith-concat-convention | index.js | concatenateFile | function concatenateFile(file, done) {
// Append the concat file itself to the end of the concatenation.
files[file].files.push(file)
// Make sure the output is defined.
if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) {
// Output the file to the destination, without the ".concat".
const dir = path.dirname(file)
const filename = path.basename(file, opts.extname)
const final = path.join(dir, filename)
files[file].output = final
}
// Tell Metalsmith Concat plugin to concatinate the files.
metalsmithConcat(files[file])(files, metalsmith, done)
} | javascript | function concatenateFile(file, done) {
// Append the concat file itself to the end of the concatenation.
files[file].files.push(file)
// Make sure the output is defined.
if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) {
// Output the file to the destination, without the ".concat".
const dir = path.dirname(file)
const filename = path.basename(file, opts.extname)
const final = path.join(dir, filename)
files[file].output = final
}
// Tell Metalsmith Concat plugin to concatinate the files.
metalsmithConcat(files[file])(files, metalsmith, done)
} | [
"function",
"concatenateFile",
"(",
"file",
",",
"done",
")",
"{",
"// Append the concat file itself to the end of the concatenation.",
"files",
"[",
"file",
"]",
".",
"files",
".",
"push",
"(",
"file",
")",
"// Make sure the output is defined.",
"if",
"(",
"!",
"Obje... | Tell Metalsmith Concatenate to process on the given file config. | [
"Tell",
"Metalsmith",
"Concatenate",
"to",
"process",
"on",
"the",
"given",
"file",
"config",
"."
] | 631950f41b06423494ebf657635856ada5460615 | https://github.com/kalamuna/metalsmith-concat-convention/blob/631950f41b06423494ebf657635856ada5460615/index.js#L29-L44 |
31,716 | feedhenry/fh-mbaas-express | lib/cloud/fh-reports.js | getMessagingConfig | function getMessagingConfig() {
return {
host: process.env.FH_MESSAGING_HOST || '',
cluster: process.env.FH_MESSAGING_CLUSTER || '',
realTimeLoggingEnabled: isRealtimeLoggingEnabled(),
mbaasType: mbaasType(),
decoupled: process.env.FH_MBAAS_DECOUPLED || false,
msgServer: {
logMessageURL: getLogMessageURL()
},
backupFiles: {
fileName: process.env.FH_MESSAGING_BACKUP_FILE || ''
},
recoveryFiles:{
fileName: process.env.FH_MESSAGING_RECOVERY_FILE || ''
}
};
} | javascript | function getMessagingConfig() {
return {
host: process.env.FH_MESSAGING_HOST || '',
cluster: process.env.FH_MESSAGING_CLUSTER || '',
realTimeLoggingEnabled: isRealtimeLoggingEnabled(),
mbaasType: mbaasType(),
decoupled: process.env.FH_MBAAS_DECOUPLED || false,
msgServer: {
logMessageURL: getLogMessageURL()
},
backupFiles: {
fileName: process.env.FH_MESSAGING_BACKUP_FILE || ''
},
recoveryFiles:{
fileName: process.env.FH_MESSAGING_RECOVERY_FILE || ''
}
};
} | [
"function",
"getMessagingConfig",
"(",
")",
"{",
"return",
"{",
"host",
":",
"process",
".",
"env",
".",
"FH_MESSAGING_HOST",
"||",
"''",
",",
"cluster",
":",
"process",
".",
"env",
".",
"FH_MESSAGING_CLUSTER",
"||",
"''",
",",
"realTimeLoggingEnabled",
":",
... | Build the messaging configuration for the Reporting Client | [
"Build",
"the",
"messaging",
"configuration",
"for",
"the",
"Reporting",
"Client"
] | 381c2a5842b49a4cbc4519d55b9a3c870b364d3c | https://github.com/feedhenry/fh-mbaas-express/blob/381c2a5842b49a4cbc4519d55b9a3c870b364d3c/lib/cloud/fh-reports.js#L60-L77 |
31,717 | feedhenry/fh-mbaas-express | lib/cloud/fh-reports.js | getLogMessageURL | function getLogMessageURL() {
var url = '';
if (process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP) {
url = 'http://' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP + ':' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_PORT;
url += '/sys/admin/reports/TOPIC';
} else {
url = process.env.FH_MESSAGING_SERVER || ''; // Default setting
}
return url;
} | javascript | function getLogMessageURL() {
var url = '';
if (process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP) {
url = 'http://' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_IP + ':' + process.env.OPENSHIFT_FEEDHENRY_REPORTER_PORT;
url += '/sys/admin/reports/TOPIC';
} else {
url = process.env.FH_MESSAGING_SERVER || ''; // Default setting
}
return url;
} | [
"function",
"getLogMessageURL",
"(",
")",
"{",
"var",
"url",
"=",
"''",
";",
"if",
"(",
"process",
".",
"env",
".",
"OPENSHIFT_FEEDHENRY_REPORTER_IP",
")",
"{",
"url",
"=",
"'http://'",
"+",
"process",
".",
"env",
".",
"OPENSHIFT_FEEDHENRY_REPORTER_IP",
"+",
... | Get the logging message URL taking into account OpenShift environmental factors | [
"Get",
"the",
"logging",
"message",
"URL",
"taking",
"into",
"account",
"OpenShift",
"environmental",
"factors"
] | 381c2a5842b49a4cbc4519d55b9a3c870b364d3c | https://github.com/feedhenry/fh-mbaas-express/blob/381c2a5842b49a4cbc4519d55b9a3c870b364d3c/lib/cloud/fh-reports.js#L82-L91 |
31,718 | feedhenry/fh-mbaas-express | lib/cloud/fh-reports.js | isRealtimeLoggingEnabled | function isRealtimeLoggingEnabled() {
var flag = process.env.FH_MESSAGING_REALTIME_ENABLED;
if (flag && (flag === 'true' || flag === true) ) {
return true;
}
return false;
} | javascript | function isRealtimeLoggingEnabled() {
var flag = process.env.FH_MESSAGING_REALTIME_ENABLED;
if (flag && (flag === 'true' || flag === true) ) {
return true;
}
return false;
} | [
"function",
"isRealtimeLoggingEnabled",
"(",
")",
"{",
"var",
"flag",
"=",
"process",
".",
"env",
".",
"FH_MESSAGING_REALTIME_ENABLED",
";",
"if",
"(",
"flag",
"&&",
"(",
"flag",
"===",
"'true'",
"||",
"flag",
"===",
"true",
")",
")",
"{",
"return",
"true"... | Is realtime logging enabled for this application | [
"Is",
"realtime",
"logging",
"enabled",
"for",
"this",
"application"
] | 381c2a5842b49a4cbc4519d55b9a3c870b364d3c | https://github.com/feedhenry/fh-mbaas-express/blob/381c2a5842b49a4cbc4519d55b9a3c870b364d3c/lib/cloud/fh-reports.js#L105-L111 |
31,719 | yhtml5/yhtml5-cli | packages/yhtml5-cli/demo/lib/options.js | getMetadata | function getMetadata (dir) {
var json = path.join(dir, 'meta.json')
var js = path.join(dir, 'meta.js')
var opts = {}
if (exists(json)) {
opts = metadata.sync(json)
} else if (exists(js)) {
var req = require(path.resolve(js))
if (req !== Object(req)) {
throw new Error('meta.js needs to expose an object')
}
opts = req
}
return opts
} | javascript | function getMetadata (dir) {
var json = path.join(dir, 'meta.json')
var js = path.join(dir, 'meta.js')
var opts = {}
if (exists(json)) {
opts = metadata.sync(json)
} else if (exists(js)) {
var req = require(path.resolve(js))
if (req !== Object(req)) {
throw new Error('meta.js needs to expose an object')
}
opts = req
}
return opts
} | [
"function",
"getMetadata",
"(",
"dir",
")",
"{",
"var",
"json",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"'meta.json'",
")",
"var",
"js",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"'meta.js'",
")",
"var",
"opts",
"=",
"{",
"}",
"if",
"(",
"exi... | Gets the metadata from either a meta.json or meta.js file.
@param {String} dir
@return {Object} | [
"Gets",
"the",
"metadata",
"from",
"either",
"a",
"meta",
".",
"json",
"or",
"meta",
".",
"js",
"file",
"."
] | 521a8ad160058e453dff87c7cc9bfb16215715c6 | https://github.com/yhtml5/yhtml5-cli/blob/521a8ad160058e453dff87c7cc9bfb16215715c6/packages/yhtml5-cli/demo/lib/options.js#L35-L51 |
31,720 | dowjones/distribucache | lib/decorators/PopulateDecorator.js | PopulateDecorator | function PopulateDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populate: joi.func().required(),
timeoutPopulateIn: joi.number().integer().default(1000 * 30),
leaseExpiresIn: joi.number().integer()
}));
this._store = this._getStore();
this._lease = this._store.createLease(
this._config.leaseExpiresIn || this._config.timeoutPopulateIn + 1000);
this.on('get:stale', this._onStaleEvent.bind(this));
} | javascript | function PopulateDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
populate: joi.func().required(),
timeoutPopulateIn: joi.number().integer().default(1000 * 30),
leaseExpiresIn: joi.number().integer()
}));
this._store = this._getStore();
this._lease = this._store.createLease(
this._config.leaseExpiresIn || this._config.timeoutPopulateIn + 1000);
this.on('get:stale', this._onStaleEvent.bind(this));
} | [
"function",
"PopulateDecorator",
"(",
"cache",
",",
"config",
")",
"{",
"BaseDecorator",
".",
"call",
"(",
"this",
",",
"cache",
",",
"config",
",",
"joi",
".",
"object",
"(",
")",
".",
"keys",
"(",
"{",
"populate",
":",
"joi",
".",
"func",
"(",
")",... | Self-populating data-store independent cache
@param {Cache} cache
@param {Object} config
@param {Function} config.populate
@param {Number} [config.leaseExpiresIn] in ms
@param {Number} [config.timeoutPopulateIn] in ms, defaults to 30sec | [
"Self",
"-",
"populating",
"data",
"-",
"store",
"independent",
"cache"
] | ad79caee277771a6e49ee4a98c4983480cd89945 | https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/PopulateDecorator.js#L22-L32 |
31,721 | SandJS/http | lib/middleware/logRequestTime.js | logRequest | function logRequest(err, res) {
if (res) {
let ms = new Date() - res.requestStartTime;
var time = ms < 1000 ? `${ms}ms` : `${(ms/1000).toFixed(2)}s`;
logRoute(`${res.req.method} ${res.statusCode} (${time}): ${res.req.originalUrl}`);
}
} | javascript | function logRequest(err, res) {
if (res) {
let ms = new Date() - res.requestStartTime;
var time = ms < 1000 ? `${ms}ms` : `${(ms/1000).toFixed(2)}s`;
logRoute(`${res.req.method} ${res.statusCode} (${time}): ${res.req.originalUrl}`);
}
} | [
"function",
"logRequest",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"res",
")",
"{",
"let",
"ms",
"=",
"new",
"Date",
"(",
")",
"-",
"res",
".",
"requestStartTime",
";",
"var",
"time",
"=",
"ms",
"<",
"1000",
"?",
"`",
"${",
"ms",
"}",
"`",
... | Log the request time when finished
@param {null|Error} err - Request error if there was one
@param {Request} req - Request Object | [
"Log",
"the",
"request",
"time",
"when",
"finished"
] | 8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f | https://github.com/SandJS/http/blob/8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f/lib/middleware/logRequestTime.js#L30-L38 |
31,722 | Rhinostone/gina | script/post_install.js | function() {
self.isWin32 = ( os.platform() == 'win32' ) ? true : false;
self.path = _( __dirname.substring(0, (__dirname.length - "script".length)-1 ) );
self.root = process.cwd().toString();
createVersionFile();
//console.log('[ debug ] createVersionFile()');
createGinaFileForPlatform();
//console.log('[ debug ] createGinaFileForPlatform()');
} | javascript | function() {
self.isWin32 = ( os.platform() == 'win32' ) ? true : false;
self.path = _( __dirname.substring(0, (__dirname.length - "script".length)-1 ) );
self.root = process.cwd().toString();
createVersionFile();
//console.log('[ debug ] createVersionFile()');
createGinaFileForPlatform();
//console.log('[ debug ] createGinaFileForPlatform()');
} | [
"function",
"(",
")",
"{",
"self",
".",
"isWin32",
"=",
"(",
"os",
".",
"platform",
"(",
")",
"==",
"'win32'",
")",
"?",
"true",
":",
"false",
";",
"self",
".",
"path",
"=",
"_",
"(",
"__dirname",
".",
"substring",
"(",
"0",
",",
"(",
"__dirname"... | Initialize post installation scripts. | [
"Initialize",
"post",
"installation",
"scripts",
"."
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/script/post_install.js#L33-L43 | |
31,723 | Rhinostone/gina | script/post_install.js | function(win32Name, callback) {
var name = require( _(self.path + '/package.json') ).name;
var appPath = _( self.path.substring(0, (self.path.length - ("node_modules/" + name + '/').length)) );
var source = _(self.path + '/core/template/command/gina.tpl');
var target = _(appPath +'/'+ name);
if ( typeof(win32Name) != 'undefined') {
target = _(appPath +'/'+ win32Name)
}
//Will override.
if ( typeof(callback) != 'undefined') {
try {
utils.generator.createFileFromTemplateSync(source, target);
setTimeout(function () {
callback(false)
}, 1000)
} catch (err) {
callback(err)
}
} else {
utils.generator.createFileFromTemplateSync(source, target)
}
} | javascript | function(win32Name, callback) {
var name = require( _(self.path + '/package.json') ).name;
var appPath = _( self.path.substring(0, (self.path.length - ("node_modules/" + name + '/').length)) );
var source = _(self.path + '/core/template/command/gina.tpl');
var target = _(appPath +'/'+ name);
if ( typeof(win32Name) != 'undefined') {
target = _(appPath +'/'+ win32Name)
}
//Will override.
if ( typeof(callback) != 'undefined') {
try {
utils.generator.createFileFromTemplateSync(source, target);
setTimeout(function () {
callback(false)
}, 1000)
} catch (err) {
callback(err)
}
} else {
utils.generator.createFileFromTemplateSync(source, target)
}
} | [
"function",
"(",
"win32Name",
",",
"callback",
")",
"{",
"var",
"name",
"=",
"require",
"(",
"_",
"(",
"self",
".",
"path",
"+",
"'/package.json'",
")",
")",
".",
"name",
";",
"var",
"appPath",
"=",
"_",
"(",
"self",
".",
"path",
".",
"substring",
... | Creating framework command line file for nix. | [
"Creating",
"framework",
"command",
"line",
"file",
"for",
"nix",
"."
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/script/post_install.js#L75-L98 | |
31,724 | Jack12816/greppy | lib/http/mvc/loader.js | function(callback) {
try {
var controller = require(path);
callback(null, controller);
} catch (e) {
return callback(e);
}
} | javascript | function(callback) {
try {
var controller = require(path);
callback(null, controller);
} catch (e) {
return callback(e);
}
} | [
"function",
"(",
"callback",
")",
"{",
"try",
"{",
"var",
"controller",
"=",
"require",
"(",
"path",
")",
";",
"callback",
"(",
"null",
",",
"controller",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"callback",
"(",
"e",
")",
";",
"}",
... | Prepare the controller | [
"Prepare",
"the",
"controller"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L237-L245 | |
31,725 | Jack12816/greppy | lib/http/mvc/loader.js | function(controller, callback) {
// Allow configure-method less controllers
if ('function' !== typeof controller.configure) {
return callback(null, controller);
}
controller.configure(
self.worker.app,
self.worker.server,
function(err) {
callback(err, controller);
});
} | javascript | function(controller, callback) {
// Allow configure-method less controllers
if ('function' !== typeof controller.configure) {
return callback(null, controller);
}
controller.configure(
self.worker.app,
self.worker.server,
function(err) {
callback(err, controller);
});
} | [
"function",
"(",
"controller",
",",
"callback",
")",
"{",
"// Allow configure-method less controllers",
"if",
"(",
"'function'",
"!==",
"typeof",
"controller",
".",
"configure",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"controller",
")",
";",
"}",
"cont... | Run the configure method of the current controller | [
"Run",
"the",
"configure",
"method",
"of",
"the",
"current",
"controller"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L248-L261 | |
31,726 | Jack12816/greppy | lib/http/mvc/loader.js | function(controller, callback) {
// Add the given name to the controller
controller.name = name;
controller.module = module;
// Set default value on the controller instance
controller.basePath = self.getBasePath(
controller, path, module
);
// Add the canonical path
controller.canonicalPath = self.getCanonicalPath(
path, name, module
);
callback(null, controller);
} | javascript | function(controller, callback) {
// Add the given name to the controller
controller.name = name;
controller.module = module;
// Set default value on the controller instance
controller.basePath = self.getBasePath(
controller, path, module
);
// Add the canonical path
controller.canonicalPath = self.getCanonicalPath(
path, name, module
);
callback(null, controller);
} | [
"function",
"(",
"controller",
",",
"callback",
")",
"{",
"// Add the given name to the controller",
"controller",
".",
"name",
"=",
"name",
";",
"controller",
".",
"module",
"=",
"module",
";",
"// Set default value on the controller instance",
"controller",
".",
"base... | Run any options generation | [
"Run",
"any",
"options",
"generation"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L264-L281 | |
31,727 | Jack12816/greppy | lib/http/mvc/loader.js | function(controller, callback) {
self.prepareControllerActions(controller, function(err, actions) {
callback(err, controller, actions);
});
} | javascript | function(controller, callback) {
self.prepareControllerActions(controller, function(err, actions) {
callback(err, controller, actions);
});
} | [
"function",
"(",
"controller",
",",
"callback",
")",
"{",
"self",
".",
"prepareControllerActions",
"(",
"controller",
",",
"function",
"(",
"err",
",",
"actions",
")",
"{",
"callback",
"(",
"err",
",",
"controller",
",",
"actions",
")",
";",
"}",
")",
";... | Prepare all actions of the controller | [
"Prepare",
"all",
"actions",
"of",
"the",
"controller"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L284-L288 | |
31,728 | Jack12816/greppy | lib/http/mvc/loader.js | function(controller, actions, callback) {
self.worker.context.routes = self.worker.context.routes.concat(
actions
);
callback(null, controller);
} | javascript | function(controller, actions, callback) {
self.worker.context.routes = self.worker.context.routes.concat(
actions
);
callback(null, controller);
} | [
"function",
"(",
"controller",
",",
"actions",
",",
"callback",
")",
"{",
"self",
".",
"worker",
".",
"context",
".",
"routes",
"=",
"self",
".",
"worker",
".",
"context",
".",
"routes",
".",
"concat",
"(",
"actions",
")",
";",
"callback",
"(",
"null",... | Register routes to the worker context | [
"Register",
"routes",
"to",
"the",
"worker",
"context"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L291-L296 | |
31,729 | Jack12816/greppy | lib/http/mvc/loader.js | function(callback) {
async.map(modules, function(module, callback) {
callback && callback(
null,
{
name: module,
path: process.cwd() + '/modules/' +
module + '/controllers/'
}
);
}, callback);
} | javascript | function(callback) {
async.map(modules, function(module, callback) {
callback && callback(
null,
{
name: module,
path: process.cwd() + '/modules/' +
module + '/controllers/'
}
);
}, callback);
} | [
"function",
"(",
"callback",
")",
"{",
"async",
".",
"map",
"(",
"modules",
",",
"function",
"(",
"module",
",",
"callback",
")",
"{",
"callback",
"&&",
"callback",
"(",
"null",
",",
"{",
"name",
":",
"module",
",",
"path",
":",
"process",
".",
"cwd"... | Build module paths | [
"Build",
"module",
"paths"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L329-L340 | |
31,730 | Jack12816/greppy | lib/http/mvc/loader.js | function(map, callback) {
async.filter(map, function(module, callback) {
fs.exists(module.path, callback);
}, function(map) {
callback(null, map);
});
} | javascript | function(map, callback) {
async.filter(map, function(module, callback) {
fs.exists(module.path, callback);
}, function(map) {
callback(null, map);
});
} | [
"function",
"(",
"map",
",",
"callback",
")",
"{",
"async",
".",
"filter",
"(",
"map",
",",
"function",
"(",
"module",
",",
"callback",
")",
"{",
"fs",
".",
"exists",
"(",
"module",
".",
"path",
",",
"callback",
")",
";",
"}",
",",
"function",
"(",... | Check for valid modules - paths | [
"Check",
"for",
"valid",
"modules",
"-",
"paths"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L343-L349 | |
31,731 | Jack12816/greppy | lib/http/mvc/loader.js | function(map, callback) {
// Walk through all modules in parallel
async.map(map, function(module, callback) {
// Filter all non-js files in parallel
async.filter(
pathHelper.list(module.path),
function(path, callback) {
callback(path.match(/\.js$/i));
}, function(paths) {
module.paths = paths;
callback(null, module);
});
}, callback);
} | javascript | function(map, callback) {
// Walk through all modules in parallel
async.map(map, function(module, callback) {
// Filter all non-js files in parallel
async.filter(
pathHelper.list(module.path),
function(path, callback) {
callback(path.match(/\.js$/i));
}, function(paths) {
module.paths = paths;
callback(null, module);
});
}, callback);
} | [
"function",
"(",
"map",
",",
"callback",
")",
"{",
"// Walk through all modules in parallel",
"async",
".",
"map",
"(",
"map",
",",
"function",
"(",
"module",
",",
"callback",
")",
"{",
"// Filter all non-js files in parallel",
"async",
".",
"filter",
"(",
"pathHe... | Search for javascript files | [
"Search",
"for",
"javascript",
"files"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L352-L368 | |
31,732 | Jack12816/greppy | lib/http/mvc/loader.js | function(map, callback) {
// Walk through all modules in parallel
async.map(map, function(module, callback) {
logger.info('Loading ' + (module.name).blue + ' module');
// Walk through all possible controllers of the module
async.map(module.paths, function(path, callback) {
self.loadController(
path,
basename(path.replace(/\.js$/g, '')),
module.name,
callback
);
}, function(err, controllers) {
module.controllers = controllers;
callback(err, module);
});
}, callback);
} | javascript | function(map, callback) {
// Walk through all modules in parallel
async.map(map, function(module, callback) {
logger.info('Loading ' + (module.name).blue + ' module');
// Walk through all possible controllers of the module
async.map(module.paths, function(path, callback) {
self.loadController(
path,
basename(path.replace(/\.js$/g, '')),
module.name,
callback
);
}, function(err, controllers) {
module.controllers = controllers;
callback(err, module);
});
}, callback);
} | [
"function",
"(",
"map",
",",
"callback",
")",
"{",
"// Walk through all modules in parallel",
"async",
".",
"map",
"(",
"map",
",",
"function",
"(",
"module",
",",
"callback",
")",
"{",
"logger",
".",
"info",
"(",
"'Loading '",
"+",
"(",
"module",
".",
"na... | Load controllers of the modules | [
"Load",
"controllers",
"of",
"the",
"modules"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/http/mvc/loader.js#L371-L394 | |
31,733 | zhennann/egg-born-backend | lib/module/locales.js | getText | function getText(locale, ...args) {
const key = args[0];
if (!key) return null;
// try locale
let resource = ebLocales[locale] || {};
let text = resource[key];
if (text === undefined && locale !== 'en-us') {
// try en-us
resource = ebLocales['en-us'] || {};
text = resource[key];
}
// equal key
if (text === undefined) {
text = key;
}
// format
args[0] = text;
return localeutil.getText.apply(localeutil, args);
} | javascript | function getText(locale, ...args) {
const key = args[0];
if (!key) return null;
// try locale
let resource = ebLocales[locale] || {};
let text = resource[key];
if (text === undefined && locale !== 'en-us') {
// try en-us
resource = ebLocales['en-us'] || {};
text = resource[key];
}
// equal key
if (text === undefined) {
text = key;
}
// format
args[0] = text;
return localeutil.getText.apply(localeutil, args);
} | [
"function",
"getText",
"(",
"locale",
",",
"...",
"args",
")",
"{",
"const",
"key",
"=",
"args",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"key",
")",
"return",
"null",
";",
"// try locale",
"let",
"resource",
"=",
"ebLocales",
"[",
"locale",
"]",
"||",
... | based on koa-locales
https://github.com/koajs/locales/blob/master/index.js | [
"based",
"on",
"koa",
"-",
"locales"
] | 5b376e22b00b1284b56d9cb563aa28b49cf9ac73 | https://github.com/zhennann/egg-born-backend/blob/5b376e22b00b1284b56d9cb563aa28b49cf9ac73/lib/module/locales.js#L91-L110 |
31,734 | township/township-access | index.js | create | function create (key, scopes, callback) {
const data = {
key: key,
scopes: scopes
}
db.put(key, data, function (err) {
if (err) return callback(err)
else callback(null, data)
})
} | javascript | function create (key, scopes, callback) {
const data = {
key: key,
scopes: scopes
}
db.put(key, data, function (err) {
if (err) return callback(err)
else callback(null, data)
})
} | [
"function",
"create",
"(",
"key",
",",
"scopes",
",",
"callback",
")",
"{",
"const",
"data",
"=",
"{",
"key",
":",
"key",
",",
"scopes",
":",
"scopes",
"}",
"db",
".",
"put",
"(",
"key",
",",
"data",
",",
"function",
"(",
"err",
")",
"{",
"if",
... | Create a set of access scopes
@name access.create
@memberof townshipAccess
@param {string} key - the key for the access scopes
@param {array} scopes - array of strings
@param {function} callback - callback with `err`, `data` arguments | [
"Create",
"a",
"set",
"of",
"access",
"scopes"
] | c710f40e96712c1e1ee936b01da299010f6c4086 | https://github.com/township/township-access/blob/c710f40e96712c1e1ee936b01da299010f6c4086/index.js#L41-L51 |
31,735 | township/township-access | index.js | update | function update (key, scopes, callback) {
const unlock = lock(key)
get(key, function (err, account) {
if (err) {
unlock()
return callback(err)
}
account.scopes = scopes
db.put(key, account, function (err) {
unlock()
if (err) return callback(err)
else callback(null, account)
})
})
} | javascript | function update (key, scopes, callback) {
const unlock = lock(key)
get(key, function (err, account) {
if (err) {
unlock()
return callback(err)
}
account.scopes = scopes
db.put(key, account, function (err) {
unlock()
if (err) return callback(err)
else callback(null, account)
})
})
} | [
"function",
"update",
"(",
"key",
",",
"scopes",
",",
"callback",
")",
"{",
"const",
"unlock",
"=",
"lock",
"(",
"key",
")",
"get",
"(",
"key",
",",
"function",
"(",
"err",
",",
"account",
")",
"{",
"if",
"(",
"err",
")",
"{",
"unlock",
"(",
")",... | Update a set of access scopes
@name access.update
@memberof townshipAccess
@param {string} key - the key for the access scopes
@param {array} scopes - array of strings
@param {function} callback - callback with `err`, `data` arguments | [
"Update",
"a",
"set",
"of",
"access",
"scopes"
] | c710f40e96712c1e1ee936b01da299010f6c4086 | https://github.com/township/township-access/blob/c710f40e96712c1e1ee936b01da299010f6c4086/index.js#L62-L79 |
31,736 | township/township-access | index.js | verify | function verify (key, scopes, callback) {
db.get(key, function (err, account) {
if (err) return callback(err)
var scopeAccess = verifyScopes(account, scopes)
if (scopeAccess) return callback(null, account)
else callback(new Error('Access denied'))
})
} | javascript | function verify (key, scopes, callback) {
db.get(key, function (err, account) {
if (err) return callback(err)
var scopeAccess = verifyScopes(account, scopes)
if (scopeAccess) return callback(null, account)
else callback(new Error('Access denied'))
})
} | [
"function",
"verify",
"(",
"key",
",",
"scopes",
",",
"callback",
")",
"{",
"db",
".",
"get",
"(",
"key",
",",
"function",
"(",
"err",
",",
"account",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
"var",
"scopeAccess",
"="... | Verify that a set of scopes match what is in the db for a key
@name access.verify
@memberof townshipAccess
@param {string} key - the key for the access scopes
@param {array} scopes - array of strings with scopes that must match
@param {function} callback - callback with `err`, `data` arguments | [
"Verify",
"that",
"a",
"set",
"of",
"scopes",
"match",
"what",
"is",
"in",
"the",
"db",
"for",
"a",
"key"
] | c710f40e96712c1e1ee936b01da299010f6c4086 | https://github.com/township/township-access/blob/c710f40e96712c1e1ee936b01da299010f6c4086/index.js#L102-L109 |
31,737 | township/township-access | index.js | verifyScopes | function verifyScopes (data, scopes) {
let i = 0
const l = scopes.length
for (i; i < l; i++) {
if (!verifyScope(data, scopes[i])) return false
}
return true
} | javascript | function verifyScopes (data, scopes) {
let i = 0
const l = scopes.length
for (i; i < l; i++) {
if (!verifyScope(data, scopes[i])) return false
}
return true
} | [
"function",
"verifyScopes",
"(",
"data",
",",
"scopes",
")",
"{",
"let",
"i",
"=",
"0",
"const",
"l",
"=",
"scopes",
".",
"length",
"for",
"(",
"i",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"verifyScope",
"(",
"data",
",",
... | Verify that a set of scopes match what is available in an object with a scopes property
@name access.verifyScopes
@memberof townshipAccess
@param {object} data
@param {array} data.scopes - array of strings
@param {array} scopes - array of strings with scopes that must match
@return {boolean} returns `true` if `scopes` are all found in `data.scopes` | [
"Verify",
"that",
"a",
"set",
"of",
"scopes",
"match",
"what",
"is",
"available",
"in",
"an",
"object",
"with",
"a",
"scopes",
"property"
] | c710f40e96712c1e1ee936b01da299010f6c4086 | https://github.com/township/township-access/blob/c710f40e96712c1e1ee936b01da299010f6c4086/index.js#L121-L130 |
31,738 | township/township-access | index.js | verifyScope | function verifyScope (account, scope) {
if (!account || !account.scopes || !account.scopes.length || !scope) return false
return account.scopes.includes(scope)
} | javascript | function verifyScope (account, scope) {
if (!account || !account.scopes || !account.scopes.length || !scope) return false
return account.scopes.includes(scope)
} | [
"function",
"verifyScope",
"(",
"account",
",",
"scope",
")",
"{",
"if",
"(",
"!",
"account",
"||",
"!",
"account",
".",
"scopes",
"||",
"!",
"account",
".",
"scopes",
".",
"length",
"||",
"!",
"scope",
")",
"return",
"false",
"return",
"account",
".",... | Verify that a scope matches what is available in an object with a scopes property
@name access.verifyScope
@memberof townshipAccess
@param {string} key - the key for the access scopes
@param {function} callback - callback with `err`, `data` arguments
@return {boolean} returns `true` if `scope` is found in `data.scopes` | [
"Verify",
"that",
"a",
"scope",
"matches",
"what",
"is",
"available",
"in",
"an",
"object",
"with",
"a",
"scopes",
"property"
] | c710f40e96712c1e1ee936b01da299010f6c4086 | https://github.com/township/township-access/blob/c710f40e96712c1e1ee936b01da299010f6c4086/index.js#L141-L144 |
31,739 | doug-martin/it | examples/requirejs/scripts/it.js | _suite | function _suite(description, cb) {
var test = new this(description, {});
var it = test._addAction;
_(["suite", "test", "timeout", "getAction", "beforeAll", "beforeEach",
"afterAll", "afterEach", "context", "get", "set", "skip"]).forEach(function (key) {
it[key] = test[key];
});
cb(test);
return test;
} | javascript | function _suite(description, cb) {
var test = new this(description, {});
var it = test._addAction;
_(["suite", "test", "timeout", "getAction", "beforeAll", "beforeEach",
"afterAll", "afterEach", "context", "get", "set", "skip"]).forEach(function (key) {
it[key] = test[key];
});
cb(test);
return test;
} | [
"function",
"_suite",
"(",
"description",
",",
"cb",
")",
"{",
"var",
"test",
"=",
"new",
"this",
"(",
"description",
",",
"{",
"}",
")",
";",
"var",
"it",
"=",
"test",
".",
"_addAction",
";",
"_",
"(",
"[",
"\"suite\"",
",",
"\"test\"",
",",
"\"ti... | Creates a test with it.
@param {String} description the description of the test.
@param {Function} [cb] the function to invoke in the scope of the test. The it suite is passed as the first argument.
@return {it.Suite} the test. | [
"Creates",
"a",
"test",
"with",
"it",
"."
] | 0f8036ef6495fbef9dec1111e7913bec1af7301d | https://github.com/doug-martin/it/blob/0f8036ef6495fbef9dec1111e7913bec1af7301d/examples/requirejs/scripts/it.js#L6300-L6309 |
31,740 | doug-martin/it | examples/requirejs/scripts/it.js | run | function run(filter) {
var filter;
if (typeof window !== "undefined") {
try {
it.reporter("html", "it");
} catch (e) {
it.reporter("tap");
}
var paramStr = window.location.search.substring(1);
var params = {};
if (paramStr.length > 0) {
_(paramStr.split('&')).forEach(function (part) {
var p = part.split('=');
params[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
});
}
if (params.hasOwnProperty("filter")) {
filter = params.filter;
}
} else {
it.reporter("tap");
}
return interfaces.run(filter);
} | javascript | function run(filter) {
var filter;
if (typeof window !== "undefined") {
try {
it.reporter("html", "it");
} catch (e) {
it.reporter("tap");
}
var paramStr = window.location.search.substring(1);
var params = {};
if (paramStr.length > 0) {
_(paramStr.split('&')).forEach(function (part) {
var p = part.split('=');
params[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
});
}
if (params.hasOwnProperty("filter")) {
filter = params.filter;
}
} else {
it.reporter("tap");
}
return interfaces.run(filter);
} | [
"function",
"run",
"(",
"filter",
")",
"{",
"var",
"filter",
";",
"if",
"(",
"typeof",
"window",
"!==",
"\"undefined\"",
")",
"{",
"try",
"{",
"it",
".",
"reporter",
"(",
"\"html\"",
",",
"\"it\"",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"it",
... | Run all tests that are currently registered.
@return {comb.Promise} a promise that is resolved once all tests are done running. | [
"Run",
"all",
"tests",
"that",
"are",
"currently",
"registered",
"."
] | 0f8036ef6495fbef9dec1111e7913bec1af7301d | https://github.com/doug-martin/it/blob/0f8036ef6495fbef9dec1111e7913bec1af7301d/examples/requirejs/scripts/it.js#L8919-L8942 |
31,741 | Kronos-Integration/kronos-interceptor-object-data-processor-row | lib/recordCheck/data-check-number.js | parseNumberString | function parseNumberString(numberString, type, decimalSeparator) {
let result;
if (numberString !== undefined) {
if (typeof numberString === 'string') {
// The given value is a string
if (decimalSeparator === ',') {
numberString = numberString.replace(/\./g, '');
numberString = numberString.replace(/,/g, '\.');
} else {
numberString = numberString.replace(/,/g, '');
}
if (numberString.match(/[^0-9\.]/g)) {
// check if the string contains NO number values
result = 'NUMBER_NOT_VALID';
} else if ((numberString.match(/\./g) || []).length > 1) {
// proof that only one decimal separator exists
result = 'NUMBER_NOT_VALID';
} else {
if (type === 'float') {
result = parseFloat(numberString);
if (result === undefined) {
result = 'NOT_FLOAT';
}
} else if (type === 'integer') {
if (numberString.match(/\./g)) {
result = 'NOT_INTEGER';
} else {
result = parseInt(numberString);
if (result === undefined) {
result = 'NOT_INTEGER';
}
}
} else if (type === 'number') {
result = parseFloat(numberString);
if (result === undefined) {
result = parseInt(numberString);
result = 'NUMBER_NOT_VALID';
}
}
}
} else if (typeof numberString === 'number') {
result = numberString;
} else {
result = 'NUMBER_NOT_VALID';
}
}
return result;
} | javascript | function parseNumberString(numberString, type, decimalSeparator) {
let result;
if (numberString !== undefined) {
if (typeof numberString === 'string') {
// The given value is a string
if (decimalSeparator === ',') {
numberString = numberString.replace(/\./g, '');
numberString = numberString.replace(/,/g, '\.');
} else {
numberString = numberString.replace(/,/g, '');
}
if (numberString.match(/[^0-9\.]/g)) {
// check if the string contains NO number values
result = 'NUMBER_NOT_VALID';
} else if ((numberString.match(/\./g) || []).length > 1) {
// proof that only one decimal separator exists
result = 'NUMBER_NOT_VALID';
} else {
if (type === 'float') {
result = parseFloat(numberString);
if (result === undefined) {
result = 'NOT_FLOAT';
}
} else if (type === 'integer') {
if (numberString.match(/\./g)) {
result = 'NOT_INTEGER';
} else {
result = parseInt(numberString);
if (result === undefined) {
result = 'NOT_INTEGER';
}
}
} else if (type === 'number') {
result = parseFloat(numberString);
if (result === undefined) {
result = parseInt(numberString);
result = 'NUMBER_NOT_VALID';
}
}
}
} else if (typeof numberString === 'number') {
result = numberString;
} else {
result = 'NUMBER_NOT_VALID';
}
}
return result;
} | [
"function",
"parseNumberString",
"(",
"numberString",
",",
"type",
",",
"decimalSeparator",
")",
"{",
"let",
"result",
";",
"if",
"(",
"numberString",
"!==",
"undefined",
")",
"{",
"if",
"(",
"typeof",
"numberString",
"===",
"'string'",
")",
"{",
"// The given... | Parses a string and try to convert it in a valid number.
If the string does not match a valid number it will return the error message, else the parsed number.
@param numberString The string to be checked
@param type The expected type ["float", "integer", "number"]
@param decimalSeparator The used decimal separator. | [
"Parses",
"a",
"string",
"and",
"try",
"to",
"convert",
"it",
"in",
"a",
"valid",
"number",
".",
"If",
"the",
"string",
"does",
"not",
"match",
"a",
"valid",
"number",
"it",
"will",
"return",
"the",
"error",
"message",
"else",
"the",
"parsed",
"number",
... | 678a59b84dab4a9082377c90849a0d62d97a1ea4 | https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/recordCheck/data-check-number.js#L259-L309 |
31,742 | vimlet/vimlet-commons | src/browser/schemaValidator.js | validateModel | function validateModel(json, model) {
var schemaKeys = [];
for (var keyInSchema in model) {
schemaKeys.push(keyInSchema);
}
// Check if foreing keys are allowed.
if (!model[SCHEMAALLOWUNKNOWN]) {
// TODO ensure that null and false enter here.
checkUnknown(json, schemaKeys);
}
for (var schemaKeyI = 0; schemaKeyI < schemaKeys.length; schemaKeyI++) {
var node = null;
var schemaKey = schemaKeys[schemaKeyI];
if (json[schemaKey]) {
node = json[schemaKey];
}
if (!isReservedWord(schemaKey)) {
validateNode(node, model[schemaKey], schemaKey);
}
}
} | javascript | function validateModel(json, model) {
var schemaKeys = [];
for (var keyInSchema in model) {
schemaKeys.push(keyInSchema);
}
// Check if foreing keys are allowed.
if (!model[SCHEMAALLOWUNKNOWN]) {
// TODO ensure that null and false enter here.
checkUnknown(json, schemaKeys);
}
for (var schemaKeyI = 0; schemaKeyI < schemaKeys.length; schemaKeyI++) {
var node = null;
var schemaKey = schemaKeys[schemaKeyI];
if (json[schemaKey]) {
node = json[schemaKey];
}
if (!isReservedWord(schemaKey)) {
validateNode(node, model[schemaKey], schemaKey);
}
}
} | [
"function",
"validateModel",
"(",
"json",
",",
"model",
")",
"{",
"var",
"schemaKeys",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"keyInSchema",
"in",
"model",
")",
"{",
"schemaKeys",
".",
"push",
"(",
"keyInSchema",
")",
";",
"}",
"// Check if foreing keys ar... | Validate model. Mode is an object in the schema, it can be root node or an object inside it.
@param {[type]} json [description]
@param {[type]} model [description]
@return {[type]} [description] | [
"Validate",
"model",
".",
"Mode",
"is",
"an",
"object",
"in",
"the",
"schema",
"it",
"can",
"be",
"root",
"node",
"or",
"an",
"object",
"inside",
"it",
"."
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L68-L88 |
31,743 | vimlet/vimlet-commons | src/browser/schemaValidator.js | isRequired | function isRequired(schema) {
var required = false;
if (schema[SCHEMAREQUIRED]) {
try {
required = schema[SCHEMAREQUIRED];
if (typeof required != "boolean") {
throw new ValidationException(
schema[SCHEMAREQUIRED] + " cast exception."
);
}
} catch (e) {
throw new ValidationException(
schema[SCHEMAREQUIRED] + " cast exception."
);
}
}
return required;
} | javascript | function isRequired(schema) {
var required = false;
if (schema[SCHEMAREQUIRED]) {
try {
required = schema[SCHEMAREQUIRED];
if (typeof required != "boolean") {
throw new ValidationException(
schema[SCHEMAREQUIRED] + " cast exception."
);
}
} catch (e) {
throw new ValidationException(
schema[SCHEMAREQUIRED] + " cast exception."
);
}
}
return required;
} | [
"function",
"isRequired",
"(",
"schema",
")",
"{",
"var",
"required",
"=",
"false",
";",
"if",
"(",
"schema",
"[",
"SCHEMAREQUIRED",
"]",
")",
"{",
"try",
"{",
"required",
"=",
"schema",
"[",
"SCHEMAREQUIRED",
"]",
";",
"if",
"(",
"typeof",
"required",
... | Check if a key is required by schema
@param {[type]} schema [description]
@return {Boolean} [description] | [
"Check",
"if",
"a",
"key",
"is",
"required",
"by",
"schema"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L128-L145 |
31,744 | vimlet/vimlet-commons | src/browser/schemaValidator.js | checkUnknown | function checkUnknown(json, schemaKeys) {
var jsonKeys = [];
for (var k in json) {
if (schemaKeys.indexOf(k) === -1) {
throw new ValidationException(
"The key: " +
k +
" is not declared in the schema. Declare it or allow unknown keys."
);
}
}
} | javascript | function checkUnknown(json, schemaKeys) {
var jsonKeys = [];
for (var k in json) {
if (schemaKeys.indexOf(k) === -1) {
throw new ValidationException(
"The key: " +
k +
" is not declared in the schema. Declare it or allow unknown keys."
);
}
}
} | [
"function",
"checkUnknown",
"(",
"json",
",",
"schemaKeys",
")",
"{",
"var",
"jsonKeys",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"k",
"in",
"json",
")",
"{",
"if",
"(",
"schemaKeys",
".",
"indexOf",
"(",
"k",
")",
"===",
"-",
"1",
")",
"{",
"throw... | Check for unknown keys
@param {[type]} json [description]
@param {[type]} schemaKeys [description]
@return {[type]} [description] | [
"Check",
"for",
"unknown",
"keys"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L162-L173 |
31,745 | vimlet/vimlet-commons | src/browser/schemaValidator.js | validateObject | function validateObject(node, schema, key) {
if (typeof node == "object") {
try {
validateModel(node, schema[SCHEMADATA]);
} catch (e) {
throw new ValidationException(e.message + " at " + key + ".");
}
} else {
throw new ValidationException("Expected object for " + key);
}
} | javascript | function validateObject(node, schema, key) {
if (typeof node == "object") {
try {
validateModel(node, schema[SCHEMADATA]);
} catch (e) {
throw new ValidationException(e.message + " at " + key + ".");
}
} else {
throw new ValidationException("Expected object for " + key);
}
} | [
"function",
"validateObject",
"(",
"node",
",",
"schema",
",",
"key",
")",
"{",
"if",
"(",
"typeof",
"node",
"==",
"\"object\"",
")",
"{",
"try",
"{",
"validateModel",
"(",
"node",
",",
"schema",
"[",
"SCHEMADATA",
"]",
")",
";",
"}",
"catch",
"(",
"... | Validate an object node
@param {[type]} node [description]
@param {[type]} schema [description]
@param {[type]} key [description]
@return {[type]} [description] | [
"Validate",
"an",
"object",
"node"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L182-L192 |
31,746 | vimlet/vimlet-commons | src/browser/schemaValidator.js | validateArray | function validateArray(node, schema, key) {
if (Array.isArray(node)) {
if (schema[SCHEMALENGTH]) {
checkLength(node.length, schema, key);
}
for (var arrayI = 0; arrayI < node.length; arrayI++) {
try {
validateNode(node[arrayI], schema[SCHEMADATA], "");
} catch (e) {
throw new ValidationException(
e.message + key + " position " + arrayI
);
}
}
} else {
throw new ValidationException("Expected array for " + key);
}
} | javascript | function validateArray(node, schema, key) {
if (Array.isArray(node)) {
if (schema[SCHEMALENGTH]) {
checkLength(node.length, schema, key);
}
for (var arrayI = 0; arrayI < node.length; arrayI++) {
try {
validateNode(node[arrayI], schema[SCHEMADATA], "");
} catch (e) {
throw new ValidationException(
e.message + key + " position " + arrayI
);
}
}
} else {
throw new ValidationException("Expected array for " + key);
}
} | [
"function",
"validateArray",
"(",
"node",
",",
"schema",
",",
"key",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"node",
")",
")",
"{",
"if",
"(",
"schema",
"[",
"SCHEMALENGTH",
"]",
")",
"{",
"checkLength",
"(",
"node",
".",
"length",
",",
... | Validate an array node.
@param {[type]} node [description]
@param {[type]} schema [description]
@param {[type]} key [description]
@return {[type]} [description] | [
"Validate",
"an",
"array",
"node",
"."
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L201-L218 |
31,747 | vimlet/vimlet-commons | src/browser/schemaValidator.js | validateNumber | function validateNumber(node, schema, key) {
if (isNaN(parseFloat(node)) || !isFinite(node)) {
throw new ValidationException("Expected number for " + key);
}
if (schema[SCHEMAREGEX]) {
checkRegex(node, schema, key);
}
} | javascript | function validateNumber(node, schema, key) {
if (isNaN(parseFloat(node)) || !isFinite(node)) {
throw new ValidationException("Expected number for " + key);
}
if (schema[SCHEMAREGEX]) {
checkRegex(node, schema, key);
}
} | [
"function",
"validateNumber",
"(",
"node",
",",
"schema",
",",
"key",
")",
"{",
"if",
"(",
"isNaN",
"(",
"parseFloat",
"(",
"node",
")",
")",
"||",
"!",
"isFinite",
"(",
"node",
")",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"\"Expected numbe... | Validate a number node
@param {[type]} node [description]
@param {[type]} schema [description]
@param {[type]} key [description]
@return {[type]} [description] | [
"Validate",
"a",
"number",
"node"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L227-L234 |
31,748 | vimlet/vimlet-commons | src/browser/schemaValidator.js | checkLength | function checkLength(size, schema, key) {
//Check if it is an int
if (Number.isInteger(schema[SCHEMALENGTH])) {
if (size != schema[SCHEMALENGTH]) {
throw new ValidationException("Size of " + key + " is not correct.");
}
} else if (typeof schema[SCHEMALENGTH] == "string") {
if (
size < getMin(schema[SCHEMALENGTH], key) ||
size > getMax(schema[SCHEMALENGTH], key)
) {
throw new ValidationException("Size of " + key + " is not correct.");
}
} else {
throw new ValidationException(SCHEMALENGTH + " cast exception: " + key);
}
} | javascript | function checkLength(size, schema, key) {
//Check if it is an int
if (Number.isInteger(schema[SCHEMALENGTH])) {
if (size != schema[SCHEMALENGTH]) {
throw new ValidationException("Size of " + key + " is not correct.");
}
} else if (typeof schema[SCHEMALENGTH] == "string") {
if (
size < getMin(schema[SCHEMALENGTH], key) ||
size > getMax(schema[SCHEMALENGTH], key)
) {
throw new ValidationException("Size of " + key + " is not correct.");
}
} else {
throw new ValidationException(SCHEMALENGTH + " cast exception: " + key);
}
} | [
"function",
"checkLength",
"(",
"size",
",",
"schema",
",",
"key",
")",
"{",
"//Check if it is an int",
"if",
"(",
"Number",
".",
"isInteger",
"(",
"schema",
"[",
"SCHEMALENGTH",
"]",
")",
")",
"{",
"if",
"(",
"size",
"!=",
"schema",
"[",
"SCHEMALENGTH",
... | Check that an array fit its lenght
@param {[type]} size [description]
@param {[type]} schema [description]
@param {[type]} key [description]
@return {[type]} [description] | [
"Check",
"that",
"an",
"array",
"fit",
"its",
"lenght"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L264-L280 |
31,749 | vimlet/vimlet-commons | src/browser/schemaValidator.js | checkRegex | function checkRegex(node, schema, key) {
try {
schema[SCHEMAREGEX].test(node);
} catch (e) {
throw new ValidationException(key + " doesn't match its regex.");
}
} | javascript | function checkRegex(node, schema, key) {
try {
schema[SCHEMAREGEX].test(node);
} catch (e) {
throw new ValidationException(key + " doesn't match its regex.");
}
} | [
"function",
"checkRegex",
"(",
"node",
",",
"schema",
",",
"key",
")",
"{",
"try",
"{",
"schema",
"[",
"SCHEMAREGEX",
"]",
".",
"test",
"(",
"node",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"key",
"+",
... | Check regex.
@param {[type]} node [description]
@param {[type]} schema [description]
@param {[type]} key [description]
@return {[type]} [description] | [
"Check",
"regex",
"."
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/src/browser/schemaValidator.js#L329-L335 |
31,750 | kevinoid/promise-nodeify | benchmark/index.js | defineGlobals | function defineGlobals() {
Object.keys(NODEIFY_FUNCTIONS).forEach((nodeifyName) => {
global[nodeifyName] = NODEIFY_FUNCTIONS[nodeifyName].nodeify;
});
Object.keys(PROMISE_TYPES).forEach((promiseName) => {
global[promiseName] = PROMISE_TYPES[promiseName].Promise;
});
} | javascript | function defineGlobals() {
Object.keys(NODEIFY_FUNCTIONS).forEach((nodeifyName) => {
global[nodeifyName] = NODEIFY_FUNCTIONS[nodeifyName].nodeify;
});
Object.keys(PROMISE_TYPES).forEach((promiseName) => {
global[promiseName] = PROMISE_TYPES[promiseName].Promise;
});
} | [
"function",
"defineGlobals",
"(",
")",
"{",
"Object",
".",
"keys",
"(",
"NODEIFY_FUNCTIONS",
")",
".",
"forEach",
"(",
"(",
"nodeifyName",
")",
"=>",
"{",
"global",
"[",
"nodeifyName",
"]",
"=",
"NODEIFY_FUNCTIONS",
"[",
"nodeifyName",
"]",
".",
"nodeify",
... | Exposes nodeify functions and promise types as globals so that they can
be accessed in the benchmark code.
@private | [
"Exposes",
"nodeify",
"functions",
"and",
"promise",
"types",
"as",
"globals",
"so",
"that",
"they",
"can",
"be",
"accessed",
"in",
"the",
"benchmark",
"code",
"."
] | 1542cb7824c1b5e0e19e925dfb9650bfe8c7cdbd | https://github.com/kevinoid/promise-nodeify/blob/1542cb7824c1b5e0e19e925dfb9650bfe8c7cdbd/benchmark/index.js#L123-L131 |
31,751 | Rhinostone/gina | core/asset/js/plugin/dist/gina.min.js | Collection | function Collection(name) {
// retrieve collections state
collections = JSON.parse(storage.getItem(this['bucket']));
//console.log('collections ', (collections || null) );
if ( typeof(collections[name]) == 'undefined' ) {
collections[name] = [];
storage.setItem(this['bucket'], JSON.stringify(collections));
collections = JSON.parse(storage.getItem(this['bucket']));
}
entities[name] = { '_collection': name, '_bucket': this['bucket'] };
entities[name] = merge(entities[name], entityProto);
return entities[name]
} | javascript | function Collection(name) {
// retrieve collections state
collections = JSON.parse(storage.getItem(this['bucket']));
//console.log('collections ', (collections || null) );
if ( typeof(collections[name]) == 'undefined' ) {
collections[name] = [];
storage.setItem(this['bucket'], JSON.stringify(collections));
collections = JSON.parse(storage.getItem(this['bucket']));
}
entities[name] = { '_collection': name, '_bucket': this['bucket'] };
entities[name] = merge(entities[name], entityProto);
return entities[name]
} | [
"function",
"Collection",
"(",
"name",
")",
"{",
"// retrieve collections state",
"collections",
"=",
"JSON",
".",
"parse",
"(",
"storage",
".",
"getItem",
"(",
"this",
"[",
"'bucket'",
"]",
")",
")",
";",
"//console.log('collections ', (collections || null) );",
"i... | Create or Get Collection by name
@param {string} name - Collection name | [
"Create",
"or",
"Get",
"Collection",
"by",
"name"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/asset/js/plugin/dist/gina.min.js#L3992-L4006 |
31,752 | Rhinostone/gina | core/asset/js/plugin/dist/gina.min.js | collectionInsert | function collectionInsert(content) {
// TODO - add uuid
content['_id'] = uuid.v1();
content['_createdAt'] = new Date().format("isoDateTime");
content['_updatedAt'] = new Date().format("isoDateTime");
collections[ this['_collection'] ][ collections[ this['_collection'] ].length ] = content;
storage.setItem(this['_bucket'], JSON.stringify(collections));
} | javascript | function collectionInsert(content) {
// TODO - add uuid
content['_id'] = uuid.v1();
content['_createdAt'] = new Date().format("isoDateTime");
content['_updatedAt'] = new Date().format("isoDateTime");
collections[ this['_collection'] ][ collections[ this['_collection'] ].length ] = content;
storage.setItem(this['_bucket'], JSON.stringify(collections));
} | [
"function",
"collectionInsert",
"(",
"content",
")",
"{",
"// TODO - add uuid",
"content",
"[",
"'_id'",
"]",
"=",
"uuid",
".",
"v1",
"(",
")",
";",
"content",
"[",
"'_createdAt'",
"]",
"=",
"new",
"Date",
"(",
")",
".",
"format",
"(",
"\"isoDateTime\"",
... | Insert into collection
@param {object} content | [
"Insert",
"into",
"collection"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/asset/js/plugin/dist/gina.min.js#L4029-L4039 |
31,753 | Rhinostone/gina | core/asset/js/plugin/dist/gina.min.js | collectionFind | function collectionFind(filter, options) {
if (!filter) {
// TODO - limit of ten by
return collections[ this['_collection'] ]
}
if ( typeof(filter) !== 'object' ) { // == findAll
throw new Error('filter must be an object');
} else {
//console.log('search into ', this['_collection'], collections[ this['_collection'] ], collections);
var content = collections[ this['_collection'] ]
, condition = filter.count()
, i = 0
, found = []
, localeLowerCase = '';
for (var o in content) {
for (var f in filter) {
localeLowerCase = ( typeof(filter[f]) != 'boolean' ) ? filter[f].toLocaleLowerCase() : filter[f];
if ( filter[f] && keywords.indexOf(localeLowerCase) > -1 && localeLowerCase == 'not null' && typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] != 'null' && content[o][f] != 'undefined' ) {
if (found.indexOf(content[o][f]) < 0 ) {
found[i] = content[o][f];
++i
}
} else if ( typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] === filter[f] ) {
found[i] = content[o];
++i
}
}
}
}
return found
} | javascript | function collectionFind(filter, options) {
if (!filter) {
// TODO - limit of ten by
return collections[ this['_collection'] ]
}
if ( typeof(filter) !== 'object' ) { // == findAll
throw new Error('filter must be an object');
} else {
//console.log('search into ', this['_collection'], collections[ this['_collection'] ], collections);
var content = collections[ this['_collection'] ]
, condition = filter.count()
, i = 0
, found = []
, localeLowerCase = '';
for (var o in content) {
for (var f in filter) {
localeLowerCase = ( typeof(filter[f]) != 'boolean' ) ? filter[f].toLocaleLowerCase() : filter[f];
if ( filter[f] && keywords.indexOf(localeLowerCase) > -1 && localeLowerCase == 'not null' && typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] != 'null' && content[o][f] != 'undefined' ) {
if (found.indexOf(content[o][f]) < 0 ) {
found[i] = content[o][f];
++i
}
} else if ( typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] === filter[f] ) {
found[i] = content[o];
++i
}
}
}
}
return found
} | [
"function",
"collectionFind",
"(",
"filter",
",",
"options",
")",
"{",
"if",
"(",
"!",
"filter",
")",
"{",
"// TODO - limit of ten by",
"return",
"collections",
"[",
"this",
"[",
"'_collection'",
"]",
"]",
"}",
"if",
"(",
"typeof",
"(",
"filter",
")",
"!==... | Find from collection
// TODO - add options
@param {object} filter
@param {object} [options] - e.g.: limit
@return {array} result | [
"Find",
"from",
"collection"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/asset/js/plugin/dist/gina.min.js#L4051-L4085 |
31,754 | Rhinostone/gina | core/asset/js/plugin/dist/gina.min.js | collectionDelete | function collectionDelete(filter) {
if ( typeof(filter) !== 'object' ) {
throw new Error('filter must be an object');
} else {
var content = JSON.parse(JSON.stringify( collections[ this['_collection'] ] ))
//, condition = filter.count()
, i = 0
, found = [];
for (var o in content) {
for (var f in filter) {
if ( filter[f] && keywords.indexOf(filter[f].toLocaleLowerCase()) > -1 && filter[f].toLowerCase() == 'not null' && typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] != 'null' && content[o][f] != 'undefined' ) {
if (found.indexOf(content[o][f]) < 0 ) {
found[i] = content[o][f];
delete collections[ this['_collection'] ][o][f];
++i
}
} else if ( typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] === filter[f] ) {
found[i] = content[o];
collections[ this['_collection'] ].splice(o, 1);
++i
}
}
}
}
if (found.length > 0 ) {
storage.setItem(this['_bucket'], JSON.stringify(collections));
return true
}
return false
} | javascript | function collectionDelete(filter) {
if ( typeof(filter) !== 'object' ) {
throw new Error('filter must be an object');
} else {
var content = JSON.parse(JSON.stringify( collections[ this['_collection'] ] ))
//, condition = filter.count()
, i = 0
, found = [];
for (var o in content) {
for (var f in filter) {
if ( filter[f] && keywords.indexOf(filter[f].toLocaleLowerCase()) > -1 && filter[f].toLowerCase() == 'not null' && typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] != 'null' && content[o][f] != 'undefined' ) {
if (found.indexOf(content[o][f]) < 0 ) {
found[i] = content[o][f];
delete collections[ this['_collection'] ][o][f];
++i
}
} else if ( typeof(content[o][f]) != 'undefined' && typeof(content[o][f]) !== 'object' && content[o][f] === filter[f] ) {
found[i] = content[o];
collections[ this['_collection'] ].splice(o, 1);
++i
}
}
}
}
if (found.length > 0 ) {
storage.setItem(this['_bucket'], JSON.stringify(collections));
return true
}
return false
} | [
"function",
"collectionDelete",
"(",
"filter",
")",
"{",
"if",
"(",
"typeof",
"(",
"filter",
")",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'filter must be an object'",
")",
";",
"}",
"else",
"{",
"var",
"content",
"=",
"JSON",
".",
"pa... | Delete from collection
@param {object} filter
@return {array} result | [
"Delete",
"from",
"collection"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/asset/js/plugin/dist/gina.min.js#L4257-L4291 |
31,755 | Rhinostone/gina | core/asset/js/plugin/dist/gina.min.js | WS | function WS(opts) {
var forceBase64 = opts && opts.forceBase64;
if (forceBase64) {
this.supportsBinary = false;
}
this.perMessageDeflate = opts.perMessageDeflate;
this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
this.protocols = opts.protocols;
if (!this.usingBrowserWebSocket) {
WebSocket = NodeWebSocket;
}
Transport.call(this, opts);
} | javascript | function WS(opts) {
var forceBase64 = opts && opts.forceBase64;
if (forceBase64) {
this.supportsBinary = false;
}
this.perMessageDeflate = opts.perMessageDeflate;
this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
this.protocols = opts.protocols;
if (!this.usingBrowserWebSocket) {
WebSocket = NodeWebSocket;
}
Transport.call(this, opts);
} | [
"function",
"WS",
"(",
"opts",
")",
"{",
"var",
"forceBase64",
"=",
"opts",
"&&",
"opts",
".",
"forceBase64",
";",
"if",
"(",
"forceBase64",
")",
"{",
"this",
".",
"supportsBinary",
"=",
"false",
";",
"}",
"this",
".",
"perMessageDeflate",
"=",
"opts",
... | WebSocket transport constructor.
@api {Object} connection options
@api public | [
"WebSocket",
"transport",
"constructor",
"."
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/asset/js/plugin/dist/gina.min.js#L9489-L9501 |
31,756 | AlCalzone/shared-utils | build/typeguards/index.js | isArray | function isArray(it) {
if (Array.isArray != null)
return Array.isArray(it);
return Object.prototype.toString.call(it) === "[object Array]";
} | javascript | function isArray(it) {
if (Array.isArray != null)
return Array.isArray(it);
return Object.prototype.toString.call(it) === "[object Array]";
} | [
"function",
"isArray",
"(",
"it",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"!=",
"null",
")",
"return",
"Array",
".",
"isArray",
"(",
"it",
")",
";",
"return",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"it",
")",
"===",
"\... | Tests whether the given variable is really an Array
@param it The variable to test | [
"Tests",
"whether",
"the",
"given",
"variable",
"is",
"really",
"an",
"Array"
] | 9048e1f8793909fae7acb503984a4d8aadad4f3b | https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/typeguards/index.js#L20-L24 |
31,757 | Rhinostone/gina | core/gna.js | function(err) {
if (
process.argv[2] == '-s' && startWithGina
|| process.argv[2] == '--start' && startWithGina
//Avoid -h, -v ....
|| !startWithGina && isPath && process.argv.length > 3
) {
if (isPath && !startWithGina) {
console.log('You are trying to load gina by hand: just make sure that your env ['+env+'] matches the given path ['+ path +']');
} else if ( typeof(err.stack) != 'undefined' ) {
console.log('Gina could not determine which bundle to load: ' + err +' ['+env+']' + '\n' + err.stack);
} else {
console.log('Gina could not determine which bundle to load: ' + err +' ['+env+']');
}
process.exit(1);
}
} | javascript | function(err) {
if (
process.argv[2] == '-s' && startWithGina
|| process.argv[2] == '--start' && startWithGina
//Avoid -h, -v ....
|| !startWithGina && isPath && process.argv.length > 3
) {
if (isPath && !startWithGina) {
console.log('You are trying to load gina by hand: just make sure that your env ['+env+'] matches the given path ['+ path +']');
} else if ( typeof(err.stack) != 'undefined' ) {
console.log('Gina could not determine which bundle to load: ' + err +' ['+env+']' + '\n' + err.stack);
} else {
console.log('Gina could not determine which bundle to load: ' + err +' ['+env+']');
}
process.exit(1);
}
} | [
"function",
"(",
"err",
")",
"{",
"if",
"(",
"process",
".",
"argv",
"[",
"2",
"]",
"==",
"'-s'",
"&&",
"startWithGina",
"||",
"process",
".",
"argv",
"[",
"2",
"]",
"==",
"'--start'",
"&&",
"startWithGina",
"//Avoid -h, -v ....",
"||",
"!",
"startWithG... | Todo - load from env.json or locals or project.json ?? | [
"Todo",
"-",
"load",
"from",
"env",
".",
"json",
"or",
"locals",
"or",
"project",
".",
"json",
"??"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/gna.js#L228-L245 | |
31,758 | MarkGriffiths/badges | src/cli.js | render | async function render(template) {
const content = {
badges: await badges(argv.context),
usage: ''
}
if (argv.usage) {
content.usage = readFileSync(resolve(argv.usage))
}
const page = await remark().use(gap).use(squeeze).process(template(content))
process.stdout.write(page.toString())
} | javascript | async function render(template) {
const content = {
badges: await badges(argv.context),
usage: ''
}
if (argv.usage) {
content.usage = readFileSync(resolve(argv.usage))
}
const page = await remark().use(gap).use(squeeze).process(template(content))
process.stdout.write(page.toString())
} | [
"async",
"function",
"render",
"(",
"template",
")",
"{",
"const",
"content",
"=",
"{",
"badges",
":",
"await",
"badges",
"(",
"argv",
".",
"context",
")",
",",
"usage",
":",
"''",
"}",
"if",
"(",
"argv",
".",
"usage",
")",
"{",
"content",
".",
"us... | Render the page to stdout
@param {lodash} template A processed lodash template of the source | [
"Render",
"the",
"page",
"to",
"stdout"
] | 94fd02f96f50b0a6e3995c6acbd8f28497e43244 | https://github.com/MarkGriffiths/badges/blob/94fd02f96f50b0a6e3995c6acbd8f28497e43244/src/cli.js#L134-L146 |
31,759 | AlCalzone/shared-utils | build/async/index.js | promiseSequence | function promiseSequence(promiseFactories) {
return __awaiter(this, void 0, void 0, function* () {
const ret = [];
for (const f of promiseFactories) {
ret.push(yield f());
}
return ret;
});
} | javascript | function promiseSequence(promiseFactories) {
return __awaiter(this, void 0, void 0, function* () {
const ret = [];
for (const f of promiseFactories) {
ret.push(yield f());
}
return ret;
});
} | [
"function",
"promiseSequence",
"(",
"promiseFactories",
")",
"{",
"return",
"__awaiter",
"(",
"this",
",",
"void",
"0",
",",
"void",
"0",
",",
"function",
"*",
"(",
")",
"{",
"const",
"ret",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"f",
"of",
"promis... | Executes the given promise-returning functions in sequence
@param promiseFactories An array of promise-returning functions
@returns An array containing all return values of the executed promises | [
"Executes",
"the",
"given",
"promise",
"-",
"returning",
"functions",
"in",
"sequence"
] | 9048e1f8793909fae7acb503984a4d8aadad4f3b | https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/async/index.js#L54-L62 |
31,760 | Rhinostone/gina | core/utils/helpers/path.js | function(source, destination, i, callback, excluded) {
var isExcluded = false;
if ( typeof(excluded) != 'undefined' && excluded != undefined) {
var f, p = source.split('/');
f = p[p.length-1];
for (var r= 0; r<excluded.length; ++r) {
if ( typeof(excluded[r]) == 'object' ) {
if (excluded[r].test(f)) {
isExcluded = true
}
} else if (f === excluded[r]) {
isExcluded = true
}
}
}
if (!isExcluded) {
fs.lstat(destination, function(err, stats) {
//Means that nothing exists. Needs create.
if (err) {
startCopy(source, destination, i, function(err, i) {
//TODO - log error.
callback(err, source, i)
})
} else {
if ( stats.isDirectory() ) {
var str;
var path = '/'+ (str = source.split(/\//g))[str.length-1];
destination += path
}
fs.exists(destination, function(replaceFlag) {
if (replaceFlag) {
fs.unlink(destination, function(err) {
//TODO - log error.
startCopy(source, destination, i, function(err, i) {
callback(err, source, i)
})
})
} else {
startCopy(source, destination, i, function(err, i) {
//TODO - log error.
callback(err, source, i)
})
}
})
}//EO if (err)
})
} else {
callback(false, source, i)
}
var startCopy = function(source, destination, i, callback) {
copyFile(source, destination, i, function(err, i) {
if (err) {
console.error(err.stack)
}
callback(err, i)
})
}
} | javascript | function(source, destination, i, callback, excluded) {
var isExcluded = false;
if ( typeof(excluded) != 'undefined' && excluded != undefined) {
var f, p = source.split('/');
f = p[p.length-1];
for (var r= 0; r<excluded.length; ++r) {
if ( typeof(excluded[r]) == 'object' ) {
if (excluded[r].test(f)) {
isExcluded = true
}
} else if (f === excluded[r]) {
isExcluded = true
}
}
}
if (!isExcluded) {
fs.lstat(destination, function(err, stats) {
//Means that nothing exists. Needs create.
if (err) {
startCopy(source, destination, i, function(err, i) {
//TODO - log error.
callback(err, source, i)
})
} else {
if ( stats.isDirectory() ) {
var str;
var path = '/'+ (str = source.split(/\//g))[str.length-1];
destination += path
}
fs.exists(destination, function(replaceFlag) {
if (replaceFlag) {
fs.unlink(destination, function(err) {
//TODO - log error.
startCopy(source, destination, i, function(err, i) {
callback(err, source, i)
})
})
} else {
startCopy(source, destination, i, function(err, i) {
//TODO - log error.
callback(err, source, i)
})
}
})
}//EO if (err)
})
} else {
callback(false, source, i)
}
var startCopy = function(source, destination, i, callback) {
copyFile(source, destination, i, function(err, i) {
if (err) {
console.error(err.stack)
}
callback(err, i)
})
}
} | [
"function",
"(",
"source",
",",
"destination",
",",
"i",
",",
"callback",
",",
"excluded",
")",
"{",
"var",
"isExcluded",
"=",
"false",
";",
"if",
"(",
"typeof",
"(",
"excluded",
")",
"!=",
"'undefined'",
"&&",
"excluded",
"!=",
"undefined",
")",
"{",
... | Copy file to file
@param {string} source
@param {string} destination
@param {number} [i]
@param {number} [fileCount]
@callback callback
@param {bool|string} err | [
"Copy",
"file",
"to",
"file"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/helpers/path.js#L788-L853 | |
31,761 | AlCalzone/shared-utils | build/objects/index.js | entries | function entries(obj) {
return Object.keys(obj)
.map(key => [key, obj[key]]);
} | javascript | function entries(obj) {
return Object.keys(obj)
.map(key => [key, obj[key]]);
} | [
"function",
"entries",
"(",
"obj",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"map",
"(",
"key",
"=>",
"[",
"key",
",",
"obj",
"[",
"key",
"]",
"]",
")",
";",
"}"
] | Provides a polyfill for Object.entries | [
"Provides",
"a",
"polyfill",
"for",
"Object",
".",
"entries"
] | 9048e1f8793909fae7acb503984a4d8aadad4f3b | https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/objects/index.js#L5-L8 |
31,762 | AlCalzone/shared-utils | build/objects/index.js | filter | function filter(obj, predicate) {
return composeObject(entries(obj).filter(([key, value]) => predicate(value, key)));
} | javascript | function filter(obj, predicate) {
return composeObject(entries(obj).filter(([key, value]) => predicate(value, key)));
} | [
"function",
"filter",
"(",
"obj",
",",
"predicate",
")",
"{",
"return",
"composeObject",
"(",
"entries",
"(",
"obj",
")",
".",
"filter",
"(",
"(",
"[",
"key",
",",
"value",
"]",
")",
"=>",
"predicate",
"(",
"value",
",",
"key",
")",
")",
")",
";",
... | Returns a subset of an object, whose properties match the given predicate
@param obj The object whose properties should be filtered
@param predicate A predicate function which is applied to the object's properties | [
"Returns",
"a",
"subset",
"of",
"an",
"object",
"whose",
"properties",
"match",
"the",
"given",
"predicate"
] | 9048e1f8793909fae7acb503984a4d8aadad4f3b | https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/objects/index.js#L21-L23 |
31,763 | AlCalzone/shared-utils | build/objects/index.js | composeObject | function composeObject(properties) {
return properties.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
} | javascript | function composeObject(properties) {
return properties.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
} | [
"function",
"composeObject",
"(",
"properties",
")",
"{",
"return",
"properties",
".",
"reduce",
"(",
"(",
"acc",
",",
"[",
"key",
",",
"value",
"]",
")",
"=>",
"{",
"acc",
"[",
"key",
"]",
"=",
"value",
";",
"return",
"acc",
";",
"}",
",",
"{",
... | Combines multiple key value pairs into an object
@param properties The key value pairs to combine into an object | [
"Combines",
"multiple",
"key",
"value",
"pairs",
"into",
"an",
"object"
] | 9048e1f8793909fae7acb503984a4d8aadad4f3b | https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/objects/index.js#L29-L34 |
31,764 | dowjones/distribucache | lib/decorators/MarshallDecorator.js | unmarshallWrapper | function unmarshallWrapper (cb) {
return function (err, value) {
if (err) return cb(err);
var m = unmarshall(value);
cb(m.error, m.value);
};
} | javascript | function unmarshallWrapper (cb) {
return function (err, value) {
if (err) return cb(err);
var m = unmarshall(value);
cb(m.error, m.value);
};
} | [
"function",
"unmarshallWrapper",
"(",
"cb",
")",
"{",
"return",
"function",
"(",
"err",
",",
"value",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"var",
"m",
"=",
"unmarshall",
"(",
"value",
")",
";",
"cb",
"(",
"m",
".... | Helper for unmarshalling values
provided to a callback.
@param {Object} cb
@return {Function} (err, marshalledValue) | [
"Helper",
"for",
"unmarshalling",
"values",
"provided",
"to",
"a",
"callback",
"."
] | ad79caee277771a6e49ee4a98c4983480cd89945 | https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/MarshallDecorator.js#L85-L91 |
31,765 | redgeoff/quelle | scripts/filtered-stream-iterator.js | function (streamIterator, onItem) {
StreamIterator.apply(this, arguments);
this._streamIterator = streamIterator;
this._onItem = onItem;
// Pipe data so that we can filter it in FilteredStreamIterator
streamIterator.pipe(this);
} | javascript | function (streamIterator, onItem) {
StreamIterator.apply(this, arguments);
this._streamIterator = streamIterator;
this._onItem = onItem;
// Pipe data so that we can filter it in FilteredStreamIterator
streamIterator.pipe(this);
} | [
"function",
"(",
"streamIterator",
",",
"onItem",
")",
"{",
"StreamIterator",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"this",
".",
"_streamIterator",
"=",
"streamIterator",
";",
"this",
".",
"_onItem",
"=",
"onItem",
";",
"// Pipe data so that w... | onItem can be a promise factory or just a factory. It should return null when the item should be filtered out. | [
"onItem",
"can",
"be",
"a",
"promise",
"factory",
"or",
"just",
"a",
"factory",
".",
"It",
"should",
"return",
"null",
"when",
"the",
"item",
"should",
"be",
"filtered",
"out",
"."
] | f919d8fc59a1e3cb468f43dc322f799ab817ce3e | https://github.com/redgeoff/quelle/blob/f919d8fc59a1e3cb468f43dc322f799ab817ce3e/scripts/filtered-stream-iterator.js#L9-L17 | |
31,766 | Jack12816/greppy | lib/db/adapter/mongodb.js | function(callback)
{
// Connect to the given URI with the given options
self.mongo.MongoClient.connect(self.config.uri, defaultOpts, function(err, db) {
if (err) {
return callback && callback(err);
}
// Rewrite connection
self.connection = db;
callback && callback(null, db);
});
} | javascript | function(callback)
{
// Connect to the given URI with the given options
self.mongo.MongoClient.connect(self.config.uri, defaultOpts, function(err, db) {
if (err) {
return callback && callback(err);
}
// Rewrite connection
self.connection = db;
callback && callback(null, db);
});
} | [
"function",
"(",
"callback",
")",
"{",
"// Connect to the given URI with the given options",
"self",
".",
"mongo",
".",
"MongoClient",
".",
"connect",
"(",
"self",
".",
"config",
".",
"uri",
",",
"defaultOpts",
",",
"function",
"(",
"err",
",",
"db",
")",
"{",... | Setup the plain MongoDB connection | [
"Setup",
"the",
"plain",
"MongoDB",
"connection"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/db/adapter/mongodb.js#L64-L78 | |
31,767 | vimlet/vimlet-commons | docs/release/framework/vcomet/data/store/StoreRest.js | restXhr | function restXhr(store, url, eventName, sortRequest) {
// Set up request
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// TODO - Set range header parameter
xhr.setRequestHeader("Content-Type", "application/json");
// Callback
xhr.onload = function(e) {
// If operation has been completed - ready state 4
if (xhr.readyState === 4) {
// Response status successfully completed - status 200
if (xhr.status === 200) {
// Set up store
store._setUpData(xhr.response);
// Process store data filters and lists
vcomet.StoreMemory.processData(store);
// Set data as sorted
store.data.__sorted = sortRequest;
// Update store data items length
store.size = xhr.getResponseHeader("Total");
// Trigger user callback once data has been retrieved
vcomet.triggerCallback(eventName, store, store, [store.rootData]);
vcomet.createCallback("onSourceChanged", store, store, [store.rootData]);
}
}
};
// Execute request
store.onLoaded(function(){xhr.send()});
} | javascript | function restXhr(store, url, eventName, sortRequest) {
// Set up request
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
// TODO - Set range header parameter
xhr.setRequestHeader("Content-Type", "application/json");
// Callback
xhr.onload = function(e) {
// If operation has been completed - ready state 4
if (xhr.readyState === 4) {
// Response status successfully completed - status 200
if (xhr.status === 200) {
// Set up store
store._setUpData(xhr.response);
// Process store data filters and lists
vcomet.StoreMemory.processData(store);
// Set data as sorted
store.data.__sorted = sortRequest;
// Update store data items length
store.size = xhr.getResponseHeader("Total");
// Trigger user callback once data has been retrieved
vcomet.triggerCallback(eventName, store, store, [store.rootData]);
vcomet.createCallback("onSourceChanged", store, store, [store.rootData]);
}
}
};
// Execute request
store.onLoaded(function(){xhr.send()});
} | [
"function",
"restXhr",
"(",
"store",
",",
"url",
",",
"eventName",
",",
"sortRequest",
")",
"{",
"// Set up request",
"var",
"xhr",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"xhr",
".",
"open",
"(",
"\"GET\"",
",",
"url",
",",
"true",
")",
";",
"// ... | Set up and execute xhr request
@param {[type]} el [description]
@param {[type]} url [description]
@param {[type]} event [description]
@return {[type]} [description]
/*
@function restXhr
@description Set up and execute xhr request
@param {Object} store [Store element]
@param {String} url [Request url]
@param {String} eventName [Callback event name]
@param {Boolean} sortRequest [Whether or not data has been sorted] | [
"Set",
"up",
"and",
"execute",
"xhr",
"request"
] | c2d06dd64637e6729872ef82b40e99b7155b0dea | https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/docs/release/framework/vcomet/data/store/StoreRest.js#L311-L339 |
31,768 | Jack12816/greppy | bin/command/new.js | function(callback) {
var binary = binaries.bower;
binary.command = 'bower --allow-root install';
helper.runCommand(
binary, path,
'bower binary is not ready to use, fix this (npm install -g bower) and retry ' +
'installation of frontend dependencies manually'.grey,
callback
);
} | javascript | function(callback) {
var binary = binaries.bower;
binary.command = 'bower --allow-root install';
helper.runCommand(
binary, path,
'bower binary is not ready to use, fix this (npm install -g bower) and retry ' +
'installation of frontend dependencies manually'.grey,
callback
);
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"binary",
"=",
"binaries",
".",
"bower",
";",
"binary",
".",
"command",
"=",
"'bower --allow-root install'",
";",
"helper",
".",
"runCommand",
"(",
"binary",
",",
"path",
",",
"'bower binary is not ready to use, fix th... | Run bower to install all frontend dependencies | [
"Run",
"bower",
"to",
"install",
"all",
"frontend",
"dependencies"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/bin/command/new.js#L183-L194 | |
31,769 | Jack12816/greppy | bin/command/new.js | function(binaries, callback) {
helper.createProjectStructure(appPath, function(err) {
callback && callback(err, binaries);
});
} | javascript | function(binaries, callback) {
helper.createProjectStructure(appPath, function(err) {
callback && callback(err, binaries);
});
} | [
"function",
"(",
"binaries",
",",
"callback",
")",
"{",
"helper",
".",
"createProjectStructure",
"(",
"appPath",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"&&",
"callback",
"(",
"err",
",",
"binaries",
")",
";",
"}",
")",
";",
"}"
] | Create the project structure | [
"Create",
"the",
"project",
"structure"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/bin/command/new.js#L245-L249 | |
31,770 | Kronos-Integration/kronos-interceptor-object-data-processor-row | lib/recordCheck/data-check-date.js | function (fieldDefinition, fieldName) {
const fieldType = propertyHelper.getFieldType(fieldDefinition);
if (fieldType === 'date') {
// This field is a date field. Create the checks
return createDateChecks(fieldDefinition, fieldName);
}
} | javascript | function (fieldDefinition, fieldName) {
const fieldType = propertyHelper.getFieldType(fieldDefinition);
if (fieldType === 'date') {
// This field is a date field. Create the checks
return createDateChecks(fieldDefinition, fieldName);
}
} | [
"function",
"(",
"fieldDefinition",
",",
"fieldName",
")",
"{",
"const",
"fieldType",
"=",
"propertyHelper",
".",
"getFieldType",
"(",
"fieldDefinition",
")",
";",
"if",
"(",
"fieldType",
"===",
"'date'",
")",
"{",
"// This field is a date field. Create the checks",
... | Creates the date checks for a date field
@param fieldDefinition The field_definition schema
@param fieldName The name of the current field | [
"Creates",
"the",
"date",
"checks",
"for",
"a",
"date",
"field"
] | 678a59b84dab4a9082377c90849a0d62d97a1ea4 | https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/recordCheck/data-check-date.js#L15-L22 | |
31,771 | Rhinostone/gina | core/utils/lib/url/index.js | function(route) {
return (route != null && self.routes != null && typeof(self.routes[route]) != 'undefined' && self.routes[route] != null)
} | javascript | function(route) {
return (route != null && self.routes != null && typeof(self.routes[route]) != 'undefined' && self.routes[route] != null)
} | [
"function",
"(",
"route",
")",
"{",
"return",
"(",
"route",
"!=",
"null",
"&&",
"self",
".",
"routes",
"!=",
"null",
"&&",
"typeof",
"(",
"self",
".",
"routes",
"[",
"route",
"]",
")",
"!=",
"'undefined'",
"&&",
"self",
".",
"routes",
"[",
"route",
... | Check if the route name exists in routing. | [
"Check",
"if",
"the",
"route",
"name",
"exists",
"in",
"routing",
"."
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/url/index.js#L111-L113 | |
31,772 | Rhinostone/gina | core/utils/lib/url/index.js | function(route, args) {
var index;
// There is a requirement for this route.
if (typeof(self.routes[route].requirements) != 'undefined') {
// For each arguments.
for (index in args) {
// If there is a requirement.
if (self.routes[route].requirements[index] != null) {
// Check if it is fulfilled.
var regTest = (new RegExp(self.routes[route].requirements[index]));
// If not, replace data with :argument.
if (!regTest.test(args[index])) {
args[index] = ':' + index
}
}
}
}
return args
} | javascript | function(route, args) {
var index;
// There is a requirement for this route.
if (typeof(self.routes[route].requirements) != 'undefined') {
// For each arguments.
for (index in args) {
// If there is a requirement.
if (self.routes[route].requirements[index] != null) {
// Check if it is fulfilled.
var regTest = (new RegExp(self.routes[route].requirements[index]));
// If not, replace data with :argument.
if (!regTest.test(args[index])) {
args[index] = ':' + index
}
}
}
}
return args
} | [
"function",
"(",
"route",
",",
"args",
")",
"{",
"var",
"index",
";",
"// There is a requirement for this route.",
"if",
"(",
"typeof",
"(",
"self",
".",
"routes",
"[",
"route",
"]",
".",
"requirements",
")",
"!=",
"'undefined'",
")",
"{",
"// For each argumen... | Check if each arguments given has a requirement and check if it is fulfilled. | [
"Check",
"if",
"each",
"arguments",
"given",
"has",
"a",
"requirement",
"and",
"check",
"if",
"it",
"is",
"fulfilled",
"."
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/url/index.js#L116-L135 | |
31,773 | Kronos-Integration/kronos-interceptor-object-data-processor-row | lib/data-processor-row.js | getCheckInfo | function getCheckInfo(checkProperty, fieldName) {
let severity;
let value;
if (typeof checkProperty[fieldName] === 'object') {
severity = checkProperty[fieldName].severity;
value = checkProperty[fieldName].val;
} else {
severity = checkProperty.severity;
value = checkProperty[fieldName];
}
return {
val: value,
severity: severity
};
} | javascript | function getCheckInfo(checkProperty, fieldName) {
let severity;
let value;
if (typeof checkProperty[fieldName] === 'object') {
severity = checkProperty[fieldName].severity;
value = checkProperty[fieldName].val;
} else {
severity = checkProperty.severity;
value = checkProperty[fieldName];
}
return {
val: value,
severity: severity
};
} | [
"function",
"getCheckInfo",
"(",
"checkProperty",
",",
"fieldName",
")",
"{",
"let",
"severity",
";",
"let",
"value",
";",
"if",
"(",
"typeof",
"checkProperty",
"[",
"fieldName",
"]",
"===",
"'object'",
")",
"{",
"severity",
"=",
"checkProperty",
"[",
"field... | Extracts the type value and the severity of a given check name from the checkProperty
@param checkProperty The checkProperty as defined in the schema
@param fieldName The name of the field in the checkProperty
@return infoObject An object containing the boolean value and the severity | [
"Extracts",
"the",
"type",
"value",
"and",
"the",
"severity",
"of",
"a",
"given",
"check",
"name",
"from",
"the",
"checkProperty"
] | 678a59b84dab4a9082377c90849a0d62d97a1ea4 | https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/data-processor-row.js#L130-L145 |
31,774 | dowjones/distribucache | lib/decorators/PromiseDecorator.js | PromiseDecorator | function PromiseDecorator(cache) {
BaseDecorator.call(this, cache);
this.get = promisify(this.get.bind(this));
this.set = promisify(this.set.bind(this));
this.del = promisify(this.del.bind(this));
} | javascript | function PromiseDecorator(cache) {
BaseDecorator.call(this, cache);
this.get = promisify(this.get.bind(this));
this.set = promisify(this.set.bind(this));
this.del = promisify(this.del.bind(this));
} | [
"function",
"PromiseDecorator",
"(",
"cache",
")",
"{",
"BaseDecorator",
".",
"call",
"(",
"this",
",",
"cache",
")",
";",
"this",
".",
"get",
"=",
"promisify",
"(",
"this",
".",
"get",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"set",
"... | If no callbacks are provided to
get, set or del a Promise will
be returned. | [
"If",
"no",
"callbacks",
"are",
"provided",
"to",
"get",
"set",
"or",
"del",
"a",
"Promise",
"will",
"be",
"returned",
"."
] | ad79caee277771a6e49ee4a98c4983480cd89945 | https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/PromiseDecorator.js#L13-L18 |
31,775 | Rhinostone/gina | core/utils/lib/config.js | function(app, file, content, callback) {
var paths = {
root : content.paths.root,
utils : content.paths.utils
};
var gnaFolder = content.paths.root + '/.gna';
self.project = content.project;
self.paths = paths;
//Create path.
var createFolder = function(){
if ( fs.existsSync(gnaFolder) ) {
if ( !fs.existsSync(gnaFolder +'/'+ file) ) {
createContent(gnaFolder +'/'+ file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
} else { // already existing ... won't overwrite
callback(false)
}
} else {
fs.mkdir(gnaFolder, 0777, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Creating content.
createContent(gnaFolder+ '/' +file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
}
})
}
};
fs.exists(gnaFolder, function(exists){
if (!exists) {
createFolder()
} else {
// test if decalred path matches real path and overwrite if not the same
// in case you move your project
var filename = _(gnaFolder +'/'+ file, true);
var checksumFileOld = _(gnaFolder +'/'+ math.checkSumSync( JSON.stringify( require(filename) ), 'sha1'), true) + '.txt';
var checksumFile = _(gnaFolder +'/'+ math.checkSumSync( JSON.stringify(content), 'sha1'), true) + '.txt';
var verified = (checksumFileOld == checksumFile) ? true : false;
if ( !fs.existsSync(checksumFile) && fs.existsSync(filename) || !fs.existsSync(filename) || !verified) {
if ( fs.existsSync(filename) ) fs.unlinkSync(filename);
if ( fs.existsSync(checksumFile) ) fs.unlinkSync(checksumFile);
createContent(filename, gnaFolder, content, function(err){
fs.openSync(checksumFile, 'w');
setTimeout(function(){
callback(err)
}, 500)
})
} else if ( fs.existsSync(filename) ) {
var locals = require(gnaFolder +'/'+ file);
if (paths.utils != locals.paths.utils) {
new _(gnaFolder).rm( function(err){
if (err) {
console.warn('found error while trying to remove `.gna`\n' + err.stack)
}
//setTimeout(function(){
//console.debug('Done removing `gnaFolder` : '+ gnaFolder);
createFolder();
//}, 200);
})
} else {
callback(false)// nothing to do
}
} else {
callback(false)// nothing to do
}
}
})
} | javascript | function(app, file, content, callback) {
var paths = {
root : content.paths.root,
utils : content.paths.utils
};
var gnaFolder = content.paths.root + '/.gna';
self.project = content.project;
self.paths = paths;
//Create path.
var createFolder = function(){
if ( fs.existsSync(gnaFolder) ) {
if ( !fs.existsSync(gnaFolder +'/'+ file) ) {
createContent(gnaFolder +'/'+ file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
} else { // already existing ... won't overwrite
callback(false)
}
} else {
fs.mkdir(gnaFolder, 0777, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Creating content.
createContent(gnaFolder+ '/' +file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
}
})
}
};
fs.exists(gnaFolder, function(exists){
if (!exists) {
createFolder()
} else {
// test if decalred path matches real path and overwrite if not the same
// in case you move your project
var filename = _(gnaFolder +'/'+ file, true);
var checksumFileOld = _(gnaFolder +'/'+ math.checkSumSync( JSON.stringify( require(filename) ), 'sha1'), true) + '.txt';
var checksumFile = _(gnaFolder +'/'+ math.checkSumSync( JSON.stringify(content), 'sha1'), true) + '.txt';
var verified = (checksumFileOld == checksumFile) ? true : false;
if ( !fs.existsSync(checksumFile) && fs.existsSync(filename) || !fs.existsSync(filename) || !verified) {
if ( fs.existsSync(filename) ) fs.unlinkSync(filename);
if ( fs.existsSync(checksumFile) ) fs.unlinkSync(checksumFile);
createContent(filename, gnaFolder, content, function(err){
fs.openSync(checksumFile, 'w');
setTimeout(function(){
callback(err)
}, 500)
})
} else if ( fs.existsSync(filename) ) {
var locals = require(gnaFolder +'/'+ file);
if (paths.utils != locals.paths.utils) {
new _(gnaFolder).rm( function(err){
if (err) {
console.warn('found error while trying to remove `.gna`\n' + err.stack)
}
//setTimeout(function(){
//console.debug('Done removing `gnaFolder` : '+ gnaFolder);
createFolder();
//}, 200);
})
} else {
callback(false)// nothing to do
}
} else {
callback(false)// nothing to do
}
}
})
} | [
"function",
"(",
"app",
",",
"file",
",",
"content",
",",
"callback",
")",
"{",
"var",
"paths",
"=",
"{",
"root",
":",
"content",
".",
"paths",
".",
"root",
",",
"utils",
":",
"content",
".",
"paths",
".",
"utils",
"}",
";",
"var",
"gnaFolder",
"="... | Create a config file
@param {string} app - Targeted application
@param {string} file - File save
@param {string} content - Content fo the file to save
TOTO - Avoid systematics file override.
@private | [
"Create",
"a",
"config",
"file"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/config.js#L196-L286 | |
31,776 | Rhinostone/gina | core/utils/lib/config.js | function(){
if ( fs.existsSync(gnaFolder) ) {
if ( !fs.existsSync(gnaFolder +'/'+ file) ) {
createContent(gnaFolder +'/'+ file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
} else { // already existing ... won't overwrite
callback(false)
}
} else {
fs.mkdir(gnaFolder, 0777, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Creating content.
createContent(gnaFolder+ '/' +file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
}
})
}
} | javascript | function(){
if ( fs.existsSync(gnaFolder) ) {
if ( !fs.existsSync(gnaFolder +'/'+ file) ) {
createContent(gnaFolder +'/'+ file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
} else { // already existing ... won't overwrite
callback(false)
}
} else {
fs.mkdir(gnaFolder, 0777, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Creating content.
createContent(gnaFolder+ '/' +file, gnaFolder, content, function(err){
setTimeout(function(){
callback(err)
}, 500)
})
}
})
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"gnaFolder",
")",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"gnaFolder",
"+",
"'/'",
"+",
"file",
")",
")",
"{",
"createContent",
"(",
"gnaFolder",
"+",
"'/'",
"+",
... | Create path. | [
"Create",
"path",
"."
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/config.js#L209-L237 | |
31,777 | Rhinostone/gina | core/utils/lib/config.js | function(path, callback){
fs.exists(path, function(exists){
if (exists) {
fs.lstat(path, function(err, stats){
if (err) console.error(err.stack);
if ( stats.isSymbolicLink() ) fs.unlink(path, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Trigger.
onSymlinkRemoved(self.paths, function(err){
if (err) console.error(err.stack);
callback(false)
})
}
})
})
} else {
//log & ignore. This is not a real issue.
//logger.warn('gina', 'UTILS:CONFIG:WARN:1', 'Path not found: ' + path, __stack);
console.warn( 'Path not found: ' + path, __stack);
onSymlinkRemoved(self.paths, function(err){
//if (err) logger.error('gina', 'UTILS:CONFIG:ERR:9', err, __stack);
if (err) console.error(err.stack||err.message);
callback(false)
})
}
})
} | javascript | function(path, callback){
fs.exists(path, function(exists){
if (exists) {
fs.lstat(path, function(err, stats){
if (err) console.error(err.stack);
if ( stats.isSymbolicLink() ) fs.unlink(path, function(err){
if (err) {
console.error(err.stack);
callback(err)
} else {
//Trigger.
onSymlinkRemoved(self.paths, function(err){
if (err) console.error(err.stack);
callback(false)
})
}
})
})
} else {
//log & ignore. This is not a real issue.
//logger.warn('gina', 'UTILS:CONFIG:WARN:1', 'Path not found: ' + path, __stack);
console.warn( 'Path not found: ' + path, __stack);
onSymlinkRemoved(self.paths, function(err){
//if (err) logger.error('gina', 'UTILS:CONFIG:ERR:9', err, __stack);
if (err) console.error(err.stack||err.message);
callback(false)
})
}
})
} | [
"function",
"(",
"path",
",",
"callback",
")",
"{",
"fs",
".",
"exists",
"(",
"path",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"fs",
".",
"lstat",
"(",
"path",
",",
"function",
"(",
"err",
",",
"stats",
")",
"{",
... | Remove symbolic link
@param {string} path
@callback callback
@private | [
"Remove",
"symbolic",
"link"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/config.js#L297-L330 | |
31,778 | Rhinostone/gina | core/utils/lib/config.js | function(namespace, config) {
if ( typeof(config) == "undefined" )
var config = self.getSync(app);
if (config != null) {
var split = namespace.split('.'), k=0;
while (k<split.length) {
config = config[split[k++]]
}
return config
} else {
return null
}
} | javascript | function(namespace, config) {
if ( typeof(config) == "undefined" )
var config = self.getSync(app);
if (config != null) {
var split = namespace.split('.'), k=0;
while (k<split.length) {
config = config[split[k++]]
}
return config
} else {
return null
}
} | [
"function",
"(",
"namespace",
",",
"config",
")",
"{",
"if",
"(",
"typeof",
"(",
"config",
")",
"==",
"\"undefined\"",
")",
"var",
"config",
"=",
"self",
".",
"getSync",
"(",
"app",
")",
";",
"if",
"(",
"config",
"!=",
"null",
")",
"{",
"var",
"spl... | Get var value by namespace
@param {string} namespace
@param {object} [config ] - Config object
@return {*} value - Can be String or Array
@private | [
"Get",
"var",
"value",
"by",
"namespace"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/config.js#L406-L419 | |
31,779 | Rhinostone/gina | core/utils/lib/config.js | function(app, namespace, callback){
self.get(app, function(err, config){
if (err) {
//logger.error('gina', 'UTILS:CONFIG:ERR:4', err, __stack);
console.error(err.stack||err.message);
callback(err + 'Utils.Config.get(...)');
}
try {
callback( false, getVar('paths.' + namespace, config) );
} catch (err) {
var err = new Error('Config.getPath(app, cat, callback): cat not found');
callback(err)
}
})
} | javascript | function(app, namespace, callback){
self.get(app, function(err, config){
if (err) {
//logger.error('gina', 'UTILS:CONFIG:ERR:4', err, __stack);
console.error(err.stack||err.message);
callback(err + 'Utils.Config.get(...)');
}
try {
callback( false, getVar('paths.' + namespace, config) );
} catch (err) {
var err = new Error('Config.getPath(app, cat, callback): cat not found');
callback(err)
}
})
} | [
"function",
"(",
"app",
",",
"namespace",
",",
"callback",
")",
"{",
"self",
".",
"get",
"(",
"app",
",",
"function",
"(",
"err",
",",
"config",
")",
"{",
"if",
"(",
"err",
")",
"{",
"//logger.error('gina', 'UTILS:CONFIG:ERR:4', err, __stack);",
"console",
"... | Get path by app & namespance
@param {string} app
@param {string} namespace
@callback callback
@param {string} err
@param {string} path
@private | [
"Get",
"path",
"by",
"app",
"&",
"namespance"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/config.js#L433-L450 | |
31,780 | Rhinostone/gina | core/utils/lib/cmd/gina-add-bundle.js | function(callback) {
var data = JSON.parse(JSON.stringify(self.projectData, null, 4));
data.bundles[self.bundle] = {
"comment" : "Your comment goes here.",
"tag" : "001",
"src" : "src/" + bundle,
"release" : {
"version" : "0.0.1",
"link" : "bundles/"+ bundle
}
};
try {
fs.writeFileSync(self.project, JSON.stringify(data, null, 4));
callback(false, data)
} catch (err) {
callback(err, undefined)
}
} | javascript | function(callback) {
var data = JSON.parse(JSON.stringify(self.projectData, null, 4));
data.bundles[self.bundle] = {
"comment" : "Your comment goes here.",
"tag" : "001",
"src" : "src/" + bundle,
"release" : {
"version" : "0.0.1",
"link" : "bundles/"+ bundle
}
};
try {
fs.writeFileSync(self.project, JSON.stringify(data, null, 4));
callback(false, data)
} catch (err) {
callback(err, undefined)
}
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"data",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"self",
".",
"projectData",
",",
"null",
",",
"4",
")",
")",
";",
"data",
".",
"bundles",
"[",
"self",
".",
"bundle",
"]",
"=",
"... | Save project.json
@param {string} projectPath
@param {object} content - Project file content to save | [
"Save",
"project",
".",
"json"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/cmd/gina-add-bundle.js#L113-L130 | |
31,781 | majorleaguesoccer/respectify | lib/respectify.js | validVersion | function validVersion(version, spec) {
// Normalize route versions
var test = spec.versions || [spec.version]
// Check for direct version match
if (~test.indexOf(version)) {
return true
}
// Use semver and attempt to match on supplied version
return !!test.filter(function(v) {
return semver.satisfies(v, version)
}).length
} | javascript | function validVersion(version, spec) {
// Normalize route versions
var test = spec.versions || [spec.version]
// Check for direct version match
if (~test.indexOf(version)) {
return true
}
// Use semver and attempt to match on supplied version
return !!test.filter(function(v) {
return semver.satisfies(v, version)
}).length
} | [
"function",
"validVersion",
"(",
"version",
",",
"spec",
")",
"{",
"// Normalize route versions",
"var",
"test",
"=",
"spec",
".",
"versions",
"||",
"[",
"spec",
".",
"version",
"]",
"// Check for direct version match",
"if",
"(",
"~",
"test",
".",
"indexOf",
... | Check if a version is valid for a given route spec
@param {String} version
@param {Object} route specification
@return {Boolean} valid
@api private | [
"Check",
"if",
"a",
"version",
"is",
"valid",
"for",
"a",
"given",
"route",
"spec"
] | d19bac22526c1719c954864b74944e8a2707be15 | https://github.com/majorleaguesoccer/respectify/blob/d19bac22526c1719c954864b74944e8a2707be15/lib/respectify.js#L37-L50 |
31,782 | majorleaguesoccer/respectify | lib/respectify.js | errorWrap | function errorWrap(err, param, sent) {
if (err instanceof restify.RestError) {
err.body.parameter = param
err.body.received = sent
}
return err
} | javascript | function errorWrap(err, param, sent) {
if (err instanceof restify.RestError) {
err.body.parameter = param
err.body.received = sent
}
return err
} | [
"function",
"errorWrap",
"(",
"err",
",",
"param",
",",
"sent",
")",
"{",
"if",
"(",
"err",
"instanceof",
"restify",
".",
"RestError",
")",
"{",
"err",
".",
"body",
".",
"parameter",
"=",
"param",
"err",
".",
"body",
".",
"received",
"=",
"sent",
"}"... | Add extra information to a restify error instance
@param {Error} restify RestError
@param {Object} parameter spec
@param {Any} value received | [
"Add",
"extra",
"information",
"to",
"a",
"restify",
"error",
"instance"
] | d19bac22526c1719c954864b74944e8a2707be15 | https://github.com/majorleaguesoccer/respectify/blob/d19bac22526c1719c954864b74944e8a2707be15/lib/respectify.js#L60-L66 |
31,783 | majorleaguesoccer/respectify | lib/respectify.js | arrayDefaults | function arrayDefaults(arr, values) {
values.forEach(function(x) {
if (!~arr.indexOf(x)) arr.push(x)
})
} | javascript | function arrayDefaults(arr, values) {
values.forEach(function(x) {
if (!~arr.indexOf(x)) arr.push(x)
})
} | [
"function",
"arrayDefaults",
"(",
"arr",
",",
"values",
")",
"{",
"values",
".",
"forEach",
"(",
"function",
"(",
"x",
")",
"{",
"if",
"(",
"!",
"~",
"arr",
".",
"indexOf",
"(",
"x",
")",
")",
"arr",
".",
"push",
"(",
"x",
")",
"}",
")",
"}"
] | Array defaults helper, ensure all elements within
`default` exist in the `arr` input
@param {Array} source array
@param {Array} default values to check
@api private | [
"Array",
"defaults",
"helper",
"ensure",
"all",
"elements",
"within",
"default",
"exist",
"in",
"the",
"arr",
"input"
] | d19bac22526c1719c954864b74944e8a2707be15 | https://github.com/majorleaguesoccer/respectify/blob/d19bac22526c1719c954864b74944e8a2707be15/lib/respectify.js#L77-L81 |
31,784 | majorleaguesoccer/respectify | lib/respectify.js | getParams | function getParams(obj) {
var defs = []
for (var name in obj) {
var data = obj[name]
, fromPath = ~required.indexOf(name)
// If string, assume a single data type
if (typeof data === 'string') {
data = data.split(',')
}
// If array, assume array of data types
if (Array.isArray(data)) {
data = obj[name] = {
dataTypes: data
}
}
// Check for singular spelling
if (data.dataType) {
data.dataTypes = data.dataType
}
// Ensure datatypes is an array
if (!Array.isArray(data.dataTypes)) {
data.dataTypes = [data.dataTypes]
}
// Normalize data types
var types = _.uniq((data.dataTypes || []).map(function(type) {
return type && type.toLowerCase()
}))
// Parameter type / source
var paramType = 'path'
if (!fromPath) {
// If not a URI param, check to see if a `post` source
// was specified, otherwise default to `querystring`
paramType = (data.paramType && data.paramType === 'post')
? 'post'
: 'querystring'
}
// Parameter spec information
var param = {
name: name
, required: fromPath ? true : !!data.required
, paramType: paramType
, dataTypes: types
}
// If we have a number, check if a min / max value was set
if (~types.indexOf('number')) {
if (_.has(data, 'min')) param.min = +data.min;
if (_.has(data, 'max')) param.max = +data.max;
}
// Add in any extra information defined from options
if (self.options.paramProperties) {
self.options.paramProperties.forEach(function(prop) {
if (_.has(data, prop)) {
param[prop] = data[prop]
}
})
}
// If we have an object type, check for sub-schemas
if (~types.indexOf('object') && data.params) {
param.params = getParams(data.params)
}
defs.push(param)
}
return defs
} | javascript | function getParams(obj) {
var defs = []
for (var name in obj) {
var data = obj[name]
, fromPath = ~required.indexOf(name)
// If string, assume a single data type
if (typeof data === 'string') {
data = data.split(',')
}
// If array, assume array of data types
if (Array.isArray(data)) {
data = obj[name] = {
dataTypes: data
}
}
// Check for singular spelling
if (data.dataType) {
data.dataTypes = data.dataType
}
// Ensure datatypes is an array
if (!Array.isArray(data.dataTypes)) {
data.dataTypes = [data.dataTypes]
}
// Normalize data types
var types = _.uniq((data.dataTypes || []).map(function(type) {
return type && type.toLowerCase()
}))
// Parameter type / source
var paramType = 'path'
if (!fromPath) {
// If not a URI param, check to see if a `post` source
// was specified, otherwise default to `querystring`
paramType = (data.paramType && data.paramType === 'post')
? 'post'
: 'querystring'
}
// Parameter spec information
var param = {
name: name
, required: fromPath ? true : !!data.required
, paramType: paramType
, dataTypes: types
}
// If we have a number, check if a min / max value was set
if (~types.indexOf('number')) {
if (_.has(data, 'min')) param.min = +data.min;
if (_.has(data, 'max')) param.max = +data.max;
}
// Add in any extra information defined from options
if (self.options.paramProperties) {
self.options.paramProperties.forEach(function(prop) {
if (_.has(data, prop)) {
param[prop] = data[prop]
}
})
}
// If we have an object type, check for sub-schemas
if (~types.indexOf('object') && data.params) {
param.params = getParams(data.params)
}
defs.push(param)
}
return defs
} | [
"function",
"getParams",
"(",
"obj",
")",
"{",
"var",
"defs",
"=",
"[",
"]",
"for",
"(",
"var",
"name",
"in",
"obj",
")",
"{",
"var",
"data",
"=",
"obj",
"[",
"name",
"]",
",",
"fromPath",
"=",
"~",
"required",
".",
"indexOf",
"(",
"name",
")",
... | Iterate through all defined parameter definitions | [
"Iterate",
"through",
"all",
"defined",
"parameter",
"definitions"
] | d19bac22526c1719c954864b74944e8a2707be15 | https://github.com/majorleaguesoccer/respectify/blob/d19bac22526c1719c954864b74944e8a2707be15/lib/respectify.js#L745-L820 |
31,785 | artdecocode/spawncommand | build/index.js | spawnCommand | function spawnCommand(command, args, options) {
if (!command) throw new Error('Please specify a command to spawn.')
const proc = /** @type {!_spawncommand.ChildProcessWithPromise} */ (spawn(command, args, options))
const promise = getPromise(proc)
proc.promise = promise
/** @suppress {checkTypes} */
proc.spawnCommand = proc['spawnargs'].join(' ')
return proc
} | javascript | function spawnCommand(command, args, options) {
if (!command) throw new Error('Please specify a command to spawn.')
const proc = /** @type {!_spawncommand.ChildProcessWithPromise} */ (spawn(command, args, options))
const promise = getPromise(proc)
proc.promise = promise
/** @suppress {checkTypes} */
proc.spawnCommand = proc['spawnargs'].join(' ')
return proc
} | [
"function",
"spawnCommand",
"(",
"command",
",",
"args",
",",
"options",
")",
"{",
"if",
"(",
"!",
"command",
")",
"throw",
"new",
"Error",
"(",
"'Please specify a command to spawn.'",
")",
"const",
"proc",
"=",
"/** @type {!_spawncommand.ChildProcessWithPromise} */",... | Spawns a new process using the `command` and returns an instance of a ChildProcess, extended to have a `promise` property which is resolved when the process exits. The resolved value is an object with `stdout`, `stderr` and `code` properties.
@param {string} command The command to run.
@param {!Array<string>} [args] List of string arguments.
@param {!child_process.SpawnOptions} [options] Options used to spawn. | [
"Spawns",
"a",
"new",
"process",
"using",
"the",
"command",
"and",
"returns",
"an",
"instance",
"of",
"a",
"ChildProcess",
"extended",
"to",
"have",
"a",
"promise",
"property",
"which",
"is",
"resolved",
"when",
"the",
"process",
"exits",
".",
"The",
"resolv... | baf242e35b8214230aee69a6f28288cb303be04b | https://github.com/artdecocode/spawncommand/blob/baf242e35b8214230aee69a6f28288cb303be04b/build/index.js#L32-L41 |
31,786 | artdecocode/spawncommand | build/index.js | fork | function fork(mod, args, options) {
if (!mod) throw new Error('Please specify a module to fork')
const proc = /** @type {!_spawncommand.ChildProcessWithPromise} */ (forkCp(mod, args, options))
const promise = getPromise(proc)
proc.promise = promise
/** @suppress {checkTypes} */
proc.spawnCommand = proc['spawnargs'].join(' ')
return proc
} | javascript | function fork(mod, args, options) {
if (!mod) throw new Error('Please specify a module to fork')
const proc = /** @type {!_spawncommand.ChildProcessWithPromise} */ (forkCp(mod, args, options))
const promise = getPromise(proc)
proc.promise = promise
/** @suppress {checkTypes} */
proc.spawnCommand = proc['spawnargs'].join(' ')
return proc
} | [
"function",
"fork",
"(",
"mod",
",",
"args",
",",
"options",
")",
"{",
"if",
"(",
"!",
"mod",
")",
"throw",
"new",
"Error",
"(",
"'Please specify a module to fork'",
")",
"const",
"proc",
"=",
"/** @type {!_spawncommand.ChildProcessWithPromise} */",
"(",
"forkCp",... | Forks a process and assign a `promise` property to it, resolved with `stderr`, `stdout` and `code` properties on exit.
@param {string} mod The module to run in the child.
@param {!Array<string>} [args] List of string arguments.
@param {!child_process.ForkOptions} [options] Options to fork the process with. | [
"Forks",
"a",
"process",
"and",
"assign",
"a",
"promise",
"property",
"to",
"it",
"resolved",
"with",
"stderr",
"stdout",
"and",
"code",
"properties",
"on",
"exit",
"."
] | baf242e35b8214230aee69a6f28288cb303be04b | https://github.com/artdecocode/spawncommand/blob/baf242e35b8214230aee69a6f28288cb303be04b/build/index.js#L49-L58 |
31,787 | invisible-tech/mongoose-extras | helpers/mongooseHelper.js | isSameObjectId | function isSameObjectId(a, b) {
assert(isObjectId(a), '1st argument is not an ObjectId')
assert(isObjectId(b), '2nd argument is not an ObjectId')
return a.toString() === b.toString()
} | javascript | function isSameObjectId(a, b) {
assert(isObjectId(a), '1st argument is not an ObjectId')
assert(isObjectId(b), '2nd argument is not an ObjectId')
return a.toString() === b.toString()
} | [
"function",
"isSameObjectId",
"(",
"a",
",",
"b",
")",
"{",
"assert",
"(",
"isObjectId",
"(",
"a",
")",
",",
"'1st argument is not an ObjectId'",
")",
"assert",
"(",
"isObjectId",
"(",
"b",
")",
",",
"'2nd argument is not an ObjectId'",
")",
"return",
"a",
"."... | A boolean representing if the objects given have the same Mongoose Object Id.
Throws if the objects given aren't a Mongoose Object Id.
@method isSameObjectId
@param {ObjectId} a - A Mongoose Object Id (see mongoose.Types.ObjectId)
@param {ObjectId} b - A Mongoose Object Id (see mongoose.Types.ObjectId)
@return {Boolean} - A boolean representing if the objects given have the same Mongoose Object Id.
@throws {Error} - Throws if the inputs are not Object Ids (mongoose.Types.ObjectId) | [
"A",
"boolean",
"representing",
"if",
"the",
"objects",
"given",
"have",
"the",
"same",
"Mongoose",
"Object",
"Id",
".",
"Throws",
"if",
"the",
"objects",
"given",
"aren",
"t",
"a",
"Mongoose",
"Object",
"Id",
"."
] | 9b572554a292ead1644b0afa3fc5a5b382d5dec9 | https://github.com/invisible-tech/mongoose-extras/blob/9b572554a292ead1644b0afa3fc5a5b382d5dec9/helpers/mongooseHelper.js#L72-L76 |
31,788 | invisible-tech/mongoose-extras | helpers/mongooseHelper.js | assertInstance | function assertInstance(instance, model) {
const modelName = get('modelName')(model)
try {
mongoose.model(modelName)
} catch (err) {
throw Error(`no such model as ${modelName}`)
}
const errMsg = stripIndents`
Expected an instance of ${modelName} but got this:
${JSON.stringify(instance, undefined, 2)}`
assert(instance instanceof model, errMsg)
} | javascript | function assertInstance(instance, model) {
const modelName = get('modelName')(model)
try {
mongoose.model(modelName)
} catch (err) {
throw Error(`no such model as ${modelName}`)
}
const errMsg = stripIndents`
Expected an instance of ${modelName} but got this:
${JSON.stringify(instance, undefined, 2)}`
assert(instance instanceof model, errMsg)
} | [
"function",
"assertInstance",
"(",
"instance",
",",
"model",
")",
"{",
"const",
"modelName",
"=",
"get",
"(",
"'modelName'",
")",
"(",
"model",
")",
"try",
"{",
"mongoose",
".",
"model",
"(",
"modelName",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"throw... | Throws if a given object is not an instance of given model.
@method assertInstance
@param {Mixed} instance - Could be anything, but most likely a mongoose Model
@param {Model} model - The Model from Mongoose (see mongoose.model('User'))
@return {undefined}
@throws {Error} - Throws if input is not an instance of model, or if model doesn't exist | [
"Throws",
"if",
"a",
"given",
"object",
"is",
"not",
"an",
"instance",
"of",
"given",
"model",
"."
] | 9b572554a292ead1644b0afa3fc5a5b382d5dec9 | https://github.com/invisible-tech/mongoose-extras/blob/9b572554a292ead1644b0afa3fc5a5b382d5dec9/helpers/mongooseHelper.js#L86-L97 |
31,789 | dowjones/distribucache | lib/decorators/ExpiresDecorator.js | ExpiresDecorator | function ExpiresDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
expiresIn: joi.number().integer().min(0).default(Infinity),
staleIn: joi.number().integer().min(0).default(Infinity)
}));
this.on('set:after', this.setCreatedAt.bind(this));
this._store = this._getStore();
} | javascript | function ExpiresDecorator(cache, config) {
BaseDecorator.call(this, cache, config, joi.object().keys({
expiresIn: joi.number().integer().min(0).default(Infinity),
staleIn: joi.number().integer().min(0).default(Infinity)
}));
this.on('set:after', this.setCreatedAt.bind(this));
this._store = this._getStore();
} | [
"function",
"ExpiresDecorator",
"(",
"cache",
",",
"config",
")",
"{",
"BaseDecorator",
".",
"call",
"(",
"this",
",",
"cache",
",",
"config",
",",
"joi",
".",
"object",
"(",
")",
".",
"keys",
"(",
"{",
"expiresIn",
":",
"joi",
".",
"number",
"(",
")... | Expire Redis-backed cache
@param {Cache} cache
@param {Object} [config]
@param {String} [config.expiresIn] in ms
@param {String} [config.staleIn] in ms | [
"Expire",
"Redis",
"-",
"backed",
"cache"
] | ad79caee277771a6e49ee4a98c4983480cd89945 | https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/ExpiresDecorator.js#L18-L25 |
31,790 | Jack12816/greppy | lib/helper/service/json-wsp/client.js | function(err) {
var message = 'Error occured while performing a JSON-WSP request. ' +
err.message + '\n' +
JSON.stringify({
options : curOpts
}, null, ' ').yellow;
logger.error(message);
} | javascript | function(err) {
var message = 'Error occured while performing a JSON-WSP request. ' +
err.message + '\n' +
JSON.stringify({
options : curOpts
}, null, ' ').yellow;
logger.error(message);
} | [
"function",
"(",
"err",
")",
"{",
"var",
"message",
"=",
"'Error occured while performing a JSON-WSP request. '",
"+",
"err",
".",
"message",
"+",
"'\\n'",
"+",
"JSON",
".",
"stringify",
"(",
"{",
"options",
":",
"curOpts",
"}",
",",
"null",
",",
"' '",
")"... | Default error handler | [
"Default",
"error",
"handler"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/helper/service/json-wsp/client.js#L140-L149 | |
31,791 | angrykoala/xejs | main.js | promesify | function promesify(err, res) {
if (!err) return Promise.resolve(res);
else return Promise.reject(err);
} | javascript | function promesify(err, res) {
if (!err) return Promise.resolve(res);
else return Promise.reject(err);
} | [
"function",
"promesify",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"!",
"err",
")",
"return",
"Promise",
".",
"resolve",
"(",
"res",
")",
";",
"else",
"return",
"Promise",
".",
"reject",
"(",
"err",
")",
";",
"}"
] | Private function to return a promise if no done is found | [
"Private",
"function",
"to",
"return",
"a",
"promise",
"if",
"no",
"done",
"is",
"found"
] | 9c5ec8d880d416d39b4e51c17b88694fb3bae9ce | https://github.com/angrykoala/xejs/blob/9c5ec8d880d416d39b4e51c17b88694fb3bae9ce/main.js#L65-L68 |
31,792 | smartholdem/sth-js | lib/ecsignature.js | ECSignature | function ECSignature (r, s) {
typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
/** @type {BigInteger} */ this.r = r
/** @type {BigInteger} */ this.s = s
} | javascript | function ECSignature (r, s) {
typeforce(types.tuple(types.BigInt, types.BigInt), arguments)
/** @type {BigInteger} */ this.r = r
/** @type {BigInteger} */ this.s = s
} | [
"function",
"ECSignature",
"(",
"r",
",",
"s",
")",
"{",
"typeforce",
"(",
"types",
".",
"tuple",
"(",
"types",
".",
"BigInt",
",",
"types",
".",
"BigInt",
")",
",",
"arguments",
")",
"/** @type {BigInteger} */",
"this",
".",
"r",
"=",
"r",
"/** @type {B... | Creates a new ECSignature.
@constructor
@param {BigInteger} r
@param {BigInteger} s | [
"Creates",
"a",
"new",
"ECSignature",
"."
] | c65cb4fb97dd691d01d7089ec812b749948882f9 | https://github.com/smartholdem/sth-js/blob/c65cb4fb97dd691d01d7089ec812b749948882f9/lib/ecsignature.js#L14-L19 |
31,793 | stormpath/stormpath-node-config | lib/ConfigLoader.js | ConfigLoader | function ConfigLoader(strategies, logger) {
this.strategies = [];
if (logger) {
if (typeof logger.debug !== 'function') {
throw new Error('Provided logger is required to have method debug().');
}
this.logger = logger;
}
if (strategies && !(strategies instanceof Array)) {
throw new Error('Argument \'strategies\' must be an array.');
}
for (var i = 0; i < strategies.length; i++) {
this.add(strategies[i]);
}
} | javascript | function ConfigLoader(strategies, logger) {
this.strategies = [];
if (logger) {
if (typeof logger.debug !== 'function') {
throw new Error('Provided logger is required to have method debug().');
}
this.logger = logger;
}
if (strategies && !(strategies instanceof Array)) {
throw new Error('Argument \'strategies\' must be an array.');
}
for (var i = 0; i < strategies.length; i++) {
this.add(strategies[i]);
}
} | [
"function",
"ConfigLoader",
"(",
"strategies",
",",
"logger",
")",
"{",
"this",
".",
"strategies",
"=",
"[",
"]",
";",
"if",
"(",
"logger",
")",
"{",
"if",
"(",
"typeof",
"logger",
".",
"debug",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
... | ConfigLoader
Represents a configuration loader that loads a configuration through a list of strategies.
@constructor | [
"ConfigLoader",
"Represents",
"a",
"configuration",
"loader",
"that",
"loads",
"a",
"configuration",
"through",
"a",
"list",
"of",
"strategies",
"."
] | c9983cea3afada94d122aac395b1472e7d99b854 | https://github.com/stormpath/stormpath-node-config/blob/c9983cea3afada94d122aac395b1472e7d99b854/lib/ConfigLoader.js#L14-L31 |
31,794 | Rhinostone/gina | core/utils/lib/proc.js | function() {
//Default.
var pathObj = new _( getPath('root') + '/tmp/pid/' );
var path = pathObj.toString();
//Create dir if needed.
//console.debug("MKDIR pathObj (pid:"+self.proc.pid+") - ", self.bundle);
process.list = (process.list == undefined) ? [] : process.list;
process.pids = (process.pids == undefined) ? {} : process.pids;
self.register(self.bundle, self.proc.pid);
if (usePidFile) {
pathObj.mkdir( function(err, path){
console.debug('path created ('+path+') now saving PID ' + bundle);
//logger.info('gina', 'PROC:INFO:1', 'path created ('+path+') now saving PID ' + bundle, __stack);
//Save file.
if (!err) {
self.PID = self.proc.pid;
self.path = path + pathObj.sep;
//Add PID file.
setPID(self.bundle, self.PID, self.proc);
save(self.bundle, self.PID, self.proc)
}
})
}
} | javascript | function() {
//Default.
var pathObj = new _( getPath('root') + '/tmp/pid/' );
var path = pathObj.toString();
//Create dir if needed.
//console.debug("MKDIR pathObj (pid:"+self.proc.pid+") - ", self.bundle);
process.list = (process.list == undefined) ? [] : process.list;
process.pids = (process.pids == undefined) ? {} : process.pids;
self.register(self.bundle, self.proc.pid);
if (usePidFile) {
pathObj.mkdir( function(err, path){
console.debug('path created ('+path+') now saving PID ' + bundle);
//logger.info('gina', 'PROC:INFO:1', 'path created ('+path+') now saving PID ' + bundle, __stack);
//Save file.
if (!err) {
self.PID = self.proc.pid;
self.path = path + pathObj.sep;
//Add PID file.
setPID(self.bundle, self.PID, self.proc);
save(self.bundle, self.PID, self.proc)
}
})
}
} | [
"function",
"(",
")",
"{",
"//Default.",
"var",
"pathObj",
"=",
"new",
"_",
"(",
"getPath",
"(",
"'root'",
")",
"+",
"'/tmp/pid/'",
")",
";",
"var",
"path",
"=",
"pathObj",
".",
"toString",
"(",
")",
";",
"//Create dir if needed.",
"//console.debug(\"MKDIR ... | Check target path
@param {string} path
@param {integer} PID Id of the PID to save | [
"Check",
"target",
"path"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/proc.js#L80-L107 | |
31,795 | Jack12816/greppy | lib/db/adapter/mysql.js | function(callback)
{
self.pool = (require('mysql')).createPool({
user : self.config.username,
password : self.config.password,
database : self.config.db,
host : self.config.host,
port : self.config.port
});
// Initiate a connection - just to proof configuration
self.pool.getConnection(function(err, connection) {
if (err || !connection) {
callback && callback(err);
return;
}
self.prepare(connection);
// The connection can be closed immediately
connection.release();
return callback && callback(null, self.pool);
});
} | javascript | function(callback)
{
self.pool = (require('mysql')).createPool({
user : self.config.username,
password : self.config.password,
database : self.config.db,
host : self.config.host,
port : self.config.port
});
// Initiate a connection - just to proof configuration
self.pool.getConnection(function(err, connection) {
if (err || !connection) {
callback && callback(err);
return;
}
self.prepare(connection);
// The connection can be closed immediately
connection.release();
return callback && callback(null, self.pool);
});
} | [
"function",
"(",
"callback",
")",
"{",
"self",
".",
"pool",
"=",
"(",
"require",
"(",
"'mysql'",
")",
")",
".",
"createPool",
"(",
"{",
"user",
":",
"self",
".",
"config",
".",
"username",
",",
"password",
":",
"self",
".",
"config",
".",
"password",... | Setup the plain MySQL connection, pooling enabled | [
"Setup",
"the",
"plain",
"MySQL",
"connection",
"pooling",
"enabled"
] | ede2157b90c207896781cc41fb9ea115e83951dd | https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/db/adapter/mysql.js#L45-L69 | |
31,796 | Rhinostone/gina | core/locales/index.js | Locales | function Locales() {
var _require = function(path) {
var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
if (cacheless) {
try {
delete require.cache[require.resolve(path)];
return require(path)
} catch (err) {
throw err
}
} else {
return require(path)
}
}
/**
* init
*
* return {array} regions collection
* */
var init = function () {
var dir = __dirname + '/dist/region' // regions by language
, files = fs.readdirSync(dir)
, i = 0
, key = null
, regions = []
;
for (var f = 0, len = files.length; f < len; ++f) {
if ( ! /^\./.test(files[f]) || f == len-1 ) {
key = files[f].split(/\./)[0];
regions[i] = { lang: key, content: _require( dir + '/' + files[f] ) }
}
}
return regions
}
return init()
} | javascript | function Locales() {
var _require = function(path) {
var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
if (cacheless) {
try {
delete require.cache[require.resolve(path)];
return require(path)
} catch (err) {
throw err
}
} else {
return require(path)
}
}
/**
* init
*
* return {array} regions collection
* */
var init = function () {
var dir = __dirname + '/dist/region' // regions by language
, files = fs.readdirSync(dir)
, i = 0
, key = null
, regions = []
;
for (var f = 0, len = files.length; f < len; ++f) {
if ( ! /^\./.test(files[f]) || f == len-1 ) {
key = files[f].split(/\./)[0];
regions[i] = { lang: key, content: _require( dir + '/' + files[f] ) }
}
}
return regions
}
return init()
} | [
"function",
"Locales",
"(",
")",
"{",
"var",
"_require",
"=",
"function",
"(",
"path",
")",
"{",
"var",
"cacheless",
"=",
"(",
"process",
".",
"env",
".",
"IS_CACHELESS",
"==",
"'false'",
")",
"?",
"false",
":",
"true",
";",
"if",
"(",
"cacheless",
"... | Gina.Core.Locales Class
@package Gina.Core
@author Rhinostone <gina@rhinostone.com> | [
"Gina",
".",
"Core",
".",
"Locales",
"Class"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/locales/index.js#L18-L62 |
31,797 | Rhinostone/gina | core/config.js | function(bundle, env) {
if ( !self.isStandalone ) {
if ( !bundle && typeof(self.bundle) != 'undefined' ) {
var bundle = self.bundle
}
return ( typeof(self.envConf) != "undefined" ) ? self.envConf[bundle][env] : null;
} else {
if (!bundle) { // if getContext().bundle is lost .. eg.: worker context
var model = (arguments.length == 1) ? bundle : model
, file = ( !/node_modules/.test(__stack[1].getFileName()) ) ? __stack[1].getFileName() : __stack[2].getFileName()
, a = file.replace('.js', '').split('/')
, i = a.length-1
, bundles = getContext('gina').config.bundles
, index = 0;
for (; i >= 0; --i) {
index = bundles.indexOf(a[i]);
if ( index > -1 ) {
bundle = bundles[index];
break
}
}
}
if ( typeof(self.envConf) != "undefined" ) {
self.envConf[bundle][env].hostname = self.envConf[self.startingApp][env].hostname;
self.envConf[bundle][env].content.routing = self.envConf[self.startingApp][env].content.routing;
if ( bundle && env ) {
return self.envConf[bundle][env]
} else if ( bundle && !env ) {
return self.envConf[bundle]
} else {
return self.envConf
}
}
return null
}
} | javascript | function(bundle, env) {
if ( !self.isStandalone ) {
if ( !bundle && typeof(self.bundle) != 'undefined' ) {
var bundle = self.bundle
}
return ( typeof(self.envConf) != "undefined" ) ? self.envConf[bundle][env] : null;
} else {
if (!bundle) { // if getContext().bundle is lost .. eg.: worker context
var model = (arguments.length == 1) ? bundle : model
, file = ( !/node_modules/.test(__stack[1].getFileName()) ) ? __stack[1].getFileName() : __stack[2].getFileName()
, a = file.replace('.js', '').split('/')
, i = a.length-1
, bundles = getContext('gina').config.bundles
, index = 0;
for (; i >= 0; --i) {
index = bundles.indexOf(a[i]);
if ( index > -1 ) {
bundle = bundles[index];
break
}
}
}
if ( typeof(self.envConf) != "undefined" ) {
self.envConf[bundle][env].hostname = self.envConf[self.startingApp][env].hostname;
self.envConf[bundle][env].content.routing = self.envConf[self.startingApp][env].content.routing;
if ( bundle && env ) {
return self.envConf[bundle][env]
} else if ( bundle && !env ) {
return self.envConf[bundle]
} else {
return self.envConf
}
}
return null
}
} | [
"function",
"(",
"bundle",
",",
"env",
")",
"{",
"if",
"(",
"!",
"self",
".",
"isStandalone",
")",
"{",
"if",
"(",
"!",
"bundle",
"&&",
"typeof",
"(",
"self",
".",
"bundle",
")",
"!=",
"'undefined'",
")",
"{",
"var",
"bundle",
"=",
"self",
".",
"... | Get env config
@param {string} bundle
@param {string} env
@return {Object} json conf | [
"Get",
"env",
"config"
] | c6ba13d3255a43734c54880ff12d3a50df53ebea | https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/config.js#L291-L332 | |
31,798 | maichong/string-random | index.js | random | function random(length, options) {
length || (length = 8);
options || (options = {});
var chars = '';
var result = '';
if (options === true) {
chars = numbers + letters + specials;
} else if (typeof options == 'string') {
chars = options;
} else {
if (options.numbers !== false) {
chars += (typeof options.numbers == 'string') ? options.numbers : numbers;
}
if (options.letters !== false) {
chars += (typeof options.letters == 'string') ? options.letters : letters;
}
if (options.specials) {
chars += (typeof options.specials == 'string') ? options.specials : specials;
}
}
while (length > 0) {
length--;
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
} | javascript | function random(length, options) {
length || (length = 8);
options || (options = {});
var chars = '';
var result = '';
if (options === true) {
chars = numbers + letters + specials;
} else if (typeof options == 'string') {
chars = options;
} else {
if (options.numbers !== false) {
chars += (typeof options.numbers == 'string') ? options.numbers : numbers;
}
if (options.letters !== false) {
chars += (typeof options.letters == 'string') ? options.letters : letters;
}
if (options.specials) {
chars += (typeof options.specials == 'string') ? options.specials : specials;
}
}
while (length > 0) {
length--;
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
} | [
"function",
"random",
"(",
"length",
",",
"options",
")",
"{",
"length",
"||",
"(",
"length",
"=",
"8",
")",
";",
"options",
"||",
"(",
"options",
"=",
"{",
"}",
")",
";",
"var",
"chars",
"=",
"''",
";",
"var",
"result",
"=",
"''",
";",
"if",
"... | Generate random string
@param {Number} length
@param {Object} options | [
"Generate",
"random",
"string"
] | 1d1adf06fe6740b8aecfe82ac9fd6937e5486e0d | https://github.com/maichong/string-random/blob/1d1adf06fe6740b8aecfe82ac9fd6937e5486e0d/index.js#L18-L48 |
31,799 | rackfx/Node-WAV-File-Info | wav-file-info.js | post_process | function post_process(){
var error = false;
var invalid_reasons = []
if (read_result.riff_head != "RIFF") invalid_reasons.push("Expected \"RIFF\" string at 0" )
if (read_result.wave_identifier != "WAVE") invalid_reasons.push("Expected \"WAVE\" string at 4")
if (read_result.fmt_identifier != "fmt ") invalid_reasons.push("Expected \"fmt \" string at 8")
if (
(read_result.audio_format != 1) && // Wav
(read_result.audio_format != 65534) && // Extensible PCM
(read_result.audio_format != 2) && // Wav
(read_result.audio_format != 22127) && // Vorbis ?? (issue #11)
(read_result.audio_format != 3)) // Wav
invalid_reasons.push("Unknown format: "+read_result.audio_format)
if ((read_result.chunk_size + 8) !== stats.size) invalid_reasons.push("chunk_size does not match file size")
//if ((read_result.data_identifier) != "data") invalid_reasons.push("Expected data identifier at the end of the header")
if (invalid_reasons.length > 0) error = true;
if (error) return cb({
error : true,
invalid_reasons: invalid_reasons,
header: read_result,
stats: stats
});
cb(null, {
header: read_result,
stats: stats,
duration: ((read_result.chunk_size) / (read_result.sample_rate * read_result.num_channels * (read_result.bits_per_sample / 8)))
});
} | javascript | function post_process(){
var error = false;
var invalid_reasons = []
if (read_result.riff_head != "RIFF") invalid_reasons.push("Expected \"RIFF\" string at 0" )
if (read_result.wave_identifier != "WAVE") invalid_reasons.push("Expected \"WAVE\" string at 4")
if (read_result.fmt_identifier != "fmt ") invalid_reasons.push("Expected \"fmt \" string at 8")
if (
(read_result.audio_format != 1) && // Wav
(read_result.audio_format != 65534) && // Extensible PCM
(read_result.audio_format != 2) && // Wav
(read_result.audio_format != 22127) && // Vorbis ?? (issue #11)
(read_result.audio_format != 3)) // Wav
invalid_reasons.push("Unknown format: "+read_result.audio_format)
if ((read_result.chunk_size + 8) !== stats.size) invalid_reasons.push("chunk_size does not match file size")
//if ((read_result.data_identifier) != "data") invalid_reasons.push("Expected data identifier at the end of the header")
if (invalid_reasons.length > 0) error = true;
if (error) return cb({
error : true,
invalid_reasons: invalid_reasons,
header: read_result,
stats: stats
});
cb(null, {
header: read_result,
stats: stats,
duration: ((read_result.chunk_size) / (read_result.sample_rate * read_result.num_channels * (read_result.bits_per_sample / 8)))
});
} | [
"function",
"post_process",
"(",
")",
"{",
"var",
"error",
"=",
"false",
";",
"var",
"invalid_reasons",
"=",
"[",
"]",
"if",
"(",
"read_result",
".",
"riff_head",
"!=",
"\"RIFF\"",
")",
"invalid_reasons",
".",
"push",
"(",
"\"Expected \\\"RIFF\\\" string at 0\""... | end fs.read | [
"end",
"fs",
".",
"read"
] | 000e6bc3c98c032178564c178862026724c015ce | https://github.com/rackfx/Node-WAV-File-Info/blob/000e6bc3c98c032178564c178862026724c015ce/wav-file-info.js#L65-L96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.