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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
17,100
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function($root, $el, rentManager, manager) {
var $filtered;
// If selector is specified, attempt to find it.
if (manager.selector) {
if (rentManager.noel) {
$filtered = $root.filter(manager.selector);
$root = $filtered.length ? $filtered : $root.find(manager.selector);
} else {
$root = $root.find(manager.selector);
}
}
// Use the insert method if the parent's `insert` argument is true.
if (rentManager.insert) {
this.insert($root, $el);
} else {
this.html($root, $el);
}
}
|
javascript
|
function($root, $el, rentManager, manager) {
var $filtered;
// If selector is specified, attempt to find it.
if (manager.selector) {
if (rentManager.noel) {
$filtered = $root.filter(manager.selector);
$root = $filtered.length ? $filtered : $root.find(manager.selector);
} else {
$root = $root.find(manager.selector);
}
}
// Use the insert method if the parent's `insert` argument is true.
if (rentManager.insert) {
this.insert($root, $el);
} else {
this.html($root, $el);
}
}
|
[
"function",
"(",
"$root",
",",
"$el",
",",
"rentManager",
",",
"manager",
")",
"{",
"var",
"$filtered",
";",
"// If selector is specified, attempt to find it.",
"if",
"(",
"manager",
".",
"selector",
")",
"{",
"if",
"(",
"rentManager",
".",
"noel",
")",
"{",
"$filtered",
"=",
"$root",
".",
"filter",
"(",
"manager",
".",
"selector",
")",
";",
"$root",
"=",
"$filtered",
".",
"length",
"?",
"$filtered",
":",
"$root",
".",
"find",
"(",
"manager",
".",
"selector",
")",
";",
"}",
"else",
"{",
"$root",
"=",
"$root",
".",
"find",
"(",
"manager",
".",
"selector",
")",
";",
"}",
"}",
"// Use the insert method if the parent's `insert` argument is true.",
"if",
"(",
"rentManager",
".",
"insert",
")",
"{",
"this",
".",
"insert",
"(",
"$root",
",",
"$el",
")",
";",
"}",
"else",
"{",
"this",
".",
"html",
"(",
"$root",
",",
"$el",
")",
";",
"}",
"}"
] |
This is the most common way you will want to partially apply a view into a layout.
|
[
"This",
"is",
"the",
"most",
"common",
"way",
"you",
"will",
"want",
"to",
"partially",
"apply",
"a",
"view",
"into",
"a",
"layout",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L1027-L1046
|
|
17,101
|
tbranyen/backbone.layoutmanager
|
backbone.layoutmanager.js
|
function(rootView, subViews, selector) {
// Shorthand the parent manager object.
var rentManager = rootView.__manager__;
// Create a simplified manager object that tells partial() where
// place the elements.
var manager = { selector: selector };
// Get the elements to be inserted into the root view.
var els = _.reduce(subViews, function(memo, sub) {
// Check if keep is present - do boolean check in case the user
// has created a `keep` function.
var keep = typeof sub.keep === "boolean" ? sub.keep : sub.options.keep;
// If a subView is present, don't push it. This can only happen if
// `keep: true`. We do the keep check for speed as $.contains is not
// cheap.
var exists = keep && $.contains(rootView.el, sub.el);
// If there is an element and it doesn't already exist in our structure
// attach it.
if (sub.el && !exists) {
memo.push(sub.el);
}
return memo;
}, []);
// Use partial to apply the elements. Wrap els in jQ obj for cheerio.
return this.partial(rootView.$el, $(els), rentManager, manager);
}
|
javascript
|
function(rootView, subViews, selector) {
// Shorthand the parent manager object.
var rentManager = rootView.__manager__;
// Create a simplified manager object that tells partial() where
// place the elements.
var manager = { selector: selector };
// Get the elements to be inserted into the root view.
var els = _.reduce(subViews, function(memo, sub) {
// Check if keep is present - do boolean check in case the user
// has created a `keep` function.
var keep = typeof sub.keep === "boolean" ? sub.keep : sub.options.keep;
// If a subView is present, don't push it. This can only happen if
// `keep: true`. We do the keep check for speed as $.contains is not
// cheap.
var exists = keep && $.contains(rootView.el, sub.el);
// If there is an element and it doesn't already exist in our structure
// attach it.
if (sub.el && !exists) {
memo.push(sub.el);
}
return memo;
}, []);
// Use partial to apply the elements. Wrap els in jQ obj for cheerio.
return this.partial(rootView.$el, $(els), rentManager, manager);
}
|
[
"function",
"(",
"rootView",
",",
"subViews",
",",
"selector",
")",
"{",
"// Shorthand the parent manager object.",
"var",
"rentManager",
"=",
"rootView",
".",
"__manager__",
";",
"// Create a simplified manager object that tells partial() where",
"// place the elements.",
"var",
"manager",
"=",
"{",
"selector",
":",
"selector",
"}",
";",
"// Get the elements to be inserted into the root view.",
"var",
"els",
"=",
"_",
".",
"reduce",
"(",
"subViews",
",",
"function",
"(",
"memo",
",",
"sub",
")",
"{",
"// Check if keep is present - do boolean check in case the user",
"// has created a `keep` function.",
"var",
"keep",
"=",
"typeof",
"sub",
".",
"keep",
"===",
"\"boolean\"",
"?",
"sub",
".",
"keep",
":",
"sub",
".",
"options",
".",
"keep",
";",
"// If a subView is present, don't push it. This can only happen if",
"// `keep: true`. We do the keep check for speed as $.contains is not",
"// cheap.",
"var",
"exists",
"=",
"keep",
"&&",
"$",
".",
"contains",
"(",
"rootView",
".",
"el",
",",
"sub",
".",
"el",
")",
";",
"// If there is an element and it doesn't already exist in our structure",
"// attach it.",
"if",
"(",
"sub",
".",
"el",
"&&",
"!",
"exists",
")",
"{",
"memo",
".",
"push",
"(",
"sub",
".",
"el",
")",
";",
"}",
"return",
"memo",
";",
"}",
",",
"[",
"]",
")",
";",
"// Use partial to apply the elements. Wrap els in jQ obj for cheerio.",
"return",
"this",
".",
"partial",
"(",
"rootView",
".",
"$el",
",",
"$",
"(",
"els",
")",
",",
"rentManager",
",",
"manager",
")",
";",
"}"
] |
Used for inserting subViews in a single batch. This gives a small performance boost as we write to a disconnected fragment instead of to the DOM directly. Smarter browsers like Chrome will batch writes internally and layout as seldom as possible, but even in that case this provides a decent boost. jQuery will use a DocumentFragment for the batch update, but Cheerio in Node will not.
|
[
"Used",
"for",
"inserting",
"subViews",
"in",
"a",
"single",
"batch",
".",
"This",
"gives",
"a",
"small",
"performance",
"boost",
"as",
"we",
"write",
"to",
"a",
"disconnected",
"fragment",
"instead",
"of",
"to",
"the",
"DOM",
"directly",
".",
"Smarter",
"browsers",
"like",
"Chrome",
"will",
"batch",
"writes",
"internally",
"and",
"layout",
"as",
"seldom",
"as",
"possible",
"but",
"even",
"in",
"that",
"case",
"this",
"provides",
"a",
"decent",
"boost",
".",
"jQuery",
"will",
"use",
"a",
"DocumentFragment",
"for",
"the",
"batch",
"update",
"but",
"Cheerio",
"in",
"Node",
"will",
"not",
"."
] |
ba2a8ae3dc4c2519765cad3761cb59c7bb179312
|
https://github.com/tbranyen/backbone.layoutmanager/blob/ba2a8ae3dc4c2519765cad3761cb59c7bb179312/backbone.layoutmanager.js#L1060-L1088
|
|
17,102
|
simontabor/jquery-toggles
|
toggles.js
|
function(e) {
el.off('mousemove');
elSlide.off('mouseleave');
elBlob.off('mouseup');
if (!diff && opts['click'] && e.type !== 'mouseleave') {
doToggle();
return;
}
var overBound = active ? diff < -slideLimit : diff > slideLimit;
if (overBound) {
// dragged far enough, toggle
doToggle();
} else {
// reset to previous state
elInner.stop().animate({
marginLeft: active ? 0 : -width + height
}, opts['animate'] / 2, opts['easing']);
}
}
|
javascript
|
function(e) {
el.off('mousemove');
elSlide.off('mouseleave');
elBlob.off('mouseup');
if (!diff && opts['click'] && e.type !== 'mouseleave') {
doToggle();
return;
}
var overBound = active ? diff < -slideLimit : diff > slideLimit;
if (overBound) {
// dragged far enough, toggle
doToggle();
} else {
// reset to previous state
elInner.stop().animate({
marginLeft: active ? 0 : -width + height
}, opts['animate'] / 2, opts['easing']);
}
}
|
[
"function",
"(",
"e",
")",
"{",
"el",
".",
"off",
"(",
"'mousemove'",
")",
";",
"elSlide",
".",
"off",
"(",
"'mouseleave'",
")",
";",
"elBlob",
".",
"off",
"(",
"'mouseup'",
")",
";",
"if",
"(",
"!",
"diff",
"&&",
"opts",
"[",
"'click'",
"]",
"&&",
"e",
".",
"type",
"!==",
"'mouseleave'",
")",
"{",
"doToggle",
"(",
")",
";",
"return",
";",
"}",
"var",
"overBound",
"=",
"active",
"?",
"diff",
"<",
"-",
"slideLimit",
":",
"diff",
">",
"slideLimit",
";",
"if",
"(",
"overBound",
")",
"{",
"// dragged far enough, toggle",
"doToggle",
"(",
")",
";",
"}",
"else",
"{",
"// reset to previous state",
"elInner",
".",
"stop",
"(",
")",
".",
"animate",
"(",
"{",
"marginLeft",
":",
"active",
"?",
"0",
":",
"-",
"width",
"+",
"height",
"}",
",",
"opts",
"[",
"'animate'",
"]",
"/",
"2",
",",
"opts",
"[",
"'easing'",
"]",
")",
";",
"}",
"}"
] |
fired on mouseup and mouseleave events
|
[
"fired",
"on",
"mouseup",
"and",
"mouseleave",
"events"
] |
1fc33ce039dd07cbf6bcfbe35f891d1e99723347
|
https://github.com/simontabor/jquery-toggles/blob/1fc33ce039dd07cbf6bcfbe35f891d1e99723347/toggles.js#L195-L215
|
|
17,103
|
xzyfer/sass-graph
|
sass-graph.js
|
resolveSassPath
|
function resolveSassPath(sassPath, loadPaths, extensions) {
// trim sass file extensions
var re = new RegExp('(\.('+extensions.join('|')+'))$', 'i');
var sassPathName = sassPath.replace(re, '');
// check all load paths
var i, j, length = loadPaths.length, scssPath, partialPath;
for (i = 0; i < length; i++) {
for (j = 0; j < extensions.length; j++) {
scssPath = path.normalize(loadPaths[i] + '/' + sassPathName + '.' + extensions[j]);
try {
if (fs.lstatSync(scssPath).isFile()) {
return scssPath;
}
} catch (e) {}
}
// special case for _partials
for (j = 0; j < extensions.length; j++) {
scssPath = path.normalize(loadPaths[i] + '/' + sassPathName + '.' + extensions[j]);
partialPath = path.join(path.dirname(scssPath), '_' + path.basename(scssPath));
try {
if (fs.lstatSync(partialPath).isFile()) {
return partialPath;
}
} catch (e) {}
}
}
// File to import not found or unreadable so we assume this is a custom import
return false;
}
|
javascript
|
function resolveSassPath(sassPath, loadPaths, extensions) {
// trim sass file extensions
var re = new RegExp('(\.('+extensions.join('|')+'))$', 'i');
var sassPathName = sassPath.replace(re, '');
// check all load paths
var i, j, length = loadPaths.length, scssPath, partialPath;
for (i = 0; i < length; i++) {
for (j = 0; j < extensions.length; j++) {
scssPath = path.normalize(loadPaths[i] + '/' + sassPathName + '.' + extensions[j]);
try {
if (fs.lstatSync(scssPath).isFile()) {
return scssPath;
}
} catch (e) {}
}
// special case for _partials
for (j = 0; j < extensions.length; j++) {
scssPath = path.normalize(loadPaths[i] + '/' + sassPathName + '.' + extensions[j]);
partialPath = path.join(path.dirname(scssPath), '_' + path.basename(scssPath));
try {
if (fs.lstatSync(partialPath).isFile()) {
return partialPath;
}
} catch (e) {}
}
}
// File to import not found or unreadable so we assume this is a custom import
return false;
}
|
[
"function",
"resolveSassPath",
"(",
"sassPath",
",",
"loadPaths",
",",
"extensions",
")",
"{",
"// trim sass file extensions",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"'(\\.('",
"+",
"extensions",
".",
"join",
"(",
"'|'",
")",
"+",
"'))$'",
",",
"'i'",
")",
";",
"var",
"sassPathName",
"=",
"sassPath",
".",
"replace",
"(",
"re",
",",
"''",
")",
";",
"// check all load paths",
"var",
"i",
",",
"j",
",",
"length",
"=",
"loadPaths",
".",
"length",
",",
"scssPath",
",",
"partialPath",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"extensions",
".",
"length",
";",
"j",
"++",
")",
"{",
"scssPath",
"=",
"path",
".",
"normalize",
"(",
"loadPaths",
"[",
"i",
"]",
"+",
"'/'",
"+",
"sassPathName",
"+",
"'.'",
"+",
"extensions",
"[",
"j",
"]",
")",
";",
"try",
"{",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"scssPath",
")",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"scssPath",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"// special case for _partials",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"extensions",
".",
"length",
";",
"j",
"++",
")",
"{",
"scssPath",
"=",
"path",
".",
"normalize",
"(",
"loadPaths",
"[",
"i",
"]",
"+",
"'/'",
"+",
"sassPathName",
"+",
"'.'",
"+",
"extensions",
"[",
"j",
"]",
")",
";",
"partialPath",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"scssPath",
")",
",",
"'_'",
"+",
"path",
".",
"basename",
"(",
"scssPath",
")",
")",
";",
"try",
"{",
"if",
"(",
"fs",
".",
"lstatSync",
"(",
"partialPath",
")",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"partialPath",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"}",
"}",
"// File to import not found or unreadable so we assume this is a custom import",
"return",
"false",
";",
"}"
] |
resolve a sass module to a path
|
[
"resolve",
"a",
"sass",
"module",
"to",
"a",
"path"
] |
fa9fb9098b018f7c90f9f2464203ed3e1ef9da90
|
https://github.com/xzyfer/sass-graph/blob/fa9fb9098b018f7c90f9f2464203ed3e1ef9da90/sass-graph.js#L10-L40
|
17,104
|
CenterForOpenScience/ember-osf
|
addon/utils/auth.js
|
getCookieAuthUrl
|
function getCookieAuthUrl(nextUri) {
nextUri = nextUri || config.OSF.redirectUri;
const loginUri = `${config.OSF.url}login/?next=${encodeURIComponent(nextUri)}`;
return `${config.OSF.cookieLoginUrl}?service=${encodeURIComponent(loginUri)}`;
}
|
javascript
|
function getCookieAuthUrl(nextUri) {
nextUri = nextUri || config.OSF.redirectUri;
const loginUri = `${config.OSF.url}login/?next=${encodeURIComponent(nextUri)}`;
return `${config.OSF.cookieLoginUrl}?service=${encodeURIComponent(loginUri)}`;
}
|
[
"function",
"getCookieAuthUrl",
"(",
"nextUri",
")",
"{",
"nextUri",
"=",
"nextUri",
"||",
"config",
".",
"OSF",
".",
"redirectUri",
";",
"const",
"loginUri",
"=",
"`",
"${",
"config",
".",
"OSF",
".",
"url",
"}",
"${",
"encodeURIComponent",
"(",
"nextUri",
")",
"}",
"`",
";",
"return",
"`",
"${",
"config",
".",
"OSF",
".",
"cookieLoginUrl",
"}",
"${",
"encodeURIComponent",
"(",
"loginUri",
")",
"}",
"`",
";",
"}"
] |
Retrieve the correct URL for cookie-based in the OSF, including any additional configurable parameters
@private
@method getCookieAuthUrl
@param {string} nextUri Where to send the browser after a successful login request
@return {string}
|
[
"Retrieve",
"the",
"correct",
"URL",
"for",
"cookie",
"-",
"based",
"in",
"the",
"OSF",
"including",
"any",
"additional",
"configurable",
"parameters"
] |
833db862ece4f164a7932c43a90861429cb8bb98
|
https://github.com/CenterForOpenScience/ember-osf/blob/833db862ece4f164a7932c43a90861429cb8bb98/addon/utils/auth.js#L41-L45
|
17,105
|
CenterForOpenScience/ember-osf
|
addon/utils/discover-page.js
|
buildQueryBody
|
function buildQueryBody(queryParams, filters, queryParamsChanged) {
let query = {
query_string: {
query: queryParams.q || '*',
},
};
if (filters.length) {
query = {
bool: {
must: query,
filter: filters,
},
};
}
const queryBody = {
query,
from: (queryParams.page - 1) * queryParams.size,
aggregations: elasticAggregations,
};
let sortValue = queryParams.sort;
if (!queryParamsChanged) {
sortValue = '-date_modified';
}
if (sortValue) {
const sortBy = {};
sortBy[sortValue.replace(/^-/, '')] = sortValue[0] === '-' ? 'desc' : 'asc';
queryBody.sort = sortBy;
}
return JSON.stringify(queryBody);
}
|
javascript
|
function buildQueryBody(queryParams, filters, queryParamsChanged) {
let query = {
query_string: {
query: queryParams.q || '*',
},
};
if (filters.length) {
query = {
bool: {
must: query,
filter: filters,
},
};
}
const queryBody = {
query,
from: (queryParams.page - 1) * queryParams.size,
aggregations: elasticAggregations,
};
let sortValue = queryParams.sort;
if (!queryParamsChanged) {
sortValue = '-date_modified';
}
if (sortValue) {
const sortBy = {};
sortBy[sortValue.replace(/^-/, '')] = sortValue[0] === '-' ? 'desc' : 'asc';
queryBody.sort = sortBy;
}
return JSON.stringify(queryBody);
}
|
[
"function",
"buildQueryBody",
"(",
"queryParams",
",",
"filters",
",",
"queryParamsChanged",
")",
"{",
"let",
"query",
"=",
"{",
"query_string",
":",
"{",
"query",
":",
"queryParams",
".",
"q",
"||",
"'*'",
",",
"}",
",",
"}",
";",
"if",
"(",
"filters",
".",
"length",
")",
"{",
"query",
"=",
"{",
"bool",
":",
"{",
"must",
":",
"query",
",",
"filter",
":",
"filters",
",",
"}",
",",
"}",
";",
"}",
"const",
"queryBody",
"=",
"{",
"query",
",",
"from",
":",
"(",
"queryParams",
".",
"page",
"-",
"1",
")",
"*",
"queryParams",
".",
"size",
",",
"aggregations",
":",
"elasticAggregations",
",",
"}",
";",
"let",
"sortValue",
"=",
"queryParams",
".",
"sort",
";",
"if",
"(",
"!",
"queryParamsChanged",
")",
"{",
"sortValue",
"=",
"'-date_modified'",
";",
"}",
"if",
"(",
"sortValue",
")",
"{",
"const",
"sortBy",
"=",
"{",
"}",
";",
"sortBy",
"[",
"sortValue",
".",
"replace",
"(",
"/",
"^-",
"/",
",",
"''",
")",
"]",
"=",
"sortValue",
"[",
"0",
"]",
"===",
"'-'",
"?",
"'desc'",
":",
"'asc'",
";",
"queryBody",
".",
"sort",
"=",
"sortBy",
";",
"}",
"return",
"JSON",
".",
"stringify",
"(",
"queryBody",
")",
";",
"}"
] |
Construct queryBody for OSF facets
@method buildQueryBody
@param {Object} queryParams - Ember Parachute queryParams
@param {List} filters - Filters for query body
@param {Boolean} queryParamsChanged - Whether or not any queryParams differ from their defaults
@return {String} queryBody - Stringified queryBody
|
[
"Construct",
"queryBody",
"for",
"OSF",
"facets"
] |
833db862ece4f164a7932c43a90861429cb8bb98
|
https://github.com/CenterForOpenScience/ember-osf/blob/833db862ece4f164a7932c43a90861429cb8bb98/addon/utils/discover-page.js#L64-L98
|
17,106
|
CenterForOpenScience/ember-osf
|
addon/utils/discover-page.js
|
sortContributors
|
function sortContributors(contributors) {
return contributors
.sort((b, a) => (b.order_cited || -1) - (a.order_cited || -1))
.map(contributor => ({
users: Object.keys(contributor).reduce(
(acc, key) => Ember.assign(acc, { [Ember.String.camelize(key)]: contributor[key] }),
{ bibliographic: contributor.relation !== 'contributor' }
)
}));
}
|
javascript
|
function sortContributors(contributors) {
return contributors
.sort((b, a) => (b.order_cited || -1) - (a.order_cited || -1))
.map(contributor => ({
users: Object.keys(contributor).reduce(
(acc, key) => Ember.assign(acc, { [Ember.String.camelize(key)]: contributor[key] }),
{ bibliographic: contributor.relation !== 'contributor' }
)
}));
}
|
[
"function",
"sortContributors",
"(",
"contributors",
")",
"{",
"return",
"contributors",
".",
"sort",
"(",
"(",
"b",
",",
"a",
")",
"=>",
"(",
"b",
".",
"order_cited",
"||",
"-",
"1",
")",
"-",
"(",
"a",
".",
"order_cited",
"||",
"-",
"1",
")",
")",
".",
"map",
"(",
"contributor",
"=>",
"(",
"{",
"users",
":",
"Object",
".",
"keys",
"(",
"contributor",
")",
".",
"reduce",
"(",
"(",
"acc",
",",
"key",
")",
"=>",
"Ember",
".",
"assign",
"(",
"acc",
",",
"{",
"[",
"Ember",
".",
"String",
".",
"camelize",
"(",
"key",
")",
"]",
":",
"contributor",
"[",
"key",
"]",
"}",
")",
",",
"{",
"bibliographic",
":",
"contributor",
".",
"relation",
"!==",
"'contributor'",
"}",
")",
"}",
")",
")",
";",
"}"
] |
Sort contributors by order cited and set bibliographic property
@private
@method sortContributors
@param {List} contributors - list.contributors from a SHARE ES result
@return {List}
|
[
"Sort",
"contributors",
"by",
"order",
"cited",
"and",
"set",
"bibliographic",
"property"
] |
833db862ece4f164a7932c43a90861429cb8bb98
|
https://github.com/CenterForOpenScience/ember-osf/blob/833db862ece4f164a7932c43a90861429cb8bb98/addon/utils/discover-page.js#L154-L163
|
17,107
|
CenterForOpenScience/ember-osf
|
addon/utils/discover-page.js
|
transformShareData
|
function transformShareData(result) {
const transformedResult = Ember.assign(result._source, {
id: result._id,
type: 'elastic-search-result',
workType: result._source['@type'],
abstract: result._source.description,
subjects: result._source.subjects.map(each => ({ text: each })),
subject_synonyms: result._source.subject_synonyms.map(each => ({ text: each })),
providers: result._source.sources.map(item => ({
name: item,
})),
hyperLinks: [ // Links that are hyperlinks from hit._source.lists.links
{
type: 'share',
url: `${config.OSF.shareBaseUrl}${result._source.type.replace(/ /g, '')}/${result._id}`,
},
],
infoLinks: [], // Links that are not hyperlinks hit._source.lists.links
registrationType: result._source.registration_type, // for registries
});
result._source.identifiers.forEach(function(identifier) {
if (identifier.startsWith('http://')) {
transformedResult.hyperLinks.push({ url: identifier });
} else {
const spl = identifier.split('://');
const [type, uri] = spl;
transformedResult.infoLinks.push({ type, uri });
}
});
transformedResult.contributors = transformedResult.lists.contributors ?
sortContributors(transformedResult.lists.contributors) :
[];
// Temporary fix to handle half way migrated SHARE ES
// Only false will result in a false here.
transformedResult.contributors.map((contributor) => {
const contrib = contributor;
contrib.users.bibliographic = !(contributor.users.bibliographic === false);
return contrib;
});
return transformedResult;
}
|
javascript
|
function transformShareData(result) {
const transformedResult = Ember.assign(result._source, {
id: result._id,
type: 'elastic-search-result',
workType: result._source['@type'],
abstract: result._source.description,
subjects: result._source.subjects.map(each => ({ text: each })),
subject_synonyms: result._source.subject_synonyms.map(each => ({ text: each })),
providers: result._source.sources.map(item => ({
name: item,
})),
hyperLinks: [ // Links that are hyperlinks from hit._source.lists.links
{
type: 'share',
url: `${config.OSF.shareBaseUrl}${result._source.type.replace(/ /g, '')}/${result._id}`,
},
],
infoLinks: [], // Links that are not hyperlinks hit._source.lists.links
registrationType: result._source.registration_type, // for registries
});
result._source.identifiers.forEach(function(identifier) {
if (identifier.startsWith('http://')) {
transformedResult.hyperLinks.push({ url: identifier });
} else {
const spl = identifier.split('://');
const [type, uri] = spl;
transformedResult.infoLinks.push({ type, uri });
}
});
transformedResult.contributors = transformedResult.lists.contributors ?
sortContributors(transformedResult.lists.contributors) :
[];
// Temporary fix to handle half way migrated SHARE ES
// Only false will result in a false here.
transformedResult.contributors.map((contributor) => {
const contrib = contributor;
contrib.users.bibliographic = !(contributor.users.bibliographic === false);
return contrib;
});
return transformedResult;
}
|
[
"function",
"transformShareData",
"(",
"result",
")",
"{",
"const",
"transformedResult",
"=",
"Ember",
".",
"assign",
"(",
"result",
".",
"_source",
",",
"{",
"id",
":",
"result",
".",
"_id",
",",
"type",
":",
"'elastic-search-result'",
",",
"workType",
":",
"result",
".",
"_source",
"[",
"'@type'",
"]",
",",
"abstract",
":",
"result",
".",
"_source",
".",
"description",
",",
"subjects",
":",
"result",
".",
"_source",
".",
"subjects",
".",
"map",
"(",
"each",
"=>",
"(",
"{",
"text",
":",
"each",
"}",
")",
")",
",",
"subject_synonyms",
":",
"result",
".",
"_source",
".",
"subject_synonyms",
".",
"map",
"(",
"each",
"=>",
"(",
"{",
"text",
":",
"each",
"}",
")",
")",
",",
"providers",
":",
"result",
".",
"_source",
".",
"sources",
".",
"map",
"(",
"item",
"=>",
"(",
"{",
"name",
":",
"item",
",",
"}",
")",
")",
",",
"hyperLinks",
":",
"[",
"// Links that are hyperlinks from hit._source.lists.links",
"{",
"type",
":",
"'share'",
",",
"url",
":",
"`",
"${",
"config",
".",
"OSF",
".",
"shareBaseUrl",
"}",
"${",
"result",
".",
"_source",
".",
"type",
".",
"replace",
"(",
"/",
" ",
"/",
"g",
",",
"''",
")",
"}",
"${",
"result",
".",
"_id",
"}",
"`",
",",
"}",
",",
"]",
",",
"infoLinks",
":",
"[",
"]",
",",
"// Links that are not hyperlinks hit._source.lists.links",
"registrationType",
":",
"result",
".",
"_source",
".",
"registration_type",
",",
"// for registries",
"}",
")",
";",
"result",
".",
"_source",
".",
"identifiers",
".",
"forEach",
"(",
"function",
"(",
"identifier",
")",
"{",
"if",
"(",
"identifier",
".",
"startsWith",
"(",
"'http://'",
")",
")",
"{",
"transformedResult",
".",
"hyperLinks",
".",
"push",
"(",
"{",
"url",
":",
"identifier",
"}",
")",
";",
"}",
"else",
"{",
"const",
"spl",
"=",
"identifier",
".",
"split",
"(",
"'://'",
")",
";",
"const",
"[",
"type",
",",
"uri",
"]",
"=",
"spl",
";",
"transformedResult",
".",
"infoLinks",
".",
"push",
"(",
"{",
"type",
",",
"uri",
"}",
")",
";",
"}",
"}",
")",
";",
"transformedResult",
".",
"contributors",
"=",
"transformedResult",
".",
"lists",
".",
"contributors",
"?",
"sortContributors",
"(",
"transformedResult",
".",
"lists",
".",
"contributors",
")",
":",
"[",
"]",
";",
"// Temporary fix to handle half way migrated SHARE ES",
"// Only false will result in a false here.",
"transformedResult",
".",
"contributors",
".",
"map",
"(",
"(",
"contributor",
")",
"=>",
"{",
"const",
"contrib",
"=",
"contributor",
";",
"contrib",
".",
"users",
".",
"bibliographic",
"=",
"!",
"(",
"contributor",
".",
"users",
".",
"bibliographic",
"===",
"false",
")",
";",
"return",
"contrib",
";",
"}",
")",
";",
"return",
"transformedResult",
";",
"}"
] |
Make share data look like apiv2 preprints data and pull out identifiers
@private
@method transformShareData
@param {Object} result - hit from a SHARE ES
@return {Object}
|
[
"Make",
"share",
"data",
"look",
"like",
"apiv2",
"preprints",
"data",
"and",
"pull",
"out",
"identifiers"
] |
833db862ece4f164a7932c43a90861429cb8bb98
|
https://github.com/CenterForOpenScience/ember-osf/blob/833db862ece4f164a7932c43a90861429cb8bb98/addon/utils/discover-page.js#L173-L217
|
17,108
|
apvarun/toastify-js
|
src/toastify.js
|
function(options) {
// Verifying and validating the input object
if (!options) {
options = {};
}
// Creating the options object
this.options = {};
// Validating the options
this.options.text = options.text || "Hi there!"; // Display message
this.options.duration = options.duration || 3000; // Display duration
this.options.selector = options.selector; // Parent selector
this.options.callback = options.callback || function() {}; // Callback after display
this.options.destination = options.destination; // On-click destination
this.options.newWindow = options.newWindow || false; // Open destination in new window
this.options.close = options.close || false; // Show toast close icon
this.options.gravity = options.gravity == "bottom" ? "toastify-bottom" : "toastify-top"; // toast position - top or bottom
this.options.positionLeft = options.positionLeft || false; // toast position - left or right
this.options.backgroundColor = options.backgroundColor; // toast background color
this.options.avatar = options.avatar || ""; // toast position - left or right
this.options.className = options.className || ""; // additional class names for the toast
// Returning the current object for chaining functions
return this;
}
|
javascript
|
function(options) {
// Verifying and validating the input object
if (!options) {
options = {};
}
// Creating the options object
this.options = {};
// Validating the options
this.options.text = options.text || "Hi there!"; // Display message
this.options.duration = options.duration || 3000; // Display duration
this.options.selector = options.selector; // Parent selector
this.options.callback = options.callback || function() {}; // Callback after display
this.options.destination = options.destination; // On-click destination
this.options.newWindow = options.newWindow || false; // Open destination in new window
this.options.close = options.close || false; // Show toast close icon
this.options.gravity = options.gravity == "bottom" ? "toastify-bottom" : "toastify-top"; // toast position - top or bottom
this.options.positionLeft = options.positionLeft || false; // toast position - left or right
this.options.backgroundColor = options.backgroundColor; // toast background color
this.options.avatar = options.avatar || ""; // toast position - left or right
this.options.className = options.className || ""; // additional class names for the toast
// Returning the current object for chaining functions
return this;
}
|
[
"function",
"(",
"options",
")",
"{",
"// Verifying and validating the input object",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"// Creating the options object",
"this",
".",
"options",
"=",
"{",
"}",
";",
"// Validating the options",
"this",
".",
"options",
".",
"text",
"=",
"options",
".",
"text",
"||",
"\"Hi there!\"",
";",
"// Display message",
"this",
".",
"options",
".",
"duration",
"=",
"options",
".",
"duration",
"||",
"3000",
";",
"// Display duration",
"this",
".",
"options",
".",
"selector",
"=",
"options",
".",
"selector",
";",
"// Parent selector",
"this",
".",
"options",
".",
"callback",
"=",
"options",
".",
"callback",
"||",
"function",
"(",
")",
"{",
"}",
";",
"// Callback after display",
"this",
".",
"options",
".",
"destination",
"=",
"options",
".",
"destination",
";",
"// On-click destination",
"this",
".",
"options",
".",
"newWindow",
"=",
"options",
".",
"newWindow",
"||",
"false",
";",
"// Open destination in new window",
"this",
".",
"options",
".",
"close",
"=",
"options",
".",
"close",
"||",
"false",
";",
"// Show toast close icon",
"this",
".",
"options",
".",
"gravity",
"=",
"options",
".",
"gravity",
"==",
"\"bottom\"",
"?",
"\"toastify-bottom\"",
":",
"\"toastify-top\"",
";",
"// toast position - top or bottom",
"this",
".",
"options",
".",
"positionLeft",
"=",
"options",
".",
"positionLeft",
"||",
"false",
";",
"// toast position - left or right",
"this",
".",
"options",
".",
"backgroundColor",
"=",
"options",
".",
"backgroundColor",
";",
"// toast background color",
"this",
".",
"options",
".",
"avatar",
"=",
"options",
".",
"avatar",
"||",
"\"\"",
";",
"// toast position - left or right",
"this",
".",
"options",
".",
"className",
"=",
"options",
".",
"className",
"||",
"\"\"",
";",
"// additional class names for the toast",
"// Returning the current object for chaining functions",
"return",
"this",
";",
"}"
] |
Initializing the object with required parameters
|
[
"Initializing",
"the",
"object",
"with",
"required",
"parameters"
] |
ee56ec7a185e731cae0868e50b0711786c851384
|
https://github.com/apvarun/toastify-js/blob/ee56ec7a185e731cae0868e50b0711786c851384/src/toastify.js#L31-L56
|
|
17,109
|
apvarun/toastify-js
|
src/toastify.js
|
function() {
// Validating if the options are defined
if (!this.options) {
throw "Toastify is not initialized";
}
// Creating the DOM object
var divElement = document.createElement("div");
divElement.className = "toastify on " + this.options.className;
// Positioning toast to left or right
if (this.options.positionLeft === true) {
divElement.className += " toastify-left";
} else {
divElement.className += " toastify-right";
}
// Assigning gravity of element
divElement.className += " " + this.options.gravity;
if (this.options.backgroundColor) {
divElement.style.background = this.options.backgroundColor;
}
// Adding the toast message
divElement.innerHTML = this.options.text;
if (this.options.avatar !== "") {
var avatarElement = document.createElement("img");
avatarElement.src = this.options.avatar;
avatarElement.className = "toastify-avatar";
if (this.options.positionLeft === true) {
// Adding close icon on the left of content
divElement.appendChild(avatarElement);
} else {
// Adding close icon on the right of content
divElement.insertAdjacentElement("beforeend", avatarElement);
}
}
// Adding a close icon to the toast
if (this.options.close === true) {
// Create a span for close element
var closeElement = document.createElement("span");
closeElement.innerHTML = "✖";
closeElement.className = "toast-close";
// Triggering the removal of toast from DOM on close click
closeElement.addEventListener(
"click",
function(event) {
event.stopPropagation();
this.removeElement(event.target.parentElement);
window.clearTimeout(event.target.parentElement.timeOutValue);
}.bind(this)
);
//Calculating screen width
var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
// Adding the close icon to the toast element
// Display on the right if screen width is less than or equal to 360px
if (this.options.positionLeft === true && width > 360) {
// Adding close icon on the left of content
divElement.insertAdjacentElement("afterbegin", closeElement);
} else {
// Adding close icon on the right of content
divElement.appendChild(closeElement);
}
}
// Adding an on-click destination path
if (typeof this.options.destination !== "undefined") {
divElement.addEventListener(
"click",
function(event) {
event.stopPropagation();
if (this.options.newWindow === true) {
window.open(this.options.destination, "_blank");
} else {
window.location = this.options.destination;
}
}.bind(this)
);
}
// Returning the generated element
return divElement;
}
|
javascript
|
function() {
// Validating if the options are defined
if (!this.options) {
throw "Toastify is not initialized";
}
// Creating the DOM object
var divElement = document.createElement("div");
divElement.className = "toastify on " + this.options.className;
// Positioning toast to left or right
if (this.options.positionLeft === true) {
divElement.className += " toastify-left";
} else {
divElement.className += " toastify-right";
}
// Assigning gravity of element
divElement.className += " " + this.options.gravity;
if (this.options.backgroundColor) {
divElement.style.background = this.options.backgroundColor;
}
// Adding the toast message
divElement.innerHTML = this.options.text;
if (this.options.avatar !== "") {
var avatarElement = document.createElement("img");
avatarElement.src = this.options.avatar;
avatarElement.className = "toastify-avatar";
if (this.options.positionLeft === true) {
// Adding close icon on the left of content
divElement.appendChild(avatarElement);
} else {
// Adding close icon on the right of content
divElement.insertAdjacentElement("beforeend", avatarElement);
}
}
// Adding a close icon to the toast
if (this.options.close === true) {
// Create a span for close element
var closeElement = document.createElement("span");
closeElement.innerHTML = "✖";
closeElement.className = "toast-close";
// Triggering the removal of toast from DOM on close click
closeElement.addEventListener(
"click",
function(event) {
event.stopPropagation();
this.removeElement(event.target.parentElement);
window.clearTimeout(event.target.parentElement.timeOutValue);
}.bind(this)
);
//Calculating screen width
var width = window.innerWidth > 0 ? window.innerWidth : screen.width;
// Adding the close icon to the toast element
// Display on the right if screen width is less than or equal to 360px
if (this.options.positionLeft === true && width > 360) {
// Adding close icon on the left of content
divElement.insertAdjacentElement("afterbegin", closeElement);
} else {
// Adding close icon on the right of content
divElement.appendChild(closeElement);
}
}
// Adding an on-click destination path
if (typeof this.options.destination !== "undefined") {
divElement.addEventListener(
"click",
function(event) {
event.stopPropagation();
if (this.options.newWindow === true) {
window.open(this.options.destination, "_blank");
} else {
window.location = this.options.destination;
}
}.bind(this)
);
}
// Returning the generated element
return divElement;
}
|
[
"function",
"(",
")",
"{",
"// Validating if the options are defined",
"if",
"(",
"!",
"this",
".",
"options",
")",
"{",
"throw",
"\"Toastify is not initialized\"",
";",
"}",
"// Creating the DOM object",
"var",
"divElement",
"=",
"document",
".",
"createElement",
"(",
"\"div\"",
")",
";",
"divElement",
".",
"className",
"=",
"\"toastify on \"",
"+",
"this",
".",
"options",
".",
"className",
";",
"// Positioning toast to left or right",
"if",
"(",
"this",
".",
"options",
".",
"positionLeft",
"===",
"true",
")",
"{",
"divElement",
".",
"className",
"+=",
"\" toastify-left\"",
";",
"}",
"else",
"{",
"divElement",
".",
"className",
"+=",
"\" toastify-right\"",
";",
"}",
"// Assigning gravity of element",
"divElement",
".",
"className",
"+=",
"\" \"",
"+",
"this",
".",
"options",
".",
"gravity",
";",
"if",
"(",
"this",
".",
"options",
".",
"backgroundColor",
")",
"{",
"divElement",
".",
"style",
".",
"background",
"=",
"this",
".",
"options",
".",
"backgroundColor",
";",
"}",
"// Adding the toast message",
"divElement",
".",
"innerHTML",
"=",
"this",
".",
"options",
".",
"text",
";",
"if",
"(",
"this",
".",
"options",
".",
"avatar",
"!==",
"\"\"",
")",
"{",
"var",
"avatarElement",
"=",
"document",
".",
"createElement",
"(",
"\"img\"",
")",
";",
"avatarElement",
".",
"src",
"=",
"this",
".",
"options",
".",
"avatar",
";",
"avatarElement",
".",
"className",
"=",
"\"toastify-avatar\"",
";",
"if",
"(",
"this",
".",
"options",
".",
"positionLeft",
"===",
"true",
")",
"{",
"// Adding close icon on the left of content",
"divElement",
".",
"appendChild",
"(",
"avatarElement",
")",
";",
"}",
"else",
"{",
"// Adding close icon on the right of content",
"divElement",
".",
"insertAdjacentElement",
"(",
"\"beforeend\"",
",",
"avatarElement",
")",
";",
"}",
"}",
"// Adding a close icon to the toast",
"if",
"(",
"this",
".",
"options",
".",
"close",
"===",
"true",
")",
"{",
"// Create a span for close element",
"var",
"closeElement",
"=",
"document",
".",
"createElement",
"(",
"\"span\"",
")",
";",
"closeElement",
".",
"innerHTML",
"=",
"\"✖\"",
";",
"closeElement",
".",
"className",
"=",
"\"toast-close\"",
";",
"// Triggering the removal of toast from DOM on close click",
"closeElement",
".",
"addEventListener",
"(",
"\"click\"",
",",
"function",
"(",
"event",
")",
"{",
"event",
".",
"stopPropagation",
"(",
")",
";",
"this",
".",
"removeElement",
"(",
"event",
".",
"target",
".",
"parentElement",
")",
";",
"window",
".",
"clearTimeout",
"(",
"event",
".",
"target",
".",
"parentElement",
".",
"timeOutValue",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"//Calculating screen width",
"var",
"width",
"=",
"window",
".",
"innerWidth",
">",
"0",
"?",
"window",
".",
"innerWidth",
":",
"screen",
".",
"width",
";",
"// Adding the close icon to the toast element",
"// Display on the right if screen width is less than or equal to 360px",
"if",
"(",
"this",
".",
"options",
".",
"positionLeft",
"===",
"true",
"&&",
"width",
">",
"360",
")",
"{",
"// Adding close icon on the left of content",
"divElement",
".",
"insertAdjacentElement",
"(",
"\"afterbegin\"",
",",
"closeElement",
")",
";",
"}",
"else",
"{",
"// Adding close icon on the right of content",
"divElement",
".",
"appendChild",
"(",
"closeElement",
")",
";",
"}",
"}",
"// Adding an on-click destination path",
"if",
"(",
"typeof",
"this",
".",
"options",
".",
"destination",
"!==",
"\"undefined\"",
")",
"{",
"divElement",
".",
"addEventListener",
"(",
"\"click\"",
",",
"function",
"(",
"event",
")",
"{",
"event",
".",
"stopPropagation",
"(",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"newWindow",
"===",
"true",
")",
"{",
"window",
".",
"open",
"(",
"this",
".",
"options",
".",
"destination",
",",
"\"_blank\"",
")",
";",
"}",
"else",
"{",
"window",
".",
"location",
"=",
"this",
".",
"options",
".",
"destination",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"// Returning the generated element",
"return",
"divElement",
";",
"}"
] |
Building the DOM element
|
[
"Building",
"the",
"DOM",
"element"
] |
ee56ec7a185e731cae0868e50b0711786c851384
|
https://github.com/apvarun/toastify-js/blob/ee56ec7a185e731cae0868e50b0711786c851384/src/toastify.js#L59-L150
|
|
17,110
|
apvarun/toastify-js
|
src/toastify.js
|
function() {
// Creating the DOM object for the toast
var toastElement = this.buildToast();
// Getting the root element to with the toast needs to be added
var rootElement;
if (typeof this.options.selector === "undefined") {
rootElement = document.body;
} else {
rootElement = document.getElementById(this.options.selector);
}
// Validating if root element is present in DOM
if (!rootElement) {
throw "Root element is not defined";
}
// Adding the DOM element
rootElement.insertBefore(toastElement, rootElement.firstChild);
// Repositioning the toasts in case multiple toasts are present
Toastify.reposition();
toastElement.timeOutValue = window.setTimeout(
function() {
// Remove the toast from DOM
this.removeElement(toastElement);
}.bind(this),
this.options.duration
); // Binding `this` for function invocation
// Supporting function chaining
return this;
}
|
javascript
|
function() {
// Creating the DOM object for the toast
var toastElement = this.buildToast();
// Getting the root element to with the toast needs to be added
var rootElement;
if (typeof this.options.selector === "undefined") {
rootElement = document.body;
} else {
rootElement = document.getElementById(this.options.selector);
}
// Validating if root element is present in DOM
if (!rootElement) {
throw "Root element is not defined";
}
// Adding the DOM element
rootElement.insertBefore(toastElement, rootElement.firstChild);
// Repositioning the toasts in case multiple toasts are present
Toastify.reposition();
toastElement.timeOutValue = window.setTimeout(
function() {
// Remove the toast from DOM
this.removeElement(toastElement);
}.bind(this),
this.options.duration
); // Binding `this` for function invocation
// Supporting function chaining
return this;
}
|
[
"function",
"(",
")",
"{",
"// Creating the DOM object for the toast",
"var",
"toastElement",
"=",
"this",
".",
"buildToast",
"(",
")",
";",
"// Getting the root element to with the toast needs to be added",
"var",
"rootElement",
";",
"if",
"(",
"typeof",
"this",
".",
"options",
".",
"selector",
"===",
"\"undefined\"",
")",
"{",
"rootElement",
"=",
"document",
".",
"body",
";",
"}",
"else",
"{",
"rootElement",
"=",
"document",
".",
"getElementById",
"(",
"this",
".",
"options",
".",
"selector",
")",
";",
"}",
"// Validating if root element is present in DOM",
"if",
"(",
"!",
"rootElement",
")",
"{",
"throw",
"\"Root element is not defined\"",
";",
"}",
"// Adding the DOM element",
"rootElement",
".",
"insertBefore",
"(",
"toastElement",
",",
"rootElement",
".",
"firstChild",
")",
";",
"// Repositioning the toasts in case multiple toasts are present",
"Toastify",
".",
"reposition",
"(",
")",
";",
"toastElement",
".",
"timeOutValue",
"=",
"window",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"// Remove the toast from DOM",
"this",
".",
"removeElement",
"(",
"toastElement",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"this",
".",
"options",
".",
"duration",
")",
";",
"// Binding `this` for function invocation",
"// Supporting function chaining",
"return",
"this",
";",
"}"
] |
Displaying the toast
|
[
"Displaying",
"the",
"toast"
] |
ee56ec7a185e731cae0868e50b0711786c851384
|
https://github.com/apvarun/toastify-js/blob/ee56ec7a185e731cae0868e50b0711786c851384/src/toastify.js#L153-L186
|
|
17,111
|
apvarun/toastify-js
|
src/toastify.js
|
function(toastElement) {
// Hiding the element
// toastElement.classList.remove("on");
toastElement.className = toastElement.className.replace(" on", "");
// Removing the element from DOM after transition end
window.setTimeout(
function() {
// Remove the elemenf from the DOM
toastElement.parentNode.removeChild(toastElement);
// Calling the callback function
this.options.callback.call(toastElement);
// Repositioning the toasts again
Toastify.reposition();
}.bind(this),
400
); // Binding `this` for function invocation
}
|
javascript
|
function(toastElement) {
// Hiding the element
// toastElement.classList.remove("on");
toastElement.className = toastElement.className.replace(" on", "");
// Removing the element from DOM after transition end
window.setTimeout(
function() {
// Remove the elemenf from the DOM
toastElement.parentNode.removeChild(toastElement);
// Calling the callback function
this.options.callback.call(toastElement);
// Repositioning the toasts again
Toastify.reposition();
}.bind(this),
400
); // Binding `this` for function invocation
}
|
[
"function",
"(",
"toastElement",
")",
"{",
"// Hiding the element",
"// toastElement.classList.remove(\"on\");",
"toastElement",
".",
"className",
"=",
"toastElement",
".",
"className",
".",
"replace",
"(",
"\" on\"",
",",
"\"\"",
")",
";",
"// Removing the element from DOM after transition end",
"window",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"// Remove the elemenf from the DOM",
"toastElement",
".",
"parentNode",
".",
"removeChild",
"(",
"toastElement",
")",
";",
"// Calling the callback function",
"this",
".",
"options",
".",
"callback",
".",
"call",
"(",
"toastElement",
")",
";",
"// Repositioning the toasts again",
"Toastify",
".",
"reposition",
"(",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
",",
"400",
")",
";",
"// Binding `this` for function invocation",
"}"
] |
Removing the element from the DOM
|
[
"Removing",
"the",
"element",
"from",
"the",
"DOM"
] |
ee56ec7a185e731cae0868e50b0711786c851384
|
https://github.com/apvarun/toastify-js/blob/ee56ec7a185e731cae0868e50b0711786c851384/src/toastify.js#L189-L208
|
|
17,112
|
michaelleeallen/mocha-junit-reporter
|
index.js
|
getSetting
|
function getSetting(value, key, defaultVal, transform) {
if (process.env[key] !== undefined) {
var envVal = process.env[key];
return (typeof transform === 'function') ? transform(envVal) : envVal;
}
if (value !== undefined) {
return value;
}
return defaultVal;
}
|
javascript
|
function getSetting(value, key, defaultVal, transform) {
if (process.env[key] !== undefined) {
var envVal = process.env[key];
return (typeof transform === 'function') ? transform(envVal) : envVal;
}
if (value !== undefined) {
return value;
}
return defaultVal;
}
|
[
"function",
"getSetting",
"(",
"value",
",",
"key",
",",
"defaultVal",
",",
"transform",
")",
"{",
"if",
"(",
"process",
".",
"env",
"[",
"key",
"]",
"!==",
"undefined",
")",
"{",
"var",
"envVal",
"=",
"process",
".",
"env",
"[",
"key",
"]",
";",
"return",
"(",
"typeof",
"transform",
"===",
"'function'",
")",
"?",
"transform",
"(",
"envVal",
")",
":",
"envVal",
";",
"}",
"if",
"(",
"value",
"!==",
"undefined",
")",
"{",
"return",
"value",
";",
"}",
"return",
"defaultVal",
";",
"}"
] |
Determine an option value.
1. If `key` is present in the environment, then use the environment value
2. If `value` is specified, then use that value
3. Fall back to `defaultVal`
@module mocha-junit-reporter
@param {Object} value - the value from the reporter options
@param {String} key - the environment variable to check
@param {Object} defaultVal - the fallback value
@param {function} transform - a transformation function to be used when loading values from the environment
|
[
"Determine",
"an",
"option",
"value",
".",
"1",
".",
"If",
"key",
"is",
"present",
"in",
"the",
"environment",
"then",
"use",
"the",
"environment",
"value",
"2",
".",
"If",
"value",
"is",
"specified",
"then",
"use",
"that",
"value",
"3",
".",
"Fall",
"back",
"to",
"defaultVal"
] |
74ca40423385113214144477233ad441744452b1
|
https://github.com/michaelleeallen/mocha-junit-reporter/blob/74ca40423385113214144477233ad441744452b1/index.js#L77-L86
|
17,113
|
michaelleeallen/mocha-junit-reporter
|
index.js
|
MochaJUnitReporter
|
function MochaJUnitReporter(runner, options) {
this._options = configureDefaults(options);
this._runner = runner;
this._generateSuiteTitle = this._options.useFullSuiteTitle ? fullSuiteTitle : defaultSuiteTitle;
this._antId = 0;
var testsuites = [];
function lastSuite() {
return testsuites[testsuites.length - 1].testsuite;
}
// get functionality from the Base reporter
Base.call(this, runner);
// remove old results
this._runner.on('start', function() {
if (fs.existsSync(this._options.mochaFile)) {
debug('removing report file', this._options.mochaFile);
fs.unlinkSync(this._options.mochaFile);
}
}.bind(this));
this._runner.on('suite', function(suite) {
if (!isInvalidSuite(suite)) {
testsuites.push(this.getTestsuiteData(suite));
}
}.bind(this));
this._runner.on('pass', function(test) {
lastSuite().push(this.getTestcaseData(test));
}.bind(this));
this._runner.on('fail', function(test, err) {
lastSuite().push(this.getTestcaseData(test, err));
}.bind(this));
if (this._options.includePending) {
this._runner.on('pending', function(test) {
var testcase = this.getTestcaseData(test);
testcase.testcase.push({ skipped: null });
lastSuite().push(testcase);
}.bind(this));
}
this._runner.on('end', function(){
this.flush(testsuites);
}.bind(this));
}
|
javascript
|
function MochaJUnitReporter(runner, options) {
this._options = configureDefaults(options);
this._runner = runner;
this._generateSuiteTitle = this._options.useFullSuiteTitle ? fullSuiteTitle : defaultSuiteTitle;
this._antId = 0;
var testsuites = [];
function lastSuite() {
return testsuites[testsuites.length - 1].testsuite;
}
// get functionality from the Base reporter
Base.call(this, runner);
// remove old results
this._runner.on('start', function() {
if (fs.existsSync(this._options.mochaFile)) {
debug('removing report file', this._options.mochaFile);
fs.unlinkSync(this._options.mochaFile);
}
}.bind(this));
this._runner.on('suite', function(suite) {
if (!isInvalidSuite(suite)) {
testsuites.push(this.getTestsuiteData(suite));
}
}.bind(this));
this._runner.on('pass', function(test) {
lastSuite().push(this.getTestcaseData(test));
}.bind(this));
this._runner.on('fail', function(test, err) {
lastSuite().push(this.getTestcaseData(test, err));
}.bind(this));
if (this._options.includePending) {
this._runner.on('pending', function(test) {
var testcase = this.getTestcaseData(test);
testcase.testcase.push({ skipped: null });
lastSuite().push(testcase);
}.bind(this));
}
this._runner.on('end', function(){
this.flush(testsuites);
}.bind(this));
}
|
[
"function",
"MochaJUnitReporter",
"(",
"runner",
",",
"options",
")",
"{",
"this",
".",
"_options",
"=",
"configureDefaults",
"(",
"options",
")",
";",
"this",
".",
"_runner",
"=",
"runner",
";",
"this",
".",
"_generateSuiteTitle",
"=",
"this",
".",
"_options",
".",
"useFullSuiteTitle",
"?",
"fullSuiteTitle",
":",
"defaultSuiteTitle",
";",
"this",
".",
"_antId",
"=",
"0",
";",
"var",
"testsuites",
"=",
"[",
"]",
";",
"function",
"lastSuite",
"(",
")",
"{",
"return",
"testsuites",
"[",
"testsuites",
".",
"length",
"-",
"1",
"]",
".",
"testsuite",
";",
"}",
"// get functionality from the Base reporter",
"Base",
".",
"call",
"(",
"this",
",",
"runner",
")",
";",
"// remove old results",
"this",
".",
"_runner",
".",
"on",
"(",
"'start'",
",",
"function",
"(",
")",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"this",
".",
"_options",
".",
"mochaFile",
")",
")",
"{",
"debug",
"(",
"'removing report file'",
",",
"this",
".",
"_options",
".",
"mochaFile",
")",
";",
"fs",
".",
"unlinkSync",
"(",
"this",
".",
"_options",
".",
"mochaFile",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_runner",
".",
"on",
"(",
"'suite'",
",",
"function",
"(",
"suite",
")",
"{",
"if",
"(",
"!",
"isInvalidSuite",
"(",
"suite",
")",
")",
"{",
"testsuites",
".",
"push",
"(",
"this",
".",
"getTestsuiteData",
"(",
"suite",
")",
")",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_runner",
".",
"on",
"(",
"'pass'",
",",
"function",
"(",
"test",
")",
"{",
"lastSuite",
"(",
")",
".",
"push",
"(",
"this",
".",
"getTestcaseData",
"(",
"test",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"_runner",
".",
"on",
"(",
"'fail'",
",",
"function",
"(",
"test",
",",
"err",
")",
"{",
"lastSuite",
"(",
")",
".",
"push",
"(",
"this",
".",
"getTestcaseData",
"(",
"test",
",",
"err",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"if",
"(",
"this",
".",
"_options",
".",
"includePending",
")",
"{",
"this",
".",
"_runner",
".",
"on",
"(",
"'pending'",
",",
"function",
"(",
"test",
")",
"{",
"var",
"testcase",
"=",
"this",
".",
"getTestcaseData",
"(",
"test",
")",
";",
"testcase",
".",
"testcase",
".",
"push",
"(",
"{",
"skipped",
":",
"null",
"}",
")",
";",
"lastSuite",
"(",
")",
".",
"push",
"(",
"testcase",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"this",
".",
"_runner",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"this",
".",
"flush",
"(",
"testsuites",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
JUnit reporter for mocha.js.
@module mocha-junit-reporter
@param {EventEmitter} runner - the test runner
@param {Object} options - mocha options
|
[
"JUnit",
"reporter",
"for",
"mocha",
".",
"js",
"."
] |
74ca40423385113214144477233ad441744452b1
|
https://github.com/michaelleeallen/mocha-junit-reporter/blob/74ca40423385113214144477233ad441744452b1/index.js#L157-L206
|
17,114
|
moszeed/easysoap
|
src/index.js
|
mandatoryCheck
|
function mandatoryCheck (params = {}) {
assert.ok(params.host !== void 0, 'no host given');
assert.ok(params.path !== void 0, 'no path given');
assert.ok(params.wsdl !== void 0, 'no wsdl given');
}
|
javascript
|
function mandatoryCheck (params = {}) {
assert.ok(params.host !== void 0, 'no host given');
assert.ok(params.path !== void 0, 'no path given');
assert.ok(params.wsdl !== void 0, 'no wsdl given');
}
|
[
"function",
"mandatoryCheck",
"(",
"params",
"=",
"{",
"}",
")",
"{",
"assert",
".",
"ok",
"(",
"params",
".",
"host",
"!==",
"void",
"0",
",",
"'no host given'",
")",
";",
"assert",
".",
"ok",
"(",
"params",
".",
"path",
"!==",
"void",
"0",
",",
"'no path given'",
")",
";",
"assert",
".",
"ok",
"(",
"params",
".",
"wsdl",
"!==",
"void",
"0",
",",
"'no wsdl given'",
")",
";",
"}"
] |
check given params object
@param {[type]} params [description]
@return {[type]} [description]
|
[
"check",
"given",
"params",
"object"
] |
349e3e709fa59c4678ae526e94b22c349feabc6f
|
https://github.com/moszeed/easysoap/blob/349e3e709fa59c4678ae526e94b22c349feabc6f/src/index.js#L16-L20
|
17,115
|
steelbreeze/state.js
|
lib/node/state.js
|
invoke
|
function invoke(actions, message, instance, deepHistory) {
if (deepHistory === void 0) { deepHistory = false; }
for (var _i = 0, actions_2 = actions; _i < actions_2.length; _i++) {
var action = actions_2[_i];
action(message, instance, deepHistory);
}
}
|
javascript
|
function invoke(actions, message, instance, deepHistory) {
if (deepHistory === void 0) { deepHistory = false; }
for (var _i = 0, actions_2 = actions; _i < actions_2.length; _i++) {
var action = actions_2[_i];
action(message, instance, deepHistory);
}
}
|
[
"function",
"invoke",
"(",
"actions",
",",
"message",
",",
"instance",
",",
"deepHistory",
")",
"{",
"if",
"(",
"deepHistory",
"===",
"void",
"0",
")",
"{",
"deepHistory",
"=",
"false",
";",
"}",
"for",
"(",
"var",
"_i",
"=",
"0",
",",
"actions_2",
"=",
"actions",
";",
"_i",
"<",
"actions_2",
".",
"length",
";",
"_i",
"++",
")",
"{",
"var",
"action",
"=",
"actions_2",
"[",
"_i",
"]",
";",
"action",
"(",
"message",
",",
"instance",
",",
"deepHistory",
")",
";",
"}",
"}"
] |
Invokes behavior.
@param actions The set of [[Action]]s to invoke.
@param message The message that caused the [[Transition]] to be traversed that is triggering this behavior.
@param instance The state machine instance.
@param deepHistory True if [[DeepHistory]] semantics are in force at the time the behavior is invoked.
@internal
|
[
"Invokes",
"behavior",
"."
] |
2e563d7e916de67c7fb8b1e78b09e40420750a38
|
https://github.com/steelbreeze/state.js/blob/2e563d7e916de67c7fb8b1e78b09e40420750a38/lib/node/state.js#L750-L756
|
17,116
|
ciena-blueplanet/pr-bumper
|
lib/utils.js
|
getEnv
|
function getEnv (key, defaultValue) {
let value = process.env[key]
if (value === 'undefined') {
value = undefined
}
return (value === undefined) ? defaultValue : value
}
|
javascript
|
function getEnv (key, defaultValue) {
let value = process.env[key]
if (value === 'undefined') {
value = undefined
}
return (value === undefined) ? defaultValue : value
}
|
[
"function",
"getEnv",
"(",
"key",
",",
"defaultValue",
")",
"{",
"let",
"value",
"=",
"process",
".",
"env",
"[",
"key",
"]",
"if",
"(",
"value",
"===",
"'undefined'",
")",
"{",
"value",
"=",
"undefined",
"}",
"return",
"(",
"value",
"===",
"undefined",
")",
"?",
"defaultValue",
":",
"value",
"}"
] |
Get the given key from process.env, substituting "undefined" for the real undefined
@param {String} key - the environment variable we want to get
@param {*} defaultValue - value to return if key not in env, or if it is 'undefined'
@returns {*} whatever is at process.env[key] with the one exception of "undefined" being translated to undefined
|
[
"Get",
"the",
"given",
"key",
"from",
"process",
".",
"env",
"substituting",
"undefined",
"for",
"the",
"real",
"undefined"
] |
bb98aa046556f5b925576528d3fc15c268249d01
|
https://github.com/ciena-blueplanet/pr-bumper/blob/bb98aa046556f5b925576528d3fc15c268249d01/lib/utils.js#L68-L75
|
17,117
|
ciena-blueplanet/pr-bumper
|
lib/utils.js
|
processEnv
|
function processEnv (config) {
// Grab the CI stuff from env
config.computed.ci.buildNumber = getEnv(config.ci.env.buildNumber)
config.computed.ci.prNumber = getEnv(config.ci.env.pr, 'false')
config.computed.ci.isPr = config.computed.ci.prNumber !== 'false'
config.computed.ci.branch = getEnv(config.ci.env.branch, 'master')
logger.log(`pr-bumper::config: prNumber [${config.computed.ci.prNumber}], isPr [${config.computed.ci.isPr}]`)
// Fill in the owner/repo from the repo slug in env if necessary
const repoSlug = getEnv(config.ci.env.repoSlug)
if (repoSlug) {
const parts = repoSlug.split('/')
if (!config.vcs.repository.owner) {
config.vcs.repository.owner = parts[0]
}
if (!config.vcs.repository.name) {
config.vcs.repository.name = parts[1]
}
}
// Grab the VCS stuff from the env
config.computed.vcs.auth = {
password: getEnv(config.vcs.env.password),
readToken: getEnv(config.vcs.env.readToken),
username: getEnv(config.vcs.env.username),
writeToken: getEnv(config.vcs.env.writeToken)
}
}
|
javascript
|
function processEnv (config) {
// Grab the CI stuff from env
config.computed.ci.buildNumber = getEnv(config.ci.env.buildNumber)
config.computed.ci.prNumber = getEnv(config.ci.env.pr, 'false')
config.computed.ci.isPr = config.computed.ci.prNumber !== 'false'
config.computed.ci.branch = getEnv(config.ci.env.branch, 'master')
logger.log(`pr-bumper::config: prNumber [${config.computed.ci.prNumber}], isPr [${config.computed.ci.isPr}]`)
// Fill in the owner/repo from the repo slug in env if necessary
const repoSlug = getEnv(config.ci.env.repoSlug)
if (repoSlug) {
const parts = repoSlug.split('/')
if (!config.vcs.repository.owner) {
config.vcs.repository.owner = parts[0]
}
if (!config.vcs.repository.name) {
config.vcs.repository.name = parts[1]
}
}
// Grab the VCS stuff from the env
config.computed.vcs.auth = {
password: getEnv(config.vcs.env.password),
readToken: getEnv(config.vcs.env.readToken),
username: getEnv(config.vcs.env.username),
writeToken: getEnv(config.vcs.env.writeToken)
}
}
|
[
"function",
"processEnv",
"(",
"config",
")",
"{",
"// Grab the CI stuff from env",
"config",
".",
"computed",
".",
"ci",
".",
"buildNumber",
"=",
"getEnv",
"(",
"config",
".",
"ci",
".",
"env",
".",
"buildNumber",
")",
"config",
".",
"computed",
".",
"ci",
".",
"prNumber",
"=",
"getEnv",
"(",
"config",
".",
"ci",
".",
"env",
".",
"pr",
",",
"'false'",
")",
"config",
".",
"computed",
".",
"ci",
".",
"isPr",
"=",
"config",
".",
"computed",
".",
"ci",
".",
"prNumber",
"!==",
"'false'",
"config",
".",
"computed",
".",
"ci",
".",
"branch",
"=",
"getEnv",
"(",
"config",
".",
"ci",
".",
"env",
".",
"branch",
",",
"'master'",
")",
"logger",
".",
"log",
"(",
"`",
"${",
"config",
".",
"computed",
".",
"ci",
".",
"prNumber",
"}",
"${",
"config",
".",
"computed",
".",
"ci",
".",
"isPr",
"}",
"`",
")",
"// Fill in the owner/repo from the repo slug in env if necessary",
"const",
"repoSlug",
"=",
"getEnv",
"(",
"config",
".",
"ci",
".",
"env",
".",
"repoSlug",
")",
"if",
"(",
"repoSlug",
")",
"{",
"const",
"parts",
"=",
"repoSlug",
".",
"split",
"(",
"'/'",
")",
"if",
"(",
"!",
"config",
".",
"vcs",
".",
"repository",
".",
"owner",
")",
"{",
"config",
".",
"vcs",
".",
"repository",
".",
"owner",
"=",
"parts",
"[",
"0",
"]",
"}",
"if",
"(",
"!",
"config",
".",
"vcs",
".",
"repository",
".",
"name",
")",
"{",
"config",
".",
"vcs",
".",
"repository",
".",
"name",
"=",
"parts",
"[",
"1",
"]",
"}",
"}",
"// Grab the VCS stuff from the env",
"config",
".",
"computed",
".",
"vcs",
".",
"auth",
"=",
"{",
"password",
":",
"getEnv",
"(",
"config",
".",
"vcs",
".",
"env",
".",
"password",
")",
",",
"readToken",
":",
"getEnv",
"(",
"config",
".",
"vcs",
".",
"env",
".",
"readToken",
")",
",",
"username",
":",
"getEnv",
"(",
"config",
".",
"vcs",
".",
"env",
".",
"username",
")",
",",
"writeToken",
":",
"getEnv",
"(",
"config",
".",
"vcs",
".",
"env",
".",
"writeToken",
")",
"}",
"}"
] |
Process the environment variable sections in the config and fill in the computed properties within it
@param {Config} config - the config object to process (will be mutated in-place)
|
[
"Process",
"the",
"environment",
"variable",
"sections",
"in",
"the",
"config",
"and",
"fill",
"in",
"the",
"computed",
"properties",
"within",
"it"
] |
bb98aa046556f5b925576528d3fc15c268249d01
|
https://github.com/ciena-blueplanet/pr-bumper/blob/bb98aa046556f5b925576528d3fc15c268249d01/lib/utils.js#L95-L125
|
17,118
|
ciena-blueplanet/pr-bumper
|
lib/vcs/github-enterprise.js
|
getFetchOpts
|
function getFetchOpts (config) {
const readToken = config.computed.vcs.auth.readToken
const headers = {}
logger.log(`RO_GH_TOKEN = [${readToken}]`)
if (readToken) {
headers['Authorization'] = `token ${readToken}`
}
return {headers}
}
|
javascript
|
function getFetchOpts (config) {
const readToken = config.computed.vcs.auth.readToken
const headers = {}
logger.log(`RO_GH_TOKEN = [${readToken}]`)
if (readToken) {
headers['Authorization'] = `token ${readToken}`
}
return {headers}
}
|
[
"function",
"getFetchOpts",
"(",
"config",
")",
"{",
"const",
"readToken",
"=",
"config",
".",
"computed",
".",
"vcs",
".",
"auth",
".",
"readToken",
"const",
"headers",
"=",
"{",
"}",
"logger",
".",
"log",
"(",
"`",
"${",
"readToken",
"}",
"`",
")",
"if",
"(",
"readToken",
")",
"{",
"headers",
"[",
"'Authorization'",
"]",
"=",
"`",
"${",
"readToken",
"}",
"`",
"}",
"return",
"{",
"headers",
"}",
"}"
] |
Get fetch options
@param {Config} config - the pr-bumper config object
@returns {Object} the options
|
[
"Get",
"fetch",
"options"
] |
bb98aa046556f5b925576528d3fc15c268249d01
|
https://github.com/ciena-blueplanet/pr-bumper/blob/bb98aa046556f5b925576528d3fc15c268249d01/lib/vcs/github-enterprise.js#L19-L27
|
17,119
|
ciena-blueplanet/pr-bumper
|
lib/vcs/github-enterprise.js
|
convertPr
|
function convertPr (ghPr) {
return {
number: ghPr.number,
description: ghPr.body,
url: ghPr.html_url,
headSha: ghPr.head.sha
}
}
|
javascript
|
function convertPr (ghPr) {
return {
number: ghPr.number,
description: ghPr.body,
url: ghPr.html_url,
headSha: ghPr.head.sha
}
}
|
[
"function",
"convertPr",
"(",
"ghPr",
")",
"{",
"return",
"{",
"number",
":",
"ghPr",
".",
"number",
",",
"description",
":",
"ghPr",
".",
"body",
",",
"url",
":",
"ghPr",
".",
"html_url",
",",
"headSha",
":",
"ghPr",
".",
"head",
".",
"sha",
"}",
"}"
] |
Convert a GitHub PR to a PR representation
@param {GitHubPullRequest} ghPr - the API response from a GitHub API looking for a PR
@returns {PullRequest} a pull request in standard format
|
[
"Convert",
"a",
"GitHub",
"PR",
"to",
"a",
"PR",
"representation"
] |
bb98aa046556f5b925576528d3fc15c268249d01
|
https://github.com/ciena-blueplanet/pr-bumper/blob/bb98aa046556f5b925576528d3fc15c268249d01/lib/vcs/github-enterprise.js#L34-L41
|
17,120
|
ciena-blueplanet/pr-bumper
|
lib/bumper.js
|
addModifiedFile
|
function addModifiedFile (info, filename) {
if (info.modifiedFiles.indexOf(filename) === -1) {
info.modifiedFiles.push(filename)
}
}
|
javascript
|
function addModifiedFile (info, filename) {
if (info.modifiedFiles.indexOf(filename) === -1) {
info.modifiedFiles.push(filename)
}
}
|
[
"function",
"addModifiedFile",
"(",
"info",
",",
"filename",
")",
"{",
"if",
"(",
"info",
".",
"modifiedFiles",
".",
"indexOf",
"(",
"filename",
")",
"===",
"-",
"1",
")",
"{",
"info",
".",
"modifiedFiles",
".",
"push",
"(",
"filename",
")",
"}",
"}"
] |
Adds the given filename to info.modifiedFiles if it doesn't already exist
@param {PrInfo} info - the info for the PR
@param {String[]} info.modifiedFiles - the list of modified files so far
@param {String} filename - the filename to add to info.modifiedFiles if it's not already there
|
[
"Adds",
"the",
"given",
"filename",
"to",
"info",
".",
"modifiedFiles",
"if",
"it",
"doesn",
"t",
"already",
"exist"
] |
bb98aa046556f5b925576528d3fc15c268249d01
|
https://github.com/ciena-blueplanet/pr-bumper/blob/bb98aa046556f5b925576528d3fc15c268249d01/lib/bumper.js#L33-L37
|
17,121
|
NathanaelA/nativescript-permissions
|
src/permissions.android.js
|
handlePermissionResults
|
function handlePermissionResults(args) {
// get current promise set
//noinspection JSUnresolvedVariable
const promises = pendingPromises[args.requestCode];
// We have either gotten a promise from somewhere else or a bug has occurred and android has called us twice
// In either case we will ignore it...
if (!promises || typeof promises.granted !== 'function') {
return;
}
// Delete it, since we no longer need to track it
//noinspection JSUnresolvedVariable
delete pendingPromises[args.requestCode];
let trackingResults = promises.results;
//noinspection JSUnresolvedVariable
const length = args.permissions.length;
for (let i = 0; i < length; i++) {
// Convert back to JS String
//noinspection JSUnresolvedVariable
const name = args.permissions[i].toString();
//noinspection RedundantIfStatementJS,JSUnresolvedVariable,JSUnresolvedFunction
if (args.grantResults[i] === android.content.pm.PackageManager.PERMISSION_GRANTED) {
trackingResults[name] = true;
} else {
trackingResults[name] = false;
}
}
// Any Failures
let failureCount = 0;
for (let key in trackingResults) {
if (!trackingResults.hasOwnProperty(key)) continue;
if (trackingResults[key] === false) failureCount++;
}
if (Object.keys(pendingPromises).length === 0) {
removeEventListeners();
}
if (failureCount === 0) {
promises.granted(trackingResults);
} else {
promises.failed(trackingResults);
}
}
|
javascript
|
function handlePermissionResults(args) {
// get current promise set
//noinspection JSUnresolvedVariable
const promises = pendingPromises[args.requestCode];
// We have either gotten a promise from somewhere else or a bug has occurred and android has called us twice
// In either case we will ignore it...
if (!promises || typeof promises.granted !== 'function') {
return;
}
// Delete it, since we no longer need to track it
//noinspection JSUnresolvedVariable
delete pendingPromises[args.requestCode];
let trackingResults = promises.results;
//noinspection JSUnresolvedVariable
const length = args.permissions.length;
for (let i = 0; i < length; i++) {
// Convert back to JS String
//noinspection JSUnresolvedVariable
const name = args.permissions[i].toString();
//noinspection RedundantIfStatementJS,JSUnresolvedVariable,JSUnresolvedFunction
if (args.grantResults[i] === android.content.pm.PackageManager.PERMISSION_GRANTED) {
trackingResults[name] = true;
} else {
trackingResults[name] = false;
}
}
// Any Failures
let failureCount = 0;
for (let key in trackingResults) {
if (!trackingResults.hasOwnProperty(key)) continue;
if (trackingResults[key] === false) failureCount++;
}
if (Object.keys(pendingPromises).length === 0) {
removeEventListeners();
}
if (failureCount === 0) {
promises.granted(trackingResults);
} else {
promises.failed(trackingResults);
}
}
|
[
"function",
"handlePermissionResults",
"(",
"args",
")",
"{",
"// get current promise set",
"//noinspection JSUnresolvedVariable",
"const",
"promises",
"=",
"pendingPromises",
"[",
"args",
".",
"requestCode",
"]",
";",
"// We have either gotten a promise from somewhere else or a bug has occurred and android has called us twice",
"// In either case we will ignore it...",
"if",
"(",
"!",
"promises",
"||",
"typeof",
"promises",
".",
"granted",
"!==",
"'function'",
")",
"{",
"return",
";",
"}",
"// Delete it, since we no longer need to track it",
"//noinspection JSUnresolvedVariable",
"delete",
"pendingPromises",
"[",
"args",
".",
"requestCode",
"]",
";",
"let",
"trackingResults",
"=",
"promises",
".",
"results",
";",
"//noinspection JSUnresolvedVariable",
"const",
"length",
"=",
"args",
".",
"permissions",
".",
"length",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"// Convert back to JS String",
"//noinspection JSUnresolvedVariable",
"const",
"name",
"=",
"args",
".",
"permissions",
"[",
"i",
"]",
".",
"toString",
"(",
")",
";",
"//noinspection RedundantIfStatementJS,JSUnresolvedVariable,JSUnresolvedFunction",
"if",
"(",
"args",
".",
"grantResults",
"[",
"i",
"]",
"===",
"android",
".",
"content",
".",
"pm",
".",
"PackageManager",
".",
"PERMISSION_GRANTED",
")",
"{",
"trackingResults",
"[",
"name",
"]",
"=",
"true",
";",
"}",
"else",
"{",
"trackingResults",
"[",
"name",
"]",
"=",
"false",
";",
"}",
"}",
"// Any Failures",
"let",
"failureCount",
"=",
"0",
";",
"for",
"(",
"let",
"key",
"in",
"trackingResults",
")",
"{",
"if",
"(",
"!",
"trackingResults",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"continue",
";",
"if",
"(",
"trackingResults",
"[",
"key",
"]",
"===",
"false",
")",
"failureCount",
"++",
";",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"pendingPromises",
")",
".",
"length",
"===",
"0",
")",
"{",
"removeEventListeners",
"(",
")",
";",
"}",
"if",
"(",
"failureCount",
"===",
"0",
")",
"{",
"promises",
".",
"granted",
"(",
"trackingResults",
")",
";",
"}",
"else",
"{",
"promises",
".",
"failed",
"(",
"trackingResults",
")",
";",
"}",
"}"
] |
noinspection JSUnresolvedVariable,JSUnresolvedFunction
This handles the results of getting the permissions!
|
[
"noinspection",
"JSUnresolvedVariable",
"JSUnresolvedFunction",
"This",
"handles",
"the",
"results",
"of",
"getting",
"the",
"permissions!"
] |
5abbb3c8150e5d446aecda1932045068c472d6e2
|
https://github.com/NathanaelA/nativescript-permissions/blob/5abbb3c8150e5d446aecda1932045068c472d6e2/src/permissions.android.js#L31-L81
|
17,122
|
NathanaelA/nativescript-permissions
|
src/permissions.android.js
|
hasSupportVersion4
|
function hasSupportVersion4() {
//noinspection JSUnresolvedVariable
if (!android.support || !android.support.v4 || !android.support.v4.content || !android.support.v4.content.ContextCompat || !android.support.v4.content.ContextCompat.checkSelfPermission) {
return false;
}
return true;
}
|
javascript
|
function hasSupportVersion4() {
//noinspection JSUnresolvedVariable
if (!android.support || !android.support.v4 || !android.support.v4.content || !android.support.v4.content.ContextCompat || !android.support.v4.content.ContextCompat.checkSelfPermission) {
return false;
}
return true;
}
|
[
"function",
"hasSupportVersion4",
"(",
")",
"{",
"//noinspection JSUnresolvedVariable",
"if",
"(",
"!",
"android",
".",
"support",
"||",
"!",
"android",
".",
"support",
".",
"v4",
"||",
"!",
"android",
".",
"support",
".",
"v4",
".",
"content",
"||",
"!",
"android",
".",
"support",
".",
"v4",
".",
"content",
".",
"ContextCompat",
"||",
"!",
"android",
".",
"support",
".",
"v4",
".",
"content",
".",
"ContextCompat",
".",
"checkSelfPermission",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Checks to see if v4 is installed and has the proper calls with it
@returns {boolean}
|
[
"Checks",
"to",
"see",
"if",
"v4",
"is",
"installed",
"and",
"has",
"the",
"proper",
"calls",
"with",
"it"
] |
5abbb3c8150e5d446aecda1932045068c472d6e2
|
https://github.com/NathanaelA/nativescript-permissions/blob/5abbb3c8150e5d446aecda1932045068c472d6e2/src/permissions.android.js#L163-L169
|
17,123
|
NathanaelA/nativescript-permissions
|
src/permissions.android.js
|
hasAndroidX
|
function hasAndroidX() {
//noinspection JSUnresolvedVariable
if (!global.androidx || !global.androidx.core || !global.androidx.core.content || !global.androidx.core.content.ContextCompat || !global.androidx.core.content.ContextCompat.checkSelfPermission) {
return false;
}
return true;
}
|
javascript
|
function hasAndroidX() {
//noinspection JSUnresolvedVariable
if (!global.androidx || !global.androidx.core || !global.androidx.core.content || !global.androidx.core.content.ContextCompat || !global.androidx.core.content.ContextCompat.checkSelfPermission) {
return false;
}
return true;
}
|
[
"function",
"hasAndroidX",
"(",
")",
"{",
"//noinspection JSUnresolvedVariable",
"if",
"(",
"!",
"global",
".",
"androidx",
"||",
"!",
"global",
".",
"androidx",
".",
"core",
"||",
"!",
"global",
".",
"androidx",
".",
"core",
".",
"content",
"||",
"!",
"global",
".",
"androidx",
".",
"core",
".",
"content",
".",
"ContextCompat",
"||",
"!",
"global",
".",
"androidx",
".",
"core",
".",
"content",
".",
"ContextCompat",
".",
"checkSelfPermission",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Checks to see if androidx is installed and has the proper calls for it.
@returns {boolean}
|
[
"Checks",
"to",
"see",
"if",
"androidx",
"is",
"installed",
"and",
"has",
"the",
"proper",
"calls",
"for",
"it",
"."
] |
5abbb3c8150e5d446aecda1932045068c472d6e2
|
https://github.com/NathanaelA/nativescript-permissions/blob/5abbb3c8150e5d446aecda1932045068c472d6e2/src/permissions.android.js#L176-L182
|
17,124
|
NathanaelA/nativescript-permissions
|
src/permissions.android.js
|
getContext
|
function getContext() {
if (application.android.context) {
return (application.android.context);
}
if (typeof application.getNativeApplication === 'function') {
let ctx = application.getNativeApplication();
if (ctx) {
return ctx;
}
}
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
let ctx = java.lang.Class.forName("android.app.AppGlobals").getMethod("getInitialApplication", null).invoke(null, null);
if (ctx) return ctx;
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
ctx = java.lang.Class.forName("android.app.ActivityThread").getMethod("currentApplication", null).invoke(null, null);
if (ctx) return ctx;
return ctx;
}
|
javascript
|
function getContext() {
if (application.android.context) {
return (application.android.context);
}
if (typeof application.getNativeApplication === 'function') {
let ctx = application.getNativeApplication();
if (ctx) {
return ctx;
}
}
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
let ctx = java.lang.Class.forName("android.app.AppGlobals").getMethod("getInitialApplication", null).invoke(null, null);
if (ctx) return ctx;
//noinspection JSUnresolvedFunction,JSUnresolvedVariable
ctx = java.lang.Class.forName("android.app.ActivityThread").getMethod("currentApplication", null).invoke(null, null);
if (ctx) return ctx;
return ctx;
}
|
[
"function",
"getContext",
"(",
")",
"{",
"if",
"(",
"application",
".",
"android",
".",
"context",
")",
"{",
"return",
"(",
"application",
".",
"android",
".",
"context",
")",
";",
"}",
"if",
"(",
"typeof",
"application",
".",
"getNativeApplication",
"===",
"'function'",
")",
"{",
"let",
"ctx",
"=",
"application",
".",
"getNativeApplication",
"(",
")",
";",
"if",
"(",
"ctx",
")",
"{",
"return",
"ctx",
";",
"}",
"}",
"//noinspection JSUnresolvedFunction,JSUnresolvedVariable",
"let",
"ctx",
"=",
"java",
".",
"lang",
".",
"Class",
".",
"forName",
"(",
"\"android.app.AppGlobals\"",
")",
".",
"getMethod",
"(",
"\"getInitialApplication\"",
",",
"null",
")",
".",
"invoke",
"(",
"null",
",",
"null",
")",
";",
"if",
"(",
"ctx",
")",
"return",
"ctx",
";",
"//noinspection JSUnresolvedFunction,JSUnresolvedVariable",
"ctx",
"=",
"java",
".",
"lang",
".",
"Class",
".",
"forName",
"(",
"\"android.app.ActivityThread\"",
")",
".",
"getMethod",
"(",
"\"currentApplication\"",
",",
"null",
")",
".",
"invoke",
"(",
"null",
",",
"null",
")",
";",
"if",
"(",
"ctx",
")",
"return",
"ctx",
";",
"return",
"ctx",
";",
"}"
] |
gets the current application context
@returns {*}
@private
|
[
"gets",
"the",
"current",
"application",
"context"
] |
5abbb3c8150e5d446aecda1932045068c472d6e2
|
https://github.com/NathanaelA/nativescript-permissions/blob/5abbb3c8150e5d446aecda1932045068c472d6e2/src/permissions.android.js#L212-L233
|
17,125
|
Availity/availity-workflow
|
packages/workflow/scripts/proxy.js
|
proxyLogRewrite
|
function proxyLogRewrite(daArgs) {
const args = Array.prototype.slice.call(daArgs);
return args.map(arg => {
if (typeof arg === 'string') {
return arg.replace(/\[HPM\] /g, '').replace(/ {2}/g, ' ');
}
return arg;
});
}
|
javascript
|
function proxyLogRewrite(daArgs) {
const args = Array.prototype.slice.call(daArgs);
return args.map(arg => {
if (typeof arg === 'string') {
return arg.replace(/\[HPM\] /g, '').replace(/ {2}/g, ' ');
}
return arg;
});
}
|
[
"function",
"proxyLogRewrite",
"(",
"daArgs",
")",
"{",
"const",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"daArgs",
")",
";",
"return",
"args",
".",
"map",
"(",
"arg",
"=>",
"{",
"if",
"(",
"typeof",
"arg",
"===",
"'string'",
")",
"{",
"return",
"arg",
".",
"replace",
"(",
"/",
"\\[HPM\\] ",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"/",
" {2}",
"/",
"g",
",",
"' '",
")",
";",
"}",
"return",
"arg",
";",
"}",
")",
";",
"}"
] |
Clean up HPM messages so they appear more @availity/workflow like ;)
|
[
"Clean",
"up",
"HPM",
"messages",
"so",
"they",
"appear",
"more"
] |
5a92d4fbebea3e56bd7e8ff4b1ac0e8d7d268b70
|
https://github.com/Availity/availity-workflow/blob/5a92d4fbebea3e56bd7e8ff4b1ac0e8d7d268b70/packages/workflow/scripts/proxy.js#L12-L22
|
17,126
|
Availity/availity-workflow
|
packages/workflow/scripts/format.js
|
formatMessage
|
function formatMessage(message) {
let lines = message.split('\n');
// Remove webpack-specific loader notation from filename.
// Before:
// ./~/css-loader!./~/postcss-loader!./src/App.css
// After:
// ./src/App.css
if (lines[0].lastIndexOf('!') !== -1) {
lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
}
// line #0 is filename
// line #1 is the main error message
if (!lines[0] || !lines[1]) {
return lines.join('\n');
}
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1].indexOf('Module not found: ') === 0) {
lines = [
lines[0],
// Clean up message because "Module not found: " is descriptive enough.
lines[1]
.replace("Cannot resolve 'file' or 'directory' ", '')
.replace('Cannot resolve module ', '')
.replace('Error: ', ''),
// Skip all irrelevant lines.
// (For some reason they only appear on the client in browser.)
'',
lines[lines.length - 1] // error location is the last line
];
}
// Cleans up syntax error messages.
if (lines[1].indexOf('Module build failed: ') === 0) {
const cleanedLines = [];
lines.forEach(line => {
if (line !== '') {
cleanedLines.push(line);
}
});
// We are clean now!
lines = cleanedLines;
// Finally, brush up the error message a little.
lines[1] = lines[1].replace('Module build failed: SyntaxError:', friendlySyntaxErrorLabel);
}
// Reassemble the message.
message = lines.join('\n');
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by WebPack. For more information see
// https://github.com/facebookincubator/create-react-app/pull/1050
message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y
return message;
}
|
javascript
|
function formatMessage(message) {
let lines = message.split('\n');
// Remove webpack-specific loader notation from filename.
// Before:
// ./~/css-loader!./~/postcss-loader!./src/App.css
// After:
// ./src/App.css
if (lines[0].lastIndexOf('!') !== -1) {
lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1);
}
// line #0 is filename
// line #1 is the main error message
if (!lines[0] || !lines[1]) {
return lines.join('\n');
}
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1].indexOf('Module not found: ') === 0) {
lines = [
lines[0],
// Clean up message because "Module not found: " is descriptive enough.
lines[1]
.replace("Cannot resolve 'file' or 'directory' ", '')
.replace('Cannot resolve module ', '')
.replace('Error: ', ''),
// Skip all irrelevant lines.
// (For some reason they only appear on the client in browser.)
'',
lines[lines.length - 1] // error location is the last line
];
}
// Cleans up syntax error messages.
if (lines[1].indexOf('Module build failed: ') === 0) {
const cleanedLines = [];
lines.forEach(line => {
if (line !== '') {
cleanedLines.push(line);
}
});
// We are clean now!
lines = cleanedLines;
// Finally, brush up the error message a little.
lines[1] = lines[1].replace('Module build failed: SyntaxError:', friendlySyntaxErrorLabel);
}
// Reassemble the message.
message = lines.join('\n');
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by WebPack. For more information see
// https://github.com/facebookincubator/create-react-app/pull/1050
message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, ''); // at ... ...:x:y
return message;
}
|
[
"function",
"formatMessage",
"(",
"message",
")",
"{",
"let",
"lines",
"=",
"message",
".",
"split",
"(",
"'\\n'",
")",
";",
"// Remove webpack-specific loader notation from filename.",
"// Before:",
"// ./~/css-loader!./~/postcss-loader!./src/App.css",
"// After:",
"// ./src/App.css",
"if",
"(",
"lines",
"[",
"0",
"]",
".",
"lastIndexOf",
"(",
"'!'",
")",
"!==",
"-",
"1",
")",
"{",
"lines",
"[",
"0",
"]",
"=",
"lines",
"[",
"0",
"]",
".",
"substr",
"(",
"lines",
"[",
"0",
"]",
".",
"lastIndexOf",
"(",
"'!'",
")",
"+",
"1",
")",
";",
"}",
"// line #0 is filename",
"// line #1 is the main error message",
"if",
"(",
"!",
"lines",
"[",
"0",
"]",
"||",
"!",
"lines",
"[",
"1",
"]",
")",
"{",
"return",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"}",
"// Cleans up verbose \"module not found\" messages for files and packages.",
"if",
"(",
"lines",
"[",
"1",
"]",
".",
"indexOf",
"(",
"'Module not found: '",
")",
"===",
"0",
")",
"{",
"lines",
"=",
"[",
"lines",
"[",
"0",
"]",
",",
"// Clean up message because \"Module not found: \" is descriptive enough.",
"lines",
"[",
"1",
"]",
".",
"replace",
"(",
"\"Cannot resolve 'file' or 'directory' \"",
",",
"''",
")",
".",
"replace",
"(",
"'Cannot resolve module '",
",",
"''",
")",
".",
"replace",
"(",
"'Error: '",
",",
"''",
")",
",",
"// Skip all irrelevant lines.",
"// (For some reason they only appear on the client in browser.)",
"''",
",",
"lines",
"[",
"lines",
".",
"length",
"-",
"1",
"]",
"// error location is the last line",
"]",
";",
"}",
"// Cleans up syntax error messages.",
"if",
"(",
"lines",
"[",
"1",
"]",
".",
"indexOf",
"(",
"'Module build failed: '",
")",
"===",
"0",
")",
"{",
"const",
"cleanedLines",
"=",
"[",
"]",
";",
"lines",
".",
"forEach",
"(",
"line",
"=>",
"{",
"if",
"(",
"line",
"!==",
"''",
")",
"{",
"cleanedLines",
".",
"push",
"(",
"line",
")",
";",
"}",
"}",
")",
";",
"// We are clean now!",
"lines",
"=",
"cleanedLines",
";",
"// Finally, brush up the error message a little.",
"lines",
"[",
"1",
"]",
"=",
"lines",
"[",
"1",
"]",
".",
"replace",
"(",
"'Module build failed: SyntaxError:'",
",",
"friendlySyntaxErrorLabel",
")",
";",
"}",
"// Reassemble the message.",
"message",
"=",
"lines",
".",
"join",
"(",
"'\\n'",
")",
";",
"// Internal stacks are generally useless so we strip them... with the",
"// exception of stacks containing `webpack:` because they're normally",
"// from user code generated by WebPack. For more information see",
"// https://github.com/facebookincubator/create-react-app/pull/1050",
"message",
"=",
"message",
".",
"replace",
"(",
"/",
"^\\s*at\\s((?!webpack:).)*:\\d+:\\d+[\\s)]*(\\n|$)",
"/",
"gm",
",",
"''",
")",
";",
"// at ... ...:x:y",
"return",
"message",
";",
"}"
] |
Cleans up webpack error messages.
|
[
"Cleans",
"up",
"webpack",
"error",
"messages",
"."
] |
5a92d4fbebea3e56bd7e8ff4b1ac0e8d7d268b70
|
https://github.com/Availity/availity-workflow/blob/5a92d4fbebea3e56bd7e8ff4b1ac0e8d7d268b70/packages/workflow/scripts/format.js#L8-L65
|
17,127
|
leepowellcouk/mongoose-validator
|
lib/mongoose-validator.js
|
validate
|
function validate(options) {
if (is.undef(options.validator)) {
throw new Error('validator option undefined')
}
if (!is.function(options.validator) && !is.string(options.validator)) {
throw new Error(
`validator must be of type function or string, received ${typeof options.validator}`
)
}
const validatorName = is.string(options.validator) ? options.validator : ''
const validatorFn = getValidatorFn(options.validator)
if (is.undef(validatorFn)) {
throw new Error(
`validator \`${validatorName}\` does not exist in validator.js or as a custom validator`
)
}
const passIfEmpty = !!options.passIfEmpty
const mongooseOpts = omit(
options,
'passIfEmpty',
'message',
'validator',
'arguments'
)
const args = toArray(options.arguments)
const messageStr = findFirstString(
options.message,
customErrorMessages[validatorName],
defaultErrorMessages[validatorName],
'Error'
)
const message = interpolateMessageWithArgs(messageStr, args)
const validator = createValidator(validatorFn, args, passIfEmpty)
return Object.assign(
{
validator,
message,
},
mongooseOpts
)
}
|
javascript
|
function validate(options) {
if (is.undef(options.validator)) {
throw new Error('validator option undefined')
}
if (!is.function(options.validator) && !is.string(options.validator)) {
throw new Error(
`validator must be of type function or string, received ${typeof options.validator}`
)
}
const validatorName = is.string(options.validator) ? options.validator : ''
const validatorFn = getValidatorFn(options.validator)
if (is.undef(validatorFn)) {
throw new Error(
`validator \`${validatorName}\` does not exist in validator.js or as a custom validator`
)
}
const passIfEmpty = !!options.passIfEmpty
const mongooseOpts = omit(
options,
'passIfEmpty',
'message',
'validator',
'arguments'
)
const args = toArray(options.arguments)
const messageStr = findFirstString(
options.message,
customErrorMessages[validatorName],
defaultErrorMessages[validatorName],
'Error'
)
const message = interpolateMessageWithArgs(messageStr, args)
const validator = createValidator(validatorFn, args, passIfEmpty)
return Object.assign(
{
validator,
message,
},
mongooseOpts
)
}
|
[
"function",
"validate",
"(",
"options",
")",
"{",
"if",
"(",
"is",
".",
"undef",
"(",
"options",
".",
"validator",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'validator option undefined'",
")",
"}",
"if",
"(",
"!",
"is",
".",
"function",
"(",
"options",
".",
"validator",
")",
"&&",
"!",
"is",
".",
"string",
"(",
"options",
".",
"validator",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"typeof",
"options",
".",
"validator",
"}",
"`",
")",
"}",
"const",
"validatorName",
"=",
"is",
".",
"string",
"(",
"options",
".",
"validator",
")",
"?",
"options",
".",
"validator",
":",
"''",
"const",
"validatorFn",
"=",
"getValidatorFn",
"(",
"options",
".",
"validator",
")",
"if",
"(",
"is",
".",
"undef",
"(",
"validatorFn",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"\\`",
"${",
"validatorName",
"}",
"\\`",
"`",
")",
"}",
"const",
"passIfEmpty",
"=",
"!",
"!",
"options",
".",
"passIfEmpty",
"const",
"mongooseOpts",
"=",
"omit",
"(",
"options",
",",
"'passIfEmpty'",
",",
"'message'",
",",
"'validator'",
",",
"'arguments'",
")",
"const",
"args",
"=",
"toArray",
"(",
"options",
".",
"arguments",
")",
"const",
"messageStr",
"=",
"findFirstString",
"(",
"options",
".",
"message",
",",
"customErrorMessages",
"[",
"validatorName",
"]",
",",
"defaultErrorMessages",
"[",
"validatorName",
"]",
",",
"'Error'",
")",
"const",
"message",
"=",
"interpolateMessageWithArgs",
"(",
"messageStr",
",",
"args",
")",
"const",
"validator",
"=",
"createValidator",
"(",
"validatorFn",
",",
"args",
",",
"passIfEmpty",
")",
"return",
"Object",
".",
"assign",
"(",
"{",
"validator",
",",
"message",
",",
"}",
",",
"mongooseOpts",
")",
"}"
] |
Create a validator object
@alias module:mongoose-validator
@param {object} options Options object
@param {string} options.validator Validator name to use
@param {*} [options.arguments=[]] Arguments to pass to validator. If more than one argument is required an array must be used. Single arguments will internally be coerced into an array
@param {boolean} [options.passIfEmpty=false] Weather the validator should pass if the value being validated is empty
@param {string} [options.message=Error] Validator error message
@return {object} Returns validator compatible with mongoosejs
@throws If validator option property is not defined
@throws If validator option is not a function or string
@throws If validator option is a validator method (string) and method does not exist in validate.js or as a custom validator
@example
require('mongoose-validator').validate({ validator: 'isLength', arguments: [4, 40], passIfEmpty: true, message: 'Value should be between 4 and 40 characters' )
|
[
"Create",
"a",
"validator",
"object"
] |
9a702aed336516f12905ab72494e9b21768e193a
|
https://github.com/leepowellcouk/mongoose-validator/blob/9a702aed336516f12905ab72494e9b21768e193a/lib/mongoose-validator.js#L71-L116
|
17,128
|
bunkat/schedule
|
src/core/resource-manager.js
|
addResourceToMap
|
function addResourceToMap(map, def, start) {
var sched = JSON.parse(JSON.stringify(def.available || defaultSched)),
nextFn = schedule.memoizedRangeFn(later.schedule(sched).nextRange);
map[def.id] = { schedule: sched, next: nextFn, nextAvail: nextFn(start) };
}
|
javascript
|
function addResourceToMap(map, def, start) {
var sched = JSON.parse(JSON.stringify(def.available || defaultSched)),
nextFn = schedule.memoizedRangeFn(later.schedule(sched).nextRange);
map[def.id] = { schedule: sched, next: nextFn, nextAvail: nextFn(start) };
}
|
[
"function",
"addResourceToMap",
"(",
"map",
",",
"def",
",",
"start",
")",
"{",
"var",
"sched",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"def",
".",
"available",
"||",
"defaultSched",
")",
")",
",",
"nextFn",
"=",
"schedule",
".",
"memoizedRangeFn",
"(",
"later",
".",
"schedule",
"(",
"sched",
")",
".",
"nextRange",
")",
";",
"map",
"[",
"def",
".",
"id",
"]",
"=",
"{",
"schedule",
":",
"sched",
",",
"next",
":",
"nextFn",
",",
"nextAvail",
":",
"nextFn",
"(",
"start",
")",
"}",
";",
"}"
] |
Adds a resource to the resource map.
|
[
"Adds",
"a",
"resource",
"to",
"the",
"resource",
"map",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L38-L43
|
17,129
|
bunkat/schedule
|
src/core/resource-manager.js
|
getReservation
|
function getReservation(resources, start, min, max) {
var reservation, schedules = [], delays = {},
maxTries = 50;
initRanges(resources, start, schedules, delays);
while(!(reservation = tryReservation(schedules, min, max)).success && --maxTries) {
updateRanges(schedules, nextValidStart(schedules), delays);
}
reservation.delays = delays;
return reservation;
}
|
javascript
|
function getReservation(resources, start, min, max) {
var reservation, schedules = [], delays = {},
maxTries = 50;
initRanges(resources, start, schedules, delays);
while(!(reservation = tryReservation(schedules, min, max)).success && --maxTries) {
updateRanges(schedules, nextValidStart(schedules), delays);
}
reservation.delays = delays;
return reservation;
}
|
[
"function",
"getReservation",
"(",
"resources",
",",
"start",
",",
"min",
",",
"max",
")",
"{",
"var",
"reservation",
",",
"schedules",
"=",
"[",
"]",
",",
"delays",
"=",
"{",
"}",
",",
"maxTries",
"=",
"50",
";",
"initRanges",
"(",
"resources",
",",
"start",
",",
"schedules",
",",
"delays",
")",
";",
"while",
"(",
"!",
"(",
"reservation",
"=",
"tryReservation",
"(",
"schedules",
",",
"min",
",",
"max",
")",
")",
".",
"success",
"&&",
"--",
"maxTries",
")",
"{",
"updateRanges",
"(",
"schedules",
",",
"nextValidStart",
"(",
"schedules",
")",
",",
"delays",
")",
";",
"}",
"reservation",
".",
"delays",
"=",
"delays",
";",
"return",
"reservation",
";",
"}"
] |
Attempts to find the next time that all resources are available, starting
from the start time, with a duration of at least min minutes but no more
than max minutes.
|
[
"Attempts",
"to",
"find",
"the",
"next",
"time",
"that",
"all",
"resources",
"are",
"available",
"starting",
"from",
"the",
"start",
"time",
"with",
"a",
"duration",
"of",
"at",
"least",
"min",
"minutes",
"but",
"no",
"more",
"than",
"max",
"minutes",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L50-L61
|
17,130
|
bunkat/schedule
|
src/core/resource-manager.js
|
initRanges
|
function initRanges(resources, start, ranges, delays) {
for(var i = 0, len = resources.length; i < len; i++) {
var resId = resources[i];
// handles nested resources (OR)
if(Array.isArray(resId)) {
var subRanges = [], subDelays = {};
initRanges(resId, start, subRanges, subDelays);
var longDelay = getLongestDelay(subDelays);
if(longDelay) {
delays[longDelay] = subDelays[longDelay];
}
var schedule = {subRanges: subRanges};
setEarliestSubRange(schedule);
ranges.push(schedule);
}
else {
var res = rMap[resId],
range = res.nextAvail[0] >= start ? res.nextAvail :
res.next(start);
if(range[0] > start && resId !== '_proj') {
delays[resId] = { needed: start, available: range[0] };
}
ranges.push({id: resId, range: range});
}
}
}
|
javascript
|
function initRanges(resources, start, ranges, delays) {
for(var i = 0, len = resources.length; i < len; i++) {
var resId = resources[i];
// handles nested resources (OR)
if(Array.isArray(resId)) {
var subRanges = [], subDelays = {};
initRanges(resId, start, subRanges, subDelays);
var longDelay = getLongestDelay(subDelays);
if(longDelay) {
delays[longDelay] = subDelays[longDelay];
}
var schedule = {subRanges: subRanges};
setEarliestSubRange(schedule);
ranges.push(schedule);
}
else {
var res = rMap[resId],
range = res.nextAvail[0] >= start ? res.nextAvail :
res.next(start);
if(range[0] > start && resId !== '_proj') {
delays[resId] = { needed: start, available: range[0] };
}
ranges.push({id: resId, range: range});
}
}
}
|
[
"function",
"initRanges",
"(",
"resources",
",",
"start",
",",
"ranges",
",",
"delays",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"resources",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"resId",
"=",
"resources",
"[",
"i",
"]",
";",
"// handles nested resources (OR)",
"if",
"(",
"Array",
".",
"isArray",
"(",
"resId",
")",
")",
"{",
"var",
"subRanges",
"=",
"[",
"]",
",",
"subDelays",
"=",
"{",
"}",
";",
"initRanges",
"(",
"resId",
",",
"start",
",",
"subRanges",
",",
"subDelays",
")",
";",
"var",
"longDelay",
"=",
"getLongestDelay",
"(",
"subDelays",
")",
";",
"if",
"(",
"longDelay",
")",
"{",
"delays",
"[",
"longDelay",
"]",
"=",
"subDelays",
"[",
"longDelay",
"]",
";",
"}",
"var",
"schedule",
"=",
"{",
"subRanges",
":",
"subRanges",
"}",
";",
"setEarliestSubRange",
"(",
"schedule",
")",
";",
"ranges",
".",
"push",
"(",
"schedule",
")",
";",
"}",
"else",
"{",
"var",
"res",
"=",
"rMap",
"[",
"resId",
"]",
",",
"range",
"=",
"res",
".",
"nextAvail",
"[",
"0",
"]",
">=",
"start",
"?",
"res",
".",
"nextAvail",
":",
"res",
".",
"next",
"(",
"start",
")",
";",
"if",
"(",
"range",
"[",
"0",
"]",
">",
"start",
"&&",
"resId",
"!==",
"'_proj'",
")",
"{",
"delays",
"[",
"resId",
"]",
"=",
"{",
"needed",
":",
"start",
",",
"available",
":",
"range",
"[",
"0",
"]",
"}",
";",
"}",
"ranges",
".",
"push",
"(",
"{",
"id",
":",
"resId",
",",
"range",
":",
"range",
"}",
")",
";",
"}",
"}",
"}"
] |
Initializes the resource schedule availablity based on the start date
provided. Resources that were not immediately available are captured in
the delays array to be reported with the reservation.
|
[
"Initializes",
"the",
"resource",
"schedule",
"availablity",
"based",
"on",
"the",
"start",
"date",
"provided",
".",
"Resources",
"that",
"were",
"not",
"immediately",
"available",
"are",
"captured",
"in",
"the",
"delays",
"array",
"to",
"be",
"reported",
"with",
"the",
"reservation",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L68-L98
|
17,131
|
bunkat/schedule
|
src/core/resource-manager.js
|
tryReservation
|
function tryReservation(schedules, min,max) {
var reservation = {success: false},
resources = [], start, end;
for(var i = 0, len = schedules.length; i < len; i++) {
var schedule = schedules[i],
range = schedule.range;
if(!isInternal(schedule)) {
resources.push(schedule.id);
}
start = !start || range[0] > start ? range[0] : start;
end = !end || range[1] < end ? range[1] : end;
}
var duration = (end - start) / later.MIN;
if(duration >= min || duration >= max) {
duration = max && duration > max ? max : duration;
reservation = createReservation(resources, start, duration);
}
return reservation;
}
|
javascript
|
function tryReservation(schedules, min,max) {
var reservation = {success: false},
resources = [], start, end;
for(var i = 0, len = schedules.length; i < len; i++) {
var schedule = schedules[i],
range = schedule.range;
if(!isInternal(schedule)) {
resources.push(schedule.id);
}
start = !start || range[0] > start ? range[0] : start;
end = !end || range[1] < end ? range[1] : end;
}
var duration = (end - start) / later.MIN;
if(duration >= min || duration >= max) {
duration = max && duration > max ? max : duration;
reservation = createReservation(resources, start, duration);
}
return reservation;
}
|
[
"function",
"tryReservation",
"(",
"schedules",
",",
"min",
",",
"max",
")",
"{",
"var",
"reservation",
"=",
"{",
"success",
":",
"false",
"}",
",",
"resources",
"=",
"[",
"]",
",",
"start",
",",
"end",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"schedules",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"schedule",
"=",
"schedules",
"[",
"i",
"]",
",",
"range",
"=",
"schedule",
".",
"range",
";",
"if",
"(",
"!",
"isInternal",
"(",
"schedule",
")",
")",
"{",
"resources",
".",
"push",
"(",
"schedule",
".",
"id",
")",
";",
"}",
"start",
"=",
"!",
"start",
"||",
"range",
"[",
"0",
"]",
">",
"start",
"?",
"range",
"[",
"0",
"]",
":",
"start",
";",
"end",
"=",
"!",
"end",
"||",
"range",
"[",
"1",
"]",
"<",
"end",
"?",
"range",
"[",
"1",
"]",
":",
"end",
";",
"}",
"var",
"duration",
"=",
"(",
"end",
"-",
"start",
")",
"/",
"later",
".",
"MIN",
";",
"if",
"(",
"duration",
">=",
"min",
"||",
"duration",
">=",
"max",
")",
"{",
"duration",
"=",
"max",
"&&",
"duration",
">",
"max",
"?",
"max",
":",
"duration",
";",
"reservation",
"=",
"createReservation",
"(",
"resources",
",",
"start",
",",
"duration",
")",
";",
"}",
"return",
"reservation",
";",
"}"
] |
Determines if the current schedules overlap for at least min minutes. If
they do, a reservation is created, otherwise a failure is reported.
|
[
"Determines",
"if",
"the",
"current",
"schedules",
"overlap",
"for",
"at",
"least",
"min",
"minutes",
".",
"If",
"they",
"do",
"a",
"reservation",
"is",
"created",
"otherwise",
"a",
"failure",
"is",
"reported",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L104-L127
|
17,132
|
bunkat/schedule
|
src/core/resource-manager.js
|
createReservation
|
function createReservation(resources, start, duration) {
var end = start + (duration * later.MIN),
reservation = {
resources: resources,
start: start,
end: end,
duration: duration,
success: true
};
applyReservation(resources, start, end);
return reservation;
}
|
javascript
|
function createReservation(resources, start, duration) {
var end = start + (duration * later.MIN),
reservation = {
resources: resources,
start: start,
end: end,
duration: duration,
success: true
};
applyReservation(resources, start, end);
return reservation;
}
|
[
"function",
"createReservation",
"(",
"resources",
",",
"start",
",",
"duration",
")",
"{",
"var",
"end",
"=",
"start",
"+",
"(",
"duration",
"*",
"later",
".",
"MIN",
")",
",",
"reservation",
"=",
"{",
"resources",
":",
"resources",
",",
"start",
":",
"start",
",",
"end",
":",
"end",
",",
"duration",
":",
"duration",
",",
"success",
":",
"true",
"}",
";",
"applyReservation",
"(",
"resources",
",",
"start",
",",
"end",
")",
";",
"return",
"reservation",
";",
"}"
] |
Generates a new reservation object and reserves the associated resources.
|
[
"Generates",
"a",
"new",
"reservation",
"object",
"and",
"reserves",
"the",
"associated",
"resources",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L132-L144
|
17,133
|
bunkat/schedule
|
src/core/resource-manager.js
|
updateRanges
|
function updateRanges(resources, start, delays) {
for(var i = 0, len = resources.length; i < len; i++) {
var res = resources[i];
if(res.range[1] > start) continue;
if(res.subRanges) {
updateRanges(res.subRanges, start, {});
setEarliestSubRange(res);
}
else {
res.range = rMap[res.id].next(start);
if(res.id !== '_proj' && !delays[res.id]) {
delays[res.id] = { needed: start, available: res.range[0] };
}
}
}
}
|
javascript
|
function updateRanges(resources, start, delays) {
for(var i = 0, len = resources.length; i < len; i++) {
var res = resources[i];
if(res.range[1] > start) continue;
if(res.subRanges) {
updateRanges(res.subRanges, start, {});
setEarliestSubRange(res);
}
else {
res.range = rMap[res.id].next(start);
if(res.id !== '_proj' && !delays[res.id]) {
delays[res.id] = { needed: start, available: res.range[0] };
}
}
}
}
|
[
"function",
"updateRanges",
"(",
"resources",
",",
"start",
",",
"delays",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"resources",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"res",
"=",
"resources",
"[",
"i",
"]",
";",
"if",
"(",
"res",
".",
"range",
"[",
"1",
"]",
">",
"start",
")",
"continue",
";",
"if",
"(",
"res",
".",
"subRanges",
")",
"{",
"updateRanges",
"(",
"res",
".",
"subRanges",
",",
"start",
",",
"{",
"}",
")",
";",
"setEarliestSubRange",
"(",
"res",
")",
";",
"}",
"else",
"{",
"res",
".",
"range",
"=",
"rMap",
"[",
"res",
".",
"id",
"]",
".",
"next",
"(",
"start",
")",
";",
"if",
"(",
"res",
".",
"id",
"!==",
"'_proj'",
"&&",
"!",
"delays",
"[",
"res",
".",
"id",
"]",
")",
"{",
"delays",
"[",
"res",
".",
"id",
"]",
"=",
"{",
"needed",
":",
"start",
",",
"available",
":",
"res",
".",
"range",
"[",
"0",
"]",
"}",
";",
"}",
"}",
"}",
"}"
] |
Updates ranges after a failed reservation attempt. Resources that were not
immediately available are captured in the delays array to be reported with
the reservation.
|
[
"Updates",
"ranges",
"after",
"a",
"failed",
"reservation",
"attempt",
".",
"Resources",
"that",
"were",
"not",
"immediately",
"available",
"are",
"captured",
"in",
"the",
"delays",
"array",
"to",
"be",
"reported",
"with",
"the",
"reservation",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L151-L168
|
17,134
|
bunkat/schedule
|
src/core/resource-manager.js
|
nextValidStart
|
function nextValidStart(schedules) {
var latest;
for(var i = 0, len = schedules.length; i < len; i++) {
var end = schedules[i].range[1];
latest = !latest || end < latest ? end : latest;
}
return latest;
}
|
javascript
|
function nextValidStart(schedules) {
var latest;
for(var i = 0, len = schedules.length; i < len; i++) {
var end = schedules[i].range[1];
latest = !latest || end < latest ? end : latest;
}
return latest;
}
|
[
"function",
"nextValidStart",
"(",
"schedules",
")",
"{",
"var",
"latest",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"schedules",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"end",
"=",
"schedules",
"[",
"i",
"]",
".",
"range",
"[",
"1",
"]",
";",
"latest",
"=",
"!",
"latest",
"||",
"end",
"<",
"latest",
"?",
"end",
":",
"latest",
";",
"}",
"return",
"latest",
";",
"}"
] |
Determines the earliest time that a schedule goes invalid which is the
time that should be used to update resource ranges from.
|
[
"Determines",
"the",
"earliest",
"time",
"that",
"a",
"schedule",
"goes",
"invalid",
"which",
"is",
"the",
"time",
"that",
"should",
"be",
"used",
"to",
"update",
"resource",
"ranges",
"from",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L196-L204
|
17,135
|
bunkat/schedule
|
src/core/resource-manager.js
|
getLongestDelay
|
function getLongestDelay(delays) {
var latest, lid;
for(var id in delays) {
var available = delays[id].available;
if(!latest || available < latest) {
latest = available;
lid = id;
}
}
return lid;
}
|
javascript
|
function getLongestDelay(delays) {
var latest, lid;
for(var id in delays) {
var available = delays[id].available;
if(!latest || available < latest) {
latest = available;
lid = id;
}
}
return lid;
}
|
[
"function",
"getLongestDelay",
"(",
"delays",
")",
"{",
"var",
"latest",
",",
"lid",
";",
"for",
"(",
"var",
"id",
"in",
"delays",
")",
"{",
"var",
"available",
"=",
"delays",
"[",
"id",
"]",
".",
"available",
";",
"if",
"(",
"!",
"latest",
"||",
"available",
"<",
"latest",
")",
"{",
"latest",
"=",
"available",
";",
"lid",
"=",
"id",
";",
"}",
"}",
"return",
"lid",
";",
"}"
] |
Determines the longest delay amongst a set of delays. Used to determine
which resource to report for resources that are OR'd together.
|
[
"Determines",
"the",
"longest",
"delay",
"amongst",
"a",
"set",
"of",
"delays",
".",
"Used",
"to",
"determine",
"which",
"resource",
"to",
"report",
"for",
"resources",
"that",
"are",
"OR",
"d",
"together",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L230-L241
|
17,136
|
bunkat/schedule
|
src/core/resource-manager.js
|
function(arr, prefix, start) {
for(var i = 0, len = arr.length; i < len; i++) {
var def = typeof arr[i] !== 'object' ?
{ id: prefix + arr[i] } :
{ id: prefix + arr[i].id, available: arr[i].available, isNotReservable: arr[i].isNotReservable };
if(!rMap[def.id]) {
addResourceToMap(rMap, def, start);
}
}
}
|
javascript
|
function(arr, prefix, start) {
for(var i = 0, len = arr.length; i < len; i++) {
var def = typeof arr[i] !== 'object' ?
{ id: prefix + arr[i] } :
{ id: prefix + arr[i].id, available: arr[i].available, isNotReservable: arr[i].isNotReservable };
if(!rMap[def.id]) {
addResourceToMap(rMap, def, start);
}
}
}
|
[
"function",
"(",
"arr",
",",
"prefix",
",",
"start",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"arr",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"def",
"=",
"typeof",
"arr",
"[",
"i",
"]",
"!==",
"'object'",
"?",
"{",
"id",
":",
"prefix",
"+",
"arr",
"[",
"i",
"]",
"}",
":",
"{",
"id",
":",
"prefix",
"+",
"arr",
"[",
"i",
"]",
".",
"id",
",",
"available",
":",
"arr",
"[",
"i",
"]",
".",
"available",
",",
"isNotReservable",
":",
"arr",
"[",
"i",
"]",
".",
"isNotReservable",
"}",
";",
"if",
"(",
"!",
"rMap",
"[",
"def",
".",
"id",
"]",
")",
"{",
"addResourceToMap",
"(",
"rMap",
",",
"def",
",",
"start",
")",
";",
"}",
"}",
"}"
] |
Adds a new resource to the resource map if a resource doesn't already exist
with that id. Expects resources to be passed in as an array and will
prefix each resource with the prefix specified.
|
[
"Adds",
"a",
"new",
"resource",
"to",
"the",
"resource",
"map",
"if",
"a",
"resource",
"doesn",
"t",
"already",
"exist",
"with",
"that",
"id",
".",
"Expects",
"resources",
"to",
"be",
"passed",
"in",
"as",
"an",
"array",
"and",
"will",
"prefix",
"each",
"resource",
"with",
"the",
"prefix",
"specified",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L265-L275
|
|
17,137
|
bunkat/schedule
|
src/core/resource-manager.js
|
function(resources, start, min, max) {
start = start ? new Date(start) : new Date();
return getReservation(resources, start.getTime(), min || 1, max);
}
|
javascript
|
function(resources, start, min, max) {
start = start ? new Date(start) : new Date();
return getReservation(resources, start.getTime(), min || 1, max);
}
|
[
"function",
"(",
"resources",
",",
"start",
",",
"min",
",",
"max",
")",
"{",
"start",
"=",
"start",
"?",
"new",
"Date",
"(",
"start",
")",
":",
"new",
"Date",
"(",
")",
";",
"return",
"getReservation",
"(",
"resources",
",",
"start",
".",
"getTime",
"(",
")",
",",
"min",
"||",
"1",
",",
"max",
")",
";",
"}"
] |
Attempts to reserve the set of resources at the earliest possible time from
start time provide with a duration of at least min and no more than max
minutes.
|
[
"Attempts",
"to",
"reserve",
"the",
"set",
"of",
"resources",
"at",
"the",
"earliest",
"possible",
"time",
"from",
"start",
"time",
"provide",
"with",
"a",
"duration",
"of",
"at",
"least",
"min",
"and",
"no",
"more",
"than",
"max",
"minutes",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resource-manager.js#L282-L285
|
|
17,138
|
bunkat/schedule
|
src/core/resources.js
|
resources
|
function resources(data) {
var items = [],
fid = schedule.functor(id),
favailable = schedule.functor(available),
freserve = schedule.functor(isNotReservable);
for(var i = 0, len = data.length; i < len; i++) {
var resource = data[i],
rId = fid.call(this, resource, i),
rAvailable = favailable.call(this, resource, i),
rReserve = freserve.call(this, resource, i);
items.push({id: rId, available: rAvailable, isNotReservable: rReserve});
}
return items;
}
|
javascript
|
function resources(data) {
var items = [],
fid = schedule.functor(id),
favailable = schedule.functor(available),
freserve = schedule.functor(isNotReservable);
for(var i = 0, len = data.length; i < len; i++) {
var resource = data[i],
rId = fid.call(this, resource, i),
rAvailable = favailable.call(this, resource, i),
rReserve = freserve.call(this, resource, i);
items.push({id: rId, available: rAvailable, isNotReservable: rReserve});
}
return items;
}
|
[
"function",
"resources",
"(",
"data",
")",
"{",
"var",
"items",
"=",
"[",
"]",
",",
"fid",
"=",
"schedule",
".",
"functor",
"(",
"id",
")",
",",
"favailable",
"=",
"schedule",
".",
"functor",
"(",
"available",
")",
",",
"freserve",
"=",
"schedule",
".",
"functor",
"(",
"isNotReservable",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"data",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"resource",
"=",
"data",
"[",
"i",
"]",
",",
"rId",
"=",
"fid",
".",
"call",
"(",
"this",
",",
"resource",
",",
"i",
")",
",",
"rAvailable",
"=",
"favailable",
".",
"call",
"(",
"this",
",",
"resource",
",",
"i",
")",
",",
"rReserve",
"=",
"freserve",
".",
"call",
"(",
"this",
",",
"resource",
",",
"i",
")",
";",
"items",
".",
"push",
"(",
"{",
"id",
":",
"rId",
",",
"available",
":",
"rAvailable",
",",
"isNotReservable",
":",
"rReserve",
"}",
")",
";",
"}",
"return",
"items",
";",
"}"
] |
Takes an array of objects and returns an array of schedule resource objects.
|
[
"Takes",
"an",
"array",
"of",
"objects",
"and",
"returns",
"an",
"array",
"of",
"schedule",
"resource",
"objects",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/resources.js#L21-L37
|
17,139
|
bunkat/schedule
|
src/core/create.js
|
forwardPassTask
|
function forwardPassTask(task, start) {
var resAll = ['_proj', '_task' + task.id],
resources = task.resources ? resAll.concat(task.resources) : resAll,
duration = task.duration,
next = start,
scheduledTask = {schedule: [], duration: task.duration};
while(duration) {
var r = resMgr.makeReservation(resources, next, task.minSchedule || 1, duration);
if(!r.success) return undefined;
scheduledTask.earlyStart = scheduledTask.earlyStart || r.start;
scheduledTask.schedule.push(r);
duration -= r.duration;
next = r.end;
}
scheduledTask.earlyFinish = next;
scheduledTasks[task.id] = scheduledTask;
return next;
}
|
javascript
|
function forwardPassTask(task, start) {
var resAll = ['_proj', '_task' + task.id],
resources = task.resources ? resAll.concat(task.resources) : resAll,
duration = task.duration,
next = start,
scheduledTask = {schedule: [], duration: task.duration};
while(duration) {
var r = resMgr.makeReservation(resources, next, task.minSchedule || 1, duration);
if(!r.success) return undefined;
scheduledTask.earlyStart = scheduledTask.earlyStart || r.start;
scheduledTask.schedule.push(r);
duration -= r.duration;
next = r.end;
}
scheduledTask.earlyFinish = next;
scheduledTasks[task.id] = scheduledTask;
return next;
}
|
[
"function",
"forwardPassTask",
"(",
"task",
",",
"start",
")",
"{",
"var",
"resAll",
"=",
"[",
"'_proj'",
",",
"'_task'",
"+",
"task",
".",
"id",
"]",
",",
"resources",
"=",
"task",
".",
"resources",
"?",
"resAll",
".",
"concat",
"(",
"task",
".",
"resources",
")",
":",
"resAll",
",",
"duration",
"=",
"task",
".",
"duration",
",",
"next",
"=",
"start",
",",
"scheduledTask",
"=",
"{",
"schedule",
":",
"[",
"]",
",",
"duration",
":",
"task",
".",
"duration",
"}",
";",
"while",
"(",
"duration",
")",
"{",
"var",
"r",
"=",
"resMgr",
".",
"makeReservation",
"(",
"resources",
",",
"next",
",",
"task",
".",
"minSchedule",
"||",
"1",
",",
"duration",
")",
";",
"if",
"(",
"!",
"r",
".",
"success",
")",
"return",
"undefined",
";",
"scheduledTask",
".",
"earlyStart",
"=",
"scheduledTask",
".",
"earlyStart",
"||",
"r",
".",
"start",
";",
"scheduledTask",
".",
"schedule",
".",
"push",
"(",
"r",
")",
";",
"duration",
"-=",
"r",
".",
"duration",
";",
"next",
"=",
"r",
".",
"end",
";",
"}",
"scheduledTask",
".",
"earlyFinish",
"=",
"next",
";",
"scheduledTasks",
"[",
"task",
".",
"id",
"]",
"=",
"scheduledTask",
";",
"return",
"next",
";",
"}"
] |
Finds the next available time that all of a tasks constraints are met and
makes the appropriate resource reservations. A task may be scheduled in a
single contiguous block or multiple blocks of time.
|
[
"Finds",
"the",
"next",
"available",
"time",
"that",
"all",
"of",
"a",
"tasks",
"constraints",
"are",
"met",
"and",
"makes",
"the",
"appropriate",
"resource",
"reservations",
".",
"A",
"task",
"may",
"be",
"scheduled",
"in",
"a",
"single",
"contiguous",
"block",
"or",
"multiple",
"blocks",
"of",
"time",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/create.js#L88-L109
|
17,140
|
bunkat/schedule
|
src/core/dependency-graph.js
|
createDependencyGraph
|
function createDependencyGraph(tasks) {
var graph = {
tasks: {},
roots: [],
leaves: [],
resources: [],
depth: 0,
end : 0
};
for(var i = 0, len = tasks.length; i < len; i++) {
var t = tasks[i];
graph.tasks[t.id] = {
id: t.id,
duration: t.duration,
priority: t.priority,
schedule: t.schedule,
minSchedule: t.minSchedule,
dependsOn: t.dependsOn,
resources: t.resources
};
}
setResources(graph);
setRequiredBy(graph.tasks);
setRootsAndLeaves(graph);
setDepth(graph, graph.leaves, 0);
graph.depth += 1; // increment depth so it is 1 based
forwardPass(graph, {}, graph.roots, 0);
setEnd(graph, graph.leaves);
backwardPass(graph, {}, graph.leaves, graph.end);
return graph;
}
|
javascript
|
function createDependencyGraph(tasks) {
var graph = {
tasks: {},
roots: [],
leaves: [],
resources: [],
depth: 0,
end : 0
};
for(var i = 0, len = tasks.length; i < len; i++) {
var t = tasks[i];
graph.tasks[t.id] = {
id: t.id,
duration: t.duration,
priority: t.priority,
schedule: t.schedule,
minSchedule: t.minSchedule,
dependsOn: t.dependsOn,
resources: t.resources
};
}
setResources(graph);
setRequiredBy(graph.tasks);
setRootsAndLeaves(graph);
setDepth(graph, graph.leaves, 0);
graph.depth += 1; // increment depth so it is 1 based
forwardPass(graph, {}, graph.roots, 0);
setEnd(graph, graph.leaves);
backwardPass(graph, {}, graph.leaves, graph.end);
return graph;
}
|
[
"function",
"createDependencyGraph",
"(",
"tasks",
")",
"{",
"var",
"graph",
"=",
"{",
"tasks",
":",
"{",
"}",
",",
"roots",
":",
"[",
"]",
",",
"leaves",
":",
"[",
"]",
",",
"resources",
":",
"[",
"]",
",",
"depth",
":",
"0",
",",
"end",
":",
"0",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"tasks",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"t",
"=",
"tasks",
"[",
"i",
"]",
";",
"graph",
".",
"tasks",
"[",
"t",
".",
"id",
"]",
"=",
"{",
"id",
":",
"t",
".",
"id",
",",
"duration",
":",
"t",
".",
"duration",
",",
"priority",
":",
"t",
".",
"priority",
",",
"schedule",
":",
"t",
".",
"schedule",
",",
"minSchedule",
":",
"t",
".",
"minSchedule",
",",
"dependsOn",
":",
"t",
".",
"dependsOn",
",",
"resources",
":",
"t",
".",
"resources",
"}",
";",
"}",
"setResources",
"(",
"graph",
")",
";",
"setRequiredBy",
"(",
"graph",
".",
"tasks",
")",
";",
"setRootsAndLeaves",
"(",
"graph",
")",
";",
"setDepth",
"(",
"graph",
",",
"graph",
".",
"leaves",
",",
"0",
")",
";",
"graph",
".",
"depth",
"+=",
"1",
";",
"// increment depth so it is 1 based",
"forwardPass",
"(",
"graph",
",",
"{",
"}",
",",
"graph",
".",
"roots",
",",
"0",
")",
";",
"setEnd",
"(",
"graph",
",",
"graph",
".",
"leaves",
")",
";",
"backwardPass",
"(",
"graph",
",",
"{",
"}",
",",
"graph",
".",
"leaves",
",",
"graph",
".",
"end",
")",
";",
"return",
"graph",
";",
"}"
] |
Starting point for creating the dependency graph, clones the tasks and
then fills out the graph properties.
|
[
"Starting",
"point",
"for",
"creating",
"the",
"dependency",
"graph",
"clones",
"the",
"tasks",
"and",
"then",
"fills",
"out",
"the",
"graph",
"properties",
"."
] |
7698978c94e3c54a3e26c1ee701fef8349102ff5
|
https://github.com/bunkat/schedule/blob/7698978c94e3c54a3e26c1ee701fef8349102ff5/src/core/dependency-graph.js#L21-L56
|
17,141
|
milankinen/livereactload
|
examples/02-redux/src/reducers/counter.js
|
counter
|
function counter(state = 0, action = {}) {
switch (action.type) {
case INCREMENT_COUNTER:
return state + 1;
case DECREMENT_COUNTER:
return state - 1;
default:
return state;
}
}
|
javascript
|
function counter(state = 0, action = {}) {
switch (action.type) {
case INCREMENT_COUNTER:
return state + 1;
case DECREMENT_COUNTER:
return state - 1;
default:
return state;
}
}
|
[
"function",
"counter",
"(",
"state",
"=",
"0",
",",
"action",
"=",
"{",
"}",
")",
"{",
"switch",
"(",
"action",
".",
"type",
")",
"{",
"case",
"INCREMENT_COUNTER",
":",
"return",
"state",
"+",
"1",
";",
"case",
"DECREMENT_COUNTER",
":",
"return",
"state",
"-",
"1",
";",
"default",
":",
"return",
"state",
";",
"}",
"}"
] |
reducer for the counter
@param {number} state input state
@param {object} action object containing the action type
@param {string} action.type action type
@return {number}
|
[
"reducer",
"for",
"the",
"counter"
] |
4ec023240308e0603f6e40c16f2ab1757eab467d
|
https://github.com/milankinen/livereactload/blob/4ec023240308e0603f6e40c16f2ab1757eab467d/examples/02-redux/src/reducers/counter.js#L14-L23
|
17,142
|
lega911/angular-light
|
src/ext/router.es.js
|
routeMatcher
|
function routeMatcher(route) {
var segments = route.replace(/^\/+|\/+$/, '').split(/\/+/);
var names = [];
var rules = [];
segments.forEach(function(segment){
var rule;
if (segment.charAt(0) === ':') {
names.push(segment.slice(1));
rules.push('([^\/]+)');
} else if (segment === '**') {
names.push('tail');
rules.push('(.+)');
} else {
rules.push(escapeRegExp(segment));
}
});
var regex = new RegExp('^\/' + rules.join('\/') + '\/?$', 'i');
var matcher = function(url) {
var match = url.match(regex);
if (! match) {
return;
}
var result = {};
names.forEach(function(name, i) {
result[name] = match[i + 1];
});
return result;
};
return matcher;
}
|
javascript
|
function routeMatcher(route) {
var segments = route.replace(/^\/+|\/+$/, '').split(/\/+/);
var names = [];
var rules = [];
segments.forEach(function(segment){
var rule;
if (segment.charAt(0) === ':') {
names.push(segment.slice(1));
rules.push('([^\/]+)');
} else if (segment === '**') {
names.push('tail');
rules.push('(.+)');
} else {
rules.push(escapeRegExp(segment));
}
});
var regex = new RegExp('^\/' + rules.join('\/') + '\/?$', 'i');
var matcher = function(url) {
var match = url.match(regex);
if (! match) {
return;
}
var result = {};
names.forEach(function(name, i) {
result[name] = match[i + 1];
});
return result;
};
return matcher;
}
|
[
"function",
"routeMatcher",
"(",
"route",
")",
"{",
"var",
"segments",
"=",
"route",
".",
"replace",
"(",
"/",
"^\\/+|\\/+$",
"/",
",",
"''",
")",
".",
"split",
"(",
"/",
"\\/+",
"/",
")",
";",
"var",
"names",
"=",
"[",
"]",
";",
"var",
"rules",
"=",
"[",
"]",
";",
"segments",
".",
"forEach",
"(",
"function",
"(",
"segment",
")",
"{",
"var",
"rule",
";",
"if",
"(",
"segment",
".",
"charAt",
"(",
"0",
")",
"===",
"':'",
")",
"{",
"names",
".",
"push",
"(",
"segment",
".",
"slice",
"(",
"1",
")",
")",
";",
"rules",
".",
"push",
"(",
"'([^\\/]+)'",
")",
";",
"}",
"else",
"if",
"(",
"segment",
"===",
"'**'",
")",
"{",
"names",
".",
"push",
"(",
"'tail'",
")",
";",
"rules",
".",
"push",
"(",
"'(.+)'",
")",
";",
"}",
"else",
"{",
"rules",
".",
"push",
"(",
"escapeRegExp",
"(",
"segment",
")",
")",
";",
"}",
"}",
")",
";",
"var",
"regex",
"=",
"new",
"RegExp",
"(",
"'^\\/'",
"+",
"rules",
".",
"join",
"(",
"'\\/'",
")",
"+",
"'\\/?$'",
",",
"'i'",
")",
";",
"var",
"matcher",
"=",
"function",
"(",
"url",
")",
"{",
"var",
"match",
"=",
"url",
".",
"match",
"(",
"regex",
")",
";",
"if",
"(",
"!",
"match",
")",
"{",
"return",
";",
"}",
"var",
"result",
"=",
"{",
"}",
";",
"names",
".",
"forEach",
"(",
"function",
"(",
"name",
",",
"i",
")",
"{",
"result",
"[",
"name",
"]",
"=",
"match",
"[",
"i",
"+",
"1",
"]",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
";",
"return",
"matcher",
";",
"}"
] |
coded by rumkin
|
[
"coded",
"by",
"rumkin"
] |
9450ce65e79b7068ac3ef35a9572a866d104edf8
|
https://github.com/lega911/angular-light/blob/9450ce65e79b7068ac3ef35a9572a866d104edf8/src/ext/router.es.js#L274-L309
|
17,143
|
publiclab/inline-markdown-editor
|
spec/javascripts/customizations_spec.js
|
exampleBookFunction
|
function exampleBookFunction(element, uniqueId) {
expect(element).not.toBeUndefined();
expect(element.length).toBe(1);
expect($('.inline-edit-btn-' + uniqueId).length).toBe(2); // two because there are two buttons per section
expect($('.inline-edit-btn-' + uniqueId + '-fa-book').length).toBe(1);
buttonSetupRunCount += 1;
}
|
javascript
|
function exampleBookFunction(element, uniqueId) {
expect(element).not.toBeUndefined();
expect(element.length).toBe(1);
expect($('.inline-edit-btn-' + uniqueId).length).toBe(2); // two because there are two buttons per section
expect($('.inline-edit-btn-' + uniqueId + '-fa-book').length).toBe(1);
buttonSetupRunCount += 1;
}
|
[
"function",
"exampleBookFunction",
"(",
"element",
",",
"uniqueId",
")",
"{",
"expect",
"(",
"element",
")",
".",
"not",
".",
"toBeUndefined",
"(",
")",
";",
"expect",
"(",
"element",
".",
"length",
")",
".",
"toBe",
"(",
"1",
")",
";",
"expect",
"(",
"$",
"(",
"'.inline-edit-btn-'",
"+",
"uniqueId",
")",
".",
"length",
")",
".",
"toBe",
"(",
"2",
")",
";",
"// two because there are two buttons per section",
"expect",
"(",
"$",
"(",
"'.inline-edit-btn-'",
"+",
"uniqueId",
"+",
"'-fa-book'",
")",
".",
"length",
")",
".",
"toBe",
"(",
"1",
")",
";",
"buttonSetupRunCount",
"+=",
"1",
";",
"}"
] |
here we specify a button icon and a function to be run on it
|
[
"here",
"we",
"specify",
"a",
"button",
"icon",
"and",
"a",
"function",
"to",
"be",
"run",
"on",
"it"
] |
c6342531174ee9dd92538ae63efc1e303cc7e842
|
https://github.com/publiclab/inline-markdown-editor/blob/c6342531174ee9dd92538ae63efc1e303cc7e842/spec/javascripts/customizations_spec.js#L13-L19
|
17,144
|
publiclab/inline-markdown-editor
|
src/processSection.js
|
onEdit
|
function onEdit() {
var editor;
if (o.wysiwyg && $('#' + uniqueId).find('.wk-container').length === 0) {
// insert rich editor
var editorOptions = o.editorOptions || {};
editorOptions.textarea = $('#' + uniqueId + ' textarea')[0];
editorOptions.tagsModule = (editorOptions.tagsModule === true); // disable this to not require Bloodhound, unless overridden
editor = new PL.Editor(editorOptions);
}
_form.find('.cancel').click(function inlineEditCancelClick(e) {
e.preventDefault();
_form.hide();
});
_form.find('button.submit').click(function(e) {
prepareAndSendSectionForm(e, _form, editor, originalSectionMarkdown);
});
}
|
javascript
|
function onEdit() {
var editor;
if (o.wysiwyg && $('#' + uniqueId).find('.wk-container').length === 0) {
// insert rich editor
var editorOptions = o.editorOptions || {};
editorOptions.textarea = $('#' + uniqueId + ' textarea')[0];
editorOptions.tagsModule = (editorOptions.tagsModule === true); // disable this to not require Bloodhound, unless overridden
editor = new PL.Editor(editorOptions);
}
_form.find('.cancel').click(function inlineEditCancelClick(e) {
e.preventDefault();
_form.hide();
});
_form.find('button.submit').click(function(e) {
prepareAndSendSectionForm(e, _form, editor, originalSectionMarkdown);
});
}
|
[
"function",
"onEdit",
"(",
")",
"{",
"var",
"editor",
";",
"if",
"(",
"o",
".",
"wysiwyg",
"&&",
"$",
"(",
"'#'",
"+",
"uniqueId",
")",
".",
"find",
"(",
"'.wk-container'",
")",
".",
"length",
"===",
"0",
")",
"{",
"// insert rich editor",
"var",
"editorOptions",
"=",
"o",
".",
"editorOptions",
"||",
"{",
"}",
";",
"editorOptions",
".",
"textarea",
"=",
"$",
"(",
"'#'",
"+",
"uniqueId",
"+",
"' textarea'",
")",
"[",
"0",
"]",
";",
"editorOptions",
".",
"tagsModule",
"=",
"(",
"editorOptions",
".",
"tagsModule",
"===",
"true",
")",
";",
"// disable this to not require Bloodhound, unless overridden",
"editor",
"=",
"new",
"PL",
".",
"Editor",
"(",
"editorOptions",
")",
";",
"}",
"_form",
".",
"find",
"(",
"'.cancel'",
")",
".",
"click",
"(",
"function",
"inlineEditCancelClick",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"_form",
".",
"hide",
"(",
")",
";",
"}",
")",
";",
"_form",
".",
"find",
"(",
"'button.submit'",
")",
".",
"click",
"(",
"function",
"(",
"e",
")",
"{",
"prepareAndSendSectionForm",
"(",
"e",
",",
"_form",
",",
"editor",
",",
"originalSectionMarkdown",
")",
";",
"}",
")",
";",
"}"
] |
plan for swappable editors; will need to specify both constructor and onEditorSubmit
|
[
"plan",
"for",
"swappable",
"editors",
";",
"will",
"need",
"to",
"specify",
"both",
"constructor",
"and",
"onEditorSubmit"
] |
c6342531174ee9dd92538ae63efc1e303cc7e842
|
https://github.com/publiclab/inline-markdown-editor/blob/c6342531174ee9dd92538ae63efc1e303cc7e842/src/processSection.js#L27-L43
|
17,145
|
fex-team/kity
|
demo/public/draggable.js
|
function () {
var target = this.dragTarget;
target.off( DRAG_START_EVENT, target._dragStartHandler );
target.getPaper().off( DRAG_END_EVENT, target._dragEndHandler );
delete target._dragStartHandler;
delete target._dragEndHandler;
this.dragEnabled = false;
return this;
}
|
javascript
|
function () {
var target = this.dragTarget;
target.off( DRAG_START_EVENT, target._dragStartHandler );
target.getPaper().off( DRAG_END_EVENT, target._dragEndHandler );
delete target._dragStartHandler;
delete target._dragEndHandler;
this.dragEnabled = false;
return this;
}
|
[
"function",
"(",
")",
"{",
"var",
"target",
"=",
"this",
".",
"dragTarget",
";",
"target",
".",
"off",
"(",
"DRAG_START_EVENT",
",",
"target",
".",
"_dragStartHandler",
")",
";",
"target",
".",
"getPaper",
"(",
")",
".",
"off",
"(",
"DRAG_END_EVENT",
",",
"target",
".",
"_dragEndHandler",
")",
";",
"delete",
"target",
".",
"_dragStartHandler",
";",
"delete",
"target",
".",
"_dragEndHandler",
";",
"this",
".",
"dragEnabled",
"=",
"false",
";",
"return",
"this",
";",
"}"
] |
end of drag
|
[
"end",
"of",
"drag"
] |
592279cf2b095e940d6a457a1c6d2591eb9a9302
|
https://github.com/fex-team/kity/blob/592279cf2b095e940d6a457a1c6d2591eb9a9302/demo/public/draggable.js#L129-L137
|
|
17,146
|
pbatey/query-to-mongo
|
index.js
|
typedValue
|
function typedValue(value) {
if (value[0] == '!') value = value.substr(1)
var regex = value.match(/^\/(.*)\/(i?)$/);
var quotedString = value.match(/(["'])(?:\\\1|.)*?\1/);
if (regex) {
return new RegExp(regex[1], regex[2]);
} else if (quotedString) {
return quotedString[0].substr(1, quotedString[0].length - 2);
} else if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
} else if (iso8601.test(value) && value.length !== 4) {
return new Date(value);
} else if (!isNaN(Number(value))) {
return Number(value);
}
return value;
}
|
javascript
|
function typedValue(value) {
if (value[0] == '!') value = value.substr(1)
var regex = value.match(/^\/(.*)\/(i?)$/);
var quotedString = value.match(/(["'])(?:\\\1|.)*?\1/);
if (regex) {
return new RegExp(regex[1], regex[2]);
} else if (quotedString) {
return quotedString[0].substr(1, quotedString[0].length - 2);
} else if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
} else if (iso8601.test(value) && value.length !== 4) {
return new Date(value);
} else if (!isNaN(Number(value))) {
return Number(value);
}
return value;
}
|
[
"function",
"typedValue",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"[",
"0",
"]",
"==",
"'!'",
")",
"value",
"=",
"value",
".",
"substr",
"(",
"1",
")",
"var",
"regex",
"=",
"value",
".",
"match",
"(",
"/",
"^\\/(.*)\\/(i?)$",
"/",
")",
";",
"var",
"quotedString",
"=",
"value",
".",
"match",
"(",
"/",
"([\"'])(?:\\\\\\1|.)*?\\1",
"/",
")",
";",
"if",
"(",
"regex",
")",
"{",
"return",
"new",
"RegExp",
"(",
"regex",
"[",
"1",
"]",
",",
"regex",
"[",
"2",
"]",
")",
";",
"}",
"else",
"if",
"(",
"quotedString",
")",
"{",
"return",
"quotedString",
"[",
"0",
"]",
".",
"substr",
"(",
"1",
",",
"quotedString",
"[",
"0",
"]",
".",
"length",
"-",
"2",
")",
";",
"}",
"else",
"if",
"(",
"value",
"===",
"'true'",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"value",
"===",
"'false'",
")",
"{",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"iso8601",
".",
"test",
"(",
"value",
")",
"&&",
"value",
".",
"length",
"!==",
"4",
")",
"{",
"return",
"new",
"Date",
"(",
"value",
")",
";",
"}",
"else",
"if",
"(",
"!",
"isNaN",
"(",
"Number",
"(",
"value",
")",
")",
")",
"{",
"return",
"Number",
"(",
"value",
")",
";",
"}",
"return",
"value",
";",
"}"
] |
Convert String to Number, Date, or Boolean if possible. Also strips ! prefix
|
[
"Convert",
"String",
"to",
"Number",
"Date",
"or",
"Boolean",
"if",
"possible",
".",
"Also",
"strips",
"!",
"prefix"
] |
062dc0fbacb368d1c0ba43585998203417edaab8
|
https://github.com/pbatey/query-to-mongo/blob/062dc0fbacb368d1c0ba43585998203417edaab8/index.js#L40-L60
|
17,147
|
pbatey/query-to-mongo
|
index.js
|
typedValues
|
function typedValues(svalue) {
var commaSplit = /("[^"]*")|('[^']*')|([^,]+)/g
var values = []
svalue
.match(commaSplit)
.forEach(function(value) {
values.push(typedValue(value))
})
return values;
}
|
javascript
|
function typedValues(svalue) {
var commaSplit = /("[^"]*")|('[^']*')|([^,]+)/g
var values = []
svalue
.match(commaSplit)
.forEach(function(value) {
values.push(typedValue(value))
})
return values;
}
|
[
"function",
"typedValues",
"(",
"svalue",
")",
"{",
"var",
"commaSplit",
"=",
"/",
"(\"[^\"]*\")|('[^']*')|([^,]+)",
"/",
"g",
"var",
"values",
"=",
"[",
"]",
"svalue",
".",
"match",
"(",
"commaSplit",
")",
".",
"forEach",
"(",
"function",
"(",
"value",
")",
"{",
"values",
".",
"push",
"(",
"typedValue",
"(",
"value",
")",
")",
"}",
")",
"return",
"values",
";",
"}"
] |
Convert a comma separated string value to an array of values. Commas in a quoted string are ignored. Also strips ! prefix from values.
|
[
"Convert",
"a",
"comma",
"separated",
"string",
"value",
"to",
"an",
"array",
"of",
"values",
".",
"Commas",
"in",
"a",
"quoted",
"string",
"are",
"ignored",
".",
"Also",
"strips",
"!",
"prefix",
"from",
"values",
"."
] |
062dc0fbacb368d1c0ba43585998203417edaab8
|
https://github.com/pbatey/query-to-mongo/blob/062dc0fbacb368d1c0ba43585998203417edaab8/index.js#L64-L73
|
17,148
|
Mindmapp/mmp
|
example/app.js
|
downloadMap
|
function downloadMap(map) {
let data = map.exportAsJSON(),
json = JSON.stringify(data),
blob = new Blob([json], {type: "application/json"}),
a = document.createElement("a");
a.download = "example.json";
a.href = URL.createObjectURL(blob);
a.click();
}
|
javascript
|
function downloadMap(map) {
let data = map.exportAsJSON(),
json = JSON.stringify(data),
blob = new Blob([json], {type: "application/json"}),
a = document.createElement("a");
a.download = "example.json";
a.href = URL.createObjectURL(blob);
a.click();
}
|
[
"function",
"downloadMap",
"(",
"map",
")",
"{",
"let",
"data",
"=",
"map",
".",
"exportAsJSON",
"(",
")",
",",
"json",
"=",
"JSON",
".",
"stringify",
"(",
"data",
")",
",",
"blob",
"=",
"new",
"Blob",
"(",
"[",
"json",
"]",
",",
"{",
"type",
":",
"\"application/json\"",
"}",
")",
",",
"a",
"=",
"document",
".",
"createElement",
"(",
"\"a\"",
")",
";",
"a",
".",
"download",
"=",
"\"example.json\"",
";",
"a",
".",
"href",
"=",
"URL",
".",
"createObjectURL",
"(",
"blob",
")",
";",
"a",
".",
"click",
"(",
")",
";",
"}"
] |
Download the json of the map
|
[
"Download",
"the",
"json",
"of",
"the",
"map"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L23-L32
|
17,149
|
Mindmapp/mmp
|
example/app.js
|
uploadMap
|
function uploadMap(map, e) {
let reader = new window.FileReader();
reader.readAsText(e.target.files[0]);
reader.onload = function () {
let data = JSON.parse(event.target.result);
map.new(data);
};
}
|
javascript
|
function uploadMap(map, e) {
let reader = new window.FileReader();
reader.readAsText(e.target.files[0]);
reader.onload = function () {
let data = JSON.parse(event.target.result);
map.new(data);
};
}
|
[
"function",
"uploadMap",
"(",
"map",
",",
"e",
")",
"{",
"let",
"reader",
"=",
"new",
"window",
".",
"FileReader",
"(",
")",
";",
"reader",
".",
"readAsText",
"(",
"e",
".",
"target",
".",
"files",
"[",
"0",
"]",
")",
";",
"reader",
".",
"onload",
"=",
"function",
"(",
")",
"{",
"let",
"data",
"=",
"JSON",
".",
"parse",
"(",
"event",
".",
"target",
".",
"result",
")",
";",
"map",
".",
"new",
"(",
"data",
")",
";",
"}",
";",
"}"
] |
Upload a mmp json to map
|
[
"Upload",
"a",
"mmp",
"json",
"to",
"map"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L35-L44
|
17,150
|
Mindmapp/mmp
|
example/app.js
|
downloadImage
|
function downloadImage(map) {
map.exportAsImage(function (url) {
let a = document.createElement("a");
a.download = "example";
a.href = url;
a.click();
}, "jpeg");
}
|
javascript
|
function downloadImage(map) {
map.exportAsImage(function (url) {
let a = document.createElement("a");
a.download = "example";
a.href = url;
a.click();
}, "jpeg");
}
|
[
"function",
"downloadImage",
"(",
"map",
")",
"{",
"map",
".",
"exportAsImage",
"(",
"function",
"(",
"url",
")",
"{",
"let",
"a",
"=",
"document",
".",
"createElement",
"(",
"\"a\"",
")",
";",
"a",
".",
"download",
"=",
"\"example\"",
";",
"a",
".",
"href",
"=",
"url",
";",
"a",
".",
"click",
"(",
")",
";",
"}",
",",
"\"jpeg\"",
")",
";",
"}"
] |
Save the image of the map
|
[
"Save",
"the",
"image",
"of",
"the",
"map"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L47-L54
|
17,151
|
Mindmapp/mmp
|
example/app.js
|
insertImage
|
function insertImage(map) {
let src = map.selectNode().image.src;
if (src === "") {
let value = prompt("Please enter your name", "example/img/material-icons/add.svg");
if (value) {
map.updateNode("imageSrc", value);
}
} else {
map.updateNode("imageSrc", "");
}
}
|
javascript
|
function insertImage(map) {
let src = map.selectNode().image.src;
if (src === "") {
let value = prompt("Please enter your name", "example/img/material-icons/add.svg");
if (value) {
map.updateNode("imageSrc", value);
}
} else {
map.updateNode("imageSrc", "");
}
}
|
[
"function",
"insertImage",
"(",
"map",
")",
"{",
"let",
"src",
"=",
"map",
".",
"selectNode",
"(",
")",
".",
"image",
".",
"src",
";",
"if",
"(",
"src",
"===",
"\"\"",
")",
"{",
"let",
"value",
"=",
"prompt",
"(",
"\"Please enter your name\"",
",",
"\"example/img/material-icons/add.svg\"",
")",
";",
"if",
"(",
"value",
")",
"{",
"map",
".",
"updateNode",
"(",
"\"imageSrc\"",
",",
"value",
")",
";",
"}",
"}",
"else",
"{",
"map",
".",
"updateNode",
"(",
"\"imageSrc\"",
",",
"\"\"",
")",
";",
"}",
"}"
] |
Insert an image in the selected node
|
[
"Insert",
"an",
"image",
"in",
"the",
"selected",
"node"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L57-L69
|
17,152
|
Mindmapp/mmp
|
example/app.js
|
bold
|
function bold(map) {
let value = map.selectNode().font.weight !== "bold" ? "bold" : "normal";
map.updateNode("fontWeight", value);
}
|
javascript
|
function bold(map) {
let value = map.selectNode().font.weight !== "bold" ? "bold" : "normal";
map.updateNode("fontWeight", value);
}
|
[
"function",
"bold",
"(",
"map",
")",
"{",
"let",
"value",
"=",
"map",
".",
"selectNode",
"(",
")",
".",
"font",
".",
"weight",
"!==",
"\"bold\"",
"?",
"\"bold\"",
":",
"\"normal\"",
";",
"map",
".",
"updateNode",
"(",
"\"fontWeight\"",
",",
"value",
")",
";",
"}"
] |
Update bold status
|
[
"Update",
"bold",
"status"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L72-L75
|
17,153
|
Mindmapp/mmp
|
example/app.js
|
italic
|
function italic(map) {
let value = map.selectNode().font.style !== "italic" ? "italic" : "normal";
map.updateNode("fontStyle", value);
}
|
javascript
|
function italic(map) {
let value = map.selectNode().font.style !== "italic" ? "italic" : "normal";
map.updateNode("fontStyle", value);
}
|
[
"function",
"italic",
"(",
"map",
")",
"{",
"let",
"value",
"=",
"map",
".",
"selectNode",
"(",
")",
".",
"font",
".",
"style",
"!==",
"\"italic\"",
"?",
"\"italic\"",
":",
"\"normal\"",
";",
"map",
".",
"updateNode",
"(",
"\"fontStyle\"",
",",
"value",
")",
";",
"}"
] |
Update italic status
|
[
"Update",
"italic",
"status"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L78-L81
|
17,154
|
Mindmapp/mmp
|
example/app.js
|
updateValues
|
function updateValues(node, map) {
dom.fontSize[map].value = node.fontSize;
dom.imageSize[map].value = node.image.size;
dom.backgroundColor[map].value = node.colors.background;
dom.branchColor[map].value = node.colors.branch || "#ffffff";
dom.nameColor[map].value = node.colors.name;
}
|
javascript
|
function updateValues(node, map) {
dom.fontSize[map].value = node.fontSize;
dom.imageSize[map].value = node.image.size;
dom.backgroundColor[map].value = node.colors.background;
dom.branchColor[map].value = node.colors.branch || "#ffffff";
dom.nameColor[map].value = node.colors.name;
}
|
[
"function",
"updateValues",
"(",
"node",
",",
"map",
")",
"{",
"dom",
".",
"fontSize",
"[",
"map",
"]",
".",
"value",
"=",
"node",
".",
"fontSize",
";",
"dom",
".",
"imageSize",
"[",
"map",
"]",
".",
"value",
"=",
"node",
".",
"image",
".",
"size",
";",
"dom",
".",
"backgroundColor",
"[",
"map",
"]",
".",
"value",
"=",
"node",
".",
"colors",
".",
"background",
";",
"dom",
".",
"branchColor",
"[",
"map",
"]",
".",
"value",
"=",
"node",
".",
"colors",
".",
"branch",
"||",
"\"#ffffff\"",
";",
"dom",
".",
"nameColor",
"[",
"map",
"]",
".",
"value",
"=",
"node",
".",
"colors",
".",
"name",
";",
"}"
] |
Update the values of map controls
|
[
"Update",
"the",
"values",
"of",
"map",
"controls"
] |
ddb60450af6f7967e2c3eb6fc0326a2e989d9829
|
https://github.com/Mindmapp/mmp/blob/ddb60450af6f7967e2c3eb6fc0326a2e989d9829/example/app.js#L84-L90
|
17,155
|
wmurphyrd/aframe-super-hands-component
|
index.js
|
sorter
|
function sorter (a, b) {
const aDist = a.distance == null ? -1 : a.distance
const bDist = b.distance == null ? -1 : b.distance
if (aDist < bDist) {
return 1
}
if (bDist < aDist) {
return -1
}
return 0
}
|
javascript
|
function sorter (a, b) {
const aDist = a.distance == null ? -1 : a.distance
const bDist = b.distance == null ? -1 : b.distance
if (aDist < bDist) {
return 1
}
if (bDist < aDist) {
return -1
}
return 0
}
|
[
"function",
"sorter",
"(",
"a",
",",
"b",
")",
"{",
"const",
"aDist",
"=",
"a",
".",
"distance",
"==",
"null",
"?",
"-",
"1",
":",
"a",
".",
"distance",
"const",
"bDist",
"=",
"b",
".",
"distance",
"==",
"null",
"?",
"-",
"1",
":",
"b",
".",
"distance",
"if",
"(",
"aDist",
"<",
"bDist",
")",
"{",
"return",
"1",
"}",
"if",
"(",
"bDist",
"<",
"aDist",
")",
"{",
"return",
"-",
"1",
"}",
"return",
"0",
"}"
] |
closer objects and objects with no distance come later in list
|
[
"closer",
"objects",
"and",
"objects",
"with",
"no",
"distance",
"come",
"later",
"in",
"list"
] |
c24b4d7172856147d4370090b48ce6c401a71df0
|
https://github.com/wmurphyrd/aframe-super-hands-component/blob/c24b4d7172856147d4370090b48ce6c401a71df0/index.js#L138-L148
|
17,156
|
yvele/azure-function-express
|
src/IncomingMessage.js
|
createConnectionObject
|
function createConnectionObject(context) {
const { req } = context.bindings;
const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;
return {
encrypted : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
remoteAddress : removePortFromAddress(xForwardedFor)
};
}
|
javascript
|
function createConnectionObject(context) {
const { req } = context.bindings;
const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;
return {
encrypted : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
remoteAddress : removePortFromAddress(xForwardedFor)
};
}
|
[
"function",
"createConnectionObject",
"(",
"context",
")",
"{",
"const",
"{",
"req",
"}",
"=",
"context",
".",
"bindings",
";",
"const",
"xForwardedFor",
"=",
"req",
".",
"headers",
"?",
"req",
".",
"headers",
"[",
"\"x-forwarded-for\"",
"]",
":",
"undefined",
";",
"return",
"{",
"encrypted",
":",
"req",
".",
"originalUrl",
"&&",
"req",
".",
"originalUrl",
".",
"toLowerCase",
"(",
")",
".",
"startsWith",
"(",
"\"https\"",
")",
",",
"remoteAddress",
":",
"removePortFromAddress",
"(",
"xForwardedFor",
")",
"}",
";",
"}"
] |
Create a fake connection object
@param {Object} context Raw Azure context object for a single HTTP request
@returns {object} Connection object
|
[
"Create",
"a",
"fake",
"connection",
"object"
] |
2bd90411b20480f2e430d730b638974d3391e671
|
https://github.com/yvele/azure-function-express/blob/2bd90411b20480f2e430d730b638974d3391e671/src/IncomingMessage.js#L18-L26
|
17,157
|
yvele/azure-function-express
|
src/IncomingMessage.js
|
sanitizeContext
|
function sanitizeContext(context) {
const sanitizedContext = {
...context,
log : context.log.bind(context)
};
// We don't want the developper to mess up express flow
// See https://github.com/yvele/azure-function-express/pull/12#issuecomment-336733540
delete sanitizedContext.done;
return sanitizedContext;
}
|
javascript
|
function sanitizeContext(context) {
const sanitizedContext = {
...context,
log : context.log.bind(context)
};
// We don't want the developper to mess up express flow
// See https://github.com/yvele/azure-function-express/pull/12#issuecomment-336733540
delete sanitizedContext.done;
return sanitizedContext;
}
|
[
"function",
"sanitizeContext",
"(",
"context",
")",
"{",
"const",
"sanitizedContext",
"=",
"{",
"...",
"context",
",",
"log",
":",
"context",
".",
"log",
".",
"bind",
"(",
"context",
")",
"}",
";",
"// We don't want the developper to mess up express flow",
"// See https://github.com/yvele/azure-function-express/pull/12#issuecomment-336733540",
"delete",
"sanitizedContext",
".",
"done",
";",
"return",
"sanitizedContext",
";",
"}"
] |
Copy usefull context properties from the native context provided by the Azure Function engine
See:
- https://docs.microsoft.com/en-us/azure/azure-functions/functions-reference-node#context-object
- https://github.com/christopheranderson/azure-functions-typescript/blob/master/src/context.d.ts
@param {Object} context Raw Azure context object for a single HTTP request
@returns {Object} Filtered context
|
[
"Copy",
"usefull",
"context",
"properties",
"from",
"the",
"native",
"context",
"provided",
"by",
"the",
"Azure",
"Function",
"engine"
] |
2bd90411b20480f2e430d730b638974d3391e671
|
https://github.com/yvele/azure-function-express/blob/2bd90411b20480f2e430d730b638974d3391e671/src/IncomingMessage.js#L38-L49
|
17,158
|
s-yadav/patternLock
|
lib/util.js
|
getLengthAngle
|
function getLengthAngle(x1, x2, y1, y2) {
var xDiff = x2 - x1;
var yDiff = y2 - y1;
return {
length: Math.ceil(Math.sqrt(xDiff * xDiff + yDiff * yDiff)),
angle: Math.round(Math.atan2(yDiff, xDiff) * 180 / Math.PI)
};
}
|
javascript
|
function getLengthAngle(x1, x2, y1, y2) {
var xDiff = x2 - x1;
var yDiff = y2 - y1;
return {
length: Math.ceil(Math.sqrt(xDiff * xDiff + yDiff * yDiff)),
angle: Math.round(Math.atan2(yDiff, xDiff) * 180 / Math.PI)
};
}
|
[
"function",
"getLengthAngle",
"(",
"x1",
",",
"x2",
",",
"y1",
",",
"y2",
")",
"{",
"var",
"xDiff",
"=",
"x2",
"-",
"x1",
";",
"var",
"yDiff",
"=",
"y2",
"-",
"y1",
";",
"return",
"{",
"length",
":",
"Math",
".",
"ceil",
"(",
"Math",
".",
"sqrt",
"(",
"xDiff",
"*",
"xDiff",
"+",
"yDiff",
"*",
"yDiff",
")",
")",
",",
"angle",
":",
"Math",
".",
"round",
"(",
"Math",
".",
"atan2",
"(",
"yDiff",
",",
"xDiff",
")",
"*",
"180",
"/",
"Math",
".",
"PI",
")",
"}",
";",
"}"
] |
return height and angle for lines
|
[
"return",
"height",
"and",
"angle",
"for",
"lines"
] |
6d33baeb85818852b5cf06e05c96fdd81dd85fb0
|
https://github.com/s-yadav/patternLock/blob/6d33baeb85818852b5cf06e05c96fdd81dd85fb0/lib/util.js#L88-L97
|
17,159
|
leeoniya/RgbQuant.js
|
src/rgbquant.js
|
distEuclidean
|
function distEuclidean(rgb0, rgb1) {
var rd = rgb1[0]-rgb0[0],
gd = rgb1[1]-rgb0[1],
bd = rgb1[2]-rgb0[2];
return Math.sqrt(Pr*rd*rd + Pg*gd*gd + Pb*bd*bd) / euclMax;
}
|
javascript
|
function distEuclidean(rgb0, rgb1) {
var rd = rgb1[0]-rgb0[0],
gd = rgb1[1]-rgb0[1],
bd = rgb1[2]-rgb0[2];
return Math.sqrt(Pr*rd*rd + Pg*gd*gd + Pb*bd*bd) / euclMax;
}
|
[
"function",
"distEuclidean",
"(",
"rgb0",
",",
"rgb1",
")",
"{",
"var",
"rd",
"=",
"rgb1",
"[",
"0",
"]",
"-",
"rgb0",
"[",
"0",
"]",
",",
"gd",
"=",
"rgb1",
"[",
"1",
"]",
"-",
"rgb0",
"[",
"1",
"]",
",",
"bd",
"=",
"rgb1",
"[",
"2",
"]",
"-",
"rgb0",
"[",
"2",
"]",
";",
"return",
"Math",
".",
"sqrt",
"(",
"Pr",
"*",
"rd",
"*",
"rd",
"+",
"Pg",
"*",
"gd",
"*",
"gd",
"+",
"Pb",
"*",
"bd",
"*",
"bd",
")",
"/",
"euclMax",
";",
"}"
] |
perceptual Euclidean color distance
|
[
"perceptual",
"Euclidean",
"color",
"distance"
] |
dd80ef94c2256eb0af4b8451b3f5c4e1b5a70988
|
https://github.com/leeoniya/RgbQuant.js/blob/dd80ef94c2256eb0af4b8451b3f5c4e1b5a70988/src/rgbquant.js#L723-L729
|
17,160
|
leeoniya/RgbQuant.js
|
src/rgbquant.js
|
distManhattan
|
function distManhattan(rgb0, rgb1) {
var rd = Math.abs(rgb1[0]-rgb0[0]),
gd = Math.abs(rgb1[1]-rgb0[1]),
bd = Math.abs(rgb1[2]-rgb0[2]);
return (Pr*rd + Pg*gd + Pb*bd) / manhMax;
}
|
javascript
|
function distManhattan(rgb0, rgb1) {
var rd = Math.abs(rgb1[0]-rgb0[0]),
gd = Math.abs(rgb1[1]-rgb0[1]),
bd = Math.abs(rgb1[2]-rgb0[2]);
return (Pr*rd + Pg*gd + Pb*bd) / manhMax;
}
|
[
"function",
"distManhattan",
"(",
"rgb0",
",",
"rgb1",
")",
"{",
"var",
"rd",
"=",
"Math",
".",
"abs",
"(",
"rgb1",
"[",
"0",
"]",
"-",
"rgb0",
"[",
"0",
"]",
")",
",",
"gd",
"=",
"Math",
".",
"abs",
"(",
"rgb1",
"[",
"1",
"]",
"-",
"rgb0",
"[",
"1",
"]",
")",
",",
"bd",
"=",
"Math",
".",
"abs",
"(",
"rgb1",
"[",
"2",
"]",
"-",
"rgb0",
"[",
"2",
"]",
")",
";",
"return",
"(",
"Pr",
"*",
"rd",
"+",
"Pg",
"*",
"gd",
"+",
"Pb",
"*",
"bd",
")",
"/",
"manhMax",
";",
"}"
] |
perceptual Manhattan color distance
|
[
"perceptual",
"Manhattan",
"color",
"distance"
] |
dd80ef94c2256eb0af4b8451b3f5c4e1b5a70988
|
https://github.com/leeoniya/RgbQuant.js/blob/dd80ef94c2256eb0af4b8451b3f5c4e1b5a70988/src/rgbquant.js#L733-L739
|
17,161
|
leeoniya/RgbQuant.js
|
src/rgbquant.js
|
sortedHashKeys
|
function sortedHashKeys(obj, desc) {
var keys = [];
for (var key in obj)
keys.push(key);
return sort.call(keys, function(a,b) {
return desc ? obj[b] - obj[a] : obj[a] - obj[b];
});
}
|
javascript
|
function sortedHashKeys(obj, desc) {
var keys = [];
for (var key in obj)
keys.push(key);
return sort.call(keys, function(a,b) {
return desc ? obj[b] - obj[a] : obj[a] - obj[b];
});
}
|
[
"function",
"sortedHashKeys",
"(",
"obj",
",",
"desc",
")",
"{",
"var",
"keys",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"obj",
")",
"keys",
".",
"push",
"(",
"key",
")",
";",
"return",
"sort",
".",
"call",
"(",
"keys",
",",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"desc",
"?",
"obj",
"[",
"b",
"]",
"-",
"obj",
"[",
"a",
"]",
":",
"obj",
"[",
"a",
"]",
"-",
"obj",
"[",
"b",
"]",
";",
"}",
")",
";",
"}"
] |
returns array of hash keys sorted by their values
|
[
"returns",
"array",
"of",
"hash",
"keys",
"sorted",
"by",
"their",
"values"
] |
dd80ef94c2256eb0af4b8451b3f5c4e1b5a70988
|
https://github.com/leeoniya/RgbQuant.js/blob/dd80ef94c2256eb0af4b8451b3f5c4e1b5a70988/src/rgbquant.js#L916-L925
|
17,162
|
serverless-heaven/serverless-aws-alias
|
lib/stackops/functions.js
|
mergeAliases
|
function mergeAliases(stackName, newTemplate, currentTemplate, aliasStackTemplates, currentAliasStackTemplate, removedResources) {
const allAliasTemplates = _.concat(aliasStackTemplates, currentAliasStackTemplate);
// Get all referenced function logical resource ids
const aliasedFunctions =
_.flatMap(
allAliasTemplates,
template => _.compact(_.map(
template.Resources,
(resource, name) => {
if (resource.Type === 'AWS::Lambda::Alias') {
return {
name: _.replace(name, /Alias$/, 'LambdaFunction'),
version: _.replace(_.get(resource, 'Properties.FunctionVersion.Fn::ImportValue'), `${stackName}-`, '')
};
}
return null;
}
))
);
// Get currently deployed function definitions and versions and retain them in the stack update
const usedFunctionElements = {
Resources: _.map(aliasedFunctions, aliasedFunction => _.assign(
{},
_.pick(currentTemplate.Resources, [ aliasedFunction.name, aliasedFunction.version ])
)),
Outputs: _.map(aliasedFunctions, aliasedFunction => _.assign(
{},
_.pick(currentTemplate.Outputs, [ `${aliasedFunction.name}Arn`, aliasedFunction.version ])
))
};
_.forEach(usedFunctionElements.Resources, resources => _.defaults(newTemplate.Resources, resources));
_.forEach(usedFunctionElements.Outputs, outputs => _.defaults(newTemplate.Outputs, outputs));
// Set references to obsoleted resources in fct env to "REMOVED" in case
// the alias that is removed was the last deployment of the stage.
// This will change the function definition, but that does not matter
// as is is neither aliased nor versioned
_.forEach(_.filter(newTemplate.Resources, [ 'Type', 'AWS::Lambda::Function' ]), func => {
const refs = utils.findReferences(func, removedResources);
_.forEach(refs, ref => _.set(func, ref, "REMOVED"));
});
}
|
javascript
|
function mergeAliases(stackName, newTemplate, currentTemplate, aliasStackTemplates, currentAliasStackTemplate, removedResources) {
const allAliasTemplates = _.concat(aliasStackTemplates, currentAliasStackTemplate);
// Get all referenced function logical resource ids
const aliasedFunctions =
_.flatMap(
allAliasTemplates,
template => _.compact(_.map(
template.Resources,
(resource, name) => {
if (resource.Type === 'AWS::Lambda::Alias') {
return {
name: _.replace(name, /Alias$/, 'LambdaFunction'),
version: _.replace(_.get(resource, 'Properties.FunctionVersion.Fn::ImportValue'), `${stackName}-`, '')
};
}
return null;
}
))
);
// Get currently deployed function definitions and versions and retain them in the stack update
const usedFunctionElements = {
Resources: _.map(aliasedFunctions, aliasedFunction => _.assign(
{},
_.pick(currentTemplate.Resources, [ aliasedFunction.name, aliasedFunction.version ])
)),
Outputs: _.map(aliasedFunctions, aliasedFunction => _.assign(
{},
_.pick(currentTemplate.Outputs, [ `${aliasedFunction.name}Arn`, aliasedFunction.version ])
))
};
_.forEach(usedFunctionElements.Resources, resources => _.defaults(newTemplate.Resources, resources));
_.forEach(usedFunctionElements.Outputs, outputs => _.defaults(newTemplate.Outputs, outputs));
// Set references to obsoleted resources in fct env to "REMOVED" in case
// the alias that is removed was the last deployment of the stage.
// This will change the function definition, but that does not matter
// as is is neither aliased nor versioned
_.forEach(_.filter(newTemplate.Resources, [ 'Type', 'AWS::Lambda::Function' ]), func => {
const refs = utils.findReferences(func, removedResources);
_.forEach(refs, ref => _.set(func, ref, "REMOVED"));
});
}
|
[
"function",
"mergeAliases",
"(",
"stackName",
",",
"newTemplate",
",",
"currentTemplate",
",",
"aliasStackTemplates",
",",
"currentAliasStackTemplate",
",",
"removedResources",
")",
"{",
"const",
"allAliasTemplates",
"=",
"_",
".",
"concat",
"(",
"aliasStackTemplates",
",",
"currentAliasStackTemplate",
")",
";",
"// Get all referenced function logical resource ids",
"const",
"aliasedFunctions",
"=",
"_",
".",
"flatMap",
"(",
"allAliasTemplates",
",",
"template",
"=>",
"_",
".",
"compact",
"(",
"_",
".",
"map",
"(",
"template",
".",
"Resources",
",",
"(",
"resource",
",",
"name",
")",
"=>",
"{",
"if",
"(",
"resource",
".",
"Type",
"===",
"'AWS::Lambda::Alias'",
")",
"{",
"return",
"{",
"name",
":",
"_",
".",
"replace",
"(",
"name",
",",
"/",
"Alias$",
"/",
",",
"'LambdaFunction'",
")",
",",
"version",
":",
"_",
".",
"replace",
"(",
"_",
".",
"get",
"(",
"resource",
",",
"'Properties.FunctionVersion.Fn::ImportValue'",
")",
",",
"`",
"${",
"stackName",
"}",
"`",
",",
"''",
")",
"}",
";",
"}",
"return",
"null",
";",
"}",
")",
")",
")",
";",
"// Get currently deployed function definitions and versions and retain them in the stack update",
"const",
"usedFunctionElements",
"=",
"{",
"Resources",
":",
"_",
".",
"map",
"(",
"aliasedFunctions",
",",
"aliasedFunction",
"=>",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"_",
".",
"pick",
"(",
"currentTemplate",
".",
"Resources",
",",
"[",
"aliasedFunction",
".",
"name",
",",
"aliasedFunction",
".",
"version",
"]",
")",
")",
")",
",",
"Outputs",
":",
"_",
".",
"map",
"(",
"aliasedFunctions",
",",
"aliasedFunction",
"=>",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"_",
".",
"pick",
"(",
"currentTemplate",
".",
"Outputs",
",",
"[",
"`",
"${",
"aliasedFunction",
".",
"name",
"}",
"`",
",",
"aliasedFunction",
".",
"version",
"]",
")",
")",
")",
"}",
";",
"_",
".",
"forEach",
"(",
"usedFunctionElements",
".",
"Resources",
",",
"resources",
"=>",
"_",
".",
"defaults",
"(",
"newTemplate",
".",
"Resources",
",",
"resources",
")",
")",
";",
"_",
".",
"forEach",
"(",
"usedFunctionElements",
".",
"Outputs",
",",
"outputs",
"=>",
"_",
".",
"defaults",
"(",
"newTemplate",
".",
"Outputs",
",",
"outputs",
")",
")",
";",
"// Set references to obsoleted resources in fct env to \"REMOVED\" in case",
"// the alias that is removed was the last deployment of the stage.",
"// This will change the function definition, but that does not matter",
"// as is is neither aliased nor versioned",
"_",
".",
"forEach",
"(",
"_",
".",
"filter",
"(",
"newTemplate",
".",
"Resources",
",",
"[",
"'Type'",
",",
"'AWS::Lambda::Function'",
"]",
")",
",",
"func",
"=>",
"{",
"const",
"refs",
"=",
"utils",
".",
"findReferences",
"(",
"func",
",",
"removedResources",
")",
";",
"_",
".",
"forEach",
"(",
"refs",
",",
"ref",
"=>",
"_",
".",
"set",
"(",
"func",
",",
"ref",
",",
"\"REMOVED\"",
")",
")",
";",
"}",
")",
";",
"}"
] |
Merge template definitions that are still in use into the new template
@param stackName {String} Main stack name
@param newTemplate {Object} New main stack template
@param currentTemplate {Object} Currently deployed main stack template
@param aliasStackTemplates {Array<Object>} Currently deployed and references aliases
|
[
"Merge",
"template",
"definitions",
"that",
"are",
"still",
"in",
"use",
"into",
"the",
"new",
"template"
] |
6b9d0ac66a71dd686627eefccf071e0ea7e266ee
|
https://github.com/serverless-heaven/serverless-aws-alias/blob/6b9d0ac66a71dd686627eefccf071e0ea7e266ee/lib/stackops/functions.js#L17-L63
|
17,163
|
cabal-club/cabal-core
|
index.js
|
Cabal
|
function Cabal (storage, key, opts) {
if (!(this instanceof Cabal)) return new Cabal(storage, key, opts)
if (!opts) opts = {}
events.EventEmitter.call(this)
var json = {
encode: function (obj) {
return Buffer.from(JSON.stringify(obj))
},
decode: function (buf) {
var str = buf.toString('utf8')
try { var obj = JSON.parse(str) } catch (err) { return {} }
return obj
}
}
this.maxFeeds = opts.maxFeeds
this.key = key || null
this.db = kappa(storage, {
valueEncoding: json
})
// Create (if needed) and open local write feed
var self = this
this.feed = thunky(function (cb) {
self.db.ready(function () {
self.db.feed('local', function (err, feed) {
if (!self.key) self.key = feed.key.toString('hex')
cb(feed)
})
})
})
// views
this.db.use('channels', createChannelView(memdb({ valueEncoding: json })))
this.db.use('messages', createMessagesView(memdb({ valueEncoding: json })))
this.db.use('topics', createTopicsView(memdb({ valueEncoding: json })))
this.db.use('users', createUsersView(memdb({ valueEncoding: json })))
this.messages = this.db.api.messages
this.channels = this.db.api.channels
this.topics = this.db.api.topics
this.users = this.db.api.users
}
|
javascript
|
function Cabal (storage, key, opts) {
if (!(this instanceof Cabal)) return new Cabal(storage, key, opts)
if (!opts) opts = {}
events.EventEmitter.call(this)
var json = {
encode: function (obj) {
return Buffer.from(JSON.stringify(obj))
},
decode: function (buf) {
var str = buf.toString('utf8')
try { var obj = JSON.parse(str) } catch (err) { return {} }
return obj
}
}
this.maxFeeds = opts.maxFeeds
this.key = key || null
this.db = kappa(storage, {
valueEncoding: json
})
// Create (if needed) and open local write feed
var self = this
this.feed = thunky(function (cb) {
self.db.ready(function () {
self.db.feed('local', function (err, feed) {
if (!self.key) self.key = feed.key.toString('hex')
cb(feed)
})
})
})
// views
this.db.use('channels', createChannelView(memdb({ valueEncoding: json })))
this.db.use('messages', createMessagesView(memdb({ valueEncoding: json })))
this.db.use('topics', createTopicsView(memdb({ valueEncoding: json })))
this.db.use('users', createUsersView(memdb({ valueEncoding: json })))
this.messages = this.db.api.messages
this.channels = this.db.api.channels
this.topics = this.db.api.topics
this.users = this.db.api.users
}
|
[
"function",
"Cabal",
"(",
"storage",
",",
"key",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Cabal",
")",
")",
"return",
"new",
"Cabal",
"(",
"storage",
",",
"key",
",",
"opts",
")",
"if",
"(",
"!",
"opts",
")",
"opts",
"=",
"{",
"}",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
"var",
"json",
"=",
"{",
"encode",
":",
"function",
"(",
"obj",
")",
"{",
"return",
"Buffer",
".",
"from",
"(",
"JSON",
".",
"stringify",
"(",
"obj",
")",
")",
"}",
",",
"decode",
":",
"function",
"(",
"buf",
")",
"{",
"var",
"str",
"=",
"buf",
".",
"toString",
"(",
"'utf8'",
")",
"try",
"{",
"var",
"obj",
"=",
"JSON",
".",
"parse",
"(",
"str",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"{",
"}",
"}",
"return",
"obj",
"}",
"}",
"this",
".",
"maxFeeds",
"=",
"opts",
".",
"maxFeeds",
"this",
".",
"key",
"=",
"key",
"||",
"null",
"this",
".",
"db",
"=",
"kappa",
"(",
"storage",
",",
"{",
"valueEncoding",
":",
"json",
"}",
")",
"// Create (if needed) and open local write feed",
"var",
"self",
"=",
"this",
"this",
".",
"feed",
"=",
"thunky",
"(",
"function",
"(",
"cb",
")",
"{",
"self",
".",
"db",
".",
"ready",
"(",
"function",
"(",
")",
"{",
"self",
".",
"db",
".",
"feed",
"(",
"'local'",
",",
"function",
"(",
"err",
",",
"feed",
")",
"{",
"if",
"(",
"!",
"self",
".",
"key",
")",
"self",
".",
"key",
"=",
"feed",
".",
"key",
".",
"toString",
"(",
"'hex'",
")",
"cb",
"(",
"feed",
")",
"}",
")",
"}",
")",
"}",
")",
"// views",
"this",
".",
"db",
".",
"use",
"(",
"'channels'",
",",
"createChannelView",
"(",
"memdb",
"(",
"{",
"valueEncoding",
":",
"json",
"}",
")",
")",
")",
"this",
".",
"db",
".",
"use",
"(",
"'messages'",
",",
"createMessagesView",
"(",
"memdb",
"(",
"{",
"valueEncoding",
":",
"json",
"}",
")",
")",
")",
"this",
".",
"db",
".",
"use",
"(",
"'topics'",
",",
"createTopicsView",
"(",
"memdb",
"(",
"{",
"valueEncoding",
":",
"json",
"}",
")",
")",
")",
"this",
".",
"db",
".",
"use",
"(",
"'users'",
",",
"createUsersView",
"(",
"memdb",
"(",
"{",
"valueEncoding",
":",
"json",
"}",
")",
")",
")",
"this",
".",
"messages",
"=",
"this",
".",
"db",
".",
"api",
".",
"messages",
"this",
".",
"channels",
"=",
"this",
".",
"db",
".",
"api",
".",
"channels",
"this",
".",
"topics",
"=",
"this",
".",
"db",
".",
"api",
".",
"topics",
"this",
".",
"users",
"=",
"this",
".",
"db",
".",
"api",
".",
"users",
"}"
] |
Create a new cabal. This is the object handling all
local nickname -> mesh interactions for a single user.
@constructor
@param {string|function} storage - A hyperdb compatible storage function, or a string representing the local data path.
@param {string} key - The dat link
@param {Object} opts -
|
[
"Create",
"a",
"new",
"cabal",
".",
"This",
"is",
"the",
"object",
"handling",
"all",
"local",
"nickname",
"-",
">",
"mesh",
"interactions",
"for",
"a",
"single",
"user",
"."
] |
5c2a69a398a6e66221fc3ef2cebfd43df2def320
|
https://github.com/cabal-club/cabal-core/blob/5c2a69a398a6e66221fc3ef2cebfd43df2def320/index.js#L25-L69
|
17,164
|
cabal-club/cabal-core
|
views/topics.js
|
sanitize
|
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
if (typeof msg.value.content.channel !== 'string') return null
if (typeof msg.value.content.text !== 'string') return null
return msg
}
|
javascript
|
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
if (typeof msg.value.content.channel !== 'string') return null
if (typeof msg.value.content.text !== 'string') return null
return msg
}
|
[
"function",
"sanitize",
"(",
"msg",
")",
"{",
"if",
"(",
"typeof",
"msg",
"!==",
"'object'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
"!==",
"'object'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"content",
"!==",
"'object'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"timestamp",
"!==",
"'number'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"type",
"!==",
"'string'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"content",
".",
"channel",
"!==",
"'string'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"content",
".",
"text",
"!==",
"'string'",
")",
"return",
"null",
"return",
"msg",
"}"
] |
Either returns a well-formed channel message, or null.
|
[
"Either",
"returns",
"a",
"well",
"-",
"formed",
"channel",
"message",
"or",
"null",
"."
] |
5c2a69a398a6e66221fc3ef2cebfd43df2def320
|
https://github.com/cabal-club/cabal-core/blob/5c2a69a398a6e66221fc3ef2cebfd43df2def320/views/topics.js#L50-L59
|
17,165
|
cabal-club/cabal-core
|
views/users.js
|
sanitize
|
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
return msg
}
|
javascript
|
function sanitize (msg) {
if (typeof msg !== 'object') return null
if (typeof msg.value !== 'object') return null
if (typeof msg.value.content !== 'object') return null
if (typeof msg.value.timestamp !== 'number') return null
if (typeof msg.value.type !== 'string') return null
return msg
}
|
[
"function",
"sanitize",
"(",
"msg",
")",
"{",
"if",
"(",
"typeof",
"msg",
"!==",
"'object'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
"!==",
"'object'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"content",
"!==",
"'object'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"timestamp",
"!==",
"'number'",
")",
"return",
"null",
"if",
"(",
"typeof",
"msg",
".",
"value",
".",
"type",
"!==",
"'string'",
")",
"return",
"null",
"return",
"msg",
"}"
] |
Either returns a well-formed user message, or null.
|
[
"Either",
"returns",
"a",
"well",
"-",
"formed",
"user",
"message",
"or",
"null",
"."
] |
5c2a69a398a6e66221fc3ef2cebfd43df2def320
|
https://github.com/cabal-club/cabal-core/blob/5c2a69a398a6e66221fc3ef2cebfd43df2def320/views/users.js#L80-L87
|
17,166
|
cabal-club/cabal-core
|
views/messages.js
|
function (core, channel, opts) {
opts = opts || {}
var t = through.obj()
if (opts.gt) opts.gt = 'msg!' + channel + '!' + charwise.encode(opts.gt) + '!'
else opts.gt = 'msg!' + channel + '!'
if (opts.lt) opts.lt = 'msg!' + channel + '!' + charwise.encode(opts.lt) + '~'
else opts.lt = 'msg!' + channel + '~'
this.ready(function () {
var v = lvl.createValueStream(xtend({reverse: true}, opts))
v.pipe(t)
})
return readonly(t)
}
|
javascript
|
function (core, channel, opts) {
opts = opts || {}
var t = through.obj()
if (opts.gt) opts.gt = 'msg!' + channel + '!' + charwise.encode(opts.gt) + '!'
else opts.gt = 'msg!' + channel + '!'
if (opts.lt) opts.lt = 'msg!' + channel + '!' + charwise.encode(opts.lt) + '~'
else opts.lt = 'msg!' + channel + '~'
this.ready(function () {
var v = lvl.createValueStream(xtend({reverse: true}, opts))
v.pipe(t)
})
return readonly(t)
}
|
[
"function",
"(",
"core",
",",
"channel",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
"var",
"t",
"=",
"through",
".",
"obj",
"(",
")",
"if",
"(",
"opts",
".",
"gt",
")",
"opts",
".",
"gt",
"=",
"'msg!'",
"+",
"channel",
"+",
"'!'",
"+",
"charwise",
".",
"encode",
"(",
"opts",
".",
"gt",
")",
"+",
"'!'",
"else",
"opts",
".",
"gt",
"=",
"'msg!'",
"+",
"channel",
"+",
"'!'",
"if",
"(",
"opts",
".",
"lt",
")",
"opts",
".",
"lt",
"=",
"'msg!'",
"+",
"channel",
"+",
"'!'",
"+",
"charwise",
".",
"encode",
"(",
"opts",
".",
"lt",
")",
"+",
"'~'",
"else",
"opts",
".",
"lt",
"=",
"'msg!'",
"+",
"channel",
"+",
"'~'",
"this",
".",
"ready",
"(",
"function",
"(",
")",
"{",
"var",
"v",
"=",
"lvl",
".",
"createValueStream",
"(",
"xtend",
"(",
"{",
"reverse",
":",
"true",
"}",
",",
"opts",
")",
")",
"v",
".",
"pipe",
"(",
"t",
")",
"}",
")",
"return",
"readonly",
"(",
"t",
")",
"}"
] |
Creates a read stream of messages
@param {Object} core - HyperCore to stream messages from.
@param {String} channel - Name of channel
@param {Object} opts :
`gt` {Number} - Filter by timestamp where message.timestamp is greater than `gt`
`lt` {Number} - Filter by timestamp where message.timestamp is lesser than `lt`
Supports all levelup.createValueStream() options as well:
`reverse` {Boolean} - Streams messages in Ascending time order, default: `true` (Descending)
|
[
"Creates",
"a",
"read",
"stream",
"of",
"messages"
] |
5c2a69a398a6e66221fc3ef2cebfd43df2def320
|
https://github.com/cabal-club/cabal-core/blob/5c2a69a398a6e66221fc3ef2cebfd43df2def320/views/messages.js#L54-L70
|
|
17,167
|
johnpduane/confluence-api
|
lib/confluence.js
|
Confluence
|
function Confluence(config) {
if (!(this instanceof Confluence)) return new Confluence(config);
if (!config) {
throw new Error("Confluence module expects a config object.");
}
else if (!config.username || ! config.password) {
throw new Error("Confluence module expects a config object with both a username and password.");
}
else if (!config.baseUrl) {
throw new Error("Confluence module expects a config object with a baseUrl.");
}
this.config = config;
this.config.apiPath = '/rest/api';
this.config.extension = ''; // no extension by default
if (this.config.version && this.config.version === 4) {
this.config.apiPath = '/rest/prototype/latest';
this.config.extension = '.json';
}
}
|
javascript
|
function Confluence(config) {
if (!(this instanceof Confluence)) return new Confluence(config);
if (!config) {
throw new Error("Confluence module expects a config object.");
}
else if (!config.username || ! config.password) {
throw new Error("Confluence module expects a config object with both a username and password.");
}
else if (!config.baseUrl) {
throw new Error("Confluence module expects a config object with a baseUrl.");
}
this.config = config;
this.config.apiPath = '/rest/api';
this.config.extension = ''; // no extension by default
if (this.config.version && this.config.version === 4) {
this.config.apiPath = '/rest/prototype/latest';
this.config.extension = '.json';
}
}
|
[
"function",
"Confluence",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Confluence",
")",
")",
"return",
"new",
"Confluence",
"(",
"config",
")",
";",
"if",
"(",
"!",
"config",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Confluence module expects a config object.\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"config",
".",
"username",
"||",
"!",
"config",
".",
"password",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Confluence module expects a config object with both a username and password.\"",
")",
";",
"}",
"else",
"if",
"(",
"!",
"config",
".",
"baseUrl",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Confluence module expects a config object with a baseUrl.\"",
")",
";",
"}",
"this",
".",
"config",
"=",
"config",
";",
"this",
".",
"config",
".",
"apiPath",
"=",
"'/rest/api'",
";",
"this",
".",
"config",
".",
"extension",
"=",
"''",
";",
"// no extension by default",
"if",
"(",
"this",
".",
"config",
".",
"version",
"&&",
"this",
".",
"config",
".",
"version",
"===",
"4",
")",
"{",
"this",
".",
"config",
".",
"apiPath",
"=",
"'/rest/prototype/latest'",
";",
"this",
".",
"config",
".",
"extension",
"=",
"'.json'",
";",
"}",
"}"
] |
Construct Confluence.
@constructor
@this {Confluence}
@param {Object} config
@param {string} config.username
@param {string} config.password
@param {string} config.baseUrl
@param {number} config.version - Optional
|
[
"Construct",
"Confluence",
"."
] |
27f300d6d50e37991ed950f7ed395f4ccca49e3f
|
https://github.com/johnpduane/confluence-api/blob/27f300d6d50e37991ed950f7ed395f4ccca49e3f/lib/confluence.js#L23-L45
|
17,168
|
fiduswriter/xslt-processor
|
src/xslt.js
|
xsltPassThrough
|
function xsltPassThrough(input, template, output, outputDocument) {
if (template.nodeType == DOM_TEXT_NODE) {
if (xsltPassText(template)) {
let node = domCreateTextNode(outputDocument, template.nodeValue);
domAppendChild(output, node);
}
} else if (template.nodeType == DOM_ELEMENT_NODE) {
let node = domCreateElement(outputDocument, template.nodeName);
for (const a of template.attributes) {
if (a) {
const name = a.nodeName;
const value = xsltAttributeValue(a.nodeValue, input);
domSetAttribute(node, name, value);
}
}
domAppendChild(output, node);
xsltChildNodes(input, template, node);
} else {
// This applies also to the DOCUMENT_NODE of the XSL stylesheet,
// so we don't have to treat it specially.
xsltChildNodes(input, template, output);
}
}
|
javascript
|
function xsltPassThrough(input, template, output, outputDocument) {
if (template.nodeType == DOM_TEXT_NODE) {
if (xsltPassText(template)) {
let node = domCreateTextNode(outputDocument, template.nodeValue);
domAppendChild(output, node);
}
} else if (template.nodeType == DOM_ELEMENT_NODE) {
let node = domCreateElement(outputDocument, template.nodeName);
for (const a of template.attributes) {
if (a) {
const name = a.nodeName;
const value = xsltAttributeValue(a.nodeValue, input);
domSetAttribute(node, name, value);
}
}
domAppendChild(output, node);
xsltChildNodes(input, template, node);
} else {
// This applies also to the DOCUMENT_NODE of the XSL stylesheet,
// so we don't have to treat it specially.
xsltChildNodes(input, template, output);
}
}
|
[
"function",
"xsltPassThrough",
"(",
"input",
",",
"template",
",",
"output",
",",
"outputDocument",
")",
"{",
"if",
"(",
"template",
".",
"nodeType",
"==",
"DOM_TEXT_NODE",
")",
"{",
"if",
"(",
"xsltPassText",
"(",
"template",
")",
")",
"{",
"let",
"node",
"=",
"domCreateTextNode",
"(",
"outputDocument",
",",
"template",
".",
"nodeValue",
")",
";",
"domAppendChild",
"(",
"output",
",",
"node",
")",
";",
"}",
"}",
"else",
"if",
"(",
"template",
".",
"nodeType",
"==",
"DOM_ELEMENT_NODE",
")",
"{",
"let",
"node",
"=",
"domCreateElement",
"(",
"outputDocument",
",",
"template",
".",
"nodeName",
")",
";",
"for",
"(",
"const",
"a",
"of",
"template",
".",
"attributes",
")",
"{",
"if",
"(",
"a",
")",
"{",
"const",
"name",
"=",
"a",
".",
"nodeName",
";",
"const",
"value",
"=",
"xsltAttributeValue",
"(",
"a",
".",
"nodeValue",
",",
"input",
")",
";",
"domSetAttribute",
"(",
"node",
",",
"name",
",",
"value",
")",
";",
"}",
"}",
"domAppendChild",
"(",
"output",
",",
"node",
")",
";",
"xsltChildNodes",
"(",
"input",
",",
"template",
",",
"node",
")",
";",
"}",
"else",
"{",
"// This applies also to the DOCUMENT_NODE of the XSL stylesheet,",
"// so we don't have to treat it specially.",
"xsltChildNodes",
"(",
"input",
",",
"template",
",",
"output",
")",
";",
"}",
"}"
] |
Passes template text to the output. The current template node does not specify an XSL-T operation and therefore is appended to the output with all its attributes. Then continues traversing the template node tree.
|
[
"Passes",
"template",
"text",
"to",
"the",
"output",
".",
"The",
"current",
"template",
"node",
"does",
"not",
"specify",
"an",
"XSL",
"-",
"T",
"operation",
"and",
"therefore",
"is",
"appended",
"to",
"the",
"output",
"with",
"all",
"its",
"attributes",
".",
"Then",
"continues",
"traversing",
"the",
"template",
"node",
"tree",
"."
] |
fc5f2d6fa1d63da2ba96e4bce692d2e5ab52bf53
|
https://github.com/fiduswriter/xslt-processor/blob/fc5f2d6fa1d63da2ba96e4bce692d2e5ab52bf53/src/xslt.js#L404-L429
|
17,169
|
yibn2008/find-process
|
lib/find.js
|
find
|
function find (by, value, strict) {
return new Promise((resolve, reject) => {
if (!(by in findBy)) {
reject(new Error(`do not support find by "${by}"`))
} else {
findBy[by](value, strict).then(resolve, reject)
}
})
}
|
javascript
|
function find (by, value, strict) {
return new Promise((resolve, reject) => {
if (!(by in findBy)) {
reject(new Error(`do not support find by "${by}"`))
} else {
findBy[by](value, strict).then(resolve, reject)
}
})
}
|
[
"function",
"find",
"(",
"by",
",",
"value",
",",
"strict",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"if",
"(",
"!",
"(",
"by",
"in",
"findBy",
")",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"by",
"}",
"`",
")",
")",
"}",
"else",
"{",
"findBy",
"[",
"by",
"]",
"(",
"value",
",",
"strict",
")",
".",
"then",
"(",
"resolve",
",",
"reject",
")",
"}",
"}",
")",
"}"
] |
find process by condition
return Promise: [{
pid: <process id>,
ppid: <process parent id>,
uid: <user id (*nix)>,
gid: <user group id (*nix)>,
name: <command name>,
cmd: <process run args>
}, ...]
If no process found, resolve process with empty array (only reject when error occured)
@param {String} by condition: port/pid/name ...
@param {Mixed} condition value
@return {Promise}
|
[
"find",
"process",
"by",
"condition"
] |
a0a154cc6b0676312233ded67fd042d6c5095913
|
https://github.com/yibn2008/find-process/blob/a0a154cc6b0676312233ded67fd042d6c5095913/lib/find.js#L55-L63
|
17,170
|
firesharkstudios/butterfly-server-dotnet
|
docs/docfx/styles/docfx.js
|
renderNavbar
|
function renderNavbar() {
var navbar = $('#navbar ul')[0];
if (typeof (navbar) === 'undefined') {
loadNavbar();
} else {
$('#navbar ul a.active').parents('li').addClass(active);
renderBreadcrumb();
}
function loadNavbar() {
var navbarPath = $("meta[property='docfx\\:navrel']").attr("content");
if (!navbarPath) {
return;
}
navbarPath = navbarPath.replace(/\\/g, '/');
var tocPath = $("meta[property='docfx\\:tocrel']").attr("content") || '';
if (tocPath) tocPath = tocPath.replace(/\\/g, '/');
$.get(navbarPath, function (data) {
$(data).find("#toc>ul").appendTo("#navbar");
if ($('#search-results').length !== 0) {
$('#search').show();
$('body').trigger("searchEvent");
}
var index = navbarPath.lastIndexOf('/');
var navrel = '';
if (index > -1) {
navrel = navbarPath.substr(0, index + 1);
}
$('#navbar>ul').addClass('navbar-nav');
var currentAbsPath = util.getAbsolutePath(window.location.pathname);
// set active item
$('#navbar').find('a[href]').each(function (i, e) {
var href = $(e).attr("href");
if (util.isRelativePath(href)) {
href = navrel + href;
$(e).attr("href", href);
// TODO: currently only support one level navbar
var isActive = false;
var originalHref = e.name;
if (originalHref) {
originalHref = navrel + originalHref;
if (util.getDirectory(util.getAbsolutePath(originalHref)) === util.getDirectory(util.getAbsolutePath(tocPath))) {
isActive = true;
}
} else {
if (util.getAbsolutePath(href) === currentAbsPath) {
var dropdown = $(e).attr('data-toggle') == "dropdown"
if (!dropdown) {
isActive = true;
}
}
}
if (isActive) {
$(e).addClass(active);
}
}
});
renderNavbar();
});
}
}
|
javascript
|
function renderNavbar() {
var navbar = $('#navbar ul')[0];
if (typeof (navbar) === 'undefined') {
loadNavbar();
} else {
$('#navbar ul a.active').parents('li').addClass(active);
renderBreadcrumb();
}
function loadNavbar() {
var navbarPath = $("meta[property='docfx\\:navrel']").attr("content");
if (!navbarPath) {
return;
}
navbarPath = navbarPath.replace(/\\/g, '/');
var tocPath = $("meta[property='docfx\\:tocrel']").attr("content") || '';
if (tocPath) tocPath = tocPath.replace(/\\/g, '/');
$.get(navbarPath, function (data) {
$(data).find("#toc>ul").appendTo("#navbar");
if ($('#search-results').length !== 0) {
$('#search').show();
$('body').trigger("searchEvent");
}
var index = navbarPath.lastIndexOf('/');
var navrel = '';
if (index > -1) {
navrel = navbarPath.substr(0, index + 1);
}
$('#navbar>ul').addClass('navbar-nav');
var currentAbsPath = util.getAbsolutePath(window.location.pathname);
// set active item
$('#navbar').find('a[href]').each(function (i, e) {
var href = $(e).attr("href");
if (util.isRelativePath(href)) {
href = navrel + href;
$(e).attr("href", href);
// TODO: currently only support one level navbar
var isActive = false;
var originalHref = e.name;
if (originalHref) {
originalHref = navrel + originalHref;
if (util.getDirectory(util.getAbsolutePath(originalHref)) === util.getDirectory(util.getAbsolutePath(tocPath))) {
isActive = true;
}
} else {
if (util.getAbsolutePath(href) === currentAbsPath) {
var dropdown = $(e).attr('data-toggle') == "dropdown"
if (!dropdown) {
isActive = true;
}
}
}
if (isActive) {
$(e).addClass(active);
}
}
});
renderNavbar();
});
}
}
|
[
"function",
"renderNavbar",
"(",
")",
"{",
"var",
"navbar",
"=",
"$",
"(",
"'#navbar ul'",
")",
"[",
"0",
"]",
";",
"if",
"(",
"typeof",
"(",
"navbar",
")",
"===",
"'undefined'",
")",
"{",
"loadNavbar",
"(",
")",
";",
"}",
"else",
"{",
"$",
"(",
"'#navbar ul a.active'",
")",
".",
"parents",
"(",
"'li'",
")",
".",
"addClass",
"(",
"active",
")",
";",
"renderBreadcrumb",
"(",
")",
";",
"}",
"function",
"loadNavbar",
"(",
")",
"{",
"var",
"navbarPath",
"=",
"$",
"(",
"\"meta[property='docfx\\\\:navrel']\"",
")",
".",
"attr",
"(",
"\"content\"",
")",
";",
"if",
"(",
"!",
"navbarPath",
")",
"{",
"return",
";",
"}",
"navbarPath",
"=",
"navbarPath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"var",
"tocPath",
"=",
"$",
"(",
"\"meta[property='docfx\\\\:tocrel']\"",
")",
".",
"attr",
"(",
"\"content\"",
")",
"||",
"''",
";",
"if",
"(",
"tocPath",
")",
"tocPath",
"=",
"tocPath",
".",
"replace",
"(",
"/",
"\\\\",
"/",
"g",
",",
"'/'",
")",
";",
"$",
".",
"get",
"(",
"navbarPath",
",",
"function",
"(",
"data",
")",
"{",
"$",
"(",
"data",
")",
".",
"find",
"(",
"\"#toc>ul\"",
")",
".",
"appendTo",
"(",
"\"#navbar\"",
")",
";",
"if",
"(",
"$",
"(",
"'#search-results'",
")",
".",
"length",
"!==",
"0",
")",
"{",
"$",
"(",
"'#search'",
")",
".",
"show",
"(",
")",
";",
"$",
"(",
"'body'",
")",
".",
"trigger",
"(",
"\"searchEvent\"",
")",
";",
"}",
"var",
"index",
"=",
"navbarPath",
".",
"lastIndexOf",
"(",
"'/'",
")",
";",
"var",
"navrel",
"=",
"''",
";",
"if",
"(",
"index",
">",
"-",
"1",
")",
"{",
"navrel",
"=",
"navbarPath",
".",
"substr",
"(",
"0",
",",
"index",
"+",
"1",
")",
";",
"}",
"$",
"(",
"'#navbar>ul'",
")",
".",
"addClass",
"(",
"'navbar-nav'",
")",
";",
"var",
"currentAbsPath",
"=",
"util",
".",
"getAbsolutePath",
"(",
"window",
".",
"location",
".",
"pathname",
")",
";",
"// set active item",
"$",
"(",
"'#navbar'",
")",
".",
"find",
"(",
"'a[href]'",
")",
".",
"each",
"(",
"function",
"(",
"i",
",",
"e",
")",
"{",
"var",
"href",
"=",
"$",
"(",
"e",
")",
".",
"attr",
"(",
"\"href\"",
")",
";",
"if",
"(",
"util",
".",
"isRelativePath",
"(",
"href",
")",
")",
"{",
"href",
"=",
"navrel",
"+",
"href",
";",
"$",
"(",
"e",
")",
".",
"attr",
"(",
"\"href\"",
",",
"href",
")",
";",
"// TODO: currently only support one level navbar",
"var",
"isActive",
"=",
"false",
";",
"var",
"originalHref",
"=",
"e",
".",
"name",
";",
"if",
"(",
"originalHref",
")",
"{",
"originalHref",
"=",
"navrel",
"+",
"originalHref",
";",
"if",
"(",
"util",
".",
"getDirectory",
"(",
"util",
".",
"getAbsolutePath",
"(",
"originalHref",
")",
")",
"===",
"util",
".",
"getDirectory",
"(",
"util",
".",
"getAbsolutePath",
"(",
"tocPath",
")",
")",
")",
"{",
"isActive",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"util",
".",
"getAbsolutePath",
"(",
"href",
")",
"===",
"currentAbsPath",
")",
"{",
"var",
"dropdown",
"=",
"$",
"(",
"e",
")",
".",
"attr",
"(",
"'data-toggle'",
")",
"==",
"\"dropdown\"",
"if",
"(",
"!",
"dropdown",
")",
"{",
"isActive",
"=",
"true",
";",
"}",
"}",
"}",
"if",
"(",
"isActive",
")",
"{",
"$",
"(",
"e",
")",
".",
"addClass",
"(",
"active",
")",
";",
"}",
"}",
"}",
")",
";",
"renderNavbar",
"(",
")",
";",
"}",
")",
";",
"}",
"}"
] |
Update href in navbar
|
[
"Update",
"href",
"in",
"navbar"
] |
9859557197966d970e8030e91f908c73c5082e0f
|
https://github.com/firesharkstudios/butterfly-server-dotnet/blob/9859557197966d970e8030e91f908c73c5082e0f/docs/docfx/styles/docfx.js#L343-L404
|
17,171
|
BinaryMuse/planetary.js
|
site/public/examples/quake/quake.js
|
autocenter
|
function autocenter(options) {
options = options || {};
var needsCentering = false;
var globe = null;
var resize = function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
globe.canvas.width = width;
globe.canvas.height = height;
globe.projection.translate([width / 2, height / 2]);
};
return function(planet) {
globe = planet;
planet.onInit(function() {
needsCentering = true;
d3.select(window).on('resize', function() {
needsCentering = true;
});
});
planet.onDraw(function() {
if (needsCentering) { resize(); needsCentering = false; }
});
};
}
|
javascript
|
function autocenter(options) {
options = options || {};
var needsCentering = false;
var globe = null;
var resize = function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
globe.canvas.width = width;
globe.canvas.height = height;
globe.projection.translate([width / 2, height / 2]);
};
return function(planet) {
globe = planet;
planet.onInit(function() {
needsCentering = true;
d3.select(window).on('resize', function() {
needsCentering = true;
});
});
planet.onDraw(function() {
if (needsCentering) { resize(); needsCentering = false; }
});
};
}
|
[
"function",
"autocenter",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"needsCentering",
"=",
"false",
";",
"var",
"globe",
"=",
"null",
";",
"var",
"resize",
"=",
"function",
"(",
")",
"{",
"var",
"width",
"=",
"window",
".",
"innerWidth",
"+",
"(",
"options",
".",
"extraWidth",
"||",
"0",
")",
";",
"var",
"height",
"=",
"window",
".",
"innerHeight",
"+",
"(",
"options",
".",
"extraHeight",
"||",
"0",
")",
";",
"globe",
".",
"canvas",
".",
"width",
"=",
"width",
";",
"globe",
".",
"canvas",
".",
"height",
"=",
"height",
";",
"globe",
".",
"projection",
".",
"translate",
"(",
"[",
"width",
"/",
"2",
",",
"height",
"/",
"2",
"]",
")",
";",
"}",
";",
"return",
"function",
"(",
"planet",
")",
"{",
"globe",
"=",
"planet",
";",
"planet",
".",
"onInit",
"(",
"function",
"(",
")",
"{",
"needsCentering",
"=",
"true",
";",
"d3",
".",
"select",
"(",
"window",
")",
".",
"on",
"(",
"'resize'",
",",
"function",
"(",
")",
"{",
"needsCentering",
"=",
"true",
";",
"}",
")",
";",
"}",
")",
";",
"planet",
".",
"onDraw",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"needsCentering",
")",
"{",
"resize",
"(",
")",
";",
"needsCentering",
"=",
"false",
";",
"}",
"}",
")",
";",
"}",
";",
"}"
] |
Plugin to resize the canvas to fill the window and to automatically center the planet when the window size changes
|
[
"Plugin",
"to",
"resize",
"the",
"canvas",
"to",
"fill",
"the",
"window",
"and",
"to",
"automatically",
"center",
"the",
"planet",
"when",
"the",
"window",
"size",
"changes"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/examples/quake/quake.js#L163-L189
|
17,172
|
BinaryMuse/planetary.js
|
site/public/examples/quake/quake.js
|
autoscale
|
function autoscale(options) {
options = options || {};
return function(planet) {
planet.onInit(function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
planet.projection.scale(Math.min(width, height) / 2);
});
};
}
|
javascript
|
function autoscale(options) {
options = options || {};
return function(planet) {
planet.onInit(function() {
var width = window.innerWidth + (options.extraWidth || 0);
var height = window.innerHeight + (options.extraHeight || 0);
planet.projection.scale(Math.min(width, height) / 2);
});
};
}
|
[
"function",
"autoscale",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"return",
"function",
"(",
"planet",
")",
"{",
"planet",
".",
"onInit",
"(",
"function",
"(",
")",
"{",
"var",
"width",
"=",
"window",
".",
"innerWidth",
"+",
"(",
"options",
".",
"extraWidth",
"||",
"0",
")",
";",
"var",
"height",
"=",
"window",
".",
"innerHeight",
"+",
"(",
"options",
".",
"extraHeight",
"||",
"0",
")",
";",
"planet",
".",
"projection",
".",
"scale",
"(",
"Math",
".",
"min",
"(",
"width",
",",
"height",
")",
"/",
"2",
")",
";",
"}",
")",
";",
"}",
";",
"}"
] |
Plugin to automatically scale the planet's projection based on the window size when the planet is initialized
|
[
"Plugin",
"to",
"automatically",
"scale",
"the",
"planet",
"s",
"projection",
"based",
"on",
"the",
"window",
"size",
"when",
"the",
"planet",
"is",
"initialized"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/examples/quake/quake.js#L193-L202
|
17,173
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function() {
$module
.data(metadata.promise, false)
.data(metadata.xhr, false)
;
$context
.removeClass(className.error)
.removeClass(className.loading)
;
}
|
javascript
|
function() {
$module
.data(metadata.promise, false)
.data(metadata.xhr, false)
;
$context
.removeClass(className.error)
.removeClass(className.loading)
;
}
|
[
"function",
"(",
")",
"{",
"$module",
".",
"data",
"(",
"metadata",
".",
"promise",
",",
"false",
")",
".",
"data",
"(",
"metadata",
".",
"xhr",
",",
"false",
")",
";",
"$context",
".",
"removeClass",
"(",
"className",
".",
"error",
")",
".",
"removeClass",
"(",
"className",
".",
"loading",
")",
";",
"}"
] |
reset api request
|
[
"reset",
"api",
"request"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L765-L774
|
|
17,174
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(member) {
users = $module.data('users');
if(member.id != 'anonymous' && users[ member.id ] === undefined ) {
users[ member.id ] = member.info;
if(settings.randomColor && member.info.color === undefined) {
member.info.color = settings.templates.color(member.id);
}
html = settings.templates.userList(member.info);
if(member.info.isAdmin) {
$(html)
.prependTo($userList)
;
}
else {
$(html)
.appendTo($userList)
;
}
if(settings.partingMessages) {
$log
.append( settings.templates.joined(member.info) )
;
module.message.scroll.test();
}
module.user.updateCount();
}
}
|
javascript
|
function(member) {
users = $module.data('users');
if(member.id != 'anonymous' && users[ member.id ] === undefined ) {
users[ member.id ] = member.info;
if(settings.randomColor && member.info.color === undefined) {
member.info.color = settings.templates.color(member.id);
}
html = settings.templates.userList(member.info);
if(member.info.isAdmin) {
$(html)
.prependTo($userList)
;
}
else {
$(html)
.appendTo($userList)
;
}
if(settings.partingMessages) {
$log
.append( settings.templates.joined(member.info) )
;
module.message.scroll.test();
}
module.user.updateCount();
}
}
|
[
"function",
"(",
"member",
")",
"{",
"users",
"=",
"$module",
".",
"data",
"(",
"'users'",
")",
";",
"if",
"(",
"member",
".",
"id",
"!=",
"'anonymous'",
"&&",
"users",
"[",
"member",
".",
"id",
"]",
"===",
"undefined",
")",
"{",
"users",
"[",
"member",
".",
"id",
"]",
"=",
"member",
".",
"info",
";",
"if",
"(",
"settings",
".",
"randomColor",
"&&",
"member",
".",
"info",
".",
"color",
"===",
"undefined",
")",
"{",
"member",
".",
"info",
".",
"color",
"=",
"settings",
".",
"templates",
".",
"color",
"(",
"member",
".",
"id",
")",
";",
"}",
"html",
"=",
"settings",
".",
"templates",
".",
"userList",
"(",
"member",
".",
"info",
")",
";",
"if",
"(",
"member",
".",
"info",
".",
"isAdmin",
")",
"{",
"$",
"(",
"html",
")",
".",
"prependTo",
"(",
"$userList",
")",
";",
"}",
"else",
"{",
"$",
"(",
"html",
")",
".",
"appendTo",
"(",
"$userList",
")",
";",
"}",
"if",
"(",
"settings",
".",
"partingMessages",
")",
"{",
"$log",
".",
"append",
"(",
"settings",
".",
"templates",
".",
"joined",
"(",
"member",
".",
"info",
")",
")",
";",
"module",
".",
"message",
".",
"scroll",
".",
"test",
"(",
")",
";",
"}",
"module",
".",
"user",
".",
"updateCount",
"(",
")",
";",
"}",
"}"
] |
add user to user list
|
[
"add",
"user",
"to",
"user",
"list"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L2924-L2950
|
|
17,175
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(member) {
users = $module.data('users');
if(member !== undefined && member.id !== 'anonymous') {
delete users[ member.id ];
$module
.data('users', users)
;
$userList
.find('[data-id='+ member.id + ']')
.remove()
;
if(settings.partingMessages) {
$log
.append( settings.templates.left(member.info) )
;
module.message.scroll.test();
}
module.user.updateCount();
}
}
|
javascript
|
function(member) {
users = $module.data('users');
if(member !== undefined && member.id !== 'anonymous') {
delete users[ member.id ];
$module
.data('users', users)
;
$userList
.find('[data-id='+ member.id + ']')
.remove()
;
if(settings.partingMessages) {
$log
.append( settings.templates.left(member.info) )
;
module.message.scroll.test();
}
module.user.updateCount();
}
}
|
[
"function",
"(",
"member",
")",
"{",
"users",
"=",
"$module",
".",
"data",
"(",
"'users'",
")",
";",
"if",
"(",
"member",
"!==",
"undefined",
"&&",
"member",
".",
"id",
"!==",
"'anonymous'",
")",
"{",
"delete",
"users",
"[",
"member",
".",
"id",
"]",
";",
"$module",
".",
"data",
"(",
"'users'",
",",
"users",
")",
";",
"$userList",
".",
"find",
"(",
"'[data-id='",
"+",
"member",
".",
"id",
"+",
"']'",
")",
".",
"remove",
"(",
")",
";",
"if",
"(",
"settings",
".",
"partingMessages",
")",
"{",
"$log",
".",
"append",
"(",
"settings",
".",
"templates",
".",
"left",
"(",
"member",
".",
"info",
")",
")",
";",
"module",
".",
"message",
".",
"scroll",
".",
"test",
"(",
")",
";",
"}",
"module",
".",
"user",
".",
"updateCount",
"(",
")",
";",
"}",
"}"
] |
remove user from user list
|
[
"remove",
"user",
"from",
"user",
"list"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L2953-L2972
|
|
17,176
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(members) {
users = {};
members.each(function(member) {
if(member.id !== 'anonymous' && member.id !== 'undefined') {
if(settings.randomColor && member.info.color === undefined) {
member.info.color = settings.templates.color(member.id);
}
// sort list with admin first
html = (member.info.isAdmin)
? settings.templates.userList(member.info) + html
: html + settings.templates.userList(member.info)
;
users[ member.id ] = member.info;
}
});
$module
.data('users', users)
.data('user', users[members.me.id] )
.removeClass(className.loading)
;
$userList
.html(html)
;
module.user.updateCount();
$.proxy(settings.onJoin, $userList.children())();
}
|
javascript
|
function(members) {
users = {};
members.each(function(member) {
if(member.id !== 'anonymous' && member.id !== 'undefined') {
if(settings.randomColor && member.info.color === undefined) {
member.info.color = settings.templates.color(member.id);
}
// sort list with admin first
html = (member.info.isAdmin)
? settings.templates.userList(member.info) + html
: html + settings.templates.userList(member.info)
;
users[ member.id ] = member.info;
}
});
$module
.data('users', users)
.data('user', users[members.me.id] )
.removeClass(className.loading)
;
$userList
.html(html)
;
module.user.updateCount();
$.proxy(settings.onJoin, $userList.children())();
}
|
[
"function",
"(",
"members",
")",
"{",
"users",
"=",
"{",
"}",
";",
"members",
".",
"each",
"(",
"function",
"(",
"member",
")",
"{",
"if",
"(",
"member",
".",
"id",
"!==",
"'anonymous'",
"&&",
"member",
".",
"id",
"!==",
"'undefined'",
")",
"{",
"if",
"(",
"settings",
".",
"randomColor",
"&&",
"member",
".",
"info",
".",
"color",
"===",
"undefined",
")",
"{",
"member",
".",
"info",
".",
"color",
"=",
"settings",
".",
"templates",
".",
"color",
"(",
"member",
".",
"id",
")",
";",
"}",
"// sort list with admin first",
"html",
"=",
"(",
"member",
".",
"info",
".",
"isAdmin",
")",
"?",
"settings",
".",
"templates",
".",
"userList",
"(",
"member",
".",
"info",
")",
"+",
"html",
":",
"html",
"+",
"settings",
".",
"templates",
".",
"userList",
"(",
"member",
".",
"info",
")",
";",
"users",
"[",
"member",
".",
"id",
"]",
"=",
"member",
".",
"info",
";",
"}",
"}",
")",
";",
"$module",
".",
"data",
"(",
"'users'",
",",
"users",
")",
".",
"data",
"(",
"'user'",
",",
"users",
"[",
"members",
".",
"me",
".",
"id",
"]",
")",
".",
"removeClass",
"(",
"className",
".",
"loading",
")",
";",
"$userList",
".",
"html",
"(",
"html",
")",
";",
"module",
".",
"user",
".",
"updateCount",
"(",
")",
";",
"$",
".",
"proxy",
"(",
"settings",
".",
"onJoin",
",",
"$userList",
".",
"children",
"(",
")",
")",
"(",
")",
";",
"}"
] |
receives list of members and generates user list
|
[
"receives",
"list",
"of",
"members",
"and",
"generates",
"user",
"list"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L2977-L3002
|
|
17,177
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function() {
$log
.animate({
width: (module.width.log - module.width.userList)
}, {
duration : settings.speed,
easing : settings.easing,
complete : module.message.scroll.move
})
;
}
|
javascript
|
function() {
$log
.animate({
width: (module.width.log - module.width.userList)
}, {
duration : settings.speed,
easing : settings.easing,
complete : module.message.scroll.move
})
;
}
|
[
"function",
"(",
")",
"{",
"$log",
".",
"animate",
"(",
"{",
"width",
":",
"(",
"module",
".",
"width",
".",
"log",
"-",
"module",
".",
"width",
".",
"userList",
")",
"}",
",",
"{",
"duration",
":",
"settings",
".",
"speed",
",",
"easing",
":",
"settings",
".",
"easing",
",",
"complete",
":",
"module",
".",
"message",
".",
"scroll",
".",
"move",
"}",
")",
";",
"}"
] |
shows user list
|
[
"shows",
"user",
"list"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3005-L3015
|
|
17,178
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(message) {
if( !module.utils.emptyString(message) ) {
$.api({
url : settings.endpoint.message,
method : 'POST',
data : {
'message': {
content : message,
timestamp : new Date().getTime()
}
}
});
}
}
|
javascript
|
function(message) {
if( !module.utils.emptyString(message) ) {
$.api({
url : settings.endpoint.message,
method : 'POST',
data : {
'message': {
content : message,
timestamp : new Date().getTime()
}
}
});
}
}
|
[
"function",
"(",
"message",
")",
"{",
"if",
"(",
"!",
"module",
".",
"utils",
".",
"emptyString",
"(",
"message",
")",
")",
"{",
"$",
".",
"api",
"(",
"{",
"url",
":",
"settings",
".",
"endpoint",
".",
"message",
",",
"method",
":",
"'POST'",
",",
"data",
":",
"{",
"'message'",
":",
"{",
"content",
":",
"message",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"}",
"}",
"}",
")",
";",
"}",
"}"
] |
sends chat message
|
[
"sends",
"chat",
"message"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3055-L3068
|
|
17,179
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(response) {
message = response.data;
users = $module.data('users');
loggedInUser = $module.data('user');
if(users[ message.userID] !== undefined) {
// logged in user's messages already pushed instantly
if(loggedInUser === undefined || loggedInUser.id != message.userID) {
message.user = users[ message.userID ];
module.message.display(message);
}
}
}
|
javascript
|
function(response) {
message = response.data;
users = $module.data('users');
loggedInUser = $module.data('user');
if(users[ message.userID] !== undefined) {
// logged in user's messages already pushed instantly
if(loggedInUser === undefined || loggedInUser.id != message.userID) {
message.user = users[ message.userID ];
module.message.display(message);
}
}
}
|
[
"function",
"(",
"response",
")",
"{",
"message",
"=",
"response",
".",
"data",
";",
"users",
"=",
"$module",
".",
"data",
"(",
"'users'",
")",
";",
"loggedInUser",
"=",
"$module",
".",
"data",
"(",
"'user'",
")",
";",
"if",
"(",
"users",
"[",
"message",
".",
"userID",
"]",
"!==",
"undefined",
")",
"{",
"// logged in user's messages already pushed instantly",
"if",
"(",
"loggedInUser",
"===",
"undefined",
"||",
"loggedInUser",
".",
"id",
"!=",
"message",
".",
"userID",
")",
"{",
"message",
".",
"user",
"=",
"users",
"[",
"message",
".",
"userID",
"]",
";",
"module",
".",
"message",
".",
"display",
"(",
"message",
")",
";",
"}",
"}",
"}"
] |
receives chat response and processes
|
[
"receives",
"chat",
"response",
"and",
"processes"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3071-L3082
|
|
17,180
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(message) {
$log
.append( settings.templates.message(message) )
;
module.message.scroll.test();
$.proxy(settings.onMessage, $log.children().last() )();
}
|
javascript
|
function(message) {
$log
.append( settings.templates.message(message) )
;
module.message.scroll.test();
$.proxy(settings.onMessage, $log.children().last() )();
}
|
[
"function",
"(",
"message",
")",
"{",
"$log",
".",
"append",
"(",
"settings",
".",
"templates",
".",
"message",
"(",
"message",
")",
")",
";",
"module",
".",
"message",
".",
"scroll",
".",
"test",
"(",
")",
";",
"$",
".",
"proxy",
"(",
"settings",
".",
"onMessage",
",",
"$log",
".",
"children",
"(",
")",
".",
"last",
"(",
")",
")",
"(",
")",
";",
"}"
] |
displays message in chat log
|
[
"displays",
"message",
"in",
"chat",
"log"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3085-L3091
|
|
17,181
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function() {
var
message = $messageInput.val(),
loggedInUser = $module.data('user')
;
if(loggedInUser !== undefined && !module.utils.emptyString(message)) {
module.message.send(message);
// display immediately
module.message.display({
user: loggedInUser,
text: message
});
module.message.scroll.move();
$messageInput
.val('')
;
}
}
|
javascript
|
function() {
var
message = $messageInput.val(),
loggedInUser = $module.data('user')
;
if(loggedInUser !== undefined && !module.utils.emptyString(message)) {
module.message.send(message);
// display immediately
module.message.display({
user: loggedInUser,
text: message
});
module.message.scroll.move();
$messageInput
.val('')
;
}
}
|
[
"function",
"(",
")",
"{",
"var",
"message",
"=",
"$messageInput",
".",
"val",
"(",
")",
",",
"loggedInUser",
"=",
"$module",
".",
"data",
"(",
"'user'",
")",
";",
"if",
"(",
"loggedInUser",
"!==",
"undefined",
"&&",
"!",
"module",
".",
"utils",
".",
"emptyString",
"(",
"message",
")",
")",
"{",
"module",
".",
"message",
".",
"send",
"(",
"message",
")",
";",
"// display immediately",
"module",
".",
"message",
".",
"display",
"(",
"{",
"user",
":",
"loggedInUser",
",",
"text",
":",
"message",
"}",
")",
";",
"module",
".",
"message",
".",
"scroll",
".",
"move",
"(",
")",
";",
"$messageInput",
".",
"val",
"(",
"''",
")",
";",
"}",
"}"
] |
handles message form submit
|
[
"handles",
"message",
"form",
"submit"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3135-L3153
|
|
17,182
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function() {
if( !$module.hasClass(className.expand) ) {
$expandButton
.addClass(className.active)
;
module.expand();
}
else {
$expandButton
.removeClass(className.active)
;
module.contract();
}
}
|
javascript
|
function() {
if( !$module.hasClass(className.expand) ) {
$expandButton
.addClass(className.active)
;
module.expand();
}
else {
$expandButton
.removeClass(className.active)
;
module.contract();
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"$module",
".",
"hasClass",
"(",
"className",
".",
"expand",
")",
")",
"{",
"$expandButton",
".",
"addClass",
"(",
"className",
".",
"active",
")",
";",
"module",
".",
"expand",
"(",
")",
";",
"}",
"else",
"{",
"$expandButton",
".",
"removeClass",
"(",
"className",
".",
"active",
")",
";",
"module",
".",
"contract",
"(",
")",
";",
"}",
"}"
] |
handles button click on expand button
|
[
"handles",
"button",
"click",
"on",
"expand",
"button"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3156-L3169
|
|
17,183
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function() {
if( !$log.is(':animated') ) {
if( !$userListButton.hasClass(className.active) ) {
$userListButton
.addClass(className.active)
;
module.user.list.show();
}
else {
$userListButton
.removeClass('active')
;
module.user.list.hide();
}
}
}
|
javascript
|
function() {
if( !$log.is(':animated') ) {
if( !$userListButton.hasClass(className.active) ) {
$userListButton
.addClass(className.active)
;
module.user.list.show();
}
else {
$userListButton
.removeClass('active')
;
module.user.list.hide();
}
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"$log",
".",
"is",
"(",
"':animated'",
")",
")",
"{",
"if",
"(",
"!",
"$userListButton",
".",
"hasClass",
"(",
"className",
".",
"active",
")",
")",
"{",
"$userListButton",
".",
"addClass",
"(",
"className",
".",
"active",
")",
";",
"module",
".",
"user",
".",
"list",
".",
"show",
"(",
")",
";",
"}",
"else",
"{",
"$userListButton",
".",
"removeClass",
"(",
"'active'",
")",
";",
"module",
".",
"user",
".",
"list",
".",
"hide",
"(",
")",
";",
"}",
"}",
"}"
] |
handles button click on user list button
|
[
"handles",
"button",
"click",
"on",
"user",
"list",
"button"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L3172-L3188
|
|
17,184
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(source, id, url) {
module.debug('Changing video to ', source, id, url);
$module
.data(metadata.source, source)
.data(metadata.id, id)
.data(metadata.url, url)
;
settings.onChange();
}
|
javascript
|
function(source, id, url) {
module.debug('Changing video to ', source, id, url);
$module
.data(metadata.source, source)
.data(metadata.id, id)
.data(metadata.url, url)
;
settings.onChange();
}
|
[
"function",
"(",
"source",
",",
"id",
",",
"url",
")",
"{",
"module",
".",
"debug",
"(",
"'Changing video to '",
",",
"source",
",",
"id",
",",
"url",
")",
";",
"$module",
".",
"data",
"(",
"metadata",
".",
"source",
",",
"source",
")",
".",
"data",
"(",
"metadata",
".",
"id",
",",
"id",
")",
".",
"data",
"(",
"metadata",
".",
"url",
",",
"url",
")",
";",
"settings",
".",
"onChange",
"(",
")",
";",
"}"
] |
sets new video
|
[
"sets",
"new",
"video"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L11301-L11309
|
|
17,185
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function() {
module.debug('Playing video');
var
source = $module.data(metadata.source) || false,
url = $module.data(metadata.url) || false,
id = $module.data(metadata.id) || false
;
$embed
.html( module.generate.html(source, id, url) )
;
$module
.addClass(className.active)
;
settings.onPlay();
}
|
javascript
|
function() {
module.debug('Playing video');
var
source = $module.data(metadata.source) || false,
url = $module.data(metadata.url) || false,
id = $module.data(metadata.id) || false
;
$embed
.html( module.generate.html(source, id, url) )
;
$module
.addClass(className.active)
;
settings.onPlay();
}
|
[
"function",
"(",
")",
"{",
"module",
".",
"debug",
"(",
"'Playing video'",
")",
";",
"var",
"source",
"=",
"$module",
".",
"data",
"(",
"metadata",
".",
"source",
")",
"||",
"false",
",",
"url",
"=",
"$module",
".",
"data",
"(",
"metadata",
".",
"url",
")",
"||",
"false",
",",
"id",
"=",
"$module",
".",
"data",
"(",
"metadata",
".",
"id",
")",
"||",
"false",
";",
"$embed",
".",
"html",
"(",
"module",
".",
"generate",
".",
"html",
"(",
"source",
",",
"id",
",",
"url",
")",
")",
";",
"$module",
".",
"addClass",
"(",
"className",
".",
"active",
")",
";",
"settings",
".",
"onPlay",
"(",
")",
";",
"}"
] |
plays current video
|
[
"plays",
"current",
"video"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L11327-L11341
|
|
17,186
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(source, id, url) {
module.debug('Generating embed html');
var
width = (settings.width == 'auto')
? $module.width()
: settings.width,
height = (settings.height == 'auto')
? $module.height()
: settings.height,
html
;
if(source && id) {
if(source == 'vimeo') {
html = ''
+ '<iframe src="http://player.vimeo.com/video/' + id + '?=' + module.generate.url(source) + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
else if(source == 'youtube') {
html = ''
+ '<iframe src="http://www.youtube.com/embed/' + id + '?=' + module.generate.url(source) + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
}
else if(url) {
html = ''
+ '<iframe src="' + url + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
else {
module.error(error.noVideo);
}
return html;
}
|
javascript
|
function(source, id, url) {
module.debug('Generating embed html');
var
width = (settings.width == 'auto')
? $module.width()
: settings.width,
height = (settings.height == 'auto')
? $module.height()
: settings.height,
html
;
if(source && id) {
if(source == 'vimeo') {
html = ''
+ '<iframe src="http://player.vimeo.com/video/' + id + '?=' + module.generate.url(source) + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
else if(source == 'youtube') {
html = ''
+ '<iframe src="http://www.youtube.com/embed/' + id + '?=' + module.generate.url(source) + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
}
else if(url) {
html = ''
+ '<iframe src="' + url + '"'
+ ' width="' + width + '" height="' + height + '"'
+ ' frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
}
else {
module.error(error.noVideo);
}
return html;
}
|
[
"function",
"(",
"source",
",",
"id",
",",
"url",
")",
"{",
"module",
".",
"debug",
"(",
"'Generating embed html'",
")",
";",
"var",
"width",
"=",
"(",
"settings",
".",
"width",
"==",
"'auto'",
")",
"?",
"$module",
".",
"width",
"(",
")",
":",
"settings",
".",
"width",
",",
"height",
"=",
"(",
"settings",
".",
"height",
"==",
"'auto'",
")",
"?",
"$module",
".",
"height",
"(",
")",
":",
"settings",
".",
"height",
",",
"html",
";",
"if",
"(",
"source",
"&&",
"id",
")",
"{",
"if",
"(",
"source",
"==",
"'vimeo'",
")",
"{",
"html",
"=",
"''",
"+",
"'<iframe src=\"http://player.vimeo.com/video/'",
"+",
"id",
"+",
"'?='",
"+",
"module",
".",
"generate",
".",
"url",
"(",
"source",
")",
"+",
"'\"'",
"+",
"' width=\"'",
"+",
"width",
"+",
"'\" height=\"'",
"+",
"height",
"+",
"'\"'",
"+",
"' frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'",
";",
"}",
"else",
"if",
"(",
"source",
"==",
"'youtube'",
")",
"{",
"html",
"=",
"''",
"+",
"'<iframe src=\"http://www.youtube.com/embed/'",
"+",
"id",
"+",
"'?='",
"+",
"module",
".",
"generate",
".",
"url",
"(",
"source",
")",
"+",
"'\"'",
"+",
"' width=\"'",
"+",
"width",
"+",
"'\" height=\"'",
"+",
"height",
"+",
"'\"'",
"+",
"' frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'",
";",
"}",
"}",
"else",
"if",
"(",
"url",
")",
"{",
"html",
"=",
"''",
"+",
"'<iframe src=\"'",
"+",
"url",
"+",
"'\"'",
"+",
"' width=\"'",
"+",
"width",
"+",
"'\" height=\"'",
"+",
"height",
"+",
"'\"'",
"+",
"' frameborder=\"0\" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'",
";",
"}",
"else",
"{",
"module",
".",
"error",
"(",
"error",
".",
"noVideo",
")",
";",
"}",
"return",
"html",
";",
"}"
] |
generates iframe html
|
[
"generates",
"iframe",
"html"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L11345-L11383
|
|
17,187
|
BinaryMuse/planetary.js
|
site/public/semantic/javascript/semantic.js
|
function(source) {
var
api = (settings.api)
? 1
: 0,
autoplay = (settings.autoplay)
? 1
: 0,
hd = (settings.hd)
? 1
: 0,
showUI = (settings.showUI)
? 1
: 0,
// opposite used for some params
hideUI = !(settings.showUI)
? 1
: 0,
url = ''
;
if(source == 'vimeo') {
url = ''
+ 'api=' + api
+ '&title=' + showUI
+ '&byline=' + showUI
+ '&portrait=' + showUI
+ '&autoplay=' + autoplay
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
if(source == 'ustream') {
url = ''
+ 'autoplay=' + autoplay
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
else if(source == 'youtube') {
url = ''
+ 'enablejsapi=' + api
+ '&autoplay=' + autoplay
+ '&autohide=' + hideUI
+ '&hq=' + hd
+ '&modestbranding=1'
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
return url;
}
|
javascript
|
function(source) {
var
api = (settings.api)
? 1
: 0,
autoplay = (settings.autoplay)
? 1
: 0,
hd = (settings.hd)
? 1
: 0,
showUI = (settings.showUI)
? 1
: 0,
// opposite used for some params
hideUI = !(settings.showUI)
? 1
: 0,
url = ''
;
if(source == 'vimeo') {
url = ''
+ 'api=' + api
+ '&title=' + showUI
+ '&byline=' + showUI
+ '&portrait=' + showUI
+ '&autoplay=' + autoplay
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
if(source == 'ustream') {
url = ''
+ 'autoplay=' + autoplay
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
else if(source == 'youtube') {
url = ''
+ 'enablejsapi=' + api
+ '&autoplay=' + autoplay
+ '&autohide=' + hideUI
+ '&hq=' + hd
+ '&modestbranding=1'
;
if(settings.color) {
url += '&color=' + settings.color;
}
}
return url;
}
|
[
"function",
"(",
"source",
")",
"{",
"var",
"api",
"=",
"(",
"settings",
".",
"api",
")",
"?",
"1",
":",
"0",
",",
"autoplay",
"=",
"(",
"settings",
".",
"autoplay",
")",
"?",
"1",
":",
"0",
",",
"hd",
"=",
"(",
"settings",
".",
"hd",
")",
"?",
"1",
":",
"0",
",",
"showUI",
"=",
"(",
"settings",
".",
"showUI",
")",
"?",
"1",
":",
"0",
",",
"// opposite used for some params",
"hideUI",
"=",
"!",
"(",
"settings",
".",
"showUI",
")",
"?",
"1",
":",
"0",
",",
"url",
"=",
"''",
";",
"if",
"(",
"source",
"==",
"'vimeo'",
")",
"{",
"url",
"=",
"''",
"+",
"'api='",
"+",
"api",
"+",
"'&title='",
"+",
"showUI",
"+",
"'&byline='",
"+",
"showUI",
"+",
"'&portrait='",
"+",
"showUI",
"+",
"'&autoplay='",
"+",
"autoplay",
";",
"if",
"(",
"settings",
".",
"color",
")",
"{",
"url",
"+=",
"'&color='",
"+",
"settings",
".",
"color",
";",
"}",
"}",
"if",
"(",
"source",
"==",
"'ustream'",
")",
"{",
"url",
"=",
"''",
"+",
"'autoplay='",
"+",
"autoplay",
";",
"if",
"(",
"settings",
".",
"color",
")",
"{",
"url",
"+=",
"'&color='",
"+",
"settings",
".",
"color",
";",
"}",
"}",
"else",
"if",
"(",
"source",
"==",
"'youtube'",
")",
"{",
"url",
"=",
"''",
"+",
"'enablejsapi='",
"+",
"api",
"+",
"'&autoplay='",
"+",
"autoplay",
"+",
"'&autohide='",
"+",
"hideUI",
"+",
"'&hq='",
"+",
"hd",
"+",
"'&modestbranding=1'",
";",
"if",
"(",
"settings",
".",
"color",
")",
"{",
"url",
"+=",
"'&color='",
"+",
"settings",
".",
"color",
";",
"}",
"}",
"return",
"url",
";",
"}"
] |
generate url parameters
|
[
"generate",
"url",
"parameters"
] |
838bf922655bdc7e501b3eb59c8e162a20d43f41
|
https://github.com/BinaryMuse/planetary.js/blob/838bf922655bdc7e501b3eb59c8e162a20d43f41/site/public/semantic/javascript/semantic.js#L11386-L11439
|
|
17,188
|
brozeph/node-craigslist
|
src/index.js
|
_getPostings
|
function _getPostings (options, markup) {
let
$ = cheerio.load(markup),
// hostname = options.hostname,
posting = {},
postings = [],
secure = options.secure;
$('div.content')
.find('.result-row')
.each((i, element) => {
let
// introducing fix for #11 - Craigslist markup changed
details = $(element)
.find('.result-title')
.attr('href')
.split(/\//g)
.filter((term) => term.length)
.map((term) => term.split(RE_HTML)[0]),
// fix for #6 and #24
detailsUrl = url.parse($(element)
.find('.result-title')
.attr('href'));
// ensure hostname and protocol are properly set
detailsUrl.hostname = detailsUrl.hostname || options.hostname;
detailsUrl.protocol = secure ? PROTOCOL_SECURE : PROTOCOL_INSECURE;
posting = {
category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
coordinates : {
lat : $(element).attr('data-latitude'),
lon : $(element).attr('data-longitude')
},
date : ($(element)
.find('time')
.attr('datetime') || '')
.trim(),
hasPic : RE_TAGS_MAP
.test($(element)
.find('.result-tags')
.text() || ''),
location : ($(element)
.find('.result-hood')
.text() || '')
.trim(),
pid : ($(element)
.attr('data-pid') || '')
.trim(),
price : ($(element)
.find('.result-meta .result-price')
.text() || '')
.replace(/^\&\#x0024\;/g, '')
.trim(), // sanitize
title : ($(element)
.find('.result-title')
.text() || '')
.trim(),
url : detailsUrl.format()
};
// make sure lat / lon is valid
if (typeof posting.coordinates.lat === 'undefined' ||
typeof posting.coordinates.lon === 'undefined') {
delete posting.coordinates;
}
postings.push(posting);
});
return postings;
}
|
javascript
|
function _getPostings (options, markup) {
let
$ = cheerio.load(markup),
// hostname = options.hostname,
posting = {},
postings = [],
secure = options.secure;
$('div.content')
.find('.result-row')
.each((i, element) => {
let
// introducing fix for #11 - Craigslist markup changed
details = $(element)
.find('.result-title')
.attr('href')
.split(/\//g)
.filter((term) => term.length)
.map((term) => term.split(RE_HTML)[0]),
// fix for #6 and #24
detailsUrl = url.parse($(element)
.find('.result-title')
.attr('href'));
// ensure hostname and protocol are properly set
detailsUrl.hostname = detailsUrl.hostname || options.hostname;
detailsUrl.protocol = secure ? PROTOCOL_SECURE : PROTOCOL_INSECURE;
posting = {
category : details[DEFAULT_CATEGORY_DETAILS_INDEX],
coordinates : {
lat : $(element).attr('data-latitude'),
lon : $(element).attr('data-longitude')
},
date : ($(element)
.find('time')
.attr('datetime') || '')
.trim(),
hasPic : RE_TAGS_MAP
.test($(element)
.find('.result-tags')
.text() || ''),
location : ($(element)
.find('.result-hood')
.text() || '')
.trim(),
pid : ($(element)
.attr('data-pid') || '')
.trim(),
price : ($(element)
.find('.result-meta .result-price')
.text() || '')
.replace(/^\&\#x0024\;/g, '')
.trim(), // sanitize
title : ($(element)
.find('.result-title')
.text() || '')
.trim(),
url : detailsUrl.format()
};
// make sure lat / lon is valid
if (typeof posting.coordinates.lat === 'undefined' ||
typeof posting.coordinates.lon === 'undefined') {
delete posting.coordinates;
}
postings.push(posting);
});
return postings;
}
|
[
"function",
"_getPostings",
"(",
"options",
",",
"markup",
")",
"{",
"let",
"$",
"=",
"cheerio",
".",
"load",
"(",
"markup",
")",
",",
"// hostname = options.hostname,",
"posting",
"=",
"{",
"}",
",",
"postings",
"=",
"[",
"]",
",",
"secure",
"=",
"options",
".",
"secure",
";",
"$",
"(",
"'div.content'",
")",
".",
"find",
"(",
"'.result-row'",
")",
".",
"each",
"(",
"(",
"i",
",",
"element",
")",
"=>",
"{",
"let",
"// introducing fix for #11 - Craigslist markup changed",
"details",
"=",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'.result-title'",
")",
".",
"attr",
"(",
"'href'",
")",
".",
"split",
"(",
"/",
"\\/",
"/",
"g",
")",
".",
"filter",
"(",
"(",
"term",
")",
"=>",
"term",
".",
"length",
")",
".",
"map",
"(",
"(",
"term",
")",
"=>",
"term",
".",
"split",
"(",
"RE_HTML",
")",
"[",
"0",
"]",
")",
",",
"// fix for #6 and #24",
"detailsUrl",
"=",
"url",
".",
"parse",
"(",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'.result-title'",
")",
".",
"attr",
"(",
"'href'",
")",
")",
";",
"// ensure hostname and protocol are properly set",
"detailsUrl",
".",
"hostname",
"=",
"detailsUrl",
".",
"hostname",
"||",
"options",
".",
"hostname",
";",
"detailsUrl",
".",
"protocol",
"=",
"secure",
"?",
"PROTOCOL_SECURE",
":",
"PROTOCOL_INSECURE",
";",
"posting",
"=",
"{",
"category",
":",
"details",
"[",
"DEFAULT_CATEGORY_DETAILS_INDEX",
"]",
",",
"coordinates",
":",
"{",
"lat",
":",
"$",
"(",
"element",
")",
".",
"attr",
"(",
"'data-latitude'",
")",
",",
"lon",
":",
"$",
"(",
"element",
")",
".",
"attr",
"(",
"'data-longitude'",
")",
"}",
",",
"date",
":",
"(",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'time'",
")",
".",
"attr",
"(",
"'datetime'",
")",
"||",
"''",
")",
".",
"trim",
"(",
")",
",",
"hasPic",
":",
"RE_TAGS_MAP",
".",
"test",
"(",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'.result-tags'",
")",
".",
"text",
"(",
")",
"||",
"''",
")",
",",
"location",
":",
"(",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'.result-hood'",
")",
".",
"text",
"(",
")",
"||",
"''",
")",
".",
"trim",
"(",
")",
",",
"pid",
":",
"(",
"$",
"(",
"element",
")",
".",
"attr",
"(",
"'data-pid'",
")",
"||",
"''",
")",
".",
"trim",
"(",
")",
",",
"price",
":",
"(",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'.result-meta .result-price'",
")",
".",
"text",
"(",
")",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"^\\&\\#x0024\\;",
"/",
"g",
",",
"''",
")",
".",
"trim",
"(",
")",
",",
"// sanitize",
"title",
":",
"(",
"$",
"(",
"element",
")",
".",
"find",
"(",
"'.result-title'",
")",
".",
"text",
"(",
")",
"||",
"''",
")",
".",
"trim",
"(",
")",
",",
"url",
":",
"detailsUrl",
".",
"format",
"(",
")",
"}",
";",
"// make sure lat / lon is valid",
"if",
"(",
"typeof",
"posting",
".",
"coordinates",
".",
"lat",
"===",
"'undefined'",
"||",
"typeof",
"posting",
".",
"coordinates",
".",
"lon",
"===",
"'undefined'",
")",
"{",
"delete",
"posting",
".",
"coordinates",
";",
"}",
"postings",
".",
"push",
"(",
"posting",
")",
";",
"}",
")",
";",
"return",
"postings",
";",
"}"
] |
Accepts string of HTML and parses that string to find all pertinent postings.
@param {object} options - Request options used for the request to craigslist
@param {string} markup - Markup from the request to Craigslist
@returns {Array} postings - The processed and normalized array of postings
|
[
"Accepts",
"string",
"of",
"HTML",
"and",
"parses",
"that",
"string",
"to",
"find",
"all",
"pertinent",
"postings",
"."
] |
73730d95c94f06feaefcc6a8b33443bf1ff46795
|
https://github.com/brozeph/node-craigslist/blob/73730d95c94f06feaefcc6a8b33443bf1ff46795/src/index.js#L134-L205
|
17,189
|
MikeMcl/decimal.js-light
|
decimal.js
|
multiplyInteger
|
function multiplyInteger(x, k) {
var temp,
carry = 0,
i = x.length;
for (x = x.slice(); i--;) {
temp = x[i] * k + carry;
x[i] = temp % BASE | 0;
carry = temp / BASE | 0;
}
if (carry) x.unshift(carry);
return x;
}
|
javascript
|
function multiplyInteger(x, k) {
var temp,
carry = 0,
i = x.length;
for (x = x.slice(); i--;) {
temp = x[i] * k + carry;
x[i] = temp % BASE | 0;
carry = temp / BASE | 0;
}
if (carry) x.unshift(carry);
return x;
}
|
[
"function",
"multiplyInteger",
"(",
"x",
",",
"k",
")",
"{",
"var",
"temp",
",",
"carry",
"=",
"0",
",",
"i",
"=",
"x",
".",
"length",
";",
"for",
"(",
"x",
"=",
"x",
".",
"slice",
"(",
")",
";",
"i",
"--",
";",
")",
"{",
"temp",
"=",
"x",
"[",
"i",
"]",
"*",
"k",
"+",
"carry",
";",
"x",
"[",
"i",
"]",
"=",
"temp",
"%",
"BASE",
"|",
"0",
";",
"carry",
"=",
"temp",
"/",
"BASE",
"|",
"0",
";",
"}",
"if",
"(",
"carry",
")",
"x",
".",
"unshift",
"(",
"carry",
")",
";",
"return",
"x",
";",
"}"
] |
Assumes non-zero x and k, and hence non-zero result.
|
[
"Assumes",
"non",
"-",
"zero",
"x",
"and",
"k",
"and",
"hence",
"non",
"-",
"zero",
"result",
"."
] |
ff1e0f93ef0967e18c198f09aa2b329791e7dc0e
|
https://github.com/MikeMcl/decimal.js-light/blob/ff1e0f93ef0967e18c198f09aa2b329791e7dc0e/decimal.js#L1042-L1056
|
17,190
|
MikeMcl/decimal.js-light
|
decimal.js
|
getBase10Exponent
|
function getBase10Exponent(x) {
var e = x.e * LOG_BASE,
w = x.d[0];
// Add the number of digits of the first word of the digits array.
for (; w >= 10; w /= 10) e++;
return e;
}
|
javascript
|
function getBase10Exponent(x) {
var e = x.e * LOG_BASE,
w = x.d[0];
// Add the number of digits of the first word of the digits array.
for (; w >= 10; w /= 10) e++;
return e;
}
|
[
"function",
"getBase10Exponent",
"(",
"x",
")",
"{",
"var",
"e",
"=",
"x",
".",
"e",
"*",
"LOG_BASE",
",",
"w",
"=",
"x",
".",
"d",
"[",
"0",
"]",
";",
"// Add the number of digits of the first word of the digits array.",
"for",
"(",
";",
"w",
">=",
"10",
";",
"w",
"/=",
"10",
")",
"e",
"++",
";",
"return",
"e",
";",
"}"
] |
Calculate the base 10 exponent from the base 1e7 exponent.
|
[
"Calculate",
"the",
"base",
"10",
"exponent",
"from",
"the",
"base",
"1e7",
"exponent",
"."
] |
ff1e0f93ef0967e18c198f09aa2b329791e7dc0e
|
https://github.com/MikeMcl/decimal.js-light/blob/ff1e0f93ef0967e18c198f09aa2b329791e7dc0e/decimal.js#L1337-L1344
|
17,191
|
MikeMcl/decimal.js-light
|
decimal.js
|
truncate
|
function truncate(arr, len) {
if (arr.length > len) {
arr.length = len;
return true;
}
}
|
javascript
|
function truncate(arr, len) {
if (arr.length > len) {
arr.length = len;
return true;
}
}
|
[
"function",
"truncate",
"(",
"arr",
",",
"len",
")",
"{",
"if",
"(",
"arr",
".",
"length",
">",
"len",
")",
"{",
"arr",
".",
"length",
"=",
"len",
";",
"return",
"true",
";",
"}",
"}"
] |
Does not strip trailing zeros.
|
[
"Does",
"not",
"strip",
"trailing",
"zeros",
"."
] |
ff1e0f93ef0967e18c198f09aa2b329791e7dc0e
|
https://github.com/MikeMcl/decimal.js-light/blob/ff1e0f93ef0967e18c198f09aa2b329791e7dc0e/decimal.js#L1822-L1827
|
17,192
|
vzhou842/faster.js
|
src/optimizations/array-reduce.js
|
writeReduceForLoop
|
function writeReduceForLoop(t, path, reducePath, reduceRight) {
const reduceCall = reducePath.node;
const array = defineIdIfNeeded(t, reducePath.get('callee.object'), path);
const func = extractDynamicFuncIfNeeded(t, reducePath, path);
const acc = path.scope.generateUidIdentifier('acc');
const i = path.scope.generateUidIdentifier('i');
// Initialize the accumulator.
// let acc = arguments[1] || (reduceRight ? arr[arr.length - 1] : arr[0]);
const initVal = reduceCall.arguments[1] || arrayMember(t, array, 0, reduceRight);
path.insertBefore(t.VariableDeclaration('let', [
t.VariableDeclarator(acc, initVal),
]));
// Write the for loop.
const newReduceCall = t.callExpression(func, [
acc,
t.memberExpression(array, i, true),
i,
array,
]);
const forBody = t.blockStatement([
t.expressionStatement(
t.assignmentExpression('=', acc, newReduceCall)
),
]);
let initI;
if (!reduceCall.arguments[1]) {
initI = reduceRight ? arrayIndex(t, array, 1, true) : t.numericLiteral(1);
}
path.insertBefore(basicArrayForLoop(t, i, array, forBody, reduceRight, initI));
return acc;
}
|
javascript
|
function writeReduceForLoop(t, path, reducePath, reduceRight) {
const reduceCall = reducePath.node;
const array = defineIdIfNeeded(t, reducePath.get('callee.object'), path);
const func = extractDynamicFuncIfNeeded(t, reducePath, path);
const acc = path.scope.generateUidIdentifier('acc');
const i = path.scope.generateUidIdentifier('i');
// Initialize the accumulator.
// let acc = arguments[1] || (reduceRight ? arr[arr.length - 1] : arr[0]);
const initVal = reduceCall.arguments[1] || arrayMember(t, array, 0, reduceRight);
path.insertBefore(t.VariableDeclaration('let', [
t.VariableDeclarator(acc, initVal),
]));
// Write the for loop.
const newReduceCall = t.callExpression(func, [
acc,
t.memberExpression(array, i, true),
i,
array,
]);
const forBody = t.blockStatement([
t.expressionStatement(
t.assignmentExpression('=', acc, newReduceCall)
),
]);
let initI;
if (!reduceCall.arguments[1]) {
initI = reduceRight ? arrayIndex(t, array, 1, true) : t.numericLiteral(1);
}
path.insertBefore(basicArrayForLoop(t, i, array, forBody, reduceRight, initI));
return acc;
}
|
[
"function",
"writeReduceForLoop",
"(",
"t",
",",
"path",
",",
"reducePath",
",",
"reduceRight",
")",
"{",
"const",
"reduceCall",
"=",
"reducePath",
".",
"node",
";",
"const",
"array",
"=",
"defineIdIfNeeded",
"(",
"t",
",",
"reducePath",
".",
"get",
"(",
"'callee.object'",
")",
",",
"path",
")",
";",
"const",
"func",
"=",
"extractDynamicFuncIfNeeded",
"(",
"t",
",",
"reducePath",
",",
"path",
")",
";",
"const",
"acc",
"=",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"'acc'",
")",
";",
"const",
"i",
"=",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"'i'",
")",
";",
"// Initialize the accumulator.",
"// let acc = arguments[1] || (reduceRight ? arr[arr.length - 1] : arr[0]);",
"const",
"initVal",
"=",
"reduceCall",
".",
"arguments",
"[",
"1",
"]",
"||",
"arrayMember",
"(",
"t",
",",
"array",
",",
"0",
",",
"reduceRight",
")",
";",
"path",
".",
"insertBefore",
"(",
"t",
".",
"VariableDeclaration",
"(",
"'let'",
",",
"[",
"t",
".",
"VariableDeclarator",
"(",
"acc",
",",
"initVal",
")",
",",
"]",
")",
")",
";",
"// Write the for loop.",
"const",
"newReduceCall",
"=",
"t",
".",
"callExpression",
"(",
"func",
",",
"[",
"acc",
",",
"t",
".",
"memberExpression",
"(",
"array",
",",
"i",
",",
"true",
")",
",",
"i",
",",
"array",
",",
"]",
")",
";",
"const",
"forBody",
"=",
"t",
".",
"blockStatement",
"(",
"[",
"t",
".",
"expressionStatement",
"(",
"t",
".",
"assignmentExpression",
"(",
"'='",
",",
"acc",
",",
"newReduceCall",
")",
")",
",",
"]",
")",
";",
"let",
"initI",
";",
"if",
"(",
"!",
"reduceCall",
".",
"arguments",
"[",
"1",
"]",
")",
"{",
"initI",
"=",
"reduceRight",
"?",
"arrayIndex",
"(",
"t",
",",
"array",
",",
"1",
",",
"true",
")",
":",
"t",
".",
"numericLiteral",
"(",
"1",
")",
";",
"}",
"path",
".",
"insertBefore",
"(",
"basicArrayForLoop",
"(",
"t",
",",
"i",
",",
"array",
",",
"forBody",
",",
"reduceRight",
",",
"initI",
")",
")",
";",
"return",
"acc",
";",
"}"
] |
Returns the identifier the result is stored in.
|
[
"Returns",
"the",
"identifier",
"the",
"result",
"is",
"stored",
"in",
"."
] |
0031e22a65f9069c44476ffd19e7f7553ea54f41
|
https://github.com/vzhou842/faster.js/blob/0031e22a65f9069c44476ffd19e7f7553ea54f41/src/optimizations/array-reduce.js#L52-L85
|
17,193
|
vzhou842/faster.js
|
bench/utils.js
|
randomArray
|
function randomArray(size) {
const cache = arrayCaches[size];
return cache[Math.floor(Math.random() * cache.length)];
}
|
javascript
|
function randomArray(size) {
const cache = arrayCaches[size];
return cache[Math.floor(Math.random() * cache.length)];
}
|
[
"function",
"randomArray",
"(",
"size",
")",
"{",
"const",
"cache",
"=",
"arrayCaches",
"[",
"size",
"]",
";",
"return",
"cache",
"[",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"cache",
".",
"length",
")",
"]",
";",
"}"
] |
Returns an array of random length with random contents.
@param {string} size - Either 'small', 'medium', or 'large'.
|
[
"Returns",
"an",
"array",
"of",
"random",
"length",
"with",
"random",
"contents",
"."
] |
0031e22a65f9069c44476ffd19e7f7553ea54f41
|
https://github.com/vzhou842/faster.js/blob/0031e22a65f9069c44476ffd19e7f7553ea54f41/bench/utils.js#L15-L18
|
17,194
|
IonicaBizau/json2md
|
lib/index.js
|
json2md
|
function json2md(data, prefix, _type) {
prefix = prefix || ""
if (typeof data === "string" || typeof data === "number") {
return indento(data, 1, prefix)
}
let content = []
// Handle arrays
if (Array.isArray(data)) {
for (let i = 0; i < data.length; ++i) {
content.push(indento(json2md(data[i], "", _type), 1, prefix))
}
return content.join("\n")
} else {
let type = Object.keys(data)[0]
, func = converters[_type || type]
if (typeof func === "function") {
return indento(func(_type ? data : data[type], json2md), 1, prefix) + "\n"
}
throw new Error("There is no such converter: " + type)
}
}
|
javascript
|
function json2md(data, prefix, _type) {
prefix = prefix || ""
if (typeof data === "string" || typeof data === "number") {
return indento(data, 1, prefix)
}
let content = []
// Handle arrays
if (Array.isArray(data)) {
for (let i = 0; i < data.length; ++i) {
content.push(indento(json2md(data[i], "", _type), 1, prefix))
}
return content.join("\n")
} else {
let type = Object.keys(data)[0]
, func = converters[_type || type]
if (typeof func === "function") {
return indento(func(_type ? data : data[type], json2md), 1, prefix) + "\n"
}
throw new Error("There is no such converter: " + type)
}
}
|
[
"function",
"json2md",
"(",
"data",
",",
"prefix",
",",
"_type",
")",
"{",
"prefix",
"=",
"prefix",
"||",
"\"\"",
"if",
"(",
"typeof",
"data",
"===",
"\"string\"",
"||",
"typeof",
"data",
"===",
"\"number\"",
")",
"{",
"return",
"indento",
"(",
"data",
",",
"1",
",",
"prefix",
")",
"}",
"let",
"content",
"=",
"[",
"]",
"// Handle arrays",
"if",
"(",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"++",
"i",
")",
"{",
"content",
".",
"push",
"(",
"indento",
"(",
"json2md",
"(",
"data",
"[",
"i",
"]",
",",
"\"\"",
",",
"_type",
")",
",",
"1",
",",
"prefix",
")",
")",
"}",
"return",
"content",
".",
"join",
"(",
"\"\\n\"",
")",
"}",
"else",
"{",
"let",
"type",
"=",
"Object",
".",
"keys",
"(",
"data",
")",
"[",
"0",
"]",
",",
"func",
"=",
"converters",
"[",
"_type",
"||",
"type",
"]",
"if",
"(",
"typeof",
"func",
"===",
"\"function\"",
")",
"{",
"return",
"indento",
"(",
"func",
"(",
"_type",
"?",
"data",
":",
"data",
"[",
"type",
"]",
",",
"json2md",
")",
",",
"1",
",",
"prefix",
")",
"+",
"\"\\n\"",
"}",
"throw",
"new",
"Error",
"(",
"\"There is no such converter: \"",
"+",
"type",
")",
"}",
"}"
] |
json2md
Converts a JSON input to markdown.
**Supported elements**
| Type | Element | Data | Example |
|--------------|--------------------|--------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
| `h1` | Heading 1 | The heading text as string. | `{ h1: "heading 1" }` |
| `h2` | Heading 2 | The heading text as string. | `{ h2: "heading 2" }` |
| `h3` | Heading 3 | The heading text as string. | `{ h3: "heading 3" }` |
| `h4` | Heading 4 | The heading text as string. | `{ h4: "heading 4" }` |
| `h5` | Heading 5 | The heading text as string. | `{ h5: "heading 5" }` |
| `h6` | Heading 6 | The heading text as string. | `{ h6: "heading 6" }` |
| `p` | Paragraphs | The paragraph text as string or array (multiple paragraphs). | `{ p: "Hello World"}` or multiple paragraphs: `{ p: ["Hello", "World"] }` |
| `blockquote` | Blockquote | The blockquote as string or array (multiple blockquotes) | `{ blockquote: "Hello World"}` or multiple blockquotes: `{ blockquote: ["Hello", "World"] }` |
| `img` | Image | An object or an array of objects containing the `title` and `source` fields. | `{ img: { title: "My image title", source: "http://example.com/image.png" } }` |
| `ul` | Unordered list | An array of strings representing the items. | `{ ul: ["item 1", "item 2"] }` |
| `ol` | Ordered list | An array of strings representing the items. | `{ ol: ["item 1", "item 2"] }` |
| `code` | Code block element | An object containing the `language` (`String`) and `content` (`Array` or `String`) fields. | `{ code: { "language": "html", "content": "<script src='dummy.js'></script>" } }` |
| `table` | Table | An object containing the `headers` (`Array` of `String`s) and `rows` (`Array` of `Array`s or `Object`s). | `{ table: { headers: ["a", "b"], rows: [{ a: "col1", b: "col2" }] } }` or `{ table: { headers: ["a", "b"], rows: [["col1", "col2"]] } }` |
| `link` | Link | An object containing the `title` and the `url` fields. |
You can extend the `json2md.converters` object to support your custom types.
```js
json2md.converters.sayHello = function (input, json2md) {
return "Hello " + input + "!"
}
```
Then you can use it:
```js
json2md({ sayHello: "World" })
// => "Hello World!"
```
@name json2md
@function
@param {Array|Object|String} data The input JSON data.
@param {String} prefix A snippet to add before each line.
@return {String} The generated markdown result.
|
[
"json2md",
"Converts",
"a",
"JSON",
"input",
"to",
"markdown",
"."
] |
25076ad5ed0af419c0e0fe806e005842275605fc
|
https://github.com/IonicaBizau/json2md/blob/25076ad5ed0af419c0e0fe806e005842275605fc/lib/index.js#L51-L74
|
17,195
|
flimshaw/Valiant360
|
src/valiant.jquery.js
|
function() {
var muteControl = this.options.muted ? 'fa-volume-off' : 'fa-volume-up';
var playPauseControl = this.options.autoplay ? 'fa-pause' : 'fa-play';
var controlsHTML = ' \
<div class="controlsWrapper">\
<div class="valiant-progress-bar">\
<div style="width: 0;"></div><div style="width: 100%;"></div>\
</div>\
<div class="controls"> \
<a href="#" class="playButton button fa '+ playPauseControl +'"></a> \
<div class="audioControl">\
<a href="#" class="muteButton button fa '+ muteControl +'"></a> \
<div class="volumeControl">\
<div class="volumeBar">\
<div class="volumeProgress"></div>\
<div class="volumeCursor"></div>\
</div>\
</div>\
</div>\
<span class="timeLabel"></span> \
<a href="#" class="fullscreenButton button fa fa-expand"></a> \
</div> \
</div>\
';
$(this.element).append(controlsHTML, true);
$(this.element).append('<div class="timeTooltip">00:00</div>', true);
// hide controls if option is set
if(this.options.hideControls) {
$(this.element).find('.controls').hide();
}
// wire up controller events to dom elements
this.attachControlEvents();
}
|
javascript
|
function() {
var muteControl = this.options.muted ? 'fa-volume-off' : 'fa-volume-up';
var playPauseControl = this.options.autoplay ? 'fa-pause' : 'fa-play';
var controlsHTML = ' \
<div class="controlsWrapper">\
<div class="valiant-progress-bar">\
<div style="width: 0;"></div><div style="width: 100%;"></div>\
</div>\
<div class="controls"> \
<a href="#" class="playButton button fa '+ playPauseControl +'"></a> \
<div class="audioControl">\
<a href="#" class="muteButton button fa '+ muteControl +'"></a> \
<div class="volumeControl">\
<div class="volumeBar">\
<div class="volumeProgress"></div>\
<div class="volumeCursor"></div>\
</div>\
</div>\
</div>\
<span class="timeLabel"></span> \
<a href="#" class="fullscreenButton button fa fa-expand"></a> \
</div> \
</div>\
';
$(this.element).append(controlsHTML, true);
$(this.element).append('<div class="timeTooltip">00:00</div>', true);
// hide controls if option is set
if(this.options.hideControls) {
$(this.element).find('.controls').hide();
}
// wire up controller events to dom elements
this.attachControlEvents();
}
|
[
"function",
"(",
")",
"{",
"var",
"muteControl",
"=",
"this",
".",
"options",
".",
"muted",
"?",
"'fa-volume-off'",
":",
"'fa-volume-up'",
";",
"var",
"playPauseControl",
"=",
"this",
".",
"options",
".",
"autoplay",
"?",
"'fa-pause'",
":",
"'fa-play'",
";",
"var",
"controlsHTML",
"=",
"' \\\n <div class=\"controlsWrapper\">\\\n <div class=\"valiant-progress-bar\">\\\n <div style=\"width: 0;\"></div><div style=\"width: 100%;\"></div>\\\n </div>\\\n <div class=\"controls\"> \\\n <a href=\"#\" class=\"playButton button fa '",
"+",
"playPauseControl",
"+",
"'\"></a> \\\n\t\t\t\t\t<div class=\"audioControl\">\\\n\t\t\t\t\t\t<a href=\"#\" class=\"muteButton button fa '",
"+",
"muteControl",
"+",
"'\"></a> \\\n\t\t\t\t\t\t<div class=\"volumeControl\">\\\n\t\t\t\t\t\t\t<div class=\"volumeBar\">\\\n\t\t\t\t\t\t\t\t<div class=\"volumeProgress\"></div>\\\n\t\t\t\t\t\t\t\t<div class=\"volumeCursor\"></div>\\\n\t\t\t\t\t\t\t</div>\\\n\t\t\t\t\t\t</div>\\\n\t\t\t\t\t</div>\\\n\t\t\t\t\t<span class=\"timeLabel\"></span> \\\n <a href=\"#\" class=\"fullscreenButton button fa fa-expand\"></a> \\\n </div> \\\n </div>\\\n '",
";",
"$",
"(",
"this",
".",
"element",
")",
".",
"append",
"(",
"controlsHTML",
",",
"true",
")",
";",
"$",
"(",
"this",
".",
"element",
")",
".",
"append",
"(",
"'<div class=\"timeTooltip\">00:00</div>'",
",",
"true",
")",
";",
"// hide controls if option is set",
"if",
"(",
"this",
".",
"options",
".",
"hideControls",
")",
"{",
"$",
"(",
"this",
".",
"element",
")",
".",
"find",
"(",
"'.controls'",
")",
".",
"hide",
"(",
")",
";",
"}",
"// wire up controller events to dom elements",
"this",
".",
"attachControlEvents",
"(",
")",
";",
"}"
] |
creates div and buttons for onscreen video controls
|
[
"creates",
"div",
"and",
"buttons",
"for",
"onscreen",
"video",
"controls"
] |
79f1b528886ab580e1624ef3b5857dbd541d62c4
|
https://github.com/flimshaw/Valiant360/blob/79f1b528886ab580e1624ef3b5857dbd541d62c4/src/valiant.jquery.js#L298-L335
|
|
17,196
|
flimshaw/Valiant360
|
src/lib/Three.js
|
cacheUniformLocations
|
function cacheUniformLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.uniforms[ id ] = _gl.getUniformLocation( program, id );
}
}
|
javascript
|
function cacheUniformLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.uniforms[ id ] = _gl.getUniformLocation( program, id );
}
}
|
[
"function",
"cacheUniformLocations",
"(",
"program",
",",
"identifiers",
")",
"{",
"var",
"i",
",",
"l",
",",
"id",
";",
"for",
"(",
"i",
"=",
"0",
",",
"l",
"=",
"identifiers",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"id",
"=",
"identifiers",
"[",
"i",
"]",
";",
"program",
".",
"uniforms",
"[",
"id",
"]",
"=",
"_gl",
".",
"getUniformLocation",
"(",
"program",
",",
"id",
")",
";",
"}",
"}"
] |
Shader parameters cache
|
[
"Shader",
"parameters",
"cache"
] |
79f1b528886ab580e1624ef3b5857dbd541d62c4
|
https://github.com/flimshaw/Valiant360/blob/79f1b528886ab580e1624ef3b5857dbd541d62c4/src/lib/Three.js#L25483-L25494
|
17,197
|
ucbl/HyLAR-Reasoner
|
hylar/core/Logics/Rule.js
|
function() {
var factConj = '';
for(var key in this.causes) {
factConj += ' ^ ' + this.causes[key].toString().substring(1).replace(/,/g, '');
}
for(var key in this.operatorCauses) {
factConj += ' ^ ' + this.operatorCauses[key].toString().substring(1).replace(/,/g, '');
}
return factConj.substr(3) + ' -> ' + this.consequences.toString().substring(1).replace(/,/g, '');
}
|
javascript
|
function() {
var factConj = '';
for(var key in this.causes) {
factConj += ' ^ ' + this.causes[key].toString().substring(1).replace(/,/g, '');
}
for(var key in this.operatorCauses) {
factConj += ' ^ ' + this.operatorCauses[key].toString().substring(1).replace(/,/g, '');
}
return factConj.substr(3) + ' -> ' + this.consequences.toString().substring(1).replace(/,/g, '');
}
|
[
"function",
"(",
")",
"{",
"var",
"factConj",
"=",
"''",
";",
"for",
"(",
"var",
"key",
"in",
"this",
".",
"causes",
")",
"{",
"factConj",
"+=",
"' ^ '",
"+",
"this",
".",
"causes",
"[",
"key",
"]",
".",
"toString",
"(",
")",
".",
"substring",
"(",
"1",
")",
".",
"replace",
"(",
"/",
",",
"/",
"g",
",",
"''",
")",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"this",
".",
"operatorCauses",
")",
"{",
"factConj",
"+=",
"' ^ '",
"+",
"this",
".",
"operatorCauses",
"[",
"key",
"]",
".",
"toString",
"(",
")",
".",
"substring",
"(",
"1",
")",
".",
"replace",
"(",
"/",
",",
"/",
"g",
",",
"''",
")",
";",
"}",
"return",
"factConj",
".",
"substr",
"(",
"3",
")",
"+",
"' -> '",
"+",
"this",
".",
"consequences",
".",
"toString",
"(",
")",
".",
"substring",
"(",
"1",
")",
".",
"replace",
"(",
"/",
",",
"/",
"g",
",",
"''",
")",
";",
"}"
] |
Convenient method to stringify a rule.
@returns {string}
|
[
"Convenient",
"method",
"to",
"stringify",
"a",
"rule",
"."
] |
a66cd396de89cc2e1921b18f23ec9a8906313df2
|
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/Logics/Rule.js#L45-L54
|
|
17,198
|
ucbl/HyLAR-Reasoner
|
hylar/core/ReasoningEngine.js
|
function(FeAdd, FeDel, F, R) {
var FiAdd = [], FiAddNew = [], additions, deletions,
Fe = Logics.getOnlyExplicitFacts(F), FiAddNew = [];
// Deletion
if(FeDel && FeDel.length) {
Fe = Logics.minus(Fe, FeDel);
}
// Insertion
if(FeAdd && FeAdd.length) {
Fe = Utils.uniques(Fe, FeAdd);
}
// Recalculation
do {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
FiAddNew = Solver.evaluateRuleSet(R, Utils.uniques(Fe, FiAdd));
} while (!Logics.containsFacts(FiAdd, FiAddNew));
additions = Utils.uniques(FeAdd, FiAdd);
deletions = Logics.minus(F, Utils.uniques(Fe, FiAdd));
F = Utils.uniques(Fe, FiAdd);
return {
additions: additions,
deletions: deletions,
updatedF: F
};
}
|
javascript
|
function(FeAdd, FeDel, F, R) {
var FiAdd = [], FiAddNew = [], additions, deletions,
Fe = Logics.getOnlyExplicitFacts(F), FiAddNew = [];
// Deletion
if(FeDel && FeDel.length) {
Fe = Logics.minus(Fe, FeDel);
}
// Insertion
if(FeAdd && FeAdd.length) {
Fe = Utils.uniques(Fe, FeAdd);
}
// Recalculation
do {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
FiAddNew = Solver.evaluateRuleSet(R, Utils.uniques(Fe, FiAdd));
} while (!Logics.containsFacts(FiAdd, FiAddNew));
additions = Utils.uniques(FeAdd, FiAdd);
deletions = Logics.minus(F, Utils.uniques(Fe, FiAdd));
F = Utils.uniques(Fe, FiAdd);
return {
additions: additions,
deletions: deletions,
updatedF: F
};
}
|
[
"function",
"(",
"FeAdd",
",",
"FeDel",
",",
"F",
",",
"R",
")",
"{",
"var",
"FiAdd",
"=",
"[",
"]",
",",
"FiAddNew",
"=",
"[",
"]",
",",
"additions",
",",
"deletions",
",",
"Fe",
"=",
"Logics",
".",
"getOnlyExplicitFacts",
"(",
"F",
")",
",",
"FiAddNew",
"=",
"[",
"]",
";",
"// Deletion",
"if",
"(",
"FeDel",
"&&",
"FeDel",
".",
"length",
")",
"{",
"Fe",
"=",
"Logics",
".",
"minus",
"(",
"Fe",
",",
"FeDel",
")",
";",
"}",
"// Insertion",
"if",
"(",
"FeAdd",
"&&",
"FeAdd",
".",
"length",
")",
"{",
"Fe",
"=",
"Utils",
".",
"uniques",
"(",
"Fe",
",",
"FeAdd",
")",
";",
"}",
"// Recalculation",
"do",
"{",
"FiAdd",
"=",
"Utils",
".",
"uniques",
"(",
"FiAdd",
",",
"FiAddNew",
")",
";",
"FiAddNew",
"=",
"Solver",
".",
"evaluateRuleSet",
"(",
"R",
",",
"Utils",
".",
"uniques",
"(",
"Fe",
",",
"FiAdd",
")",
")",
";",
"}",
"while",
"(",
"!",
"Logics",
".",
"containsFacts",
"(",
"FiAdd",
",",
"FiAddNew",
")",
")",
";",
"additions",
"=",
"Utils",
".",
"uniques",
"(",
"FeAdd",
",",
"FiAdd",
")",
";",
"deletions",
"=",
"Logics",
".",
"minus",
"(",
"F",
",",
"Utils",
".",
"uniques",
"(",
"Fe",
",",
"FiAdd",
")",
")",
";",
"F",
"=",
"Utils",
".",
"uniques",
"(",
"Fe",
",",
"FiAdd",
")",
";",
"return",
"{",
"additions",
":",
"additions",
",",
"deletions",
":",
"deletions",
",",
"updatedF",
":",
"F",
"}",
";",
"}"
] |
A naive reasoner that recalculates the entire knowledge base.
@deprecated
@param triplesIns
@param triplesDel
@param rules
@returns {{fi: *, fe: *}}
|
[
"A",
"naive",
"reasoner",
"that",
"recalculates",
"the",
"entire",
"knowledge",
"base",
"."
] |
a66cd396de89cc2e1921b18f23ec9a8906313df2
|
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/ReasoningEngine.js#L25-L55
|
|
17,199
|
ucbl/HyLAR-Reasoner
|
hylar/core/ReasoningEngine.js
|
function (FeAdd, FeDel, F, R) {
var Rdel = [], Rred = [], Rins = [],
FiDel = [], FiAdd = [],
FiDelNew = [], FiAddNew = [],
superSet = [],
additions, deletions,
Fe = Logics.getOnlyExplicitFacts(F),
Fi = Logics.getOnlyImplicitFacts(F),
deferred = q.defer(),
startAlgorithm = function() {
overDeletionEvaluationLoop();
},
overDeletionEvaluationLoop = function() {
FiDel = Utils.uniques(FiDel, FiDelNew);
Rdel = Logics.restrictRuleSet(R, Utils.uniques(FeDel, FiDel));
Solver.evaluateRuleSet(Rdel, Utils.uniques(Utils.uniques(Fi, Fe), FeDel))
.then(function(values) {
FiDelNew = values.cons;
if (Utils.uniques(FiDel, FiDelNew).length > FiDel.length) {
overDeletionEvaluationLoop();
} else {
Fe = Logics.minus(Fe, FeDel);
Fi = Logics.minus(Fi, FiDel);
rederivationEvaluationLoop();
}
});
},
rederivationEvaluationLoop = function() {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
Rred = Logics.restrictRuleSet(R, FiDel);
Solver.evaluateRuleSet(Rred, Utils.uniques(Fe, Fi))
.then(function(values) {
FiAddNew = values.cons;
if (Utils.uniques(FiAdd, FiAddNew).length > FiAdd.length) {
rederivationEvaluationLoop();
} else {
insertionEvaluationLoop();
}
});
},
insertionEvaluationLoop = function() {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
superSet = Utils.uniques(Utils.uniques(Utils.uniques(Fe, Fi), FeAdd), FiAdd);
Rins = Logics.restrictRuleSet(R, superSet);
Solver.evaluateRuleSet(Rins, superSet)
.then(function(values) {
FiAddNew = values.cons;
if (!Utils.containsSubset(FiAdd, FiAddNew)) {
insertionEvaluationLoop();
} else {
additions = Utils.uniques(FeAdd, FiAdd);
deletions = Utils.uniques(FeDel, FiDel);
deferred.resolve({
additions: additions,
deletions: deletions
});
}
}).fail(function(err) {
console.error(err);
});
};
startAlgorithm();
return deferred.promise;
}
|
javascript
|
function (FeAdd, FeDel, F, R) {
var Rdel = [], Rred = [], Rins = [],
FiDel = [], FiAdd = [],
FiDelNew = [], FiAddNew = [],
superSet = [],
additions, deletions,
Fe = Logics.getOnlyExplicitFacts(F),
Fi = Logics.getOnlyImplicitFacts(F),
deferred = q.defer(),
startAlgorithm = function() {
overDeletionEvaluationLoop();
},
overDeletionEvaluationLoop = function() {
FiDel = Utils.uniques(FiDel, FiDelNew);
Rdel = Logics.restrictRuleSet(R, Utils.uniques(FeDel, FiDel));
Solver.evaluateRuleSet(Rdel, Utils.uniques(Utils.uniques(Fi, Fe), FeDel))
.then(function(values) {
FiDelNew = values.cons;
if (Utils.uniques(FiDel, FiDelNew).length > FiDel.length) {
overDeletionEvaluationLoop();
} else {
Fe = Logics.minus(Fe, FeDel);
Fi = Logics.minus(Fi, FiDel);
rederivationEvaluationLoop();
}
});
},
rederivationEvaluationLoop = function() {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
Rred = Logics.restrictRuleSet(R, FiDel);
Solver.evaluateRuleSet(Rred, Utils.uniques(Fe, Fi))
.then(function(values) {
FiAddNew = values.cons;
if (Utils.uniques(FiAdd, FiAddNew).length > FiAdd.length) {
rederivationEvaluationLoop();
} else {
insertionEvaluationLoop();
}
});
},
insertionEvaluationLoop = function() {
FiAdd = Utils.uniques(FiAdd, FiAddNew);
superSet = Utils.uniques(Utils.uniques(Utils.uniques(Fe, Fi), FeAdd), FiAdd);
Rins = Logics.restrictRuleSet(R, superSet);
Solver.evaluateRuleSet(Rins, superSet)
.then(function(values) {
FiAddNew = values.cons;
if (!Utils.containsSubset(FiAdd, FiAddNew)) {
insertionEvaluationLoop();
} else {
additions = Utils.uniques(FeAdd, FiAdd);
deletions = Utils.uniques(FeDel, FiDel);
deferred.resolve({
additions: additions,
deletions: deletions
});
}
}).fail(function(err) {
console.error(err);
});
};
startAlgorithm();
return deferred.promise;
}
|
[
"function",
"(",
"FeAdd",
",",
"FeDel",
",",
"F",
",",
"R",
")",
"{",
"var",
"Rdel",
"=",
"[",
"]",
",",
"Rred",
"=",
"[",
"]",
",",
"Rins",
"=",
"[",
"]",
",",
"FiDel",
"=",
"[",
"]",
",",
"FiAdd",
"=",
"[",
"]",
",",
"FiDelNew",
"=",
"[",
"]",
",",
"FiAddNew",
"=",
"[",
"]",
",",
"superSet",
"=",
"[",
"]",
",",
"additions",
",",
"deletions",
",",
"Fe",
"=",
"Logics",
".",
"getOnlyExplicitFacts",
"(",
"F",
")",
",",
"Fi",
"=",
"Logics",
".",
"getOnlyImplicitFacts",
"(",
"F",
")",
",",
"deferred",
"=",
"q",
".",
"defer",
"(",
")",
",",
"startAlgorithm",
"=",
"function",
"(",
")",
"{",
"overDeletionEvaluationLoop",
"(",
")",
";",
"}",
",",
"overDeletionEvaluationLoop",
"=",
"function",
"(",
")",
"{",
"FiDel",
"=",
"Utils",
".",
"uniques",
"(",
"FiDel",
",",
"FiDelNew",
")",
";",
"Rdel",
"=",
"Logics",
".",
"restrictRuleSet",
"(",
"R",
",",
"Utils",
".",
"uniques",
"(",
"FeDel",
",",
"FiDel",
")",
")",
";",
"Solver",
".",
"evaluateRuleSet",
"(",
"Rdel",
",",
"Utils",
".",
"uniques",
"(",
"Utils",
".",
"uniques",
"(",
"Fi",
",",
"Fe",
")",
",",
"FeDel",
")",
")",
".",
"then",
"(",
"function",
"(",
"values",
")",
"{",
"FiDelNew",
"=",
"values",
".",
"cons",
";",
"if",
"(",
"Utils",
".",
"uniques",
"(",
"FiDel",
",",
"FiDelNew",
")",
".",
"length",
">",
"FiDel",
".",
"length",
")",
"{",
"overDeletionEvaluationLoop",
"(",
")",
";",
"}",
"else",
"{",
"Fe",
"=",
"Logics",
".",
"minus",
"(",
"Fe",
",",
"FeDel",
")",
";",
"Fi",
"=",
"Logics",
".",
"minus",
"(",
"Fi",
",",
"FiDel",
")",
";",
"rederivationEvaluationLoop",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"rederivationEvaluationLoop",
"=",
"function",
"(",
")",
"{",
"FiAdd",
"=",
"Utils",
".",
"uniques",
"(",
"FiAdd",
",",
"FiAddNew",
")",
";",
"Rred",
"=",
"Logics",
".",
"restrictRuleSet",
"(",
"R",
",",
"FiDel",
")",
";",
"Solver",
".",
"evaluateRuleSet",
"(",
"Rred",
",",
"Utils",
".",
"uniques",
"(",
"Fe",
",",
"Fi",
")",
")",
".",
"then",
"(",
"function",
"(",
"values",
")",
"{",
"FiAddNew",
"=",
"values",
".",
"cons",
";",
"if",
"(",
"Utils",
".",
"uniques",
"(",
"FiAdd",
",",
"FiAddNew",
")",
".",
"length",
">",
"FiAdd",
".",
"length",
")",
"{",
"rederivationEvaluationLoop",
"(",
")",
";",
"}",
"else",
"{",
"insertionEvaluationLoop",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
",",
"insertionEvaluationLoop",
"=",
"function",
"(",
")",
"{",
"FiAdd",
"=",
"Utils",
".",
"uniques",
"(",
"FiAdd",
",",
"FiAddNew",
")",
";",
"superSet",
"=",
"Utils",
".",
"uniques",
"(",
"Utils",
".",
"uniques",
"(",
"Utils",
".",
"uniques",
"(",
"Fe",
",",
"Fi",
")",
",",
"FeAdd",
")",
",",
"FiAdd",
")",
";",
"Rins",
"=",
"Logics",
".",
"restrictRuleSet",
"(",
"R",
",",
"superSet",
")",
";",
"Solver",
".",
"evaluateRuleSet",
"(",
"Rins",
",",
"superSet",
")",
".",
"then",
"(",
"function",
"(",
"values",
")",
"{",
"FiAddNew",
"=",
"values",
".",
"cons",
";",
"if",
"(",
"!",
"Utils",
".",
"containsSubset",
"(",
"FiAdd",
",",
"FiAddNew",
")",
")",
"{",
"insertionEvaluationLoop",
"(",
")",
";",
"}",
"else",
"{",
"additions",
"=",
"Utils",
".",
"uniques",
"(",
"FeAdd",
",",
"FiAdd",
")",
";",
"deletions",
"=",
"Utils",
".",
"uniques",
"(",
"FeDel",
",",
"FiDel",
")",
";",
"deferred",
".",
"resolve",
"(",
"{",
"additions",
":",
"additions",
",",
"deletions",
":",
"deletions",
"}",
")",
";",
"}",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"startAlgorithm",
"(",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
] |
Incremental reasoning which avoids complete recalculation of facts.
Concat is preferred over merge for evaluation purposes.
@param R set of rules
@param F set of assertions
@param FeAdd set of assertions to be added
@param FeDel set of assertions to be deleted
|
[
"Incremental",
"reasoning",
"which",
"avoids",
"complete",
"recalculation",
"of",
"facts",
".",
"Concat",
"is",
"preferred",
"over",
"merge",
"for",
"evaluation",
"purposes",
"."
] |
a66cd396de89cc2e1921b18f23ec9a8906313df2
|
https://github.com/ucbl/HyLAR-Reasoner/blob/a66cd396de89cc2e1921b18f23ec9a8906313df2/hylar/core/ReasoningEngine.js#L65-L136
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.