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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
33,300 | wachunga/omega | r.js | function (fileContents, fileName) {
//Uglify's ast generation removes comments, so just convert to ast,
//then back to source code to get rid of comments.
return uglify.uglify.gen_code(uglify.parser.parse(fileContents), true);
} | javascript | function (fileContents, fileName) {
//Uglify's ast generation removes comments, so just convert to ast,
//then back to source code to get rid of comments.
return uglify.uglify.gen_code(uglify.parser.parse(fileContents), true);
} | [
"function",
"(",
"fileContents",
",",
"fileName",
")",
"{",
"//Uglify's ast generation removes comments, so just convert to ast,",
"//then back to source code to get rid of comments.",
"return",
"uglify",
".",
"uglify",
".",
"gen_code",
"(",
"uglify",
".",
"parser",
".",
"par... | Removes the comments from a string.
@param {String} fileContents
@param {String} fileName mostly used for informative reasons if an error.
@returns {String} a string of JS with comments removed. | [
"Removes",
"the",
"comments",
"from",
"a",
"string",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L8262-L8266 | |
33,301 | wachunga/omega | r.js | makeWriteFile | function makeWriteFile(anonDefRegExp, namespaceWithDot, layer) {
function writeFile(name, contents) {
logger.trace('Saving plugin-optimized file: ' + name);
file.saveUtf8File(name, contents);
}
writeFile.asModule = function (moduleName, fileName, contents) {
writeFile(fileName,
build.toTransport(anonDefRegExp, namespaceWithDot, moduleName, fileName, contents, layer));
};
return writeFile;
} | javascript | function makeWriteFile(anonDefRegExp, namespaceWithDot, layer) {
function writeFile(name, contents) {
logger.trace('Saving plugin-optimized file: ' + name);
file.saveUtf8File(name, contents);
}
writeFile.asModule = function (moduleName, fileName, contents) {
writeFile(fileName,
build.toTransport(anonDefRegExp, namespaceWithDot, moduleName, fileName, contents, layer));
};
return writeFile;
} | [
"function",
"makeWriteFile",
"(",
"anonDefRegExp",
",",
"namespaceWithDot",
",",
"layer",
")",
"{",
"function",
"writeFile",
"(",
"name",
",",
"contents",
")",
"{",
"logger",
".",
"trace",
"(",
"'Saving plugin-optimized file: '",
"+",
"name",
")",
";",
"file",
... | Method used by plugin writeFile calls, defined up here to avoid jslint warning about "making a function in a loop". | [
"Method",
"used",
"by",
"plugin",
"writeFile",
"calls",
"defined",
"up",
"here",
"to",
"avoid",
"jslint",
"warning",
"about",
"making",
"a",
"function",
"in",
"a",
"loop",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L8410-L8422 |
33,302 | wachunga/omega | r.js | setBaseUrl | function setBaseUrl(fileName) {
//Use the file name's directory as the baseUrl if available.
dir = fileName.replace(/\\/g, '/');
if (dir.indexOf('/') !== -1) {
dir = dir.split('/');
dir.pop();
dir = dir.join('/');
exec("require({baseUrl: '" + dir + "'});");
}
} | javascript | function setBaseUrl(fileName) {
//Use the file name's directory as the baseUrl if available.
dir = fileName.replace(/\\/g, '/');
if (dir.indexOf('/') !== -1) {
dir = dir.split('/');
dir.pop();
dir = dir.join('/');
exec("require({baseUrl: '" + dir + "'});");
}
} | [
"function",
"setBaseUrl",
"(",
"fileName",
")",
"{",
"//Use the file name's directory as the baseUrl if available.",
"dir",
"=",
"fileName",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"if",
"(",
"dir",
".",
"indexOf",
"(",
"'/'",
")",
... | Sets the default baseUrl for requirejs to be directory of top level
script. | [
"Sets",
"the",
"default",
"baseUrl",
"for",
"requirejs",
"to",
"be",
"directory",
"of",
"top",
"level",
"script",
"."
] | c5ecf4ed058d2198065f17c3313b0884e8efa6a9 | https://github.com/wachunga/omega/blob/c5ecf4ed058d2198065f17c3313b0884e8efa6a9/r.js#L9406-L9415 |
33,303 | cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | validateCompoundWithType | function validateCompoundWithType(attribute, values) {
for(var i in values) {
var value = values[i];
if(typeof(value) !== 'object') {
errors.push([attribute + '-' + i, "not-an-object"]);
} else if(! value.type) {
errors.push([attribute + '-' + i, "missing-type"]);
} else if(! value.value) { // empty values are not allowed.
errors.push([attribute + '-' + i, "missing-value"]);
}
}
} | javascript | function validateCompoundWithType(attribute, values) {
for(var i in values) {
var value = values[i];
if(typeof(value) !== 'object') {
errors.push([attribute + '-' + i, "not-an-object"]);
} else if(! value.type) {
errors.push([attribute + '-' + i, "missing-type"]);
} else if(! value.value) { // empty values are not allowed.
errors.push([attribute + '-' + i, "missing-value"]);
}
}
} | [
"function",
"validateCompoundWithType",
"(",
"attribute",
",",
"values",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"values",
")",
"{",
"var",
"value",
"=",
"values",
"[",
"i",
"]",
";",
"if",
"(",
"typeof",
"(",
"value",
")",
"!==",
"'object'",
")",
"{... | make sure compound fields have their type & value set (to prevent mistakes such as vcard.addAttribute('email', 'foo@bar.baz') | [
"make",
"sure",
"compound",
"fields",
"have",
"their",
"type",
"&",
"value",
"set",
"(",
"to",
"prevent",
"mistakes",
"such",
"as",
"vcard",
".",
"addAttribute",
"(",
"email",
"foo"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L150-L161 |
33,304 | cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | function(key, value) {
console.log('add attribute', key, value);
if(! value) {
return;
}
if(VCard.multivaluedKeys[key]) {
if(this[key]) {
console.log('multivalued push');
this[key].push(value)
} else {
console.log('multivalued set');
this.setAttribute(key, [value]);
}
} else {
this.setAttribute(key, value);
}
} | javascript | function(key, value) {
console.log('add attribute', key, value);
if(! value) {
return;
}
if(VCard.multivaluedKeys[key]) {
if(this[key]) {
console.log('multivalued push');
this[key].push(value)
} else {
console.log('multivalued set');
this.setAttribute(key, [value]);
}
} else {
this.setAttribute(key, value);
}
} | [
"function",
"(",
"key",
",",
"value",
")",
"{",
"console",
".",
"log",
"(",
"'add attribute'",
",",
"key",
",",
"value",
")",
";",
"if",
"(",
"!",
"value",
")",
"{",
"return",
";",
"}",
"if",
"(",
"VCard",
".",
"multivaluedKeys",
"[",
"key",
"]",
... | Set the given attribute to the given value. If the given attribute's key has cardinality > 1, instead of overwriting the current value, an additional value is appended. | [
"Set",
"the",
"given",
"attribute",
"to",
"the",
"given",
"value",
".",
"If",
"the",
"given",
"attribute",
"s",
"key",
"has",
"cardinality",
">",
"1",
"instead",
"of",
"overwriting",
"the",
"current",
"value",
"an",
"additional",
"value",
"is",
"appended",
... | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L206-L222 | |
33,305 | cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | function(aDate, bDate, addSub) {
if(typeof(addSub) == 'undefined') { addSub = true };
if(! aDate) { return bDate; }
if(! bDate) { return aDate; }
var a = Number(aDate);
var b = Number(bDate);
var c = addSub ? a + b : a - b;
return new Date(c);
} | javascript | function(aDate, bDate, addSub) {
if(typeof(addSub) == 'undefined') { addSub = true };
if(! aDate) { return bDate; }
if(! bDate) { return aDate; }
var a = Number(aDate);
var b = Number(bDate);
var c = addSub ? a + b : a - b;
return new Date(c);
} | [
"function",
"(",
"aDate",
",",
"bDate",
",",
"addSub",
")",
"{",
"if",
"(",
"typeof",
"(",
"addSub",
")",
"==",
"'undefined'",
")",
"{",
"addSub",
"=",
"true",
"}",
";",
"if",
"(",
"!",
"aDate",
")",
"{",
"return",
"bDate",
";",
"}",
"if",
"(",
... | add two dates. if addSub is false, substract instead of add. | [
"add",
"two",
"dates",
".",
"if",
"addSub",
"is",
"false",
"substract",
"instead",
"of",
"add",
"."
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L629-L637 | |
33,306 | cozy/cozy-emails | client/plugins/vcard/js/vcardjs-0.3.js | function(str){
str = (str || "").toString();
str = str.replace(/\=(?:\r?\n|$)/g, "");
var str2 = "";
for(var i=0, len = str.length; i<len; i++){
chr = str.charAt(i);
if(chr == "=" && (hex = str.substr(i+1, 2)) && /[\da-fA-F]{2}/.test(hex)){
str2 += String.fromCharCode(parseInt(hex,16));
i+=2;
continue;
}
str2 += chr;
}
return str2;
} | javascript | function(str){
str = (str || "").toString();
str = str.replace(/\=(?:\r?\n|$)/g, "");
var str2 = "";
for(var i=0, len = str.length; i<len; i++){
chr = str.charAt(i);
if(chr == "=" && (hex = str.substr(i+1, 2)) && /[\da-fA-F]{2}/.test(hex)){
str2 += String.fromCharCode(parseInt(hex,16));
i+=2;
continue;
}
str2 += chr;
}
return str2;
} | [
"function",
"(",
"str",
")",
"{",
"str",
"=",
"(",
"str",
"||",
"\"\"",
")",
".",
"toString",
"(",
")",
";",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\=(?:\\r?\\n|$)",
"/",
"g",
",",
"\"\"",
")",
";",
"var",
"str2",
"=",
"\"\"",
";",
"for... | Quoted Printable Parser
Parses quoted-printable strings, which sometimes appear in
vCard 2.1 files (usually the address field)
Code adapted from:
https://github.com/andris9/mimelib | [
"Quoted",
"Printable",
"Parser"
] | e31b4e724e6310a3e0451ab1703857287aef1f6f | https://github.com/cozy/cozy-emails/blob/e31b4e724e6310a3e0451ab1703857287aef1f6f/client/plugins/vcard/js/vcardjs-0.3.js#L793-L807 | |
33,307 | mangalam-research/wed | lib/wed/polyfills/firstElementChild_etc.js | addParentNodeInterfaceToPrototype | function addParentNodeInterfaceToPrototype(p) {
Object.defineProperty(p, "firstElementChild", {
get: function firstElementChild() {
var el = this.firstChild;
while (el && el.nodeType !== 1) {
el = el.nextSibling;
}
return el;
},
});
Object.defineProperty(p, "lastElementChild", {
get: function lastElementChild() {
var el = this.lastChild;
while (el && el.nodeType !== 1) {
el = el.previousSibling;
}
return el;
},
});
Object.defineProperty(p, "childElementCount", {
get: function childElementCount() {
var el = this.firstElementChild;
var count = 0;
while (el) {
count++;
el = el.nextElementSibling;
}
return count;
},
});
} | javascript | function addParentNodeInterfaceToPrototype(p) {
Object.defineProperty(p, "firstElementChild", {
get: function firstElementChild() {
var el = this.firstChild;
while (el && el.nodeType !== 1) {
el = el.nextSibling;
}
return el;
},
});
Object.defineProperty(p, "lastElementChild", {
get: function lastElementChild() {
var el = this.lastChild;
while (el && el.nodeType !== 1) {
el = el.previousSibling;
}
return el;
},
});
Object.defineProperty(p, "childElementCount", {
get: function childElementCount() {
var el = this.firstElementChild;
var count = 0;
while (el) {
count++;
el = el.nextElementSibling;
}
return count;
},
});
} | [
"function",
"addParentNodeInterfaceToPrototype",
"(",
"p",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"p",
",",
"\"firstElementChild\"",
",",
"{",
"get",
":",
"function",
"firstElementChild",
"(",
")",
"{",
"var",
"el",
"=",
"this",
".",
"firstChild",
";"... | This polyfill has been tested with IE 11 and 10. It has not been tested with older versions of IE because we do not support them. | [
"This",
"polyfill",
"has",
"been",
"tested",
"with",
"IE",
"11",
"and",
"10",
".",
"It",
"has",
"not",
"been",
"tested",
"with",
"older",
"versions",
"of",
"IE",
"because",
"we",
"do",
"not",
"support",
"them",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/polyfills/firstElementChild_etc.js#L28-L60 |
33,308 | mangalam-research/wed | lib/wed/polyfills/firstElementChild_etc.js | addChildrenToPrototype | function addChildrenToPrototype(p) {
// Unfortunately, it is not possible to emulate the liveness of the
// HTMLCollection this property *should* provide.
Object.defineProperty(p, "children", {
get: function children() {
var ret = [];
var el = this.firstElementChild;
while (el) {
ret.push(el);
el = el.nextElementSibling;
}
return ret;
},
});
} | javascript | function addChildrenToPrototype(p) {
// Unfortunately, it is not possible to emulate the liveness of the
// HTMLCollection this property *should* provide.
Object.defineProperty(p, "children", {
get: function children() {
var ret = [];
var el = this.firstElementChild;
while (el) {
ret.push(el);
el = el.nextElementSibling;
}
return ret;
},
});
} | [
"function",
"addChildrenToPrototype",
"(",
"p",
")",
"{",
"// Unfortunately, it is not possible to emulate the liveness of the",
"// HTMLCollection this property *should* provide.",
"Object",
".",
"defineProperty",
"(",
"p",
",",
"\"children\"",
",",
"{",
"get",
":",
"function"... | We separate children from the rest because it is possible to have firstElementChild, etc defined and yet not have children defined. Go figure... | [
"We",
"separate",
"children",
"from",
"the",
"rest",
"because",
"it",
"is",
"possible",
"to",
"have",
"firstElementChild",
"etc",
"defined",
"and",
"yet",
"not",
"have",
"children",
"defined",
".",
"Go",
"figure",
"..."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/polyfills/firstElementChild_etc.js#L65-L80 |
33,309 | mangalam-research/wed | misc/util.js | captureConfigObject | function captureConfigObject(config) {
let captured;
const require = {};
require.config = function _config(conf) {
captured = conf;
};
let wedConfig;
// eslint-disable-next-line no-unused-vars
function define(name, obj) {
if (wedConfig !== undefined) {
throw new Error("more than one define");
}
switch (arguments.length) {
case 0:
throw new Error("no arguments to the define!");
case 1:
if (typeof name !== "object") {
throw new Error("if define has only one argument, it must be an " +
"object");
}
wedConfig = name;
break;
default:
throw new Error("captureConfigObject is designed to capture a " +
"maximum of two arguments.");
}
}
eval(config); // eslint-disable-line no-eval
return {
requireConfig: captured,
wedConfig,
};
} | javascript | function captureConfigObject(config) {
let captured;
const require = {};
require.config = function _config(conf) {
captured = conf;
};
let wedConfig;
// eslint-disable-next-line no-unused-vars
function define(name, obj) {
if (wedConfig !== undefined) {
throw new Error("more than one define");
}
switch (arguments.length) {
case 0:
throw new Error("no arguments to the define!");
case 1:
if (typeof name !== "object") {
throw new Error("if define has only one argument, it must be an " +
"object");
}
wedConfig = name;
break;
default:
throw new Error("captureConfigObject is designed to capture a " +
"maximum of two arguments.");
}
}
eval(config); // eslint-disable-line no-eval
return {
requireConfig: captured,
wedConfig,
};
} | [
"function",
"captureConfigObject",
"(",
"config",
")",
"{",
"let",
"captured",
";",
"const",
"require",
"=",
"{",
"}",
";",
"require",
".",
"config",
"=",
"function",
"_config",
"(",
"conf",
")",
"{",
"captured",
"=",
"conf",
";",
"}",
";",
"let",
"wed... | This function defines ``require.config`` so that evaluating our
configuration file will capture the configuration passed to
``require.config``.
@param {String} config The text of the configuration file.
@returns {Object} The configuration object. | [
"This",
"function",
"defines",
"require",
".",
"config",
"so",
"that",
"evaluating",
"our",
"configuration",
"file",
"will",
"capture",
"the",
"configuration",
"passed",
"to",
"require",
".",
"config",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/misc/util.js#L14-L50 |
33,310 | mangalam-research/wed | lib/wed/onerror.js | _reset | function _reset() {
terminating = false;
if (termination_timeout) {
termination_window.clearTimeout(termination_timeout);
termination_timeout = undefined;
}
$modal.off();
$modal.modal("hide");
$modal.remove();
} | javascript | function _reset() {
terminating = false;
if (termination_timeout) {
termination_window.clearTimeout(termination_timeout);
termination_timeout = undefined;
}
$modal.off();
$modal.modal("hide");
$modal.remove();
} | [
"function",
"_reset",
"(",
")",
"{",
"terminating",
"=",
"false",
";",
"if",
"(",
"termination_timeout",
")",
"{",
"termination_window",
".",
"clearTimeout",
"(",
"termination_timeout",
")",
";",
"termination_timeout",
"=",
"undefined",
";",
"}",
"$modal",
".",
... | Normally onerror will be reset by reloading but when testing with mocha we don't want reloading, so we export this function. | [
"Normally",
"onerror",
"will",
"be",
"reset",
"by",
"reloading",
"but",
"when",
"testing",
"with",
"mocha",
"we",
"don",
"t",
"want",
"reloading",
"so",
"we",
"export",
"this",
"function",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/onerror.js#L44-L53 |
33,311 | mangalam-research/wed | lib/wed/onerror.js | showModal | function showModal(saveMessages, errorMessage) {
$(document.body).append($modal);
$modal.find(".save-messages")[0].innerHTML = saveMessages;
$modal.find(".error-message")[0].textContent = errorMessage;
$modal.on("hide.bs.modal.modal", function hidden() {
$modal.remove();
window.location.reload();
});
$modal.modal();
} | javascript | function showModal(saveMessages, errorMessage) {
$(document.body).append($modal);
$modal.find(".save-messages")[0].innerHTML = saveMessages;
$modal.find(".error-message")[0].textContent = errorMessage;
$modal.on("hide.bs.modal.modal", function hidden() {
$modal.remove();
window.location.reload();
});
$modal.modal();
} | [
"function",
"showModal",
"(",
"saveMessages",
",",
"errorMessage",
")",
"{",
"$",
"(",
"document",
".",
"body",
")",
".",
"append",
"(",
"$modal",
")",
";",
"$modal",
".",
"find",
"(",
"\".save-messages\"",
")",
"[",
"0",
"]",
".",
"innerHTML",
"=",
"s... | So that we can issue clearTimeout elsewhere. | [
"So",
"that",
"we",
"can",
"issue",
"clearTimeout",
"elsewhere",
"."
] | f0c6d23492ac97afa730098df46e18fdeb647ef5 | https://github.com/mangalam-research/wed/blob/f0c6d23492ac97afa730098df46e18fdeb647ef5/lib/wed/onerror.js#L78-L87 |
33,312 | jonschlinkert/lazy-cache | index.js | lazyCache | function lazyCache(requireFn) {
var cache = {};
return function proxy(name, alias) {
var key = alias;
// camel-case the module `name` if `alias` is not defined
if (typeof key !== 'string') {
key = camelcase(name);
}
// create a getter to lazily invoke the module the first time it's called
function getter() {
return cache[key] || (cache[key] = requireFn(name));
}
// trip the getter if `process.env.UNLAZY` is defined
if (unlazy(process.env)) {
getter();
}
set(proxy, key, getter);
return getter;
};
} | javascript | function lazyCache(requireFn) {
var cache = {};
return function proxy(name, alias) {
var key = alias;
// camel-case the module `name` if `alias` is not defined
if (typeof key !== 'string') {
key = camelcase(name);
}
// create a getter to lazily invoke the module the first time it's called
function getter() {
return cache[key] || (cache[key] = requireFn(name));
}
// trip the getter if `process.env.UNLAZY` is defined
if (unlazy(process.env)) {
getter();
}
set(proxy, key, getter);
return getter;
};
} | [
"function",
"lazyCache",
"(",
"requireFn",
")",
"{",
"var",
"cache",
"=",
"{",
"}",
";",
"return",
"function",
"proxy",
"(",
"name",
",",
"alias",
")",
"{",
"var",
"key",
"=",
"alias",
";",
"// camel-case the module `name` if `alias` is not defined",
"if",
"("... | Cache results of the first function call to ensure only calling once.
```js
var utils = require('lazy-cache')(require);
// cache the call to `require('ansi-yellow')`
utils('ansi-yellow', 'yellow');
// use `ansi-yellow`
console.log(utils.yellow('this is yellow'));
```
@param {Function} `fn` Function that will be called only once.
@return {Function} Function that can be called to get the cached function
@api public | [
"Cache",
"results",
"of",
"the",
"first",
"function",
"call",
"to",
"ensure",
"only",
"calling",
"once",
"."
] | 2f15129f05f2d69cbc2cb7ba52e383fc31b9fc2c | https://github.com/jonschlinkert/lazy-cache/blob/2f15129f05f2d69cbc2cb7ba52e383fc31b9fc2c/index.js#L21-L45 |
33,313 | temando/remark-mermaid | src/utils.js | getDestinationDir | function getDestinationDir(vFile) {
if (vFile.data.destinationDir) {
return vFile.data.destinationDir;
}
return vFile.dirname;
} | javascript | function getDestinationDir(vFile) {
if (vFile.data.destinationDir) {
return vFile.data.destinationDir;
}
return vFile.dirname;
} | [
"function",
"getDestinationDir",
"(",
"vFile",
")",
"{",
"if",
"(",
"vFile",
".",
"data",
".",
"destinationDir",
")",
"{",
"return",
"vFile",
".",
"data",
".",
"destinationDir",
";",
"}",
"return",
"vFile",
".",
"dirname",
";",
"}"
] | Returns the destination for the SVG to be rendered at, explicity defined
using `vFile.data.destinationDir`, or falling back to the file's current
directory.
@param {vFile} vFile
@return {string} | [
"Returns",
"the",
"destination",
"for",
"the",
"SVG",
"to",
"be",
"rendered",
"at",
"explicity",
"defined",
"using",
"vFile",
".",
"data",
".",
"destinationDir",
"or",
"falling",
"back",
"to",
"the",
"file",
"s",
"current",
"directory",
"."
] | 3c0aaa8e90ff8ca0d043a9648c651683c0867ae3 | https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/utils.js#L64-L70 |
33,314 | IonicaBizau/parse-url | lib/index.js | parseUrl | function parseUrl(url, normalize = false) {
if (typeof url !== "string" || !url.trim()) {
throw new Error("Invalid url.")
}
if (normalize) {
if (typeof normalize !== "object") {
normalize = {
stripFragment: false
}
}
url = normalizeUrl(url, normalize)
}
const parsed = parsePath(url)
return parsed;
} | javascript | function parseUrl(url, normalize = false) {
if (typeof url !== "string" || !url.trim()) {
throw new Error("Invalid url.")
}
if (normalize) {
if (typeof normalize !== "object") {
normalize = {
stripFragment: false
}
}
url = normalizeUrl(url, normalize)
}
const parsed = parsePath(url)
return parsed;
} | [
"function",
"parseUrl",
"(",
"url",
",",
"normalize",
"=",
"false",
")",
"{",
"if",
"(",
"typeof",
"url",
"!==",
"\"string\"",
"||",
"!",
"url",
".",
"trim",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Invalid url.\"",
")",
"}",
"if",
"(",
... | parseUrl
Parses the input url.
**Note**: This *throws* if invalid urls are provided.
@name parseUrl
@function
@param {String} url The input url.
@param {Boolean|Object} normalize Wheter to normalize the url or not.
Default is `false`. If `true`, the url will
be normalized. If an object, it will be the
options object sent to [`normalize-url`](https://github.com/sindresorhus/normalize-url).
For SSH urls, normalize won't work.
@return {Object} An object containing the following fields:
- `protocols` (Array): An array with the url protocols (usually it has one element).
- `protocol` (String): The first protocol, `"ssh"` (if the url is a ssh url) or `"file"`.
- `port` (null|Number): The domain port.
- `resource` (String): The url domain (including subdomains).
- `user` (String): The authentication user (usually for ssh urls).
- `pathname` (String): The url pathname.
- `hash` (String): The url hash.
- `search` (String): The url querystring value.
- `href` (String): The input url.
- `query` (Object): The url querystring, parsed as object. | [
"parseUrl",
"Parses",
"the",
"input",
"url",
"."
] | 0be4cd98d7ad1b82a006e1edd7dbb3bde56a7537 | https://github.com/IonicaBizau/parse-url/blob/0be4cd98d7ad1b82a006e1edd7dbb3bde56a7537/lib/index.js#L35-L49 |
33,315 | Pamblam/jSQL | jSQL.js | function(query, data, successCallback, failureCallback) {
if(typeof successCallback != "function") successCallback = function(){};
if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };
var i, l, remaining;
if(!Array.isArray(data[0])) data = [data];
remaining = data.length;
var innerSuccessCallback = function(tx, rs) {
var i, l, output = [];
remaining = remaining - 1;
if (!remaining) {
for (i = 0, l = rs.rows.length; i < l; i = i + 1){
var j = rs.rows.item(i).json;
//j = JSON.parse(j);
output.push(j);
}
successCallback(output);
}
};
self.db.transaction(function (tx) {
for (i = 0, l = data.length; i < l; i = i + 1) {
tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
}
});
} | javascript | function(query, data, successCallback, failureCallback) {
if(typeof successCallback != "function") successCallback = function(){};
if(typeof failureCallback != "function") failureCallback = function(){ return _throw(new jSQL_Error("0054")); };
var i, l, remaining;
if(!Array.isArray(data[0])) data = [data];
remaining = data.length;
var innerSuccessCallback = function(tx, rs) {
var i, l, output = [];
remaining = remaining - 1;
if (!remaining) {
for (i = 0, l = rs.rows.length; i < l; i = i + 1){
var j = rs.rows.item(i).json;
//j = JSON.parse(j);
output.push(j);
}
successCallback(output);
}
};
self.db.transaction(function (tx) {
for (i = 0, l = data.length; i < l; i = i + 1) {
tx.executeSql(query, data[i], innerSuccessCallback, failureCallback);
}
});
} | [
"function",
"(",
"query",
",",
"data",
",",
"successCallback",
",",
"failureCallback",
")",
"{",
"if",
"(",
"typeof",
"successCallback",
"!=",
"\"function\"",
")",
"successCallback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"if",
"(",
"typeof",
"failureCall... | private function to execute a query | [
"private",
"function",
"to",
"execute",
"a",
"query"
] | 507ef210e339fdb8f820b26412e2173aa8c19d82 | https://github.com/Pamblam/jSQL/blob/507ef210e339fdb8f820b26412e2173aa8c19d82/jSQL.js#L2370-L2395 | |
33,316 | temando/remark-mermaid | src/index.js | replaceLinkWithEmbedded | function replaceLinkWithEmbedded(node, index, parent, vFile) {
const { title, url, position } = node;
let newNode;
// If the node isn't mermaid, ignore it.
if (!isMermaid(title)) {
return node;
}
try {
const value = fs.readFileSync(`${vFile.dirname}/${url}`, { encoding: 'utf-8' });
newNode = createMermaidDiv(value);
parent.children.splice(index, 1, newNode);
vFile.info('mermaid link replaced with div', position, PLUGIN_NAME);
} catch (error) {
vFile.message(error, position, PLUGIN_NAME);
return node;
}
return node;
} | javascript | function replaceLinkWithEmbedded(node, index, parent, vFile) {
const { title, url, position } = node;
let newNode;
// If the node isn't mermaid, ignore it.
if (!isMermaid(title)) {
return node;
}
try {
const value = fs.readFileSync(`${vFile.dirname}/${url}`, { encoding: 'utf-8' });
newNode = createMermaidDiv(value);
parent.children.splice(index, 1, newNode);
vFile.info('mermaid link replaced with div', position, PLUGIN_NAME);
} catch (error) {
vFile.message(error, position, PLUGIN_NAME);
return node;
}
return node;
} | [
"function",
"replaceLinkWithEmbedded",
"(",
"node",
",",
"index",
",",
"parent",
",",
"vFile",
")",
"{",
"const",
"{",
"title",
",",
"url",
",",
"position",
"}",
"=",
"node",
";",
"let",
"newNode",
";",
"// If the node isn't mermaid, ignore it.",
"if",
"(",
... | Given a link to a mermaid diagram, grab the contents from the link and put it
into a div that Mermaid JS can act upon.
@param {object} node
@param {integer} index
@param {object} parent
@param {vFile} vFile
@return {object} | [
"Given",
"a",
"link",
"to",
"a",
"mermaid",
"diagram",
"grab",
"the",
"contents",
"from",
"the",
"link",
"and",
"put",
"it",
"into",
"a",
"div",
"that",
"Mermaid",
"JS",
"can",
"act",
"upon",
"."
] | 3c0aaa8e90ff8ca0d043a9648c651683c0867ae3 | https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/index.js#L60-L81 |
33,317 | temando/remark-mermaid | src/index.js | visitCodeBlock | function visitCodeBlock(ast, vFile, isSimple) {
return visit(ast, 'code', (node, index, parent) => {
const { lang, value, position } = node;
const destinationDir = getDestinationDir(vFile);
let newNode;
// If this codeblock is not mermaid, bail.
if (lang !== 'mermaid') {
return node;
}
// Are we just transforming to a <div>, or replacing with an image?
if (isSimple) {
newNode = createMermaidDiv(value);
vFile.info(`${lang} code block replaced with div`, position, PLUGIN_NAME);
// Otherwise, let's try and generate a graph!
} else {
let graphSvgFilename;
try {
graphSvgFilename = render(value, destinationDir);
vFile.info(`${lang} code block replaced with graph`, position, PLUGIN_NAME);
} catch (error) {
vFile.message(error, position, PLUGIN_NAME);
return node;
}
newNode = {
type: 'image',
title: '`mermaid` image',
url: graphSvgFilename,
};
}
parent.children.splice(index, 1, newNode);
return node;
});
} | javascript | function visitCodeBlock(ast, vFile, isSimple) {
return visit(ast, 'code', (node, index, parent) => {
const { lang, value, position } = node;
const destinationDir = getDestinationDir(vFile);
let newNode;
// If this codeblock is not mermaid, bail.
if (lang !== 'mermaid') {
return node;
}
// Are we just transforming to a <div>, or replacing with an image?
if (isSimple) {
newNode = createMermaidDiv(value);
vFile.info(`${lang} code block replaced with div`, position, PLUGIN_NAME);
// Otherwise, let's try and generate a graph!
} else {
let graphSvgFilename;
try {
graphSvgFilename = render(value, destinationDir);
vFile.info(`${lang} code block replaced with graph`, position, PLUGIN_NAME);
} catch (error) {
vFile.message(error, position, PLUGIN_NAME);
return node;
}
newNode = {
type: 'image',
title: '`mermaid` image',
url: graphSvgFilename,
};
}
parent.children.splice(index, 1, newNode);
return node;
});
} | [
"function",
"visitCodeBlock",
"(",
"ast",
",",
"vFile",
",",
"isSimple",
")",
"{",
"return",
"visit",
"(",
"ast",
",",
"'code'",
",",
"(",
"node",
",",
"index",
",",
"parent",
")",
"=>",
"{",
"const",
"{",
"lang",
",",
"value",
",",
"position",
"}",
... | Given the MDAST ast, look for all fenced codeblocks that have a language of
`mermaid` and pass that to mermaid.cli to render the image. Replaces the
codeblocks with an image of the rendered graph.
@param {object} ast
@param {vFile} vFile
@param {boolean} isSimple
@return {function} | [
"Given",
"the",
"MDAST",
"ast",
"look",
"for",
"all",
"fenced",
"codeblocks",
"that",
"have",
"a",
"language",
"of",
"mermaid",
"and",
"pass",
"that",
"to",
"mermaid",
".",
"cli",
"to",
"render",
"the",
"image",
".",
"Replaces",
"the",
"codeblocks",
"with"... | 3c0aaa8e90ff8ca0d043a9648c651683c0867ae3 | https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/index.js#L93-L133 |
33,318 | temando/remark-mermaid | src/index.js | mermaid | function mermaid(options = {}) {
const simpleMode = options.simple || false;
/**
* @param {object} ast MDAST
* @param {vFile} vFile
* @param {function} next
* @return {object}
*/
return function transformer(ast, vFile, next) {
visitCodeBlock(ast, vFile, simpleMode);
visitLink(ast, vFile, simpleMode);
visitImage(ast, vFile, simpleMode);
if (typeof next === 'function') {
return next(null, ast, vFile);
}
return ast;
};
} | javascript | function mermaid(options = {}) {
const simpleMode = options.simple || false;
/**
* @param {object} ast MDAST
* @param {vFile} vFile
* @param {function} next
* @return {object}
*/
return function transformer(ast, vFile, next) {
visitCodeBlock(ast, vFile, simpleMode);
visitLink(ast, vFile, simpleMode);
visitImage(ast, vFile, simpleMode);
if (typeof next === 'function') {
return next(null, ast, vFile);
}
return ast;
};
} | [
"function",
"mermaid",
"(",
"options",
"=",
"{",
"}",
")",
"{",
"const",
"simpleMode",
"=",
"options",
".",
"simple",
"||",
"false",
";",
"/**\n * @param {object} ast MDAST\n * @param {vFile} vFile\n * @param {function} next\n * @return {object}\n */",
"return",
"fu... | Returns the transformer which acts on the MDAST tree and given VFile.
If `options.simple` is passed as a truthy value, the plugin will convert
to `<div class="mermaid">` rather than a SVG image.
@link https://github.com/unifiedjs/unified#function-transformernode-file-next
@link https://github.com/syntax-tree/mdast
@link https://github.com/vfile/vfile
@param {object} options
@return {function} | [
"Returns",
"the",
"transformer",
"which",
"acts",
"on",
"the",
"MDAST",
"tree",
"and",
"given",
"VFile",
"."
] | 3c0aaa8e90ff8ca0d043a9648c651683c0867ae3 | https://github.com/temando/remark-mermaid/blob/3c0aaa8e90ff8ca0d043a9648c651683c0867ae3/src/index.js#L184-L204 |
33,319 | sematext/spm-agent-nodejs | lib/httpServerAgent.js | safeProcess | function safeProcess (ctx, fn) {
return function processRequest (req, res) {
try {
fn(ctx, req, res)
} catch (ex) {
ctx.logger.error(ex)
}
}
} | javascript | function safeProcess (ctx, fn) {
return function processRequest (req, res) {
try {
fn(ctx, req, res)
} catch (ex) {
ctx.logger.error(ex)
}
}
} | [
"function",
"safeProcess",
"(",
"ctx",
",",
"fn",
")",
"{",
"return",
"function",
"processRequest",
"(",
"req",
",",
"res",
")",
"{",
"try",
"{",
"fn",
"(",
"ctx",
",",
"req",
",",
"res",
")",
"}",
"catch",
"(",
"ex",
")",
"{",
"ctx",
".",
"logge... | Make sure we deoptimize small part of fn | [
"Make",
"sure",
"we",
"deoptimize",
"small",
"part",
"of",
"fn"
] | e4f639321568926e5c8fb6760a4afa201c54933e | https://github.com/sematext/spm-agent-nodejs/blob/e4f639321568926e5c8fb6760a4afa201c54933e/lib/httpServerAgent.js#L124-L132 |
33,320 | peerigon/socket.io-session-middleware | index.js | ioSession | function ioSession(options) {
var cookieParser = options.cookieParser,
sessionStore = options.store,
key = options.key || "connect.sid";
function findCookie(handshake) {
return (handshake.secureCookies && handshake.secureCookies[key])
|| (handshake.signedCookies && handshake.signedCookies[key])
|| (handshake.cookies && handshake.cookies[key]);
}
function getSession(socketHandshake, callback) {
cookieParser(socketHandshake, {}, function (parseErr) {
if(parseErr) {
callback(parseErr);
return;
}
// use sessionStore.get() instead of deprecated sessionStore.load()
sessionStore.get(findCookie(socketHandshake), function (storeErr, session) {
if(storeErr) {
callback(storeErr);
return;
}
if(!session) {
callback(new Error("could not look up session by key: " + key));
return;
}
callback(null, session);
});
});
}
return function handleSession(socket, next) {
getSession(socket.request, function (err, session) {
if(err) {
next(err);
return;
}
socket.session = session;
next();
});
};
} | javascript | function ioSession(options) {
var cookieParser = options.cookieParser,
sessionStore = options.store,
key = options.key || "connect.sid";
function findCookie(handshake) {
return (handshake.secureCookies && handshake.secureCookies[key])
|| (handshake.signedCookies && handshake.signedCookies[key])
|| (handshake.cookies && handshake.cookies[key]);
}
function getSession(socketHandshake, callback) {
cookieParser(socketHandshake, {}, function (parseErr) {
if(parseErr) {
callback(parseErr);
return;
}
// use sessionStore.get() instead of deprecated sessionStore.load()
sessionStore.get(findCookie(socketHandshake), function (storeErr, session) {
if(storeErr) {
callback(storeErr);
return;
}
if(!session) {
callback(new Error("could not look up session by key: " + key));
return;
}
callback(null, session);
});
});
}
return function handleSession(socket, next) {
getSession(socket.request, function (err, session) {
if(err) {
next(err);
return;
}
socket.session = session;
next();
});
};
} | [
"function",
"ioSession",
"(",
"options",
")",
"{",
"var",
"cookieParser",
"=",
"options",
".",
"cookieParser",
",",
"sessionStore",
"=",
"options",
".",
"store",
",",
"key",
"=",
"options",
".",
"key",
"||",
"\"connect.sid\"",
";",
"function",
"findCookie",
... | pass session...
- cookieParse
- store
- key
returns a socket.io compatible middleware (v1.+)
which attaches the session to socket.session
if no session could be found it nexts with an error
handle the error with sockets.on("error", ...)
@param {Object} options
@returns {Function} handleSession | [
"pass",
"session",
"...",
"-",
"cookieParse",
"-",
"store",
"-",
"key"
] | a2ff55865021f07753634a17f28e8f7e7024ae37 | https://github.com/peerigon/socket.io-session-middleware/blob/a2ff55865021f07753634a17f28e8f7e7024ae37/index.js#L19-L64 |
33,321 | CrabDude/trycatch | lib/formatError.js | normalizeError | function normalizeError(err, stack) {
err = coerceToError(err)
if (!err.normalized) {
addNonEnumerableValue(err, 'originalStack', stack || err.message)
addNonEnumerableValue(err, 'normalized', true)
addNonEnumerableValue(err, 'coreThrown', isCoreError(err))
addNonEnumerableValue(err, 'catchable', isCatchableError(err))
}
return err
} | javascript | function normalizeError(err, stack) {
err = coerceToError(err)
if (!err.normalized) {
addNonEnumerableValue(err, 'originalStack', stack || err.message)
addNonEnumerableValue(err, 'normalized', true)
addNonEnumerableValue(err, 'coreThrown', isCoreError(err))
addNonEnumerableValue(err, 'catchable', isCatchableError(err))
}
return err
} | [
"function",
"normalizeError",
"(",
"err",
",",
"stack",
")",
"{",
"err",
"=",
"coerceToError",
"(",
"err",
")",
"if",
"(",
"!",
"err",
".",
"normalized",
")",
"{",
"addNonEnumerableValue",
"(",
"err",
",",
"'originalStack'",
",",
"stack",
"||",
"err",
".... | Ensure error conforms to common expectations | [
"Ensure",
"error",
"conforms",
"to",
"common",
"expectations"
] | 66621d9410776743e677c0e481a580ef598ecc85 | https://github.com/CrabDude/trycatch/blob/66621d9410776743e677c0e481a580ef598ecc85/lib/formatError.js#L39-L48 |
33,322 | lykmapipo/express-mquery | lib/parser.js | function (projection = '') {
//prepare projections
let fields = _.compact(projection.split(','));
fields = _.map(fields, _.trim);
fields = _.uniq(fields);
const accumulator = {};
_.forEach(fields, function (field) {
//if exclude e.g -name
if (field[0] === '-') {
accumulator[field.substring(1)] = 0;
}
//if include i.e name
else {
accumulator[field] = 1;
}
});
return accumulator;
} | javascript | function (projection = '') {
//prepare projections
let fields = _.compact(projection.split(','));
fields = _.map(fields, _.trim);
fields = _.uniq(fields);
const accumulator = {};
_.forEach(fields, function (field) {
//if exclude e.g -name
if (field[0] === '-') {
accumulator[field.substring(1)] = 0;
}
//if include i.e name
else {
accumulator[field] = 1;
}
});
return accumulator;
} | [
"function",
"(",
"projection",
"=",
"''",
")",
"{",
"//prepare projections",
"let",
"fields",
"=",
"_",
".",
"compact",
"(",
"projection",
".",
"split",
"(",
"','",
")",
")",
";",
"fields",
"=",
"_",
".",
"map",
"(",
"fields",
",",
"_",
".",
"trim",
... | parse comma separated fields into mongodb awase projections | [
"parse",
"comma",
"separated",
"fields",
"into",
"mongodb",
"awase",
"projections"
] | 15c685d6767e2894e15907b138f1ea56a3d3f69b | https://github.com/lykmapipo/express-mquery/blob/15c685d6767e2894e15907b138f1ea56a3d3f69b/lib/parser.js#L442-L465 | |
33,323 | fulup-bzh/GeoGate | AisWeb/app/Frontend/widgets/LeafletMap/AisToMap.js | DeviceOnMap | function DeviceOnMap (map, data) {
this.trace=[]; // keep trace of device trace on xx positions
this.count=0; // number of points created for this device
this.devid = data.devid;
this.src = data.src;
this.name = data.name;
this.cargo = data.cargo;
this.vessel= ' cargo-' + data.cargo;
this.map=map;
this.lastshow = new Date().getTime();
} | javascript | function DeviceOnMap (map, data) {
this.trace=[]; // keep trace of device trace on xx positions
this.count=0; // number of points created for this device
this.devid = data.devid;
this.src = data.src;
this.name = data.name;
this.cargo = data.cargo;
this.vessel= ' cargo-' + data.cargo;
this.map=map;
this.lastshow = new Date().getTime();
} | [
"function",
"DeviceOnMap",
"(",
"map",
",",
"data",
")",
"{",
"this",
".",
"trace",
"=",
"[",
"]",
";",
"// keep trace of device trace on xx positions",
"this",
".",
"count",
"=",
"0",
";",
"// number of points created for this device",
"this",
".",
"devid",
"=",
... | Class to add vessel as POI on Leaflet | [
"Class",
"to",
"add",
"vessel",
"as",
"POI",
"on",
"Leaflet"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/AisWeb/app/Frontend/widgets/LeafletMap/AisToMap.js#L27-L37 |
33,324 | fulup-bzh/GeoGate | server/lib/GG-Controller.js | TcpClientData | function TcpClientData (buffer) {
this.controller.Debug(7, "[%s] Data=[%s]", this.uid, buffer);
// call adapter specific routine to process messages
var status = this.adapter.ParseBuffer(this, buffer);
} | javascript | function TcpClientData (buffer) {
this.controller.Debug(7, "[%s] Data=[%s]", this.uid, buffer);
// call adapter specific routine to process messages
var status = this.adapter.ParseBuffer(this, buffer);
} | [
"function",
"TcpClientData",
"(",
"buffer",
")",
"{",
"this",
".",
"controller",
".",
"Debug",
"(",
"7",
",",
"\"[%s] Data=[%s]\"",
",",
"this",
".",
"uid",
",",
"buffer",
")",
";",
"// call adapter specific routine to process messages",
"var",
"status",
"=",
"t... | Client receive data from server | [
"Client",
"receive",
"data",
"from",
"server"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/GG-Controller.js#L103-L108 |
33,325 | kunalnagar/jquery.peekABar | dist/js/jquery.peekabar.js | function() {
that.bar = $('<div></div>').addClass('peek-a-bar').attr('id', '__peek_a_bar_' + rand);
$('html').append(that.bar);
that.bar.hide();
} | javascript | function() {
that.bar = $('<div></div>').addClass('peek-a-bar').attr('id', '__peek_a_bar_' + rand);
$('html').append(that.bar);
that.bar.hide();
} | [
"function",
"(",
")",
"{",
"that",
".",
"bar",
"=",
"$",
"(",
"'<div></div>'",
")",
".",
"addClass",
"(",
"'peek-a-bar'",
")",
".",
"attr",
"(",
"'id'",
",",
"'__peek_a_bar_'",
"+",
"rand",
")",
";",
"$",
"(",
"'html'",
")",
".",
"append",
"(",
"th... | Create the Bar | [
"Create",
"the",
"Bar"
] | 1d7252e68606ebdc70704fd1e582f8e6854ffdac | https://github.com/kunalnagar/jquery.peekABar/blob/1d7252e68606ebdc70704fd1e582f8e6854ffdac/dist/js/jquery.peekabar.js#L88-L92 | |
33,326 | kunalnagar/jquery.peekABar | dist/js/jquery.peekabar.js | function() {
if(that.settings.cssClass !== null) {
that.bar.addClass(that.settings.cssClass);
}
} | javascript | function() {
if(that.settings.cssClass !== null) {
that.bar.addClass(that.settings.cssClass);
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"that",
".",
"settings",
".",
"cssClass",
"!==",
"null",
")",
"{",
"that",
".",
"bar",
".",
"addClass",
"(",
"that",
".",
"settings",
".",
"cssClass",
")",
";",
"}",
"}"
] | Apply Custom CSS Class | [
"Apply",
"Custom",
"CSS",
"Class"
] | 1d7252e68606ebdc70704fd1e582f8e6854ffdac | https://github.com/kunalnagar/jquery.peekABar/blob/1d7252e68606ebdc70704fd1e582f8e6854ffdac/dist/js/jquery.peekabar.js#L131-L135 | |
33,327 | kunalnagar/jquery.peekABar | dist/js/jquery.peekabar.js | function() {
switch(that.settings.position) {
case 'top':
that.bar.css('top', 0);
break;
case 'bottom':
that.bar.css('bottom', 0);
break;
default:
that.bar.css('top', 0);
}
} | javascript | function() {
switch(that.settings.position) {
case 'top':
that.bar.css('top', 0);
break;
case 'bottom':
that.bar.css('bottom', 0);
break;
default:
that.bar.css('top', 0);
}
} | [
"function",
"(",
")",
"{",
"switch",
"(",
"that",
".",
"settings",
".",
"position",
")",
"{",
"case",
"'top'",
":",
"that",
".",
"bar",
".",
"css",
"(",
"'top'",
",",
"0",
")",
";",
"break",
";",
"case",
"'bottom'",
":",
"that",
".",
"bar",
".",
... | Apply Position where the Bar should be shown | [
"Apply",
"Position",
"where",
"the",
"Bar",
"should",
"be",
"shown"
] | 1d7252e68606ebdc70704fd1e582f8e6854ffdac | https://github.com/kunalnagar/jquery.peekABar/blob/1d7252e68606ebdc70704fd1e582f8e6854ffdac/dist/js/jquery.peekabar.js#L143-L154 | |
33,328 | fulup-bzh/GeoGate | server/lib/_HttpClient.js | GpsdHttpClient | function GpsdHttpClient (adapter, devid) {
this.debug = adapter.debug; // inherit debug level
this.uid = "httpclient//" + adapter.info + ":" + devid;
this.adapter = adapter;
this.gateway = adapter.gateway;
this.controller = adapter.controller;
this.socket = null; // we cannot rely on socket to talk to device
this.devid = false; // we get uid directly from device
this.name = false;
this.logged = false;
this.alarm = 0; // count alarm messages
this.count = 0; // generic counter used by file backend
this.errorcount = 0; // number of ignore messages
this.uid = "httpclient://" + this.adapter.info + ":" + this.adapter.id;
} | javascript | function GpsdHttpClient (adapter, devid) {
this.debug = adapter.debug; // inherit debug level
this.uid = "httpclient//" + adapter.info + ":" + devid;
this.adapter = adapter;
this.gateway = adapter.gateway;
this.controller = adapter.controller;
this.socket = null; // we cannot rely on socket to talk to device
this.devid = false; // we get uid directly from device
this.name = false;
this.logged = false;
this.alarm = 0; // count alarm messages
this.count = 0; // generic counter used by file backend
this.errorcount = 0; // number of ignore messages
this.uid = "httpclient://" + this.adapter.info + ":" + this.adapter.id;
} | [
"function",
"GpsdHttpClient",
"(",
"adapter",
",",
"devid",
")",
"{",
"this",
".",
"debug",
"=",
"adapter",
".",
"debug",
";",
"// inherit debug level",
"this",
".",
"uid",
"=",
"\"httpclient//\"",
"+",
"adapter",
".",
"info",
"+",
"\":\"",
"+",
"devid",
"... | called from http class of adapter | [
"called",
"from",
"http",
"class",
"of",
"adapter"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/_HttpClient.js#L42-L60 |
33,329 | fulup-bzh/GeoGate | simulator/bin/HubSimulator.js | ScanGpxDir | function ScanGpxDir (gpxdir) {
var availableRoutes=[];
var count=0;
var routesDir = gpxdir;
var directory = fs.readdirSync(routesDir);
for (var i in directory) {
var file = directory [i];
var route = path.basename (directory [i],".gpx");
var name = routesDir + route + '.gpx';
try {
if (fs.statSync(name).isFile()) {
count ++;
availableRoutes [route] = name;
console.log ("Found Gpx Route: " + route + " file: " + availableRoutes [route]);
}
} catch (err) {/* ignore errors */}
}
if (count < 3) {
console.log ("Find only [%d] GPX file in [%s] please check your directory", count, parsing.opts.gpxdir);
process.exit (-1);
}
return (availableRoutes);
} | javascript | function ScanGpxDir (gpxdir) {
var availableRoutes=[];
var count=0;
var routesDir = gpxdir;
var directory = fs.readdirSync(routesDir);
for (var i in directory) {
var file = directory [i];
var route = path.basename (directory [i],".gpx");
var name = routesDir + route + '.gpx';
try {
if (fs.statSync(name).isFile()) {
count ++;
availableRoutes [route] = name;
console.log ("Found Gpx Route: " + route + " file: " + availableRoutes [route]);
}
} catch (err) {/* ignore errors */}
}
if (count < 3) {
console.log ("Find only [%d] GPX file in [%s] please check your directory", count, parsing.opts.gpxdir);
process.exit (-1);
}
return (availableRoutes);
} | [
"function",
"ScanGpxDir",
"(",
"gpxdir",
")",
"{",
"var",
"availableRoutes",
"=",
"[",
"]",
";",
"var",
"count",
"=",
"0",
";",
"var",
"routesDir",
"=",
"gpxdir",
";",
"var",
"directory",
"=",
"fs",
".",
"readdirSync",
"(",
"routesDir",
")",
";",
"for"... | scan directory and extract all .gpx files | [
"scan",
"directory",
"and",
"extract",
"all",
".",
"gpx",
"files"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/bin/HubSimulator.js#L118-L140 |
33,330 | fulup-bzh/GeoGate | server/adapters/AisProxyNmea-adapter.js | SetGarbage | function SetGarbage (proxy, timeout) {
// let's call back ourself after timeout*1000/4
proxy.Debug (4, "SetGarbage timeout=%d", timeout);
setTimeout (function(){SetGarbage (proxy, timeout);}, timeout*500);
// let compute timeout timeout limit
var lastshow = new Date().getTime() - (timeout *1000);
for (var mmsi in proxy.vessels) {
var vessel = proxy.vessels[mmsi];
if (vessel.lastshow < lastshow) {
proxy.Debug (5, "Removed Vessel mmsi=%s", mmsi);
delete proxy.vessels [mmsi];
}
}
} | javascript | function SetGarbage (proxy, timeout) {
// let's call back ourself after timeout*1000/4
proxy.Debug (4, "SetGarbage timeout=%d", timeout);
setTimeout (function(){SetGarbage (proxy, timeout);}, timeout*500);
// let compute timeout timeout limit
var lastshow = new Date().getTime() - (timeout *1000);
for (var mmsi in proxy.vessels) {
var vessel = proxy.vessels[mmsi];
if (vessel.lastshow < lastshow) {
proxy.Debug (5, "Removed Vessel mmsi=%s", mmsi);
delete proxy.vessels [mmsi];
}
}
} | [
"function",
"SetGarbage",
"(",
"proxy",
",",
"timeout",
")",
"{",
"// let's call back ourself after timeout*1000/4",
"proxy",
".",
"Debug",
"(",
"4",
",",
"\"SetGarbage timeout=%d\"",
",",
"timeout",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"SetGarb... | this function scan active device table and remove dead one based on inactivity timeout | [
"this",
"function",
"scan",
"active",
"device",
"table",
"and",
"remove",
"dead",
"one",
"based",
"on",
"inactivity",
"timeout"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/AisProxyNmea-adapter.js#L35-L51 |
33,331 | florianheinemann/passwordless-mongostore | lib/mongostore.js | MongoStore | function MongoStore(connection, options) {
if(arguments.length === 0 || typeof arguments[0] !== 'string') {
throw new Error('A valid connection string has to be provided');
}
TokenStore.call(this);
this._options = options || {};
this._collectionName = 'passwordless-token';
if(this._options.mongostore) {
if(this._options.mongostore.collection) {
this._collectionName = this._options.mongostore.collection;
}
delete this._options.mongostore;
}
this._uri = connection;
this._db = null;
this._collection = null;
} | javascript | function MongoStore(connection, options) {
if(arguments.length === 0 || typeof arguments[0] !== 'string') {
throw new Error('A valid connection string has to be provided');
}
TokenStore.call(this);
this._options = options || {};
this._collectionName = 'passwordless-token';
if(this._options.mongostore) {
if(this._options.mongostore.collection) {
this._collectionName = this._options.mongostore.collection;
}
delete this._options.mongostore;
}
this._uri = connection;
this._db = null;
this._collection = null;
} | [
"function",
"MongoStore",
"(",
"connection",
",",
"options",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
"||",
"typeof",
"arguments",
"[",
"0",
"]",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'A valid connection string has t... | Constructor of MongoStore
@param {String} connection URI as defined by the MongoDB specification. Please
check the documentation for details:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
@param {Object} [options] Combines both the options for the MongoClient as well
as the options for MongoStore. For the MongoClient options please refer back to
the documentation. MongoStore understands the following options:
(1) { mongostore: { collection: string }} to change the name of the collection
being used. Defaults to: 'passwordless-token'
@constructor | [
"Constructor",
"of",
"MongoStore"
] | 3352c12c916abaf1a5d2c6dd1af633d2a62ea34b | https://github.com/florianheinemann/passwordless-mongostore/blob/3352c12c916abaf1a5d2c6dd1af633d2a62ea34b/lib/mongostore.js#L20-L39 |
33,332 | fulup-bzh/GeoGate | server/lib/GG-Gateway.js | SetCrontab | function SetCrontab (gateway, inactivity) {
// let's call back ourself after inactivity*1000/4
gateway.Debug (5, "SetCrontab inactivity=%d", inactivity);
setTimeout (function(){SetCrontab (gateway, inactivity);}, inactivity*250);
// let compute inactivity timeout limit
var timeout = new Date().getTime() - (inactivity *1000);
for (var devid in gateway.activeClients) {
var device = gateway.activeClients[devid];
if (device.lastshow < timeout) {
gateway.Debug (1, "Removed ActiveDev Id=%s uid=%s", device.devid, device.uid);
delete gateway.activeClients [devid];
}
}
} | javascript | function SetCrontab (gateway, inactivity) {
// let's call back ourself after inactivity*1000/4
gateway.Debug (5, "SetCrontab inactivity=%d", inactivity);
setTimeout (function(){SetCrontab (gateway, inactivity);}, inactivity*250);
// let compute inactivity timeout limit
var timeout = new Date().getTime() - (inactivity *1000);
for (var devid in gateway.activeClients) {
var device = gateway.activeClients[devid];
if (device.lastshow < timeout) {
gateway.Debug (1, "Removed ActiveDev Id=%s uid=%s", device.devid, device.uid);
delete gateway.activeClients [devid];
}
}
} | [
"function",
"SetCrontab",
"(",
"gateway",
",",
"inactivity",
")",
"{",
"// let's call back ourself after inactivity*1000/4",
"gateway",
".",
"Debug",
"(",
"5",
",",
"\"SetCrontab inactivity=%d\"",
",",
"inactivity",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
... | 30s in between two retry this function scan active device table and remove dead one based on inactivity timeout | [
"30s",
"in",
"between",
"two",
"retry",
"this",
"function",
"scan",
"active",
"device",
"table",
"and",
"remove",
"dead",
"one",
"based",
"on",
"inactivity",
"timeout"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/GG-Gateway.js#L35-L51 |
33,333 | fulup-bzh/GeoGate | server/lib/GG-Gateway.js | JobCallback | function JobCallback (job) {
if (job !== null) {
job.gateway.Debug (6,"Queued Request:%s command=%s devid=%s [done]", job.request, job.command, job.devId);
}
} | javascript | function JobCallback (job) {
if (job !== null) {
job.gateway.Debug (6,"Queued Request:%s command=%s devid=%s [done]", job.request, job.command, job.devId);
}
} | [
"function",
"JobCallback",
"(",
"job",
")",
"{",
"if",
"(",
"job",
"!==",
"null",
")",
"{",
"job",
".",
"gateway",
".",
"Debug",
"(",
"6",
",",
"\"Queued Request:%s command=%s devid=%s [done]\"",
",",
"job",
".",
"request",
",",
"job",
".",
"command",
",",... | Callback notify Async API that curent JobQueue processing is done | [
"Callback",
"notify",
"Async",
"API",
"that",
"curent",
"JobQueue",
"processing",
"is",
"done"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/GG-Gateway.js#L54-L58 |
33,334 | fulup-bzh/GeoGate | simulator/lib/GG-Dispatcher.js | TcpStreamConnect | function TcpStreamConnect () {
this.simulator.Debug (3, 'Dispatcher connected to %s:%s', simulator.opts.host, simulator.opts.port);
ActiveClients[this] = this; // register on remote server in active socket list
} | javascript | function TcpStreamConnect () {
this.simulator.Debug (3, 'Dispatcher connected to %s:%s', simulator.opts.host, simulator.opts.port);
ActiveClients[this] = this; // register on remote server in active socket list
} | [
"function",
"TcpStreamConnect",
"(",
")",
"{",
"this",
".",
"simulator",
".",
"Debug",
"(",
"3",
",",
"'Dispatcher connected to %s:%s'",
",",
"simulator",
".",
"opts",
".",
"host",
",",
"simulator",
".",
"opts",
".",
"port",
")",
";",
"ActiveClients",
"[",
... | this handler is called when TcpClient connect onto server | [
"this",
"handler",
"is",
"called",
"when",
"TcpClient",
"connect",
"onto",
"server"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Dispatcher.js#L218-L221 |
33,335 | fulup-bzh/GeoGate | simulator/lib/GG-Dispatcher.js | TcpStreamEnd | function TcpStreamEnd () {
this.simulator.Debug (3,"TcpStream [%s:%s] connection ended", simulator.opts.host, simulator.opts.port);
delete ActiveClients[this];
setTimeout (function(){ // wait for timeout and recreate a new Object from scratch
simulator.TcpClient ();
}, this.opts.timeout);
} | javascript | function TcpStreamEnd () {
this.simulator.Debug (3,"TcpStream [%s:%s] connection ended", simulator.opts.host, simulator.opts.port);
delete ActiveClients[this];
setTimeout (function(){ // wait for timeout and recreate a new Object from scratch
simulator.TcpClient ();
}, this.opts.timeout);
} | [
"function",
"TcpStreamEnd",
"(",
")",
"{",
"this",
".",
"simulator",
".",
"Debug",
"(",
"3",
",",
"\"TcpStream [%s:%s] connection ended\"",
",",
"simulator",
".",
"opts",
".",
"host",
",",
"simulator",
".",
"opts",
".",
"port",
")",
";",
"delete",
"ActiveCli... | Remote server close connection let's retry it | [
"Remote",
"server",
"close",
"connection",
"let",
"s",
"retry",
"it"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Dispatcher.js#L230-L236 |
33,336 | fulup-bzh/GeoGate | server/adapters/TelnetConsole-adapter.js | function (dbresult) {
if (dbresult === null || dbresult === undefined) {
this.Debug (1,"Hoops: no DB info for %s", data.devid);
return;
}
for (var idx = 0; (idx < dbresult.length); idx ++) {
var posi= dbresult[idx];
posi.lon = posi.lon.toFixed (4);
posi.lat = posi.lat.toFixed (4);
posi.sog = posi.sog.toFixed (2);
posi.cog = posi.cog.toFixed (2);
var info=util.format ("> -%d- Lat:%s Lon:%s Sog:%s Cog:%s Alt:%s Acquired:%s\n"
, idx, posi.lat, posi.lon, posi.sog, posi.cog, posi.alt, posi.acquired_at);
socket.write (info);
}
} | javascript | function (dbresult) {
if (dbresult === null || dbresult === undefined) {
this.Debug (1,"Hoops: no DB info for %s", data.devid);
return;
}
for (var idx = 0; (idx < dbresult.length); idx ++) {
var posi= dbresult[idx];
posi.lon = posi.lon.toFixed (4);
posi.lat = posi.lat.toFixed (4);
posi.sog = posi.sog.toFixed (2);
posi.cog = posi.cog.toFixed (2);
var info=util.format ("> -%d- Lat:%s Lon:%s Sog:%s Cog:%s Alt:%s Acquired:%s\n"
, idx, posi.lat, posi.lon, posi.sog, posi.cog, posi.alt, posi.acquired_at);
socket.write (info);
}
} | [
"function",
"(",
"dbresult",
")",
"{",
"if",
"(",
"dbresult",
"===",
"null",
"||",
"dbresult",
"===",
"undefined",
")",
"{",
"this",
".",
"Debug",
"(",
"1",
",",
"\"Hoops: no DB info for %s\"",
",",
"data",
".",
"devid",
")",
";",
"return",
";",
"}",
"... | Ask DB backend to display on telnet socket last X position for devid=yyyy | [
"Ask",
"DB",
"backend",
"to",
"display",
"on",
"telnet",
"socket",
"last",
"X",
"position",
"for",
"devid",
"=",
"yyyy"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/TelnetConsole-adapter.js#L315-L331 | |
33,337 | fulup-bzh/GeoGate | server/adapters/NmeaTcpFeed-adapter.js | DevAdapter | function DevAdapter (controller) {
this.id = controller.svc;
this.uid = "//" + controller.svcopts.adapter + "/" + controller.svc + "@" + controller.svcopts.hostname + ":" +controller.svcopts.remport;
this.info = 'nmeatcp';
this.control = 'tcpfeed'; // this adapter connect onto a remote server
this.debug = controller.svcopts.debug; // inherit debug from controller
this.controller= controller; // keep a link to device controller and TCP socket
this.mmsi = controller.svcopts.mmsi; // use fake MMSI provided by user application in service options
// Check mmsi is unique
if (registermmsi [this.mmsi] !== undefined) {
this.Debug (0,'Fatal adapter:%s this.mmsi:%s SHOULD be unique', this.info, this.mmsi);
console.log ("Gpsd [duplicated NMEA MMSI] application aborted [please fix your configuration]");
process.exit (-1);
}
registermmsi [this.mmsi] = true;
this.Debug (1,"uid=%s mmsi=%s", this.uid,this.mmsi);
} | javascript | function DevAdapter (controller) {
this.id = controller.svc;
this.uid = "//" + controller.svcopts.adapter + "/" + controller.svc + "@" + controller.svcopts.hostname + ":" +controller.svcopts.remport;
this.info = 'nmeatcp';
this.control = 'tcpfeed'; // this adapter connect onto a remote server
this.debug = controller.svcopts.debug; // inherit debug from controller
this.controller= controller; // keep a link to device controller and TCP socket
this.mmsi = controller.svcopts.mmsi; // use fake MMSI provided by user application in service options
// Check mmsi is unique
if (registermmsi [this.mmsi] !== undefined) {
this.Debug (0,'Fatal adapter:%s this.mmsi:%s SHOULD be unique', this.info, this.mmsi);
console.log ("Gpsd [duplicated NMEA MMSI] application aborted [please fix your configuration]");
process.exit (-1);
}
registermmsi [this.mmsi] = true;
this.Debug (1,"uid=%s mmsi=%s", this.uid,this.mmsi);
} | [
"function",
"DevAdapter",
"(",
"controller",
")",
"{",
"this",
".",
"id",
"=",
"controller",
".",
"svc",
";",
"this",
".",
"uid",
"=",
"\"//\"",
"+",
"controller",
".",
"svcopts",
".",
"adapter",
"+",
"\"/\"",
"+",
"controller",
".",
"svc",
"+",
"\"@\"... | keep track of nmea MMSI for uniqueness Adapter is an object own by a given device controller that handle data connection | [
"keep",
"track",
"of",
"nmea",
"MMSI",
"for",
"uniqueness",
"Adapter",
"is",
"an",
"object",
"own",
"by",
"a",
"given",
"device",
"controller",
"that",
"handle",
"data",
"connection"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/NmeaTcpFeed-adapter.js#L45-L63 |
33,338 | fulup-bzh/GeoGate | server/bin/Tracker2Json.js | EventHandlerQueue | function EventHandlerQueue (status, job){
console.log ("#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d", count, status, job.devId, job.command, job.request, job.retry);
} | javascript | function EventHandlerQueue (status, job){
console.log ("#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d", count, status, job.devId, job.command, job.request, job.retry);
} | [
"function",
"EventHandlerQueue",
"(",
"status",
",",
"job",
")",
"{",
"console",
".",
"log",
"(",
"\"#%d- Queue Status=%s DevId=%s Command=%s JobReq=%d Retry=%d\"",
",",
"count",
",",
"status",
",",
"job",
".",
"devId",
",",
"job",
".",
"command",
",",
"job",
".... | Simple counter to make easier to follow message flow Events from queued jobs | [
"Simple",
"counter",
"to",
"make",
"easier",
"to",
"follow",
"message",
"flow",
"Events",
"from",
"queued",
"jobs"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/bin/Tracker2Json.js#L107-L109 |
33,339 | Erdiko/ngx-user-admin | dist/bundles/ng-user-admin.umd.js | mergeResolvedReflectiveProviders | function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
for (var /** @type {?} */ i = 0; i < providers.length; i++) {
var /** @type {?} */ provider = providers[i];
var /** @type {?} */ existing = normalizedProvidersMap.get(provider.key.id);
if (existing) {
if (provider.multiProvider !== existing.multiProvider) {
throw new MixingMultiProvidersWithRegularProvidersError(existing, provider);
}
if (provider.multiProvider) {
for (var /** @type {?} */ j = 0; j < provider.resolvedFactories.length; j++) {
existing.resolvedFactories.push(provider.resolvedFactories[j]);
}
}
else {
normalizedProvidersMap.set(provider.key.id, provider);
}
}
else {
var /** @type {?} */ resolvedProvider = void 0;
if (provider.multiProvider) {
resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
}
else {
resolvedProvider = provider;
}
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
}
}
return normalizedProvidersMap;
} | javascript | function mergeResolvedReflectiveProviders(providers, normalizedProvidersMap) {
for (var /** @type {?} */ i = 0; i < providers.length; i++) {
var /** @type {?} */ provider = providers[i];
var /** @type {?} */ existing = normalizedProvidersMap.get(provider.key.id);
if (existing) {
if (provider.multiProvider !== existing.multiProvider) {
throw new MixingMultiProvidersWithRegularProvidersError(existing, provider);
}
if (provider.multiProvider) {
for (var /** @type {?} */ j = 0; j < provider.resolvedFactories.length; j++) {
existing.resolvedFactories.push(provider.resolvedFactories[j]);
}
}
else {
normalizedProvidersMap.set(provider.key.id, provider);
}
}
else {
var /** @type {?} */ resolvedProvider = void 0;
if (provider.multiProvider) {
resolvedProvider = new ResolvedReflectiveProvider_(provider.key, provider.resolvedFactories.slice(), provider.multiProvider);
}
else {
resolvedProvider = provider;
}
normalizedProvidersMap.set(provider.key.id, resolvedProvider);
}
}
return normalizedProvidersMap;
} | [
"function",
"mergeResolvedReflectiveProviders",
"(",
"providers",
",",
"normalizedProvidersMap",
")",
"{",
"for",
"(",
"var",
"/** @type {?} */",
"i",
"=",
"0",
";",
"i",
"<",
"providers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"/** @type {?} */",
"pr... | Merges a list of ResolvedProviders into a list where
each key is contained exactly once and multi providers
have been merged.
@param {?} providers
@param {?} normalizedProvidersMap
@return {?} | [
"Merges",
"a",
"list",
"of",
"ResolvedProviders",
"into",
"a",
"list",
"where",
"each",
"key",
"is",
"contained",
"exactly",
"once",
"and",
"multi",
"providers",
"have",
"been",
"merged",
"."
] | 21901b69f6af39764b813c11502c482b0e451537 | https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L2382-L2411 |
33,340 | Erdiko/ngx-user-admin | dist/bundles/ng-user-admin.umd.js | assertPlatform | function assertPlatform(requiredToken) {
var /** @type {?} */ platform = getPlatform();
if (!platform) {
throw new Error('No platform exists!');
}
if (!platform.injector.get(requiredToken, null)) {
throw new Error('A platform with a different configuration has been created. Please destroy it first.');
}
return platform;
} | javascript | function assertPlatform(requiredToken) {
var /** @type {?} */ platform = getPlatform();
if (!platform) {
throw new Error('No platform exists!');
}
if (!platform.injector.get(requiredToken, null)) {
throw new Error('A platform with a different configuration has been created. Please destroy it first.');
}
return platform;
} | [
"function",
"assertPlatform",
"(",
"requiredToken",
")",
"{",
"var",
"/** @type {?} */",
"platform",
"=",
"getPlatform",
"(",
")",
";",
"if",
"(",
"!",
"platform",
")",
"{",
"throw",
"new",
"Error",
"(",
"'No platform exists!'",
")",
";",
"}",
"if",
"(",
"... | Checks that there currently is a platform
which contains the given token as a provider.
\@experimental APIs related to application bootstrap are currently under review.
@param {?} requiredToken
@return {?} | [
"Checks",
"that",
"there",
"currently",
"is",
"a",
"platform",
"which",
"contains",
"the",
"given",
"token",
"as",
"a",
"provider",
"."
] | 21901b69f6af39764b813c11502c482b0e451537 | https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L8923-L8932 |
33,341 | Erdiko/ngx-user-admin | dist/bundles/ng-user-admin.umd.js | getLocale | function getLocale (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray$2(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
} | javascript | function getLocale (key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray$2(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
} | [
"function",
"getLocale",
"(",
"key",
")",
"{",
"var",
"locale",
";",
"if",
"(",
"key",
"&&",
"key",
".",
"_locale",
"&&",
"key",
".",
"_locale",
".",
"_abbr",
")",
"{",
"key",
"=",
"key",
".",
"_locale",
".",
"_abbr",
";",
"}",
"if",
"(",
"!",
... | returns locale data | [
"returns",
"locale",
"data"
] | 21901b69f6af39764b813c11502c482b0e451537 | https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L31707-L31728 |
33,342 | Erdiko/ngx-user-admin | dist/bundles/ng-user-admin.umd.js | ComponentLoader | function ComponentLoader(_viewContainerRef, _renderer, _elementRef, _injector, _componentFactoryResolver, _ngZone, _posService) {
this.onBeforeShow = new EventEmitter();
this.onShown = new EventEmitter();
this.onBeforeHide = new EventEmitter();
this.onHidden = new EventEmitter();
this._providers = [];
this._ngZone = _ngZone;
this._injector = _injector;
this._renderer = _renderer;
this._elementRef = _elementRef;
this._posService = _posService;
this._viewContainerRef = _viewContainerRef;
this._componentFactoryResolver = _componentFactoryResolver;
} | javascript | function ComponentLoader(_viewContainerRef, _renderer, _elementRef, _injector, _componentFactoryResolver, _ngZone, _posService) {
this.onBeforeShow = new EventEmitter();
this.onShown = new EventEmitter();
this.onBeforeHide = new EventEmitter();
this.onHidden = new EventEmitter();
this._providers = [];
this._ngZone = _ngZone;
this._injector = _injector;
this._renderer = _renderer;
this._elementRef = _elementRef;
this._posService = _posService;
this._viewContainerRef = _viewContainerRef;
this._componentFactoryResolver = _componentFactoryResolver;
} | [
"function",
"ComponentLoader",
"(",
"_viewContainerRef",
",",
"_renderer",
",",
"_elementRef",
",",
"_injector",
",",
"_componentFactoryResolver",
",",
"_ngZone",
",",
"_posService",
")",
"{",
"this",
".",
"onBeforeShow",
"=",
"new",
"EventEmitter",
"(",
")",
";",... | Do not use this directly, it should be instanced via
`ComponentLoadFactory.attach`
@internal
@param _viewContainerRef
@param _elementRef
@param _injector
@param _renderer
@param _componentFactoryResolver
@param _ngZone
@param _posService
tslint:disable-next-line | [
"Do",
"not",
"use",
"this",
"directly",
"it",
"should",
"be",
"instanced",
"via",
"ComponentLoadFactory",
".",
"attach"
] | 21901b69f6af39764b813c11502c482b0e451537 | https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L34953-L34966 |
33,343 | Erdiko/ngx-user-admin | dist/bundles/ng-user-admin.umd.js | delayWhen$2 | function delayWhen$2(delayDurationSelector, subscriptionDelay) {
if (subscriptionDelay) {
return new SubscriptionDelayObservable(this, subscriptionDelay)
.lift(new DelayWhenOperator(delayDurationSelector));
}
return this.lift(new DelayWhenOperator(delayDurationSelector));
} | javascript | function delayWhen$2(delayDurationSelector, subscriptionDelay) {
if (subscriptionDelay) {
return new SubscriptionDelayObservable(this, subscriptionDelay)
.lift(new DelayWhenOperator(delayDurationSelector));
}
return this.lift(new DelayWhenOperator(delayDurationSelector));
} | [
"function",
"delayWhen$2",
"(",
"delayDurationSelector",
",",
"subscriptionDelay",
")",
"{",
"if",
"(",
"subscriptionDelay",
")",
"{",
"return",
"new",
"SubscriptionDelayObservable",
"(",
"this",
",",
"subscriptionDelay",
")",
".",
"lift",
"(",
"new",
"DelayWhenOper... | Delays the emission of items from the source Observable by a given time span
determined by the emissions of another Observable.
<span class="informal">It's like {@link delay}, but the time span of the
delay duration is determined by a second Observable.</span>
<img src="./img/delayWhen.png" width="100%">
`delayWhen` time shifts each emitted value from the source Observable by a
time span determined by another Observable. When the source emits a value,
the `delayDurationSelector` function is called with the source value as
argument, and should return an Observable, called the "duration" Observable.
The source value is emitted on the output Observable only when the duration
Observable emits a value or completes.
Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which
is an Observable. When `subscriptionDelay` emits its first value or
completes, the source Observable is subscribed to and starts behaving like
described in the previous paragraph. If `subscriptionDelay` is not provided,
`delayWhen` will subscribe to the source Observable as soon as the output
Observable is subscribed.
@example <caption>Delay each click by a random amount of time, between 0 and 5 seconds</caption>
var clicks = Rx.Observable.fromEvent(document, 'click');
var delayedClicks = clicks.delayWhen(event =>
Rx.Observable.interval(Math.random() * 5000)
);
delayedClicks.subscribe(x => console.log(x));
@see {@link debounce}
@see {@link delay}
@param {function(value: T): Observable} delayDurationSelector A function that
returns an Observable for each value emitted by the source Observable, which
is then used to delay the emission of that item on the output Observable
until the Observable returned from this function emits a value.
@param {Observable} subscriptionDelay An Observable that triggers the
subscription to the source Observable once it emits any value.
@return {Observable} An Observable that delays the emissions of the source
Observable by an amount of time specified by the Observable returned by
`delayDurationSelector`.
@method delayWhen
@owner Observable | [
"Delays",
"the",
"emission",
"of",
"items",
"from",
"the",
"source",
"Observable",
"by",
"a",
"given",
"time",
"span",
"determined",
"by",
"the",
"emissions",
"of",
"another",
"Observable",
"."
] | 21901b69f6af39764b813c11502c482b0e451537 | https://github.com/Erdiko/ngx-user-admin/blob/21901b69f6af39764b813c11502c482b0e451537/dist/bundles/ng-user-admin.umd.js#L47236-L47242 |
33,344 | niieani/chunk-splitting-plugin | ChunkSplittingPlugin.js | leadingZeros | function leadingZeros(number, minLength = 0, padWith = '0') {
const stringNumber = number.toString()
const paddingLength = minLength - stringNumber.length
return paddingLength > 0 ? `${padWith.repeat(paddingLength)}${stringNumber}` : stringNumber
} | javascript | function leadingZeros(number, minLength = 0, padWith = '0') {
const stringNumber = number.toString()
const paddingLength = minLength - stringNumber.length
return paddingLength > 0 ? `${padWith.repeat(paddingLength)}${stringNumber}` : stringNumber
} | [
"function",
"leadingZeros",
"(",
"number",
",",
"minLength",
"=",
"0",
",",
"padWith",
"=",
"'0'",
")",
"{",
"const",
"stringNumber",
"=",
"number",
".",
"toString",
"(",
")",
"const",
"paddingLength",
"=",
"minLength",
"-",
"stringNumber",
".",
"length",
... | Ensures a number is padded with a certain amount of leading characters
@param {number} number
@param {number} minLength
@param {string} padWith | [
"Ensures",
"a",
"number",
"is",
"padded",
"with",
"a",
"certain",
"amount",
"of",
"leading",
"characters"
] | 6af9e696751d882219d8fc0ead6865522034ba29 | https://github.com/niieani/chunk-splitting-plugin/blob/6af9e696751d882219d8fc0ead6865522034ba29/ChunkSplittingPlugin.js#L62-L66 |
33,345 | fulup-bzh/GeoGate | server/adapters/HttpAjax-adapter.js | function(dbresult) {
// start with response header
var jsonresponse= // validate syntaxe at http://geojsonlint.com/
{"type":"GeometryCollection"
,"device":
{"type":"Device"
,"class":device.class
,"model": device.model
,"call": device.call
},"properties":
{"type":"Properties"
,'id' : query.devid
,"name": device.name
,'url': devurl
,'img': device.img
}
,"geometries":[]
};
for (var idx in dbresult) {
var pos = dbresult [idx];
var ptsinfo=util.format ("%s<br>Position:[%s,%s] Speed:%s",pos.date,pos.lon.toFixed(4),pos.lat.toFixed(4),pos.sog.toFixed(1));
jsonresponse.geometries.push (
{'type':'Point'
,'coordinates' :[pos.lon, pos.lat]
,'sog' : pos.sog
,'cog' : pos.cog
,'date' : pos.date.getTime()
,'properties' :
{'type':'Properties'
,"title": ptsinfo
}});
};
if (query.jsoncallback === undefined) {
response.writeHead(200,{"Content-Type": "application/json"});
response.write(JSON.stringify(jsonresponse));
} else {
response.writeHead(200,{"Content-Type": "text/javascript",'Cache-Control':'no-cache'});
var fakescript=query.jsoncallback +'(' + JSON.stringify(jsonresponse) +');';
response.write (fakescript);
}
response.end();
} | javascript | function(dbresult) {
// start with response header
var jsonresponse= // validate syntaxe at http://geojsonlint.com/
{"type":"GeometryCollection"
,"device":
{"type":"Device"
,"class":device.class
,"model": device.model
,"call": device.call
},"properties":
{"type":"Properties"
,'id' : query.devid
,"name": device.name
,'url': devurl
,'img': device.img
}
,"geometries":[]
};
for (var idx in dbresult) {
var pos = dbresult [idx];
var ptsinfo=util.format ("%s<br>Position:[%s,%s] Speed:%s",pos.date,pos.lon.toFixed(4),pos.lat.toFixed(4),pos.sog.toFixed(1));
jsonresponse.geometries.push (
{'type':'Point'
,'coordinates' :[pos.lon, pos.lat]
,'sog' : pos.sog
,'cog' : pos.cog
,'date' : pos.date.getTime()
,'properties' :
{'type':'Properties'
,"title": ptsinfo
}});
};
if (query.jsoncallback === undefined) {
response.writeHead(200,{"Content-Type": "application/json"});
response.write(JSON.stringify(jsonresponse));
} else {
response.writeHead(200,{"Content-Type": "text/javascript",'Cache-Control':'no-cache'});
var fakescript=query.jsoncallback +'(' + JSON.stringify(jsonresponse) +');';
response.write (fakescript);
}
response.end();
} | [
"function",
"(",
"dbresult",
")",
"{",
"// start with response header",
"var",
"jsonresponse",
"=",
"// validate syntaxe at http://geojsonlint.com/",
"{",
"\"type\"",
":",
"\"GeometryCollection\"",
",",
"\"device\"",
":",
"{",
"\"type\"",
":",
"\"Device\"",
",",
"\"class\... | DB callback return a json object with device name and possition | [
"DB",
"callback",
"return",
"a",
"json",
"object",
"with",
"device",
"name",
"and",
"possition"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/HttpAjax-adapter.js#L145-L187 | |
33,346 | fulup-bzh/GeoGate | server/adapters/HttpAjax-adapter.js | ReadFileCB | function ReadFileCB (err, byteread, buffer) {
if (err) {
response.write(err.toString());
} else {
response.write(buffer);
}
response.end();
} | javascript | function ReadFileCB (err, byteread, buffer) {
if (err) {
response.write(err.toString());
} else {
response.write(buffer);
}
response.end();
} | [
"function",
"ReadFileCB",
"(",
"err",
",",
"byteread",
",",
"buffer",
")",
"{",
"if",
"(",
"err",
")",
"{",
"response",
".",
"write",
"(",
"err",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"response",
".",
"write",
"(",
"buffer",
")",
... | push file back onto response HTTP response handler | [
"push",
"file",
"back",
"onto",
"response",
"HTTP",
"response",
"handler"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/HttpAjax-adapter.js#L232-L239 |
33,347 | fulup-bzh/GeoGate | server/adapters/HttpAjax-adapter.js | OpenFileCB | function OpenFileCB (err, fd) {
if (err) {
response.setHeader('Content-Type','text/html');
response.writeHead(404, err.toString("utf8"));
response.write("Hoops:" + err );
response.end();
return;
}
fs.fstat(fd, function(err,stats){
// get file size and allocate buffer to read it
var buffer = new Buffer (stats.size);
fs.read (fd, buffer,0,buffer.length,0,ReadFileCB);
});
} | javascript | function OpenFileCB (err, fd) {
if (err) {
response.setHeader('Content-Type','text/html');
response.writeHead(404, err.toString("utf8"));
response.write("Hoops:" + err );
response.end();
return;
}
fs.fstat(fd, function(err,stats){
// get file size and allocate buffer to read it
var buffer = new Buffer (stats.size);
fs.read (fd, buffer,0,buffer.length,0,ReadFileCB);
});
} | [
"function",
"OpenFileCB",
"(",
"err",
",",
"fd",
")",
"{",
"if",
"(",
"err",
")",
"{",
"response",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'text/html'",
")",
";",
"response",
".",
"writeHead",
"(",
"404",
",",
"err",
".",
"toString",
"(",
"\"utf... | open file and check if its supported | [
"open",
"file",
"and",
"check",
"if",
"its",
"supported"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/HttpAjax-adapter.js#L242-L255 |
33,348 | fulup-bzh/GeoGate | server/backends/MongoDB-backend.js | CreateConnection | function CreateConnection (backend) {
backend.Debug (4, "MongoDB creating connection [%s]", backend.uid);
MongoClient.connect(backend.uid, function (err, db) {
if (err) {
backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err)
} else {
backend.Debug (4, "Connected to MongoDB: %s", backend.uid)
backend.base = db;
}
});
} | javascript | function CreateConnection (backend) {
backend.Debug (4, "MongoDB creating connection [%s]", backend.uid);
MongoClient.connect(backend.uid, function (err, db) {
if (err) {
backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err)
} else {
backend.Debug (4, "Connected to MongoDB: %s", backend.uid)
backend.base = db;
}
});
} | [
"function",
"CreateConnection",
"(",
"backend",
")",
"{",
"backend",
".",
"Debug",
"(",
"4",
",",
"\"MongoDB creating connection [%s]\"",
",",
"backend",
".",
"uid",
")",
";",
"MongoClient",
".",
"connect",
"(",
"backend",
".",
"uid",
",",
"function",
"(",
"... | 10s timeout in between two MONGO reconnects ConnectDB is done on at creation time | [
"10s",
"timeout",
"in",
"between",
"two",
"MONGO",
"reconnects",
"ConnectDB",
"is",
"done",
"on",
"at",
"creation",
"time"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/backends/MongoDB-backend.js#L25-L36 |
33,349 | fulup-bzh/GeoGate | server/backends/MongoDB-backend.js | BackendStorage | function BackendStorage (gateway, opts){
// prepare ourself to make debug possible
this.debug =opts.debug;
this.gateway=gateway;
this.opts=
{ hostname : opts.mongodb.hostname || "localhost"
, username : opts.mongodb.username
, password : opts.mongodb.password
, basename : opts.mongodb.basename || opts.mongo.username
, port : opts.mongodb.port || 27017
};
this.uid ="mongodb://" + this.opts.username + ':' + this.opts.password + "@" + this.opts.hostname +':'+ this.opts.port + "/" + this.opts.basename;
// create initial connection handler to database
CreateConnection (this);
} | javascript | function BackendStorage (gateway, opts){
// prepare ourself to make debug possible
this.debug =opts.debug;
this.gateway=gateway;
this.opts=
{ hostname : opts.mongodb.hostname || "localhost"
, username : opts.mongodb.username
, password : opts.mongodb.password
, basename : opts.mongodb.basename || opts.mongo.username
, port : opts.mongodb.port || 27017
};
this.uid ="mongodb://" + this.opts.username + ':' + this.opts.password + "@" + this.opts.hostname +':'+ this.opts.port + "/" + this.opts.basename;
// create initial connection handler to database
CreateConnection (this);
} | [
"function",
"BackendStorage",
"(",
"gateway",
",",
"opts",
")",
"{",
"// prepare ourself to make debug possible",
"this",
".",
"debug",
"=",
"opts",
".",
"debug",
";",
"this",
".",
"gateway",
"=",
"gateway",
";",
"this",
".",
"opts",
"=",
"{",
"hostname",
":... | Create MongoDB Backend object | [
"Create",
"MongoDB",
"Backend",
"object"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/backends/MongoDB-backend.js#L39-L56 |
33,350 | fulup-bzh/GeoGate | utils/USR-TCP232-Config.js | WriteIpAddr | function WriteIpAddr (buffer, offset, ipstring) {
var addr= ipstring.split('.');
buffer.writeUInt8(parseInt(addr[3]), offset);
buffer.writeUInt8(parseInt(addr[2]), offset + 1);
buffer.writeUInt8(parseInt(addr[1]), offset + 2);
buffer.writeUInt8(parseInt(addr[0]), offset + 3);
} | javascript | function WriteIpAddr (buffer, offset, ipstring) {
var addr= ipstring.split('.');
buffer.writeUInt8(parseInt(addr[3]), offset);
buffer.writeUInt8(parseInt(addr[2]), offset + 1);
buffer.writeUInt8(parseInt(addr[1]), offset + 2);
buffer.writeUInt8(parseInt(addr[0]), offset + 3);
} | [
"function",
"WriteIpAddr",
"(",
"buffer",
",",
"offset",
",",
"ipstring",
")",
"{",
"var",
"addr",
"=",
"ipstring",
".",
"split",
"(",
"'.'",
")",
";",
"buffer",
".",
"writeUInt8",
"(",
"parseInt",
"(",
"addr",
"[",
"3",
"]",
")",
",",
"offset",
")",... | adapter address at discovery parse IP Addr and add it to config buffer | [
"adapter",
"address",
"at",
"discovery",
"parse",
"IP",
"Addr",
"and",
"add",
"it",
"to",
"config",
"buffer"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/utils/USR-TCP232-Config.js#L92-L98 |
33,351 | fulup-bzh/GeoGate | simulator/lib/GG-NmeaAisEncoder.js | NmeaAisEncoder | function NmeaAisEncoder (data) {
var msg;
// Use NMEA GRPMC or AIVDM depending on Vessel MMSI
if (data.mmsi === 0) {
// this ship has no MMSI let's use GPRMC format
switch (data.cmd) {
case 1:
msg = { // built a Fake NMEA authentication message
valid: true,
nmea: "FAKID" + data.mmsi +',' + data.shipname
};
break;
case 2:
msg = new GGencode.NmeaEncode(data);
break;
default:
msg = null;
}
} else {
// we are facing multiple boats use AIS ADVDM
switch (data.cmd) {
case 1:
if (data.class === 'A') data.aistype = 5; else data.aistype = 24;
msg = new GGencode.AisEncode(data);
break;
case 2:
if (data.class === 'A') data.aistype = 3; else data.aistype = 18;
msg = new GGencode.AisEncode(data);
break;
default:
msg = null;
}
}
if (msg.valid) return (msg.nmea);
else return (null);
} | javascript | function NmeaAisEncoder (data) {
var msg;
// Use NMEA GRPMC or AIVDM depending on Vessel MMSI
if (data.mmsi === 0) {
// this ship has no MMSI let's use GPRMC format
switch (data.cmd) {
case 1:
msg = { // built a Fake NMEA authentication message
valid: true,
nmea: "FAKID" + data.mmsi +',' + data.shipname
};
break;
case 2:
msg = new GGencode.NmeaEncode(data);
break;
default:
msg = null;
}
} else {
// we are facing multiple boats use AIS ADVDM
switch (data.cmd) {
case 1:
if (data.class === 'A') data.aistype = 5; else data.aistype = 24;
msg = new GGencode.AisEncode(data);
break;
case 2:
if (data.class === 'A') data.aistype = 3; else data.aistype = 18;
msg = new GGencode.AisEncode(data);
break;
default:
msg = null;
}
}
if (msg.valid) return (msg.nmea);
else return (null);
} | [
"function",
"NmeaAisEncoder",
"(",
"data",
")",
"{",
"var",
"msg",
";",
"// Use NMEA GRPMC or AIVDM depending on Vessel MMSI",
"if",
"(",
"data",
".",
"mmsi",
"===",
"0",
")",
"{",
"// this ship has no MMSI let's use GPRMC format",
"switch",
"(",
"data",
".",
"cmd",
... | Encode AIS AIVDM or GPRMC depending on position MMSI | [
"Encode",
"AIS",
"AIVDM",
"or",
"GPRMC",
"depending",
"on",
"position",
"MMSI"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-NmeaAisEncoder.js#L29-L65 |
33,352 | fulup-bzh/GeoGate | simulator/lib/GG-Simulator.js | JobQueuePost | function JobQueuePost (job, callback) {
// dummy job to activate jobqueue
if (job === null) {
callback ();
return;
} else {
// force change to simulator context
job.simulator.NewPosition.call (job.simulator, job);
}
// wait tic time before sending next message
job.simulator.queue.pause ();
// provide some randomization on tic with a 50% fluxtuation
var nexttic = parseInt (job.simulator.ticms * (1+ Math.random()/2));
setTimeout(function () {job.simulator.queue.resume();}, nexttic);
callback ();
} | javascript | function JobQueuePost (job, callback) {
// dummy job to activate jobqueue
if (job === null) {
callback ();
return;
} else {
// force change to simulator context
job.simulator.NewPosition.call (job.simulator, job);
}
// wait tic time before sending next message
job.simulator.queue.pause ();
// provide some randomization on tic with a 50% fluxtuation
var nexttic = parseInt (job.simulator.ticms * (1+ Math.random()/2));
setTimeout(function () {job.simulator.queue.resume();}, nexttic);
callback ();
} | [
"function",
"JobQueuePost",
"(",
"job",
",",
"callback",
")",
"{",
"// dummy job to activate jobqueue",
"if",
"(",
"job",
"===",
"null",
")",
"{",
"callback",
"(",
")",
";",
"return",
";",
"}",
"else",
"{",
"// force change to simulator context",
"job",
".",
"... | Notice method is called by async within async context !!!! | [
"Notice",
"method",
"is",
"called",
"by",
"async",
"within",
"async",
"context",
"!!!!"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Simulator.js#L76-L91 |
33,353 | fulup-bzh/GeoGate | simulator/lib/GG-Simulator.js | JobQueueActivate | function JobQueueActivate(queue, callback, timeout) {
setTimeout(function () {queue.push (null, callback);}, timeout); // wait 5S before start
} | javascript | function JobQueueActivate(queue, callback, timeout) {
setTimeout(function () {queue.push (null, callback);}, timeout); // wait 5S before start
} | [
"function",
"JobQueueActivate",
"(",
"queue",
",",
"callback",
",",
"timeout",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"queue",
".",
"push",
"(",
"null",
",",
"callback",
")",
";",
"}",
",",
"timeout",
")",
";",
"// wait 5S before start",
... | push a dummy job in queue to force activation | [
"push",
"a",
"dummy",
"job",
"in",
"queue",
"to",
"force",
"activation"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/simulator/lib/GG-Simulator.js#L196-L198 |
33,354 | fulup-bzh/GeoGate | server/adapters/AisTcpProxy-adapter.js | EventDevAuth | function EventDevAuth (device){
if (!device.mmsi) device.mmsi = parseInt (device.devid);
if (isNaN (device.mmsi)) device.mmsi=String2Hash(device.devid);
adapter.BroadcastStatic (device);
if (device.stamp) adapter.BroadcastPos (device);
} | javascript | function EventDevAuth (device){
if (!device.mmsi) device.mmsi = parseInt (device.devid);
if (isNaN (device.mmsi)) device.mmsi=String2Hash(device.devid);
adapter.BroadcastStatic (device);
if (device.stamp) adapter.BroadcastPos (device);
} | [
"function",
"EventDevAuth",
"(",
"device",
")",
"{",
"if",
"(",
"!",
"device",
".",
"mmsi",
")",
"device",
".",
"mmsi",
"=",
"parseInt",
"(",
"device",
".",
"devid",
")",
";",
"if",
"(",
"isNaN",
"(",
"device",
".",
"mmsi",
")",
")",
"device",
".",... | if no MMSI avaliable let's try to build a fakeone | [
"if",
"no",
"MMSI",
"avaliable",
"let",
"s",
"try",
"to",
"build",
"a",
"fakeone"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/adapters/AisTcpProxy-adapter.js#L53-L58 |
33,355 | fulup-bzh/GeoGate | smsc/lib/GG-SmsBatch.js | SmsBatch | function SmsBatch (smsc, callback, smsarray) {
var idx=0;
// when message is processed move to next one otherwise call user applicationCB
function InternalCB (data) {
// [good or bad] let's notify user application
if (data.status != 0) callback (data);
// it's time to move to next message
if (data.status <= 0) {
if (++idx < smsarray.length) {
new SmsRequest (smsc, InternalCB, smsarray [idx]);
} else {
callback ({status: 0});
}
}
}
// let's start by sending 1st SMS of the array
new SmsRequest(smsc, InternalCB, smsarray [idx]);
} | javascript | function SmsBatch (smsc, callback, smsarray) {
var idx=0;
// when message is processed move to next one otherwise call user applicationCB
function InternalCB (data) {
// [good or bad] let's notify user application
if (data.status != 0) callback (data);
// it's time to move to next message
if (data.status <= 0) {
if (++idx < smsarray.length) {
new SmsRequest (smsc, InternalCB, smsarray [idx]);
} else {
callback ({status: 0});
}
}
}
// let's start by sending 1st SMS of the array
new SmsRequest(smsc, InternalCB, smsarray [idx]);
} | [
"function",
"SmsBatch",
"(",
"smsc",
",",
"callback",
",",
"smsarray",
")",
"{",
"var",
"idx",
"=",
"0",
";",
"// when message is processed move to next one otherwise call user applicationCB",
"function",
"InternalCB",
"(",
"data",
")",
"{",
"// [good or bad] let's notify... | this method send a batch of SMS and call user CB with status=0 when finish | [
"this",
"method",
"send",
"a",
"batch",
"of",
"SMS",
"and",
"call",
"user",
"CB",
"with",
"status",
"=",
"0",
"when",
"finish"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsBatch.js#L24-L45 |
33,356 | fulup-bzh/GeoGate | smsc/lib/GG-SmsBatch.js | InternalCB | function InternalCB (data) {
// [good or bad] let's notify user application
if (data.status != 0) callback (data);
// it's time to move to next message
if (data.status <= 0) {
if (++idx < smsarray.length) {
new SmsRequest (smsc, InternalCB, smsarray [idx]);
} else {
callback ({status: 0});
}
}
} | javascript | function InternalCB (data) {
// [good or bad] let's notify user application
if (data.status != 0) callback (data);
// it's time to move to next message
if (data.status <= 0) {
if (++idx < smsarray.length) {
new SmsRequest (smsc, InternalCB, smsarray [idx]);
} else {
callback ({status: 0});
}
}
} | [
"function",
"InternalCB",
"(",
"data",
")",
"{",
"// [good or bad] let's notify user application",
"if",
"(",
"data",
".",
"status",
"!=",
"0",
")",
"callback",
"(",
"data",
")",
";",
"// it's time to move to next message",
"if",
"(",
"data",
".",
"status",
"<=",
... | when message is processed move to next one otherwise call user applicationCB | [
"when",
"message",
"is",
"processed",
"move",
"to",
"next",
"one",
"otherwise",
"call",
"user",
"applicationCB"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsBatch.js#L28-L41 |
33,357 | fulup-bzh/GeoGate | server/backends/Dummy-backend.js | BackendStorage | function BackendStorage (gateway, opts){
// prepare ourself to make debug possible
this.uid="Dummy@nothing";
this.gateway =gateway;
this.debug=opts.debug;
this.count=0;
this.storesize= 20 +1; // number of position slot/devices
this.event = new EventEmitter();
} | javascript | function BackendStorage (gateway, opts){
// prepare ourself to make debug possible
this.uid="Dummy@nothing";
this.gateway =gateway;
this.debug=opts.debug;
this.count=0;
this.storesize= 20 +1; // number of position slot/devices
this.event = new EventEmitter();
} | [
"function",
"BackendStorage",
"(",
"gateway",
",",
"opts",
")",
"{",
"// prepare ourself to make debug possible",
"this",
".",
"uid",
"=",
"\"Dummy@nothing\"",
";",
"this",
".",
"gateway",
"=",
"gateway",
";",
"this",
".",
"debug",
"=",
"opts",
".",
"debug",
"... | This is our fake device authentication DB table | [
"This",
"is",
"our",
"fake",
"device",
"authentication",
"DB",
"table"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/backends/Dummy-backend.js#L43-L53 |
33,358 | fulup-bzh/GeoGate | encoder/bin/Ais2JsonClient.js | function (job, callback) {
// decode AIS message ignoring any not AIDVM paquet
var nmea= job.toString ('ascii');
var ais = new AisDecode (nmea);
// if message valid and mssi not excluded by --mmsi option
if (ais.valid) {
// Some cleanup to make JSON/AIS more human readable
delete ais.bitarray;
delete ais.valid;
delete ais.length;
delete ais.channel;
delete ais.repeat;
delete ais.navstatus;
delete ais.utc;
ais.lon = (parseInt(ais.lon * 10000))/10000;
ais.lat = (parseInt(ais.lat * 10000))/10000;
ais.sog = (parseInt(ais.sog * 10))/10;
ais.cog = (parseInt(ais.cog * 10))/10;
// we do not need class for each navigation report
if (ais.msgtype === 18 || ais.msgtype === 3) {
delete ais.class;
}
MsgCount ++;
// push AIS usefull info to user
if (DumpFd !== null) {
fs.writeSync (DumpFd,MsgCount + " , " +JSON.stringify (ais)+'\n');
}
if ((MmsiFilter===null || MmsiFilter===parseInt(ais.mmsi))
&& (TypeFilter===null || TypeFilter===parseInt(ais.msgtype))){
console.log ("-%d- %s", MsgCount, JSON.stringify (ais));
}
if (Verbose) console.log ("-%d- %s", MsgCount, nmea)
} else {
if (Verbose) console.log ("\n-***- %s", nmea)
}
// we're done let's move to next job in queue
callback();
} | javascript | function (job, callback) {
// decode AIS message ignoring any not AIDVM paquet
var nmea= job.toString ('ascii');
var ais = new AisDecode (nmea);
// if message valid and mssi not excluded by --mmsi option
if (ais.valid) {
// Some cleanup to make JSON/AIS more human readable
delete ais.bitarray;
delete ais.valid;
delete ais.length;
delete ais.channel;
delete ais.repeat;
delete ais.navstatus;
delete ais.utc;
ais.lon = (parseInt(ais.lon * 10000))/10000;
ais.lat = (parseInt(ais.lat * 10000))/10000;
ais.sog = (parseInt(ais.sog * 10))/10;
ais.cog = (parseInt(ais.cog * 10))/10;
// we do not need class for each navigation report
if (ais.msgtype === 18 || ais.msgtype === 3) {
delete ais.class;
}
MsgCount ++;
// push AIS usefull info to user
if (DumpFd !== null) {
fs.writeSync (DumpFd,MsgCount + " , " +JSON.stringify (ais)+'\n');
}
if ((MmsiFilter===null || MmsiFilter===parseInt(ais.mmsi))
&& (TypeFilter===null || TypeFilter===parseInt(ais.msgtype))){
console.log ("-%d- %s", MsgCount, JSON.stringify (ais));
}
if (Verbose) console.log ("-%d- %s", MsgCount, nmea)
} else {
if (Verbose) console.log ("\n-***- %s", nmea)
}
// we're done let's move to next job in queue
callback();
} | [
"function",
"(",
"job",
",",
"callback",
")",
"{",
"// decode AIS message ignoring any not AIDVM paquet",
"var",
"nmea",
"=",
"job",
".",
"toString",
"(",
"'ascii'",
")",
";",
"var",
"ais",
"=",
"new",
"AisDecode",
"(",
"nmea",
")",
";",
"// if message valid and... | Notice method is called by async within unknow context !!!! | [
"Notice",
"method",
"is",
"called",
"by",
"async",
"within",
"unknow",
"context",
"!!!!"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/encoder/bin/Ais2JsonClient.js#L62-L105 | |
33,359 | fulup-bzh/GeoGate | smsc/lib/GG-SmsRequest.js | CheckDevAckCB | function CheckDevAckCB(err, results) {
self.retry ++; // retry counter for ACK
self.Debug (6, "CheckDevAckCB Phone=%s Retry=%d/%d Result=%j", smscmd.phone, self.retry, smsc.opts.retry, results);
// ack no received
if (results.length === 0) {
if (self.retry <= smsc.opts.retry) {
setTimeout (function() {CheckDevAck ();}, smsc.opts.delay);
} else {
self.Debug (7, "CheckDevAckCB Ack Abandoned MaxRetry=%s", smsc.opts.retry);
appcb ({status: -2, smsid: smscmd.id});
}
} else {
// we may have more than one responses for a given command
for (var slot in results) {
var ack =
{ status: 2
, smsid: smscmd.id
, phone: smscmd.phone
, ack: results[slot].TextDecoded
};
// ACK received, delete it from inbox and send it to application
self.Debug (6, "CheckDevAckCB Ack Received %j", ack);
smsc.DelById (DelByIdCB, results[slot].Id);
appcb({status: 2, smsid: smscmd.id, msg: ack});
}
appcb({status: 0});
}
} | javascript | function CheckDevAckCB(err, results) {
self.retry ++; // retry counter for ACK
self.Debug (6, "CheckDevAckCB Phone=%s Retry=%d/%d Result=%j", smscmd.phone, self.retry, smsc.opts.retry, results);
// ack no received
if (results.length === 0) {
if (self.retry <= smsc.opts.retry) {
setTimeout (function() {CheckDevAck ();}, smsc.opts.delay);
} else {
self.Debug (7, "CheckDevAckCB Ack Abandoned MaxRetry=%s", smsc.opts.retry);
appcb ({status: -2, smsid: smscmd.id});
}
} else {
// we may have more than one responses for a given command
for (var slot in results) {
var ack =
{ status: 2
, smsid: smscmd.id
, phone: smscmd.phone
, ack: results[slot].TextDecoded
};
// ACK received, delete it from inbox and send it to application
self.Debug (6, "CheckDevAckCB Ack Received %j", ack);
smsc.DelById (DelByIdCB, results[slot].Id);
appcb({status: 2, smsid: smscmd.id, msg: ack});
}
appcb({status: 0});
}
} | [
"function",
"CheckDevAckCB",
"(",
"err",
",",
"results",
")",
"{",
"self",
".",
"retry",
"++",
";",
"// retry counter for ACK",
"self",
".",
"Debug",
"(",
"6",
",",
"\"CheckDevAckCB Phone=%s Retry=%d/%d Result=%j\"",
",",
"smscmd",
".",
"phone",
",",
"self",
"."... | this method is called by MySql when sms.GetFrom return | [
"this",
"method",
"is",
"called",
"by",
"MySql",
"when",
"sms",
".",
"GetFrom",
"return"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L36-L63 |
33,360 | fulup-bzh/GeoGate | smsc/lib/GG-SmsRequest.js | CheckDevAck | function CheckDevAck() {
self.Debug (3,"Waiting Acknowledgment Response %d/%d", self.retry, smsc.opts.retry);
smsc.GetFrom (CheckDevAckCB, smscmd.phone)
} | javascript | function CheckDevAck() {
self.Debug (3,"Waiting Acknowledgment Response %d/%d", self.retry, smsc.opts.retry);
smsc.GetFrom (CheckDevAckCB, smscmd.phone)
} | [
"function",
"CheckDevAck",
"(",
")",
"{",
"self",
".",
"Debug",
"(",
"3",
",",
"\"Waiting Acknowledgment Response %d/%d\"",
",",
"self",
".",
"retry",
",",
"smsc",
".",
"opts",
".",
"retry",
")",
";",
"smsc",
".",
"GetFrom",
"(",
"CheckDevAckCB",
",",
"sms... | this method check sms inbox table for OK ack from device | [
"this",
"method",
"check",
"sms",
"inbox",
"table",
"for",
"OK",
"ack",
"from",
"device"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L66-L69 |
33,361 | fulup-bzh/GeoGate | smsc/lib/GG-SmsRequest.js | CheckOutboxCB | function CheckOutboxCB(err, results) {
var result = results[0]; // Query result is alway an array of response even when unique
self.retry ++; // update retry counter
// if message is still in queue retry
self.Debug (6,"CheckOutboxCB Phone=%s Result=%j Retry=%d/%d", smscmd.phone, result, self.retry, smsc.opts.retry);
if (result !== undefined) {
// message is still in queue loop one more time
if (self.retry <= smsc.opts.retry) {
setTimeout (function() {CheckOutbox (result.ID);}, smsc.opts.delay);
} else {
// notify appcb that SMS failed and was deleted
self.Debug (6,"CheckOutboxCB Fail SqlId=%s SMS=%j", result.ID, smscmd);
smsc.DelById (DelByIdCB, result.ID);
appcb ({status: -1, smsid: smscmd.id});
}
} else {
// le message à été expédié
self.Debug (6,"CheckOutboxCB OK SMS=%j", smscmd);
appcb ({status: 1, smsid: smscmd.id});
// if an acknowledgement is asked loop until we get it.
if (smscmd.ack) {
self.retry = 0; // reset retry counter for ack
setTimeout (function() {CheckDevAck (smscmd);}, smsc.opts.delay);
} else {
appcb ({status: 0});
}
}
} | javascript | function CheckOutboxCB(err, results) {
var result = results[0]; // Query result is alway an array of response even when unique
self.retry ++; // update retry counter
// if message is still in queue retry
self.Debug (6,"CheckOutboxCB Phone=%s Result=%j Retry=%d/%d", smscmd.phone, result, self.retry, smsc.opts.retry);
if (result !== undefined) {
// message is still in queue loop one more time
if (self.retry <= smsc.opts.retry) {
setTimeout (function() {CheckOutbox (result.ID);}, smsc.opts.delay);
} else {
// notify appcb that SMS failed and was deleted
self.Debug (6,"CheckOutboxCB Fail SqlId=%s SMS=%j", result.ID, smscmd);
smsc.DelById (DelByIdCB, result.ID);
appcb ({status: -1, smsid: smscmd.id});
}
} else {
// le message à été expédié
self.Debug (6,"CheckOutboxCB OK SMS=%j", smscmd);
appcb ({status: 1, smsid: smscmd.id});
// if an acknowledgement is asked loop until we get it.
if (smscmd.ack) {
self.retry = 0; // reset retry counter for ack
setTimeout (function() {CheckDevAck (smscmd);}, smsc.opts.delay);
} else {
appcb ({status: 0});
}
}
} | [
"function",
"CheckOutboxCB",
"(",
"err",
",",
"results",
")",
"{",
"var",
"result",
"=",
"results",
"[",
"0",
"]",
";",
"// Query result is alway an array of response even when unique",
"self",
".",
"retry",
"++",
";",
"// update retry counter",
"// if message is still ... | this function is call when MySql checked outbox | [
"this",
"function",
"is",
"call",
"when",
"MySql",
"checked",
"outbox"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L72-L101 |
33,362 | fulup-bzh/GeoGate | smsc/lib/GG-SmsRequest.js | CheckOutbox | function CheckOutbox (insertId) {
self.Debug (3,"Waiting Sent Confirmation %d/%d", self.retry, smsc.opts.retry);
smsc.CheckById (CheckOutboxCB, insertId)
} | javascript | function CheckOutbox (insertId) {
self.Debug (3,"Waiting Sent Confirmation %d/%d", self.retry, smsc.opts.retry);
smsc.CheckById (CheckOutboxCB, insertId)
} | [
"function",
"CheckOutbox",
"(",
"insertId",
")",
"{",
"self",
".",
"Debug",
"(",
"3",
",",
"\"Waiting Sent Confirmation %d/%d\"",
",",
"self",
".",
"retry",
",",
"smsc",
".",
"opts",
".",
"retry",
")",
";",
"smsc",
".",
"CheckById",
"(",
"CheckOutboxCB",
... | this function loop until SMS is effectively sent | [
"this",
"function",
"loop",
"until",
"SMS",
"is",
"effectively",
"sent"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L104-L107 |
33,363 | fulup-bzh/GeoGate | smsc/lib/GG-SmsRequest.js | SendToCB | function SendToCB (err, result) {
// check if sms was sent from output table
self.Debug (7,"SendToCB SMS=%j result=%j err=%j", smscmd, result, err);
if (err) {
self.Debug (1, "Insert in MySql outbox refused %s", err);
appcb ({status: -1, id: smscmd.id, error: err});
} else {
setTimeout (function() {CheckOutbox (result.insertId);}, smsc.opts.delay);
}
} | javascript | function SendToCB (err, result) {
// check if sms was sent from output table
self.Debug (7,"SendToCB SMS=%j result=%j err=%j", smscmd, result, err);
if (err) {
self.Debug (1, "Insert in MySql outbox refused %s", err);
appcb ({status: -1, id: smscmd.id, error: err});
} else {
setTimeout (function() {CheckOutbox (result.insertId);}, smsc.opts.delay);
}
} | [
"function",
"SendToCB",
"(",
"err",
",",
"result",
")",
"{",
"// check if sms was sent from output table",
"self",
".",
"Debug",
"(",
"7",
",",
"\"SendToCB SMS=%j result=%j err=%j\"",
",",
"smscmd",
",",
"result",
",",
"err",
")",
";",
"if",
"(",
"err",
")",
"... | this function is called when MySql inserted SMS in outbox | [
"this",
"function",
"is",
"called",
"when",
"MySql",
"inserted",
"SMS",
"in",
"outbox"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsc/lib/GG-SmsRequest.js#L110-L119 |
33,364 | fulup-bzh/GeoGate | server/lib/_TcpClient.js | TcpClient | function TcpClient (socket) {
this.debug = socket.controller.debug; // inherit controller debug level
this.gateway = socket.controller.gateway;
this.controller= socket.controller;
this.adapter = socket.adapter;
this.socket = socket;
this.devid = false; // devid/mmsi directly from device or adapter
this.name = false;
this.logged = false;
this.alarmcount= 0; // count alarm messages
this.errorcount= 0; // number of ignore messages
this.jobcount = 0; // Job commands send to gateway
this.count = 0; // generic counter used by file backend
if (socket.remoteAddress !== undefined) {
this.uid= "tcpclient//" + this.adapter.info + "/remote:" + socket.remoteAddress +":" + socket.remotePort;
} else {
this.uid= "tcpclient://" + this.adapter.info + ":" + socket.port;
}
} | javascript | function TcpClient (socket) {
this.debug = socket.controller.debug; // inherit controller debug level
this.gateway = socket.controller.gateway;
this.controller= socket.controller;
this.adapter = socket.adapter;
this.socket = socket;
this.devid = false; // devid/mmsi directly from device or adapter
this.name = false;
this.logged = false;
this.alarmcount= 0; // count alarm messages
this.errorcount= 0; // number of ignore messages
this.jobcount = 0; // Job commands send to gateway
this.count = 0; // generic counter used by file backend
if (socket.remoteAddress !== undefined) {
this.uid= "tcpclient//" + this.adapter.info + "/remote:" + socket.remoteAddress +":" + socket.remotePort;
} else {
this.uid= "tcpclient://" + this.adapter.info + ":" + socket.port;
}
} | [
"function",
"TcpClient",
"(",
"socket",
")",
"{",
"this",
".",
"debug",
"=",
"socket",
".",
"controller",
".",
"debug",
";",
"// inherit controller debug level",
"this",
".",
"gateway",
"=",
"socket",
".",
"controller",
".",
"gateway",
";",
"this",
".",
"con... | called from TcpFeed class of adapter | [
"called",
"from",
"TcpFeed",
"class",
"of",
"adapter"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/server/lib/_TcpClient.js#L61-L80 |
33,365 | fulup-bzh/GeoGate | encoder/lib/GG-NmeaDecode.js | function(lat){
// TK103 sample 4737.1024,N for 47°37'.1024
var deg= parseInt (lat[0]/100) || 0;
var min= lat[0] - (deg*100);
var dec= deg + (min/60);
if (lat [1] === 'S' || lat [1] === 'W') dec= dec * -1;
return (dec);
} | javascript | function(lat){
// TK103 sample 4737.1024,N for 47°37'.1024
var deg= parseInt (lat[0]/100) || 0;
var min= lat[0] - (deg*100);
var dec= deg + (min/60);
if (lat [1] === 'S' || lat [1] === 'W') dec= dec * -1;
return (dec);
} | [
"function",
"(",
"lat",
")",
"{",
"// TK103 sample 4737.1024,N for 47°37'.1024",
"var",
"deg",
"=",
"parseInt",
"(",
"lat",
"[",
"0",
"]",
"/",
"100",
")",
"||",
"0",
";",
"var",
"min",
"=",
"lat",
"[",
"0",
"]",
"-",
"(",
"deg",
"*",
"100",
")",
"... | Convert gps coordonnates in decimal | [
"Convert",
"gps",
"coordonnates",
"in",
"decimal"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/encoder/lib/GG-NmeaDecode.js#L96-L104 | |
33,366 | fulup-bzh/GeoGate | smsg/lib/GG-SmsControl.js | BatchCB | function BatchCB (response) {
console.log ("### Batch SMS CallBack --> Status=%j", response);
if (response.status === 0 || response.status === -4) {
console.log ("SMS Batch Test done");
setTimeout (process.exit, 1000);
}
} | javascript | function BatchCB (response) {
console.log ("### Batch SMS CallBack --> Status=%j", response);
if (response.status === 0 || response.status === -4) {
console.log ("SMS Batch Test done");
setTimeout (process.exit, 1000);
}
} | [
"function",
"BatchCB",
"(",
"response",
")",
"{",
"console",
".",
"log",
"(",
"\"### Batch SMS CallBack --> Status=%j\"",
",",
"response",
")",
";",
"if",
"(",
"response",
".",
"status",
"===",
"0",
"||",
"response",
".",
"status",
"===",
"-",
"4",
")",
"{... | Batch callback for acknowledgement | [
"Batch",
"callback",
"for",
"acknowledgement"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsg/lib/GG-SmsControl.js#L136-L143 |
33,367 | fulup-bzh/GeoGate | smsg/lib/GG-SmsControl.js | ResponseCB | function ResponseCB (response) {
console.log ("### Single SMS CallBack --> Status=%j", response);
if (response.status === 0) {
var batch = require('../sample/SmsCommand-batch');
smscontrol.ProcessBatch (BatchCB, phonenumber, password, batch);
}
if (response.status < 0) {
console.log ("Single SMS Test Fail");
setTimeout (process.exit, 1000);
}
} | javascript | function ResponseCB (response) {
console.log ("### Single SMS CallBack --> Status=%j", response);
if (response.status === 0) {
var batch = require('../sample/SmsCommand-batch');
smscontrol.ProcessBatch (BatchCB, phonenumber, password, batch);
}
if (response.status < 0) {
console.log ("Single SMS Test Fail");
setTimeout (process.exit, 1000);
}
} | [
"function",
"ResponseCB",
"(",
"response",
")",
"{",
"console",
".",
"log",
"(",
"\"### Single SMS CallBack --> Status=%j\"",
",",
"response",
")",
";",
"if",
"(",
"response",
".",
"status",
"===",
"0",
")",
"{",
"var",
"batch",
"=",
"require",
"(",
"'../sam... | application callback for acknowledgement | [
"application",
"callback",
"for",
"acknowledgement"
] | 34d9f256545b74d596747d1c2faf9bb450eb0777 | https://github.com/fulup-bzh/GeoGate/blob/34d9f256545b74d596747d1c2faf9bb450eb0777/smsg/lib/GG-SmsControl.js#L147-L159 |
33,368 | krunkosaurus/simg | src/simg.js | function(svg){
if (!svg){
throw new Error('.toString: No SVG found.');
}
[
['version', 1.1],
['xmlns', "http://www.w3.org/2000/svg"],
].forEach(function(item){
svg.setAttribute(item[0], item[1]);
});
return svg.outerHTML;
} | javascript | function(svg){
if (!svg){
throw new Error('.toString: No SVG found.');
}
[
['version', 1.1],
['xmlns', "http://www.w3.org/2000/svg"],
].forEach(function(item){
svg.setAttribute(item[0], item[1]);
});
return svg.outerHTML;
} | [
"function",
"(",
"svg",
")",
"{",
"if",
"(",
"!",
"svg",
")",
"{",
"throw",
"new",
"Error",
"(",
"'.toString: No SVG found.'",
")",
";",
"}",
"[",
"[",
"'version'",
",",
"1.1",
"]",
",",
"[",
"'xmlns'",
",",
"\"http://www.w3.org/2000/svg\"",
"]",
",",
... | Return SVG text. | [
"Return",
"SVG",
"text",
"."
] | 2b50dbdc06d80faad14dfae2312e594d7cdfcb02 | https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L29-L41 | |
33,369 | krunkosaurus/simg | src/simg.js | function(cb){
this.toSvgImage(function(img){
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
cb(canvas);
});
} | javascript | function(cb){
this.toSvgImage(function(img){
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0);
cb(canvas);
});
} | [
"function",
"(",
"cb",
")",
"{",
"this",
".",
"toSvgImage",
"(",
"function",
"(",
"img",
")",
"{",
"var",
"canvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"var",
"context",
"=",
"canvas",
".",
"getContext",
"(",
"\"2d\"",
")"... | Return canvas with this SVG drawn inside. | [
"Return",
"canvas",
"with",
"this",
"SVG",
"drawn",
"inside",
"."
] | 2b50dbdc06d80faad14dfae2312e594d7cdfcb02 | https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L44-L55 | |
33,370 | krunkosaurus/simg | src/simg.js | function(cb){
this.toCanvas(function(canvas){
var canvasData = canvas.toDataURL("image/png");
var img = document.createElement('img');
img.onload = function(){
cb(img);
};
// Make pngImg's source the canvas data.
img.setAttribute('src', canvasData);
});
} | javascript | function(cb){
this.toCanvas(function(canvas){
var canvasData = canvas.toDataURL("image/png");
var img = document.createElement('img');
img.onload = function(){
cb(img);
};
// Make pngImg's source the canvas data.
img.setAttribute('src', canvasData);
});
} | [
"function",
"(",
"cb",
")",
"{",
"this",
".",
"toCanvas",
"(",
"function",
"(",
"canvas",
")",
"{",
"var",
"canvasData",
"=",
"canvas",
".",
"toDataURL",
"(",
"\"image/png\"",
")",
";",
"var",
"img",
"=",
"document",
".",
"createElement",
"(",
"'img'",
... | Returns callback to new img from SVG. Call with no arguments to return svg image element. Call with callback to return png image element. | [
"Returns",
"callback",
"to",
"new",
"img",
"from",
"SVG",
".",
"Call",
"with",
"no",
"arguments",
"to",
"return",
"svg",
"image",
"element",
".",
"Call",
"with",
"callback",
"to",
"return",
"png",
"image",
"element",
"."
] | 2b50dbdc06d80faad14dfae2312e594d7cdfcb02 | https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L74-L86 | |
33,371 | krunkosaurus/simg | src/simg.js | function(cb){
this.toCanvas(function(canvas){
var dataUrl = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, "");
var byteString = atob(escape(dataUrl));
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(ab);
var blob = new Blob([dataView], {type: "image/png"});
cb(blob);
});
} | javascript | function(cb){
this.toCanvas(function(canvas){
var dataUrl = canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, "");
var byteString = atob(escape(dataUrl));
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var dataView = new DataView(ab);
var blob = new Blob([dataView], {type: "image/png"});
cb(blob);
});
} | [
"function",
"(",
"cb",
")",
"{",
"this",
".",
"toCanvas",
"(",
"function",
"(",
"canvas",
")",
"{",
"var",
"dataUrl",
"=",
"canvas",
".",
"toDataURL",
"(",
")",
".",
"replace",
"(",
"/",
"^data:image\\/(png|jpg);base64,",
"/",
",",
"\"\"",
")",
";",
"v... | Converts canvas to binary blob. | [
"Converts",
"canvas",
"to",
"binary",
"blob",
"."
] | 2b50dbdc06d80faad14dfae2312e594d7cdfcb02 | https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L101-L115 | |
33,372 | krunkosaurus/simg | src/simg.js | function(filename){
if (!filename){
filename = 'chart';
}
this.toImg(function(img){
var a = document.createElement("a");
// Name of the file being downloaded.
a.download = filename + ".png";
a.href = img.getAttribute('src');
// Support for Firefox which requires inserting in dom.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
} | javascript | function(filename){
if (!filename){
filename = 'chart';
}
this.toImg(function(img){
var a = document.createElement("a");
// Name of the file being downloaded.
a.download = filename + ".png";
a.href = img.getAttribute('src');
// Support for Firefox which requires inserting in dom.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
} | [
"function",
"(",
"filename",
")",
"{",
"if",
"(",
"!",
"filename",
")",
"{",
"filename",
"=",
"'chart'",
";",
"}",
"this",
".",
"toImg",
"(",
"function",
"(",
"img",
")",
"{",
"var",
"a",
"=",
"document",
".",
"createElement",
"(",
"\"a\"",
")",
";... | Trigger download of image. | [
"Trigger",
"download",
"of",
"image",
"."
] | 2b50dbdc06d80faad14dfae2312e594d7cdfcb02 | https://github.com/krunkosaurus/simg/blob/2b50dbdc06d80faad14dfae2312e594d7cdfcb02/src/simg.js#L118-L133 | |
33,373 | xch89820/wx-chart | src/util/helper.js | _assignGenerator | function _assignGenerator(own) {
let _copy = function(target, ...source) {
let deep = true;
if (is.Boolean(target)) {
deep = target;
target = 0 in source
? source.shift()
: null;
}
if (is.Array(target)) {
source.forEach(sc => {
target.push(...sc);
});
} else if (is.Object(target)) {
source.forEach(sc => {
for (let key in sc) {
if (own && !sc.hasOwnProperty(key))
continue;
let so = sc[key],
to = target[key];
if (is.PureObject(so)) {
target[key] = deep
? extend(true, is.PureObject(to)
? to
: {}, so)
: so;
} else if (is.Array(so)) {
target[key] = deep
? extend(true, is.Array(to)
? to
: [], so)
: so;
} else {
target[key] = so;
}
}
});
}
// Do nothing
return target;
};
return _copy;
} | javascript | function _assignGenerator(own) {
let _copy = function(target, ...source) {
let deep = true;
if (is.Boolean(target)) {
deep = target;
target = 0 in source
? source.shift()
: null;
}
if (is.Array(target)) {
source.forEach(sc => {
target.push(...sc);
});
} else if (is.Object(target)) {
source.forEach(sc => {
for (let key in sc) {
if (own && !sc.hasOwnProperty(key))
continue;
let so = sc[key],
to = target[key];
if (is.PureObject(so)) {
target[key] = deep
? extend(true, is.PureObject(to)
? to
: {}, so)
: so;
} else if (is.Array(so)) {
target[key] = deep
? extend(true, is.Array(to)
? to
: [], so)
: so;
} else {
target[key] = so;
}
}
});
}
// Do nothing
return target;
};
return _copy;
} | [
"function",
"_assignGenerator",
"(",
"own",
")",
"{",
"let",
"_copy",
"=",
"function",
"(",
"target",
",",
"...",
"source",
")",
"{",
"let",
"deep",
"=",
"true",
";",
"if",
"(",
"is",
".",
"Boolean",
"(",
"target",
")",
")",
"{",
"deep",
"=",
"targ... | Assign function generator | [
"Assign",
"function",
"generator"
] | 8cbbbcb17c43e650533a2c43e4fbb10cb9232f28 | https://github.com/xch89820/wx-chart/blob/8cbbbcb17c43e650533a2c43e4fbb10cb9232f28/src/util/helper.js#L101-L144 |
33,374 | amadeusmuc/node-ifttt | ifttt.js | function(req, res, next){
that.accessCheck(req, res, next, {forceHeaderCheck: true});
} | javascript | function(req, res, next){
that.accessCheck(req, res, next, {forceHeaderCheck: true});
} | [
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"that",
".",
"accessCheck",
"(",
"req",
",",
"res",
",",
"next",
",",
"{",
"forceHeaderCheck",
":",
"true",
"}",
")",
";",
"}"
] | Header check middleware wrapper. | [
"Header",
"check",
"middleware",
"wrapper",
"."
] | 6004507e9ad4b9f247c7ecc7c4882019d42ba926 | https://github.com/amadeusmuc/node-ifttt/blob/6004507e9ad4b9f247c7ecc7c4882019d42ba926/ifttt.js#L73-L75 | |
33,375 | mradionov/karma-jasmine-diff-reporter | src/format.js | strictReplace | function strictReplace(str, pairs, multiline) {
var index;
var fromIndex = 0;
pairs.some(function (pair) {
var toReplace = pair[0];
var replaceWith = pair[1];
index = str.indexOf(toReplace, fromIndex);
if (index === -1) {
return true;
}
var lhs = str.substr(0, index);
var rhs = str.substr(index + toReplace.length);
if (multiline) {
lhs = trimSpaceAndPunctuation(lhs);
rhs = trimSpaceAndPunctuation(rhs);
}
str = lhs + replaceWith + rhs;
fromIndex = index + replaceWith.length;
return false;
});
return str;
} | javascript | function strictReplace(str, pairs, multiline) {
var index;
var fromIndex = 0;
pairs.some(function (pair) {
var toReplace = pair[0];
var replaceWith = pair[1];
index = str.indexOf(toReplace, fromIndex);
if (index === -1) {
return true;
}
var lhs = str.substr(0, index);
var rhs = str.substr(index + toReplace.length);
if (multiline) {
lhs = trimSpaceAndPunctuation(lhs);
rhs = trimSpaceAndPunctuation(rhs);
}
str = lhs + replaceWith + rhs;
fromIndex = index + replaceWith.length;
return false;
});
return str;
} | [
"function",
"strictReplace",
"(",
"str",
",",
"pairs",
",",
"multiline",
")",
"{",
"var",
"index",
";",
"var",
"fromIndex",
"=",
"0",
";",
"pairs",
".",
"some",
"(",
"function",
"(",
"pair",
")",
"{",
"var",
"toReplace",
"=",
"pair",
"[",
"0",
"]",
... | Replace while increasing indexFrom If multiline is true - eat all spaces and punctuation around diffed objects - it will keep things look nice. | [
"Replace",
"while",
"increasing",
"indexFrom",
"If",
"multiline",
"is",
"true",
"-",
"eat",
"all",
"spaces",
"and",
"punctuation",
"around",
"diffed",
"objects",
"-",
"it",
"will",
"keep",
"things",
"look",
"nice",
"."
] | c53c38313f66afac73e4c594e1b1090d8cd12326 | https://github.com/mradionov/karma-jasmine-diff-reporter/blob/c53c38313f66afac73e4c594e1b1090d8cd12326/src/format.js#L23-L52 |
33,376 | mradionov/karma-jasmine-diff-reporter | src/parse.js | isMultipleArray | function isMultipleArray(valueStr) {
var wrappedValueStr = '[ ' + valueStr + ' ]';
var wrappedArray = createArray(wrappedValueStr, {}, {
checkMultipleArray: false
});
return wrappedArray.children.length > 1;
} | javascript | function isMultipleArray(valueStr) {
var wrappedValueStr = '[ ' + valueStr + ' ]';
var wrappedArray = createArray(wrappedValueStr, {}, {
checkMultipleArray: false
});
return wrappedArray.children.length > 1;
} | [
"function",
"isMultipleArray",
"(",
"valueStr",
")",
"{",
"var",
"wrappedValueStr",
"=",
"'[ '",
"+",
"valueStr",
"+",
"' ]'",
";",
"var",
"wrappedArray",
"=",
"createArray",
"(",
"wrappedValueStr",
",",
"{",
"}",
",",
"{",
"checkMultipleArray",
":",
"false",
... | Wrap value in extra array, an it will have multiple children - then it's a multiple array. Make sure not to go recursive. | [
"Wrap",
"value",
"in",
"extra",
"array",
"an",
"it",
"will",
"have",
"multiple",
"children",
"-",
"then",
"it",
"s",
"a",
"multiple",
"array",
".",
"Make",
"sure",
"not",
"to",
"go",
"recursive",
"."
] | c53c38313f66afac73e4c594e1b1090d8cd12326 | https://github.com/mradionov/karma-jasmine-diff-reporter/blob/c53c38313f66afac73e4c594e1b1090d8cd12326/src/parse.js#L263-L269 |
33,377 | axemclion/grunt-saucelabs | grunt/saucelabs-custom.js | updateJob | function updateJob(jobId, attributes) {
var user = process.env.SAUCE_USERNAME;
var pass = process.env.SAUCE_ACCESS_KEY;
return utils
.makeRequest({
method: 'PUT',
url: ['https://saucelabs.com/rest/v1', user, 'jobs', jobId].join('/'),
auth: { user: user, pass: pass },
json: attributes
});
} | javascript | function updateJob(jobId, attributes) {
var user = process.env.SAUCE_USERNAME;
var pass = process.env.SAUCE_ACCESS_KEY;
return utils
.makeRequest({
method: 'PUT',
url: ['https://saucelabs.com/rest/v1', user, 'jobs', jobId].join('/'),
auth: { user: user, pass: pass },
json: attributes
});
} | [
"function",
"updateJob",
"(",
"jobId",
",",
"attributes",
")",
"{",
"var",
"user",
"=",
"process",
".",
"env",
".",
"SAUCE_USERNAME",
";",
"var",
"pass",
"=",
"process",
".",
"env",
".",
"SAUCE_ACCESS_KEY",
";",
"return",
"utils",
".",
"makeRequest",
"(",
... | Updates a job's attributes.
@param {String} jobId - Job ID.
@param {Object} attributes - The attributes to update.
@returns {Object} - A promise which will eventually be resolved after the job is
updated. | [
"Updates",
"a",
"job",
"s",
"attributes",
"."
] | 127cac287947399be79b5d6c96493dff5fb45184 | https://github.com/axemclion/grunt-saucelabs/blob/127cac287947399be79b5d6c96493dff5fb45184/grunt/saucelabs-custom.js#L16-L27 |
33,378 | 3logic/apollo-cassandra | libs/apollo.js | function(properties){
/**
* Create a new instance for the model
* @class Model
* @augments BaseModel
* @param {object} instance_values Key/value object containing values of the row *
* @classdesc Generic model. Use it statically to find documents on Cassandra. Any instance represent a row retrieved or which can be saved on DB
*/
var Model = function(instance_values){
BaseModel.apply(this,Array.prototype.slice.call(arguments));
};
util.inherits(Model,BaseModel);
for(var i in BaseModel){
if(BaseModel.hasOwnProperty(i)){
Model[i] = BaseModel[i];
}
}
Model._set_properties(properties);
return Model;
} | javascript | function(properties){
/**
* Create a new instance for the model
* @class Model
* @augments BaseModel
* @param {object} instance_values Key/value object containing values of the row *
* @classdesc Generic model. Use it statically to find documents on Cassandra. Any instance represent a row retrieved or which can be saved on DB
*/
var Model = function(instance_values){
BaseModel.apply(this,Array.prototype.slice.call(arguments));
};
util.inherits(Model,BaseModel);
for(var i in BaseModel){
if(BaseModel.hasOwnProperty(i)){
Model[i] = BaseModel[i];
}
}
Model._set_properties(properties);
return Model;
} | [
"function",
"(",
"properties",
")",
"{",
"/**\n * Create a new instance for the model\n * @class Model\n * @augments BaseModel\n * @param {object} instance_values Key/value object containing values of the row *\n * @classdesc Generic model. Use it statically to fin... | Generate a Model
@param {object} properties Properties for the model
@return {Model} Construcotr for the model
@private | [
"Generate",
"a",
"Model"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L44-L68 | |
33,379 | 3logic/apollo-cassandra | libs/apollo.js | function(){
var copy_fields = ['contactPoints'],
temp_connection = {},
connection = this._connection;
for(var fk in copy_fields){
temp_connection[copy_fields[fk]] = connection[copy_fields[fk]];
}
return new cql.Client(temp_connection);
} | javascript | function(){
var copy_fields = ['contactPoints'],
temp_connection = {},
connection = this._connection;
for(var fk in copy_fields){
temp_connection[copy_fields[fk]] = connection[copy_fields[fk]];
}
return new cql.Client(temp_connection);
} | [
"function",
"(",
")",
"{",
"var",
"copy_fields",
"=",
"[",
"'contactPoints'",
"]",
",",
"temp_connection",
"=",
"{",
"}",
",",
"connection",
"=",
"this",
".",
"_connection",
";",
"for",
"(",
"var",
"fk",
"in",
"copy_fields",
")",
"{",
"temp_connection",
... | Returns a client to be used only for keyspace assertion
@return {Client} Node driver client
@private | [
"Returns",
"a",
"client",
"to",
"be",
"used",
"only",
"for",
"keyspace",
"assertion"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L75-L84 | |
33,380 | 3logic/apollo-cassandra | libs/apollo.js | function(replication_option){
if( typeof replication_option == 'string'){
return replication_option;
}else{
var properties = [];
for(var k in replication_option){
properties.push(util.format("'%s': '%s'", k, replication_option[k] ));
}
return util.format('{%s}', properties.join(','));
}
} | javascript | function(replication_option){
if( typeof replication_option == 'string'){
return replication_option;
}else{
var properties = [];
for(var k in replication_option){
properties.push(util.format("'%s': '%s'", k, replication_option[k] ));
}
return util.format('{%s}', properties.join(','));
}
} | [
"function",
"(",
"replication_option",
")",
"{",
"if",
"(",
"typeof",
"replication_option",
"==",
"'string'",
")",
"{",
"return",
"replication_option",
";",
"}",
"else",
"{",
"var",
"properties",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"k",
"in",
"replicati... | Generate replication strategy text for keyspace creation query
@param {object|string} replication_option An object or a string representing replication strategy
@return {string} Replication strategy text
@private | [
"Generate",
"replication",
"strategy",
"text",
"for",
"keyspace",
"creation",
"query"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L92-L102 | |
33,381 | 3logic/apollo-cassandra | libs/apollo.js | function(callback){
var client = this._get_system_client();
var keyspace_name = this._connection.keyspace,
replication_text = '',
options = this._options;
replication_text = this._generate_replication_text(options.replication_strategy);
var query = util.format(
"CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = %s;",
keyspace_name,
replication_text
);
client.execute(query, function(err,result){
client.shutdown(function(){
callback(err,result);
});
});
} | javascript | function(callback){
var client = this._get_system_client();
var keyspace_name = this._connection.keyspace,
replication_text = '',
options = this._options;
replication_text = this._generate_replication_text(options.replication_strategy);
var query = util.format(
"CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = %s;",
keyspace_name,
replication_text
);
client.execute(query, function(err,result){
client.shutdown(function(){
callback(err,result);
});
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"client",
"=",
"this",
".",
"_get_system_client",
"(",
")",
";",
"var",
"keyspace_name",
"=",
"this",
".",
"_connection",
".",
"keyspace",
",",
"replication_text",
"=",
"''",
",",
"options",
"=",
"this",
".",
... | Ensure specified keyspace exists, try to create it otherwise
@param {Apollo~GenericCallback} callback Called on keyspace assertion
@private | [
"Ensure",
"specified",
"keyspace",
"exists",
"try",
"to",
"create",
"it",
"otherwise"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L109-L128 | |
33,382 | 3logic/apollo-cassandra | libs/apollo.js | function(client){
var define_connection_options = lodash.clone(this._connection);
define_connection_options.policies = {
loadBalancing: new SingleNodePolicy()
};
//define_connection_options.hosts = define_connection_options.contactPoints;
this._client = client;
this._define_connection = new cql.Client(define_connection_options);
/*this._client.on('log',function(level, message){
console.log(message);
});*/
//Reset connections on all models
for(var i in this._models){
this._models[i]._properties.cql = this._client;
this._models[i]._properties.define_connection = this._define_connection;
}
} | javascript | function(client){
var define_connection_options = lodash.clone(this._connection);
define_connection_options.policies = {
loadBalancing: new SingleNodePolicy()
};
//define_connection_options.hosts = define_connection_options.contactPoints;
this._client = client;
this._define_connection = new cql.Client(define_connection_options);
/*this._client.on('log',function(level, message){
console.log(message);
});*/
//Reset connections on all models
for(var i in this._models){
this._models[i]._properties.cql = this._client;
this._models[i]._properties.define_connection = this._define_connection;
}
} | [
"function",
"(",
"client",
")",
"{",
"var",
"define_connection_options",
"=",
"lodash",
".",
"clone",
"(",
"this",
".",
"_connection",
")",
";",
"define_connection_options",
".",
"policies",
"=",
"{",
"loadBalancing",
":",
"new",
"SingleNodePolicy",
"(",
")",
... | Set internal clients
@param {object} client Node driver client
@private | [
"Set",
"internal",
"clients"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L135-L155 | |
33,383 | 3logic/apollo-cassandra | libs/apollo.js | function(callback){
var on_keyspace = function(err){
if(err){ return callback(err);}
this._set_client(new cql.Client(this._connection));
callback(err, this);
};
if(this._keyspace){
this._assert_keyspace( on_keyspace.bind(this) );
}else{
on_keyspace.call(this);
}
} | javascript | function(callback){
var on_keyspace = function(err){
if(err){ return callback(err);}
this._set_client(new cql.Client(this._connection));
callback(err, this);
};
if(this._keyspace){
this._assert_keyspace( on_keyspace.bind(this) );
}else{
on_keyspace.call(this);
}
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"on_keyspace",
"=",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"this",
".",
"_set_client",
"(",
"new",
"cql",
".",
"Client",
"(",
"thi... | Connect your instance of Apollo to Cassandra
@param {Apollo~onConnect} callback Callback on connection result | [
"Connect",
"your",
"instance",
"of",
"Apollo",
"to",
"Cassandra"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L181-L193 | |
33,384 | 3logic/apollo-cassandra | libs/apollo.js | function(model_name, model_schema, options) {
if(!model_name || typeof(model_name) != "string")
throw("Si deve specificare un nome per il modello");
options = options || {};
options.mismatch_behaviour = options.mismatch_behaviour || 'fail';
if(options.mismatch_behaviour !== 'fail' && options.mismatch_behaviour !== 'drop')
throw 'Valid option values for "mismatch_behaviour": "fail" , "drop". Got: "'+options.mismatch_behaviour+'"';
//model_schema = schemer.normalize_model_schema(model_schema);
schemer.validate_model_schema(model_schema);
var base_properties = {
name : model_name,
schema : model_schema,
keyspace : this._keyspace,
mismatch_behaviour : options.mismatch_behaviour,
define_connection : this._define_connection,
cql : this._client,
get_constructor : this.get_model.bind(this,model_name),
connect: this.connect.bind(this)
};
return (this._models[model_name] = this._generate_model(base_properties));
} | javascript | function(model_name, model_schema, options) {
if(!model_name || typeof(model_name) != "string")
throw("Si deve specificare un nome per il modello");
options = options || {};
options.mismatch_behaviour = options.mismatch_behaviour || 'fail';
if(options.mismatch_behaviour !== 'fail' && options.mismatch_behaviour !== 'drop')
throw 'Valid option values for "mismatch_behaviour": "fail" , "drop". Got: "'+options.mismatch_behaviour+'"';
//model_schema = schemer.normalize_model_schema(model_schema);
schemer.validate_model_schema(model_schema);
var base_properties = {
name : model_name,
schema : model_schema,
keyspace : this._keyspace,
mismatch_behaviour : options.mismatch_behaviour,
define_connection : this._define_connection,
cql : this._client,
get_constructor : this.get_model.bind(this,model_name),
connect: this.connect.bind(this)
};
return (this._models[model_name] = this._generate_model(base_properties));
} | [
"function",
"(",
"model_name",
",",
"model_schema",
",",
"options",
")",
"{",
"if",
"(",
"!",
"model_name",
"||",
"typeof",
"(",
"model_name",
")",
"!=",
"\"string\"",
")",
"throw",
"(",
"\"Si deve specificare un nome per il modello\"",
")",
";",
"options",
"=",... | Create a model based on proposed schema
@param {string} model_name - Name for the model
@param {object} model_schema - Schema for the model
@param {Apollo~ModelCreationOptions} options - Options for the creation
@return {Model} Model constructor | [
"Create",
"a",
"model",
"based",
"on",
"proposed",
"schema"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L203-L227 | |
33,385 | 3logic/apollo-cassandra | libs/apollo.js | function(callback){
callback = callback || noop;
if(!this._client){
return callback();
}
this._client.shutdown(function(err){
if(!this._define_connection){
return callback(err);
}
this._define_connection.shutdown(function(derr){
callback(err || derr);
});
}.bind(this));
} | javascript | function(callback){
callback = callback || noop;
if(!this._client){
return callback();
}
this._client.shutdown(function(err){
if(!this._define_connection){
return callback(err);
}
this._define_connection.shutdown(function(derr){
callback(err || derr);
});
}.bind(this));
} | [
"function",
"(",
"callback",
")",
"{",
"callback",
"=",
"callback",
"||",
"noop",
";",
"if",
"(",
"!",
"this",
".",
"_client",
")",
"{",
"return",
"callback",
"(",
")",
";",
"}",
"this",
".",
"_client",
".",
"shutdown",
"(",
"function",
"(",
"err",
... | Chiusura della connessione
@param {Function} callback callback | [
"Chiusura",
"della",
"connessione"
] | d618b98e497f53d22c685d4e4690087ccf731f91 | https://github.com/3logic/apollo-cassandra/blob/d618b98e497f53d22c685d4e4690087ccf731f91/libs/apollo.js#L243-L257 | |
33,386 | hashchange/backbone.select | dist/backbone.select.js | triggerMultiSelectEvents | function triggerMultiSelectEvents ( collection, prevSelected, options, reselected ) {
function mapCidsToModels ( cids, collection, previousSelection ) {
function mapper ( cid ) {
// Find the model in the collection. If not found, it has been removed, so get it from the array of
// previously selected models.
return collection.get( cid ) || previousSelection[cid];
}
return _.map( cids, mapper );
}
if ( options.silent || options["@bbs:silentLocally"] ) return;
var diff,
label = getLabel( options, collection ),
selectionSize = getSelectionSize( collection, label ),
length = collection.length,
prevSelectedCids = _.keys( prevSelected ),
selectedCids = _.keys( collection[label] ),
addedCids = _.difference( selectedCids, prevSelectedCids ),
removedCids = _.difference( prevSelectedCids, selectedCids ),
unchanged = (selectionSize === prevSelectedCids.length && addedCids.length === 0 && removedCids.length === 0);
if ( reselected && reselected.length && !options["@bbs:silentReselect"] ) {
queueEventSet( "reselect:any", label, [ reselected, collection, toEventOptions( options, label, collection ) ], collection, options );
}
if ( unchanged ) return;
diff = {
selected: mapCidsToModels( addedCids, collection, prevSelected ),
deselected: mapCidsToModels( removedCids, collection, prevSelected )
};
if ( selectionSize === 0 ) {
queueEventSet( "select:none", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options );
return;
}
if ( selectionSize === length ) {
queueEventSet( "select:all", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options );
return;
}
if ( selectionSize > 0 && selectionSize < length ) {
queueEventSet( "select:some", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options );
return;
}
} | javascript | function triggerMultiSelectEvents ( collection, prevSelected, options, reselected ) {
function mapCidsToModels ( cids, collection, previousSelection ) {
function mapper ( cid ) {
// Find the model in the collection. If not found, it has been removed, so get it from the array of
// previously selected models.
return collection.get( cid ) || previousSelection[cid];
}
return _.map( cids, mapper );
}
if ( options.silent || options["@bbs:silentLocally"] ) return;
var diff,
label = getLabel( options, collection ),
selectionSize = getSelectionSize( collection, label ),
length = collection.length,
prevSelectedCids = _.keys( prevSelected ),
selectedCids = _.keys( collection[label] ),
addedCids = _.difference( selectedCids, prevSelectedCids ),
removedCids = _.difference( prevSelectedCids, selectedCids ),
unchanged = (selectionSize === prevSelectedCids.length && addedCids.length === 0 && removedCids.length === 0);
if ( reselected && reselected.length && !options["@bbs:silentReselect"] ) {
queueEventSet( "reselect:any", label, [ reselected, collection, toEventOptions( options, label, collection ) ], collection, options );
}
if ( unchanged ) return;
diff = {
selected: mapCidsToModels( addedCids, collection, prevSelected ),
deselected: mapCidsToModels( removedCids, collection, prevSelected )
};
if ( selectionSize === 0 ) {
queueEventSet( "select:none", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options );
return;
}
if ( selectionSize === length ) {
queueEventSet( "select:all", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options );
return;
}
if ( selectionSize > 0 && selectionSize < length ) {
queueEventSet( "select:some", label, [ diff, collection, toEventOptions( options, label, collection ) ], collection, options );
return;
}
} | [
"function",
"triggerMultiSelectEvents",
"(",
"collection",
",",
"prevSelected",
",",
"options",
",",
"reselected",
")",
"{",
"function",
"mapCidsToModels",
"(",
"cids",
",",
"collection",
",",
"previousSelection",
")",
"{",
"function",
"mapper",
"(",
"cid",
")",
... | Trigger events from a multi-select collection, based on the number of selected items. | [
"Trigger",
"events",
"from",
"a",
"multi",
"-",
"select",
"collection",
"based",
"on",
"the",
"number",
"of",
"selected",
"items",
"."
] | 237d75bf2fb3e0d955f07114d74622401f8942ae | https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/dist/backbone.select.js#L651-L702 |
33,387 | hashchange/backbone.select | dist/backbone.select.js | ensureModelMixin | function ensureModelMixin( model, collection, options ) {
var applyModelMixin;
if ( !model._pickyType ) {
applyModelMixin = Backbone.Select.Me.custom.applyModelMixin;
if ( applyModelMixin && _.isFunction( applyModelMixin ) ) {
applyModelMixin( model, collection, options );
} else {
Backbone.Select.Me.applyTo( model, options );
}
}
} | javascript | function ensureModelMixin( model, collection, options ) {
var applyModelMixin;
if ( !model._pickyType ) {
applyModelMixin = Backbone.Select.Me.custom.applyModelMixin;
if ( applyModelMixin && _.isFunction( applyModelMixin ) ) {
applyModelMixin( model, collection, options );
} else {
Backbone.Select.Me.applyTo( model, options );
}
}
} | [
"function",
"ensureModelMixin",
"(",
"model",
",",
"collection",
",",
"options",
")",
"{",
"var",
"applyModelMixin",
";",
"if",
"(",
"!",
"model",
".",
"_pickyType",
")",
"{",
"applyModelMixin",
"=",
"Backbone",
".",
"Select",
".",
"Me",
".",
"custom",
"."... | Auto-apply the Backbone.Select.Me mixin if not yet done for the model. Options are passed on to the mixin. Ie, if `defaultLabel` has been defined in the options, the model will be set up accordingly. | [
"Auto",
"-",
"apply",
"the",
"Backbone",
".",
"Select",
".",
"Me",
"mixin",
"if",
"not",
"yet",
"done",
"for",
"the",
"model",
".",
"Options",
"are",
"passed",
"on",
"to",
"the",
"mixin",
".",
"Ie",
"if",
"defaultLabel",
"has",
"been",
"defined",
"in",... | 237d75bf2fb3e0d955f07114d74622401f8942ae | https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/dist/backbone.select.js#L882-L895 |
33,388 | hashchange/backbone.select | demo/amd/trailing.js | function ( model ) {
var trailing = this.collection.trailing && this.collection.trailing.id || this.collection.first().id,
view = this,
cbUpdateTrailing = function () {
view.collection.get( Math.round( this.trailingId ) ).select( { label: "trailing" } );
};
// Animate the trailing element and make it catch up. Use the .select() method with the label
// "trailing".
$( { trailingId: trailing } ).animate(
{ trailingId: model.id },
{ step: cbUpdateTrailing, done: cbUpdateTrailing, duration: trailingLag }
);
} | javascript | function ( model ) {
var trailing = this.collection.trailing && this.collection.trailing.id || this.collection.first().id,
view = this,
cbUpdateTrailing = function () {
view.collection.get( Math.round( this.trailingId ) ).select( { label: "trailing" } );
};
// Animate the trailing element and make it catch up. Use the .select() method with the label
// "trailing".
$( { trailingId: trailing } ).animate(
{ trailingId: model.id },
{ step: cbUpdateTrailing, done: cbUpdateTrailing, duration: trailingLag }
);
} | [
"function",
"(",
"model",
")",
"{",
"var",
"trailing",
"=",
"this",
".",
"collection",
".",
"trailing",
"&&",
"this",
".",
"collection",
".",
"trailing",
".",
"id",
"||",
"this",
".",
"collection",
".",
"first",
"(",
")",
".",
"id",
",",
"view",
"=",... | Only runs when a model is selected with the default label, not with the custom label "trailing" | [
"Only",
"runs",
"when",
"a",
"model",
"is",
"selected",
"with",
"the",
"default",
"label",
"not",
"with",
"the",
"custom",
"label",
"trailing"
] | 237d75bf2fb3e0d955f07114d74622401f8942ae | https://github.com/hashchange/backbone.select/blob/237d75bf2fb3e0d955f07114d74622401f8942ae/demo/amd/trailing.js#L82-L96 | |
33,389 | doowb/npm-api | lib/models/maintainer.js | Maintainer | function Maintainer (name, store) {
if (!(this instanceof Maintainer)) {
return new Maintainer(name);
}
Base.call(this, store);
this.is('maintainer');
this.name = name;
} | javascript | function Maintainer (name, store) {
if (!(this instanceof Maintainer)) {
return new Maintainer(name);
}
Base.call(this, store);
this.is('maintainer');
this.name = name;
} | [
"function",
"Maintainer",
"(",
"name",
",",
"store",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Maintainer",
")",
")",
"{",
"return",
"new",
"Maintainer",
"(",
"name",
")",
";",
"}",
"Base",
".",
"call",
"(",
"this",
",",
"store",
")",
"... | Maintainer constructor. Create an instance of an npm maintainer by maintainer name.
```js
var maintainer = new Maintainer('doowb');
```
@param {String} `name` Name of the npm maintainer to get information about.
@param {Object} `store` Optional cache store instance for caching results. Defaults to a memory store.
@api public | [
"Maintainer",
"constructor",
".",
"Create",
"an",
"instance",
"of",
"an",
"npm",
"maintainer",
"by",
"maintainer",
"name",
"."
] | 2204395a7da8815465c12ba147cd7622b9d5bae2 | https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/lib/models/maintainer.js#L25-L32 |
33,390 | ozum/sequelize-pg-generator | lib/index.js | template | function template(filePath, locals, fn) {
filePath = path.join(getConfig('template.folder'), filePath + '.' + getConfig('template.extension')); // i.e. index -> index.ejs
return cons[getConfig('template.engine')].call(null, filePath, locals, fn); // i.e. cons.swig('views/page.html', { user: 'tobi' }, function(err, html){}
} | javascript | function template(filePath, locals, fn) {
filePath = path.join(getConfig('template.folder'), filePath + '.' + getConfig('template.extension')); // i.e. index -> index.ejs
return cons[getConfig('template.engine')].call(null, filePath, locals, fn); // i.e. cons.swig('views/page.html', { user: 'tobi' }, function(err, html){}
} | [
"function",
"template",
"(",
"filePath",
",",
"locals",
",",
"fn",
")",
"{",
"filePath",
"=",
"path",
".",
"join",
"(",
"getConfig",
"(",
"'template.folder'",
")",
",",
"filePath",
"+",
"'.'",
"+",
"getConfig",
"(",
"'template.extension'",
")",
")",
";",
... | Renders the template and executes callback function.
@private
@param {string} filePath - Path of the template file relative to template folder.
@param {object} locals - Local variables to pass to template
@param {function} fn - Callback function(err, output) | [
"Renders",
"the",
"template",
"and",
"executes",
"callback",
"function",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L93-L96 |
33,391 | ozum/sequelize-pg-generator | lib/index.js | parseDB | function parseDB(callback) {
pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'),
getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') },
callback);
} | javascript | function parseDB(callback) {
pgStructure(getConfig('database.host'), getConfig('database.database'), getConfig('database.user'),
getConfig('database.password'), { port: getConfig('database.port'), schema: getConfig('database.schema') },
callback);
} | [
"function",
"parseDB",
"(",
"callback",
")",
"{",
"pgStructure",
"(",
"getConfig",
"(",
"'database.host'",
")",
",",
"getConfig",
"(",
"'database.database'",
")",
",",
"getConfig",
"(",
"'database.user'",
")",
",",
"getConfig",
"(",
"'database.password'",
")",
"... | Parses by reverse engineering using pgStructure module and calls callback.
@private
@param {function} callback - Callback function(err, structure) | [
"Parses",
"by",
"reverse",
"engineering",
"using",
"pgStructure",
"module",
"and",
"calls",
"callback",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L104-L108 |
33,392 | ozum/sequelize-pg-generator | lib/index.js | getBelongsToName | function getBelongsToName(fkc) {
var as = fkc.foreignKey(0).name(), // company_id
tableName = fkc.table().name(),
camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related
if (as.match(/_id$/i)) {
as = as.replace(/_id$/i, ''); // company_id -> company
} else {
as = prefix + '_' + as; // company -> related_company
}
if (camelCase) {
as = inflection.camelize(inflection.underscore(as), true);
}
return inflection.singularize(as);
} | javascript | function getBelongsToName(fkc) {
var as = fkc.foreignKey(0).name(), // company_id
tableName = fkc.table().name(),
camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related
if (as.match(/_id$/i)) {
as = as.replace(/_id$/i, ''); // company_id -> company
} else {
as = prefix + '_' + as; // company -> related_company
}
if (camelCase) {
as = inflection.camelize(inflection.underscore(as), true);
}
return inflection.singularize(as);
} | [
"function",
"getBelongsToName",
"(",
"fkc",
")",
"{",
"var",
"as",
"=",
"fkc",
".",
"foreignKey",
"(",
"0",
")",
".",
"name",
"(",
")",
",",
"// company_id",
"tableName",
"=",
"fkc",
".",
"table",
"(",
")",
".",
"name",
"(",
")",
",",
"camelCase",
... | Calculates belongsTo relation name based on table, column and config.
@private
@param {object} fkc - pg-structure foreign key constraint object.
@returns {string} - Name for the belongsTo relationship. | [
"Calculates",
"belongsTo",
"relation",
"name",
"based",
"on",
"table",
"column",
"and",
"config",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L166-L181 |
33,393 | ozum/sequelize-pg-generator | lib/index.js | getBelongsToManyName | function getBelongsToManyName(hasManyThrough) {
var tfkc = hasManyThrough.throughForeignKeyConstraint(),
as = tfkc.foreignKey(0).name(), // company_id
throughTableName = hasManyThrough.through().name(),
relationName = hasManyThrough.throughForeignKeyConstraintToSelf().name(),
tableName = hasManyThrough.table().name(),
camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related
if (getSpecificConfig(tableName, 'generate.addRelationNameToManyToMany')) {
if (getSpecificConfig(tableName, 'generate.stripFirstTableNameFromManyToMany')) {
relationName = relationName.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_item
}
as = inflection.singularize(relationName) + '_' + as;
} else if (getSpecificConfig(tableName, 'generate.addTableNameToManyToMany')) {
as = inflection.singularize(throughTableName) + '_' + as;
}
if (as.match(/_id$/i)) {
as = as.replace(/_id$/i, ''); // company_id -> company
} else {
as = prefix + '_' + as; // company -> related_company
}
if (camelCase) {
as = inflection.camelize(inflection.underscore(as), true);
}
return inflection.pluralize(as);
} | javascript | function getBelongsToManyName(hasManyThrough) {
var tfkc = hasManyThrough.throughForeignKeyConstraint(),
as = tfkc.foreignKey(0).name(), // company_id
throughTableName = hasManyThrough.through().name(),
relationName = hasManyThrough.throughForeignKeyConstraintToSelf().name(),
tableName = hasManyThrough.table().name(),
camelCase = getSpecificConfig(tableName, 'generate.relationAccessorCamelCase'),
prefix = getSpecificConfig(tableName, 'generate.prefixForBelongsTo'); // related
if (getSpecificConfig(tableName, 'generate.addRelationNameToManyToMany')) {
if (getSpecificConfig(tableName, 'generate.stripFirstTableNameFromManyToMany')) {
relationName = relationName.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_item
}
as = inflection.singularize(relationName) + '_' + as;
} else if (getSpecificConfig(tableName, 'generate.addTableNameToManyToMany')) {
as = inflection.singularize(throughTableName) + '_' + as;
}
if (as.match(/_id$/i)) {
as = as.replace(/_id$/i, ''); // company_id -> company
} else {
as = prefix + '_' + as; // company -> related_company
}
if (camelCase) {
as = inflection.camelize(inflection.underscore(as), true);
}
return inflection.pluralize(as);
} | [
"function",
"getBelongsToManyName",
"(",
"hasManyThrough",
")",
"{",
"var",
"tfkc",
"=",
"hasManyThrough",
".",
"throughForeignKeyConstraint",
"(",
")",
",",
"as",
"=",
"tfkc",
".",
"foreignKey",
"(",
"0",
")",
".",
"name",
"(",
")",
",",
"// company_id",
"t... | Calculates belongsToMany relation name based on table, column and config.
@private
@param {object} hasManyThrough - pg-structure foreign key constraint object.
@returns {string} - Name for the belongsToMany relationship. | [
"Calculates",
"belongsToMany",
"relation",
"name",
"based",
"on",
"table",
"column",
"and",
"config",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L190-L217 |
33,394 | ozum/sequelize-pg-generator | lib/index.js | getHasManyName | function getHasManyName(hasMany) {
var as, tableName;
if (hasMany.through() !== undefined) {
as = getBelongsToManyName(hasMany); //inflection.pluralize(getBelongsToName(hasMany.throughForeignKeyConstraint()));
} else {
as = inflection.pluralize(hasMany.name()); // cart_cart_line_items
tableName = hasMany.table().name();
if (getSpecificConfig(tableName, 'generate.stripFirstTableFromHasMany')) {
as = as.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_items
}
if (getSpecificConfig(tableName, 'generate.relationAccessorCamelCase')) {
as = inflection.camelize(inflection.underscore(as), true); // cart_line_items -> cartLineItems
}
}
return as;
} | javascript | function getHasManyName(hasMany) {
var as, tableName;
if (hasMany.through() !== undefined) {
as = getBelongsToManyName(hasMany); //inflection.pluralize(getBelongsToName(hasMany.throughForeignKeyConstraint()));
} else {
as = inflection.pluralize(hasMany.name()); // cart_cart_line_items
tableName = hasMany.table().name();
if (getSpecificConfig(tableName, 'generate.stripFirstTableFromHasMany')) {
as = as.replace(new RegExp('^' + tableName + '[_-]?', 'i'), ''); // cart_cart_line_items -> cart_line_items
}
if (getSpecificConfig(tableName, 'generate.relationAccessorCamelCase')) {
as = inflection.camelize(inflection.underscore(as), true); // cart_line_items -> cartLineItems
}
}
return as;
} | [
"function",
"getHasManyName",
"(",
"hasMany",
")",
"{",
"var",
"as",
",",
"tableName",
";",
"if",
"(",
"hasMany",
".",
"through",
"(",
")",
"!==",
"undefined",
")",
"{",
"as",
"=",
"getBelongsToManyName",
"(",
"hasMany",
")",
";",
"//inflection.pluralize(get... | Calculates hasMany relation name based on table, column and config.
@private
@param {object} hasMany - pg-structure foreign key constraint object.
@returns {string} - Name for the belongsTo relationship. | [
"Calculates",
"hasMany",
"relation",
"name",
"based",
"on",
"table",
"column",
"and",
"config",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L226-L243 |
33,395 | ozum/sequelize-pg-generator | lib/index.js | getModelNameFor | function getModelNameFor(table) {
var schemaName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.schema().name()), true) : table.schema().name(),
tableName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.name()), true) : table.name();
return getSpecificConfig(table.name(), 'generate.useSchemaName') ? schemaName + '.' + tableName : tableName;
} | javascript | function getModelNameFor(table) {
var schemaName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.schema().name()), true) : table.schema().name(),
tableName = getSpecificConfig(table.name(), 'generate.modelCamelCase') ? inflection.camelize(inflection.underscore(table.name()), true) : table.name();
return getSpecificConfig(table.name(), 'generate.useSchemaName') ? schemaName + '.' + tableName : tableName;
} | [
"function",
"getModelNameFor",
"(",
"table",
")",
"{",
"var",
"schemaName",
"=",
"getSpecificConfig",
"(",
"table",
".",
"name",
"(",
")",
",",
"'generate.modelCamelCase'",
")",
"?",
"inflection",
".",
"camelize",
"(",
"inflection",
".",
"underscore",
"(",
"ta... | Calculates model name for given table.
@private
@param {object} table - pg-structure table object.
@returns {string} - Model name for table | [
"Calculates",
"model",
"name",
"for",
"given",
"table",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L252-L257 |
33,396 | ozum/sequelize-pg-generator | lib/index.js | getTableOptions | function getTableOptions(table) {
logger.debug('table details are calculated for: %s', table.name());
var specificName = 'tableOptionsOverride.' + table.name(),
specificOptions = config.has(specificName) ? getConfig(specificName) : {},
generalOptions = getConfig('tableOptions'),
otherOptions = {
modelName : getModelNameFor(table),
tableName : table.name(),
schema : table.schema().name(),
comment : getSpecificConfig(table.name(), 'generate.tableDescription') ? table.description() : undefined,
columns : [],
hasManies : [],
belongsTos : [],
belongsToManies : []
},
tableOptions = filterAttributes(lodash.defaults(specificOptions, generalOptions, otherOptions));
tableOptions.baseFileName = table.name();
return tableOptions;
} | javascript | function getTableOptions(table) {
logger.debug('table details are calculated for: %s', table.name());
var specificName = 'tableOptionsOverride.' + table.name(),
specificOptions = config.has(specificName) ? getConfig(specificName) : {},
generalOptions = getConfig('tableOptions'),
otherOptions = {
modelName : getModelNameFor(table),
tableName : table.name(),
schema : table.schema().name(),
comment : getSpecificConfig(table.name(), 'generate.tableDescription') ? table.description() : undefined,
columns : [],
hasManies : [],
belongsTos : [],
belongsToManies : []
},
tableOptions = filterAttributes(lodash.defaults(specificOptions, generalOptions, otherOptions));
tableOptions.baseFileName = table.name();
return tableOptions;
} | [
"function",
"getTableOptions",
"(",
"table",
")",
"{",
"logger",
".",
"debug",
"(",
"'table details are calculated for: %s'",
",",
"table",
".",
"name",
"(",
")",
")",
";",
"var",
"specificName",
"=",
"'tableOptionsOverride.'",
"+",
"table",
".",
"name",
"(",
... | Returns table details as plain object to use in templates.
@private
@param table
@returns {Object} | [
"Returns",
"table",
"details",
"as",
"plain",
"object",
"to",
"use",
"in",
"templates",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L266-L285 |
33,397 | ozum/sequelize-pg-generator | lib/index.js | sequelizeType | function sequelizeType(column, varName) {
varName = varName || 'DataTypes'; // DataTypes.INTEGER etc. prefix
var enumValues = column.enumValues();
var type = enumValues ? '.ENUM' : sequelizeTypes[column.type()].type;
var realType = column.arrayDimension() >= 1 ? column.arrayType() : column.type(); // type or type of array (if array).
var hasLength = sequelizeTypes[realType].hasLength;
var hasPrecision = sequelizeTypes[realType].hasPrecision;
var isObject = type && type.indexOf('.') !== -1; // . ile başlıyorsa değişkene çevirmek için
var details;
var isArrayTypeObject;
if (isObject) { type = varName + type; }
details = function(num1, num2) {
var detail = '';
if (num1 >= 0 && num1 !== null && num2 && num2 !== null) {
detail = '(' + num1 + ',' + num2 + ')'; // (5,2)
} else if (num1 >= 0 && num1 !== null) {
detail = '(' + num1 + ')'; // (5)
}
return detail;
};
if (column.arrayDimension() >= 1) {
isArrayTypeObject = sequelizeTypes[column.arrayType()].type.indexOf('.') !== -1;
type += '(';
if (column.arrayDimension() > 1) { type += new Array(column.arrayDimension()).join(varName + '.ARRAY('); } // arrayDimension -1 tane 'ARRAY(' yaz
type += isArrayTypeObject ? varName : "'";
type += sequelizeTypes[column.arrayType()].type;
type += isArrayTypeObject ? '' : "'";
}
if (enumValues) {
enumValues = util.inspect(enumValues.substring(1, enumValues.length - 1).split(',')); // Strip { and } -> make array -> makeJSON;
enumValues = enumValues.substring(2, enumValues.length - 2); // Strip '[ ' and ' ]'
type += '(' + enumValues + ')';
}
if (hasPrecision) {
type += details(column.precision(), column.scale());
}
if (hasLength) {
type += details(column.length());
}
if (column.arrayDimension() >= 1) {
type += new Array(column.arrayDimension() + 1).join(')'); // arrayDimension -1 tane ) yaz
}
if (!isObject) {
type = "'" + type + "'";
}
return type;
} | javascript | function sequelizeType(column, varName) {
varName = varName || 'DataTypes'; // DataTypes.INTEGER etc. prefix
var enumValues = column.enumValues();
var type = enumValues ? '.ENUM' : sequelizeTypes[column.type()].type;
var realType = column.arrayDimension() >= 1 ? column.arrayType() : column.type(); // type or type of array (if array).
var hasLength = sequelizeTypes[realType].hasLength;
var hasPrecision = sequelizeTypes[realType].hasPrecision;
var isObject = type && type.indexOf('.') !== -1; // . ile başlıyorsa değişkene çevirmek için
var details;
var isArrayTypeObject;
if (isObject) { type = varName + type; }
details = function(num1, num2) {
var detail = '';
if (num1 >= 0 && num1 !== null && num2 && num2 !== null) {
detail = '(' + num1 + ',' + num2 + ')'; // (5,2)
} else if (num1 >= 0 && num1 !== null) {
detail = '(' + num1 + ')'; // (5)
}
return detail;
};
if (column.arrayDimension() >= 1) {
isArrayTypeObject = sequelizeTypes[column.arrayType()].type.indexOf('.') !== -1;
type += '(';
if (column.arrayDimension() > 1) { type += new Array(column.arrayDimension()).join(varName + '.ARRAY('); } // arrayDimension -1 tane 'ARRAY(' yaz
type += isArrayTypeObject ? varName : "'";
type += sequelizeTypes[column.arrayType()].type;
type += isArrayTypeObject ? '' : "'";
}
if (enumValues) {
enumValues = util.inspect(enumValues.substring(1, enumValues.length - 1).split(',')); // Strip { and } -> make array -> makeJSON;
enumValues = enumValues.substring(2, enumValues.length - 2); // Strip '[ ' and ' ]'
type += '(' + enumValues + ')';
}
if (hasPrecision) {
type += details(column.precision(), column.scale());
}
if (hasLength) {
type += details(column.length());
}
if (column.arrayDimension() >= 1) {
type += new Array(column.arrayDimension() + 1).join(')'); // arrayDimension -1 tane ) yaz
}
if (!isObject) {
type = "'" + type + "'";
}
return type;
} | [
"function",
"sequelizeType",
"(",
"column",
",",
"varName",
")",
"{",
"varName",
"=",
"varName",
"||",
"'DataTypes'",
";",
"// DataTypes.INTEGER etc. prefix",
"var",
"enumValues",
"=",
"column",
".",
"enumValues",
"(",
")",
";",
"var",
"type",
"=",
"enumValues",... | Returns Sequelize ORM datatype for column.
@param {Object} column - pg-structure column object.
@param {string} [varName = DataTypes] - Variable name to use in sequelize data type. ie. 'DataTypes' for DataTypes.INTEGER
@returns {string}
@private
@example
var typeA = column.sequelizeType(); // DataTypes.INTEGER(3)
var typeB = column.sequelizeType('Sequelize'); // Sequelize.INTEGER(3) | [
"Returns",
"Sequelize",
"ORM",
"datatype",
"for",
"column",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L299-L356 |
33,398 | ozum/sequelize-pg-generator | lib/index.js | getColumnDetails | function getColumnDetails(column) {
logger.debug('column details are calculated for: %s', column.name());
var result = filterAttributes({
source : 'generator',
accessorName : getSpecificConfig(column.table().name(), 'generate.columnAccessorCamelCase') ? inflection.camelize(inflection.underscore(column.name()), true) : column.name(),
name : column.name(),
primaryKey : column.isPrimaryKey(),
autoIncrement : column.isAutoIncrement() && getSpecificConfig(column.table().name(), 'generate.columnAutoIncrement') ? true : undefined,
allowNull : column.allowNull(),
defaultValue : getSpecificConfig(column.table().name(), 'generate.columnDefault') && column.default() !== null ? clearDefaultValue(column.default()) : undefined,
unique : column.unique(),
comment : getSpecificConfig(column.table().name(), 'generate.columnDescription') ? column.description() : undefined,
references : column.foreignKeyConstraint() ? getModelNameFor(column.foreignKeyConstraint().referencesTable()) : undefined,
referencesKey : column.foreignKeyConstraint() ? column.foreignKeyConstraint().foreignKey(0).name() : undefined,
onUpdate : column.onUpdate(),
onDelete : column.onDelete()
});
result.type = sequelizeType(column, getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes.
//result.type = column.sequelizeType(getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes.
return result;
} | javascript | function getColumnDetails(column) {
logger.debug('column details are calculated for: %s', column.name());
var result = filterAttributes({
source : 'generator',
accessorName : getSpecificConfig(column.table().name(), 'generate.columnAccessorCamelCase') ? inflection.camelize(inflection.underscore(column.name()), true) : column.name(),
name : column.name(),
primaryKey : column.isPrimaryKey(),
autoIncrement : column.isAutoIncrement() && getSpecificConfig(column.table().name(), 'generate.columnAutoIncrement') ? true : undefined,
allowNull : column.allowNull(),
defaultValue : getSpecificConfig(column.table().name(), 'generate.columnDefault') && column.default() !== null ? clearDefaultValue(column.default()) : undefined,
unique : column.unique(),
comment : getSpecificConfig(column.table().name(), 'generate.columnDescription') ? column.description() : undefined,
references : column.foreignKeyConstraint() ? getModelNameFor(column.foreignKeyConstraint().referencesTable()) : undefined,
referencesKey : column.foreignKeyConstraint() ? column.foreignKeyConstraint().foreignKey(0).name() : undefined,
onUpdate : column.onUpdate(),
onDelete : column.onDelete()
});
result.type = sequelizeType(column, getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes.
//result.type = column.sequelizeType(getSpecificConfig(column.table().name(), 'generate.dataTypeVariable')); // To prevent type having quotes.
return result;
} | [
"function",
"getColumnDetails",
"(",
"column",
")",
"{",
"logger",
".",
"debug",
"(",
"'column details are calculated for: %s'",
",",
"column",
".",
"name",
"(",
")",
")",
";",
"var",
"result",
"=",
"filterAttributes",
"(",
"{",
"source",
":",
"'generator'",
"... | Returns column details as plain object to use in templates.
@private
@param {object} column - pg-structure column object
@returns {Object} - Simple object to use in template | [
"Returns",
"column",
"details",
"as",
"plain",
"object",
"to",
"use",
"in",
"templates",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L365-L386 |
33,399 | ozum/sequelize-pg-generator | lib/index.js | getHasManyDetails | function getHasManyDetails(hasMany) {
logger.debug('hasMany%s details are calculated for: %s', hasMany.through() ? 'through' : '', hasMany.name());
var model = getModelNameFor(hasMany.referencesTable()),
as = getHasManyName(hasMany);
return filterAttributes({
type : 'hasMany',
source : 'generator',
name : hasMany.name(),
model : model,
as : getAlias(hasMany.table(), as, 'hasMany'),
targetSchema : hasMany.referencesTable().schema().name(),
targetTable : hasMany.referencesTable().name(),
foreignKey : hasMany.foreignKey(0).name(), // Sequelize support single key only
onDelete : hasMany.onDelete(),
onUpdate : hasMany.onUpdate(),
through : hasMany.through() ? hasMany.through().name() : undefined
});
} | javascript | function getHasManyDetails(hasMany) {
logger.debug('hasMany%s details are calculated for: %s', hasMany.through() ? 'through' : '', hasMany.name());
var model = getModelNameFor(hasMany.referencesTable()),
as = getHasManyName(hasMany);
return filterAttributes({
type : 'hasMany',
source : 'generator',
name : hasMany.name(),
model : model,
as : getAlias(hasMany.table(), as, 'hasMany'),
targetSchema : hasMany.referencesTable().schema().name(),
targetTable : hasMany.referencesTable().name(),
foreignKey : hasMany.foreignKey(0).name(), // Sequelize support single key only
onDelete : hasMany.onDelete(),
onUpdate : hasMany.onUpdate(),
through : hasMany.through() ? hasMany.through().name() : undefined
});
} | [
"function",
"getHasManyDetails",
"(",
"hasMany",
")",
"{",
"logger",
".",
"debug",
"(",
"'hasMany%s details are calculated for: %s'",
",",
"hasMany",
".",
"through",
"(",
")",
"?",
"'through'",
":",
"''",
",",
"hasMany",
".",
"name",
"(",
")",
")",
";",
"var... | Returns hasMany details as plain object to use in templates.
@private
@param {object} hasMany - pg-structure hasMany object
@returns {Object} - Simple object to use in template | [
"Returns",
"hasMany",
"details",
"as",
"plain",
"object",
"to",
"use",
"in",
"templates",
"."
] | c38491b4d560981713a96a1923ad48d70e4aaff8 | https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/lib/index.js#L410-L428 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.