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
|
---|---|---|---|---|---|---|---|---|---|---|---|
43,400 | yamadapc/mocha-spec-cov-alt | bin/index.js | extend | function extend(target, source) {
var keys = Object.keys(source);
for(var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
target[key] = source[key];
}
return target;
} | javascript | function extend(target, source) {
var keys = Object.keys(source);
for(var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
target[key] = source[key];
}
return target;
} | [
"function",
"extend",
"(",
"target",
",",
"source",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"source",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"target",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
"return",
"target",
";",
"}"
]
| Merges two objects together, overwriting the second's properties onto the
first.
@param {Object} target
@param {Object} source
@return {Object} result The modified `target` parameter | [
"Merges",
"two",
"objects",
"together",
"overwriting",
"the",
"second",
"s",
"properties",
"onto",
"the",
"first",
"."
]
| 2f834c58e15bc186441cf21d0e2c586de13c6e9b | https://github.com/yamadapc/mocha-spec-cov-alt/blob/2f834c58e15bc186441cf21d0e2c586de13c6e9b/bin/index.js#L84-L91 |
43,401 | Xaxis/jquery.eye | src/jquery.eye.js | function() {
$.each(watched_props, function(index, value) {
if (index != '_interval' && index != '_interval_func' && index != '_element' && index != '_speed' && index != '_status' && index != '_load') {
var new_value = value.orig_value;
// Are we returning a jQuery function value?
if (index.match(/\)/g)) {
var j_func = index.replace(/\(\)/g, "");
// Do we have arguments to pass to the function
if ($.isPlainObject(value) && 'args' in value.orig_object) {
// If function is method of jQuery
if (j_func in $) {
new_value = $[j_func].apply(j_func, value.orig_object.args);
// Assume function is method of jQuery.fn
} else {
new_value = $.fn[j_func].apply($(plugin.element), value.orig_object.args);
}
} else {
// If function is method of jQuery
if (j_func in $) {
new_value = $(plugin.element)[j_func]();
// Assume function is method of jQuery.fn
} else {
new_value = $.fn[j_func].apply($(plugin.element));
}
}
// Are we watching a property of the DOM element
} else if (index in plugin.element) {
new_value = plugin.element[index];
// Are we watching a CSS property?
} else {
new_value = plugin.element.style[index];
}
}
// Execute the interval callback when present
if ($.isPlainObject(value.orig_object)) {
if ('onInterval' in value.orig_object) {
value.orig_object.onInterval( value.orig_value, value.elm_ref);
}
}
// When the currently calculated value differs from the original, execute callback
if (new_value != value.orig_value || plugin._load) {
if ($.isFunction(value.orig_object)) {
plugin._load = false;
value.orig_object( value.orig_value, new_value, value.elm_ref );
} else if ($.isPlainObject(value.orig_object)) {
plugin._load = false;
value.orig_object.onChange( value.orig_value, new_value, value.elm_ref, 'args' in value.orig_object ? value.orig_object.args : [] );
}
// Update the original value with the new value
value.orig_value = new_value;
}
});
} | javascript | function() {
$.each(watched_props, function(index, value) {
if (index != '_interval' && index != '_interval_func' && index != '_element' && index != '_speed' && index != '_status' && index != '_load') {
var new_value = value.orig_value;
// Are we returning a jQuery function value?
if (index.match(/\)/g)) {
var j_func = index.replace(/\(\)/g, "");
// Do we have arguments to pass to the function
if ($.isPlainObject(value) && 'args' in value.orig_object) {
// If function is method of jQuery
if (j_func in $) {
new_value = $[j_func].apply(j_func, value.orig_object.args);
// Assume function is method of jQuery.fn
} else {
new_value = $.fn[j_func].apply($(plugin.element), value.orig_object.args);
}
} else {
// If function is method of jQuery
if (j_func in $) {
new_value = $(plugin.element)[j_func]();
// Assume function is method of jQuery.fn
} else {
new_value = $.fn[j_func].apply($(plugin.element));
}
}
// Are we watching a property of the DOM element
} else if (index in plugin.element) {
new_value = plugin.element[index];
// Are we watching a CSS property?
} else {
new_value = plugin.element.style[index];
}
}
// Execute the interval callback when present
if ($.isPlainObject(value.orig_object)) {
if ('onInterval' in value.orig_object) {
value.orig_object.onInterval( value.orig_value, value.elm_ref);
}
}
// When the currently calculated value differs from the original, execute callback
if (new_value != value.orig_value || plugin._load) {
if ($.isFunction(value.orig_object)) {
plugin._load = false;
value.orig_object( value.orig_value, new_value, value.elm_ref );
} else if ($.isPlainObject(value.orig_object)) {
plugin._load = false;
value.orig_object.onChange( value.orig_value, new_value, value.elm_ref, 'args' in value.orig_object ? value.orig_object.args : [] );
}
// Update the original value with the new value
value.orig_value = new_value;
}
});
} | [
"function",
"(",
")",
"{",
"$",
".",
"each",
"(",
"watched_props",
",",
"function",
"(",
"index",
",",
"value",
")",
"{",
"if",
"(",
"index",
"!=",
"'_interval'",
"&&",
"index",
"!=",
"'_interval_func'",
"&&",
"index",
"!=",
"'_element'",
"&&",
"index",
"!=",
"'_speed'",
"&&",
"index",
"!=",
"'_status'",
"&&",
"index",
"!=",
"'_load'",
")",
"{",
"var",
"new_value",
"=",
"value",
".",
"orig_value",
";",
"// Are we returning a jQuery function value?\r",
"if",
"(",
"index",
".",
"match",
"(",
"/",
"\\)",
"/",
"g",
")",
")",
"{",
"var",
"j_func",
"=",
"index",
".",
"replace",
"(",
"/",
"\\(\\)",
"/",
"g",
",",
"\"\"",
")",
";",
"// Do we have arguments to pass to the function\r",
"if",
"(",
"$",
".",
"isPlainObject",
"(",
"value",
")",
"&&",
"'args'",
"in",
"value",
".",
"orig_object",
")",
"{",
"// If function is method of jQuery\r",
"if",
"(",
"j_func",
"in",
"$",
")",
"{",
"new_value",
"=",
"$",
"[",
"j_func",
"]",
".",
"apply",
"(",
"j_func",
",",
"value",
".",
"orig_object",
".",
"args",
")",
";",
"// Assume function is method of jQuery.fn\r",
"}",
"else",
"{",
"new_value",
"=",
"$",
".",
"fn",
"[",
"j_func",
"]",
".",
"apply",
"(",
"$",
"(",
"plugin",
".",
"element",
")",
",",
"value",
".",
"orig_object",
".",
"args",
")",
";",
"}",
"}",
"else",
"{",
"// If function is method of jQuery\r",
"if",
"(",
"j_func",
"in",
"$",
")",
"{",
"new_value",
"=",
"$",
"(",
"plugin",
".",
"element",
")",
"[",
"j_func",
"]",
"(",
")",
";",
"// Assume function is method of jQuery.fn\r",
"}",
"else",
"{",
"new_value",
"=",
"$",
".",
"fn",
"[",
"j_func",
"]",
".",
"apply",
"(",
"$",
"(",
"plugin",
".",
"element",
")",
")",
";",
"}",
"}",
"// Are we watching a property of the DOM element\r",
"}",
"else",
"if",
"(",
"index",
"in",
"plugin",
".",
"element",
")",
"{",
"new_value",
"=",
"plugin",
".",
"element",
"[",
"index",
"]",
";",
"// Are we watching a CSS property?\r",
"}",
"else",
"{",
"new_value",
"=",
"plugin",
".",
"element",
".",
"style",
"[",
"index",
"]",
";",
"}",
"}",
"// Execute the interval callback when present\r",
"if",
"(",
"$",
".",
"isPlainObject",
"(",
"value",
".",
"orig_object",
")",
")",
"{",
"if",
"(",
"'onInterval'",
"in",
"value",
".",
"orig_object",
")",
"{",
"value",
".",
"orig_object",
".",
"onInterval",
"(",
"value",
".",
"orig_value",
",",
"value",
".",
"elm_ref",
")",
";",
"}",
"}",
"// When the currently calculated value differs from the original, execute callback\r",
"if",
"(",
"new_value",
"!=",
"value",
".",
"orig_value",
"||",
"plugin",
".",
"_load",
")",
"{",
"if",
"(",
"$",
".",
"isFunction",
"(",
"value",
".",
"orig_object",
")",
")",
"{",
"plugin",
".",
"_load",
"=",
"false",
";",
"value",
".",
"orig_object",
"(",
"value",
".",
"orig_value",
",",
"new_value",
",",
"value",
".",
"elm_ref",
")",
";",
"}",
"else",
"if",
"(",
"$",
".",
"isPlainObject",
"(",
"value",
".",
"orig_object",
")",
")",
"{",
"plugin",
".",
"_load",
"=",
"false",
";",
"value",
".",
"orig_object",
".",
"onChange",
"(",
"value",
".",
"orig_value",
",",
"new_value",
",",
"value",
".",
"elm_ref",
",",
"'args'",
"in",
"value",
".",
"orig_object",
"?",
"value",
".",
"orig_object",
".",
"args",
":",
"[",
"]",
")",
";",
"}",
"// Update the original value with the new value\r",
"value",
".",
"orig_value",
"=",
"new_value",
";",
"}",
"}",
")",
";",
"}"
]
| Reference the interval function | [
"Reference",
"the",
"interval",
"function"
]
| 4abf914194c04cd0536f65d110b03d226e9cacdc | https://github.com/Xaxis/jquery.eye/blob/4abf914194c04cd0536f65d110b03d226e9cacdc/src/jquery.eye.js#L124-L187 |
|
43,402 | numbers1311407/mongoose-friends | lib/plugin.js | function (query, update, fship) {
var options = { new: false };
return function (done) {
this.findOneAndUpdate(query, update, options, function (err, res) {
done(err, fship);
});
}
} | javascript | function (query, update, fship) {
var options = { new: false };
return function (done) {
this.findOneAndUpdate(query, update, options, function (err, res) {
done(err, fship);
});
}
} | [
"function",
"(",
"query",
",",
"update",
",",
"fship",
")",
"{",
"var",
"options",
"=",
"{",
"new",
":",
"false",
"}",
";",
"return",
"function",
"(",
"done",
")",
"{",
"this",
".",
"findOneAndUpdate",
"(",
"query",
",",
"update",
",",
"options",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"done",
"(",
"err",
",",
"fship",
")",
";",
"}",
")",
";",
"}",
"}"
]
| The work function which pushes or updates embedded friend objects
for two documents, returns a function
@api private | [
"The",
"work",
"function",
"which",
"pushes",
"or",
"updates",
"embedded",
"friend",
"objects",
"for",
"two",
"documents",
"returns",
"a",
"function"
]
| da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc | https://github.com/numbers1311407/mongoose-friends/blob/da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc/lib/plugin.js#L66-L74 |
|
43,403 | numbers1311407/mongoose-friends | lib/plugin.js | function (m1, m2, fship) {
var query = {_id: m1};
query[pathName] = {$elemMatch: {_id: m2}};
var updater = {$set: {}};
updater.$set[pathName+".$.status"] = fship.status;
return _update(query, updater, fship);
} | javascript | function (m1, m2, fship) {
var query = {_id: m1};
query[pathName] = {$elemMatch: {_id: m2}};
var updater = {$set: {}};
updater.$set[pathName+".$.status"] = fship.status;
return _update(query, updater, fship);
} | [
"function",
"(",
"m1",
",",
"m2",
",",
"fship",
")",
"{",
"var",
"query",
"=",
"{",
"_id",
":",
"m1",
"}",
";",
"query",
"[",
"pathName",
"]",
"=",
"{",
"$elemMatch",
":",
"{",
"_id",
":",
"m2",
"}",
"}",
";",
"var",
"updater",
"=",
"{",
"$set",
":",
"{",
"}",
"}",
";",
"updater",
".",
"$set",
"[",
"pathName",
"+",
"\".$.status\"",
"]",
"=",
"fship",
".",
"status",
";",
"return",
"_update",
"(",
"query",
",",
"updater",
",",
"fship",
")",
";",
"}"
]
| Return a function to update a friendship between two parties
@api private | [
"Return",
"a",
"function",
"to",
"update",
"a",
"friendship",
"between",
"two",
"parties"
]
| da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc | https://github.com/numbers1311407/mongoose-friends/blob/da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc/lib/plugin.js#L81-L89 |
|
43,404 | numbers1311407/mongoose-friends | lib/plugin.js | function (m1, m2, fship) {
var query = {_id: m1};
fship.added = new Date();
var updater = {$push: {}};
updater.$push[pathName] = fship;
return _update(query, updater, fship);
} | javascript | function (m1, m2, fship) {
var query = {_id: m1};
fship.added = new Date();
var updater = {$push: {}};
updater.$push[pathName] = fship;
return _update(query, updater, fship);
} | [
"function",
"(",
"m1",
",",
"m2",
",",
"fship",
")",
"{",
"var",
"query",
"=",
"{",
"_id",
":",
"m1",
"}",
";",
"fship",
".",
"added",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"updater",
"=",
"{",
"$push",
":",
"{",
"}",
"}",
";",
"updater",
".",
"$push",
"[",
"pathName",
"]",
"=",
"fship",
";",
"return",
"_update",
"(",
"query",
",",
"updater",
",",
"fship",
")",
";",
"}"
]
| Return a function to create a new friendship between two parties
@api private | [
"Return",
"a",
"function",
"to",
"create",
"a",
"new",
"friendship",
"between",
"two",
"parties"
]
| da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc | https://github.com/numbers1311407/mongoose-friends/blob/da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc/lib/plugin.js#L97-L106 |
|
43,405 | numbers1311407/mongoose-friends | lib/plugin.js | function (done) {
var select = {};
select[pathName] = 1;
Model.findOne({_id: model}, select, function (err, doc) {
if (err) return done(err);
if (!doc) return done(null, []);
done(null, doc[pathName].reduce(function (o, friend) {
o[friend._id] = friend.toObject();
return o;
}, {}));
});
} | javascript | function (done) {
var select = {};
select[pathName] = 1;
Model.findOne({_id: model}, select, function (err, doc) {
if (err) return done(err);
if (!doc) return done(null, []);
done(null, doc[pathName].reduce(function (o, friend) {
o[friend._id] = friend.toObject();
return o;
}, {}));
});
} | [
"function",
"(",
"done",
")",
"{",
"var",
"select",
"=",
"{",
"}",
";",
"select",
"[",
"pathName",
"]",
"=",
"1",
";",
"Model",
".",
"findOne",
"(",
"{",
"_id",
":",
"model",
"}",
",",
"select",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
";",
"if",
"(",
"!",
"doc",
")",
"return",
"done",
"(",
"null",
",",
"[",
"]",
")",
";",
"done",
"(",
"null",
",",
"doc",
"[",
"pathName",
"]",
".",
"reduce",
"(",
"function",
"(",
"o",
",",
"friend",
")",
"{",
"o",
"[",
"friend",
".",
"_id",
"]",
"=",
"friend",
".",
"toObject",
"(",
")",
";",
"return",
"o",
";",
"}",
",",
"{",
"}",
")",
")",
";",
"}",
")",
";",
"}"
]
| Reduce local friend docs to map which will be populated and then combined with the queried remote friends to generate the resulting array | [
"Reduce",
"local",
"friend",
"docs",
"to",
"map",
"which",
"will",
"be",
"populated",
"and",
"then",
"combined",
"with",
"the",
"queried",
"remote",
"friends",
"to",
"generate",
"the",
"resulting",
"array"
]
| da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc | https://github.com/numbers1311407/mongoose-friends/blob/da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc/lib/plugin.js#L308-L321 |
|
43,406 | numbers1311407/mongoose-friends | lib/plugin.js | defaults | function defaults(options, defaultOptions) {
options || (options = {});
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) {
options[opt] = defaultOptions[opt];
}
}
return options;
} | javascript | function defaults(options, defaultOptions) {
options || (options = {});
for (var opt in defaultOptions) {
if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) {
options[opt] = defaultOptions[opt];
}
}
return options;
} | [
"function",
"defaults",
"(",
"options",
",",
"defaultOptions",
")",
"{",
"options",
"||",
"(",
"options",
"=",
"{",
"}",
")",
";",
"for",
"(",
"var",
"opt",
"in",
"defaultOptions",
")",
"{",
"if",
"(",
"defaultOptions",
".",
"hasOwnProperty",
"(",
"opt",
")",
"&&",
"!",
"options",
".",
"hasOwnProperty",
"(",
"opt",
")",
")",
"{",
"options",
"[",
"opt",
"]",
"=",
"defaultOptions",
"[",
"opt",
"]",
";",
"}",
"}",
"return",
"options",
";",
"}"
]
| simple function for extending an object with defaults
@api private | [
"simple",
"function",
"for",
"extending",
"an",
"object",
"with",
"defaults"
]
| da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc | https://github.com/numbers1311407/mongoose-friends/blob/da567ac5c0e3c83fa3cbaa4f52ae1d7c7e3949cc/lib/plugin.js#L491-L501 |
43,407 | thlorenz/hha | lib/storyboard.js | resetSeat | function resetSeat(s) {
const street = this.street
const stage = this.stage
const preflop = street === 'preflop'
const chipsName = 'chips' + street[0].toUpperCase() + street.slice(1)
const p = script.players[s.playerIdx]
const chips = p[chipsName]
return Object.assign({}, seats[p.seatno], {
chips : chips
, action : null
, amount : 0
, chipsInFront: preflop ? p.chipsInFront : 0
, bet : 0
, investedBet : preflop && p.bb ? 1 : 0
, _lastUpdate : stage
})
} | javascript | function resetSeat(s) {
const street = this.street
const stage = this.stage
const preflop = street === 'preflop'
const chipsName = 'chips' + street[0].toUpperCase() + street.slice(1)
const p = script.players[s.playerIdx]
const chips = p[chipsName]
return Object.assign({}, seats[p.seatno], {
chips : chips
, action : null
, amount : 0
, chipsInFront: preflop ? p.chipsInFront : 0
, bet : 0
, investedBet : preflop && p.bb ? 1 : 0
, _lastUpdate : stage
})
} | [
"function",
"resetSeat",
"(",
"s",
")",
"{",
"const",
"street",
"=",
"this",
".",
"street",
"const",
"stage",
"=",
"this",
".",
"stage",
"const",
"preflop",
"=",
"street",
"===",
"'preflop'",
"const",
"chipsName",
"=",
"'chips'",
"+",
"street",
"[",
"0",
"]",
".",
"toUpperCase",
"(",
")",
"+",
"street",
".",
"slice",
"(",
"1",
")",
"const",
"p",
"=",
"script",
".",
"players",
"[",
"s",
".",
"playerIdx",
"]",
"const",
"chips",
"=",
"p",
"[",
"chipsName",
"]",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"seats",
"[",
"p",
".",
"seatno",
"]",
",",
"{",
"chips",
":",
"chips",
",",
"action",
":",
"null",
",",
"amount",
":",
"0",
",",
"chipsInFront",
":",
"preflop",
"?",
"p",
".",
"chipsInFront",
":",
"0",
",",
"bet",
":",
"0",
",",
"investedBet",
":",
"preflop",
"&&",
"p",
".",
"bb",
"?",
"1",
":",
"0",
",",
"_lastUpdate",
":",
"stage",
"}",
")",
"}"
]
| From now on we always map seats even though we reuse the variable in order to avoid affecting previous states | [
"From",
"now",
"on",
"we",
"always",
"map",
"seats",
"even",
"though",
"we",
"reuse",
"the",
"variable",
"in",
"order",
"to",
"avoid",
"affecting",
"previous",
"states"
]
| 28ae03e9d422881ad8a3b3dba9de32e01d8ac04c | https://github.com/thlorenz/hha/blob/28ae03e9d422881ad8a3b3dba9de32e01d8ac04c/lib/storyboard.js#L72-L89 |
43,408 | alexyoung/ico | src/normaliser.js | function() {
var min = typeof this.options.start_value !== 'undefined' && this.min >= 0 ? this.options.start_value : this.min,
start_value = this.round(min, 1);
/* This is a boundary condition */
if (this.min > 0 && start_value > this.min) {
return 0;
}
if (this.min === this.max) {
return 0;
}
return start_value;
} | javascript | function() {
var min = typeof this.options.start_value !== 'undefined' && this.min >= 0 ? this.options.start_value : this.min,
start_value = this.round(min, 1);
/* This is a boundary condition */
if (this.min > 0 && start_value > this.min) {
return 0;
}
if (this.min === this.max) {
return 0;
}
return start_value;
} | [
"function",
"(",
")",
"{",
"var",
"min",
"=",
"typeof",
"this",
".",
"options",
".",
"start_value",
"!==",
"'undefined'",
"&&",
"this",
".",
"min",
">=",
"0",
"?",
"this",
".",
"options",
".",
"start_value",
":",
"this",
".",
"min",
",",
"start_value",
"=",
"this",
".",
"round",
"(",
"min",
",",
"1",
")",
";",
"/* This is a boundary condition */",
"if",
"(",
"this",
".",
"min",
">",
"0",
"&&",
"start_value",
">",
"this",
".",
"min",
")",
"{",
"return",
"0",
";",
"}",
"if",
"(",
"this",
".",
"min",
"===",
"this",
".",
"max",
")",
"{",
"return",
"0",
";",
"}",
"return",
"start_value",
";",
"}"
]
| Calculates the start value. This is often 0.
@returns {Float} The start value | [
"Calculates",
"the",
"start",
"value",
".",
"This",
"is",
"often",
"0",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/normaliser.js#L30-L44 |
|
43,409 | alexyoung/ico | src/normaliser.js | function(value) {
return Math.pow(10, Math.round((Math.log(value) / Math.LN10)) - 1);
} | javascript | function(value) {
return Math.pow(10, Math.round((Math.log(value) / Math.LN10)) - 1);
} | [
"function",
"(",
"value",
")",
"{",
"return",
"Math",
".",
"pow",
"(",
"10",
",",
"Math",
".",
"round",
"(",
"(",
"Math",
".",
"log",
"(",
"value",
")",
"/",
"Math",
".",
"LN10",
")",
")",
"-",
"1",
")",
";",
"}"
]
| Calculates the label step value.
@param {Float} value A value to convert to a label position
@returns {Float} The rounded label step result | [
"Calculates",
"the",
"label",
"step",
"value",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/normaliser.js#L76-L78 |
|
43,410 | alexyoung/ico | src/graphs/bar.js | function(data, options) {
if (typeof data.length !== 'undefined') {
if (typeof data[0].length !== 'undefined') {
this.grouped = true;
// TODO: Find longest?
this.group_size = data[0].length;
var o = {}, k, i = 0;
for (k in options.labels) {
k = options.labels[k];
o[k] = data[i];
i++;
}
return o;
} else {
return { 'one': data };
}
} else {
return data;
}
} | javascript | function(data, options) {
if (typeof data.length !== 'undefined') {
if (typeof data[0].length !== 'undefined') {
this.grouped = true;
// TODO: Find longest?
this.group_size = data[0].length;
var o = {}, k, i = 0;
for (k in options.labels) {
k = options.labels[k];
o[k] = data[i];
i++;
}
return o;
} else {
return { 'one': data };
}
} else {
return data;
}
} | [
"function",
"(",
"data",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"data",
".",
"length",
"!==",
"'undefined'",
")",
"{",
"if",
"(",
"typeof",
"data",
"[",
"0",
"]",
".",
"length",
"!==",
"'undefined'",
")",
"{",
"this",
".",
"grouped",
"=",
"true",
";",
"// TODO: Find longest?",
"this",
".",
"group_size",
"=",
"data",
"[",
"0",
"]",
".",
"length",
";",
"var",
"o",
"=",
"{",
"}",
",",
"k",
",",
"i",
"=",
"0",
";",
"for",
"(",
"k",
"in",
"options",
".",
"labels",
")",
"{",
"k",
"=",
"options",
".",
"labels",
"[",
"k",
"]",
";",
"o",
"[",
"k",
"]",
"=",
"data",
"[",
"i",
"]",
";",
"i",
"++",
";",
"}",
"return",
"o",
";",
"}",
"else",
"{",
"return",
"{",
"'one'",
":",
"data",
"}",
";",
"}",
"}",
"else",
"{",
"return",
"data",
";",
"}",
"}"
]
| Overridden to handle grouped bar graphs | [
"Overridden",
"to",
"handle",
"grouped",
"bar",
"graphs"
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/graphs/bar.js#L13-L33 |
|
43,411 | alexyoung/ico | src/graphs/bar.js | function() {
// Make sure the true largest value is used for max
return this.options.line ? { start_value: 0, max: Helpers.max([Helpers.max(this.options.line), Helpers.max(this.flat_data)]) } : { start_value: 0 };
} | javascript | function() {
// Make sure the true largest value is used for max
return this.options.line ? { start_value: 0, max: Helpers.max([Helpers.max(this.options.line), Helpers.max(this.flat_data)]) } : { start_value: 0 };
} | [
"function",
"(",
")",
"{",
"// Make sure the true largest value is used for max",
"return",
"this",
".",
"options",
".",
"line",
"?",
"{",
"start_value",
":",
"0",
",",
"max",
":",
"Helpers",
".",
"max",
"(",
"[",
"Helpers",
".",
"max",
"(",
"this",
".",
"options",
".",
"line",
")",
",",
"Helpers",
".",
"max",
"(",
"this",
".",
"flat_data",
")",
"]",
")",
"}",
":",
"{",
"start_value",
":",
"0",
"}",
";",
"}"
]
| Ensures the normalises is always 0. | [
"Ensures",
"the",
"normalises",
"is",
"always",
"0",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/graphs/bar.js#L45-L48 |
|
43,412 | alexyoung/ico | src/graphs/bar.js | function() {
this.bar_padding = this.options.bar_padding || 5;
this.bar_width = this.options.bar_size || this.calculateBarWidth();
if (this.options.bar_size && !this.options.bar_padding) {
this.bar_padding = this.graph_width / this.data_size;
}
this.options.plot_padding = (this.bar_width / 2) - (this.bar_padding / 2);
this.step = this.calculateStep();
this.grid_start_offset = this.bar_padding - 1;
this.start_y = this.options.height - this.y_padding_bottom;
} | javascript | function() {
this.bar_padding = this.options.bar_padding || 5;
this.bar_width = this.options.bar_size || this.calculateBarWidth();
if (this.options.bar_size && !this.options.bar_padding) {
this.bar_padding = this.graph_width / this.data_size;
}
this.options.plot_padding = (this.bar_width / 2) - (this.bar_padding / 2);
this.step = this.calculateStep();
this.grid_start_offset = this.bar_padding - 1;
this.start_y = this.options.height - this.y_padding_bottom;
} | [
"function",
"(",
")",
"{",
"this",
".",
"bar_padding",
"=",
"this",
".",
"options",
".",
"bar_padding",
"||",
"5",
";",
"this",
".",
"bar_width",
"=",
"this",
".",
"options",
".",
"bar_size",
"||",
"this",
".",
"calculateBarWidth",
"(",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"bar_size",
"&&",
"!",
"this",
".",
"options",
".",
"bar_padding",
")",
"{",
"this",
".",
"bar_padding",
"=",
"this",
".",
"graph_width",
"/",
"this",
".",
"data_size",
";",
"}",
"this",
".",
"options",
".",
"plot_padding",
"=",
"(",
"this",
".",
"bar_width",
"/",
"2",
")",
"-",
"(",
"this",
".",
"bar_padding",
"/",
"2",
")",
";",
"this",
".",
"step",
"=",
"this",
".",
"calculateStep",
"(",
")",
";",
"this",
".",
"grid_start_offset",
"=",
"this",
".",
"bar_padding",
"-",
"1",
";",
"this",
".",
"start_y",
"=",
"this",
".",
"options",
".",
"height",
"-",
"this",
".",
"y_padding_bottom",
";",
"}"
]
| Options specific to BarGraph. | [
"Options",
"specific",
"to",
"BarGraph",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/graphs/bar.js#L53-L65 |
|
43,413 | alexyoung/ico | src/graphs/bar.js | function() {
var width = (this.graph_width / this.data_size) - this.bar_padding;
if (this.grouped) {
//width = width / this.group_size - (this.bar_padding * this.group_size);
}
if (this.options.max_bar_size && width > this.options.max_bar_size) {
width = this.options.max_bar_size;
this.bar_padding = this.graph_width / this.data_size;
}
return width;
} | javascript | function() {
var width = (this.graph_width / this.data_size) - this.bar_padding;
if (this.grouped) {
//width = width / this.group_size - (this.bar_padding * this.group_size);
}
if (this.options.max_bar_size && width > this.options.max_bar_size) {
width = this.options.max_bar_size;
this.bar_padding = this.graph_width / this.data_size;
}
return width;
} | [
"function",
"(",
")",
"{",
"var",
"width",
"=",
"(",
"this",
".",
"graph_width",
"/",
"this",
".",
"data_size",
")",
"-",
"this",
".",
"bar_padding",
";",
"if",
"(",
"this",
".",
"grouped",
")",
"{",
"//width = width / this.group_size - (this.bar_padding * this.group_size);",
"}",
"if",
"(",
"this",
".",
"options",
".",
"max_bar_size",
"&&",
"width",
">",
"this",
".",
"options",
".",
"max_bar_size",
")",
"{",
"width",
"=",
"this",
".",
"options",
".",
"max_bar_size",
";",
"this",
".",
"bar_padding",
"=",
"this",
".",
"graph_width",
"/",
"this",
".",
"data_size",
";",
"}",
"return",
"width",
";",
"}"
]
| Calculates the width of each bar.
@returns {Integer} The bar width | [
"Calculates",
"the",
"width",
"of",
"each",
"bar",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/graphs/bar.js#L72-L85 |
|
43,414 | alexyoung/ico | src/graphs/bar.js | function(index, pathString, x, y, colour) {
if (this.options.highlight_colours && this.options.highlight_colours.hasOwnProperty(index)) {
colour = this.options.highlight_colours[index];
}
x = x + this.bar_padding;
pathString += 'M' + x + ',' + this.start_y;
pathString += 'L' + x + ',' + y;
this.paper.path(pathString).attr({ stroke: colour, 'stroke-width': this.bar_width + 'px' });
pathString = '';
x = x + this.step;
pathString += 'M' + x + ',' + this.start_y;
return pathString;
} | javascript | function(index, pathString, x, y, colour) {
if (this.options.highlight_colours && this.options.highlight_colours.hasOwnProperty(index)) {
colour = this.options.highlight_colours[index];
}
x = x + this.bar_padding;
pathString += 'M' + x + ',' + this.start_y;
pathString += 'L' + x + ',' + y;
this.paper.path(pathString).attr({ stroke: colour, 'stroke-width': this.bar_width + 'px' });
pathString = '';
x = x + this.step;
pathString += 'M' + x + ',' + this.start_y;
return pathString;
} | [
"function",
"(",
"index",
",",
"pathString",
",",
"x",
",",
"y",
",",
"colour",
")",
"{",
"if",
"(",
"this",
".",
"options",
".",
"highlight_colours",
"&&",
"this",
".",
"options",
".",
"highlight_colours",
".",
"hasOwnProperty",
"(",
"index",
")",
")",
"{",
"colour",
"=",
"this",
".",
"options",
".",
"highlight_colours",
"[",
"index",
"]",
";",
"}",
"x",
"=",
"x",
"+",
"this",
".",
"bar_padding",
";",
"pathString",
"+=",
"'M'",
"+",
"x",
"+",
"','",
"+",
"this",
".",
"start_y",
";",
"pathString",
"+=",
"'L'",
"+",
"x",
"+",
"','",
"+",
"y",
";",
"this",
".",
"paper",
".",
"path",
"(",
"pathString",
")",
".",
"attr",
"(",
"{",
"stroke",
":",
"colour",
",",
"'stroke-width'",
":",
"this",
".",
"bar_width",
"+",
"'px'",
"}",
")",
";",
"pathString",
"=",
"''",
";",
"x",
"=",
"x",
"+",
"this",
".",
"step",
";",
"pathString",
"+=",
"'M'",
"+",
"x",
"+",
"','",
"+",
"this",
".",
"start_y",
";",
"return",
"pathString",
";",
"}"
]
| Generates paths for Raphael.
@param {Integer} index The index of the data value to plot
@param {String} pathString The pathString so far
@param {Integer} x The x-coord to plot
@param {Integer} y The y-coord to plot
@param {String} colour A string that represents a colour
@returns {String} The resulting path string | [
"Generates",
"paths",
"for",
"Raphael",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/graphs/bar.js#L106-L119 |
|
43,415 | alexyoung/ico | docs/prettify.js | attribToHtml | function attribToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>')
.replace(pr_quot, '"');
} | javascript | function attribToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>')
.replace(pr_quot, '"');
} | [
"function",
"attribToHtml",
"(",
"str",
")",
"{",
"return",
"str",
".",
"replace",
"(",
"pr_amp",
",",
"'&'",
")",
".",
"replace",
"(",
"pr_lt",
",",
"'<'",
")",
".",
"replace",
"(",
"pr_gt",
",",
"'>'",
")",
".",
"replace",
"(",
"pr_quot",
",",
"'"'",
")",
";",
"}"
]
| like textToHtml but escapes double quotes to be attribute safe. | [
"like",
"textToHtml",
"but",
"escapes",
"double",
"quotes",
"to",
"be",
"attribute",
"safe",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L229-L234 |
43,416 | alexyoung/ico | docs/prettify.js | htmlToText | function htmlToText(html) {
var pos = html.indexOf('&');
if (pos < 0) { return html; }
// Handle numeric entities specially. We can't use functional substitution
// since that doesn't work in older versions of Safari.
// These should be rare since most browsers convert them to normal chars.
for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
var end = html.indexOf(';', pos);
if (end >= 0) {
var num = html.substring(pos + 3, end);
var radix = 10;
if (num && num.charAt(0) === 'x') {
num = num.substring(1);
radix = 16;
}
var codePoint = parseInt(num, radix);
if (!isNaN(codePoint)) {
html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
html.substring(end + 1));
}
}
}
return html.replace(pr_ltEnt, '<')
.replace(pr_gtEnt, '>')
.replace(pr_aposEnt, "'")
.replace(pr_quotEnt, '"')
.replace(pr_nbspEnt, ' ')
.replace(pr_ampEnt, '&');
} | javascript | function htmlToText(html) {
var pos = html.indexOf('&');
if (pos < 0) { return html; }
// Handle numeric entities specially. We can't use functional substitution
// since that doesn't work in older versions of Safari.
// These should be rare since most browsers convert them to normal chars.
for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
var end = html.indexOf(';', pos);
if (end >= 0) {
var num = html.substring(pos + 3, end);
var radix = 10;
if (num && num.charAt(0) === 'x') {
num = num.substring(1);
radix = 16;
}
var codePoint = parseInt(num, radix);
if (!isNaN(codePoint)) {
html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
html.substring(end + 1));
}
}
}
return html.replace(pr_ltEnt, '<')
.replace(pr_gtEnt, '>')
.replace(pr_aposEnt, "'")
.replace(pr_quotEnt, '"')
.replace(pr_nbspEnt, ' ')
.replace(pr_ampEnt, '&');
} | [
"function",
"htmlToText",
"(",
"html",
")",
"{",
"var",
"pos",
"=",
"html",
".",
"indexOf",
"(",
"'&'",
")",
";",
"if",
"(",
"pos",
"<",
"0",
")",
"{",
"return",
"html",
";",
"}",
"// Handle numeric entities specially. We can't use functional substitution",
"// since that doesn't work in older versions of Safari.",
"// These should be rare since most browsers convert them to normal chars.",
"for",
"(",
"--",
"pos",
";",
"(",
"pos",
"=",
"html",
".",
"indexOf",
"(",
"'&#'",
",",
"pos",
"+",
"1",
")",
")",
">=",
"0",
";",
")",
"{",
"var",
"end",
"=",
"html",
".",
"indexOf",
"(",
"';'",
",",
"pos",
")",
";",
"if",
"(",
"end",
">=",
"0",
")",
"{",
"var",
"num",
"=",
"html",
".",
"substring",
"(",
"pos",
"+",
"3",
",",
"end",
")",
";",
"var",
"radix",
"=",
"10",
";",
"if",
"(",
"num",
"&&",
"num",
".",
"charAt",
"(",
"0",
")",
"===",
"'x'",
")",
"{",
"num",
"=",
"num",
".",
"substring",
"(",
"1",
")",
";",
"radix",
"=",
"16",
";",
"}",
"var",
"codePoint",
"=",
"parseInt",
"(",
"num",
",",
"radix",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"codePoint",
")",
")",
"{",
"html",
"=",
"(",
"html",
".",
"substring",
"(",
"0",
",",
"pos",
")",
"+",
"String",
".",
"fromCharCode",
"(",
"codePoint",
")",
"+",
"html",
".",
"substring",
"(",
"end",
"+",
"1",
")",
")",
";",
"}",
"}",
"}",
"return",
"html",
".",
"replace",
"(",
"pr_ltEnt",
",",
"'<'",
")",
".",
"replace",
"(",
"pr_gtEnt",
",",
"'>'",
")",
".",
"replace",
"(",
"pr_aposEnt",
",",
"\"'\"",
")",
".",
"replace",
"(",
"pr_quotEnt",
",",
"'\"'",
")",
".",
"replace",
"(",
"pr_nbspEnt",
",",
"' '",
")",
".",
"replace",
"(",
"pr_ampEnt",
",",
"'&'",
")",
";",
"}"
]
| unescapes html to plain text. | [
"unescapes",
"html",
"to",
"plain",
"text",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L251-L280 |
43,417 | alexyoung/ico | docs/prettify.js | isPreformatted | function isPreformatted(node, content) {
// PRE means preformatted, and is a very common case, so don't create
// unnecessary computed style objects.
if ('PRE' === node.tagName) { return true; }
if (!newlineRe.test(content)) { return true; } // Don't care
var whitespace = '';
// For disconnected nodes, IE has no currentStyle.
if (node.currentStyle) {
whitespace = node.currentStyle.whiteSpace;
} else if (window.getComputedStyle) {
// Firefox makes a best guess if node is disconnected whereas Safari
// returns the empty string.
whitespace = window.getComputedStyle(node, null).whiteSpace;
}
return !whitespace || whitespace === 'pre';
} | javascript | function isPreformatted(node, content) {
// PRE means preformatted, and is a very common case, so don't create
// unnecessary computed style objects.
if ('PRE' === node.tagName) { return true; }
if (!newlineRe.test(content)) { return true; } // Don't care
var whitespace = '';
// For disconnected nodes, IE has no currentStyle.
if (node.currentStyle) {
whitespace = node.currentStyle.whiteSpace;
} else if (window.getComputedStyle) {
// Firefox makes a best guess if node is disconnected whereas Safari
// returns the empty string.
whitespace = window.getComputedStyle(node, null).whiteSpace;
}
return !whitespace || whitespace === 'pre';
} | [
"function",
"isPreformatted",
"(",
"node",
",",
"content",
")",
"{",
"// PRE means preformatted, and is a very common case, so don't create",
"// unnecessary computed style objects.",
"if",
"(",
"'PRE'",
"===",
"node",
".",
"tagName",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"newlineRe",
".",
"test",
"(",
"content",
")",
")",
"{",
"return",
"true",
";",
"}",
"// Don't care",
"var",
"whitespace",
"=",
"''",
";",
"// For disconnected nodes, IE has no currentStyle.",
"if",
"(",
"node",
".",
"currentStyle",
")",
"{",
"whitespace",
"=",
"node",
".",
"currentStyle",
".",
"whiteSpace",
";",
"}",
"else",
"if",
"(",
"window",
".",
"getComputedStyle",
")",
"{",
"// Firefox makes a best guess if node is disconnected whereas Safari",
"// returns the empty string.",
"whitespace",
"=",
"window",
".",
"getComputedStyle",
"(",
"node",
",",
"null",
")",
".",
"whiteSpace",
";",
"}",
"return",
"!",
"whitespace",
"||",
"whitespace",
"===",
"'pre'",
";",
"}"
]
| Are newlines and adjacent spaces significant in the given node's innerHTML? | [
"Are",
"newlines",
"and",
"adjacent",
"spaces",
"significant",
"in",
"the",
"given",
"node",
"s",
"innerHTML?"
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L291-L306 |
43,418 | alexyoung/ico | docs/prettify.js | makeTabExpander | function makeTabExpander(tabWidth) {
var SPACES = ' ';
var charInLine = 0;
return function (plainText) {
// walk over each character looking for tabs and newlines.
// On tabs, expand them. On newlines, reset charInLine.
// Otherwise increment charInLine
var out = null;
var pos = 0;
for (var i = 0, n = plainText.length; i < n; ++i) {
var ch = plainText.charAt(i);
switch (ch) {
case '\t':
if (!out) { out = []; }
out.push(plainText.substring(pos, i));
// calculate how much space we need in front of this part
// nSpaces is the amount of padding -- the number of spaces needed
// to move us to the next column, where columns occur at factors of
// tabWidth.
var nSpaces = tabWidth - (charInLine % tabWidth);
charInLine += nSpaces;
for (; nSpaces >= 0; nSpaces -= SPACES.length) {
out.push(SPACES.substring(0, nSpaces));
}
pos = i + 1;
break;
case '\n':
charInLine = 0;
break;
default:
++charInLine;
}
}
if (!out) { return plainText; }
out.push(plainText.substring(pos));
return out.join('');
};
} | javascript | function makeTabExpander(tabWidth) {
var SPACES = ' ';
var charInLine = 0;
return function (plainText) {
// walk over each character looking for tabs and newlines.
// On tabs, expand them. On newlines, reset charInLine.
// Otherwise increment charInLine
var out = null;
var pos = 0;
for (var i = 0, n = plainText.length; i < n; ++i) {
var ch = plainText.charAt(i);
switch (ch) {
case '\t':
if (!out) { out = []; }
out.push(plainText.substring(pos, i));
// calculate how much space we need in front of this part
// nSpaces is the amount of padding -- the number of spaces needed
// to move us to the next column, where columns occur at factors of
// tabWidth.
var nSpaces = tabWidth - (charInLine % tabWidth);
charInLine += nSpaces;
for (; nSpaces >= 0; nSpaces -= SPACES.length) {
out.push(SPACES.substring(0, nSpaces));
}
pos = i + 1;
break;
case '\n':
charInLine = 0;
break;
default:
++charInLine;
}
}
if (!out) { return plainText; }
out.push(plainText.substring(pos));
return out.join('');
};
} | [
"function",
"makeTabExpander",
"(",
"tabWidth",
")",
"{",
"var",
"SPACES",
"=",
"' '",
";",
"var",
"charInLine",
"=",
"0",
";",
"return",
"function",
"(",
"plainText",
")",
"{",
"// walk over each character looking for tabs and newlines.",
"// On tabs, expand them. On newlines, reset charInLine.",
"// Otherwise increment charInLine",
"var",
"out",
"=",
"null",
";",
"var",
"pos",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"plainText",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"var",
"ch",
"=",
"plainText",
".",
"charAt",
"(",
"i",
")",
";",
"switch",
"(",
"ch",
")",
"{",
"case",
"'\\t'",
":",
"if",
"(",
"!",
"out",
")",
"{",
"out",
"=",
"[",
"]",
";",
"}",
"out",
".",
"push",
"(",
"plainText",
".",
"substring",
"(",
"pos",
",",
"i",
")",
")",
";",
"// calculate how much space we need in front of this part",
"// nSpaces is the amount of padding -- the number of spaces needed",
"// to move us to the next column, where columns occur at factors of",
"// tabWidth.",
"var",
"nSpaces",
"=",
"tabWidth",
"-",
"(",
"charInLine",
"%",
"tabWidth",
")",
";",
"charInLine",
"+=",
"nSpaces",
";",
"for",
"(",
";",
"nSpaces",
">=",
"0",
";",
"nSpaces",
"-=",
"SPACES",
".",
"length",
")",
"{",
"out",
".",
"push",
"(",
"SPACES",
".",
"substring",
"(",
"0",
",",
"nSpaces",
")",
")",
";",
"}",
"pos",
"=",
"i",
"+",
"1",
";",
"break",
";",
"case",
"'\\n'",
":",
"charInLine",
"=",
"0",
";",
"break",
";",
"default",
":",
"++",
"charInLine",
";",
"}",
"}",
"if",
"(",
"!",
"out",
")",
"{",
"return",
"plainText",
";",
"}",
"out",
".",
"push",
"(",
"plainText",
".",
"substring",
"(",
"pos",
")",
")",
";",
"return",
"out",
".",
"join",
"(",
"''",
")",
";",
"}",
";",
"}"
]
| returns a function that expand tabs to spaces. This function can be fed
successive chunks of text, and will maintain its own internal state to
keep track of how tabs are expanded.
@return {function (string) : string} a function that takes
plain text and return the text with tabs expanded.
@private | [
"returns",
"a",
"function",
"that",
"expand",
"tabs",
"to",
"spaces",
".",
"This",
"function",
"can",
"be",
"fed",
"successive",
"chunks",
"of",
"text",
"and",
"will",
"maintain",
"its",
"own",
"internal",
"state",
"to",
"keep",
"track",
"of",
"how",
"tabs",
"are",
"expanded",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L613-L652 |
43,419 | alexyoung/ico | docs/prettify.js | function (job) {
var sourceCode = job.source, basePos = job.basePos;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
} | javascript | function (job) {
var sourceCode = job.source, basePos = job.basePos;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
} | [
"function",
"(",
"job",
")",
"{",
"var",
"sourceCode",
"=",
"job",
".",
"source",
",",
"basePos",
"=",
"job",
".",
"basePos",
";",
"/** Even entries are positions in source in ascending order. Odd enties\n * are style markers (e.g., PR_COMMENT) that run from that position until\n * the end.\n * @type {Array.<number|string>}\n */",
"var",
"decorations",
"=",
"[",
"basePos",
",",
"PR_PLAIN",
"]",
";",
"var",
"pos",
"=",
"0",
";",
"// index into sourceCode",
"var",
"tokens",
"=",
"sourceCode",
".",
"match",
"(",
"tokenizer",
")",
"||",
"[",
"]",
";",
"var",
"styleCache",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"ti",
"=",
"0",
",",
"nTokens",
"=",
"tokens",
".",
"length",
";",
"ti",
"<",
"nTokens",
";",
"++",
"ti",
")",
"{",
"var",
"token",
"=",
"tokens",
"[",
"ti",
"]",
";",
"var",
"style",
"=",
"styleCache",
"[",
"token",
"]",
";",
"var",
"match",
"=",
"void",
"0",
";",
"var",
"isEmbedded",
";",
"if",
"(",
"typeof",
"style",
"===",
"'string'",
")",
"{",
"isEmbedded",
"=",
"false",
";",
"}",
"else",
"{",
"var",
"patternParts",
"=",
"shortcuts",
"[",
"token",
".",
"charAt",
"(",
"0",
")",
"]",
";",
"if",
"(",
"patternParts",
")",
"{",
"match",
"=",
"token",
".",
"match",
"(",
"patternParts",
"[",
"1",
"]",
")",
";",
"style",
"=",
"patternParts",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nPatterns",
";",
"++",
"i",
")",
"{",
"patternParts",
"=",
"fallthroughStylePatterns",
"[",
"i",
"]",
";",
"match",
"=",
"token",
".",
"match",
"(",
"patternParts",
"[",
"1",
"]",
")",
";",
"if",
"(",
"match",
")",
"{",
"style",
"=",
"patternParts",
"[",
"0",
"]",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"match",
")",
"{",
"// make sure that we make progress",
"style",
"=",
"PR_PLAIN",
";",
"}",
"}",
"isEmbedded",
"=",
"style",
".",
"length",
">=",
"5",
"&&",
"'lang-'",
"===",
"style",
".",
"substring",
"(",
"0",
",",
"5",
")",
";",
"if",
"(",
"isEmbedded",
"&&",
"!",
"(",
"match",
"&&",
"typeof",
"match",
"[",
"1",
"]",
"===",
"'string'",
")",
")",
"{",
"isEmbedded",
"=",
"false",
";",
"style",
"=",
"PR_SOURCE",
";",
"}",
"if",
"(",
"!",
"isEmbedded",
")",
"{",
"styleCache",
"[",
"token",
"]",
"=",
"style",
";",
"}",
"}",
"var",
"tokenStart",
"=",
"pos",
";",
"pos",
"+=",
"token",
".",
"length",
";",
"if",
"(",
"!",
"isEmbedded",
")",
"{",
"decorations",
".",
"push",
"(",
"basePos",
"+",
"tokenStart",
",",
"style",
")",
";",
"}",
"else",
"{",
"// Treat group 1 as an embedded block of source code.",
"var",
"embeddedSource",
"=",
"match",
"[",
"1",
"]",
";",
"var",
"embeddedSourceStart",
"=",
"token",
".",
"indexOf",
"(",
"embeddedSource",
")",
";",
"var",
"embeddedSourceEnd",
"=",
"embeddedSourceStart",
"+",
"embeddedSource",
".",
"length",
";",
"if",
"(",
"match",
"[",
"2",
"]",
")",
"{",
"// If embeddedSource can be blank, then it would match at the",
"// beginning which would cause us to infinitely recurse on the",
"// entire token, so we catch the right context in match[2].",
"embeddedSourceEnd",
"=",
"token",
".",
"length",
"-",
"match",
"[",
"2",
"]",
".",
"length",
";",
"embeddedSourceStart",
"=",
"embeddedSourceEnd",
"-",
"embeddedSource",
".",
"length",
";",
"}",
"var",
"lang",
"=",
"style",
".",
"substring",
"(",
"5",
")",
";",
"// Decorate the left of the embedded source",
"appendDecorations",
"(",
"basePos",
"+",
"tokenStart",
",",
"token",
".",
"substring",
"(",
"0",
",",
"embeddedSourceStart",
")",
",",
"decorate",
",",
"decorations",
")",
";",
"// Decorate the embedded source",
"appendDecorations",
"(",
"basePos",
"+",
"tokenStart",
"+",
"embeddedSourceStart",
",",
"embeddedSource",
",",
"langHandlerForExtension",
"(",
"lang",
",",
"embeddedSource",
")",
",",
"decorations",
")",
";",
"// Decorate the right of the embedded section",
"appendDecorations",
"(",
"basePos",
"+",
"tokenStart",
"+",
"embeddedSourceEnd",
",",
"token",
".",
"substring",
"(",
"embeddedSourceEnd",
")",
",",
"decorate",
",",
"decorations",
")",
";",
"}",
"}",
"job",
".",
"decorations",
"=",
"decorations",
";",
"}"
]
| Lexes job.source and produces an output array job.decorations of style
classes preceded by the position at which they start in job.source in
order.
@param {Object} job an object like {@code
source: {string} sourceText plain text,
basePos: {int} position of job.source in the larger chunk of
sourceCode.
} | [
"Lexes",
"job",
".",
"source",
"and",
"produces",
"an",
"output",
"array",
"job",
".",
"decorations",
"of",
"style",
"classes",
"preceded",
"by",
"the",
"position",
"at",
"which",
"they",
"start",
"in",
"job",
".",
"source",
"in",
"order",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L849-L934 |
|
43,420 | alexyoung/ico | docs/prettify.js | sourceDecorator | function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push(
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
if (options['hashComments']) {
if (options['cStyleComments']) {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
if (options['regexLiterals']) {
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C]'
// escape sequences (\x5C),
+ '|\\x5C[\\s\\S]'
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var keywords = options['keywords'].replace(/^\s+|\s+$/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
[PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
} | javascript | function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push(
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
if (options['hashComments']) {
if (options['cStyleComments']) {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
if (options['regexLiterals']) {
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C]'
// escape sequences (\x5C),
+ '|\\x5C[\\s\\S]'
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var keywords = options['keywords'].replace(/^\s+|\s+$/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
[PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
} | [
"function",
"sourceDecorator",
"(",
"options",
")",
"{",
"var",
"shortcutStylePatterns",
"=",
"[",
"]",
",",
"fallthroughStylePatterns",
"=",
"[",
"]",
";",
"if",
"(",
"options",
"[",
"'tripleQuotedStrings'",
"]",
")",
"{",
"// '''multi-line-string''', 'single-line-string', and double-quoted",
"shortcutStylePatterns",
".",
"push",
"(",
"[",
"PR_STRING",
",",
"/",
"^(?:\\'\\'\\'(?:[^\\'\\\\]|\\\\[\\s\\S]|\\'{1,2}(?=[^\\']))*(?:\\'\\'\\'|$)|\\\"\\\"\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S]|\\\"{1,2}(?=[^\\\"]))*(?:\\\"\\\"\\\"|$)|\\'(?:[^\\\\\\']|\\\\[\\s\\S])*(?:\\'|$)|\\\"(?:[^\\\\\\\"]|\\\\[\\s\\S])*(?:\\\"|$))",
"/",
",",
"null",
",",
"'\\'\"'",
"]",
")",
";",
"}",
"else",
"if",
"(",
"options",
"[",
"'multiLineStrings'",
"]",
")",
"{",
"// 'multi-line-string', \"multi-line-string\"",
"shortcutStylePatterns",
".",
"push",
"(",
"[",
"PR_STRING",
",",
"/",
"^(?:\\'(?:[^\\\\\\']|\\\\[\\s\\S])*(?:\\'|$)|\\\"(?:[^\\\\\\\"]|\\\\[\\s\\S])*(?:\\\"|$)|\\`(?:[^\\\\\\`]|\\\\[\\s\\S])*(?:\\`|$))",
"/",
",",
"null",
",",
"'\\'\"`'",
"]",
")",
";",
"}",
"else",
"{",
"// 'single-line-string', \"single-line-string\"",
"shortcutStylePatterns",
".",
"push",
"(",
"[",
"PR_STRING",
",",
"/",
"^(?:\\'(?:[^\\\\\\'\\r\\n]|\\\\.)*(?:\\'|$)|\\\"(?:[^\\\\\\\"\\r\\n]|\\\\.)*(?:\\\"|$))",
"/",
",",
"null",
",",
"'\"\\''",
"]",
")",
";",
"}",
"if",
"(",
"options",
"[",
"'verbatimStrings'",
"]",
")",
"{",
"// verbatim-string-literal production from the C# grammar. See issue 93.",
"fallthroughStylePatterns",
".",
"push",
"(",
"[",
"PR_STRING",
",",
"/",
"^@\\\"(?:[^\\\"]|\\\"\\\")*(?:\\\"|$)",
"/",
",",
"null",
"]",
")",
";",
"}",
"if",
"(",
"options",
"[",
"'hashComments'",
"]",
")",
"{",
"if",
"(",
"options",
"[",
"'cStyleComments'",
"]",
")",
"{",
"// Stop C preprocessor declarations at an unclosed open comment",
"shortcutStylePatterns",
".",
"push",
"(",
"[",
"PR_COMMENT",
",",
"/",
"^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\\b|[^\\r\\n]*)",
"/",
",",
"null",
",",
"'#'",
"]",
")",
";",
"fallthroughStylePatterns",
".",
"push",
"(",
"[",
"PR_STRING",
",",
"/",
"^<(?:(?:(?:\\.\\.\\/)*|\\/?)(?:[\\w-]+(?:\\/[\\w-]+)+)?[\\w-]+\\.h|[a-z]\\w*)>",
"/",
",",
"null",
"]",
")",
";",
"}",
"else",
"{",
"shortcutStylePatterns",
".",
"push",
"(",
"[",
"PR_COMMENT",
",",
"/",
"^#[^\\r\\n]*",
"/",
",",
"null",
",",
"'#'",
"]",
")",
";",
"}",
"}",
"if",
"(",
"options",
"[",
"'cStyleComments'",
"]",
")",
"{",
"fallthroughStylePatterns",
".",
"push",
"(",
"[",
"PR_COMMENT",
",",
"/",
"^\\/\\/[^\\r\\n]*",
"/",
",",
"null",
"]",
")",
";",
"fallthroughStylePatterns",
".",
"push",
"(",
"[",
"PR_COMMENT",
",",
"/",
"^\\/\\*[\\s\\S]*?(?:\\*\\/|$)",
"/",
",",
"null",
"]",
")",
";",
"}",
"if",
"(",
"options",
"[",
"'regexLiterals'",
"]",
")",
"{",
"var",
"REGEX_LITERAL",
"=",
"(",
"// A regular expression literal starts with a slash that is",
"// not followed by * or / so that it is not confused with",
"// comments.",
"'/(?=[^/*])'",
"// and then contains any number of raw characters,",
"+",
"'(?:[^/\\\\x5B\\\\x5C]'",
"// escape sequences (\\x5C),",
"+",
"'|\\\\x5C[\\\\s\\\\S]'",
"// or non-nesting character sets (\\x5B\\x5D);",
"+",
"'|\\\\x5B(?:[^\\\\x5C\\\\x5D]|\\\\x5C[\\\\s\\\\S])*(?:\\\\x5D|$))+'",
"// finally closed by a /.",
"+",
"'/'",
")",
";",
"fallthroughStylePatterns",
".",
"push",
"(",
"[",
"'lang-regex'",
",",
"new",
"RegExp",
"(",
"'^'",
"+",
"REGEXP_PRECEDER_PATTERN",
"+",
"'('",
"+",
"REGEX_LITERAL",
"+",
"')'",
")",
"]",
")",
";",
"}",
"var",
"keywords",
"=",
"options",
"[",
"'keywords'",
"]",
".",
"replace",
"(",
"/",
"^\\s+|\\s+$",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"keywords",
".",
"length",
")",
"{",
"fallthroughStylePatterns",
".",
"push",
"(",
"[",
"PR_KEYWORD",
",",
"new",
"RegExp",
"(",
"'^(?:'",
"+",
"keywords",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"'|'",
")",
"+",
"')\\\\b'",
")",
",",
"null",
"]",
")",
";",
"}",
"shortcutStylePatterns",
".",
"push",
"(",
"[",
"PR_PLAIN",
",",
"/",
"^\\s+",
"/",
",",
"null",
",",
"' \\r\\n\\t\\xA0'",
"]",
")",
";",
"fallthroughStylePatterns",
".",
"push",
"(",
"// TODO(mikesamuel): recognize non-latin letters and numerals in idents",
"[",
"PR_LITERAL",
",",
"/",
"^@[a-z_$][a-z_$@0-9]*",
"/",
"i",
",",
"null",
"]",
",",
"[",
"PR_TYPE",
",",
"/",
"^@?[A-Z]+[a-z][A-Za-z_$@0-9]*",
"/",
",",
"null",
"]",
",",
"[",
"PR_PLAIN",
",",
"/",
"^[a-z_$][a-z_$@0-9]*",
"/",
"i",
",",
"null",
"]",
",",
"[",
"PR_LITERAL",
",",
"new",
"RegExp",
"(",
"'^(?:'",
"// A hex number",
"+",
"'0x[a-f0-9]+'",
"// or an octal or decimal number,",
"+",
"'|(?:\\\\d(?:_\\\\d+)*\\\\d*(?:\\\\.\\\\d*)?|\\\\.\\\\d\\\\+)'",
"// possibly in scientific notation",
"+",
"'(?:e[+\\\\-]?\\\\d+)?'",
"+",
"')'",
"// with an optional modifier like UL for unsigned long",
"+",
"'[a-z]*'",
",",
"'i'",
")",
",",
"null",
",",
"'0123456789'",
"]",
",",
"[",
"PR_PUNCTUATION",
",",
"/",
"^.[^\\s\\w\\.$@\\'\\\"\\`\\/\\#]*",
"/",
",",
"null",
"]",
")",
";",
"return",
"createSimpleLexer",
"(",
"shortcutStylePatterns",
",",
"fallthroughStylePatterns",
")",
";",
"}"
]
| returns a function that produces a list of decorations from source text.
This code treats ", ', and ` as string delimiters, and \ as a string
escape. It does not recognize perl's qq() style strings.
It has no special handling for double delimiter escapes as in basic, or
the tripled delimiters used in python, but should work on those regardless
although in those cases a single string literal may be broken up into
multiple adjacent string literals.
It recognizes C, C++, and shell style comments.
@param {Object} options a set of optional parameters.
@return {function (Object)} a function that examines the source code
in the input job and builds the decoration list. | [
"returns",
"a",
"function",
"that",
"produces",
"a",
"list",
"of",
"decorations",
"from",
"source",
"text",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L953-L1045 |
43,421 | alexyoung/ico | docs/prettify.js | emitTextUpTo | function emitTextUpTo(sourceIdx) {
if (sourceIdx > outputIdx) {
if (openDecoration && openDecoration !== currentDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
if (!openDecoration && currentDecoration) {
openDecoration = currentDecoration;
html.push('<span class="', openDecoration, '">');
}
// This interacts badly with some wikis which introduces paragraph tags
// into pre blocks for some strange reason.
// It's necessary for IE though which seems to lose the preformattedness
// of <pre> tags when their innerHTML is assigned.
// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
// and it serves to undo the conversion of <br>s to newlines done in
// chunkify.
var htmlChunk = textToHtml(
tabExpander(sourceText.substring(outputIdx, sourceIdx)))
.replace(lastWasSpace
? startOrSpaceRe
: adjacentSpaceRe, '$1 ');
// Keep track of whether we need to escape space at the beginning of the
// next chunk.
lastWasSpace = trailingSpaceRe.test(htmlChunk);
html.push(htmlChunk.replace(newlineRe, lineBreaker));
outputIdx = sourceIdx;
}
} | javascript | function emitTextUpTo(sourceIdx) {
if (sourceIdx > outputIdx) {
if (openDecoration && openDecoration !== currentDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
if (!openDecoration && currentDecoration) {
openDecoration = currentDecoration;
html.push('<span class="', openDecoration, '">');
}
// This interacts badly with some wikis which introduces paragraph tags
// into pre blocks for some strange reason.
// It's necessary for IE though which seems to lose the preformattedness
// of <pre> tags when their innerHTML is assigned.
// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
// and it serves to undo the conversion of <br>s to newlines done in
// chunkify.
var htmlChunk = textToHtml(
tabExpander(sourceText.substring(outputIdx, sourceIdx)))
.replace(lastWasSpace
? startOrSpaceRe
: adjacentSpaceRe, '$1 ');
// Keep track of whether we need to escape space at the beginning of the
// next chunk.
lastWasSpace = trailingSpaceRe.test(htmlChunk);
html.push(htmlChunk.replace(newlineRe, lineBreaker));
outputIdx = sourceIdx;
}
} | [
"function",
"emitTextUpTo",
"(",
"sourceIdx",
")",
"{",
"if",
"(",
"sourceIdx",
">",
"outputIdx",
")",
"{",
"if",
"(",
"openDecoration",
"&&",
"openDecoration",
"!==",
"currentDecoration",
")",
"{",
"// Close the current decoration",
"html",
".",
"push",
"(",
"'</span>'",
")",
";",
"openDecoration",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"openDecoration",
"&&",
"currentDecoration",
")",
"{",
"openDecoration",
"=",
"currentDecoration",
";",
"html",
".",
"push",
"(",
"'<span class=\"'",
",",
"openDecoration",
",",
"'\">'",
")",
";",
"}",
"// This interacts badly with some wikis which introduces paragraph tags",
"// into pre blocks for some strange reason.",
"// It's necessary for IE though which seems to lose the preformattedness",
"// of <pre> tags when their innerHTML is assigned.",
"// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html",
"// and it serves to undo the conversion of <br>s to newlines done in",
"// chunkify.",
"var",
"htmlChunk",
"=",
"textToHtml",
"(",
"tabExpander",
"(",
"sourceText",
".",
"substring",
"(",
"outputIdx",
",",
"sourceIdx",
")",
")",
")",
".",
"replace",
"(",
"lastWasSpace",
"?",
"startOrSpaceRe",
":",
"adjacentSpaceRe",
",",
"'$1 '",
")",
";",
"// Keep track of whether we need to escape space at the beginning of the",
"// next chunk.",
"lastWasSpace",
"=",
"trailingSpaceRe",
".",
"test",
"(",
"htmlChunk",
")",
";",
"html",
".",
"push",
"(",
"htmlChunk",
".",
"replace",
"(",
"newlineRe",
",",
"lineBreaker",
")",
")",
";",
"outputIdx",
"=",
"sourceIdx",
";",
"}",
"}"
]
| A helper function that is responsible for opening sections of decoration and outputing properly escaped chunks of source | [
"A",
"helper",
"function",
"that",
"is",
"responsible",
"for",
"opening",
"sections",
"of",
"decoration",
"and",
"outputing",
"properly",
"escaped",
"chunks",
"of",
"source"
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/docs/prettify.js#L1135-L1164 |
43,422 | sockethub/sockethub-platform-xmpp | lib/incoming-handlers.js | referenceProtection | function referenceProtection(session) {
function checkScope(funcName) {
return (msg) => {
if (typeof session[funcName] === 'function') {
session[funcName](msg);
}
}
}
return {
actor: session.actor,
debug: checkScope('debug'),
sendToClient: checkScope('sendToClient')
}
} | javascript | function referenceProtection(session) {
function checkScope(funcName) {
return (msg) => {
if (typeof session[funcName] === 'function') {
session[funcName](msg);
}
}
}
return {
actor: session.actor,
debug: checkScope('debug'),
sendToClient: checkScope('sendToClient')
}
} | [
"function",
"referenceProtection",
"(",
"session",
")",
"{",
"function",
"checkScope",
"(",
"funcName",
")",
"{",
"return",
"(",
"msg",
")",
"=>",
"{",
"if",
"(",
"typeof",
"session",
"[",
"funcName",
"]",
"===",
"'function'",
")",
"{",
"session",
"[",
"funcName",
"]",
"(",
"msg",
")",
";",
"}",
"}",
"}",
"return",
"{",
"actor",
":",
"session",
".",
"actor",
",",
"debug",
":",
"checkScope",
"(",
"'debug'",
")",
",",
"sendToClient",
":",
"checkScope",
"(",
"'sendToClient'",
")",
"}",
"}"
]
| if the platform throws an exception, the worker will kill & restart it, however if a callback comes in there could be a race condition which tries to still access session functions which have already been terminated by the worker. this function wrapper only calls the session functions if they still exist. | [
"if",
"the",
"platform",
"throws",
"an",
"exception",
"the",
"worker",
"will",
"kill",
"&",
"restart",
"it",
"however",
"if",
"a",
"callback",
"comes",
"in",
"there",
"could",
"be",
"a",
"race",
"condition",
"which",
"tries",
"to",
"still",
"access",
"session",
"functions",
"which",
"have",
"already",
"been",
"terminated",
"by",
"the",
"worker",
".",
"this",
"function",
"wrapper",
"only",
"calls",
"the",
"session",
"functions",
"if",
"they",
"still",
"exist",
"."
]
| 1a7f50b77320bedf9555a1e8cb546e92c6b19132 | https://github.com/sockethub/sockethub-platform-xmpp/blob/1a7f50b77320bedf9555a1e8cb546e92c6b19132/lib/incoming-handlers.js#L11-L24 |
43,423 | chenboxiang/fdfs-client | lib/protocol.js | function(raw) {
var result = {}
var md = raw.split(protocol.FDFS_RECORD_SEPERATOR)
md.forEach(function(item) {
var arr = item.split(protocol.FDFS_FIELD_SEPERATOR)
var key = helpers.trim(arr[0])
var value = helpers.trim(arr[1])
result[key] = value
})
return result
} | javascript | function(raw) {
var result = {}
var md = raw.split(protocol.FDFS_RECORD_SEPERATOR)
md.forEach(function(item) {
var arr = item.split(protocol.FDFS_FIELD_SEPERATOR)
var key = helpers.trim(arr[0])
var value = helpers.trim(arr[1])
result[key] = value
})
return result
} | [
"function",
"(",
"raw",
")",
"{",
"var",
"result",
"=",
"{",
"}",
"var",
"md",
"=",
"raw",
".",
"split",
"(",
"protocol",
".",
"FDFS_RECORD_SEPERATOR",
")",
"md",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"arr",
"=",
"item",
".",
"split",
"(",
"protocol",
".",
"FDFS_FIELD_SEPERATOR",
")",
"var",
"key",
"=",
"helpers",
".",
"trim",
"(",
"arr",
"[",
"0",
"]",
")",
"var",
"value",
"=",
"helpers",
".",
"trim",
"(",
"arr",
"[",
"1",
"]",
")",
"result",
"[",
"key",
"]",
"=",
"value",
"}",
")",
"return",
"result",
"}"
]
| raw meta data to structure
@param raw | [
"raw",
"meta",
"data",
"to",
"structure"
]
| bca7eb8db6c0b732c6a2dc43decac3c4c71d8a5a | https://github.com/chenboxiang/fdfs-client/blob/bca7eb8db6c0b732c6a2dc43decac3c4c71d8a5a/lib/protocol.js#L301-L312 |
|
43,424 | alexyoung/ico | src/helpers.js | getStyle | function getStyle(el, styleProp) {
if (typeof window === 'undefined') {
return;
}
var style;
if (el.currentStyle) {
style = el.currentStyle[styleProp];
} else if (window.getComputedStyle) {
style = document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
}
if (style && style.length === 0) {
style = null;
}
return style;
} | javascript | function getStyle(el, styleProp) {
if (typeof window === 'undefined') {
return;
}
var style;
if (el.currentStyle) {
style = el.currentStyle[styleProp];
} else if (window.getComputedStyle) {
style = document.defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
}
if (style && style.length === 0) {
style = null;
}
return style;
} | [
"function",
"getStyle",
"(",
"el",
",",
"styleProp",
")",
"{",
"if",
"(",
"typeof",
"window",
"===",
"'undefined'",
")",
"{",
"return",
";",
"}",
"var",
"style",
";",
"if",
"(",
"el",
".",
"currentStyle",
")",
"{",
"style",
"=",
"el",
".",
"currentStyle",
"[",
"styleProp",
"]",
";",
"}",
"else",
"if",
"(",
"window",
".",
"getComputedStyle",
")",
"{",
"style",
"=",
"document",
".",
"defaultView",
".",
"getComputedStyle",
"(",
"el",
",",
"null",
")",
".",
"getPropertyValue",
"(",
"styleProp",
")",
";",
"}",
"if",
"(",
"style",
"&&",
"style",
".",
"length",
"===",
"0",
")",
"{",
"style",
"=",
"null",
";",
"}",
"return",
"style",
";",
"}"
]
| Gets a CSS style property.
@param {Object} el A DOM element
@param {String} styleProp The name of a style property
@returns {Object} The style value | [
"Gets",
"a",
"CSS",
"style",
"property",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/src/helpers.js#L19-L34 |
43,425 | solid/solid-web-client | src/util/graph-util.js | parseGraph | function parseGraph (rdf, baseUrl, rdfSource, contentType) {
let parsedGraph = rdf.graph()
rdf.parse(rdfSource, parsedGraph, baseUrl, contentType)
return parsedGraph
} | javascript | function parseGraph (rdf, baseUrl, rdfSource, contentType) {
let parsedGraph = rdf.graph()
rdf.parse(rdfSource, parsedGraph, baseUrl, contentType)
return parsedGraph
} | [
"function",
"parseGraph",
"(",
"rdf",
",",
"baseUrl",
",",
"rdfSource",
",",
"contentType",
")",
"{",
"let",
"parsedGraph",
"=",
"rdf",
".",
"graph",
"(",
")",
"rdf",
".",
"parse",
"(",
"rdfSource",
",",
"parsedGraph",
",",
"baseUrl",
",",
"contentType",
")",
"return",
"parsedGraph",
"}"
]
| Parses a given graph, from text rdfSource, as a given content type.
Returns parsed graph.
@method parseGraph
@param rdf {RDF} RDF library such as rdflib.js
@param baseUrl {string}
@param rdfSource {string} Text source code
@param contentType {string} Mime Type (determines which parser to use)
@return {Graph} | [
"Parses",
"a",
"given",
"graph",
"from",
"text",
"rdfSource",
"as",
"a",
"given",
"content",
"type",
".",
"Returns",
"parsed",
"graph",
"."
]
| 1b3a9b333a68c3a288125acd29cff07d397c15b4 | https://github.com/solid/solid-web-client/blob/1b3a9b333a68c3a288125acd29cff07d397c15b4/src/util/graph-util.js#L60-L66 |
43,426 | alexyoung/ico | ico.js | function(num, dec) {
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
} | javascript | function(num, dec) {
var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
return result;
} | [
"function",
"(",
"num",
",",
"dec",
")",
"{",
"var",
"result",
"=",
"Math",
".",
"round",
"(",
"num",
"*",
"Math",
".",
"pow",
"(",
"10",
",",
"dec",
")",
")",
"/",
"Math",
".",
"pow",
"(",
"10",
",",
"dec",
")",
";",
"return",
"result",
";",
"}"
]
| Rounds a float to the specified number of decimal places.
@param {Float} num A number to round
@param {Integer} dec The number of decimal places
@returns {Float} The rounded result | [
"Rounds",
"a",
"float",
"to",
"the",
"specified",
"number",
"of",
"decimal",
"places",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/ico.js#L21-L24 |
|
43,427 | alexyoung/ico | ico.js | function(data) {
var values = [],
i = 0;
for (i = 0; i < data.length; i++) {
values.push(this.normalise(data[i]));
}
return values;
} | javascript | function(data) {
var values = [],
i = 0;
for (i = 0; i < data.length; i++) {
values.push(this.normalise(data[i]));
}
return values;
} | [
"function",
"(",
"data",
")",
"{",
"var",
"values",
"=",
"[",
"]",
",",
"i",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"values",
".",
"push",
"(",
"this",
".",
"normalise",
"(",
"data",
"[",
"i",
"]",
")",
")",
";",
"}",
"return",
"values",
";",
"}"
]
| Runs this.normalise on each value.
@param {Array} data Values to normalise
@returns {Array} Normalised values | [
"Runs",
"this",
".",
"normalise",
"on",
"each",
"value",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/ico.js#L234-L241 |
|
43,428 | alexyoung/ico | ico.js | function(data) {
var flat_data = [];
if (typeof data.length === 'undefined') {
if (typeof data === 'object') {
for (var key in data) {
if (data.hasOwnProperty(key))
flat_data = flat_data.concat(this.flatten(data[key]));
}
} else {
return [];
}
}
for (var i = 0; i < data.length; i++) {
if (typeof data[i].length === 'number') {
flat_data = flat_data.concat(this.flatten(data[i]));
} else {
flat_data.push(data[i]);
}
}
return flat_data;
} | javascript | function(data) {
var flat_data = [];
if (typeof data.length === 'undefined') {
if (typeof data === 'object') {
for (var key in data) {
if (data.hasOwnProperty(key))
flat_data = flat_data.concat(this.flatten(data[key]));
}
} else {
return [];
}
}
for (var i = 0; i < data.length; i++) {
if (typeof data[i].length === 'number') {
flat_data = flat_data.concat(this.flatten(data[i]));
} else {
flat_data.push(data[i]);
}
}
return flat_data;
} | [
"function",
"(",
"data",
")",
"{",
"var",
"flat_data",
"=",
"[",
"]",
";",
"if",
"(",
"typeof",
"data",
".",
"length",
"===",
"'undefined'",
")",
"{",
"if",
"(",
"typeof",
"data",
"===",
"'object'",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"data",
")",
"{",
"if",
"(",
"data",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"flat_data",
"=",
"flat_data",
".",
"concat",
"(",
"this",
".",
"flatten",
"(",
"data",
"[",
"key",
"]",
")",
")",
";",
"}",
"}",
"else",
"{",
"return",
"[",
"]",
";",
"}",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"data",
"[",
"i",
"]",
".",
"length",
"===",
"'number'",
")",
"{",
"flat_data",
"=",
"flat_data",
".",
"concat",
"(",
"this",
".",
"flatten",
"(",
"data",
"[",
"i",
"]",
")",
")",
";",
"}",
"else",
"{",
"flat_data",
".",
"push",
"(",
"data",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
"flat_data",
";",
"}"
]
| Flattens objects into an array.
@param {Object} data Values to flatten
@returns {Array} Flattened values | [
"Flattens",
"objects",
"into",
"an",
"array",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/ico.js#L249-L271 |
|
43,429 | alexyoung/ico | ico.js | function(start, end, options) {
var values = [], i;
for (i = start; i < end; i++) {
if (options && options.skip) {
if (i % options.skip === 0) {
values.push(i);
} else {
values.push(undefined);
}
} else {
values.push(i);
}
}
return values;
} | javascript | function(start, end, options) {
var values = [], i;
for (i = start; i < end; i++) {
if (options && options.skip) {
if (i % options.skip === 0) {
values.push(i);
} else {
values.push(undefined);
}
} else {
values.push(i);
}
}
return values;
} | [
"function",
"(",
"start",
",",
"end",
",",
"options",
")",
"{",
"var",
"values",
"=",
"[",
"]",
",",
"i",
";",
"for",
"(",
"i",
"=",
"start",
";",
"i",
"<",
"end",
";",
"i",
"++",
")",
"{",
"if",
"(",
"options",
"&&",
"options",
".",
"skip",
")",
"{",
"if",
"(",
"i",
"%",
"options",
".",
"skip",
"===",
"0",
")",
"{",
"values",
".",
"push",
"(",
"i",
")",
";",
"}",
"else",
"{",
"values",
".",
"push",
"(",
"undefined",
")",
";",
"}",
"}",
"else",
"{",
"values",
".",
"push",
"(",
"i",
")",
";",
"}",
"}",
"return",
"values",
";",
"}"
]
| Handy method to produce an array of numbers.
@param {Integer} start A number to start at
@param {Integer} end A number to end at
@returns {Array} An array of values | [
"Handy",
"method",
"to",
"produce",
"an",
"array",
"of",
"numbers",
"."
]
| b2f296660e0ae7814024f2d839b2dea2270c378f | https://github.com/alexyoung/ico/blob/b2f296660e0ae7814024f2d839b2dea2270c378f/ico.js#L280-L294 |
|
43,430 | thlorenz/hha | lib/summary.js | summary | function summary(hand) {
const res = {}
if (hand.players == null || hand.players.length === 0) return res
const bb = hand.info.bb
res.header = getHeader(hand)
const seatsInfo = getSeats(hand)
res.seats = seatsInfo.seats
res.chipStackRatio = seatsInfo.hero != null
? getChipStackRatio(res.header.gametype, res.header.bb, seatsInfo.hero)
: null
res.preflopSummary = seatsInfo.preflopSummary
res.preflopActions = getPlayerActions(hand, hand.actions.preflop)
if (hand.actions.flop != null && hand.actions.flop.length > 0) {
res.flopSummary = getFlopSummary(hand, bb)
res.flopActions = getPlayerActions(hand, hand.actions.flop)
}
if (hand.actions.turn != null && hand.actions.turn.length > 0) {
res.turnSummary = getTurnSummary(hand, bb)
res.turnActions = getPlayerActions(hand, hand.actions.turn)
}
if (hand.actions.river != null && hand.actions.river.length > 0) {
res.riverSummary = getRiverSummary(hand, bb)
res.riverActions = getPlayerActions(hand, hand.actions.river)
}
res.totalPot = getTotalPot(hand)
res.spoilers = getSpoilers(hand.players)
return res
} | javascript | function summary(hand) {
const res = {}
if (hand.players == null || hand.players.length === 0) return res
const bb = hand.info.bb
res.header = getHeader(hand)
const seatsInfo = getSeats(hand)
res.seats = seatsInfo.seats
res.chipStackRatio = seatsInfo.hero != null
? getChipStackRatio(res.header.gametype, res.header.bb, seatsInfo.hero)
: null
res.preflopSummary = seatsInfo.preflopSummary
res.preflopActions = getPlayerActions(hand, hand.actions.preflop)
if (hand.actions.flop != null && hand.actions.flop.length > 0) {
res.flopSummary = getFlopSummary(hand, bb)
res.flopActions = getPlayerActions(hand, hand.actions.flop)
}
if (hand.actions.turn != null && hand.actions.turn.length > 0) {
res.turnSummary = getTurnSummary(hand, bb)
res.turnActions = getPlayerActions(hand, hand.actions.turn)
}
if (hand.actions.river != null && hand.actions.river.length > 0) {
res.riverSummary = getRiverSummary(hand, bb)
res.riverActions = getPlayerActions(hand, hand.actions.river)
}
res.totalPot = getTotalPot(hand)
res.spoilers = getSpoilers(hand.players)
return res
} | [
"function",
"summary",
"(",
"hand",
")",
"{",
"const",
"res",
"=",
"{",
"}",
"if",
"(",
"hand",
".",
"players",
"==",
"null",
"||",
"hand",
".",
"players",
".",
"length",
"===",
"0",
")",
"return",
"res",
"const",
"bb",
"=",
"hand",
".",
"info",
".",
"bb",
"res",
".",
"header",
"=",
"getHeader",
"(",
"hand",
")",
"const",
"seatsInfo",
"=",
"getSeats",
"(",
"hand",
")",
"res",
".",
"seats",
"=",
"seatsInfo",
".",
"seats",
"res",
".",
"chipStackRatio",
"=",
"seatsInfo",
".",
"hero",
"!=",
"null",
"?",
"getChipStackRatio",
"(",
"res",
".",
"header",
".",
"gametype",
",",
"res",
".",
"header",
".",
"bb",
",",
"seatsInfo",
".",
"hero",
")",
":",
"null",
"res",
".",
"preflopSummary",
"=",
"seatsInfo",
".",
"preflopSummary",
"res",
".",
"preflopActions",
"=",
"getPlayerActions",
"(",
"hand",
",",
"hand",
".",
"actions",
".",
"preflop",
")",
"if",
"(",
"hand",
".",
"actions",
".",
"flop",
"!=",
"null",
"&&",
"hand",
".",
"actions",
".",
"flop",
".",
"length",
">",
"0",
")",
"{",
"res",
".",
"flopSummary",
"=",
"getFlopSummary",
"(",
"hand",
",",
"bb",
")",
"res",
".",
"flopActions",
"=",
"getPlayerActions",
"(",
"hand",
",",
"hand",
".",
"actions",
".",
"flop",
")",
"}",
"if",
"(",
"hand",
".",
"actions",
".",
"turn",
"!=",
"null",
"&&",
"hand",
".",
"actions",
".",
"turn",
".",
"length",
">",
"0",
")",
"{",
"res",
".",
"turnSummary",
"=",
"getTurnSummary",
"(",
"hand",
",",
"bb",
")",
"res",
".",
"turnActions",
"=",
"getPlayerActions",
"(",
"hand",
",",
"hand",
".",
"actions",
".",
"turn",
")",
"}",
"if",
"(",
"hand",
".",
"actions",
".",
"river",
"!=",
"null",
"&&",
"hand",
".",
"actions",
".",
"river",
".",
"length",
">",
"0",
")",
"{",
"res",
".",
"riverSummary",
"=",
"getRiverSummary",
"(",
"hand",
",",
"bb",
")",
"res",
".",
"riverActions",
"=",
"getPlayerActions",
"(",
"hand",
",",
"hand",
".",
"actions",
".",
"river",
")",
"}",
"res",
".",
"totalPot",
"=",
"getTotalPot",
"(",
"hand",
")",
"res",
".",
"spoilers",
"=",
"getSpoilers",
"(",
"hand",
".",
"players",
")",
"return",
"res",
"}"
]
| Converts a hand that was analyzed and then scripted to a summary representation.
The summary has the following properties:
- header: contains game info, like room, pokertype, blinds, etc.
- seats: lists the seats of the players including pos, chips and hero indicators
- chipsStackRatio: hero's M for tournaments, his BBs for cash games
- preflopSummary: hero's cards and position
- preflopActions: action types + amounts of each player by position
- flopSummary: pot at flop, board and playersInvolved
- flopActions: same as preflopActions
- turnSummary: pot at turn, turn card and playersInvolved
- turnActions: same as preflopActions
- riverSummary: pot at river, river card and playersInvolved
- riverActions: same as preflopActions
- totalPot: total money in the pot
- spoilers: players whos cards are known by position
@name hha.summary
@function
@param {Object} script
@returns {Object} the hand summarized | [
"Converts",
"a",
"hand",
"that",
"was",
"analyzed",
"and",
"then",
"scripted",
"to",
"a",
"summary",
"representation",
"."
]
| 28ae03e9d422881ad8a3b3dba9de32e01d8ac04c | https://github.com/thlorenz/hha/blob/28ae03e9d422881ad8a3b3dba9de32e01d8ac04c/lib/summary.js#L236-L270 |
43,431 | urbancups/node-sheets | src/sheets.js | sheetToTable | function sheetToTable(sheet) {
if (sheet.data.length === 0 || sheet.data[0].rowData === undefined) {
return {
title: sheet.properties.title,
headers: [],
formats: [],
rows: []
};
}
const gridData = sheet.data[0]; // first (unique) range
const headers = gridData.rowData[0].values // first row (headers)
.map(col => formattedValue(col));
const otherRows = gridData.rowData.slice(1);
const values =
otherRows.length > 0
? otherRows[0].values
: new Array(headers.length).fill({});
return {
title: sheet.properties.title,
headers: headers,
formats: values.map(value => effectiveFormat(value)),
rows: otherRows.map(row =>
zipObject(
headers,
row.values.map(value => ({
value: effectiveValue(value),
stringValue: formattedValue(value)
}))
)
)
};
} | javascript | function sheetToTable(sheet) {
if (sheet.data.length === 0 || sheet.data[0].rowData === undefined) {
return {
title: sheet.properties.title,
headers: [],
formats: [],
rows: []
};
}
const gridData = sheet.data[0]; // first (unique) range
const headers = gridData.rowData[0].values // first row (headers)
.map(col => formattedValue(col));
const otherRows = gridData.rowData.slice(1);
const values =
otherRows.length > 0
? otherRows[0].values
: new Array(headers.length).fill({});
return {
title: sheet.properties.title,
headers: headers,
formats: values.map(value => effectiveFormat(value)),
rows: otherRows.map(row =>
zipObject(
headers,
row.values.map(value => ({
value: effectiveValue(value),
stringValue: formattedValue(value)
}))
)
)
};
} | [
"function",
"sheetToTable",
"(",
"sheet",
")",
"{",
"if",
"(",
"sheet",
".",
"data",
".",
"length",
"===",
"0",
"||",
"sheet",
".",
"data",
"[",
"0",
"]",
".",
"rowData",
"===",
"undefined",
")",
"{",
"return",
"{",
"title",
":",
"sheet",
".",
"properties",
".",
"title",
",",
"headers",
":",
"[",
"]",
",",
"formats",
":",
"[",
"]",
",",
"rows",
":",
"[",
"]",
"}",
";",
"}",
"const",
"gridData",
"=",
"sheet",
".",
"data",
"[",
"0",
"]",
";",
"// first (unique) range",
"const",
"headers",
"=",
"gridData",
".",
"rowData",
"[",
"0",
"]",
".",
"values",
"// first row (headers)",
".",
"map",
"(",
"col",
"=>",
"formattedValue",
"(",
"col",
")",
")",
";",
"const",
"otherRows",
"=",
"gridData",
".",
"rowData",
".",
"slice",
"(",
"1",
")",
";",
"const",
"values",
"=",
"otherRows",
".",
"length",
">",
"0",
"?",
"otherRows",
"[",
"0",
"]",
".",
"values",
":",
"new",
"Array",
"(",
"headers",
".",
"length",
")",
".",
"fill",
"(",
"{",
"}",
")",
";",
"return",
"{",
"title",
":",
"sheet",
".",
"properties",
".",
"title",
",",
"headers",
":",
"headers",
",",
"formats",
":",
"values",
".",
"map",
"(",
"value",
"=>",
"effectiveFormat",
"(",
"value",
")",
")",
",",
"rows",
":",
"otherRows",
".",
"map",
"(",
"row",
"=>",
"zipObject",
"(",
"headers",
",",
"row",
".",
"values",
".",
"map",
"(",
"value",
"=>",
"(",
"{",
"value",
":",
"effectiveValue",
"(",
"value",
")",
",",
"stringValue",
":",
"formattedValue",
"(",
"value",
")",
"}",
")",
")",
")",
")",
"}",
";",
"}"
]
| Converter from google sheet format to node-sheets format | [
"Converter",
"from",
"google",
"sheet",
"format",
"to",
"node",
"-",
"sheets",
"format"
]
| 28078439fd71afc3cfd40ef060bd44c0e9366853 | https://github.com/urbancups/node-sheets/blob/28078439fd71afc3cfd40ef060bd44c0e9366853/src/sheets.js#L183-L217 |
43,432 | urbancups/node-sheets | src/sheets.js | getRanges | async function getRanges(
auth,
spreadsheetId,
ranges,
fields = 'properties.title,sheets.properties,sheets.data(rowData.values.effectiveValue,rowData.values.formattedValue,rowData.values.effectiveFormat.numberFormat)'
) {
var sheets = google.sheets('v4');
const response = await Q.ninvoke(sheets.spreadsheets, 'get', {
auth: auth,
spreadsheetId: spreadsheetId,
// https://developers.google.com/sheets/guides/concepts, https://developers.google.com/sheets/samples/sheet
fields: fields,
includeGridData: true,
ranges: ranges
});
const spreadsheet = response.data;
return spreadsheet;
} | javascript | async function getRanges(
auth,
spreadsheetId,
ranges,
fields = 'properties.title,sheets.properties,sheets.data(rowData.values.effectiveValue,rowData.values.formattedValue,rowData.values.effectiveFormat.numberFormat)'
) {
var sheets = google.sheets('v4');
const response = await Q.ninvoke(sheets.spreadsheets, 'get', {
auth: auth,
spreadsheetId: spreadsheetId,
// https://developers.google.com/sheets/guides/concepts, https://developers.google.com/sheets/samples/sheet
fields: fields,
includeGridData: true,
ranges: ranges
});
const spreadsheet = response.data;
return spreadsheet;
} | [
"async",
"function",
"getRanges",
"(",
"auth",
",",
"spreadsheetId",
",",
"ranges",
",",
"fields",
"=",
"'properties.title,sheets.properties,sheets.data(rowData.values.effectiveValue,rowData.values.formattedValue,rowData.values.effectiveFormat.numberFormat)'",
")",
"{",
"var",
"sheets",
"=",
"google",
".",
"sheets",
"(",
"'v4'",
")",
";",
"const",
"response",
"=",
"await",
"Q",
".",
"ninvoke",
"(",
"sheets",
".",
"spreadsheets",
",",
"'get'",
",",
"{",
"auth",
":",
"auth",
",",
"spreadsheetId",
":",
"spreadsheetId",
",",
"// https://developers.google.com/sheets/guides/concepts, https://developers.google.com/sheets/samples/sheet",
"fields",
":",
"fields",
",",
"includeGridData",
":",
"true",
",",
"ranges",
":",
"ranges",
"}",
")",
";",
"const",
"spreadsheet",
"=",
"response",
".",
"data",
";",
"return",
"spreadsheet",
";",
"}"
]
| Utility function to get a range from a spreadsheet | [
"Utility",
"function",
"to",
"get",
"a",
"range",
"from",
"a",
"spreadsheet"
]
| 28078439fd71afc3cfd40ef060bd44c0e9366853 | https://github.com/urbancups/node-sheets/blob/28078439fd71afc3cfd40ef060bd44c0e9366853/src/sheets.js#L295-L312 |
43,433 | behrad/mqtt-nedb-store | mqtt-nedb-store.js | function (options) {
if (!(this instanceof Store)) {
return new Store(options)
}
this._opts = options || {}
this.db = new Datastore({ filename: this._opts.filename, autoload: true })
} | javascript | function (options) {
if (!(this instanceof Store)) {
return new Store(options)
}
this._opts = options || {}
this.db = new Datastore({ filename: this._opts.filename, autoload: true })
} | [
"function",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Store",
")",
")",
"{",
"return",
"new",
"Store",
"(",
"options",
")",
"}",
"this",
".",
"_opts",
"=",
"options",
"||",
"{",
"}",
"this",
".",
"db",
"=",
"new",
"Datastore",
"(",
"{",
"filename",
":",
"this",
".",
"_opts",
".",
"filename",
",",
"autoload",
":",
"true",
"}",
")",
"}"
]
| NeDB implementation of the message store | [
"NeDB",
"implementation",
"of",
"the",
"message",
"store"
]
| 91c64e9c0ac39b3ebc96aa861327f66e208b0326 | https://github.com/behrad/mqtt-nedb-store/blob/91c64e9c0ac39b3ebc96aa861327f66e208b0326/mqtt-nedb-store.js#L14-L21 |
|
43,434 | audiojs/audio-gain | direct.js | gain | function gain(options) {
// gain()
if (options == null) options = {volume: 1};
// gain(Function)
// gain(Number)
else if (typeof options === 'function' || typeof options === 'number') options = {volume: options};
var volume;
if (options.mode === 'tan') {
volume = Math.tan(options.volume);
} else {
volume = options.volume;
}
//in case if volume is fn
if (typeof volume === 'function') return buf => util.fill(buf, (v, x, channels) => v * volume(x, channels, v));
return buf => util.fill(buf, v => v * volume);
} | javascript | function gain(options) {
// gain()
if (options == null) options = {volume: 1};
// gain(Function)
// gain(Number)
else if (typeof options === 'function' || typeof options === 'number') options = {volume: options};
var volume;
if (options.mode === 'tan') {
volume = Math.tan(options.volume);
} else {
volume = options.volume;
}
//in case if volume is fn
if (typeof volume === 'function') return buf => util.fill(buf, (v, x, channels) => v * volume(x, channels, v));
return buf => util.fill(buf, v => v * volume);
} | [
"function",
"gain",
"(",
"options",
")",
"{",
"// gain()",
"if",
"(",
"options",
"==",
"null",
")",
"options",
"=",
"{",
"volume",
":",
"1",
"}",
";",
"// gain(Function)",
"// gain(Number)",
"else",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
"||",
"typeof",
"options",
"===",
"'number'",
")",
"options",
"=",
"{",
"volume",
":",
"options",
"}",
";",
"var",
"volume",
";",
"if",
"(",
"options",
".",
"mode",
"===",
"'tan'",
")",
"{",
"volume",
"=",
"Math",
".",
"tan",
"(",
"options",
".",
"volume",
")",
";",
"}",
"else",
"{",
"volume",
"=",
"options",
".",
"volume",
";",
"}",
"//in case if volume is fn",
"if",
"(",
"typeof",
"volume",
"===",
"'function'",
")",
"return",
"buf",
"=>",
"util",
".",
"fill",
"(",
"buf",
",",
"(",
"v",
",",
"x",
",",
"channels",
")",
"=>",
"v",
"*",
"volume",
"(",
"x",
",",
"channels",
",",
"v",
")",
")",
";",
"return",
"buf",
"=>",
"util",
".",
"fill",
"(",
"buf",
",",
"v",
"=>",
"v",
"*",
"volume",
")",
";",
"}"
]
| Create pcm volume controller.
@function | [
"Create",
"pcm",
"volume",
"controller",
"."
]
| 0ac4ef52335c275a519940aaf20d0d6a45c42f9d | https://github.com/audiojs/audio-gain/blob/0ac4ef52335c275a519940aaf20d0d6a45c42f9d/direct.js#L17-L36 |
43,435 | chenboxiang/fdfs-client | lib/helpers.js | function(fileId) {
var pos = fileId.indexOf('/')
return {
group: fileId.substring(0, pos),
filename: fileId.substring(pos + 1)
}
} | javascript | function(fileId) {
var pos = fileId.indexOf('/')
return {
group: fileId.substring(0, pos),
filename: fileId.substring(pos + 1)
}
} | [
"function",
"(",
"fileId",
")",
"{",
"var",
"pos",
"=",
"fileId",
".",
"indexOf",
"(",
"'/'",
")",
"return",
"{",
"group",
":",
"fileId",
".",
"substring",
"(",
"0",
",",
"pos",
")",
",",
"filename",
":",
"fileId",
".",
"substring",
"(",
"pos",
"+",
"1",
")",
"}",
"}"
]
| file id conver to group and filename
@param fileId
@returns {{group: string, filename: string}} | [
"file",
"id",
"conver",
"to",
"group",
"and",
"filename"
]
| bca7eb8db6c0b732c6a2dc43decac3c4c71d8a5a | https://github.com/chenboxiang/fdfs-client/blob/bca7eb8db6c0b732c6a2dc43decac3c4c71d8a5a/lib/helpers.js#L84-L90 |
|
43,436 | Sixthdim/angular-vertilize | angular-vertilize.js | function(){
var clone = element.clone()
.removeAttr('vertilize')
.css({
height: '',
width: element.outerWidth(),
position: 'fixed',
top: 0,
left: 0,
visibility: 'hidden'
});
element.after(clone);
var realHeight = clone.height();
clone['remove']();
return realHeight;
} | javascript | function(){
var clone = element.clone()
.removeAttr('vertilize')
.css({
height: '',
width: element.outerWidth(),
position: 'fixed',
top: 0,
left: 0,
visibility: 'hidden'
});
element.after(clone);
var realHeight = clone.height();
clone['remove']();
return realHeight;
} | [
"function",
"(",
")",
"{",
"var",
"clone",
"=",
"element",
".",
"clone",
"(",
")",
".",
"removeAttr",
"(",
"'vertilize'",
")",
".",
"css",
"(",
"{",
"height",
":",
"''",
",",
"width",
":",
"element",
".",
"outerWidth",
"(",
")",
",",
"position",
":",
"'fixed'",
",",
"top",
":",
"0",
",",
"left",
":",
"0",
",",
"visibility",
":",
"'hidden'",
"}",
")",
";",
"element",
".",
"after",
"(",
"clone",
")",
";",
"var",
"realHeight",
"=",
"clone",
".",
"height",
"(",
")",
";",
"clone",
"[",
"'remove'",
"]",
"(",
")",
";",
"return",
"realHeight",
";",
"}"
]
| Get my real height by cloning so my height is not affected. | [
"Get",
"my",
"real",
"height",
"by",
"cloning",
"so",
"my",
"height",
"is",
"not",
"affected",
"."
]
| 860c0dd22f90eebfcc392d176e8d9cb5c3ef6ee1 | https://github.com/Sixthdim/angular-vertilize/blob/860c0dd22f90eebfcc392d176e8d9cb5c3ef6ee1/angular-vertilize.js#L67-L82 |
|
43,437 | kchapelier/cellular-automata | lib/cellular-automata.js | neighbourhoodSorter | function neighbourhoodSorter (a, b) {
a = a.join(',');
b = b.join(',');
return a > b ? 1 : a < b ? -1 : 0;
} | javascript | function neighbourhoodSorter (a, b) {
a = a.join(',');
b = b.join(',');
return a > b ? 1 : a < b ? -1 : 0;
} | [
"function",
"neighbourhoodSorter",
"(",
"a",
",",
"b",
")",
"{",
"a",
"=",
"a",
".",
"join",
"(",
"','",
")",
";",
"b",
"=",
"b",
".",
"join",
"(",
"','",
")",
";",
"return",
"a",
">",
"b",
"?",
"1",
":",
"a",
"<",
"b",
"?",
"-",
"1",
":",
"0",
";",
"}"
]
| Sort the neighbourhood from left to right, top to bottom, ...
@param {Array} a First neighbour
@param {Array} b Second neighbour
@returns {number} | [
"Sort",
"the",
"neighbourhood",
"from",
"left",
"to",
"right",
"top",
"to",
"bottom",
"..."
]
| 1f21a7a15fad262c92e84eee834d2308bdba48c2 | https://github.com/kchapelier/cellular-automata/blob/1f21a7a15fad262c92e84eee834d2308bdba48c2/lib/cellular-automata.js#L95-L99 |
43,438 | StyleT/js-acl | src/index.js | getRules | function getRules (resource, role, create) {
resource = typeof resource === 'undefined' ? null : resource;
role = typeof role === 'undefined' ? null : role;
create = typeof create === 'undefined' ? false : create;
var visitor;
// follow $resource
do {
if (resource === null) {
visitor = _rules.allResources;
break;
}
//var resourceId = resource.getResourceId();
var resourceId = resource;
if (_rules.byResourceId[resourceId] === undefined) {
if (!create) {
return null;
}
_rules.byResourceId[resourceId] = {};
}
visitor = _rules.byResourceId[resourceId];
} while (false);
// follow $role
if (role === null) {
if (visitor.allRoles === undefined) {
if (!create) {
return null;
}
set(visitor, 'allRoles.byPrivilegeId', {});
}
return visitor.allRoles;
}
//var roleId = role.getRoleId();
var roleId = role;
if (visitor.byRoleId === undefined || visitor.byRoleId[roleId] === undefined) {
if (!create) {
return null;
}
set(visitor, 'byRoleId.' + roleId + '.byPrivilegeId', {});
}
return visitor.byRoleId[roleId];
} | javascript | function getRules (resource, role, create) {
resource = typeof resource === 'undefined' ? null : resource;
role = typeof role === 'undefined' ? null : role;
create = typeof create === 'undefined' ? false : create;
var visitor;
// follow $resource
do {
if (resource === null) {
visitor = _rules.allResources;
break;
}
//var resourceId = resource.getResourceId();
var resourceId = resource;
if (_rules.byResourceId[resourceId] === undefined) {
if (!create) {
return null;
}
_rules.byResourceId[resourceId] = {};
}
visitor = _rules.byResourceId[resourceId];
} while (false);
// follow $role
if (role === null) {
if (visitor.allRoles === undefined) {
if (!create) {
return null;
}
set(visitor, 'allRoles.byPrivilegeId', {});
}
return visitor.allRoles;
}
//var roleId = role.getRoleId();
var roleId = role;
if (visitor.byRoleId === undefined || visitor.byRoleId[roleId] === undefined) {
if (!create) {
return null;
}
set(visitor, 'byRoleId.' + roleId + '.byPrivilegeId', {});
}
return visitor.byRoleId[roleId];
} | [
"function",
"getRules",
"(",
"resource",
",",
"role",
",",
"create",
")",
"{",
"resource",
"=",
"typeof",
"resource",
"===",
"'undefined'",
"?",
"null",
":",
"resource",
";",
"role",
"=",
"typeof",
"role",
"===",
"'undefined'",
"?",
"null",
":",
"role",
";",
"create",
"=",
"typeof",
"create",
"===",
"'undefined'",
"?",
"false",
":",
"create",
";",
"var",
"visitor",
";",
"// follow $resource",
"do",
"{",
"if",
"(",
"resource",
"===",
"null",
")",
"{",
"visitor",
"=",
"_rules",
".",
"allResources",
";",
"break",
";",
"}",
"//var resourceId = resource.getResourceId();",
"var",
"resourceId",
"=",
"resource",
";",
"if",
"(",
"_rules",
".",
"byResourceId",
"[",
"resourceId",
"]",
"===",
"undefined",
")",
"{",
"if",
"(",
"!",
"create",
")",
"{",
"return",
"null",
";",
"}",
"_rules",
".",
"byResourceId",
"[",
"resourceId",
"]",
"=",
"{",
"}",
";",
"}",
"visitor",
"=",
"_rules",
".",
"byResourceId",
"[",
"resourceId",
"]",
";",
"}",
"while",
"(",
"false",
")",
";",
"// follow $role",
"if",
"(",
"role",
"===",
"null",
")",
"{",
"if",
"(",
"visitor",
".",
"allRoles",
"===",
"undefined",
")",
"{",
"if",
"(",
"!",
"create",
")",
"{",
"return",
"null",
";",
"}",
"set",
"(",
"visitor",
",",
"'allRoles.byPrivilegeId'",
",",
"{",
"}",
")",
";",
"}",
"return",
"visitor",
".",
"allRoles",
";",
"}",
"//var roleId = role.getRoleId();",
"var",
"roleId",
"=",
"role",
";",
"if",
"(",
"visitor",
".",
"byRoleId",
"===",
"undefined",
"||",
"visitor",
".",
"byRoleId",
"[",
"roleId",
"]",
"===",
"undefined",
")",
"{",
"if",
"(",
"!",
"create",
")",
"{",
"return",
"null",
";",
"}",
"set",
"(",
"visitor",
",",
"'byRoleId.'",
"+",
"roleId",
"+",
"'.byPrivilegeId'",
",",
"{",
"}",
")",
";",
"}",
"return",
"visitor",
".",
"byRoleId",
"[",
"roleId",
"]",
";",
"}"
]
| Returns the rules associated with a Resource and a Role, or null if no such rules exist
If either $resource or $role is null, this means that the rules returned are for all Resources or all Roles,
respectively. Both can be null to return the default rule set for all Resources and all Roles.
If the $create parameter is true, then a rule set is first created and then returned to the caller.
@param {string} [resource=null]
@param {string} [role=null]
@param {boolean} [create=false]
@return {Object|null} | [
"Returns",
"the",
"rules",
"associated",
"with",
"a",
"Resource",
"and",
"a",
"Role",
"or",
"null",
"if",
"no",
"such",
"rules",
"exist"
]
| 63eeb77866e99831611c900fcb4db3f73f72148b | https://github.com/StyleT/js-acl/blob/63eeb77866e99831611c900fcb4db3f73f72148b/src/index.js#L783-L826 |
43,439 | StyleT/js-acl | src/index.js | getRuleType | function getRuleType(resource, role, privilege) {
resource = typeof resource === 'undefined' ? null : resource;
role = typeof role === 'undefined' ? null : role;
privilege = typeof privilege === 'undefined' ? null : privilege;
// get the rules for the $resource and $role
var rules = getRules(resource, role), rule;
if (rules === null) {
return null;
}
// follow $privilege
if (privilege === null) {
if (rules.allPrivileges !== undefined) {
rule = rules.allPrivileges;
} else {
return null;
}
} else if (rules.byPrivilegeId === undefined || rules.byPrivilegeId[privilege] === undefined) {
return null;
} else {
rule = rules.byPrivilegeId[privilege];
}
// check assertion first
var assertionValue = null;
if (rule.assert !== null) {
var assertion = rule.assert;
assertionValue = assertion.call(
self,
_isAllowedRole === self.USER_IDENTITY_ROLE && self.getUserIdentity() !== null ? self.getUserIdentity() : role,
_isAllowedResource !== null ? _isAllowedResource : resource,
privilege
);
}
if (rule.assert === null || assertionValue === true) {
return rule.type;
} else if (null !== resource || null !== role || null !== privilege) {
return null;
} else if (self.TYPE_ALLOW === rule.type) {
return self.TYPE_DENY;
}
return self.TYPE_ALLOW;
} | javascript | function getRuleType(resource, role, privilege) {
resource = typeof resource === 'undefined' ? null : resource;
role = typeof role === 'undefined' ? null : role;
privilege = typeof privilege === 'undefined' ? null : privilege;
// get the rules for the $resource and $role
var rules = getRules(resource, role), rule;
if (rules === null) {
return null;
}
// follow $privilege
if (privilege === null) {
if (rules.allPrivileges !== undefined) {
rule = rules.allPrivileges;
} else {
return null;
}
} else if (rules.byPrivilegeId === undefined || rules.byPrivilegeId[privilege] === undefined) {
return null;
} else {
rule = rules.byPrivilegeId[privilege];
}
// check assertion first
var assertionValue = null;
if (rule.assert !== null) {
var assertion = rule.assert;
assertionValue = assertion.call(
self,
_isAllowedRole === self.USER_IDENTITY_ROLE && self.getUserIdentity() !== null ? self.getUserIdentity() : role,
_isAllowedResource !== null ? _isAllowedResource : resource,
privilege
);
}
if (rule.assert === null || assertionValue === true) {
return rule.type;
} else if (null !== resource || null !== role || null !== privilege) {
return null;
} else if (self.TYPE_ALLOW === rule.type) {
return self.TYPE_DENY;
}
return self.TYPE_ALLOW;
} | [
"function",
"getRuleType",
"(",
"resource",
",",
"role",
",",
"privilege",
")",
"{",
"resource",
"=",
"typeof",
"resource",
"===",
"'undefined'",
"?",
"null",
":",
"resource",
";",
"role",
"=",
"typeof",
"role",
"===",
"'undefined'",
"?",
"null",
":",
"role",
";",
"privilege",
"=",
"typeof",
"privilege",
"===",
"'undefined'",
"?",
"null",
":",
"privilege",
";",
"// get the rules for the $resource and $role",
"var",
"rules",
"=",
"getRules",
"(",
"resource",
",",
"role",
")",
",",
"rule",
";",
"if",
"(",
"rules",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// follow $privilege",
"if",
"(",
"privilege",
"===",
"null",
")",
"{",
"if",
"(",
"rules",
".",
"allPrivileges",
"!==",
"undefined",
")",
"{",
"rule",
"=",
"rules",
".",
"allPrivileges",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"else",
"if",
"(",
"rules",
".",
"byPrivilegeId",
"===",
"undefined",
"||",
"rules",
".",
"byPrivilegeId",
"[",
"privilege",
"]",
"===",
"undefined",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"rule",
"=",
"rules",
".",
"byPrivilegeId",
"[",
"privilege",
"]",
";",
"}",
"// check assertion first",
"var",
"assertionValue",
"=",
"null",
";",
"if",
"(",
"rule",
".",
"assert",
"!==",
"null",
")",
"{",
"var",
"assertion",
"=",
"rule",
".",
"assert",
";",
"assertionValue",
"=",
"assertion",
".",
"call",
"(",
"self",
",",
"_isAllowedRole",
"===",
"self",
".",
"USER_IDENTITY_ROLE",
"&&",
"self",
".",
"getUserIdentity",
"(",
")",
"!==",
"null",
"?",
"self",
".",
"getUserIdentity",
"(",
")",
":",
"role",
",",
"_isAllowedResource",
"!==",
"null",
"?",
"_isAllowedResource",
":",
"resource",
",",
"privilege",
")",
";",
"}",
"if",
"(",
"rule",
".",
"assert",
"===",
"null",
"||",
"assertionValue",
"===",
"true",
")",
"{",
"return",
"rule",
".",
"type",
";",
"}",
"else",
"if",
"(",
"null",
"!==",
"resource",
"||",
"null",
"!==",
"role",
"||",
"null",
"!==",
"privilege",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"self",
".",
"TYPE_ALLOW",
"===",
"rule",
".",
"type",
")",
"{",
"return",
"self",
".",
"TYPE_DENY",
";",
"}",
"return",
"self",
".",
"TYPE_ALLOW",
";",
"}"
]
| Returns the rule type associated with the specified Resource, Role, and privilege
combination.
If a rule does not exist or its attached assertion fails, which means that
the rule is not applicable, then this method returns null. Otherwise, the
rule type applies and is returned as either TYPE_ALLOW or TYPE_DENY.
If $resource or $role is null, then this means that the rule must apply to
all Resources or Roles, respectively.
If $privilege is null, then the rule must apply to all privileges.
If all three parameters are null, then the default ACL rule type is returned,
based on whether its assertion method passes.
@param {null|string} [resource=null]
@param {null|string} [role=null]
@param {null|string} [privilege=null]
@return {(string|null)} | [
"Returns",
"the",
"rule",
"type",
"associated",
"with",
"the",
"specified",
"Resource",
"Role",
"and",
"privilege",
"combination",
"."
]
| 63eeb77866e99831611c900fcb4db3f73f72148b | https://github.com/StyleT/js-acl/blob/63eeb77866e99831611c900fcb4db3f73f72148b/src/index.js#L1007-L1053 |
43,440 | StyleT/js-acl | src/index.js | getChildResources | function getChildResources(resource){
var result = [], children = _resources[resource].children;
children.forEach(function (child) {
var childReturn = getChildResources(child);
childReturn.push(child);
result = result.concat(childReturn);
});
return result;
} | javascript | function getChildResources(resource){
var result = [], children = _resources[resource].children;
children.forEach(function (child) {
var childReturn = getChildResources(child);
childReturn.push(child);
result = result.concat(childReturn);
});
return result;
} | [
"function",
"getChildResources",
"(",
"resource",
")",
"{",
"var",
"result",
"=",
"[",
"]",
",",
"children",
"=",
"_resources",
"[",
"resource",
"]",
".",
"children",
";",
"children",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"var",
"childReturn",
"=",
"getChildResources",
"(",
"child",
")",
";",
"childReturn",
".",
"push",
"(",
"child",
")",
";",
"result",
"=",
"result",
".",
"concat",
"(",
"childReturn",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
]
| Returns all child resources from the given resource.
@param {string} resource
@return [] | [
"Returns",
"all",
"child",
"resources",
"from",
"the",
"given",
"resource",
"."
]
| 63eeb77866e99831611c900fcb4db3f73f72148b | https://github.com/StyleT/js-acl/blob/63eeb77866e99831611c900fcb4db3f73f72148b/src/index.js#L1061-L1070 |
43,441 | Havelaer/node-orientdb-http | lib/Base.js | function(evname, callback, context) {
this._events = this._events || {};
var a = this._events[evname] = this._events[evname] || [];
a.push({
cb: callback,
ctxt: context || this
});
return this;
} | javascript | function(evname, callback, context) {
this._events = this._events || {};
var a = this._events[evname] = this._events[evname] || [];
a.push({
cb: callback,
ctxt: context || this
});
return this;
} | [
"function",
"(",
"evname",
",",
"callback",
",",
"context",
")",
"{",
"this",
".",
"_events",
"=",
"this",
".",
"_events",
"||",
"{",
"}",
";",
"var",
"a",
"=",
"this",
".",
"_events",
"[",
"evname",
"]",
"=",
"this",
".",
"_events",
"[",
"evname",
"]",
"||",
"[",
"]",
";",
"a",
".",
"push",
"(",
"{",
"cb",
":",
"callback",
",",
"ctxt",
":",
"context",
"||",
"this",
"}",
")",
";",
"return",
"this",
";",
"}"
]
| Bind event listener
@param {string} name of event
@param {function} callback if event is triggered
@param {object} context in which callback is called
@return {this} | [
"Bind",
"event",
"listener"
]
| b76a50b070643d34485941eef9a610e100737b7b | https://github.com/Havelaer/node-orientdb-http/blob/b76a50b070643d34485941eef9a610e100737b7b/lib/Base.js#L187-L195 |
|
43,442 | Havelaer/node-orientdb-http | lib/Base.js | function(evname, callback, context) {
var self = this, args = arguments;
this.on(evname, function() {
callback.apply(context, arguments);
self.off.apply(self, args);
});
return this;
} | javascript | function(evname, callback, context) {
var self = this, args = arguments;
this.on(evname, function() {
callback.apply(context, arguments);
self.off.apply(self, args);
});
return this;
} | [
"function",
"(",
"evname",
",",
"callback",
",",
"context",
")",
"{",
"var",
"self",
"=",
"this",
",",
"args",
"=",
"arguments",
";",
"this",
".",
"on",
"(",
"evname",
",",
"function",
"(",
")",
"{",
"callback",
".",
"apply",
"(",
"context",
",",
"arguments",
")",
";",
"self",
".",
"off",
".",
"apply",
"(",
"self",
",",
"args",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
]
| Bind event listener and only fire once
@param {string} name of event
@param {function} callback if event is triggered
@param {object} context in which callback is called
@return {this} | [
"Bind",
"event",
"listener",
"and",
"only",
"fire",
"once"
]
| b76a50b070643d34485941eef9a610e100737b7b | https://github.com/Havelaer/node-orientdb-http/blob/b76a50b070643d34485941eef9a610e100737b7b/lib/Base.js#L205-L212 |
|
43,443 | Havelaer/node-orientdb-http | lib/Base.js | function(evname) {
var fns = this._events && this._events[evname] || [],
args = __slice.call(arguments, 1);
for (var i = 0, ii = fns.length; i < ii; i++) {
fns[i].cb.apply(fns[i].ctxt, args);
}
} | javascript | function(evname) {
var fns = this._events && this._events[evname] || [],
args = __slice.call(arguments, 1);
for (var i = 0, ii = fns.length; i < ii; i++) {
fns[i].cb.apply(fns[i].ctxt, args);
}
} | [
"function",
"(",
"evname",
")",
"{",
"var",
"fns",
"=",
"this",
".",
"_events",
"&&",
"this",
".",
"_events",
"[",
"evname",
"]",
"||",
"[",
"]",
",",
"args",
"=",
"__slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"ii",
"=",
"fns",
".",
"length",
";",
"i",
"<",
"ii",
";",
"i",
"++",
")",
"{",
"fns",
"[",
"i",
"]",
".",
"cb",
".",
"apply",
"(",
"fns",
"[",
"i",
"]",
".",
"ctxt",
",",
"args",
")",
";",
"}",
"}"
]
| Trigger event on object
@param {string} name of event
@param {array} array of arguments
@return {this} | [
"Trigger",
"event",
"on",
"object"
]
| b76a50b070643d34485941eef9a610e100737b7b | https://github.com/Havelaer/node-orientdb-http/blob/b76a50b070643d34485941eef9a610e100737b7b/lib/Base.js#L248-L254 |
|
43,444 | Havelaer/node-orientdb-http | lib/Base.js | function(other, evname, callback) {
other.on(evname, callback, this);
var a = this._listeningTo = this._listeningTo || {},
b = a[other._cid] = other;
} | javascript | function(other, evname, callback) {
other.on(evname, callback, this);
var a = this._listeningTo = this._listeningTo || {},
b = a[other._cid] = other;
} | [
"function",
"(",
"other",
",",
"evname",
",",
"callback",
")",
"{",
"other",
".",
"on",
"(",
"evname",
",",
"callback",
",",
"this",
")",
";",
"var",
"a",
"=",
"this",
".",
"_listeningTo",
"=",
"this",
".",
"_listeningTo",
"||",
"{",
"}",
",",
"b",
"=",
"a",
"[",
"other",
".",
"_cid",
"]",
"=",
"other",
";",
"}"
]
| Bind event listener on an other object
@param {object} object to listen to
@param {string} name of event
@param {function} callback
@return {this} | [
"Bind",
"event",
"listener",
"on",
"an",
"other",
"object"
]
| b76a50b070643d34485941eef9a610e100737b7b | https://github.com/Havelaer/node-orientdb-http/blob/b76a50b070643d34485941eef9a610e100737b7b/lib/Base.js#L264-L268 |
|
43,445 | Havelaer/node-orientdb-http | lib/Base.js | function(other, evname, callback) {
if (!this._listeningTo) return;
if (!other) {
for (var cid in this._listeningTo) {
this.stopListening(this._listeningTo[cid], evname, callback);
}
} else {
other.off(evname, callback, this);
// TODO: remove local listener tracker
}
} | javascript | function(other, evname, callback) {
if (!this._listeningTo) return;
if (!other) {
for (var cid in this._listeningTo) {
this.stopListening(this._listeningTo[cid], evname, callback);
}
} else {
other.off(evname, callback, this);
// TODO: remove local listener tracker
}
} | [
"function",
"(",
"other",
",",
"evname",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_listeningTo",
")",
"return",
";",
"if",
"(",
"!",
"other",
")",
"{",
"for",
"(",
"var",
"cid",
"in",
"this",
".",
"_listeningTo",
")",
"{",
"this",
".",
"stopListening",
"(",
"this",
".",
"_listeningTo",
"[",
"cid",
"]",
",",
"evname",
",",
"callback",
")",
";",
"}",
"}",
"else",
"{",
"other",
".",
"off",
"(",
"evname",
",",
"callback",
",",
"this",
")",
";",
"// TODO: remove local listener tracker",
"}",
"}"
]
| Remove event listener from an other object
@param {object} object to listening to
@param {string} name of event
@param {function} callback
@return {this} | [
"Remove",
"event",
"listener",
"from",
"an",
"other",
"object"
]
| b76a50b070643d34485941eef9a610e100737b7b | https://github.com/Havelaer/node-orientdb-http/blob/b76a50b070643d34485941eef9a610e100737b7b/lib/Base.js#L278-L288 |
|
43,446 | zedgu/surface | lib/surface.js | Surface | function Surface(app, options) {
if (!(this instanceof Surface)) {
return new Surface(app, options);
}
this.conf = setting(options);
this.middleware(app);
context(app, this);
} | javascript | function Surface(app, options) {
if (!(this instanceof Surface)) {
return new Surface(app, options);
}
this.conf = setting(options);
this.middleware(app);
context(app, this);
} | [
"function",
"Surface",
"(",
"app",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Surface",
")",
")",
"{",
"return",
"new",
"Surface",
"(",
"app",
",",
"options",
")",
";",
"}",
"this",
".",
"conf",
"=",
"setting",
"(",
"options",
")",
";",
"this",
".",
"middleware",
"(",
"app",
")",
";",
"context",
"(",
"app",
",",
"this",
")",
";",
"}"
]
| Surface Constructor.
@param {Object} app koa().
@param {Object} options Config object.
@api public | [
"Surface",
"Constructor",
"."
]
| 3f32b0ef98c781c923b26cef543fdea457da1030 | https://github.com/zedgu/surface/blob/3f32b0ef98c781c923b26cef543fdea457da1030/lib/surface.js#L77-L86 |
43,447 | tjvantoll/nativescript-maps | demo/app/tns_modules/js-libs/reworkcss/reworkcss.js | athost | function athost() {
var pos = position();
var m = match(/^@host */);
if (!m) return;
if (!open()) return error("@host missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@host missing '}'");
return pos({
type: 'host',
rules: style
});
} | javascript | function athost() {
var pos = position();
var m = match(/^@host */);
if (!m) return;
if (!open()) return error("@host missing '{'");
var style = comments().concat(rules());
if (!close()) return error("@host missing '}'");
return pos({
type: 'host',
rules: style
});
} | [
"function",
"athost",
"(",
")",
"{",
"var",
"pos",
"=",
"position",
"(",
")",
";",
"var",
"m",
"=",
"match",
"(",
"/",
"^@host *",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"if",
"(",
"!",
"open",
"(",
")",
")",
"return",
"error",
"(",
"\"@host missing '{'\"",
")",
";",
"var",
"style",
"=",
"comments",
"(",
")",
".",
"concat",
"(",
"rules",
"(",
")",
")",
";",
"if",
"(",
"!",
"close",
"(",
")",
")",
"return",
"error",
"(",
"\"@host missing '}'\"",
")",
";",
"return",
"pos",
"(",
"{",
"type",
":",
"'host'",
",",
"rules",
":",
"style",
"}",
")",
";",
"}"
]
| Parse host. | [
"Parse",
"host",
"."
]
| 7ba076e576968fbce1364e294fbc5470808ba8d9 | https://github.com/tjvantoll/nativescript-maps/blob/7ba076e576968fbce1364e294fbc5470808ba8d9/demo/app/tns_modules/js-libs/reworkcss/reworkcss.js#L351-L367 |
43,448 | tjvantoll/nativescript-maps | demo/app/tns_modules/js-libs/reworkcss/reworkcss.js | atcustommedia | function atcustommedia() {
var pos = position();
var m = match(/^@custom-media (--[^\s]+) *([^{;]+);/);
if (!m) return;
return pos({
type: 'custom-media',
name: trim(m[1]),
media: trim(m[2])
});
} | javascript | function atcustommedia() {
var pos = position();
var m = match(/^@custom-media (--[^\s]+) *([^{;]+);/);
if (!m) return;
return pos({
type: 'custom-media',
name: trim(m[1]),
media: trim(m[2])
});
} | [
"function",
"atcustommedia",
"(",
")",
"{",
"var",
"pos",
"=",
"position",
"(",
")",
";",
"var",
"m",
"=",
"match",
"(",
"/",
"^@custom-media (--[^\\s]+) *([^{;]+);",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"return",
"pos",
"(",
"{",
"type",
":",
"'custom-media'",
",",
"name",
":",
"trim",
"(",
"m",
"[",
"1",
"]",
")",
",",
"media",
":",
"trim",
"(",
"m",
"[",
"2",
"]",
")",
"}",
")",
";",
"}"
]
| Parse custom-media. | [
"Parse",
"custom",
"-",
"media",
"."
]
| 7ba076e576968fbce1364e294fbc5470808ba8d9 | https://github.com/tjvantoll/nativescript-maps/blob/7ba076e576968fbce1364e294fbc5470808ba8d9/demo/app/tns_modules/js-libs/reworkcss/reworkcss.js#L398-L408 |
43,449 | tjvantoll/nativescript-maps | demo/app/tns_modules/js-libs/reworkcss/reworkcss.js | atfontface | function atfontface() {
var pos = position();
var m = match(/^@font-face */);
if (!m) return;
if (!open()) return error("@font-face missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("@font-face missing '}'");
return pos({
type: 'font-face',
declarations: decls
});
} | javascript | function atfontface() {
var pos = position();
var m = match(/^@font-face */);
if (!m) return;
if (!open()) return error("@font-face missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("@font-face missing '}'");
return pos({
type: 'font-face',
declarations: decls
});
} | [
"function",
"atfontface",
"(",
")",
"{",
"var",
"pos",
"=",
"position",
"(",
")",
";",
"var",
"m",
"=",
"match",
"(",
"/",
"^@font-face *",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"return",
";",
"if",
"(",
"!",
"open",
"(",
")",
")",
"return",
"error",
"(",
"\"@font-face missing '{'\"",
")",
";",
"var",
"decls",
"=",
"comments",
"(",
")",
";",
"// declarations",
"var",
"decl",
";",
"while",
"(",
"decl",
"=",
"declaration",
"(",
")",
")",
"{",
"decls",
".",
"push",
"(",
"decl",
")",
";",
"decls",
"=",
"decls",
".",
"concat",
"(",
"comments",
"(",
")",
")",
";",
"}",
"if",
"(",
"!",
"close",
"(",
")",
")",
"return",
"error",
"(",
"\"@font-face missing '}'\"",
")",
";",
"return",
"pos",
"(",
"{",
"type",
":",
"'font-face'",
",",
"declarations",
":",
"decls",
"}",
")",
";",
"}"
]
| Parse font-face. | [
"Parse",
"font",
"-",
"face",
"."
]
| 7ba076e576968fbce1364e294fbc5470808ba8d9 | https://github.com/tjvantoll/nativescript-maps/blob/7ba076e576968fbce1364e294fbc5470808ba8d9/demo/app/tns_modules/js-libs/reworkcss/reworkcss.js#L470-L491 |
43,450 | mysticatea/appcache-manifest | lib/generate.js | generateContent | function generateContent(globOrGlobArray, options) {
// Detect base.
const globs = toArray(globOrGlobArray)
assert(globs.length > 0, "globs should exist")
const base = commonPart(globs)
assert(base != null, "the common parent directory of globs is not found.")
// Create streams.
const globStream = createGlobStream(globs, { base })
const appcacheStream = globStream.pipe(new AppcacheTransform(options))
globStream.on("error", (err) => appcacheStream.emit("error", err))
return appcacheStream
} | javascript | function generateContent(globOrGlobArray, options) {
// Detect base.
const globs = toArray(globOrGlobArray)
assert(globs.length > 0, "globs should exist")
const base = commonPart(globs)
assert(base != null, "the common parent directory of globs is not found.")
// Create streams.
const globStream = createGlobStream(globs, { base })
const appcacheStream = globStream.pipe(new AppcacheTransform(options))
globStream.on("error", (err) => appcacheStream.emit("error", err))
return appcacheStream
} | [
"function",
"generateContent",
"(",
"globOrGlobArray",
",",
"options",
")",
"{",
"// Detect base.",
"const",
"globs",
"=",
"toArray",
"(",
"globOrGlobArray",
")",
"assert",
"(",
"globs",
".",
"length",
">",
"0",
",",
"\"globs should exist\"",
")",
"const",
"base",
"=",
"commonPart",
"(",
"globs",
")",
"assert",
"(",
"base",
"!=",
"null",
",",
"\"the common parent directory of globs is not found.\"",
")",
"// Create streams.",
"const",
"globStream",
"=",
"createGlobStream",
"(",
"globs",
",",
"{",
"base",
"}",
")",
"const",
"appcacheStream",
"=",
"globStream",
".",
"pipe",
"(",
"new",
"AppcacheTransform",
"(",
"options",
")",
")",
"globStream",
".",
"on",
"(",
"\"error\"",
",",
"(",
"err",
")",
"=>",
"appcacheStream",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
")",
"return",
"appcacheStream",
"}"
]
| Create the stream to generate the cache section of appcache manifest.
@param {string|string[]} globOrGlobArray - The glob patterns to spcify the files of the cache section.
@param {object} options - The option object.
@returns {AppcacheTransform} The created stream.
@private | [
"Create",
"the",
"stream",
"to",
"generate",
"the",
"cache",
"section",
"of",
"appcache",
"manifest",
"."
]
| c44f4d54096287212149a7cf5031bd3e4f5a1fbe | https://github.com/mysticatea/appcache-manifest/blob/c44f4d54096287212149a7cf5031bd3e4f5a1fbe/lib/generate.js#L158-L173 |
43,451 | mysticatea/appcache-manifest | bin/appcache-manifest.js | generate | function generate(globs, options, callback) {
if (generationQueue.size > 0) {
// There is a process not started.
return
}
if (typeof options.delay === "number") {
generationQueue.push(next => setTimeout(next, options.delay))
}
generationQueue.push(next => {
//eslint-disable-next-line require-jsdoc
function done(err) {
if (err != null) {
process.exitCode = 1
console.error(` ERROR: ${err.message}`)
}
if (options.verbose && err == null) {
console.log(" Done.")
}
next()
if (callback != null) {
callback(err)
}
}
const appcacheStream = createAppcacheStream(globs, options)
if (options.verbose) {
console.log(`Generate: ${options.output}`)
appcacheStream
.on("addpath", (e) => console.log(` Add: ${e.path}`))
.on("addhash", (e) => console.log(` Add fingerprint: ${e.digest}`))
}
// Pipe to output.
if (options.output) {
const dir = path.dirname(path.resolve(options.output))
mkdir(dir, (err) => {
if (err != null) {
done(err)
}
else {
appcacheStream
.pipe(fs.createWriteStream(options.output))
.on("finish", done)
.on("error", done)
}
})
}
else {
appcacheStream
.on("end", done)
.pipe(process.stdout)
}
})
} | javascript | function generate(globs, options, callback) {
if (generationQueue.size > 0) {
// There is a process not started.
return
}
if (typeof options.delay === "number") {
generationQueue.push(next => setTimeout(next, options.delay))
}
generationQueue.push(next => {
//eslint-disable-next-line require-jsdoc
function done(err) {
if (err != null) {
process.exitCode = 1
console.error(` ERROR: ${err.message}`)
}
if (options.verbose && err == null) {
console.log(" Done.")
}
next()
if (callback != null) {
callback(err)
}
}
const appcacheStream = createAppcacheStream(globs, options)
if (options.verbose) {
console.log(`Generate: ${options.output}`)
appcacheStream
.on("addpath", (e) => console.log(` Add: ${e.path}`))
.on("addhash", (e) => console.log(` Add fingerprint: ${e.digest}`))
}
// Pipe to output.
if (options.output) {
const dir = path.dirname(path.resolve(options.output))
mkdir(dir, (err) => {
if (err != null) {
done(err)
}
else {
appcacheStream
.pipe(fs.createWriteStream(options.output))
.on("finish", done)
.on("error", done)
}
})
}
else {
appcacheStream
.on("end", done)
.pipe(process.stdout)
}
})
} | [
"function",
"generate",
"(",
"globs",
",",
"options",
",",
"callback",
")",
"{",
"if",
"(",
"generationQueue",
".",
"size",
">",
"0",
")",
"{",
"// There is a process not started.",
"return",
"}",
"if",
"(",
"typeof",
"options",
".",
"delay",
"===",
"\"number\"",
")",
"{",
"generationQueue",
".",
"push",
"(",
"next",
"=>",
"setTimeout",
"(",
"next",
",",
"options",
".",
"delay",
")",
")",
"}",
"generationQueue",
".",
"push",
"(",
"next",
"=>",
"{",
"//eslint-disable-next-line require-jsdoc",
"function",
"done",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"!=",
"null",
")",
"{",
"process",
".",
"exitCode",
"=",
"1",
"console",
".",
"error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
"}",
"if",
"(",
"options",
".",
"verbose",
"&&",
"err",
"==",
"null",
")",
"{",
"console",
".",
"log",
"(",
"\" Done.\"",
")",
"}",
"next",
"(",
")",
"if",
"(",
"callback",
"!=",
"null",
")",
"{",
"callback",
"(",
"err",
")",
"}",
"}",
"const",
"appcacheStream",
"=",
"createAppcacheStream",
"(",
"globs",
",",
"options",
")",
"if",
"(",
"options",
".",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"options",
".",
"output",
"}",
"`",
")",
"appcacheStream",
".",
"on",
"(",
"\"addpath\"",
",",
"(",
"e",
")",
"=>",
"console",
".",
"log",
"(",
"`",
"${",
"e",
".",
"path",
"}",
"`",
")",
")",
".",
"on",
"(",
"\"addhash\"",
",",
"(",
"e",
")",
"=>",
"console",
".",
"log",
"(",
"`",
"${",
"e",
".",
"digest",
"}",
"`",
")",
")",
"}",
"// Pipe to output.",
"if",
"(",
"options",
".",
"output",
")",
"{",
"const",
"dir",
"=",
"path",
".",
"dirname",
"(",
"path",
".",
"resolve",
"(",
"options",
".",
"output",
")",
")",
"mkdir",
"(",
"dir",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
"!=",
"null",
")",
"{",
"done",
"(",
"err",
")",
"}",
"else",
"{",
"appcacheStream",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"options",
".",
"output",
")",
")",
".",
"on",
"(",
"\"finish\"",
",",
"done",
")",
".",
"on",
"(",
"\"error\"",
",",
"done",
")",
"}",
"}",
")",
"}",
"else",
"{",
"appcacheStream",
".",
"on",
"(",
"\"end\"",
",",
"done",
")",
".",
"pipe",
"(",
"process",
".",
"stdout",
")",
"}",
"}",
")",
"}"
]
| Generate appcache manifest.
@param {string[]} globs - The globs which specifies the target files.
@param {object} options - The option object.
@param {function} callback - The callback function.
@returns {void}
@private | [
"Generate",
"appcache",
"manifest",
"."
]
| c44f4d54096287212149a7cf5031bd3e4f5a1fbe | https://github.com/mysticatea/appcache-manifest/blob/c44f4d54096287212149a7cf5031bd3e4f5a1fbe/bin/appcache-manifest.js#L143-L198 |
43,452 | mysticatea/appcache-manifest | bin/appcache-manifest.js | watch | function watch(globs, options) {
options.delay = 1000
chokidar
.watch(globs, { persistent: true, ignoreInitial: true })
.on("add", () => generate(globs, options))
.on("unlink", () => generate(globs, options))
.on("change", () => generate(globs, options))
.on("error", (err) => console.error(`ERROR: ${err.message}`))
.on("ready", () => {
if (options.verbose) {
console.log(`Be watching ${globs.join(", ")}`)
}
})
// In order to kill by the test harness.
process.on("message", () => {
process.exit(0)
})
} | javascript | function watch(globs, options) {
options.delay = 1000
chokidar
.watch(globs, { persistent: true, ignoreInitial: true })
.on("add", () => generate(globs, options))
.on("unlink", () => generate(globs, options))
.on("change", () => generate(globs, options))
.on("error", (err) => console.error(`ERROR: ${err.message}`))
.on("ready", () => {
if (options.verbose) {
console.log(`Be watching ${globs.join(", ")}`)
}
})
// In order to kill by the test harness.
process.on("message", () => {
process.exit(0)
})
} | [
"function",
"watch",
"(",
"globs",
",",
"options",
")",
"{",
"options",
".",
"delay",
"=",
"1000",
"chokidar",
".",
"watch",
"(",
"globs",
",",
"{",
"persistent",
":",
"true",
",",
"ignoreInitial",
":",
"true",
"}",
")",
".",
"on",
"(",
"\"add\"",
",",
"(",
")",
"=>",
"generate",
"(",
"globs",
",",
"options",
")",
")",
".",
"on",
"(",
"\"unlink\"",
",",
"(",
")",
"=>",
"generate",
"(",
"globs",
",",
"options",
")",
")",
".",
"on",
"(",
"\"change\"",
",",
"(",
")",
"=>",
"generate",
"(",
"globs",
",",
"options",
")",
")",
".",
"on",
"(",
"\"error\"",
",",
"(",
"err",
")",
"=>",
"console",
".",
"error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
")",
".",
"on",
"(",
"\"ready\"",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"options",
".",
"verbose",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"globs",
".",
"join",
"(",
"\", \"",
")",
"}",
"`",
")",
"}",
"}",
")",
"// In order to kill by the test harness.",
"process",
".",
"on",
"(",
"\"message\"",
",",
"(",
")",
"=>",
"{",
"process",
".",
"exit",
"(",
"0",
")",
"}",
")",
"}"
]
| Generate appcache manifest for each change.
@param {string[]} globs - The globs which specifies the target files.
@param {object} options - The option object.
@returns {void}
@private | [
"Generate",
"appcache",
"manifest",
"for",
"each",
"change",
"."
]
| c44f4d54096287212149a7cf5031bd3e4f5a1fbe | https://github.com/mysticatea/appcache-manifest/blob/c44f4d54096287212149a7cf5031bd3e4f5a1fbe/bin/appcache-manifest.js#L208-L227 |
43,453 | ekryski/node-hl7 | lib/server.js | Server | function Server(host, port, options) {
var self = this;
// Needed to convert this constructor into EventEmitter
EventEmitter.call(this);
options = options || {};
this.host = host || '127.0.0.1';
this.port = port || 59895;
this.debug = options.debug || false;
this.json = options.json || true;
var parser = new xml2js.Parser();
var responseMessageNumber = 0;
// TODO: Build up proper ACKS
var applicationAcceptACK = 'MSH|^~\\&|||||20121217154325.194-0700||ACK^RO1|101|T|2.6\nMSA|AA|17';
var applicationErrorACK = 'MSH|^~\\&|NES|NINTENDO|TESTSYSTEM|TESTFACILITY|20121217158325.194-0700||ACK^RO1|101|T|2.6\nMSA|AE|17';
// Bind to TCP socket for HL7
var hl7TcpSocket = net.createServer({ allowHalfOpen: false}, function(socket){
socket.setEncoding("utf8");
function handleError(error){
socket.write(applicationErrorACK);
self.emit('error', error);
console.log("HL7 TCP Server ERROR: ", error);
}
function createEL7AckForMessageNumber(messageNumber) {
var ack = 'MSH|^~\\&|||||' + generateTimeStamp() + '||ACK^RO1|'+ getUniqueMessageNumber() +'|T|2.6\rMSA|AA|' + messageNumber;
return ack;
}
function zeroFill( number, width ) {
width -= number.toString().length;
if ( width > 0 ) {
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}
function generateTimeStamp() {
var now = new Date();
var month = zeroFill(now.getUTCMonth() + 1, 2);
var date = zeroFill(now.getUTCDate(), 2);
var hours = zeroFill(now.getUTCHours(), 2);
var minutes = zeroFill(now.getUTCMinutes(), 2);
var seconds = zeroFill(now.getUTCSeconds(), 2);
var timestamp = now.getUTCFullYear().toString()
+ month
+ date
+ hours
+ minutes
+ seconds
+ '.'
+ now.getUTCMilliseconds().toString()
+ '+0000'
return timestamp;
}
function getUniqueMessageNumber() {
responseMessageNumber = responseMessageNumber + 1;
return responseMessageNumber;
}
function createXMLAckForMessageNumber(messageNumber) {
var ack = String.fromCharCode(0x0b) + '<?xml version="1.0" encoding="UTF-8"?>' +
'\n<ACK xmlns="urn:hl7-org:v2xml">'+
'\n<MSH>' +
'\n<MSH.1>|</MSH.1>' +
'\n<MSH.2>^~\&</MSH.2>' +
'\n<MSH.7>' + generateTimeStamp() + '</MSH.7>' +
'\n<MSH.9>' +
'\n<MSG.1>ACK</MSG.1>' +
'\n<MSG.2>R01</MSG.2>' +
'\n</MSH.9>' +
'\n<MSH.10>' + getUniqueMessageNumber() + '</MSH.10>' +
'\n<MSH.11>' +
'\n<PT.1>T</PT.1>' +
'\n</MSH.11>' +
'\n<MSH.12>' +
'\n<VID.1>2.6</VID.1>' +
'\n</MSH.12>' +
'\n</MSH>' +
'\n<MSA>' +
'\n<MSA.1>AA</MSA.1>' +
'\n<MSA.2>' + messageNumber +'</MSA.2>' +
'\n</MSA>' +
'\n</ACK>\n' + String.fromCharCode(0x1c) + '\r';
console.log("Generated ACK: " + ack);
return ack;
}
function handleXML(xml, sendEL7Ack){
parser.parseString(xml, function(error, result){
if (error) return handleError(error);
if (self.debug) {
console.log("Message: ", util.inspect(result, false, 7, true));
console.log('Sending ACK');
}
self.emit('hl7', result);
console.log(result);
var messageNumber = 0;
for (var key in result) {
if (result.hasOwnProperty(key)) {
if (result[key].MSH) {
var msg = result[key].MSH[0]["MSH.10"][0];
messageNumber = msg;
}
}
}
console.log("Sending ACK for messageNumber "+messageNumber);
if (sendEL7Ack) {
var ack = createEL7AckForMessageNumber(messageNumber);
socket.write(ack);
}
else {
var ack = createXMLAckForMessageNumber(messageNumber);
socket.write(new Buffer(ack, encoding = "utf8"));
}
socket.end();
});
}
socket.on('connect', function() {
if (self.debug) {
var now = new Date();
console.log(now + " - HL7 TCP Client Connected");
}
});
socket.on('data', function(packet) {
if (self.debug) {
console.log(packet);
}
if (!packet) return handleError(new Error('Packet is empty'));
// It is XML format
if (packet.indexOf('<?xml') !== -1) {
handleXML(packet.trim(), false);
}
// It is EL7 format
else {
hl7.toXml(packet, function(error, xml){
if (error) return handleError(error);
handleXML(xml, true);
});
}
});
socket.on('error', function(error){
handleError(error);
});
socket.on('close', function(){
if (self.debug) {
var now = new Date();
console.log(now + " - HL7 TCP Server Disconnected");
}
});
socket.on('end', function() {
if (self.debug) {
var now = new Date();
console.log(now + " - HL7 TCP Client Disconnected");
}
});
});
hl7TcpSocket.listen( this.port, function(){
var address = hl7TcpSocket.address();
console.log("HL7 TCP Server listening on: " + address.address + ":" + address.port);
});
} | javascript | function Server(host, port, options) {
var self = this;
// Needed to convert this constructor into EventEmitter
EventEmitter.call(this);
options = options || {};
this.host = host || '127.0.0.1';
this.port = port || 59895;
this.debug = options.debug || false;
this.json = options.json || true;
var parser = new xml2js.Parser();
var responseMessageNumber = 0;
// TODO: Build up proper ACKS
var applicationAcceptACK = 'MSH|^~\\&|||||20121217154325.194-0700||ACK^RO1|101|T|2.6\nMSA|AA|17';
var applicationErrorACK = 'MSH|^~\\&|NES|NINTENDO|TESTSYSTEM|TESTFACILITY|20121217158325.194-0700||ACK^RO1|101|T|2.6\nMSA|AE|17';
// Bind to TCP socket for HL7
var hl7TcpSocket = net.createServer({ allowHalfOpen: false}, function(socket){
socket.setEncoding("utf8");
function handleError(error){
socket.write(applicationErrorACK);
self.emit('error', error);
console.log("HL7 TCP Server ERROR: ", error);
}
function createEL7AckForMessageNumber(messageNumber) {
var ack = 'MSH|^~\\&|||||' + generateTimeStamp() + '||ACK^RO1|'+ getUniqueMessageNumber() +'|T|2.6\rMSA|AA|' + messageNumber;
return ack;
}
function zeroFill( number, width ) {
width -= number.toString().length;
if ( width > 0 ) {
return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
}
return number + ""; // always return a string
}
function generateTimeStamp() {
var now = new Date();
var month = zeroFill(now.getUTCMonth() + 1, 2);
var date = zeroFill(now.getUTCDate(), 2);
var hours = zeroFill(now.getUTCHours(), 2);
var minutes = zeroFill(now.getUTCMinutes(), 2);
var seconds = zeroFill(now.getUTCSeconds(), 2);
var timestamp = now.getUTCFullYear().toString()
+ month
+ date
+ hours
+ minutes
+ seconds
+ '.'
+ now.getUTCMilliseconds().toString()
+ '+0000'
return timestamp;
}
function getUniqueMessageNumber() {
responseMessageNumber = responseMessageNumber + 1;
return responseMessageNumber;
}
function createXMLAckForMessageNumber(messageNumber) {
var ack = String.fromCharCode(0x0b) + '<?xml version="1.0" encoding="UTF-8"?>' +
'\n<ACK xmlns="urn:hl7-org:v2xml">'+
'\n<MSH>' +
'\n<MSH.1>|</MSH.1>' +
'\n<MSH.2>^~\&</MSH.2>' +
'\n<MSH.7>' + generateTimeStamp() + '</MSH.7>' +
'\n<MSH.9>' +
'\n<MSG.1>ACK</MSG.1>' +
'\n<MSG.2>R01</MSG.2>' +
'\n</MSH.9>' +
'\n<MSH.10>' + getUniqueMessageNumber() + '</MSH.10>' +
'\n<MSH.11>' +
'\n<PT.1>T</PT.1>' +
'\n</MSH.11>' +
'\n<MSH.12>' +
'\n<VID.1>2.6</VID.1>' +
'\n</MSH.12>' +
'\n</MSH>' +
'\n<MSA>' +
'\n<MSA.1>AA</MSA.1>' +
'\n<MSA.2>' + messageNumber +'</MSA.2>' +
'\n</MSA>' +
'\n</ACK>\n' + String.fromCharCode(0x1c) + '\r';
console.log("Generated ACK: " + ack);
return ack;
}
function handleXML(xml, sendEL7Ack){
parser.parseString(xml, function(error, result){
if (error) return handleError(error);
if (self.debug) {
console.log("Message: ", util.inspect(result, false, 7, true));
console.log('Sending ACK');
}
self.emit('hl7', result);
console.log(result);
var messageNumber = 0;
for (var key in result) {
if (result.hasOwnProperty(key)) {
if (result[key].MSH) {
var msg = result[key].MSH[0]["MSH.10"][0];
messageNumber = msg;
}
}
}
console.log("Sending ACK for messageNumber "+messageNumber);
if (sendEL7Ack) {
var ack = createEL7AckForMessageNumber(messageNumber);
socket.write(ack);
}
else {
var ack = createXMLAckForMessageNumber(messageNumber);
socket.write(new Buffer(ack, encoding = "utf8"));
}
socket.end();
});
}
socket.on('connect', function() {
if (self.debug) {
var now = new Date();
console.log(now + " - HL7 TCP Client Connected");
}
});
socket.on('data', function(packet) {
if (self.debug) {
console.log(packet);
}
if (!packet) return handleError(new Error('Packet is empty'));
// It is XML format
if (packet.indexOf('<?xml') !== -1) {
handleXML(packet.trim(), false);
}
// It is EL7 format
else {
hl7.toXml(packet, function(error, xml){
if (error) return handleError(error);
handleXML(xml, true);
});
}
});
socket.on('error', function(error){
handleError(error);
});
socket.on('close', function(){
if (self.debug) {
var now = new Date();
console.log(now + " - HL7 TCP Server Disconnected");
}
});
socket.on('end', function() {
if (self.debug) {
var now = new Date();
console.log(now + " - HL7 TCP Client Disconnected");
}
});
});
hl7TcpSocket.listen( this.port, function(){
var address = hl7TcpSocket.address();
console.log("HL7 TCP Server listening on: " + address.address + ":" + address.port);
});
} | [
"function",
"Server",
"(",
"host",
",",
"port",
",",
"options",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// Needed to convert this constructor into EventEmitter",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"host",
"=",
"host",
"||",
"'127.0.0.1'",
";",
"this",
".",
"port",
"=",
"port",
"||",
"59895",
";",
"this",
".",
"debug",
"=",
"options",
".",
"debug",
"||",
"false",
";",
"this",
".",
"json",
"=",
"options",
".",
"json",
"||",
"true",
";",
"var",
"parser",
"=",
"new",
"xml2js",
".",
"Parser",
"(",
")",
";",
"var",
"responseMessageNumber",
"=",
"0",
";",
"// TODO: Build up proper ACKS",
"var",
"applicationAcceptACK",
"=",
"'MSH|^~\\\\&|||||20121217154325.194-0700||ACK^RO1|101|T|2.6\\nMSA|AA|17'",
";",
"var",
"applicationErrorACK",
"=",
"'MSH|^~\\\\&|NES|NINTENDO|TESTSYSTEM|TESTFACILITY|20121217158325.194-0700||ACK^RO1|101|T|2.6\\nMSA|AE|17'",
";",
"// Bind to TCP socket for HL7",
"var",
"hl7TcpSocket",
"=",
"net",
".",
"createServer",
"(",
"{",
"allowHalfOpen",
":",
"false",
"}",
",",
"function",
"(",
"socket",
")",
"{",
"socket",
".",
"setEncoding",
"(",
"\"utf8\"",
")",
";",
"function",
"handleError",
"(",
"error",
")",
"{",
"socket",
".",
"write",
"(",
"applicationErrorACK",
")",
";",
"self",
".",
"emit",
"(",
"'error'",
",",
"error",
")",
";",
"console",
".",
"log",
"(",
"\"HL7 TCP Server ERROR: \"",
",",
"error",
")",
";",
"}",
"function",
"createEL7AckForMessageNumber",
"(",
"messageNumber",
")",
"{",
"var",
"ack",
"=",
"'MSH|^~\\\\&|||||'",
"+",
"generateTimeStamp",
"(",
")",
"+",
"'||ACK^RO1|'",
"+",
"getUniqueMessageNumber",
"(",
")",
"+",
"'|T|2.6\\rMSA|AA|'",
"+",
"messageNumber",
";",
"return",
"ack",
";",
"}",
"function",
"zeroFill",
"(",
"number",
",",
"width",
")",
"{",
"width",
"-=",
"number",
".",
"toString",
"(",
")",
".",
"length",
";",
"if",
"(",
"width",
">",
"0",
")",
"{",
"return",
"new",
"Array",
"(",
"width",
"+",
"(",
"/",
"\\.",
"/",
".",
"test",
"(",
"number",
")",
"?",
"2",
":",
"1",
")",
")",
".",
"join",
"(",
"'0'",
")",
"+",
"number",
";",
"}",
"return",
"number",
"+",
"\"\"",
";",
"// always return a string",
"}",
"function",
"generateTimeStamp",
"(",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"var",
"month",
"=",
"zeroFill",
"(",
"now",
".",
"getUTCMonth",
"(",
")",
"+",
"1",
",",
"2",
")",
";",
"var",
"date",
"=",
"zeroFill",
"(",
"now",
".",
"getUTCDate",
"(",
")",
",",
"2",
")",
";",
"var",
"hours",
"=",
"zeroFill",
"(",
"now",
".",
"getUTCHours",
"(",
")",
",",
"2",
")",
";",
"var",
"minutes",
"=",
"zeroFill",
"(",
"now",
".",
"getUTCMinutes",
"(",
")",
",",
"2",
")",
";",
"var",
"seconds",
"=",
"zeroFill",
"(",
"now",
".",
"getUTCSeconds",
"(",
")",
",",
"2",
")",
";",
"var",
"timestamp",
"=",
"now",
".",
"getUTCFullYear",
"(",
")",
".",
"toString",
"(",
")",
"+",
"month",
"+",
"date",
"+",
"hours",
"+",
"minutes",
"+",
"seconds",
"+",
"'.'",
"+",
"now",
".",
"getUTCMilliseconds",
"(",
")",
".",
"toString",
"(",
")",
"+",
"'+0000'",
"return",
"timestamp",
";",
"}",
"function",
"getUniqueMessageNumber",
"(",
")",
"{",
"responseMessageNumber",
"=",
"responseMessageNumber",
"+",
"1",
";",
"return",
"responseMessageNumber",
";",
"}",
"function",
"createXMLAckForMessageNumber",
"(",
"messageNumber",
")",
"{",
"var",
"ack",
"=",
"String",
".",
"fromCharCode",
"(",
"0x0b",
")",
"+",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
"+",
"'\\n<ACK xmlns=\"urn:hl7-org:v2xml\">'",
"+",
"'\\n<MSH>'",
"+",
"'\\n<MSH.1>|</MSH.1>'",
"+",
"'\\n<MSH.2>^~\\&</MSH.2>'",
"+",
"'\\n<MSH.7>'",
"+",
"generateTimeStamp",
"(",
")",
"+",
"'</MSH.7>'",
"+",
"'\\n<MSH.9>'",
"+",
"'\\n<MSG.1>ACK</MSG.1>'",
"+",
"'\\n<MSG.2>R01</MSG.2>'",
"+",
"'\\n</MSH.9>'",
"+",
"'\\n<MSH.10>'",
"+",
"getUniqueMessageNumber",
"(",
")",
"+",
"'</MSH.10>'",
"+",
"'\\n<MSH.11>'",
"+",
"'\\n<PT.1>T</PT.1>'",
"+",
"'\\n</MSH.11>'",
"+",
"'\\n<MSH.12>'",
"+",
"'\\n<VID.1>2.6</VID.1>'",
"+",
"'\\n</MSH.12>'",
"+",
"'\\n</MSH>'",
"+",
"'\\n<MSA>'",
"+",
"'\\n<MSA.1>AA</MSA.1>'",
"+",
"'\\n<MSA.2>'",
"+",
"messageNumber",
"+",
"'</MSA.2>'",
"+",
"'\\n</MSA>'",
"+",
"'\\n</ACK>\\n'",
"+",
"String",
".",
"fromCharCode",
"(",
"0x1c",
")",
"+",
"'\\r'",
";",
"console",
".",
"log",
"(",
"\"Generated ACK: \"",
"+",
"ack",
")",
";",
"return",
"ack",
";",
"}",
"function",
"handleXML",
"(",
"xml",
",",
"sendEL7Ack",
")",
"{",
"parser",
".",
"parseString",
"(",
"xml",
",",
"function",
"(",
"error",
",",
"result",
")",
"{",
"if",
"(",
"error",
")",
"return",
"handleError",
"(",
"error",
")",
";",
"if",
"(",
"self",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"\"Message: \"",
",",
"util",
".",
"inspect",
"(",
"result",
",",
"false",
",",
"7",
",",
"true",
")",
")",
";",
"console",
".",
"log",
"(",
"'Sending ACK'",
")",
";",
"}",
"self",
".",
"emit",
"(",
"'hl7'",
",",
"result",
")",
";",
"console",
".",
"log",
"(",
"result",
")",
";",
"var",
"messageNumber",
"=",
"0",
";",
"for",
"(",
"var",
"key",
"in",
"result",
")",
"{",
"if",
"(",
"result",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"if",
"(",
"result",
"[",
"key",
"]",
".",
"MSH",
")",
"{",
"var",
"msg",
"=",
"result",
"[",
"key",
"]",
".",
"MSH",
"[",
"0",
"]",
"[",
"\"MSH.10\"",
"]",
"[",
"0",
"]",
";",
"messageNumber",
"=",
"msg",
";",
"}",
"}",
"}",
"console",
".",
"log",
"(",
"\"Sending ACK for messageNumber \"",
"+",
"messageNumber",
")",
";",
"if",
"(",
"sendEL7Ack",
")",
"{",
"var",
"ack",
"=",
"createEL7AckForMessageNumber",
"(",
"messageNumber",
")",
";",
"socket",
".",
"write",
"(",
"ack",
")",
";",
"}",
"else",
"{",
"var",
"ack",
"=",
"createXMLAckForMessageNumber",
"(",
"messageNumber",
")",
";",
"socket",
".",
"write",
"(",
"new",
"Buffer",
"(",
"ack",
",",
"encoding",
"=",
"\"utf8\"",
")",
")",
";",
"}",
"socket",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"}",
"socket",
".",
"on",
"(",
"'connect'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"debug",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"console",
".",
"log",
"(",
"now",
"+",
"\" - HL7 TCP Client Connected\"",
")",
";",
"}",
"}",
")",
";",
"socket",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"packet",
")",
"{",
"if",
"(",
"self",
".",
"debug",
")",
"{",
"console",
".",
"log",
"(",
"packet",
")",
";",
"}",
"if",
"(",
"!",
"packet",
")",
"return",
"handleError",
"(",
"new",
"Error",
"(",
"'Packet is empty'",
")",
")",
";",
"// It is XML format",
"if",
"(",
"packet",
".",
"indexOf",
"(",
"'<?xml'",
")",
"!==",
"-",
"1",
")",
"{",
"handleXML",
"(",
"packet",
".",
"trim",
"(",
")",
",",
"false",
")",
";",
"}",
"// It is EL7 format",
"else",
"{",
"hl7",
".",
"toXml",
"(",
"packet",
",",
"function",
"(",
"error",
",",
"xml",
")",
"{",
"if",
"(",
"error",
")",
"return",
"handleError",
"(",
"error",
")",
";",
"handleXML",
"(",
"xml",
",",
"true",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"socket",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"handleError",
"(",
"error",
")",
";",
"}",
")",
";",
"socket",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"debug",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"console",
".",
"log",
"(",
"now",
"+",
"\" - HL7 TCP Server Disconnected\"",
")",
";",
"}",
"}",
")",
";",
"socket",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"debug",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
";",
"console",
".",
"log",
"(",
"now",
"+",
"\" - HL7 TCP Client Disconnected\"",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"hl7TcpSocket",
".",
"listen",
"(",
"this",
".",
"port",
",",
"function",
"(",
")",
"{",
"var",
"address",
"=",
"hl7TcpSocket",
".",
"address",
"(",
")",
";",
"console",
".",
"log",
"(",
"\"HL7 TCP Server listening on: \"",
"+",
"address",
".",
"address",
"+",
"\":\"",
"+",
"address",
".",
"port",
")",
";",
"}",
")",
";",
"}"
]
| Creates a HL7 Server
@param String host to listen for HL7 data
@param Integer port to listen to HL7 data - default is 59895
@param {Object} options
@api public | [
"Creates",
"a",
"HL7",
"Server"
]
| 9ee63f524ac0335892ed281b572d7290e56f7167 | https://github.com/ekryski/node-hl7/blob/9ee63f524ac0335892ed281b572d7290e56f7167/lib/server.js#L30-L216 |
43,454 | Vizzuality/node-varnish | lib/node-varnish/varnish_client.js | _send | function _send(cmd, callback) {
cmd_callback = callback;
if(connected) {
client.write(cmd + '\n');
} else {
connect();
}
} | javascript | function _send(cmd, callback) {
cmd_callback = callback;
if(connected) {
client.write(cmd + '\n');
} else {
connect();
}
} | [
"function",
"_send",
"(",
"cmd",
",",
"callback",
")",
"{",
"cmd_callback",
"=",
"callback",
";",
"if",
"(",
"connected",
")",
"{",
"client",
".",
"write",
"(",
"cmd",
"+",
"'\\n'",
")",
";",
"}",
"else",
"{",
"connect",
"(",
")",
";",
"}",
"}"
]
| sends the command to the server | [
"sends",
"the",
"command",
"to",
"the",
"server"
]
| c0ce86b8c7016dc3a3900ef3a6bdd795e83c3436 | https://github.com/Vizzuality/node-varnish/blob/c0ce86b8c7016dc3a3900ef3a6bdd795e83c3436/lib/node-varnish/varnish_client.js#L119-L126 |
43,455 | mysticatea/appcache-manifest | lib/common-part.js | globParentToArray | function globParentToArray(glob) {
return path.resolve(globParent(glob))
.replace(BACK_SLASH, "/")
.split("/")
.filter(Boolean)
} | javascript | function globParentToArray(glob) {
return path.resolve(globParent(glob))
.replace(BACK_SLASH, "/")
.split("/")
.filter(Boolean)
} | [
"function",
"globParentToArray",
"(",
"glob",
")",
"{",
"return",
"path",
".",
"resolve",
"(",
"globParent",
"(",
"glob",
")",
")",
".",
"replace",
"(",
"BACK_SLASH",
",",
"\"/\"",
")",
".",
"split",
"(",
"\"/\"",
")",
".",
"filter",
"(",
"Boolean",
")",
"}"
]
| Get the parent path of the given glob as an array of path elements.
@param {string} glob - The glob to get.
@returns {string[]} The path elements.
@private | [
"Get",
"the",
"parent",
"path",
"of",
"the",
"given",
"glob",
"as",
"an",
"array",
"of",
"path",
"elements",
"."
]
| c44f4d54096287212149a7cf5031bd3e4f5a1fbe | https://github.com/mysticatea/appcache-manifest/blob/c44f4d54096287212149a7cf5031bd3e4f5a1fbe/lib/common-part.js#L31-L36 |
43,456 | mysticatea/appcache-manifest | lib/common-part.js | findLastCommonIndex | function findLastCommonIndex(xs, ys) {
for (let i = Math.min(xs.length, ys.length) - 1; i >= 0; --i) {
if (xs[i] === ys[i]) {
return i
}
}
return -1
} | javascript | function findLastCommonIndex(xs, ys) {
for (let i = Math.min(xs.length, ys.length) - 1; i >= 0; --i) {
if (xs[i] === ys[i]) {
return i
}
}
return -1
} | [
"function",
"findLastCommonIndex",
"(",
"xs",
",",
"ys",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"Math",
".",
"min",
"(",
"xs",
".",
"length",
",",
"ys",
".",
"length",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"--",
"i",
")",
"{",
"if",
"(",
"xs",
"[",
"i",
"]",
"===",
"ys",
"[",
"i",
"]",
")",
"{",
"return",
"i",
"}",
"}",
"return",
"-",
"1",
"}"
]
| Get the index of the last element which is same between the given 2 elements.
@param {string[]} xs - An array to compare.
@param {string[]} ys - Another array to compare.
@returns {number} The index of the last element is same.
@private | [
"Get",
"the",
"index",
"of",
"the",
"last",
"element",
"which",
"is",
"same",
"between",
"the",
"given",
"2",
"elements",
"."
]
| c44f4d54096287212149a7cf5031bd3e4f5a1fbe | https://github.com/mysticatea/appcache-manifest/blob/c44f4d54096287212149a7cf5031bd3e4f5a1fbe/lib/common-part.js#L46-L53 |
43,457 | zhangchiqing/bluebird-promisell | index.js | function(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
} | javascript | function(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
} | [
"function",
"(",
"val",
")",
"{",
"return",
"val",
"===",
"null",
"?",
"'Null'",
":",
"val",
"===",
"undefined",
"?",
"'Undefined'",
":",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"val",
")",
".",
"slice",
"(",
"8",
",",
"-",
"1",
")",
";",
"}"
]
| a -> String | [
"a",
"-",
">",
"String"
]
| ade459c0ceb9710cacc0a8c992907e3eb421a4c2 | https://github.com/zhangchiqing/bluebird-promisell/blob/ade459c0ceb9710cacc0a8c992907e3eb421a4c2/index.js#L153-L157 |
|
43,458 | zhangchiqing/bluebird-promisell | index.js | function(expectedType, value) {
var actualType = getType(value);
if (expectedType!== actualType) {
throw new TypeError('Expected type to be ' +
expectedType + ', but got ' + actualType);
}
return value;
} | javascript | function(expectedType, value) {
var actualType = getType(value);
if (expectedType!== actualType) {
throw new TypeError('Expected type to be ' +
expectedType + ', but got ' + actualType);
}
return value;
} | [
"function",
"(",
"expectedType",
",",
"value",
")",
"{",
"var",
"actualType",
"=",
"getType",
"(",
"value",
")",
";",
"if",
"(",
"expectedType",
"!==",
"actualType",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Expected type to be '",
"+",
"expectedType",
"+",
"', but got '",
"+",
"actualType",
")",
";",
"}",
"return",
"value",
";",
"}"
]
| String -> String -> a -> a | [
"String",
"-",
">",
"String",
"-",
">",
"a",
"-",
">",
"a"
]
| ade459c0ceb9710cacc0a8c992907e3eb421a4c2 | https://github.com/zhangchiqing/bluebird-promisell/blob/ade459c0ceb9710cacc0a8c992907e3eb421a4c2/index.js#L160-L167 |
|
43,459 | sidorares/node-cli-debugger | lib/interface.js | leftPad | function leftPad(n, prefix) {
var s = n.toString(),
nchars = intChars(n),
nspaces = nchars - s.length - 1;
prefix || (prefix = ' ');
for (var i = 0; i < nspaces; i++) {
prefix += ' ';
}
return prefix + s;
} | javascript | function leftPad(n, prefix) {
var s = n.toString(),
nchars = intChars(n),
nspaces = nchars - s.length - 1;
prefix || (prefix = ' ');
for (var i = 0; i < nspaces; i++) {
prefix += ' ';
}
return prefix + s;
} | [
"function",
"leftPad",
"(",
"n",
",",
"prefix",
")",
"{",
"var",
"s",
"=",
"n",
".",
"toString",
"(",
")",
",",
"nchars",
"=",
"intChars",
"(",
"n",
")",
",",
"nspaces",
"=",
"nchars",
"-",
"s",
".",
"length",
"-",
"1",
";",
"prefix",
"||",
"(",
"prefix",
"=",
"' '",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"nspaces",
";",
"i",
"++",
")",
"{",
"prefix",
"+=",
"' '",
";",
"}",
"return",
"prefix",
"+",
"s",
";",
"}"
]
| Adds spaces and prefix to number | [
"Adds",
"spaces",
"and",
"prefix",
"to",
"number"
]
| 3887de612751e05564e6b50759371b4e7f04569f | https://github.com/sidorares/node-cli-debugger/blob/3887de612751e05564e6b50759371b4e7f04569f/lib/interface.js#L386-L398 |
43,460 | angusgibbs/statsjs | lib/stats.js | function(arr) {
return new stats.init(arguments.length > 1 ?
Array.prototype.slice.call(arguments, 0) :
arr);
} | javascript | function(arr) {
return new stats.init(arguments.length > 1 ?
Array.prototype.slice.call(arguments, 0) :
arr);
} | [
"function",
"(",
"arr",
")",
"{",
"return",
"new",
"stats",
".",
"init",
"(",
"arguments",
".",
"length",
">",
"1",
"?",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
":",
"arr",
")",
";",
"}"
]
| Wrapper to create a chainable stats object. arr - The array to work with. Returns a new chainable object. | [
"Wrapper",
"to",
"create",
"a",
"chainable",
"stats",
"object",
".",
"arr",
"-",
"The",
"array",
"to",
"work",
"with",
".",
"Returns",
"a",
"new",
"chainable",
"object",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L14-L18 |
|
43,461 | angusgibbs/statsjs | lib/stats.js | function(fn) {
var arr = this.arr;
if (arr.length === undefined) {
// The wrapped array is a JSON object
for (var key in arr) {
this.arr[key] = fn.call(arr[key], arr[key], key, arr);
}
} else {
// The wrapped array is an array
for (var i = 0, l = this.arr.length; i < l; i++) {
this.arr[i] = fn.call(arr[i], arr[i], i, arr);
}
}
return this;
} | javascript | function(fn) {
var arr = this.arr;
if (arr.length === undefined) {
// The wrapped array is a JSON object
for (var key in arr) {
this.arr[key] = fn.call(arr[key], arr[key], key, arr);
}
} else {
// The wrapped array is an array
for (var i = 0, l = this.arr.length; i < l; i++) {
this.arr[i] = fn.call(arr[i], arr[i], i, arr);
}
}
return this;
} | [
"function",
"(",
"fn",
")",
"{",
"var",
"arr",
"=",
"this",
".",
"arr",
";",
"if",
"(",
"arr",
".",
"length",
"===",
"undefined",
")",
"{",
"// The wrapped array is a JSON object\r",
"for",
"(",
"var",
"key",
"in",
"arr",
")",
"{",
"this",
".",
"arr",
"[",
"key",
"]",
"=",
"fn",
".",
"call",
"(",
"arr",
"[",
"key",
"]",
",",
"arr",
"[",
"key",
"]",
",",
"key",
",",
"arr",
")",
";",
"}",
"}",
"else",
"{",
"// The wrapped array is an array\r",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"this",
".",
"arr",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"this",
".",
"arr",
"[",
"i",
"]",
"=",
"fn",
".",
"call",
"(",
"arr",
"[",
"i",
"]",
",",
"arr",
"[",
"i",
"]",
",",
"i",
",",
"arr",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
]
| Replaces each element in an array or JSON object with the result of the function that is called against each element. fn - The function to call on each element el - The array or object element index - The index or key of the array element Returns nothing. | [
"Replaces",
"each",
"element",
"in",
"an",
"array",
"or",
"JSON",
"object",
"with",
"the",
"result",
"of",
"the",
"function",
"that",
"is",
"called",
"against",
"each",
"element",
".",
"fn",
"-",
"The",
"function",
"to",
"call",
"on",
"each",
"element",
"el",
"-",
"The",
"array",
"or",
"object",
"element",
"index",
"-",
"The",
"index",
"or",
"key",
"of",
"the",
"array",
"element",
"Returns",
"nothing",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L64-L80 |
|
43,462 | angusgibbs/statsjs | lib/stats.js | function(attr) {
var newArr = [];
if (this.arr.length === undefined) {
// The wrapped array is a JSON object
for (var key in arr) {
newArr.push(this.arr[key][attr]);
}
} else {
// The wrapped array is an array
for (var i = 0, l = this.arr.length; i < l; i++) {
newArr.push(this.arr[i][attr]);
}
}
return stats(newArr);
} | javascript | function(attr) {
var newArr = [];
if (this.arr.length === undefined) {
// The wrapped array is a JSON object
for (var key in arr) {
newArr.push(this.arr[key][attr]);
}
} else {
// The wrapped array is an array
for (var i = 0, l = this.arr.length; i < l; i++) {
newArr.push(this.arr[i][attr]);
}
}
return stats(newArr);
} | [
"function",
"(",
"attr",
")",
"{",
"var",
"newArr",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"arr",
".",
"length",
"===",
"undefined",
")",
"{",
"// The wrapped array is a JSON object\r",
"for",
"(",
"var",
"key",
"in",
"arr",
")",
"{",
"newArr",
".",
"push",
"(",
"this",
".",
"arr",
"[",
"key",
"]",
"[",
"attr",
"]",
")",
";",
"}",
"}",
"else",
"{",
"// The wrapped array is an array\r",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"this",
".",
"arr",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"newArr",
".",
"push",
"(",
"this",
".",
"arr",
"[",
"i",
"]",
"[",
"attr",
"]",
")",
";",
"}",
"}",
"return",
"stats",
"(",
"newArr",
")",
";",
"}"
]
| Replaces each element of the array with the attribute of that given element. attr - The attribute to pluck. Returns nothing. | [
"Replaces",
"each",
"element",
"of",
"the",
"array",
"with",
"the",
"attribute",
"of",
"that",
"given",
"element",
".",
"attr",
"-",
"The",
"attribute",
"to",
"pluck",
".",
"Returns",
"nothing",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L88-L104 |
|
43,463 | angusgibbs/statsjs | lib/stats.js | function(attr) {
// Get the numbers
var arr = this.arr;
// Go through each of the numbers and find the minimum
var minimum = attr == null ? arr[0] : arr[0][attr];
var minimumEl = attr == null ? arr[0] : arr[0];
stats(arr).each(function(num, index) {
if ((attr == null ? num : num[attr]) < minimum) {
minimum = attr == null ? num : num[attr];
minimumEl = num;
}
});
return minimumEl;
} | javascript | function(attr) {
// Get the numbers
var arr = this.arr;
// Go through each of the numbers and find the minimum
var minimum = attr == null ? arr[0] : arr[0][attr];
var minimumEl = attr == null ? arr[0] : arr[0];
stats(arr).each(function(num, index) {
if ((attr == null ? num : num[attr]) < minimum) {
minimum = attr == null ? num : num[attr];
minimumEl = num;
}
});
return minimumEl;
} | [
"function",
"(",
"attr",
")",
"{",
"// Get the numbers\r",
"var",
"arr",
"=",
"this",
".",
"arr",
";",
"// Go through each of the numbers and find the minimum\r",
"var",
"minimum",
"=",
"attr",
"==",
"null",
"?",
"arr",
"[",
"0",
"]",
":",
"arr",
"[",
"0",
"]",
"[",
"attr",
"]",
";",
"var",
"minimumEl",
"=",
"attr",
"==",
"null",
"?",
"arr",
"[",
"0",
"]",
":",
"arr",
"[",
"0",
"]",
";",
"stats",
"(",
"arr",
")",
".",
"each",
"(",
"function",
"(",
"num",
",",
"index",
")",
"{",
"if",
"(",
"(",
"attr",
"==",
"null",
"?",
"num",
":",
"num",
"[",
"attr",
"]",
")",
"<",
"minimum",
")",
"{",
"minimum",
"=",
"attr",
"==",
"null",
"?",
"num",
":",
"num",
"[",
"attr",
"]",
";",
"minimumEl",
"=",
"num",
";",
"}",
"}",
")",
";",
"return",
"minimumEl",
";",
"}"
]
| Finds the smallest number. attr - Optional. If passed, the elemnt with the minimum value for the given attribute will be returned. Returns the minimum. | [
"Finds",
"the",
"smallest",
"number",
".",
"attr",
"-",
"Optional",
".",
"If",
"passed",
"the",
"elemnt",
"with",
"the",
"minimum",
"value",
"for",
"the",
"given",
"attribute",
"will",
"be",
"returned",
".",
"Returns",
"the",
"minimum",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L112-L128 |
|
43,464 | angusgibbs/statsjs | lib/stats.js | function(attr) {
// Get the numbers
var arr = this.arr;
// Go through each of the numbers and find the maximum
var maximum = attr == null ? arr[0] : arr[0][attr];
var maximumEl = attr == null ? arr[0] : arr[0];
stats(arr).each(function(num, index) {
if ((attr == null ? num : num[attr]) > maximum) {
maximum = attr == null ? num : num[attr];
maximumEl = num;
}
});
return maximumEl;
} | javascript | function(attr) {
// Get the numbers
var arr = this.arr;
// Go through each of the numbers and find the maximum
var maximum = attr == null ? arr[0] : arr[0][attr];
var maximumEl = attr == null ? arr[0] : arr[0];
stats(arr).each(function(num, index) {
if ((attr == null ? num : num[attr]) > maximum) {
maximum = attr == null ? num : num[attr];
maximumEl = num;
}
});
return maximumEl;
} | [
"function",
"(",
"attr",
")",
"{",
"// Get the numbers\r",
"var",
"arr",
"=",
"this",
".",
"arr",
";",
"// Go through each of the numbers and find the maximum\r",
"var",
"maximum",
"=",
"attr",
"==",
"null",
"?",
"arr",
"[",
"0",
"]",
":",
"arr",
"[",
"0",
"]",
"[",
"attr",
"]",
";",
"var",
"maximumEl",
"=",
"attr",
"==",
"null",
"?",
"arr",
"[",
"0",
"]",
":",
"arr",
"[",
"0",
"]",
";",
"stats",
"(",
"arr",
")",
".",
"each",
"(",
"function",
"(",
"num",
",",
"index",
")",
"{",
"if",
"(",
"(",
"attr",
"==",
"null",
"?",
"num",
":",
"num",
"[",
"attr",
"]",
")",
">",
"maximum",
")",
"{",
"maximum",
"=",
"attr",
"==",
"null",
"?",
"num",
":",
"num",
"[",
"attr",
"]",
";",
"maximumEl",
"=",
"num",
";",
"}",
"}",
")",
";",
"return",
"maximumEl",
";",
"}"
]
| Finds the largest number. attr - Optional. If passed, the elemnt with the maximum value for the given attribute will be returned. Returns the maximum. | [
"Finds",
"the",
"largest",
"number",
".",
"attr",
"-",
"Optional",
".",
"If",
"passed",
"the",
"elemnt",
"with",
"the",
"maximum",
"value",
"for",
"the",
"given",
"attribute",
"will",
"be",
"returned",
".",
"Returns",
"the",
"maximum",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L136-L152 |
|
43,465 | angusgibbs/statsjs | lib/stats.js | function() {
// Sort the numbers
var arr = this.clone().sort().toArray();
if (arr.length % 2 === 0) {
// There are an even number of elements in the array; the median
// is the average of the middle two
return (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
} else {
// There are an odd number of elements in the array; the median
// is the middle one
return arr[(arr.length - 1) / 2];
}
} | javascript | function() {
// Sort the numbers
var arr = this.clone().sort().toArray();
if (arr.length % 2 === 0) {
// There are an even number of elements in the array; the median
// is the average of the middle two
return (arr[arr.length / 2 - 1] + arr[arr.length / 2]) / 2;
} else {
// There are an odd number of elements in the array; the median
// is the middle one
return arr[(arr.length - 1) / 2];
}
} | [
"function",
"(",
")",
"{",
"// Sort the numbers\r",
"var",
"arr",
"=",
"this",
".",
"clone",
"(",
")",
".",
"sort",
"(",
")",
".",
"toArray",
"(",
")",
";",
"if",
"(",
"arr",
".",
"length",
"%",
"2",
"===",
"0",
")",
"{",
"// There are an even number of elements in the array; the median\r",
"// is the average of the middle two\r",
"return",
"(",
"arr",
"[",
"arr",
".",
"length",
"/",
"2",
"-",
"1",
"]",
"+",
"arr",
"[",
"arr",
".",
"length",
"/",
"2",
"]",
")",
"/",
"2",
";",
"}",
"else",
"{",
"// There are an odd number of elements in the array; the median\r",
"// is the middle one\r",
"return",
"arr",
"[",
"(",
"arr",
".",
"length",
"-",
"1",
")",
"/",
"2",
"]",
";",
"}",
"}"
]
| Finds the median of the numbers. Returns the median. | [
"Finds",
"the",
"median",
"of",
"the",
"numbers",
".",
"Returns",
"the",
"median",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L157-L170 |
|
43,466 | angusgibbs/statsjs | lib/stats.js | function() {
// Handle the single element case
if (this.length == 1) {
return this.arr[0];
}
// Sort the numbers
var nums = this.clone().sort();
// The third quartile is the median of the upper half of the numbers
return nums.slice(Math.ceil(nums.size() / 2)).median();
} | javascript | function() {
// Handle the single element case
if (this.length == 1) {
return this.arr[0];
}
// Sort the numbers
var nums = this.clone().sort();
// The third quartile is the median of the upper half of the numbers
return nums.slice(Math.ceil(nums.size() / 2)).median();
} | [
"function",
"(",
")",
"{",
"// Handle the single element case\r",
"if",
"(",
"this",
".",
"length",
"==",
"1",
")",
"{",
"return",
"this",
".",
"arr",
"[",
"0",
"]",
";",
"}",
"// Sort the numbers\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
".",
"sort",
"(",
")",
";",
"// The third quartile is the median of the upper half of the numbers\r",
"return",
"nums",
".",
"slice",
"(",
"Math",
".",
"ceil",
"(",
"nums",
".",
"size",
"(",
")",
"/",
"2",
")",
")",
".",
"median",
"(",
")",
";",
"}"
]
| Finds the third quartile of the numbers. Returns the third quartile. | [
"Finds",
"the",
"third",
"quartile",
"of",
"the",
"numbers",
".",
"Returns",
"the",
"third",
"quartile",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L191-L202 |
|
43,467 | angusgibbs/statsjs | lib/stats.js | function() {
// Get the mean
var mean = this.mean();
// Get a new stats object to work with
var nums = this.clone();
// Map each element of nums to the square of the element minus the
// mean
nums.map(function(num) {
return Math.pow(num - mean, 2);
});
// Return the standard deviation
return Math.sqrt(nums.sum() / (nums.size() - 1));
} | javascript | function() {
// Get the mean
var mean = this.mean();
// Get a new stats object to work with
var nums = this.clone();
// Map each element of nums to the square of the element minus the
// mean
nums.map(function(num) {
return Math.pow(num - mean, 2);
});
// Return the standard deviation
return Math.sqrt(nums.sum() / (nums.size() - 1));
} | [
"function",
"(",
")",
"{",
"// Get the mean\r",
"var",
"mean",
"=",
"this",
".",
"mean",
"(",
")",
";",
"// Get a new stats object to work with\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
";",
"// Map each element of nums to the square of the element minus the\r",
"// mean\r",
"nums",
".",
"map",
"(",
"function",
"(",
"num",
")",
"{",
"return",
"Math",
".",
"pow",
"(",
"num",
"-",
"mean",
",",
"2",
")",
";",
"}",
")",
";",
"// Return the standard deviation\r",
"return",
"Math",
".",
"sqrt",
"(",
"nums",
".",
"sum",
"(",
")",
"/",
"(",
"nums",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
";",
"}"
]
| Finds the standard deviation of the numbers. Returns the standard deviation. | [
"Finds",
"the",
"standard",
"deviation",
"of",
"the",
"numbers",
".",
"Returns",
"the",
"standard",
"deviation",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L290-L305 |
|
43,468 | angusgibbs/statsjs | lib/stats.js | function() {
// Get the x and y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Get the means for the x and y coordinates
var meanX = xCoords.mean();
var meanY = yCoords.mean();
// Get the standard deviations for the x and y coordinates
var stdDevX = xCoords.stdDev();
var stdDevY = yCoords.stdDev();
// Map each element to the difference of the element and the mean
// divided by the standard deviation
xCoords.map(function(num) {
return (num - meanX) / stdDevX;
});
yCoords.map(function(num) {
return (num - meanY) / stdDevY;
});
// Multiply each element in the x by the corresponding value in
// the y
var nums = this.clone().map(function(num, index) {
return xCoords.get(index) * yCoords.get(index);
});
// r is the sum of xCoords over the number of points minus 1
return nums.sum() / (nums.size() - 1);
} | javascript | function() {
// Get the x and y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Get the means for the x and y coordinates
var meanX = xCoords.mean();
var meanY = yCoords.mean();
// Get the standard deviations for the x and y coordinates
var stdDevX = xCoords.stdDev();
var stdDevY = yCoords.stdDev();
// Map each element to the difference of the element and the mean
// divided by the standard deviation
xCoords.map(function(num) {
return (num - meanX) / stdDevX;
});
yCoords.map(function(num) {
return (num - meanY) / stdDevY;
});
// Multiply each element in the x by the corresponding value in
// the y
var nums = this.clone().map(function(num, index) {
return xCoords.get(index) * yCoords.get(index);
});
// r is the sum of xCoords over the number of points minus 1
return nums.sum() / (nums.size() - 1);
} | [
"function",
"(",
")",
"{",
"// Get the x and y coordinates\r",
"var",
"xCoords",
"=",
"this",
".",
"pluck",
"(",
"'x'",
")",
";",
"var",
"yCoords",
"=",
"this",
".",
"pluck",
"(",
"'y'",
")",
";",
"// Get the means for the x and y coordinates\r",
"var",
"meanX",
"=",
"xCoords",
".",
"mean",
"(",
")",
";",
"var",
"meanY",
"=",
"yCoords",
".",
"mean",
"(",
")",
";",
"// Get the standard deviations for the x and y coordinates\r",
"var",
"stdDevX",
"=",
"xCoords",
".",
"stdDev",
"(",
")",
";",
"var",
"stdDevY",
"=",
"yCoords",
".",
"stdDev",
"(",
")",
";",
"// Map each element to the difference of the element and the mean\r",
"// divided by the standard deviation\r",
"xCoords",
".",
"map",
"(",
"function",
"(",
"num",
")",
"{",
"return",
"(",
"num",
"-",
"meanX",
")",
"/",
"stdDevX",
";",
"}",
")",
";",
"yCoords",
".",
"map",
"(",
"function",
"(",
"num",
")",
"{",
"return",
"(",
"num",
"-",
"meanY",
")",
"/",
"stdDevY",
";",
"}",
")",
";",
"// Multiply each element in the x by the corresponding value in\r",
"// the y\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
".",
"map",
"(",
"function",
"(",
"num",
",",
"index",
")",
"{",
"return",
"xCoords",
".",
"get",
"(",
"index",
")",
"*",
"yCoords",
".",
"get",
"(",
"index",
")",
";",
"}",
")",
";",
"// r is the sum of xCoords over the number of points minus 1\r",
"return",
"nums",
".",
"sum",
"(",
")",
"/",
"(",
"nums",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}"
]
| Calculates the correlation coefficient for the data set. Returns the value of r. | [
"Calculates",
"the",
"correlation",
"coefficient",
"for",
"the",
"data",
"set",
".",
"Returns",
"the",
"value",
"of",
"r",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L310-L340 |
|
43,469 | angusgibbs/statsjs | lib/stats.js | function() {
// Get the x and y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Get the means for the x and y coordinates
var meanX = xCoords.mean();
var meanY = yCoords.mean();
// Get the standard deviations for the x and y coordinates
var stdDevX = xCoords.stdDev();
var stdDevY = yCoords.stdDev();
// Calculate the correlation coefficient
var r = this.r();
// Calculate the slope
var slope = r * (stdDevY / stdDevX);
// Calculate the y-intercept
var yIntercept = meanY - slope * meanX;
return {
slope: slope,
yIntercept: yIntercept,
r: r
};
} | javascript | function() {
// Get the x and y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Get the means for the x and y coordinates
var meanX = xCoords.mean();
var meanY = yCoords.mean();
// Get the standard deviations for the x and y coordinates
var stdDevX = xCoords.stdDev();
var stdDevY = yCoords.stdDev();
// Calculate the correlation coefficient
var r = this.r();
// Calculate the slope
var slope = r * (stdDevY / stdDevX);
// Calculate the y-intercept
var yIntercept = meanY - slope * meanX;
return {
slope: slope,
yIntercept: yIntercept,
r: r
};
} | [
"function",
"(",
")",
"{",
"// Get the x and y coordinates\r",
"var",
"xCoords",
"=",
"this",
".",
"pluck",
"(",
"'x'",
")",
";",
"var",
"yCoords",
"=",
"this",
".",
"pluck",
"(",
"'y'",
")",
";",
"// Get the means for the x and y coordinates\r",
"var",
"meanX",
"=",
"xCoords",
".",
"mean",
"(",
")",
";",
"var",
"meanY",
"=",
"yCoords",
".",
"mean",
"(",
")",
";",
"// Get the standard deviations for the x and y coordinates\r",
"var",
"stdDevX",
"=",
"xCoords",
".",
"stdDev",
"(",
")",
";",
"var",
"stdDevY",
"=",
"yCoords",
".",
"stdDev",
"(",
")",
";",
"// Calculate the correlation coefficient\r",
"var",
"r",
"=",
"this",
".",
"r",
"(",
")",
";",
"// Calculate the slope\r",
"var",
"slope",
"=",
"r",
"*",
"(",
"stdDevY",
"/",
"stdDevX",
")",
";",
"// Calculate the y-intercept\r",
"var",
"yIntercept",
"=",
"meanY",
"-",
"slope",
"*",
"meanX",
";",
"return",
"{",
"slope",
":",
"slope",
",",
"yIntercept",
":",
"yIntercept",
",",
"r",
":",
"r",
"}",
";",
"}"
]
| Calculates the Least Squares Regression line for the data set. Returns an object with the slope and y intercept. | [
"Calculates",
"the",
"Least",
"Squares",
"Regression",
"line",
"for",
"the",
"data",
"set",
".",
"Returns",
"an",
"object",
"with",
"the",
"slope",
"and",
"y",
"intercept",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L345-L372 |
|
43,470 | angusgibbs/statsjs | lib/stats.js | function() {
// Get y coordinates
var yCoords = this.pluck('y');
// Do a semi-log transformation of the coordinates
yCoords.map(function(num) {
return Math.log(num);
});
// Get a new stats object to work with that has the transformed data
var nums = this.clone().map(function(coord, index) {
return {
x: coord.x,
y: yCoords.get(index)
};
});
// Calculate the linear regression for the linearized data
var linReg = nums.linReg();
// Calculate the coefficient for the exponential equation
var coefficient = Math.pow(Math.E, linReg.yIntercept);
// Calculate the base for the exponential equation
var base = Math.pow(Math.E, linReg.slope);
return {
coefficient: coefficient,
base: base,
r: linReg.r
};
} | javascript | function() {
// Get y coordinates
var yCoords = this.pluck('y');
// Do a semi-log transformation of the coordinates
yCoords.map(function(num) {
return Math.log(num);
});
// Get a new stats object to work with that has the transformed data
var nums = this.clone().map(function(coord, index) {
return {
x: coord.x,
y: yCoords.get(index)
};
});
// Calculate the linear regression for the linearized data
var linReg = nums.linReg();
// Calculate the coefficient for the exponential equation
var coefficient = Math.pow(Math.E, linReg.yIntercept);
// Calculate the base for the exponential equation
var base = Math.pow(Math.E, linReg.slope);
return {
coefficient: coefficient,
base: base,
r: linReg.r
};
} | [
"function",
"(",
")",
"{",
"// Get y coordinates\r",
"var",
"yCoords",
"=",
"this",
".",
"pluck",
"(",
"'y'",
")",
";",
"// Do a semi-log transformation of the coordinates\r",
"yCoords",
".",
"map",
"(",
"function",
"(",
"num",
")",
"{",
"return",
"Math",
".",
"log",
"(",
"num",
")",
";",
"}",
")",
";",
"// Get a new stats object to work with that has the transformed data\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
".",
"map",
"(",
"function",
"(",
"coord",
",",
"index",
")",
"{",
"return",
"{",
"x",
":",
"coord",
".",
"x",
",",
"y",
":",
"yCoords",
".",
"get",
"(",
"index",
")",
"}",
";",
"}",
")",
";",
"// Calculate the linear regression for the linearized data\r",
"var",
"linReg",
"=",
"nums",
".",
"linReg",
"(",
")",
";",
"// Calculate the coefficient for the exponential equation\r",
"var",
"coefficient",
"=",
"Math",
".",
"pow",
"(",
"Math",
".",
"E",
",",
"linReg",
".",
"yIntercept",
")",
";",
"// Calculate the base for the exponential equation\r",
"var",
"base",
"=",
"Math",
".",
"pow",
"(",
"Math",
".",
"E",
",",
"linReg",
".",
"slope",
")",
";",
"return",
"{",
"coefficient",
":",
"coefficient",
",",
"base",
":",
"base",
",",
"r",
":",
"linReg",
".",
"r",
"}",
";",
"}"
]
| Calculates the exponential regression line for the data set. Returns an object with the coefficient, base, and correlation coefficient for the linearized data. | [
"Calculates",
"the",
"exponential",
"regression",
"line",
"for",
"the",
"data",
"set",
".",
"Returns",
"an",
"object",
"with",
"the",
"coefficient",
"base",
"and",
"correlation",
"coefficient",
"for",
"the",
"linearized",
"data",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L378-L409 |
|
43,471 | angusgibbs/statsjs | lib/stats.js | function() {
// Get y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Do a log-log transformation of the coordinates
xCoords.map(function(num) {
return Math.log(num);
});
yCoords.map(function(num) {
return Math.log(num);
});
// Get a new stats object to work with that has the transformed data
var nums = this.clone().map(function(coord, index) {
return {
x: xCoords.get(index),
y: yCoords.get(index)
};
});
// Calculate the linear regression for the linearized data
var linReg = nums.linReg();
// Calculate the coefficient for the power equation
var coefficient = Math.pow(Math.E, linReg.yIntercept);
// Calculate the exponent for the power equation
var exponent = linReg.slope;
return {
coefficient: coefficient,
exponent: exponent,
r: linReg.r
};
} | javascript | function() {
// Get y coordinates
var xCoords = this.pluck('x');
var yCoords = this.pluck('y');
// Do a log-log transformation of the coordinates
xCoords.map(function(num) {
return Math.log(num);
});
yCoords.map(function(num) {
return Math.log(num);
});
// Get a new stats object to work with that has the transformed data
var nums = this.clone().map(function(coord, index) {
return {
x: xCoords.get(index),
y: yCoords.get(index)
};
});
// Calculate the linear regression for the linearized data
var linReg = nums.linReg();
// Calculate the coefficient for the power equation
var coefficient = Math.pow(Math.E, linReg.yIntercept);
// Calculate the exponent for the power equation
var exponent = linReg.slope;
return {
coefficient: coefficient,
exponent: exponent,
r: linReg.r
};
} | [
"function",
"(",
")",
"{",
"// Get y coordinates\r",
"var",
"xCoords",
"=",
"this",
".",
"pluck",
"(",
"'x'",
")",
";",
"var",
"yCoords",
"=",
"this",
".",
"pluck",
"(",
"'y'",
")",
";",
"// Do a log-log transformation of the coordinates\r",
"xCoords",
".",
"map",
"(",
"function",
"(",
"num",
")",
"{",
"return",
"Math",
".",
"log",
"(",
"num",
")",
";",
"}",
")",
";",
"yCoords",
".",
"map",
"(",
"function",
"(",
"num",
")",
"{",
"return",
"Math",
".",
"log",
"(",
"num",
")",
";",
"}",
")",
";",
"// Get a new stats object to work with that has the transformed data\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
".",
"map",
"(",
"function",
"(",
"coord",
",",
"index",
")",
"{",
"return",
"{",
"x",
":",
"xCoords",
".",
"get",
"(",
"index",
")",
",",
"y",
":",
"yCoords",
".",
"get",
"(",
"index",
")",
"}",
";",
"}",
")",
";",
"// Calculate the linear regression for the linearized data\r",
"var",
"linReg",
"=",
"nums",
".",
"linReg",
"(",
")",
";",
"// Calculate the coefficient for the power equation\r",
"var",
"coefficient",
"=",
"Math",
".",
"pow",
"(",
"Math",
".",
"E",
",",
"linReg",
".",
"yIntercept",
")",
";",
"// Calculate the exponent for the power equation\r",
"var",
"exponent",
"=",
"linReg",
".",
"slope",
";",
"return",
"{",
"coefficient",
":",
"coefficient",
",",
"exponent",
":",
"exponent",
",",
"r",
":",
"linReg",
".",
"r",
"}",
";",
"}"
]
| Calculates the power regression line for the data set. Returns an object with the coefficient, base, and correlation coefficient for the linearized data. | [
"Calculates",
"the",
"power",
"regression",
"line",
"for",
"the",
"data",
"set",
".",
"Returns",
"an",
"object",
"with",
"the",
"coefficient",
"base",
"and",
"correlation",
"coefficient",
"for",
"the",
"linearized",
"data",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L415-L450 |
|
43,472 | angusgibbs/statsjs | lib/stats.js | function() {
// Create a new stats object to work with
var nums = this.clone();
// Go through each element and make the element the gcd of it
// and the element to its left
for (var i = 1; i < nums.size(); i++) {
nums.set(i, gcd(nums.get(i - 1), nums.get(i)));
}
// The gcd of all the numbers is now in the final element
return nums.get(nums.size() - 1);
} | javascript | function() {
// Create a new stats object to work with
var nums = this.clone();
// Go through each element and make the element the gcd of it
// and the element to its left
for (var i = 1; i < nums.size(); i++) {
nums.set(i, gcd(nums.get(i - 1), nums.get(i)));
}
// The gcd of all the numbers is now in the final element
return nums.get(nums.size() - 1);
} | [
"function",
"(",
")",
"{",
"// Create a new stats object to work with\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
";",
"// Go through each element and make the element the gcd of it\r",
"// and the element to its left\r",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"nums",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"nums",
".",
"set",
"(",
"i",
",",
"gcd",
"(",
"nums",
".",
"get",
"(",
"i",
"-",
"1",
")",
",",
"nums",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"}",
"// The gcd of all the numbers is now in the final element\r",
"return",
"nums",
".",
"get",
"(",
"nums",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}"
]
| Calculates the greatest common divisor of the set. Returns a Number, the gcd. | [
"Calculates",
"the",
"greatest",
"common",
"divisor",
"of",
"the",
"set",
".",
"Returns",
"a",
"Number",
"the",
"gcd",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L520-L532 |
|
43,473 | angusgibbs/statsjs | lib/stats.js | function() {
// Create a new stats object to work with
var nums = this.clone();
// Go through each element and make the element the lcm of it
// and the element to its left
for (var i = 1; i < nums.size(); i++) {
nums.set(i, lcm(nums.get(i - 1), nums.get(i)));
}
// The lcm of all the numbers if now in the final element
return nums.get(nums.size() - 1);
} | javascript | function() {
// Create a new stats object to work with
var nums = this.clone();
// Go through each element and make the element the lcm of it
// and the element to its left
for (var i = 1; i < nums.size(); i++) {
nums.set(i, lcm(nums.get(i - 1), nums.get(i)));
}
// The lcm of all the numbers if now in the final element
return nums.get(nums.size() - 1);
} | [
"function",
"(",
")",
"{",
"// Create a new stats object to work with\r",
"var",
"nums",
"=",
"this",
".",
"clone",
"(",
")",
";",
"// Go through each element and make the element the lcm of it\r",
"// and the element to its left\r",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"nums",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"nums",
".",
"set",
"(",
"i",
",",
"lcm",
"(",
"nums",
".",
"get",
"(",
"i",
"-",
"1",
")",
",",
"nums",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"}",
"// The lcm of all the numbers if now in the final element\r",
"return",
"nums",
".",
"get",
"(",
"nums",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"}"
]
| Calculates the least common multiple of the set. Returns a Number, the lcm. | [
"Calculates",
"the",
"least",
"common",
"multiple",
"of",
"the",
"set",
".",
"Returns",
"a",
"Number",
"the",
"lcm",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L537-L549 |
|
43,474 | angusgibbs/statsjs | lib/stats.js | gcd | function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a - b * Math.floor(a / b));
} | javascript | function gcd(a, b) {
if (b === 0) {
return a;
}
return gcd(b, a - b * Math.floor(a / b));
} | [
"function",
"gcd",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"b",
"===",
"0",
")",
"{",
"return",
"a",
";",
"}",
"return",
"gcd",
"(",
"b",
",",
"a",
"-",
"b",
"*",
"Math",
".",
"floor",
"(",
"a",
"/",
"b",
")",
")",
";",
"}"
]
| Private. Calculates the gcd of two numbers using Euclid's method. Returns a Number. | [
"Private",
".",
"Calculates",
"the",
"gcd",
"of",
"two",
"numbers",
"using",
"Euclid",
"s",
"method",
".",
"Returns",
"a",
"Number",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L555-L561 |
43,475 | angusgibbs/statsjs | lib/stats.js | lcm | function lcm(a, b) {
// The least common multiple is the absolute value of the product of
// the numbers divided by the greatest common denominator
return Math.abs(a * b) / gcd(a, b);
} | javascript | function lcm(a, b) {
// The least common multiple is the absolute value of the product of
// the numbers divided by the greatest common denominator
return Math.abs(a * b) / gcd(a, b);
} | [
"function",
"lcm",
"(",
"a",
",",
"b",
")",
"{",
"// The least common multiple is the absolute value of the product of\r",
"// the numbers divided by the greatest common denominator\r",
"return",
"Math",
".",
"abs",
"(",
"a",
"*",
"b",
")",
"/",
"gcd",
"(",
"a",
",",
"b",
")",
";",
"}"
]
| Private. Calculates the lcm of two numbers. Returns a Number. | [
"Private",
".",
"Calculates",
"the",
"lcm",
"of",
"two",
"numbers",
".",
"Returns",
"a",
"Number",
"."
]
| 791d599bbc224999b7de1ae5fc3e9adeb8406861 | https://github.com/angusgibbs/statsjs/blob/791d599bbc224999b7de1ae5fc3e9adeb8406861/lib/stats.js#L566-L570 |
43,476 | marco-loche/saw | saw.js | function (win) {
if (win == null) {
return null;
}
while ((win.API == null) && (win.parent != null) && (win.parent != win)) {
findAPITries++;
if (findAPITries > 7) {
return null;
}
win = win.parent;
}
return win.API;
} | javascript | function (win) {
if (win == null) {
return null;
}
while ((win.API == null) && (win.parent != null) && (win.parent != win)) {
findAPITries++;
if (findAPITries > 7) {
return null;
}
win = win.parent;
}
return win.API;
} | [
"function",
"(",
"win",
")",
"{",
"if",
"(",
"win",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"while",
"(",
"(",
"win",
".",
"API",
"==",
"null",
")",
"&&",
"(",
"win",
".",
"parent",
"!=",
"null",
")",
"&&",
"(",
"win",
".",
"parent",
"!=",
"win",
")",
")",
"{",
"findAPITries",
"++",
";",
"if",
"(",
"findAPITries",
">",
"7",
")",
"{",
"return",
"null",
";",
"}",
"win",
"=",
"win",
".",
"parent",
";",
"}",
"return",
"win",
".",
"API",
";",
"}"
]
| The function charged to locate the API adapter object presented by the LMS. As described in section 3.3.6.1 of the documentation. | [
"The",
"function",
"charged",
"to",
"locate",
"the",
"API",
"adapter",
"object",
"presented",
"by",
"the",
"LMS",
".",
"As",
"described",
"in",
"section",
"3",
".",
"3",
".",
"6",
".",
"1",
"of",
"the",
"documentation",
"."
]
| d6c0c9713b020ffa0eda1be73a37144b1451a41d | https://github.com/marco-loche/saw/blob/d6c0c9713b020ffa0eda1be73a37144b1451a41d/saw.js#L12-L25 |
|
43,477 | mysticatea/appcache-manifest | lib/queue.js | dequeue | function dequeue(queue, item) {
queue[SIZE] -= 1
let done = false
item.action(() => {
if (done) {
return
}
done = true
if (item.next) {
dequeue(queue, item.next)
}
else {
assert(queue[TAIL] === item, "BROKEN")
queue[TAIL] = null
}
})
} | javascript | function dequeue(queue, item) {
queue[SIZE] -= 1
let done = false
item.action(() => {
if (done) {
return
}
done = true
if (item.next) {
dequeue(queue, item.next)
}
else {
assert(queue[TAIL] === item, "BROKEN")
queue[TAIL] = null
}
})
} | [
"function",
"dequeue",
"(",
"queue",
",",
"item",
")",
"{",
"queue",
"[",
"SIZE",
"]",
"-=",
"1",
"let",
"done",
"=",
"false",
"item",
".",
"action",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"done",
")",
"{",
"return",
"}",
"done",
"=",
"true",
"if",
"(",
"item",
".",
"next",
")",
"{",
"dequeue",
"(",
"queue",
",",
"item",
".",
"next",
")",
"}",
"else",
"{",
"assert",
"(",
"queue",
"[",
"TAIL",
"]",
"===",
"item",
",",
"\"BROKEN\"",
")",
"queue",
"[",
"TAIL",
"]",
"=",
"null",
"}",
"}",
")",
"}"
]
| Execute actions in series.
@param {Queue} queue - The queue instance.
@param {object} item - The queued item to be executed.
@returns {void} | [
"Execute",
"actions",
"in",
"series",
"."
]
| c44f4d54096287212149a7cf5031bd3e4f5a1fbe | https://github.com/mysticatea/appcache-manifest/blob/c44f4d54096287212149a7cf5031bd3e4f5a1fbe/lib/queue.js#L28-L46 |
43,478 | MattL922/greeks | greeks.js | _stdNormDensity | function _stdNormDensity(x)
{
return Math.pow(Math.E, -1 * Math.pow(x, 2) / 2) / Math.sqrt(2 * Math.PI);
} | javascript | function _stdNormDensity(x)
{
return Math.pow(Math.E, -1 * Math.pow(x, 2) / 2) / Math.sqrt(2 * Math.PI);
} | [
"function",
"_stdNormDensity",
"(",
"x",
")",
"{",
"return",
"Math",
".",
"pow",
"(",
"Math",
".",
"E",
",",
"-",
"1",
"*",
"Math",
".",
"pow",
"(",
"x",
",",
"2",
")",
"/",
"2",
")",
"/",
"Math",
".",
"sqrt",
"(",
"2",
"*",
"Math",
".",
"PI",
")",
";",
"}"
]
| Standard normal density function.
@private
@param {Number} x The value to calculate the standard normal density of
@returns {Number} The value of the standard normal density function at x | [
"Standard",
"normal",
"density",
"function",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L18-L21 |
43,479 | MattL922/greeks | greeks.js | getDelta | function getDelta(s, k, t, v, r, callPut)
{
if(callPut === "call")
{
return _callDelta(s, k, t, v, r);
}
else // put
{
return _putDelta(s, k, t, v, r);
}
} | javascript | function getDelta(s, k, t, v, r, callPut)
{
if(callPut === "call")
{
return _callDelta(s, k, t, v, r);
}
else // put
{
return _putDelta(s, k, t, v, r);
}
} | [
"function",
"getDelta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
",",
"callPut",
")",
"{",
"if",
"(",
"callPut",
"===",
"\"call\"",
")",
"{",
"return",
"_callDelta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
";",
"}",
"else",
"// put",
"{",
"return",
"_putDelta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
";",
"}",
"}"
]
| Calculates the delta of an option.
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@param {String} callPut The type of option - "call" or "put"
@returns {Number} The delta of the option | [
"Calculates",
"the",
"delta",
"of",
"an",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L34-L44 |
43,480 | MattL922/greeks | greeks.js | _callDelta | function _callDelta(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
var delta = null;
if(!isFinite(w))
{
delta = (s > k) ? 1 : 0;
}
else
{
delta = bs.stdNormCDF(w);
}
return delta;
} | javascript | function _callDelta(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
var delta = null;
if(!isFinite(w))
{
delta = (s > k) ? 1 : 0;
}
else
{
delta = bs.stdNormCDF(w);
}
return delta;
} | [
"function",
"_callDelta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"{",
"var",
"w",
"=",
"bs",
".",
"getW",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
";",
"var",
"delta",
"=",
"null",
";",
"if",
"(",
"!",
"isFinite",
"(",
"w",
")",
")",
"{",
"delta",
"=",
"(",
"s",
">",
"k",
")",
"?",
"1",
":",
"0",
";",
"}",
"else",
"{",
"delta",
"=",
"bs",
".",
"stdNormCDF",
"(",
"w",
")",
";",
"}",
"return",
"delta",
";",
"}"
]
| Calculates the delta of a call option.
@private
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@returns {Number} The delta of the call option | [
"Calculates",
"the",
"delta",
"of",
"a",
"call",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L57-L70 |
43,481 | MattL922/greeks | greeks.js | _putDelta | function _putDelta(s, k, t, v, r)
{
var delta = _callDelta(s, k, t, v, r) - 1;
return (delta == -1 && k == s) ? 0 : delta;
} | javascript | function _putDelta(s, k, t, v, r)
{
var delta = _callDelta(s, k, t, v, r) - 1;
return (delta == -1 && k == s) ? 0 : delta;
} | [
"function",
"_putDelta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"{",
"var",
"delta",
"=",
"_callDelta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"-",
"1",
";",
"return",
"(",
"delta",
"==",
"-",
"1",
"&&",
"k",
"==",
"s",
")",
"?",
"0",
":",
"delta",
";",
"}"
]
| Calculates the delta of a put option.
@private
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@returns {Number} The delta of the put option | [
"Calculates",
"the",
"delta",
"of",
"a",
"put",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L83-L87 |
43,482 | MattL922/greeks | greeks.js | getRho | function getRho(s, k, t, v, r, callPut, scale)
{
scale = scale || 100;
if(callPut === "call")
{
return _callRho(s, k, t, v, r) / scale;
}
else // put
{
return _putRho(s, k, t, v, r) / scale;
}
} | javascript | function getRho(s, k, t, v, r, callPut, scale)
{
scale = scale || 100;
if(callPut === "call")
{
return _callRho(s, k, t, v, r) / scale;
}
else // put
{
return _putRho(s, k, t, v, r) / scale;
}
} | [
"function",
"getRho",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
",",
"callPut",
",",
"scale",
")",
"{",
"scale",
"=",
"scale",
"||",
"100",
";",
"if",
"(",
"callPut",
"===",
"\"call\"",
")",
"{",
"return",
"_callRho",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"/",
"scale",
";",
"}",
"else",
"// put",
"{",
"return",
"_putRho",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"/",
"scale",
";",
"}",
"}"
]
| Calculates the rho of an option.
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@param {String} callPut The type of option - "call" or "put"
@param {String} [scale=100] The value to scale rho by (100=100BPS=1%, 10000=1BPS=.01%)
@returns {Number} The rho of the option | [
"Calculates",
"the",
"rho",
"of",
"an",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L101-L112 |
43,483 | MattL922/greeks | greeks.js | _putRho | function _putRho(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
if(!isNaN(w))
{
return -1 * k * t * Math.pow(Math.E, -1 * r * t) * bs.stdNormCDF(v * Math.sqrt(t) - w);
}
else
{
return 0;
}
} | javascript | function _putRho(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
if(!isNaN(w))
{
return -1 * k * t * Math.pow(Math.E, -1 * r * t) * bs.stdNormCDF(v * Math.sqrt(t) - w);
}
else
{
return 0;
}
} | [
"function",
"_putRho",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"{",
"var",
"w",
"=",
"bs",
".",
"getW",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"w",
")",
")",
"{",
"return",
"-",
"1",
"*",
"k",
"*",
"t",
"*",
"Math",
".",
"pow",
"(",
"Math",
".",
"E",
",",
"-",
"1",
"*",
"r",
"*",
"t",
")",
"*",
"bs",
".",
"stdNormCDF",
"(",
"v",
"*",
"Math",
".",
"sqrt",
"(",
"t",
")",
"-",
"w",
")",
";",
"}",
"else",
"{",
"return",
"0",
";",
"}",
"}"
]
| Calculates the rho of a put option.
@private
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@returns {Number} The rho of the put option | [
"Calculates",
"the",
"rho",
"of",
"a",
"put",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L149-L160 |
43,484 | MattL922/greeks | greeks.js | getVega | function getVega(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
return (isFinite(w)) ? (s * Math.sqrt(t) * _stdNormDensity(w) / 100) : 0;
} | javascript | function getVega(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
return (isFinite(w)) ? (s * Math.sqrt(t) * _stdNormDensity(w) / 100) : 0;
} | [
"function",
"getVega",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"{",
"var",
"w",
"=",
"bs",
".",
"getW",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
";",
"return",
"(",
"isFinite",
"(",
"w",
")",
")",
"?",
"(",
"s",
"*",
"Math",
".",
"sqrt",
"(",
"t",
")",
"*",
"_stdNormDensity",
"(",
"w",
")",
"/",
"100",
")",
":",
"0",
";",
"}"
]
| Calculates the vega of a call and put option.
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@returns {Number} The vega of the option | [
"Calculates",
"the",
"vega",
"of",
"a",
"call",
"and",
"put",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L172-L176 |
43,485 | MattL922/greeks | greeks.js | getTheta | function getTheta(s, k, t, v, r, callPut, scale)
{
scale = scale || 365;
if(callPut === "call")
{
return _callTheta(s, k, t, v, r) / scale;
}
else // put
{
return _putTheta(s, k, t, v, r) / scale;
}
} | javascript | function getTheta(s, k, t, v, r, callPut, scale)
{
scale = scale || 365;
if(callPut === "call")
{
return _callTheta(s, k, t, v, r) / scale;
}
else // put
{
return _putTheta(s, k, t, v, r) / scale;
}
} | [
"function",
"getTheta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
",",
"callPut",
",",
"scale",
")",
"{",
"scale",
"=",
"scale",
"||",
"365",
";",
"if",
"(",
"callPut",
"===",
"\"call\"",
")",
"{",
"return",
"_callTheta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"/",
"scale",
";",
"}",
"else",
"// put",
"{",
"return",
"_putTheta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"/",
"scale",
";",
"}",
"}"
]
| Calculates the theta of an option.
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@param {String} callPut The type of option - "call" or "put"
@param {String} [scale=365] The number of days to scale theta by - usually 365 or 252
@returns {Number} The theta of the option | [
"Calculates",
"the",
"theta",
"of",
"an",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L190-L201 |
43,486 | MattL922/greeks | greeks.js | _callTheta | function _callTheta(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
if(isFinite(w))
{
return -1 * v * s * _stdNormDensity(w) / (2 * Math.sqrt(t)) - k * r * Math.pow(Math.E, -1 * r * t) * bs.stdNormCDF(w - v * Math.sqrt(t));
}
else
{
return 0;
}
} | javascript | function _callTheta(s, k, t, v, r)
{
var w = bs.getW(s, k, t, v, r);
if(isFinite(w))
{
return -1 * v * s * _stdNormDensity(w) / (2 * Math.sqrt(t)) - k * r * Math.pow(Math.E, -1 * r * t) * bs.stdNormCDF(w - v * Math.sqrt(t));
}
else
{
return 0;
}
} | [
"function",
"_callTheta",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
"{",
"var",
"w",
"=",
"bs",
".",
"getW",
"(",
"s",
",",
"k",
",",
"t",
",",
"v",
",",
"r",
")",
";",
"if",
"(",
"isFinite",
"(",
"w",
")",
")",
"{",
"return",
"-",
"1",
"*",
"v",
"*",
"s",
"*",
"_stdNormDensity",
"(",
"w",
")",
"/",
"(",
"2",
"*",
"Math",
".",
"sqrt",
"(",
"t",
")",
")",
"-",
"k",
"*",
"r",
"*",
"Math",
".",
"pow",
"(",
"Math",
".",
"E",
",",
"-",
"1",
"*",
"r",
"*",
"t",
")",
"*",
"bs",
".",
"stdNormCDF",
"(",
"w",
"-",
"v",
"*",
"Math",
".",
"sqrt",
"(",
"t",
")",
")",
";",
"}",
"else",
"{",
"return",
"0",
";",
"}",
"}"
]
| Calculates the theta of a call option.
@private
@param {Number} s Current price of the underlying
@param {Number} k Strike price
@param {Number} t Time to experiation in years
@param {Number} v Volatility as a decimal
@param {Number} r Anual risk-free interest rate as a decimal
@returns {Number} The theta of the call option | [
"Calculates",
"the",
"theta",
"of",
"a",
"call",
"option",
"."
]
| f2369ba37de67d6f4ecddec55b647592d6580604 | https://github.com/MattL922/greeks/blob/f2369ba37de67d6f4ecddec55b647592d6580604/greeks.js#L214-L225 |
43,487 | GitbookIO/plugin-sitemap | index.js | function() {
var sitemap = sm.createSitemap({
cacheTime: 600000,
hostname: url.resolve(this.config.get('pluginsConfig.sitemap.hostname'), '/'),
urls: urls
});
var xml = sitemap.toString();
return this.output.writeFile('sitemap.xml', xml);
} | javascript | function() {
var sitemap = sm.createSitemap({
cacheTime: 600000,
hostname: url.resolve(this.config.get('pluginsConfig.sitemap.hostname'), '/'),
urls: urls
});
var xml = sitemap.toString();
return this.output.writeFile('sitemap.xml', xml);
} | [
"function",
"(",
")",
"{",
"var",
"sitemap",
"=",
"sm",
".",
"createSitemap",
"(",
"{",
"cacheTime",
":",
"600000",
",",
"hostname",
":",
"url",
".",
"resolve",
"(",
"this",
".",
"config",
".",
"get",
"(",
"'pluginsConfig.sitemap.hostname'",
")",
",",
"'/'",
")",
",",
"urls",
":",
"urls",
"}",
")",
";",
"var",
"xml",
"=",
"sitemap",
".",
"toString",
"(",
")",
";",
"return",
"this",
".",
"output",
".",
"writeFile",
"(",
"'sitemap.xml'",
",",
"xml",
")",
";",
"}"
]
| Write sitemap.xml | [
"Write",
"sitemap",
".",
"xml"
]
| dbffc38230dfd39d29002065b61e6fc7103e3db6 | https://github.com/GitbookIO/plugin-sitemap/blob/dbffc38230dfd39d29002065b61e6fc7103e3db6/index.js#L25-L35 |
|
43,488 | robinpowered/robin-js-sdk-public | lib/grid/connection.js | Connection | function Connection (gridModule) {
try {
Connection.super_.apply(this, arguments);
RbnUtil.__copyProperties(this, gridModule);
this.validate();
this.connectionStub = '/' + this.endpoint + '/' + this.identifier;
} catch (err) {
throw err;
}
} | javascript | function Connection (gridModule) {
try {
Connection.super_.apply(this, arguments);
RbnUtil.__copyProperties(this, gridModule);
this.validate();
this.connectionStub = '/' + this.endpoint + '/' + this.identifier;
} catch (err) {
throw err;
}
} | [
"function",
"Connection",
"(",
"gridModule",
")",
"{",
"try",
"{",
"Connection",
".",
"super_",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"RbnUtil",
".",
"__copyProperties",
"(",
"this",
",",
"gridModule",
")",
";",
"this",
".",
"validate",
"(",
")",
";",
"this",
".",
"connectionStub",
"=",
"'/'",
"+",
"this",
".",
"endpoint",
"+",
"'/'",
"+",
"this",
".",
"identifier",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"}"
]
| This connection class is instantiated as an object when you call the `connect`
method on a grid module. It sets up the connection to a specific point entity
on the grid and emits messages as they come in. You can also sent messages of a specific type
to this connection.
@param {Object} gridModule A previously instantiated `grid` module. | [
"This",
"connection",
"class",
"is",
"instantiated",
"as",
"an",
"object",
"when",
"you",
"call",
"the",
"connect",
"method",
"on",
"a",
"grid",
"module",
".",
"It",
"sets",
"up",
"the",
"connection",
"to",
"a",
"specific",
"point",
"entity",
"on",
"the",
"grid",
"and",
"emits",
"messages",
"as",
"they",
"come",
"in",
".",
"You",
"can",
"also",
"sent",
"messages",
"of",
"a",
"specific",
"type",
"to",
"this",
"connection",
"."
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/grid/connection.js#L23-L32 |
43,489 | robinpowered/robin-js-sdk-public | lib/api/modules/spaces.js | function (spaceIdentifier, params) {
var path = this.constructPath(constants.SPACES, spaceIdentifier);
return this.Core.GET(path, params);
} | javascript | function (spaceIdentifier, params) {
var path = this.constructPath(constants.SPACES, spaceIdentifier);
return this.Core.GET(path, params);
} | [
"function",
"(",
"spaceIdentifier",
",",
"params",
")",
"{",
"var",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"SPACES",
",",
"spaceIdentifier",
")",
";",
"return",
"this",
".",
"Core",
".",
"GET",
"(",
"path",
",",
"params",
")",
";",
"}"
]
| Get all spaces or a particular space identified by `spaceIdentifier`
@param {String|Integer} spaceIdentifier A Robin space identifier
@param {Object|undefined} params A querystring object
@return {Function} A promise | [
"Get",
"all",
"spaces",
"or",
"a",
"particular",
"space",
"identified",
"by",
"spaceIdentifier"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/spaces.js#L20-L23 |
|
43,490 | robinpowered/robin-js-sdk-public | lib/api/modules/spaces.js | function (spaceIdentifier, data) {
var path;
if (data) {
path = this.constructPath(constants.SPACES, spaceIdentifier);
return this.Core.PATCH(path, data);
} else {
return this.rejectRequest('Bad Request: Space data is required');
}
} | javascript | function (spaceIdentifier, data) {
var path;
if (data) {
path = this.constructPath(constants.SPACES, spaceIdentifier);
return this.Core.PATCH(path, data);
} else {
return this.rejectRequest('Bad Request: Space data is required');
}
} | [
"function",
"(",
"spaceIdentifier",
",",
"data",
")",
"{",
"var",
"path",
";",
"if",
"(",
"data",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"SPACES",
",",
"spaceIdentifier",
")",
";",
"return",
"this",
".",
"Core",
".",
"PATCH",
"(",
"path",
",",
"data",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: Space data is required'",
")",
";",
"}",
"}"
]
| Update a space
@param {String|Integer} spaceIdentifier A Robin space identifier
@param {Object} data A data object
@return {Function} A promise | [
"Update",
"a",
"space"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/spaces.js#L31-L39 |
|
43,491 | robinpowered/robin-js-sdk-public | lib/api/modules/spaces.js | function (spaceIdentifier, deviceIdentifier, params) {
var path;
if (spaceIdentifier) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.DEVICES, deviceIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A space identifier is required.');
}
} | javascript | function (spaceIdentifier, deviceIdentifier, params) {
var path;
if (spaceIdentifier) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.DEVICES, deviceIdentifier);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A space identifier is required.');
}
} | [
"function",
"(",
"spaceIdentifier",
",",
"deviceIdentifier",
",",
"params",
")",
"{",
"var",
"path",
";",
"if",
"(",
"spaceIdentifier",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"SPACES",
",",
"spaceIdentifier",
",",
"constants",
".",
"DEVICES",
",",
"deviceIdentifier",
")",
";",
"return",
"this",
".",
"Core",
".",
"GET",
"(",
"path",
",",
"params",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: A space identifier is required.'",
")",
";",
"}",
"}"
]
| Get all the devices for a space or a particular device identified by `deviceIdentifier`
@param {String|Integer} spaceIdentifier A Robin space identifier
@param {String|Integer|undefined} deviceIdentifier A Robin device identifier
@param {Object|undefined} params A querystring object
@return {Function} A Promise | [
"Get",
"all",
"the",
"devices",
"for",
"a",
"space",
"or",
"a",
"particular",
"device",
"identified",
"by",
"deviceIdentifier"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/spaces.js#L68-L76 |
|
43,492 | robinpowered/robin-js-sdk-public | lib/api/modules/spaces.js | function (spaceIdentifier, data) {
var path;
if (spaceIdentifier && data) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.DEVICES);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A space identifier and device data are required');
}
} | javascript | function (spaceIdentifier, data) {
var path;
if (spaceIdentifier && data) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.DEVICES);
return this.Core.POST(path, data);
} else {
return this.rejectRequest('Bad Request: A space identifier and device data are required');
}
} | [
"function",
"(",
"spaceIdentifier",
",",
"data",
")",
"{",
"var",
"path",
";",
"if",
"(",
"spaceIdentifier",
"&&",
"data",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"SPACES",
",",
"spaceIdentifier",
",",
"constants",
".",
"DEVICES",
")",
";",
"return",
"this",
".",
"Core",
".",
"POST",
"(",
"path",
",",
"data",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: A space identifier and device data are required'",
")",
";",
"}",
"}"
]
| Create a device in a space
@param {String|Integer} spaceIdentifier A Robin space identifier
@param {Object} data A data object
@return {Function} A Promise | [
"Create",
"a",
"device",
"in",
"a",
"space"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/spaces.js#L84-L92 |
|
43,493 | robinpowered/robin-js-sdk-public | lib/api/modules/spaces.js | function (spaceIdentifier, params) {
var path;
if (spaceIdentifier) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.PRESENCE);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A space identifier is required.');
}
} | javascript | function (spaceIdentifier, params) {
var path;
if (spaceIdentifier) {
path = this.constructPath(constants.SPACES, spaceIdentifier, constants.PRESENCE);
return this.Core.GET(path, params);
} else {
return this.rejectRequest('Bad Request: A space identifier is required.');
}
} | [
"function",
"(",
"spaceIdentifier",
",",
"params",
")",
"{",
"var",
"path",
";",
"if",
"(",
"spaceIdentifier",
")",
"{",
"path",
"=",
"this",
".",
"constructPath",
"(",
"constants",
".",
"SPACES",
",",
"spaceIdentifier",
",",
"constants",
".",
"PRESENCE",
")",
";",
"return",
"this",
".",
"Core",
".",
"GET",
"(",
"path",
",",
"params",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"rejectRequest",
"(",
"'Bad Request: A space identifier is required.'",
")",
";",
"}",
"}"
]
| Get all the presence for a space
@param {String|Integer} spaceIdentifier A Robin space identifier
@param {Object|undefined} params A querystring object
@return {Function} A Promise | [
"Get",
"all",
"the",
"presence",
"for",
"a",
"space"
]
| c3119f8340a728a2fba607c353893559376dd490 | https://github.com/robinpowered/robin-js-sdk-public/blob/c3119f8340a728a2fba607c353893559376dd490/lib/api/modules/spaces.js#L138-L146 |
|
43,494 | CoryG89/markedejs | index.js | function (html) {
var sep = '----------------------------------------------------------';
console.log('\n' + sep);
console.log('markedejs: HTML OUT (markedejs.DEBUG = false to silence)');
console.log(sep);
console.log(html);
console.log(sep + '\n');
} | javascript | function (html) {
var sep = '----------------------------------------------------------';
console.log('\n' + sep);
console.log('markedejs: HTML OUT (markedejs.DEBUG = false to silence)');
console.log(sep);
console.log(html);
console.log(sep + '\n');
} | [
"function",
"(",
"html",
")",
"{",
"var",
"sep",
"=",
"'----------------------------------------------------------'",
";",
"console",
".",
"log",
"(",
"'\\n'",
"+",
"sep",
")",
";",
"console",
".",
"log",
"(",
"'markedejs: HTML OUT (markedejs.DEBUG = false to silence)'",
")",
";",
"console",
".",
"log",
"(",
"sep",
")",
";",
"console",
".",
"log",
"(",
"html",
")",
";",
"console",
".",
"log",
"(",
"sep",
"+",
"'\\n'",
")",
";",
"}"
]
| Helper method to debug html output of marked engine | [
"Helper",
"method",
"to",
"debug",
"html",
"output",
"of",
"marked",
"engine"
]
| 1af6da328f7104b99caa8cd20601b9f45e24610b | https://github.com/CoryG89/markedejs/blob/1af6da328f7104b99caa8cd20601b9f45e24610b/index.js#L22-L29 |
|
43,495 | mclaeysb/geojson-polygon-self-intersections | index.js | ifIsectAddToOutput | function ifIsectAddToOutput(ring0, edge0, ring1, edge1) {
var start0 = coord[ring0][edge0];
var end0 = coord[ring0][edge0+1];
var start1 = coord[ring1][edge1];
var end1 = coord[ring1][edge1+1];
var isect = intersect(start0, end0, start1, end1);
if (isect == null) return; // discard parallels and coincidence
frac0, frac1;
if (end0[0] != start0[0]) {
var frac0 = (isect[0]-start0[0])/(end0[0]-start0[0]);
} else {
var frac0 = (isect[1]-start0[1])/(end0[1]-start0[1]);
};
if (end1[0] != start1[0]) {
var frac1 = (isect[0]-start1[0])/(end1[0]-start1[0]);
} else {
var frac1 = (isect[1]-start1[1])/(end1[1]-start1[1]);
};
// There are roughly three cases we need to deal with.
// 1. If at least one of the fracs lies outside [0,1], there is no intersection.
if (isOutside(frac0) || isOutside(frac1)) {
return; // require segment intersection
}
// 2. If both are either exactly 0 or exactly 1, this is not an intersection but just
// two edge segments sharing a common vertex.
if (isBoundaryCase(frac0) && isBoundaryCase(frac1)){
if(! options.reportVertexOnVertex) return;
}
// 3. If only one of the fractions is exactly 0 or 1, this is
// a vertex-on-edge situation.
if (isBoundaryCase(frac0) || isBoundaryCase(frac1)){
if(! options.reportVertexOnEdge) return;
}
var key = isect;
var unique = !seen[key];
if (unique) {
seen[key] = true;
}
if (filterFn) {
output.push(filterFn(isect, ring0, edge0, start0, end0, frac0, ring1, edge1, start1, end1, frac1, unique));
} else {
output.push(isect);
}
} | javascript | function ifIsectAddToOutput(ring0, edge0, ring1, edge1) {
var start0 = coord[ring0][edge0];
var end0 = coord[ring0][edge0+1];
var start1 = coord[ring1][edge1];
var end1 = coord[ring1][edge1+1];
var isect = intersect(start0, end0, start1, end1);
if (isect == null) return; // discard parallels and coincidence
frac0, frac1;
if (end0[0] != start0[0]) {
var frac0 = (isect[0]-start0[0])/(end0[0]-start0[0]);
} else {
var frac0 = (isect[1]-start0[1])/(end0[1]-start0[1]);
};
if (end1[0] != start1[0]) {
var frac1 = (isect[0]-start1[0])/(end1[0]-start1[0]);
} else {
var frac1 = (isect[1]-start1[1])/(end1[1]-start1[1]);
};
// There are roughly three cases we need to deal with.
// 1. If at least one of the fracs lies outside [0,1], there is no intersection.
if (isOutside(frac0) || isOutside(frac1)) {
return; // require segment intersection
}
// 2. If both are either exactly 0 or exactly 1, this is not an intersection but just
// two edge segments sharing a common vertex.
if (isBoundaryCase(frac0) && isBoundaryCase(frac1)){
if(! options.reportVertexOnVertex) return;
}
// 3. If only one of the fractions is exactly 0 or 1, this is
// a vertex-on-edge situation.
if (isBoundaryCase(frac0) || isBoundaryCase(frac1)){
if(! options.reportVertexOnEdge) return;
}
var key = isect;
var unique = !seen[key];
if (unique) {
seen[key] = true;
}
if (filterFn) {
output.push(filterFn(isect, ring0, edge0, start0, end0, frac0, ring1, edge1, start1, end1, frac1, unique));
} else {
output.push(isect);
}
} | [
"function",
"ifIsectAddToOutput",
"(",
"ring0",
",",
"edge0",
",",
"ring1",
",",
"edge1",
")",
"{",
"var",
"start0",
"=",
"coord",
"[",
"ring0",
"]",
"[",
"edge0",
"]",
";",
"var",
"end0",
"=",
"coord",
"[",
"ring0",
"]",
"[",
"edge0",
"+",
"1",
"]",
";",
"var",
"start1",
"=",
"coord",
"[",
"ring1",
"]",
"[",
"edge1",
"]",
";",
"var",
"end1",
"=",
"coord",
"[",
"ring1",
"]",
"[",
"edge1",
"+",
"1",
"]",
";",
"var",
"isect",
"=",
"intersect",
"(",
"start0",
",",
"end0",
",",
"start1",
",",
"end1",
")",
";",
"if",
"(",
"isect",
"==",
"null",
")",
"return",
";",
"// discard parallels and coincidence",
"frac0",
",",
"frac1",
";",
"if",
"(",
"end0",
"[",
"0",
"]",
"!=",
"start0",
"[",
"0",
"]",
")",
"{",
"var",
"frac0",
"=",
"(",
"isect",
"[",
"0",
"]",
"-",
"start0",
"[",
"0",
"]",
")",
"/",
"(",
"end0",
"[",
"0",
"]",
"-",
"start0",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"var",
"frac0",
"=",
"(",
"isect",
"[",
"1",
"]",
"-",
"start0",
"[",
"1",
"]",
")",
"/",
"(",
"end0",
"[",
"1",
"]",
"-",
"start0",
"[",
"1",
"]",
")",
";",
"}",
";",
"if",
"(",
"end1",
"[",
"0",
"]",
"!=",
"start1",
"[",
"0",
"]",
")",
"{",
"var",
"frac1",
"=",
"(",
"isect",
"[",
"0",
"]",
"-",
"start1",
"[",
"0",
"]",
")",
"/",
"(",
"end1",
"[",
"0",
"]",
"-",
"start1",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"var",
"frac1",
"=",
"(",
"isect",
"[",
"1",
"]",
"-",
"start1",
"[",
"1",
"]",
")",
"/",
"(",
"end1",
"[",
"1",
"]",
"-",
"start1",
"[",
"1",
"]",
")",
";",
"}",
";",
"// There are roughly three cases we need to deal with.",
"// 1. If at least one of the fracs lies outside [0,1], there is no intersection.",
"if",
"(",
"isOutside",
"(",
"frac0",
")",
"||",
"isOutside",
"(",
"frac1",
")",
")",
"{",
"return",
";",
"// require segment intersection",
"}",
"// 2. If both are either exactly 0 or exactly 1, this is not an intersection but just",
"// two edge segments sharing a common vertex.",
"if",
"(",
"isBoundaryCase",
"(",
"frac0",
")",
"&&",
"isBoundaryCase",
"(",
"frac1",
")",
")",
"{",
"if",
"(",
"!",
"options",
".",
"reportVertexOnVertex",
")",
"return",
";",
"}",
"// 3. If only one of the fractions is exactly 0 or 1, this is",
"// a vertex-on-edge situation.",
"if",
"(",
"isBoundaryCase",
"(",
"frac0",
")",
"||",
"isBoundaryCase",
"(",
"frac1",
")",
")",
"{",
"if",
"(",
"!",
"options",
".",
"reportVertexOnEdge",
")",
"return",
";",
"}",
"var",
"key",
"=",
"isect",
";",
"var",
"unique",
"=",
"!",
"seen",
"[",
"key",
"]",
";",
"if",
"(",
"unique",
")",
"{",
"seen",
"[",
"key",
"]",
"=",
"true",
";",
"}",
"if",
"(",
"filterFn",
")",
"{",
"output",
".",
"push",
"(",
"filterFn",
"(",
"isect",
",",
"ring0",
",",
"edge0",
",",
"start0",
",",
"end0",
",",
"frac0",
",",
"ring1",
",",
"edge1",
",",
"start1",
",",
"end1",
",",
"frac1",
",",
"unique",
")",
")",
";",
"}",
"else",
"{",
"output",
".",
"push",
"(",
"isect",
")",
";",
"}",
"}"
]
| Function to check if two edges intersect and add the intersection to the output | [
"Function",
"to",
"check",
"if",
"two",
"edges",
"intersect",
"and",
"add",
"the",
"intersection",
"to",
"the",
"output"
]
| 4a699e6042b1234034a97288a9ccdfde82d267f4 | https://github.com/mclaeysb/geojson-polygon-self-intersections/blob/4a699e6042b1234034a97288a9ccdfde82d267f4/index.js#L82-L132 |
43,496 | mclaeysb/geojson-polygon-self-intersections | index.js | rbushTreeItem | function rbushTreeItem(ring, edge) {
var start = coord[ring][edge];
var end = coord[ring][edge+1];
if (start[0] < end[0]) {
var minX = start[0], maxX = end[0];
} else {
var minX = end[0], maxX = start[0];
};
if (start[1] < end[1]) {
var minY = start[1], maxY = end[1];
} else {
var minY = end[1], maxY = start[1];
}
return {minX: minX, minY: minY, maxX: maxX, maxY: maxY, ring: ring, edge: edge};
} | javascript | function rbushTreeItem(ring, edge) {
var start = coord[ring][edge];
var end = coord[ring][edge+1];
if (start[0] < end[0]) {
var minX = start[0], maxX = end[0];
} else {
var minX = end[0], maxX = start[0];
};
if (start[1] < end[1]) {
var minY = start[1], maxY = end[1];
} else {
var minY = end[1], maxY = start[1];
}
return {minX: minX, minY: minY, maxX: maxX, maxY: maxY, ring: ring, edge: edge};
} | [
"function",
"rbushTreeItem",
"(",
"ring",
",",
"edge",
")",
"{",
"var",
"start",
"=",
"coord",
"[",
"ring",
"]",
"[",
"edge",
"]",
";",
"var",
"end",
"=",
"coord",
"[",
"ring",
"]",
"[",
"edge",
"+",
"1",
"]",
";",
"if",
"(",
"start",
"[",
"0",
"]",
"<",
"end",
"[",
"0",
"]",
")",
"{",
"var",
"minX",
"=",
"start",
"[",
"0",
"]",
",",
"maxX",
"=",
"end",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"var",
"minX",
"=",
"end",
"[",
"0",
"]",
",",
"maxX",
"=",
"start",
"[",
"0",
"]",
";",
"}",
";",
"if",
"(",
"start",
"[",
"1",
"]",
"<",
"end",
"[",
"1",
"]",
")",
"{",
"var",
"minY",
"=",
"start",
"[",
"1",
"]",
",",
"maxY",
"=",
"end",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"var",
"minY",
"=",
"end",
"[",
"1",
"]",
",",
"maxY",
"=",
"start",
"[",
"1",
"]",
";",
"}",
"return",
"{",
"minX",
":",
"minX",
",",
"minY",
":",
"minY",
",",
"maxX",
":",
"maxX",
",",
"maxY",
":",
"maxY",
",",
"ring",
":",
"ring",
",",
"edge",
":",
"edge",
"}",
";",
"}"
]
| Function to return a rbush tree item given an ring and edge number | [
"Function",
"to",
"return",
"a",
"rbush",
"tree",
"item",
"given",
"an",
"ring",
"and",
"edge",
"number"
]
| 4a699e6042b1234034a97288a9ccdfde82d267f4 | https://github.com/mclaeysb/geojson-polygon-self-intersections/blob/4a699e6042b1234034a97288a9ccdfde82d267f4/index.js#L135-L151 |
43,497 | dsfields/radargun | lib/report.js | padEnd | function padEnd(str, length) {
/* istanbul ignore next */
if (str.length >= length) return str;
return str + ' '.repeat(length - str.length);
} | javascript | function padEnd(str, length) {
/* istanbul ignore next */
if (str.length >= length) return str;
return str + ' '.repeat(length - str.length);
} | [
"function",
"padEnd",
"(",
"str",
",",
"length",
")",
"{",
"/* istanbul ignore next */",
"if",
"(",
"str",
".",
"length",
">=",
"length",
")",
"return",
"str",
";",
"return",
"str",
"+",
"' '",
".",
"repeat",
"(",
"length",
"-",
"str",
".",
"length",
")",
";",
"}"
]
| TABLE HELPERS
A String.prototype.padEnd shim.
@param {string} str
@param {number} length | [
"TABLE",
"HELPERS",
"A",
"String",
".",
"prototype",
".",
"padEnd",
"shim",
"."
]
| c0cf2730441e1e454355603c2fd7539b9d552f1a | https://github.com/dsfields/radargun/blob/c0cf2730441e1e454355603c2fd7539b9d552f1a/lib/report.js#L58-L62 |
43,498 | dsfields/radargun | lib/report.js | tableDimensions | function tableDimensions(metrics) {
const pointPad = UNIT.length + 2;
let name = 6;
let point = 5;
for (let i = 0; i < metrics.length; i++) {
const metric = metrics[i];
name = Math.max(name, metric.label.length + 2);
point = Math.max(
point,
numDigits(metric.avg) + pointPad,
numDigits(metric.min) + pointPad,
numDigits(metric.max) + pointPad
);
}
return {
name,
avg: point,
min: point,
max: point,
};
} | javascript | function tableDimensions(metrics) {
const pointPad = UNIT.length + 2;
let name = 6;
let point = 5;
for (let i = 0; i < metrics.length; i++) {
const metric = metrics[i];
name = Math.max(name, metric.label.length + 2);
point = Math.max(
point,
numDigits(metric.avg) + pointPad,
numDigits(metric.min) + pointPad,
numDigits(metric.max) + pointPad
);
}
return {
name,
avg: point,
min: point,
max: point,
};
} | [
"function",
"tableDimensions",
"(",
"metrics",
")",
"{",
"const",
"pointPad",
"=",
"UNIT",
".",
"length",
"+",
"2",
";",
"let",
"name",
"=",
"6",
";",
"let",
"point",
"=",
"5",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"metrics",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"metric",
"=",
"metrics",
"[",
"i",
"]",
";",
"name",
"=",
"Math",
".",
"max",
"(",
"name",
",",
"metric",
".",
"label",
".",
"length",
"+",
"2",
")",
";",
"point",
"=",
"Math",
".",
"max",
"(",
"point",
",",
"numDigits",
"(",
"metric",
".",
"avg",
")",
"+",
"pointPad",
",",
"numDigits",
"(",
"metric",
".",
"min",
")",
"+",
"pointPad",
",",
"numDigits",
"(",
"metric",
".",
"max",
")",
"+",
"pointPad",
")",
";",
"}",
"return",
"{",
"name",
",",
"avg",
":",
"point",
",",
"min",
":",
"point",
",",
"max",
":",
"point",
",",
"}",
";",
"}"
]
| Calculates table cell dimensions.
@param {@link FunctionMetrics[]} metrics
@returns {Dimensions} | [
"Calculates",
"table",
"cell",
"dimensions",
"."
]
| c0cf2730441e1e454355603c2fd7539b9d552f1a | https://github.com/dsfields/radargun/blob/c0cf2730441e1e454355603c2fd7539b9d552f1a/lib/report.js#L84-L106 |
43,499 | dsfields/radargun | lib/report.js | divider | function divider(dimensions, type) {
let left = BORDER_RUD;
let right = BORDER_LUD;
let line = BORDER_HORZ;
let joint = BORDER_LRUD;
switch (type) {
case 'top':
left = BORDER_RD;
right = BORDER_LD;
joint = BORDER_LRD;
break;
case 'bottom':
left = BORDER_RU;
right = BORDER_LU;
joint = BORDER_LRU;
break;
case 'header':
left = BORDER_UD_DBL_R;
right = BORDER_UD_DBL_L;
line = BORDER_DBL_HORZ;
joint = BORDER_UD_DBL_LR;
break;
default: break;
}
const {
name,
avg,
min,
max,
} = dimensions;
return left
+ line.repeat(name)
+ joint
+ line.repeat(avg)
+ joint
+ line.repeat(min)
+ joint
+ line.repeat(max)
+ right
+ '\n';
} | javascript | function divider(dimensions, type) {
let left = BORDER_RUD;
let right = BORDER_LUD;
let line = BORDER_HORZ;
let joint = BORDER_LRUD;
switch (type) {
case 'top':
left = BORDER_RD;
right = BORDER_LD;
joint = BORDER_LRD;
break;
case 'bottom':
left = BORDER_RU;
right = BORDER_LU;
joint = BORDER_LRU;
break;
case 'header':
left = BORDER_UD_DBL_R;
right = BORDER_UD_DBL_L;
line = BORDER_DBL_HORZ;
joint = BORDER_UD_DBL_LR;
break;
default: break;
}
const {
name,
avg,
min,
max,
} = dimensions;
return left
+ line.repeat(name)
+ joint
+ line.repeat(avg)
+ joint
+ line.repeat(min)
+ joint
+ line.repeat(max)
+ right
+ '\n';
} | [
"function",
"divider",
"(",
"dimensions",
",",
"type",
")",
"{",
"let",
"left",
"=",
"BORDER_RUD",
";",
"let",
"right",
"=",
"BORDER_LUD",
";",
"let",
"line",
"=",
"BORDER_HORZ",
";",
"let",
"joint",
"=",
"BORDER_LRUD",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"'top'",
":",
"left",
"=",
"BORDER_RD",
";",
"right",
"=",
"BORDER_LD",
";",
"joint",
"=",
"BORDER_LRD",
";",
"break",
";",
"case",
"'bottom'",
":",
"left",
"=",
"BORDER_RU",
";",
"right",
"=",
"BORDER_LU",
";",
"joint",
"=",
"BORDER_LRU",
";",
"break",
";",
"case",
"'header'",
":",
"left",
"=",
"BORDER_UD_DBL_R",
";",
"right",
"=",
"BORDER_UD_DBL_L",
";",
"line",
"=",
"BORDER_DBL_HORZ",
";",
"joint",
"=",
"BORDER_UD_DBL_LR",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"const",
"{",
"name",
",",
"avg",
",",
"min",
",",
"max",
",",
"}",
"=",
"dimensions",
";",
"return",
"left",
"+",
"line",
".",
"repeat",
"(",
"name",
")",
"+",
"joint",
"+",
"line",
".",
"repeat",
"(",
"avg",
")",
"+",
"joint",
"+",
"line",
".",
"repeat",
"(",
"min",
")",
"+",
"joint",
"+",
"line",
".",
"repeat",
"(",
"max",
")",
"+",
"right",
"+",
"'\\n'",
";",
"}"
]
| Creates a row divider for the given dimensions of a specific type.
@param {Dimensions} dimensions
@param {('top'|'bottom'|'header'|'row')} type
@returns {string} | [
"Creates",
"a",
"row",
"divider",
"for",
"the",
"given",
"dimensions",
"of",
"a",
"specific",
"type",
"."
]
| c0cf2730441e1e454355603c2fd7539b9d552f1a | https://github.com/dsfields/radargun/blob/c0cf2730441e1e454355603c2fd7539b9d552f1a/lib/report.js#L117-L163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.