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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
52,700
|
jmendiara/gitftw
|
src/commands.js
|
tag
|
function tag(options) {
assert.ok(options.tag, 'tag name is mandatory');
if (options.annotated) {
assert.ok(options.message, 'message is mandatory when creating an annotated tag');
}
var args = [
'tag',
options.tag,
options.annotated ? '-a' : null,
options.message ? '-m' : null,
options.message ? options.message : null
];
return git(args)
.then(silent);
}
|
javascript
|
function tag(options) {
assert.ok(options.tag, 'tag name is mandatory');
if (options.annotated) {
assert.ok(options.message, 'message is mandatory when creating an annotated tag');
}
var args = [
'tag',
options.tag,
options.annotated ? '-a' : null,
options.message ? '-m' : null,
options.message ? options.message : null
];
return git(args)
.then(silent);
}
|
[
"function",
"tag",
"(",
"options",
")",
"{",
"assert",
".",
"ok",
"(",
"options",
".",
"tag",
",",
"'tag name is mandatory'",
")",
";",
"if",
"(",
"options",
".",
"annotated",
")",
"{",
"assert",
".",
"ok",
"(",
"options",
".",
"message",
",",
"'message is mandatory when creating an annotated tag'",
")",
";",
"}",
"var",
"args",
"=",
"[",
"'tag'",
",",
"options",
".",
"tag",
",",
"options",
".",
"annotated",
"?",
"'-a'",
":",
"null",
",",
"options",
".",
"message",
"?",
"'-m'",
":",
"null",
",",
"options",
".",
"message",
"?",
"options",
".",
"message",
":",
"null",
"]",
";",
"return",
"git",
"(",
"args",
")",
".",
"then",
"(",
"silent",
")",
";",
"}"
] |
Creates a git tag
Executes `git tag v1.0.0 -m "v1.0.0" -a`
@example
var git = require('gitftw');
git.tag({
tag: 'v1.2.0'
})
@memberof git
@type {command}
@param {Object} options The options object. All its properties are {@link Resolvable}
@param {Resolvable|String} options.tag The tag name
@param {Resolvable|String} [options.message] The tag message. Mandatory when creating
an annotated tag
@param {Resolvable|Boolean} [options.annotated] Should this tag be annotated?
@param {callback} [cb] The execution callback result
@returns {Promise} Promise Resolves with undefined
|
[
"Creates",
"a",
"git",
"tag",
"Executes",
"git",
"tag",
"v1",
".",
"0",
".",
"0",
"-",
"m",
"v1",
".",
"0",
".",
"0",
"-",
"a"
] |
ba91b0d68b7791b5b557addc685737f6c912b4f3
|
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L637-L653
|
52,701
|
jmendiara/gitftw
|
src/commands.js
|
removeLocalTags
|
function removeLocalTags(options) {
assert.ok(options.tags, 'tags is mandatory');
return options.tags
.reduce(function(soFar, tag) {
var args = [
'tag',
'-d',
tag
];
return soFar
.then(gitFn(args))
.catch(passWarning)
.then(silent);
}, Promise.resolve());
}
|
javascript
|
function removeLocalTags(options) {
assert.ok(options.tags, 'tags is mandatory');
return options.tags
.reduce(function(soFar, tag) {
var args = [
'tag',
'-d',
tag
];
return soFar
.then(gitFn(args))
.catch(passWarning)
.then(silent);
}, Promise.resolve());
}
|
[
"function",
"removeLocalTags",
"(",
"options",
")",
"{",
"assert",
".",
"ok",
"(",
"options",
".",
"tags",
",",
"'tags is mandatory'",
")",
";",
"return",
"options",
".",
"tags",
".",
"reduce",
"(",
"function",
"(",
"soFar",
",",
"tag",
")",
"{",
"var",
"args",
"=",
"[",
"'tag'",
",",
"'-d'",
",",
"tag",
"]",
";",
"return",
"soFar",
".",
"then",
"(",
"gitFn",
"(",
"args",
")",
")",
".",
"catch",
"(",
"passWarning",
")",
".",
"then",
"(",
"silent",
")",
";",
"}",
",",
"Promise",
".",
"resolve",
"(",
")",
")",
";",
"}"
] |
Removes a set of tags from the local repo
Executes `git tag -d v1.0.0`
It does not fail when the tag does not exists
@example
var git = require('gitftw');
//remove all local tags
git.removeLocalTags({
tags: git.getTags //It's a resolvable. You can specify also ['v1.0.0', 'v1.0.1']
});
@memberof git
@type {command}
@param {Object} options The options object. All its properties are {@link Resolvable}
@param {Resolvable|Array<String>} options.tags The tags to remove
@param {callback} [cb] The execution callback result
@returns {Promise} Promise Resolves with undefined
|
[
"Removes",
"a",
"set",
"of",
"tags",
"from",
"the",
"local",
"repo",
"Executes",
"git",
"tag",
"-",
"d",
"v1",
".",
"0",
".",
"0"
] |
ba91b0d68b7791b5b557addc685737f6c912b4f3
|
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L702-L717
|
52,702
|
jmendiara/gitftw
|
src/commands.js
|
removeTags
|
function removeTags(options) {
return Promise.resolve()
.then(git.removeLocalTags.bind(null, options))
.then(git.removeRemoteTags.bind(null, options));
}
|
javascript
|
function removeTags(options) {
return Promise.resolve()
.then(git.removeLocalTags.bind(null, options))
.then(git.removeRemoteTags.bind(null, options));
}
|
[
"function",
"removeTags",
"(",
"options",
")",
"{",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"git",
".",
"removeLocalTags",
".",
"bind",
"(",
"null",
",",
"options",
")",
")",
".",
"then",
"(",
"git",
".",
"removeRemoteTags",
".",
"bind",
"(",
"null",
",",
"options",
")",
")",
";",
"}"
] |
Removes a set of tags from the remote and local repo
@example
var git = require('gitftw');
//remove all local tags in local and remote 'origin'
git.removeTags({
tags: git.getTags //It's a resolvable. You can specify also ['v1.0.0', 'v1.0.1']
});
@memberof git
@type {command}
@param {Object} options The options object. All its properties are {@link Resolvable}
@param {Resolvable|String} [options.remote="origin"] The remote ref where the tag will be removed
@param {Resolvable|Array<String>} options.tags The tags to remove
@param {callback} [cb] The execution callback result
@returns {Promise} Promise Resolves with undefined
|
[
"Removes",
"a",
"set",
"of",
"tags",
"from",
"the",
"remote",
"and",
"local",
"repo"
] |
ba91b0d68b7791b5b557addc685737f6c912b4f3
|
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L777-L781
|
52,703
|
jmendiara/gitftw
|
src/commands.js
|
parseVersion
|
function parseVersion(str) {
var match = /git version ([0-9\.]+)/.exec(str);
if (match) {
return match[1];
} else {
throw new Error('Unable to parse version response', str);
}
}
|
javascript
|
function parseVersion(str) {
var match = /git version ([0-9\.]+)/.exec(str);
if (match) {
return match[1];
} else {
throw new Error('Unable to parse version response', str);
}
}
|
[
"function",
"parseVersion",
"(",
"str",
")",
"{",
"var",
"match",
"=",
"/",
"git version ([0-9\\.]+)",
"/",
".",
"exec",
"(",
"str",
")",
";",
"if",
"(",
"match",
")",
"{",
"return",
"match",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Unable to parse version response'",
",",
"str",
")",
";",
"}",
"}"
] |
Parses the git version
@private
@param {Resolvable|String} str The 'git version' command output
@throws {Error} parsing error
@returns {String} the version number
|
[
"Parses",
"the",
"git",
"version"
] |
ba91b0d68b7791b5b557addc685737f6c912b4f3
|
https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/commands.js#L823-L831
|
52,704
|
ergo-cms/ergo-core
|
lib/plugins/collate.js
|
_render
|
function _render(text, fields, fileInfo, context)
{
var options = _.extend({}, default_options, this.plugin_options);
if (options.disable === true)
return text;
//l.vvlogd(l.dump(options));
_collateData(fields, options, fileInfo, context);
if (!fields.dynamic_list)
fields.dynamic_list = _field_dynamic_list;
var dl = fields.dynamic_list;
/*//debug dynlists...
fields.dynamic_list = function() {
l.vlog("Dynlist for: " + fileInfo.relPath)
dl.call(this)
}
*/
return fields.content;
}
|
javascript
|
function _render(text, fields, fileInfo, context)
{
var options = _.extend({}, default_options, this.plugin_options);
if (options.disable === true)
return text;
//l.vvlogd(l.dump(options));
_collateData(fields, options, fileInfo, context);
if (!fields.dynamic_list)
fields.dynamic_list = _field_dynamic_list;
var dl = fields.dynamic_list;
/*//debug dynlists...
fields.dynamic_list = function() {
l.vlog("Dynlist for: " + fileInfo.relPath)
dl.call(this)
}
*/
return fields.content;
}
|
[
"function",
"_render",
"(",
"text",
",",
"fields",
",",
"fileInfo",
",",
"context",
")",
"{",
"var",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"}",
",",
"default_options",
",",
"this",
".",
"plugin_options",
")",
";",
"if",
"(",
"options",
".",
"disable",
"===",
"true",
")",
"return",
"text",
";",
"//l.vvlogd(l.dump(options));",
"_collateData",
"(",
"fields",
",",
"options",
",",
"fileInfo",
",",
"context",
")",
";",
"if",
"(",
"!",
"fields",
".",
"dynamic_list",
")",
"fields",
".",
"dynamic_list",
"=",
"_field_dynamic_list",
";",
"var",
"dl",
"=",
"fields",
".",
"dynamic_list",
";",
"/*//debug dynlists...\n\tfields.dynamic_list = function() { \n\t\tl.vlog(\"Dynlist for: \" + fileInfo.relPath)\n\t\tdl.call(this)\n\t\t}\n\t*/",
"return",
"fields",
".",
"content",
";",
"}"
] |
the main entry point for the plugin
|
[
"the",
"main",
"entry",
"point",
"for",
"the",
"plugin"
] |
8ed4d087554b5f8cd93f0765719ecee14164ca71
|
https://github.com/ergo-cms/ergo-core/blob/8ed4d087554b5f8cd93f0765719ecee14164ca71/lib/plugins/collate.js#L348-L366
|
52,705
|
piranna/WebhookPost
|
index.js
|
getHostname
|
function getHostname()
{
var interfaces = networkInterfaces()
for(var name in interfaces)
{
var info = interfaces[name].filter(filterIPv4)[0]
if(info) return info.address
}
}
|
javascript
|
function getHostname()
{
var interfaces = networkInterfaces()
for(var name in interfaces)
{
var info = interfaces[name].filter(filterIPv4)[0]
if(info) return info.address
}
}
|
[
"function",
"getHostname",
"(",
")",
"{",
"var",
"interfaces",
"=",
"networkInterfaces",
"(",
")",
"for",
"(",
"var",
"name",
"in",
"interfaces",
")",
"{",
"var",
"info",
"=",
"interfaces",
"[",
"name",
"]",
".",
"filter",
"(",
"filterIPv4",
")",
"[",
"0",
"]",
"if",
"(",
"info",
")",
"return",
"info",
".",
"address",
"}",
"}"
] |
Get the adfress of an external IPv4 network interface in the current system
@return {string|undefined}
|
[
"Get",
"the",
"adfress",
"of",
"an",
"external",
"IPv4",
"network",
"interface",
"in",
"the",
"current",
"system"
] |
b9348d58cb1304663e81cde89d092542050bd199
|
https://github.com/piranna/WebhookPost/blob/b9348d58cb1304663e81cde89d092542050bd199/index.js#L33-L41
|
52,706
|
piranna/WebhookPost
|
index.js
|
createEventSource
|
function createEventSource(webhook, options)
{
var self = this
var eventSource = new EventSource(webhook, options)
eventSource.addEventListener('open', this.emit.bind(this, 'open', webhook))
eventSource.addEventListener('message', function(message)
{
self.push(message.data)
})
return eventSource
}
|
javascript
|
function createEventSource(webhook, options)
{
var self = this
var eventSource = new EventSource(webhook, options)
eventSource.addEventListener('open', this.emit.bind(this, 'open', webhook))
eventSource.addEventListener('message', function(message)
{
self.push(message.data)
})
return eventSource
}
|
[
"function",
"createEventSource",
"(",
"webhook",
",",
"options",
")",
"{",
"var",
"self",
"=",
"this",
"var",
"eventSource",
"=",
"new",
"EventSource",
"(",
"webhook",
",",
"options",
")",
"eventSource",
".",
"addEventListener",
"(",
"'open'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'open'",
",",
"webhook",
")",
")",
"eventSource",
".",
"addEventListener",
"(",
"'message'",
",",
"function",
"(",
"message",
")",
"{",
"self",
".",
"push",
"(",
"message",
".",
"data",
")",
"}",
")",
"return",
"eventSource",
"}"
] |
Connect to a remove SSE server to receive the webhook notifications
@param {string} webhook
@param {Object} [options]
@param {Boolean} [options.withCredentials=false]
@return {EventSource}
|
[
"Connect",
"to",
"a",
"remove",
"SSE",
"server",
"to",
"receive",
"the",
"webhook",
"notifications"
] |
b9348d58cb1304663e81cde89d092542050bd199
|
https://github.com/piranna/WebhookPost/blob/b9348d58cb1304663e81cde89d092542050bd199/index.js#L53-L66
|
52,707
|
piranna/WebhookPost
|
index.js
|
createServer
|
function createServer(webhook)
{
var self = this
var onError = this.emit.bind(this, 'error')
var port = webhook.port || 0
var hostname = webhook.hostname || HOSTNAME
var server = http.createServer(function(req, res)
{
if(req.method === 'GET')
{
res.end()
return self.push(parse(req.url).query)
}
req.pipe(concat(function(body)
{
res.end()
self.push(body.toString())
}))
})
.listen(port, hostname, function()
{
var address = this.address()
if(hostname === HOSTNAME) hostname = getHostname()
if(!hostname)
{
self.emit('error', new Error("There's no public available interfaces"))
return this.close()
}
self.emit('open', 'http://'+hostname+':'+address.port)
})
.on('error' , onError)
.on('clientError', onError)
return server
}
|
javascript
|
function createServer(webhook)
{
var self = this
var onError = this.emit.bind(this, 'error')
var port = webhook.port || 0
var hostname = webhook.hostname || HOSTNAME
var server = http.createServer(function(req, res)
{
if(req.method === 'GET')
{
res.end()
return self.push(parse(req.url).query)
}
req.pipe(concat(function(body)
{
res.end()
self.push(body.toString())
}))
})
.listen(port, hostname, function()
{
var address = this.address()
if(hostname === HOSTNAME) hostname = getHostname()
if(!hostname)
{
self.emit('error', new Error("There's no public available interfaces"))
return this.close()
}
self.emit('open', 'http://'+hostname+':'+address.port)
})
.on('error' , onError)
.on('clientError', onError)
return server
}
|
[
"function",
"createServer",
"(",
"webhook",
")",
"{",
"var",
"self",
"=",
"this",
"var",
"onError",
"=",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'error'",
")",
"var",
"port",
"=",
"webhook",
".",
"port",
"||",
"0",
"var",
"hostname",
"=",
"webhook",
".",
"hostname",
"||",
"HOSTNAME",
"var",
"server",
"=",
"http",
".",
"createServer",
"(",
"function",
"(",
"req",
",",
"res",
")",
"{",
"if",
"(",
"req",
".",
"method",
"===",
"'GET'",
")",
"{",
"res",
".",
"end",
"(",
")",
"return",
"self",
".",
"push",
"(",
"parse",
"(",
"req",
".",
"url",
")",
".",
"query",
")",
"}",
"req",
".",
"pipe",
"(",
"concat",
"(",
"function",
"(",
"body",
")",
"{",
"res",
".",
"end",
"(",
")",
"self",
".",
"push",
"(",
"body",
".",
"toString",
"(",
")",
")",
"}",
")",
")",
"}",
")",
".",
"listen",
"(",
"port",
",",
"hostname",
",",
"function",
"(",
")",
"{",
"var",
"address",
"=",
"this",
".",
"address",
"(",
")",
"if",
"(",
"hostname",
"===",
"HOSTNAME",
")",
"hostname",
"=",
"getHostname",
"(",
")",
"if",
"(",
"!",
"hostname",
")",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"new",
"Error",
"(",
"\"There's no public available interfaces\"",
")",
")",
"return",
"this",
".",
"close",
"(",
")",
"}",
"self",
".",
"emit",
"(",
"'open'",
",",
"'http://'",
"+",
"hostname",
"+",
"':'",
"+",
"address",
".",
"port",
")",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"onError",
")",
".",
"on",
"(",
"'clientError'",
",",
"onError",
")",
"return",
"server",
"}"
] |
Create an ad-hoc web server where to receive the webhook notifications
@param {Object} webhook
@param {string} [webhook.hostname='0.0.0.0']
@param {Number} [webhook.port=0]
@return {http.Server}
|
[
"Create",
"an",
"ad",
"-",
"hoc",
"web",
"server",
"where",
"to",
"receive",
"the",
"webhook",
"notifications"
] |
b9348d58cb1304663e81cde89d092542050bd199
|
https://github.com/piranna/WebhookPost/blob/b9348d58cb1304663e81cde89d092542050bd199/index.js#L77-L121
|
52,708
|
piranna/WebhookPost
|
index.js
|
WebhookPost
|
function WebhookPost(webhook, options)
{
if(!(this instanceof WebhookPost)) return new WebhookPost(webhook, options)
var self = this
options = options || {}
options.objectMode = true
WebhookPost.super_.call(this, options)
// Remote ServerSendEvent server
if(typeof webhook === 'string')
{
var eventSource = createEventSource.call(this, webhook, options)
eventSource.addEventListener('error', function(error)
{
if(this.readyState !== EventSource.CLOSED)
return self.emit('error', error)
self.push(null)
eventSource = null
})
}
// Ad-hoc local web server
else
{
if(webhook == null) webhook = {}
else if(typeof webhook === 'number') webhook = {port: webhook}
var server = createServer.call(this, webhook)
.on('close', function()
{
self.push(null)
server = null
})
}
//
// Public API
//
/**
* Close the connection and stop emitting more data updates
*/
this.close = function()
{
var connection = eventSource || server
if(!connection) return
connection.close()
}
}
|
javascript
|
function WebhookPost(webhook, options)
{
if(!(this instanceof WebhookPost)) return new WebhookPost(webhook, options)
var self = this
options = options || {}
options.objectMode = true
WebhookPost.super_.call(this, options)
// Remote ServerSendEvent server
if(typeof webhook === 'string')
{
var eventSource = createEventSource.call(this, webhook, options)
eventSource.addEventListener('error', function(error)
{
if(this.readyState !== EventSource.CLOSED)
return self.emit('error', error)
self.push(null)
eventSource = null
})
}
// Ad-hoc local web server
else
{
if(webhook == null) webhook = {}
else if(typeof webhook === 'number') webhook = {port: webhook}
var server = createServer.call(this, webhook)
.on('close', function()
{
self.push(null)
server = null
})
}
//
// Public API
//
/**
* Close the connection and stop emitting more data updates
*/
this.close = function()
{
var connection = eventSource || server
if(!connection) return
connection.close()
}
}
|
[
"function",
"WebhookPost",
"(",
"webhook",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"WebhookPost",
")",
")",
"return",
"new",
"WebhookPost",
"(",
"webhook",
",",
"options",
")",
"var",
"self",
"=",
"this",
"options",
"=",
"options",
"||",
"{",
"}",
"options",
".",
"objectMode",
"=",
"true",
"WebhookPost",
".",
"super_",
".",
"call",
"(",
"this",
",",
"options",
")",
"// Remote ServerSendEvent server",
"if",
"(",
"typeof",
"webhook",
"===",
"'string'",
")",
"{",
"var",
"eventSource",
"=",
"createEventSource",
".",
"call",
"(",
"this",
",",
"webhook",
",",
"options",
")",
"eventSource",
".",
"addEventListener",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"this",
".",
"readyState",
"!==",
"EventSource",
".",
"CLOSED",
")",
"return",
"self",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
"self",
".",
"push",
"(",
"null",
")",
"eventSource",
"=",
"null",
"}",
")",
"}",
"// Ad-hoc local web server",
"else",
"{",
"if",
"(",
"webhook",
"==",
"null",
")",
"webhook",
"=",
"{",
"}",
"else",
"if",
"(",
"typeof",
"webhook",
"===",
"'number'",
")",
"webhook",
"=",
"{",
"port",
":",
"webhook",
"}",
"var",
"server",
"=",
"createServer",
".",
"call",
"(",
"this",
",",
"webhook",
")",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"self",
".",
"push",
"(",
"null",
")",
"server",
"=",
"null",
"}",
")",
"}",
"//",
"// Public API",
"//",
"/**\n * Close the connection and stop emitting more data updates\n */",
"this",
".",
"close",
"=",
"function",
"(",
")",
"{",
"var",
"connection",
"=",
"eventSource",
"||",
"server",
"if",
"(",
"!",
"connection",
")",
"return",
"connection",
".",
"close",
"(",
")",
"}",
"}"
] |
Create a stream of webhook notifications
@constructor
@param {Object|string|Number} [webhook={}]
@param {string} [webhook.hostname='0.0.0.0']
@param {Number} [webhook.port=0]
@param {Object} [options]
@param {Boolean} [options.withCredentials=false]
@emits WebhookPost#open
@emits WebhookPost#data
@emits WebhookPost#error
@emits Readable#end
|
[
"Create",
"a",
"stream",
"of",
"webhook",
"notifications"
] |
b9348d58cb1304663e81cde89d092542050bd199
|
https://github.com/piranna/WebhookPost/blob/b9348d58cb1304663e81cde89d092542050bd199/index.js#L140-L196
|
52,709
|
cli-kit/cli-env
|
index.js
|
function(conf) {
Object.defineProperty(this, 'conf',
{
enumerable: false,
configurable: false,
writable: false,
value: conf || {}
}
);
if(this.conf.initialize) {
this.load();
}
}
|
javascript
|
function(conf) {
Object.defineProperty(this, 'conf',
{
enumerable: false,
configurable: false,
writable: false,
value: conf || {}
}
);
if(this.conf.initialize) {
this.load();
}
}
|
[
"function",
"(",
"conf",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'conf'",
",",
"{",
"enumerable",
":",
"false",
",",
"configurable",
":",
"false",
",",
"writable",
":",
"false",
",",
"value",
":",
"conf",
"||",
"{",
"}",
"}",
")",
";",
"if",
"(",
"this",
".",
"conf",
".",
"initialize",
")",
"{",
"this",
".",
"load",
"(",
")",
";",
"}",
"}"
] |
Helper class for accessing environment variables
using a defined prefix.
@param conf The configuration object.
|
[
"Helper",
"class",
"for",
"accessing",
"environment",
"variables",
"using",
"a",
"defined",
"prefix",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L33-L45
|
|
52,710
|
cli-kit/cli-env
|
index.js
|
getKey
|
function getKey(key) {
if(this.conf.transform) {
if(typeof(this.conf.transform.key) == 'function') {
return this.conf.transform.key.call(this, key);
}
}
key = delimited(key, this.conf.delimiter);
key = key.replace(/- /, this.conf.delimiter);
key = key.replace(/[^a-zA-Z0-9_]/, '');
if(this.conf.prefix) {
return this.conf.prefix + this.conf.delimiter + key.toLowerCase()
}
return key.toLowerCase();
}
|
javascript
|
function getKey(key) {
if(this.conf.transform) {
if(typeof(this.conf.transform.key) == 'function') {
return this.conf.transform.key.call(this, key);
}
}
key = delimited(key, this.conf.delimiter);
key = key.replace(/- /, this.conf.delimiter);
key = key.replace(/[^a-zA-Z0-9_]/, '');
if(this.conf.prefix) {
return this.conf.prefix + this.conf.delimiter + key.toLowerCase()
}
return key.toLowerCase();
}
|
[
"function",
"getKey",
"(",
"key",
")",
"{",
"if",
"(",
"this",
".",
"conf",
".",
"transform",
")",
"{",
"if",
"(",
"typeof",
"(",
"this",
".",
"conf",
".",
"transform",
".",
"key",
")",
"==",
"'function'",
")",
"{",
"return",
"this",
".",
"conf",
".",
"transform",
".",
"key",
".",
"call",
"(",
"this",
",",
"key",
")",
";",
"}",
"}",
"key",
"=",
"delimited",
"(",
"key",
",",
"this",
".",
"conf",
".",
"delimiter",
")",
";",
"key",
"=",
"key",
".",
"replace",
"(",
"/",
"- ",
"/",
",",
"this",
".",
"conf",
".",
"delimiter",
")",
";",
"key",
"=",
"key",
".",
"replace",
"(",
"/",
"[^a-zA-Z0-9_]",
"/",
",",
"''",
")",
";",
"if",
"(",
"this",
".",
"conf",
".",
"prefix",
")",
"{",
"return",
"this",
".",
"conf",
".",
"prefix",
"+",
"this",
".",
"conf",
".",
"delimiter",
"+",
"key",
".",
"toLowerCase",
"(",
")",
"}",
"return",
"key",
".",
"toLowerCase",
"(",
")",
";",
"}"
] |
Retrieve a suitable key for setting an environment
variable.
@api private
@param key The candidate key.
@return A converted key.
|
[
"Retrieve",
"a",
"suitable",
"key",
"for",
"setting",
"an",
"environment",
"variable",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L57-L70
|
52,711
|
cli-kit/cli-env
|
index.js
|
getValue
|
function getValue (key, name, raw) {
if(this.conf.transform) {
if(typeof(this.conf.transform.value) == 'function') {
return this.conf.transform.value.call(this, key, name, raw);
}
}
var value = process.env[raw] || this[name];
if(this.conf.native && typeof(value) == 'string') {
value = native.to(
value, this.conf.native.delimiter, this.conf.native.json);
}
return value;
}
|
javascript
|
function getValue (key, name, raw) {
if(this.conf.transform) {
if(typeof(this.conf.transform.value) == 'function') {
return this.conf.transform.value.call(this, key, name, raw);
}
}
var value = process.env[raw] || this[name];
if(this.conf.native && typeof(value) == 'string') {
value = native.to(
value, this.conf.native.delimiter, this.conf.native.json);
}
return value;
}
|
[
"function",
"getValue",
"(",
"key",
",",
"name",
",",
"raw",
")",
"{",
"if",
"(",
"this",
".",
"conf",
".",
"transform",
")",
"{",
"if",
"(",
"typeof",
"(",
"this",
".",
"conf",
".",
"transform",
".",
"value",
")",
"==",
"'function'",
")",
"{",
"return",
"this",
".",
"conf",
".",
"transform",
".",
"value",
".",
"call",
"(",
"this",
",",
"key",
",",
"name",
",",
"raw",
")",
";",
"}",
"}",
"var",
"value",
"=",
"process",
".",
"env",
"[",
"raw",
"]",
"||",
"this",
"[",
"name",
"]",
";",
"if",
"(",
"this",
".",
"conf",
".",
"native",
"&&",
"typeof",
"(",
"value",
")",
"==",
"'string'",
")",
"{",
"value",
"=",
"native",
".",
"to",
"(",
"value",
",",
"this",
".",
"conf",
".",
"native",
".",
"delimiter",
",",
"this",
".",
"conf",
".",
"native",
".",
"json",
")",
";",
"}",
"return",
"value",
";",
"}"
] |
Retrieve the value of a variable from the environment.
@api private
@param key The key that has already been passed through
the key transformation function.
@param property The name of a property corresponding to the key.
@param raw The raw untouched key.
@return The value of the environment variable.
|
[
"Retrieve",
"the",
"value",
"of",
"a",
"variable",
"from",
"the",
"environment",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L84-L96
|
52,712
|
cli-kit/cli-env
|
index.js
|
getName
|
function getName(key) {
if(key == '_') return key;
if(this.conf.transform) {
if(typeof(this.conf.transform.name) == 'function') {
return this.conf.transform.name.call(this, key);
}
}
if(this.conf.prefix) {
key = key.replace(this.conf.prefix + '_', '');
}
// guard against silly variables such as npm_config_cache____foo
key = key.replace(
new RegExp(this.conf.delimiter + '+', 'g'), this.conf.delimiter);
return camelcase(key, this.conf.delimiter)
}
|
javascript
|
function getName(key) {
if(key == '_') return key;
if(this.conf.transform) {
if(typeof(this.conf.transform.name) == 'function') {
return this.conf.transform.name.call(this, key);
}
}
if(this.conf.prefix) {
key = key.replace(this.conf.prefix + '_', '');
}
// guard against silly variables such as npm_config_cache____foo
key = key.replace(
new RegExp(this.conf.delimiter + '+', 'g'), this.conf.delimiter);
return camelcase(key, this.conf.delimiter)
}
|
[
"function",
"getName",
"(",
"key",
")",
"{",
"if",
"(",
"key",
"==",
"'_'",
")",
"return",
"key",
";",
"if",
"(",
"this",
".",
"conf",
".",
"transform",
")",
"{",
"if",
"(",
"typeof",
"(",
"this",
".",
"conf",
".",
"transform",
".",
"name",
")",
"==",
"'function'",
")",
"{",
"return",
"this",
".",
"conf",
".",
"transform",
".",
"name",
".",
"call",
"(",
"this",
",",
"key",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"conf",
".",
"prefix",
")",
"{",
"key",
"=",
"key",
".",
"replace",
"(",
"this",
".",
"conf",
".",
"prefix",
"+",
"'_'",
",",
"''",
")",
";",
"}",
"// guard against silly variables such as npm_config_cache____foo",
"key",
"=",
"key",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"this",
".",
"conf",
".",
"delimiter",
"+",
"'+'",
",",
"'g'",
")",
",",
"this",
".",
"conf",
".",
"delimiter",
")",
";",
"return",
"camelcase",
"(",
"key",
",",
"this",
".",
"conf",
".",
"delimiter",
")",
"}"
] |
Convert a key into a property name.
@param key The property key.
@return A camel case property name.
|
[
"Convert",
"a",
"key",
"into",
"a",
"property",
"name",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L105-L120
|
52,713
|
cli-kit/cli-env
|
index.js
|
set
|
function set(key, value) {
var k = this.getKey(key);
var name = this.getName(key);
if(this.conf.native && typeof(value) == 'string') {
try {
value = native.to(
value, this.conf.native.delimiter, this.conf.native.json);
}catch(e){}
}
this[name] = process.env[k] = value;
}
|
javascript
|
function set(key, value) {
var k = this.getKey(key);
var name = this.getName(key);
if(this.conf.native && typeof(value) == 'string') {
try {
value = native.to(
value, this.conf.native.delimiter, this.conf.native.json);
}catch(e){}
}
this[name] = process.env[k] = value;
}
|
[
"function",
"set",
"(",
"key",
",",
"value",
")",
"{",
"var",
"k",
"=",
"this",
".",
"getKey",
"(",
"key",
")",
";",
"var",
"name",
"=",
"this",
".",
"getName",
"(",
"key",
")",
";",
"if",
"(",
"this",
".",
"conf",
".",
"native",
"&&",
"typeof",
"(",
"value",
")",
"==",
"'string'",
")",
"{",
"try",
"{",
"value",
"=",
"native",
".",
"to",
"(",
"value",
",",
"this",
".",
"conf",
".",
"native",
".",
"delimiter",
",",
"this",
".",
"conf",
".",
"native",
".",
"json",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"this",
"[",
"name",
"]",
"=",
"process",
".",
"env",
"[",
"k",
"]",
"=",
"value",
";",
"}"
] |
Set an environment variable using the transform
set function.
@param key The variable key.
@param value The variable value.
|
[
"Set",
"an",
"environment",
"variable",
"using",
"the",
"transform",
"set",
"function",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L129-L139
|
52,714
|
cli-kit/cli-env
|
index.js
|
get
|
function get(key) {
var k = this.getKey(key);
var name = this.getName(key);
var value = this.getValue(k, name, key);
return value;
}
|
javascript
|
function get(key) {
var k = this.getKey(key);
var name = this.getName(key);
var value = this.getValue(k, name, key);
return value;
}
|
[
"function",
"get",
"(",
"key",
")",
"{",
"var",
"k",
"=",
"this",
".",
"getKey",
"(",
"key",
")",
";",
"var",
"name",
"=",
"this",
".",
"getName",
"(",
"key",
")",
";",
"var",
"value",
"=",
"this",
".",
"getValue",
"(",
"k",
",",
"name",
",",
"key",
")",
";",
"return",
"value",
";",
"}"
] |
Get an environment variable using the transform
get function.
@param key The variable key.
@return The variable value.
|
[
"Get",
"an",
"environment",
"variable",
"using",
"the",
"transform",
"get",
"function",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L149-L154
|
52,715
|
cli-kit/cli-env
|
index.js
|
load
|
function load(match) {
match = match || this.conf.match;
for(var z in process.env) {
if(match instanceof RegExp) {
if(match.test(z)) {
this.set(z.toLowerCase(), process.env[z]);
}
}else{
this.set(z.toLowerCase(), process.env[z]);
}
}
// expand out camel case strings using another delimiter
if(this.conf.expand && this.conf.expand.delimiter) {
var o = {}, k, v, val;
for(k in this) {
val = this[k];
v = delimited(k, this.conf.expand.delimiter);
if(typeof this.conf.expand.transform === 'function') {
v = this.conf.expand.transform(v);
}
this.set(v, val);
delete this[k];
}
}
}
|
javascript
|
function load(match) {
match = match || this.conf.match;
for(var z in process.env) {
if(match instanceof RegExp) {
if(match.test(z)) {
this.set(z.toLowerCase(), process.env[z]);
}
}else{
this.set(z.toLowerCase(), process.env[z]);
}
}
// expand out camel case strings using another delimiter
if(this.conf.expand && this.conf.expand.delimiter) {
var o = {}, k, v, val;
for(k in this) {
val = this[k];
v = delimited(k, this.conf.expand.delimiter);
if(typeof this.conf.expand.transform === 'function') {
v = this.conf.expand.transform(v);
}
this.set(v, val);
delete this[k];
}
}
}
|
[
"function",
"load",
"(",
"match",
")",
"{",
"match",
"=",
"match",
"||",
"this",
".",
"conf",
".",
"match",
";",
"for",
"(",
"var",
"z",
"in",
"process",
".",
"env",
")",
"{",
"if",
"(",
"match",
"instanceof",
"RegExp",
")",
"{",
"if",
"(",
"match",
".",
"test",
"(",
"z",
")",
")",
"{",
"this",
".",
"set",
"(",
"z",
".",
"toLowerCase",
"(",
")",
",",
"process",
".",
"env",
"[",
"z",
"]",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"set",
"(",
"z",
".",
"toLowerCase",
"(",
")",
",",
"process",
".",
"env",
"[",
"z",
"]",
")",
";",
"}",
"}",
"// expand out camel case strings using another delimiter",
"if",
"(",
"this",
".",
"conf",
".",
"expand",
"&&",
"this",
".",
"conf",
".",
"expand",
".",
"delimiter",
")",
"{",
"var",
"o",
"=",
"{",
"}",
",",
"k",
",",
"v",
",",
"val",
";",
"for",
"(",
"k",
"in",
"this",
")",
"{",
"val",
"=",
"this",
"[",
"k",
"]",
";",
"v",
"=",
"delimited",
"(",
"k",
",",
"this",
".",
"conf",
".",
"expand",
".",
"delimiter",
")",
";",
"if",
"(",
"typeof",
"this",
".",
"conf",
".",
"expand",
".",
"transform",
"===",
"'function'",
")",
"{",
"v",
"=",
"this",
".",
"conf",
".",
"expand",
".",
"transform",
"(",
"v",
")",
";",
"}",
"this",
".",
"set",
"(",
"v",
",",
"val",
")",
";",
"delete",
"this",
"[",
"k",
"]",
";",
"}",
"}",
"}"
] |
Load variables from the environment into this
instance.
@param match A regular expression test determining
which variables to load.
|
[
"Load",
"variables",
"from",
"the",
"environment",
"into",
"this",
"instance",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L163-L189
|
52,716
|
cli-kit/cli-env
|
index.js
|
env
|
function env(root, env, escaping) {
walk(root, function visit(props) {
return (props.value instanceof String) || typeof props.value === 'string';
}, function transform(props) {
props.parent[props.name] = replace(props.value, env, escaping);
})
}
|
javascript
|
function env(root, env, escaping) {
walk(root, function visit(props) {
return (props.value instanceof String) || typeof props.value === 'string';
}, function transform(props) {
props.parent[props.name] = replace(props.value, env, escaping);
})
}
|
[
"function",
"env",
"(",
"root",
",",
"env",
",",
"escaping",
")",
"{",
"walk",
"(",
"root",
",",
"function",
"visit",
"(",
"props",
")",
"{",
"return",
"(",
"props",
".",
"value",
"instanceof",
"String",
")",
"||",
"typeof",
"props",
".",
"value",
"===",
"'string'",
";",
"}",
",",
"function",
"transform",
"(",
"props",
")",
"{",
"props",
".",
"parent",
"[",
"props",
".",
"name",
"]",
"=",
"replace",
"(",
"props",
".",
"value",
",",
"env",
",",
"escaping",
")",
";",
"}",
")",
"}"
] |
Performs recursive substitution of environment variables within
complex objects.
@param root The root object.
@param env An object containing environment variables
default is process.env.
@param escaping Whether escaped dollars indicate replacement
should be ignored.
|
[
"Performs",
"recursive",
"substitution",
"of",
"environment",
"variables",
"within",
"complex",
"objects",
"."
] |
53681525ce05205e42a77c1d5cc846b5f21d7fb1
|
https://github.com/cli-kit/cli-env/blob/53681525ce05205e42a77c1d5cc846b5f21d7fb1/index.js#L250-L256
|
52,717
|
origin1tech/chek
|
build/bump.js
|
isTruthy
|
function isTruthy(val) {
return val >= 0 && !isNaN(val) && val !== false
&& val !== undefined && val !== null && val !== '';
}
|
javascript
|
function isTruthy(val) {
return val >= 0 && !isNaN(val) && val !== false
&& val !== undefined && val !== null && val !== '';
}
|
[
"function",
"isTruthy",
"(",
"val",
")",
"{",
"return",
"val",
">=",
"0",
"&&",
"!",
"isNaN",
"(",
"val",
")",
"&&",
"val",
"!==",
"false",
"&&",
"val",
"!==",
"undefined",
"&&",
"val",
"!==",
"null",
"&&",
"val",
"!==",
"''",
";",
"}"
] |
Check for truthy value.
|
[
"Check",
"for",
"truthy",
"value",
"."
] |
6bc3ab0ac36126cc7918a244a606009749897b2e
|
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/build/bump.js#L28-L31
|
52,718
|
origin1tech/chek
|
build/bump.js
|
parseVer
|
function parseVer(idx, set, setting) {
var parsed = tryParseInt(idx);
if (parsed === false || parsed < 0 || isNaN(parsed))
return false;
if (set)
return parseVer(argv[parsed + 1], null, true);
if (setting)
return parsed;
return true;
}
|
javascript
|
function parseVer(idx, set, setting) {
var parsed = tryParseInt(idx);
if (parsed === false || parsed < 0 || isNaN(parsed))
return false;
if (set)
return parseVer(argv[parsed + 1], null, true);
if (setting)
return parsed;
return true;
}
|
[
"function",
"parseVer",
"(",
"idx",
",",
"set",
",",
"setting",
")",
"{",
"var",
"parsed",
"=",
"tryParseInt",
"(",
"idx",
")",
";",
"if",
"(",
"parsed",
"===",
"false",
"||",
"parsed",
"<",
"0",
"||",
"isNaN",
"(",
"parsed",
")",
")",
"return",
"false",
";",
"if",
"(",
"set",
")",
"return",
"parseVer",
"(",
"argv",
"[",
"parsed",
"+",
"1",
"]",
",",
"null",
",",
"true",
")",
";",
"if",
"(",
"setting",
")",
"return",
"parsed",
";",
"return",
"true",
";",
"}"
] |
Parse the version from command line.
|
[
"Parse",
"the",
"version",
"from",
"command",
"line",
"."
] |
6bc3ab0ac36126cc7918a244a606009749897b2e
|
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/build/bump.js#L43-L52
|
52,719
|
origin1tech/chek
|
build/bump.js
|
setVersion
|
function setVersion(type, ver) {
const idx = verMap[type];
let cur = verArr[idx];
let next = cur + 1;
if (isTruthy(ver))
next = ver;
if (isTruthy(ver)) {
verArr[idx] = ver;
}
else {
if (type === 'patch') {
if (next > maxPatch) {
// zero current stepping
// up to minor.
verArr[idx] = 0;
return setVersion('minor');
}
else {
verArr[idx] = next;
}
}
else if (type === 'minor') {
if (next > maxMinor) {
// zero current stepping
// up to major.
verArr[idx] = 0;
return setVersion('major');
}
else {
verArr[idx] = next;
}
}
else {
verArr[idx] = next;
}
}
}
|
javascript
|
function setVersion(type, ver) {
const idx = verMap[type];
let cur = verArr[idx];
let next = cur + 1;
if (isTruthy(ver))
next = ver;
if (isTruthy(ver)) {
verArr[idx] = ver;
}
else {
if (type === 'patch') {
if (next > maxPatch) {
// zero current stepping
// up to minor.
verArr[idx] = 0;
return setVersion('minor');
}
else {
verArr[idx] = next;
}
}
else if (type === 'minor') {
if (next > maxMinor) {
// zero current stepping
// up to major.
verArr[idx] = 0;
return setVersion('major');
}
else {
verArr[idx] = next;
}
}
else {
verArr[idx] = next;
}
}
}
|
[
"function",
"setVersion",
"(",
"type",
",",
"ver",
")",
"{",
"const",
"idx",
"=",
"verMap",
"[",
"type",
"]",
";",
"let",
"cur",
"=",
"verArr",
"[",
"idx",
"]",
";",
"let",
"next",
"=",
"cur",
"+",
"1",
";",
"if",
"(",
"isTruthy",
"(",
"ver",
")",
")",
"next",
"=",
"ver",
";",
"if",
"(",
"isTruthy",
"(",
"ver",
")",
")",
"{",
"verArr",
"[",
"idx",
"]",
"=",
"ver",
";",
"}",
"else",
"{",
"if",
"(",
"type",
"===",
"'patch'",
")",
"{",
"if",
"(",
"next",
">",
"maxPatch",
")",
"{",
"// zero current stepping",
"// up to minor.",
"verArr",
"[",
"idx",
"]",
"=",
"0",
";",
"return",
"setVersion",
"(",
"'minor'",
")",
";",
"}",
"else",
"{",
"verArr",
"[",
"idx",
"]",
"=",
"next",
";",
"}",
"}",
"else",
"if",
"(",
"type",
"===",
"'minor'",
")",
"{",
"if",
"(",
"next",
">",
"maxMinor",
")",
"{",
"// zero current stepping",
"// up to major.",
"verArr",
"[",
"idx",
"]",
"=",
"0",
";",
"return",
"setVersion",
"(",
"'major'",
")",
";",
"}",
"else",
"{",
"verArr",
"[",
"idx",
"]",
"=",
"next",
";",
"}",
"}",
"else",
"{",
"verArr",
"[",
"idx",
"]",
"=",
"next",
";",
"}",
"}",
"}"
] |
Recursive for setting version.
|
[
"Recursive",
"for",
"setting",
"version",
"."
] |
6bc3ab0ac36126cc7918a244a606009749897b2e
|
https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/build/bump.js#L62-L103
|
52,720
|
Mike96Angelo/CompileIt
|
lib/utils.js
|
repeat
|
function repeat(str, n) {
var result = '';
for (var i = 0; i < n; i++) {
result += str;
}
return result;
}
|
javascript
|
function repeat(str, n) {
var result = '';
for (var i = 0; i < n; i++) {
result += str;
}
return result;
}
|
[
"function",
"repeat",
"(",
"str",
",",
"n",
")",
"{",
"var",
"result",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"result",
"+=",
"str",
";",
"}",
"return",
"result",
";",
"}"
] |
Repeats a string `n` time.
@param {String} str String to be repeated.
@param {Number} n Number of times to repeat.
|
[
"Repeats",
"a",
"string",
"n",
"time",
"."
] |
7c2e79d67d7d25fcfe66aaf25648afece804b5c4
|
https://github.com/Mike96Angelo/CompileIt/blob/7c2e79d67d7d25fcfe66aaf25648afece804b5c4/lib/utils.js#L32-L40
|
52,721
|
Mike96Angelo/CompileIt
|
lib/utils.js
|
bufferSlice
|
function bufferSlice(code, range, format) {
format = format || varThrough;
return JSON.stringify(
code.slice(Math.max(0, code.index - range), code.index)
)
.slice(1, -1) +
format(
JSON.stringify(code.charAt(code.index) || 'EOF')
.slice(1, -1)
) +
JSON.stringify(
code.slice(
code.index + 1,
Math.min(code.length, code.index + 1 + range)
)
)
.slice(1, -1);
}
|
javascript
|
function bufferSlice(code, range, format) {
format = format || varThrough;
return JSON.stringify(
code.slice(Math.max(0, code.index - range), code.index)
)
.slice(1, -1) +
format(
JSON.stringify(code.charAt(code.index) || 'EOF')
.slice(1, -1)
) +
JSON.stringify(
code.slice(
code.index + 1,
Math.min(code.length, code.index + 1 + range)
)
)
.slice(1, -1);
}
|
[
"function",
"bufferSlice",
"(",
"code",
",",
"range",
",",
"format",
")",
"{",
"format",
"=",
"format",
"||",
"varThrough",
";",
"return",
"JSON",
".",
"stringify",
"(",
"code",
".",
"slice",
"(",
"Math",
".",
"max",
"(",
"0",
",",
"code",
".",
"index",
"-",
"range",
")",
",",
"code",
".",
"index",
")",
")",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
"+",
"format",
"(",
"JSON",
".",
"stringify",
"(",
"code",
".",
"charAt",
"(",
"code",
".",
"index",
")",
"||",
"'EOF'",
")",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
")",
"+",
"JSON",
".",
"stringify",
"(",
"code",
".",
"slice",
"(",
"code",
".",
"index",
"+",
"1",
",",
"Math",
".",
"min",
"(",
"code",
".",
"length",
",",
"code",
".",
"index",
"+",
"1",
"+",
"range",
")",
")",
")",
".",
"slice",
"(",
"1",
",",
"-",
"1",
")",
";",
"}"
] |
Stringified CodeBuffer slice.
@param {CodeBuffer} code CodeBuffer to slice.
@param {Number} range Range to slice before and after `code.index`.
|
[
"Stringified",
"CodeBuffer",
"slice",
"."
] |
7c2e79d67d7d25fcfe66aaf25648afece804b5c4
|
https://github.com/Mike96Angelo/CompileIt/blob/7c2e79d67d7d25fcfe66aaf25648afece804b5c4/lib/utils.js#L57-L74
|
52,722
|
Kashio/fspvr
|
index.js
|
function(segment, strict) {
if (!_.isString(segment)) {
throw new TypeError('segment must be of type string');
}
if (!_.isBoolean(strict)) {
strict = true;
}
segment = segment.replace(illegalCharacters, '');
if (strict && osType === "Windows_NT") {
segment = segment.replace(illegalNames, '');
while (illegalTrailingCharacters.test(segment)) {
segment = segment.replace(illegalTrailingCharacters, '');
}
}
return segment;
}
|
javascript
|
function(segment, strict) {
if (!_.isString(segment)) {
throw new TypeError('segment must be of type string');
}
if (!_.isBoolean(strict)) {
strict = true;
}
segment = segment.replace(illegalCharacters, '');
if (strict && osType === "Windows_NT") {
segment = segment.replace(illegalNames, '');
while (illegalTrailingCharacters.test(segment)) {
segment = segment.replace(illegalTrailingCharacters, '');
}
}
return segment;
}
|
[
"function",
"(",
"segment",
",",
"strict",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"segment",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'segment must be of type string'",
")",
";",
"}",
"if",
"(",
"!",
"_",
".",
"isBoolean",
"(",
"strict",
")",
")",
"{",
"strict",
"=",
"true",
";",
"}",
"segment",
"=",
"segment",
".",
"replace",
"(",
"illegalCharacters",
",",
"''",
")",
";",
"if",
"(",
"strict",
"&&",
"osType",
"===",
"\"Windows_NT\"",
")",
"{",
"segment",
"=",
"segment",
".",
"replace",
"(",
"illegalNames",
",",
"''",
")",
";",
"while",
"(",
"illegalTrailingCharacters",
".",
"test",
"(",
"segment",
")",
")",
"{",
"segment",
"=",
"segment",
".",
"replace",
"(",
"illegalTrailingCharacters",
",",
"''",
")",
";",
"}",
"}",
"return",
"segment",
";",
"}"
] |
Reformat fs segment to be valid
@param {String} segment
@param {Boolean=true} strict
@return {String}
|
[
"Reformat",
"fs",
"segment",
"to",
"be",
"valid"
] |
3777dedc7f25ec6d596b6011a954724e77cb0258
|
https://github.com/Kashio/fspvr/blob/3777dedc7f25ec6d596b6011a954724e77cb0258/index.js#L35-L50
|
|
52,723
|
Kashio/fspvr
|
index.js
|
function(fsPath, strict) {
if (!_.isString(fsPath)) {
throw new TypeError('path must be of type string');
}
var segments = _.filter(fsPath.substring(fsPath.indexOf(path.sep) + 1).split(path.sep), function(segment) {
return segment !== '';
});
for (var i = 0; i < segments.length; i++) {
var replaceWith = module.exports.reformatSegment(segments[i], strict);
var find = util.format('%s%s', replaceWith === '' ? path.sep : '', segments[i]);
fsPath = fsPath.replace(find, replaceWith);
}
return fsPath;
}
|
javascript
|
function(fsPath, strict) {
if (!_.isString(fsPath)) {
throw new TypeError('path must be of type string');
}
var segments = _.filter(fsPath.substring(fsPath.indexOf(path.sep) + 1).split(path.sep), function(segment) {
return segment !== '';
});
for (var i = 0; i < segments.length; i++) {
var replaceWith = module.exports.reformatSegment(segments[i], strict);
var find = util.format('%s%s', replaceWith === '' ? path.sep : '', segments[i]);
fsPath = fsPath.replace(find, replaceWith);
}
return fsPath;
}
|
[
"function",
"(",
"fsPath",
",",
"strict",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"fsPath",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'path must be of type string'",
")",
";",
"}",
"var",
"segments",
"=",
"_",
".",
"filter",
"(",
"fsPath",
".",
"substring",
"(",
"fsPath",
".",
"indexOf",
"(",
"path",
".",
"sep",
")",
"+",
"1",
")",
".",
"split",
"(",
"path",
".",
"sep",
")",
",",
"function",
"(",
"segment",
")",
"{",
"return",
"segment",
"!==",
"''",
";",
"}",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"segments",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"replaceWith",
"=",
"module",
".",
"exports",
".",
"reformatSegment",
"(",
"segments",
"[",
"i",
"]",
",",
"strict",
")",
";",
"var",
"find",
"=",
"util",
".",
"format",
"(",
"'%s%s'",
",",
"replaceWith",
"===",
"''",
"?",
"path",
".",
"sep",
":",
"''",
",",
"segments",
"[",
"i",
"]",
")",
";",
"fsPath",
"=",
"fsPath",
".",
"replace",
"(",
"find",
",",
"replaceWith",
")",
";",
"}",
"return",
"fsPath",
";",
"}"
] |
Reformat fs path to be valid
@param {String} fsPath
@param {Boolean=true} strict
@return {String}
|
[
"Reformat",
"fs",
"path",
"to",
"be",
"valid"
] |
3777dedc7f25ec6d596b6011a954724e77cb0258
|
https://github.com/Kashio/fspvr/blob/3777dedc7f25ec6d596b6011a954724e77cb0258/index.js#L58-L71
|
|
52,724
|
Kashio/fspvr
|
index.js
|
function(fsPath, strict) {
if (!_.isString(fsPath)) {
throw new TypeError('path must be of type string');
}
return fsPath === module.exports.reformatPath(fsPath, strict);
}
|
javascript
|
function(fsPath, strict) {
if (!_.isString(fsPath)) {
throw new TypeError('path must be of type string');
}
return fsPath === module.exports.reformatPath(fsPath, strict);
}
|
[
"function",
"(",
"fsPath",
",",
"strict",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"fsPath",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'path must be of type string'",
")",
";",
"}",
"return",
"fsPath",
"===",
"module",
".",
"exports",
".",
"reformatPath",
"(",
"fsPath",
",",
"strict",
")",
";",
"}"
] |
Checks if fs path is valid
@param {String} fsPath
@param {Boolean=true} strict
@return {Boolean}
|
[
"Checks",
"if",
"fs",
"path",
"is",
"valid"
] |
3777dedc7f25ec6d596b6011a954724e77cb0258
|
https://github.com/Kashio/fspvr/blob/3777dedc7f25ec6d596b6011a954724e77cb0258/index.js#L79-L84
|
|
52,725
|
Kashio/fspvr
|
index.js
|
function(segment, strict) {
if (!_.isString(segment)) {
throw new TypeError('segment must be of type string');
}
return segment === module.exports.reformatSegment(segment, strict);
}
|
javascript
|
function(segment, strict) {
if (!_.isString(segment)) {
throw new TypeError('segment must be of type string');
}
return segment === module.exports.reformatSegment(segment, strict);
}
|
[
"function",
"(",
"segment",
",",
"strict",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isString",
"(",
"segment",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'segment must be of type string'",
")",
";",
"}",
"return",
"segment",
"===",
"module",
".",
"exports",
".",
"reformatSegment",
"(",
"segment",
",",
"strict",
")",
";",
"}"
] |
Checks if fs segment is valid
@param {String} segment
@param {Boolean=true} strict
@return {Boolean}
|
[
"Checks",
"if",
"fs",
"segment",
"is",
"valid"
] |
3777dedc7f25ec6d596b6011a954724e77cb0258
|
https://github.com/Kashio/fspvr/blob/3777dedc7f25ec6d596b6011a954724e77cb0258/index.js#L92-L97
|
|
52,726
|
Ivshti/named-queue
|
index.js
|
update
|
function update() {
while (waiting.length && count < concurrency) (function() {
var t = waiting.shift()
if (inProg[t.task.id]) {
inProg[t.task.id].push(t.cb)
return
} else {
inProg[t.task.id] = [t.cb]
count++
processor(t.task, function() {
var args = arguments
if (!inProg[t.task.id]) return // probably callback called twice
count--
inProg[t.task.id].forEach(function(cb) { cb.apply(null, args) })
delete inProg[t.task.id]
setImmediate(update)
})
}
})()
}
|
javascript
|
function update() {
while (waiting.length && count < concurrency) (function() {
var t = waiting.shift()
if (inProg[t.task.id]) {
inProg[t.task.id].push(t.cb)
return
} else {
inProg[t.task.id] = [t.cb]
count++
processor(t.task, function() {
var args = arguments
if (!inProg[t.task.id]) return // probably callback called twice
count--
inProg[t.task.id].forEach(function(cb) { cb.apply(null, args) })
delete inProg[t.task.id]
setImmediate(update)
})
}
})()
}
|
[
"function",
"update",
"(",
")",
"{",
"while",
"(",
"waiting",
".",
"length",
"&&",
"count",
"<",
"concurrency",
")",
"(",
"function",
"(",
")",
"{",
"var",
"t",
"=",
"waiting",
".",
"shift",
"(",
")",
"if",
"(",
"inProg",
"[",
"t",
".",
"task",
".",
"id",
"]",
")",
"{",
"inProg",
"[",
"t",
".",
"task",
".",
"id",
"]",
".",
"push",
"(",
"t",
".",
"cb",
")",
"return",
"}",
"else",
"{",
"inProg",
"[",
"t",
".",
"task",
".",
"id",
"]",
"=",
"[",
"t",
".",
"cb",
"]",
"count",
"++",
"processor",
"(",
"t",
".",
"task",
",",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"arguments",
"if",
"(",
"!",
"inProg",
"[",
"t",
".",
"task",
".",
"id",
"]",
")",
"return",
"// probably callback called twice",
"count",
"--",
"inProg",
"[",
"t",
".",
"task",
".",
"id",
"]",
".",
"forEach",
"(",
"function",
"(",
"cb",
")",
"{",
"cb",
".",
"apply",
"(",
"null",
",",
"args",
")",
"}",
")",
"delete",
"inProg",
"[",
"t",
".",
"task",
".",
"id",
"]",
"setImmediate",
"(",
"update",
")",
"}",
")",
"}",
"}",
")",
"(",
")",
"}"
] |
var paused = false
|
[
"var",
"paused",
"=",
"false"
] |
3dfd103466a869a3c6dd23012813ac11cb4fe906
|
https://github.com/Ivshti/named-queue/blob/3dfd103466a869a3c6dd23012813ac11cb4fe906/index.js#L11-L34
|
52,727
|
Nazariglez/perenquen
|
lib/pixi/src/core/math/shapes/Circle.js
|
Circle
|
function Circle(x, y, radius)
{
/**
* @member {number}
* @default 0
*/
this.x = x || 0;
/**
* @member {number}
* @default 0
*/
this.y = y || 0;
/**
* @member {number}
* @default 0
*/
this.radius = radius || 0;
/**
* The type of the object, mainly used to avoid `instanceof` checks
*
* @member {number}
*/
this.type = CONST.SHAPES.CIRC;
}
|
javascript
|
function Circle(x, y, radius)
{
/**
* @member {number}
* @default 0
*/
this.x = x || 0;
/**
* @member {number}
* @default 0
*/
this.y = y || 0;
/**
* @member {number}
* @default 0
*/
this.radius = radius || 0;
/**
* The type of the object, mainly used to avoid `instanceof` checks
*
* @member {number}
*/
this.type = CONST.SHAPES.CIRC;
}
|
[
"function",
"Circle",
"(",
"x",
",",
"y",
",",
"radius",
")",
"{",
"/**\n * @member {number}\n * @default 0\n */",
"this",
".",
"x",
"=",
"x",
"||",
"0",
";",
"/**\n * @member {number}\n * @default 0\n */",
"this",
".",
"y",
"=",
"y",
"||",
"0",
";",
"/**\n * @member {number}\n * @default 0\n */",
"this",
".",
"radius",
"=",
"radius",
"||",
"0",
";",
"/**\n * The type of the object, mainly used to avoid `instanceof` checks\n *\n * @member {number}\n */",
"this",
".",
"type",
"=",
"CONST",
".",
"SHAPES",
".",
"CIRC",
";",
"}"
] |
The Circle object can be used to specify a hit area for displayObjects
@class
@memberof PIXI
@param x {number} The X coordinate of the center of this circle
@param y {number} The Y coordinate of the center of this circle
@param radius {number} The radius of the circle
|
[
"The",
"Circle",
"object",
"can",
"be",
"used",
"to",
"specify",
"a",
"hit",
"area",
"for",
"displayObjects"
] |
e023964d05afeefebdcac4e2044819fdfa3899ae
|
https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/core/math/shapes/Circle.js#L13-L39
|
52,728
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (words, options) {
var puzzle = [], i, j, len;
// initialize the puzzle with blanks
for (i = 0; i < options.height; i++) {
puzzle.push([]);
for (j = 0; j < options.width; j++) {
puzzle[i].push('');
}
}
// add each word into the puzzle one at a time
for (i = 0, len = words.length; i < len; i++) {
if (!placeWordInPuzzle(puzzle, options, words[i])) {
// if a word didn't fit in the puzzle, give up
return null;
}
}
// return the puzzle
return puzzle;
}
|
javascript
|
function (words, options) {
var puzzle = [], i, j, len;
// initialize the puzzle with blanks
for (i = 0; i < options.height; i++) {
puzzle.push([]);
for (j = 0; j < options.width; j++) {
puzzle[i].push('');
}
}
// add each word into the puzzle one at a time
for (i = 0, len = words.length; i < len; i++) {
if (!placeWordInPuzzle(puzzle, options, words[i])) {
// if a word didn't fit in the puzzle, give up
return null;
}
}
// return the puzzle
return puzzle;
}
|
[
"function",
"(",
"words",
",",
"options",
")",
"{",
"var",
"puzzle",
"=",
"[",
"]",
",",
"i",
",",
"j",
",",
"len",
";",
"// initialize the puzzle with blanks",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"height",
";",
"i",
"++",
")",
"{",
"puzzle",
".",
"push",
"(",
"[",
"]",
")",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"options",
".",
"width",
";",
"j",
"++",
")",
"{",
"puzzle",
"[",
"i",
"]",
".",
"push",
"(",
"''",
")",
";",
"}",
"}",
"// add each word into the puzzle one at a time",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"words",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"placeWordInPuzzle",
"(",
"puzzle",
",",
"options",
",",
"words",
"[",
"i",
"]",
")",
")",
"{",
"// if a word didn't fit in the puzzle, give up",
"return",
"null",
";",
"}",
"}",
"// return the puzzle",
"return",
"puzzle",
";",
"}"
] |
Initializes the puzzle and places words in the puzzle one at a time.
Returns either a valid puzzle with all of the words or null if a valid
puzzle was not found.
@param {[String]} words: The list of words to fit into the puzzle
@param {[Options]} options: The options to use when filling the puzzle
|
[
"Initializes",
"the",
"puzzle",
"and",
"places",
"words",
"in",
"the",
"puzzle",
"one",
"at",
"a",
"time",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L82-L100
|
|
52,729
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (puzzle, options, word) {
// find all of the best locations where this word would fit
var locations = findBestLocations(puzzle, options, word);
if (locations.length === 0) {
return false;
}
// select a location at random and place the word there
var sel = locations[Math.floor(Math.random() * locations.length)];
placeWord(puzzle, word, sel.x, sel.y, orientations[sel.orientation]);
return true;
}
|
javascript
|
function (puzzle, options, word) {
// find all of the best locations where this word would fit
var locations = findBestLocations(puzzle, options, word);
if (locations.length === 0) {
return false;
}
// select a location at random and place the word there
var sel = locations[Math.floor(Math.random() * locations.length)];
placeWord(puzzle, word, sel.x, sel.y, orientations[sel.orientation]);
return true;
}
|
[
"function",
"(",
"puzzle",
",",
"options",
",",
"word",
")",
"{",
"// find all of the best locations where this word would fit",
"var",
"locations",
"=",
"findBestLocations",
"(",
"puzzle",
",",
"options",
",",
"word",
")",
";",
"if",
"(",
"locations",
".",
"length",
"===",
"0",
")",
"{",
"return",
"false",
";",
"}",
"// select a location at random and place the word there",
"var",
"sel",
"=",
"locations",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"locations",
".",
"length",
")",
"]",
";",
"placeWord",
"(",
"puzzle",
",",
"word",
",",
"sel",
".",
"x",
",",
"sel",
".",
"y",
",",
"orientations",
"[",
"sel",
".",
"orientation",
"]",
")",
";",
"return",
"true",
";",
"}"
] |
Adds the specified word to the puzzle by finding all of the possible
locations where the word will fit and then randomly selecting one. Options
controls whether or not word overlap should be maximized.
Returns true if the word was successfully placed, false otherwise.
@param {[[String]]} puzzle: The current state of the puzzle
@param {[Options]} options: The options to use when filling the puzzle
@param {String} word: The word to fit into the puzzle.
|
[
"Adds",
"the",
"specified",
"word",
"to",
"the",
"puzzle",
"by",
"finding",
"all",
"of",
"the",
"possible",
"locations",
"where",
"the",
"word",
"will",
"fit",
"and",
"then",
"randomly",
"selecting",
"one",
".",
"Options",
"controls",
"whether",
"or",
"not",
"word",
"overlap",
"should",
"be",
"maximized",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L112-L122
|
|
52,730
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (puzzle, options, word) {
var locations = [], height = options.height, width = options.width, wordLength = word.length, maxOverlap = 0; // we'll start looking at overlap = 0
// loop through all of the possible orientations at this position
for (var k = 0, len = options.orientations.length; k < len; k++) {
var orientation = options.orientations[k], check = checkOrientations[orientation], next = orientations[orientation], skipTo = skipOrientations[orientation], x = 0, y = 0;
// loop through every position on the board
while (y < height) {
// see if this orientation is even possible at this location
if (check(x, y, height, width, wordLength)) {
// determine if the word fits at the current position
var overlap = calcOverlap(word, puzzle, x, y, next);
// if the overlap was bigger than previous overlaps that we've seen
if (overlap >= maxOverlap || (!options.preferOverlap && overlap > -1)) {
maxOverlap = overlap;
locations.push({ x: x, y: y, orientation: orientation, overlap: overlap });
}
x++;
if (x >= width) {
x = 0;
y++;
}
}
else {
// if current cell is invalid, then skip to the next cell where
// this orientation is possible. this greatly reduces the number
// of checks that we have to do overall
var nextPossible = skipTo(x, y, wordLength);
x = nextPossible.x;
y = nextPossible.y;
}
}
}
// finally prune down all of the possible locations we found by
// only using the ones with the maximum overlap that we calculated
return options.preferOverlap ?
pruneLocations(locations, maxOverlap) :
locations;
}
|
javascript
|
function (puzzle, options, word) {
var locations = [], height = options.height, width = options.width, wordLength = word.length, maxOverlap = 0; // we'll start looking at overlap = 0
// loop through all of the possible orientations at this position
for (var k = 0, len = options.orientations.length; k < len; k++) {
var orientation = options.orientations[k], check = checkOrientations[orientation], next = orientations[orientation], skipTo = skipOrientations[orientation], x = 0, y = 0;
// loop through every position on the board
while (y < height) {
// see if this orientation is even possible at this location
if (check(x, y, height, width, wordLength)) {
// determine if the word fits at the current position
var overlap = calcOverlap(word, puzzle, x, y, next);
// if the overlap was bigger than previous overlaps that we've seen
if (overlap >= maxOverlap || (!options.preferOverlap && overlap > -1)) {
maxOverlap = overlap;
locations.push({ x: x, y: y, orientation: orientation, overlap: overlap });
}
x++;
if (x >= width) {
x = 0;
y++;
}
}
else {
// if current cell is invalid, then skip to the next cell where
// this orientation is possible. this greatly reduces the number
// of checks that we have to do overall
var nextPossible = skipTo(x, y, wordLength);
x = nextPossible.x;
y = nextPossible.y;
}
}
}
// finally prune down all of the possible locations we found by
// only using the ones with the maximum overlap that we calculated
return options.preferOverlap ?
pruneLocations(locations, maxOverlap) :
locations;
}
|
[
"function",
"(",
"puzzle",
",",
"options",
",",
"word",
")",
"{",
"var",
"locations",
"=",
"[",
"]",
",",
"height",
"=",
"options",
".",
"height",
",",
"width",
"=",
"options",
".",
"width",
",",
"wordLength",
"=",
"word",
".",
"length",
",",
"maxOverlap",
"=",
"0",
";",
"// we'll start looking at overlap = 0",
"// loop through all of the possible orientations at this position",
"for",
"(",
"var",
"k",
"=",
"0",
",",
"len",
"=",
"options",
".",
"orientations",
".",
"length",
";",
"k",
"<",
"len",
";",
"k",
"++",
")",
"{",
"var",
"orientation",
"=",
"options",
".",
"orientations",
"[",
"k",
"]",
",",
"check",
"=",
"checkOrientations",
"[",
"orientation",
"]",
",",
"next",
"=",
"orientations",
"[",
"orientation",
"]",
",",
"skipTo",
"=",
"skipOrientations",
"[",
"orientation",
"]",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
";",
"// loop through every position on the board",
"while",
"(",
"y",
"<",
"height",
")",
"{",
"// see if this orientation is even possible at this location",
"if",
"(",
"check",
"(",
"x",
",",
"y",
",",
"height",
",",
"width",
",",
"wordLength",
")",
")",
"{",
"// determine if the word fits at the current position",
"var",
"overlap",
"=",
"calcOverlap",
"(",
"word",
",",
"puzzle",
",",
"x",
",",
"y",
",",
"next",
")",
";",
"// if the overlap was bigger than previous overlaps that we've seen",
"if",
"(",
"overlap",
">=",
"maxOverlap",
"||",
"(",
"!",
"options",
".",
"preferOverlap",
"&&",
"overlap",
">",
"-",
"1",
")",
")",
"{",
"maxOverlap",
"=",
"overlap",
";",
"locations",
".",
"push",
"(",
"{",
"x",
":",
"x",
",",
"y",
":",
"y",
",",
"orientation",
":",
"orientation",
",",
"overlap",
":",
"overlap",
"}",
")",
";",
"}",
"x",
"++",
";",
"if",
"(",
"x",
">=",
"width",
")",
"{",
"x",
"=",
"0",
";",
"y",
"++",
";",
"}",
"}",
"else",
"{",
"// if current cell is invalid, then skip to the next cell where",
"// this orientation is possible. this greatly reduces the number",
"// of checks that we have to do overall",
"var",
"nextPossible",
"=",
"skipTo",
"(",
"x",
",",
"y",
",",
"wordLength",
")",
";",
"x",
"=",
"nextPossible",
".",
"x",
";",
"y",
"=",
"nextPossible",
".",
"y",
";",
"}",
"}",
"}",
"// finally prune down all of the possible locations we found by",
"// only using the ones with the maximum overlap that we calculated",
"return",
"options",
".",
"preferOverlap",
"?",
"pruneLocations",
"(",
"locations",
",",
"maxOverlap",
")",
":",
"locations",
";",
"}"
] |
Iterates through the puzzle and determines all of the locations where
the word will fit. Options determines if overlap should be maximized or
not.
Returns a list of location objects which contain an x,y cooridinate
indicating the start of the word, the orientation of the word, and the
number of letters that overlapped with existing letter.
@param {[[String]]} puzzle: The current state of the puzzle
@param {[Options]} options: The options to use when filling the puzzle
@param {String} word: The word to fit into the puzzle.
|
[
"Iterates",
"through",
"the",
"puzzle",
"and",
"determines",
"all",
"of",
"the",
"locations",
"where",
"the",
"word",
"will",
"fit",
".",
"Options",
"determines",
"if",
"overlap",
"should",
"be",
"maximized",
"or",
"not",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L136-L173
|
|
52,731
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (word, puzzle, x, y, fnGetSquare) {
var overlap = 0;
// traverse the squares to determine if the word fits
for (var i = 0, len = word.length; i < len; i++) {
var next = fnGetSquare(x, y, i), square = puzzle[next.y][next.x];
// if the puzzle square already contains the letter we
// are looking for, then count it as an overlap square
if (square === word[i]) {
overlap++;
}
else if (square !== '') {
return -1;
}
}
// if the entire word is overlapping, skip it to ensure words aren't
// hidden in other words
return overlap;
}
|
javascript
|
function (word, puzzle, x, y, fnGetSquare) {
var overlap = 0;
// traverse the squares to determine if the word fits
for (var i = 0, len = word.length; i < len; i++) {
var next = fnGetSquare(x, y, i), square = puzzle[next.y][next.x];
// if the puzzle square already contains the letter we
// are looking for, then count it as an overlap square
if (square === word[i]) {
overlap++;
}
else if (square !== '') {
return -1;
}
}
// if the entire word is overlapping, skip it to ensure words aren't
// hidden in other words
return overlap;
}
|
[
"function",
"(",
"word",
",",
"puzzle",
",",
"x",
",",
"y",
",",
"fnGetSquare",
")",
"{",
"var",
"overlap",
"=",
"0",
";",
"// traverse the squares to determine if the word fits",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"word",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"next",
"=",
"fnGetSquare",
"(",
"x",
",",
"y",
",",
"i",
")",
",",
"square",
"=",
"puzzle",
"[",
"next",
".",
"y",
"]",
"[",
"next",
".",
"x",
"]",
";",
"// if the puzzle square already contains the letter we",
"// are looking for, then count it as an overlap square",
"if",
"(",
"square",
"===",
"word",
"[",
"i",
"]",
")",
"{",
"overlap",
"++",
";",
"}",
"else",
"if",
"(",
"square",
"!==",
"''",
")",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"// if the entire word is overlapping, skip it to ensure words aren't",
"// hidden in other words",
"return",
"overlap",
";",
"}"
] |
Determines whether or not a particular word fits in a particular
orientation within the puzzle.
Returns the number of letters overlapped with existing words if the word
fits in the specified position, -1 if the word does not fit.
@param {String} word: The word to fit into the puzzle.
@param {[[String]]} puzzle: The current state of the puzzle
@param {int} x: The x position to check
@param {int} y: The y position to check
@param {function} fnGetSquare: Function that returns the next square
|
[
"Determines",
"whether",
"or",
"not",
"a",
"particular",
"word",
"fits",
"in",
"a",
"particular",
"orientation",
"within",
"the",
"puzzle",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L187-L204
|
|
52,732
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (locations, overlap) {
var pruned = [];
for (var i = 0, len = locations.length; i < len; i++) {
if (locations[i].overlap >= overlap) {
pruned.push(locations[i]);
}
}
return pruned;
}
|
javascript
|
function (locations, overlap) {
var pruned = [];
for (var i = 0, len = locations.length; i < len; i++) {
if (locations[i].overlap >= overlap) {
pruned.push(locations[i]);
}
}
return pruned;
}
|
[
"function",
"(",
"locations",
",",
"overlap",
")",
"{",
"var",
"pruned",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"locations",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"locations",
"[",
"i",
"]",
".",
"overlap",
">=",
"overlap",
")",
"{",
"pruned",
".",
"push",
"(",
"locations",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"pruned",
";",
"}"
] |
If overlap maximization was indicated, this function is used to prune the
list of valid locations down to the ones that contain the maximum overlap
that was previously calculated.
Returns the pruned set of locations.
@param {[Location]} locations: The set of locations to prune
@param {int} overlap: The required level of overlap
|
[
"If",
"overlap",
"maximization",
"was",
"indicated",
"this",
"function",
"is",
"used",
"to",
"prune",
"the",
"list",
"of",
"valid",
"locations",
"down",
"to",
"the",
"ones",
"that",
"contain",
"the",
"maximum",
"overlap",
"that",
"was",
"previously",
"calculated",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L215-L223
|
|
52,733
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (puzzle) {
for (var i = 0, height = puzzle.length; i < height; i++) {
var row = puzzle[i];
for (var j = 0, width = row.length; j < width; j++) {
if (!puzzle[i][j]) {
var randomLetter = Math.floor(Math.random() * letters.length);
puzzle[i][j] = letters[randomLetter];
}
}
}
}
|
javascript
|
function (puzzle) {
for (var i = 0, height = puzzle.length; i < height; i++) {
var row = puzzle[i];
for (var j = 0, width = row.length; j < width; j++) {
if (!puzzle[i][j]) {
var randomLetter = Math.floor(Math.random() * letters.length);
puzzle[i][j] = letters[randomLetter];
}
}
}
}
|
[
"function",
"(",
"puzzle",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"height",
"=",
"puzzle",
".",
"length",
";",
"i",
"<",
"height",
";",
"i",
"++",
")",
"{",
"var",
"row",
"=",
"puzzle",
"[",
"i",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"width",
"=",
"row",
".",
"length",
";",
"j",
"<",
"width",
";",
"j",
"++",
")",
"{",
"if",
"(",
"!",
"puzzle",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"{",
"var",
"randomLetter",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"letters",
".",
"length",
")",
";",
"puzzle",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"letters",
"[",
"randomLetter",
"]",
";",
"}",
"}",
"}",
"}"
] |
Fills in any empty spaces in the puzzle with random letters.
@param {[[String]]} puzzle: The current state of the puzzle
@api public
|
[
"Fills",
"in",
"any",
"empty",
"spaces",
"in",
"the",
"puzzle",
"with",
"random",
"letters",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L309-L319
|
|
52,734
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (puzzle, words) {
var options = {
height: puzzle.length,
width: puzzle[0].length,
orientations: allOrientations,
preferOverlap: true
}, found = [], notFound = [];
for (var i = 0, len = words.length; i < len; i++) {
var word = words[i], locations = findBestLocations(puzzle, options, word);
if (locations.length > 0 && locations[0].overlap === word.length) {
if (locations.length > 0 && locations[0].overlap === word.length) {
locations[0].word = word;
found.push(locations[0]);
}
else {
notFound.push(word);
}
}
}
return { found: found, notFound: notFound };
}
|
javascript
|
function (puzzle, words) {
var options = {
height: puzzle.length,
width: puzzle[0].length,
orientations: allOrientations,
preferOverlap: true
}, found = [], notFound = [];
for (var i = 0, len = words.length; i < len; i++) {
var word = words[i], locations = findBestLocations(puzzle, options, word);
if (locations.length > 0 && locations[0].overlap === word.length) {
if (locations.length > 0 && locations[0].overlap === word.length) {
locations[0].word = word;
found.push(locations[0]);
}
else {
notFound.push(word);
}
}
}
return { found: found, notFound: notFound };
}
|
[
"function",
"(",
"puzzle",
",",
"words",
")",
"{",
"var",
"options",
"=",
"{",
"height",
":",
"puzzle",
".",
"length",
",",
"width",
":",
"puzzle",
"[",
"0",
"]",
".",
"length",
",",
"orientations",
":",
"allOrientations",
",",
"preferOverlap",
":",
"true",
"}",
",",
"found",
"=",
"[",
"]",
",",
"notFound",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"words",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"word",
"=",
"words",
"[",
"i",
"]",
",",
"locations",
"=",
"findBestLocations",
"(",
"puzzle",
",",
"options",
",",
"word",
")",
";",
"if",
"(",
"locations",
".",
"length",
">",
"0",
"&&",
"locations",
"[",
"0",
"]",
".",
"overlap",
"===",
"word",
".",
"length",
")",
"{",
"if",
"(",
"locations",
".",
"length",
">",
"0",
"&&",
"locations",
"[",
"0",
"]",
".",
"overlap",
"===",
"word",
".",
"length",
")",
"{",
"locations",
"[",
"0",
"]",
".",
"word",
"=",
"word",
";",
"found",
".",
"push",
"(",
"locations",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"notFound",
".",
"push",
"(",
"word",
")",
";",
"}",
"}",
"}",
"return",
"{",
"found",
":",
"found",
",",
"notFound",
":",
"notFound",
"}",
";",
"}"
] |
Returns the starting location and orientation of the specified words
within the puzzle. Any words that are not found are returned in the
notFound array.
Returns
x position of start of word
y position of start of word
orientation of word
word
overlap (always equal to word.length)
@param {[[String]]} puzzle: The current state of the puzzle
@param {[String]} words: The list of words to find
@api public
|
[
"Returns",
"the",
"starting",
"location",
"and",
"orientation",
"of",
"the",
"specified",
"words",
"within",
"the",
"puzzle",
".",
"Any",
"words",
"that",
"are",
"not",
"found",
"are",
"returned",
"in",
"the",
"notFound",
"array",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L336-L356
|
|
52,735
|
haztivity/hz-soupletter
|
src/lib/wordfind.js
|
function (puzzle) {
var puzzleString = '';
for (var i = 0, height = puzzle.length; i < height; i++) {
var row = puzzle[i];
for (var j = 0, width = row.length; j < width; j++) {
puzzleString += (row[j] === '' ? ' ' : row[j]) + ' ';
}
puzzleString += '\n';
}
console.log(puzzleString);
return puzzleString;
}
|
javascript
|
function (puzzle) {
var puzzleString = '';
for (var i = 0, height = puzzle.length; i < height; i++) {
var row = puzzle[i];
for (var j = 0, width = row.length; j < width; j++) {
puzzleString += (row[j] === '' ? ' ' : row[j]) + ' ';
}
puzzleString += '\n';
}
console.log(puzzleString);
return puzzleString;
}
|
[
"function",
"(",
"puzzle",
")",
"{",
"var",
"puzzleString",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"height",
"=",
"puzzle",
".",
"length",
";",
"i",
"<",
"height",
";",
"i",
"++",
")",
"{",
"var",
"row",
"=",
"puzzle",
"[",
"i",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"width",
"=",
"row",
".",
"length",
";",
"j",
"<",
"width",
";",
"j",
"++",
")",
"{",
"puzzleString",
"+=",
"(",
"row",
"[",
"j",
"]",
"===",
"''",
"?",
"' '",
":",
"row",
"[",
"j",
"]",
")",
"+",
"' '",
";",
"}",
"puzzleString",
"+=",
"'\\n'",
";",
"}",
"console",
".",
"log",
"(",
"puzzleString",
")",
";",
"return",
"puzzleString",
";",
"}"
] |
Outputs a puzzle to the console, useful for debugging.
Returns a formatted string representing the puzzle.
@param {[[String]]} puzzle: The current state of the puzzle
@api public
|
[
"Outputs",
"a",
"puzzle",
"to",
"the",
"console",
"useful",
"for",
"debugging",
".",
"Returns",
"a",
"formatted",
"string",
"representing",
"the",
"puzzle",
"."
] |
38cbcd0c6e9ad029b7e74ce9e9e75f8775870956
|
https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfind.js#L364-L375
|
|
52,736
|
xiamidaxia/xiami
|
meteor/accounts-base/accounts_server.js
|
function (connection, attempt) {
var clonedAttempt = EJSON.clone(attempt);
clonedAttempt.connection = connection;
return clonedAttempt;
}
|
javascript
|
function (connection, attempt) {
var clonedAttempt = EJSON.clone(attempt);
clonedAttempt.connection = connection;
return clonedAttempt;
}
|
[
"function",
"(",
"connection",
",",
"attempt",
")",
"{",
"var",
"clonedAttempt",
"=",
"EJSON",
".",
"clone",
"(",
"attempt",
")",
";",
"clonedAttempt",
".",
"connection",
"=",
"connection",
";",
"return",
"clonedAttempt",
";",
"}"
] |
Give each login hook callback a fresh cloned copy of the attempt object, but don't clone the connection.
|
[
"Give",
"each",
"login",
"hook",
"callback",
"a",
"fresh",
"cloned",
"copy",
"of",
"the",
"attempt",
"object",
"but",
"don",
"t",
"clone",
"the",
"connection",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/accounts-base/accounts_server.js#L77-L81
|
|
52,737
|
xiamidaxia/xiami
|
meteor/accounts-base/accounts_server.js
|
function (methodInvocation, options) {
for (var i = 0; i < loginHandlers.length; ++i) {
var handler = loginHandlers[i];
var result = tryLoginMethod(
handler.name,
function () {
return handler.handler.call(methodInvocation, options);
}
);
if (result)
return result;
else if (result !== undefined)
throw new Meteor.Error(400, "A login handler should return a result or undefined");
}
return {
type: null,
error: new Meteor.Error(400, "Unrecognized options for login request")
};
}
|
javascript
|
function (methodInvocation, options) {
for (var i = 0; i < loginHandlers.length; ++i) {
var handler = loginHandlers[i];
var result = tryLoginMethod(
handler.name,
function () {
return handler.handler.call(methodInvocation, options);
}
);
if (result)
return result;
else if (result !== undefined)
throw new Meteor.Error(400, "A login handler should return a result or undefined");
}
return {
type: null,
error: new Meteor.Error(400, "Unrecognized options for login request")
};
}
|
[
"function",
"(",
"methodInvocation",
",",
"options",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"loginHandlers",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"handler",
"=",
"loginHandlers",
"[",
"i",
"]",
";",
"var",
"result",
"=",
"tryLoginMethod",
"(",
"handler",
".",
"name",
",",
"function",
"(",
")",
"{",
"return",
"handler",
".",
"handler",
".",
"call",
"(",
"methodInvocation",
",",
"options",
")",
";",
"}",
")",
";",
"if",
"(",
"result",
")",
"return",
"result",
";",
"else",
"if",
"(",
"result",
"!==",
"undefined",
")",
"throw",
"new",
"Meteor",
".",
"Error",
"(",
"400",
",",
"\"A login handler should return a result or undefined\"",
")",
";",
"}",
"return",
"{",
"type",
":",
"null",
",",
"error",
":",
"new",
"Meteor",
".",
"Error",
"(",
"400",
",",
"\"Unrecognized options for login request\"",
")",
"}",
";",
"}"
] |
Try all of the registered login handlers until one of them doesn't return `undefined`, meaning it handled this call to `login`. Return that return value.
|
[
"Try",
"all",
"of",
"the",
"registered",
"login",
"handlers",
"until",
"one",
"of",
"them",
"doesn",
"t",
"return",
"undefined",
"meaning",
"it",
"handled",
"this",
"call",
"to",
"login",
".",
"Return",
"that",
"return",
"value",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/accounts-base/accounts_server.js#L376-L397
|
|
52,738
|
xiamidaxia/xiami
|
meteor/accounts-base/accounts_server.js
|
function () {
var self = this;
var user = Meteor.users.findOne(self.userId, {
fields: { "services.resume.loginTokens": 1 }
});
if (! self.userId || ! user) {
throw new Meteor.Error("You are not logged in.");
}
// Be careful not to generate a new token that has a later
// expiration than the curren token. Otherwise, a bad guy with a
// stolen token could use this method to stop his stolen token from
// ever expiring.
var currentHashedToken = Accounts._getLoginToken(self.connection.id);
var currentStampedToken = _.find(
user.services.resume.loginTokens,
function (stampedToken) {
return stampedToken.hashedToken === currentHashedToken;
}
);
if (! currentStampedToken) { // safety belt: this should never happen
throw new Meteor.Error("Invalid login token");
}
var newStampedToken = Accounts._generateStampedLoginToken();
newStampedToken.when = currentStampedToken.when;
Accounts._insertLoginToken(self.userId, newStampedToken);
return loginUser(self, self.userId, newStampedToken);
}
|
javascript
|
function () {
var self = this;
var user = Meteor.users.findOne(self.userId, {
fields: { "services.resume.loginTokens": 1 }
});
if (! self.userId || ! user) {
throw new Meteor.Error("You are not logged in.");
}
// Be careful not to generate a new token that has a later
// expiration than the curren token. Otherwise, a bad guy with a
// stolen token could use this method to stop his stolen token from
// ever expiring.
var currentHashedToken = Accounts._getLoginToken(self.connection.id);
var currentStampedToken = _.find(
user.services.resume.loginTokens,
function (stampedToken) {
return stampedToken.hashedToken === currentHashedToken;
}
);
if (! currentStampedToken) { // safety belt: this should never happen
throw new Meteor.Error("Invalid login token");
}
var newStampedToken = Accounts._generateStampedLoginToken();
newStampedToken.when = currentStampedToken.when;
Accounts._insertLoginToken(self.userId, newStampedToken);
return loginUser(self, self.userId, newStampedToken);
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"user",
"=",
"Meteor",
".",
"users",
".",
"findOne",
"(",
"self",
".",
"userId",
",",
"{",
"fields",
":",
"{",
"\"services.resume.loginTokens\"",
":",
"1",
"}",
"}",
")",
";",
"if",
"(",
"!",
"self",
".",
"userId",
"||",
"!",
"user",
")",
"{",
"throw",
"new",
"Meteor",
".",
"Error",
"(",
"\"You are not logged in.\"",
")",
";",
"}",
"// Be careful not to generate a new token that has a later",
"// expiration than the curren token. Otherwise, a bad guy with a",
"// stolen token could use this method to stop his stolen token from",
"// ever expiring.",
"var",
"currentHashedToken",
"=",
"Accounts",
".",
"_getLoginToken",
"(",
"self",
".",
"connection",
".",
"id",
")",
";",
"var",
"currentStampedToken",
"=",
"_",
".",
"find",
"(",
"user",
".",
"services",
".",
"resume",
".",
"loginTokens",
",",
"function",
"(",
"stampedToken",
")",
"{",
"return",
"stampedToken",
".",
"hashedToken",
"===",
"currentHashedToken",
";",
"}",
")",
";",
"if",
"(",
"!",
"currentStampedToken",
")",
"{",
"// safety belt: this should never happen",
"throw",
"new",
"Meteor",
".",
"Error",
"(",
"\"Invalid login token\"",
")",
";",
"}",
"var",
"newStampedToken",
"=",
"Accounts",
".",
"_generateStampedLoginToken",
"(",
")",
";",
"newStampedToken",
".",
"when",
"=",
"currentStampedToken",
".",
"when",
";",
"Accounts",
".",
"_insertLoginToken",
"(",
"self",
".",
"userId",
",",
"newStampedToken",
")",
";",
"return",
"loginUser",
"(",
"self",
",",
"self",
".",
"userId",
",",
"newStampedToken",
")",
";",
"}"
] |
Generates a new login token with the same expiration as the connection's current token and saves it to the database. Associates the connection with this new token and returns it. Throws an error if called on a connection that isn't logged in. @returns Object If successful, returns { token: <new token>, id: <user id>, tokenExpires: <expiration date> }.
|
[
"Generates",
"a",
"new",
"login",
"token",
"with",
"the",
"same",
"expiration",
"as",
"the",
"connection",
"s",
"current",
"token",
"and",
"saves",
"it",
"to",
"the",
"database",
".",
"Associates",
"the",
"connection",
"with",
"this",
"new",
"token",
"and",
"returns",
"it",
".",
"Throws",
"an",
"error",
"if",
"called",
"on",
"a",
"connection",
"that",
"isn",
"t",
"logged",
"in",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/accounts-base/accounts_server.js#L513-L539
|
|
52,739
|
xiamidaxia/xiami
|
meteor/accounts-base/accounts_server.js
|
function () {
var self = this;
if (! self.userId) {
throw new Meteor.Error("You are not logged in.");
}
var currentToken = Accounts._getLoginToken(self.connection.id);
Meteor.users.update(self.userId, {
$pull: {
"services.resume.loginTokens": { hashedToken: { $ne: currentToken } }
}
});
}
|
javascript
|
function () {
var self = this;
if (! self.userId) {
throw new Meteor.Error("You are not logged in.");
}
var currentToken = Accounts._getLoginToken(self.connection.id);
Meteor.users.update(self.userId, {
$pull: {
"services.resume.loginTokens": { hashedToken: { $ne: currentToken } }
}
});
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"self",
".",
"userId",
")",
"{",
"throw",
"new",
"Meteor",
".",
"Error",
"(",
"\"You are not logged in.\"",
")",
";",
"}",
"var",
"currentToken",
"=",
"Accounts",
".",
"_getLoginToken",
"(",
"self",
".",
"connection",
".",
"id",
")",
";",
"Meteor",
".",
"users",
".",
"update",
"(",
"self",
".",
"userId",
",",
"{",
"$pull",
":",
"{",
"\"services.resume.loginTokens\"",
":",
"{",
"hashedToken",
":",
"{",
"$ne",
":",
"currentToken",
"}",
"}",
"}",
"}",
")",
";",
"}"
] |
Removes all tokens except the token associated with the current connection. Throws an error if the connection is not logged in. Returns nothing on success.
|
[
"Removes",
"all",
"tokens",
"except",
"the",
"token",
"associated",
"with",
"the",
"current",
"connection",
".",
"Throws",
"an",
"error",
"if",
"the",
"connection",
"is",
"not",
"logged",
"in",
".",
"Returns",
"nothing",
"on",
"success",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/accounts-base/accounts_server.js#L544-L555
|
|
52,740
|
xiamidaxia/xiami
|
meteor/accounts-base/accounts_server.js
|
function (serviceData, userId) {
_.each(_.keys(serviceData), function (key) {
var value = serviceData[key];
if (OAuthEncryption && OAuthEncryption.isSealed(value))
value = OAuthEncryption.seal(OAuthEncryption.open(value), userId);
serviceData[key] = value;
});
}
|
javascript
|
function (serviceData, userId) {
_.each(_.keys(serviceData), function (key) {
var value = serviceData[key];
if (OAuthEncryption && OAuthEncryption.isSealed(value))
value = OAuthEncryption.seal(OAuthEncryption.open(value), userId);
serviceData[key] = value;
});
}
|
[
"function",
"(",
"serviceData",
",",
"userId",
")",
"{",
"_",
".",
"each",
"(",
"_",
".",
"keys",
"(",
"serviceData",
")",
",",
"function",
"(",
"key",
")",
"{",
"var",
"value",
"=",
"serviceData",
"[",
"key",
"]",
";",
"if",
"(",
"OAuthEncryption",
"&&",
"OAuthEncryption",
".",
"isSealed",
"(",
"value",
")",
")",
"value",
"=",
"OAuthEncryption",
".",
"seal",
"(",
"OAuthEncryption",
".",
"open",
"(",
"value",
")",
",",
"userId",
")",
";",
"serviceData",
"[",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"}"
] |
OAuth service data is temporarily stored in the pending credentials collection during the oauth authentication process. Sensitive data such as access tokens are encrypted without the user id because we don't know the user id yet. We re-encrypt these fields with the user id included when storing the service data permanently in the users collection.
|
[
"OAuth",
"service",
"data",
"is",
"temporarily",
"stored",
"in",
"the",
"pending",
"credentials",
"collection",
"during",
"the",
"oauth",
"authentication",
"process",
".",
"Sensitive",
"data",
"such",
"as",
"access",
"tokens",
"are",
"encrypted",
"without",
"the",
"user",
"id",
"because",
"we",
"don",
"t",
"know",
"the",
"user",
"id",
"yet",
".",
"We",
"re",
"-",
"encrypt",
"these",
"fields",
"with",
"the",
"user",
"id",
"included",
"when",
"storing",
"the",
"service",
"data",
"permanently",
"in",
"the",
"users",
"collection",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/accounts-base/accounts_server.js#L933-L940
|
|
52,741
|
xiamidaxia/xiami
|
meteor/accounts-base/accounts_server.js
|
function (userId, user, fields, modifier) {
// make sure it is our record
if (user._id !== userId)
return false;
// user can only modify the 'profile' field. sets to multiple
// sub-keys (eg profile.foo and profile.bar) are merged into entry
// in the fields list.
if (fields.length !== 1 || fields[0] !== 'profile')
return false;
return true;
}
|
javascript
|
function (userId, user, fields, modifier) {
// make sure it is our record
if (user._id !== userId)
return false;
// user can only modify the 'profile' field. sets to multiple
// sub-keys (eg profile.foo and profile.bar) are merged into entry
// in the fields list.
if (fields.length !== 1 || fields[0] !== 'profile')
return false;
return true;
}
|
[
"function",
"(",
"userId",
",",
"user",
",",
"fields",
",",
"modifier",
")",
"{",
"// make sure it is our record",
"if",
"(",
"user",
".",
"_id",
"!==",
"userId",
")",
"return",
"false",
";",
"// user can only modify the 'profile' field. sets to multiple",
"// sub-keys (eg profile.foo and profile.bar) are merged into entry",
"// in the fields list.",
"if",
"(",
"fields",
".",
"length",
"!==",
"1",
"||",
"fields",
"[",
"0",
"]",
"!==",
"'profile'",
")",
"return",
"false",
";",
"return",
"true",
";",
"}"
] |
clients can modify the profile field of their own document, and nothing else.
|
[
"clients",
"can",
"modify",
"the",
"profile",
"field",
"of",
"their",
"own",
"document",
"and",
"nothing",
"else",
"."
] |
6fcee92c493c12bf8fd67c7068e67fa6a72a306b
|
https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/meteor/accounts-base/accounts_server.js#L1304-L1316
|
|
52,742
|
Digznav/bilberry
|
log.js
|
logMessage
|
function logMessage(fig, st, lns) {
return lns.reduce((a, b) => a.concat(` ${b}`), [`\n${fig} ${st}`]);
}
|
javascript
|
function logMessage(fig, st, lns) {
return lns.reduce((a, b) => a.concat(` ${b}`), [`\n${fig} ${st}`]);
}
|
[
"function",
"logMessage",
"(",
"fig",
",",
"st",
",",
"lns",
")",
"{",
"return",
"lns",
".",
"reduce",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"concat",
"(",
"`",
"${",
"b",
"}",
"`",
")",
",",
"[",
"`",
"\\n",
"${",
"fig",
"}",
"${",
"st",
"}",
"`",
"]",
")",
";",
"}"
] |
It adds an icon and tabulates the log massage.
@param {string} fig Icon.
@param {string} st First line of the log message.
@param {array} lns Rest of the message.
@return {array} Parsed message.
|
[
"It",
"adds",
"an",
"icon",
"and",
"tabulates",
"the",
"log",
"massage",
"."
] |
ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4
|
https://github.com/Digznav/bilberry/blob/ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4/log.js#L11-L13
|
52,743
|
Digznav/bilberry
|
log.js
|
log
|
function log(first, ...lines) {
console.log(logMessage(figures.bullet, first, lines).join('\n'));
}
|
javascript
|
function log(first, ...lines) {
console.log(logMessage(figures.bullet, first, lines).join('\n'));
}
|
[
"function",
"log",
"(",
"first",
",",
"...",
"lines",
")",
"{",
"console",
".",
"log",
"(",
"logMessage",
"(",
"figures",
".",
"bullet",
",",
"first",
",",
"lines",
")",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"}"
] |
Console log custom wrapper.
@param {string} first First line.
@param {args} lines Rest of the lines.
@return {log} Log message.
|
[
"Console",
"log",
"custom",
"wrapper",
"."
] |
ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4
|
https://github.com/Digznav/bilberry/blob/ef6db49de6c8b0d2f4f9d3e10e8a8153e39ffcc4/log.js#L21-L23
|
52,744
|
PeterNaydenov/ask-for-promise
|
src/askForPromise.js
|
_singlePromise
|
function _singlePromise () {
let done, cancel;
const x = new Promise ( (resolve, reject ) => {
done = resolve
cancel = reject
})
return {
promise : x
, done : done
, cancel : cancel
, onComplete : _after(x)
}
}
|
javascript
|
function _singlePromise () {
let done, cancel;
const x = new Promise ( (resolve, reject ) => {
done = resolve
cancel = reject
})
return {
promise : x
, done : done
, cancel : cancel
, onComplete : _after(x)
}
}
|
[
"function",
"_singlePromise",
"(",
")",
"{",
"let",
"done",
",",
"cancel",
";",
"const",
"x",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"done",
"=",
"resolve",
"cancel",
"=",
"reject",
"}",
")",
"return",
"{",
"promise",
":",
"x",
",",
"done",
":",
"done",
",",
"cancel",
":",
"cancel",
",",
"onComplete",
":",
"_after",
"(",
"x",
")",
"}",
"}"
] |
askForPromise func.
|
[
"askForPromise",
"func",
"."
] |
2aca2eaf947c234ec7ea3b6f3e95ec6f09634354
|
https://github.com/PeterNaydenov/ask-for-promise/blob/2aca2eaf947c234ec7ea3b6f3e95ec6f09634354/src/askForPromise.js#L32-L45
|
52,745
|
PeterNaydenov/ask-for-promise
|
src/askForPromise.js
|
_manyPromises
|
function _manyPromises ( list ) {
let askObject = list.map ( el => _singlePromise() )
let askList = askObject.map ( o => o.promise )
askObject [ 'promises' ] = askList
askObject [ 'onComplete' ] = _after ( Promise.all (askList) )
return askObject
}
|
javascript
|
function _manyPromises ( list ) {
let askObject = list.map ( el => _singlePromise() )
let askList = askObject.map ( o => o.promise )
askObject [ 'promises' ] = askList
askObject [ 'onComplete' ] = _after ( Promise.all (askList) )
return askObject
}
|
[
"function",
"_manyPromises",
"(",
"list",
")",
"{",
"let",
"askObject",
"=",
"list",
".",
"map",
"(",
"el",
"=>",
"_singlePromise",
"(",
")",
")",
"let",
"askList",
"=",
"askObject",
".",
"map",
"(",
"o",
"=>",
"o",
".",
"promise",
")",
"askObject",
"[",
"'promises'",
"]",
"=",
"askList",
"askObject",
"[",
"'onComplete'",
"]",
"=",
"_after",
"(",
"Promise",
".",
"all",
"(",
"askList",
")",
")",
"return",
"askObject",
"}"
] |
_singlePromise func.
|
[
"_singlePromise",
"func",
"."
] |
2aca2eaf947c234ec7ea3b6f3e95ec6f09634354
|
https://github.com/PeterNaydenov/ask-for-promise/blob/2aca2eaf947c234ec7ea3b6f3e95ec6f09634354/src/askForPromise.js#L49-L56
|
52,746
|
skerit/alchemy
|
lib/core/discovery.js
|
onServerMessage
|
function onServerMessage(message, rinfo) {
var packet,
respond;
alchemy.setStatus('multicast_messages', ++messages);
try {
packet = bson.deserialize(message);
} catch(err) {
log.warn('Received corrupt multicast message from ' + rinfo.address);
return;
}
// Ignore packets that come from here
if (packet.origin == alchemy.discovery_id) {
return;
}
packet.remote = rinfo;
if (packet.respond) {
respond = function respond(data) {
var response_packet = {
type : 'response',
response_to : packet.id,
data : data
};
submit(response_packet);
};
}
// Emit it as a multicast event
alchemy.emit('multicast', packet, respond, null);
if (packet.response_to) {
if (typeof callbacks[packet.response_to] === 'function') {
callbacks[packet.response_to](packet.data, packet);
}
} else {
// Emit it for multicast listeners only
mevents.emit(packet.type, packet.data, packet, respond, null);
}
}
|
javascript
|
function onServerMessage(message, rinfo) {
var packet,
respond;
alchemy.setStatus('multicast_messages', ++messages);
try {
packet = bson.deserialize(message);
} catch(err) {
log.warn('Received corrupt multicast message from ' + rinfo.address);
return;
}
// Ignore packets that come from here
if (packet.origin == alchemy.discovery_id) {
return;
}
packet.remote = rinfo;
if (packet.respond) {
respond = function respond(data) {
var response_packet = {
type : 'response',
response_to : packet.id,
data : data
};
submit(response_packet);
};
}
// Emit it as a multicast event
alchemy.emit('multicast', packet, respond, null);
if (packet.response_to) {
if (typeof callbacks[packet.response_to] === 'function') {
callbacks[packet.response_to](packet.data, packet);
}
} else {
// Emit it for multicast listeners only
mevents.emit(packet.type, packet.data, packet, respond, null);
}
}
|
[
"function",
"onServerMessage",
"(",
"message",
",",
"rinfo",
")",
"{",
"var",
"packet",
",",
"respond",
";",
"alchemy",
".",
"setStatus",
"(",
"'multicast_messages'",
",",
"++",
"messages",
")",
";",
"try",
"{",
"packet",
"=",
"bson",
".",
"deserialize",
"(",
"message",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"log",
".",
"warn",
"(",
"'Received corrupt multicast message from '",
"+",
"rinfo",
".",
"address",
")",
";",
"return",
";",
"}",
"// Ignore packets that come from here",
"if",
"(",
"packet",
".",
"origin",
"==",
"alchemy",
".",
"discovery_id",
")",
"{",
"return",
";",
"}",
"packet",
".",
"remote",
"=",
"rinfo",
";",
"if",
"(",
"packet",
".",
"respond",
")",
"{",
"respond",
"=",
"function",
"respond",
"(",
"data",
")",
"{",
"var",
"response_packet",
"=",
"{",
"type",
":",
"'response'",
",",
"response_to",
":",
"packet",
".",
"id",
",",
"data",
":",
"data",
"}",
";",
"submit",
"(",
"response_packet",
")",
";",
"}",
";",
"}",
"// Emit it as a multicast event",
"alchemy",
".",
"emit",
"(",
"'multicast'",
",",
"packet",
",",
"respond",
",",
"null",
")",
";",
"if",
"(",
"packet",
".",
"response_to",
")",
"{",
"if",
"(",
"typeof",
"callbacks",
"[",
"packet",
".",
"response_to",
"]",
"===",
"'function'",
")",
"{",
"callbacks",
"[",
"packet",
".",
"response_to",
"]",
"(",
"packet",
".",
"data",
",",
"packet",
")",
";",
"}",
"}",
"else",
"{",
"// Emit it for multicast listeners only",
"mevents",
".",
"emit",
"(",
"packet",
".",
"type",
",",
"packet",
".",
"data",
",",
"packet",
",",
"respond",
",",
"null",
")",
";",
"}",
"}"
] |
Listen for messages
@author Jelle De Loecker <jelle@develry.be>
@since 0.1.0
@version 0.4.3
|
[
"Listen",
"for",
"messages"
] |
ede1dad07a5a737d5d1e10c2ff87fdfb057443f8
|
https://github.com/skerit/alchemy/blob/ede1dad07a5a737d5d1e10c2ff87fdfb057443f8/lib/core/discovery.js#L74-L119
|
52,747
|
CoderByBlood/deified
|
scanner.js
|
tree
|
async function tree(dir, files) {
log.trace.configure({ reading: dir });
const { filter } = conf;
const ls = await readdir(dir, conf.options);
for (let i = 0; i < ls.length; i += 1) {
const file = path.join(dir, ls[i]);
if (!filter || filter([file]).length) {
log.trace.configure({ passed_fitler: file });
files.push(file);
// eslint-disable-next-line no-await-in-loop
if ((await stat(file)).isDirectory()) {
log.trace.configure({ recursing: file });
// eslint-disable-next-line no-await-in-loop
await tree(file, files);
}
}
}
return files;
}
|
javascript
|
async function tree(dir, files) {
log.trace.configure({ reading: dir });
const { filter } = conf;
const ls = await readdir(dir, conf.options);
for (let i = 0; i < ls.length; i += 1) {
const file = path.join(dir, ls[i]);
if (!filter || filter([file]).length) {
log.trace.configure({ passed_fitler: file });
files.push(file);
// eslint-disable-next-line no-await-in-loop
if ((await stat(file)).isDirectory()) {
log.trace.configure({ recursing: file });
// eslint-disable-next-line no-await-in-loop
await tree(file, files);
}
}
}
return files;
}
|
[
"async",
"function",
"tree",
"(",
"dir",
",",
"files",
")",
"{",
"log",
".",
"trace",
".",
"configure",
"(",
"{",
"reading",
":",
"dir",
"}",
")",
";",
"const",
"{",
"filter",
"}",
"=",
"conf",
";",
"const",
"ls",
"=",
"await",
"readdir",
"(",
"dir",
",",
"conf",
".",
"options",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"ls",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"const",
"file",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"ls",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"filter",
"||",
"filter",
"(",
"[",
"file",
"]",
")",
".",
"length",
")",
"{",
"log",
".",
"trace",
".",
"configure",
"(",
"{",
"passed_fitler",
":",
"file",
"}",
")",
";",
"files",
".",
"push",
"(",
"file",
")",
";",
"// eslint-disable-next-line no-await-in-loop",
"if",
"(",
"(",
"await",
"stat",
"(",
"file",
")",
")",
".",
"isDirectory",
"(",
")",
")",
"{",
"log",
".",
"trace",
".",
"configure",
"(",
"{",
"recursing",
":",
"file",
"}",
")",
";",
"// eslint-disable-next-line no-await-in-loop",
"await",
"tree",
"(",
"file",
",",
"files",
")",
";",
"}",
"}",
"}",
"return",
"files",
";",
"}"
] |
Recursively builds a list of files and directories for the specified
directory and all subdirectors - can be optionally filtered.
@param {string} dir - The directory to list (ls)
@param {array} files - The array for appending files/directors
@return {array} The files argument
|
[
"Recursively",
"builds",
"a",
"list",
"of",
"files",
"and",
"directories",
"for",
"the",
"specified",
"directory",
"and",
"all",
"subdirectors",
"-",
"can",
"be",
"optionally",
"filtered",
"."
] |
f2d212ffe111b8dfb4872819afe3d5a7a3b8a1b6
|
https://github.com/CoderByBlood/deified/blob/f2d212ffe111b8dfb4872819afe3d5a7a3b8a1b6/scanner.js#L56-L78
|
52,748
|
Bartozzz/get-link
|
dist/index.js
|
regenerateLink
|
function regenerateLink(base, link) {
const parsedBase = (0, _url.parse)(base);
const parsedLink = link.split("/");
let parts = [];
let port = "";
if (!link.startsWith("/")) {
parts = parsedBase.pathname.split("/");
parts.pop();
}
for (const part of parsedLink) {
// Current directory:
if (part === ".") {
continue;
} // Parent directory:
if (part === "..") {
// Accessing non-existing parent directories:
if (!parts.pop() || parts.length === 0) {
return null;
}
} else {
parts.push(part);
}
}
if (parsedBase.port) {
port = ":" + parsedBase.port;
} // eslint-disable-next-line max-len
return `${parsedBase.protocol}//${parsedBase.hostname}${port}${parts.join("/")}`;
}
|
javascript
|
function regenerateLink(base, link) {
const parsedBase = (0, _url.parse)(base);
const parsedLink = link.split("/");
let parts = [];
let port = "";
if (!link.startsWith("/")) {
parts = parsedBase.pathname.split("/");
parts.pop();
}
for (const part of parsedLink) {
// Current directory:
if (part === ".") {
continue;
} // Parent directory:
if (part === "..") {
// Accessing non-existing parent directories:
if (!parts.pop() || parts.length === 0) {
return null;
}
} else {
parts.push(part);
}
}
if (parsedBase.port) {
port = ":" + parsedBase.port;
} // eslint-disable-next-line max-len
return `${parsedBase.protocol}//${parsedBase.hostname}${port}${parts.join("/")}`;
}
|
[
"function",
"regenerateLink",
"(",
"base",
",",
"link",
")",
"{",
"const",
"parsedBase",
"=",
"(",
"0",
",",
"_url",
".",
"parse",
")",
"(",
"base",
")",
";",
"const",
"parsedLink",
"=",
"link",
".",
"split",
"(",
"\"/\"",
")",
";",
"let",
"parts",
"=",
"[",
"]",
";",
"let",
"port",
"=",
"\"\"",
";",
"if",
"(",
"!",
"link",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"parts",
"=",
"parsedBase",
".",
"pathname",
".",
"split",
"(",
"\"/\"",
")",
";",
"parts",
".",
"pop",
"(",
")",
";",
"}",
"for",
"(",
"const",
"part",
"of",
"parsedLink",
")",
"{",
"// Current directory:",
"if",
"(",
"part",
"===",
"\".\"",
")",
"{",
"continue",
";",
"}",
"// Parent directory:",
"if",
"(",
"part",
"===",
"\"..\"",
")",
"{",
"// Accessing non-existing parent directories:",
"if",
"(",
"!",
"parts",
".",
"pop",
"(",
")",
"||",
"parts",
".",
"length",
"===",
"0",
")",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"{",
"parts",
".",
"push",
"(",
"part",
")",
";",
"}",
"}",
"if",
"(",
"parsedBase",
".",
"port",
")",
"{",
"port",
"=",
"\":\"",
"+",
"parsedBase",
".",
"port",
";",
"}",
"// eslint-disable-next-line max-len",
"return",
"`",
"${",
"parsedBase",
".",
"protocol",
"}",
"${",
"parsedBase",
".",
"hostname",
"}",
"${",
"port",
"}",
"${",
"parts",
".",
"join",
"(",
"\"/\"",
")",
"}",
"`",
";",
"}"
] |
Regenerates an absolute URL from `base` and relative `link`.
@param {string} base Absolute base url
@param {string} link Relative link
@return {string|null}
|
[
"Regenerates",
"an",
"absolute",
"URL",
"from",
"base",
"and",
"relative",
"link",
"."
] |
4506cfade27e420e51774978b9761f089d47965a
|
https://github.com/Bartozzz/get-link/blob/4506cfade27e420e51774978b9761f089d47965a/dist/index.js#L44-L78
|
52,749
|
Bartozzz/get-link
|
dist/index.js
|
_default
|
function _default(base, link) {
// Dynamic stuff:
if (typeof link !== "string" || link.match(REGEX_DYNAMIC)) {
return base;
} // Link is absolute:
if (link.match(REGEX_ABSOLUTE)) {
try {
const parsedBase = parseLink(base);
const parsedLink = parseLink(link); // Both `base` and `link` are on different domains:
if (parsedBase.domain !== parsedLink.domain) {
return false;
} // Absolute path from same domain:
if (parsedLink.path) {
return (0, _url.resolve)(base, parsedLink.path);
} // Same domains without path:
return (0, _url.parse)(base).href;
} catch (err) {
return false;
}
} // Relative stuff:
return regenerateLink(base, link);
}
|
javascript
|
function _default(base, link) {
// Dynamic stuff:
if (typeof link !== "string" || link.match(REGEX_DYNAMIC)) {
return base;
} // Link is absolute:
if (link.match(REGEX_ABSOLUTE)) {
try {
const parsedBase = parseLink(base);
const parsedLink = parseLink(link); // Both `base` and `link` are on different domains:
if (parsedBase.domain !== parsedLink.domain) {
return false;
} // Absolute path from same domain:
if (parsedLink.path) {
return (0, _url.resolve)(base, parsedLink.path);
} // Same domains without path:
return (0, _url.parse)(base).href;
} catch (err) {
return false;
}
} // Relative stuff:
return regenerateLink(base, link);
}
|
[
"function",
"_default",
"(",
"base",
",",
"link",
")",
"{",
"// Dynamic stuff:",
"if",
"(",
"typeof",
"link",
"!==",
"\"string\"",
"||",
"link",
".",
"match",
"(",
"REGEX_DYNAMIC",
")",
")",
"{",
"return",
"base",
";",
"}",
"// Link is absolute:",
"if",
"(",
"link",
".",
"match",
"(",
"REGEX_ABSOLUTE",
")",
")",
"{",
"try",
"{",
"const",
"parsedBase",
"=",
"parseLink",
"(",
"base",
")",
";",
"const",
"parsedLink",
"=",
"parseLink",
"(",
"link",
")",
";",
"// Both `base` and `link` are on different domains:",
"if",
"(",
"parsedBase",
".",
"domain",
"!==",
"parsedLink",
".",
"domain",
")",
"{",
"return",
"false",
";",
"}",
"// Absolute path from same domain:",
"if",
"(",
"parsedLink",
".",
"path",
")",
"{",
"return",
"(",
"0",
",",
"_url",
".",
"resolve",
")",
"(",
"base",
",",
"parsedLink",
".",
"path",
")",
";",
"}",
"// Same domains without path:",
"return",
"(",
"0",
",",
"_url",
".",
"parse",
")",
"(",
"base",
")",
".",
"href",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
";",
"}",
"}",
"// Relative stuff:",
"return",
"regenerateLink",
"(",
"base",
",",
"link",
")",
";",
"}"
] |
Transform a relative path into an absolute url.
@param {string} base Absolute base url
@param {string} link Link to parse
@return {string|false} Absolute path
|
[
"Transform",
"a",
"relative",
"path",
"into",
"an",
"absolute",
"url",
"."
] |
4506cfade27e420e51774978b9761f089d47965a
|
https://github.com/Bartozzz/get-link/blob/4506cfade27e420e51774978b9761f089d47965a/dist/index.js#L88-L118
|
52,750
|
benignware-legacy/broccoli-mincer
|
index.js
|
gzip
|
function gzip(data) {
var unit8Array = new Uint8Array(toBuffer(data));
return new Buffer(pako.gzip(unit8Array));
}
|
javascript
|
function gzip(data) {
var unit8Array = new Uint8Array(toBuffer(data));
return new Buffer(pako.gzip(unit8Array));
}
|
[
"function",
"gzip",
"(",
"data",
")",
"{",
"var",
"unit8Array",
"=",
"new",
"Uint8Array",
"(",
"toBuffer",
"(",
"data",
")",
")",
";",
"return",
"new",
"Buffer",
"(",
"pako",
".",
"gzip",
"(",
"unit8Array",
")",
")",
";",
"}"
] |
Compress given String or Buffer
|
[
"Compress",
"given",
"String",
"or",
"Buffer"
] |
fc8b59bb7b13c9bf419f3fe4e8c858a3ac90b2ea
|
https://github.com/benignware-legacy/broccoli-mincer/blob/fc8b59bb7b13c9bf419f3fe4e8c858a3ac90b2ea/index.js#L168-L171
|
52,751
|
MostlyJS/mostly-poplarjs
|
src/context.js
|
dynamic
|
function dynamic (val, toType, ctx) {
if (Array.isArray(val)) {
return _.map(val, function (v) {
return dynamic(v, toType, ctx);
});
}
return (new Dynamic(val, ctx)).to(toType);
}
|
javascript
|
function dynamic (val, toType, ctx) {
if (Array.isArray(val)) {
return _.map(val, function (v) {
return dynamic(v, toType, ctx);
});
}
return (new Dynamic(val, ctx)).to(toType);
}
|
[
"function",
"dynamic",
"(",
"val",
",",
"toType",
",",
"ctx",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"return",
"_",
".",
"map",
"(",
"val",
",",
"function",
"(",
"v",
")",
"{",
"return",
"dynamic",
"(",
"v",
",",
"toType",
",",
"ctx",
")",
";",
"}",
")",
";",
"}",
"return",
"(",
"new",
"Dynamic",
"(",
"val",
",",
"ctx",
")",
")",
".",
"to",
"(",
"toType",
")",
";",
"}"
] |
Use dynamic to coerce a value or array of values.
|
[
"Use",
"dynamic",
"to",
"coerce",
"a",
"value",
"or",
"array",
"of",
"values",
"."
] |
bda12a72891e8c8d338e7560e7fe9e11ad74a2d9
|
https://github.com/MostlyJS/mostly-poplarjs/blob/bda12a72891e8c8d338e7560e7fe9e11ad74a2d9/src/context.js#L194-L201
|
52,752
|
Holusion/node-xdg-apps
|
lib/MimeType.js
|
glob2regexp
|
function glob2regexp(glob, sensitive){
return new RegExp('^' + glob.replace(ESCAPE_REG_EXP, '\\$1').replace(/\*/g, '.*') + '$', sensitive ? '' : 'i')
}
|
javascript
|
function glob2regexp(glob, sensitive){
return new RegExp('^' + glob.replace(ESCAPE_REG_EXP, '\\$1').replace(/\*/g, '.*') + '$', sensitive ? '' : 'i')
}
|
[
"function",
"glob2regexp",
"(",
"glob",
",",
"sensitive",
")",
"{",
"return",
"new",
"RegExp",
"(",
"'^'",
"+",
"glob",
".",
"replace",
"(",
"ESCAPE_REG_EXP",
",",
"'\\\\$1'",
")",
".",
"replace",
"(",
"/",
"\\*",
"/",
"g",
",",
"'.*'",
")",
"+",
"'$'",
",",
"sensitive",
"?",
"''",
":",
"'i'",
")",
"}"
] |
CHeck it's not bracketed
|
[
"CHeck",
"it",
"s",
"not",
"bracketed"
] |
875c9614c6359cbbc22c986acd88ed3d387aea66
|
https://github.com/Holusion/node-xdg-apps/blob/875c9614c6359cbbc22c986acd88ed3d387aea66/lib/MimeType.js#L11-L13
|
52,753
|
halfblood369/monitor
|
lib/systemMonitor.js
|
getSysInfo
|
function getSysInfo(callback) {
if (process.platform === 'windows') return;
var reData = getBasicInfo();
exec('iostat ', function(err, output) {
if (!!err) {
console.error('getSysInfo failed! ' + err.stack);
} else {
reData.iostat = format(output);
}
callback(reData);
});
}
|
javascript
|
function getSysInfo(callback) {
if (process.platform === 'windows') return;
var reData = getBasicInfo();
exec('iostat ', function(err, output) {
if (!!err) {
console.error('getSysInfo failed! ' + err.stack);
} else {
reData.iostat = format(output);
}
callback(reData);
});
}
|
[
"function",
"getSysInfo",
"(",
"callback",
")",
"{",
"if",
"(",
"process",
".",
"platform",
"===",
"'windows'",
")",
"return",
";",
"var",
"reData",
"=",
"getBasicInfo",
"(",
")",
";",
"exec",
"(",
"'iostat '",
",",
"function",
"(",
"err",
",",
"output",
")",
"{",
"if",
"(",
"!",
"!",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'getSysInfo failed! '",
"+",
"err",
".",
"stack",
")",
";",
"}",
"else",
"{",
"reData",
".",
"iostat",
"=",
"format",
"(",
"output",
")",
";",
"}",
"callback",
"(",
"reData",
")",
";",
"}",
")",
";",
"}"
] |
get information of operating-system
@param {Function} callback
@api public
|
[
"get",
"information",
"of",
"operating",
"-",
"system"
] |
900b5cadf59edcccac4754e5706a22719925ddb9
|
https://github.com/halfblood369/monitor/blob/900b5cadf59edcccac4754e5706a22719925ddb9/lib/systemMonitor.js#L24-L35
|
52,754
|
PeerioTechnologies/peerio-updater
|
signing.js
|
verify
|
function verify(publicKeys, sig, text) {
// Parse signature.
validateBase64(sig);
const binsig = Buffer.from(sig, 'base64');
// Check signature length.
if (binsig.length !== 10 + nacl.sign.signatureLength) {
throw new Error('Bad signature length');
}
// Check signature algorithm.
if (binsig[0] !== 69 /* 'E' */ || binsig[1] !== 100 /* 'd' */) {
throw new Error('Unknown signature algorithm');
}
// Find the appropriate key for signature based on
// algorithm and public key fingerprint embedded into signature.
let key = null;
for (let i = 0; i < publicKeys.length; i++) {
const binkey = Buffer.from(publicKeys[i], 'base64');
// Check public key format.
if (binkey.length !== 10 + nacl.sign.publicKeyLength) {
throw new Error('Bad public key length');
}
// If algorithm (2 bytes) and key number (8) bytes match,
// we found the needed key.
if (nacl.verify(binkey.subarray(0, 10), binsig.subarray(0, 10))) {
key = binkey;
break;
}
}
if (!key) {
throw new Error('Invalid signature: no matching key found');
}
const bintext = Buffer.from(text, 'utf8');
if (!nacl.sign.detached.verify(bintext, binsig.subarray(10), key.subarray(10))) {
throw new Error('Invalid signature');
}
}
|
javascript
|
function verify(publicKeys, sig, text) {
// Parse signature.
validateBase64(sig);
const binsig = Buffer.from(sig, 'base64');
// Check signature length.
if (binsig.length !== 10 + nacl.sign.signatureLength) {
throw new Error('Bad signature length');
}
// Check signature algorithm.
if (binsig[0] !== 69 /* 'E' */ || binsig[1] !== 100 /* 'd' */) {
throw new Error('Unknown signature algorithm');
}
// Find the appropriate key for signature based on
// algorithm and public key fingerprint embedded into signature.
let key = null;
for (let i = 0; i < publicKeys.length; i++) {
const binkey = Buffer.from(publicKeys[i], 'base64');
// Check public key format.
if (binkey.length !== 10 + nacl.sign.publicKeyLength) {
throw new Error('Bad public key length');
}
// If algorithm (2 bytes) and key number (8) bytes match,
// we found the needed key.
if (nacl.verify(binkey.subarray(0, 10), binsig.subarray(0, 10))) {
key = binkey;
break;
}
}
if (!key) {
throw new Error('Invalid signature: no matching key found');
}
const bintext = Buffer.from(text, 'utf8');
if (!nacl.sign.detached.verify(bintext, binsig.subarray(10), key.subarray(10))) {
throw new Error('Invalid signature');
}
}
|
[
"function",
"verify",
"(",
"publicKeys",
",",
"sig",
",",
"text",
")",
"{",
"// Parse signature.",
"validateBase64",
"(",
"sig",
")",
";",
"const",
"binsig",
"=",
"Buffer",
".",
"from",
"(",
"sig",
",",
"'base64'",
")",
";",
"// Check signature length.",
"if",
"(",
"binsig",
".",
"length",
"!==",
"10",
"+",
"nacl",
".",
"sign",
".",
"signatureLength",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Bad signature length'",
")",
";",
"}",
"// Check signature algorithm.",
"if",
"(",
"binsig",
"[",
"0",
"]",
"!==",
"69",
"/* 'E' */",
"||",
"binsig",
"[",
"1",
"]",
"!==",
"100",
"/* 'd' */",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown signature algorithm'",
")",
";",
"}",
"// Find the appropriate key for signature based on",
"// algorithm and public key fingerprint embedded into signature.",
"let",
"key",
"=",
"null",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"publicKeys",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"binkey",
"=",
"Buffer",
".",
"from",
"(",
"publicKeys",
"[",
"i",
"]",
",",
"'base64'",
")",
";",
"// Check public key format.",
"if",
"(",
"binkey",
".",
"length",
"!==",
"10",
"+",
"nacl",
".",
"sign",
".",
"publicKeyLength",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Bad public key length'",
")",
";",
"}",
"// If algorithm (2 bytes) and key number (8) bytes match,",
"// we found the needed key.",
"if",
"(",
"nacl",
".",
"verify",
"(",
"binkey",
".",
"subarray",
"(",
"0",
",",
"10",
")",
",",
"binsig",
".",
"subarray",
"(",
"0",
",",
"10",
")",
")",
")",
"{",
"key",
"=",
"binkey",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"key",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid signature: no matching key found'",
")",
";",
"}",
"const",
"bintext",
"=",
"Buffer",
".",
"from",
"(",
"text",
",",
"'utf8'",
")",
";",
"if",
"(",
"!",
"nacl",
".",
"sign",
".",
"detached",
".",
"verify",
"(",
"bintext",
",",
"binsig",
".",
"subarray",
"(",
"10",
")",
",",
"key",
".",
"subarray",
"(",
"10",
")",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid signature'",
")",
";",
"}",
"}"
] |
Verifies signature.
Throws if signature is invalid.
@param {Array<string>} publicKeys list of base64-encoded public key in signify format
@param {string} sig base64-encoded signature in signify format
@param {string} text message to verify
|
[
"Verifies",
"signature",
".",
"Throws",
"if",
"signature",
"is",
"invalid",
"."
] |
9d6fedeec727f16a31653e4bbd4efe164e0957cb
|
https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/signing.js#L24-L65
|
52,755
|
PeerioTechnologies/peerio-updater
|
signing.js
|
sign
|
function sign(secretKey, text) {
const sec = parseSecretKey(secretKey);
const bintext = Buffer.from(text, 'utf8');
const sig = nacl.sign.detached(bintext, sec.key);
// Full signature includes algorithm id ('Ed'), key number,
// and the signature itself.
const fullsig = new Uint8Array(2 + 8 + 64);
fullsig[0] = 69 // 'E'
fullsig[1] = 100; // 'd'
fullsig.set(sec.num, 2) // key number
fullsig.set(sig, 10); // signature
return Buffer.from(fullsig.buffer).toString('base64');
}
|
javascript
|
function sign(secretKey, text) {
const sec = parseSecretKey(secretKey);
const bintext = Buffer.from(text, 'utf8');
const sig = nacl.sign.detached(bintext, sec.key);
// Full signature includes algorithm id ('Ed'), key number,
// and the signature itself.
const fullsig = new Uint8Array(2 + 8 + 64);
fullsig[0] = 69 // 'E'
fullsig[1] = 100; // 'd'
fullsig.set(sec.num, 2) // key number
fullsig.set(sig, 10); // signature
return Buffer.from(fullsig.buffer).toString('base64');
}
|
[
"function",
"sign",
"(",
"secretKey",
",",
"text",
")",
"{",
"const",
"sec",
"=",
"parseSecretKey",
"(",
"secretKey",
")",
";",
"const",
"bintext",
"=",
"Buffer",
".",
"from",
"(",
"text",
",",
"'utf8'",
")",
";",
"const",
"sig",
"=",
"nacl",
".",
"sign",
".",
"detached",
"(",
"bintext",
",",
"sec",
".",
"key",
")",
";",
"// Full signature includes algorithm id ('Ed'), key number,",
"// and the signature itself.",
"const",
"fullsig",
"=",
"new",
"Uint8Array",
"(",
"2",
"+",
"8",
"+",
"64",
")",
";",
"fullsig",
"[",
"0",
"]",
"=",
"69",
"// 'E'",
"fullsig",
"[",
"1",
"]",
"=",
"100",
";",
"// 'd'",
"fullsig",
".",
"set",
"(",
"sec",
".",
"num",
",",
"2",
")",
"// key number",
"fullsig",
".",
"set",
"(",
"sig",
",",
"10",
")",
";",
"// signature",
"return",
"Buffer",
".",
"from",
"(",
"fullsig",
".",
"buffer",
")",
".",
"toString",
"(",
"'base64'",
")",
";",
"}"
] |
Signs text with the given secret key, returning signature.
Note that secret key is stored in the same format as signify,
but requires rounds = 0, so it is unencrypted.
Secret key format:
2 bytes - signature algorithm
2 bytes - kdf algorithm ('B', 'K')
4 bytes - kdf rounds (00 00 00 00)
16 bytes - salt (any bytes, ignored)
8 bytes - checksum (SHA512(secret key))
8 bytes - key num (random bytes, embedded in signature and public key)
64 bytes - secret key
@param {string} secretKey
@param {string} text
@returns {string} signature
|
[
"Signs",
"text",
"with",
"the",
"given",
"secret",
"key",
"returning",
"signature",
"."
] |
9d6fedeec727f16a31653e4bbd4efe164e0957cb
|
https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/signing.js#L87-L99
|
52,756
|
PeerioTechnologies/peerio-updater
|
signing.js
|
parseSecretKey
|
function parseSecretKey(secretKey) {
const k = Buffer.from(secretKey, 'base64');
if (k.length < 2 + 2 + 4 + 16 + 8 + 8 + 64) {
throw new Error('Incorrect secret key length');
}
// Check signature algorithm.
if (k[0] !== 69 /* 'E' */ || k[1] !== 100 /* 'd' */) {
throw new Error('Unknown signature algorithm');
}
// Check KDF algorithm
if (k[2] !== 66 /* 'B' */ || k[3] !== 75 /* 'K' */) {
throw new Error('Unsupported KDF algorithm');
}
// Extract fields.
const rounds = k.slice(4, 8).readUInt32BE(0);
if (rounds !== 0) {
throw new Error('Rounds must be 0; unlock key before passing to sign.')
}
const checksum = k.slice(24, 32);
const num = Buffer.from(k.slice(32, 40));
const key = Buffer.from(k.slice(40, 104));
// Verify key checksum.
if (!nacl.verify(checksum, nacl.hash(key).subarray(0, 8))) {
throw new Error('Key checksum verification failure');
}
return {
num,
key
};
}
|
javascript
|
function parseSecretKey(secretKey) {
const k = Buffer.from(secretKey, 'base64');
if (k.length < 2 + 2 + 4 + 16 + 8 + 8 + 64) {
throw new Error('Incorrect secret key length');
}
// Check signature algorithm.
if (k[0] !== 69 /* 'E' */ || k[1] !== 100 /* 'd' */) {
throw new Error('Unknown signature algorithm');
}
// Check KDF algorithm
if (k[2] !== 66 /* 'B' */ || k[3] !== 75 /* 'K' */) {
throw new Error('Unsupported KDF algorithm');
}
// Extract fields.
const rounds = k.slice(4, 8).readUInt32BE(0);
if (rounds !== 0) {
throw new Error('Rounds must be 0; unlock key before passing to sign.')
}
const checksum = k.slice(24, 32);
const num = Buffer.from(k.slice(32, 40));
const key = Buffer.from(k.slice(40, 104));
// Verify key checksum.
if (!nacl.verify(checksum, nacl.hash(key).subarray(0, 8))) {
throw new Error('Key checksum verification failure');
}
return {
num,
key
};
}
|
[
"function",
"parseSecretKey",
"(",
"secretKey",
")",
"{",
"const",
"k",
"=",
"Buffer",
".",
"from",
"(",
"secretKey",
",",
"'base64'",
")",
";",
"if",
"(",
"k",
".",
"length",
"<",
"2",
"+",
"2",
"+",
"4",
"+",
"16",
"+",
"8",
"+",
"8",
"+",
"64",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Incorrect secret key length'",
")",
";",
"}",
"// Check signature algorithm.",
"if",
"(",
"k",
"[",
"0",
"]",
"!==",
"69",
"/* 'E' */",
"||",
"k",
"[",
"1",
"]",
"!==",
"100",
"/* 'd' */",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown signature algorithm'",
")",
";",
"}",
"// Check KDF algorithm",
"if",
"(",
"k",
"[",
"2",
"]",
"!==",
"66",
"/* 'B' */",
"||",
"k",
"[",
"3",
"]",
"!==",
"75",
"/* 'K' */",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unsupported KDF algorithm'",
")",
";",
"}",
"// Extract fields.",
"const",
"rounds",
"=",
"k",
".",
"slice",
"(",
"4",
",",
"8",
")",
".",
"readUInt32BE",
"(",
"0",
")",
";",
"if",
"(",
"rounds",
"!==",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Rounds must be 0; unlock key before passing to sign.'",
")",
"}",
"const",
"checksum",
"=",
"k",
".",
"slice",
"(",
"24",
",",
"32",
")",
";",
"const",
"num",
"=",
"Buffer",
".",
"from",
"(",
"k",
".",
"slice",
"(",
"32",
",",
"40",
")",
")",
";",
"const",
"key",
"=",
"Buffer",
".",
"from",
"(",
"k",
".",
"slice",
"(",
"40",
",",
"104",
")",
")",
";",
"// Verify key checksum.",
"if",
"(",
"!",
"nacl",
".",
"verify",
"(",
"checksum",
",",
"nacl",
".",
"hash",
"(",
"key",
")",
".",
"subarray",
"(",
"0",
",",
"8",
")",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Key checksum verification failure'",
")",
";",
"}",
"return",
"{",
"num",
",",
"key",
"}",
";",
"}"
] |
Converts secretKey from base64-encoded representation
into a Uint8Array acceptable for nacl.sign.
Returns an object with key num and secret key.
{
num: Uint8Array
key: Uint8Array
}
Throws if key format is incorrect.
@param {string} secretKey
@returns {Object} object { num, key }
|
[
"Converts",
"secretKey",
"from",
"base64",
"-",
"encoded",
"representation",
"into",
"a",
"Uint8Array",
"acceptable",
"for",
"nacl",
".",
"sign",
"."
] |
9d6fedeec727f16a31653e4bbd4efe164e0957cb
|
https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/signing.js#L117-L153
|
52,757
|
ergo-cms/ergo-core
|
api/plugin.js
|
_normaliseExt
|
function _normaliseExt(ext) { // we don't use '.' in our extension info... but some might leak in here and there
ext = (ext||'').trim();
if (ext.length && ext[0]=='.')
return ext.substr(1);
return ext;
}
|
javascript
|
function _normaliseExt(ext) { // we don't use '.' in our extension info... but some might leak in here and there
ext = (ext||'').trim();
if (ext.length && ext[0]=='.')
return ext.substr(1);
return ext;
}
|
[
"function",
"_normaliseExt",
"(",
"ext",
")",
"{",
"// we don't use '.' in our extension info... but some might leak in here and there",
"ext",
"=",
"(",
"ext",
"||",
"''",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"ext",
".",
"length",
"&&",
"ext",
"[",
"0",
"]",
"==",
"'.'",
")",
"return",
"ext",
".",
"substr",
"(",
"1",
")",
";",
"return",
"ext",
";",
"}"
] |
l.color = l._colors.Dim+l._colors.FgRed;
|
[
"l",
".",
"color",
"=",
"l",
".",
"_colors",
".",
"Dim",
"+",
"l",
".",
"_colors",
".",
"FgRed",
";"
] |
8ed4d087554b5f8cd93f0765719ecee14164ca71
|
https://github.com/ergo-cms/ergo-core/blob/8ed4d087554b5f8cd93f0765719ecee14164ca71/api/plugin.js#L24-L29
|
52,758
|
origin1tech/pargv
|
build/index.js
|
normalize
|
function normalize(def) {
if (~noMergeCmds.indexOf(command))
return stiks.argv.splitArgs(def);
return stiks.argv.mergeArgs(def, input);
}
|
javascript
|
function normalize(def) {
if (~noMergeCmds.indexOf(command))
return stiks.argv.splitArgs(def);
return stiks.argv.mergeArgs(def, input);
}
|
[
"function",
"normalize",
"(",
"def",
")",
"{",
"if",
"(",
"~",
"noMergeCmds",
".",
"indexOf",
"(",
"command",
")",
")",
"return",
"stiks",
".",
"argv",
".",
"splitArgs",
"(",
"def",
")",
";",
"return",
"stiks",
".",
"argv",
".",
"mergeArgs",
"(",
"def",
",",
"input",
")",
";",
"}"
] |
Merges default args with any input args.
|
[
"Merges",
"default",
"args",
"with",
"any",
"input",
"args",
"."
] |
3dfe91190b843e9b0d84f9a65bcd45a86617cc05
|
https://github.com/origin1tech/pargv/blob/3dfe91190b843e9b0d84f9a65bcd45a86617cc05/build/index.js#L27-L31
|
52,759
|
jasonsites/proxy-es-aws
|
src/aws.js
|
createSignedAWSRequest
|
function createSignedAWSRequest(params) {
const { body, credentials, endpoint, headers, method = 'GET', path, region } = params
const request = new AWS.HttpRequest(endpoint)
Object.assign(request, {
body,
headers: {
Host: endpoint.host,
'presigned-expires': false,
},
method,
path,
region,
})
const signed = signAWSRequest({ credentials, request })
return mergeAllowedClientHeaders({ headers, request: signed })
}
|
javascript
|
function createSignedAWSRequest(params) {
const { body, credentials, endpoint, headers, method = 'GET', path, region } = params
const request = new AWS.HttpRequest(endpoint)
Object.assign(request, {
body,
headers: {
Host: endpoint.host,
'presigned-expires': false,
},
method,
path,
region,
})
const signed = signAWSRequest({ credentials, request })
return mergeAllowedClientHeaders({ headers, request: signed })
}
|
[
"function",
"createSignedAWSRequest",
"(",
"params",
")",
"{",
"const",
"{",
"body",
",",
"credentials",
",",
"endpoint",
",",
"headers",
",",
"method",
"=",
"'GET'",
",",
"path",
",",
"region",
"}",
"=",
"params",
"const",
"request",
"=",
"new",
"AWS",
".",
"HttpRequest",
"(",
"endpoint",
")",
"Object",
".",
"assign",
"(",
"request",
",",
"{",
"body",
",",
"headers",
":",
"{",
"Host",
":",
"endpoint",
".",
"host",
",",
"'presigned-expires'",
":",
"false",
",",
"}",
",",
"method",
",",
"path",
",",
"region",
",",
"}",
")",
"const",
"signed",
"=",
"signAWSRequest",
"(",
"{",
"credentials",
",",
"request",
"}",
")",
"return",
"mergeAllowedClientHeaders",
"(",
"{",
"headers",
",",
"request",
":",
"signed",
"}",
")",
"}"
] |
Compose the request data to be sent to the AWS Node HTTP Client
@param {String} params.body - raw client request body
@param {Object} params.credentials - aws credentials
@param {String} params.endpoint - aws elasticsearch endpoint
@param {Object} params.headers - client request headers
@param {String} params.method - client request method
@param {String} params.path - client request path (url)
@param {String} params.region - aws region
@return {Object}
|
[
"Compose",
"the",
"request",
"data",
"to",
"be",
"sent",
"to",
"the",
"AWS",
"Node",
"HTTP",
"Client"
] |
b2625106d877fea76f74b0b88ed8568a8ff61612
|
https://github.com/jasonsites/proxy-es-aws/blob/b2625106d877fea76f74b0b88ed8568a8ff61612/src/aws.js#L22-L39
|
52,760
|
jasonsites/proxy-es-aws
|
src/aws.js
|
sendAWSRequest
|
function sendAWSRequest(req) {
return new Promise((resolve, reject) => {
const send = new AWS.NodeHttpClient()
send.handleRequest(req, null, (res) => {
let body = ''
res.on('data', (chunk) => {
body += chunk
})
res.on('end', () => {
const { headers, statusCode } = res
resolve({ body, headers, statusCode })
})
res.on('error', (err) => {
console.log(`Error: ${err}`)
reject(err)
})
}, (err) => {
console.log(`Error: ${err}`)
reject(err)
})
})
}
|
javascript
|
function sendAWSRequest(req) {
return new Promise((resolve, reject) => {
const send = new AWS.NodeHttpClient()
send.handleRequest(req, null, (res) => {
let body = ''
res.on('data', (chunk) => {
body += chunk
})
res.on('end', () => {
const { headers, statusCode } = res
resolve({ body, headers, statusCode })
})
res.on('error', (err) => {
console.log(`Error: ${err}`)
reject(err)
})
}, (err) => {
console.log(`Error: ${err}`)
reject(err)
})
})
}
|
[
"function",
"sendAWSRequest",
"(",
"req",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"send",
"=",
"new",
"AWS",
".",
"NodeHttpClient",
"(",
")",
"send",
".",
"handleRequest",
"(",
"req",
",",
"null",
",",
"(",
"res",
")",
"=>",
"{",
"let",
"body",
"=",
"''",
"res",
".",
"on",
"(",
"'data'",
",",
"(",
"chunk",
")",
"=>",
"{",
"body",
"+=",
"chunk",
"}",
")",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"const",
"{",
"headers",
",",
"statusCode",
"}",
"=",
"res",
"resolve",
"(",
"{",
"body",
",",
"headers",
",",
"statusCode",
"}",
")",
"}",
")",
"res",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"err",
"}",
"`",
")",
"reject",
"(",
"err",
")",
"}",
")",
"}",
",",
"(",
"err",
")",
"=>",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"err",
"}",
"`",
")",
"reject",
"(",
"err",
")",
"}",
")",
"}",
")",
"}"
] |
AWS HTTP request handler
@param {String} req - signed aws request
@return {Promise}
|
[
"AWS",
"HTTP",
"request",
"handler"
] |
b2625106d877fea76f74b0b88ed8568a8ff61612
|
https://github.com/jasonsites/proxy-es-aws/blob/b2625106d877fea76f74b0b88ed8568a8ff61612/src/aws.js#L84-L105
|
52,761
|
jasonsites/proxy-es-aws
|
src/aws.js
|
signAWSRequest
|
function signAWSRequest({ credentials, request }) {
const signer = new AWS.Signers.V4(request, 'es')
signer.addAuthorization(credentials, new Date())
return request
}
|
javascript
|
function signAWSRequest({ credentials, request }) {
const signer = new AWS.Signers.V4(request, 'es')
signer.addAuthorization(credentials, new Date())
return request
}
|
[
"function",
"signAWSRequest",
"(",
"{",
"credentials",
",",
"request",
"}",
")",
"{",
"const",
"signer",
"=",
"new",
"AWS",
".",
"Signers",
".",
"V4",
"(",
"request",
",",
"'es'",
")",
"signer",
".",
"addAuthorization",
"(",
"credentials",
",",
"new",
"Date",
"(",
")",
")",
"return",
"request",
"}"
] |
Signs an AWS HTTP Request object with the provided AWS Credentials object
@param {Object} param.credentials - aws credentials object
@param {Object} param.request - aws http request object
@return {Object} signed request
|
[
"Signs",
"an",
"AWS",
"HTTP",
"Request",
"object",
"with",
"the",
"provided",
"AWS",
"Credentials",
"object"
] |
b2625106d877fea76f74b0b88ed8568a8ff61612
|
https://github.com/jasonsites/proxy-es-aws/blob/b2625106d877fea76f74b0b88ed8568a8ff61612/src/aws.js#L131-L135
|
52,762
|
byron-dupreez/aws-stream-consumer-core
|
identify.js
|
resolveAndSetEventIdAndSeqNos
|
function resolveAndSetEventIdAndSeqNos(record, userRecord, state, context) {
// Get the resolveEventIdAndSeqNos function to use
const resolveEventIdAndSeqNos = settings.getResolveEventIdAndSeqNosFunction(context);
if (!resolveEventIdAndSeqNos) {
const errMsg = `FATAL - Cannot resolve event id & sequence numbers, since no 'resolveEventIdAndSeqNos' function is configured. Configure one & redeploy ASAP!`;
context.error(errMsg);
throw new FatalError(errMsg);
}
try {
// Resolve the event id & sequence number(s)
const eventIdAndSeqNos = resolveEventIdAndSeqNos(record, userRecord) || {};
// Set the event id & sequence number(s) on the given message's state or unusable record's state
setEventIdAndSeqNos(state, eventIdAndSeqNos);
return eventIdAndSeqNos;
} finally {
// Cache a description of the record for logging purposes
resolveAndSetRecordDesc(state);
}
}
|
javascript
|
function resolveAndSetEventIdAndSeqNos(record, userRecord, state, context) {
// Get the resolveEventIdAndSeqNos function to use
const resolveEventIdAndSeqNos = settings.getResolveEventIdAndSeqNosFunction(context);
if (!resolveEventIdAndSeqNos) {
const errMsg = `FATAL - Cannot resolve event id & sequence numbers, since no 'resolveEventIdAndSeqNos' function is configured. Configure one & redeploy ASAP!`;
context.error(errMsg);
throw new FatalError(errMsg);
}
try {
// Resolve the event id & sequence number(s)
const eventIdAndSeqNos = resolveEventIdAndSeqNos(record, userRecord) || {};
// Set the event id & sequence number(s) on the given message's state or unusable record's state
setEventIdAndSeqNos(state, eventIdAndSeqNos);
return eventIdAndSeqNos;
} finally {
// Cache a description of the record for logging purposes
resolveAndSetRecordDesc(state);
}
}
|
[
"function",
"resolveAndSetEventIdAndSeqNos",
"(",
"record",
",",
"userRecord",
",",
"state",
",",
"context",
")",
"{",
"// Get the resolveEventIdAndSeqNos function to use",
"const",
"resolveEventIdAndSeqNos",
"=",
"settings",
".",
"getResolveEventIdAndSeqNosFunction",
"(",
"context",
")",
";",
"if",
"(",
"!",
"resolveEventIdAndSeqNos",
")",
"{",
"const",
"errMsg",
"=",
"`",
"`",
";",
"context",
".",
"error",
"(",
"errMsg",
")",
";",
"throw",
"new",
"FatalError",
"(",
"errMsg",
")",
";",
"}",
"try",
"{",
"// Resolve the event id & sequence number(s)",
"const",
"eventIdAndSeqNos",
"=",
"resolveEventIdAndSeqNos",
"(",
"record",
",",
"userRecord",
")",
"||",
"{",
"}",
";",
"// Set the event id & sequence number(s) on the given message's state or unusable record's state",
"setEventIdAndSeqNos",
"(",
"state",
",",
"eventIdAndSeqNos",
")",
";",
"return",
"eventIdAndSeqNos",
";",
"}",
"finally",
"{",
"// Cache a description of the record for logging purposes",
"resolveAndSetRecordDesc",
"(",
"state",
")",
";",
"}",
"}"
] |
Resolves the eventID, eventSeqNo and optional eventSubSeqNo for the given record & optional user record using the
configured `resolveEventIdAndSeqNos` function and then updates the given message or unusable record state with the
resolved values.
@param {Record} record - the record from which to resolve its eventID and eventSeqNo
@param {UserRecord|undefined} [userRecord] - the optional user record (if applicable) from which to resolve its eventSubSeqNo
@param {MessageState|UnusableRecordState} state - the message's or unusable record's tracked state to update with the resolved event id and sequence numbers
@param {StreamConsumerContext} context - the context to use
@param {ResolveEventIdAndSeqNos} [context.streamProcessing.resolveEventIdAndSeqNos]
@return {EventIdAndSeqNos} the resolved event id & sequence number(s)
|
[
"Resolves",
"the",
"eventID",
"eventSeqNo",
"and",
"optional",
"eventSubSeqNo",
"for",
"the",
"given",
"record",
"&",
"optional",
"user",
"record",
"using",
"the",
"configured",
"resolveEventIdAndSeqNos",
"function",
"and",
"then",
"updates",
"the",
"given",
"message",
"or",
"unusable",
"record",
"state",
"with",
"the",
"resolved",
"values",
"."
] |
9b256084297f80d373bcf483aaf68a9da176b3d7
|
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/identify.js#L87-L110
|
52,763
|
byron-dupreez/aws-stream-consumer-core
|
identify.js
|
setMessageIdsAndSeqNos
|
function setMessageIdsAndSeqNos(state, messageIdsAndSeqNos) {
const {ids, keys, seqNos} = messageIdsAndSeqNos || {};
setIds(state, ids);
setKeys(state, keys);
setSeqNos(state, seqNos);
return state;
}
|
javascript
|
function setMessageIdsAndSeqNos(state, messageIdsAndSeqNos) {
const {ids, keys, seqNos} = messageIdsAndSeqNos || {};
setIds(state, ids);
setKeys(state, keys);
setSeqNos(state, seqNos);
return state;
}
|
[
"function",
"setMessageIdsAndSeqNos",
"(",
"state",
",",
"messageIdsAndSeqNos",
")",
"{",
"const",
"{",
"ids",
",",
"keys",
",",
"seqNos",
"}",
"=",
"messageIdsAndSeqNos",
"||",
"{",
"}",
";",
"setIds",
"(",
"state",
",",
"ids",
")",
";",
"setKeys",
"(",
"state",
",",
"keys",
")",
";",
"setSeqNos",
"(",
"state",
",",
"seqNos",
")",
";",
"return",
"state",
";",
"}"
] |
Updates the given message state with the given message ids, keys & sequence numbers & event id & sequence numbers.
@param {MessageState} state - the message state to be updated
@param {MessageIdsAndSeqNos} messageIdsAndSeqNos
|
[
"Updates",
"the",
"given",
"message",
"state",
"with",
"the",
"given",
"message",
"ids",
"keys",
"&",
"sequence",
"numbers",
"&",
"event",
"id",
"&",
"sequence",
"numbers",
"."
] |
9b256084297f80d373bcf483aaf68a9da176b3d7
|
https://github.com/byron-dupreez/aws-stream-consumer-core/blob/9b256084297f80d373bcf483aaf68a9da176b3d7/identify.js#L192-L200
|
52,764
|
staticbuild/staticbuild
|
lib/devserver/app.js
|
init
|
function init(targetBuild) {
// CONSIDER: The `|| StaticBuild.current` isn't really necessary.
build = targetBuild || StaticBuild.current;
initViewEngines();
// Request Pipeline
initFavicon();
initLogging();
initApiProxy();
initParsing();
initCssLESS();
initSASS();
initViewRouting();
initErrorHandling();
}
|
javascript
|
function init(targetBuild) {
// CONSIDER: The `|| StaticBuild.current` isn't really necessary.
build = targetBuild || StaticBuild.current;
initViewEngines();
// Request Pipeline
initFavicon();
initLogging();
initApiProxy();
initParsing();
initCssLESS();
initSASS();
initViewRouting();
initErrorHandling();
}
|
[
"function",
"init",
"(",
"targetBuild",
")",
"{",
"// CONSIDER: The `|| StaticBuild.current` isn't really necessary.",
"build",
"=",
"targetBuild",
"||",
"StaticBuild",
".",
"current",
";",
"initViewEngines",
"(",
")",
";",
"// Request Pipeline",
"initFavicon",
"(",
")",
";",
"initLogging",
"(",
")",
";",
"initApiProxy",
"(",
")",
";",
"initParsing",
"(",
")",
";",
"initCssLESS",
"(",
")",
";",
"initSASS",
"(",
")",
";",
"initViewRouting",
"(",
")",
";",
"initErrorHandling",
"(",
")",
";",
"}"
] |
Initializes the Express app without running it.
@param {StaticBuild} [targetBuild] The target build.
|
[
"Initializes",
"the",
"Express",
"app",
"without",
"running",
"it",
"."
] |
73891a9a719de46ba07c26a10ce36c43da34ff0e
|
https://github.com/staticbuild/staticbuild/blob/73891a9a719de46ba07c26a10ce36c43da34ff0e/lib/devserver/app.js#L34-L47
|
52,765
|
troybetz/common-vimeo
|
lib/prepare-embed.js
|
prepareEmbed
|
function prepareEmbed(embedID) {
var embed = document.getElementById(embedID);
if (!isEmbeddedVideo(embed)) {
throw new Error('embed must be an iframe');
}
enableAPIControl(embed);
}
|
javascript
|
function prepareEmbed(embedID) {
var embed = document.getElementById(embedID);
if (!isEmbeddedVideo(embed)) {
throw new Error('embed must be an iframe');
}
enableAPIControl(embed);
}
|
[
"function",
"prepareEmbed",
"(",
"embedID",
")",
"{",
"var",
"embed",
"=",
"document",
".",
"getElementById",
"(",
"embedID",
")",
";",
"if",
"(",
"!",
"isEmbeddedVideo",
"(",
"embed",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'embed must be an iframe'",
")",
";",
"}",
"enableAPIControl",
"(",
"embed",
")",
";",
"}"
] |
Prepare an iframe for API control.
Embedded Vimeo videos require `api` & `player_id`
parameters set to be controlled.
@param {String} embedID - id of iframe to prepare
|
[
"Prepare",
"an",
"iframe",
"for",
"API",
"control",
"."
] |
c978bbf75cef73872c476369dd6d7363e2dddc39
|
https://github.com/troybetz/common-vimeo/blob/c978bbf75cef73872c476369dd6d7363e2dddc39/lib/prepare-embed.js#L16-L24
|
52,766
|
troybetz/common-vimeo
|
lib/prepare-embed.js
|
isAPIEnabled
|
function isAPIEnabled(embed) {
var regex = '\/?api=1&player_id=' + embed.id;
regex = new RegExp(regex);
return regex.test(embed.src);
}
|
javascript
|
function isAPIEnabled(embed) {
var regex = '\/?api=1&player_id=' + embed.id;
regex = new RegExp(regex);
return regex.test(embed.src);
}
|
[
"function",
"isAPIEnabled",
"(",
"embed",
")",
"{",
"var",
"regex",
"=",
"'\\/?api=1&player_id='",
"+",
"embed",
".",
"id",
";",
"regex",
"=",
"new",
"RegExp",
"(",
"regex",
")",
";",
"return",
"regex",
".",
"test",
"(",
"embed",
".",
"src",
")",
";",
"}"
] |
Determine if required `src` parameters are included in `embed`
@param {Object} embed
@returns {Boolean}
|
[
"Determine",
"if",
"required",
"src",
"parameters",
"are",
"included",
"in",
"embed"
] |
c978bbf75cef73872c476369dd6d7363e2dddc39
|
https://github.com/troybetz/common-vimeo/blob/c978bbf75cef73872c476369dd6d7363e2dddc39/lib/prepare-embed.js#L45-L49
|
52,767
|
redisjs/jsr-server
|
lib/request.js
|
Request
|
function Request(conn, cmd, args) {
// current connection
this.conn = conn;
// command name
this.cmd = cmd;
// command arguments may be modified
// during validation
this.args = args;
// raw command arguments, injected by the server
this.raw = null;
// server will inject this
// based upon the selected db index
// for the connection
this.db = null;
// info object decorated with additional
// information during validation, server will
// inject this
this.info = null;
// server configuration object
this.conf = null;
// alias to the command definition
this.def = null;
// mark this request as coming from a script
this.script = false;
}
|
javascript
|
function Request(conn, cmd, args) {
// current connection
this.conn = conn;
// command name
this.cmd = cmd;
// command arguments may be modified
// during validation
this.args = args;
// raw command arguments, injected by the server
this.raw = null;
// server will inject this
// based upon the selected db index
// for the connection
this.db = null;
// info object decorated with additional
// information during validation, server will
// inject this
this.info = null;
// server configuration object
this.conf = null;
// alias to the command definition
this.def = null;
// mark this request as coming from a script
this.script = false;
}
|
[
"function",
"Request",
"(",
"conn",
",",
"cmd",
",",
"args",
")",
"{",
"// current connection",
"this",
".",
"conn",
"=",
"conn",
";",
"// command name",
"this",
".",
"cmd",
"=",
"cmd",
";",
"// command arguments may be modified",
"// during validation",
"this",
".",
"args",
"=",
"args",
";",
"// raw command arguments, injected by the server",
"this",
".",
"raw",
"=",
"null",
";",
"// server will inject this",
"// based upon the selected db index",
"// for the connection",
"this",
".",
"db",
"=",
"null",
";",
"// info object decorated with additional",
"// information during validation, server will",
"// inject this",
"this",
".",
"info",
"=",
"null",
";",
"// server configuration object",
"this",
".",
"conf",
"=",
"null",
";",
"// alias to the command definition",
"this",
".",
"def",
"=",
"null",
";",
"// mark this request as coming from a script",
"this",
".",
"script",
"=",
"false",
";",
"}"
] |
Encapsulate a connection request.
@param conn The connection handling the request.
@param cmd The command to execute.
@param args The command arguments.
|
[
"Encapsulate",
"a",
"connection",
"request",
"."
] |
49413052d3039524fbdd2ade0ef9bae26cb4d647
|
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/request.js#L8-L41
|
52,768
|
redisjs/jsr-server
|
lib/request.js
|
destroy
|
function destroy() {
this.conn = null;
this.cmd = null;
this.args = null;
this.db = null;
this.info = null;
this.conf = null;
this.def = null;
}
|
javascript
|
function destroy() {
this.conn = null;
this.cmd = null;
this.args = null;
this.db = null;
this.info = null;
this.conf = null;
this.def = null;
}
|
[
"function",
"destroy",
"(",
")",
"{",
"this",
".",
"conn",
"=",
"null",
";",
"this",
".",
"cmd",
"=",
"null",
";",
"this",
".",
"args",
"=",
"null",
";",
"this",
".",
"db",
"=",
"null",
";",
"this",
".",
"info",
"=",
"null",
";",
"this",
".",
"conf",
"=",
"null",
";",
"this",
".",
"def",
"=",
"null",
";",
"}"
] |
Destroy this request.
|
[
"Destroy",
"this",
"request",
"."
] |
49413052d3039524fbdd2ade0ef9bae26cb4d647
|
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/request.js#L46-L54
|
52,769
|
redisjs/jsr-server
|
lib/command/pubsub/subscribe.js
|
execute
|
function execute(req, res) {
this.state.pubsub.subscribe(req.conn, req.args);
}
|
javascript
|
function execute(req, res) {
this.state.pubsub.subscribe(req.conn, req.args);
}
|
[
"function",
"execute",
"(",
"req",
",",
"res",
")",
"{",
"this",
".",
"state",
".",
"pubsub",
".",
"subscribe",
"(",
"req",
".",
"conn",
",",
"req",
".",
"args",
")",
";",
"}"
] |
Respond to the SUBSCRIBE command.
|
[
"Respond",
"to",
"the",
"SUBSCRIBE",
"command",
"."
] |
49413052d3039524fbdd2ade0ef9bae26cb4d647
|
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/pubsub/subscribe.js#L17-L19
|
52,770
|
sendanor/nor-nopg
|
src/bin/nopg.js
|
markdown_table
|
function markdown_table (headers, table) {
// FIXME: Implement better markdown table formating
return ARRAY([headers, [ "---", "---" ]]).concat(table).map(cols => '| ' + ARRAY(cols).join(' | ') + ' |').join('\n');
}
|
javascript
|
function markdown_table (headers, table) {
// FIXME: Implement better markdown table formating
return ARRAY([headers, [ "---", "---" ]]).concat(table).map(cols => '| ' + ARRAY(cols).join(' | ') + ' |').join('\n');
}
|
[
"function",
"markdown_table",
"(",
"headers",
",",
"table",
")",
"{",
"// FIXME: Implement better markdown table formating",
"return",
"ARRAY",
"(",
"[",
"headers",
",",
"[",
"\"---\"",
",",
"\"---\"",
"]",
"]",
")",
".",
"concat",
"(",
"table",
")",
".",
"map",
"(",
"cols",
"=>",
"'| '",
"+",
"ARRAY",
"(",
"cols",
")",
".",
"join",
"(",
"' | '",
")",
"+",
"' |'",
")",
".",
"join",
"(",
"'\\n'",
")",
";",
"}"
] |
Returns markdown formated table
@param headers
@param table
@returns {number}
|
[
"Returns",
"markdown",
"formated",
"table"
] |
0d99b86c1a1996b5828b56de8de23700df8bbc0c
|
https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/bin/nopg.js#L61-L64
|
52,771
|
ENOW-IJI/ENOW-console
|
dist/src/group.js
|
_orphan
|
function _orphan(_el) {
var id = _jsPlumb.getId(_el);
var pos = _jsPlumb.getOffset(_el);
_el.parentNode.removeChild(_el);
_jsPlumb.getContainer().appendChild(_el);
_jsPlumb.setPosition(_el, pos);
delete _el._jsPlumbGroup;
_unbindDragHandlers(_el);
_jsPlumb.dragManager.clearParent(_el, id);
}
|
javascript
|
function _orphan(_el) {
var id = _jsPlumb.getId(_el);
var pos = _jsPlumb.getOffset(_el);
_el.parentNode.removeChild(_el);
_jsPlumb.getContainer().appendChild(_el);
_jsPlumb.setPosition(_el, pos);
delete _el._jsPlumbGroup;
_unbindDragHandlers(_el);
_jsPlumb.dragManager.clearParent(_el, id);
}
|
[
"function",
"_orphan",
"(",
"_el",
")",
"{",
"var",
"id",
"=",
"_jsPlumb",
".",
"getId",
"(",
"_el",
")",
";",
"var",
"pos",
"=",
"_jsPlumb",
".",
"getOffset",
"(",
"_el",
")",
";",
"_el",
".",
"parentNode",
".",
"removeChild",
"(",
"_el",
")",
";",
"_jsPlumb",
".",
"getContainer",
"(",
")",
".",
"appendChild",
"(",
"_el",
")",
";",
"_jsPlumb",
".",
"setPosition",
"(",
"_el",
",",
"pos",
")",
";",
"delete",
"_el",
".",
"_jsPlumbGroup",
";",
"_unbindDragHandlers",
"(",
"_el",
")",
";",
"_jsPlumb",
".",
"dragManager",
".",
"clearParent",
"(",
"_el",
",",
"id",
")",
";",
"}"
] |
orphaning an element means taking it out of the group and adding it to the main jsplumb container.
|
[
"orphaning",
"an",
"element",
"means",
"taking",
"it",
"out",
"of",
"the",
"group",
"and",
"adding",
"it",
"to",
"the",
"main",
"jsplumb",
"container",
"."
] |
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
|
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/dist/src/group.js#L539-L548
|
52,772
|
ENOW-IJI/ENOW-console
|
dist/src/group.js
|
_pruneOrOrphan
|
function _pruneOrOrphan(p) {
if (!_isInsideParent(p.el, p.pos)) {
p.el._jsPlumbGroup.remove(p.el);
if (prune) {
_jsPlumb.remove(p.el);
} else {
_orphan(p.el);
}
}
}
|
javascript
|
function _pruneOrOrphan(p) {
if (!_isInsideParent(p.el, p.pos)) {
p.el._jsPlumbGroup.remove(p.el);
if (prune) {
_jsPlumb.remove(p.el);
} else {
_orphan(p.el);
}
}
}
|
[
"function",
"_pruneOrOrphan",
"(",
"p",
")",
"{",
"if",
"(",
"!",
"_isInsideParent",
"(",
"p",
".",
"el",
",",
"p",
".",
"pos",
")",
")",
"{",
"p",
".",
"el",
".",
"_jsPlumbGroup",
".",
"remove",
"(",
"p",
".",
"el",
")",
";",
"if",
"(",
"prune",
")",
"{",
"_jsPlumb",
".",
"remove",
"(",
"p",
".",
"el",
")",
";",
"}",
"else",
"{",
"_orphan",
"(",
"p",
".",
"el",
")",
";",
"}",
"}",
"}"
] |
remove an element from the group, then either prune it from the jsplumb instance, or just orphan it.
|
[
"remove",
"an",
"element",
"from",
"the",
"group",
"then",
"either",
"prune",
"it",
"from",
"the",
"jsplumb",
"instance",
"or",
"just",
"orphan",
"it",
"."
] |
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
|
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/dist/src/group.js#L553-L562
|
52,773
|
ENOW-IJI/ENOW-console
|
dist/src/group.js
|
_revalidate
|
function _revalidate(_el) {
var id = _jsPlumb.getId(_el);
_jsPlumb.revalidate(_el);
_jsPlumb.dragManager.revalidateParent(_el, id);
}
|
javascript
|
function _revalidate(_el) {
var id = _jsPlumb.getId(_el);
_jsPlumb.revalidate(_el);
_jsPlumb.dragManager.revalidateParent(_el, id);
}
|
[
"function",
"_revalidate",
"(",
"_el",
")",
"{",
"var",
"id",
"=",
"_jsPlumb",
".",
"getId",
"(",
"_el",
")",
";",
"_jsPlumb",
".",
"revalidate",
"(",
"_el",
")",
";",
"_jsPlumb",
".",
"dragManager",
".",
"revalidateParent",
"(",
"_el",
",",
"id",
")",
";",
"}"
] |
redraws the element
|
[
"redraws",
"the",
"element"
] |
f241ed4e645a7da0cd1a6ca86e896a5b73be53e5
|
https://github.com/ENOW-IJI/ENOW-console/blob/f241ed4e645a7da0cd1a6ca86e896a5b73be53e5/dist/src/group.js#L567-L571
|
52,774
|
IonicaBizau/camelo
|
lib/index.js
|
camelo
|
function camelo(input, regex, uc) {
regex = regex || DEFAULT_SPLIT;
var splits = null;
if (Array.isArray(regex)) {
regex = new RegExp(regex.map(reEscape).join("|"), "g");
} else if (typeof regex === "boolean") {
uc = regex;
regex = DEFAULT_SPLIT;
}
splits = input.split(regex);
if (uc) {
return ucFirstArray(splits).join("");
}
return splits[0] + ucFirstArray(splits.slice(1)).join("");
}
|
javascript
|
function camelo(input, regex, uc) {
regex = regex || DEFAULT_SPLIT;
var splits = null;
if (Array.isArray(regex)) {
regex = new RegExp(regex.map(reEscape).join("|"), "g");
} else if (typeof regex === "boolean") {
uc = regex;
regex = DEFAULT_SPLIT;
}
splits = input.split(regex);
if (uc) {
return ucFirstArray(splits).join("");
}
return splits[0] + ucFirstArray(splits.slice(1)).join("");
}
|
[
"function",
"camelo",
"(",
"input",
",",
"regex",
",",
"uc",
")",
"{",
"regex",
"=",
"regex",
"||",
"DEFAULT_SPLIT",
";",
"var",
"splits",
"=",
"null",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"regex",
")",
")",
"{",
"regex",
"=",
"new",
"RegExp",
"(",
"regex",
".",
"map",
"(",
"reEscape",
")",
".",
"join",
"(",
"\"|\"",
")",
",",
"\"g\"",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"regex",
"===",
"\"boolean\"",
")",
"{",
"uc",
"=",
"regex",
";",
"regex",
"=",
"DEFAULT_SPLIT",
";",
"}",
"splits",
"=",
"input",
".",
"split",
"(",
"regex",
")",
";",
"if",
"(",
"uc",
")",
"{",
"return",
"ucFirstArray",
"(",
"splits",
")",
".",
"join",
"(",
"\"\"",
")",
";",
"}",
"return",
"splits",
"[",
"0",
"]",
"+",
"ucFirstArray",
"(",
"splits",
".",
"slice",
"(",
"1",
")",
")",
".",
"join",
"(",
"\"\"",
")",
";",
"}"
] |
camelo
Converts an input string into camel-case style.
@name camelo
@function
@param {String} input The input string.
@param {Regex|String|Array} regex A regular expression, a string character or an array of strings used to split the input string.
@param {Boolean} uc If `true`, it will uppercase the first word as well.
@return {String} The camelized input value.
|
[
"camelo",
"Converts",
"an",
"input",
"string",
"into",
"camel",
"-",
"case",
"style",
"."
] |
abc9c956b29acad48d2600f1cd83bda762a5ab88
|
https://github.com/IonicaBizau/camelo/blob/abc9c956b29acad48d2600f1cd83bda762a5ab88/lib/index.js#L20-L40
|
52,775
|
AndiDittrich/Node.cluster-magic
|
lib/worker-manager.js
|
startWorker
|
function startWorker(triggeredByError=false){
return new Promise(function(resolve){
// default restart delay
let restartDelay = 0;
// worker restart because of died process ?
if (triggeredByError === true){
// increment restart counter
_restartCounter++;
}
// delayed restart ?
if (_restartCounter > 10){
// calculate restart delay (min: 2s)
restartDelay = 200 * _restartCounter;
// trigger alert message
_logger.alert(`delayed worker-restart of ${restartDelay/1000}s - number of failed processes: ${_restartCounter}`);
}
// trigger async fork
setTimeout(() => {
// create a new child process
// note: this method RELOADS the entire js file/module! - it is NOT a classical process.fork() !
// this allows you to hot-reload your application by restarting the workers
const worker = _cluster.fork();
// return worker
resolve(worker);
}, restartDelay);
});
}
|
javascript
|
function startWorker(triggeredByError=false){
return new Promise(function(resolve){
// default restart delay
let restartDelay = 0;
// worker restart because of died process ?
if (triggeredByError === true){
// increment restart counter
_restartCounter++;
}
// delayed restart ?
if (_restartCounter > 10){
// calculate restart delay (min: 2s)
restartDelay = 200 * _restartCounter;
// trigger alert message
_logger.alert(`delayed worker-restart of ${restartDelay/1000}s - number of failed processes: ${_restartCounter}`);
}
// trigger async fork
setTimeout(() => {
// create a new child process
// note: this method RELOADS the entire js file/module! - it is NOT a classical process.fork() !
// this allows you to hot-reload your application by restarting the workers
const worker = _cluster.fork();
// return worker
resolve(worker);
}, restartDelay);
});
}
|
[
"function",
"startWorker",
"(",
"triggeredByError",
"=",
"false",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"// default restart delay",
"let",
"restartDelay",
"=",
"0",
";",
"// worker restart because of died process ?",
"if",
"(",
"triggeredByError",
"===",
"true",
")",
"{",
"// increment restart counter",
"_restartCounter",
"++",
";",
"}",
"// delayed restart ?",
"if",
"(",
"_restartCounter",
">",
"10",
")",
"{",
"// calculate restart delay (min: 2s)",
"restartDelay",
"=",
"200",
"*",
"_restartCounter",
";",
"// trigger alert message",
"_logger",
".",
"alert",
"(",
"`",
"${",
"restartDelay",
"/",
"1000",
"}",
"${",
"_restartCounter",
"}",
"`",
")",
";",
"}",
"// trigger async fork",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"// create a new child process",
"// note: this method RELOADS the entire js file/module! - it is NOT a classical process.fork() !",
"// this allows you to hot-reload your application by restarting the workers",
"const",
"worker",
"=",
"_cluster",
".",
"fork",
"(",
")",
";",
"// return worker",
"resolve",
"(",
"worker",
")",
";",
"}",
",",
"restartDelay",
")",
";",
"}",
")",
";",
"}"
] |
start a new worker
|
[
"start",
"a",
"new",
"worker"
] |
b6b1d49164055ff8cbaaf679c208b62beba3ccbe
|
https://github.com/AndiDittrich/Node.cluster-magic/blob/b6b1d49164055ff8cbaaf679c208b62beba3ccbe/lib/worker-manager.js#L16-L48
|
52,776
|
AndiDittrich/Node.cluster-magic
|
lib/worker-manager.js
|
stopWorker
|
function stopWorker(worker){
return new Promise(function(resolve, reject){
// set kill timeout
const killTimeout = setTimeout(() => {
// kill the worker
worker.kill();
// failed to disconnect within given time
reject(new Error(`process ${worker.process.pid} killed by timeout of ${_workerShutdownTimeout/1000}s - disconnect() failed`));
}, _workerShutdownTimeout);
// wait for exit + disconnect
worker.on('disconnect', () => {
_logger.log(`disconnect event ${worker.process.pid}`);
// disable kill timer
clearTimeout(killTimeout);
// ok
resolve();
});
// trigger disconnect
worker.disconnect();
});
}
|
javascript
|
function stopWorker(worker){
return new Promise(function(resolve, reject){
// set kill timeout
const killTimeout = setTimeout(() => {
// kill the worker
worker.kill();
// failed to disconnect within given time
reject(new Error(`process ${worker.process.pid} killed by timeout of ${_workerShutdownTimeout/1000}s - disconnect() failed`));
}, _workerShutdownTimeout);
// wait for exit + disconnect
worker.on('disconnect', () => {
_logger.log(`disconnect event ${worker.process.pid}`);
// disable kill timer
clearTimeout(killTimeout);
// ok
resolve();
});
// trigger disconnect
worker.disconnect();
});
}
|
[
"function",
"stopWorker",
"(",
"worker",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"// set kill timeout",
"const",
"killTimeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"// kill the worker",
"worker",
".",
"kill",
"(",
")",
";",
"// failed to disconnect within given time",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"worker",
".",
"process",
".",
"pid",
"}",
"${",
"_workerShutdownTimeout",
"/",
"1000",
"}",
"`",
")",
")",
";",
"}",
",",
"_workerShutdownTimeout",
")",
";",
"// wait for exit + disconnect",
"worker",
".",
"on",
"(",
"'disconnect'",
",",
"(",
")",
"=>",
"{",
"_logger",
".",
"log",
"(",
"`",
"${",
"worker",
".",
"process",
".",
"pid",
"}",
"`",
")",
";",
"// disable kill timer",
"clearTimeout",
"(",
"killTimeout",
")",
";",
"// ok",
"resolve",
"(",
")",
";",
"}",
")",
";",
"// trigger disconnect",
"worker",
".",
"disconnect",
"(",
")",
";",
"}",
")",
";",
"}"
] |
worker gracefull shutdown
|
[
"worker",
"gracefull",
"shutdown"
] |
b6b1d49164055ff8cbaaf679c208b62beba3ccbe
|
https://github.com/AndiDittrich/Node.cluster-magic/blob/b6b1d49164055ff8cbaaf679c208b62beba3ccbe/lib/worker-manager.js#L51-L75
|
52,777
|
AndiDittrich/Node.cluster-magic
|
lib/worker-manager.js
|
shutdown
|
function shutdown(){
// trigger stop on all workers
// catch errors thrown by killed workers
return Promise.all(Object.values(_cluster.workers).map(worker => stopWorker(worker).catch(err => _logger.error(err))));
}
|
javascript
|
function shutdown(){
// trigger stop on all workers
// catch errors thrown by killed workers
return Promise.all(Object.values(_cluster.workers).map(worker => stopWorker(worker).catch(err => _logger.error(err))));
}
|
[
"function",
"shutdown",
"(",
")",
"{",
"// trigger stop on all workers",
"// catch errors thrown by killed workers",
"return",
"Promise",
".",
"all",
"(",
"Object",
".",
"values",
"(",
"_cluster",
".",
"workers",
")",
".",
"map",
"(",
"worker",
"=>",
"stopWorker",
"(",
"worker",
")",
".",
"catch",
"(",
"err",
"=>",
"_logger",
".",
"error",
"(",
"err",
")",
")",
")",
")",
";",
"}"
] |
shutdown all workers
|
[
"shutdown",
"all",
"workers"
] |
b6b1d49164055ff8cbaaf679c208b62beba3ccbe
|
https://github.com/AndiDittrich/Node.cluster-magic/blob/b6b1d49164055ff8cbaaf679c208b62beba3ccbe/lib/worker-manager.js#L78-L82
|
52,778
|
psiphi75/ss-logger
|
index.js
|
setOutput
|
function setOutput(output) {
if (!output ||
typeof output.log !== 'function') {
throw Error('logger.setOutput: expect an object as the parameter with "log" and "error" properties.');
}
outputFunctions = {
log: output.log,
error: (typeof output.error === 'function') ? output.error : output.log
};
}
|
javascript
|
function setOutput(output) {
if (!output ||
typeof output.log !== 'function') {
throw Error('logger.setOutput: expect an object as the parameter with "log" and "error" properties.');
}
outputFunctions = {
log: output.log,
error: (typeof output.error === 'function') ? output.error : output.log
};
}
|
[
"function",
"setOutput",
"(",
"output",
")",
"{",
"if",
"(",
"!",
"output",
"||",
"typeof",
"output",
".",
"log",
"!==",
"'function'",
")",
"{",
"throw",
"Error",
"(",
"'logger.setOutput: expect an object as the parameter with \"log\" and \"error\" properties.'",
")",
";",
"}",
"outputFunctions",
"=",
"{",
"log",
":",
"output",
".",
"log",
",",
"error",
":",
"(",
"typeof",
"output",
".",
"error",
"===",
"'function'",
")",
"?",
"output",
".",
"error",
":",
"output",
".",
"log",
"}",
";",
"}"
] |
By default the `error` and `warn` levels log output to `console.error`, while all other
levels log output to `console.log`.
@param {Object} output - An object with 'log' and 'error' functions.
@throws {Error}
@example
log.setOutput({
error: myErrorStream
log: myLogStream
});
|
[
"By",
"default",
"the",
"error",
"and",
"warn",
"levels",
"log",
"output",
"to",
"console",
".",
"error",
"while",
"all",
"other",
"levels",
"log",
"output",
"to",
"console",
".",
"log",
"."
] |
f6042397b3403dbf864c3eba094978ffe8e93dea
|
https://github.com/psiphi75/ss-logger/blob/f6042397b3403dbf864c3eba094978ffe8e93dea/index.js#L142-L151
|
52,779
|
psiphi75/ss-logger
|
index.js
|
joinMsgArgs
|
function joinMsgArgs(msgArgs) {
if (!msgArgs) {
return '';
}
return msgArgs.map((arg) => {
if (arg === null) {
return 'null';
} else if (typeof arg === 'undefined') {
return 'undefined';
} else if (typeof arg === 'string') {
return arg;
} else if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch (ex) {
return arg.toString();
}
} else { // boolean, symbol, number, function
return arg.toString();
}
}).join(' ');
}
|
javascript
|
function joinMsgArgs(msgArgs) {
if (!msgArgs) {
return '';
}
return msgArgs.map((arg) => {
if (arg === null) {
return 'null';
} else if (typeof arg === 'undefined') {
return 'undefined';
} else if (typeof arg === 'string') {
return arg;
} else if (typeof arg === 'object') {
try {
return JSON.stringify(arg);
} catch (ex) {
return arg.toString();
}
} else { // boolean, symbol, number, function
return arg.toString();
}
}).join(' ');
}
|
[
"function",
"joinMsgArgs",
"(",
"msgArgs",
")",
"{",
"if",
"(",
"!",
"msgArgs",
")",
"{",
"return",
"''",
";",
"}",
"return",
"msgArgs",
".",
"map",
"(",
"(",
"arg",
")",
"=>",
"{",
"if",
"(",
"arg",
"===",
"null",
")",
"{",
"return",
"'null'",
";",
"}",
"else",
"if",
"(",
"typeof",
"arg",
"===",
"'undefined'",
")",
"{",
"return",
"'undefined'",
";",
"}",
"else",
"if",
"(",
"typeof",
"arg",
"===",
"'string'",
")",
"{",
"return",
"arg",
";",
"}",
"else",
"if",
"(",
"typeof",
"arg",
"===",
"'object'",
")",
"{",
"try",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"arg",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"arg",
".",
"toString",
"(",
")",
";",
"}",
"}",
"else",
"{",
"// boolean, symbol, number, function",
"return",
"arg",
".",
"toString",
"(",
")",
";",
"}",
"}",
")",
".",
"join",
"(",
"' '",
")",
";",
"}"
] |
Create the logging functions
|
[
"Create",
"the",
"logging",
"functions"
] |
f6042397b3403dbf864c3eba094978ffe8e93dea
|
https://github.com/psiphi75/ss-logger/blob/f6042397b3403dbf864c3eba094978ffe8e93dea/index.js#L160-L181
|
52,780
|
psiphi75/ss-logger
|
index.js
|
writeLog
|
function writeLog(levelName, varArgs) { // eslint-disable-line no-unused-vars
const args = [].slice.call(arguments);
args.splice(0, 1);
const str = format(new Date(), levelName, label, args);
if (LEVELS[levelName] <= LEVELS.warn) {
outputFunctions.error(str);
} else {
outputFunctions.log(str);
}
}
|
javascript
|
function writeLog(levelName, varArgs) { // eslint-disable-line no-unused-vars
const args = [].slice.call(arguments);
args.splice(0, 1);
const str = format(new Date(), levelName, label, args);
if (LEVELS[levelName] <= LEVELS.warn) {
outputFunctions.error(str);
} else {
outputFunctions.log(str);
}
}
|
[
"function",
"writeLog",
"(",
"levelName",
",",
"varArgs",
")",
"{",
"// eslint-disable-line no-unused-vars",
"const",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"args",
".",
"splice",
"(",
"0",
",",
"1",
")",
";",
"const",
"str",
"=",
"format",
"(",
"new",
"Date",
"(",
")",
",",
"levelName",
",",
"label",
",",
"args",
")",
";",
"if",
"(",
"LEVELS",
"[",
"levelName",
"]",
"<=",
"LEVELS",
".",
"warn",
")",
"{",
"outputFunctions",
".",
"error",
"(",
"str",
")",
";",
"}",
"else",
"{",
"outputFunctions",
".",
"log",
"(",
"str",
")",
";",
"}",
"}"
] |
Create the log for writing.
@param {string} levelName - The name of the level to log at.
@param {...*} varArgs - The parameters of the original log.
@private
|
[
"Create",
"the",
"log",
"for",
"writing",
"."
] |
f6042397b3403dbf864c3eba094978ffe8e93dea
|
https://github.com/psiphi75/ss-logger/blob/f6042397b3403dbf864c3eba094978ffe8e93dea/index.js#L207-L218
|
52,781
|
jesusgoku/arrispwod
|
src/index.js
|
genPassOfDay
|
function genPassOfDay(d, s = DEFAULT_SEED) {
if (!(d instanceof Date)) {
throw new TypeError('Date is not a Date instance');
}
if (typeof s !== 'string') {
throw new TypeError('Seed is not a String instance');
}
if (s.length < 1) {
throw new Error('Seed min length: 1');
}
const seed = s.repeat(10);
const year = d.getFullYear() % 100; // Two last digits
const month = d.getMonth() + 1; // January === 1
const dayOfMonth = d.getDate();
const dayOfWeek = d.getDay() === 0 ? 6 : d.getDay() - 1; // Monday === 1
const l1 = TABLE1[dayOfWeek].slice(0);
l1.push(dayOfMonth);
l1.push(year + month - dayOfMonth < 0
? (year + month - dayOfMonth + 36) % 36
: (year + month - dayOfMonth) % 36);
l1.push((3 + (year + month) % 12) * dayOfMonth % 37 % 36);
const l2 = [...Array(8).keys()].map((_, i) => seed.charCodeAt(i) % 36);
const l3 = l1.map((f, i) => (f + l2[i]) % 36);
const l38 = l3.reduce((t, i) => t + i, 0) % 36;
const num8 = l38 % 6;
l3.push(l38);
l3.push(Math.round(Math.pow(num8, 2)));
const l4 = TABLE2[num8].map(i => l3[i]);
const l5 = l4.map((v, i) => (seed.charCodeAt(i) + v) % 36);
return l5.map(i => ALPHANUM[i]).join('');
}
|
javascript
|
function genPassOfDay(d, s = DEFAULT_SEED) {
if (!(d instanceof Date)) {
throw new TypeError('Date is not a Date instance');
}
if (typeof s !== 'string') {
throw new TypeError('Seed is not a String instance');
}
if (s.length < 1) {
throw new Error('Seed min length: 1');
}
const seed = s.repeat(10);
const year = d.getFullYear() % 100; // Two last digits
const month = d.getMonth() + 1; // January === 1
const dayOfMonth = d.getDate();
const dayOfWeek = d.getDay() === 0 ? 6 : d.getDay() - 1; // Monday === 1
const l1 = TABLE1[dayOfWeek].slice(0);
l1.push(dayOfMonth);
l1.push(year + month - dayOfMonth < 0
? (year + month - dayOfMonth + 36) % 36
: (year + month - dayOfMonth) % 36);
l1.push((3 + (year + month) % 12) * dayOfMonth % 37 % 36);
const l2 = [...Array(8).keys()].map((_, i) => seed.charCodeAt(i) % 36);
const l3 = l1.map((f, i) => (f + l2[i]) % 36);
const l38 = l3.reduce((t, i) => t + i, 0) % 36;
const num8 = l38 % 6;
l3.push(l38);
l3.push(Math.round(Math.pow(num8, 2)));
const l4 = TABLE2[num8].map(i => l3[i]);
const l5 = l4.map((v, i) => (seed.charCodeAt(i) + v) % 36);
return l5.map(i => ALPHANUM[i]).join('');
}
|
[
"function",
"genPassOfDay",
"(",
"d",
",",
"s",
"=",
"DEFAULT_SEED",
")",
"{",
"if",
"(",
"!",
"(",
"d",
"instanceof",
"Date",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Date is not a Date instance'",
")",
";",
"}",
"if",
"(",
"typeof",
"s",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Seed is not a String instance'",
")",
";",
"}",
"if",
"(",
"s",
".",
"length",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Seed min length: 1'",
")",
";",
"}",
"const",
"seed",
"=",
"s",
".",
"repeat",
"(",
"10",
")",
";",
"const",
"year",
"=",
"d",
".",
"getFullYear",
"(",
")",
"%",
"100",
";",
"// Two last digits",
"const",
"month",
"=",
"d",
".",
"getMonth",
"(",
")",
"+",
"1",
";",
"// January === 1",
"const",
"dayOfMonth",
"=",
"d",
".",
"getDate",
"(",
")",
";",
"const",
"dayOfWeek",
"=",
"d",
".",
"getDay",
"(",
")",
"===",
"0",
"?",
"6",
":",
"d",
".",
"getDay",
"(",
")",
"-",
"1",
";",
"// Monday === 1",
"const",
"l1",
"=",
"TABLE1",
"[",
"dayOfWeek",
"]",
".",
"slice",
"(",
"0",
")",
";",
"l1",
".",
"push",
"(",
"dayOfMonth",
")",
";",
"l1",
".",
"push",
"(",
"year",
"+",
"month",
"-",
"dayOfMonth",
"<",
"0",
"?",
"(",
"year",
"+",
"month",
"-",
"dayOfMonth",
"+",
"36",
")",
"%",
"36",
":",
"(",
"year",
"+",
"month",
"-",
"dayOfMonth",
")",
"%",
"36",
")",
";",
"l1",
".",
"push",
"(",
"(",
"3",
"+",
"(",
"year",
"+",
"month",
")",
"%",
"12",
")",
"*",
"dayOfMonth",
"%",
"37",
"%",
"36",
")",
";",
"const",
"l2",
"=",
"[",
"...",
"Array",
"(",
"8",
")",
".",
"keys",
"(",
")",
"]",
".",
"map",
"(",
"(",
"_",
",",
"i",
")",
"=>",
"seed",
".",
"charCodeAt",
"(",
"i",
")",
"%",
"36",
")",
";",
"const",
"l3",
"=",
"l1",
".",
"map",
"(",
"(",
"f",
",",
"i",
")",
"=>",
"(",
"f",
"+",
"l2",
"[",
"i",
"]",
")",
"%",
"36",
")",
";",
"const",
"l38",
"=",
"l3",
".",
"reduce",
"(",
"(",
"t",
",",
"i",
")",
"=>",
"t",
"+",
"i",
",",
"0",
")",
"%",
"36",
";",
"const",
"num8",
"=",
"l38",
"%",
"6",
";",
"l3",
".",
"push",
"(",
"l38",
")",
";",
"l3",
".",
"push",
"(",
"Math",
".",
"round",
"(",
"Math",
".",
"pow",
"(",
"num8",
",",
"2",
")",
")",
")",
";",
"const",
"l4",
"=",
"TABLE2",
"[",
"num8",
"]",
".",
"map",
"(",
"i",
"=>",
"l3",
"[",
"i",
"]",
")",
";",
"const",
"l5",
"=",
"l4",
".",
"map",
"(",
"(",
"v",
",",
"i",
")",
"=>",
"(",
"seed",
".",
"charCodeAt",
"(",
"i",
")",
"+",
"v",
")",
"%",
"36",
")",
";",
"return",
"l5",
".",
"map",
"(",
"i",
"=>",
"ALPHANUM",
"[",
"i",
"]",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
] |
Generate Pass of the day for Arris Router
@param {Date} d - Date for calculate password
@param {String} s - Seed for generate password. Min length: 1
|
[
"Generate",
"Pass",
"of",
"the",
"day",
"for",
"Arris",
"Router"
] |
59a5e8708f59a0424b27004b52d53a5e95df047c
|
https://github.com/jesusgoku/arrispwod/blob/59a5e8708f59a0424b27004b52d53a5e95df047c/src/index.js#L36-L75
|
52,782
|
linyngfly/omelo-admin
|
lib/consoleService.js
|
function(args) {
let service = args.service;
let record = args.record;
if (!service || !record || !record.module || !record.enable) {
return;
}
if (service.master) {
record.module.masterHandler(service.agent, null, function(err) {
logger.error('interval push should not have a callback.');
});
} else {
record.module.monitorHandler(service.agent, null, function(err) {
logger.error('interval push should not have a callback.');
});
}
}
|
javascript
|
function(args) {
let service = args.service;
let record = args.record;
if (!service || !record || !record.module || !record.enable) {
return;
}
if (service.master) {
record.module.masterHandler(service.agent, null, function(err) {
logger.error('interval push should not have a callback.');
});
} else {
record.module.monitorHandler(service.agent, null, function(err) {
logger.error('interval push should not have a callback.');
});
}
}
|
[
"function",
"(",
"args",
")",
"{",
"let",
"service",
"=",
"args",
".",
"service",
";",
"let",
"record",
"=",
"args",
".",
"record",
";",
"if",
"(",
"!",
"service",
"||",
"!",
"record",
"||",
"!",
"record",
".",
"module",
"||",
"!",
"record",
".",
"enable",
")",
"{",
"return",
";",
"}",
"if",
"(",
"service",
".",
"master",
")",
"{",
"record",
".",
"module",
".",
"masterHandler",
"(",
"service",
".",
"agent",
",",
"null",
",",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"'interval push should not have a callback.'",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"record",
".",
"module",
".",
"monitorHandler",
"(",
"service",
".",
"agent",
",",
"null",
",",
"function",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"'interval push should not have a callback.'",
")",
";",
"}",
")",
";",
"}",
"}"
] |
run schedule job
@param {Object} args argments
@api private
|
[
"run",
"schedule",
"job"
] |
1cd692c16ab63b9c0d4009535f300f2ca584b691
|
https://github.com/linyngfly/omelo-admin/blob/1cd692c16ab63b9c0d4009535f300f2ca584b691/lib/consoleService.js#L317-L333
|
|
52,783
|
jaredhanson/node-xtraverse
|
lib/collection.js
|
wrap
|
function wrap(nodes) {
nodes = nodes || [];
if ('string' == typeof nodes) {
nodes = new DOMParser().parseFromString(nodes);
}
if (nodes.attrNS && nodes._related) {
// attempt to re-wrap Collection, return it directly
return nodes;
} else if (nodes.documentElement) {
nodes = [ nodes.documentElement ];
} else if (nodes.nodeType) {
nodes = [ nodes ];
}
return new Collection(nodes);
}
|
javascript
|
function wrap(nodes) {
nodes = nodes || [];
if ('string' == typeof nodes) {
nodes = new DOMParser().parseFromString(nodes);
}
if (nodes.attrNS && nodes._related) {
// attempt to re-wrap Collection, return it directly
return nodes;
} else if (nodes.documentElement) {
nodes = [ nodes.documentElement ];
} else if (nodes.nodeType) {
nodes = [ nodes ];
}
return new Collection(nodes);
}
|
[
"function",
"wrap",
"(",
"nodes",
")",
"{",
"nodes",
"=",
"nodes",
"||",
"[",
"]",
";",
"if",
"(",
"'string'",
"==",
"typeof",
"nodes",
")",
"{",
"nodes",
"=",
"new",
"DOMParser",
"(",
")",
".",
"parseFromString",
"(",
"nodes",
")",
";",
"}",
"if",
"(",
"nodes",
".",
"attrNS",
"&&",
"nodes",
".",
"_related",
")",
"{",
"// attempt to re-wrap Collection, return it directly",
"return",
"nodes",
";",
"}",
"else",
"if",
"(",
"nodes",
".",
"documentElement",
")",
"{",
"nodes",
"=",
"[",
"nodes",
".",
"documentElement",
"]",
";",
"}",
"else",
"if",
"(",
"nodes",
".",
"nodeType",
")",
"{",
"nodes",
"=",
"[",
"nodes",
"]",
";",
"}",
"return",
"new",
"Collection",
"(",
"nodes",
")",
";",
"}"
] |
Wraps and returns a new collection of elements.
Examples:
$('<xml/>');
@param {String|Node|Collection|Array} nodes XML string or DOM nodes to wrap.
@return {Collection} The wrapped nodes.
@api public
|
[
"Wraps",
"and",
"returns",
"a",
"new",
"collection",
"of",
"elements",
"."
] |
ae5433a53600591d263385e12fbbacc32499d676
|
https://github.com/jaredhanson/node-xtraverse/blob/ae5433a53600591d263385e12fbbacc32499d676/lib/collection.js#L20-L35
|
52,784
|
jaredhanson/node-xtraverse
|
lib/collection.js
|
unique
|
function unique(ar) {
var a = []
, i = -1
, j
, has;
while (++i < ar.length) {
j = -1;
has = false;
while (++j < a.length) {
if (a[j] === ar[i]) {
has = true;
break;
}
}
if (!has) { a.push(ar[i]); }
}
return a;
}
|
javascript
|
function unique(ar) {
var a = []
, i = -1
, j
, has;
while (++i < ar.length) {
j = -1;
has = false;
while (++j < a.length) {
if (a[j] === ar[i]) {
has = true;
break;
}
}
if (!has) { a.push(ar[i]); }
}
return a;
}
|
[
"function",
"unique",
"(",
"ar",
")",
"{",
"var",
"a",
"=",
"[",
"]",
",",
"i",
"=",
"-",
"1",
",",
"j",
",",
"has",
";",
"while",
"(",
"++",
"i",
"<",
"ar",
".",
"length",
")",
"{",
"j",
"=",
"-",
"1",
";",
"has",
"=",
"false",
";",
"while",
"(",
"++",
"j",
"<",
"a",
".",
"length",
")",
"{",
"if",
"(",
"a",
"[",
"j",
"]",
"===",
"ar",
"[",
"i",
"]",
")",
"{",
"has",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"has",
")",
"{",
"a",
".",
"push",
"(",
"ar",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"a",
";",
"}"
] |
Returns an array consisting of unique elements.
@param {Array} ar
@return {Array}
@api private
|
[
"Returns",
"an",
"array",
"consisting",
"of",
"unique",
"elements",
"."
] |
ae5433a53600591d263385e12fbbacc32499d676
|
https://github.com/jaredhanson/node-xtraverse/blob/ae5433a53600591d263385e12fbbacc32499d676/lib/collection.js#L44-L61
|
52,785
|
jaredhanson/node-xtraverse
|
lib/collection.js
|
Collection
|
function Collection(nodes) {
this.length = 0;
if (nodes) {
nodes = unique(nodes);
this.length = nodes.length;
// add each node to an index-based property on collection, in order to
// appear "array"-like
for (var i = 0, len = nodes.length; i < len; i++) {
this[i] = nodes[i];
}
}
}
|
javascript
|
function Collection(nodes) {
this.length = 0;
if (nodes) {
nodes = unique(nodes);
this.length = nodes.length;
// add each node to an index-based property on collection, in order to
// appear "array"-like
for (var i = 0, len = nodes.length; i < len; i++) {
this[i] = nodes[i];
}
}
}
|
[
"function",
"Collection",
"(",
"nodes",
")",
"{",
"this",
".",
"length",
"=",
"0",
";",
"if",
"(",
"nodes",
")",
"{",
"nodes",
"=",
"unique",
"(",
"nodes",
")",
";",
"this",
".",
"length",
"=",
"nodes",
".",
"length",
";",
"// add each node to an index-based property on collection, in order to",
"// appear \"array\"-like",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"nodes",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"this",
"[",
"i",
"]",
"=",
"nodes",
"[",
"i",
"]",
";",
"}",
"}",
"}"
] |
Creates an instance of `Collection`.
@constructor
@param {Array} nodes DOM elements to wrap.
@api protected
|
[
"Creates",
"an",
"instance",
"of",
"Collection",
"."
] |
ae5433a53600591d263385e12fbbacc32499d676
|
https://github.com/jaredhanson/node-xtraverse/blob/ae5433a53600591d263385e12fbbacc32499d676/lib/collection.js#L71-L82
|
52,786
|
philipbordallo/eslint-config
|
src/utilities/disableRules.js
|
disableRules
|
async function disableRules(rules) {
return Object.keys(rules)
.reduce((collection, rule) => ({
...collection,
[rule]: OFF,
}), {});
}
|
javascript
|
async function disableRules(rules) {
return Object.keys(rules)
.reduce((collection, rule) => ({
...collection,
[rule]: OFF,
}), {});
}
|
[
"async",
"function",
"disableRules",
"(",
"rules",
")",
"{",
"return",
"Object",
".",
"keys",
"(",
"rules",
")",
".",
"reduce",
"(",
"(",
"collection",
",",
"rule",
")",
"=>",
"(",
"{",
"...",
"collection",
",",
"[",
"rule",
"]",
":",
"OFF",
",",
"}",
")",
",",
"{",
"}",
")",
";",
"}"
] |
Automatically disable all rules given a rules list
@param {Object} rules - Rules to disable
@returns {Promise} A promise to return a rules list with each rule disabled
|
[
"Automatically",
"disable",
"all",
"rules",
"given",
"a",
"rules",
"list"
] |
a2f1bff442fdb8ee622f842f075fa10d555302a4
|
https://github.com/philipbordallo/eslint-config/blob/a2f1bff442fdb8ee622f842f075fa10d555302a4/src/utilities/disableRules.js#L9-L15
|
52,787
|
inviqa/deck-task-registry
|
src/build/build.js
|
build
|
function build (conf, undertaker, done) {
return undertaker.series(
require('./clean').bind(null, conf, undertaker),
undertaker.parallel(
require('../scripts/lintScripts').bind(null, conf, undertaker),
require('../styles/lintStyles').bind(null, conf, undertaker)
),
undertaker.parallel(
require('../scripts/buildScripts').bind(null, conf, undertaker),
require('../styles/buildStyles').bind(null, conf, undertaker),
require('../assets/buildImages').bind(null, conf, undertaker),
require('../assets/buildFonts').bind(null, conf, undertaker)
),
require('../styles/holograph').bind(null, conf, undertaker)
)(done);
}
|
javascript
|
function build (conf, undertaker, done) {
return undertaker.series(
require('./clean').bind(null, conf, undertaker),
undertaker.parallel(
require('../scripts/lintScripts').bind(null, conf, undertaker),
require('../styles/lintStyles').bind(null, conf, undertaker)
),
undertaker.parallel(
require('../scripts/buildScripts').bind(null, conf, undertaker),
require('../styles/buildStyles').bind(null, conf, undertaker),
require('../assets/buildImages').bind(null, conf, undertaker),
require('../assets/buildFonts').bind(null, conf, undertaker)
),
require('../styles/holograph').bind(null, conf, undertaker)
)(done);
}
|
[
"function",
"build",
"(",
"conf",
",",
"undertaker",
",",
"done",
")",
"{",
"return",
"undertaker",
".",
"series",
"(",
"require",
"(",
"'./clean'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
",",
"undertaker",
".",
"parallel",
"(",
"require",
"(",
"'../scripts/lintScripts'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
",",
"require",
"(",
"'../styles/lintStyles'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
")",
",",
"undertaker",
".",
"parallel",
"(",
"require",
"(",
"'../scripts/buildScripts'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
",",
"require",
"(",
"'../styles/buildStyles'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
",",
"require",
"(",
"'../assets/buildImages'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
",",
"require",
"(",
"'../assets/buildFonts'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
")",
",",
"require",
"(",
"'../styles/holograph'",
")",
".",
"bind",
"(",
"null",
",",
"conf",
",",
"undertaker",
")",
")",
"(",
"done",
")",
";",
"}"
] |
Run all test and build tasks with maximum concurrency.
@param {ConfigParser} conf A configuration parser object.
@param {Undertaker} undertaker An Undertaker instance.
@param {Function} done A callback to call on task completion/
@returns {Stream} A stream of files.
|
[
"Run",
"all",
"test",
"and",
"build",
"tasks",
"with",
"maximum",
"concurrency",
"."
] |
4c31787b978e9d99a47052e090d4589a50cd3015
|
https://github.com/inviqa/deck-task-registry/blob/4c31787b978e9d99a47052e090d4589a50cd3015/src/build/build.js#L12-L27
|
52,788
|
pkrll/JavaScript
|
Tooltip/Source/tooltip-1.1.js
|
function () {
// Remove the other tooltips
// if it was requested.
if (this.reset !== false)
this.resetTooltip();
// Create the tooltip elements
var container = $("<div>").attr({
"class": "error-label-container"
}).appendTo(this.settings.element);
var arrow = $("<div>").attr({
"class": "error-label-arrow-" + this.settings.arrow
}).appendTo(container);
var label = $("<div>").attr({
"class": "error-label"
}).html(this.settings.label).appendTo(container);
// Set the red glow around the input
this.settings.element.addClass("tooltip-active");
// If the fadeout option is set, then
// fade it out after the given time.
// Otherwise, make it clickable to let
// the user remove it.
if ($.isNumeric(this.settings.fadeOut))
container.delay(this.settings.fadeOut).fadeOut("slow");
label.click(function () {
$(this).parent().remove();
});
}
|
javascript
|
function () {
// Remove the other tooltips
// if it was requested.
if (this.reset !== false)
this.resetTooltip();
// Create the tooltip elements
var container = $("<div>").attr({
"class": "error-label-container"
}).appendTo(this.settings.element);
var arrow = $("<div>").attr({
"class": "error-label-arrow-" + this.settings.arrow
}).appendTo(container);
var label = $("<div>").attr({
"class": "error-label"
}).html(this.settings.label).appendTo(container);
// Set the red glow around the input
this.settings.element.addClass("tooltip-active");
// If the fadeout option is set, then
// fade it out after the given time.
// Otherwise, make it clickable to let
// the user remove it.
if ($.isNumeric(this.settings.fadeOut))
container.delay(this.settings.fadeOut).fadeOut("slow");
label.click(function () {
$(this).parent().remove();
});
}
|
[
"function",
"(",
")",
"{",
"// Remove the other tooltips",
"// if it was requested.",
"if",
"(",
"this",
".",
"reset",
"!==",
"false",
")",
"this",
".",
"resetTooltip",
"(",
")",
";",
"// Create the tooltip elements",
"var",
"container",
"=",
"$",
"(",
"\"<div>\"",
")",
".",
"attr",
"(",
"{",
"\"class\"",
":",
"\"error-label-container\"",
"}",
")",
".",
"appendTo",
"(",
"this",
".",
"settings",
".",
"element",
")",
";",
"var",
"arrow",
"=",
"$",
"(",
"\"<div>\"",
")",
".",
"attr",
"(",
"{",
"\"class\"",
":",
"\"error-label-arrow-\"",
"+",
"this",
".",
"settings",
".",
"arrow",
"}",
")",
".",
"appendTo",
"(",
"container",
")",
";",
"var",
"label",
"=",
"$",
"(",
"\"<div>\"",
")",
".",
"attr",
"(",
"{",
"\"class\"",
":",
"\"error-label\"",
"}",
")",
".",
"html",
"(",
"this",
".",
"settings",
".",
"label",
")",
".",
"appendTo",
"(",
"container",
")",
";",
"// Set the red glow around the input",
"this",
".",
"settings",
".",
"element",
".",
"addClass",
"(",
"\"tooltip-active\"",
")",
";",
"// If the fadeout option is set, then",
"// fade it out after the given time.",
"// Otherwise, make it clickable to let",
"// the user remove it.",
"if",
"(",
"$",
".",
"isNumeric",
"(",
"this",
".",
"settings",
".",
"fadeOut",
")",
")",
"container",
".",
"delay",
"(",
"this",
".",
"settings",
".",
"fadeOut",
")",
".",
"fadeOut",
"(",
"\"slow\"",
")",
";",
"label",
".",
"click",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"parent",
"(",
")",
".",
"remove",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Create the tooltip
|
[
"Create",
"the",
"tooltip"
] |
2757281c61e14895694d921b98a699a96cb6d346
|
https://github.com/pkrll/JavaScript/blob/2757281c61e14895694d921b98a699a96cb6d346/Tooltip/Source/tooltip-1.1.js#L139-L165
|
|
52,789
|
redisjs/jsr-store
|
lib/database.js
|
Database
|
function Database(store, opts) {
opts = opts || {};
// the store that holds this database
this._store = store;
// do not coerce values to strings
this.raw = opts.raw !== undefined ? opts.raw : true;
// pattern matcher
this.pattern = opts.pattern || new Pattern();
this.options = opts;
// set up initial state
this.flushdb();
if(store) {
// proxy via the store so the server
// can get statistics across all databases
this.on('expired', function onExpired(key) {
store.emit('expired', key);
})
this.on('hit', function onHit(key) {
store.emit('hit', key);
})
this.on('miss', function onMiss(key) {
store.emit('miss', key);
})
}
}
|
javascript
|
function Database(store, opts) {
opts = opts || {};
// the store that holds this database
this._store = store;
// do not coerce values to strings
this.raw = opts.raw !== undefined ? opts.raw : true;
// pattern matcher
this.pattern = opts.pattern || new Pattern();
this.options = opts;
// set up initial state
this.flushdb();
if(store) {
// proxy via the store so the server
// can get statistics across all databases
this.on('expired', function onExpired(key) {
store.emit('expired', key);
})
this.on('hit', function onHit(key) {
store.emit('hit', key);
})
this.on('miss', function onMiss(key) {
store.emit('miss', key);
})
}
}
|
[
"function",
"Database",
"(",
"store",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"// the store that holds this database",
"this",
".",
"_store",
"=",
"store",
";",
"// do not coerce values to strings",
"this",
".",
"raw",
"=",
"opts",
".",
"raw",
"!==",
"undefined",
"?",
"opts",
".",
"raw",
":",
"true",
";",
"// pattern matcher",
"this",
".",
"pattern",
"=",
"opts",
".",
"pattern",
"||",
"new",
"Pattern",
"(",
")",
";",
"this",
".",
"options",
"=",
"opts",
";",
"// set up initial state",
"this",
".",
"flushdb",
"(",
")",
";",
"if",
"(",
"store",
")",
"{",
"// proxy via the store so the server",
"// can get statistics across all databases",
"this",
".",
"on",
"(",
"'expired'",
",",
"function",
"onExpired",
"(",
"key",
")",
"{",
"store",
".",
"emit",
"(",
"'expired'",
",",
"key",
")",
";",
"}",
")",
"this",
".",
"on",
"(",
"'hit'",
",",
"function",
"onHit",
"(",
"key",
")",
"{",
"store",
".",
"emit",
"(",
"'hit'",
",",
"key",
")",
";",
"}",
")",
"this",
".",
"on",
"(",
"'miss'",
",",
"function",
"onMiss",
"(",
"key",
")",
"{",
"store",
".",
"emit",
"(",
"'miss'",
",",
"key",
")",
";",
"}",
")",
"}",
"}"
] |
Represents a collection of key value pairs as a database.
This module allows for a request object to be passed as the
last argument to each command. The request object will then be
passed as an argument when emitting on a write event by key.
This allows transactional semantics whereby a connection needs to
know if a watched key has been modified between the multi and exec
commands.
This class does not perform any validation and it is expected that
command and argument validation has already been performed using the
validate module.
This module will not throw errors or emit an error event you must ensure
data integrity before invoking database methods.
|
[
"Represents",
"a",
"collection",
"of",
"key",
"value",
"pairs",
"as",
"a",
"database",
"."
] |
b2b5c5b0347819f8a388b5d67e121ee8d73f328c
|
https://github.com/redisjs/jsr-store/blob/b2b5c5b0347819f8a388b5d67e121ee8d73f328c/lib/database.js#L24-L56
|
52,790
|
redisjs/jsr-resp
|
lib/encoder.js
|
Encoder
|
function Encoder(options) {
options = options || {};
Transform.call(this, {objectMode: true});
// string length chunk for bulk strings, strings large than this amount
// are broken over process ticks so as not to block the event loop
// note this is character length, not byte length
this.strlen = options.strlen || 4096;
// maximum array length before iterating using
// setImmediate
this.arrlen = 512;
// allow buffers to be passed through untouched
this.buffers = options.buffers;
// treat buffers as bulk strings
this.return_buffers = options.return_buffers;
}
|
javascript
|
function Encoder(options) {
options = options || {};
Transform.call(this, {objectMode: true});
// string length chunk for bulk strings, strings large than this amount
// are broken over process ticks so as not to block the event loop
// note this is character length, not byte length
this.strlen = options.strlen || 4096;
// maximum array length before iterating using
// setImmediate
this.arrlen = 512;
// allow buffers to be passed through untouched
this.buffers = options.buffers;
// treat buffers as bulk strings
this.return_buffers = options.return_buffers;
}
|
[
"function",
"Encoder",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"Transform",
".",
"call",
"(",
"this",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
";",
"// string length chunk for bulk strings, strings large than this amount",
"// are broken over process ticks so as not to block the event loop",
"// note this is character length, not byte length",
"this",
".",
"strlen",
"=",
"options",
".",
"strlen",
"||",
"4096",
";",
"// maximum array length before iterating using",
"// setImmediate",
"this",
".",
"arrlen",
"=",
"512",
";",
"// allow buffers to be passed through untouched",
"this",
".",
"buffers",
"=",
"options",
".",
"buffers",
";",
"// treat buffers as bulk strings",
"this",
".",
"return_buffers",
"=",
"options",
".",
"return_buffers",
";",
"}"
] |
Class for encoding javascript types to RESP messages.
Public methods throw an error on an attempt to encode
an invalid type.
Stream methods emit an error event.
|
[
"Class",
"for",
"encoding",
"javascript",
"types",
"to",
"RESP",
"messages",
"."
] |
9f998fc65a4494a358fca296adfe37fc5fb3f03c
|
https://github.com/redisjs/jsr-resp/blob/9f998fc65a4494a358fca296adfe37fc5fb3f03c/lib/encoder.js#L16-L34
|
52,791
|
redisjs/jsr-resp
|
lib/encoder.js
|
pack
|
function pack(arr, buf) {
assert(Array.isArray(arr), 'array expected');
var i;
buf = buf || new Buffer(0);
buf = _preamble(buf, arr);
for(i = 0;i < arr.length;i++) {
buf = _arr(buf, arr[i]);
}
return buf;
}
|
javascript
|
function pack(arr, buf) {
assert(Array.isArray(arr), 'array expected');
var i;
buf = buf || new Buffer(0);
buf = _preamble(buf, arr);
for(i = 0;i < arr.length;i++) {
buf = _arr(buf, arr[i]);
}
return buf;
}
|
[
"function",
"pack",
"(",
"arr",
",",
"buf",
")",
"{",
"assert",
"(",
"Array",
".",
"isArray",
"(",
"arr",
")",
",",
"'array expected'",
")",
";",
"var",
"i",
";",
"buf",
"=",
"buf",
"||",
"new",
"Buffer",
"(",
"0",
")",
";",
"buf",
"=",
"_preamble",
"(",
"buf",
",",
"arr",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"buf",
"=",
"_arr",
"(",
"buf",
",",
"arr",
"[",
"i",
"]",
")",
";",
"}",
"return",
"buf",
";",
"}"
] |
Pack an array of arrays.
Typcially used when a caller wishes to pack multiple command arrays.
@param arr An array of arrays.
@param buf A buffer to append the encoded contents to (optional).
@return A buffer with the RESP encoded contents.
|
[
"Pack",
"an",
"array",
"of",
"arrays",
"."
] |
9f998fc65a4494a358fca296adfe37fc5fb3f03c
|
https://github.com/redisjs/jsr-resp/blob/9f998fc65a4494a358fca296adfe37fc5fb3f03c/lib/encoder.js#L135-L144
|
52,792
|
redisjs/jsr-resp
|
lib/encoder.js
|
value
|
function value(val, buf, simple) {
buf = buf || new Buffer(0);
var type = typeof val;
// coerce booleans to integers
val = type === 'boolean' ? Number(val) : val;
// treat floats as strings
if(type === 'number' && parseInt(val) !== val) {
val = '' + val;
}
// String instances are treated as simple strings
if(val instanceof String) {
simple = true;
val = val.toString();
}
// re-evaluate type after coercion
type = typeof val;
if(val instanceof Buffer) {
buf = _bst(buf, val);
}else if(val === null) {
buf = _nil(buf);
}else if(Array.isArray(val)) {
buf = _arr(buf, val);
}else if(type === 'number'){
buf = _int(buf, val);
}else if(type === 'string') {
buf = simple ? _str(buf, val) : _bst(buf, val);
}else if(val instanceof Error) {
buf = _err(buf, val);
}else{
assert(false, 'invalid encoder type: ' + type);
}
return buf;
}
|
javascript
|
function value(val, buf, simple) {
buf = buf || new Buffer(0);
var type = typeof val;
// coerce booleans to integers
val = type === 'boolean' ? Number(val) : val;
// treat floats as strings
if(type === 'number' && parseInt(val) !== val) {
val = '' + val;
}
// String instances are treated as simple strings
if(val instanceof String) {
simple = true;
val = val.toString();
}
// re-evaluate type after coercion
type = typeof val;
if(val instanceof Buffer) {
buf = _bst(buf, val);
}else if(val === null) {
buf = _nil(buf);
}else if(Array.isArray(val)) {
buf = _arr(buf, val);
}else if(type === 'number'){
buf = _int(buf, val);
}else if(type === 'string') {
buf = simple ? _str(buf, val) : _bst(buf, val);
}else if(val instanceof Error) {
buf = _err(buf, val);
}else{
assert(false, 'invalid encoder type: ' + type);
}
return buf;
}
|
[
"function",
"value",
"(",
"val",
",",
"buf",
",",
"simple",
")",
"{",
"buf",
"=",
"buf",
"||",
"new",
"Buffer",
"(",
"0",
")",
";",
"var",
"type",
"=",
"typeof",
"val",
";",
"// coerce booleans to integers",
"val",
"=",
"type",
"===",
"'boolean'",
"?",
"Number",
"(",
"val",
")",
":",
"val",
";",
"// treat floats as strings",
"if",
"(",
"type",
"===",
"'number'",
"&&",
"parseInt",
"(",
"val",
")",
"!==",
"val",
")",
"{",
"val",
"=",
"''",
"+",
"val",
";",
"}",
"// String instances are treated as simple strings",
"if",
"(",
"val",
"instanceof",
"String",
")",
"{",
"simple",
"=",
"true",
";",
"val",
"=",
"val",
".",
"toString",
"(",
")",
";",
"}",
"// re-evaluate type after coercion",
"type",
"=",
"typeof",
"val",
";",
"if",
"(",
"val",
"instanceof",
"Buffer",
")",
"{",
"buf",
"=",
"_bst",
"(",
"buf",
",",
"val",
")",
";",
"}",
"else",
"if",
"(",
"val",
"===",
"null",
")",
"{",
"buf",
"=",
"_nil",
"(",
"buf",
")",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"buf",
"=",
"_arr",
"(",
"buf",
",",
"val",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'number'",
")",
"{",
"buf",
"=",
"_int",
"(",
"buf",
",",
"val",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'string'",
")",
"{",
"buf",
"=",
"simple",
"?",
"_str",
"(",
"buf",
",",
"val",
")",
":",
"_bst",
"(",
"buf",
",",
"val",
")",
";",
"}",
"else",
"if",
"(",
"val",
"instanceof",
"Error",
")",
"{",
"buf",
"=",
"_err",
"(",
"buf",
",",
"val",
")",
";",
"}",
"else",
"{",
"assert",
"(",
"false",
",",
"'invalid encoder type: '",
"+",
"type",
")",
";",
"}",
"return",
"buf",
";",
"}"
] |
Encode a single javascript value.
@param val The value to encode.
@param buf A buffer to append the encoded contents to (optional).
@param simple Force a string value to be treated as a simple string.
@return A buffer with the RESP encoded contents.
|
[
"Encode",
"a",
"single",
"javascript",
"value",
"."
] |
9f998fc65a4494a358fca296adfe37fc5fb3f03c
|
https://github.com/redisjs/jsr-resp/blob/9f998fc65a4494a358fca296adfe37fc5fb3f03c/lib/encoder.js#L170-L207
|
52,793
|
molecuel/mlcl_wishlist
|
index.js
|
function() {
var self = this;
molecuel.once('mlcl::elements::registrations:pre', function(module) {
elements = module;
self.wishlistSchema = {
name: { type: String, list: true, trim: true},
creation: { type: Date, 'default': Date.now, form: {readonly: true}},
entries: {
},
listelements: [{type: elements.Types.Mixed}]
};
_.each(molecuel.config.wishlist.types, function(type) {
self.wishlistSchema.entries[type] = [{type: elements.ObjectId, ref: type}];
});
// module == elements module
var schemaDefinition = {
schemaName: 'wishlist',
schema: self.wishlistSchema,
options: {indexable: true, avoidTranslate: true}
};
molecuel.config.url.pattern.wishlist = '/wishlist/{{t _id}}';
elements.registerSchemaDefinition(schemaDefinition);
});
return this;
}
|
javascript
|
function() {
var self = this;
molecuel.once('mlcl::elements::registrations:pre', function(module) {
elements = module;
self.wishlistSchema = {
name: { type: String, list: true, trim: true},
creation: { type: Date, 'default': Date.now, form: {readonly: true}},
entries: {
},
listelements: [{type: elements.Types.Mixed}]
};
_.each(molecuel.config.wishlist.types, function(type) {
self.wishlistSchema.entries[type] = [{type: elements.ObjectId, ref: type}];
});
// module == elements module
var schemaDefinition = {
schemaName: 'wishlist',
schema: self.wishlistSchema,
options: {indexable: true, avoidTranslate: true}
};
molecuel.config.url.pattern.wishlist = '/wishlist/{{t _id}}';
elements.registerSchemaDefinition(schemaDefinition);
});
return this;
}
|
[
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"molecuel",
".",
"once",
"(",
"'mlcl::elements::registrations:pre'",
",",
"function",
"(",
"module",
")",
"{",
"elements",
"=",
"module",
";",
"self",
".",
"wishlistSchema",
"=",
"{",
"name",
":",
"{",
"type",
":",
"String",
",",
"list",
":",
"true",
",",
"trim",
":",
"true",
"}",
",",
"creation",
":",
"{",
"type",
":",
"Date",
",",
"'default'",
":",
"Date",
".",
"now",
",",
"form",
":",
"{",
"readonly",
":",
"true",
"}",
"}",
",",
"entries",
":",
"{",
"}",
",",
"listelements",
":",
"[",
"{",
"type",
":",
"elements",
".",
"Types",
".",
"Mixed",
"}",
"]",
"}",
";",
"_",
".",
"each",
"(",
"molecuel",
".",
"config",
".",
"wishlist",
".",
"types",
",",
"function",
"(",
"type",
")",
"{",
"self",
".",
"wishlistSchema",
".",
"entries",
"[",
"type",
"]",
"=",
"[",
"{",
"type",
":",
"elements",
".",
"ObjectId",
",",
"ref",
":",
"type",
"}",
"]",
";",
"}",
")",
";",
"// module == elements module",
"var",
"schemaDefinition",
"=",
"{",
"schemaName",
":",
"'wishlist'",
",",
"schema",
":",
"self",
".",
"wishlistSchema",
",",
"options",
":",
"{",
"indexable",
":",
"true",
",",
"avoidTranslate",
":",
"true",
"}",
"}",
";",
"molecuel",
".",
"config",
".",
"url",
".",
"pattern",
".",
"wishlist",
"=",
"'/wishlist/{{t _id}}'",
";",
"elements",
".",
"registerSchemaDefinition",
"(",
"schemaDefinition",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] |
This module serves wishlist database element
@constructor
|
[
"This",
"module",
"serves",
"wishlist",
"database",
"element"
] |
7cbe5c2924a41201449de9963a48e144c60b68a4
|
https://github.com/molecuel/mlcl_wishlist/blob/7cbe5c2924a41201449de9963a48e144c60b68a4/index.js#L13-L44
|
|
52,794
|
gfax/junkyard-brawl
|
src/util.js
|
baseWeight
|
function baseWeight(player, target, card, game) {
let weight = card.damage || 0
weight += Math.min(player.maxHp - player.hp, (parseInt(card.hp) || 0))
weight += card.missTurns / 2 || 0
// Prefer to contact weaker targets
weight += ((target.maxHp - player.hp) / 10)
// Unstoppable cards are instantly more valuable
if (card.type === 'unstoppable') {
weight += 3
}
// Try to avoid contacting a target with a deflector
if (Util.find(target.conditionCards, { id: 'deflector' })) {
weight = -weight
}
return weight
}
|
javascript
|
function baseWeight(player, target, card, game) {
let weight = card.damage || 0
weight += Math.min(player.maxHp - player.hp, (parseInt(card.hp) || 0))
weight += card.missTurns / 2 || 0
// Prefer to contact weaker targets
weight += ((target.maxHp - player.hp) / 10)
// Unstoppable cards are instantly more valuable
if (card.type === 'unstoppable') {
weight += 3
}
// Try to avoid contacting a target with a deflector
if (Util.find(target.conditionCards, { id: 'deflector' })) {
weight = -weight
}
return weight
}
|
[
"function",
"baseWeight",
"(",
"player",
",",
"target",
",",
"card",
",",
"game",
")",
"{",
"let",
"weight",
"=",
"card",
".",
"damage",
"||",
"0",
"weight",
"+=",
"Math",
".",
"min",
"(",
"player",
".",
"maxHp",
"-",
"player",
".",
"hp",
",",
"(",
"parseInt",
"(",
"card",
".",
"hp",
")",
"||",
"0",
")",
")",
"weight",
"+=",
"card",
".",
"missTurns",
"/",
"2",
"||",
"0",
"// Prefer to contact weaker targets",
"weight",
"+=",
"(",
"(",
"target",
".",
"maxHp",
"-",
"player",
".",
"hp",
")",
"/",
"10",
")",
"// Unstoppable cards are instantly more valuable",
"if",
"(",
"card",
".",
"type",
"===",
"'unstoppable'",
")",
"{",
"weight",
"+=",
"3",
"}",
"// Try to avoid contacting a target with a deflector",
"if",
"(",
"Util",
".",
"find",
"(",
"target",
".",
"conditionCards",
",",
"{",
"id",
":",
"'deflector'",
"}",
")",
")",
"{",
"weight",
"=",
"-",
"weight",
"}",
"return",
"weight",
"}"
] |
Calculate the base weight for a card play
|
[
"Calculate",
"the",
"base",
"weight",
"for",
"a",
"card",
"play"
] |
5e1b9d3b622ffa6e602c7abe51995269a43423e1
|
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L26-L45
|
52,795
|
gfax/junkyard-brawl
|
src/util.js
|
findNext
|
function findNext(array, item) {
return array[(Util.findIndex(array, el => el === item) + 1) % array.length]
}
|
javascript
|
function findNext(array, item) {
return array[(Util.findIndex(array, el => el === item) + 1) % array.length]
}
|
[
"function",
"findNext",
"(",
"array",
",",
"item",
")",
"{",
"return",
"array",
"[",
"(",
"Util",
".",
"findIndex",
"(",
"array",
",",
"el",
"=>",
"el",
"===",
"item",
")",
"+",
"1",
")",
"%",
"array",
".",
"length",
"]",
"}"
] |
Return the next item in an array. If there is no next, return the first.
|
[
"Return",
"the",
"next",
"item",
"in",
"an",
"array",
".",
"If",
"there",
"is",
"no",
"next",
"return",
"the",
"first",
"."
] |
5e1b9d3b622ffa6e602c7abe51995269a43423e1
|
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L48-L50
|
52,796
|
gfax/junkyard-brawl
|
src/util.js
|
getAttackResults
|
function getAttackResults(_cards) {
// Force the cards into an array. Clone is too
// to avoid side effects from the simulation.
const cards = Util.clone(Array.isArray(_cards) ? _cards : [_cards])
const Junkyard = require('./junkyard')
const game = new Junkyard('1', '')
game.addPlayer('2', '')
game.addPlayer('3', '')
game.start()
const [p1, , p3] = game.players
p1.hand = cards
game.play(p1, [...cards], p3.id)
game.pass(p3)
return {
damage: p3.maxHp - p3.hp,
missTurns: p3.missTurns
}
}
|
javascript
|
function getAttackResults(_cards) {
// Force the cards into an array. Clone is too
// to avoid side effects from the simulation.
const cards = Util.clone(Array.isArray(_cards) ? _cards : [_cards])
const Junkyard = require('./junkyard')
const game = new Junkyard('1', '')
game.addPlayer('2', '')
game.addPlayer('3', '')
game.start()
const [p1, , p3] = game.players
p1.hand = cards
game.play(p1, [...cards], p3.id)
game.pass(p3)
return {
damage: p3.maxHp - p3.hp,
missTurns: p3.missTurns
}
}
|
[
"function",
"getAttackResults",
"(",
"_cards",
")",
"{",
"// Force the cards into an array. Clone is too",
"// to avoid side effects from the simulation.",
"const",
"cards",
"=",
"Util",
".",
"clone",
"(",
"Array",
".",
"isArray",
"(",
"_cards",
")",
"?",
"_cards",
":",
"[",
"_cards",
"]",
")",
"const",
"Junkyard",
"=",
"require",
"(",
"'./junkyard'",
")",
"const",
"game",
"=",
"new",
"Junkyard",
"(",
"'1'",
",",
"''",
")",
"game",
".",
"addPlayer",
"(",
"'2'",
",",
"''",
")",
"game",
".",
"addPlayer",
"(",
"'3'",
",",
"''",
")",
"game",
".",
"start",
"(",
")",
"const",
"[",
"p1",
",",
",",
"p3",
"]",
"=",
"game",
".",
"players",
"p1",
".",
"hand",
"=",
"cards",
"game",
".",
"play",
"(",
"p1",
",",
"[",
"...",
"cards",
"]",
",",
"p3",
".",
"id",
")",
"game",
".",
"pass",
"(",
"p3",
")",
"return",
"{",
"damage",
":",
"p3",
".",
"maxHp",
"-",
"p3",
".",
"hp",
",",
"missTurns",
":",
"p3",
".",
"missTurns",
"}",
"}"
] |
Determine an attack's damages by simulating playing it
|
[
"Determine",
"an",
"attack",
"s",
"damages",
"by",
"simulating",
"playing",
"it"
] |
5e1b9d3b622ffa6e602c7abe51995269a43423e1
|
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L53-L70
|
52,797
|
gfax/junkyard-brawl
|
src/util.js
|
getCardWeight
|
function getCardWeight(player, target, card, game) {
let moves = []
if (card.validPlays) {
moves = card.validPlays(player, target, game)
}
if (card.validCounters && target.discard.length) {
moves = card.validCounters(player, target, game)
}
if (card.validDisasters) {
moves = card.validDisasters(player, game)
}
// Pick out the highest weight of those moves
return moves.reduce((acc, move) => {
return move.weight > acc ? move.weight : acc
}, 0)
}
|
javascript
|
function getCardWeight(player, target, card, game) {
let moves = []
if (card.validPlays) {
moves = card.validPlays(player, target, game)
}
if (card.validCounters && target.discard.length) {
moves = card.validCounters(player, target, game)
}
if (card.validDisasters) {
moves = card.validDisasters(player, game)
}
// Pick out the highest weight of those moves
return moves.reduce((acc, move) => {
return move.weight > acc ? move.weight : acc
}, 0)
}
|
[
"function",
"getCardWeight",
"(",
"player",
",",
"target",
",",
"card",
",",
"game",
")",
"{",
"let",
"moves",
"=",
"[",
"]",
"if",
"(",
"card",
".",
"validPlays",
")",
"{",
"moves",
"=",
"card",
".",
"validPlays",
"(",
"player",
",",
"target",
",",
"game",
")",
"}",
"if",
"(",
"card",
".",
"validCounters",
"&&",
"target",
".",
"discard",
".",
"length",
")",
"{",
"moves",
"=",
"card",
".",
"validCounters",
"(",
"player",
",",
"target",
",",
"game",
")",
"}",
"if",
"(",
"card",
".",
"validDisasters",
")",
"{",
"moves",
"=",
"card",
".",
"validDisasters",
"(",
"player",
",",
"game",
")",
"}",
"// Pick out the highest weight of those moves",
"return",
"moves",
".",
"reduce",
"(",
"(",
"acc",
",",
"move",
")",
"=>",
"{",
"return",
"move",
".",
"weight",
">",
"acc",
"?",
"move",
".",
"weight",
":",
"acc",
"}",
",",
"0",
")",
"}"
] |
Return a cards best weight
|
[
"Return",
"a",
"cards",
"best",
"weight"
] |
5e1b9d3b622ffa6e602c7abe51995269a43423e1
|
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L73-L88
|
52,798
|
gfax/junkyard-brawl
|
src/util.js
|
getPlayerCounters
|
function getPlayerCounters(player, attacker, game) {
return player.hand
.map((card) => {
return card.validCounters ? card.validCounters(player, attacker, game) : []
})
.reduce((acc, array) => {
return acc.concat(array)
}, [])
.sort((counterA, counterB) => counterB.weight - counterA.weight)
}
|
javascript
|
function getPlayerCounters(player, attacker, game) {
return player.hand
.map((card) => {
return card.validCounters ? card.validCounters(player, attacker, game) : []
})
.reduce((acc, array) => {
return acc.concat(array)
}, [])
.sort((counterA, counterB) => counterB.weight - counterA.weight)
}
|
[
"function",
"getPlayerCounters",
"(",
"player",
",",
"attacker",
",",
"game",
")",
"{",
"return",
"player",
".",
"hand",
".",
"map",
"(",
"(",
"card",
")",
"=>",
"{",
"return",
"card",
".",
"validCounters",
"?",
"card",
".",
"validCounters",
"(",
"player",
",",
"attacker",
",",
"game",
")",
":",
"[",
"]",
"}",
")",
".",
"reduce",
"(",
"(",
"acc",
",",
"array",
")",
"=>",
"{",
"return",
"acc",
".",
"concat",
"(",
"array",
")",
"}",
",",
"[",
"]",
")",
".",
"sort",
"(",
"(",
"counterA",
",",
"counterB",
")",
"=>",
"counterB",
".",
"weight",
"-",
"counterA",
".",
"weight",
")",
"}"
] |
Get a list of possible counter moves, sorted by best option
|
[
"Get",
"a",
"list",
"of",
"possible",
"counter",
"moves",
"sorted",
"by",
"best",
"option"
] |
5e1b9d3b622ffa6e602c7abe51995269a43423e1
|
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L91-L100
|
52,799
|
gfax/junkyard-brawl
|
src/util.js
|
getPlayerDisasters
|
function getPlayerDisasters(player, game) {
return player.hand
.map((card) => {
return card.validDisasters ? card.validDisasters(player, game) : []
})
.reduce((acc, array) => {
return acc.concat(array)
}, [])
.sort((disasterA, disasterB) => disasterB.weight - disasterA.weight)
}
|
javascript
|
function getPlayerDisasters(player, game) {
return player.hand
.map((card) => {
return card.validDisasters ? card.validDisasters(player, game) : []
})
.reduce((acc, array) => {
return acc.concat(array)
}, [])
.sort((disasterA, disasterB) => disasterB.weight - disasterA.weight)
}
|
[
"function",
"getPlayerDisasters",
"(",
"player",
",",
"game",
")",
"{",
"return",
"player",
".",
"hand",
".",
"map",
"(",
"(",
"card",
")",
"=>",
"{",
"return",
"card",
".",
"validDisasters",
"?",
"card",
".",
"validDisasters",
"(",
"player",
",",
"game",
")",
":",
"[",
"]",
"}",
")",
".",
"reduce",
"(",
"(",
"acc",
",",
"array",
")",
"=>",
"{",
"return",
"acc",
".",
"concat",
"(",
"array",
")",
"}",
",",
"[",
"]",
")",
".",
"sort",
"(",
"(",
"disasterA",
",",
"disasterB",
")",
"=>",
"disasterB",
".",
"weight",
"-",
"disasterA",
".",
"weight",
")",
"}"
] |
Get a list of possible disaster moves, sorted by best option
|
[
"Get",
"a",
"list",
"of",
"possible",
"disaster",
"moves",
"sorted",
"by",
"best",
"option"
] |
5e1b9d3b622ffa6e602c7abe51995269a43423e1
|
https://github.com/gfax/junkyard-brawl/blob/5e1b9d3b622ffa6e602c7abe51995269a43423e1/src/util.js#L103-L112
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.