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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,300 | anodejs/node-rebus | lib/rebus.js | _publish | function _publish(obj, callback) {
// Write the object to the separate file.
var shortname = prop + '.json';
var data = JSON.stringify(obj);
var hash = _checkNewHash(shortname, data);
if (!hash) {
// No need to publish if the data is the same.
return callback();
}
published[shortname] = true;
// Update new object and call notifications.
_updateObject(shortname, obj, hash);
var fullname = path.join(folder, shortname);
fs.writeFile(fullname, data, function (err) {
if (err) {
console.error('Failed to write file %s err:', fullname, err);
}
return callback(err);
});
} | javascript | function _publish(obj, callback) {
// Write the object to the separate file.
var shortname = prop + '.json';
var data = JSON.stringify(obj);
var hash = _checkNewHash(shortname, data);
if (!hash) {
// No need to publish if the data is the same.
return callback();
}
published[shortname] = true;
// Update new object and call notifications.
_updateObject(shortname, obj, hash);
var fullname = path.join(folder, shortname);
fs.writeFile(fullname, data, function (err) {
if (err) {
console.error('Failed to write file %s err:', fullname, err);
}
return callback(err);
});
} | [
"function",
"_publish",
"(",
"obj",
",",
"callback",
")",
"{",
"// Write the object to the separate file.\r",
"var",
"shortname",
"=",
"prop",
"+",
"'.json'",
";",
"var",
"data",
"=",
"JSON",
".",
"stringify",
"(",
"obj",
")",
";",
"var",
"hash",
"=",
"_chec... | Worker for publishing queue. | [
"Worker",
"for",
"publishing",
"queue",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L158-L177 |
32,301 | anodejs/node-rebus | lib/rebus.js | close | function close() {
if (watcher && !closed) {
if (options.persistent) {
// Close handle only if watcher was created persistent.
watcher.close();
}
else {
// Stop handling change events.
watcher.removeAllListeners();
// Leave watcher on error events that may come from unclosed handle.
watcher.on('error', function (err) { });
}
closed = true;
}
} | javascript | function close() {
if (watcher && !closed) {
if (options.persistent) {
// Close handle only if watcher was created persistent.
watcher.close();
}
else {
// Stop handling change events.
watcher.removeAllListeners();
// Leave watcher on error events that may come from unclosed handle.
watcher.on('error', function (err) { });
}
closed = true;
}
} | [
"function",
"close",
"(",
")",
"{",
"if",
"(",
"watcher",
"&&",
"!",
"closed",
")",
"{",
"if",
"(",
"options",
".",
"persistent",
")",
"{",
"// Close handle only if watcher was created persistent.\r",
"watcher",
".",
"close",
"(",
")",
";",
"}",
"else",
"{",... | Cleanup rebus instance. | [
"Cleanup",
"rebus",
"instance",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L203-L217 |
32,302 | anodejs/node-rebus | lib/rebus.js | _updateSingleton | function _updateSingleton() {
if (!options.singletons) {
return;
}
if (process.rebusinstances[folder]) {
// Somebody added instance already.
return;
}
// Save this instance to return the same for the same folder.
process.rebusinstances[folder] = instance;
} | javascript | function _updateSingleton() {
if (!options.singletons) {
return;
}
if (process.rebusinstances[folder]) {
// Somebody added instance already.
return;
}
// Save this instance to return the same for the same folder.
process.rebusinstances[folder] = instance;
} | [
"function",
"_updateSingleton",
"(",
")",
"{",
"if",
"(",
"!",
"options",
".",
"singletons",
")",
"{",
"return",
";",
"}",
"if",
"(",
"process",
".",
"rebusinstances",
"[",
"folder",
"]",
")",
"{",
"// Somebody added instance already.\r",
"return",
";",
"}",... | Store the instance of rebus per process to be reused if requried again. | [
"Store",
"the",
"instance",
"of",
"rebus",
"per",
"process",
"to",
"be",
"reused",
"if",
"requried",
"again",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L245-L255 |
32,303 | anodejs/node-rebus | lib/rebus.js | _startWatchdog | function _startWatchdog() {
if (!watcher) {
var watcherOptions = { persistent: !!options.persistent };
watcher = fs.watch(folder, watcherOptions, function (event, filename) {
if (event === 'change' && filename.charAt(0) != '.') {
// On every change load the changed file. This will trigger notifications for interested
// subscribers.
_loadFile(filename);
}
});
}
} | javascript | function _startWatchdog() {
if (!watcher) {
var watcherOptions = { persistent: !!options.persistent };
watcher = fs.watch(folder, watcherOptions, function (event, filename) {
if (event === 'change' && filename.charAt(0) != '.') {
// On every change load the changed file. This will trigger notifications for interested
// subscribers.
_loadFile(filename);
}
});
}
} | [
"function",
"_startWatchdog",
"(",
")",
"{",
"if",
"(",
"!",
"watcher",
")",
"{",
"var",
"watcherOptions",
"=",
"{",
"persistent",
":",
"!",
"!",
"options",
".",
"persistent",
"}",
";",
"watcher",
"=",
"fs",
".",
"watch",
"(",
"folder",
",",
"watcherOp... | Start watching directory changes. | [
"Start",
"watching",
"directory",
"changes",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L265-L276 |
32,304 | anodejs/node-rebus | lib/rebus.js | _loadFile | function _loadFile(filename, callback) {
callback = callback || function () { };
if (filename.charAt(0) == '.') {
callback();
return;
}
var filepath = path.join(folder, filename);
fs.readFile(filepath, function (err, data) {
if (err) {
console.error('Failed to read file ' + filepath + ' err:', err);
callback(err);
return;
}
try {
_loadData(filename, data.toString());
}
catch (e) {
console.info('Object ' + filename + ' was not yet fully written, exception:', e);
// There will be another notification of change when the last write to file is completed.
// Meanwhile leave the previous value.
if (loader) {
// Store this error to wait until file will be successfully loaded for the 1st time.
loader.errors[filename] = e;
}
// Don't return error to continue asynchronous loading of other files. Errors are assembled on loader.
callback();
return;
}
console.log('Loaded ' + filename);
if (loader) {
if (loader.errors[filename]) {
// File that previously failed to load, now is loaded.
delete loader.errors[filename];
var countErrors = Object.keys(loader.errors).length;
if (countErrors === 0) {
// All errors are fixed. This is the time to complete loading.
var initcb = loader.callback;
loader = null;
_updateSingleton();
initcb();
}
}
}
callback();
});
} | javascript | function _loadFile(filename, callback) {
callback = callback || function () { };
if (filename.charAt(0) == '.') {
callback();
return;
}
var filepath = path.join(folder, filename);
fs.readFile(filepath, function (err, data) {
if (err) {
console.error('Failed to read file ' + filepath + ' err:', err);
callback(err);
return;
}
try {
_loadData(filename, data.toString());
}
catch (e) {
console.info('Object ' + filename + ' was not yet fully written, exception:', e);
// There will be another notification of change when the last write to file is completed.
// Meanwhile leave the previous value.
if (loader) {
// Store this error to wait until file will be successfully loaded for the 1st time.
loader.errors[filename] = e;
}
// Don't return error to continue asynchronous loading of other files. Errors are assembled on loader.
callback();
return;
}
console.log('Loaded ' + filename);
if (loader) {
if (loader.errors[filename]) {
// File that previously failed to load, now is loaded.
delete loader.errors[filename];
var countErrors = Object.keys(loader.errors).length;
if (countErrors === 0) {
// All errors are fixed. This is the time to complete loading.
var initcb = loader.callback;
loader = null;
_updateSingleton();
initcb();
}
}
}
callback();
});
} | [
"function",
"_loadFile",
"(",
"filename",
",",
"callback",
")",
"{",
"callback",
"=",
"callback",
"||",
"function",
"(",
")",
"{",
"}",
";",
"if",
"(",
"filename",
".",
"charAt",
"(",
"0",
")",
"==",
"'.'",
")",
"{",
"callback",
"(",
")",
";",
"ret... | Load object from a file. Update state and call notifications. | [
"Load",
"object",
"from",
"a",
"file",
".",
"Update",
"state",
"and",
"call",
"notifications",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L280-L327 |
32,305 | anodejs/node-rebus | lib/rebus.js | _traverse | function _traverse(props, obj, notification) {
var length = props.length;
var refobj = shared;
var refmeta = meta;
var handler = {};
var fns = [];
for (var i = 0; i < length; i++) {
var prop = props[i];
if (!refmeta[prop]) {
refmeta[prop] = {};
refmeta[prop][nfs] = {};
}
var currentmeta = refmeta[prop];
if (!refobj[prop]) {
refobj[prop] = {};
}
var currentobj = refobj[prop];
if (i === (length - 1)) {
// The end of the path.
if (obj) {
// Pin the object here.
refobj[prop] = obj;
// Since object changed, append all notifications in the subtree.
_traverseSubtree(currentmeta, obj, fns);
}
if (notification) {
// Pin notification at the end of the path.
var id = freeId++;
currentmeta[nfs][id] = notification;
// Return value indicates where the notification was pinned.
handler = { id: id, close: closeNotification };
handler[nfs] = currentmeta[nfs];
// Call the notification with initial value of the object.
// Call notification in the next tick, so that return value from subsribtion
// will be available.
process.nextTick(function () {
notification(currentobj);
});
}
}
else if (obj) {
// If change occured, call all notifications along the path.
_pushNotifications(currentmeta, currentobj, fns);
}
// Go deep into the tree.
refobj = currentobj;
refmeta = currentmeta;
}
if (obj) {
// Call all notifications.
async.parallel(fns);
}
return handler;
} | javascript | function _traverse(props, obj, notification) {
var length = props.length;
var refobj = shared;
var refmeta = meta;
var handler = {};
var fns = [];
for (var i = 0; i < length; i++) {
var prop = props[i];
if (!refmeta[prop]) {
refmeta[prop] = {};
refmeta[prop][nfs] = {};
}
var currentmeta = refmeta[prop];
if (!refobj[prop]) {
refobj[prop] = {};
}
var currentobj = refobj[prop];
if (i === (length - 1)) {
// The end of the path.
if (obj) {
// Pin the object here.
refobj[prop] = obj;
// Since object changed, append all notifications in the subtree.
_traverseSubtree(currentmeta, obj, fns);
}
if (notification) {
// Pin notification at the end of the path.
var id = freeId++;
currentmeta[nfs][id] = notification;
// Return value indicates where the notification was pinned.
handler = { id: id, close: closeNotification };
handler[nfs] = currentmeta[nfs];
// Call the notification with initial value of the object.
// Call notification in the next tick, so that return value from subsribtion
// will be available.
process.nextTick(function () {
notification(currentobj);
});
}
}
else if (obj) {
// If change occured, call all notifications along the path.
_pushNotifications(currentmeta, currentobj, fns);
}
// Go deep into the tree.
refobj = currentobj;
refmeta = currentmeta;
}
if (obj) {
// Call all notifications.
async.parallel(fns);
}
return handler;
} | [
"function",
"_traverse",
"(",
"props",
",",
"obj",
",",
"notification",
")",
"{",
"var",
"length",
"=",
"props",
".",
"length",
";",
"var",
"refobj",
"=",
"shared",
";",
"var",
"refmeta",
"=",
"meta",
";",
"var",
"handler",
"=",
"{",
"}",
";",
"var",... | Traverse the shared object according to property path. If object is specified, call all affected notifications. Those are the notifications along the property path and in the subtree at the end of the path. props - the path in the shared object. obj - if defined, pin the object at the end of the specified path. notification - if defined, pin the notification at the end of the specified path. Returns - if called with notification, returns the handler with information where the notification was pinned, so can be unpinned later. | [
"Traverse",
"the",
"shared",
"object",
"according",
"to",
"property",
"path",
".",
"If",
"object",
"is",
"specified",
"call",
"all",
"affected",
"notifications",
".",
"Those",
"are",
"the",
"notifications",
"along",
"the",
"property",
"path",
"and",
"in",
"the... | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L370-L432 |
32,306 | anodejs/node-rebus | lib/rebus.js | _traverseSubtree | function _traverseSubtree(meta, obj, fns) {
_pushNotifications(meta, obj, fns);
for (var key in meta) {
if (key === nfs) {
continue;
}
var subobj;
if (obj) {
subobj = obj[key];
}
_traverseSubtree(meta[key], subobj, fns);
}
} | javascript | function _traverseSubtree(meta, obj, fns) {
_pushNotifications(meta, obj, fns);
for (var key in meta) {
if (key === nfs) {
continue;
}
var subobj;
if (obj) {
subobj = obj[key];
}
_traverseSubtree(meta[key], subobj, fns);
}
} | [
"function",
"_traverseSubtree",
"(",
"meta",
",",
"obj",
",",
"fns",
")",
"{",
"_pushNotifications",
"(",
"meta",
",",
"obj",
",",
"fns",
")",
";",
"for",
"(",
"var",
"key",
"in",
"meta",
")",
"{",
"if",
"(",
"key",
"===",
"nfs",
")",
"{",
"continu... | Append notificaitons for entire subtree. | [
"Append",
"notificaitons",
"for",
"entire",
"subtree",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L435-L447 |
32,307 | anodejs/node-rebus | lib/rebus.js | _pushNotifications | function _pushNotifications(meta, obj, fns) {
for (var id in meta[nfs]) {
fns.push(function (i) {
return function () {
meta[nfs][i](obj);
}
} (id));
}
} | javascript | function _pushNotifications(meta, obj, fns) {
for (var id in meta[nfs]) {
fns.push(function (i) {
return function () {
meta[nfs][i](obj);
}
} (id));
}
} | [
"function",
"_pushNotifications",
"(",
"meta",
",",
"obj",
",",
"fns",
")",
"{",
"for",
"(",
"var",
"id",
"in",
"meta",
"[",
"nfs",
"]",
")",
"{",
"fns",
".",
"push",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"function",
"(",
")",
"{",
"meta... | Append notification from the tree node. | [
"Append",
"notification",
"from",
"the",
"tree",
"node",
"."
] | fdf415d91dc72991263d6f70f678507cfafdece5 | https://github.com/anodejs/node-rebus/blob/fdf415d91dc72991263d6f70f678507cfafdece5/lib/rebus.js#L450-L458 |
32,308 | hash-bang/tree-tools | dist/ngTreeTools.js | children | function children(tree, query, options) {
var compiledQuery = query ? _.matches(query) : null;
var settings = _.defaults(options, {
childNode: ['children']
});
settings.childNode = _.castArray(settings.childNode);
var rootNode = query ? treeTools.find(tree, query) : tree;
var seekStack = [];
var seekDown = function seekDown(branch, level) {
if (level > 0) seekStack.push(branch);
settings.childNode.some(function (key) {
if (branch[key] && _.isArray(branch[key])) {
branch[key].forEach(function (branchChild) {
seekDown(branchChild, level + 1);
});
return true;
}
});
};
seekDown(rootNode, 0);
return seekStack;
} | javascript | function children(tree, query, options) {
var compiledQuery = query ? _.matches(query) : null;
var settings = _.defaults(options, {
childNode: ['children']
});
settings.childNode = _.castArray(settings.childNode);
var rootNode = query ? treeTools.find(tree, query) : tree;
var seekStack = [];
var seekDown = function seekDown(branch, level) {
if (level > 0) seekStack.push(branch);
settings.childNode.some(function (key) {
if (branch[key] && _.isArray(branch[key])) {
branch[key].forEach(function (branchChild) {
seekDown(branchChild, level + 1);
});
return true;
}
});
};
seekDown(rootNode, 0);
return seekStack;
} | [
"function",
"children",
"(",
"tree",
",",
"query",
",",
"options",
")",
"{",
"var",
"compiledQuery",
"=",
"query",
"?",
"_",
".",
"matches",
"(",
"query",
")",
":",
"null",
";",
"var",
"settings",
"=",
"_",
".",
"defaults",
"(",
"options",
",",
"{",
... | Utility function to deep search a tree structure for a matching query and find all children after the given query
If found this function will return an array of all child elements NOT including the query element
@param {Object|array} tree The tree structure to search (assumed to be a collection)
@param {Object|function|null} [query] A valid lodash query to run (anything valid via _.find()) or a callback function. If null the entire flattened tree is returned
@param {Object} [options] Optional options object
@param {array|string} [options.childNode="children"] Node or nodes to examine to discover the child elements
@return {array} An array of all child elements under that item | [
"Utility",
"function",
"to",
"deep",
"search",
"a",
"tree",
"structure",
"for",
"a",
"matching",
"query",
"and",
"find",
"all",
"children",
"after",
"the",
"given",
"query",
"If",
"found",
"this",
"function",
"will",
"return",
"an",
"array",
"of",
"all",
"... | 12544aebaaaa506cb34259f16da34e4b5364829d | https://github.com/hash-bang/tree-tools/blob/12544aebaaaa506cb34259f16da34e4b5364829d/dist/ngTreeTools.js#L158-L183 |
32,309 | carbon-design-system/toolkit | packages/npm/src/getPackageInfoFrom.js | getPackageInfoFrom | function getPackageInfoFrom(string) {
if (string[0] === '@') {
const [scope, rawName] = string.split('/');
const { name, version } = getVersionFromString(rawName);
return {
name: `${scope}/${name}`,
version,
};
}
return getVersionFromString(string);
} | javascript | function getPackageInfoFrom(string) {
if (string[0] === '@') {
const [scope, rawName] = string.split('/');
const { name, version } = getVersionFromString(rawName);
return {
name: `${scope}/${name}`,
version,
};
}
return getVersionFromString(string);
} | [
"function",
"getPackageInfoFrom",
"(",
"string",
")",
"{",
"if",
"(",
"string",
"[",
"0",
"]",
"===",
"'@'",
")",
"{",
"const",
"[",
"scope",
",",
"rawName",
"]",
"=",
"string",
".",
"split",
"(",
"'/'",
")",
";",
"const",
"{",
"name",
",",
"versio... | some-package some-package@next @foo/some-package @foo/some-package@next | [
"some",
"-",
"package",
"some",
"-",
"package"
] | e3674566154a96e99fb93237faa2171a02f09275 | https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/npm/src/getPackageInfoFrom.js#L7-L18 |
32,310 | pbeshai/react-computed-props | examples/many-circles/src/Circles.js | visProps | function visProps(props) {
const {
data,
height,
width,
} = props;
const padding = {
top: 20,
right: 20,
bottom: 40,
left: 50,
};
const plotAreaWidth = width - padding.left - padding.right;
const plotAreaHeight = height - padding.top - padding.bottom;
const xDomain = d3.extent(data, d => d.x);
const yDomain = d3.extent(data, d => d.y);
const xDomainPadding = 0.05 * xDomain[1];
const yDomainPadding = 0.02 * yDomain[1];
const xScale = d3.scaleLinear()
.domain([xDomain[0] - xDomainPadding, xDomain[1] + xDomainPadding])
.range([0, plotAreaWidth]);
const yScale = d3.scaleLinear()
.domain([yDomain[0] - yDomainPadding, yDomain[1] + yDomainPadding])
.range([plotAreaHeight, 0]);
const color = ({ y }) => `rgb(150, 200, ${Math.floor(255 * (yScale(y) / plotAreaHeight))})`;
const voronoiDiagram = d3.voronoi()
.x(d => xScale(d.x))
.y(d => yScale(d.y))
.size([plotAreaWidth, plotAreaHeight])(data);
return {
color,
padding,
plotAreaWidth,
plotAreaHeight,
xScale,
yScale,
voronoiDiagram,
};
} | javascript | function visProps(props) {
const {
data,
height,
width,
} = props;
const padding = {
top: 20,
right: 20,
bottom: 40,
left: 50,
};
const plotAreaWidth = width - padding.left - padding.right;
const plotAreaHeight = height - padding.top - padding.bottom;
const xDomain = d3.extent(data, d => d.x);
const yDomain = d3.extent(data, d => d.y);
const xDomainPadding = 0.05 * xDomain[1];
const yDomainPadding = 0.02 * yDomain[1];
const xScale = d3.scaleLinear()
.domain([xDomain[0] - xDomainPadding, xDomain[1] + xDomainPadding])
.range([0, plotAreaWidth]);
const yScale = d3.scaleLinear()
.domain([yDomain[0] - yDomainPadding, yDomain[1] + yDomainPadding])
.range([plotAreaHeight, 0]);
const color = ({ y }) => `rgb(150, 200, ${Math.floor(255 * (yScale(y) / plotAreaHeight))})`;
const voronoiDiagram = d3.voronoi()
.x(d => xScale(d.x))
.y(d => yScale(d.y))
.size([plotAreaWidth, plotAreaHeight])(data);
return {
color,
padding,
plotAreaWidth,
plotAreaHeight,
xScale,
yScale,
voronoiDiagram,
};
} | [
"function",
"visProps",
"(",
"props",
")",
"{",
"const",
"{",
"data",
",",
"height",
",",
"width",
",",
"}",
"=",
"props",
";",
"const",
"padding",
"=",
"{",
"top",
":",
"20",
",",
"right",
":",
"20",
",",
"bottom",
":",
"40",
",",
"left",
":",
... | Figure out what is needed to render the chart based on the props of the component | [
"Figure",
"out",
"what",
"is",
"needed",
"to",
"render",
"the",
"chart",
"based",
"on",
"the",
"props",
"of",
"the",
"component"
] | e5098cb209d4958ac1bd743fb4b451b1834ff910 | https://github.com/pbeshai/react-computed-props/blob/e5098cb209d4958ac1bd743fb4b451b1834ff910/examples/many-circles/src/Circles.js#L8-L55 |
32,311 | pbeshai/react-computed-props | src/shallowEquals.js | excludeIncludeKeys | function excludeIncludeKeys(objA, objB, excludeKeys, includeKeys) {
let keysA = Object.keys(objA);
let keysB = Object.keys(objB);
if (excludeKeys) {
keysA = keysA.filter(key => excludeKeys.indexOf(key) === -1);
keysB = keysB.filter(key => excludeKeys.indexOf(key) === -1);
} else if (includeKeys) {
keysA = keysA.filter(key => includeKeys.indexOf(key) !== -1);
keysB = keysB.filter(key => includeKeys.indexOf(key) !== -1);
}
return [keysA, keysB];
} | javascript | function excludeIncludeKeys(objA, objB, excludeKeys, includeKeys) {
let keysA = Object.keys(objA);
let keysB = Object.keys(objB);
if (excludeKeys) {
keysA = keysA.filter(key => excludeKeys.indexOf(key) === -1);
keysB = keysB.filter(key => excludeKeys.indexOf(key) === -1);
} else if (includeKeys) {
keysA = keysA.filter(key => includeKeys.indexOf(key) !== -1);
keysB = keysB.filter(key => includeKeys.indexOf(key) !== -1);
}
return [keysA, keysB];
} | [
"function",
"excludeIncludeKeys",
"(",
"objA",
",",
"objB",
",",
"excludeKeys",
",",
"includeKeys",
")",
"{",
"let",
"keysA",
"=",
"Object",
".",
"keys",
"(",
"objA",
")",
";",
"let",
"keysB",
"=",
"Object",
".",
"keys",
"(",
"objB",
")",
";",
"if",
... | Helper function to include or exclude keys before comparing | [
"Helper",
"function",
"to",
"include",
"or",
"exclude",
"keys",
"before",
"comparing"
] | e5098cb209d4958ac1bd743fb4b451b1834ff910 | https://github.com/pbeshai/react-computed-props/blob/e5098cb209d4958ac1bd743fb4b451b1834ff910/src/shallowEquals.js#L4-L17 |
32,312 | carbon-design-system/toolkit | packages/cli-config/src/load.js | loadPlugin | function loadPlugin(descriptor, loader) {
const config = Array.isArray(descriptor) ? descriptor : [descriptor];
const [name, options = {}] = config;
const { error, module: plugin } = loader(name);
if (error) {
return {
error,
name,
};
}
if (typeof plugin !== 'function') {
return {
error: new Error(
`Expected the plugin \`${name}\` to export a function, instead ` +
`recieved: ${typeof plugin}`
),
name,
};
}
return {
name,
options,
plugin,
};
} | javascript | function loadPlugin(descriptor, loader) {
const config = Array.isArray(descriptor) ? descriptor : [descriptor];
const [name, options = {}] = config;
const { error, module: plugin } = loader(name);
if (error) {
return {
error,
name,
};
}
if (typeof plugin !== 'function') {
return {
error: new Error(
`Expected the plugin \`${name}\` to export a function, instead ` +
`recieved: ${typeof plugin}`
),
name,
};
}
return {
name,
options,
plugin,
};
} | [
"function",
"loadPlugin",
"(",
"descriptor",
",",
"loader",
")",
"{",
"const",
"config",
"=",
"Array",
".",
"isArray",
"(",
"descriptor",
")",
"?",
"descriptor",
":",
"[",
"descriptor",
"]",
";",
"const",
"[",
"name",
",",
"options",
"=",
"{",
"}",
"]"... | Load the plugin descriptor with the given loader
@param {Descriptor} descriptor
@param {Loader} loader | [
"Load",
"the",
"plugin",
"descriptor",
"with",
"the",
"given",
"loader"
] | e3674566154a96e99fb93237faa2171a02f09275 | https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/cli-config/src/load.js#L47-L74 |
32,313 | carbon-design-system/toolkit | packages/cli-config/src/load.js | loadPreset | function loadPreset(descriptor, loader) {
const config = Array.isArray(descriptor) ? descriptor : [descriptor];
const [name, options = {}] = config;
const { error: loaderError, module: getPreset } = loader(name);
if (loaderError) {
return {
error: loaderError,
name,
};
}
if (typeof getPreset !== 'function') {
return {
error: new Error(
`Expected the preset \`${name}\` to export a function, instead ` +
`recieved: ${typeof getPreset}`
),
name,
};
}
let preset;
try {
preset = getPreset(options);
} catch (error) {
return {
error,
name,
options,
};
}
const { presets = [], plugins = [] } = preset;
return {
name,
options,
presets: presets.map(descriptor => loadPreset(descriptor, loader)),
plugins: plugins.map(descriptor => loadPlugin(descriptor, loader)),
};
} | javascript | function loadPreset(descriptor, loader) {
const config = Array.isArray(descriptor) ? descriptor : [descriptor];
const [name, options = {}] = config;
const { error: loaderError, module: getPreset } = loader(name);
if (loaderError) {
return {
error: loaderError,
name,
};
}
if (typeof getPreset !== 'function') {
return {
error: new Error(
`Expected the preset \`${name}\` to export a function, instead ` +
`recieved: ${typeof getPreset}`
),
name,
};
}
let preset;
try {
preset = getPreset(options);
} catch (error) {
return {
error,
name,
options,
};
}
const { presets = [], plugins = [] } = preset;
return {
name,
options,
presets: presets.map(descriptor => loadPreset(descriptor, loader)),
plugins: plugins.map(descriptor => loadPlugin(descriptor, loader)),
};
} | [
"function",
"loadPreset",
"(",
"descriptor",
",",
"loader",
")",
"{",
"const",
"config",
"=",
"Array",
".",
"isArray",
"(",
"descriptor",
")",
"?",
"descriptor",
":",
"[",
"descriptor",
"]",
";",
"const",
"[",
"name",
",",
"options",
"=",
"{",
"}",
"]"... | Load the preset with the given loader
@param {Descriptor} descriptor
@param {Loader} loader | [
"Load",
"the",
"preset",
"with",
"the",
"given",
"loader"
] | e3674566154a96e99fb93237faa2171a02f09275 | https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/cli-config/src/load.js#L81-L122 |
32,314 | carbon-design-system/toolkit | packages/cli-runtime/src/plugins/create/create.js | create | async function create(name, options, api, env) {
// Grab the cwd and npmClient off of the environment. We can use these to
// create the folder for the project and for determining what client to use
// for npm-related commands
const { CLI_ENV, cwd, npmClient } = env;
// We support a couple of options for our `create` command, some only exist
// during development (like link and linkCli).
const { link, linkCli, plugins = [], presets = [], skip } = options;
const root = path.join(cwd, name);
logger.trace('Creating project:', name, 'at:', root);
if (await fs.exists(root)) {
throw new Error(`A folder already exists at \`${root}\``);
}
// Create the root directory for the new project
await fs.ensureDir(root);
const {
writePackageJson,
installDependencies,
linkDependencies,
} = await createClient(npmClient, root);
const packageJson = {
name,
private: true,
license: 'MIT',
scripts: {},
dependencies: {},
devDependencies: {},
toolkit: {},
};
// Write the packageJson to the newly created `root` folder
await writePackageJson(packageJson);
const installer = linkCli ? linkDependencies : installDependencies;
await installer(['@carbon/toolkit']);
if (CLI_ENV === 'production') {
clearConsole();
}
if (skip) {
displaySuccess(root, name, npmClient);
return;
}
const toolkit = await which('toolkit', { cwd: root });
if (presets.length > 0) {
const args = ['add', ...presets, link && '--link'].filter(Boolean);
await spawn(toolkit, args, {
cwd: root,
stdio: 'inherit',
});
}
if (plugins.length > 0) {
const args = ['add', ...plugins, link && '--link'].filter(Boolean);
await spawn(toolkit, args, {
cwd: root,
stdio: 'inherit',
});
}
displaySuccess(root, name, npmClient);
} | javascript | async function create(name, options, api, env) {
// Grab the cwd and npmClient off of the environment. We can use these to
// create the folder for the project and for determining what client to use
// for npm-related commands
const { CLI_ENV, cwd, npmClient } = env;
// We support a couple of options for our `create` command, some only exist
// during development (like link and linkCli).
const { link, linkCli, plugins = [], presets = [], skip } = options;
const root = path.join(cwd, name);
logger.trace('Creating project:', name, 'at:', root);
if (await fs.exists(root)) {
throw new Error(`A folder already exists at \`${root}\``);
}
// Create the root directory for the new project
await fs.ensureDir(root);
const {
writePackageJson,
installDependencies,
linkDependencies,
} = await createClient(npmClient, root);
const packageJson = {
name,
private: true,
license: 'MIT',
scripts: {},
dependencies: {},
devDependencies: {},
toolkit: {},
};
// Write the packageJson to the newly created `root` folder
await writePackageJson(packageJson);
const installer = linkCli ? linkDependencies : installDependencies;
await installer(['@carbon/toolkit']);
if (CLI_ENV === 'production') {
clearConsole();
}
if (skip) {
displaySuccess(root, name, npmClient);
return;
}
const toolkit = await which('toolkit', { cwd: root });
if (presets.length > 0) {
const args = ['add', ...presets, link && '--link'].filter(Boolean);
await spawn(toolkit, args, {
cwd: root,
stdio: 'inherit',
});
}
if (plugins.length > 0) {
const args = ['add', ...plugins, link && '--link'].filter(Boolean);
await spawn(toolkit, args, {
cwd: root,
stdio: 'inherit',
});
}
displaySuccess(root, name, npmClient);
} | [
"async",
"function",
"create",
"(",
"name",
",",
"options",
",",
"api",
",",
"env",
")",
"{",
"// Grab the cwd and npmClient off of the environment. We can use these to",
"// create the folder for the project and for determining what client to use",
"// for npm-related commands",
"co... | Create a toolkit project with the given name and options. | [
"Create",
"a",
"toolkit",
"project",
"with",
"the",
"given",
"name",
"and",
"options",
"."
] | e3674566154a96e99fb93237faa2171a02f09275 | https://github.com/carbon-design-system/toolkit/blob/e3674566154a96e99fb93237faa2171a02f09275/packages/cli-runtime/src/plugins/create/create.js#L20-L88 |
32,315 | whxaxes/mus | lib/compile/parser.js | collect | function collect(str, type) {
if (!type) {
if (otherRE.test(str)) {
// base type, null|undefined etc.
type = 'base';
} else if (objectRE.test(str)) {
// simple property
type = 'prop';
}
}
fragments.push(last = lastEl = {
expr: str,
type,
});
} | javascript | function collect(str, type) {
if (!type) {
if (otherRE.test(str)) {
// base type, null|undefined etc.
type = 'base';
} else if (objectRE.test(str)) {
// simple property
type = 'prop';
}
}
fragments.push(last = lastEl = {
expr: str,
type,
});
} | [
"function",
"collect",
"(",
"str",
",",
"type",
")",
"{",
"if",
"(",
"!",
"type",
")",
"{",
"if",
"(",
"otherRE",
".",
"test",
"(",
"str",
")",
")",
"{",
"// base type, null|undefined etc.",
"type",
"=",
"'base'",
";",
"}",
"else",
"if",
"(",
"object... | collect property | base type | string | [
"collect",
"property",
"|",
"base",
"type",
"|",
"string"
] | 221d48b258cb896bcadac0832d4d9167ad6b4d7a | https://github.com/whxaxes/mus/blob/221d48b258cb896bcadac0832d4d9167ad6b4d7a/lib/compile/parser.js#L331-L346 |
32,316 | vibhor1997a/nodejs-open-file-explorer | lib/linux.js | openExplorerinLinux | function openExplorerinLinux(path, callback) {
path = path || '/';
let p = spawn('xdg-open', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
} | javascript | function openExplorerinLinux(path, callback) {
path = path || '/';
let p = spawn('xdg-open', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
} | [
"function",
"openExplorerinLinux",
"(",
"path",
",",
"callback",
")",
"{",
"path",
"=",
"path",
"||",
"'/'",
";",
"let",
"p",
"=",
"spawn",
"(",
"'xdg-open'",
",",
"[",
"path",
"]",
")",
";",
"p",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
... | Opens the Explorer and executes the callback function in ubuntu like os
@param {string} path The path string to be opened in the explorer
@param {Function} callback Callback function to which error is passed if some error occurs | [
"Opens",
"the",
"Explorer",
"and",
"executes",
"the",
"callback",
"function",
"in",
"ubuntu",
"like",
"os"
] | ea86151dfb85251be2f07dbbaa73eb4dce36ddb8 | https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/lib/linux.js#L8-L15 |
32,317 | vibhor1997a/nodejs-open-file-explorer | index.js | openExplorer | function openExplorer(path, callback) {
if (osType == 'Windows_NT') {
openExplorerinWindows(path, callback);
}
else if (osType == 'Darwin') {
openExplorerinMac(path, callback);
}
else {
openExplorerinLinux(path, callback);
}
} | javascript | function openExplorer(path, callback) {
if (osType == 'Windows_NT') {
openExplorerinWindows(path, callback);
}
else if (osType == 'Darwin') {
openExplorerinMac(path, callback);
}
else {
openExplorerinLinux(path, callback);
}
} | [
"function",
"openExplorer",
"(",
"path",
",",
"callback",
")",
"{",
"if",
"(",
"osType",
"==",
"'Windows_NT'",
")",
"{",
"openExplorerinWindows",
"(",
"path",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"osType",
"==",
"'Darwin'",
")",
"{",
"openE... | Opens the Explorer and executes the callback function
@param {string} path The path string to be opened in the explorer
@param {Function} callback Callback function to which error is passed if some error occurs | [
"Opens",
"the",
"Explorer",
"and",
"executes",
"the",
"callback",
"function"
] | ea86151dfb85251be2f07dbbaa73eb4dce36ddb8 | https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/index.js#L12-L22 |
32,318 | vibhor1997a/nodejs-open-file-explorer | lib/mac.js | openExplorerinMac | function openExplorerinMac(path, callback) {
path = path || '/';
let p = spawn('open', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
} | javascript | function openExplorerinMac(path, callback) {
path = path || '/';
let p = spawn('open', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
} | [
"function",
"openExplorerinMac",
"(",
"path",
",",
"callback",
")",
"{",
"path",
"=",
"path",
"||",
"'/'",
";",
"let",
"p",
"=",
"spawn",
"(",
"'open'",
",",
"[",
"path",
"]",
")",
";",
"p",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
"=>",
... | Opens the Explorer and executes the callback function in osX
@param {string} path The path string to be opened in the explorer
@param {Function} callback Callback function to which error is passed if some error occurs | [
"Opens",
"the",
"Explorer",
"and",
"executes",
"the",
"callback",
"function",
"in",
"osX"
] | ea86151dfb85251be2f07dbbaa73eb4dce36ddb8 | https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/lib/mac.js#L8-L15 |
32,319 | vibhor1997a/nodejs-open-file-explorer | lib/win.js | openExplorerinWindows | function openExplorerinWindows(path, callback) {
path = path || '=';
let p = spawn('explorer', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
} | javascript | function openExplorerinWindows(path, callback) {
path = path || '=';
let p = spawn('explorer', [path]);
p.on('error', (err) => {
p.kill();
return callback(err);
});
} | [
"function",
"openExplorerinWindows",
"(",
"path",
",",
"callback",
")",
"{",
"path",
"=",
"path",
"||",
"'='",
";",
"let",
"p",
"=",
"spawn",
"(",
"'explorer'",
",",
"[",
"path",
"]",
")",
";",
"p",
".",
"on",
"(",
"'error'",
",",
"(",
"err",
")",
... | Opens the Explorer and executes the callback function in windows os
@param {string} path The path string to be opened in the explorer
@param {Function} callback Callback function to which error is passed if some error occurs | [
"Opens",
"the",
"Explorer",
"and",
"executes",
"the",
"callback",
"function",
"in",
"windows",
"os"
] | ea86151dfb85251be2f07dbbaa73eb4dce36ddb8 | https://github.com/vibhor1997a/nodejs-open-file-explorer/blob/ea86151dfb85251be2f07dbbaa73eb4dce36ddb8/lib/win.js#L8-L15 |
32,320 | johnwebbcole/jscad-utils | dist/index.js | function(p1, p2) {
var r = {
c: 90,
A: Math.abs(p2.x - p1.x),
B: Math.abs(p2.y - p1.y)
};
var brad = Math.atan2(r.B, r.A);
r.b = this.toDegrees(brad);
// r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2));
r.C = r.B / Math.sin(brad);
r.a = 90 - r.b;
return r;
} | javascript | function(p1, p2) {
var r = {
c: 90,
A: Math.abs(p2.x - p1.x),
B: Math.abs(p2.y - p1.y)
};
var brad = Math.atan2(r.B, r.A);
r.b = this.toDegrees(brad);
// r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2));
r.C = r.B / Math.sin(brad);
r.a = 90 - r.b;
return r;
} | [
"function",
"(",
"p1",
",",
"p2",
")",
"{",
"var",
"r",
"=",
"{",
"c",
":",
"90",
",",
"A",
":",
"Math",
".",
"abs",
"(",
"p2",
".",
"x",
"-",
"p1",
".",
"x",
")",
",",
"B",
":",
"Math",
".",
"abs",
"(",
"p2",
".",
"y",
"-",
"p1",
"."... | Solve a 90 degree triangle from two points.
@param {Number} p1.x Point 1 x coordinate
@param {Number} p1.y Point 1 y coordinate
@param {Number} p2.x Point 2 x coordinate
@param {Number} p2.y Point 2 y coordinate
@return {Object} A triangle object {A,B,C,a,b,c} | [
"Solve",
"a",
"90",
"degree",
"triangle",
"from",
"two",
"points",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L36-L49 | |
32,321 | johnwebbcole/jscad-utils | dist/index.js | function(r) {
r = Object.assign(r, {
C: 90
});
r.A = r.A || 90 - r.B;
r.B = r.B || 90 - r.A;
var arad = toRadians(r.A);
// sinA = a/c
// a = c * sinA
// tanA = a/b
// a = b * tanA
r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad));
// sinA = a/c
r.c = r.c || r.a / Math.sin(arad);
// tanA = a/b
r.b = r.b || r.a / Math.tan(arad);
return r;
} | javascript | function(r) {
r = Object.assign(r, {
C: 90
});
r.A = r.A || 90 - r.B;
r.B = r.B || 90 - r.A;
var arad = toRadians(r.A);
// sinA = a/c
// a = c * sinA
// tanA = a/b
// a = b * tanA
r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad));
// sinA = a/c
r.c = r.c || r.a / Math.sin(arad);
// tanA = a/b
r.b = r.b || r.a / Math.tan(arad);
return r;
} | [
"function",
"(",
"r",
")",
"{",
"r",
"=",
"Object",
".",
"assign",
"(",
"r",
",",
"{",
"C",
":",
"90",
"}",
")",
";",
"r",
".",
"A",
"=",
"r",
".",
"A",
"||",
"90",
"-",
"r",
".",
"B",
";",
"r",
".",
"B",
"=",
"r",
".",
"B",
"||",
"... | Solve a partial triangle object. Angles are in degrees.
Angle `C` is set to 90 degrees.
@param {Number} r.a Length of side `a`
@param {Number} r.A Angle `A` in degrees
@param {Number} r.b Length of side `b`
@param {Number} r.B Angle `B` in degrees
@param {Number} r.c Length of side `c`
@return {Object} A solved triangle object {A,B,C,a,b,c} | [
"Solve",
"a",
"partial",
"triangle",
"object",
".",
"Angles",
"are",
"in",
"degrees",
".",
"Angle",
"C",
"is",
"set",
"to",
"90",
"degrees",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L61-L84 | |
32,322 | johnwebbcole/jscad-utils | dist/index.js | function(object) {
return Array.isArray(object) ? object : [object.x, object.y, object.z];
} | javascript | function(object) {
return Array.isArray(object) ? object : [object.x, object.y, object.z];
} | [
"function",
"(",
"object",
")",
"{",
"return",
"Array",
".",
"isArray",
"(",
"object",
")",
"?",
"object",
":",
"[",
"object",
".",
"x",
",",
"object",
".",
"y",
",",
"object",
".",
"z",
"]",
";",
"}"
] | Converts an object with x, y, and z properties into
an array, or an array if passed an array.
@param {Object|Array} object | [
"Converts",
"an",
"object",
"with",
"x",
"y",
"and",
"z",
"properties",
"into",
"an",
"array",
"or",
"an",
"array",
"if",
"passed",
"an",
"array",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L132-L134 | |
32,323 | johnwebbcole/jscad-utils | dist/index.js | function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) {
return (Math.floor(desired / nozzel) + nozzie) * nozzel;
} | javascript | function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) {
return (Math.floor(desired / nozzel) + nozzie) * nozzel;
} | [
"function",
"(",
"desired",
",",
"nozzel",
"=",
"NOZZEL_SIZE",
",",
"nozzie",
"=",
"0",
")",
"{",
"return",
"(",
"Math",
".",
"floor",
"(",
"desired",
"/",
"nozzel",
")",
"+",
"nozzie",
")",
"*",
"nozzel",
";",
"}"
] | Return the largest number that is a multiple of the
nozzel size.
@param {Number} desired Desired value
@param {Number} [nozzel=NOZZEL_SIZE] Nozel size, defaults to `NOZZEL_SIZE`
@param {Number} [nozzie=0] Number of nozzel sizes to add to the value
@return {Number} Multiple of nozzel size | [
"Return",
"the",
"largest",
"number",
"that",
"is",
"a",
"multiple",
"of",
"the",
"nozzel",
"size",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L194-L196 | |
32,324 | johnwebbcole/jscad-utils | dist/index.js | function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) {
return (Math.ceil(desired / nozzel) + nozzie) * nozzel;
} | javascript | function(desired, nozzel = NOZZEL_SIZE, nozzie = 0) {
return (Math.ceil(desired / nozzel) + nozzie) * nozzel;
} | [
"function",
"(",
"desired",
",",
"nozzel",
"=",
"NOZZEL_SIZE",
",",
"nozzie",
"=",
"0",
")",
"{",
"return",
"(",
"Math",
".",
"ceil",
"(",
"desired",
"/",
"nozzel",
")",
"+",
"nozzie",
")",
"*",
"nozzel",
";",
"}"
] | Returns the largest number that is a multipel of the
nozzel size, just over the desired value.
@param {Number} desired Desired value
@param {Number} [nozzel=NOZZEL_SIZE] Nozel size, defaults to `NOZZEL_SIZE`
@param {Number} [nozzie=0] Number of nozzel sizes to add to the value
@return {Number} Multiple of nozzel size | [
"Returns",
"the",
"largest",
"number",
"that",
"is",
"a",
"multipel",
"of",
"the",
"nozzel",
"size",
"just",
"over",
"the",
"desired",
"value",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L205-L207 | |
32,325 | johnwebbcole/jscad-utils | dist/index.js | function(msg, o) {
echo(
msg,
JSON.stringify(o.getBounds()),
JSON.stringify(this.size(o.getBounds()))
);
} | javascript | function(msg, o) {
echo(
msg,
JSON.stringify(o.getBounds()),
JSON.stringify(this.size(o.getBounds()))
);
} | [
"function",
"(",
"msg",
",",
"o",
")",
"{",
"echo",
"(",
"msg",
",",
"JSON",
".",
"stringify",
"(",
"o",
".",
"getBounds",
"(",
")",
")",
",",
"JSON",
".",
"stringify",
"(",
"this",
".",
"size",
"(",
"o",
".",
"getBounds",
"(",
")",
")",
")",
... | Print a message and CSG object bounds and size to the conosle.
@param {String} msg Message to print
@param {CSG} o A CSG object to print the bounds and size of. | [
"Print",
"a",
"message",
"and",
"CSG",
"object",
"bounds",
"and",
"size",
"to",
"the",
"conosle",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L263-L269 | |
32,326 | johnwebbcole/jscad-utils | dist/index.js | function(object, segments, axis) {
var size = object.size()[axis];
var width = size / segments;
var result = [];
for (var i = width; i < size; i += width) {
result.push(i);
}
return result;
} | javascript | function(object, segments, axis) {
var size = object.size()[axis];
var width = size / segments;
var result = [];
for (var i = width; i < size; i += width) {
result.push(i);
}
return result;
} | [
"function",
"(",
"object",
",",
"segments",
",",
"axis",
")",
"{",
"var",
"size",
"=",
"object",
".",
"size",
"(",
")",
"[",
"axis",
"]",
";",
"var",
"width",
"=",
"size",
"/",
"segments",
";",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"... | Returns an array of positions along an object on a given axis.
@param {CSG} object The object to calculate the segments on.
@param {number} segments The number of segments to create.
@param {string} axis Axis to create the sgements on.
@return {Array} An array of segment positions. | [
"Returns",
"an",
"array",
"of",
"positions",
"along",
"an",
"object",
"on",
"a",
"given",
"axis",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L366-L374 | |
32,327 | johnwebbcole/jscad-utils | dist/index.js | size | function size(o) {
var bbox = o.getBounds ? o.getBounds() : o;
var foo = bbox[1].minus(bbox[0]);
return foo;
} | javascript | function size(o) {
var bbox = o.getBounds ? o.getBounds() : o;
var foo = bbox[1].minus(bbox[0]);
return foo;
} | [
"function",
"size",
"(",
"o",
")",
"{",
"var",
"bbox",
"=",
"o",
".",
"getBounds",
"?",
"o",
".",
"getBounds",
"(",
")",
":",
"o",
";",
"var",
"foo",
"=",
"bbox",
"[",
"1",
"]",
".",
"minus",
"(",
"bbox",
"[",
"0",
"]",
")",
";",
"return",
... | Returns a `Vector3D` with the size of the object.
@param {CSG} o A `CSG` like object or an array of `CSG.Vector3D` objects (the result of getBounds()).
@return {CSG.Vector3D} Vector3d with the size of the object | [
"Returns",
"a",
"Vector3D",
"with",
"the",
"size",
"of",
"the",
"object",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L475-L480 |
32,328 | johnwebbcole/jscad-utils | dist/index.js | fit | function fit(object, x, y, z, keep_aspect_ratio) {
var a;
if (Array.isArray(x)) {
a = x;
keep_aspect_ratio = y;
x = a[0];
y = a[1];
z = a[2];
} else {
a = [x, y, z];
}
// var c = util.centroid(object);
var size = this.size(object.getBounds());
function scale(size, value) {
if (value == 0) return 1;
return value / size;
}
var s = [scale(size.x, x), scale(size.y, y), scale(size.z, z)];
var min = util.array.min(s);
return util.centerWith(
object.scale(
s.map(function(d, i) {
if (a[i] === 0) return 1; // don't scale when value is zero
return keep_aspect_ratio ? min : d;
})
),
"xyz",
object
);
} | javascript | function fit(object, x, y, z, keep_aspect_ratio) {
var a;
if (Array.isArray(x)) {
a = x;
keep_aspect_ratio = y;
x = a[0];
y = a[1];
z = a[2];
} else {
a = [x, y, z];
}
// var c = util.centroid(object);
var size = this.size(object.getBounds());
function scale(size, value) {
if (value == 0) return 1;
return value / size;
}
var s = [scale(size.x, x), scale(size.y, y), scale(size.z, z)];
var min = util.array.min(s);
return util.centerWith(
object.scale(
s.map(function(d, i) {
if (a[i] === 0) return 1; // don't scale when value is zero
return keep_aspect_ratio ? min : d;
})
),
"xyz",
object
);
} | [
"function",
"fit",
"(",
"object",
",",
"x",
",",
"y",
",",
"z",
",",
"keep_aspect_ratio",
")",
"{",
"var",
"a",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"x",
")",
")",
"{",
"a",
"=",
"x",
";",
"keep_aspect_ratio",
"=",
"y",
";",
"x",
"=",
... | Fit an object inside a bounding box. Often used
with text labels.
@param {CSG} object [description]
@param {number | array} x [description]
@param {number} y [description]
@param {number} z [description]
@param {boolean} keep_aspect_ratio [description]
@return {CSG} [description] | [
"Fit",
"an",
"object",
"inside",
"a",
"bounding",
"box",
".",
"Often",
"used",
"with",
"text",
"labels",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L557-L589 |
32,329 | johnwebbcole/jscad-utils | dist/index.js | flush | function flush(moveobj, withobj, axis, mside, wside) {
return moveobj.translate(
util.calcFlush(moveobj, withobj, axis, mside, wside)
);
} | javascript | function flush(moveobj, withobj, axis, mside, wside) {
return moveobj.translate(
util.calcFlush(moveobj, withobj, axis, mside, wside)
);
} | [
"function",
"flush",
"(",
"moveobj",
",",
"withobj",
",",
"axis",
",",
"mside",
",",
"wside",
")",
"{",
"return",
"moveobj",
".",
"translate",
"(",
"util",
".",
"calcFlush",
"(",
"moveobj",
",",
"withobj",
",",
"axis",
",",
"mside",
",",
"wside",
")",
... | Moves an object flush with another object
@param {CSG} moveobj Object to move
@param {CSG} withobj Object to make flush with
@param {String} axis Which axis: 'x', 'y', 'z'
@param {Number} mside 0 or 1
@param {Number} wside 0 or 1
@return {CSG} [description] | [
"Moves",
"an",
"object",
"flush",
"with",
"another",
"object"
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L702-L706 |
32,330 | johnwebbcole/jscad-utils | dist/index.js | getDelta | function getDelta(size, bounds, axis, offset, nonzero) {
if (!util.isEmpty(offset) && nonzero) {
if (Math.abs(offset) < 1e-4) {
offset = 1e-4 * (util.isNegative(offset) ? -1 : 1);
}
}
// if the offset is negative, then it's an offset from
// the positive side of the axis
var dist = util.isNegative(offset) ? (offset = size[axis] + offset) : offset;
return util.axisApply(axis, function(i, a) {
return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
});
} | javascript | function getDelta(size, bounds, axis, offset, nonzero) {
if (!util.isEmpty(offset) && nonzero) {
if (Math.abs(offset) < 1e-4) {
offset = 1e-4 * (util.isNegative(offset) ? -1 : 1);
}
}
// if the offset is negative, then it's an offset from
// the positive side of the axis
var dist = util.isNegative(offset) ? (offset = size[axis] + offset) : offset;
return util.axisApply(axis, function(i, a) {
return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
});
} | [
"function",
"getDelta",
"(",
"size",
",",
"bounds",
",",
"axis",
",",
"offset",
",",
"nonzero",
")",
"{",
"if",
"(",
"!",
"util",
".",
"isEmpty",
"(",
"offset",
")",
"&&",
"nonzero",
")",
"{",
"if",
"(",
"Math",
".",
"abs",
"(",
"offset",
")",
"<... | Given an size, bounds and an axis, a Point
along the axis will be returned. If no `offset`
is given, then the midway point on the axis is returned.
When the `offset` is positive, a point `offset` from the
mininum axis is returned. When the `offset` is negative,
the `offset` is subtracted from the axis maximum.
@param {Size} size Size array of the object
@param {Bounds} bounds Bounds of the object
@param {String} axis Axis to find the point on
@param {Number} offset Offset from either end
@param {Boolean} nonzero When true, no offset values under 1e-4 are allowed.
@return {Point} The point along the axis. | [
"Given",
"an",
"size",
"bounds",
"and",
"an",
"axis",
"a",
"Point",
"along",
"the",
"axis",
"will",
"be",
"returned",
".",
"If",
"no",
"offset",
"is",
"given",
"then",
"the",
"midway",
"point",
"on",
"the",
"axis",
"is",
"returned",
".",
"When",
"the",... | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L801-L813 |
32,331 | johnwebbcole/jscad-utils | dist/index.js | bisect | function bisect(
object,
axis,
offset,
angle,
rotateaxis,
rotateoffset,
options
) {
options = util.defaults(options, {
addRotationCenter: false
});
angle = angle || 0;
var info = util.normalVector(axis);
var bounds = object.getBounds();
var size = util.size(object);
rotateaxis =
rotateaxis ||
{
x: "y",
y: "x",
z: "x"
}[axis];
// function getDelta(axis, offset) {
// // if the offset is negative, then it's an offset from
// // the positive side of the axis
// var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset;
// return util.axisApply(axis, function (i, a) {
// return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
// });
// }
var cutDelta = options.cutDelta || util.getDelta(size, bounds, axis, offset);
var rotateOffsetAxis = {
xy: "z",
yz: "x",
xz: "y"
}[[axis, rotateaxis].sort().join("")];
var centroid = object.centroid();
var rotateDelta = util.getDelta(size, bounds, rotateOffsetAxis, rotateoffset);
var rotationCenter =
options.rotationCenter ||
new CSG$1.Vector3D(
util.axisApply("xyz", function(i, a) {
if (a == axis) return cutDelta[i];
if (a == rotateOffsetAxis) return rotateDelta[i];
return centroid[a];
})
);
var rotationAxis = util.rotationAxes[rotateaxis];
var cutplane = CSG$1.OrthoNormalBasis.GetCartesian(
info.orthoNormalCartesian[0],
info.orthoNormalCartesian[1]
)
.translate(cutDelta)
.rotate(rotationCenter, rotationAxis, angle);
var g = util.group("negative,positive", [
object.cutByPlane(cutplane.plane).color("red"),
object.cutByPlane(cutplane.plane.flipped()).color("blue")
]);
if (options.addRotationCenter)
g.add(
util.unitAxis(size.length() + 10, 0.5, rotationCenter),
"rotationCenter"
);
return g;
} | javascript | function bisect(
object,
axis,
offset,
angle,
rotateaxis,
rotateoffset,
options
) {
options = util.defaults(options, {
addRotationCenter: false
});
angle = angle || 0;
var info = util.normalVector(axis);
var bounds = object.getBounds();
var size = util.size(object);
rotateaxis =
rotateaxis ||
{
x: "y",
y: "x",
z: "x"
}[axis];
// function getDelta(axis, offset) {
// // if the offset is negative, then it's an offset from
// // the positive side of the axis
// var dist = util.isNegative(offset) ? offset = size[axis] + offset : offset;
// return util.axisApply(axis, function (i, a) {
// return bounds[0][a] + (util.isEmpty(dist) ? size[axis] / 2 : dist);
// });
// }
var cutDelta = options.cutDelta || util.getDelta(size, bounds, axis, offset);
var rotateOffsetAxis = {
xy: "z",
yz: "x",
xz: "y"
}[[axis, rotateaxis].sort().join("")];
var centroid = object.centroid();
var rotateDelta = util.getDelta(size, bounds, rotateOffsetAxis, rotateoffset);
var rotationCenter =
options.rotationCenter ||
new CSG$1.Vector3D(
util.axisApply("xyz", function(i, a) {
if (a == axis) return cutDelta[i];
if (a == rotateOffsetAxis) return rotateDelta[i];
return centroid[a];
})
);
var rotationAxis = util.rotationAxes[rotateaxis];
var cutplane = CSG$1.OrthoNormalBasis.GetCartesian(
info.orthoNormalCartesian[0],
info.orthoNormalCartesian[1]
)
.translate(cutDelta)
.rotate(rotationCenter, rotationAxis, angle);
var g = util.group("negative,positive", [
object.cutByPlane(cutplane.plane).color("red"),
object.cutByPlane(cutplane.plane.flipped()).color("blue")
]);
if (options.addRotationCenter)
g.add(
util.unitAxis(size.length() + 10, 0.5, rotationCenter),
"rotationCenter"
);
return g;
} | [
"function",
"bisect",
"(",
"object",
",",
"axis",
",",
"offset",
",",
"angle",
",",
"rotateaxis",
",",
"rotateoffset",
",",
"options",
")",
"{",
"options",
"=",
"util",
".",
"defaults",
"(",
"options",
",",
"{",
"addRotationCenter",
":",
"false",
"}",
")... | Cut an object into two pieces, along a given axis. The offset
allows you to move the cut plane along the cut axis. For example,
a 10mm cube with an offset of 2, will create a 2mm side and an 8mm side.
Negative offsets operate off of the larger side of the axes. In the previous example, an offset of -2 creates a 8mm side and a 2mm side.
You can angle the cut plane and poistion the rotation point.

@param {CSG} object object to bisect
@param {string} axis axis to cut along
@param {number} offset offset to cut at
@param {number} angle angle to rotate the cut plane to
@return {object} Returns a group object with a parts object. | [
"Cut",
"an",
"object",
"into",
"two",
"pieces",
"along",
"a",
"given",
"axis",
".",
"The",
"offset",
"allows",
"you",
"to",
"move",
"the",
"cut",
"plane",
"along",
"the",
"cut",
"axis",
".",
"For",
"example",
"a",
"10mm",
"cube",
"with",
"an",
"offset"... | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L831-L904 |
32,332 | johnwebbcole/jscad-utils | dist/index.js | stretch | function stretch(object, axis, distance, offset) {
var normal = {
x: [1, 0, 0],
y: [0, 1, 0],
z: [0, 0, 1]
};
var bounds = object.getBounds();
var size = util.size(object);
var cutDelta = util.getDelta(size, bounds, axis, offset, true);
// console.log('stretch.cutDelta', cutDelta, normal[axis]);
return object.stretchAtPlane(normal[axis], cutDelta, distance);
} | javascript | function stretch(object, axis, distance, offset) {
var normal = {
x: [1, 0, 0],
y: [0, 1, 0],
z: [0, 0, 1]
};
var bounds = object.getBounds();
var size = util.size(object);
var cutDelta = util.getDelta(size, bounds, axis, offset, true);
// console.log('stretch.cutDelta', cutDelta, normal[axis]);
return object.stretchAtPlane(normal[axis], cutDelta, distance);
} | [
"function",
"stretch",
"(",
"object",
",",
"axis",
",",
"distance",
",",
"offset",
")",
"{",
"var",
"normal",
"=",
"{",
"x",
":",
"[",
"1",
",",
"0",
",",
"0",
"]",
",",
"y",
":",
"[",
"0",
",",
"1",
",",
"0",
"]",
",",
"z",
":",
"[",
"0"... | Wraps the `stretchAtPlane` call using the same
logic as `bisect`.
@param {CSG} object Object to stretch
@param {String} axis Axis to streatch along
@param {Number} distance Distance to stretch
@param {Number} offset Offset along the axis to cut the object
@return {CSG} The stretched object. | [
"Wraps",
"the",
"stretchAtPlane",
"call",
"using",
"the",
"same",
"logic",
"as",
"bisect",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L915-L926 |
32,333 | johnwebbcole/jscad-utils | dist/index.js | poly2solid | function poly2solid(top, bottom, height) {
if (top.sides.length == 0) {
// empty!
return new CSG$1();
}
// var offsetVector = CSG.parseOptionAs3DVector(options, "offset", [0, 0, 10]);
var offsetVector = CSG$1.Vector3D.Create(0, 0, height);
var normalVector = CSG$1.Vector3D.Create(0, 1, 0);
var polygons = [];
// bottom and top
polygons = polygons.concat(
bottom._toPlanePolygons({
translation: [0, 0, 0],
normalVector: normalVector,
flipped: !(offsetVector.z < 0)
})
);
polygons = polygons.concat(
top._toPlanePolygons({
translation: offsetVector,
normalVector: normalVector,
flipped: offsetVector.z < 0
})
);
// walls
var c1 = new CSG$1.Connector(
offsetVector.times(0),
[0, 0, offsetVector.z],
normalVector
);
var c2 = new CSG$1.Connector(
offsetVector,
[0, 0, offsetVector.z],
normalVector
);
polygons = polygons.concat(
bottom._toWallPolygons({
cag: top,
toConnector1: c1,
toConnector2: c2
})
);
// }
return CSG$1.fromPolygons(polygons);
} | javascript | function poly2solid(top, bottom, height) {
if (top.sides.length == 0) {
// empty!
return new CSG$1();
}
// var offsetVector = CSG.parseOptionAs3DVector(options, "offset", [0, 0, 10]);
var offsetVector = CSG$1.Vector3D.Create(0, 0, height);
var normalVector = CSG$1.Vector3D.Create(0, 1, 0);
var polygons = [];
// bottom and top
polygons = polygons.concat(
bottom._toPlanePolygons({
translation: [0, 0, 0],
normalVector: normalVector,
flipped: !(offsetVector.z < 0)
})
);
polygons = polygons.concat(
top._toPlanePolygons({
translation: offsetVector,
normalVector: normalVector,
flipped: offsetVector.z < 0
})
);
// walls
var c1 = new CSG$1.Connector(
offsetVector.times(0),
[0, 0, offsetVector.z],
normalVector
);
var c2 = new CSG$1.Connector(
offsetVector,
[0, 0, offsetVector.z],
normalVector
);
polygons = polygons.concat(
bottom._toWallPolygons({
cag: top,
toConnector1: c1,
toConnector2: c2
})
);
// }
return CSG$1.fromPolygons(polygons);
} | [
"function",
"poly2solid",
"(",
"top",
",",
"bottom",
",",
"height",
")",
"{",
"if",
"(",
"top",
".",
"sides",
".",
"length",
"==",
"0",
")",
"{",
"// empty!",
"return",
"new",
"CSG$1",
"(",
")",
";",
"}",
"// var offsetVector = CSG.parseOptionAs3DVector(opti... | Takes two CSG polygons and createds a solid of `height`.
Similar to `CSG.extrude`, excdept you can resize either
polygon.
@param {CAG} top Top polygon
@param {CAG} bottom Bottom polygon
@param {number} height heigth of solid
@return {CSG} generated solid | [
"Takes",
"two",
"CSG",
"polygons",
"and",
"createds",
"a",
"solid",
"of",
"height",
".",
"Similar",
"to",
"CSG",
".",
"extrude",
"excdept",
"you",
"can",
"resize",
"either",
"polygon",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L937-L983 |
32,334 | johnwebbcole/jscad-utils | dist/index.js | Hexagon | function Hexagon(diameter, height) {
var radius = diameter / 2;
var sqrt3 = Math.sqrt(3) / 2;
var hex = CAG.fromPoints([
[radius, 0],
[radius / 2, radius * sqrt3],
[-radius / 2, radius * sqrt3],
[-radius, 0],
[-radius / 2, -radius * sqrt3],
[radius / 2, -radius * sqrt3]
]);
return hex.extrude({
offset: [0, 0, height]
});
} | javascript | function Hexagon(diameter, height) {
var radius = diameter / 2;
var sqrt3 = Math.sqrt(3) / 2;
var hex = CAG.fromPoints([
[radius, 0],
[radius / 2, radius * sqrt3],
[-radius / 2, radius * sqrt3],
[-radius, 0],
[-radius / 2, -radius * sqrt3],
[radius / 2, -radius * sqrt3]
]);
return hex.extrude({
offset: [0, 0, height]
});
} | [
"function",
"Hexagon",
"(",
"diameter",
",",
"height",
")",
"{",
"var",
"radius",
"=",
"diameter",
"/",
"2",
";",
"var",
"sqrt3",
"=",
"Math",
".",
"sqrt",
"(",
"3",
")",
"/",
"2",
";",
"var",
"hex",
"=",
"CAG",
".",
"fromPoints",
"(",
"[",
"[",
... | Crate a hexagon.
@param {number} diameter Outside diameter of the hexagon
@param {number} height height of the hexagon | [
"Crate",
"a",
"hexagon",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L1848-L1863 |
32,335 | johnwebbcole/jscad-utils | dist/index.js | Tube | function Tube(
outsideDiameter,
insideDiameter,
height,
outsideOptions,
insideOptions
) {
return Parts.Cylinder(outsideDiameter, height, outsideOptions).subtract(
Parts.Cylinder(insideDiameter, height, insideOptions || outsideOptions)
);
} | javascript | function Tube(
outsideDiameter,
insideDiameter,
height,
outsideOptions,
insideOptions
) {
return Parts.Cylinder(outsideDiameter, height, outsideOptions).subtract(
Parts.Cylinder(insideDiameter, height, insideOptions || outsideOptions)
);
} | [
"function",
"Tube",
"(",
"outsideDiameter",
",",
"insideDiameter",
",",
"height",
",",
"outsideOptions",
",",
"insideOptions",
")",
"{",
"return",
"Parts",
".",
"Cylinder",
"(",
"outsideDiameter",
",",
"height",
",",
"outsideOptions",
")",
".",
"subtract",
"(",
... | Create a tube
@param {Number} outsideDiameter Outside diameter of the tube
@param {Number} insideDiameter Inside diameter of the tube
@param {Number} height Height of the tube
@param {Object} outsideOptions Options passed to the outside cylinder
@param {Object} insideOptions Options passed to the inside cylinder
@returns {CSG} A CSG Tube | [
"Create",
"a",
"tube"
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L1887-L1897 |
32,336 | johnwebbcole/jscad-utils | dist/index.js | function(
headDiameter,
headLength,
diameter,
length,
clearLength,
options
) {
var head = Parts.Hexagon(headDiameter, headLength);
var thread = Parts.Cylinder(diameter, length);
if (clearLength) {
var headClearSpace = Parts.Hexagon(headDiameter, clearLength);
}
return Parts.Hardware.Screw(head, thread, headClearSpace, options);
} | javascript | function(
headDiameter,
headLength,
diameter,
length,
clearLength,
options
) {
var head = Parts.Hexagon(headDiameter, headLength);
var thread = Parts.Cylinder(diameter, length);
if (clearLength) {
var headClearSpace = Parts.Hexagon(headDiameter, clearLength);
}
return Parts.Hardware.Screw(head, thread, headClearSpace, options);
} | [
"function",
"(",
"headDiameter",
",",
"headLength",
",",
"diameter",
",",
"length",
",",
"clearLength",
",",
"options",
")",
"{",
"var",
"head",
"=",
"Parts",
".",
"Hexagon",
"(",
"headDiameter",
",",
"headLength",
")",
";",
"var",
"thread",
"=",
"Parts",
... | Creates a `Group` object with a Hex Head Screw.
@param {number} headDiameter Diameter of the head of the screw
@param {number} headLength Length of the head
@param {number} diameter Diameter of the threaded shaft
@param {number} length Length of the threaded shaft
@param {number} clearLength Length of the clearance section of the head.
@param {object} options Screw options include orientation and clerance scale. | [
"Creates",
"a",
"Group",
"object",
"with",
"a",
"Hex",
"Head",
"Screw",
"."
] | 7c52e446aa5c001ccbb0a867a69b160da20a13e7 | https://github.com/johnwebbcole/jscad-utils/blob/7c52e446aa5c001ccbb0a867a69b160da20a13e7/dist/index.js#L1986-L2002 | |
32,337 | Clarence-pan/format-webpack-stats-errors-warnings | src/format-webpack-stats-errors-warnings.js | _formatErrorsWarnings | function _formatErrorsWarnings(level, list, projectRoot){
return list.map(x => {
let file, line, col, endLine, endCol, message
try{
// resolve the relative path
let fullFilePath = data_get(x, 'module.resource')
file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : ''
// file = file.replace(/[\\//]/g, '/')
line = data_get(x, 'error.error.loc.line') || 0
col = data_get(x, 'error.error.loc.column') || 0
// only need first line of message
let fullMessage = (x.message + '').trim()
let crPos = fullMessage.indexOf("\n")
if (crPos >= 0){
message = fullMessage.substring(0, crPos)
} else {
message = fullMessage
}
if (!line){
let linesColsInfo
let m
if (x.name === 'ModuleNotFoundError'
&& (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1])
} else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0
&& (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]})
} else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'})
} else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim())
message = fullMessage.replace(/\n/g, ' ')
}
if (linesColsInfo){
line = linesColsInfo.line || 0
col = linesColsInfo.col || 0
endLine = linesColsInfo.endLine
endCol = linesColsInfo.endCol
}
}
let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : ''
return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}`
} catch (e){
console.warn(e)
return ''
}
}).join("\n")
} | javascript | function _formatErrorsWarnings(level, list, projectRoot){
return list.map(x => {
let file, line, col, endLine, endCol, message
try{
// resolve the relative path
let fullFilePath = data_get(x, 'module.resource')
file = fullFilePath && projectRoot ? path.relative(projectRoot, fullFilePath) : ''
// file = file.replace(/[\\//]/g, '/')
line = data_get(x, 'error.error.loc.line') || 0
col = data_get(x, 'error.error.loc.column') || 0
// only need first line of message
let fullMessage = (x.message + '').trim()
let crPos = fullMessage.indexOf("\n")
if (crPos >= 0){
message = fullMessage.substring(0, crPos)
} else {
message = fullMessage
}
if (!line){
let linesColsInfo
let m
if (x.name === 'ModuleNotFoundError'
&& (m = fullMessage.match(MODULE_NOT_FOUND_ERR_MSG_PATTERN))){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1])
} else if (fullMessage.indexOf('component lists rendered with v-for should have explicit keys') > 0
&& (m = fullMessage.match(/([a-zA-Z-_]+)\s+(v-for=['"].*?['"])/))){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[2], {after: m[1]})
} else if (m = fullMessage.match(/export ['"](\S+?)['"] was not found/)){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1], {after: 'import'})
} else if (m = fullMessage.match(/Error compiling template:((?:.|[\r\n])*)- Component template/m)){
linesColsInfo = _resolveLineColNumInFile(fullFilePath, m[1].trim())
message = fullMessage.replace(/\n/g, ' ')
}
if (linesColsInfo){
line = linesColsInfo.line || 0
col = linesColsInfo.col || 0
endLine = linesColsInfo.endLine
endCol = linesColsInfo.endCol
}
}
let endLinesCols = (endLine || endCol) ? ('~' + (endLine || '') + (endLine ? ',' : '') + (endCol || '0')) : ''
return `!>${level}: ${file}:${line},${col}${endLinesCols}: ${message || '@see output window'}`
} catch (e){
console.warn(e)
return ''
}
}).join("\n")
} | [
"function",
"_formatErrorsWarnings",
"(",
"level",
",",
"list",
",",
"projectRoot",
")",
"{",
"return",
"list",
".",
"map",
"(",
"x",
"=>",
"{",
"let",
"file",
",",
"line",
",",
"col",
",",
"endLine",
",",
"endCol",
",",
"message",
"try",
"{",
"// reso... | Format errors or warnings
@param {string} level
@param {Array<Error>} list
@param {String|null} projectRoot | [
"Format",
"errors",
"or",
"warnings"
] | 35211ed18023e9e060d56f1227ae7483ac40fc23 | https://github.com/Clarence-pan/format-webpack-stats-errors-warnings/blob/35211ed18023e9e060d56f1227ae7483ac40fc23/src/format-webpack-stats-errors-warnings.js#L30-L83 |
32,338 | Clarence-pan/format-webpack-stats-errors-warnings | src/format-webpack-stats-errors-warnings.js | _resolveLineColNumInFile | function _resolveLineColNumInFile(file, message, options={}){
if (!message){
return {line: 0, col: 0}
}
let fileContent = fs.readFileSync(file, 'utf8')
let beyondPos = 0
switch (typeof options.after){
case 'string':
beyondPos = fileContent.indexOf(options.after)
break
case 'number':
beyondPos = options.after
break
default:
break
}
let pos = fileContent.indexOf(message, beyondPos >= 0 ? beyondPos : 0)
if (pos <= 0){
return {line: 0, col: 0}
}
let lineNum = 1
let linePos = 0
for (let i = 0; i < pos; i++){
if (fileContent.charCodeAt(i) === 10){ // 10: "\n"
lineNum++
linePos = i
}
}
return {line: lineNum, col: pos - linePos, endCol: pos - linePos + message.length}
} | javascript | function _resolveLineColNumInFile(file, message, options={}){
if (!message){
return {line: 0, col: 0}
}
let fileContent = fs.readFileSync(file, 'utf8')
let beyondPos = 0
switch (typeof options.after){
case 'string':
beyondPos = fileContent.indexOf(options.after)
break
case 'number':
beyondPos = options.after
break
default:
break
}
let pos = fileContent.indexOf(message, beyondPos >= 0 ? beyondPos : 0)
if (pos <= 0){
return {line: 0, col: 0}
}
let lineNum = 1
let linePos = 0
for (let i = 0; i < pos; i++){
if (fileContent.charCodeAt(i) === 10){ // 10: "\n"
lineNum++
linePos = i
}
}
return {line: lineNum, col: pos - linePos, endCol: pos - linePos + message.length}
} | [
"function",
"_resolveLineColNumInFile",
"(",
"file",
",",
"message",
",",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"message",
")",
"{",
"return",
"{",
"line",
":",
"0",
",",
"col",
":",
"0",
"}",
"}",
"let",
"fileContent",
"=",
"fs",
"."... | Resolve the line num of a message in a file | [
"Resolve",
"the",
"line",
"num",
"of",
"a",
"message",
"in",
"a",
"file"
] | 35211ed18023e9e060d56f1227ae7483ac40fc23 | https://github.com/Clarence-pan/format-webpack-stats-errors-warnings/blob/35211ed18023e9e060d56f1227ae7483ac40fc23/src/format-webpack-stats-errors-warnings.js#L88-L123 |
32,339 | Mogztter/opal-node-compiler | src/opal-builder.js | qpdecode | function qpdecode(callback) {
return function(data) {
var string = callback(data);
return string
.replace(/[\t\x20]$/gm, '')
.replace(/=(?:\r\n?|\n|$)/g, '')
.replace(/=([a-fA-F0-9]{2})/g, function($0, $1) {
var codePoint = parseInt($1, 16);
return String.fromCharCode(codePoint);
});
}
} | javascript | function qpdecode(callback) {
return function(data) {
var string = callback(data);
return string
.replace(/[\t\x20]$/gm, '')
.replace(/=(?:\r\n?|\n|$)/g, '')
.replace(/=([a-fA-F0-9]{2})/g, function($0, $1) {
var codePoint = parseInt($1, 16);
return String.fromCharCode(codePoint);
});
}
} | [
"function",
"qpdecode",
"(",
"callback",
")",
"{",
"return",
"function",
"(",
"data",
")",
"{",
"var",
"string",
"=",
"callback",
"(",
"data",
")",
";",
"return",
"string",
".",
"replace",
"(",
"/",
"[\\t\\x20]$",
"/",
"gm",
",",
"''",
")",
".",
"rep... | quoted-printable decode | [
"quoted",
"-",
"printable",
"decode"
] | 9eae6daef84f9ebfeb9b1ac50fc04455622cc22c | https://github.com/Mogztter/opal-node-compiler/blob/9eae6daef84f9ebfeb9b1ac50fc04455622cc22c/src/opal-builder.js#L33378-L33390 |
32,340 | saebekassebil/piu | lib/name.js | order | function order(type, name) {
if (type === '' || type === 'M') return name;
if (type === 'm') return type + name;
if (type === 'aug') return name + '#5';
if (type === 'm#5') return 'm' + name + '#5';
if (type === 'dim') return name === 'b7' ? 'dim7' : 'm' + name + 'b5';
if (type === 'Mb5') return name + 'b5';
else return name + type;
} | javascript | function order(type, name) {
if (type === '' || type === 'M') return name;
if (type === 'm') return type + name;
if (type === 'aug') return name + '#5';
if (type === 'm#5') return 'm' + name + '#5';
if (type === 'dim') return name === 'b7' ? 'dim7' : 'm' + name + 'b5';
if (type === 'Mb5') return name + 'b5';
else return name + type;
} | [
"function",
"order",
"(",
"type",
",",
"name",
")",
"{",
"if",
"(",
"type",
"===",
"''",
"||",
"type",
"===",
"'M'",
")",
"return",
"name",
";",
"if",
"(",
"type",
"===",
"'m'",
")",
"return",
"type",
"+",
"name",
";",
"if",
"(",
"type",
"===",
... | Return chord type and extensions in the correct order | [
"Return",
"chord",
"type",
"and",
"extensions",
"in",
"the",
"correct",
"order"
] | e3aca0c4f5e0556a5e36e233801b8e8e34aa89db | https://github.com/saebekassebil/piu/blob/e3aca0c4f5e0556a5e36e233801b8e8e34aa89db/lib/name.js#L11-L19 |
32,341 | Yomguithereal/obliterator | combinations.js | indicesToItems | function indicesToItems(target, items, indices, r) {
for (var i = 0; i < r; i++)
target[i] = items[indices[i]];
} | javascript | function indicesToItems(target, items, indices, r) {
for (var i = 0; i < r; i++)
target[i] = items[indices[i]];
} | [
"function",
"indicesToItems",
"(",
"target",
",",
"items",
",",
"indices",
",",
"r",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"r",
";",
"i",
"++",
")",
"target",
"[",
"i",
"]",
"=",
"items",
"[",
"indices",
"[",
"i",
"]",
"]... | Helper mapping indices to items. | [
"Helper",
"mapping",
"indices",
"to",
"items",
"."
] | e28692aadd3c1c8be686c5c4b4d7bb988924a97a | https://github.com/Yomguithereal/obliterator/blob/e28692aadd3c1c8be686c5c4b4d7bb988924a97a/combinations.js#L12-L15 |
32,342 | Yomguithereal/obliterator | split.js | makeGlobal | function makeGlobal(pattern) {
var flags = 'g';
if (pattern.multiline) flags += 'm';
if (pattern.ignoreCase) flags += 'i';
if (pattern.sticky) flags += 'y';
if (pattern.unicode) flags += 'u';
return new RegExp(pattern.source, flags);
} | javascript | function makeGlobal(pattern) {
var flags = 'g';
if (pattern.multiline) flags += 'm';
if (pattern.ignoreCase) flags += 'i';
if (pattern.sticky) flags += 'y';
if (pattern.unicode) flags += 'u';
return new RegExp(pattern.source, flags);
} | [
"function",
"makeGlobal",
"(",
"pattern",
")",
"{",
"var",
"flags",
"=",
"'g'",
";",
"if",
"(",
"pattern",
".",
"multiline",
")",
"flags",
"+=",
"'m'",
";",
"if",
"(",
"pattern",
".",
"ignoreCase",
")",
"flags",
"+=",
"'i'",
";",
"if",
"(",
"pattern"... | Function used to make the given pattern global.
@param {RegExp} pattern - Regular expression to make global.
@return {RegExp} | [
"Function",
"used",
"to",
"make",
"the",
"given",
"pattern",
"global",
"."
] | e28692aadd3c1c8be686c5c4b4d7bb988924a97a | https://github.com/Yomguithereal/obliterator/blob/e28692aadd3c1c8be686c5c4b4d7bb988924a97a/split.js#L15-L24 |
32,343 | Yomguithereal/obliterator | foreach.js | forEach | function forEach(iterable, callback) {
var iterator, k, i, l, s;
if (!iterable)
throw new Error('obliterator/forEach: invalid iterable.');
if (typeof callback !== 'function')
throw new Error('obliterator/forEach: expecting a callback.');
// The target is an array or a string or function arguments
if (
Array.isArray(iterable) ||
(ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable)) ||
typeof iterable === 'string' ||
iterable.toString() === '[object Arguments]'
) {
for (i = 0, l = iterable.length; i < l; i++)
callback(iterable[i], i);
return;
}
// The target has a #.forEach method
if (typeof iterable.forEach === 'function') {
iterable.forEach(callback);
return;
}
// The target is iterable
if (
SYMBOL_SUPPORT &&
Symbol.iterator in iterable &&
typeof iterable.next !== 'function'
) {
iterable = iterable[Symbol.iterator]();
}
// The target is an iterator
if (typeof iterable.next === 'function') {
iterator = iterable;
i = 0;
while ((s = iterator.next(), s.done !== true)) {
callback(s.value, i);
i++;
}
return;
}
// The target is a plain object
for (k in iterable) {
if (iterable.hasOwnProperty(k)) {
callback(iterable[k], k);
}
}
return;
} | javascript | function forEach(iterable, callback) {
var iterator, k, i, l, s;
if (!iterable)
throw new Error('obliterator/forEach: invalid iterable.');
if (typeof callback !== 'function')
throw new Error('obliterator/forEach: expecting a callback.');
// The target is an array or a string or function arguments
if (
Array.isArray(iterable) ||
(ARRAY_BUFFER_SUPPORT && ArrayBuffer.isView(iterable)) ||
typeof iterable === 'string' ||
iterable.toString() === '[object Arguments]'
) {
for (i = 0, l = iterable.length; i < l; i++)
callback(iterable[i], i);
return;
}
// The target has a #.forEach method
if (typeof iterable.forEach === 'function') {
iterable.forEach(callback);
return;
}
// The target is iterable
if (
SYMBOL_SUPPORT &&
Symbol.iterator in iterable &&
typeof iterable.next !== 'function'
) {
iterable = iterable[Symbol.iterator]();
}
// The target is an iterator
if (typeof iterable.next === 'function') {
iterator = iterable;
i = 0;
while ((s = iterator.next(), s.done !== true)) {
callback(s.value, i);
i++;
}
return;
}
// The target is a plain object
for (k in iterable) {
if (iterable.hasOwnProperty(k)) {
callback(iterable[k], k);
}
}
return;
} | [
"function",
"forEach",
"(",
"iterable",
",",
"callback",
")",
"{",
"var",
"iterator",
",",
"k",
",",
"i",
",",
"l",
",",
"s",
";",
"if",
"(",
"!",
"iterable",
")",
"throw",
"new",
"Error",
"(",
"'obliterator/forEach: invalid iterable.'",
")",
";",
"if",
... | Function able to iterate over almost any iterable JS value.
@param {any} iterable - Iterable value.
@param {function} callback - Callback function. | [
"Function",
"able",
"to",
"iterate",
"over",
"almost",
"any",
"iterable",
"JS",
"value",
"."
] | e28692aadd3c1c8be686c5c4b4d7bb988924a97a | https://github.com/Yomguithereal/obliterator/blob/e28692aadd3c1c8be686c5c4b4d7bb988924a97a/foreach.js#L20-L77 |
32,344 | thlorenz/docme | lib/init-tmp-dir.js | initTmpDir | function initTmpDir (dirname, cb) {
var dir = path.join(os.tmpDir(), dirname);
rmrf(dir, function (err) {
if (err) return cb(err);
mkdir(dir, function (err) {
if (err) return cb(err);
cb(null, dir);
});
});
} | javascript | function initTmpDir (dirname, cb) {
var dir = path.join(os.tmpDir(), dirname);
rmrf(dir, function (err) {
if (err) return cb(err);
mkdir(dir, function (err) {
if (err) return cb(err);
cb(null, dir);
});
});
} | [
"function",
"initTmpDir",
"(",
"dirname",
",",
"cb",
")",
"{",
"var",
"dir",
"=",
"path",
".",
"join",
"(",
"os",
".",
"tmpDir",
"(",
")",
",",
"dirname",
")",
";",
"rmrf",
"(",
"dir",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")... | Initializes a tmp dir into which to place intermediate files
@name initTmpDir
@private
@function
@param {String} dirname
@param {Function(Error, String)} cb called back with the full path to the initialized tmp dir | [
"Initializes",
"a",
"tmp",
"dir",
"into",
"which",
"to",
"place",
"intermediate",
"files"
] | 4dcd56a961dfe0393653c1d3f7d6744584199e79 | https://github.com/thlorenz/docme/blob/4dcd56a961dfe0393653c1d3f7d6744584199e79/lib/init-tmp-dir.js#L19-L29 |
32,345 | kengz/lomath | chart/plot.js | p | function p() {
// global promise object to wait for all plot options to be completed before writing
this.promises = [];
// global array for options to plot
this.optArray = [];
// simple plot
this.plot = function(seriesArr, title, yLabel, xLabel) {
// console.log("plotting")
var defer = q.defer();
this.promises.push(defer.promise);
title = title || false;
yLabel = yLabel || false;
xLabel = xLabel || false;
var opt = _.cloneDeep(tmpOpt),
set = _.set.bind(null, opt);
set('series', seriesArr);
set('title.text', title);
set('yAxis.title.text', yLabel);
set('xAxis.title.text', xLabel);
// setTimeout(function() {}, 2000);
this.optArray.push(opt);
defer.resolve();
return opt;
};
// advance plot = specify your own highcharts options
this.advPlot = function(opt) {
var defer = q.defer();
this.promises.push(defer.promise);
this.optArray.push(opt);
defer.resolve();
return opt;
};
// write highchart options to json for rendering
// if autosave is true, charts will save on view
this.write = function(autosave) {
var defer = q.defer();
for (var i = 0; i < this.optArray.length; i++) {
_.set(this.optArray[i], 'chart.renderTo', 'hchart' + i);
_.set(this.optArray[i], 'autosave', autosave);
}
fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve);
return defer.promise;
};
// serialize optArray and write to
this.serialize = function(autosave) {
var defer = q.defer();
q.all(this.promises)
.then(this.write(autosave))
.then(defer.resolve());
return defer.promise;
};
// finally, render after all plots specified
// if autosave is true, charts will save on view
this.render = function(autosave) {
var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot;
this.serialize(autosave)
.then(gulpplot)
};
this.dynrender = function() {
this.serialize()
// .then(dyngulpplot)
};
} | javascript | function p() {
// global promise object to wait for all plot options to be completed before writing
this.promises = [];
// global array for options to plot
this.optArray = [];
// simple plot
this.plot = function(seriesArr, title, yLabel, xLabel) {
// console.log("plotting")
var defer = q.defer();
this.promises.push(defer.promise);
title = title || false;
yLabel = yLabel || false;
xLabel = xLabel || false;
var opt = _.cloneDeep(tmpOpt),
set = _.set.bind(null, opt);
set('series', seriesArr);
set('title.text', title);
set('yAxis.title.text', yLabel);
set('xAxis.title.text', xLabel);
// setTimeout(function() {}, 2000);
this.optArray.push(opt);
defer.resolve();
return opt;
};
// advance plot = specify your own highcharts options
this.advPlot = function(opt) {
var defer = q.defer();
this.promises.push(defer.promise);
this.optArray.push(opt);
defer.resolve();
return opt;
};
// write highchart options to json for rendering
// if autosave is true, charts will save on view
this.write = function(autosave) {
var defer = q.defer();
for (var i = 0; i < this.optArray.length; i++) {
_.set(this.optArray[i], 'chart.renderTo', 'hchart' + i);
_.set(this.optArray[i], 'autosave', autosave);
}
fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve);
return defer.promise;
};
// serialize optArray and write to
this.serialize = function(autosave) {
var defer = q.defer();
q.all(this.promises)
.then(this.write(autosave))
.then(defer.resolve());
return defer.promise;
};
// finally, render after all plots specified
// if autosave is true, charts will save on view
this.render = function(autosave) {
var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot;
this.serialize(autosave)
.then(gulpplot)
};
this.dynrender = function() {
this.serialize()
// .then(dyngulpplot)
};
} | [
"function",
"p",
"(",
")",
"{",
"// global promise object to wait for all plot options to be completed before writing",
"this",
".",
"promises",
"=",
"[",
"]",
";",
"// global array for options to plot",
"this",
".",
"optArray",
"=",
"[",
"]",
";",
"// simple plot",
"this... | definition of plot package, uses highcharts | [
"definition",
"of",
"plot",
"package",
"uses",
"highcharts"
] | 6b0454843816da515e8c30b8e0eb571899e6b085 | https://github.com/kengz/lomath/blob/6b0454843816da515e8c30b8e0eb571899e6b085/chart/plot.js#L18-L96 |
32,346 | kengz/lomath | chart/src/js/render.js | localExport | function localExport(opt) {
var ind = _.reGet(/\d/)(opt.chart.renderTo);
_.assign(opt, {
'exporting': {
'buttons': {
'contextButton': {
'y': -10,
'menuItems': [{
'text': 'Save as PNG',
onclick: function() {
this.createCanvas(opt.title, 'png', ind);
},
'separator': false
}, {
'text': 'Save as JPEG',
onclick: function() {
this.createCanvas(opt.title, 'jpeg', ind);
},
'separator': false
}]
}
}
}
})
return opt;
} | javascript | function localExport(opt) {
var ind = _.reGet(/\d/)(opt.chart.renderTo);
_.assign(opt, {
'exporting': {
'buttons': {
'contextButton': {
'y': -10,
'menuItems': [{
'text': 'Save as PNG',
onclick: function() {
this.createCanvas(opt.title, 'png', ind);
},
'separator': false
}, {
'text': 'Save as JPEG',
onclick: function() {
this.createCanvas(opt.title, 'jpeg', ind);
},
'separator': false
}]
}
}
}
})
return opt;
} | [
"function",
"localExport",
"(",
"opt",
")",
"{",
"var",
"ind",
"=",
"_",
".",
"reGet",
"(",
"/",
"\\d",
"/",
")",
"(",
"opt",
".",
"chart",
".",
"renderTo",
")",
";",
"_",
".",
"assign",
"(",
"opt",
",",
"{",
"'exporting'",
":",
"{",
"'buttons'",... | extending exporting properties for local save | [
"extending",
"exporting",
"properties",
"for",
"local",
"save"
] | 6b0454843816da515e8c30b8e0eb571899e6b085 | https://github.com/kengz/lomath/blob/6b0454843816da515e8c30b8e0eb571899e6b085/chart/src/js/render.js#L34-L59 |
32,347 | thlorenz/docme | index.js | docme | function docme(readme, args, jsdocargs, cb) {
args = args || {};
jsdocargs = jsdocargs || [];
log.level = args.loglevel || 'info';
var projectRoot = args.projectRoot || process.cwd()
, projectName = path.basename(projectRoot)
resolveReadme(readme, function (err, fullPath) {
if (err) return cb(err);
log.info('docme', 'Updating API in "%s" with current jsdocs', readme);
update(projectRoot, projectName, jsdocargs, fullPath, cb);
});
} | javascript | function docme(readme, args, jsdocargs, cb) {
args = args || {};
jsdocargs = jsdocargs || [];
log.level = args.loglevel || 'info';
var projectRoot = args.projectRoot || process.cwd()
, projectName = path.basename(projectRoot)
resolveReadme(readme, function (err, fullPath) {
if (err) return cb(err);
log.info('docme', 'Updating API in "%s" with current jsdocs', readme);
update(projectRoot, projectName, jsdocargs, fullPath, cb);
});
} | [
"function",
"docme",
"(",
"readme",
",",
"args",
",",
"jsdocargs",
",",
"cb",
")",
"{",
"args",
"=",
"args",
"||",
"{",
"}",
";",
"jsdocargs",
"=",
"jsdocargs",
"||",
"[",
"]",
";",
"log",
".",
"level",
"=",
"args",
".",
"loglevel",
"||",
"'info'",... | Generates jsdocs for non-private members of the project in the current folder.
It then updates the given README with the githubified version of the generated API docs.
@name docme
@function
@param {String} readme path to readme in which the API docs should be updated
@param {Array.<String>} args consumed by docme
@param {String=} args.loglevel (info) level at which to log: silly|verbose|info|warn|error|silent
@param {Array.<String>} jsdocargs consumed by jsdoc
@param {Function(Error)} cb called back when docme finished updating the README | [
"Generates",
"jsdocs",
"for",
"non",
"-",
"private",
"members",
"of",
"the",
"project",
"in",
"the",
"current",
"folder",
".",
"It",
"then",
"updates",
"the",
"given",
"README",
"with",
"the",
"githubified",
"version",
"of",
"the",
"generated",
"API",
"docs"... | 4dcd56a961dfe0393653c1d3f7d6744584199e79 | https://github.com/thlorenz/docme/blob/4dcd56a961dfe0393653c1d3f7d6744584199e79/index.js#L66-L80 |
32,348 | hiddentao/sjv | index.js | function(schema) {
if (!schema) {
throw new Error('Schema is empty');
}
this._defaultLimitTypes = [String,Boolean,Number,Date,Array,Object]
this.schema = schema;
} | javascript | function(schema) {
if (!schema) {
throw new Error('Schema is empty');
}
this._defaultLimitTypes = [String,Boolean,Number,Date,Array,Object]
this.schema = schema;
} | [
"function",
"(",
"schema",
")",
"{",
"if",
"(",
"!",
"schema",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Schema is empty'",
")",
";",
"}",
"this",
".",
"_defaultLimitTypes",
"=",
"[",
"String",
",",
"Boolean",
",",
"Number",
",",
"Date",
",",
"Array",
... | A schema. | [
"A",
"schema",
"."
] | e09f30baab43aaf1864dcdea2d6096c5bdd6550d | https://github.com/hiddentao/sjv/blob/e09f30baab43aaf1864dcdea2d6096c5bdd6550d/index.js#L13-L20 | |
32,349 | boggan/unrar.js | lib/Unrar.js | unrar | function unrar(arrayBuffer) {
RarEventMgr.emitStart();
var bstream = new BitStream(arrayBuffer, false /* rtl */ );
var header = new RarVolumeHeader(bstream);
if (header.crc == 0x6152 &&
header.headType == 0x72 &&
header.flags.value == 0x1A21 &&
header.headSize == 7) {
RarEventMgr.emitInfo("Found RAR signature");
var mhead = new RarVolumeHeader(bstream);
if (mhead.headType != RarUtils.VOLUME_TYPES.MAIN_HEAD) {
RarEventMgr.emitError("Error! RAR did not include a MAIN_HEAD header");
} else {
var localFiles = [],
localFile = null;
do {
try {
localFile = new RarLocalFile(bstream);
RarEventMgr.emitInfo("RAR localFile isValid=" + localFile.isValid + ", volume packSize=" + localFile.header.packSize);
if (localFile && localFile.isValid && localFile.header.packSize > 0) {
RarUtils.PROGRESS.totalUncompressedBytesInArchive += localFile.header.unpackedSize;
localFiles.push(localFile);
} else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) {
localFile.isValid = true;
}
} catch (err) {
break;
}
RarEventMgr.emitInfo("bstream" + bstream.bytePtr + "/" + bstream.bytes.length);
} while (localFile.isValid);
RarUtils.PROGRESS.totalFilesInArchive = localFiles.length;
// now we have all console.information but things are unpacked
// TODO: unpack
localFiles = localFiles.sort(function(a, b) {
var aname = a.filename;
var bname = b.filename;
return aname > bname ? 1 : -1;
});
RarEventMgr.emitInfo(localFiles.map(function(a) {
return a.filename
}).join(', '));
for (var i = 0; i < localFiles.length; ++i) {
var localfile = localFiles[i];
RarEventMgr.emitInfo("Local file: ", localfile.filename);
// update progress
RarUtils.PROGRESS.currentFilename = localfile.header.filename;
RarUtils.PROGRESS.currentBytesUnarchivedInFile = 0;
// actually do the unzipping
localfile.unrar();
if (localfile.isValid) {
// notify extract event with file
RarEventMgr.emitExtract(localfile);
RarEventMgr.emitProgress(RarUtils.PROGRESS);
}
}
RarEventMgr.emitProgress(RarUtils.PROGRESS);
}
} else {
RarEventMgr.emitError("Invalid RAR file");
}
RarEventMgr.emitFinish(localFiles);
return localFiles;
} | javascript | function unrar(arrayBuffer) {
RarEventMgr.emitStart();
var bstream = new BitStream(arrayBuffer, false /* rtl */ );
var header = new RarVolumeHeader(bstream);
if (header.crc == 0x6152 &&
header.headType == 0x72 &&
header.flags.value == 0x1A21 &&
header.headSize == 7) {
RarEventMgr.emitInfo("Found RAR signature");
var mhead = new RarVolumeHeader(bstream);
if (mhead.headType != RarUtils.VOLUME_TYPES.MAIN_HEAD) {
RarEventMgr.emitError("Error! RAR did not include a MAIN_HEAD header");
} else {
var localFiles = [],
localFile = null;
do {
try {
localFile = new RarLocalFile(bstream);
RarEventMgr.emitInfo("RAR localFile isValid=" + localFile.isValid + ", volume packSize=" + localFile.header.packSize);
if (localFile && localFile.isValid && localFile.header.packSize > 0) {
RarUtils.PROGRESS.totalUncompressedBytesInArchive += localFile.header.unpackedSize;
localFiles.push(localFile);
} else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) {
localFile.isValid = true;
}
} catch (err) {
break;
}
RarEventMgr.emitInfo("bstream" + bstream.bytePtr + "/" + bstream.bytes.length);
} while (localFile.isValid);
RarUtils.PROGRESS.totalFilesInArchive = localFiles.length;
// now we have all console.information but things are unpacked
// TODO: unpack
localFiles = localFiles.sort(function(a, b) {
var aname = a.filename;
var bname = b.filename;
return aname > bname ? 1 : -1;
});
RarEventMgr.emitInfo(localFiles.map(function(a) {
return a.filename
}).join(', '));
for (var i = 0; i < localFiles.length; ++i) {
var localfile = localFiles[i];
RarEventMgr.emitInfo("Local file: ", localfile.filename);
// update progress
RarUtils.PROGRESS.currentFilename = localfile.header.filename;
RarUtils.PROGRESS.currentBytesUnarchivedInFile = 0;
// actually do the unzipping
localfile.unrar();
if (localfile.isValid) {
// notify extract event with file
RarEventMgr.emitExtract(localfile);
RarEventMgr.emitProgress(RarUtils.PROGRESS);
}
}
RarEventMgr.emitProgress(RarUtils.PROGRESS);
}
} else {
RarEventMgr.emitError("Invalid RAR file");
}
RarEventMgr.emitFinish(localFiles);
return localFiles;
} | [
"function",
"unrar",
"(",
"arrayBuffer",
")",
"{",
"RarEventMgr",
".",
"emitStart",
"(",
")",
";",
"var",
"bstream",
"=",
"new",
"BitStream",
"(",
"arrayBuffer",
",",
"false",
"/* rtl */",
")",
";",
"var",
"header",
"=",
"new",
"RarVolumeHeader",
"(",
"bst... | make sure we flush all tracking variables | [
"make",
"sure",
"we",
"flush",
"all",
"tracking",
"variables"
] | 88f56ee9ef9d133a24119b8f6e456b8f55a294d4 | https://github.com/boggan/unrar.js/blob/88f56ee9ef9d133a24119b8f6e456b8f55a294d4/lib/Unrar.js#L40-L115 |
32,350 | boggan/unrar.js | lib/BitStream.js | BitStream | function BitStream(ab, rtl, opt_offset, opt_length) {
// if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") {
// throw "Error! BitArray constructed with an invalid ArrayBuffer object";
// }
var offset = opt_offset || 0;
var length = opt_length || ab.byteLength;
this.bytes = new Uint8Array(ab, offset, length);
this.bytePtr = 0; // tracks which byte we are on
this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7)
this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr;
} | javascript | function BitStream(ab, rtl, opt_offset, opt_length) {
// if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") {
// throw "Error! BitArray constructed with an invalid ArrayBuffer object";
// }
var offset = opt_offset || 0;
var length = opt_length || ab.byteLength;
this.bytes = new Uint8Array(ab, offset, length);
this.bytePtr = 0; // tracks which byte we are on
this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7)
this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr;
} | [
"function",
"BitStream",
"(",
"ab",
",",
"rtl",
",",
"opt_offset",
",",
"opt_length",
")",
"{",
"// if (!ab || !ab.toString || ab.toString() !== \"[object ArrayBuffer]\") {",
"// throw \"Error! BitArray constructed with an invalid ArrayBuffer object\";",
"// }",
"var",
"offset",
... | This bit stream peeks and consumes bits out of a binary stream.
@param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array.
@param {boolean} rtl Whether the stream reads bits from the byte starting
from bit 7 to 0 (true) or bit 0 to 7 (false).
@param {Number} opt_offset The offset into the ArrayBuffer
@param {Number} opt_length The length of this BitStream | [
"This",
"bit",
"stream",
"peeks",
"and",
"consumes",
"bits",
"out",
"of",
"a",
"binary",
"stream",
"."
] | 88f56ee9ef9d133a24119b8f6e456b8f55a294d4 | https://github.com/boggan/unrar.js/blob/88f56ee9ef9d133a24119b8f6e456b8f55a294d4/lib/BitStream.js#L14-L25 |
32,351 | senecajs/seneca-web | web.js | mapRoutes | function mapRoutes(msg, done) {
var seneca = this
var adapter = msg.adapter || locals.adapter
var context = msg.context || locals.context
var options = msg.options || locals.options
var routes = Mapper(msg.routes)
var auth = msg.auth || locals.auth
// Call the adaptor with the mapped routes, context to apply them to
// and instance of seneca and the provided consumer callback.
adapter.call(seneca, options, context, auth, routes, done)
} | javascript | function mapRoutes(msg, done) {
var seneca = this
var adapter = msg.adapter || locals.adapter
var context = msg.context || locals.context
var options = msg.options || locals.options
var routes = Mapper(msg.routes)
var auth = msg.auth || locals.auth
// Call the adaptor with the mapped routes, context to apply them to
// and instance of seneca and the provided consumer callback.
adapter.call(seneca, options, context, auth, routes, done)
} | [
"function",
"mapRoutes",
"(",
"msg",
",",
"done",
")",
"{",
"var",
"seneca",
"=",
"this",
"var",
"adapter",
"=",
"msg",
".",
"adapter",
"||",
"locals",
".",
"adapter",
"var",
"context",
"=",
"msg",
".",
"context",
"||",
"locals",
".",
"context",
"var",... | Creates a route-map and passes it to a given adapter. The msg can optionally contain a custom adapter or context for once off routing. | [
"Creates",
"a",
"route",
"-",
"map",
"and",
"passes",
"it",
"to",
"a",
"given",
"adapter",
".",
"The",
"msg",
"can",
"optionally",
"contain",
"a",
"custom",
"adapter",
"or",
"context",
"for",
"once",
"off",
"routing",
"."
] | e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb | https://github.com/senecajs/seneca-web/blob/e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb/web.js#L58-L69 |
32,352 | senecajs/seneca-web | web.js | setServer | function setServer(msg, done) {
var seneca = this
var context = msg.context || locals.context
var adapter = msg.adapter || locals.adapter
var options = msg.options || locals.options
var auth = msg.auth || locals.auth
var routes = msg.routes
// If the adapter is a string, we look up the
// adapters collection in opts.adapters.
if (!_.isFunction(adapter)) {
return done(new Error('Provide a function as adapter'))
}
// either replaced or the same. Regardless
// this sets what is called by mapRoutes.
locals = {
context: context,
adapter: adapter,
auth: auth,
options: options
}
// If we have routes in the msg map them and
// let the matter handle the callback
if (routes) {
mapRoutes.call(seneca, { routes: routes }, done)
} else {
// no routes to process, let the
// caller know everything went ok.
done(null, { ok: true })
}
} | javascript | function setServer(msg, done) {
var seneca = this
var context = msg.context || locals.context
var adapter = msg.adapter || locals.adapter
var options = msg.options || locals.options
var auth = msg.auth || locals.auth
var routes = msg.routes
// If the adapter is a string, we look up the
// adapters collection in opts.adapters.
if (!_.isFunction(adapter)) {
return done(new Error('Provide a function as adapter'))
}
// either replaced or the same. Regardless
// this sets what is called by mapRoutes.
locals = {
context: context,
adapter: adapter,
auth: auth,
options: options
}
// If we have routes in the msg map them and
// let the matter handle the callback
if (routes) {
mapRoutes.call(seneca, { routes: routes }, done)
} else {
// no routes to process, let the
// caller know everything went ok.
done(null, { ok: true })
}
} | [
"function",
"setServer",
"(",
"msg",
",",
"done",
")",
"{",
"var",
"seneca",
"=",
"this",
"var",
"context",
"=",
"msg",
".",
"context",
"||",
"locals",
".",
"context",
"var",
"adapter",
"=",
"msg",
".",
"adapter",
"||",
"locals",
".",
"adapter",
"var",... | Sets the 'default' server context. Any call to mapRoutes will use this server as it's context if none is provided. This is the server returned by getServer. | [
"Sets",
"the",
"default",
"server",
"context",
".",
"Any",
"call",
"to",
"mapRoutes",
"will",
"use",
"this",
"server",
"as",
"it",
"s",
"context",
"if",
"none",
"is",
"provided",
".",
"This",
"is",
"the",
"server",
"returned",
"by",
"getServer",
"."
] | e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb | https://github.com/senecajs/seneca-web/blob/e990cc8f8fcfa70b984ffe0aa7aab57a64e8c6cb/web.js#L73-L105 |
32,353 | sidorares/nodejs-mysql-native | lib/mysql-native/command.js | cmd | function cmd(handlers)
{
this.fieldindex = 0;
this.state = "start";
this.stmt = ""
this.params = []
// mixin all handlers
for (var h in handlers)
{
this[h] = handlers[h];
}
// save command name to display in debug output
this.command_name = cmd.caller.command_name;
this.args = Array.prototype.slice.call(cmd.caller.arguments);
} | javascript | function cmd(handlers)
{
this.fieldindex = 0;
this.state = "start";
this.stmt = ""
this.params = []
// mixin all handlers
for (var h in handlers)
{
this[h] = handlers[h];
}
// save command name to display in debug output
this.command_name = cmd.caller.command_name;
this.args = Array.prototype.slice.call(cmd.caller.arguments);
} | [
"function",
"cmd",
"(",
"handlers",
")",
"{",
"this",
".",
"fieldindex",
"=",
"0",
";",
"this",
".",
"state",
"=",
"\"start\"",
";",
"this",
".",
"stmt",
"=",
"\"\"",
"this",
".",
"params",
"=",
"[",
"]",
"// mixin all handlers",
"for",
"(",
"var",
"... | base for all commands initialises EventEmitter and implemets state mashine | [
"base",
"for",
"all",
"commands",
"initialises",
"EventEmitter",
"and",
"implemets",
"state",
"mashine"
] | a7bb1356c8722b99e75e1eecf0af960fdc3c56c3 | https://github.com/sidorares/nodejs-mysql-native/blob/a7bb1356c8722b99e75e1eecf0af960fdc3c56c3/lib/mysql-native/command.js#L8-L23 |
32,354 | thaliproject/Thali_CordovaPlugin | thali/install/cordova-hooks/ios/before_plugin_install.js | updateJXcoreExtensionImport | function updateJXcoreExtensionImport(context) {
var cordovaUtil =
context.requireCordovaModule('cordova-lib/src/cordova/util');
var ConfigParser = context.requireCordovaModule('cordova-lib').configparser;
var projectRoot = cordovaUtil.isCordova();
var xml = cordovaUtil.projectConfig(projectRoot);
var cfg = new ConfigParser(xml);
var Q = context.requireCordovaModule('q');
var deferred = new Q.defer();
var jxcoreExtensionPath = path.join(
context.opts.plugin.dir, 'src', 'ios', 'JXcoreExtension.m');
try {
console.log('Updating JXcoreExtension.m');
var oldContent = fs.readFileSync(jxcoreExtensionPath, 'utf8');
var newContent = oldContent.replace('%PROJECT_NAME%', cfg.name());
fs.writeFileSync(jxcoreExtensionPath, newContent, 'utf8');
deferred.resolve();
} catch (error) {
console.log('Failed updating of JXcoreExtension.m');
deferred.reject(error);
}
return deferred.promise;
} | javascript | function updateJXcoreExtensionImport(context) {
var cordovaUtil =
context.requireCordovaModule('cordova-lib/src/cordova/util');
var ConfigParser = context.requireCordovaModule('cordova-lib').configparser;
var projectRoot = cordovaUtil.isCordova();
var xml = cordovaUtil.projectConfig(projectRoot);
var cfg = new ConfigParser(xml);
var Q = context.requireCordovaModule('q');
var deferred = new Q.defer();
var jxcoreExtensionPath = path.join(
context.opts.plugin.dir, 'src', 'ios', 'JXcoreExtension.m');
try {
console.log('Updating JXcoreExtension.m');
var oldContent = fs.readFileSync(jxcoreExtensionPath, 'utf8');
var newContent = oldContent.replace('%PROJECT_NAME%', cfg.name());
fs.writeFileSync(jxcoreExtensionPath, newContent, 'utf8');
deferred.resolve();
} catch (error) {
console.log('Failed updating of JXcoreExtension.m');
deferred.reject(error);
}
return deferred.promise;
} | [
"function",
"updateJXcoreExtensionImport",
"(",
"context",
")",
"{",
"var",
"cordovaUtil",
"=",
"context",
".",
"requireCordovaModule",
"(",
"'cordova-lib/src/cordova/util'",
")",
";",
"var",
"ConfigParser",
"=",
"context",
".",
"requireCordovaModule",
"(",
"'cordova-li... | Replaces PROJECT_NAME pattern with actual Cordova's project name | [
"Replaces",
"PROJECT_NAME",
"pattern",
"with",
"actual",
"Cordova",
"s",
"project",
"name"
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/cordova-hooks/ios/before_plugin_install.js#L13-L41 |
32,355 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/thaliMobileNativeWrapper.js | function (methodName, callback) {
Mobile(methodName).registerToNative(callback);
Mobile('didRegisterToNative').callNative(methodName, function () {
logger.debug('Method %s registered to native', methodName);
});
} | javascript | function (methodName, callback) {
Mobile(methodName).registerToNative(callback);
Mobile('didRegisterToNative').callNative(methodName, function () {
logger.debug('Method %s registered to native', methodName);
});
} | [
"function",
"(",
"methodName",
",",
"callback",
")",
"{",
"Mobile",
"(",
"methodName",
")",
".",
"registerToNative",
"(",
"callback",
")",
";",
"Mobile",
"(",
"'didRegisterToNative'",
")",
".",
"callNative",
"(",
"methodName",
",",
"function",
"(",
")",
"{",... | Function to register a method to the native side and inform that the registration was done. | [
"Function",
"to",
"register",
"a",
"method",
"to",
"the",
"native",
"side",
"and",
"inform",
"that",
"the",
"registration",
"was",
"done",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/thaliMobileNativeWrapper.js#L1224-L1229 | |
32,356 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/replication/utilities.js | compareBufferArrays | function compareBufferArrays(buffArray1, buffArray2) {
assert(Array.isArray(buffArray1), 'We only accept arrays.');
assert(Array.isArray(buffArray2), 'We only accept arrays.');
if (buffArray1.length !== buffArray2.length) {
return false;
}
for (var i = 0; i < buffArray1.length; ++i) {
var buff1 = buffArray1[i];
assert(Buffer.isBuffer(buff1), 'Only buffers allowed in 1');
var buff2 = buffArray2[i];
assert(Buffer.isBuffer(buff2), 'Only buffers allowed in 2');
if (Buffer.compare(buff1, buff2) !== 0) {
return false;
}
}
return true;
} | javascript | function compareBufferArrays(buffArray1, buffArray2) {
assert(Array.isArray(buffArray1), 'We only accept arrays.');
assert(Array.isArray(buffArray2), 'We only accept arrays.');
if (buffArray1.length !== buffArray2.length) {
return false;
}
for (var i = 0; i < buffArray1.length; ++i) {
var buff1 = buffArray1[i];
assert(Buffer.isBuffer(buff1), 'Only buffers allowed in 1');
var buff2 = buffArray2[i];
assert(Buffer.isBuffer(buff2), 'Only buffers allowed in 2');
if (Buffer.compare(buff1, buff2) !== 0) {
return false;
}
}
return true;
} | [
"function",
"compareBufferArrays",
"(",
"buffArray1",
",",
"buffArray2",
")",
"{",
"assert",
"(",
"Array",
".",
"isArray",
"(",
"buffArray1",
")",
",",
"'We only accept arrays.'",
")",
";",
"assert",
"(",
"Array",
".",
"isArray",
"(",
"buffArray2",
")",
",",
... | Compares if two buffer arrays contain the same buffers in the same order.
@param {Buffer[]} buffArray1
@param {Buffer[]} buffArray2
@returns {boolean} | [
"Compares",
"if",
"two",
"buffer",
"arrays",
"contain",
"the",
"same",
"buffers",
"in",
"the",
"same",
"order",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/replication/utilities.js#L11-L27 |
32,357 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/mux/createPeerListener.js | closeOldestServer | function closeOldestServer() {
var oldest = null;
Object.keys(self._peerServers).forEach(function (k) {
if (oldest == null) {
oldest = k;
}
else {
if (self._peerServers[k].lastActive <
self._peerServers[oldest].lastActive) {
oldest = k;
}
}
});
if (oldest) {
closeServer(self, self._peerServers[oldest], null, false);
}
} | javascript | function closeOldestServer() {
var oldest = null;
Object.keys(self._peerServers).forEach(function (k) {
if (oldest == null) {
oldest = k;
}
else {
if (self._peerServers[k].lastActive <
self._peerServers[oldest].lastActive) {
oldest = k;
}
}
});
if (oldest) {
closeServer(self, self._peerServers[oldest], null, false);
}
} | [
"function",
"closeOldestServer",
"(",
")",
"{",
"var",
"oldest",
"=",
"null",
";",
"Object",
".",
"keys",
"(",
"self",
".",
"_peerServers",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"if",
"(",
"oldest",
"==",
"null",
")",
"{",
"oldest... | This is the server that will listen for connection coming from the application | [
"This",
"is",
"the",
"server",
"that",
"will",
"listen",
"for",
"connection",
"coming",
"from",
"the",
"application"
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/mux/createPeerListener.js#L466-L482 |
32,358 | thaliproject/Thali_CordovaPlugin | thali/install/install.js | httpRequestPromise | function httpRequestPromise(method, urlObject) {
if (method !== 'GET' && method !== 'HEAD') {
return Promise.reject(new Error('We only support GET or HEAD requests'));
}
return new Promise(function (resolve, reject) {
var httpsRequestOptions = {
host: urlObject.host,
method: method,
path: urlObject.path
};
var req = https.request(httpsRequestOptions, function (res) {
if (res.statusCode !== 200) {
reject(new Error('Did not get 200 for ' + urlObject.href +
', instead got ' + res.statusCode));
return;
}
resolve(res);
})
.on('error', function (e) {
reject(new Error('Got error on ' + urlObject.href + ' - ' + e));
});
req.end();
});
} | javascript | function httpRequestPromise(method, urlObject) {
if (method !== 'GET' && method !== 'HEAD') {
return Promise.reject(new Error('We only support GET or HEAD requests'));
}
return new Promise(function (resolve, reject) {
var httpsRequestOptions = {
host: urlObject.host,
method: method,
path: urlObject.path
};
var req = https.request(httpsRequestOptions, function (res) {
if (res.statusCode !== 200) {
reject(new Error('Did not get 200 for ' + urlObject.href +
', instead got ' + res.statusCode));
return;
}
resolve(res);
})
.on('error', function (e) {
reject(new Error('Got error on ' + urlObject.href + ' - ' + e));
});
req.end();
});
} | [
"function",
"httpRequestPromise",
"(",
"method",
",",
"urlObject",
")",
"{",
"if",
"(",
"method",
"!==",
"'GET'",
"&&",
"method",
"!==",
"'HEAD'",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'We only support GET or HEAD requests'",
... | Unfortunately the obvious library, request-promise, doesn't handle streams well so it would take the multi-megabyte ZIP response file and turn it into an in-memory string. So we use this instead. | [
"Unfortunately",
"the",
"obvious",
"library",
"request",
"-",
"promise",
"doesn",
"t",
"handle",
"streams",
"well",
"so",
"it",
"would",
"take",
"the",
"multi",
"-",
"megabyte",
"ZIP",
"response",
"file",
"and",
"turn",
"it",
"into",
"an",
"in",
"-",
"memo... | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L26-L53 |
32,359 | thaliproject/Thali_CordovaPlugin | thali/install/install.js | getReleaseConfig | function getReleaseConfig() {
var configFileName = path.join(__dirname, '..', 'package.json');
return fs.readFileAsync(configFileName, 'utf-8')
.then(function (data) {
var conf;
try {
conf = JSON.parse(data);
if (conf && conf.thaliInstall) {
return conf.thaliInstall;
}
return Promise.reject('Configuration error!');
}
catch (err) {
return Promise.reject(new Error(err));
}
});
} | javascript | function getReleaseConfig() {
var configFileName = path.join(__dirname, '..', 'package.json');
return fs.readFileAsync(configFileName, 'utf-8')
.then(function (data) {
var conf;
try {
conf = JSON.parse(data);
if (conf && conf.thaliInstall) {
return conf.thaliInstall;
}
return Promise.reject('Configuration error!');
}
catch (err) {
return Promise.reject(new Error(err));
}
});
} | [
"function",
"getReleaseConfig",
"(",
")",
"{",
"var",
"configFileName",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'..'",
",",
"'package.json'",
")",
";",
"return",
"fs",
".",
"readFileAsync",
"(",
"configFileName",
",",
"'utf-8'",
")",
".",
"then",
... | This method is used to retrieve the release configuration data
stored in the releaseConfig.json.
@returns {Promise} Returns release config | [
"This",
"method",
"is",
"used",
"to",
"retrieve",
"the",
"release",
"configuration",
"data",
"stored",
"in",
"the",
"releaseConfig",
".",
"json",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L79-L96 |
32,360 | thaliproject/Thali_CordovaPlugin | thali/install/install.js | doGitHubEtagsMatch | function doGitHubEtagsMatch(projectName, depotName, branchName,
directoryToInstallIn) {
return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn)
.then(function (etagFromFile) {
if (!etagFromFile) {
return false;
}
return httpRequestPromise('HEAD',
getGitHubZipUrlObject(projectName, depotName, branchName))
.then(function (res) {
var etagFromHeadRequest = returnEtagFromResponse(res);
return etagFromFile === etagFromHeadRequest;
});
});
} | javascript | function doGitHubEtagsMatch(projectName, depotName, branchName,
directoryToInstallIn) {
return getEtagFromEtagFile(depotName, branchName, directoryToInstallIn)
.then(function (etagFromFile) {
if (!etagFromFile) {
return false;
}
return httpRequestPromise('HEAD',
getGitHubZipUrlObject(projectName, depotName, branchName))
.then(function (res) {
var etagFromHeadRequest = returnEtagFromResponse(res);
return etagFromFile === etagFromHeadRequest;
});
});
} | [
"function",
"doGitHubEtagsMatch",
"(",
"projectName",
",",
"depotName",
",",
"branchName",
",",
"directoryToInstallIn",
")",
"{",
"return",
"getEtagFromEtagFile",
"(",
"depotName",
",",
"branchName",
",",
"directoryToInstallIn",
")",
".",
"then",
"(",
"function",
"(... | This method is a hack because I'm having trouble getting GitHub to respect
if-none-match headers. So instead I'm doing a HEAD request and manually
checking if the etags match.
@param {string} projectName The project name
@param {string} depotName The depot name
@param {string} branchName The branch name
@param {string} directoryToInstallIn The directory to install in
@returns {boolean} Do the etags match? | [
"This",
"method",
"is",
"a",
"hack",
"because",
"I",
"m",
"having",
"trouble",
"getting",
"GitHub",
"to",
"respect",
"if",
"-",
"none",
"-",
"match",
"headers",
".",
"So",
"instead",
"I",
"m",
"doing",
"a",
"HEAD",
"request",
"and",
"manually",
"checking... | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L137-L152 |
32,361 | thaliproject/Thali_CordovaPlugin | thali/install/install.js | copyDevelopmentThaliCordovaPluginToProject | function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
thaliDontCheckIn,
depotName,
branchName) {
var targetDirectory = createUnzippedDirectoryPath(depotName, branchName,
thaliDontCheckIn);
var sourceDirectory = path.join(
appRootDirectory, '..', 'Thali_CordovaPlugin');
return new Promise(function (resolve, reject) {
fs.remove(targetDirectory, function (err) {
if (err) {
reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' +
'failed with ' + err));
return;
}
console.log('Copying files from ' + sourceDirectory + ' to ' +
targetDirectory);
fs.copy(sourceDirectory, targetDirectory, function (err) {
if (err) {
reject(
new Error('copyDevelopmentThaliCordovaPluginToProject failed with' +
err));
return;
}
resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn,
true));
});
});
});
} | javascript | function copyDevelopmentThaliCordovaPluginToProject(appRootDirectory,
thaliDontCheckIn,
depotName,
branchName) {
var targetDirectory = createUnzippedDirectoryPath(depotName, branchName,
thaliDontCheckIn);
var sourceDirectory = path.join(
appRootDirectory, '..', 'Thali_CordovaPlugin');
return new Promise(function (resolve, reject) {
fs.remove(targetDirectory, function (err) {
if (err) {
reject(new Error('copyDevelopmentThaliCordovaPluginToProject remove ' +
'failed with ' + err));
return;
}
console.log('Copying files from ' + sourceDirectory + ' to ' +
targetDirectory);
fs.copy(sourceDirectory, targetDirectory, function (err) {
if (err) {
reject(
new Error('copyDevelopmentThaliCordovaPluginToProject failed with' +
err));
return;
}
resolve(createGitHubZipResponse(depotName, branchName, thaliDontCheckIn,
true));
});
});
});
} | [
"function",
"copyDevelopmentThaliCordovaPluginToProject",
"(",
"appRootDirectory",
",",
"thaliDontCheckIn",
",",
"depotName",
",",
"branchName",
")",
"{",
"var",
"targetDirectory",
"=",
"createUnzippedDirectoryPath",
"(",
"depotName",
",",
"branchName",
",",
"thaliDontCheck... | This will copy the contents of a Thali_CordovaPlugin local depot to the right
directory in the current Cordova project so it will be installed. This is
used for local development only.
@param {string} appRootDirectory
@param {string} thaliDontCheckIn
@param {string} depotName
@param {string} branchName
@returns {Promise<Object|Error>} | [
"This",
"will",
"copy",
"the",
"contents",
"of",
"a",
"Thali_CordovaPlugin",
"local",
"depot",
"to",
"the",
"right",
"directory",
"in",
"the",
"current",
"Cordova",
"project",
"so",
"it",
"will",
"be",
"installed",
".",
"This",
"is",
"used",
"for",
"local",
... | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/install.js#L245-L275 |
32,362 | thaliproject/Thali_CordovaPlugin | thali/install/validateBuildEnvironment.js | checkVersion | function checkVersion(objectName, versionNumber) {
const desiredVersion = versionNumber ? versionNumber : versions[objectName];
const commandAndResult = commandsAndResults[objectName];
if (!commandAndResult) {
return Promise.reject(
new Error('Unrecognized objectName in commandsAndResults'));
}
if (!desiredVersion) {
return Promise.reject(new Error('Unrecognized objectName in versions'));
}
if (commandAndResult.platform &&
!commandAndResult.platform.includes(os.platform()))
{
return Promise.reject(new Error('Requested object is not supported on ' +
'this platform'));
}
if (typeof commandAndResult.versionCheck === 'function') {
return promiseTry(commandAndResult.versionCheck)
.catch(() =>
Promise.reject(new Error('Version Check failed on ' + objectName)))
.then((versionCheckResult) =>
commandAndResult.versionValidate(versionCheckResult, desiredVersion))
.then(() => Promise.resolve(true))
.catch(() => Promise.reject(
new Error('Version not installed of ' + objectName)));
}
return execAndCheck(commandAndResult.versionCheck,
commandAndResult.checkStdErr,
desiredVersion,
commandAndResult.versionValidate);
} | javascript | function checkVersion(objectName, versionNumber) {
const desiredVersion = versionNumber ? versionNumber : versions[objectName];
const commandAndResult = commandsAndResults[objectName];
if (!commandAndResult) {
return Promise.reject(
new Error('Unrecognized objectName in commandsAndResults'));
}
if (!desiredVersion) {
return Promise.reject(new Error('Unrecognized objectName in versions'));
}
if (commandAndResult.platform &&
!commandAndResult.platform.includes(os.platform()))
{
return Promise.reject(new Error('Requested object is not supported on ' +
'this platform'));
}
if (typeof commandAndResult.versionCheck === 'function') {
return promiseTry(commandAndResult.versionCheck)
.catch(() =>
Promise.reject(new Error('Version Check failed on ' + objectName)))
.then((versionCheckResult) =>
commandAndResult.versionValidate(versionCheckResult, desiredVersion))
.then(() => Promise.resolve(true))
.catch(() => Promise.reject(
new Error('Version not installed of ' + objectName)));
}
return execAndCheck(commandAndResult.versionCheck,
commandAndResult.checkStdErr,
desiredVersion,
commandAndResult.versionValidate);
} | [
"function",
"checkVersion",
"(",
"objectName",
",",
"versionNumber",
")",
"{",
"const",
"desiredVersion",
"=",
"versionNumber",
"?",
"versionNumber",
":",
"versions",
"[",
"objectName",
"]",
";",
"const",
"commandAndResult",
"=",
"commandsAndResults",
"[",
"objectNa... | Checks if the named object is installed with the named version, if any. If
versionNumber isn't given then we default to checking the versions global
object.
@param {string} objectName Name of the object to validate
@param {string} [versionNumber] An optional string specifying the desired
version. If omitted we will check the versions structure.
@returns {Promise<Error|boolean>} If the desired object is found at the
desired version then a resolve will be returned set to true. Otherwise an
error will be returned specifying what went wrong. | [
"Checks",
"if",
"the",
"named",
"object",
"is",
"installed",
"with",
"the",
"named",
"version",
"if",
"any",
".",
"If",
"versionNumber",
"isn",
"t",
"given",
"then",
"we",
"default",
"to",
"checking",
"the",
"versions",
"global",
"object",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/validateBuildEnvironment.js#L266-L296 |
32,363 | thaliproject/Thali_CordovaPlugin | thali/install/SSDPReplacer/hook.js | findFirstFile | function findFirstFile (name, rootDir) {
return new Promise(function (resolve, reject) {
var resultPath;
function end() {
if (resultPath) {
resolve(resultPath);
} else {
reject(new Error(
format('file is not found, name: \'%s\'', name)
));
}
}
var finder = findit(rootDir)
.on('file', function (path) {
// We can receive here 'path': 'a/b/my-file', 'a/b/bad-my-file',
// 'my-file', 'bad-my-file'.
// Both 'a/b/my-file' and 'my-file' should be valid.
if (path === name || endsWith(path, '/' + name)) {
resultPath = path;
finder.stop();
}
})
.on('error', function (error) {
reject(new Error(error));
})
.on('stop', end)
.on('end', end);
})
.catch(function (error) {
console.error(
'finder failed, error: \'%s\', stack: \'%s\'',
error.toString(), error.stack
);
return Promise.reject(error);
});
} | javascript | function findFirstFile (name, rootDir) {
return new Promise(function (resolve, reject) {
var resultPath;
function end() {
if (resultPath) {
resolve(resultPath);
} else {
reject(new Error(
format('file is not found, name: \'%s\'', name)
));
}
}
var finder = findit(rootDir)
.on('file', function (path) {
// We can receive here 'path': 'a/b/my-file', 'a/b/bad-my-file',
// 'my-file', 'bad-my-file'.
// Both 'a/b/my-file' and 'my-file' should be valid.
if (path === name || endsWith(path, '/' + name)) {
resultPath = path;
finder.stop();
}
})
.on('error', function (error) {
reject(new Error(error));
})
.on('stop', end)
.on('end', end);
})
.catch(function (error) {
console.error(
'finder failed, error: \'%s\', stack: \'%s\'',
error.toString(), error.stack
);
return Promise.reject(error);
});
} | [
"function",
"findFirstFile",
"(",
"name",
",",
"rootDir",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"resultPath",
";",
"function",
"end",
"(",
")",
"{",
"if",
"(",
"resultPath",
")",
"{",
"re... | We want to find the first path that ends with 'name'. | [
"We",
"want",
"to",
"find",
"the",
"first",
"path",
"that",
"ends",
"with",
"name",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/SSDPReplacer/hook.js#L28-L65 |
32,364 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/identityExchange/connectionTable.js | ConnectionTable | function ConnectionTable(thaliReplicationManager) {
EventEmitter.call(this);
var self = this;
this.thaliReplicationManager = thaliReplicationManager;
this.connectionTable = {};
this.connectionSuccessListener = function (successObject) {
self.connectionTable[successObject.peerIdentifier] = {
muxPort: successObject.muxPort,
time: Date.now()
};
self.emit(successObject.peerIdentifier, self.connectionTable[successObject.peerIdentifier]);
};
thaliReplicationManager.on(ThaliReplicationManager.events.CONNECTION_SUCCESS, this.connectionSuccessListener);
} | javascript | function ConnectionTable(thaliReplicationManager) {
EventEmitter.call(this);
var self = this;
this.thaliReplicationManager = thaliReplicationManager;
this.connectionTable = {};
this.connectionSuccessListener = function (successObject) {
self.connectionTable[successObject.peerIdentifier] = {
muxPort: successObject.muxPort,
time: Date.now()
};
self.emit(successObject.peerIdentifier, self.connectionTable[successObject.peerIdentifier]);
};
thaliReplicationManager.on(ThaliReplicationManager.events.CONNECTION_SUCCESS, this.connectionSuccessListener);
} | [
"function",
"ConnectionTable",
"(",
"thaliReplicationManager",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"thaliReplicationManager",
"=",
"thaliReplicationManager",
";",
"this",
".",
"connectionTable... | A temporary hack to collect connectionSuccess events. Once we put in ACLs we won't need this hack anymore.
@param thaliReplicationManager
@constructor | [
"A",
"temporary",
"hack",
"to",
"collect",
"connectionSuccess",
"events",
".",
"Once",
"we",
"put",
"in",
"ACLs",
"we",
"won",
"t",
"need",
"this",
"hack",
"anymore",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/identityExchange/connectionTable.js#L43-L57 |
32,365 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/thaliMobile.js | start | function start (router, pskIdToSecret, networkType) {
if (thaliMobileStates.started === true) {
return Promise.reject(new Error('Call Stop!'));
}
thaliMobileStates.started = true;
thaliMobileStates.networkType =
networkType || global.NETWORK_TYPE || thaliMobileStates.networkType;
return getWifiOrNativeMethodByNetworkType('start',
thaliMobileStates.networkType)(router, pskIdToSecret)
.then(function (result) {
if (result.wifiResult === null && result.nativeResult === null) {
return result;
}
return Promise.reject(result);
});
} | javascript | function start (router, pskIdToSecret, networkType) {
if (thaliMobileStates.started === true) {
return Promise.reject(new Error('Call Stop!'));
}
thaliMobileStates.started = true;
thaliMobileStates.networkType =
networkType || global.NETWORK_TYPE || thaliMobileStates.networkType;
return getWifiOrNativeMethodByNetworkType('start',
thaliMobileStates.networkType)(router, pskIdToSecret)
.then(function (result) {
if (result.wifiResult === null && result.nativeResult === null) {
return result;
}
return Promise.reject(result);
});
} | [
"function",
"start",
"(",
"router",
",",
"pskIdToSecret",
",",
"networkType",
")",
"{",
"if",
"(",
"thaliMobileStates",
".",
"started",
"===",
"true",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Call Stop!'",
")",
")",
";",
... | This object is our generic status wrapper that lets us return information
about both WiFi and Native.
@public
@typedef {Object} combinedResult
@property {?Error} wifiResult
@property {?Error} nativeResult | [
"This",
"object",
"is",
"our",
"generic",
"status",
"wrapper",
"that",
"lets",
"us",
"return",
"information",
"about",
"both",
"WiFi",
"and",
"Native",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/thaliMobile.js#L182-L198 |
32,366 | thaliproject/Thali_CordovaPlugin | thali/install/cordova-hooks/android/after_plugin_install.js | function (appRoot) {
var filePath = path.join(appRoot,
'platforms/android/src/io/jxcore/node/JXcoreExtension.java');
var content = fs.readFileSync(filePath, 'utf-8');
content = content.replace('lifeCycleMonitor.start();',
'lifeCycleMonitor.start();\n\t\tRegisterExecuteUT.Register();');
content = content.replace('package io.jxcore.node;',
'package io.jxcore.node;\nimport com.test.thalitest.RegisterExecuteUT;');
fs.writeFileSync(filePath, content, 'utf-8');
} | javascript | function (appRoot) {
var filePath = path.join(appRoot,
'platforms/android/src/io/jxcore/node/JXcoreExtension.java');
var content = fs.readFileSync(filePath, 'utf-8');
content = content.replace('lifeCycleMonitor.start();',
'lifeCycleMonitor.start();\n\t\tRegisterExecuteUT.Register();');
content = content.replace('package io.jxcore.node;',
'package io.jxcore.node;\nimport com.test.thalitest.RegisterExecuteUT;');
fs.writeFileSync(filePath, content, 'utf-8');
} | [
"function",
"(",
"appRoot",
")",
"{",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"appRoot",
",",
"'platforms/android/src/io/jxcore/node/JXcoreExtension.java'",
")",
";",
"var",
"content",
"=",
"fs",
".",
"readFileSync",
"(",
"filePath",
",",
"'utf-8'",
")... | Updates JXcoreExtension with a method which is used to register the native UT
executor. We are doing it because we don't want to mess our production code
with our test code so we create a function that dynamically adds method
executing tests only when we are actually testing.
@param {Object} appRoot | [
"Updates",
"JXcoreExtension",
"with",
"a",
"method",
"which",
"is",
"used",
"to",
"register",
"the",
"native",
"UT",
"executor",
".",
"We",
"are",
"doing",
"it",
"because",
"we",
"don",
"t",
"want",
"to",
"mess",
"our",
"production",
"code",
"with",
"our",... | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/install/cordova-hooks/android/after_plugin_install.js#L178-L188 | |
32,367 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/security/hkdf.js | HKDF | function HKDF(hashAlg, salt, ikm) {
if (!(this instanceof HKDF)) { return new HKDF(hashAlg, salt, ikm); }
this.hashAlg = hashAlg;
// create the hash alg to see if it exists and get its length
var hash = crypto.createHash(this.hashAlg);
this.hashLength = hash.digest().length;
this.salt = salt || zeros(this.hashLength);
this.ikm = ikm;
// now we compute the PRK
var hmac = crypto.createHmac(this.hashAlg, this.salt);
hmac.update(this.ikm);
this.prk = hmac.digest();
} | javascript | function HKDF(hashAlg, salt, ikm) {
if (!(this instanceof HKDF)) { return new HKDF(hashAlg, salt, ikm); }
this.hashAlg = hashAlg;
// create the hash alg to see if it exists and get its length
var hash = crypto.createHash(this.hashAlg);
this.hashLength = hash.digest().length;
this.salt = salt || zeros(this.hashLength);
this.ikm = ikm;
// now we compute the PRK
var hmac = crypto.createHmac(this.hashAlg, this.salt);
hmac.update(this.ikm);
this.prk = hmac.digest();
} | [
"function",
"HKDF",
"(",
"hashAlg",
",",
"salt",
",",
"ikm",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"HKDF",
")",
")",
"{",
"return",
"new",
"HKDF",
"(",
"hashAlg",
",",
"salt",
",",
"ikm",
")",
";",
"}",
"this",
".",
"hashAlg",
"=",... | ikm is initial keying material | [
"ikm",
"is",
"initial",
"keying",
"material"
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/security/hkdf.js#L32-L48 |
32,368 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/notification/thaliNotificationBeacons.js | createPublicKeyHash | function createPublicKeyHash (ecdhPublicKey) {
return crypto.createHash(module.exports.SHA256)
.update(ecdhPublicKey)
.digest()
.slice(0, 16);
} | javascript | function createPublicKeyHash (ecdhPublicKey) {
return crypto.createHash(module.exports.SHA256)
.update(ecdhPublicKey)
.digest()
.slice(0, 16);
} | [
"function",
"createPublicKeyHash",
"(",
"ecdhPublicKey",
")",
"{",
"return",
"crypto",
".",
"createHash",
"(",
"module",
".",
"exports",
".",
"SHA256",
")",
".",
"update",
"(",
"ecdhPublicKey",
")",
".",
"digest",
"(",
")",
".",
"slice",
"(",
"0",
",",
"... | Creates a 16 byte hash of a public key.
We choose 16 bytes as large enough to prevent accidentally collisions but
small enough not to eat up excess space in a beacon.
@param {Buffer} ecdhPublicKey The buffer representing the ECDH's public key.
@returns {Buffer} | [
"Creates",
"a",
"16",
"byte",
"hash",
"of",
"a",
"public",
"key",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L121-L126 |
32,369 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/notification/thaliNotificationBeacons.js | generatePreambleAndBeacons | function generatePreambleAndBeacons (publicKeysToNotify,
ecdhForLocalDevice,
millisecondsUntilExpiration) {
if (publicKeysToNotify == null) {
throw new Error('publicKeysToNotify cannot be null');
}
if (ecdhForLocalDevice == null) {
throw new Error('ecdhForLocalDevice cannot be null');
}
if (millisecondsUntilExpiration <= 0 ||
millisecondsUntilExpiration > module.exports.ONE_DAY) {
throw new Error('millisecondsUntilExpiration must be > 0 & < ' +
module.exports.ONE_DAY);
}
if (publicKeysToNotify.length === 0) { return null; }
var beacons = [];
var ke = crypto.createECDH(thaliConfig.BEACON_CURVE);
// Generate preamble
var pubKe = ke.generateKeys();
// We fuzz the expiration by adding on a random number that fits in
// an unsigned 8 bit integer.
var expiration = Date.now() + millisecondsUntilExpiration +
crypto.randomBytes(1).readUInt8(0);
var expirationLong = Long.fromNumber(expiration);
var expirationBuffer = new Buffer(module.exports.LONG_SIZE);
expirationBuffer.writeInt32BE(expirationLong.high, 0);
expirationBuffer.writeInt32BE(expirationLong.low, 4);
beacons.push(Buffer.concat([pubKe, expirationBuffer]));
// UnencryptedKeyId = SHA256(Kx.public().encode()).first(16)
var unencryptedKeyId =
createPublicKeyHash(ecdhForLocalDevice.getPublicKey());
publicKeysToNotify.forEach(function (pubKy) {
// Sxy = ECDH(Kx.private(), PubKy)
var sxy = ecdhForLocalDevice.computeSecret(pubKy);
// HKxy = HKDF(SHA256, Sxy, Expiration, 32)
var hkxy = HKDF(module.exports.SHA256, sxy, expirationBuffer)
.derive('', module.exports.SHA256_HMAC_KEY_SIZE);
// BeaconHmac = HMAC(SHA256, HKxy, Expiration).first(16)
var beaconHmac = crypto.createHmac(module.exports.SHA256, hkxy)
.update(expirationBuffer)
.digest()
.slice(0, module.exports.TRUNCATED_HASH_SIZE);
// Sey = ECDH(Ke.private(), PubKy)
var sey = ke.computeSecret(pubKy);
// hkey = HKDF(SHA256, Sey, Expiration, 16)
var hkey = HKDF(module.exports.SHA256, sey, expirationBuffer)
.derive('', module.exports.AES_128_KEY_SIZE);
// beacons.append(AESEncrypt(GCM, HKey, 0, 128, UnencryptedKeyId) +
// BeaconHmac)
var aes = crypto.createCipher(module.exports.GCM, hkey);
beacons.push(Buffer.concat([
Buffer.concat([aes.update(unencryptedKeyId), aes.final()]),
beaconHmac
]));
});
return Buffer.concat(beacons);
} | javascript | function generatePreambleAndBeacons (publicKeysToNotify,
ecdhForLocalDevice,
millisecondsUntilExpiration) {
if (publicKeysToNotify == null) {
throw new Error('publicKeysToNotify cannot be null');
}
if (ecdhForLocalDevice == null) {
throw new Error('ecdhForLocalDevice cannot be null');
}
if (millisecondsUntilExpiration <= 0 ||
millisecondsUntilExpiration > module.exports.ONE_DAY) {
throw new Error('millisecondsUntilExpiration must be > 0 & < ' +
module.exports.ONE_DAY);
}
if (publicKeysToNotify.length === 0) { return null; }
var beacons = [];
var ke = crypto.createECDH(thaliConfig.BEACON_CURVE);
// Generate preamble
var pubKe = ke.generateKeys();
// We fuzz the expiration by adding on a random number that fits in
// an unsigned 8 bit integer.
var expiration = Date.now() + millisecondsUntilExpiration +
crypto.randomBytes(1).readUInt8(0);
var expirationLong = Long.fromNumber(expiration);
var expirationBuffer = new Buffer(module.exports.LONG_SIZE);
expirationBuffer.writeInt32BE(expirationLong.high, 0);
expirationBuffer.writeInt32BE(expirationLong.low, 4);
beacons.push(Buffer.concat([pubKe, expirationBuffer]));
// UnencryptedKeyId = SHA256(Kx.public().encode()).first(16)
var unencryptedKeyId =
createPublicKeyHash(ecdhForLocalDevice.getPublicKey());
publicKeysToNotify.forEach(function (pubKy) {
// Sxy = ECDH(Kx.private(), PubKy)
var sxy = ecdhForLocalDevice.computeSecret(pubKy);
// HKxy = HKDF(SHA256, Sxy, Expiration, 32)
var hkxy = HKDF(module.exports.SHA256, sxy, expirationBuffer)
.derive('', module.exports.SHA256_HMAC_KEY_SIZE);
// BeaconHmac = HMAC(SHA256, HKxy, Expiration).first(16)
var beaconHmac = crypto.createHmac(module.exports.SHA256, hkxy)
.update(expirationBuffer)
.digest()
.slice(0, module.exports.TRUNCATED_HASH_SIZE);
// Sey = ECDH(Ke.private(), PubKy)
var sey = ke.computeSecret(pubKy);
// hkey = HKDF(SHA256, Sey, Expiration, 16)
var hkey = HKDF(module.exports.SHA256, sey, expirationBuffer)
.derive('', module.exports.AES_128_KEY_SIZE);
// beacons.append(AESEncrypt(GCM, HKey, 0, 128, UnencryptedKeyId) +
// BeaconHmac)
var aes = crypto.createCipher(module.exports.GCM, hkey);
beacons.push(Buffer.concat([
Buffer.concat([aes.update(unencryptedKeyId), aes.final()]),
beaconHmac
]));
});
return Buffer.concat(beacons);
} | [
"function",
"generatePreambleAndBeacons",
"(",
"publicKeysToNotify",
",",
"ecdhForLocalDevice",
",",
"millisecondsUntilExpiration",
")",
"{",
"if",
"(",
"publicKeysToNotify",
"==",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'publicKeysToNotify cannot be null'",
")",... | This function will generate a buffer containing the notification preamble and
beacons for the given set of public keys using the supplied private key and
set to the specified seconds until expiration.
@param {Buffer[]} publicKeysToNotify - An array of buffers holding ECDH
public keys.
@param {ECDH} ecdhForLocalDevice - A Crypto.ECDH object initialized with the
local device's public and private keys
@param {number} millisecondsUntilExpiration - The number of milliseconds into
the future after which the beacons should expire. Note that this value will
be fuzzed as previously described.
@returns {?Buffer} - A buffer containing the serialized preamble and beacons
or null if there are no beacons to generate | [
"This",
"function",
"will",
"generate",
"a",
"buffer",
"containing",
"the",
"notification",
"preamble",
"and",
"beacons",
"for",
"the",
"given",
"set",
"of",
"public",
"keys",
"using",
"the",
"supplied",
"private",
"key",
"and",
"set",
"to",
"the",
"specified"... | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L144-L216 |
32,370 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/notification/thaliNotificationBeacons.js | generatePskSecret | function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey,
pskIdentityField) {
var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey);
return HKDF(module.exports.SHA256, sxy, pskIdentityField)
.derive('', module.exports.AES_256_KEY_SIZE);
} | javascript | function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey,
pskIdentityField) {
var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey);
return HKDF(module.exports.SHA256, sxy, pskIdentityField)
.derive('', module.exports.AES_256_KEY_SIZE);
} | [
"function",
"generatePskSecret",
"(",
"ecdhForLocalDevice",
",",
"remotePeerPublicKey",
",",
"pskIdentityField",
")",
"{",
"var",
"sxy",
"=",
"ecdhForLocalDevice",
".",
"computeSecret",
"(",
"remotePeerPublicKey",
")",
";",
"return",
"HKDF",
"(",
"module",
".",
"exp... | Generates a PSK secret between the local device and a remote peer.
@param {ECDH} ecdhForLocalDevice
@param {Buffer} remotePeerPublicKey
@param {string} pskIdentityField
@returns {Buffer} | [
"Generates",
"a",
"PSK",
"secret",
"between",
"the",
"local",
"device",
"and",
"a",
"remote",
"peer",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L406-L411 |
32,371 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/notification/thaliNotificationBeacons.js | generatePskSecrets | function generatePskSecrets(publicKeysToNotify,
ecdhForLocalDevice,
beaconStreamWithPreAmble) {
var preAmbleSizeInBytes = module.exports.PUBLIC_KEY_SIZE +
module.exports.EXPIRATION_SIZE;
var preAmble = beaconStreamWithPreAmble.slice(0, preAmbleSizeInBytes);
var beaconStreamNoPreAmble =
beaconStreamWithPreAmble.slice(preAmbleSizeInBytes);
var beacons = [];
for (var i = 0; i < beaconStreamNoPreAmble.length;
i += module.exports.BEACON_SIZE) {
beacons.push(
beaconStreamNoPreAmble.slice(i, i + module.exports.BEACON_SIZE));
}
assert(beacons.length === publicKeysToNotify.length, 'We should have the' +
'same number of beacons as public keys to notify');
var pskMap = {};
for (i = 0; i < publicKeysToNotify.length; ++i) {
var pskIdentityField = generatePskIdentityField(preAmble, beacons[i]);
var pskSecret = generatePskSecret(ecdhForLocalDevice, publicKeysToNotify[i],
pskIdentityField);
pskMap[pskIdentityField] = {
publicKey: publicKeysToNotify[i],
pskSecret: pskSecret
};
}
return pskMap;
} | javascript | function generatePskSecrets(publicKeysToNotify,
ecdhForLocalDevice,
beaconStreamWithPreAmble) {
var preAmbleSizeInBytes = module.exports.PUBLIC_KEY_SIZE +
module.exports.EXPIRATION_SIZE;
var preAmble = beaconStreamWithPreAmble.slice(0, preAmbleSizeInBytes);
var beaconStreamNoPreAmble =
beaconStreamWithPreAmble.slice(preAmbleSizeInBytes);
var beacons = [];
for (var i = 0; i < beaconStreamNoPreAmble.length;
i += module.exports.BEACON_SIZE) {
beacons.push(
beaconStreamNoPreAmble.slice(i, i + module.exports.BEACON_SIZE));
}
assert(beacons.length === publicKeysToNotify.length, 'We should have the' +
'same number of beacons as public keys to notify');
var pskMap = {};
for (i = 0; i < publicKeysToNotify.length; ++i) {
var pskIdentityField = generatePskIdentityField(preAmble, beacons[i]);
var pskSecret = generatePskSecret(ecdhForLocalDevice, publicKeysToNotify[i],
pskIdentityField);
pskMap[pskIdentityField] = {
publicKey: publicKeysToNotify[i],
pskSecret: pskSecret
};
}
return pskMap;
} | [
"function",
"generatePskSecrets",
"(",
"publicKeysToNotify",
",",
"ecdhForLocalDevice",
",",
"beaconStreamWithPreAmble",
")",
"{",
"var",
"preAmbleSizeInBytes",
"=",
"module",
".",
"exports",
".",
"PUBLIC_KEY_SIZE",
"+",
"module",
".",
"exports",
".",
"EXPIRATION_SIZE",... | A dictionary whose key is the identity string sent over TLS and whose
value is a keyAndSecret specifying what publicKey this identity is associated
with and what secret it needs to provide.
@public
@typedef {Object.<string, keyAndSecret>} pskMap
This function takes a list of public keys and the device's ECDH private key
along with a beacon stream with preamble that was generated using those
public keys. The function requires that the beacon values in the beacon
stream MUST be in the same order as the keys listed in the publicKeysToNotify
array.
The code will then generate Sxy as given in http://thaliproject.org/PresenceProtocolBindings/#transferring-from-notification-beacon-to-tls
and then feed that to HKDF using the the PSKIdentity value which is defined
in the above as the pre-amble plus the individual beacon value for the
associated public key. This means we have to parse the beacon stream to
pull out the preamble along with the specific associated beacon and then
combine them together into a single buffer that is then base64'd using
the URL safe base64 scheme. This is then fed to HKDF as defined in the
link above which produces the value that will be used as the secret.
This function will then wrap up all of this into a dictionary whose key
is the base64 url safe'd pre-amble + beacon value and who value is the
secret along with the associated publicKey.
@param {Buffer[]} publicKeysToNotify - An array of buffers holding ECDH
public keys.
@param {ECDH} ecdhForLocalDevice - A Crypto.ECDH object initialized with the
local device's public and private keys
@param {Buffer} beaconStreamWithPreAmble - A buffer stream containing the
preamble and beacons
@returns {pskMap|Error} | [
"A",
"dictionary",
"whose",
"key",
"is",
"the",
"identity",
"string",
"sent",
"over",
"TLS",
"and",
"whose",
"value",
"is",
"a",
"keyAndSecret",
"specifying",
"what",
"publicKey",
"this",
"identity",
"is",
"associated",
"with",
"and",
"what",
"secret",
"it",
... | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/notification/thaliNotificationBeacons.js#L461-L492 |
32,372 | thaliproject/Thali_CordovaPlugin | thali/NextGeneration/thaliPeerPool/thaliPeerAction.js | PeerAction | function PeerAction (peerIdentifier, connectionType, actionType, pskIdentity,
pskKey)
{
EventEmitter.call(this);
this._peerIdentifier = peerIdentifier;
this._connectionType = connectionType;
this._actionType = actionType;
this._pskIdentity = pskIdentity;
this._pskKey = pskKey;
this._actionState = PeerAction.actionState.CREATED;
this._id = peerActionCounter;
++peerActionCounter;
} | javascript | function PeerAction (peerIdentifier, connectionType, actionType, pskIdentity,
pskKey)
{
EventEmitter.call(this);
this._peerIdentifier = peerIdentifier;
this._connectionType = connectionType;
this._actionType = actionType;
this._pskIdentity = pskIdentity;
this._pskKey = pskKey;
this._actionState = PeerAction.actionState.CREATED;
this._id = peerActionCounter;
++peerActionCounter;
} | [
"function",
"PeerAction",
"(",
"peerIdentifier",
",",
"connectionType",
",",
"actionType",
",",
"pskIdentity",
",",
"pskKey",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_peerIdentifier",
"=",
"peerIdentifier",
";",
"this",
".",... | This event is emitted synchronously when action state is changed to KILLED.
@event killed
@public
An action that has been given to the pool to manage.
When an action is created its state MUST be CREATED.
BugBug: In a sane world we would have limits on how long an action can run
and we would even set up those limits as a config item. But for now we let
each action own the stage for as long as it would like.
@public
@interface PeerAction
@constructor
@fires event:killed
@fires event:started
@param {string} peerIdentifier
@param {module:ThaliMobileNativeWrapper.connectionTypes} connectionType
@param {string} actionType
@param {string} pskIdentity
@param {Buffer} pskKey | [
"This",
"event",
"is",
"emitted",
"synchronously",
"when",
"action",
"state",
"is",
"changed",
"to",
"KILLED",
"."
] | 0496da88a125a871d2ebff39359fbbf8ba01fd8f | https://github.com/thaliproject/Thali_CordovaPlugin/blob/0496da88a125a871d2ebff39359fbbf8ba01fd8f/thali/NextGeneration/thaliPeerPool/thaliPeerAction.js#L55-L67 |
32,373 | PeculiarVentures/xadesjs | examples/html/src/helper.js | BrowserInfo | function BrowserInfo() {
var res = {
name: "",
version: ""
};
var userAgent = self.navigator.userAgent;
var reg;
if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) {
res.name = Browser.Edge;
res.version = reg[1];
}
else if (/msie/i.test(userAgent)) {
res.name = Browser.IE;
res.version = /msie ([\d\.]+)/i.exec(userAgent)[1];
}
else if (/Trident/i.test(userAgent)) {
res.name = Browser.IE;
res.version = /rv:([\d\.]+)/i.exec(userAgent)[1];
}
else if (/chrome/i.test(userAgent)) {
res.name = Browser.Chrome;
res.version = /chrome\/([\d\.]+)/i.exec(userAgent)[1];
}
else if (/safari/i.test(userAgent)) {
res.name = Browser.Safari;
res.version = /([\d\.]+) safari/i.exec(userAgent)[1];
}
else if (/firefox/i.test(userAgent)) {
res.name = Browser.Firefox;
res.version = /firefox\/([\d\.]+)/i.exec(userAgent)[1];
}
return res;
} | javascript | function BrowserInfo() {
var res = {
name: "",
version: ""
};
var userAgent = self.navigator.userAgent;
var reg;
if (reg = /edge\/([\d\.]+)/i.exec(userAgent)) {
res.name = Browser.Edge;
res.version = reg[1];
}
else if (/msie/i.test(userAgent)) {
res.name = Browser.IE;
res.version = /msie ([\d\.]+)/i.exec(userAgent)[1];
}
else if (/Trident/i.test(userAgent)) {
res.name = Browser.IE;
res.version = /rv:([\d\.]+)/i.exec(userAgent)[1];
}
else if (/chrome/i.test(userAgent)) {
res.name = Browser.Chrome;
res.version = /chrome\/([\d\.]+)/i.exec(userAgent)[1];
}
else if (/safari/i.test(userAgent)) {
res.name = Browser.Safari;
res.version = /([\d\.]+) safari/i.exec(userAgent)[1];
}
else if (/firefox/i.test(userAgent)) {
res.name = Browser.Firefox;
res.version = /firefox\/([\d\.]+)/i.exec(userAgent)[1];
}
return res;
} | [
"function",
"BrowserInfo",
"(",
")",
"{",
"var",
"res",
"=",
"{",
"name",
":",
"\"\"",
",",
"version",
":",
"\"\"",
"}",
";",
"var",
"userAgent",
"=",
"self",
".",
"navigator",
".",
"userAgent",
";",
"var",
"reg",
";",
"if",
"(",
"reg",
"=",
"/",
... | Returns info about browser | [
"Returns",
"info",
"about",
"browser"
] | c35e3895868bdcfb52e2b29685efc50c877cd1f1 | https://github.com/PeculiarVentures/xadesjs/blob/c35e3895868bdcfb52e2b29685efc50c877cd1f1/examples/html/src/helper.js#L11-L43 |
32,374 | freeCodeCamp/curriculum | unpack.js | createUnpackedBundle | function createUnpackedBundle() {
fs.mkdirp(unpackedDir, err => {
if (err && err.code !== 'EEXIST') {
console.log(err);
throw err;
}
let unpackedFile = path.join(__dirname, 'unpacked.js');
let b = browserify(unpackedFile).bundle();
b.on('error', console.error);
let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js');
const bundleFileStream = fs.createWriteStream(unpackedBundleFile);
bundleFileStream.on('finish', () => {
console.log('Wrote bundled JS into ' + unpackedBundleFile);
});
bundleFileStream.on('pipe', () => {
console.log('Writing bundled JS...');
});
bundleFileStream.on('error', console.error);
b.pipe(bundleFileStream);
// bundleFileStream.end(); // do not do this prematurely!
});
} | javascript | function createUnpackedBundle() {
fs.mkdirp(unpackedDir, err => {
if (err && err.code !== 'EEXIST') {
console.log(err);
throw err;
}
let unpackedFile = path.join(__dirname, 'unpacked.js');
let b = browserify(unpackedFile).bundle();
b.on('error', console.error);
let unpackedBundleFile = path.join(unpackedDir, 'unpacked-bundle.js');
const bundleFileStream = fs.createWriteStream(unpackedBundleFile);
bundleFileStream.on('finish', () => {
console.log('Wrote bundled JS into ' + unpackedBundleFile);
});
bundleFileStream.on('pipe', () => {
console.log('Writing bundled JS...');
});
bundleFileStream.on('error', console.error);
b.pipe(bundleFileStream);
// bundleFileStream.end(); // do not do this prematurely!
});
} | [
"function",
"createUnpackedBundle",
"(",
")",
"{",
"fs",
".",
"mkdirp",
"(",
"unpackedDir",
",",
"err",
"=>",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"'EEXIST'",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"throw",
"err",
... | bundle up the test-running JS | [
"bundle",
"up",
"the",
"test",
"-",
"running",
"JS"
] | 9c5686cbb700fb7c1443aee81592096f3c61b944 | https://github.com/freeCodeCamp/curriculum/blob/9c5686cbb700fb7c1443aee81592096f3c61b944/unpack.js#L20-L42 |
32,375 | jorgebay/node-cassandra-cql | lib/types.js | function (query, params, stringifier) {
if (!query || !query.length || !params) {
return query;
}
if (!stringifier) {
stringifier = function (a) {return a.toString()};
}
var parts = [];
var isLiteral = false;
var lastIndex = 0;
var paramsCounter = 0;
for (var i = 0; i < query.length; i++) {
var char = query.charAt(i);
if (char === "'" && query.charAt(i-1) !== '\\') {
//opening or closing quotes in a literal value of the query
isLiteral = !isLiteral;
}
if (!isLiteral && char === '?') {
//is a placeholder
parts.push(query.substring(lastIndex, i));
parts.push(stringifier(params[paramsCounter++]));
lastIndex = i+1;
}
}
parts.push(query.substring(lastIndex));
return parts.join('');
} | javascript | function (query, params, stringifier) {
if (!query || !query.length || !params) {
return query;
}
if (!stringifier) {
stringifier = function (a) {return a.toString()};
}
var parts = [];
var isLiteral = false;
var lastIndex = 0;
var paramsCounter = 0;
for (var i = 0; i < query.length; i++) {
var char = query.charAt(i);
if (char === "'" && query.charAt(i-1) !== '\\') {
//opening or closing quotes in a literal value of the query
isLiteral = !isLiteral;
}
if (!isLiteral && char === '?') {
//is a placeholder
parts.push(query.substring(lastIndex, i));
parts.push(stringifier(params[paramsCounter++]));
lastIndex = i+1;
}
}
parts.push(query.substring(lastIndex));
return parts.join('');
} | [
"function",
"(",
"query",
",",
"params",
",",
"stringifier",
")",
"{",
"if",
"(",
"!",
"query",
"||",
"!",
"query",
".",
"length",
"||",
"!",
"params",
")",
"{",
"return",
"query",
";",
"}",
"if",
"(",
"!",
"stringifier",
")",
"{",
"stringifier",
"... | Replaced the query place holders with the stringified value
@param {String} query
@param {Array} params
@param {Function} stringifier | [
"Replaced",
"the",
"query",
"place",
"holders",
"with",
"the",
"stringified",
"value"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L105-L131 | |
32,376 | jorgebay/node-cassandra-cql | lib/types.js | FrameHeader | function FrameHeader(values) {
if (values) {
if (values instanceof Buffer) {
this.fromBuffer(values);
}
else {
for (var prop in values) {
this[prop] = values[prop];
}
}
}
} | javascript | function FrameHeader(values) {
if (values) {
if (values instanceof Buffer) {
this.fromBuffer(values);
}
else {
for (var prop in values) {
this[prop] = values[prop];
}
}
}
} | [
"function",
"FrameHeader",
"(",
"values",
")",
"{",
"if",
"(",
"values",
")",
"{",
"if",
"(",
"values",
"instanceof",
"Buffer",
")",
"{",
"this",
".",
"fromBuffer",
"(",
"values",
")",
";",
"}",
"else",
"{",
"for",
"(",
"var",
"prop",
"in",
"values",... | classes
Represents a frame header that could be used to read from a Buffer or to write to a Buffer | [
"classes",
"Represents",
"a",
"frame",
"header",
"that",
"could",
"be",
"used",
"to",
"read",
"from",
"a",
"Buffer",
"or",
"to",
"write",
"to",
"a",
"Buffer"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L187-L198 |
32,377 | jorgebay/node-cassandra-cql | lib/types.js | QueueWhile | function QueueWhile(test, delayRetry) {
this.queue = async.queue(function (task, queueCallback) {
async.whilst(
test,
function(cb) {
//Retry in a while
if (delayRetry) {
setTimeout(cb, delayRetry);
}
else {
setImmediate(cb);
}
},
function() {
queueCallback(null, null);
}
);
}, 1);
} | javascript | function QueueWhile(test, delayRetry) {
this.queue = async.queue(function (task, queueCallback) {
async.whilst(
test,
function(cb) {
//Retry in a while
if (delayRetry) {
setTimeout(cb, delayRetry);
}
else {
setImmediate(cb);
}
},
function() {
queueCallback(null, null);
}
);
}, 1);
} | [
"function",
"QueueWhile",
"(",
"test",
",",
"delayRetry",
")",
"{",
"this",
".",
"queue",
"=",
"async",
".",
"queue",
"(",
"function",
"(",
"task",
",",
"queueCallback",
")",
"{",
"async",
".",
"whilst",
"(",
"test",
",",
"function",
"(",
"cb",
")",
... | Queues callbacks while the condition tests true. Similar behaviour as async.whilst. | [
"Queues",
"callbacks",
"while",
"the",
"condition",
"tests",
"true",
".",
"Similar",
"behaviour",
"as",
"async",
".",
"whilst",
"."
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L277-L295 |
32,378 | jorgebay/node-cassandra-cql | lib/types.js | DriverError | function DriverError (message, constructor) {
if (constructor) {
Error.captureStackTrace(this, constructor);
this.name = constructor.name;
}
this.message = message || 'Error';
this.info = 'Cassandra Driver Error';
} | javascript | function DriverError (message, constructor) {
if (constructor) {
Error.captureStackTrace(this, constructor);
this.name = constructor.name;
}
this.message = message || 'Error';
this.info = 'Cassandra Driver Error';
} | [
"function",
"DriverError",
"(",
"message",
",",
"constructor",
")",
"{",
"if",
"(",
"constructor",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"constructor",
")",
";",
"this",
".",
"name",
"=",
"constructor",
".",
"name",
";",
"}",
"th... | error classes
Base Error | [
"error",
"classes",
"Base",
"Error"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/types.js#L356-L363 |
32,379 | jorgebay/node-cassandra-cql | lib/utils.js | copyBuffer | function copyBuffer(buf) {
var targetBuffer = new Buffer(buf.length);
buf.copy(targetBuffer);
return targetBuffer;
} | javascript | function copyBuffer(buf) {
var targetBuffer = new Buffer(buf.length);
buf.copy(targetBuffer);
return targetBuffer;
} | [
"function",
"copyBuffer",
"(",
"buf",
")",
"{",
"var",
"targetBuffer",
"=",
"new",
"Buffer",
"(",
"buf",
".",
"length",
")",
";",
"buf",
".",
"copy",
"(",
"targetBuffer",
")",
";",
"return",
"targetBuffer",
";",
"}"
] | Creates a copy of a buffer | [
"Creates",
"a",
"copy",
"of",
"a",
"buffer"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/utils.js#L5-L9 |
32,380 | jorgebay/node-cassandra-cql | lib/utils.js | totalLength | function totalLength (arr) {
if (!arr) {
return 0;
}
var total = 0;
arr.forEach(function (item) {
var length = item.length;
length = length ? length : 0;
total += length;
});
return total;
} | javascript | function totalLength (arr) {
if (!arr) {
return 0;
}
var total = 0;
arr.forEach(function (item) {
var length = item.length;
length = length ? length : 0;
total += length;
});
return total;
} | [
"function",
"totalLength",
"(",
"arr",
")",
"{",
"if",
"(",
"!",
"arr",
")",
"{",
"return",
"0",
";",
"}",
"var",
"total",
"=",
"0",
";",
"arr",
".",
"forEach",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"length",
"=",
"item",
".",
"length",
... | Gets the sum of the length of the items of an array | [
"Gets",
"the",
"sum",
"of",
"the",
"length",
"of",
"the",
"items",
"of",
"an",
"array"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/utils.js#L22-L33 |
32,381 | jorgebay/node-cassandra-cql | index.js | Client | function Client(options) {
events.EventEmitter.call(this);
//Unlimited amount of listeners for internal event queues by default
this.setMaxListeners(0);
this.options = utils.extend({}, optionsDefault, options);
//current connection index
this.connectionIndex = 0;
//current connection index for prepared queries
this.prepareConnectionIndex = 0;
this.preparedQueries = {};
this._createPool();
} | javascript | function Client(options) {
events.EventEmitter.call(this);
//Unlimited amount of listeners for internal event queues by default
this.setMaxListeners(0);
this.options = utils.extend({}, optionsDefault, options);
//current connection index
this.connectionIndex = 0;
//current connection index for prepared queries
this.prepareConnectionIndex = 0;
this.preparedQueries = {};
this._createPool();
} | [
"function",
"Client",
"(",
"options",
")",
"{",
"events",
".",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"//Unlimited amount of listeners for internal event queues by default",
"this",
".",
"setMaxListeners",
"(",
"0",
")",
";",
"this",
".",
"options",
"... | Represents a pool of connection to multiple hosts | [
"Represents",
"a",
"pool",
"of",
"connection",
"to",
"multiple",
"hosts"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/index.js#L24-L36 |
32,382 | jorgebay/node-cassandra-cql | lib/writers.js | BatchWriter | function BatchWriter(queries, consistency, options) {
this.queries = queries;
options = utils.extend({atomic: true}, options);
this.type = options.atomic ? 0 : 1;
this.type = options.counter ? 2 : this.type;
this.consistency = consistency;
this.streamId = null;
if (consistency === null || typeof consistency === 'undefined') {
this.consistency = types.consistencies.getDefault();
}
} | javascript | function BatchWriter(queries, consistency, options) {
this.queries = queries;
options = utils.extend({atomic: true}, options);
this.type = options.atomic ? 0 : 1;
this.type = options.counter ? 2 : this.type;
this.consistency = consistency;
this.streamId = null;
if (consistency === null || typeof consistency === 'undefined') {
this.consistency = types.consistencies.getDefault();
}
} | [
"function",
"BatchWriter",
"(",
"queries",
",",
"consistency",
",",
"options",
")",
"{",
"this",
".",
"queries",
"=",
"queries",
";",
"options",
"=",
"utils",
".",
"extend",
"(",
"{",
"atomic",
":",
"true",
"}",
",",
"options",
")",
";",
"this",
".",
... | Writes a batch request
@param {Array} queries Array of objects with the properties query and params
@constructor | [
"Writes",
"a",
"batch",
"request"
] | 2136de4cdde4219f9b4ba754a8f0c043077a83f2 | https://github.com/jorgebay/node-cassandra-cql/blob/2136de4cdde4219f9b4ba754a8f0c043077a83f2/lib/writers.js#L266-L276 |
32,383 | silvermine/videojs-quality-selector | src/js/components/QualitySelector.js | function(source) {
var src = (source ? source.src : undefined);
if (this.selectedSrc !== src) {
this.selectedSrc = src;
this.update();
}
} | javascript | function(source) {
var src = (source ? source.src : undefined);
if (this.selectedSrc !== src) {
this.selectedSrc = src;
this.update();
}
} | [
"function",
"(",
"source",
")",
"{",
"var",
"src",
"=",
"(",
"source",
"?",
"source",
".",
"src",
":",
"undefined",
")",
";",
"if",
"(",
"this",
".",
"selectedSrc",
"!==",
"src",
")",
"{",
"this",
".",
"selectedSrc",
"=",
"src",
";",
"this",
".",
... | Updates the source that is selected in the menu
@param source {object} player source to display as selected | [
"Updates",
"the",
"source",
"that",
"is",
"selected",
"in",
"the",
"menu"
] | 57ab38e9118c6a4661835fe9fa38c2ee03efebb2 | https://github.com/silvermine/videojs-quality-selector/blob/57ab38e9118c6a4661835fe9fa38c2ee03efebb2/src/js/components/QualitySelector.js#L57-L64 | |
32,384 | Hypercubed/svgsaver | lib/svgsaver.js | cloneSvg | function cloneSvg(src, attrs, styles) {
var clonedSvg = src.cloneNode(true);
domWalk(src, clonedSvg, function (src, tgt) {
if (tgt.style) {
(0, _computedStyles2['default'])(src, tgt.style, styles);
}
}, function (src, tgt) {
if (tgt.style && tgt.parentNode) {
cleanStyle(tgt);
}
if (tgt.attributes) {
cleanAttrs(tgt, attrs, styles);
}
});
return clonedSvg;
} | javascript | function cloneSvg(src, attrs, styles) {
var clonedSvg = src.cloneNode(true);
domWalk(src, clonedSvg, function (src, tgt) {
if (tgt.style) {
(0, _computedStyles2['default'])(src, tgt.style, styles);
}
}, function (src, tgt) {
if (tgt.style && tgt.parentNode) {
cleanStyle(tgt);
}
if (tgt.attributes) {
cleanAttrs(tgt, attrs, styles);
}
});
return clonedSvg;
} | [
"function",
"cloneSvg",
"(",
"src",
",",
"attrs",
",",
"styles",
")",
"{",
"var",
"clonedSvg",
"=",
"src",
".",
"cloneNode",
"(",
"true",
")",
";",
"domWalk",
"(",
"src",
",",
"clonedSvg",
",",
"function",
"(",
"src",
",",
"tgt",
")",
"{",
"if",
"(... | Clones an SVGElement, copies approprate atttributes and styles. | [
"Clones",
"an",
"SVGElement",
"copies",
"approprate",
"atttributes",
"and",
"styles",
"."
] | aa4a9f270629acdba35cd1b4fea57122c7dba45f | https://github.com/Hypercubed/svgsaver/blob/aa4a9f270629acdba35cd1b4fea57122c7dba45f/lib/svgsaver.js#L163-L180 |
32,385 | Hypercubed/svgsaver | src/clonesvg.js | cleanAttrs | function cleanAttrs (el, attrs, styles) { // attrs === false - remove all, attrs === true - allow all
if (attrs === true) { return; }
Array.prototype.slice.call(el.attributes)
.forEach(function (attr) {
// remove if it is not style nor on attrs whitelist
// keeping attributes that are also styles because attributes override
if (attr.specified) {
if (attrs === '' || attrs === false || (isUndefined(styles[attr.name]) && attrs.indexOf(attr.name) < 0)) {
el.removeAttribute(attr.name);
}
}
});
} | javascript | function cleanAttrs (el, attrs, styles) { // attrs === false - remove all, attrs === true - allow all
if (attrs === true) { return; }
Array.prototype.slice.call(el.attributes)
.forEach(function (attr) {
// remove if it is not style nor on attrs whitelist
// keeping attributes that are also styles because attributes override
if (attr.specified) {
if (attrs === '' || attrs === false || (isUndefined(styles[attr.name]) && attrs.indexOf(attr.name) < 0)) {
el.removeAttribute(attr.name);
}
}
});
} | [
"function",
"cleanAttrs",
"(",
"el",
",",
"attrs",
",",
"styles",
")",
"{",
"// attrs === false - remove all, attrs === true - allow all",
"if",
"(",
"attrs",
"===",
"true",
")",
"{",
"return",
";",
"}",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(... | Removes attributes that are not valid for SVGs | [
"Removes",
"attributes",
"that",
"are",
"not",
"valid",
"for",
"SVGs"
] | aa4a9f270629acdba35cd1b4fea57122c7dba45f | https://github.com/Hypercubed/svgsaver/blob/aa4a9f270629acdba35cd1b4fea57122c7dba45f/src/clonesvg.js#L7-L20 |
32,386 | custom-select/custom-select | src/index.js | setFocusedElement | function setFocusedElement(cstOption) {
if (focusedElement) {
focusedElement.classList.remove(builderParams.hasFocusClass);
}
if (typeof cstOption !== 'undefined') {
focusedElement = cstOption;
focusedElement.classList.add(builderParams.hasFocusClass);
// Offset update: checks if the focused element is in the visible part of the panelClass
// if not dispatches a custom event
if (isOpen) {
if (cstOption.offsetTop < cstOption.offsetParent.scrollTop
|| cstOption.offsetTop >
(cstOption.offsetParent.scrollTop + cstOption.offsetParent.clientHeight)
- cstOption.clientHeight) {
cstOption.dispatchEvent(new CustomEvent('custom-select:focus-outside-panel', { bubbles: true }));
}
}
} else {
focusedElement = undefined;
}
} | javascript | function setFocusedElement(cstOption) {
if (focusedElement) {
focusedElement.classList.remove(builderParams.hasFocusClass);
}
if (typeof cstOption !== 'undefined') {
focusedElement = cstOption;
focusedElement.classList.add(builderParams.hasFocusClass);
// Offset update: checks if the focused element is in the visible part of the panelClass
// if not dispatches a custom event
if (isOpen) {
if (cstOption.offsetTop < cstOption.offsetParent.scrollTop
|| cstOption.offsetTop >
(cstOption.offsetParent.scrollTop + cstOption.offsetParent.clientHeight)
- cstOption.clientHeight) {
cstOption.dispatchEvent(new CustomEvent('custom-select:focus-outside-panel', { bubbles: true }));
}
}
} else {
focusedElement = undefined;
}
} | [
"function",
"setFocusedElement",
"(",
"cstOption",
")",
"{",
"if",
"(",
"focusedElement",
")",
"{",
"focusedElement",
".",
"classList",
".",
"remove",
"(",
"builderParams",
".",
"hasFocusClass",
")",
";",
"}",
"if",
"(",
"typeof",
"cstOption",
"!==",
"'undefin... | Inner Functions Sets the focused element with the neccessary classes substitutions | [
"Inner",
"Functions",
"Sets",
"the",
"focused",
"element",
"with",
"the",
"neccessary",
"classes",
"substitutions"
] | 388f40c79355eb38fea64dfc7834970edf020cb4 | https://github.com/custom-select/custom-select/blob/388f40c79355eb38fea64dfc7834970edf020cb4/src/index.js#L47-L67 |
32,387 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | validateTableDefinition | function validateTableDefinition(tableDefinition) {
// Do basic table name validation and leave the rest to the store
Validate.notNull(tableDefinition, 'tableDefinition');
Validate.isObject(tableDefinition, 'tableDefinition');
Validate.isString(tableDefinition.name, 'tableDefinition.name');
Validate.notNullOrEmpty(tableDefinition.name, 'tableDefinition.name');
// Validate the specified column types and check for duplicate columns
var columnDefinitions = tableDefinition.columnDefinitions,
definedColumns = {};
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
for (var columnName in columnDefinitions) {
Validate.isString(columnDefinitions[columnName], 'columnType');
Validate.notNullOrEmpty(columnDefinitions[columnName], 'columnType');
if (definedColumns[columnName.toLowerCase()]) {
throw new Error('Duplicate definition for column ' + columnName + '" in table "' + tableDefinition.name + '"');
}
definedColumns[columnName.toLowerCase()] = true;
}
} | javascript | function validateTableDefinition(tableDefinition) {
// Do basic table name validation and leave the rest to the store
Validate.notNull(tableDefinition, 'tableDefinition');
Validate.isObject(tableDefinition, 'tableDefinition');
Validate.isString(tableDefinition.name, 'tableDefinition.name');
Validate.notNullOrEmpty(tableDefinition.name, 'tableDefinition.name');
// Validate the specified column types and check for duplicate columns
var columnDefinitions = tableDefinition.columnDefinitions,
definedColumns = {};
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
for (var columnName in columnDefinitions) {
Validate.isString(columnDefinitions[columnName], 'columnType');
Validate.notNullOrEmpty(columnDefinitions[columnName], 'columnType');
if (definedColumns[columnName.toLowerCase()]) {
throw new Error('Duplicate definition for column ' + columnName + '" in table "' + tableDefinition.name + '"');
}
definedColumns[columnName.toLowerCase()] = true;
}
} | [
"function",
"validateTableDefinition",
"(",
"tableDefinition",
")",
"{",
"// Do basic table name validation and leave the rest to the store",
"Validate",
".",
"notNull",
"(",
"tableDefinition",
",",
"'tableDefinition'",
")",
";",
"Validate",
".",
"isObject",
"(",
"tableDefini... | Validates the table definition
@private | [
"Validates",
"the",
"table",
"definition"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L17-L43 |
32,388 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | addTableDefinition | function addTableDefinition(tableDefinitions, tableDefinition) {
Validate.isObject(tableDefinitions);
Validate.notNull(tableDefinitions);
validateTableDefinition(tableDefinition);
tableDefinitions[tableDefinition.name.toLowerCase()] = tableDefinition;
} | javascript | function addTableDefinition(tableDefinitions, tableDefinition) {
Validate.isObject(tableDefinitions);
Validate.notNull(tableDefinitions);
validateTableDefinition(tableDefinition);
tableDefinitions[tableDefinition.name.toLowerCase()] = tableDefinition;
} | [
"function",
"addTableDefinition",
"(",
"tableDefinitions",
",",
"tableDefinition",
")",
"{",
"Validate",
".",
"isObject",
"(",
"tableDefinitions",
")",
";",
"Validate",
".",
"notNull",
"(",
"tableDefinitions",
")",
";",
"validateTableDefinition",
"(",
"tableDefinition... | Adds a tableDefinition to the tableDefinitions object
@private | [
"Adds",
"a",
"tableDefinition",
"to",
"the",
"tableDefinitions",
"object"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L49-L55 |
32,389 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | getTableDefinition | function getTableDefinition(tableDefinitions, tableName) {
Validate.isObject(tableDefinitions);
Validate.notNull(tableDefinitions);
Validate.isString(tableName);
Validate.notNullOrEmpty(tableName);
return tableDefinitions[tableName.toLowerCase()];
} | javascript | function getTableDefinition(tableDefinitions, tableName) {
Validate.isObject(tableDefinitions);
Validate.notNull(tableDefinitions);
Validate.isString(tableName);
Validate.notNullOrEmpty(tableName);
return tableDefinitions[tableName.toLowerCase()];
} | [
"function",
"getTableDefinition",
"(",
"tableDefinitions",
",",
"tableName",
")",
"{",
"Validate",
".",
"isObject",
"(",
"tableDefinitions",
")",
";",
"Validate",
".",
"notNull",
"(",
"tableDefinitions",
")",
";",
"Validate",
".",
"isString",
"(",
"tableName",
"... | Gets the table definition for the specified table name from the tableDefinitions object
@private | [
"Gets",
"the",
"table",
"definition",
"for",
"the",
"specified",
"table",
"name",
"from",
"the",
"tableDefinitions",
"object"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L61-L68 |
32,390 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | getColumnType | function getColumnType(columnDefinitions, columnName) {
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
Validate.isString(columnName);
Validate.notNullOrEmpty(columnName);
for (var column in columnDefinitions) {
if (column.toLowerCase() === columnName.toLowerCase()) {
return columnDefinitions[column];
}
}
} | javascript | function getColumnType(columnDefinitions, columnName) {
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
Validate.isString(columnName);
Validate.notNullOrEmpty(columnName);
for (var column in columnDefinitions) {
if (column.toLowerCase() === columnName.toLowerCase()) {
return columnDefinitions[column];
}
}
} | [
"function",
"getColumnType",
"(",
"columnDefinitions",
",",
"columnName",
")",
"{",
"Validate",
".",
"isObject",
"(",
"columnDefinitions",
")",
";",
"Validate",
".",
"notNull",
"(",
"columnDefinitions",
")",
";",
"Validate",
".",
"isString",
"(",
"columnName",
"... | Gets the type of the specified column
@private | [
"Gets",
"the",
"type",
"of",
"the",
"specified",
"column"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L74-L85 |
32,391 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | getColumnName | function getColumnName(columnDefinitions, property) {
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
Validate.isString(property);
Validate.notNullOrEmpty(property);
for (var column in columnDefinitions) {
if (column.toLowerCase() === property.toLowerCase()) {
return column;
}
}
return property; // If no definition found for property, simply returns the column name as is
} | javascript | function getColumnName(columnDefinitions, property) {
Validate.isObject(columnDefinitions);
Validate.notNull(columnDefinitions);
Validate.isString(property);
Validate.notNullOrEmpty(property);
for (var column in columnDefinitions) {
if (column.toLowerCase() === property.toLowerCase()) {
return column;
}
}
return property; // If no definition found for property, simply returns the column name as is
} | [
"function",
"getColumnName",
"(",
"columnDefinitions",
",",
"property",
")",
"{",
"Validate",
".",
"isObject",
"(",
"columnDefinitions",
")",
";",
"Validate",
".",
"notNull",
"(",
"columnDefinitions",
")",
";",
"Validate",
".",
"isString",
"(",
"property",
")",
... | Returns the column name in the column definitions that matches the specified property
@private | [
"Returns",
"the",
"column",
"name",
"in",
"the",
"column",
"definitions",
"that",
"matches",
"the",
"specified",
"property"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L91-L104 |
32,392 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | getId | function getId(record) {
Validate.isObject(record);
Validate.notNull(record);
for (var property in record) {
if (property.toLowerCase() === idPropertyName.toLowerCase()) {
return record[property];
}
}
} | javascript | function getId(record) {
Validate.isObject(record);
Validate.notNull(record);
for (var property in record) {
if (property.toLowerCase() === idPropertyName.toLowerCase()) {
return record[property];
}
}
} | [
"function",
"getId",
"(",
"record",
")",
"{",
"Validate",
".",
"isObject",
"(",
"record",
")",
";",
"Validate",
".",
"notNull",
"(",
"record",
")",
";",
"for",
"(",
"var",
"property",
"in",
"record",
")",
"{",
"if",
"(",
"property",
".",
"toLowerCase",... | Returns the Id property value OR undefined if none exists
@private | [
"Returns",
"the",
"Id",
"property",
"value",
"OR",
"undefined",
"if",
"none",
"exists"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L110-L119 |
32,393 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/storeHelper.js | isId | function isId(property) {
Validate.isString(property);
Validate.notNullOrEmpty(property);
return property.toLowerCase() === idPropertyName.toLowerCase();
} | javascript | function isId(property) {
Validate.isString(property);
Validate.notNullOrEmpty(property);
return property.toLowerCase() === idPropertyName.toLowerCase();
} | [
"function",
"isId",
"(",
"property",
")",
"{",
"Validate",
".",
"isString",
"(",
"property",
")",
";",
"Validate",
".",
"notNullOrEmpty",
"(",
"property",
")",
";",
"return",
"property",
".",
"toLowerCase",
"(",
")",
"===",
"idPropertyName",
".",
"toLowerCas... | Checks if property is an ID property.
@private | [
"Checks",
"if",
"property",
"is",
"an",
"ID",
"property",
"."
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/storeHelper.js#L125-L130 |
32,394 | Azure/azure-mobile-apps-js-client | sdk/src/sync/MobileServiceSyncContext.js | upsertWithLogging | function upsertWithLogging(tableName, instance, action, shouldOverwrite) {
Validate.isString(tableName, 'tableName');
Validate.notNullOrEmpty(tableName, 'tableName');
Validate.notNull(instance, 'instance');
Validate.isValidId(instance.id, 'instance.id');
if (!store) {
throw new Error('MobileServiceSyncContext not initialized');
}
return store.lookup(tableName, instance.id, true /* suppressRecordNotFoundError */).then(function(existingRecord) {
if (existingRecord && !shouldOverwrite) {
throw new Error('Record with id ' + existingRecord.id + ' already exists in the table ' + tableName);
}
}).then(function() {
return operationTableManager.getLoggingOperation(tableName, action, instance);
}).then(function(loggingOperation) {
return store.executeBatch([
{
action: 'upsert',
tableName: tableName,
data: instance
},
loggingOperation
]);
}).then(function() {
return instance;
});
} | javascript | function upsertWithLogging(tableName, instance, action, shouldOverwrite) {
Validate.isString(tableName, 'tableName');
Validate.notNullOrEmpty(tableName, 'tableName');
Validate.notNull(instance, 'instance');
Validate.isValidId(instance.id, 'instance.id');
if (!store) {
throw new Error('MobileServiceSyncContext not initialized');
}
return store.lookup(tableName, instance.id, true /* suppressRecordNotFoundError */).then(function(existingRecord) {
if (existingRecord && !shouldOverwrite) {
throw new Error('Record with id ' + existingRecord.id + ' already exists in the table ' + tableName);
}
}).then(function() {
return operationTableManager.getLoggingOperation(tableName, action, instance);
}).then(function(loggingOperation) {
return store.executeBatch([
{
action: 'upsert',
tableName: tableName,
data: instance
},
loggingOperation
]);
}).then(function() {
return instance;
});
} | [
"function",
"upsertWithLogging",
"(",
"tableName",
",",
"instance",
",",
"action",
",",
"shouldOverwrite",
")",
"{",
"Validate",
".",
"isString",
"(",
"tableName",
",",
"'tableName'",
")",
";",
"Validate",
".",
"notNullOrEmpty",
"(",
"tableName",
",",
"'tableNam... | Performs upsert and logs the action in the operation table Validates parameters. Callers can skip validation | [
"Performs",
"upsert",
"and",
"logs",
"the",
"action",
"in",
"the",
"operation",
"table",
"Validates",
"parameters",
".",
"Callers",
"can",
"skip",
"validation"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/sync/MobileServiceSyncContext.js#L332-L361 |
32,395 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/sqliteSerializer.js | getSqliteType | function getSqliteType (columnType) {
var sqliteType;
switch (columnType) {
case ColumnType.Object:
case ColumnType.Array:
case ColumnType.String:
case ColumnType.Text:
sqliteType = "TEXT";
break;
case ColumnType.Integer:
case ColumnType.Int:
case ColumnType.Boolean:
case ColumnType.Bool:
case ColumnType.Date:
sqliteType = "INTEGER";
break;
case ColumnType.Real:
case ColumnType.Float:
sqliteType = "REAL";
break;
default:
throw new Error('Column type ' + columnType + ' is not supported');
}
return sqliteType;
} | javascript | function getSqliteType (columnType) {
var sqliteType;
switch (columnType) {
case ColumnType.Object:
case ColumnType.Array:
case ColumnType.String:
case ColumnType.Text:
sqliteType = "TEXT";
break;
case ColumnType.Integer:
case ColumnType.Int:
case ColumnType.Boolean:
case ColumnType.Bool:
case ColumnType.Date:
sqliteType = "INTEGER";
break;
case ColumnType.Real:
case ColumnType.Float:
sqliteType = "REAL";
break;
default:
throw new Error('Column type ' + columnType + ' is not supported');
}
return sqliteType;
} | [
"function",
"getSqliteType",
"(",
"columnType",
")",
"{",
"var",
"sqliteType",
";",
"switch",
"(",
"columnType",
")",
"{",
"case",
"ColumnType",
".",
"Object",
":",
"case",
"ColumnType",
".",
"Array",
":",
"case",
"ColumnType",
".",
"String",
":",
"case",
... | Gets the SQLite type that matches the specified ColumnType.
@private
@param columnType - The type of values that will be stored in the SQLite table
@throw Will throw an error if columnType is not supported | [
"Gets",
"the",
"SQLite",
"type",
"that",
"matches",
"the",
"specified",
"ColumnType",
"."
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L26-L52 |
32,396 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/sqliteSerializer.js | serialize | function serialize (value, columnDefinitions) {
var serializedValue = {};
try {
Validate.notNull(columnDefinitions, 'columnDefinitions');
Validate.isObject(columnDefinitions);
Validate.notNull(value);
Validate.isObject(value);
for (var property in value) {
var columnType = storeHelper.getColumnType(columnDefinitions, property);
// Skip properties that don't match any column in the table
if (!_.isNull(columnType)) {
serializedValue[property] = serializeMember(value[property], columnType);
}
}
} catch (error) {
throw new verror.VError(error, 'Failed to serialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions));
}
return serializedValue;
} | javascript | function serialize (value, columnDefinitions) {
var serializedValue = {};
try {
Validate.notNull(columnDefinitions, 'columnDefinitions');
Validate.isObject(columnDefinitions);
Validate.notNull(value);
Validate.isObject(value);
for (var property in value) {
var columnType = storeHelper.getColumnType(columnDefinitions, property);
// Skip properties that don't match any column in the table
if (!_.isNull(columnType)) {
serializedValue[property] = serializeMember(value[property], columnType);
}
}
} catch (error) {
throw new verror.VError(error, 'Failed to serialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions));
}
return serializedValue;
} | [
"function",
"serialize",
"(",
"value",
",",
"columnDefinitions",
")",
"{",
"var",
"serializedValue",
"=",
"{",
"}",
";",
"try",
"{",
"Validate",
".",
"notNull",
"(",
"columnDefinitions",
",",
"'columnDefinitions'",
")",
";",
"Validate",
".",
"isObject",
"(",
... | Serializes an object into an object that can be stored in a SQLite table, as defined by columnDefinitions.
@private | [
"Serializes",
"an",
"object",
"into",
"an",
"object",
"that",
"can",
"be",
"stored",
"in",
"a",
"SQLite",
"table",
"as",
"defined",
"by",
"columnDefinitions",
"."
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L145-L170 |
32,397 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/sqliteSerializer.js | deserialize | function deserialize (value, columnDefinitions) {
var deserializedValue = {};
try {
Validate.notNull(columnDefinitions, 'columnDefinitions');
Validate.isObject(columnDefinitions);
Validate.notNull(value);
Validate.isObject(value);
for (var property in value) {
var columnName = storeHelper.getColumnName(columnDefinitions, property); // this helps us deserialize with proper case for the property name
deserializedValue[columnName] = deserializeMember(value[property], storeHelper.getColumnType(columnDefinitions, property));
}
} catch (error) {
throw new verror.VError(error, 'Failed to deserialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions));
}
return deserializedValue;
} | javascript | function deserialize (value, columnDefinitions) {
var deserializedValue = {};
try {
Validate.notNull(columnDefinitions, 'columnDefinitions');
Validate.isObject(columnDefinitions);
Validate.notNull(value);
Validate.isObject(value);
for (var property in value) {
var columnName = storeHelper.getColumnName(columnDefinitions, property); // this helps us deserialize with proper case for the property name
deserializedValue[columnName] = deserializeMember(value[property], storeHelper.getColumnType(columnDefinitions, property));
}
} catch (error) {
throw new verror.VError(error, 'Failed to deserialize value ' + JSON.stringify(value) + '. Column definitions: ' + JSON.stringify(columnDefinitions));
}
return deserializedValue;
} | [
"function",
"deserialize",
"(",
"value",
",",
"columnDefinitions",
")",
"{",
"var",
"deserializedValue",
"=",
"{",
"}",
";",
"try",
"{",
"Validate",
".",
"notNull",
"(",
"columnDefinitions",
",",
"'columnDefinitions'",
")",
";",
"Validate",
".",
"isObject",
"(... | Deserializes a row read from a SQLite table into a Javascript object, as defined by columnDefinitions.
@private | [
"Deserializes",
"a",
"row",
"read",
"from",
"a",
"SQLite",
"table",
"into",
"a",
"Javascript",
"object",
"as",
"defined",
"by",
"columnDefinitions",
"."
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L176-L197 |
32,398 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/sqliteSerializer.js | serializeMember | function serializeMember(value, columnType) {
// Start by checking if the specified column type is valid
if (!isColumnTypeValid(columnType)) {
throw new Error('Column type ' + columnType + ' is not supported');
}
// Now check if the specified value can be stored in a column of type columnType
if (!isJSValueCompatibleWithColumnType(value, columnType)) {
throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.');
}
// If we are here, it means we are good to proceed with serialization
var sqliteType = getSqliteType(columnType),
serializedValue;
switch (sqliteType) {
case "TEXT":
serializedValue = typeConverter.convertToText(value);
break;
case "INTEGER":
serializedValue = typeConverter.convertToInteger(value);
break;
case "REAL":
serializedValue = typeConverter.convertToReal(value);
break;
default:
throw new Error('Column type ' + columnType + ' is not supported');
}
return serializedValue;
} | javascript | function serializeMember(value, columnType) {
// Start by checking if the specified column type is valid
if (!isColumnTypeValid(columnType)) {
throw new Error('Column type ' + columnType + ' is not supported');
}
// Now check if the specified value can be stored in a column of type columnType
if (!isJSValueCompatibleWithColumnType(value, columnType)) {
throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value + ' to type ' + columnType + ' is not supported.');
}
// If we are here, it means we are good to proceed with serialization
var sqliteType = getSqliteType(columnType),
serializedValue;
switch (sqliteType) {
case "TEXT":
serializedValue = typeConverter.convertToText(value);
break;
case "INTEGER":
serializedValue = typeConverter.convertToInteger(value);
break;
case "REAL":
serializedValue = typeConverter.convertToReal(value);
break;
default:
throw new Error('Column type ' + columnType + ' is not supported');
}
return serializedValue;
} | [
"function",
"serializeMember",
"(",
"value",
",",
"columnType",
")",
"{",
"// Start by checking if the specified column type is valid",
"if",
"(",
"!",
"isColumnTypeValid",
"(",
"columnType",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Column type '",
"+",
"columnT... | Serializes a property of an object into a value which can be stored in a SQLite column of type columnType.
@private | [
"Serializes",
"a",
"property",
"of",
"an",
"object",
"into",
"a",
"value",
"which",
"can",
"be",
"stored",
"in",
"a",
"SQLite",
"column",
"of",
"type",
"columnType",
"."
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L203-L235 |
32,399 | Azure/azure-mobile-apps-js-client | sdk/src/Platform/cordova/sqliteSerializer.js | deserializeMember | function deserializeMember(value, columnType) {
// Handle this special case first.
// Simply return 'value' if a corresponding columnType is not defined.
if (!columnType) {
return value;
}
// Start by checking if the specified column type is valid.
if (!isColumnTypeValid(columnType)) {
throw new Error('Column type ' + columnType + ' is not supported');
}
// Now check if the specified value can be stored in a column of type columnType.
if (!isSqliteValueCompatibleWithColumnType(value, columnType)) {
throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value +
' to type ' + columnType + ' is not supported.');
}
// If we are here, it means we are good to proceed with deserialization
var deserializedValue, error;
switch (columnType) {
case ColumnType.Object:
deserializedValue = typeConverter.convertToObject(value);
break;
case ColumnType.Array:
deserializedValue = typeConverter.convertToArray(value);
break;
case ColumnType.String:
case ColumnType.Text:
deserializedValue = typeConverter.convertToText(value);
break;
case ColumnType.Integer:
case ColumnType.Int:
deserializedValue = typeConverter.convertToInteger(value);
break;
case ColumnType.Boolean:
case ColumnType.Bool:
deserializedValue = typeConverter.convertToBoolean(value);
break;
case ColumnType.Date:
deserializedValue = typeConverter.convertToDate(value);
break;
case ColumnType.Real:
case ColumnType.Float:
deserializedValue = typeConverter.convertToReal(value);
break;
default:
throw new Error(_.format(Platform.getResourceString("sqliteSerializer_UnsupportedColumnType"), columnType));
}
return deserializedValue;
} | javascript | function deserializeMember(value, columnType) {
// Handle this special case first.
// Simply return 'value' if a corresponding columnType is not defined.
if (!columnType) {
return value;
}
// Start by checking if the specified column type is valid.
if (!isColumnTypeValid(columnType)) {
throw new Error('Column type ' + columnType + ' is not supported');
}
// Now check if the specified value can be stored in a column of type columnType.
if (!isSqliteValueCompatibleWithColumnType(value, columnType)) {
throw new Error('Converting value ' + JSON.stringify(value) + ' of type ' + typeof value +
' to type ' + columnType + ' is not supported.');
}
// If we are here, it means we are good to proceed with deserialization
var deserializedValue, error;
switch (columnType) {
case ColumnType.Object:
deserializedValue = typeConverter.convertToObject(value);
break;
case ColumnType.Array:
deserializedValue = typeConverter.convertToArray(value);
break;
case ColumnType.String:
case ColumnType.Text:
deserializedValue = typeConverter.convertToText(value);
break;
case ColumnType.Integer:
case ColumnType.Int:
deserializedValue = typeConverter.convertToInteger(value);
break;
case ColumnType.Boolean:
case ColumnType.Bool:
deserializedValue = typeConverter.convertToBoolean(value);
break;
case ColumnType.Date:
deserializedValue = typeConverter.convertToDate(value);
break;
case ColumnType.Real:
case ColumnType.Float:
deserializedValue = typeConverter.convertToReal(value);
break;
default:
throw new Error(_.format(Platform.getResourceString("sqliteSerializer_UnsupportedColumnType"), columnType));
}
return deserializedValue;
} | [
"function",
"deserializeMember",
"(",
"value",
",",
"columnType",
")",
"{",
"// Handle this special case first.",
"// Simply return 'value' if a corresponding columnType is not defined. ",
"if",
"(",
"!",
"columnType",
")",
"{",
"return",
"value",
";",
"}",
"// Start by che... | Deserializes a property of an object read from SQLite into a value of type columnType | [
"Deserializes",
"a",
"property",
"of",
"an",
"object",
"read",
"from",
"SQLite",
"into",
"a",
"value",
"of",
"type",
"columnType"
] | bd4f9ba795527fbb95eca0f4ab53eb798934beba | https://github.com/Azure/azure-mobile-apps-js-client/blob/bd4f9ba795527fbb95eca0f4ab53eb798934beba/sdk/src/Platform/cordova/sqliteSerializer.js#L238-L292 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.