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
38,700
rootsdev/gedcomx-js
src/rs/Link.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Link)){ return new Link(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Link.isInstance(json)){ return json; } // TODO: Enforce spec constraint that requires either an href or a template? this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Link)){ return new Link(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Link.isInstance(json)){ return json; } // TODO: Enforce spec constraint that requires either an href or a template? this.init(json); }
[ "function", "(", "json", ")", "{", "// Protect against forgetting the new keyword when calling the constructor", "if", "(", "!", "(", "this", "instanceof", "Link", ")", ")", "{", "return", "new", "Link", "(", "json", ")", ";", "}", "// If the given object is already an instance then just return it. DON'T copy it.", "if", "(", "Link", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "// TODO: Enforce spec constraint that requires either an href or a template?", "this", ".", "init", "(", "json", ")", ";", "}" ]
A representation of an available transition from one application state to another. {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/rs-specification.md#link|GEDCOM X RS Spec} @class Link @extends Base @param {Object} [json]
[ "A", "representation", "of", "an", "available", "transition", "from", "one", "application", "state", "to", "another", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/rs/Link.js#L15-L30
38,701
crcn/celeri
lib/plugins/help.js
function(category, name, desc) { if(used[name]) return; used[name]= 1; if(!items[category]) items[category] = []; items[category].push({ name: name, desc: desc }); }
javascript
function(category, name, desc) { if(used[name]) return; used[name]= 1; if(!items[category]) items[category] = []; items[category].push({ name: name, desc: desc }); }
[ "function", "(", "category", ",", "name", ",", "desc", ")", "{", "if", "(", "used", "[", "name", "]", ")", "return", ";", "used", "[", "name", "]", "=", "1", ";", "if", "(", "!", "items", "[", "category", "]", ")", "items", "[", "category", "]", "=", "[", "]", ";", "items", "[", "category", "]", ".", "push", "(", "{", "name", ":", "name", ",", "desc", ":", "desc", "}", ")", ";", "}" ]
adds a help item
[ "adds", "a", "help", "item" ]
f10471478b9119485c7c72a49015e22ec4339e29
https://github.com/crcn/celeri/blob/f10471478b9119485c7c72a49015e22ec4339e29/lib/plugins/help.js#L40-L51
38,702
rootsdev/gedcomx-js
src/rs/FamilyView.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof FamilyView)){ return new FamilyView(json); } // If the given object is already an instance then just return it. DON'T copy it. if(FamilyView.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof FamilyView)){ return new FamilyView(json); } // If the given object is already an instance then just return it. DON'T copy it. if(FamilyView.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "// Protect against forgetting the new keyword when calling the constructor", "if", "(", "!", "(", "this", "instanceof", "FamilyView", ")", ")", "{", "return", "new", "FamilyView", "(", "json", ")", ";", "}", "// If the given object is already an instance then just return it. DON'T copy it.", "if", "(", "FamilyView", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A view of a family that consists of up to two parents and a list of children who have that set of parents in common. While the Relationship data type carries the canonical information about the nature of the relationship between the each pair of persons, the FamilyView is designed as a convenience for display purposes. {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/rs-specification.md#family-view|GEDCOM X RS Spec} @class FamilyView @extends Base @param {Object} [json]
[ "A", "view", "of", "a", "family", "that", "consists", "of", "up", "to", "two", "parents", "and", "a", "list", "of", "children", "who", "have", "that", "set", "of", "parents", "in", "common", ".", "While", "the", "Relationship", "data", "type", "carries", "the", "canonical", "information", "about", "the", "nature", "of", "the", "relationship", "between", "the", "each", "pair", "of", "persons", "the", "FamilyView", "is", "designed", "as", "a", "convenience", "for", "display", "purposes", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/rs/FamilyView.js#L19-L32
38,703
xfix/python-format
lib/python-format.js
repeat
function repeat(string, times) { var result = "" // Optimized repeat function concatenates concatenated // strings. while (times > 0) { if (times & 1) result += string times >>= 1 string += string } return result }
javascript
function repeat(string, times) { var result = "" // Optimized repeat function concatenates concatenated // strings. while (times > 0) { if (times & 1) result += string times >>= 1 string += string } return result }
[ "function", "repeat", "(", "string", ",", "times", ")", "{", "var", "result", "=", "\"\"", "// Optimized repeat function concatenates concatenated", "// strings.", "while", "(", "times", ">", "0", ")", "{", "if", "(", "times", "&", "1", ")", "result", "+=", "string", "times", ">>=", "1", "string", "+=", "string", "}", "return", "result", "}" ]
Internal function used for padding
[ "Internal", "function", "used", "for", "padding" ]
3921fa3846386d754d2dfc163fa5221be654be63
https://github.com/xfix/python-format/blob/3921fa3846386d754d2dfc163fa5221be654be63/lib/python-format.js#L79-L89
38,704
zanata/fake-zanata-server
index.js
endpointWithAlias
function endpointWithAlias(path, aliasPath) { return function () { endpoint(path)(); endpoint(aliasPath, null, getJSON(path))(); } }
javascript
function endpointWithAlias(path, aliasPath) { return function () { endpoint(path)(); endpoint(aliasPath, null, getJSON(path))(); } }
[ "function", "endpointWithAlias", "(", "path", ",", "aliasPath", ")", "{", "return", "function", "(", ")", "{", "endpoint", "(", "path", ")", "(", ")", ";", "endpoint", "(", "aliasPath", ",", "null", ",", "getJSON", "(", "path", ")", ")", "(", ")", ";", "}", "}" ]
Create a thunk that registers multiple endpoints that use the same data. The path of the JSON file in the mock directory must be the same as the first path argument. @path Local portion of endpoint path. @aliasPath Alternative path that will return the same data as the first path.
[ "Create", "a", "thunk", "that", "registers", "multiple", "endpoints", "that", "use", "the", "same", "data", "." ]
e44855572514b1dc9f5779ebb49298d75f04b4fb
https://github.com/zanata/fake-zanata-server/blob/e44855572514b1dc9f5779ebb49298d75f04b4fb/index.js#L164-L169
38,705
zanata/fake-zanata-server
index.js
extendingEndpoints
function extendingEndpoints() { var segments = Array.prototype.slice.call(arguments, 0); return function () { var path = ''; segments.forEach(function (pathSegment) { path = path + pathSegment; createEndpointFromPath(path); console.log(' registered path %s', path); }); } }
javascript
function extendingEndpoints() { var segments = Array.prototype.slice.call(arguments, 0); return function () { var path = ''; segments.forEach(function (pathSegment) { path = path + pathSegment; createEndpointFromPath(path); console.log(' registered path %s', path); }); } }
[ "function", "extendingEndpoints", "(", ")", "{", "var", "segments", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "return", "function", "(", ")", "{", "var", "path", "=", "''", ";", "segments", ".", "forEach", "(", "function", "(", "pathSegment", ")", "{", "path", "=", "path", "+", "pathSegment", ";", "createEndpointFromPath", "(", "path", ")", ";", "console", ".", "log", "(", "' registered path %s'", ",", "path", ")", ";", "}", ")", ";", "}", "}" ]
Create a thunk that will build up endpoints from an ordered set of path segments, registering the endpoints at all stages along the way. Each endpoint must have a corresponding JSON file in the mocks directory.
[ "Create", "a", "thunk", "that", "will", "build", "up", "endpoints", "from", "an", "ordered", "set", "of", "path", "segments", "registering", "the", "endpoints", "at", "all", "stages", "along", "the", "way", "." ]
e44855572514b1dc9f5779ebb49298d75f04b4fb
https://github.com/zanata/fake-zanata-server/blob/e44855572514b1dc9f5779ebb49298d75f04b4fb/index.js#L177-L187
38,706
zanata/fake-zanata-server
index.js
subEndpoints
function subEndpoints(prefix, suffixes) { return function () { Array.prototype.forEach.call(suffixes, function (suffix) { var path = prefix + suffix; createEndpointFromPath(path); console.log(' registered path %s', path); }); } }
javascript
function subEndpoints(prefix, suffixes) { return function () { Array.prototype.forEach.call(suffixes, function (suffix) { var path = prefix + suffix; createEndpointFromPath(path); console.log(' registered path %s', path); }); } }
[ "function", "subEndpoints", "(", "prefix", ",", "suffixes", ")", "{", "return", "function", "(", ")", "{", "Array", ".", "prototype", ".", "forEach", ".", "call", "(", "suffixes", ",", "function", "(", "suffix", ")", "{", "var", "path", "=", "prefix", "+", "suffix", ";", "createEndpointFromPath", "(", "path", ")", ";", "console", ".", "log", "(", "' registered path %s'", ",", "path", ")", ";", "}", ")", ";", "}", "}" ]
Create a thunk to make a set of endpoints with a common prefix. The prefix is prepended to each suffix to make each path. Each endpoint must have a corresponding JSON file in the mocks directory.
[ "Create", "a", "thunk", "to", "make", "a", "set", "of", "endpoints", "with", "a", "common", "prefix", "." ]
e44855572514b1dc9f5779ebb49298d75f04b4fb
https://github.com/zanata/fake-zanata-server/blob/e44855572514b1dc9f5779ebb49298d75f04b4fb/index.js#L196-L204
38,707
zanata/fake-zanata-server
index.js
badRequestEndpoint
function badRequestEndpoint(path, query, body) { return function () { body = body || getJSON(path); createEndpointFromObject(path, query, body).status(400); console.log(' registered error path %s', path); } }
javascript
function badRequestEndpoint(path, query, body) { return function () { body = body || getJSON(path); createEndpointFromObject(path, query, body).status(400); console.log(' registered error path %s', path); } }
[ "function", "badRequestEndpoint", "(", "path", ",", "query", ",", "body", ")", "{", "return", "function", "(", ")", "{", "body", "=", "body", "||", "getJSON", "(", "path", ")", ";", "createEndpointFromObject", "(", "path", ",", "query", ",", "body", ")", ".", "status", "(", "400", ")", ";", "console", ".", "log", "(", "' registered error path %s'", ",", "path", ")", ";", "}", "}" ]
Create a thunk that registers an endpoint that responds with BAD REQUEST status.
[ "Create", "a", "thunk", "that", "registers", "an", "endpoint", "that", "responds", "with", "BAD", "REQUEST", "status", "." ]
e44855572514b1dc9f5779ebb49298d75f04b4fb
https://github.com/zanata/fake-zanata-server/blob/e44855572514b1dc9f5779ebb49298d75f04b4fb/index.js#L242-L248
38,708
zanata/fake-zanata-server
index.js
createEndpointFromPath
function createEndpointFromPath(path, query, filePath) { filePath = filePath || path; return createEndpointFromObject(path, query, getJSON(filePath)); }
javascript
function createEndpointFromPath(path, query, filePath) { filePath = filePath || path; return createEndpointFromObject(path, query, getJSON(filePath)); }
[ "function", "createEndpointFromPath", "(", "path", ",", "query", ",", "filePath", ")", "{", "filePath", "=", "filePath", "||", "path", ";", "return", "createEndpointFromObject", "(", "path", ",", "query", ",", "getJSON", "(", "filePath", ")", ")", ";", "}" ]
Registers an endpoint using the file at the given path as the response body. If filePath is not provided, path will be used as the file location.
[ "Registers", "an", "endpoint", "using", "the", "file", "at", "the", "given", "path", "as", "the", "response", "body", "." ]
e44855572514b1dc9f5779ebb49298d75f04b4fb
https://github.com/zanata/fake-zanata-server/blob/e44855572514b1dc9f5779ebb49298d75f04b4fb/index.js#L255-L258
38,709
zanata/fake-zanata-server
index.js
createEndpointFromObject
function createEndpointFromObject(path, query, body) { // OPTIONS gives server permission to use CORS server.createRoute({ request: { url: path, query: query || {}, method: 'options', }, response: { code: 200, delay: config.latency, body: {}, headers: { 'Access-Control-Allow-Origin': config.allowOrigin, // allow several methods since some endpoints are writable 'Access-Control-Allow-Methods': 'GET, PUT, POST', 'Access-Control-Allow-Credentials': 'true' } } }); return server.get(path) .query(query) .responseHeaders({ 'Access-Control-Allow-Origin': config.allowOrigin, 'Access-Control-Allow-Methods': 'GET, PUT, POST', 'Access-Control-Allow-Credentials': 'true' }) .body(body) .delay(config.latency); }
javascript
function createEndpointFromObject(path, query, body) { // OPTIONS gives server permission to use CORS server.createRoute({ request: { url: path, query: query || {}, method: 'options', }, response: { code: 200, delay: config.latency, body: {}, headers: { 'Access-Control-Allow-Origin': config.allowOrigin, // allow several methods since some endpoints are writable 'Access-Control-Allow-Methods': 'GET, PUT, POST', 'Access-Control-Allow-Credentials': 'true' } } }); return server.get(path) .query(query) .responseHeaders({ 'Access-Control-Allow-Origin': config.allowOrigin, 'Access-Control-Allow-Methods': 'GET, PUT, POST', 'Access-Control-Allow-Credentials': 'true' }) .body(body) .delay(config.latency); }
[ "function", "createEndpointFromObject", "(", "path", ",", "query", ",", "body", ")", "{", "// OPTIONS gives server permission to use CORS", "server", ".", "createRoute", "(", "{", "request", ":", "{", "url", ":", "path", ",", "query", ":", "query", "||", "{", "}", ",", "method", ":", "'options'", ",", "}", ",", "response", ":", "{", "code", ":", "200", ",", "delay", ":", "config", ".", "latency", ",", "body", ":", "{", "}", ",", "headers", ":", "{", "'Access-Control-Allow-Origin'", ":", "config", ".", "allowOrigin", ",", "// allow several methods since some endpoints are writable", "'Access-Control-Allow-Methods'", ":", "'GET, PUT, POST'", ",", "'Access-Control-Allow-Credentials'", ":", "'true'", "}", "}", "}", ")", ";", "return", "server", ".", "get", "(", "path", ")", ".", "query", "(", "query", ")", ".", "responseHeaders", "(", "{", "'Access-Control-Allow-Origin'", ":", "config", ".", "allowOrigin", ",", "'Access-Control-Allow-Methods'", ":", "'GET, PUT, POST'", ",", "'Access-Control-Allow-Credentials'", ":", "'true'", "}", ")", ".", "body", "(", "body", ")", ".", "delay", "(", "config", ".", "latency", ")", ";", "}" ]
Registers an endpoint using the given response body.
[ "Registers", "an", "endpoint", "using", "the", "given", "response", "body", "." ]
e44855572514b1dc9f5779ebb49298d75f04b4fb
https://github.com/zanata/fake-zanata-server/blob/e44855572514b1dc9f5779ebb49298d75f04b4fb/index.js#L263-L292
38,710
rootsdev/gedcomx-js
src/core/OnlineAccount.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof OnlineAccount)){ return new OnlineAccount(json); } // If the given object is already an instance then just return it. DON'T copy it. if(OnlineAccount.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof OnlineAccount)){ return new OnlineAccount(json); } // If the given object is already an instance then just return it. DON'T copy it. if(OnlineAccount.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "// Protect against forgetting the new keyword when calling the constructor", "if", "(", "!", "(", "this", "instanceof", "OnlineAccount", ")", ")", "{", "return", "new", "OnlineAccount", "(", "json", ")", ";", "}", "// If the given object is already an instance then just return it. DON'T copy it.", "if", "(", "OnlineAccount", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
An online account for a web application. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#online-account|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "An", "online", "account", "for", "a", "web", "application", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/OnlineAccount.js#L13-L26
38,711
AppGeo/cartodb
lib/compiler.js
toSQL
function toSQL(method) { method = method || this.method; var val = this[method](); var defaults = { method: method, options: assign({}, this.options), bindings: this.formatter.bindings }; if (typeof val === 'string') { val = { sql: val }; } if (method === 'select' && this.single.as) { defaults.as = this.single.as; } var out = assign(defaults, val); debug(out); return out; }
javascript
function toSQL(method) { method = method || this.method; var val = this[method](); var defaults = { method: method, options: assign({}, this.options), bindings: this.formatter.bindings }; if (typeof val === 'string') { val = { sql: val }; } if (method === 'select' && this.single.as) { defaults.as = this.single.as; } var out = assign(defaults, val); debug(out); return out; }
[ "function", "toSQL", "(", "method", ")", "{", "method", "=", "method", "||", "this", ".", "method", ";", "var", "val", "=", "this", "[", "method", "]", "(", ")", ";", "var", "defaults", "=", "{", "method", ":", "method", ",", "options", ":", "assign", "(", "{", "}", ",", "this", ".", "options", ")", ",", "bindings", ":", "this", ".", "formatter", ".", "bindings", "}", ";", "if", "(", "typeof", "val", "===", "'string'", ")", "{", "val", "=", "{", "sql", ":", "val", "}", ";", "}", "if", "(", "method", "===", "'select'", "&&", "this", ".", "single", ".", "as", ")", "{", "defaults", ".", "as", "=", "this", ".", "single", ".", "as", ";", "}", "var", "out", "=", "assign", "(", "defaults", ",", "val", ")", ";", "debug", "(", "out", ")", ";", "return", "out", ";", "}" ]
Collapse the builder into a single object
[ "Collapse", "the", "builder", "into", "a", "single", "object" ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L43-L61
38,712
AppGeo/cartodb
lib/compiler.js
select
function select() { var i = -1, statements = []; while (++i < components.length) { statements.push(this[components[i]](this)); } return statements.filter(function (item) { return item; }).join(' '); }
javascript
function select() { var i = -1, statements = []; while (++i < components.length) { statements.push(this[components[i]](this)); } return statements.filter(function (item) { return item; }).join(' '); }
[ "function", "select", "(", ")", "{", "var", "i", "=", "-", "1", ",", "statements", "=", "[", "]", ";", "while", "(", "++", "i", "<", "components", ".", "length", ")", "{", "statements", ".", "push", "(", "this", "[", "components", "[", "i", "]", "]", "(", "this", ")", ")", ";", "}", "return", "statements", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", ";", "}", ")", ".", "join", "(", "' '", ")", ";", "}" ]
Compiles the `select` statement, or nested sub-selects by calling each of the component compilers, trimming out the empties, and returning a generated query string.
[ "Compiles", "the", "select", "statement", "or", "nested", "sub", "-", "selects", "by", "calling", "each", "of", "the", "component", "compilers", "trimming", "out", "the", "empties", "and", "returning", "a", "generated", "query", "string", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L66-L75
38,713
AppGeo/cartodb
lib/compiler.js
update
function update() { var updateData = this._prepUpdate(this.single.update); var wheres = this.where(); var returning = this.single.returning; return { sql: 'update ' + this.tableName + ' set ' + updateData.join(', ') + (wheres ? ' ' + wheres : '') + this._returning(returning), returning: returning }; }
javascript
function update() { var updateData = this._prepUpdate(this.single.update); var wheres = this.where(); var returning = this.single.returning; return { sql: 'update ' + this.tableName + ' set ' + updateData.join(', ') + (wheres ? ' ' + wheres : '') + this._returning(returning), returning: returning }; }
[ "function", "update", "(", ")", "{", "var", "updateData", "=", "this", ".", "_prepUpdate", "(", "this", ".", "single", ".", "update", ")", ";", "var", "wheres", "=", "this", ".", "where", "(", ")", ";", "var", "returning", "=", "this", ".", "single", ".", "returning", ";", "return", "{", "sql", ":", "'update '", "+", "this", ".", "tableName", "+", "' set '", "+", "updateData", ".", "join", "(", "', '", ")", "+", "(", "wheres", "?", "' '", "+", "wheres", ":", "''", ")", "+", "this", ".", "_returning", "(", "returning", ")", ",", "returning", ":", "returning", "}", ";", "}" ]
Compiles the "update" query.
[ "Compiles", "the", "update", "query", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L125-L133
38,714
AppGeo/cartodb
lib/compiler.js
_columns
function _columns() { var distinct = false; if (this.onlyUnions()) { return ''; } var columns = this.grouped.columns || []; var i = -1, sql = []; if (columns) { while (++i < columns.length) { var stmt = columns[i]; if (stmt.distinct) { distinct = true; } if (stmt.type === 'aggregate') { sql.push(this.aggregate(stmt)); } else if (stmt.value && stmt.value.length > 0) { sql.push(this.formatter.columnize(stmt.value)); } } } if (sql.length === 0) { sql = ['*']; } return 'select ' + (distinct ? 'distinct ' : '') + sql.join(', ') + (this.tableName ? ' from ' + this.tableName : ''); }
javascript
function _columns() { var distinct = false; if (this.onlyUnions()) { return ''; } var columns = this.grouped.columns || []; var i = -1, sql = []; if (columns) { while (++i < columns.length) { var stmt = columns[i]; if (stmt.distinct) { distinct = true; } if (stmt.type === 'aggregate') { sql.push(this.aggregate(stmt)); } else if (stmt.value && stmt.value.length > 0) { sql.push(this.formatter.columnize(stmt.value)); } } } if (sql.length === 0) { sql = ['*']; } return 'select ' + (distinct ? 'distinct ' : '') + sql.join(', ') + (this.tableName ? ' from ' + this.tableName : ''); }
[ "function", "_columns", "(", ")", "{", "var", "distinct", "=", "false", ";", "if", "(", "this", ".", "onlyUnions", "(", ")", ")", "{", "return", "''", ";", "}", "var", "columns", "=", "this", ".", "grouped", ".", "columns", "||", "[", "]", ";", "var", "i", "=", "-", "1", ",", "sql", "=", "[", "]", ";", "if", "(", "columns", ")", "{", "while", "(", "++", "i", "<", "columns", ".", "length", ")", "{", "var", "stmt", "=", "columns", "[", "i", "]", ";", "if", "(", "stmt", ".", "distinct", ")", "{", "distinct", "=", "true", ";", "}", "if", "(", "stmt", ".", "type", "===", "'aggregate'", ")", "{", "sql", ".", "push", "(", "this", ".", "aggregate", "(", "stmt", ")", ")", ";", "}", "else", "if", "(", "stmt", ".", "value", "&&", "stmt", ".", "value", ".", "length", ">", "0", ")", "{", "sql", ".", "push", "(", "this", ".", "formatter", ".", "columnize", "(", "stmt", ".", "value", ")", ")", ";", "}", "}", "}", "if", "(", "sql", ".", "length", "===", "0", ")", "{", "sql", "=", "[", "'*'", "]", ";", "}", "return", "'select '", "+", "(", "distinct", "?", "'distinct '", ":", "''", ")", "+", "sql", ".", "join", "(", "', '", ")", "+", "(", "this", ".", "tableName", "?", "' from '", "+", "this", ".", "tableName", ":", "''", ")", ";", "}" ]
Compiles the columns in the query, specifying if an item was distinct.
[ "Compiles", "the", "columns", "in", "the", "query", "specifying", "if", "an", "item", "was", "distinct", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L136-L161
38,715
AppGeo/cartodb
lib/compiler.js
_join
function _join() { var sql = '', i = -1, joins = this.grouped.join; if (!joins) { return ''; } while (++i < joins.length) { var join = joins[i]; if (i > 0) { sql += ' '; } if (join.joinType === 'raw') { sql += this.formatter.unwrapRaw(join.table); } else { sql += join.joinType + ' join ' + this.formatter.wrap(join.table); var ii = -1; while (++ii < join.clauses.length) { var clause = join.clauses[ii]; sql += ' ' + (ii > 0 ? clause[0] : clause[1]) + ' '; sql += this.formatter.wrap(clause[2]); if (clause[3]) { sql += ' ' + this.formatter.operator(clause[3]); } if (clause[4]) { sql += ' ' + this.formatter.wrap(clause[4]); } } } } return sql; }
javascript
function _join() { var sql = '', i = -1, joins = this.grouped.join; if (!joins) { return ''; } while (++i < joins.length) { var join = joins[i]; if (i > 0) { sql += ' '; } if (join.joinType === 'raw') { sql += this.formatter.unwrapRaw(join.table); } else { sql += join.joinType + ' join ' + this.formatter.wrap(join.table); var ii = -1; while (++ii < join.clauses.length) { var clause = join.clauses[ii]; sql += ' ' + (ii > 0 ? clause[0] : clause[1]) + ' '; sql += this.formatter.wrap(clause[2]); if (clause[3]) { sql += ' ' + this.formatter.operator(clause[3]); } if (clause[4]) { sql += ' ' + this.formatter.wrap(clause[4]); } } } } return sql; }
[ "function", "_join", "(", ")", "{", "var", "sql", "=", "''", ",", "i", "=", "-", "1", ",", "joins", "=", "this", ".", "grouped", ".", "join", ";", "if", "(", "!", "joins", ")", "{", "return", "''", ";", "}", "while", "(", "++", "i", "<", "joins", ".", "length", ")", "{", "var", "join", "=", "joins", "[", "i", "]", ";", "if", "(", "i", ">", "0", ")", "{", "sql", "+=", "' '", ";", "}", "if", "(", "join", ".", "joinType", "===", "'raw'", ")", "{", "sql", "+=", "this", ".", "formatter", ".", "unwrapRaw", "(", "join", ".", "table", ")", ";", "}", "else", "{", "sql", "+=", "join", ".", "joinType", "+", "' join '", "+", "this", ".", "formatter", ".", "wrap", "(", "join", ".", "table", ")", ";", "var", "ii", "=", "-", "1", ";", "while", "(", "++", "ii", "<", "join", ".", "clauses", ".", "length", ")", "{", "var", "clause", "=", "join", ".", "clauses", "[", "ii", "]", ";", "sql", "+=", "' '", "+", "(", "ii", ">", "0", "?", "clause", "[", "0", "]", ":", "clause", "[", "1", "]", ")", "+", "' '", ";", "sql", "+=", "this", ".", "formatter", ".", "wrap", "(", "clause", "[", "2", "]", ")", ";", "if", "(", "clause", "[", "3", "]", ")", "{", "sql", "+=", "' '", "+", "this", ".", "formatter", ".", "operator", "(", "clause", "[", "3", "]", ")", ";", "}", "if", "(", "clause", "[", "4", "]", ")", "{", "sql", "+=", "' '", "+", "this", ".", "formatter", ".", "wrap", "(", "clause", "[", "4", "]", ")", ";", "}", "}", "}", "}", "return", "sql", ";", "}" ]
Compiles all each of the `join` clauses on the query, including any nested join queries.
[ "Compiles", "all", "each", "of", "the", "join", "clauses", "on", "the", "query", "including", "any", "nested", "join", "queries", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L177-L208
38,716
AppGeo/cartodb
lib/compiler.js
where
function where() { var wheres = this.grouped.where; if (!wheres) { return undefined; } var i = -1, sql = []; while (++i < wheres.length) { var stmt = wheres[i]; var val = this[stmt.type](stmt); if (val) { if (sql.length === 0) { sql[0] = 'where'; } else { sql.push(stmt.bool); } sql.push(val); } } return sql.length > 1 ? sql.join(' ') : ''; }
javascript
function where() { var wheres = this.grouped.where; if (!wheres) { return undefined; } var i = -1, sql = []; while (++i < wheres.length) { var stmt = wheres[i]; var val = this[stmt.type](stmt); if (val) { if (sql.length === 0) { sql[0] = 'where'; } else { sql.push(stmt.bool); } sql.push(val); } } return sql.length > 1 ? sql.join(' ') : ''; }
[ "function", "where", "(", ")", "{", "var", "wheres", "=", "this", ".", "grouped", ".", "where", ";", "if", "(", "!", "wheres", ")", "{", "return", "undefined", ";", "}", "var", "i", "=", "-", "1", ",", "sql", "=", "[", "]", ";", "while", "(", "++", "i", "<", "wheres", ".", "length", ")", "{", "var", "stmt", "=", "wheres", "[", "i", "]", ";", "var", "val", "=", "this", "[", "stmt", ".", "type", "]", "(", "stmt", ")", ";", "if", "(", "val", ")", "{", "if", "(", "sql", ".", "length", "===", "0", ")", "{", "sql", "[", "0", "]", "=", "'where'", ";", "}", "else", "{", "sql", ".", "push", "(", "stmt", ".", "bool", ")", ";", "}", "sql", ".", "push", "(", "val", ")", ";", "}", "}", "return", "sql", ".", "length", ">", "1", "?", "sql", ".", "join", "(", "' '", ")", ":", "''", ";", "}" ]
Compiles all `where` statements on the query.
[ "Compiles", "all", "where", "statements", "on", "the", "query", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L211-L231
38,717
AppGeo/cartodb
lib/compiler.js
having
function having() { var havings = this.grouped.having; if (!havings) { return ''; } var sql = ['having']; for (var i = 0, l = havings.length; i < l; i++) { var str = '', s = havings[i]; if (i !== 0) { str = s.bool + ' '; } if (s.type === 'havingBasic') { sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value)); } else { if (s.type === 'whereWrapped') { var val = this.whereWrapped(s); if (val) { sql.push(val); } } else { sql.push(str + this.formatter.unwrapRaw(s.value)); } } } return sql.length > 1 ? sql.join(' ') : ''; }
javascript
function having() { var havings = this.grouped.having; if (!havings) { return ''; } var sql = ['having']; for (var i = 0, l = havings.length; i < l; i++) { var str = '', s = havings[i]; if (i !== 0) { str = s.bool + ' '; } if (s.type === 'havingBasic') { sql.push(str + this.formatter.columnize(s.column) + ' ' + this.formatter.operator(s.operator) + ' ' + this.formatter.parameter(s.value)); } else { if (s.type === 'whereWrapped') { var val = this.whereWrapped(s); if (val) { sql.push(val); } } else { sql.push(str + this.formatter.unwrapRaw(s.value)); } } } return sql.length > 1 ? sql.join(' ') : ''; }
[ "function", "having", "(", ")", "{", "var", "havings", "=", "this", ".", "grouped", ".", "having", ";", "if", "(", "!", "havings", ")", "{", "return", "''", ";", "}", "var", "sql", "=", "[", "'having'", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "havings", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "str", "=", "''", ",", "s", "=", "havings", "[", "i", "]", ";", "if", "(", "i", "!==", "0", ")", "{", "str", "=", "s", ".", "bool", "+", "' '", ";", "}", "if", "(", "s", ".", "type", "===", "'havingBasic'", ")", "{", "sql", ".", "push", "(", "str", "+", "this", ".", "formatter", ".", "columnize", "(", "s", ".", "column", ")", "+", "' '", "+", "this", ".", "formatter", ".", "operator", "(", "s", ".", "operator", ")", "+", "' '", "+", "this", ".", "formatter", ".", "parameter", "(", "s", ".", "value", ")", ")", ";", "}", "else", "{", "if", "(", "s", ".", "type", "===", "'whereWrapped'", ")", "{", "var", "val", "=", "this", ".", "whereWrapped", "(", "s", ")", ";", "if", "(", "val", ")", "{", "sql", ".", "push", "(", "val", ")", ";", "}", "}", "else", "{", "sql", ".", "push", "(", "str", "+", "this", ".", "formatter", ".", "unwrapRaw", "(", "s", ".", "value", ")", ")", ";", "}", "}", "}", "return", "sql", ".", "length", ">", "1", "?", "sql", ".", "join", "(", "' '", ")", ":", "''", ";", "}" ]
Compiles the `having` statements.
[ "Compiles", "the", "having", "statements", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L242-L268
38,718
AppGeo/cartodb
lib/compiler.js
_union
function _union() { var onlyUnions = this.onlyUnions(); var unions = this.grouped.union; if (!unions) { return ''; } var sql = ''; for (var i = 0, l = unions.length; i < l; i++) { var union = unions[i]; if (i > 0) { sql += ' '; } if (i > 0 || !onlyUnions) { sql += union.clause + ' '; } var statement = this.formatter.rawOrFn(union.value); if (statement) { if (union.wrap) { sql += '('; } sql += statement; if (union.wrap) { sql += ')'; } } } return sql; }
javascript
function _union() { var onlyUnions = this.onlyUnions(); var unions = this.grouped.union; if (!unions) { return ''; } var sql = ''; for (var i = 0, l = unions.length; i < l; i++) { var union = unions[i]; if (i > 0) { sql += ' '; } if (i > 0 || !onlyUnions) { sql += union.clause + ' '; } var statement = this.formatter.rawOrFn(union.value); if (statement) { if (union.wrap) { sql += '('; } sql += statement; if (union.wrap) { sql += ')'; } } } return sql; }
[ "function", "_union", "(", ")", "{", "var", "onlyUnions", "=", "this", ".", "onlyUnions", "(", ")", ";", "var", "unions", "=", "this", ".", "grouped", ".", "union", ";", "if", "(", "!", "unions", ")", "{", "return", "''", ";", "}", "var", "sql", "=", "''", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "unions", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "var", "union", "=", "unions", "[", "i", "]", ";", "if", "(", "i", ">", "0", ")", "{", "sql", "+=", "' '", ";", "}", "if", "(", "i", ">", "0", "||", "!", "onlyUnions", ")", "{", "sql", "+=", "union", ".", "clause", "+", "' '", ";", "}", "var", "statement", "=", "this", ".", "formatter", ".", "rawOrFn", "(", "union", ".", "value", ")", ";", "if", "(", "statement", ")", "{", "if", "(", "union", ".", "wrap", ")", "{", "sql", "+=", "'('", ";", "}", "sql", "+=", "statement", ";", "if", "(", "union", ".", "wrap", ")", "{", "sql", "+=", "')'", ";", "}", "}", "}", "return", "sql", ";", "}" ]
Compile the "union" queries attached to the main query.
[ "Compile", "the", "union", "queries", "attached", "to", "the", "main", "query", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L271-L298
38,719
AppGeo/cartodb
lib/compiler.js
del
function del() { // Make sure tableName is processed by the formatter first. var tableName = this.tableName; var wheres = this.where(); var sql = 'delete from ' + tableName + (wheres ? ' ' + wheres : ''); var returning = this.single.returning; return { sql: sql + this._returning(returning), returning: returning }; }
javascript
function del() { // Make sure tableName is processed by the formatter first. var tableName = this.tableName; var wheres = this.where(); var sql = 'delete from ' + tableName + (wheres ? ' ' + wheres : ''); var returning = this.single.returning; return { sql: sql + this._returning(returning), returning: returning }; }
[ "function", "del", "(", ")", "{", "// Make sure tableName is processed by the formatter first.", "var", "tableName", "=", "this", ".", "tableName", ";", "var", "wheres", "=", "this", ".", "where", "(", ")", ";", "var", "sql", "=", "'delete from '", "+", "tableName", "+", "(", "wheres", "?", "' '", "+", "wheres", ":", "''", ")", ";", "var", "returning", "=", "this", ".", "single", ".", "returning", ";", "return", "{", "sql", ":", "sql", "+", "this", ".", "_returning", "(", "returning", ")", ",", "returning", ":", "returning", "}", ";", "}" ]
Compiles a `delete` query.
[ "Compiles", "a", "delete", "query", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L322-L332
38,720
AppGeo/cartodb
lib/compiler.js
_counter
function _counter() { var counter = this.single.counter; var toUpdate = {}; toUpdate[counter.column] = this.client.raw(this.formatter.wrap(counter.column) + ' ' + (counter.symbol || '+') + ' ' + counter.amount); this.single.update = toUpdate; return this.update(); }
javascript
function _counter() { var counter = this.single.counter; var toUpdate = {}; toUpdate[counter.column] = this.client.raw(this.formatter.wrap(counter.column) + ' ' + (counter.symbol || '+') + ' ' + counter.amount); this.single.update = toUpdate; return this.update(); }
[ "function", "_counter", "(", ")", "{", "var", "counter", "=", "this", ".", "single", ".", "counter", ";", "var", "toUpdate", "=", "{", "}", ";", "toUpdate", "[", "counter", ".", "column", "]", "=", "this", ".", "client", ".", "raw", "(", "this", ".", "formatter", ".", "wrap", "(", "counter", ".", "column", ")", "+", "' '", "+", "(", "counter", ".", "symbol", "||", "'+'", ")", "+", "' '", "+", "counter", ".", "amount", ")", ";", "this", ".", "single", ".", "update", "=", "toUpdate", ";", "return", "this", ".", "update", "(", ")", ";", "}" ]
Compile the "counter".
[ "Compile", "the", "counter", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L351-L357
38,721
AppGeo/cartodb
lib/compiler.js
whereBasic
function whereBasic(statement) { return this._not(statement, '') + this.formatter.wrap(statement.column) + ' ' + this.formatter.operator(statement.operator) + ' ' + this.formatter.parameter(statement.value); }
javascript
function whereBasic(statement) { return this._not(statement, '') + this.formatter.wrap(statement.column) + ' ' + this.formatter.operator(statement.operator) + ' ' + this.formatter.parameter(statement.value); }
[ "function", "whereBasic", "(", "statement", ")", "{", "return", "this", ".", "_not", "(", "statement", ",", "''", ")", "+", "this", ".", "formatter", ".", "wrap", "(", "statement", ".", "column", ")", "+", "' '", "+", "this", ".", "formatter", ".", "operator", "(", "statement", ".", "operator", ")", "+", "' '", "+", "this", ".", "formatter", ".", "parameter", "(", "statement", ".", "value", ")", ";", "}" ]
Compiles a basic "where" clause.
[ "Compiles", "a", "basic", "where", "clause", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L387-L389
38,722
AppGeo/cartodb
lib/compiler.js
_prepUpdate
function _prepUpdate(data) { var vals = []; var sorted = Object.keys(data).sort(); var i = -1; while (++i < sorted.length) { vals.push(this.formatter.wrap(sorted[i]) + ' = ' + this.formatter.parameter(data[sorted[i]])); } return vals; }
javascript
function _prepUpdate(data) { var vals = []; var sorted = Object.keys(data).sort(); var i = -1; while (++i < sorted.length) { vals.push(this.formatter.wrap(sorted[i]) + ' = ' + this.formatter.parameter(data[sorted[i]])); } return vals; }
[ "function", "_prepUpdate", "(", "data", ")", "{", "var", "vals", "=", "[", "]", ";", "var", "sorted", "=", "Object", ".", "keys", "(", "data", ")", ".", "sort", "(", ")", ";", "var", "i", "=", "-", "1", ";", "while", "(", "++", "i", "<", "sorted", ".", "length", ")", "{", "vals", ".", "push", "(", "this", ".", "formatter", ".", "wrap", "(", "sorted", "[", "i", "]", ")", "+", "' = '", "+", "this", ".", "formatter", ".", "parameter", "(", "data", "[", "sorted", "[", "i", "]", "]", ")", ")", ";", "}", "return", "vals", ";", "}" ]
"Preps" the update.
[ "Preps", "the", "update", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L453-L461
38,723
AppGeo/cartodb
lib/compiler.js
_groupsOrders
function _groupsOrders(type) { var items = this.grouped[type]; if (!items) { return ''; } var formatter = this.formatter; var sql = items.map(function (item) { return (item.value instanceof Raw ? formatter.unwrapRaw(item.value) : formatter.columnize(item.value)) + (type === 'order' && item.type !== 'orderByRaw' ? ' ' + formatter.direction(item.direction) : ''); }); return sql.length ? type + ' by ' + sql.join(', ') : ''; }
javascript
function _groupsOrders(type) { var items = this.grouped[type]; if (!items) { return ''; } var formatter = this.formatter; var sql = items.map(function (item) { return (item.value instanceof Raw ? formatter.unwrapRaw(item.value) : formatter.columnize(item.value)) + (type === 'order' && item.type !== 'orderByRaw' ? ' ' + formatter.direction(item.direction) : ''); }); return sql.length ? type + ' by ' + sql.join(', ') : ''; }
[ "function", "_groupsOrders", "(", "type", ")", "{", "var", "items", "=", "this", ".", "grouped", "[", "type", "]", ";", "if", "(", "!", "items", ")", "{", "return", "''", ";", "}", "var", "formatter", "=", "this", ".", "formatter", ";", "var", "sql", "=", "items", ".", "map", "(", "function", "(", "item", ")", "{", "return", "(", "item", ".", "value", "instanceof", "Raw", "?", "formatter", ".", "unwrapRaw", "(", "item", ".", "value", ")", ":", "formatter", ".", "columnize", "(", "item", ".", "value", ")", ")", "+", "(", "type", "===", "'order'", "&&", "item", ".", "type", "!==", "'orderByRaw'", "?", "' '", "+", "formatter", ".", "direction", "(", "item", ".", "direction", ")", ":", "''", ")", ";", "}", ")", ";", "return", "sql", ".", "length", "?", "type", "+", "' by '", "+", "sql", ".", "join", "(", "', '", ")", ":", "''", ";", "}" ]
Compiles the `order by` statements.
[ "Compiles", "the", "order", "by", "statements", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L464-L474
38,724
AppGeo/cartodb
lib/compiler.js
columnInfo
function columnInfo() { var column = this.single.columnInfo; return { sql: 'select * from information_schema.columns where table_name = ? and table_catalog = ?', bindings: [this.single.table, this.client.database()], output: function output(resp) { var out = resp.rows.reduce(function (columns, val) { columns[val.column_name] = { type: val.data_type, maxLength: val.character_maximum_length, nullable: val.is_nullable === 'YES', defaultValue: val.column_default }; return columns; }, {}); return column && out[column] || out; } }; }
javascript
function columnInfo() { var column = this.single.columnInfo; return { sql: 'select * from information_schema.columns where table_name = ? and table_catalog = ?', bindings: [this.single.table, this.client.database()], output: function output(resp) { var out = resp.rows.reduce(function (columns, val) { columns[val.column_name] = { type: val.data_type, maxLength: val.character_maximum_length, nullable: val.is_nullable === 'YES', defaultValue: val.column_default }; return columns; }, {}); return column && out[column] || out; } }; }
[ "function", "columnInfo", "(", ")", "{", "var", "column", "=", "this", ".", "single", ".", "columnInfo", ";", "return", "{", "sql", ":", "'select * from information_schema.columns where table_name = ? and table_catalog = ?'", ",", "bindings", ":", "[", "this", ".", "single", ".", "table", ",", "this", ".", "client", ".", "database", "(", ")", "]", ",", "output", ":", "function", "output", "(", "resp", ")", "{", "var", "out", "=", "resp", ".", "rows", ".", "reduce", "(", "function", "(", "columns", ",", "val", ")", "{", "columns", "[", "val", ".", "column_name", "]", "=", "{", "type", ":", "val", ".", "data_type", ",", "maxLength", ":", "val", ".", "character_maximum_length", ",", "nullable", ":", "val", ".", "is_nullable", "===", "'YES'", ",", "defaultValue", ":", "val", ".", "column_default", "}", ";", "return", "columns", ";", "}", ",", "{", "}", ")", ";", "return", "column", "&&", "out", "[", "column", "]", "||", "out", ";", "}", "}", ";", "}" ]
Compiles a columnInfo query
[ "Compiles", "a", "columnInfo", "query" ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/compiler.js#L489-L507
38,725
crcn/celeri
lib/plugins/command.route.js
fixRoute
function fixRoute(route) { //protect special chars while we replace return route.replace(/\s*OR\s*/g,'__OR__'). replace(/\s*->\s*/g,'__->__'). replace(/[\s\t\n]+/g,'/'). replace(/__/g,' '); }
javascript
function fixRoute(route) { //protect special chars while we replace return route.replace(/\s*OR\s*/g,'__OR__'). replace(/\s*->\s*/g,'__->__'). replace(/[\s\t\n]+/g,'/'). replace(/__/g,' '); }
[ "function", "fixRoute", "(", "route", ")", "{", "//protect special chars while we replace", "return", "route", ".", "replace", "(", "/", "\\s*OR\\s*", "/", "g", ",", "'__OR__'", ")", ".", "replace", "(", "/", "\\s*->\\s*", "/", "g", ",", "'__->__'", ")", ".", "replace", "(", "/", "[\\s\\t\\n]+", "/", "g", ",", "'/'", ")", ".", "replace", "(", "/", "__", "/", "g", ",", "' '", ")", ";", "}" ]
changes for beanpole prohibit the use of whitespace
[ "changes", "for", "beanpole", "prohibit", "the", "use", "of", "whitespace" ]
f10471478b9119485c7c72a49015e22ec4339e29
https://github.com/crcn/celeri/blob/f10471478b9119485c7c72a49015e22ec4339e29/lib/plugins/command.route.js#L9-L16
38,726
dirkbonhomme/infinite-timeout
lib/timeout.js
function(callback, timeout){ var id = index++; if(timeout > MAX_INT){ timeouts[id] = setTimeout(set.bind(undefined, callback, timeout - MAX_INT), MAX_INT); }else{ if(timeout < 0) timeout = 0; timeouts[id] = setTimeout(function(){ delete timeouts[id]; callback(); }, timeout); } return id; }
javascript
function(callback, timeout){ var id = index++; if(timeout > MAX_INT){ timeouts[id] = setTimeout(set.bind(undefined, callback, timeout - MAX_INT), MAX_INT); }else{ if(timeout < 0) timeout = 0; timeouts[id] = setTimeout(function(){ delete timeouts[id]; callback(); }, timeout); } return id; }
[ "function", "(", "callback", ",", "timeout", ")", "{", "var", "id", "=", "index", "++", ";", "if", "(", "timeout", ">", "MAX_INT", ")", "{", "timeouts", "[", "id", "]", "=", "setTimeout", "(", "set", ".", "bind", "(", "undefined", ",", "callback", ",", "timeout", "-", "MAX_INT", ")", ",", "MAX_INT", ")", ";", "}", "else", "{", "if", "(", "timeout", "<", "0", ")", "timeout", "=", "0", ";", "timeouts", "[", "id", "]", "=", "setTimeout", "(", "function", "(", ")", "{", "delete", "timeouts", "[", "id", "]", ";", "callback", "(", ")", ";", "}", ",", "timeout", ")", ";", "}", "return", "id", ";", "}" ]
Set new timeout
[ "Set", "new", "timeout" ]
adf33ec4f94feb2226fcae4d0eb80e808292d7a7
https://github.com/dirkbonhomme/infinite-timeout/blob/adf33ec4f94feb2226fcae4d0eb80e808292d7a7/lib/timeout.js#L7-L19
38,727
rootsdev/gedcomx-js
src/core/SourceDescription.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceDescription)){ return new SourceDescription(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceDescription.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceDescription)){ return new SourceDescription(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceDescription.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "// Protect against forgetting the new keyword when calling the constructor", "if", "(", "!", "(", "this", "instanceof", "SourceDescription", ")", ")", "{", "return", "new", "SourceDescription", "(", "json", ")", ";", "}", "// If the given object is already an instance then just return it. DON'T copy it.", "if", "(", "SourceDescription", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A description of a source. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#source-description|GEDCOM X JSON Spec} @class @extends ExtensibleData @apram {Object} [json]
[ "A", "description", "of", "a", "source", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/SourceDescription.js#L13-L26
38,728
apparebit/js-junction
packages/proact/vdom/component.js
from
function from(renderFn, name = renderFn.name) { if (typeof name === 'function') { [renderFn, name] = [name, renderFn]; } else if (typeof renderFn !== 'function') { throw InvalidArgType({ renderFn }, 'a function'); } name = String(name); if (!name) { throw InvalidArgValue({ name }, 'should not be empty'); } function RenderFunction(...args) { if (!new.target) return new RenderFunction(...args); // 1st argument may be constructor itself to (redundantly) capture identity. if (args[0] === RenderFunction) args.shift(); // Delegate processing of properties to Node. apply(Node, this, args); } // The isViewComponent, toStringTag, and provideContext properties are the // same for all render function components and could thus be moved into a // shared prototype. While that may reduce memory pressure, it also increases // the length of the prototype chain and thus property lookup latency. const RenderFunctionPrototype = create(NodePrototype, { constructor: { configurable, value: RenderFunction }, isViewComponent: { configurable, value: true }, // Flag to detect view component type. [toStringTag]: { configurable, value: 'Proact.Component' }, name: { configurable, enumerable, value: name }, render: { configurable, value: renderFn }, provideContext: { configurable, value: provideContext }, }); defineProperties(RenderFunction, { prototype: { value: RenderFunctionPrototype }, name: { configurable, enumerable, value: name }, }); return RenderFunction; }
javascript
function from(renderFn, name = renderFn.name) { if (typeof name === 'function') { [renderFn, name] = [name, renderFn]; } else if (typeof renderFn !== 'function') { throw InvalidArgType({ renderFn }, 'a function'); } name = String(name); if (!name) { throw InvalidArgValue({ name }, 'should not be empty'); } function RenderFunction(...args) { if (!new.target) return new RenderFunction(...args); // 1st argument may be constructor itself to (redundantly) capture identity. if (args[0] === RenderFunction) args.shift(); // Delegate processing of properties to Node. apply(Node, this, args); } // The isViewComponent, toStringTag, and provideContext properties are the // same for all render function components and could thus be moved into a // shared prototype. While that may reduce memory pressure, it also increases // the length of the prototype chain and thus property lookup latency. const RenderFunctionPrototype = create(NodePrototype, { constructor: { configurable, value: RenderFunction }, isViewComponent: { configurable, value: true }, // Flag to detect view component type. [toStringTag]: { configurable, value: 'Proact.Component' }, name: { configurable, enumerable, value: name }, render: { configurable, value: renderFn }, provideContext: { configurable, value: provideContext }, }); defineProperties(RenderFunction, { prototype: { value: RenderFunctionPrototype }, name: { configurable, enumerable, value: name }, }); return RenderFunction; }
[ "function", "from", "(", "renderFn", ",", "name", "=", "renderFn", ".", "name", ")", "{", "if", "(", "typeof", "name", "===", "'function'", ")", "{", "[", "renderFn", ",", "name", "]", "=", "[", "name", ",", "renderFn", "]", ";", "}", "else", "if", "(", "typeof", "renderFn", "!==", "'function'", ")", "{", "throw", "InvalidArgType", "(", "{", "renderFn", "}", ",", "'a function'", ")", ";", "}", "name", "=", "String", "(", "name", ")", ";", "if", "(", "!", "name", ")", "{", "throw", "InvalidArgValue", "(", "{", "name", "}", ",", "'should not be empty'", ")", ";", "}", "function", "RenderFunction", "(", "...", "args", ")", "{", "if", "(", "!", "new", ".", "target", ")", "return", "new", "RenderFunction", "(", "...", "args", ")", ";", "// 1st argument may be constructor itself to (redundantly) capture identity.", "if", "(", "args", "[", "0", "]", "===", "RenderFunction", ")", "args", ".", "shift", "(", ")", ";", "// Delegate processing of properties to Node.", "apply", "(", "Node", ",", "this", ",", "args", ")", ";", "}", "// The isViewComponent, toStringTag, and provideContext properties are the", "// same for all render function components and could thus be moved into a", "// shared prototype. While that may reduce memory pressure, it also increases", "// the length of the prototype chain and thus property lookup latency.", "const", "RenderFunctionPrototype", "=", "create", "(", "NodePrototype", ",", "{", "constructor", ":", "{", "configurable", ",", "value", ":", "RenderFunction", "}", ",", "isViewComponent", ":", "{", "configurable", ",", "value", ":", "true", "}", ",", "// Flag to detect view component type.", "[", "toStringTag", "]", ":", "{", "configurable", ",", "value", ":", "'Proact.Component'", "}", ",", "name", ":", "{", "configurable", ",", "enumerable", ",", "value", ":", "name", "}", ",", "render", ":", "{", "configurable", ",", "value", ":", "renderFn", "}", ",", "provideContext", ":", "{", "configurable", ",", "value", ":", "provideContext", "}", ",", "}", ")", ";", "defineProperties", "(", "RenderFunction", ",", "{", "prototype", ":", "{", "value", ":", "RenderFunctionPrototype", "}", ",", "name", ":", "{", "configurable", ",", "enumerable", ",", "value", ":", "name", "}", ",", "}", ")", ";", "return", "RenderFunction", ";", "}" ]
Create a functional component with the given render function and name. For named functions, the name may be omitted to avoid repetition. The name may also be specified before the render function to accommodate arrow functions while also optimizing for readability.
[ "Create", "a", "functional", "component", "with", "the", "given", "render", "function", "and", "name", ".", "For", "named", "functions", "the", "name", "may", "be", "omitted", "to", "avoid", "repetition", ".", "The", "name", "may", "also", "be", "specified", "before", "the", "render", "function", "to", "accommodate", "arrow", "functions", "while", "also", "optimizing", "for", "readability", "." ]
240b15961c35f19c3a1effd9df51e0bf8e0bbffc
https://github.com/apparebit/js-junction/blob/240b15961c35f19c3a1effd9df51e0bf8e0bbffc/packages/proact/vdom/component.js#L33-L74
38,729
codeactual/apidox
lib/apidox/index.js
ApiDox
function ApiDox() { this.settings = { input: '', inputText: null, inputTitle: '', output: '', fullSourceDescription: false }; this.anchors = {}; this.comments = []; this.curSection = null; this.fileComment = {}; this.lines = []; this.params = {}; this.returns = {}; this.sees = []; this.toc = []; this.throws = []; }
javascript
function ApiDox() { this.settings = { input: '', inputText: null, inputTitle: '', output: '', fullSourceDescription: false }; this.anchors = {}; this.comments = []; this.curSection = null; this.fileComment = {}; this.lines = []; this.params = {}; this.returns = {}; this.sees = []; this.toc = []; this.throws = []; }
[ "function", "ApiDox", "(", ")", "{", "this", ".", "settings", "=", "{", "input", ":", "''", ",", "inputText", ":", "null", ",", "inputTitle", ":", "''", ",", "output", ":", "''", ",", "fullSourceDescription", ":", "false", "}", ";", "this", ".", "anchors", "=", "{", "}", ";", "this", ".", "comments", "=", "[", "]", ";", "this", ".", "curSection", "=", "null", ";", "this", ".", "fileComment", "=", "{", "}", ";", "this", ".", "lines", "=", "[", "]", ";", "this", ".", "params", "=", "{", "}", ";", "this", ".", "returns", "=", "{", "}", ";", "this", ".", "sees", "=", "[", "]", ";", "this", ".", "toc", "=", "[", "]", ";", "this", ".", "throws", "=", "[", "]", ";", "}" ]
ApiDox constructor. Usage: var dox = require('apidox').create(); var markdown = dox .set('input', '/path/to/source.js') .set('output', '/path/to/output.md') .parse() .convert(); Configuration: - `{string} input` Source file to read - `{string} inputText` Alternative to `input` - `{string|boolean} [inputTitle=input]` Customize `Source: ...` link text - `false`: Omit `Source: ...` entirely from markdown - `string`: Set link text (does not affect link URL) - `{string} output` Markdown file to write Properties: - `{object} anchors` Keys are object paths which already have anchors - For duplicate prevention - `{array} comments` Filtered dox-provided objects to convert - `{string curSection` Current section being converted, ex. 'Klass.prototype'. - `{object} fileComment` First dox-provided comment found in the file - `{array} lines` Markdown lines - `{object} params` Collected `@param` meta indexed by method name - `{array} types` Type names - `{string} description` First line - `{array} overflow` Additional lines - `{object} returns` Collected `@return` metadata indexed by method name - `{array} types` Type names - `{string} description` First line - `{array} overflow` Additional lines - `{array} sees` Collected `@see` lines - `{array} toc` Collected table-of-contents metadata objects - `{string} title` Link title - `{string} url` Link URL - `{array} throws` Collected `@throws` lines
[ "ApiDox", "constructor", "." ]
3dd28222035d511bd210f518694b9d3cfdbf81ed
https://github.com/codeactual/apidox/blob/3dd28222035d511bd210f518694b9d3cfdbf81ed/lib/apidox/index.js#L90-L108
38,730
angie-framework/angie
src/Server.js
forceEnd
function forceEnd(path, response) { // Send a custom response for gateway timeout new $CustomResponse().head(504, null, { 'Content-Type': 'text/html' }).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`); // Log something $LogProvider.error(path, response._header); // End the response end(response); }
javascript
function forceEnd(path, response) { // Send a custom response for gateway timeout new $CustomResponse().head(504, null, { 'Content-Type': 'text/html' }).writeSync(`<h1>${RESPONSE_HEADER_MESSAGES[ 504 ]}</h1>`); // Log something $LogProvider.error(path, response._header); // End the response end(response); }
[ "function", "forceEnd", "(", "path", ",", "response", ")", "{", "// Send a custom response for gateway timeout", "new", "$CustomResponse", "(", ")", ".", "head", "(", "504", ",", "null", ",", "{", "'Content-Type'", ":", "'text/html'", "}", ")", ".", "writeSync", "(", "`", "${", "RESPONSE_HEADER_MESSAGES", "[", "504", "]", "}", "`", ")", ";", "// Log something", "$LogProvider", ".", "error", "(", "path", ",", "response", ".", "_header", ")", ";", "// End the response", "end", "(", "response", ")", ";", "}" ]
Force an ended response with a timeout
[ "Force", "an", "ended", "response", "with", "a", "timeout" ]
7d0793f6125e60e0473b17ffd40305d6d6fdbc12
https://github.com/angie-framework/angie/blob/7d0793f6125e60e0473b17ffd40305d6d6fdbc12/src/Server.js#L325-L337
38,731
edwardhotchkiss/github3
lib/github3.js
function(opts){ //defaults opts = opts || {}; this.username = opts.username || ''; this.password = opts.password || ''; // oAuth Token this.accessToken = opts.accessToken || ''; // API Rate Limit Details this.rateLimit = 5000; this.rateLimitRemaining = this.rateLimit; //rateLimitRemaining starts as rateLimit }
javascript
function(opts){ //defaults opts = opts || {}; this.username = opts.username || ''; this.password = opts.password || ''; // oAuth Token this.accessToken = opts.accessToken || ''; // API Rate Limit Details this.rateLimit = 5000; this.rateLimitRemaining = this.rateLimit; //rateLimitRemaining starts as rateLimit }
[ "function", "(", "opts", ")", "{", "//defaults", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "username", "=", "opts", ".", "username", "||", "''", ";", "this", ".", "password", "=", "opts", ".", "password", "||", "''", ";", "// oAuth Token", "this", ".", "accessToken", "=", "opts", ".", "accessToken", "||", "''", ";", "// API Rate Limit Details", "this", ".", "rateLimit", "=", "5000", ";", "this", ".", "rateLimitRemaining", "=", "this", ".", "rateLimit", ";", "//rateLimitRemaining starts as rateLimit", "}" ]
Sets credentials for GitHub access. @class Github3 @constructor @param {Object} opts {String} .username GitHub username {String} .password GitHub password {Token } .accessToken GitHub oAuth Token
[ "Sets", "credentials", "for", "GitHub", "access", "." ]
ad6cf10b63b2b92a58d0517ffab4c0af692b1db9
https://github.com/edwardhotchkiss/github3/blob/ad6cf10b63b2b92a58d0517ffab4c0af692b1db9/lib/github3.js#L24-L34
38,732
jhermsmeier/node-async-emitter
emitter.js
function( type, handler ) { if( handler === void 0 || handler === null ) throw new Error( 'Missing argument "handler"' ) if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' ) throw new TypeError( 'Handler must be a function.' ) this._events[ type ] ? this._events[ type ].push( handler ) : this._events[ type ] = [ handler ] if( Emitter.warn && this._events[ type ].length > this._maxListeners ) { if( this._maxListeners > 0 && !this._memLeakDetected ) { this._memLeakDetected = true console.warn( 'WARNING: Possible event emitter memory leak detected.', this._events[ type ].length, 'event handlers added.', 'Use emitter.setMaxListeners() to increase the threshold.' ) console.trace() } } return this }
javascript
function( type, handler ) { if( handler === void 0 || handler === null ) throw new Error( 'Missing argument "handler"' ) if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' ) throw new TypeError( 'Handler must be a function.' ) this._events[ type ] ? this._events[ type ].push( handler ) : this._events[ type ] = [ handler ] if( Emitter.warn && this._events[ type ].length > this._maxListeners ) { if( this._maxListeners > 0 && !this._memLeakDetected ) { this._memLeakDetected = true console.warn( 'WARNING: Possible event emitter memory leak detected.', this._events[ type ].length, 'event handlers added.', 'Use emitter.setMaxListeners() to increase the threshold.' ) console.trace() } } return this }
[ "function", "(", "type", ",", "handler", ")", "{", "if", "(", "handler", "===", "void", "0", "||", "handler", "===", "null", ")", "throw", "new", "Error", "(", "'Missing argument \"handler\"'", ")", "if", "(", "typeof", "handler", "!==", "'function'", "&&", "typeof", "handler", ".", "handleEvent", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'Handler must be a function.'", ")", "this", ".", "_events", "[", "type", "]", "?", "this", ".", "_events", "[", "type", "]", ".", "push", "(", "handler", ")", ":", "this", ".", "_events", "[", "type", "]", "=", "[", "handler", "]", "if", "(", "Emitter", ".", "warn", "&&", "this", ".", "_events", "[", "type", "]", ".", "length", ">", "this", ".", "_maxListeners", ")", "{", "if", "(", "this", ".", "_maxListeners", ">", "0", "&&", "!", "this", ".", "_memLeakDetected", ")", "{", "this", ".", "_memLeakDetected", "=", "true", "console", ".", "warn", "(", "'WARNING: Possible event emitter memory leak detected.'", ",", "this", ".", "_events", "[", "type", "]", ".", "length", ",", "'event handlers added.'", ",", "'Use emitter.setMaxListeners() to increase the threshold.'", ")", "console", ".", "trace", "(", ")", "}", "}", "return", "this", "}" ]
Adds a listener for the specified event @param {String} type @param {Function} handler @return {Emitter}
[ "Adds", "a", "listener", "for", "the", "specified", "event" ]
d710b4be188ca47d2f124c2c5280330691665774
https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L72-L98
38,733
jhermsmeier/node-async-emitter
emitter.js
function( type, handler ) { if( handler === void 0 || handler === null ) throw new Error( 'Missing argument "handler"' ) if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' ) throw new TypeError( 'Handler must be a function.' ) function wrapper() { this.removeListener( type, wrapper ) typeof handler !== 'function' ? handler.handleEvent.apply( handler, arguments ) : handler.apply( this, arguments ) } this._events[ type ] ? this._events[ type ].push( wrapper ) : this._events[ type ] = [ wrapper ] return this }
javascript
function( type, handler ) { if( handler === void 0 || handler === null ) throw new Error( 'Missing argument "handler"' ) if( typeof handler !== 'function' && typeof handler.handleEvent !== 'function' ) throw new TypeError( 'Handler must be a function.' ) function wrapper() { this.removeListener( type, wrapper ) typeof handler !== 'function' ? handler.handleEvent.apply( handler, arguments ) : handler.apply( this, arguments ) } this._events[ type ] ? this._events[ type ].push( wrapper ) : this._events[ type ] = [ wrapper ] return this }
[ "function", "(", "type", ",", "handler", ")", "{", "if", "(", "handler", "===", "void", "0", "||", "handler", "===", "null", ")", "throw", "new", "Error", "(", "'Missing argument \"handler\"'", ")", "if", "(", "typeof", "handler", "!==", "'function'", "&&", "typeof", "handler", ".", "handleEvent", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "'Handler must be a function.'", ")", "function", "wrapper", "(", ")", "{", "this", ".", "removeListener", "(", "type", ",", "wrapper", ")", "typeof", "handler", "!==", "'function'", "?", "handler", ".", "handleEvent", ".", "apply", "(", "handler", ",", "arguments", ")", ":", "handler", ".", "apply", "(", "this", ",", "arguments", ")", "}", "this", ".", "_events", "[", "type", "]", "?", "this", ".", "_events", "[", "type", "]", ".", "push", "(", "wrapper", ")", ":", "this", ".", "_events", "[", "type", "]", "=", "[", "wrapper", "]", "return", "this", "}" ]
Adds a one time listener for the specified event @param {String} type @param {Function} handler @return {Emitter}
[ "Adds", "a", "one", "time", "listener", "for", "the", "specified", "event" ]
d710b4be188ca47d2f124c2c5280330691665774
https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L106-L127
38,734
jhermsmeier/node-async-emitter
emitter.js
function( type ) { var emitter = this var listeners = this._events[ type ] if( type === 'error' && !listeners ) { if( !this._events.error ) { throw !( arguments[1] instanceof Error ) ? new Error( 'Unhandled "error" event.' ) : arguments[1] } } else if( !listeners ) { return false } var argv = [].slice.call( arguments, 1 ) var i, len = listeners.length function fire( handler, argv ) { typeof handler !== 'function' ? handler.handleEvent.apply( handler, argv ) : handler.apply( this, argv ) } for( i = 0; i < len; i++ ) { Emitter.nextTick( fire.bind( this, listeners[i], argv ) ) } return true }
javascript
function( type ) { var emitter = this var listeners = this._events[ type ] if( type === 'error' && !listeners ) { if( !this._events.error ) { throw !( arguments[1] instanceof Error ) ? new Error( 'Unhandled "error" event.' ) : arguments[1] } } else if( !listeners ) { return false } var argv = [].slice.call( arguments, 1 ) var i, len = listeners.length function fire( handler, argv ) { typeof handler !== 'function' ? handler.handleEvent.apply( handler, argv ) : handler.apply( this, argv ) } for( i = 0; i < len; i++ ) { Emitter.nextTick( fire.bind( this, listeners[i], argv ) ) } return true }
[ "function", "(", "type", ")", "{", "var", "emitter", "=", "this", "var", "listeners", "=", "this", ".", "_events", "[", "type", "]", "if", "(", "type", "===", "'error'", "&&", "!", "listeners", ")", "{", "if", "(", "!", "this", ".", "_events", ".", "error", ")", "{", "throw", "!", "(", "arguments", "[", "1", "]", "instanceof", "Error", ")", "?", "new", "Error", "(", "'Unhandled \"error\" event.'", ")", ":", "arguments", "[", "1", "]", "}", "}", "else", "if", "(", "!", "listeners", ")", "{", "return", "false", "}", "var", "argv", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", "var", "i", ",", "len", "=", "listeners", ".", "length", "function", "fire", "(", "handler", ",", "argv", ")", "{", "typeof", "handler", "!==", "'function'", "?", "handler", ".", "handleEvent", ".", "apply", "(", "handler", ",", "argv", ")", ":", "handler", ".", "apply", "(", "this", ",", "argv", ")", "}", "for", "(", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "Emitter", ".", "nextTick", "(", "fire", ".", "bind", "(", "this", ",", "listeners", "[", "i", "]", ",", "argv", ")", ")", "}", "return", "true", "}" ]
Execute each of the listeners in order with the supplied arguments @param {String} type @return {Boolean}
[ "Execute", "each", "of", "the", "listeners", "in", "order", "with", "the", "supplied", "arguments" ]
d710b4be188ca47d2f124c2c5280330691665774
https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L135-L167
38,735
jhermsmeier/node-async-emitter
emitter.js
function( type, handler ) { var handlers = this._events[ type ] var position = handlers.indexOf( handler ) if( handlers && ~position ) { if( handlers.length === 1 ) { this._events[ type ] = undefined delete this._events[ type ] } else { handlers.splice( position, 1 ) } } return this }
javascript
function( type, handler ) { var handlers = this._events[ type ] var position = handlers.indexOf( handler ) if( handlers && ~position ) { if( handlers.length === 1 ) { this._events[ type ] = undefined delete this._events[ type ] } else { handlers.splice( position, 1 ) } } return this }
[ "function", "(", "type", ",", "handler", ")", "{", "var", "handlers", "=", "this", ".", "_events", "[", "type", "]", "var", "position", "=", "handlers", ".", "indexOf", "(", "handler", ")", "if", "(", "handlers", "&&", "~", "position", ")", "{", "if", "(", "handlers", ".", "length", "===", "1", ")", "{", "this", ".", "_events", "[", "type", "]", "=", "undefined", "delete", "this", ".", "_events", "[", "type", "]", "}", "else", "{", "handlers", ".", "splice", "(", "position", ",", "1", ")", "}", "}", "return", "this", "}" ]
Remove a listener for the specified event @param {String} type @param {Function} handler @return {Emitter}
[ "Remove", "a", "listener", "for", "the", "specified", "event" ]
d710b4be188ca47d2f124c2c5280330691665774
https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L239-L255
38,736
jhermsmeier/node-async-emitter
emitter.js
function( type ) { if( arguments.length === 0 ) { for( type in this._events ) { this.removeAllListeners( type ) } } else { this._events[ type ] = undefined delete this._events[ type ] } return this }
javascript
function( type ) { if( arguments.length === 0 ) { for( type in this._events ) { this.removeAllListeners( type ) } } else { this._events[ type ] = undefined delete this._events[ type ] } return this }
[ "function", "(", "type", ")", "{", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "for", "(", "type", "in", "this", ".", "_events", ")", "{", "this", ".", "removeAllListeners", "(", "type", ")", "}", "}", "else", "{", "this", ".", "_events", "[", "type", "]", "=", "undefined", "delete", "this", ".", "_events", "[", "type", "]", "}", "return", "this", "}" ]
Removes all listeners, or those of the specified event @param {String} type @return {Emitter}
[ "Removes", "all", "listeners", "or", "those", "of", "the", "specified", "event" ]
d710b4be188ca47d2f124c2c5280330691665774
https://github.com/jhermsmeier/node-async-emitter/blob/d710b4be188ca47d2f124c2c5280330691665774/emitter.js#L263-L276
38,737
phillipsdata/unicode-passgen
index.js
getOptions
function getOptions(options) { var opts = { include: [ { chars: [[0x0000, 0xFFFF]], min: 0 } ], exclude: [] }; // Merge the properties of our options for (var property in options) { // Ignore options that are not in our opts set or are not an array if (!opts.hasOwnProperty(property) || !Array.isArray(options[property])) { continue; } // Reset the default value for this property since it's being overridden if (property === 'include') { opts.include = []; } // Merge the options given for (var set in options[property]) { if (typeof options[property][set] === 'object' && options[property][set].hasOwnProperty('chars') && Array.isArray(options[property][set].chars) ) { // Add the character set to the options var charSet = { chars: options[property][set].chars, min: 0 }; // Set the minimum value if given if (options[property][set].hasOwnProperty('min') && isInt(options[property][set].min) && options[property][set].min > 0 ) { charSet.min = options[property][set].min; } opts[property].push(charSet); } } } return opts; }
javascript
function getOptions(options) { var opts = { include: [ { chars: [[0x0000, 0xFFFF]], min: 0 } ], exclude: [] }; // Merge the properties of our options for (var property in options) { // Ignore options that are not in our opts set or are not an array if (!opts.hasOwnProperty(property) || !Array.isArray(options[property])) { continue; } // Reset the default value for this property since it's being overridden if (property === 'include') { opts.include = []; } // Merge the options given for (var set in options[property]) { if (typeof options[property][set] === 'object' && options[property][set].hasOwnProperty('chars') && Array.isArray(options[property][set].chars) ) { // Add the character set to the options var charSet = { chars: options[property][set].chars, min: 0 }; // Set the minimum value if given if (options[property][set].hasOwnProperty('min') && isInt(options[property][set].min) && options[property][set].min > 0 ) { charSet.min = options[property][set].min; } opts[property].push(charSet); } } } return opts; }
[ "function", "getOptions", "(", "options", ")", "{", "var", "opts", "=", "{", "include", ":", "[", "{", "chars", ":", "[", "[", "0x0000", ",", "0xFFFF", "]", "]", ",", "min", ":", "0", "}", "]", ",", "exclude", ":", "[", "]", "}", ";", "// Merge the properties of our options", "for", "(", "var", "property", "in", "options", ")", "{", "// Ignore options that are not in our opts set or are not an array", "if", "(", "!", "opts", ".", "hasOwnProperty", "(", "property", ")", "||", "!", "Array", ".", "isArray", "(", "options", "[", "property", "]", ")", ")", "{", "continue", ";", "}", "// Reset the default value for this property since it's being overridden", "if", "(", "property", "===", "'include'", ")", "{", "opts", ".", "include", "=", "[", "]", ";", "}", "// Merge the options given", "for", "(", "var", "set", "in", "options", "[", "property", "]", ")", "{", "if", "(", "typeof", "options", "[", "property", "]", "[", "set", "]", "===", "'object'", "&&", "options", "[", "property", "]", "[", "set", "]", ".", "hasOwnProperty", "(", "'chars'", ")", "&&", "Array", ".", "isArray", "(", "options", "[", "property", "]", "[", "set", "]", ".", "chars", ")", ")", "{", "// Add the character set to the options", "var", "charSet", "=", "{", "chars", ":", "options", "[", "property", "]", "[", "set", "]", ".", "chars", ",", "min", ":", "0", "}", ";", "// Set the minimum value if given", "if", "(", "options", "[", "property", "]", "[", "set", "]", ".", "hasOwnProperty", "(", "'min'", ")", "&&", "isInt", "(", "options", "[", "property", "]", "[", "set", "]", ".", "min", ")", "&&", "options", "[", "property", "]", "[", "set", "]", ".", "min", ">", "0", ")", "{", "charSet", ".", "min", "=", "options", "[", "property", "]", "[", "set", "]", ".", "min", ";", "}", "opts", "[", "property", "]", ".", "push", "(", "charSet", ")", ";", "}", "}", "}", "return", "opts", ";", "}" ]
Creates a set of options for the generator from the given options @param {Object} options An Object containing: - include (optional) - An Object containing an Array of Objects, each of which contain: - chars - An Array containing an Array of 1 character per index: - 0 - A single character, hex character, or unicode character. This may be a single character to include, or the beginning of a range of characters to include - 1 - A single character, hex character, or unicode character. This must be the end of the range of the characters to include. - min (optional) - An Integer representing the minimum number of characters from the 'chars' set that *must* be included in the generated string - exclude (optional) - An Object containing an Array of Objects, each of which contain: - chars - An Array containing an Array of 1 character per index: - 0 - A single character, hex character, or unicode character. This may be a single character to exclude, or the beginning of a range of characters to exclude - 1 - A single character, hex character, or unicode character. This must be the end of the range of the characters to exclude. @returns {Object} An Object representing the given options
[ "Creates", "a", "set", "of", "options", "for", "the", "generator", "from", "the", "given", "options" ]
b412707e45933cfc5da0428fa656d053883baadf
https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L100-L149
38,738
phillipsdata/unicode-passgen
index.js
generateString
function generateString(set, length) { var content = ''; // Cannot generate a string from an empty set if (set.length <= 0) { return content; } for (var i = 0; i < length; i++) { content += String.fromCharCode( set[Math.floor(Math.random() * set.length)] ); } return content; }
javascript
function generateString(set, length) { var content = ''; // Cannot generate a string from an empty set if (set.length <= 0) { return content; } for (var i = 0; i < length; i++) { content += String.fromCharCode( set[Math.floor(Math.random() * set.length)] ); } return content; }
[ "function", "generateString", "(", "set", ",", "length", ")", "{", "var", "content", "=", "''", ";", "// Cannot generate a string from an empty set", "if", "(", "set", ".", "length", "<=", "0", ")", "{", "return", "content", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "content", "+=", "String", ".", "fromCharCode", "(", "set", "[", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "set", ".", "length", ")", "]", ")", ";", "}", "return", "content", ";", "}" ]
Generates a string of the given length from the given set of characters @param {Array} set An Array of decimal characters @param {Integer} length The length of the string to generate @returns {String} The random generated string
[ "Generates", "a", "string", "of", "the", "given", "length", "from", "the", "given", "set", "of", "characters" ]
b412707e45933cfc5da0428fa656d053883baadf
https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L158-L173
38,739
phillipsdata/unicode-passgen
index.js
getCharacterList
function getCharacterList(options) { var regen = regenerate(); var include = options.include; for (var i in include) { for (var j in include[i].chars) { // There should always be a 0th-index element if (include[i].chars[j][0] === undefined) { continue; } regen = addCharacters(regen, include[i].chars[j]); } } removeCharacters(regen, options.exclude); return regen.valueOf(); }
javascript
function getCharacterList(options) { var regen = regenerate(); var include = options.include; for (var i in include) { for (var j in include[i].chars) { // There should always be a 0th-index element if (include[i].chars[j][0] === undefined) { continue; } regen = addCharacters(regen, include[i].chars[j]); } } removeCharacters(regen, options.exclude); return regen.valueOf(); }
[ "function", "getCharacterList", "(", "options", ")", "{", "var", "regen", "=", "regenerate", "(", ")", ";", "var", "include", "=", "options", ".", "include", ";", "for", "(", "var", "i", "in", "include", ")", "{", "for", "(", "var", "j", "in", "include", "[", "i", "]", ".", "chars", ")", "{", "// There should always be a 0th-index element", "if", "(", "include", "[", "i", "]", ".", "chars", "[", "j", "]", "[", "0", "]", "===", "undefined", ")", "{", "continue", ";", "}", "regen", "=", "addCharacters", "(", "regen", ",", "include", "[", "i", "]", ".", "chars", "[", "j", "]", ")", ";", "}", "}", "removeCharacters", "(", "regen", ",", "options", ".", "exclude", ")", ";", "return", "regen", ".", "valueOf", "(", ")", ";", "}" ]
Retrieves a complete list of all characters from the given options @param {Object} options An Object containing: - include (optional) - An Object containing an Array of Objects, each of which contain: - chars - An Array containing an Array of 1 character per index: - 0 - A single character, hex character, or unicode character. This may be a single character to include, or the beginning of a range of characters to include - 1 - A single character, hex character, or unicode character. This must be the end of the range of the characters to include. - min (optional) - An Integer representing the minimum number of characters from the 'chars' set that *must* be included in the generated string - exclude (optional) - An Object containing an Array of Objects, each of which contain: - chars - An Array containing an Array of 1 character per index: - 0 - A single character, hex character, or unicode character. This may be a single character to exclude, or the beginning of a range of characters to exclude - 1 - A single character, hex character, or unicode character. This must be the end of the range of the characters to exclude. @returns {Array} an array of characters
[ "Retrieves", "a", "complete", "list", "of", "all", "characters", "from", "the", "given", "options" ]
b412707e45933cfc5da0428fa656d053883baadf
https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L198-L216
38,740
phillipsdata/unicode-passgen
index.js
getCharacterSets
function getCharacterSets(options) { var regen; var include = options.include; var sets = []; for (var i in include) { regen = regenerate(); for (var j in include[i].chars) { // There should always be a 0th-index element if (include[i].chars[j][0] === undefined) { continue; } // Add the characters from the set regen = addCharacters(regen, include[i].chars[j]); } // Remove the characters from the exclusion set regen = removeCharacters(regen, options.exclude); sets.push( { set: regen.valueOf(), min: include[i].min } ); } return sets; }
javascript
function getCharacterSets(options) { var regen; var include = options.include; var sets = []; for (var i in include) { regen = regenerate(); for (var j in include[i].chars) { // There should always be a 0th-index element if (include[i].chars[j][0] === undefined) { continue; } // Add the characters from the set regen = addCharacters(regen, include[i].chars[j]); } // Remove the characters from the exclusion set regen = removeCharacters(regen, options.exclude); sets.push( { set: regen.valueOf(), min: include[i].min } ); } return sets; }
[ "function", "getCharacterSets", "(", "options", ")", "{", "var", "regen", ";", "var", "include", "=", "options", ".", "include", ";", "var", "sets", "=", "[", "]", ";", "for", "(", "var", "i", "in", "include", ")", "{", "regen", "=", "regenerate", "(", ")", ";", "for", "(", "var", "j", "in", "include", "[", "i", "]", ".", "chars", ")", "{", "// There should always be a 0th-index element", "if", "(", "include", "[", "i", "]", ".", "chars", "[", "j", "]", "[", "0", "]", "===", "undefined", ")", "{", "continue", ";", "}", "// Add the characters from the set", "regen", "=", "addCharacters", "(", "regen", ",", "include", "[", "i", "]", ".", "chars", "[", "j", "]", ")", ";", "}", "// Remove the characters from the exclusion set", "regen", "=", "removeCharacters", "(", "regen", ",", "options", ".", "exclude", ")", ";", "sets", ".", "push", "(", "{", "set", ":", "regen", ".", "valueOf", "(", ")", ",", "min", ":", "include", "[", "i", "]", ".", "min", "}", ")", ";", "}", "return", "sets", ";", "}" ]
Retrieves a complete list of all character sets from the given options @param {Object} options An Object containing: - include (optional) - An Object containing an Array of Objects, each of which contain: - chars - An Array containing an Array of 1 character per index: - 0 - A single character, hex character, or unicode character. This may be a single character to include, or the beginning of a range of characters to include - 1 - A single character, hex character, or unicode character. This must be the end of the range of the characters to include. - min (optional) - An Integer representing the minimum number of characters from the 'chars' set that *must* be included in the generated string - exclude (optional) - An Object containing an Array of Objects, each of which contain: - chars - An Array containing an Array of 1 character per index: - 0 - A single character, hex character, or unicode character. This may be a single character to exclude, or the beginning of a range of characters to exclude - 1 - A single character, hex character, or unicode character. This must be the end of the range of the characters to exclude. @returns {Array} An Array of Objects, each of which include: - set - An Array of decimal characters - min - An Integer representing the minimum number of characters from the set that must be included in the generated string
[ "Retrieves", "a", "complete", "list", "of", "all", "character", "sets", "from", "the", "given", "options" ]
b412707e45933cfc5da0428fa656d053883baadf
https://github.com/phillipsdata/unicode-passgen/blob/b412707e45933cfc5da0428fa656d053883baadf/index.js#L244-L274
38,741
Baqend/jahcode
jahcode.js
function() { var objectDescriptor = arguments[arguments.length - 1]; var klass = objectDescriptor.constructor !== Object? objectDescriptor.constructor: function Class(toCast) { if (!(this instanceof klass)) { return klass.asInstance(toCast); } if (this.initialize) arguments.length ? this.initialize.apply(this, arguments) : this.initialize(); }; var proto = Object.createPrototypeChain(klass, this, Array.prototype.slice.call(arguments, 0, arguments.length - 1)); var names = Object.getOwnPropertyNames(objectDescriptor); for ( var i = 0; i < names.length; ++i) { var name = names[i]; var result = false; if (Object.properties.hasOwnProperty(name)) { result = Object.properties[name](proto, objectDescriptor, name); } if (!result) { var d = Object.getOwnPropertyDescriptor(objectDescriptor, name); if (d.value) { var val = d.value; if (val instanceof Function) { if (/this\.superCall/.test(val.toString())) { d.value = Object.createSuperCallWrapper(klass, name, val); } } else if (val && (val.hasOwnProperty('get') || val.hasOwnProperty('value'))) { d = val; } } Object.defineProperty(proto, name, d); } } if (klass.initialize) { klass.initialize(); } return klass; }
javascript
function() { var objectDescriptor = arguments[arguments.length - 1]; var klass = objectDescriptor.constructor !== Object? objectDescriptor.constructor: function Class(toCast) { if (!(this instanceof klass)) { return klass.asInstance(toCast); } if (this.initialize) arguments.length ? this.initialize.apply(this, arguments) : this.initialize(); }; var proto = Object.createPrototypeChain(klass, this, Array.prototype.slice.call(arguments, 0, arguments.length - 1)); var names = Object.getOwnPropertyNames(objectDescriptor); for ( var i = 0; i < names.length; ++i) { var name = names[i]; var result = false; if (Object.properties.hasOwnProperty(name)) { result = Object.properties[name](proto, objectDescriptor, name); } if (!result) { var d = Object.getOwnPropertyDescriptor(objectDescriptor, name); if (d.value) { var val = d.value; if (val instanceof Function) { if (/this\.superCall/.test(val.toString())) { d.value = Object.createSuperCallWrapper(klass, name, val); } } else if (val && (val.hasOwnProperty('get') || val.hasOwnProperty('value'))) { d = val; } } Object.defineProperty(proto, name, d); } } if (klass.initialize) { klass.initialize(); } return klass; }
[ "function", "(", ")", "{", "var", "objectDescriptor", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ";", "var", "klass", "=", "objectDescriptor", ".", "constructor", "!==", "Object", "?", "objectDescriptor", ".", "constructor", ":", "function", "Class", "(", "toCast", ")", "{", "if", "(", "!", "(", "this", "instanceof", "klass", ")", ")", "{", "return", "klass", ".", "asInstance", "(", "toCast", ")", ";", "}", "if", "(", "this", ".", "initialize", ")", "arguments", ".", "length", "?", "this", ".", "initialize", ".", "apply", "(", "this", ",", "arguments", ")", ":", "this", ".", "initialize", "(", ")", ";", "}", ";", "var", "proto", "=", "Object", ".", "createPrototypeChain", "(", "klass", ",", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "0", ",", "arguments", ".", "length", "-", "1", ")", ")", ";", "var", "names", "=", "Object", ".", "getOwnPropertyNames", "(", "objectDescriptor", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "++", "i", ")", "{", "var", "name", "=", "names", "[", "i", "]", ";", "var", "result", "=", "false", ";", "if", "(", "Object", ".", "properties", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "result", "=", "Object", ".", "properties", "[", "name", "]", "(", "proto", ",", "objectDescriptor", ",", "name", ")", ";", "}", "if", "(", "!", "result", ")", "{", "var", "d", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "objectDescriptor", ",", "name", ")", ";", "if", "(", "d", ".", "value", ")", "{", "var", "val", "=", "d", ".", "value", ";", "if", "(", "val", "instanceof", "Function", ")", "{", "if", "(", "/", "this\\.superCall", "/", ".", "test", "(", "val", ".", "toString", "(", ")", ")", ")", "{", "d", ".", "value", "=", "Object", ".", "createSuperCallWrapper", "(", "klass", ",", "name", ",", "val", ")", ";", "}", "}", "else", "if", "(", "val", "&&", "(", "val", ".", "hasOwnProperty", "(", "'get'", ")", "||", "val", ".", "hasOwnProperty", "(", "'value'", ")", ")", ")", "{", "d", "=", "val", ";", "}", "}", "Object", ".", "defineProperty", "(", "proto", ",", "name", ",", "d", ")", ";", "}", "}", "if", "(", "klass", ".", "initialize", ")", "{", "klass", ".", "initialize", "(", ")", ";", "}", "return", "klass", ";", "}" ]
Inherits this constructor and extends it by additional properties and methods. Optional there can be mixined additional Traits @param {Trait...} traits Additional traits to mixin @param {Object} classDescriptor The descriptor of the class properties and methods @returns {Function} The new created child class
[ "Inherits", "this", "constructor", "and", "extends", "it", "by", "additional", "properties", "and", "methods", ".", "Optional", "there", "can", "be", "mixined", "additional", "Traits" ]
92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402
https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L45-L89
38,742
Baqend/jahcode
jahcode.js
function(obj) { if (obj === null || obj === void 0) return false; return Object(obj) instanceof this || classOf(obj).linearizedTypes.lastIndexOf(this) != -1; }
javascript
function(obj) { if (obj === null || obj === void 0) return false; return Object(obj) instanceof this || classOf(obj).linearizedTypes.lastIndexOf(this) != -1; }
[ "function", "(", "obj", ")", "{", "if", "(", "obj", "===", "null", "||", "obj", "===", "void", "0", ")", "return", "false", ";", "return", "Object", "(", "obj", ")", "instanceof", "this", "||", "classOf", "(", "obj", ")", ".", "linearizedTypes", ".", "lastIndexOf", "(", "this", ")", "!=", "-", "1", ";", "}" ]
Indicates if the object is an instance of this class @param obj The object to check for @returns {boolean} <code>true</code> if the object is defined and
[ "Indicates", "if", "the", "object", "is", "an", "instance", "of", "this", "class" ]
92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402
https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L105-L110
38,743
Baqend/jahcode
jahcode.js
function(object) { if (object === null || object === void 0) return object; return Object.getPrototypeOf(Object(object)).constructor; }
javascript
function(object) { if (object === null || object === void 0) return object; return Object.getPrototypeOf(Object(object)).constructor; }
[ "function", "(", "object", ")", "{", "if", "(", "object", "===", "null", "||", "object", "===", "void", "0", ")", "return", "object", ";", "return", "Object", ".", "getPrototypeOf", "(", "Object", "(", "object", ")", ")", ".", "constructor", ";", "}" ]
Returns the constructor of the given object, works for objects and primitive types @param {*} object The constructor to return for @returns {Function} The constructor of the object @global
[ "Returns", "the", "constructor", "of", "the", "given", "object", "works", "for", "objects", "and", "primitive", "types" ]
92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402
https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L255-L260
38,744
Baqend/jahcode
jahcode.js
function(obj) { if (!obj.constructor.Bind) { try { var descr = {}; Bind.each(obj, function(name, method) { descr[name] = { get : function() { return this[name] = method.bind(this.self); }, set : function(val) { Object.defineProperty(this, name, { value : val }); }, configurable : true }; }); obj.constructor.Bind = Bind.Object.inherit(descr); } catch (e) { obj.constructor.Bind = Bind.Object.inherit({}); } } return new obj.constructor.Bind(obj); }
javascript
function(obj) { if (!obj.constructor.Bind) { try { var descr = {}; Bind.each(obj, function(name, method) { descr[name] = { get : function() { return this[name] = method.bind(this.self); }, set : function(val) { Object.defineProperty(this, name, { value : val }); }, configurable : true }; }); obj.constructor.Bind = Bind.Object.inherit(descr); } catch (e) { obj.constructor.Bind = Bind.Object.inherit({}); } } return new obj.constructor.Bind(obj); }
[ "function", "(", "obj", ")", "{", "if", "(", "!", "obj", ".", "constructor", ".", "Bind", ")", "{", "try", "{", "var", "descr", "=", "{", "}", ";", "Bind", ".", "each", "(", "obj", ",", "function", "(", "name", ",", "method", ")", "{", "descr", "[", "name", "]", "=", "{", "get", ":", "function", "(", ")", "{", "return", "this", "[", "name", "]", "=", "method", ".", "bind", "(", "this", ".", "self", ")", ";", "}", ",", "set", ":", "function", "(", "val", ")", "{", "Object", ".", "defineProperty", "(", "this", ",", "name", ",", "{", "value", ":", "val", "}", ")", ";", "}", ",", "configurable", ":", "true", "}", ";", "}", ")", ";", "obj", ".", "constructor", ".", "Bind", "=", "Bind", ".", "Object", ".", "inherit", "(", "descr", ")", ";", "}", "catch", "(", "e", ")", "{", "obj", ".", "constructor", ".", "Bind", "=", "Bind", ".", "Object", ".", "inherit", "(", "{", "}", ")", ";", "}", "}", "return", "new", "obj", ".", "constructor", ".", "Bind", "(", "obj", ")", ";", "}" ]
Creates a bind proxy for the given object Each method of the given object is reflected on the proxy and bound to the object context @param {*} obj The object which will be bound @returns {Bind} The bound proxy
[ "Creates", "a", "bind", "proxy", "for", "the", "given", "object", "Each", "method", "of", "the", "given", "object", "is", "reflected", "on", "the", "proxy", "and", "bound", "to", "the", "object", "context" ]
92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402
https://github.com/Baqend/jahcode/blob/92e1a4e5754ee8ec3ad1916f641d8a5c2f58c402/jahcode.js#L316-L340
38,745
juttle/juttle-viz
src/lib/layout/facet.js
function(svg, options) { var widthCfg; // the svg element to render charts to this._svg = svg.classed('facet-layout',true); this._attributes = options || {}; this._animDuration = commonOptionDefaults.duration; // outer margins this._margin = { top: 0, bottom: 50, left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25, right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75 }; // collection of facet panels created this._facetPanels = []; this._chartCount = 0; // the number of facetd charts to be displayed this._colCount = 0; // number of columns this._rowCount = 1; // number of rows this._colWidth = 0; // width of column this._chartHeight = 0; // the height of the chart // facet.width configuration needs to be interpreted // could be column width (FIXED) OR number of columns (FLEXING) widthCfg = this._interpretWidthConfig(options.facet.width); this._layoutMode = widthCfg.mode; if (widthCfg.mode === 'fixed') { this._colWidth = widthCfg.value; } else if (widthCfg.mode === 'flex') { this._colCount = widthCfg.value; } this._facetTitleHeight = (options.facet.fields.length * FACET_LABEL_HEIGHT) + FACET_LABEL_PADDING; // the total height of vertically stacked facet field labels this._facetHeight = this._getFacetHeight(); // the height of the facet (incl titles and chart) }
javascript
function(svg, options) { var widthCfg; // the svg element to render charts to this._svg = svg.classed('facet-layout',true); this._attributes = options || {}; this._animDuration = commonOptionDefaults.duration; // outer margins this._margin = { top: 0, bottom: 50, left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25, right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75 }; // collection of facet panels created this._facetPanels = []; this._chartCount = 0; // the number of facetd charts to be displayed this._colCount = 0; // number of columns this._rowCount = 1; // number of rows this._colWidth = 0; // width of column this._chartHeight = 0; // the height of the chart // facet.width configuration needs to be interpreted // could be column width (FIXED) OR number of columns (FLEXING) widthCfg = this._interpretWidthConfig(options.facet.width); this._layoutMode = widthCfg.mode; if (widthCfg.mode === 'fixed') { this._colWidth = widthCfg.value; } else if (widthCfg.mode === 'flex') { this._colCount = widthCfg.value; } this._facetTitleHeight = (options.facet.fields.length * FACET_LABEL_HEIGHT) + FACET_LABEL_PADDING; // the total height of vertically stacked facet field labels this._facetHeight = this._getFacetHeight(); // the height of the facet (incl titles and chart) }
[ "function", "(", "svg", ",", "options", ")", "{", "var", "widthCfg", ";", "// the svg element to render charts to", "this", ".", "_svg", "=", "svg", ".", "classed", "(", "'facet-layout'", ",", "true", ")", ";", "this", ".", "_attributes", "=", "options", "||", "{", "}", ";", "this", ".", "_animDuration", "=", "commonOptionDefaults", ".", "duration", ";", "// outer margins", "this", ".", "_margin", "=", "{", "top", ":", "0", ",", "bottom", ":", "50", ",", "left", ":", "this", ".", "_attributes", ".", "yScales", ".", "primary", ".", "displayOnAxis", "===", "'left'", "?", "75", ":", "25", ",", "right", ":", "this", ".", "_attributes", ".", "yScales", ".", "primary", ".", "displayOnAxis", "===", "'left'", "?", "25", ":", "75", "}", ";", "// collection of facet panels created", "this", ".", "_facetPanels", "=", "[", "]", ";", "this", ".", "_chartCount", "=", "0", ";", "// the number of facetd charts to be displayed", "this", ".", "_colCount", "=", "0", ";", "// number of columns", "this", ".", "_rowCount", "=", "1", ";", "// number of rows", "this", ".", "_colWidth", "=", "0", ";", "// width of column", "this", ".", "_chartHeight", "=", "0", ";", "// the height of the chart", "// facet.width configuration needs to be interpreted", "// could be column width (FIXED) OR number of columns (FLEXING)", "widthCfg", "=", "this", ".", "_interpretWidthConfig", "(", "options", ".", "facet", ".", "width", ")", ";", "this", ".", "_layoutMode", "=", "widthCfg", ".", "mode", ";", "if", "(", "widthCfg", ".", "mode", "===", "'fixed'", ")", "{", "this", ".", "_colWidth", "=", "widthCfg", ".", "value", ";", "}", "else", "if", "(", "widthCfg", ".", "mode", "===", "'flex'", ")", "{", "this", ".", "_colCount", "=", "widthCfg", ".", "value", ";", "}", "this", ".", "_facetTitleHeight", "=", "(", "options", ".", "facet", ".", "fields", ".", "length", "*", "FACET_LABEL_HEIGHT", ")", "+", "FACET_LABEL_PADDING", ";", "// the total height of vertically stacked facet field labels", "this", ".", "_facetHeight", "=", "this", ".", "_getFacetHeight", "(", ")", ";", "// the height of the facet (incl titles and chart)", "}" ]
Faceted Chart Layout @param {Object} svg the element @param {Object} options
[ "Faceted", "Chart", "Layout" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/layout/facet.js#L36-L76
38,746
gyselroth/balloon-node-sync
lib/delta/delta.js
applyGroupedDelta
function applyGroupedDelta(groupedDelta, callback) { var createdCandidates = []; logger.debug('Applying grouped delta', {category: 'sync-delta'}); async.eachSeries(groupedDelta, (node, cb) => { if(node.actions.create && utility.isExcludeFile(utility.getNameFromPath(node.actions.create.path))) { //do not process files which match exclude pattern. return cb(null); } syncDb.findByRemoteId(node.id, (err, oldLocalNode) => { if(err) return cbDeltaActions(err); if(node.actions.create && node.actions.delete) delete node.actions.delete; if(!oldLocalNode) { //node localy not found by remote id -> process later to avoid conflicts //nodes which don't have a create action can be ignored (deleted nodes not present localy) if(node.actions.create) createdCandidates.push(node); cb(null); } else { applyDeltaActions(node, oldLocalNode, (err, syncedNode) => { resolveConflicts(err, syncedNode, cb); }); } }); }, (err, results) => { if(err) return callback(err); async.eachSeries(createdCandidates, (node, cb) => { applyDeltaActions(node, undefined, (err, syncedNode) => { resolveConflicts(err, syncedNode, cb); }); }, callback); }); }
javascript
function applyGroupedDelta(groupedDelta, callback) { var createdCandidates = []; logger.debug('Applying grouped delta', {category: 'sync-delta'}); async.eachSeries(groupedDelta, (node, cb) => { if(node.actions.create && utility.isExcludeFile(utility.getNameFromPath(node.actions.create.path))) { //do not process files which match exclude pattern. return cb(null); } syncDb.findByRemoteId(node.id, (err, oldLocalNode) => { if(err) return cbDeltaActions(err); if(node.actions.create && node.actions.delete) delete node.actions.delete; if(!oldLocalNode) { //node localy not found by remote id -> process later to avoid conflicts //nodes which don't have a create action can be ignored (deleted nodes not present localy) if(node.actions.create) createdCandidates.push(node); cb(null); } else { applyDeltaActions(node, oldLocalNode, (err, syncedNode) => { resolveConflicts(err, syncedNode, cb); }); } }); }, (err, results) => { if(err) return callback(err); async.eachSeries(createdCandidates, (node, cb) => { applyDeltaActions(node, undefined, (err, syncedNode) => { resolveConflicts(err, syncedNode, cb); }); }, callback); }); }
[ "function", "applyGroupedDelta", "(", "groupedDelta", ",", "callback", ")", "{", "var", "createdCandidates", "=", "[", "]", ";", "logger", ".", "debug", "(", "'Applying grouped delta'", ",", "{", "category", ":", "'sync-delta'", "}", ")", ";", "async", ".", "eachSeries", "(", "groupedDelta", ",", "(", "node", ",", "cb", ")", "=>", "{", "if", "(", "node", ".", "actions", ".", "create", "&&", "utility", ".", "isExcludeFile", "(", "utility", ".", "getNameFromPath", "(", "node", ".", "actions", ".", "create", ".", "path", ")", ")", ")", "{", "//do not process files which match exclude pattern.", "return", "cb", "(", "null", ")", ";", "}", "syncDb", ".", "findByRemoteId", "(", "node", ".", "id", ",", "(", "err", ",", "oldLocalNode", ")", "=>", "{", "if", "(", "err", ")", "return", "cbDeltaActions", "(", "err", ")", ";", "if", "(", "node", ".", "actions", ".", "create", "&&", "node", ".", "actions", ".", "delete", ")", "delete", "node", ".", "actions", ".", "delete", ";", "if", "(", "!", "oldLocalNode", ")", "{", "//node localy not found by remote id -> process later to avoid conflicts", "//nodes which don't have a create action can be ignored (deleted nodes not present localy)", "if", "(", "node", ".", "actions", ".", "create", ")", "createdCandidates", ".", "push", "(", "node", ")", ";", "cb", "(", "null", ")", ";", "}", "else", "{", "applyDeltaActions", "(", "node", ",", "oldLocalNode", ",", "(", "err", ",", "syncedNode", ")", "=>", "{", "resolveConflicts", "(", "err", ",", "syncedNode", ",", "cb", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}", ",", "(", "err", ",", "results", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "async", ".", "eachSeries", "(", "createdCandidates", ",", "(", "node", ",", "cb", ")", "=>", "{", "applyDeltaActions", "(", "node", ",", "undefined", ",", "(", "err", ",", "syncedNode", ")", "=>", "{", "resolveConflicts", "(", "err", ",", "syncedNode", ",", "cb", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Applies grouped remote delta to database @see ./remote-delta.js groupDelta @param {Object} groupedDelta - grouped remote delta @param {Function} callback - callback function @returns {void} - no return value
[ "Applies", "grouped", "remote", "delta", "to", "database" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L19-L54
38,747
gyselroth/balloon-node-sync
lib/delta/delta.js
updateNode
function updateNode(node, callback) { syncDb.update(node._id, node, (err, result) => { if(err) return callback(err); callback(null, node); }); }
javascript
function updateNode(node, callback) { syncDb.update(node._id, node, (err, result) => { if(err) return callback(err); callback(null, node); }); }
[ "function", "updateNode", "(", "node", ",", "callback", ")", "{", "syncDb", ".", "update", "(", "node", ".", "_id", ",", "node", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "node", ")", ";", "}", ")", ";", "}" ]
Updates a node in the database @param {Object} node - database node to update @param {Function} callback - callback function @returns {void} - no return value
[ "Updates", "a", "node", "in", "the", "database" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L63-L69
38,748
gyselroth/balloon-node-sync
lib/delta/delta.js
resolveConflicts
function resolveConflicts(err, syncedNode, callback) { if(err) return callback(err); if(!syncedNode) return callback(null); async.series([ (cb) => { if(syncedNode.directory === true) { resolveDirectoryConflicts(syncedNode, cb); } else { resolveFileConflicts(syncedNode, cb); } }, (cb) => { findLocalConflict(syncedNode, cb); } ], (err, res) => { if(err) return callback(err); callback(null); }); }
javascript
function resolveConflicts(err, syncedNode, callback) { if(err) return callback(err); if(!syncedNode) return callback(null); async.series([ (cb) => { if(syncedNode.directory === true) { resolveDirectoryConflicts(syncedNode, cb); } else { resolveFileConflicts(syncedNode, cb); } }, (cb) => { findLocalConflict(syncedNode, cb); } ], (err, res) => { if(err) return callback(err); callback(null); }); }
[ "function", "resolveConflicts", "(", "err", ",", "syncedNode", ",", "callback", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "if", "(", "!", "syncedNode", ")", "return", "callback", "(", "null", ")", ";", "async", ".", "series", "(", "[", "(", "cb", ")", "=>", "{", "if", "(", "syncedNode", ".", "directory", "===", "true", ")", "{", "resolveDirectoryConflicts", "(", "syncedNode", ",", "cb", ")", ";", "}", "else", "{", "resolveFileConflicts", "(", "syncedNode", ",", "cb", ")", ";", "}", "}", ",", "(", "cb", ")", "=>", "{", "findLocalConflict", "(", "syncedNode", ",", "cb", ")", ";", "}", "]", ",", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
Resolves conflicts after remote delta actions have been applied @param {Object|null} err - error object @param {Object} snycedNode - node with applied actions from database @param {Function} callback - callback function @returns {void} - no return value
[ "Resolves", "conflicts", "after", "remote", "delta", "actions", "have", "been", "applied" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L232-L252
38,749
gyselroth/balloon-node-sync
lib/delta/delta.js
resolveDirectoryConflicts
function resolveDirectoryConflicts(node, callback) { var rActions = node.remoteActions; var lActions = node.localActions; if(rActions && lActions) { if(rActions.create && lActions.create) { //on both sides created, we just need to add remoteId and remoteParent node.remoteId = rActions.create.remoteId; node.remoteParent = rActions.create.remoteParent; delete node.remoteActions; delete node.localActions; } //both sides renamed, remote wins if(rActions.rename && lActions.rename) delete lActions.rename; //both sides moved, remote wins if(rActions.move && lActions.move) delete lActions.move; //if remotely created and localy deleted node should be created localy if(rActions.create && lActions.delete) delete lActions.delete; //if localy created and remotely deleted node should be created remotely if(rActions.delete && lActions.create) delete rActions.delete; return syncDb.update(node._id, node, (err, updatedNode) => { return callback(null); }); } return callback(null); }
javascript
function resolveDirectoryConflicts(node, callback) { var rActions = node.remoteActions; var lActions = node.localActions; if(rActions && lActions) { if(rActions.create && lActions.create) { //on both sides created, we just need to add remoteId and remoteParent node.remoteId = rActions.create.remoteId; node.remoteParent = rActions.create.remoteParent; delete node.remoteActions; delete node.localActions; } //both sides renamed, remote wins if(rActions.rename && lActions.rename) delete lActions.rename; //both sides moved, remote wins if(rActions.move && lActions.move) delete lActions.move; //if remotely created and localy deleted node should be created localy if(rActions.create && lActions.delete) delete lActions.delete; //if localy created and remotely deleted node should be created remotely if(rActions.delete && lActions.create) delete rActions.delete; return syncDb.update(node._id, node, (err, updatedNode) => { return callback(null); }); } return callback(null); }
[ "function", "resolveDirectoryConflicts", "(", "node", ",", "callback", ")", "{", "var", "rActions", "=", "node", ".", "remoteActions", ";", "var", "lActions", "=", "node", ".", "localActions", ";", "if", "(", "rActions", "&&", "lActions", ")", "{", "if", "(", "rActions", ".", "create", "&&", "lActions", ".", "create", ")", "{", "//on both sides created, we just need to add remoteId and remoteParent", "node", ".", "remoteId", "=", "rActions", ".", "create", ".", "remoteId", ";", "node", ".", "remoteParent", "=", "rActions", ".", "create", ".", "remoteParent", ";", "delete", "node", ".", "remoteActions", ";", "delete", "node", ".", "localActions", ";", "}", "//both sides renamed, remote wins", "if", "(", "rActions", ".", "rename", "&&", "lActions", ".", "rename", ")", "delete", "lActions", ".", "rename", ";", "//both sides moved, remote wins", "if", "(", "rActions", ".", "move", "&&", "lActions", ".", "move", ")", "delete", "lActions", ".", "move", ";", "//if remotely created and localy deleted node should be created localy", "if", "(", "rActions", ".", "create", "&&", "lActions", ".", "delete", ")", "delete", "lActions", ".", "delete", ";", "//if localy created and remotely deleted node should be created remotely", "if", "(", "rActions", ".", "delete", "&&", "lActions", ".", "create", ")", "delete", "rActions", ".", "delete", ";", "return", "syncDb", ".", "update", "(", "node", ".", "_id", ",", "node", ",", "(", "err", ",", "updatedNode", ")", "=>", "{", "return", "callback", "(", "null", ")", ";", "}", ")", ";", "}", "return", "callback", "(", "null", ")", ";", "}" ]
Resolves conflicts for a directory node @param {Object} node - node with applied actions from database @param {Function} callback - callback function @returns {void} - no return value
[ "Resolves", "conflicts", "for", "a", "directory", "node" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L261-L293
38,750
gyselroth/balloon-node-sync
lib/delta/delta.js
resolveFileConflicts
function resolveFileConflicts(node, callback) { var rActions = node.remoteActions; var lActions = node.localActions; if(!rActions || !lActions) { //only one side changed, no conflicts return callback(null); } if(rActions.create && lActions.create) { //on both sides created or updated var currentLocalPath = utility.joinPath(node.parent, node.name); var localHash, stat; try { localHash = fsWrap.md5FileSync(currentLocalPath); stat = fsWrap.lstatSync(currentLocalPath); } catch(e) { logger.warning('resolveFileConflicts failed', {category: 'sync-delta', node, err: e}); var err = new BlnDeltaError(e.message); throw err; } if(rActions.create.hash && rActions.create.hash === localHash && rActions.create.size === stat.size) { delete node.remoteActions; delete node.localActions; node.hash = localHash; node.version = rActions.create.version; node.size = stat.size; node.mtime = stat.mtime; node.ctime = stat.ctime; node.remoteId = rActions.create.remoteId; node.remoteParent = rActions.create.remoteParent; return syncDb.update(node._id, node, callback); } else if(!rActions.delete) { //if remote path changed upload local version as new version on old path var remoteNode; return async.series([ (cb) => { //create remote localy var name = rActions.rename ? rActions.rename.remoteName : node.name; var parent = rActions.move ? rActions.move.parent : node.parent; var remoteParent = rActions.move ? rActions.move.remoteParent : rActions.create.remoteParent; var newNode = { name: name, parent: parent, directory: node.directory, remoteId: node.remoteId, remoteParent: remoteParent, remoteActions: {create: rActions.create} } syncDb.create(newNode, (err, createdNode) => { remoteNode = createdNode; cb(err); }); }, (cb) => { delete node.remoteActions; delete node.remoteParent; delete node.remoteId; delete node.hash; delete node.version; syncDb.update(node._id, node, cb); }, (cb) => { //as a new node has been created conflict resolution has to be executed for the new node resolveConflicts(null, remoteNode, cb); } ], callback); } } if(rActions.delete && lActions.delete) { //on both sides deleted, just remove it from db return syncDb.delete(node._id, (err) => { return callback(null); }); } return callback(null); }
javascript
function resolveFileConflicts(node, callback) { var rActions = node.remoteActions; var lActions = node.localActions; if(!rActions || !lActions) { //only one side changed, no conflicts return callback(null); } if(rActions.create && lActions.create) { //on both sides created or updated var currentLocalPath = utility.joinPath(node.parent, node.name); var localHash, stat; try { localHash = fsWrap.md5FileSync(currentLocalPath); stat = fsWrap.lstatSync(currentLocalPath); } catch(e) { logger.warning('resolveFileConflicts failed', {category: 'sync-delta', node, err: e}); var err = new BlnDeltaError(e.message); throw err; } if(rActions.create.hash && rActions.create.hash === localHash && rActions.create.size === stat.size) { delete node.remoteActions; delete node.localActions; node.hash = localHash; node.version = rActions.create.version; node.size = stat.size; node.mtime = stat.mtime; node.ctime = stat.ctime; node.remoteId = rActions.create.remoteId; node.remoteParent = rActions.create.remoteParent; return syncDb.update(node._id, node, callback); } else if(!rActions.delete) { //if remote path changed upload local version as new version on old path var remoteNode; return async.series([ (cb) => { //create remote localy var name = rActions.rename ? rActions.rename.remoteName : node.name; var parent = rActions.move ? rActions.move.parent : node.parent; var remoteParent = rActions.move ? rActions.move.remoteParent : rActions.create.remoteParent; var newNode = { name: name, parent: parent, directory: node.directory, remoteId: node.remoteId, remoteParent: remoteParent, remoteActions: {create: rActions.create} } syncDb.create(newNode, (err, createdNode) => { remoteNode = createdNode; cb(err); }); }, (cb) => { delete node.remoteActions; delete node.remoteParent; delete node.remoteId; delete node.hash; delete node.version; syncDb.update(node._id, node, cb); }, (cb) => { //as a new node has been created conflict resolution has to be executed for the new node resolveConflicts(null, remoteNode, cb); } ], callback); } } if(rActions.delete && lActions.delete) { //on both sides deleted, just remove it from db return syncDb.delete(node._id, (err) => { return callback(null); }); } return callback(null); }
[ "function", "resolveFileConflicts", "(", "node", ",", "callback", ")", "{", "var", "rActions", "=", "node", ".", "remoteActions", ";", "var", "lActions", "=", "node", ".", "localActions", ";", "if", "(", "!", "rActions", "||", "!", "lActions", ")", "{", "//only one side changed, no conflicts", "return", "callback", "(", "null", ")", ";", "}", "if", "(", "rActions", ".", "create", "&&", "lActions", ".", "create", ")", "{", "//on both sides created or updated", "var", "currentLocalPath", "=", "utility", ".", "joinPath", "(", "node", ".", "parent", ",", "node", ".", "name", ")", ";", "var", "localHash", ",", "stat", ";", "try", "{", "localHash", "=", "fsWrap", ".", "md5FileSync", "(", "currentLocalPath", ")", ";", "stat", "=", "fsWrap", ".", "lstatSync", "(", "currentLocalPath", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "warning", "(", "'resolveFileConflicts failed'", ",", "{", "category", ":", "'sync-delta'", ",", "node", ",", "err", ":", "e", "}", ")", ";", "var", "err", "=", "new", "BlnDeltaError", "(", "e", ".", "message", ")", ";", "throw", "err", ";", "}", "if", "(", "rActions", ".", "create", ".", "hash", "&&", "rActions", ".", "create", ".", "hash", "===", "localHash", "&&", "rActions", ".", "create", ".", "size", "===", "stat", ".", "size", ")", "{", "delete", "node", ".", "remoteActions", ";", "delete", "node", ".", "localActions", ";", "node", ".", "hash", "=", "localHash", ";", "node", ".", "version", "=", "rActions", ".", "create", ".", "version", ";", "node", ".", "size", "=", "stat", ".", "size", ";", "node", ".", "mtime", "=", "stat", ".", "mtime", ";", "node", ".", "ctime", "=", "stat", ".", "ctime", ";", "node", ".", "remoteId", "=", "rActions", ".", "create", ".", "remoteId", ";", "node", ".", "remoteParent", "=", "rActions", ".", "create", ".", "remoteParent", ";", "return", "syncDb", ".", "update", "(", "node", ".", "_id", ",", "node", ",", "callback", ")", ";", "}", "else", "if", "(", "!", "rActions", ".", "delete", ")", "{", "//if remote path changed upload local version as new version on old path", "var", "remoteNode", ";", "return", "async", ".", "series", "(", "[", "(", "cb", ")", "=>", "{", "//create remote localy", "var", "name", "=", "rActions", ".", "rename", "?", "rActions", ".", "rename", ".", "remoteName", ":", "node", ".", "name", ";", "var", "parent", "=", "rActions", ".", "move", "?", "rActions", ".", "move", ".", "parent", ":", "node", ".", "parent", ";", "var", "remoteParent", "=", "rActions", ".", "move", "?", "rActions", ".", "move", ".", "remoteParent", ":", "rActions", ".", "create", ".", "remoteParent", ";", "var", "newNode", "=", "{", "name", ":", "name", ",", "parent", ":", "parent", ",", "directory", ":", "node", ".", "directory", ",", "remoteId", ":", "node", ".", "remoteId", ",", "remoteParent", ":", "remoteParent", ",", "remoteActions", ":", "{", "create", ":", "rActions", ".", "create", "}", "}", "syncDb", ".", "create", "(", "newNode", ",", "(", "err", ",", "createdNode", ")", "=>", "{", "remoteNode", "=", "createdNode", ";", "cb", "(", "err", ")", ";", "}", ")", ";", "}", ",", "(", "cb", ")", "=>", "{", "delete", "node", ".", "remoteActions", ";", "delete", "node", ".", "remoteParent", ";", "delete", "node", ".", "remoteId", ";", "delete", "node", ".", "hash", ";", "delete", "node", ".", "version", ";", "syncDb", ".", "update", "(", "node", ".", "_id", ",", "node", ",", "cb", ")", ";", "}", ",", "(", "cb", ")", "=>", "{", "//as a new node has been created conflict resolution has to be executed for the new node", "resolveConflicts", "(", "null", ",", "remoteNode", ",", "cb", ")", ";", "}", "]", ",", "callback", ")", ";", "}", "}", "if", "(", "rActions", ".", "delete", "&&", "lActions", ".", "delete", ")", "{", "//on both sides deleted, just remove it from db", "return", "syncDb", ".", "delete", "(", "node", ".", "_id", ",", "(", "err", ")", "=>", "{", "return", "callback", "(", "null", ")", ";", "}", ")", ";", "}", "return", "callback", "(", "null", ")", ";", "}" ]
Resolves conflicts for a file node @param {Object} node - node with applied actions from database @param {Function} callback - callback function @returns {void} - no return value
[ "Resolves", "conflicts", "for", "a", "file", "node" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L302-L390
38,751
gyselroth/balloon-node-sync
lib/delta/delta.js
renameConflictNode
function renameConflictNode(newParent, oldPath, name, node, conflictingNode, callback) { var newLocalName = utility.renameConflictNode(newParent, name); try { fsWrap.renameSync(oldPath, utility.joinPath(newParent, newLocalName)); } catch(err) { return renameRemoteNode(node, name, callback); } conflictingNode.name = newLocalName; conflictingNode.localActions = conflictingNode.localActions || {}; if(!conflictingNode.localActions.create && !conflictingNode.localActions.rename) { //rename the node if not localy created or localy renamed (always keep original local rename actions) conflictingNode.localActions.rename = {immediate: false, actionInitialized: new Date(), oldName: name}; } return syncDb.update(conflictingNode._id, conflictingNode, callback); }
javascript
function renameConflictNode(newParent, oldPath, name, node, conflictingNode, callback) { var newLocalName = utility.renameConflictNode(newParent, name); try { fsWrap.renameSync(oldPath, utility.joinPath(newParent, newLocalName)); } catch(err) { return renameRemoteNode(node, name, callback); } conflictingNode.name = newLocalName; conflictingNode.localActions = conflictingNode.localActions || {}; if(!conflictingNode.localActions.create && !conflictingNode.localActions.rename) { //rename the node if not localy created or localy renamed (always keep original local rename actions) conflictingNode.localActions.rename = {immediate: false, actionInitialized: new Date(), oldName: name}; } return syncDb.update(conflictingNode._id, conflictingNode, callback); }
[ "function", "renameConflictNode", "(", "newParent", ",", "oldPath", ",", "name", ",", "node", ",", "conflictingNode", ",", "callback", ")", "{", "var", "newLocalName", "=", "utility", ".", "renameConflictNode", "(", "newParent", ",", "name", ")", ";", "try", "{", "fsWrap", ".", "renameSync", "(", "oldPath", ",", "utility", ".", "joinPath", "(", "newParent", ",", "newLocalName", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "renameRemoteNode", "(", "node", ",", "name", ",", "callback", ")", ";", "}", "conflictingNode", ".", "name", "=", "newLocalName", ";", "conflictingNode", ".", "localActions", "=", "conflictingNode", ".", "localActions", "||", "{", "}", ";", "if", "(", "!", "conflictingNode", ".", "localActions", ".", "create", "&&", "!", "conflictingNode", ".", "localActions", ".", "rename", ")", "{", "//rename the node if not localy created or localy renamed (always keep original local rename actions)", "conflictingNode", ".", "localActions", ".", "rename", "=", "{", "immediate", ":", "false", ",", "actionInitialized", ":", "new", "Date", "(", ")", ",", "oldName", ":", "name", "}", ";", "}", "return", "syncDb", ".", "update", "(", "conflictingNode", ".", "_id", ",", "conflictingNode", ",", "callback", ")", ";", "}" ]
renames a conflict file @param {string} newParent - new parent of the file @param {Object} oldPath - old path of the file @param {string} name - current name of the file @param {Object} node - node A from database @param {Object} conflictingNode - node B conflicting with node A from database @param {Function} callback - callback function @returns {void} - no return value
[ "renames", "a", "conflict", "file" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L465-L484
38,752
gyselroth/balloon-node-sync
lib/delta/delta.js
renameRemoteNode
function renameRemoteNode(node, name, callback) { var rActions = node.remoteActions || {}; var newLocalName = utility.renameConflictNodeRemote(name); var oldLocalName = node.name; var newLocalPath = utility.joinPath(node.parent, newLocalName); var oldLocalPath = utility.joinPath(node.parent, oldLocalName); if(!rActions.create && fsWrap.existsSync(oldLocalPath)) { try { fsWrap.renameSync(oldLocalPath, newLocalPath); } catch(err) { logger.warning('rename local node failed', {category: 'sync-delta', oldLocalPath, newLocalPath, err}) throw new BlnDeltaError(err.message); return; } } node.name = newLocalName; node.localActions = node.localActions || {}; var remoteId = node.remoteId || node.remoteActions.create.remoteId; return blnApi.renameNode({remoteId, name: node.name}, (err) => { if(err) { logger.warning('rename remote node failed', {category: 'sync-delta', params: {remoteId, name: node.name}, err}); throw new BlnDeltaError(err.message); return; } if(rActions.rename) { delete node.remoteActions.rename; } syncDb.update(node._id, node, callback); }); }
javascript
function renameRemoteNode(node, name, callback) { var rActions = node.remoteActions || {}; var newLocalName = utility.renameConflictNodeRemote(name); var oldLocalName = node.name; var newLocalPath = utility.joinPath(node.parent, newLocalName); var oldLocalPath = utility.joinPath(node.parent, oldLocalName); if(!rActions.create && fsWrap.existsSync(oldLocalPath)) { try { fsWrap.renameSync(oldLocalPath, newLocalPath); } catch(err) { logger.warning('rename local node failed', {category: 'sync-delta', oldLocalPath, newLocalPath, err}) throw new BlnDeltaError(err.message); return; } } node.name = newLocalName; node.localActions = node.localActions || {}; var remoteId = node.remoteId || node.remoteActions.create.remoteId; return blnApi.renameNode({remoteId, name: node.name}, (err) => { if(err) { logger.warning('rename remote node failed', {category: 'sync-delta', params: {remoteId, name: node.name}, err}); throw new BlnDeltaError(err.message); return; } if(rActions.rename) { delete node.remoteActions.rename; } syncDb.update(node._id, node, callback); }); }
[ "function", "renameRemoteNode", "(", "node", ",", "name", ",", "callback", ")", "{", "var", "rActions", "=", "node", ".", "remoteActions", "||", "{", "}", ";", "var", "newLocalName", "=", "utility", ".", "renameConflictNodeRemote", "(", "name", ")", ";", "var", "oldLocalName", "=", "node", ".", "name", ";", "var", "newLocalPath", "=", "utility", ".", "joinPath", "(", "node", ".", "parent", ",", "newLocalName", ")", ";", "var", "oldLocalPath", "=", "utility", ".", "joinPath", "(", "node", ".", "parent", ",", "oldLocalName", ")", ";", "if", "(", "!", "rActions", ".", "create", "&&", "fsWrap", ".", "existsSync", "(", "oldLocalPath", ")", ")", "{", "try", "{", "fsWrap", ".", "renameSync", "(", "oldLocalPath", ",", "newLocalPath", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "warning", "(", "'rename local node failed'", ",", "{", "category", ":", "'sync-delta'", ",", "oldLocalPath", ",", "newLocalPath", ",", "err", "}", ")", "throw", "new", "BlnDeltaError", "(", "err", ".", "message", ")", ";", "return", ";", "}", "}", "node", ".", "name", "=", "newLocalName", ";", "node", ".", "localActions", "=", "node", ".", "localActions", "||", "{", "}", ";", "var", "remoteId", "=", "node", ".", "remoteId", "||", "node", ".", "remoteActions", ".", "create", ".", "remoteId", ";", "return", "blnApi", ".", "renameNode", "(", "{", "remoteId", ",", "name", ":", "node", ".", "name", "}", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "logger", ".", "warning", "(", "'rename remote node failed'", ",", "{", "category", ":", "'sync-delta'", ",", "params", ":", "{", "remoteId", ",", "name", ":", "node", ".", "name", "}", ",", "err", "}", ")", ";", "throw", "new", "BlnDeltaError", "(", "err", ".", "message", ")", ";", "return", ";", "}", "if", "(", "rActions", ".", "rename", ")", "{", "delete", "node", ".", "remoteActions", ".", "rename", ";", "}", "syncDb", ".", "update", "(", "node", ".", "_id", ",", "node", ",", "callback", ")", ";", "}", ")", ";", "}" ]
renames a conflicting node remotely @param {Object} node - node A from database @param {string} name - current name of the file @param {Function} callback - callback function @returns {void} - no return value
[ "renames", "a", "conflicting", "node", "remotely" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L494-L533
38,753
gyselroth/balloon-node-sync
lib/delta/delta.js
function(dirPath, lastCursor, callback) { async.parallel([ (cb) => { localDelta.getDelta(dirPath, cb); }, (cb) => { remoteDelta.getDelta(lastCursor, cb); } ], (err, results) => { logger.info('getDelta ended', {category: 'sync-delta'}); if(err) return callback(err); var currentRemoteCursor = results[1]; applyGroupedDelta(remoteDelta.getGroupedDelta(), (err) => { if(err) return callback(err); callback(null, currentRemoteCursor); }); }); }
javascript
function(dirPath, lastCursor, callback) { async.parallel([ (cb) => { localDelta.getDelta(dirPath, cb); }, (cb) => { remoteDelta.getDelta(lastCursor, cb); } ], (err, results) => { logger.info('getDelta ended', {category: 'sync-delta'}); if(err) return callback(err); var currentRemoteCursor = results[1]; applyGroupedDelta(remoteDelta.getGroupedDelta(), (err) => { if(err) return callback(err); callback(null, currentRemoteCursor); }); }); }
[ "function", "(", "dirPath", ",", "lastCursor", ",", "callback", ")", "{", "async", ".", "parallel", "(", "[", "(", "cb", ")", "=>", "{", "localDelta", ".", "getDelta", "(", "dirPath", ",", "cb", ")", ";", "}", ",", "(", "cb", ")", "=>", "{", "remoteDelta", ".", "getDelta", "(", "lastCursor", ",", "cb", ")", ";", "}", "]", ",", "(", "err", ",", "results", ")", "=>", "{", "logger", ".", "info", "(", "'getDelta ended'", ",", "{", "category", ":", "'sync-delta'", "}", ")", ";", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "currentRemoteCursor", "=", "results", "[", "1", "]", ";", "applyGroupedDelta", "(", "remoteDelta", ".", "getGroupedDelta", "(", ")", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "currentRemoteCursor", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
gets the remote and local delta and merges it @param {string} dirPath - path to the root directory @param {string} lastCursor - last cursor or undefined if cursor has been reset @param {Function} callback - callback function @returns {void} - no return value
[ "gets", "the", "remote", "and", "local", "delta", "and", "merges", "it" ]
0ae8d3a6c505e33fe8af220a95fee84aa54e386b
https://github.com/gyselroth/balloon-node-sync/blob/0ae8d3a6c505e33fe8af220a95fee84aa54e386b/lib/delta/delta.js#L546-L567
38,754
rvagg/ghrepos
ghrepos.js
function (auth, org, repo, ref, options, callback) { if (typeof options == 'function') { callback = options options = {} } // a valid ref but we're not using this format ref = ref.replace(/^refs\//, '') var url = refsBaseUrl(org, repo, type) + '/' + ref ghutils.ghget(auth, url, options, callback) }
javascript
function (auth, org, repo, ref, options, callback) { if (typeof options == 'function') { callback = options options = {} } // a valid ref but we're not using this format ref = ref.replace(/^refs\//, '') var url = refsBaseUrl(org, repo, type) + '/' + ref ghutils.ghget(auth, url, options, callback) }
[ "function", "(", "auth", ",", "org", ",", "repo", ",", "ref", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "callback", "=", "options", "options", "=", "{", "}", "}", "// a valid ref but we're not using this format", "ref", "=", "ref", ".", "replace", "(", "/", "^refs\\/", "/", ",", "''", ")", "var", "url", "=", "refsBaseUrl", "(", "org", ",", "repo", ",", "type", ")", "+", "'/'", "+", "ref", "ghutils", ".", "ghget", "(", "auth", ",", "url", ",", "options", ",", "callback", ")", "}" ]
no getTag API
[ "no", "getTag", "API" ]
e5ff8fded0fb421d4cc0610c1f84d5cc242c0dc0
https://github.com/rvagg/ghrepos/blob/e5ff8fded0fb421d4cc0610c1f84d5cc242c0dc0/ghrepos.js#L59-L70
38,755
tgroshon/street.js
src/street.js
getOldManifest
async function getOldManifest () { try { var data = await getFile('.manifest.json.gz') } catch (err) { if (err.code === 'NoSuchKey') return {} else throw err } var unzippedBody = zlib.gunzipSync(data.Body) return JSON.parse(unzippedBody) }
javascript
async function getOldManifest () { try { var data = await getFile('.manifest.json.gz') } catch (err) { if (err.code === 'NoSuchKey') return {} else throw err } var unzippedBody = zlib.gunzipSync(data.Body) return JSON.parse(unzippedBody) }
[ "async", "function", "getOldManifest", "(", ")", "{", "try", "{", "var", "data", "=", "await", "getFile", "(", "'.manifest.json.gz'", ")", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'NoSuchKey'", ")", "return", "{", "}", "else", "throw", "err", "}", "var", "unzippedBody", "=", "zlib", ".", "gunzipSync", "(", "data", ".", "Body", ")", "return", "JSON", ".", "parse", "(", "unzippedBody", ")", "}" ]
Download, unzip, and parse the manifest from remote storage
[ "Download", "unzip", "and", "parse", "the", "manifest", "from", "remote", "storage" ]
8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19
https://github.com/tgroshon/street.js/blob/8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19/src/street.js#L55-L64
38,756
tgroshon/street.js
src/street.js
upload
function upload (uploadables) { var promises = uploadables.map((uploadable) => putUploadable(uploadable)) return Promise.all(promises) }
javascript
function upload (uploadables) { var promises = uploadables.map((uploadable) => putUploadable(uploadable)) return Promise.all(promises) }
[ "function", "upload", "(", "uploadables", ")", "{", "var", "promises", "=", "uploadables", ".", "map", "(", "(", "uploadable", ")", "=>", "putUploadable", "(", "uploadable", ")", ")", "return", "Promise", ".", "all", "(", "promises", ")", "}" ]
Upload files to storage destination @param Array<Uploadable>: List of uploadables to upload @param Object: Street option object @return Promise: A promise chain of all upload actions
[ "Upload", "files", "to", "storage", "destination" ]
8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19
https://github.com/tgroshon/street.js/blob/8d68d4bc6dd2d6a75a698ac7f361cf3fa1a16c19/src/street.js#L83-L86
38,757
suguru/cql-client
lib/client.js
toCassandraValues
function toCassandraValues(metadata, values) { if (values === null || values === undefined) { return null; } var specs = metadata.columnSpecs; var list = []; for (var i = 0; i < specs.length; i++) { var value = values[i]; if (value === null || value === undefined) { list.push(null); } else { var spec = specs[i]; var type = types.fromType(spec.type); list.push(type.serialize(value)); } } return list; }
javascript
function toCassandraValues(metadata, values) { if (values === null || values === undefined) { return null; } var specs = metadata.columnSpecs; var list = []; for (var i = 0; i < specs.length; i++) { var value = values[i]; if (value === null || value === undefined) { list.push(null); } else { var spec = specs[i]; var type = types.fromType(spec.type); list.push(type.serialize(value)); } } return list; }
[ "function", "toCassandraValues", "(", "metadata", ",", "values", ")", "{", "if", "(", "values", "===", "null", "||", "values", "===", "undefined", ")", "{", "return", "null", ";", "}", "var", "specs", "=", "metadata", ".", "columnSpecs", ";", "var", "list", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "specs", ".", "length", ";", "i", "++", ")", "{", "var", "value", "=", "values", "[", "i", "]", ";", "if", "(", "value", "===", "null", "||", "value", "===", "undefined", ")", "{", "list", ".", "push", "(", "null", ")", ";", "}", "else", "{", "var", "spec", "=", "specs", "[", "i", "]", ";", "var", "type", "=", "types", ".", "fromType", "(", "spec", ".", "type", ")", ";", "list", ".", "push", "(", "type", ".", "serialize", "(", "value", ")", ")", ";", "}", "}", "return", "list", ";", "}" ]
Convert values to binaries to be set for cassandra @param {object} metadata - metadata @param {array} values - value list
[ "Convert", "values", "to", "binaries", "to", "be", "set", "for", "cassandra" ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/client.js#L424-L441
38,758
benbowes/singleline
index.js
singleline
function singleline(multiLineString, noSpaces) { const delimiter = noSpaces ? '' : ' '; return multiLineString.replace(/\s\s+/g, delimiter).trim(); }
javascript
function singleline(multiLineString, noSpaces) { const delimiter = noSpaces ? '' : ' '; return multiLineString.replace(/\s\s+/g, delimiter).trim(); }
[ "function", "singleline", "(", "multiLineString", ",", "noSpaces", ")", "{", "const", "delimiter", "=", "noSpaces", "?", "''", ":", "' '", ";", "return", "multiLineString", ".", "replace", "(", "/", "\\s\\s+", "/", "g", ",", "delimiter", ")", ".", "trim", "(", ")", ";", "}" ]
Turns a multiline string into a single line string, optionallly with or without spaces. @param {String} multiLineString - If using an es6 template string be sure to tab out. @param {Boolean} noSpaces - If you'd like there to be no spaces between say your HTML add this boolean. @returns {String}
[ "Turns", "a", "multiline", "string", "into", "a", "single", "line", "string", "optionallly", "with", "or", "without", "spaces", "." ]
ce5c4df7972584b9345b34fa4f30e01918c2dc51
https://github.com/benbowes/singleline/blob/ce5c4df7972584b9345b34fa4f30e01918c2dc51/index.js#L8-L11
38,759
socialtables/geometry-utils
lib/split-arc.js
closestButNotGreaterThan
function closestButNotGreaterThan(numbers, maxNumber) { var positiveNumbers = numbers.map(function(number){ return Math.abs(number); }); var positiveMaxNumber = Math.abs(maxNumber); var winner = positiveMaxNumber; var winningDifference = positiveMaxNumber; for (var i=0; i < positiveNumbers.length; i++) { var lessThanMax = positiveNumbers[i] <= positiveMaxNumber; var closerToMax = (positiveMaxNumber - positiveNumbers[i]) < winningDifference; if (lessThanMax && closerToMax) { winner = positiveNumbers[i]; winningDifference = positiveMaxNumber-positiveNumbers[i]; } } return winner; }
javascript
function closestButNotGreaterThan(numbers, maxNumber) { var positiveNumbers = numbers.map(function(number){ return Math.abs(number); }); var positiveMaxNumber = Math.abs(maxNumber); var winner = positiveMaxNumber; var winningDifference = positiveMaxNumber; for (var i=0; i < positiveNumbers.length; i++) { var lessThanMax = positiveNumbers[i] <= positiveMaxNumber; var closerToMax = (positiveMaxNumber - positiveNumbers[i]) < winningDifference; if (lessThanMax && closerToMax) { winner = positiveNumbers[i]; winningDifference = positiveMaxNumber-positiveNumbers[i]; } } return winner; }
[ "function", "closestButNotGreaterThan", "(", "numbers", ",", "maxNumber", ")", "{", "var", "positiveNumbers", "=", "numbers", ".", "map", "(", "function", "(", "number", ")", "{", "return", "Math", ".", "abs", "(", "number", ")", ";", "}", ")", ";", "var", "positiveMaxNumber", "=", "Math", ".", "abs", "(", "maxNumber", ")", ";", "var", "winner", "=", "positiveMaxNumber", ";", "var", "winningDifference", "=", "positiveMaxNumber", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "positiveNumbers", ".", "length", ";", "i", "++", ")", "{", "var", "lessThanMax", "=", "positiveNumbers", "[", "i", "]", "<=", "positiveMaxNumber", ";", "var", "closerToMax", "=", "(", "positiveMaxNumber", "-", "positiveNumbers", "[", "i", "]", ")", "<", "winningDifference", ";", "if", "(", "lessThanMax", "&&", "closerToMax", ")", "{", "winner", "=", "positiveNumbers", "[", "i", "]", ";", "winningDifference", "=", "positiveMaxNumber", "-", "positiveNumbers", "[", "i", "]", ";", "}", "}", "return", "winner", ";", "}" ]
Return number with closest absolute value to maxNumber without exceeding it
[ "Return", "number", "with", "closest", "absolute", "value", "to", "maxNumber", "without", "exceeding", "it" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/split-arc.js#L6-L24
38,760
socialtables/geometry-utils
lib/split-arc.js
closestToZero
function closestToZero(numbers, maxNumber) { //returns the index of value closest to 0 var positiveNumbers = numbers.map(function(number) { return Math.abs(number); }); var sortedPositiveNumbers = positiveNumbers.sort(function(a, b) { return (a - b); }); return sortedPositiveNumbers[0]; }
javascript
function closestToZero(numbers, maxNumber) { //returns the index of value closest to 0 var positiveNumbers = numbers.map(function(number) { return Math.abs(number); }); var sortedPositiveNumbers = positiveNumbers.sort(function(a, b) { return (a - b); }); return sortedPositiveNumbers[0]; }
[ "function", "closestToZero", "(", "numbers", ",", "maxNumber", ")", "{", "//returns the index of value closest to 0", "var", "positiveNumbers", "=", "numbers", ".", "map", "(", "function", "(", "number", ")", "{", "return", "Math", ".", "abs", "(", "number", ")", ";", "}", ")", ";", "var", "sortedPositiveNumbers", "=", "positiveNumbers", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "(", "a", "-", "b", ")", ";", "}", ")", ";", "return", "sortedPositiveNumbers", "[", "0", "]", ";", "}" ]
Return the number that's closest to zero
[ "Return", "the", "number", "that", "s", "closest", "to", "zero" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/split-arc.js#L27-L38
38,761
socialtables/geometry-utils
lib/split-arc.js
findArcHeight
function findArcHeight(distance, radius, maxArcHeight, greaterThan180) { var heightOptions = []; heightOptions.push(radius + Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2))); heightOptions.push(radius - Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2))); if(greaterThan180){ return closestButNotGreaterThan(heightOptions, maxArcHeight); } else{ return closestToZero(heightOptions, maxArcHeight); } }
javascript
function findArcHeight(distance, radius, maxArcHeight, greaterThan180) { var heightOptions = []; heightOptions.push(radius + Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2))); heightOptions.push(radius - Math.sqrt(Math.pow(radius,2) - Math.pow(distance,2))); if(greaterThan180){ return closestButNotGreaterThan(heightOptions, maxArcHeight); } else{ return closestToZero(heightOptions, maxArcHeight); } }
[ "function", "findArcHeight", "(", "distance", ",", "radius", ",", "maxArcHeight", ",", "greaterThan180", ")", "{", "var", "heightOptions", "=", "[", "]", ";", "heightOptions", ".", "push", "(", "radius", "+", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "radius", ",", "2", ")", "-", "Math", ".", "pow", "(", "distance", ",", "2", ")", ")", ")", ";", "heightOptions", ".", "push", "(", "radius", "-", "Math", ".", "sqrt", "(", "Math", ".", "pow", "(", "radius", ",", "2", ")", "-", "Math", ".", "pow", "(", "distance", ",", "2", ")", ")", ")", ";", "if", "(", "greaterThan180", ")", "{", "return", "closestButNotGreaterThan", "(", "heightOptions", ",", "maxArcHeight", ")", ";", "}", "else", "{", "return", "closestToZero", "(", "heightOptions", ",", "maxArcHeight", ")", ";", "}", "}" ]
Compute the height of a circular arc given `distance` is half the length of the chord of the circle, `radius` is the radius of the circle in question
[ "Compute", "the", "height", "of", "a", "circular", "arc", "given", "distance", "is", "half", "the", "length", "of", "the", "chord", "of", "the", "circle", "radius", "is", "the", "radius", "of", "the", "circle", "in", "question" ]
4dc13529696a52dbe2d2cfcad3204dd39fca2f88
https://github.com/socialtables/geometry-utils/blob/4dc13529696a52dbe2d2cfcad3204dd39fca2f88/lib/split-arc.js#L42-L53
38,762
logikum/md-site-engine
source/utilities/negotiate-language.js
negotiateLanguage
function negotiateLanguage( acceptable, supported, engineDefault ) { var candidates = []; var enumeration = acceptable || ''; if (enumeration) { // Create list of candidate locales. var re = /;q=[01]\.\d,?/g; var matches = enumeration.match( re ); if (matches) // Create weighted list of locales. for (var i = 0; i < matches.length; i++) { var q = matches[ i ]; var index = enumeration.indexOf( q ); var group = enumeration.substring( 0, index ); var members = group.split( ',' ); var value = +q.substr( 3, 3 ); members.forEach( function ( member ) { candidates.push( { locale: member, weight: value } ); } ); enumeration = enumeration.substring( index + q.length ); } else { // Create simple list of locales. var locales = enumeration.split( ',' ); locales.forEach( function ( member ) { candidates.push( { locale: member, weight: 1.0 } ); } ); } } // Sort locales by weight DESC, locale length DESC. candidates.sort( function ( a, b ) { if (a.weight < b.weight) return 1; if (a.weight > b.weight) return -1; if (a.locale.length < b.locale.length) return 1; if (a.locale.length > b.locale.length) return -1; return 0; } ); // Find candidates among supported locales. for (var c = 0; c < candidates.length; c++) { var item = candidates[ c ].locale; do { if (supported.indexOf( item ) > -1) return item; // Try without country/region code. item = item.substring( 0, item.lastIndexOf( '-' ) ); } while (item); } // No supported candidate: return engine's default locale. return engineDefault; }
javascript
function negotiateLanguage( acceptable, supported, engineDefault ) { var candidates = []; var enumeration = acceptable || ''; if (enumeration) { // Create list of candidate locales. var re = /;q=[01]\.\d,?/g; var matches = enumeration.match( re ); if (matches) // Create weighted list of locales. for (var i = 0; i < matches.length; i++) { var q = matches[ i ]; var index = enumeration.indexOf( q ); var group = enumeration.substring( 0, index ); var members = group.split( ',' ); var value = +q.substr( 3, 3 ); members.forEach( function ( member ) { candidates.push( { locale: member, weight: value } ); } ); enumeration = enumeration.substring( index + q.length ); } else { // Create simple list of locales. var locales = enumeration.split( ',' ); locales.forEach( function ( member ) { candidates.push( { locale: member, weight: 1.0 } ); } ); } } // Sort locales by weight DESC, locale length DESC. candidates.sort( function ( a, b ) { if (a.weight < b.weight) return 1; if (a.weight > b.weight) return -1; if (a.locale.length < b.locale.length) return 1; if (a.locale.length > b.locale.length) return -1; return 0; } ); // Find candidates among supported locales. for (var c = 0; c < candidates.length; c++) { var item = candidates[ c ].locale; do { if (supported.indexOf( item ) > -1) return item; // Try without country/region code. item = item.substring( 0, item.lastIndexOf( '-' ) ); } while (item); } // No supported candidate: return engine's default locale. return engineDefault; }
[ "function", "negotiateLanguage", "(", "acceptable", ",", "supported", ",", "engineDefault", ")", "{", "var", "candidates", "=", "[", "]", ";", "var", "enumeration", "=", "acceptable", "||", "''", ";", "if", "(", "enumeration", ")", "{", "// Create list of candidate locales.", "var", "re", "=", "/", ";q=[01]\\.\\d,?", "/", "g", ";", "var", "matches", "=", "enumeration", ".", "match", "(", "re", ")", ";", "if", "(", "matches", ")", "// Create weighted list of locales.", "for", "(", "var", "i", "=", "0", ";", "i", "<", "matches", ".", "length", ";", "i", "++", ")", "{", "var", "q", "=", "matches", "[", "i", "]", ";", "var", "index", "=", "enumeration", ".", "indexOf", "(", "q", ")", ";", "var", "group", "=", "enumeration", ".", "substring", "(", "0", ",", "index", ")", ";", "var", "members", "=", "group", ".", "split", "(", "','", ")", ";", "var", "value", "=", "+", "q", ".", "substr", "(", "3", ",", "3", ")", ";", "members", ".", "forEach", "(", "function", "(", "member", ")", "{", "candidates", ".", "push", "(", "{", "locale", ":", "member", ",", "weight", ":", "value", "}", ")", ";", "}", ")", ";", "enumeration", "=", "enumeration", ".", "substring", "(", "index", "+", "q", ".", "length", ")", ";", "}", "else", "{", "// Create simple list of locales.", "var", "locales", "=", "enumeration", ".", "split", "(", "','", ")", ";", "locales", ".", "forEach", "(", "function", "(", "member", ")", "{", "candidates", ".", "push", "(", "{", "locale", ":", "member", ",", "weight", ":", "1.0", "}", ")", ";", "}", ")", ";", "}", "}", "// Sort locales by weight DESC, locale length DESC.", "candidates", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", ".", "weight", "<", "b", ".", "weight", ")", "return", "1", ";", "if", "(", "a", ".", "weight", ">", "b", ".", "weight", ")", "return", "-", "1", ";", "if", "(", "a", ".", "locale", ".", "length", "<", "b", ".", "locale", ".", "length", ")", "return", "1", ";", "if", "(", "a", ".", "locale", ".", "length", ">", "b", ".", "locale", ".", "length", ")", "return", "-", "1", ";", "return", "0", ";", "}", ")", ";", "// Find candidates among supported locales.", "for", "(", "var", "c", "=", "0", ";", "c", "<", "candidates", ".", "length", ";", "c", "++", ")", "{", "var", "item", "=", "candidates", "[", "c", "]", ".", "locale", ";", "do", "{", "if", "(", "supported", ".", "indexOf", "(", "item", ")", ">", "-", "1", ")", "return", "item", ";", "// Try without country/region code.", "item", "=", "item", ".", "substring", "(", "0", ",", "item", ".", "lastIndexOf", "(", "'-'", ")", ")", ";", "}", "while", "(", "item", ")", ";", "}", "// No supported candidate: return engine's default locale.", "return", "engineDefault", ";", "}" ]
Tries to determine the default language based on the acceptable languages of the browser and the supported languages of the site. @param {string} acceptable - The acceptable languages of the browser. @param {Array.<string>} supported - The supported languages of the site. @param {string} engineDefault - The default language when no common one found. @returns {string} The language to use.
[ "Tries", "to", "determine", "the", "default", "language", "based", "on", "the", "acceptable", "languages", "of", "the", "browser", "and", "the", "supported", "languages", "of", "the", "site", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/utilities/negotiate-language.js#L11-L67
38,763
Evo-Forge/Crux
lib/components/tasks/lib/entry.js
CruxTaskEntry
function CruxTaskEntry(name) { this.autorun = true; // we can disable auto running. this.name = name; this.debug = false; this.type = 'serial'; // the type of this task. Can be: serial or parallel this.__queue = []; this.__actions = {}; this.__hasActions = false; this.__started = false; this.__scheduled = false; this.__wait = 0; this.__running = false; this.__handlers = {}; // currently, only "failed", "timeout" and "completed" this.__options = { delay: 10, // number of seconds to delay the run. timeout: 0, // number of seconds until we consider the task failed. timer: 0 // number of seconds between calls. Defaults to 0(cyclic disabled) }; this.__run_queue = []; // we place any run requests while running here. EventEmitter.call(this); }
javascript
function CruxTaskEntry(name) { this.autorun = true; // we can disable auto running. this.name = name; this.debug = false; this.type = 'serial'; // the type of this task. Can be: serial or parallel this.__queue = []; this.__actions = {}; this.__hasActions = false; this.__started = false; this.__scheduled = false; this.__wait = 0; this.__running = false; this.__handlers = {}; // currently, only "failed", "timeout" and "completed" this.__options = { delay: 10, // number of seconds to delay the run. timeout: 0, // number of seconds until we consider the task failed. timer: 0 // number of seconds between calls. Defaults to 0(cyclic disabled) }; this.__run_queue = []; // we place any run requests while running here. EventEmitter.call(this); }
[ "function", "CruxTaskEntry", "(", "name", ")", "{", "this", ".", "autorun", "=", "true", ";", "// we can disable auto running.", "this", ".", "name", "=", "name", ";", "this", ".", "debug", "=", "false", ";", "this", ".", "type", "=", "'serial'", ";", "// the type of this task. Can be: serial or parallel", "this", ".", "__queue", "=", "[", "]", ";", "this", ".", "__actions", "=", "{", "}", ";", "this", ".", "__hasActions", "=", "false", ";", "this", ".", "__started", "=", "false", ";", "this", ".", "__scheduled", "=", "false", ";", "this", ".", "__wait", "=", "0", ";", "this", ".", "__running", "=", "false", ";", "this", ".", "__handlers", "=", "{", "}", ";", "// currently, only \"failed\", \"timeout\" and \"completed\"", "this", ".", "__options", "=", "{", "delay", ":", "10", ",", "// number of seconds to delay the run.", "timeout", ":", "0", ",", "// number of seconds until we consider the task failed.", "timer", ":", "0", "// number of seconds between calls. Defaults to 0(cyclic disabled)", "}", ";", "this", ".", "__run_queue", "=", "[", "]", ";", "// we place any run requests while running here.", "EventEmitter", ".", "call", "(", "this", ")", ";", "}" ]
the "this" context for each scheduled action. Also a singleton.
[ "the", "this", "context", "for", "each", "scheduled", "action", ".", "Also", "a", "singleton", "." ]
f5264fbc2eb053e3170cf2b7b38d46d08f779feb
https://github.com/Evo-Forge/Crux/blob/f5264fbc2eb053e3170cf2b7b38d46d08f779feb/lib/components/tasks/lib/entry.js#L15-L35
38,764
brandon-barker/node-xgminer
lib/xgminer.js
xgminer
function xgminer(host, port, options) { this.host = host || this.defaults.host; this.port = port || this.defaults.port; this.options = this.defaults; if (options) { _.defaults(this.options, options); } }
javascript
function xgminer(host, port, options) { this.host = host || this.defaults.host; this.port = port || this.defaults.port; this.options = this.defaults; if (options) { _.defaults(this.options, options); } }
[ "function", "xgminer", "(", "host", ",", "port", ",", "options", ")", "{", "this", ".", "host", "=", "host", "||", "this", ".", "defaults", ".", "host", ";", "this", ".", "port", "=", "port", "||", "this", ".", "defaults", ".", "port", ";", "this", ".", "options", "=", "this", ".", "defaults", ";", "if", "(", "options", ")", "{", "_", ".", "defaults", "(", "this", ".", "options", ",", "options", ")", ";", "}", "}" ]
Create an instance of xgminer. @param {Name} name @param {Host} host @param {Port} port @param {Options} options
[ "Create", "an", "instance", "of", "xgminer", "." ]
a90416e0a8929f794b5cdfc284ee6675fd705d68
https://github.com/brandon-barker/node-xgminer/blob/a90416e0a8929f794b5cdfc284ee6675fd705d68/lib/xgminer.js#L25-L33
38,765
kvnneff/s3-public-url
index.js
encodeSpecialCharacters
function encodeSpecialCharacters (str) { return encodeURI(str).replace(/[!'()* ]/g, function (char) { return '%' + char.charCodeAt(0).toString(16) }) }
javascript
function encodeSpecialCharacters (str) { return encodeURI(str).replace(/[!'()* ]/g, function (char) { return '%' + char.charCodeAt(0).toString(16) }) }
[ "function", "encodeSpecialCharacters", "(", "str", ")", "{", "return", "encodeURI", "(", "str", ")", ".", "replace", "(", "/", "[!'()* ]", "/", "g", ",", "function", "(", "char", ")", "{", "return", "'%'", "+", "char", ".", "charCodeAt", "(", "0", ")", ".", "toString", "(", "16", ")", "}", ")", "}" ]
Remove characters that are valid in URIs, but S3 does not like them for some reason. @param {String} str String to encode @return {String} Encoded string @api prviate
[ "Remove", "characters", "that", "are", "valid", "in", "URIs", "but", "S3", "does", "not", "like", "them", "for", "some", "reason", "." ]
29839e12812bdd0c20eea27d067490ff443904a7
https://github.com/kvnneff/s3-public-url/blob/29839e12812bdd0c20eea27d067490ff443904a7/index.js#L10-L14
38,766
logikum/md-site-engine
source/storage/insert-static-segments.js
insertStaticSegments
function insertStaticSegments( components, segments, languages ) { for (var componentName in components) { if (components.hasOwnProperty( componentName )) { var language; var appliedTokens = [ ]; var component = components[ componentName ]; // Determine the language of the component. if (typeof languages === 'string') language = languages; else { var parts = componentName.split( '/', 2 ); language = languages.indexOf( parts[ 0 ] ) >= 0 ? parts[ 0 ] : ''; } // Insert static segments into a language specific component only. if (language) { // Get static segment tokens of the component. component.tokens.filter( function ( token ) { return token.isStatic; } ) .forEach( function ( token ) { // Get segment. var segment = segments.get( language, token.name ); // Insert the static segment into the component. var re = new RegExp( token.expression, 'g' ); component.html = component.html.replace( re, segment.html ); appliedTokens.push( token.name ); } ); // Remove applied segment tokens. component.tokens = component.tokens.filter( function ( token ) { return appliedTokens.indexOf( token.name ) < 0; } ); } } } }
javascript
function insertStaticSegments( components, segments, languages ) { for (var componentName in components) { if (components.hasOwnProperty( componentName )) { var language; var appliedTokens = [ ]; var component = components[ componentName ]; // Determine the language of the component. if (typeof languages === 'string') language = languages; else { var parts = componentName.split( '/', 2 ); language = languages.indexOf( parts[ 0 ] ) >= 0 ? parts[ 0 ] : ''; } // Insert static segments into a language specific component only. if (language) { // Get static segment tokens of the component. component.tokens.filter( function ( token ) { return token.isStatic; } ) .forEach( function ( token ) { // Get segment. var segment = segments.get( language, token.name ); // Insert the static segment into the component. var re = new RegExp( token.expression, 'g' ); component.html = component.html.replace( re, segment.html ); appliedTokens.push( token.name ); } ); // Remove applied segment tokens. component.tokens = component.tokens.filter( function ( token ) { return appliedTokens.indexOf( token.name ) < 0; } ); } } } }
[ "function", "insertStaticSegments", "(", "components", ",", "segments", ",", "languages", ")", "{", "for", "(", "var", "componentName", "in", "components", ")", "{", "if", "(", "components", ".", "hasOwnProperty", "(", "componentName", ")", ")", "{", "var", "language", ";", "var", "appliedTokens", "=", "[", "]", ";", "var", "component", "=", "components", "[", "componentName", "]", ";", "// Determine the language of the component.", "if", "(", "typeof", "languages", "===", "'string'", ")", "language", "=", "languages", ";", "else", "{", "var", "parts", "=", "componentName", ".", "split", "(", "'/'", ",", "2", ")", ";", "language", "=", "languages", ".", "indexOf", "(", "parts", "[", "0", "]", ")", ">=", "0", "?", "parts", "[", "0", "]", ":", "''", ";", "}", "// Insert static segments into a language specific component only.", "if", "(", "language", ")", "{", "// Get static segment tokens of the component.", "component", ".", "tokens", ".", "filter", "(", "function", "(", "token", ")", "{", "return", "token", ".", "isStatic", ";", "}", ")", ".", "forEach", "(", "function", "(", "token", ")", "{", "// Get segment.", "var", "segment", "=", "segments", ".", "get", "(", "language", ",", "token", ".", "name", ")", ";", "// Insert the static segment into the component.", "var", "re", "=", "new", "RegExp", "(", "token", ".", "expression", ",", "'g'", ")", ";", "component", ".", "html", "=", "component", ".", "html", ".", "replace", "(", "re", ",", "segment", ".", "html", ")", ";", "appliedTokens", ".", "push", "(", "token", ".", "name", ")", ";", "}", ")", ";", "// Remove applied segment tokens.", "component", ".", "tokens", "=", "component", ".", "tokens", ".", "filter", "(", "function", "(", "token", ")", "{", "return", "appliedTokens", ".", "indexOf", "(", "token", ".", "name", ")", "<", "0", ";", "}", ")", ";", "}", "}", "}", "}" ]
Inserts static segments into all components. @param {object} components - The components to process. @param {SegmentDrawer} segments - The segment storage. @param {Array.<string>} languages - The list of languages.
[ "Inserts", "static", "segments", "into", "all", "components", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/storage/insert-static-segments.js#L9-L49
38,767
enmasseio/babble
lib/Conversation.js
Conversation
function Conversation (config) { if (!(this instanceof Conversation)) { throw new SyntaxError('Constructor must be called with the new operator'); } // public properties this.id = config && config.id || uuid.v4(); this.self = config && config.self || null; this.other = config && config.other || null; this.context = config && config.context || {}; // private properties this._send = config && config.send || null; this._inbox = []; // queue with received but not yet picked messages this._receivers = []; // queue with handlers waiting for a new message }
javascript
function Conversation (config) { if (!(this instanceof Conversation)) { throw new SyntaxError('Constructor must be called with the new operator'); } // public properties this.id = config && config.id || uuid.v4(); this.self = config && config.self || null; this.other = config && config.other || null; this.context = config && config.context || {}; // private properties this._send = config && config.send || null; this._inbox = []; // queue with received but not yet picked messages this._receivers = []; // queue with handlers waiting for a new message }
[ "function", "Conversation", "(", "config", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Conversation", ")", ")", "{", "throw", "new", "SyntaxError", "(", "'Constructor must be called with the new operator'", ")", ";", "}", "// public properties", "this", ".", "id", "=", "config", "&&", "config", ".", "id", "||", "uuid", ".", "v4", "(", ")", ";", "this", ".", "self", "=", "config", "&&", "config", ".", "self", "||", "null", ";", "this", ".", "other", "=", "config", "&&", "config", ".", "other", "||", "null", ";", "this", ".", "context", "=", "config", "&&", "config", ".", "context", "||", "{", "}", ";", "// private properties", "this", ".", "_send", "=", "config", "&&", "config", ".", "send", "||", "null", ";", "this", ".", "_inbox", "=", "[", "]", ";", "// queue with received but not yet picked messages", "this", ".", "_receivers", "=", "[", "]", ";", "// queue with handlers waiting for a new message", "}" ]
A conversation Holds meta data for a conversation between two peers @param {Object} [config] Configuration options: {string} [id] A unique id for the conversation. If not provided, a uuid is generated {string} self Id of the peer on this side of the conversation {string} other Id of the peer on the other side of the conversation {Object} [context] Context passed with all callbacks of the conversation {function(to: string, message: *): Promise} send Function to send a message @constructor
[ "A", "conversation", "Holds", "meta", "data", "for", "a", "conversation", "between", "two", "peers" ]
6b7e84d7fb0df2d1129f0646b37a9d89d3da2539
https://github.com/enmasseio/babble/blob/6b7e84d7fb0df2d1129f0646b37a9d89d3da2539/lib/Conversation.js#L15-L30
38,768
logikum/md-site-engine
source/utilities/r-and-d.js
setDeveloperRoutes
function setDeveloperRoutes( app, filingCabinet, paths, develop ) { // Create document template for resources. var head = '\n' + ' <link rel="stylesheet" href="' + develop.cssBootstrap + '" />\n' + ' <link rel="stylesheet" href="' + develop.cssHighlight + '">\n'; var foot = '\n' + ' <script src="' + develop.jsJQuery + '"></script>\n' + ' <script src="' + develop.jsBootstrap + '"></script>\n' + ' <script src="' + develop.jsHighlight + '"></script>\n' + ' <script>hljs.initHighlightingOnLoad();</script>\n'; function wrap( title, body ) { return '<html>\n<head>' + head + '</head>\n<style>\n' + css + '\n</style>\n\n' + '<h1>' + title + '</h1>\n' + '<p><i>' + pkgInfo.name + ' v' + pkgInfo.version + '</i></p>\n' + body + foot + '\n</body>\n</html>\n'; } // Set up developer paths. PATH.init( paths.develop ); // Developer home page. app.get( PATH.root, function ( req, res ) { res.status( 200 ).send( wrap( 'Resources', '<ul>\n' + ' <li><a href="' + PATH.list.languages + '">Languages</a></li>\n' + ' <li><a href="' + PATH.list.documents + '">Documents</a></li>\n' + ' <li><a href="' + PATH.list.layouts + '">Layouts</a></li>\n' + ' <li><a href="' + PATH.list.segments + '">Segments</a></li>\n' + ' <li><a href="' + PATH.list.contents + '">Contents</a></li>\n' + ' <li><a href="' + PATH.list.menus + '">Menus</a></li>\n' + ' <li><a href="' + PATH.list.locales + '">Locales</a></li>\n' + ' <li><a href="' + PATH.list.references + '">References</a></li>\n' + ' <li><a href="' + PATH.list.controls + '">Controls</a></li>\n' + '</ul>\n' + '<p><a class="btn btn-success" href="/">Go to site</a></p>\n' ) ); } ); logger.routeAdded( PATH.root ); // Lists all languages. app.get( PATH.list.languages, function ( req, res ) { res.status( 200 ).send( wrap( 'Languages', filingCabinet.listLanguages() + backToRoot() ) ); } ); logger.routeAdded( PATH.list.languages ); // Lists all documents. app.get( PATH.list.documents, function ( req, res ) { res.status( 200 ).send( wrap( 'Documents', filingCabinet.documents.list( PATH.show.document ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.documents ); // Display a document. app.get( PATH.show.document + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Document: ' + show( key ), filingCabinet.documents.show( key ) + backTo( PATH.list.documents ) ) ); } ); logger.routeAdded( PATH.show.document ); // Lists all layouts. app.get( PATH.list.layouts, function ( req, res ) { res.status( 200 ).send( wrap( 'Layouts', filingCabinet.layouts.list( PATH.show.layout ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.layouts ); // Display a layout. app.get( PATH.show.layout + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Layout: ' + show( key ), filingCabinet.layouts.show( key ) + backTo( PATH.list.layouts ) ) ); } ); logger.routeAdded( PATH.show.layout ); // Lists all segments. app.get( PATH.list.segments, function ( req, res ) { res.status( 200 ).send( wrap( 'Segments', filingCabinet.segments.list( PATH.show.segment ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.segments ); // Display a segment. app.get( PATH.show.segment + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Segment: ' + show( key ), filingCabinet.segments.show( key ) + backTo( PATH.list.segments ) ) ); } ); logger.routeAdded( PATH.show.segment ); // Lists all contents. app.get( PATH.list.contents, function ( req, res ) { res.status( 200 ).send( wrap( 'Contents', filingCabinet.contents.list( PATH.show.content ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.contents ); // Display a content. app.get( PATH.show.content + '/:language/:key', function ( req, res ) { var language = req.params[ 'language' ]; var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Content: ' + show( key ), filingCabinet.contents.show( language, key ) + backTo( PATH.list.contents ) ) ); } ); logger.routeAdded( PATH.show.content ); // Lists all menus. app.get( PATH.list.menus, function ( req, res ) { res.status( 200 ).send( wrap( 'Menus', filingCabinet.menus.list( PATH.show.menu ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.menus ); // Display a menu. app.get( PATH.show.menu + '/:language/:key', function ( req, res ) { var language = req.params[ 'language' ]; var key = req.params[ 'key' ]; var result = filingCabinet.menus.show( language, +key ); res.status( 200 ).send( wrap( 'Menu: ' + show( result.title ), result.list + backTo( PATH.list.menus ) ) ); } ); logger.routeAdded( PATH.show.menu ); // Lists all locales. app.get( PATH.list.locales, function ( req, res ) { res.status( 200 ).send( wrap( 'Locales', filingCabinet.locales.list( filingCabinet.languages ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.locales ); // Lists all references. app.get( PATH.list.references, function ( req, res ) { res.status( 200 ).send( wrap( 'References', filingCabinet.references.list( PATH.show.reference ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.references ); // Display a reference. app.get( PATH.show.reference + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Reference: ' + show( key ), filingCabinet.references.show( key ) + backTo( PATH.list.references ) ) ); } ); logger.routeAdded( PATH.show.reference ); // Lists all controls. app.get( PATH.list.controls, function ( req, res ) { res.status( 200 ).send( wrap( 'Controls', filingCabinet.controls.list( PATH.show.control ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.controls ); // Display a control. app.get( PATH.show.control + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Control: ' + show( key ), filingCabinet.controls.show( key ) + backTo( PATH.list.controls ) ) ); } ); logger.routeAdded( PATH.show.control ); }
javascript
function setDeveloperRoutes( app, filingCabinet, paths, develop ) { // Create document template for resources. var head = '\n' + ' <link rel="stylesheet" href="' + develop.cssBootstrap + '" />\n' + ' <link rel="stylesheet" href="' + develop.cssHighlight + '">\n'; var foot = '\n' + ' <script src="' + develop.jsJQuery + '"></script>\n' + ' <script src="' + develop.jsBootstrap + '"></script>\n' + ' <script src="' + develop.jsHighlight + '"></script>\n' + ' <script>hljs.initHighlightingOnLoad();</script>\n'; function wrap( title, body ) { return '<html>\n<head>' + head + '</head>\n<style>\n' + css + '\n</style>\n\n' + '<h1>' + title + '</h1>\n' + '<p><i>' + pkgInfo.name + ' v' + pkgInfo.version + '</i></p>\n' + body + foot + '\n</body>\n</html>\n'; } // Set up developer paths. PATH.init( paths.develop ); // Developer home page. app.get( PATH.root, function ( req, res ) { res.status( 200 ).send( wrap( 'Resources', '<ul>\n' + ' <li><a href="' + PATH.list.languages + '">Languages</a></li>\n' + ' <li><a href="' + PATH.list.documents + '">Documents</a></li>\n' + ' <li><a href="' + PATH.list.layouts + '">Layouts</a></li>\n' + ' <li><a href="' + PATH.list.segments + '">Segments</a></li>\n' + ' <li><a href="' + PATH.list.contents + '">Contents</a></li>\n' + ' <li><a href="' + PATH.list.menus + '">Menus</a></li>\n' + ' <li><a href="' + PATH.list.locales + '">Locales</a></li>\n' + ' <li><a href="' + PATH.list.references + '">References</a></li>\n' + ' <li><a href="' + PATH.list.controls + '">Controls</a></li>\n' + '</ul>\n' + '<p><a class="btn btn-success" href="/">Go to site</a></p>\n' ) ); } ); logger.routeAdded( PATH.root ); // Lists all languages. app.get( PATH.list.languages, function ( req, res ) { res.status( 200 ).send( wrap( 'Languages', filingCabinet.listLanguages() + backToRoot() ) ); } ); logger.routeAdded( PATH.list.languages ); // Lists all documents. app.get( PATH.list.documents, function ( req, res ) { res.status( 200 ).send( wrap( 'Documents', filingCabinet.documents.list( PATH.show.document ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.documents ); // Display a document. app.get( PATH.show.document + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Document: ' + show( key ), filingCabinet.documents.show( key ) + backTo( PATH.list.documents ) ) ); } ); logger.routeAdded( PATH.show.document ); // Lists all layouts. app.get( PATH.list.layouts, function ( req, res ) { res.status( 200 ).send( wrap( 'Layouts', filingCabinet.layouts.list( PATH.show.layout ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.layouts ); // Display a layout. app.get( PATH.show.layout + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Layout: ' + show( key ), filingCabinet.layouts.show( key ) + backTo( PATH.list.layouts ) ) ); } ); logger.routeAdded( PATH.show.layout ); // Lists all segments. app.get( PATH.list.segments, function ( req, res ) { res.status( 200 ).send( wrap( 'Segments', filingCabinet.segments.list( PATH.show.segment ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.segments ); // Display a segment. app.get( PATH.show.segment + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Segment: ' + show( key ), filingCabinet.segments.show( key ) + backTo( PATH.list.segments ) ) ); } ); logger.routeAdded( PATH.show.segment ); // Lists all contents. app.get( PATH.list.contents, function ( req, res ) { res.status( 200 ).send( wrap( 'Contents', filingCabinet.contents.list( PATH.show.content ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.contents ); // Display a content. app.get( PATH.show.content + '/:language/:key', function ( req, res ) { var language = req.params[ 'language' ]; var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Content: ' + show( key ), filingCabinet.contents.show( language, key ) + backTo( PATH.list.contents ) ) ); } ); logger.routeAdded( PATH.show.content ); // Lists all menus. app.get( PATH.list.menus, function ( req, res ) { res.status( 200 ).send( wrap( 'Menus', filingCabinet.menus.list( PATH.show.menu ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.menus ); // Display a menu. app.get( PATH.show.menu + '/:language/:key', function ( req, res ) { var language = req.params[ 'language' ]; var key = req.params[ 'key' ]; var result = filingCabinet.menus.show( language, +key ); res.status( 200 ).send( wrap( 'Menu: ' + show( result.title ), result.list + backTo( PATH.list.menus ) ) ); } ); logger.routeAdded( PATH.show.menu ); // Lists all locales. app.get( PATH.list.locales, function ( req, res ) { res.status( 200 ).send( wrap( 'Locales', filingCabinet.locales.list( filingCabinet.languages ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.locales ); // Lists all references. app.get( PATH.list.references, function ( req, res ) { res.status( 200 ).send( wrap( 'References', filingCabinet.references.list( PATH.show.reference ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.references ); // Display a reference. app.get( PATH.show.reference + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Reference: ' + show( key ), filingCabinet.references.show( key ) + backTo( PATH.list.references ) ) ); } ); logger.routeAdded( PATH.show.reference ); // Lists all controls. app.get( PATH.list.controls, function ( req, res ) { res.status( 200 ).send( wrap( 'Controls', filingCabinet.controls.list( PATH.show.control ) + backToRoot() ) ); } ); logger.routeAdded( PATH.list.controls ); // Display a control. app.get( PATH.show.control + '/:key', function ( req, res ) { var key = PATH.unsafe( req.params[ 'key' ] ); res.status( 200 ).send( wrap( 'Control: ' + show( key ), filingCabinet.controls.show( key ) + backTo( PATH.list.controls ) ) ); } ); logger.routeAdded( PATH.show.control ); }
[ "function", "setDeveloperRoutes", "(", "app", ",", "filingCabinet", ",", "paths", ",", "develop", ")", "{", "// Create document template for resources.", "var", "head", "=", "'\\n'", "+", "' <link rel=\"stylesheet\" href=\"'", "+", "develop", ".", "cssBootstrap", "+", "'\" />\\n'", "+", "' <link rel=\"stylesheet\" href=\"'", "+", "develop", ".", "cssHighlight", "+", "'\">\\n'", ";", "var", "foot", "=", "'\\n'", "+", "' <script src=\"'", "+", "develop", ".", "jsJQuery", "+", "'\"></script>\\n'", "+", "' <script src=\"'", "+", "develop", ".", "jsBootstrap", "+", "'\"></script>\\n'", "+", "' <script src=\"'", "+", "develop", ".", "jsHighlight", "+", "'\"></script>\\n'", "+", "' <script>hljs.initHighlightingOnLoad();</script>\\n'", ";", "function", "wrap", "(", "title", ",", "body", ")", "{", "return", "'<html>\\n<head>'", "+", "head", "+", "'</head>\\n<style>\\n'", "+", "css", "+", "'\\n</style>\\n\\n'", "+", "'<h1>'", "+", "title", "+", "'</h1>\\n'", "+", "'<p><i>'", "+", "pkgInfo", ".", "name", "+", "' v'", "+", "pkgInfo", ".", "version", "+", "'</i></p>\\n'", "+", "body", "+", "foot", "+", "'\\n</body>\\n</html>\\n'", ";", "}", "// Set up developer paths.", "PATH", ".", "init", "(", "paths", ".", "develop", ")", ";", "// Developer home page.", "app", ".", "get", "(", "PATH", ".", "root", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Resources'", ",", "'<ul>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "languages", "+", "'\">Languages</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "documents", "+", "'\">Documents</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "layouts", "+", "'\">Layouts</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "segments", "+", "'\">Segments</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "contents", "+", "'\">Contents</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "menus", "+", "'\">Menus</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "locales", "+", "'\">Locales</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "references", "+", "'\">References</a></li>\\n'", "+", "' <li><a href=\"'", "+", "PATH", ".", "list", ".", "controls", "+", "'\">Controls</a></li>\\n'", "+", "'</ul>\\n'", "+", "'<p><a class=\"btn btn-success\" href=\"/\">Go to site</a></p>\\n'", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "root", ")", ";", "// Lists all languages.", "app", ".", "get", "(", "PATH", ".", "list", ".", "languages", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Languages'", ",", "filingCabinet", ".", "listLanguages", "(", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "languages", ")", ";", "// Lists all documents.", "app", ".", "get", "(", "PATH", ".", "list", ".", "documents", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Documents'", ",", "filingCabinet", ".", "documents", ".", "list", "(", "PATH", ".", "show", ".", "document", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "documents", ")", ";", "// Display a document.", "app", ".", "get", "(", "PATH", ".", "show", ".", "document", "+", "'/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "key", "=", "PATH", ".", "unsafe", "(", "req", ".", "params", "[", "'key'", "]", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Document: '", "+", "show", "(", "key", ")", ",", "filingCabinet", ".", "documents", ".", "show", "(", "key", ")", "+", "backTo", "(", "PATH", ".", "list", ".", "documents", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "document", ")", ";", "// Lists all layouts.", "app", ".", "get", "(", "PATH", ".", "list", ".", "layouts", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Layouts'", ",", "filingCabinet", ".", "layouts", ".", "list", "(", "PATH", ".", "show", ".", "layout", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "layouts", ")", ";", "// Display a layout.", "app", ".", "get", "(", "PATH", ".", "show", ".", "layout", "+", "'/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "key", "=", "PATH", ".", "unsafe", "(", "req", ".", "params", "[", "'key'", "]", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Layout: '", "+", "show", "(", "key", ")", ",", "filingCabinet", ".", "layouts", ".", "show", "(", "key", ")", "+", "backTo", "(", "PATH", ".", "list", ".", "layouts", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "layout", ")", ";", "// Lists all segments.", "app", ".", "get", "(", "PATH", ".", "list", ".", "segments", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Segments'", ",", "filingCabinet", ".", "segments", ".", "list", "(", "PATH", ".", "show", ".", "segment", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "segments", ")", ";", "// Display a segment.", "app", ".", "get", "(", "PATH", ".", "show", ".", "segment", "+", "'/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "key", "=", "PATH", ".", "unsafe", "(", "req", ".", "params", "[", "'key'", "]", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Segment: '", "+", "show", "(", "key", ")", ",", "filingCabinet", ".", "segments", ".", "show", "(", "key", ")", "+", "backTo", "(", "PATH", ".", "list", ".", "segments", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "segment", ")", ";", "// Lists all contents.", "app", ".", "get", "(", "PATH", ".", "list", ".", "contents", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Contents'", ",", "filingCabinet", ".", "contents", ".", "list", "(", "PATH", ".", "show", ".", "content", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "contents", ")", ";", "// Display a content.", "app", ".", "get", "(", "PATH", ".", "show", ".", "content", "+", "'/:language/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "language", "=", "req", ".", "params", "[", "'language'", "]", ";", "var", "key", "=", "PATH", ".", "unsafe", "(", "req", ".", "params", "[", "'key'", "]", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Content: '", "+", "show", "(", "key", ")", ",", "filingCabinet", ".", "contents", ".", "show", "(", "language", ",", "key", ")", "+", "backTo", "(", "PATH", ".", "list", ".", "contents", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "content", ")", ";", "// Lists all menus.", "app", ".", "get", "(", "PATH", ".", "list", ".", "menus", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Menus'", ",", "filingCabinet", ".", "menus", ".", "list", "(", "PATH", ".", "show", ".", "menu", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "menus", ")", ";", "// Display a menu.", "app", ".", "get", "(", "PATH", ".", "show", ".", "menu", "+", "'/:language/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "language", "=", "req", ".", "params", "[", "'language'", "]", ";", "var", "key", "=", "req", ".", "params", "[", "'key'", "]", ";", "var", "result", "=", "filingCabinet", ".", "menus", ".", "show", "(", "language", ",", "+", "key", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Menu: '", "+", "show", "(", "result", ".", "title", ")", ",", "result", ".", "list", "+", "backTo", "(", "PATH", ".", "list", ".", "menus", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "menu", ")", ";", "// Lists all locales.", "app", ".", "get", "(", "PATH", ".", "list", ".", "locales", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Locales'", ",", "filingCabinet", ".", "locales", ".", "list", "(", "filingCabinet", ".", "languages", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "locales", ")", ";", "// Lists all references.", "app", ".", "get", "(", "PATH", ".", "list", ".", "references", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'References'", ",", "filingCabinet", ".", "references", ".", "list", "(", "PATH", ".", "show", ".", "reference", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "references", ")", ";", "// Display a reference.", "app", ".", "get", "(", "PATH", ".", "show", ".", "reference", "+", "'/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "key", "=", "PATH", ".", "unsafe", "(", "req", ".", "params", "[", "'key'", "]", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Reference: '", "+", "show", "(", "key", ")", ",", "filingCabinet", ".", "references", ".", "show", "(", "key", ")", "+", "backTo", "(", "PATH", ".", "list", ".", "references", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "reference", ")", ";", "// Lists all controls.", "app", ".", "get", "(", "PATH", ".", "list", ".", "controls", ",", "function", "(", "req", ",", "res", ")", "{", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Controls'", ",", "filingCabinet", ".", "controls", ".", "list", "(", "PATH", ".", "show", ".", "control", ")", "+", "backToRoot", "(", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "list", ".", "controls", ")", ";", "// Display a control.", "app", ".", "get", "(", "PATH", ".", "show", ".", "control", "+", "'/:key'", ",", "function", "(", "req", ",", "res", ")", "{", "var", "key", "=", "PATH", ".", "unsafe", "(", "req", ".", "params", "[", "'key'", "]", ")", ";", "res", ".", "status", "(", "200", ")", ".", "send", "(", "wrap", "(", "'Control: '", "+", "show", "(", "key", ")", ",", "filingCabinet", ".", "controls", ".", "show", "(", "key", ")", "+", "backTo", "(", "PATH", ".", "list", ".", "controls", ")", ")", ")", ";", "}", ")", ";", "logger", ".", "routeAdded", "(", "PATH", ".", "show", ".", "control", ")", ";", "}" ]
Sets the helper routes to support development. @param {Express.Application} app - The express.js application object. @param {FilingCabinet} filingCabinet - The file manager object. @param {object} paths - The configuration paths.
[ "Sets", "the", "helper", "routes", "to", "support", "development", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/utilities/r-and-d.js#L30-L208
38,769
ansuz/ansuzjs
ansuz.js
function(){ // the generator we will return var res=f(); // get the first result if(cond(res)&&failed){ // if we've failed twice, then we're done return; // return an undefined result }else if(cond(res)){ // otherwise, if we fail, try moving on f=function(){return next();} // now use the second list failed=true; // but remember that we failed once return fn(); // return the next element }else return res; // otherwise, we must have a good result, return it }
javascript
function(){ // the generator we will return var res=f(); // get the first result if(cond(res)&&failed){ // if we've failed twice, then we're done return; // return an undefined result }else if(cond(res)){ // otherwise, if we fail, try moving on f=function(){return next();} // now use the second list failed=true; // but remember that we failed once return fn(); // return the next element }else return res; // otherwise, we must have a good result, return it }
[ "function", "(", ")", "{", "// the generator we will return", "var", "res", "=", "f", "(", ")", ";", "// get the first result", "if", "(", "cond", "(", "res", ")", "&&", "failed", ")", "{", "// if we've failed twice, then we're done", "return", ";", "// return an undefined result", "}", "else", "if", "(", "cond", "(", "res", ")", ")", "{", "// otherwise, if we fail, try moving on", "f", "=", "function", "(", ")", "{", "return", "next", "(", ")", ";", "}", "// now use the second list", "failed", "=", "true", ";", "// but remember that we failed once", "return", "fn", "(", ")", ";", "// return the next element", "}", "else", "return", "res", ";", "// otherwise, we must have a good result, return it", "}" ]
this keeps us from an infinite loop
[ "this", "keeps", "us", "from", "an", "infinite", "loop" ]
d029cb8d33315eec2ec5a6b8a581b27640d0c19f
https://github.com/ansuz/ansuzjs/blob/d029cb8d33315eec2ec5a6b8a581b27640d0c19f/ansuz.js#L562-L572
38,770
ansuz/ansuzjs
ansuz.js
function(){ // the main generator you'll return var res=kid(); // call the child function and store the result if(cond(res)&&failed){ // if both generators have failed return done(); // then you're done }else if(cond(res)){ // if just the child has failed par(); // regenerate the child array return fn(); // return the next child value }else{ // otherwise.. return [temp,res]; // return combined parent and child values } }
javascript
function(){ // the main generator you'll return var res=kid(); // call the child function and store the result if(cond(res)&&failed){ // if both generators have failed return done(); // then you're done }else if(cond(res)){ // if just the child has failed par(); // regenerate the child array return fn(); // return the next child value }else{ // otherwise.. return [temp,res]; // return combined parent and child values } }
[ "function", "(", ")", "{", "// the main generator you'll return", "var", "res", "=", "kid", "(", ")", ";", "// call the child function and store the result", "if", "(", "cond", "(", "res", ")", "&&", "failed", ")", "{", "// if both generators have failed", "return", "done", "(", ")", ";", "// then you're done", "}", "else", "if", "(", "cond", "(", "res", ")", ")", "{", "// if just the child has failed", "par", "(", ")", ";", "// regenerate the child array", "return", "fn", "(", ")", ";", "// return the next child value", "}", "else", "{", "// otherwise.. ", "return", "[", "temp", ",", "res", "]", ";", "// return combined parent and child values", "}", "}" ]
now that the parent handler is defined, increment it
[ "now", "that", "the", "parent", "handler", "is", "defined", "increment", "it" ]
d029cb8d33315eec2ec5a6b8a581b27640d0c19f
https://github.com/ansuz/ansuzjs/blob/d029cb8d33315eec2ec5a6b8a581b27640d0c19f/ansuz.js#L610-L620
38,771
fin-hypergrid/fin-hypergrid-sorting-plugin
mix-ins/behavior.js
removeHiddenColumns
function removeHiddenColumns(oldSorted, hiddenColumns){ var dirty = false; oldSorted.forEach(function(i) { var j = 0, colIndex; while (j < hiddenColumns.length) { colIndex = hiddenColumns[j].index + 1; //hack to get around 0 index if (colIndex === i) { hiddenColumns[j].unSort(); dirty = true; break; } j++; } }); return dirty; }
javascript
function removeHiddenColumns(oldSorted, hiddenColumns){ var dirty = false; oldSorted.forEach(function(i) { var j = 0, colIndex; while (j < hiddenColumns.length) { colIndex = hiddenColumns[j].index + 1; //hack to get around 0 index if (colIndex === i) { hiddenColumns[j].unSort(); dirty = true; break; } j++; } }); return dirty; }
[ "function", "removeHiddenColumns", "(", "oldSorted", ",", "hiddenColumns", ")", "{", "var", "dirty", "=", "false", ";", "oldSorted", ".", "forEach", "(", "function", "(", "i", ")", "{", "var", "j", "=", "0", ",", "colIndex", ";", "while", "(", "j", "<", "hiddenColumns", ".", "length", ")", "{", "colIndex", "=", "hiddenColumns", "[", "j", "]", ".", "index", "+", "1", ";", "//hack to get around 0 index", "if", "(", "colIndex", "===", "i", ")", "{", "hiddenColumns", "[", "j", "]", ".", "unSort", "(", ")", ";", "dirty", "=", "true", ";", "break", ";", "}", "j", "++", ";", "}", "}", ")", ";", "return", "dirty", ";", "}" ]
Logic to moved to adapter layer outside of Hypergrid Core
[ "Logic", "to", "moved", "to", "adapter", "layer", "outside", "of", "Hypergrid", "Core" ]
008242e2d5b7b0d250eed83eaf692cbcdb9f8687
https://github.com/fin-hypergrid/fin-hypergrid-sorting-plugin/blob/008242e2d5b7b0d250eed83eaf692cbcdb9f8687/mix-ins/behavior.js#L29-L45
38,772
codekirei/columnize-array
lib/methods/solve.js
solve
function solve() { while (true) { // establish vars for current loop //---------------------------------------------------------- const row = this.state.i % this.state.rows const col = Math.floor(this.state.i / this.state.rows) const str = this.props.ar[this.state.i] const len = str.length const tooLong = len > this.props.maxRowLen // str is too long ? set rows to maximum //---------------------------------------------------------- if (tooLong && this.state.rows !== this.props.arLen) { this.bindState(this.props.arLen) continue } // at new col ? indent previous col //---------------------------------------------------------- if (row === 0 && this.state.i !== 0) { const prevCol = col - 1 const reqLen = this.state.widths[prevCol] + this.props.gap.len this.state.indices.forEach((ar, i) => { const prevLen = this.props.ar[ar[prevCol]].length const diff = reqLen - prevLen this.state.strs[i] += this.props.gap.ch.repeat(diff) }) } // add str to row //---------------------------------------------------------- this.state.strs[row] += str // row not too long ? update state : reset state with rows + 1 //---------------------------------------------------------- if ( this.state.strs[row].length <= this.props.maxRowLen || tooLong ) { if (len > this.state.widths[col]) this.state.widths[col] = len this.state.indices[row].push(this.state.i) this.state.i++ } else this.bindState(this.state.rows + 1) // solution reached ? exit loop //---------------------------------------------------------- if (this.state.i === this.props.arLen) break } }
javascript
function solve() { while (true) { // establish vars for current loop //---------------------------------------------------------- const row = this.state.i % this.state.rows const col = Math.floor(this.state.i / this.state.rows) const str = this.props.ar[this.state.i] const len = str.length const tooLong = len > this.props.maxRowLen // str is too long ? set rows to maximum //---------------------------------------------------------- if (tooLong && this.state.rows !== this.props.arLen) { this.bindState(this.props.arLen) continue } // at new col ? indent previous col //---------------------------------------------------------- if (row === 0 && this.state.i !== 0) { const prevCol = col - 1 const reqLen = this.state.widths[prevCol] + this.props.gap.len this.state.indices.forEach((ar, i) => { const prevLen = this.props.ar[ar[prevCol]].length const diff = reqLen - prevLen this.state.strs[i] += this.props.gap.ch.repeat(diff) }) } // add str to row //---------------------------------------------------------- this.state.strs[row] += str // row not too long ? update state : reset state with rows + 1 //---------------------------------------------------------- if ( this.state.strs[row].length <= this.props.maxRowLen || tooLong ) { if (len > this.state.widths[col]) this.state.widths[col] = len this.state.indices[row].push(this.state.i) this.state.i++ } else this.bindState(this.state.rows + 1) // solution reached ? exit loop //---------------------------------------------------------- if (this.state.i === this.props.arLen) break } }
[ "function", "solve", "(", ")", "{", "while", "(", "true", ")", "{", "// establish vars for current loop", "//----------------------------------------------------------", "const", "row", "=", "this", ".", "state", ".", "i", "%", "this", ".", "state", ".", "rows", "const", "col", "=", "Math", ".", "floor", "(", "this", ".", "state", ".", "i", "/", "this", ".", "state", ".", "rows", ")", "const", "str", "=", "this", ".", "props", ".", "ar", "[", "this", ".", "state", ".", "i", "]", "const", "len", "=", "str", ".", "length", "const", "tooLong", "=", "len", ">", "this", ".", "props", ".", "maxRowLen", "// str is too long ? set rows to maximum", "//----------------------------------------------------------", "if", "(", "tooLong", "&&", "this", ".", "state", ".", "rows", "!==", "this", ".", "props", ".", "arLen", ")", "{", "this", ".", "bindState", "(", "this", ".", "props", ".", "arLen", ")", "continue", "}", "// at new col ? indent previous col", "//----------------------------------------------------------", "if", "(", "row", "===", "0", "&&", "this", ".", "state", ".", "i", "!==", "0", ")", "{", "const", "prevCol", "=", "col", "-", "1", "const", "reqLen", "=", "this", ".", "state", ".", "widths", "[", "prevCol", "]", "+", "this", ".", "props", ".", "gap", ".", "len", "this", ".", "state", ".", "indices", ".", "forEach", "(", "(", "ar", ",", "i", ")", "=>", "{", "const", "prevLen", "=", "this", ".", "props", ".", "ar", "[", "ar", "[", "prevCol", "]", "]", ".", "length", "const", "diff", "=", "reqLen", "-", "prevLen", "this", ".", "state", ".", "strs", "[", "i", "]", "+=", "this", ".", "props", ".", "gap", ".", "ch", ".", "repeat", "(", "diff", ")", "}", ")", "}", "// add str to row", "//----------------------------------------------------------", "this", ".", "state", ".", "strs", "[", "row", "]", "+=", "str", "// row not too long ? update state : reset state with rows + 1", "//----------------------------------------------------------", "if", "(", "this", ".", "state", ".", "strs", "[", "row", "]", ".", "length", "<=", "this", ".", "props", ".", "maxRowLen", "||", "tooLong", ")", "{", "if", "(", "len", ">", "this", ".", "state", ".", "widths", "[", "col", "]", ")", "this", ".", "state", ".", "widths", "[", "col", "]", "=", "len", "this", ".", "state", ".", "indices", "[", "row", "]", ".", "push", "(", "this", ".", "state", ".", "i", ")", "this", ".", "state", ".", "i", "++", "}", "else", "this", ".", "bindState", "(", "this", ".", "state", ".", "rows", "+", "1", ")", "// solution reached ? exit loop", "//----------------------------------------------------------", "if", "(", "this", ".", "state", ".", "i", "===", "this", ".", "props", ".", "arLen", ")", "break", "}", "}" ]
Iteratively solves columnization given constraints in props. Solution is captured by this.state. @returns {undefined}
[ "Iteratively", "solves", "columnization", "given", "constraints", "in", "props", ".", "Solution", "is", "captured", "by", "this", ".", "state", "." ]
ba100d1d9cf707fa249a58fa177d6b26ec131278
https://github.com/codekirei/columnize-array/blob/ba100d1d9cf707fa249a58fa177d6b26ec131278/lib/methods/solve.js#L9-L59
38,773
avigoldman/fuse-email
lib/index.js
isInvalidInboundAddress
function isInvalidInboundAddress(inboundAddress) { if (fuse.config.restrict_inbound === false) return false; return cleanAddress(inboundAddress) !== fuse.config.inbound_address; }
javascript
function isInvalidInboundAddress(inboundAddress) { if (fuse.config.restrict_inbound === false) return false; return cleanAddress(inboundAddress) !== fuse.config.inbound_address; }
[ "function", "isInvalidInboundAddress", "(", "inboundAddress", ")", "{", "if", "(", "fuse", ".", "config", ".", "restrict_inbound", "===", "false", ")", "return", "false", ";", "return", "cleanAddress", "(", "inboundAddress", ")", "!==", "fuse", ".", "config", ".", "inbound_address", ";", "}" ]
returns boolean on if the recieving email is accepted @param {string} inboundAddress
[ "returns", "boolean", "on", "if", "the", "recieving", "email", "is", "accepted" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L270-L275
38,774
avigoldman/fuse-email
lib/index.js
getEventType
function getEventType(inboundMessage) { let recipientAddresses = _.map(inboundMessage.recipients, 'email'); let ccAddresses = _.map(inboundMessage.cc, 'email'); if (_.max([recipientAddresses.indexOf(fuse.config.inbound_address), recipientAddresses.indexOf(inboundMessage.to.email)]) >= 0) { return 'direct_email'; } else if (_.max([ccAddresses.indexOf(fuse.config.inbound_address), ccAddresses.indexOf(inboundMessage.to.email)]) >= 0) { return 'cc_email'; } else { return 'bcc_email'; } }
javascript
function getEventType(inboundMessage) { let recipientAddresses = _.map(inboundMessage.recipients, 'email'); let ccAddresses = _.map(inboundMessage.cc, 'email'); if (_.max([recipientAddresses.indexOf(fuse.config.inbound_address), recipientAddresses.indexOf(inboundMessage.to.email)]) >= 0) { return 'direct_email'; } else if (_.max([ccAddresses.indexOf(fuse.config.inbound_address), ccAddresses.indexOf(inboundMessage.to.email)]) >= 0) { return 'cc_email'; } else { return 'bcc_email'; } }
[ "function", "getEventType", "(", "inboundMessage", ")", "{", "let", "recipientAddresses", "=", "_", ".", "map", "(", "inboundMessage", ".", "recipients", ",", "'email'", ")", ";", "let", "ccAddresses", "=", "_", ".", "map", "(", "inboundMessage", ".", "cc", ",", "'email'", ")", ";", "if", "(", "_", ".", "max", "(", "[", "recipientAddresses", ".", "indexOf", "(", "fuse", ".", "config", ".", "inbound_address", ")", ",", "recipientAddresses", ".", "indexOf", "(", "inboundMessage", ".", "to", ".", "email", ")", "]", ")", ">=", "0", ")", "{", "return", "'direct_email'", ";", "}", "else", "if", "(", "_", ".", "max", "(", "[", "ccAddresses", ".", "indexOf", "(", "fuse", ".", "config", ".", "inbound_address", ")", ",", "ccAddresses", ".", "indexOf", "(", "inboundMessage", ".", "to", ".", "email", ")", "]", ")", ">=", "0", ")", "{", "return", "'cc_email'", ";", "}", "else", "{", "return", "'bcc_email'", ";", "}", "}" ]
returns a string with the event type of this message @param {InboundMessage} inboundMessage @returns {string} eventType
[ "returns", "a", "string", "with", "the", "event", "type", "of", "this", "message" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L293-L308
38,775
avigoldman/fuse-email
lib/index.js
addFromAddress
function addFromAddress(inboundMessage, outboundMessage) { if (inboundMessage && _.has(inboundMessage, 'from')) { outboundMessage.recipients = outboundMessage.recipients || []; outboundMessage.recipients.push(inboundMessage.from); } return outboundMessage; }
javascript
function addFromAddress(inboundMessage, outboundMessage) { if (inboundMessage && _.has(inboundMessage, 'from')) { outboundMessage.recipients = outboundMessage.recipients || []; outboundMessage.recipients.push(inboundMessage.from); } return outboundMessage; }
[ "function", "addFromAddress", "(", "inboundMessage", ",", "outboundMessage", ")", "{", "if", "(", "inboundMessage", "&&", "_", ".", "has", "(", "inboundMessage", ",", "'from'", ")", ")", "{", "outboundMessage", ".", "recipients", "=", "outboundMessage", ".", "recipients", "||", "[", "]", ";", "outboundMessage", ".", "recipients", ".", "push", "(", "inboundMessage", ".", "from", ")", ";", "}", "return", "outboundMessage", ";", "}" ]
gets the address that sent the inbound message and adds it as a recipient to the outbound message @param {InboundMessage} inboundMessage @param {OutboundMessage} outboundMessage @returns {OutboundMessage} outboundMessage
[ "gets", "the", "address", "that", "sent", "the", "inbound", "message", "and", "adds", "it", "as", "a", "recipient", "to", "the", "outbound", "message" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L323-L331
38,776
avigoldman/fuse-email
lib/index.js
defaultConfiguration
function defaultConfiguration(config) { config = _.defaults({}, config, { name: 'Sparky', endpoint: '/relay', convos: [], sending_address: config.address, inbound_address: config.address, transport: 'sparkpost', restrict_inbound: true, logger: 'verbose', size_limit: '50mb' }); config.address = cleanAddress(config.address); config.sending_address = cleanAddress(config.sending_address); config.inbound_address = cleanAddress(config.inbound_address); config.logger = _.isString(config.logger) ? require('./logger')(config.logger) : config.logger; return config; }
javascript
function defaultConfiguration(config) { config = _.defaults({}, config, { name: 'Sparky', endpoint: '/relay', convos: [], sending_address: config.address, inbound_address: config.address, transport: 'sparkpost', restrict_inbound: true, logger: 'verbose', size_limit: '50mb' }); config.address = cleanAddress(config.address); config.sending_address = cleanAddress(config.sending_address); config.inbound_address = cleanAddress(config.inbound_address); config.logger = _.isString(config.logger) ? require('./logger')(config.logger) : config.logger; return config; }
[ "function", "defaultConfiguration", "(", "config", ")", "{", "config", "=", "_", ".", "defaults", "(", "{", "}", ",", "config", ",", "{", "name", ":", "'Sparky'", ",", "endpoint", ":", "'/relay'", ",", "convos", ":", "[", "]", ",", "sending_address", ":", "config", ".", "address", ",", "inbound_address", ":", "config", ".", "address", ",", "transport", ":", "'sparkpost'", ",", "restrict_inbound", ":", "true", ",", "logger", ":", "'verbose'", ",", "size_limit", ":", "'50mb'", "}", ")", ";", "config", ".", "address", "=", "cleanAddress", "(", "config", ".", "address", ")", ";", "config", ".", "sending_address", "=", "cleanAddress", "(", "config", ".", "sending_address", ")", ";", "config", ".", "inbound_address", "=", "cleanAddress", "(", "config", ".", "inbound_address", ")", ";", "config", ".", "logger", "=", "_", ".", "isString", "(", "config", ".", "logger", ")", "?", "require", "(", "'./logger'", ")", "(", "config", ".", "logger", ")", ":", "config", ".", "logger", ";", "return", "config", ";", "}" ]
generate the config @param {Object} config - the given config @returns {Configuration} config
[ "generate", "the", "config" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/index.js#L380-L400
38,777
enmasseio/babble
lib/block/Decision.js
Decision
function Decision (arg1, arg2) { var decision, choices; if (!(this instanceof Decision)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof arg1 === 'function') { decision = arg1; choices = arg2; } else { decision = null; choices = arg1; } if (decision) { if (typeof decision !== 'function') { throw new TypeError('Parameter decision must be a function'); } } else { decision = function (message, context) { return message; } } if (choices && (typeof choices === 'function')) { throw new TypeError('Parameter choices must be an object'); } this.decision = decision; this.choices = {}; // append all choices if (choices) { var me = this; Object.keys(choices).forEach(function (id) { me.addChoice(id, choices[id]); }); } }
javascript
function Decision (arg1, arg2) { var decision, choices; if (!(this instanceof Decision)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (typeof arg1 === 'function') { decision = arg1; choices = arg2; } else { decision = null; choices = arg1; } if (decision) { if (typeof decision !== 'function') { throw new TypeError('Parameter decision must be a function'); } } else { decision = function (message, context) { return message; } } if (choices && (typeof choices === 'function')) { throw new TypeError('Parameter choices must be an object'); } this.decision = decision; this.choices = {}; // append all choices if (choices) { var me = this; Object.keys(choices).forEach(function (id) { me.addChoice(id, choices[id]); }); } }
[ "function", "Decision", "(", "arg1", ",", "arg2", ")", "{", "var", "decision", ",", "choices", ";", "if", "(", "!", "(", "this", "instanceof", "Decision", ")", ")", "{", "throw", "new", "SyntaxError", "(", "'Constructor must be called with the new operator'", ")", ";", "}", "if", "(", "typeof", "arg1", "===", "'function'", ")", "{", "decision", "=", "arg1", ";", "choices", "=", "arg2", ";", "}", "else", "{", "decision", "=", "null", ";", "choices", "=", "arg1", ";", "}", "if", "(", "decision", ")", "{", "if", "(", "typeof", "decision", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'Parameter decision must be a function'", ")", ";", "}", "}", "else", "{", "decision", "=", "function", "(", "message", ",", "context", ")", "{", "return", "message", ";", "}", "}", "if", "(", "choices", "&&", "(", "typeof", "choices", "===", "'function'", ")", ")", "{", "throw", "new", "TypeError", "(", "'Parameter choices must be an object'", ")", ";", "}", "this", ".", "decision", "=", "decision", ";", "this", ".", "choices", "=", "{", "}", ";", "// append all choices", "if", "(", "choices", ")", "{", "var", "me", "=", "this", ";", "Object", ".", "keys", "(", "choices", ")", ".", "forEach", "(", "function", "(", "id", ")", "{", "me", ".", "addChoice", "(", "id", ",", "choices", "[", "id", "]", ")", ";", "}", ")", ";", "}", "}" ]
extend Block with function then Decision A decision is made by executing the provided callback function, which returns a next control flow block. Syntax: new Decision(choices) new Decision(decision, choices) Where: {Function | Object} [decision] When a `decision` function is provided, the function is invoked as decision(message, context), where `message` is the output from the previous block in the chain, and `context` is an object where state can be stored during a conversation. The function must return the id for the next block in the control flow, which must be available in the provided `choices`. If `decision` is not provided, the next block will be mapped directly from the message. {Object.<String, Block>} choices A map with the possible next blocks in the flow The next block is selected by the id returned by the decision function. There is one special id for choices: 'default'. This id is called when either the decision function returns an id which does not match any of the available choices. @param arg1 @param arg2 @constructor @extends {Block}
[ "extend", "Block", "with", "function", "then", "Decision", "A", "decision", "is", "made", "by", "executing", "the", "provided", "callback", "function", "which", "returns", "a", "next", "control", "flow", "block", "." ]
6b7e84d7fb0df2d1129f0646b37a9d89d3da2539
https://github.com/enmasseio/babble/blob/6b7e84d7fb0df2d1129f0646b37a9d89d3da2539/lib/block/Decision.js#L46-L87
38,778
kant2002/crowdin-cli
api.js
function (projectName, files, params, callback) { if (callback === undefined) { callback = params; params = {}; } var filesInformation = {}; files.forEach(function (fileName) { var index = "files[" + fileName + "]"; filesInformation[index] = fs.createReadStream(fileName); }); return postApiCallWithFormData('project/' + projectName + '/add-file', extend(filesInformation, params), callback); }
javascript
function (projectName, files, params, callback) { if (callback === undefined) { callback = params; params = {}; } var filesInformation = {}; files.forEach(function (fileName) { var index = "files[" + fileName + "]"; filesInformation[index] = fs.createReadStream(fileName); }); return postApiCallWithFormData('project/' + projectName + '/add-file', extend(filesInformation, params), callback); }
[ "function", "(", "projectName", ",", "files", ",", "params", ",", "callback", ")", "{", "if", "(", "callback", "===", "undefined", ")", "{", "callback", "=", "params", ";", "params", "=", "{", "}", ";", "}", "var", "filesInformation", "=", "{", "}", ";", "files", ".", "forEach", "(", "function", "(", "fileName", ")", "{", "var", "index", "=", "\"files[\"", "+", "fileName", "+", "\"]\"", ";", "filesInformation", "[", "index", "]", "=", "fs", ".", "createReadStream", "(", "fileName", ")", ";", "}", ")", ";", "return", "postApiCallWithFormData", "(", "'project/'", "+", "projectName", "+", "'/add-file'", ",", "extend", "(", "filesInformation", ",", "params", ")", ",", "callback", ")", ";", "}" ]
Add new file to Crowdin project @param projectName {String} Should contain the project identifier @param files {Array} Files array that should be added to Crowdin project. Array keys should contain file names with path in Crowdin project. Note! 20 files max are allowed to upload per one time file transfer. @param params {Object} Information about uploaded files. @param callback {Function} Callback to call on function completition.
[ "Add", "new", "file", "to", "Crowdin", "project" ]
b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3
https://github.com/kant2002/crowdin-cli/blob/b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3/api.js#L132-L146
38,779
kant2002/crowdin-cli
api.js
function (projectName, fileNameOrStream, callback) { if (typeof fileNameOrStream === "string") { fileNameOrStream = fs.createReadStream(fileNameOrStream); } return postApiCallWithFormData('project/' + projectName + '/upload-glossary', { file: fileNameOrStream }, callback); }
javascript
function (projectName, fileNameOrStream, callback) { if (typeof fileNameOrStream === "string") { fileNameOrStream = fs.createReadStream(fileNameOrStream); } return postApiCallWithFormData('project/' + projectName + '/upload-glossary', { file: fileNameOrStream }, callback); }
[ "function", "(", "projectName", ",", "fileNameOrStream", ",", "callback", ")", "{", "if", "(", "typeof", "fileNameOrStream", "===", "\"string\"", ")", "{", "fileNameOrStream", "=", "fs", ".", "createReadStream", "(", "fileNameOrStream", ")", ";", "}", "return", "postApiCallWithFormData", "(", "'project/'", "+", "projectName", "+", "'/upload-glossary'", ",", "{", "file", ":", "fileNameOrStream", "}", ",", "callback", ")", ";", "}" ]
Upload your glossaries for Crowdin Project in TBX file format. @param projectName {String} Should contain the project identifier. @param fileNameOrStream {String} Name of the file to upload or stream which contains file to upload. @param callback {Function} Callback to call on function completition.
[ "Upload", "your", "glossaries", "for", "Crowdin", "Project", "in", "TBX", "file", "format", "." ]
b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3
https://github.com/kant2002/crowdin-cli/blob/b15df0715c4e6ae7d5447fd418af94dfe4dbb7a3/api.js#L298-L304
38,780
treojs/idb-request
src/index.js
handleError
function handleError(reject) { return (e) => { // prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873 if (typeof e.preventDefault === 'function') e.preventDefault() reject(e.target.error) } }
javascript
function handleError(reject) { return (e) => { // prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873 if (typeof e.preventDefault === 'function') e.preventDefault() reject(e.target.error) } }
[ "function", "handleError", "(", "reject", ")", "{", "return", "(", "e", ")", "=>", "{", "// prevent global error throw https://bugzilla.mozilla.org/show_bug.cgi?id=872873", "if", "(", "typeof", "e", ".", "preventDefault", "===", "'function'", ")", "e", ".", "preventDefault", "(", ")", "reject", "(", "e", ".", "target", ".", "error", ")", "}", "}" ]
Helper to handle errors and call `reject`. @param {Function} reject - from Promise constructor @return {Function}
[ "Helper", "to", "handle", "errors", "and", "call", "reject", "." ]
123794d051387c54fab1a9d4371554f0872f5d0b
https://github.com/treojs/idb-request/blob/123794d051387c54fab1a9d4371554f0872f5d0b/src/index.js#L98-L104
38,781
juttle/juttle-viz
src/views/text.js
function(newData, limit) { if ((this.buffer.length + newData.length) > options.limit) { this.buffer = this.buffer.concat(newData.slice(0, options.limit - this.buffer.length)); self._sendDisplayLimitReachedMessage(limit); } else { this.buffer = this.buffer.concat(newData); } }
javascript
function(newData, limit) { if ((this.buffer.length + newData.length) > options.limit) { this.buffer = this.buffer.concat(newData.slice(0, options.limit - this.buffer.length)); self._sendDisplayLimitReachedMessage(limit); } else { this.buffer = this.buffer.concat(newData); } }
[ "function", "(", "newData", ",", "limit", ")", "{", "if", "(", "(", "this", ".", "buffer", ".", "length", "+", "newData", ".", "length", ")", ">", "options", ".", "limit", ")", "{", "this", ".", "buffer", "=", "this", ".", "buffer", ".", "concat", "(", "newData", ".", "slice", "(", "0", ",", "options", ".", "limit", "-", "this", ".", "buffer", ".", "length", ")", ")", ";", "self", ".", "_sendDisplayLimitReachedMessage", "(", "limit", ")", ";", "}", "else", "{", "this", ".", "buffer", "=", "this", ".", "buffer", ".", "concat", "(", "newData", ")", ";", "}", "}" ]
Appends the new data to the buffer up to the current limit. Sends a message if limit is reached. @param {[type]} data [description] @return {[type]} [description]
[ "Appends", "the", "new", "data", "to", "the", "buffer", "up", "to", "the", "current", "limit", ".", "Sends", "a", "message", "if", "limit", "is", "reached", "." ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/views/text.js#L74-L82
38,782
dowjones/distribucache-redis-store
src/util.js
addReconnectOnReadonly
function addReconnectOnReadonly(cfg) { const noop = () => false; const userReconn = (typeof cfg.reconnectOnError === 'function') ? cfg.reconnectOnError : noop; cfg.reconnectOnError = err => { const shouldReconnect = (isReadonlyError(err) || userReconn(err)) ? 2 : false; if (shouldReconnect) console.warn(RECONNECT_WARNING); return shouldReconnect; }; }
javascript
function addReconnectOnReadonly(cfg) { const noop = () => false; const userReconn = (typeof cfg.reconnectOnError === 'function') ? cfg.reconnectOnError : noop; cfg.reconnectOnError = err => { const shouldReconnect = (isReadonlyError(err) || userReconn(err)) ? 2 : false; if (shouldReconnect) console.warn(RECONNECT_WARNING); return shouldReconnect; }; }
[ "function", "addReconnectOnReadonly", "(", "cfg", ")", "{", "const", "noop", "=", "(", ")", "=>", "false", ";", "const", "userReconn", "=", "(", "typeof", "cfg", ".", "reconnectOnError", "===", "'function'", ")", "?", "cfg", ".", "reconnectOnError", ":", "noop", ";", "cfg", ".", "reconnectOnError", "=", "err", "=>", "{", "const", "shouldReconnect", "=", "(", "isReadonlyError", "(", "err", ")", "||", "userReconn", "(", "err", ")", ")", "?", "2", ":", "false", ";", "if", "(", "shouldReconnect", ")", "console", ".", "warn", "(", "RECONNECT_WARNING", ")", ";", "return", "shouldReconnect", ";", "}", ";", "}" ]
This is necessary for the store to handle the case when another master is selected in ElastiCache, while connecting to the Primary Endpoint. @see https://github.com/dowjones/distribucache-redis-store/issues/3 @see https://github.com/luin/ioredis#reconnect-on-error
[ "This", "is", "necessary", "for", "the", "store", "to", "handle", "the", "case", "when", "another", "master", "is", "selected", "in", "ElastiCache", "while", "connecting", "to", "the", "Primary", "Endpoint", "." ]
25bd7b9cf790cd1f15920fc98b5732d7f2b8548f
https://github.com/dowjones/distribucache-redis-store/blob/25bd7b9cf790cd1f15920fc98b5732d7f2b8548f/src/util.js#L97-L105
38,783
doggan/three-debug-draw
index.js
_drawLine
function _drawLine(v0, v1, color) { var p = new Primitive(); p.vertices = [v0, v1]; p.color = toColor(color); renderer.addPrimitive(p); }
javascript
function _drawLine(v0, v1, color) { var p = new Primitive(); p.vertices = [v0, v1]; p.color = toColor(color); renderer.addPrimitive(p); }
[ "function", "_drawLine", "(", "v0", ",", "v1", ",", "color", ")", "{", "var", "p", "=", "new", "Primitive", "(", ")", ";", "p", ".", "vertices", "=", "[", "v0", ",", "v1", "]", ";", "p", ".", "color", "=", "toColor", "(", "color", ")", ";", "renderer", ".", "addPrimitive", "(", "p", ")", ";", "}" ]
Draws a single line from v0 to v1 with the given color. Each point is a THREE.Vector3 object.
[ "Draws", "a", "single", "line", "from", "v0", "to", "v1", "with", "the", "given", "color", "." ]
d5640ebb4e704a875348e8f88a8ee988ea041f14
https://github.com/doggan/three-debug-draw/blob/d5640ebb4e704a875348e8f88a8ee988ea041f14/index.js#L44-L51
38,784
doggan/three-debug-draw
index.js
_drawArrow
function _drawArrow(pStart, pEnd, arrowSize, color) { var p = new Primitive(); p.color = toColor(color); p.vertices.push(pStart); p.vertices.push(pEnd); var dir = new THREE.Vector3(); dir.subVectors(pEnd, pStart); dir.normalize(); var right = new THREE.Vector3(); var dot = dir.dot(UNIT_Y); if (dot > 0.99 || dot < -0.99) { right.crossVectors(dir, UNIT_X); } else { right.crossVectors(dir, UNIT_Y); } var top = new THREE.Vector3(); top.crossVectors(right, dir); dir.multiplyScalar(arrowSize); right.multiplyScalar(arrowSize); top.multiplyScalar(arrowSize); // Right slant. var tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.addVectors(pEnd, right).sub(dir)); // Left slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.subVectors(pEnd, right).sub(dir)); // Top slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.addVectors(pEnd, top).sub(dir)); // Bottom slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.subVectors(pEnd, top).sub(dir)); renderer.addPrimitive(p); }
javascript
function _drawArrow(pStart, pEnd, arrowSize, color) { var p = new Primitive(); p.color = toColor(color); p.vertices.push(pStart); p.vertices.push(pEnd); var dir = new THREE.Vector3(); dir.subVectors(pEnd, pStart); dir.normalize(); var right = new THREE.Vector3(); var dot = dir.dot(UNIT_Y); if (dot > 0.99 || dot < -0.99) { right.crossVectors(dir, UNIT_X); } else { right.crossVectors(dir, UNIT_Y); } var top = new THREE.Vector3(); top.crossVectors(right, dir); dir.multiplyScalar(arrowSize); right.multiplyScalar(arrowSize); top.multiplyScalar(arrowSize); // Right slant. var tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.addVectors(pEnd, right).sub(dir)); // Left slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.subVectors(pEnd, right).sub(dir)); // Top slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.addVectors(pEnd, top).sub(dir)); // Bottom slant. tmp = new THREE.Vector3(); p.vertices.push(pEnd); p.vertices.push(tmp.subVectors(pEnd, top).sub(dir)); renderer.addPrimitive(p); }
[ "function", "_drawArrow", "(", "pStart", ",", "pEnd", ",", "arrowSize", ",", "color", ")", "{", "var", "p", "=", "new", "Primitive", "(", ")", ";", "p", ".", "color", "=", "toColor", "(", "color", ")", ";", "p", ".", "vertices", ".", "push", "(", "pStart", ")", ";", "p", ".", "vertices", ".", "push", "(", "pEnd", ")", ";", "var", "dir", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "dir", ".", "subVectors", "(", "pEnd", ",", "pStart", ")", ";", "dir", ".", "normalize", "(", ")", ";", "var", "right", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "var", "dot", "=", "dir", ".", "dot", "(", "UNIT_Y", ")", ";", "if", "(", "dot", ">", "0.99", "||", "dot", "<", "-", "0.99", ")", "{", "right", ".", "crossVectors", "(", "dir", ",", "UNIT_X", ")", ";", "}", "else", "{", "right", ".", "crossVectors", "(", "dir", ",", "UNIT_Y", ")", ";", "}", "var", "top", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "top", ".", "crossVectors", "(", "right", ",", "dir", ")", ";", "dir", ".", "multiplyScalar", "(", "arrowSize", ")", ";", "right", ".", "multiplyScalar", "(", "arrowSize", ")", ";", "top", ".", "multiplyScalar", "(", "arrowSize", ")", ";", "// Right slant.", "var", "tmp", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "p", ".", "vertices", ".", "push", "(", "pEnd", ")", ";", "p", ".", "vertices", ".", "push", "(", "tmp", ".", "addVectors", "(", "pEnd", ",", "right", ")", ".", "sub", "(", "dir", ")", ")", ";", "// Left slant.", "tmp", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "p", ".", "vertices", ".", "push", "(", "pEnd", ")", ";", "p", ".", "vertices", ".", "push", "(", "tmp", ".", "subVectors", "(", "pEnd", ",", "right", ")", ".", "sub", "(", "dir", ")", ")", ";", "// Top slant.", "tmp", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "p", ".", "vertices", ".", "push", "(", "pEnd", ")", ";", "p", ".", "vertices", ".", "push", "(", "tmp", ".", "addVectors", "(", "pEnd", ",", "top", ")", ".", "sub", "(", "dir", ")", ")", ";", "// Bottom slant.", "tmp", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "p", ".", "vertices", ".", "push", "(", "pEnd", ")", ";", "p", ".", "vertices", ".", "push", "(", "tmp", ".", "subVectors", "(", "pEnd", ",", "top", ")", ".", "sub", "(", "dir", ")", ")", ";", "renderer", ".", "addPrimitive", "(", "p", ")", ";", "}" ]
Draws an arrow pointing from pStart to pEnd. Specify the size of the arrow with arrowSize.
[ "Draws", "an", "arrow", "pointing", "from", "pStart", "to", "pEnd", ".", "Specify", "the", "size", "of", "the", "arrow", "with", "arrowSize", "." ]
d5640ebb4e704a875348e8f88a8ee988ea041f14
https://github.com/doggan/three-debug-draw/blob/d5640ebb4e704a875348e8f88a8ee988ea041f14/index.js#L76-L123
38,785
doggan/three-debug-draw
index.js
_drawSphere
function _drawSphere(pos, r, color) { var p = new Primitive(); p.color = toColor(color); // Decreasing these angles will increase complexity of sphere. var dtheta = 35; var dphi = 35; for (var theta = -90; theta <= (90 - dtheta); theta += dtheta) { for (var phi = 0; phi <= (360 - dphi); phi += dphi) { p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD), pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD), pos.z + r * Math.sin(theta * DEG_TO_RAD) )); p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD), pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD), pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD) )); p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD), pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD), pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD) )); if ((theta > -90) && (theta < 90)) { p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD), pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD), pos.z + r * Math.sin(theta * DEG_TO_RAD) )); } } } renderer.addPrimitive(p); }
javascript
function _drawSphere(pos, r, color) { var p = new Primitive(); p.color = toColor(color); // Decreasing these angles will increase complexity of sphere. var dtheta = 35; var dphi = 35; for (var theta = -90; theta <= (90 - dtheta); theta += dtheta) { for (var phi = 0; phi <= (360 - dphi); phi += dphi) { p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD), pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD), pos.z + r * Math.sin(theta * DEG_TO_RAD) )); p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos(phi * DEG_TO_RAD), pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin(phi * DEG_TO_RAD), pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD) )); p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD), pos.y + r * Math.cos((theta + dtheta) * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD), pos.z + r * Math.sin((theta + dtheta) * DEG_TO_RAD) )); if ((theta > -90) && (theta < 90)) { p.vertices.push(new THREE.Vector3( pos.x + r * Math.cos(theta * DEG_TO_RAD) * Math.cos((phi + dphi) * DEG_TO_RAD), pos.y + r * Math.cos(theta * DEG_TO_RAD) * Math.sin((phi + dphi) * DEG_TO_RAD), pos.z + r * Math.sin(theta * DEG_TO_RAD) )); } } } renderer.addPrimitive(p); }
[ "function", "_drawSphere", "(", "pos", ",", "r", ",", "color", ")", "{", "var", "p", "=", "new", "Primitive", "(", ")", ";", "p", ".", "color", "=", "toColor", "(", "color", ")", ";", "// Decreasing these angles will increase complexity of sphere.", "var", "dtheta", "=", "35", ";", "var", "dphi", "=", "35", ";", "for", "(", "var", "theta", "=", "-", "90", ";", "theta", "<=", "(", "90", "-", "dtheta", ")", ";", "theta", "+=", "dtheta", ")", "{", "for", "(", "var", "phi", "=", "0", ";", "phi", "<=", "(", "360", "-", "dphi", ")", ";", "phi", "+=", "dphi", ")", "{", "p", ".", "vertices", ".", "push", "(", "new", "THREE", ".", "Vector3", "(", "pos", ".", "x", "+", "r", "*", "Math", ".", "cos", "(", "theta", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "cos", "(", "phi", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "y", "+", "r", "*", "Math", ".", "cos", "(", "theta", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "sin", "(", "phi", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "z", "+", "r", "*", "Math", ".", "sin", "(", "theta", "*", "DEG_TO_RAD", ")", ")", ")", ";", "p", ".", "vertices", ".", "push", "(", "new", "THREE", ".", "Vector3", "(", "pos", ".", "x", "+", "r", "*", "Math", ".", "cos", "(", "(", "theta", "+", "dtheta", ")", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "cos", "(", "phi", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "y", "+", "r", "*", "Math", ".", "cos", "(", "(", "theta", "+", "dtheta", ")", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "sin", "(", "phi", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "z", "+", "r", "*", "Math", ".", "sin", "(", "(", "theta", "+", "dtheta", ")", "*", "DEG_TO_RAD", ")", ")", ")", ";", "p", ".", "vertices", ".", "push", "(", "new", "THREE", ".", "Vector3", "(", "pos", ".", "x", "+", "r", "*", "Math", ".", "cos", "(", "(", "theta", "+", "dtheta", ")", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "cos", "(", "(", "phi", "+", "dphi", ")", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "y", "+", "r", "*", "Math", ".", "cos", "(", "(", "theta", "+", "dtheta", ")", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "sin", "(", "(", "phi", "+", "dphi", ")", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "z", "+", "r", "*", "Math", ".", "sin", "(", "(", "theta", "+", "dtheta", ")", "*", "DEG_TO_RAD", ")", ")", ")", ";", "if", "(", "(", "theta", ">", "-", "90", ")", "&&", "(", "theta", "<", "90", ")", ")", "{", "p", ".", "vertices", ".", "push", "(", "new", "THREE", ".", "Vector3", "(", "pos", ".", "x", "+", "r", "*", "Math", ".", "cos", "(", "theta", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "cos", "(", "(", "phi", "+", "dphi", ")", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "y", "+", "r", "*", "Math", ".", "cos", "(", "theta", "*", "DEG_TO_RAD", ")", "*", "Math", ".", "sin", "(", "(", "phi", "+", "dphi", ")", "*", "DEG_TO_RAD", ")", ",", "pos", ".", "z", "+", "r", "*", "Math", ".", "sin", "(", "theta", "*", "DEG_TO_RAD", ")", ")", ")", ";", "}", "}", "}", "renderer", ".", "addPrimitive", "(", "p", ")", ";", "}" ]
Draw a sphere at pos with radius r.
[ "Draw", "a", "sphere", "at", "pos", "with", "radius", "r", "." ]
d5640ebb4e704a875348e8f88a8ee988ea041f14
https://github.com/doggan/three-debug-draw/blob/d5640ebb4e704a875348e8f88a8ee988ea041f14/index.js#L175-L213
38,786
lethexa/lethexa-motionpredict
lethexa-motionpredict.js
function(position, velocity, dt) { return mf.add(position, mf.mulScalar(velocity, dt)); }
javascript
function(position, velocity, dt) { return mf.add(position, mf.mulScalar(velocity, dt)); }
[ "function", "(", "position", ",", "velocity", ",", "dt", ")", "{", "return", "mf", ".", "add", "(", "position", ",", "mf", ".", "mulScalar", "(", "velocity", ",", "dt", ")", ")", ";", "}" ]
calculates the new position by speed and delta-time. @method getPositionByVeloAndTime @param position {Vector3d} The old position. @param velocity {Velocity} The velocity. @param dt {Number} The delta-time. @return {Vector3d} The new position. @for motionpredict
[ "calculates", "the", "new", "position", "by", "speed", "and", "delta", "-", "time", "." ]
84095c2cca246c02d9931d501a10959f46f54cfa
https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L21-L23
38,787
lethexa/lethexa-motionpredict
lethexa-motionpredict.js
function( p, q ) { var wurzel = Math.sqrt((p * p / 4) - q); var vorwurzel = (-p / 2); var result = []; if( wurzel > 0 ) { result = [vorwurzel + wurzel, vorwurzel - wurzel]; } else if( wurzel === 0 ) { result = [vorwurzel]; } return result; }
javascript
function( p, q ) { var wurzel = Math.sqrt((p * p / 4) - q); var vorwurzel = (-p / 2); var result = []; if( wurzel > 0 ) { result = [vorwurzel + wurzel, vorwurzel - wurzel]; } else if( wurzel === 0 ) { result = [vorwurzel]; } return result; }
[ "function", "(", "p", ",", "q", ")", "{", "var", "wurzel", "=", "Math", ".", "sqrt", "(", "(", "p", "*", "p", "/", "4", ")", "-", "q", ")", ";", "var", "vorwurzel", "=", "(", "-", "p", "/", "2", ")", ";", "var", "result", "=", "[", "]", ";", "if", "(", "wurzel", ">", "0", ")", "{", "result", "=", "[", "vorwurzel", "+", "wurzel", ",", "vorwurzel", "-", "wurzel", "]", ";", "}", "else", "if", "(", "wurzel", "===", "0", ")", "{", "result", "=", "[", "vorwurzel", "]", ";", "}", "return", "result", ";", "}" ]
Solves the quadratic equation for p and q. @method quadEquation @param p {Number} The parameter p. @param q {Number} The parameter q. @return {Array} The result with zero, one or two solutions. @for motionpredict
[ "Solves", "the", "quadratic", "equation", "for", "p", "and", "q", "." ]
84095c2cca246c02d9931d501a10959f46f54cfa
https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L34-L45
38,788
lethexa/lethexa-motionpredict
lethexa-motionpredict.js
function(myPos, myVelo, targetPos, targetVelo) { var relTargetPos = mf.sub(targetPos, myPos); var a = mf.lengthSquared(targetVelo) - myVelo * myVelo; var b = 2.0 * mf.dot(targetVelo, relTargetPos); var c = mf.lengthSquared(relTargetPos); if( a === 0 ) { if( b !== 0 ) { var time = -c / b; if( time > 0.0 ) return time; } } else { // P und Q berechnen... var p = b / a; var q = c / a; // Quadratische Gleichung lösen... var times = this.quadEquation(p, q); if( times.length === 0 ) return []; if( times.length === 2 ) { var icptTime = Math.min(times[0], times[1]); if( icptTime < 0.0 ) { icptTime = Math.max(times[0], times[1]); } return icptTime; } else if( times.length === 1 ) { if( times[0] >= 0.0 ) { return times[0]; } } } return undefined; }
javascript
function(myPos, myVelo, targetPos, targetVelo) { var relTargetPos = mf.sub(targetPos, myPos); var a = mf.lengthSquared(targetVelo) - myVelo * myVelo; var b = 2.0 * mf.dot(targetVelo, relTargetPos); var c = mf.lengthSquared(relTargetPos); if( a === 0 ) { if( b !== 0 ) { var time = -c / b; if( time > 0.0 ) return time; } } else { // P und Q berechnen... var p = b / a; var q = c / a; // Quadratische Gleichung lösen... var times = this.quadEquation(p, q); if( times.length === 0 ) return []; if( times.length === 2 ) { var icptTime = Math.min(times[0], times[1]); if( icptTime < 0.0 ) { icptTime = Math.max(times[0], times[1]); } return icptTime; } else if( times.length === 1 ) { if( times[0] >= 0.0 ) { return times[0]; } } } return undefined; }
[ "function", "(", "myPos", ",", "myVelo", ",", "targetPos", ",", "targetVelo", ")", "{", "var", "relTargetPos", "=", "mf", ".", "sub", "(", "targetPos", ",", "myPos", ")", ";", "var", "a", "=", "mf", ".", "lengthSquared", "(", "targetVelo", ")", "-", "myVelo", "*", "myVelo", ";", "var", "b", "=", "2.0", "*", "mf", ".", "dot", "(", "targetVelo", ",", "relTargetPos", ")", ";", "var", "c", "=", "mf", ".", "lengthSquared", "(", "relTargetPos", ")", ";", "if", "(", "a", "===", "0", ")", "{", "if", "(", "b", "!==", "0", ")", "{", "var", "time", "=", "-", "c", "/", "b", ";", "if", "(", "time", ">", "0.0", ")", "return", "time", ";", "}", "}", "else", "{", "// P und Q berechnen...", "var", "p", "=", "b", "/", "a", ";", "var", "q", "=", "c", "/", "a", ";", "// Quadratische Gleichung lösen...", "var", "times", "=", "this", ".", "quadEquation", "(", "p", ",", "q", ")", ";", "if", "(", "times", ".", "length", "===", "0", ")", "return", "[", "]", ";", "if", "(", "times", ".", "length", "===", "2", ")", "{", "var", "icptTime", "=", "Math", ".", "min", "(", "times", "[", "0", "]", ",", "times", "[", "1", "]", ")", ";", "if", "(", "icptTime", "<", "0.0", ")", "{", "icptTime", "=", "Math", ".", "max", "(", "times", "[", "0", "]", ",", "times", "[", "1", "]", ")", ";", "}", "return", "icptTime", ";", "}", "else", "if", "(", "times", ".", "length", "===", "1", ")", "{", "if", "(", "times", "[", "0", "]", ">=", "0.0", ")", "{", "return", "times", "[", "0", "]", ";", "}", "}", "}", "return", "undefined", ";", "}" ]
Calculates the intercepttime to the target at a given speed. @method calcInterceptTime @param myPos {Vector3d} The position of the interceptor. @param myVelo {Number} The velocity at which the target should be intercepted. @param targetPos {Vector3d} The position of the target. @param targetVelo {Vector3d} The velocity and direction in which the target is moving. @return {Number} The time from now at which the target is reached. @for motionpredict
[ "Calculates", "the", "intercepttime", "to", "the", "target", "at", "a", "given", "speed", "." ]
84095c2cca246c02d9931d501a10959f46f54cfa
https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L115-L152
38,789
lethexa/lethexa-motionpredict
lethexa-motionpredict.js
function(myPos, myVelo, targetPos, targetVelo) { var ticpt = this.calcInterceptTime(myPos, myVelo, targetPos, targetVelo); if(ticpt === undefined) return undefined; return this.getPositionByVeloAndTime(targetPos, targetVelo, ticpt); }
javascript
function(myPos, myVelo, targetPos, targetVelo) { var ticpt = this.calcInterceptTime(myPos, myVelo, targetPos, targetVelo); if(ticpt === undefined) return undefined; return this.getPositionByVeloAndTime(targetPos, targetVelo, ticpt); }
[ "function", "(", "myPos", ",", "myVelo", ",", "targetPos", ",", "targetVelo", ")", "{", "var", "ticpt", "=", "this", ".", "calcInterceptTime", "(", "myPos", ",", "myVelo", ",", "targetPos", ",", "targetVelo", ")", ";", "if", "(", "ticpt", "===", "undefined", ")", "return", "undefined", ";", "return", "this", ".", "getPositionByVeloAndTime", "(", "targetPos", ",", "targetVelo", ",", "ticpt", ")", ";", "}" ]
Calculates the intercept-position of the target. @method calcInterceptPosition @param myPos {Vector3d} The position of the interceptor. @param myVelo {Number} The velocity at which the target should be intercepted. @param targetPos {Vector3d} The position of the target. @param targetVelo {Vector3d} The velocity and direction in which the target is moving. @return {Vector3d} The position at which the target is reached. @for motionpredict
[ "Calculates", "the", "intercept", "-", "position", "of", "the", "target", "." ]
84095c2cca246c02d9931d501a10959f46f54cfa
https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L165-L170
38,790
lethexa/lethexa-motionpredict
lethexa-motionpredict.js
function(myPos, myVelo, targetPos, targetVelo ) { var distance = Math.sqrt(mf.lengthSquared(mf.sub(targetPos, myPos))); var approachSpeed = this.calcApproachSpeed(myPos, myVelo, targetPos, targetVelo); if( approachSpeed > 0.0 ) { return distance / approachSpeed; } else { return undefined; } }
javascript
function(myPos, myVelo, targetPos, targetVelo ) { var distance = Math.sqrt(mf.lengthSquared(mf.sub(targetPos, myPos))); var approachSpeed = this.calcApproachSpeed(myPos, myVelo, targetPos, targetVelo); if( approachSpeed > 0.0 ) { return distance / approachSpeed; } else { return undefined; } }
[ "function", "(", "myPos", ",", "myVelo", ",", "targetPos", ",", "targetVelo", ")", "{", "var", "distance", "=", "Math", ".", "sqrt", "(", "mf", ".", "lengthSquared", "(", "mf", ".", "sub", "(", "targetPos", ",", "myPos", ")", ")", ")", ";", "var", "approachSpeed", "=", "this", ".", "calcApproachSpeed", "(", "myPos", ",", "myVelo", ",", "targetPos", ",", "targetVelo", ")", ";", "if", "(", "approachSpeed", ">", "0.0", ")", "{", "return", "distance", "/", "approachSpeed", ";", "}", "else", "{", "return", "undefined", ";", "}", "}" ]
Calculates the arrivaltime of the target to my position. @method calcArrivalTime @param myPos {Vector3d} The position of me. @param myVelo {Vector3d} The velocity of me. @param targetPos {Vector3d} The position of the target. @param targetVelo {Vector3d} The velocity and direction in which the target is moving. @return {Number} The time in which the target has reached me or undefined if not reachable. @for motionpredict
[ "Calculates", "the", "arrivaltime", "of", "the", "target", "to", "my", "position", "." ]
84095c2cca246c02d9931d501a10959f46f54cfa
https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L183-L192
38,791
lethexa/lethexa-motionpredict
lethexa-motionpredict.js
function(myPos, myVelo, targetPos, targetVelo) { var posDiff = mf.sub(targetPos, myPos); var veloDiff = mf.sub(targetVelo, myVelo); var approachSpeed = mf.dot(posDiff, veloDiff); var posDiffLength = Math.sqrt(mf.lengthSquared(posDiff)); if( posDiffLength <= 0.0 ) return 0.0; return -approachSpeed / posDiffLength; }
javascript
function(myPos, myVelo, targetPos, targetVelo) { var posDiff = mf.sub(targetPos, myPos); var veloDiff = mf.sub(targetVelo, myVelo); var approachSpeed = mf.dot(posDiff, veloDiff); var posDiffLength = Math.sqrt(mf.lengthSquared(posDiff)); if( posDiffLength <= 0.0 ) return 0.0; return -approachSpeed / posDiffLength; }
[ "function", "(", "myPos", ",", "myVelo", ",", "targetPos", ",", "targetVelo", ")", "{", "var", "posDiff", "=", "mf", ".", "sub", "(", "targetPos", ",", "myPos", ")", ";", "var", "veloDiff", "=", "mf", ".", "sub", "(", "targetVelo", ",", "myVelo", ")", ";", "var", "approachSpeed", "=", "mf", ".", "dot", "(", "posDiff", ",", "veloDiff", ")", ";", "var", "posDiffLength", "=", "Math", ".", "sqrt", "(", "mf", ".", "lengthSquared", "(", "posDiff", ")", ")", ";", "if", "(", "posDiffLength", "<=", "0.0", ")", "return", "0.0", ";", "return", "-", "approachSpeed", "/", "posDiffLength", ";", "}" ]
Calculates the approachspeed of the target to my position. @method calcApproachSpeed @param myPos {Vector3d} The position of me. @param myVelo {Vector3d} The velocity of me. @param targetPos {Vector3d} The position of the target. @param targetVelo {Vector3d} The velocity and direction in which the target is moving. @return {Number} The speed at which the target is approaching. @for motionpredict
[ "Calculates", "the", "approachspeed", "of", "the", "target", "to", "my", "position", "." ]
84095c2cca246c02d9931d501a10959f46f54cfa
https://github.com/lethexa/lethexa-motionpredict/blob/84095c2cca246c02d9931d501a10959f46f54cfa/lethexa-motionpredict.js#L205-L213
38,792
pattern-lab/patternengine-node-underscore
lib/engine_underscore.js
function (partialString) { var edgeQuotesMatcher = /^["']|["']$/g; var partialIDWithQuotes = partialString.replace(this.findPartialsRE, '$1'); var partialID = partialIDWithQuotes.replace(edgeQuotesMatcher, ''); return partialID; }
javascript
function (partialString) { var edgeQuotesMatcher = /^["']|["']$/g; var partialIDWithQuotes = partialString.replace(this.findPartialsRE, '$1'); var partialID = partialIDWithQuotes.replace(edgeQuotesMatcher, ''); return partialID; }
[ "function", "(", "partialString", ")", "{", "var", "edgeQuotesMatcher", "=", "/", "^[\"']|[\"']$", "/", "g", ";", "var", "partialIDWithQuotes", "=", "partialString", ".", "replace", "(", "this", ".", "findPartialsRE", ",", "'$1'", ")", ";", "var", "partialID", "=", "partialIDWithQuotes", ".", "replace", "(", "edgeQuotesMatcher", ",", "''", ")", ";", "return", "partialID", ";", "}" ]
given a pattern, and a partial string, tease out the "pattern key" and return it.
[ "given", "a", "pattern", "and", "a", "partial", "string", "tease", "out", "the", "pattern", "key", "and", "return", "it", "." ]
79ba1b4697f25cebf797bd46c5d9dc84937b4deb
https://github.com/pattern-lab/patternengine-node-underscore/blob/79ba1b4697f25cebf797bd46c5d9dc84937b4deb/lib/engine_underscore.js#L170-L176
38,793
avigoldman/fuse-email
lib/transports/transport.js
formatInboundRecipients
function formatInboundRecipients(recipients) { return _.map(recipients, (recipient) => { if (_.isString(recipient)) { return { email: recipient, name: '', }; } else { return { email: recipient.address || '', name: recipient.name || '' } } }); }
javascript
function formatInboundRecipients(recipients) { return _.map(recipients, (recipient) => { if (_.isString(recipient)) { return { email: recipient, name: '', }; } else { return { email: recipient.address || '', name: recipient.name || '' } } }); }
[ "function", "formatInboundRecipients", "(", "recipients", ")", "{", "return", "_", ".", "map", "(", "recipients", ",", "(", "recipient", ")", "=>", "{", "if", "(", "_", ".", "isString", "(", "recipient", ")", ")", "{", "return", "{", "email", ":", "recipient", ",", "name", ":", "''", ",", "}", ";", "}", "else", "{", "return", "{", "email", ":", "recipient", ".", "address", "||", "''", ",", "name", ":", "recipient", ".", "name", "||", "''", "}", "}", "}", ")", ";", "}" ]
takes an array of emails and formats them to the fuse recipient pattern @param {string[]} recipients @param {object[]} recipients
[ "takes", "an", "array", "of", "emails", "and", "formats", "them", "to", "the", "fuse", "recipient", "pattern" ]
ebb44934d7be8ce95d2aff30c5a94505a06e34eb
https://github.com/avigoldman/fuse-email/blob/ebb44934d7be8ce95d2aff30c5a94505a06e34eb/lib/transports/transport.js#L200-L215
38,794
binaryoung/laravel-elixir-vue-loader
index.js
function (webpackConfig, paths) { var defaultWebpackConfig = { output: { filename: paths.output.name, }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, ] }, }; if (fs.existsSync('webpack.config.js')) { var customWebpackConfig = require('./../../webpack.config.js'); defaultWebpackConfig = _.extend(defaultWebpackConfig, customWebpackConfig); } webpackConfig = _.extend(defaultWebpackConfig, webpackConfig); if (!_.contains(webpackConfig.module.loaders, {test: /\.vue$/, loader: 'vue'})) { webpackConfig.module.loaders.push({ test: /\.vue$/, loader: 'vue' }); } if (config.sourcemaps) { webpackConfig = _.defaults( webpackConfig, {devtool: '#source-map'} ); } if (config.production) { var currPlugins = _.isArray(webpackConfig.plugins) ? webpackConfig.plugins : []; webpackConfig.plugins = currPlugins.concat([new UglifyJsPlugin({sourceMap: false})]); } return webpackConfig; }
javascript
function (webpackConfig, paths) { var defaultWebpackConfig = { output: { filename: paths.output.name, }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, ] }, }; if (fs.existsSync('webpack.config.js')) { var customWebpackConfig = require('./../../webpack.config.js'); defaultWebpackConfig = _.extend(defaultWebpackConfig, customWebpackConfig); } webpackConfig = _.extend(defaultWebpackConfig, webpackConfig); if (!_.contains(webpackConfig.module.loaders, {test: /\.vue$/, loader: 'vue'})) { webpackConfig.module.loaders.push({ test: /\.vue$/, loader: 'vue' }); } if (config.sourcemaps) { webpackConfig = _.defaults( webpackConfig, {devtool: '#source-map'} ); } if (config.production) { var currPlugins = _.isArray(webpackConfig.plugins) ? webpackConfig.plugins : []; webpackConfig.plugins = currPlugins.concat([new UglifyJsPlugin({sourceMap: false})]); } return webpackConfig; }
[ "function", "(", "webpackConfig", ",", "paths", ")", "{", "var", "defaultWebpackConfig", "=", "{", "output", ":", "{", "filename", ":", "paths", ".", "output", ".", "name", ",", "}", ",", "module", ":", "{", "loaders", ":", "[", "{", "test", ":", "/", "\\.vue$", "/", ",", "loader", ":", "'vue'", "}", ",", "]", "}", ",", "}", ";", "if", "(", "fs", ".", "existsSync", "(", "'webpack.config.js'", ")", ")", "{", "var", "customWebpackConfig", "=", "require", "(", "'./../../webpack.config.js'", ")", ";", "defaultWebpackConfig", "=", "_", ".", "extend", "(", "defaultWebpackConfig", ",", "customWebpackConfig", ")", ";", "}", "webpackConfig", "=", "_", ".", "extend", "(", "defaultWebpackConfig", ",", "webpackConfig", ")", ";", "if", "(", "!", "_", ".", "contains", "(", "webpackConfig", ".", "module", ".", "loaders", ",", "{", "test", ":", "/", "\\.vue$", "/", ",", "loader", ":", "'vue'", "}", ")", ")", "{", "webpackConfig", ".", "module", ".", "loaders", ".", "push", "(", "{", "test", ":", "/", "\\.vue$", "/", ",", "loader", ":", "'vue'", "}", ")", ";", "}", "if", "(", "config", ".", "sourcemaps", ")", "{", "webpackConfig", "=", "_", ".", "defaults", "(", "webpackConfig", ",", "{", "devtool", ":", "'#source-map'", "}", ")", ";", "}", "if", "(", "config", ".", "production", ")", "{", "var", "currPlugins", "=", "_", ".", "isArray", "(", "webpackConfig", ".", "plugins", ")", "?", "webpackConfig", ".", "plugins", ":", "[", "]", ";", "webpackConfig", ".", "plugins", "=", "currPlugins", ".", "concat", "(", "[", "new", "UglifyJsPlugin", "(", "{", "sourceMap", ":", "false", "}", ")", "]", ")", ";", "}", "return", "webpackConfig", ";", "}" ]
Handle webpack config such as sourcemaps and minification or user's cunstom webpack config. @param {object} options @return {object}
[ "Handle", "webpack", "config", "such", "as", "sourcemaps", "and", "minification", "or", "user", "s", "cunstom", "webpack", "config", "." ]
06ddb9c010f59917f0b9997df2fe9a26c444ab24
https://github.com/binaryoung/laravel-elixir-vue-loader/blob/06ddb9c010f59917f0b9997df2fe9a26c444ab24/index.js#L63-L106
38,795
brockfanning/docpad-plugin-lunr
out/lunrdoc.js
function(index, placeholder) { if (typeof this.config.indexes[index] === 'undefined') { console.log('LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.'); return; } placeholder = placeholder || 'Search terms'; var scriptElements = ''; var dataFilename = this.config.indexes[index].indexFilename; var scripts = ['lunr.min.js', dataFilename, 'lunr-ui.min.js']; for (var i in scripts) { scriptElements += '<script src="/lunr/' + scripts[i] + '" type="text/javascript"></script>'; } return '<input type="text" class="search-bar" id="lunr-input" placeholder="' + placeholder + '" />' + '<input type="hidden" id="lunr-hidden" />' + scriptElements; }
javascript
function(index, placeholder) { if (typeof this.config.indexes[index] === 'undefined') { console.log('LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.'); return; } placeholder = placeholder || 'Search terms'; var scriptElements = ''; var dataFilename = this.config.indexes[index].indexFilename; var scripts = ['lunr.min.js', dataFilename, 'lunr-ui.min.js']; for (var i in scripts) { scriptElements += '<script src="/lunr/' + scripts[i] + '" type="text/javascript"></script>'; } return '<input type="text" class="search-bar" id="lunr-input" placeholder="' + placeholder + '" />' + '<input type="hidden" id="lunr-hidden" />' + scriptElements; }
[ "function", "(", "index", ",", "placeholder", ")", "{", "if", "(", "typeof", "this", ".", "config", ".", "indexes", "[", "index", "]", "===", "'undefined'", ")", "{", "console", ".", "log", "(", "'LUNR: getLunrSearchPage will not work unless you specify a valid index from plugins.lunr.indexes in your Docpad configuration file.'", ")", ";", "return", ";", "}", "placeholder", "=", "placeholder", "||", "'Search terms'", ";", "var", "scriptElements", "=", "''", ";", "var", "dataFilename", "=", "this", ".", "config", ".", "indexes", "[", "index", "]", ".", "indexFilename", ";", "var", "scripts", "=", "[", "'lunr.min.js'", ",", "dataFilename", ",", "'lunr-ui.min.js'", "]", ";", "for", "(", "var", "i", "in", "scripts", ")", "{", "scriptElements", "+=", "'<script src=\"/lunr/'", "+", "scripts", "[", "i", "]", "+", "'\" type=\"text/javascript\"></script>'", ";", "}", "return", "'<input type=\"text\" class=\"search-bar\" id=\"lunr-input\" placeholder=\"'", "+", "placeholder", "+", "'\" />'", "+", "'<input type=\"hidden\" id=\"lunr-hidden\" />'", "+", "scriptElements", ";", "}" ]
some helper functions we'll provide to the template
[ "some", "helper", "functions", "we", "ll", "provide", "to", "the", "template" ]
d5c23dda9e1ca5e0edbf87c26ef9035ddc840c50
https://github.com/brockfanning/docpad-plugin-lunr/blob/d5c23dda9e1ca5e0edbf87c26ef9035ddc840c50/out/lunrdoc.js#L218-L234
38,796
dy/slidy
picker.js
handle2dkeys
function handle2dkeys (keys, value, step, min, max) { //up and right - increase by one if (keys[38]) { value[1] = inc(value[1], plainify(step, 1), 1); } if (keys[39]) { value[0] = inc(value[0], plainify(step, 0), 1); } if (keys[40]) { value[1] = inc(value[1], plainify(step, 1), -1); } if (keys[37]) { value[0] = inc(value[0], plainify(step, 0), -1); } //meta var coordIdx = 1; if (keys[18] || keys[91] || keys[17] || keys[16]) coordIdx = 0; //home - min if (keys[36]) { value[coordIdx] = min[coordIdx]; } //end - max if (keys[35]) { value[coordIdx] = max[coordIdx]; } //pageup if (keys[33]) { value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), PAGE); } //pagedown if (keys[34]) { value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), -PAGE); } return value; }
javascript
function handle2dkeys (keys, value, step, min, max) { //up and right - increase by one if (keys[38]) { value[1] = inc(value[1], plainify(step, 1), 1); } if (keys[39]) { value[0] = inc(value[0], plainify(step, 0), 1); } if (keys[40]) { value[1] = inc(value[1], plainify(step, 1), -1); } if (keys[37]) { value[0] = inc(value[0], plainify(step, 0), -1); } //meta var coordIdx = 1; if (keys[18] || keys[91] || keys[17] || keys[16]) coordIdx = 0; //home - min if (keys[36]) { value[coordIdx] = min[coordIdx]; } //end - max if (keys[35]) { value[coordIdx] = max[coordIdx]; } //pageup if (keys[33]) { value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), PAGE); } //pagedown if (keys[34]) { value[coordIdx] = inc(value[coordIdx], plainify(step, coordIdx), -PAGE); } return value; }
[ "function", "handle2dkeys", "(", "keys", ",", "value", ",", "step", ",", "min", ",", "max", ")", "{", "//up and right - increase by one", "if", "(", "keys", "[", "38", "]", ")", "{", "value", "[", "1", "]", "=", "inc", "(", "value", "[", "1", "]", ",", "plainify", "(", "step", ",", "1", ")", ",", "1", ")", ";", "}", "if", "(", "keys", "[", "39", "]", ")", "{", "value", "[", "0", "]", "=", "inc", "(", "value", "[", "0", "]", ",", "plainify", "(", "step", ",", "0", ")", ",", "1", ")", ";", "}", "if", "(", "keys", "[", "40", "]", ")", "{", "value", "[", "1", "]", "=", "inc", "(", "value", "[", "1", "]", ",", "plainify", "(", "step", ",", "1", ")", ",", "-", "1", ")", ";", "}", "if", "(", "keys", "[", "37", "]", ")", "{", "value", "[", "0", "]", "=", "inc", "(", "value", "[", "0", "]", ",", "plainify", "(", "step", ",", "0", ")", ",", "-", "1", ")", ";", "}", "//meta", "var", "coordIdx", "=", "1", ";", "if", "(", "keys", "[", "18", "]", "||", "keys", "[", "91", "]", "||", "keys", "[", "17", "]", "||", "keys", "[", "16", "]", ")", "coordIdx", "=", "0", ";", "//home - min", "if", "(", "keys", "[", "36", "]", ")", "{", "value", "[", "coordIdx", "]", "=", "min", "[", "coordIdx", "]", ";", "}", "//end - max", "if", "(", "keys", "[", "35", "]", ")", "{", "value", "[", "coordIdx", "]", "=", "max", "[", "coordIdx", "]", ";", "}", "//pageup", "if", "(", "keys", "[", "33", "]", ")", "{", "value", "[", "coordIdx", "]", "=", "inc", "(", "value", "[", "coordIdx", "]", ",", "plainify", "(", "step", ",", "coordIdx", ")", ",", "PAGE", ")", ";", "}", "//pagedown", "if", "(", "keys", "[", "34", "]", ")", "{", "value", "[", "coordIdx", "]", "=", "inc", "(", "value", "[", "coordIdx", "]", ",", "plainify", "(", "step", ",", "coordIdx", ")", ",", "-", "PAGE", ")", ";", "}", "return", "value", ";", "}" ]
Apply pressed keys on the 2d value
[ "Apply", "pressed", "keys", "on", "the", "2d", "value" ]
18c57d07face0ea8f297060434fb1c13b33cd888
https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/picker.js#L714-L755
38,797
dy/slidy
picker.js
handle1dkeys
function handle1dkeys (keys, value, step, min, max) { step = step || 1; //up and right - increase by one if (keys[38] || keys[39]) { value = inc(value, step, 1); } //down and left - decrease by one if (keys[40] || keys[37]) { value = inc(value, step, -1); } //home - min if (keys[36]) { value = min; } //end - max if (keys[35]) { value = max; } //pageup if (keys[33]) { value = inc(value, step, PAGE); } //pagedown if (keys[34]) { value = inc(value, step, -PAGE); } return value; }
javascript
function handle1dkeys (keys, value, step, min, max) { step = step || 1; //up and right - increase by one if (keys[38] || keys[39]) { value = inc(value, step, 1); } //down and left - decrease by one if (keys[40] || keys[37]) { value = inc(value, step, -1); } //home - min if (keys[36]) { value = min; } //end - max if (keys[35]) { value = max; } //pageup if (keys[33]) { value = inc(value, step, PAGE); } //pagedown if (keys[34]) { value = inc(value, step, -PAGE); } return value; }
[ "function", "handle1dkeys", "(", "keys", ",", "value", ",", "step", ",", "min", ",", "max", ")", "{", "step", "=", "step", "||", "1", ";", "//up and right - increase by one", "if", "(", "keys", "[", "38", "]", "||", "keys", "[", "39", "]", ")", "{", "value", "=", "inc", "(", "value", ",", "step", ",", "1", ")", ";", "}", "//down and left - decrease by one", "if", "(", "keys", "[", "40", "]", "||", "keys", "[", "37", "]", ")", "{", "value", "=", "inc", "(", "value", ",", "step", ",", "-", "1", ")", ";", "}", "//home - min", "if", "(", "keys", "[", "36", "]", ")", "{", "value", "=", "min", ";", "}", "//end - max", "if", "(", "keys", "[", "35", "]", ")", "{", "value", "=", "max", ";", "}", "//pageup", "if", "(", "keys", "[", "33", "]", ")", "{", "value", "=", "inc", "(", "value", ",", "step", ",", "PAGE", ")", ";", "}", "//pagedown", "if", "(", "keys", "[", "34", "]", ")", "{", "value", "=", "inc", "(", "value", ",", "step", ",", "-", "PAGE", ")", ";", "}", "return", "value", ";", "}" ]
Apply pressed keys on the 1d value
[ "Apply", "pressed", "keys", "on", "the", "1d", "value" ]
18c57d07face0ea8f297060434fb1c13b33cd888
https://github.com/dy/slidy/blob/18c57d07face0ea8f297060434fb1c13b33cd888/picker.js#L759-L793
38,798
juttle/juttle-viz
src/lib/generators/event-markers.js
function(el, options) { // default options for the line var defaults = require('../utils/default-options')(); // if we don't pass options, just // make it an empty object if (typeof options === 'undefined' ) { options = {}; } options = _.defaults(options, defaults); this.width = options.width; this.height = options.height; this.margin = options.margin; this.useMarkdown = options.useMarkdown; this.el = el; this._data = []; this.selection = d3.select(el).append('g') .attr('class', 'markerSeries'); if (options.clipId) { this.selection.attr('clip-path', 'url(#' + options.clipId + ')'); } this.xScale = function() { throw new Error('X scale not set'); }; this.xfield = options.xfield; this.xfieldFormat = options.xfieldFormat; this.title = options.title; this.text = options.text; this.type = options.type; // XXX wire this up this.duration = options.duration || 250; this.currentDatapoint = null; this.draw_range = null; }
javascript
function(el, options) { // default options for the line var defaults = require('../utils/default-options')(); // if we don't pass options, just // make it an empty object if (typeof options === 'undefined' ) { options = {}; } options = _.defaults(options, defaults); this.width = options.width; this.height = options.height; this.margin = options.margin; this.useMarkdown = options.useMarkdown; this.el = el; this._data = []; this.selection = d3.select(el).append('g') .attr('class', 'markerSeries'); if (options.clipId) { this.selection.attr('clip-path', 'url(#' + options.clipId + ')'); } this.xScale = function() { throw new Error('X scale not set'); }; this.xfield = options.xfield; this.xfieldFormat = options.xfieldFormat; this.title = options.title; this.text = options.text; this.type = options.type; // XXX wire this up this.duration = options.duration || 250; this.currentDatapoint = null; this.draw_range = null; }
[ "function", "(", "el", ",", "options", ")", "{", "// default options for the line", "var", "defaults", "=", "require", "(", "'../utils/default-options'", ")", "(", ")", ";", "// if we don't pass options, just", "// make it an empty object", "if", "(", "typeof", "options", "===", "'undefined'", ")", "{", "options", "=", "{", "}", ";", "}", "options", "=", "_", ".", "defaults", "(", "options", ",", "defaults", ")", ";", "this", ".", "width", "=", "options", ".", "width", ";", "this", ".", "height", "=", "options", ".", "height", ";", "this", ".", "margin", "=", "options", ".", "margin", ";", "this", ".", "useMarkdown", "=", "options", ".", "useMarkdown", ";", "this", ".", "el", "=", "el", ";", "this", ".", "_data", "=", "[", "]", ";", "this", ".", "selection", "=", "d3", ".", "select", "(", "el", ")", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'class'", ",", "'markerSeries'", ")", ";", "if", "(", "options", ".", "clipId", ")", "{", "this", ".", "selection", ".", "attr", "(", "'clip-path'", ",", "'url(#'", "+", "options", ".", "clipId", "+", "')'", ")", ";", "}", "this", ".", "xScale", "=", "function", "(", ")", "{", "throw", "new", "Error", "(", "'X scale not set'", ")", ";", "}", ";", "this", ".", "xfield", "=", "options", ".", "xfield", ";", "this", ".", "xfieldFormat", "=", "options", ".", "xfieldFormat", ";", "this", ".", "title", "=", "options", ".", "title", ";", "this", ".", "text", "=", "options", ".", "text", ";", "this", ".", "type", "=", "options", ".", "type", ";", "// XXX wire this up", "this", ".", "duration", "=", "options", ".", "duration", "||", "250", ";", "this", ".", "currentDatapoint", "=", "null", ";", "this", ".", "draw_range", "=", "null", ";", "}" ]
event marker constructor
[ "event", "marker", "constructor" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/generators/event-markers.js#L11-L54
38,799
aspectron/iris-translator
lib/i18n.js
scanFolders
function scanFolders(rootFolderPath, folders, folderFileExtensions, callback) { var result = []; console.log('Scanning:: Folders', folders); console.log('Scanning:: Root folder path', rootFolderPath); var fileExtensions = self.fileExtensions.slice(); scanFolder(); function scanFolder() { var folder = folders.shift(); if (folder === undefined) { // console.log('Scanning:: Finished with result', result); return callback(null, result); } if(folderFileExtensions.length){ fileExtensions = folderFileExtensions.shift(); } //var path = rootFolderPath + '/' + folder; var path = rootFolderPath + folder; console.log('Scanning:: Full path to folder', path, fileExtensions); fs.readdir(path, function (err, list) { if (err) { console.error("Error scanning folder: ", path); return scanFolder(); } var files = []; for (var i = 0; i < list.length; i++) { if (acceptFile(path, list[i], fileExtensions)) { //files.push((folder.length ? folder + '/' : folder) + list[i]); files.push(path + '/' + list[i]); } } result = result.concat(files); scanFolder(); }); } }
javascript
function scanFolders(rootFolderPath, folders, folderFileExtensions, callback) { var result = []; console.log('Scanning:: Folders', folders); console.log('Scanning:: Root folder path', rootFolderPath); var fileExtensions = self.fileExtensions.slice(); scanFolder(); function scanFolder() { var folder = folders.shift(); if (folder === undefined) { // console.log('Scanning:: Finished with result', result); return callback(null, result); } if(folderFileExtensions.length){ fileExtensions = folderFileExtensions.shift(); } //var path = rootFolderPath + '/' + folder; var path = rootFolderPath + folder; console.log('Scanning:: Full path to folder', path, fileExtensions); fs.readdir(path, function (err, list) { if (err) { console.error("Error scanning folder: ", path); return scanFolder(); } var files = []; for (var i = 0; i < list.length; i++) { if (acceptFile(path, list[i], fileExtensions)) { //files.push((folder.length ? folder + '/' : folder) + list[i]); files.push(path + '/' + list[i]); } } result = result.concat(files); scanFolder(); }); } }
[ "function", "scanFolders", "(", "rootFolderPath", ",", "folders", ",", "folderFileExtensions", ",", "callback", ")", "{", "var", "result", "=", "[", "]", ";", "console", ".", "log", "(", "'Scanning:: Folders'", ",", "folders", ")", ";", "console", ".", "log", "(", "'Scanning:: Root folder path'", ",", "rootFolderPath", ")", ";", "var", "fileExtensions", "=", "self", ".", "fileExtensions", ".", "slice", "(", ")", ";", "scanFolder", "(", ")", ";", "function", "scanFolder", "(", ")", "{", "var", "folder", "=", "folders", ".", "shift", "(", ")", ";", "if", "(", "folder", "===", "undefined", ")", "{", "// console.log('Scanning:: Finished with result', result);", "return", "callback", "(", "null", ",", "result", ")", ";", "}", "if", "(", "folderFileExtensions", ".", "length", ")", "{", "fileExtensions", "=", "folderFileExtensions", ".", "shift", "(", ")", ";", "}", "//var path = rootFolderPath + '/' + folder;", "var", "path", "=", "rootFolderPath", "+", "folder", ";", "console", ".", "log", "(", "'Scanning:: Full path to folder'", ",", "path", ",", "fileExtensions", ")", ";", "fs", ".", "readdir", "(", "path", ",", "function", "(", "err", ",", "list", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "\"Error scanning folder: \"", ",", "path", ")", ";", "return", "scanFolder", "(", ")", ";", "}", "var", "files", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "if", "(", "acceptFile", "(", "path", ",", "list", "[", "i", "]", ",", "fileExtensions", ")", ")", "{", "//files.push((folder.length ? folder + '/' : folder) + list[i]);", "files", ".", "push", "(", "path", "+", "'/'", "+", "list", "[", "i", "]", ")", ";", "}", "}", "result", "=", "result", ".", "concat", "(", "files", ")", ";", "scanFolder", "(", ")", ";", "}", ")", ";", "}", "}" ]
Private functions Gets files from folders @param rootFolderPath @param folders {Array} @param callback @return {Array} array of files
[ "Private", "functions", "Gets", "files", "from", "folders" ]
3e09348f08274a0608e6b5b7f8c2b726639b31ba
https://github.com/aspectron/iris-translator/blob/3e09348f08274a0608e6b5b7f8c2b726639b31ba/lib/i18n.js#L342-L384