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
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
50,900 | wavesoft/jbb-profile-three | lib/helpers/MD2CharacterLoader.js | function(config, onload, onprogress, onerror) {
var character = new THREE.MD2Character();
character.onLoadComplete = function() {
if (onload) onload( character );
};
character.loadParts( config );
} | javascript | function(config, onload, onprogress, onerror) {
var character = new THREE.MD2Character();
character.onLoadComplete = function() {
if (onload) onload( character );
};
character.loadParts( config );
} | [
"function",
"(",
"config",
",",
"onload",
",",
"onprogress",
",",
"onerror",
")",
"{",
"var",
"character",
"=",
"new",
"THREE",
".",
"MD2Character",
"(",
")",
";",
"character",
".",
"onLoadComplete",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"onload",
")",
"onload",
"(",
"character",
")",
";",
"}",
";",
"character",
".",
"loadParts",
"(",
"config",
")",
";",
"}"
] | Load an MD2 Character with the config provided | [
"Load",
"an",
"MD2",
"Character",
"with",
"the",
"config",
"provided"
] | 8539cfbb2d04b67999eee6e530fcaf03083e0e04 | https://github.com/wavesoft/jbb-profile-three/blob/8539cfbb2d04b67999eee6e530fcaf03083e0e04/lib/helpers/MD2CharacterLoader.js#L16-L26 |
|
50,901 | derdesign/protos | drivers/postgres.js | PostgreSQL | function PostgreSQL(config) {
var self = this;
config = protos.extend({
host: 'localhost',
port: 5432
}, config);
this.className = this.constructor.name;
this.config = config;
// Set client
this.client = new Client(config);
// Connect client
this.client.connect();
// Assign storage
if (typeof config.storage == 'string') {
this.storage = app.getResource('storages/' + config.storage);
} else if (config.storage instanceof protos.lib.storage) {
this.storage = config.storage;
}
// Set db
this.db = config.database;
// Only set important properties enumerable
protos.util.onlySetEnumerable(this, ['className', 'db']);
} | javascript | function PostgreSQL(config) {
var self = this;
config = protos.extend({
host: 'localhost',
port: 5432
}, config);
this.className = this.constructor.name;
this.config = config;
// Set client
this.client = new Client(config);
// Connect client
this.client.connect();
// Assign storage
if (typeof config.storage == 'string') {
this.storage = app.getResource('storages/' + config.storage);
} else if (config.storage instanceof protos.lib.storage) {
this.storage = config.storage;
}
// Set db
this.db = config.database;
// Only set important properties enumerable
protos.util.onlySetEnumerable(this, ['className', 'db']);
} | [
"function",
"PostgreSQL",
"(",
"config",
")",
"{",
"var",
"self",
"=",
"this",
";",
"config",
"=",
"protos",
".",
"extend",
"(",
"{",
"host",
":",
"'localhost'",
",",
"port",
":",
"5432",
"}",
",",
"config",
")",
";",
"this",
".",
"className",
"=",
"this",
".",
"constructor",
".",
"name",
";",
"this",
".",
"config",
"=",
"config",
";",
"// Set client",
"this",
".",
"client",
"=",
"new",
"Client",
"(",
"config",
")",
";",
"// Connect client",
"this",
".",
"client",
".",
"connect",
"(",
")",
";",
"// Assign storage",
"if",
"(",
"typeof",
"config",
".",
"storage",
"==",
"'string'",
")",
"{",
"this",
".",
"storage",
"=",
"app",
".",
"getResource",
"(",
"'storages/'",
"+",
"config",
".",
"storage",
")",
";",
"}",
"else",
"if",
"(",
"config",
".",
"storage",
"instanceof",
"protos",
".",
"lib",
".",
"storage",
")",
"{",
"this",
".",
"storage",
"=",
"config",
".",
"storage",
";",
"}",
"// Set db",
"this",
".",
"db",
"=",
"config",
".",
"database",
";",
"// Only set important properties enumerable",
"protos",
".",
"util",
".",
"onlySetEnumerable",
"(",
"this",
",",
"[",
"'className'",
",",
"'db'",
"]",
")",
";",
"}"
] | PostgreSQL Driver class
Driver configuration
config: {
host: 'localhost',
port: 5432,
user: 'db_user',
password: 'db_password',
database: 'db_name',
storage: 'redis'
}
@class PostgreSQL
@extends Driver
@constructor
@param {object} app Application instance
@param {object} config Driver configuration | [
"PostgreSQL",
"Driver",
"class"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/drivers/postgres.js#L31-L63 |
50,902 | Jomint/jostack | lib/index.js | init | function init(options) {
var fs = require('fs');
var path = require('path');
var rootdir = path.dirname(require.main);
var options = options || {
config: require(path.join(rootdir, 'config.json')),
root: rootdir,
callback: function (noop) {}
};
var def = {};
function ModulePaths (moduledir) {
this.moduledir = moduledir;
}
ModulePaths.prototype.then = function (accept, reject) {
var moduledir = this.moduledir;
fs.readdir(moduledir, function (err, files) {
if (err) reject(err);
files.forEach(function (file) {
var name = path.basename(file, '.js');
def[name] = path.join(moduledir, name);
});
accept();
});
};
var pubpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'public', 'js'));
var prvpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'private', 'js'));
Promise.all([pubpath, prvpath])
.then(function () {
var requirejs = require('requirejs');
requirejs.config({
baseUrl: path.join(rootdir),
paths: def
});
requirejs(['loader_factory'], function (LoaderFactory) {
var fs = require('fs');
var config = options.config;
config.paths.push(path.dirname(pubpath.moduledir));
var loader = 'loader_express';
var db = 'db_mongo';
if (config.loader) loader = config.loader;
if (config.db) db = config.db;
new LoaderFactory().create(loader, db, function (loader) {
loader.init(config, options.callback);
});
});
})
.catch(function (err) {
console.error('err:', err);
});
} | javascript | function init(options) {
var fs = require('fs');
var path = require('path');
var rootdir = path.dirname(require.main);
var options = options || {
config: require(path.join(rootdir, 'config.json')),
root: rootdir,
callback: function (noop) {}
};
var def = {};
function ModulePaths (moduledir) {
this.moduledir = moduledir;
}
ModulePaths.prototype.then = function (accept, reject) {
var moduledir = this.moduledir;
fs.readdir(moduledir, function (err, files) {
if (err) reject(err);
files.forEach(function (file) {
var name = path.basename(file, '.js');
def[name] = path.join(moduledir, name);
});
accept();
});
};
var pubpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'public', 'js'));
var prvpath = new ModulePaths(path.join(path.dirname(module.filename), '..', 'private', 'js'));
Promise.all([pubpath, prvpath])
.then(function () {
var requirejs = require('requirejs');
requirejs.config({
baseUrl: path.join(rootdir),
paths: def
});
requirejs(['loader_factory'], function (LoaderFactory) {
var fs = require('fs');
var config = options.config;
config.paths.push(path.dirname(pubpath.moduledir));
var loader = 'loader_express';
var db = 'db_mongo';
if (config.loader) loader = config.loader;
if (config.db) db = config.db;
new LoaderFactory().create(loader, db, function (loader) {
loader.init(config, options.callback);
});
});
})
.catch(function (err) {
console.error('err:', err);
});
} | [
"function",
"init",
"(",
"options",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
";",
"var",
"path",
"=",
"require",
"(",
"'path'",
")",
";",
"var",
"rootdir",
"=",
"path",
".",
"dirname",
"(",
"require",
".",
"main",
")",
";",
"var",
"options",
"=",
"options",
"||",
"{",
"config",
":",
"require",
"(",
"path",
".",
"join",
"(",
"rootdir",
",",
"'config.json'",
")",
")",
",",
"root",
":",
"rootdir",
",",
"callback",
":",
"function",
"(",
"noop",
")",
"{",
"}",
"}",
";",
"var",
"def",
"=",
"{",
"}",
";",
"function",
"ModulePaths",
"(",
"moduledir",
")",
"{",
"this",
".",
"moduledir",
"=",
"moduledir",
";",
"}",
"ModulePaths",
".",
"prototype",
".",
"then",
"=",
"function",
"(",
"accept",
",",
"reject",
")",
"{",
"var",
"moduledir",
"=",
"this",
".",
"moduledir",
";",
"fs",
".",
"readdir",
"(",
"moduledir",
",",
"function",
"(",
"err",
",",
"files",
")",
"{",
"if",
"(",
"err",
")",
"reject",
"(",
"err",
")",
";",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"name",
"=",
"path",
".",
"basename",
"(",
"file",
",",
"'.js'",
")",
";",
"def",
"[",
"name",
"]",
"=",
"path",
".",
"join",
"(",
"moduledir",
",",
"name",
")",
";",
"}",
")",
";",
"accept",
"(",
")",
";",
"}",
")",
";",
"}",
";",
"var",
"pubpath",
"=",
"new",
"ModulePaths",
"(",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"module",
".",
"filename",
")",
",",
"'..'",
",",
"'public'",
",",
"'js'",
")",
")",
";",
"var",
"prvpath",
"=",
"new",
"ModulePaths",
"(",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"module",
".",
"filename",
")",
",",
"'..'",
",",
"'private'",
",",
"'js'",
")",
")",
";",
"Promise",
".",
"all",
"(",
"[",
"pubpath",
",",
"prvpath",
"]",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"requirejs",
"=",
"require",
"(",
"'requirejs'",
")",
";",
"requirejs",
".",
"config",
"(",
"{",
"baseUrl",
":",
"path",
".",
"join",
"(",
"rootdir",
")",
",",
"paths",
":",
"def",
"}",
")",
";",
"requirejs",
"(",
"[",
"'loader_factory'",
"]",
",",
"function",
"(",
"LoaderFactory",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
";",
"var",
"config",
"=",
"options",
".",
"config",
";",
"config",
".",
"paths",
".",
"push",
"(",
"path",
".",
"dirname",
"(",
"pubpath",
".",
"moduledir",
")",
")",
";",
"var",
"loader",
"=",
"'loader_express'",
";",
"var",
"db",
"=",
"'db_mongo'",
";",
"if",
"(",
"config",
".",
"loader",
")",
"loader",
"=",
"config",
".",
"loader",
";",
"if",
"(",
"config",
".",
"db",
")",
"db",
"=",
"config",
".",
"db",
";",
"new",
"LoaderFactory",
"(",
")",
".",
"create",
"(",
"loader",
",",
"db",
",",
"function",
"(",
"loader",
")",
"{",
"loader",
".",
"init",
"(",
"config",
",",
"options",
".",
"callback",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'err:'",
",",
"err",
")",
";",
"}",
")",
";",
"}"
] | Node process entry
@author - Mark Williams
Entry point for node process. All bootstrapping activity is handled
by bootstrapping process in the loader created by factory | [
"Node",
"process",
"entry"
] | 6ab3bb8f44cf275a142b7a07d9bfba67f25f5af7 | https://github.com/Jomint/jostack/blob/6ab3bb8f44cf275a142b7a07d9bfba67f25f5af7/lib/index.js#L9-L63 |
50,903 | Frijol/tessel-button | index.js | Button | function Button (hardware, callback) {
var self = this;
// Set hardware connection of the object
self.hardware = hardware;
// Object properties
self.delay = 100;
self.pressed = false;
// Begin listening for events
self.hardware.on('fall', function () {
self._press();
});
self.hardware.on('rise', function () {
self._release();
});
// Make sure the events get emitted, even if late
setInterval(function () {
if(!self.hardware.read()) {
self._press();
} else {
self._release();
}
}, self.delay);
// Emit the ready event when everything is set up
setImmediate(function emitReady() {
self.emit('ready');
});
// Call the callback with object
if (callback) {
callback(null, self);
}
} | javascript | function Button (hardware, callback) {
var self = this;
// Set hardware connection of the object
self.hardware = hardware;
// Object properties
self.delay = 100;
self.pressed = false;
// Begin listening for events
self.hardware.on('fall', function () {
self._press();
});
self.hardware.on('rise', function () {
self._release();
});
// Make sure the events get emitted, even if late
setInterval(function () {
if(!self.hardware.read()) {
self._press();
} else {
self._release();
}
}, self.delay);
// Emit the ready event when everything is set up
setImmediate(function emitReady() {
self.emit('ready');
});
// Call the callback with object
if (callback) {
callback(null, self);
}
} | [
"function",
"Button",
"(",
"hardware",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// Set hardware connection of the object",
"self",
".",
"hardware",
"=",
"hardware",
";",
"// Object properties",
"self",
".",
"delay",
"=",
"100",
";",
"self",
".",
"pressed",
"=",
"false",
";",
"// Begin listening for events",
"self",
".",
"hardware",
".",
"on",
"(",
"'fall'",
",",
"function",
"(",
")",
"{",
"self",
".",
"_press",
"(",
")",
";",
"}",
")",
";",
"self",
".",
"hardware",
".",
"on",
"(",
"'rise'",
",",
"function",
"(",
")",
"{",
"self",
".",
"_release",
"(",
")",
";",
"}",
")",
";",
"// Make sure the events get emitted, even if late",
"setInterval",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"self",
".",
"hardware",
".",
"read",
"(",
")",
")",
"{",
"self",
".",
"_press",
"(",
")",
";",
"}",
"else",
"{",
"self",
".",
"_release",
"(",
")",
";",
"}",
"}",
",",
"self",
".",
"delay",
")",
";",
"// Emit the ready event when everything is set up",
"setImmediate",
"(",
"function",
"emitReady",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"'ready'",
")",
";",
"}",
")",
";",
"// Call the callback with object",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"null",
",",
"self",
")",
";",
"}",
"}"
] | Constructor function to instantiate the hardware object | [
"Constructor",
"function",
"to",
"instantiate",
"the",
"hardware",
"object"
] | 084f1d81a3ffde2a243edc1e5159cedb531f28a4 | https://github.com/Frijol/tessel-button/blob/084f1d81a3ffde2a243edc1e5159cedb531f28a4/index.js#L6-L42 |
50,904 | Wizcorp/component-hint | lib/cli.js | formatOptionStrings | function formatOptionStrings(options, width) {
var totalWidth = (width < process.stdout.columns) ? width : process.stdout.columns;
var paddingWidth = cliOptions.largestOptionLength() + 6;
var stringWidth = totalWidth - paddingWidth;
if (stringWidth <= 0) {
return;
}
var paddingString = '\n' + (new Array(paddingWidth - 3)).join(' ');
for (var i = 0; i < options.length; i++) {
var option = options[i];
// Separate description by width taking words into consideration
var description = option.description;
var splitDescription = [];
while (description) {
if (description.length <= stringWidth) {
splitDescription.push(description);
description = '';
continue;
}
var lastSpaceI = description.lastIndexOf(' ', stringWidth);
if (lastSpaceI < 0) {
splitDescription.push(description);
description = "";
break;
}
var stringChunk = description.substring(0, lastSpaceI);
description = description.substring(lastSpaceI + 1);
splitDescription.push(stringChunk);
}
// Reconstruct description with correct padding
option.description = splitDescription.join(paddingString);
}
} | javascript | function formatOptionStrings(options, width) {
var totalWidth = (width < process.stdout.columns) ? width : process.stdout.columns;
var paddingWidth = cliOptions.largestOptionLength() + 6;
var stringWidth = totalWidth - paddingWidth;
if (stringWidth <= 0) {
return;
}
var paddingString = '\n' + (new Array(paddingWidth - 3)).join(' ');
for (var i = 0; i < options.length; i++) {
var option = options[i];
// Separate description by width taking words into consideration
var description = option.description;
var splitDescription = [];
while (description) {
if (description.length <= stringWidth) {
splitDescription.push(description);
description = '';
continue;
}
var lastSpaceI = description.lastIndexOf(' ', stringWidth);
if (lastSpaceI < 0) {
splitDescription.push(description);
description = "";
break;
}
var stringChunk = description.substring(0, lastSpaceI);
description = description.substring(lastSpaceI + 1);
splitDescription.push(stringChunk);
}
// Reconstruct description with correct padding
option.description = splitDescription.join(paddingString);
}
} | [
"function",
"formatOptionStrings",
"(",
"options",
",",
"width",
")",
"{",
"var",
"totalWidth",
"=",
"(",
"width",
"<",
"process",
".",
"stdout",
".",
"columns",
")",
"?",
"width",
":",
"process",
".",
"stdout",
".",
"columns",
";",
"var",
"paddingWidth",
"=",
"cliOptions",
".",
"largestOptionLength",
"(",
")",
"+",
"6",
";",
"var",
"stringWidth",
"=",
"totalWidth",
"-",
"paddingWidth",
";",
"if",
"(",
"stringWidth",
"<=",
"0",
")",
"{",
"return",
";",
"}",
"var",
"paddingString",
"=",
"'\\n'",
"+",
"(",
"new",
"Array",
"(",
"paddingWidth",
"-",
"3",
")",
")",
".",
"join",
"(",
"' '",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"options",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"option",
"=",
"options",
"[",
"i",
"]",
";",
"// Separate description by width taking words into consideration",
"var",
"description",
"=",
"option",
".",
"description",
";",
"var",
"splitDescription",
"=",
"[",
"]",
";",
"while",
"(",
"description",
")",
"{",
"if",
"(",
"description",
".",
"length",
"<=",
"stringWidth",
")",
"{",
"splitDescription",
".",
"push",
"(",
"description",
")",
";",
"description",
"=",
"''",
";",
"continue",
";",
"}",
"var",
"lastSpaceI",
"=",
"description",
".",
"lastIndexOf",
"(",
"' '",
",",
"stringWidth",
")",
";",
"if",
"(",
"lastSpaceI",
"<",
"0",
")",
"{",
"splitDescription",
".",
"push",
"(",
"description",
")",
";",
"description",
"=",
"\"\"",
";",
"break",
";",
"}",
"var",
"stringChunk",
"=",
"description",
".",
"substring",
"(",
"0",
",",
"lastSpaceI",
")",
";",
"description",
"=",
"description",
".",
"substring",
"(",
"lastSpaceI",
"+",
"1",
")",
";",
"splitDescription",
".",
"push",
"(",
"stringChunk",
")",
";",
"}",
"// Reconstruct description with correct padding",
"option",
".",
"description",
"=",
"splitDescription",
".",
"join",
"(",
"paddingString",
")",
";",
"}",
"}"
] | Function which re-formats commander option descriptions to have correct new lines and padding.
This makes the output a whole lot cleaner with long description strings, and takes terminal
window width into consideration.
@param {Array} options - options array from commander object
@param {Integer} width - maximum width for output, this should include padding size
@returns {undefined} | [
"Function",
"which",
"re",
"-",
"formats",
"commander",
"option",
"descriptions",
"to",
"have",
"correct",
"new",
"lines",
"and",
"padding",
".",
"This",
"makes",
"the",
"output",
"a",
"whole",
"lot",
"cleaner",
"with",
"long",
"description",
"strings",
"and",
"takes",
"terminal",
"window",
"width",
"into",
"consideration",
"."
] | ccd314a9af5dc5b7cb24dc06227c4b95f2034b19 | https://github.com/Wizcorp/component-hint/blob/ccd314a9af5dc5b7cb24dc06227c4b95f2034b19/lib/cli.js#L19-L57 |
50,905 | Wizcorp/component-hint | lib/cli.js | setupCliObject | function setupCliObject(argv) {
// Set cli options
cliOptions
.version(packageJson.version)
.usage('[options] <component_path ...>')
.option('-v, --verbose',
'Be verbose during tests. (cannot be used with --quiet or --silent)')
.option('-q, --quiet',
'Display only the final outcome.')
.option('-s, --silent',
'Suppress all output.')
.option('-r, --recursive',
'Recurse into local and external dependencies.')
.option('-d, --dep-paths <paths>',
'Colon separated list of paths to external dependencies. (default: "./components")')
.option('-w, --warn-paths <paths>',
'Colon separated list of paths where component errors will be converted to warnings. (supports minimatch globbing)')
.option('-i, --ignore-paths <paths>',
'Colon separated list of paths component-hint should ignore. (supports minimatch globbing)')
.option('-l, --lookup-paths <paths>',
'Colon separated list of paths to check for the existence of missing local ' +
'dependencies. This is used to give the user a hint where they can find them.')
.option(' --reporter <path>',
'Path to reporter file to use for output formatting.',
path.join(__dirname, './reporters/default.js'));
// Cleanup option strings and re-format them
formatOptionStrings(cliOptions.options, 100);
// Add additional info at the bottom of our help
cliOptions.on('--help', function () {
var scriptName = path.basename(argv[1]);
process.stdout.write(' Examples:\n');
process.stdout.write('\n');
process.stdout.write(' Check multiple component entry points\n');
process.stdout.write(' $ ' + scriptName + ' /path/to/single/component /path/to/another/component\n');
process.stdout.write('\n');
process.stdout.write(' Check multiple component entry point which exist in the same folder\n');
process.stdout.write(' $ ' + scriptName + ' /path/to/multiple/component/folder/*/\n');
process.stdout.write('\n');
});
// Parse arguments
cliOptions.parse(argv);
} | javascript | function setupCliObject(argv) {
// Set cli options
cliOptions
.version(packageJson.version)
.usage('[options] <component_path ...>')
.option('-v, --verbose',
'Be verbose during tests. (cannot be used with --quiet or --silent)')
.option('-q, --quiet',
'Display only the final outcome.')
.option('-s, --silent',
'Suppress all output.')
.option('-r, --recursive',
'Recurse into local and external dependencies.')
.option('-d, --dep-paths <paths>',
'Colon separated list of paths to external dependencies. (default: "./components")')
.option('-w, --warn-paths <paths>',
'Colon separated list of paths where component errors will be converted to warnings. (supports minimatch globbing)')
.option('-i, --ignore-paths <paths>',
'Colon separated list of paths component-hint should ignore. (supports minimatch globbing)')
.option('-l, --lookup-paths <paths>',
'Colon separated list of paths to check for the existence of missing local ' +
'dependencies. This is used to give the user a hint where they can find them.')
.option(' --reporter <path>',
'Path to reporter file to use for output formatting.',
path.join(__dirname, './reporters/default.js'));
// Cleanup option strings and re-format them
formatOptionStrings(cliOptions.options, 100);
// Add additional info at the bottom of our help
cliOptions.on('--help', function () {
var scriptName = path.basename(argv[1]);
process.stdout.write(' Examples:\n');
process.stdout.write('\n');
process.stdout.write(' Check multiple component entry points\n');
process.stdout.write(' $ ' + scriptName + ' /path/to/single/component /path/to/another/component\n');
process.stdout.write('\n');
process.stdout.write(' Check multiple component entry point which exist in the same folder\n');
process.stdout.write(' $ ' + scriptName + ' /path/to/multiple/component/folder/*/\n');
process.stdout.write('\n');
});
// Parse arguments
cliOptions.parse(argv);
} | [
"function",
"setupCliObject",
"(",
"argv",
")",
"{",
"// Set cli options",
"cliOptions",
".",
"version",
"(",
"packageJson",
".",
"version",
")",
".",
"usage",
"(",
"'[options] <component_path ...>'",
")",
".",
"option",
"(",
"'-v, --verbose'",
",",
"'Be verbose during tests. (cannot be used with --quiet or --silent)'",
")",
".",
"option",
"(",
"'-q, --quiet'",
",",
"'Display only the final outcome.'",
")",
".",
"option",
"(",
"'-s, --silent'",
",",
"'Suppress all output.'",
")",
".",
"option",
"(",
"'-r, --recursive'",
",",
"'Recurse into local and external dependencies.'",
")",
".",
"option",
"(",
"'-d, --dep-paths <paths>'",
",",
"'Colon separated list of paths to external dependencies. (default: \"./components\")'",
")",
".",
"option",
"(",
"'-w, --warn-paths <paths>'",
",",
"'Colon separated list of paths where component errors will be converted to warnings. (supports minimatch globbing)'",
")",
".",
"option",
"(",
"'-i, --ignore-paths <paths>'",
",",
"'Colon separated list of paths component-hint should ignore. (supports minimatch globbing)'",
")",
".",
"option",
"(",
"'-l, --lookup-paths <paths>'",
",",
"'Colon separated list of paths to check for the existence of missing local '",
"+",
"'dependencies. This is used to give the user a hint where they can find them.'",
")",
".",
"option",
"(",
"' --reporter <path>'",
",",
"'Path to reporter file to use for output formatting.'",
",",
"path",
".",
"join",
"(",
"__dirname",
",",
"'./reporters/default.js'",
")",
")",
";",
"// Cleanup option strings and re-format them",
"formatOptionStrings",
"(",
"cliOptions",
".",
"options",
",",
"100",
")",
";",
"// Add additional info at the bottom of our help",
"cliOptions",
".",
"on",
"(",
"'--help'",
",",
"function",
"(",
")",
"{",
"var",
"scriptName",
"=",
"path",
".",
"basename",
"(",
"argv",
"[",
"1",
"]",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"' Examples:\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"' Check multiple component entry points\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"' $ '",
"+",
"scriptName",
"+",
"' /path/to/single/component /path/to/another/component\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"' Check multiple component entry point which exist in the same folder\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"' $ '",
"+",
"scriptName",
"+",
"' /path/to/multiple/component/folder/*/\\n'",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
";",
"}",
")",
";",
"// Parse arguments",
"cliOptions",
".",
"parse",
"(",
"argv",
")",
";",
"}"
] | Function which sets up the commander object with all of our options and customisations.
@param {Array} argv
@returns {undefined} | [
"Function",
"which",
"sets",
"up",
"the",
"commander",
"object",
"with",
"all",
"of",
"our",
"options",
"and",
"customisations",
"."
] | ccd314a9af5dc5b7cb24dc06227c4b95f2034b19 | https://github.com/Wizcorp/component-hint/blob/ccd314a9af5dc5b7cb24dc06227c4b95f2034b19/lib/cli.js#L66-L111 |
50,906 | Wizcorp/component-hint | lib/cli.js | ensurePathsExist | function ensurePathsExist(pathsList, cb) {
async.eachLimit(pathsList, 10, function (pathItem, callback) {
var absolutePath = path.resolve(pathItem);
fs.stat(absolutePath, function (error, stats) {
if (error) {
return callback(new Error('Path does not exist: ' + absolutePath));
}
if (!stats.isDirectory()) {
return callback(new Error('Path is not a directory: ' + absolutePath));
}
return callback();
});
}, cb);
} | javascript | function ensurePathsExist(pathsList, cb) {
async.eachLimit(pathsList, 10, function (pathItem, callback) {
var absolutePath = path.resolve(pathItem);
fs.stat(absolutePath, function (error, stats) {
if (error) {
return callback(new Error('Path does not exist: ' + absolutePath));
}
if (!stats.isDirectory()) {
return callback(new Error('Path is not a directory: ' + absolutePath));
}
return callback();
});
}, cb);
} | [
"function",
"ensurePathsExist",
"(",
"pathsList",
",",
"cb",
")",
"{",
"async",
".",
"eachLimit",
"(",
"pathsList",
",",
"10",
",",
"function",
"(",
"pathItem",
",",
"callback",
")",
"{",
"var",
"absolutePath",
"=",
"path",
".",
"resolve",
"(",
"pathItem",
")",
";",
"fs",
".",
"stat",
"(",
"absolutePath",
",",
"function",
"(",
"error",
",",
"stats",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Path does not exist: '",
"+",
"absolutePath",
")",
")",
";",
"}",
"if",
"(",
"!",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Path is not a directory: '",
"+",
"absolutePath",
")",
")",
";",
"}",
"return",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"cb",
")",
";",
"}"
] | Function which esures all given paths exist. If not it will return an error via the callback
provided.
@param {Array} pathsList
@param {Function} cb
@returns {undefined} | [
"Function",
"which",
"esures",
"all",
"given",
"paths",
"exist",
".",
"If",
"not",
"it",
"will",
"return",
"an",
"error",
"via",
"the",
"callback",
"provided",
"."
] | ccd314a9af5dc5b7cb24dc06227c4b95f2034b19 | https://github.com/Wizcorp/component-hint/blob/ccd314a9af5dc5b7cb24dc06227c4b95f2034b19/lib/cli.js#L122-L137 |
50,907 | quartzjer/telehash-udp4 | index.js | createSocket | function createSocket(type, receive)
{
try{ // newer
var sock = dgram.createSocket({ type: type, reuseAddr: true }, receive);
}catch(E){ // older
var sock = dgram.createSocket(type, receive);
}
return sock;
} | javascript | function createSocket(type, receive)
{
try{ // newer
var sock = dgram.createSocket({ type: type, reuseAddr: true }, receive);
}catch(E){ // older
var sock = dgram.createSocket(type, receive);
}
return sock;
} | [
"function",
"createSocket",
"(",
"type",
",",
"receive",
")",
"{",
"try",
"{",
"// newer",
"var",
"sock",
"=",
"dgram",
".",
"createSocket",
"(",
"{",
"type",
":",
"type",
",",
"reuseAddr",
":",
"true",
"}",
",",
"receive",
")",
";",
"}",
"catch",
"(",
"E",
")",
"{",
"// older",
"var",
"sock",
"=",
"dgram",
".",
"createSocket",
"(",
"type",
",",
"receive",
")",
";",
"}",
"return",
"sock",
";",
"}"
] | compatibility wrapper between node v0.10 v0.12 and iojs | [
"compatibility",
"wrapper",
"between",
"node",
"v0",
".",
"10",
"v0",
".",
"12",
"and",
"iojs"
] | d68277335c698e65db3bdd5191d7d3e6dc64076b | https://github.com/quartzjer/telehash-udp4/blob/d68277335c698e65db3bdd5191d7d3e6dc64076b/index.js#L11-L19 |
50,908 | quartzjer/telehash-udp4 | index.js | receive | function receive(msg, rinfo){
var packet = lob.decloak(msg);
if(!packet) packet = lob.decode(msg); // accept un-encrypted discovery broadcast hints
if(!packet) return mesh.log.info('dropping invalid packet from',rinfo,msg.toString('hex'));
tp.pipe(false, {type:'udp4',ip:rinfo.address,port:rinfo.port}, function(pipe){
mesh.receive(packet, pipe);
});
} | javascript | function receive(msg, rinfo){
var packet = lob.decloak(msg);
if(!packet) packet = lob.decode(msg); // accept un-encrypted discovery broadcast hints
if(!packet) return mesh.log.info('dropping invalid packet from',rinfo,msg.toString('hex'));
tp.pipe(false, {type:'udp4',ip:rinfo.address,port:rinfo.port}, function(pipe){
mesh.receive(packet, pipe);
});
} | [
"function",
"receive",
"(",
"msg",
",",
"rinfo",
")",
"{",
"var",
"packet",
"=",
"lob",
".",
"decloak",
"(",
"msg",
")",
";",
"if",
"(",
"!",
"packet",
")",
"packet",
"=",
"lob",
".",
"decode",
"(",
"msg",
")",
";",
"// accept un-encrypted discovery broadcast hints",
"if",
"(",
"!",
"packet",
")",
"return",
"mesh",
".",
"log",
".",
"info",
"(",
"'dropping invalid packet from'",
",",
"rinfo",
",",
"msg",
".",
"toString",
"(",
"'hex'",
")",
")",
";",
"tp",
".",
"pipe",
"(",
"false",
",",
"{",
"type",
":",
"'udp4'",
",",
"ip",
":",
"rinfo",
".",
"address",
",",
"port",
":",
"rinfo",
".",
"port",
"}",
",",
"function",
"(",
"pipe",
")",
"{",
"mesh",
".",
"receive",
"(",
"packet",
",",
"pipe",
")",
";",
"}",
")",
";",
"}"
] | generic handler to receive udp datagrams | [
"generic",
"handler",
"to",
"receive",
"udp",
"datagrams"
] | d68277335c698e65db3bdd5191d7d3e6dc64076b | https://github.com/quartzjer/telehash-udp4/blob/d68277335c698e65db3bdd5191d7d3e6dc64076b/index.js#L30-L37 |
50,909 | Knorcedger/apier-authenticator | index.js | findById | function findById(schemaName, id) {
return new Promise(function(resolve, reject) {
var Model = db.mongoose.model(schemaName);
Model
.findById(id)
.exec(function(error, result) {
if (error) {
reqlog.error('internal server error', error);
reject(error);
} else {
resolve(result || 'notFound');
}
});
});
} | javascript | function findById(schemaName, id) {
return new Promise(function(resolve, reject) {
var Model = db.mongoose.model(schemaName);
Model
.findById(id)
.exec(function(error, result) {
if (error) {
reqlog.error('internal server error', error);
reject(error);
} else {
resolve(result || 'notFound');
}
});
});
} | [
"function",
"findById",
"(",
"schemaName",
",",
"id",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"Model",
"=",
"db",
".",
"mongoose",
".",
"model",
"(",
"schemaName",
")",
";",
"Model",
".",
"findById",
"(",
"id",
")",
".",
"exec",
"(",
"function",
"(",
"error",
",",
"result",
")",
"{",
"if",
"(",
"error",
")",
"{",
"reqlog",
".",
"error",
"(",
"'internal server error'",
",",
"error",
")",
";",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"result",
"||",
"'notFound'",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | custom findById that has no limitations on the data it can load
@method findById
@param {string} schemaName The schema to load
@param {string} id The Object id to search with
@return {Promise} Just a promise :p | [
"custom",
"findById",
"that",
"has",
"no",
"limitations",
"on",
"the",
"data",
"it",
"can",
"load"
] | 852a1070067274af6b6c4a3c11c49992c5caf5a9 | https://github.com/Knorcedger/apier-authenticator/blob/852a1070067274af6b6c4a3c11c49992c5caf5a9/index.js#L47-L62 |
50,910 | andrewscwei/requiem | src/helpers/getInstanceNameFromElement.js | getInstanceNameFromElement | function getInstanceNameFromElement(element) {
let nameFromName = getAttribute(element, 'name');
if (nameFromName !== null && nameFromName !== undefined && nameFromName !== '')
return nameFromName;
else
return null;
} | javascript | function getInstanceNameFromElement(element) {
let nameFromName = getAttribute(element, 'name');
if (nameFromName !== null && nameFromName !== undefined && nameFromName !== '')
return nameFromName;
else
return null;
} | [
"function",
"getInstanceNameFromElement",
"(",
"element",
")",
"{",
"let",
"nameFromName",
"=",
"getAttribute",
"(",
"element",
",",
"'name'",
")",
";",
"if",
"(",
"nameFromName",
"!==",
"null",
"&&",
"nameFromName",
"!==",
"undefined",
"&&",
"nameFromName",
"!==",
"''",
")",
"return",
"nameFromName",
";",
"else",
"return",
"null",
";",
"}"
] | Gets the instance name from a DOM element.
@param {Node} element - The DOM element.
@return {string} The instance name.
@alias module:requiem~helpers.getInstanceNameFromElement | [
"Gets",
"the",
"instance",
"name",
"from",
"a",
"DOM",
"element",
"."
] | c4182bfffc9841c6de5718f689ad3c2060511777 | https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/helpers/getInstanceNameFromElement.js#L16-L23 |
50,911 | materliu/grunt-localhosts | tasks/localhosts.js | function (lines, cb) {
fs.stat(HOSTS, function (err, stat) {
if (err) {
cb(err);
} else {
var s = fs.createWriteStream(HOSTS, { mode: stat.mode });
s.on('close', cb);
s.on('error', cb);
lines.forEach(function (line, lineNum) {
if (Array.isArray(line)) {
line = line[0] + ' ' + line[1];
}
s.write(line + (lineNum === lines.length - 1 ? '' : EOL));
});
s.end();
}
});
} | javascript | function (lines, cb) {
fs.stat(HOSTS, function (err, stat) {
if (err) {
cb(err);
} else {
var s = fs.createWriteStream(HOSTS, { mode: stat.mode });
s.on('close', cb);
s.on('error', cb);
lines.forEach(function (line, lineNum) {
if (Array.isArray(line)) {
line = line[0] + ' ' + line[1];
}
s.write(line + (lineNum === lines.length - 1 ? '' : EOL));
});
s.end();
}
});
} | [
"function",
"(",
"lines",
",",
"cb",
")",
"{",
"fs",
".",
"stat",
"(",
"HOSTS",
",",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
")",
";",
"}",
"else",
"{",
"var",
"s",
"=",
"fs",
".",
"createWriteStream",
"(",
"HOSTS",
",",
"{",
"mode",
":",
"stat",
".",
"mode",
"}",
")",
";",
"s",
".",
"on",
"(",
"'close'",
",",
"cb",
")",
";",
"s",
".",
"on",
"(",
"'error'",
",",
"cb",
")",
";",
"lines",
".",
"forEach",
"(",
"function",
"(",
"line",
",",
"lineNum",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"line",
")",
")",
"{",
"line",
"=",
"line",
"[",
"0",
"]",
"+",
"' '",
"+",
"line",
"[",
"1",
"]",
";",
"}",
"s",
".",
"write",
"(",
"line",
"+",
"(",
"lineNum",
"===",
"lines",
".",
"length",
"-",
"1",
"?",
"''",
":",
"EOL",
")",
")",
";",
"}",
")",
";",
"s",
".",
"end",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] | Write out an array of lines to the host file. Assumes that they're in the
format that `get` returns.
@param {Array.<string|Array.<string>>} lines
@param {function(Error)} cb | [
"Write",
"out",
"an",
"array",
"of",
"lines",
"to",
"the",
"host",
"file",
".",
"Assumes",
"that",
"they",
"re",
"in",
"the",
"format",
"that",
"get",
"returns",
"."
] | 65115f9f876509eeda302c9f4b76e12168cd382d | https://github.com/materliu/grunt-localhosts/blob/65115f9f876509eeda302c9f4b76e12168cd382d/tasks/localhosts.js#L112-L130 |
|
50,912 | haraldrudell/apprunner | lib/anomaly.js | getBody | function getBody(id, arr) {
var result = []
// heading and location: 'Anomaly 2012-08-11T03:23:49.725Z'
var now = new Date
result.push('Anomaly ' + now.toISOString() + ' ' + haraldutil.getISOPacific(now))
if (id) result.push()
result.push('host:' + os.hostname() +
' app:' + (opts.app || 'unknown') +
' api: ' + (id || 'unknown')) +
' pid: ' + process.pid
// output each provided argument
arr.forEach(function (value, index) {
result.push((index + 1) + ': ' + haraldutil.inspectDeep(value))
})
// a stack trace for the invocation of anomaly
var o = haraldutil.parseTrace(new Error)
if (o && Array.isArray(o.frames)) {
result.push('Anomaly invoked from:')
for (var ix = 2; ix < o.frames.length; ix++) {
var frame = o.frames[ix]
var s = [' ']
if (frame.func) s.push(frame.func)
if (frame.as) s.push('as:', frame.as)
if (frame.file) s.push(frame.file + ':' + frame.line + ':' + frame.column)
if (frame.folder) s.push(frame.folder)
if (frame.source) s.push('source:', frame.source)
result.push(s.join(' '))
}
}
return result.join('\n')
} | javascript | function getBody(id, arr) {
var result = []
// heading and location: 'Anomaly 2012-08-11T03:23:49.725Z'
var now = new Date
result.push('Anomaly ' + now.toISOString() + ' ' + haraldutil.getISOPacific(now))
if (id) result.push()
result.push('host:' + os.hostname() +
' app:' + (opts.app || 'unknown') +
' api: ' + (id || 'unknown')) +
' pid: ' + process.pid
// output each provided argument
arr.forEach(function (value, index) {
result.push((index + 1) + ': ' + haraldutil.inspectDeep(value))
})
// a stack trace for the invocation of anomaly
var o = haraldutil.parseTrace(new Error)
if (o && Array.isArray(o.frames)) {
result.push('Anomaly invoked from:')
for (var ix = 2; ix < o.frames.length; ix++) {
var frame = o.frames[ix]
var s = [' ']
if (frame.func) s.push(frame.func)
if (frame.as) s.push('as:', frame.as)
if (frame.file) s.push(frame.file + ':' + frame.line + ':' + frame.column)
if (frame.folder) s.push(frame.folder)
if (frame.source) s.push('source:', frame.source)
result.push(s.join(' '))
}
}
return result.join('\n')
} | [
"function",
"getBody",
"(",
"id",
",",
"arr",
")",
"{",
"var",
"result",
"=",
"[",
"]",
"// heading and location: 'Anomaly 2012-08-11T03:23:49.725Z'",
"var",
"now",
"=",
"new",
"Date",
"result",
".",
"push",
"(",
"'Anomaly '",
"+",
"now",
".",
"toISOString",
"(",
")",
"+",
"' '",
"+",
"haraldutil",
".",
"getISOPacific",
"(",
"now",
")",
")",
"if",
"(",
"id",
")",
"result",
".",
"push",
"(",
")",
"result",
".",
"push",
"(",
"'host:'",
"+",
"os",
".",
"hostname",
"(",
")",
"+",
"' app:'",
"+",
"(",
"opts",
".",
"app",
"||",
"'unknown'",
")",
"+",
"' api: '",
"+",
"(",
"id",
"||",
"'unknown'",
")",
")",
"+",
"' pid: '",
"+",
"process",
".",
"pid",
"// output each provided argument",
"arr",
".",
"forEach",
"(",
"function",
"(",
"value",
",",
"index",
")",
"{",
"result",
".",
"push",
"(",
"(",
"index",
"+",
"1",
")",
"+",
"': '",
"+",
"haraldutil",
".",
"inspectDeep",
"(",
"value",
")",
")",
"}",
")",
"// a stack trace for the invocation of anomaly",
"var",
"o",
"=",
"haraldutil",
".",
"parseTrace",
"(",
"new",
"Error",
")",
"if",
"(",
"o",
"&&",
"Array",
".",
"isArray",
"(",
"o",
".",
"frames",
")",
")",
"{",
"result",
".",
"push",
"(",
"'Anomaly invoked from:'",
")",
"for",
"(",
"var",
"ix",
"=",
"2",
";",
"ix",
"<",
"o",
".",
"frames",
".",
"length",
";",
"ix",
"++",
")",
"{",
"var",
"frame",
"=",
"o",
".",
"frames",
"[",
"ix",
"]",
"var",
"s",
"=",
"[",
"' '",
"]",
"if",
"(",
"frame",
".",
"func",
")",
"s",
".",
"push",
"(",
"frame",
".",
"func",
")",
"if",
"(",
"frame",
".",
"as",
")",
"s",
".",
"push",
"(",
"'as:'",
",",
"frame",
".",
"as",
")",
"if",
"(",
"frame",
".",
"file",
")",
"s",
".",
"push",
"(",
"frame",
".",
"file",
"+",
"':'",
"+",
"frame",
".",
"line",
"+",
"':'",
"+",
"frame",
".",
"column",
")",
"if",
"(",
"frame",
".",
"folder",
")",
"s",
".",
"push",
"(",
"frame",
".",
"folder",
")",
"if",
"(",
"frame",
".",
"source",
")",
"s",
".",
"push",
"(",
"'source:'",
",",
"frame",
".",
"source",
")",
"result",
".",
"push",
"(",
"s",
".",
"join",
"(",
"' '",
")",
")",
"}",
"}",
"return",
"result",
".",
"join",
"(",
"'\\n'",
")",
"}"
] | assemble the text body of one anomaly | [
"assemble",
"the",
"text",
"body",
"of",
"one",
"anomaly"
] | 8d7dead166c919d160b429e00c49a62027994c33 | https://github.com/haraldrudell/apprunner/blob/8d7dead166c919d160b429e00c49a62027994c33/lib/anomaly.js#L93-L127 |
50,913 | haraldrudell/apprunner | lib/anomaly.js | sendQueue | function sendQueue() {
var subject = ['Anomaly Report']
if (!opts.noSubjectApp && opts.app) subject.push(opts.app)
if (!opts.noSubjectHost) subject.push(os.hostname())
subject = subject.join(' ')
var body
if (skipCounter > 0) { // notify of skipped emails
enqueuedEmails.push('Skipped:' + skipCounter)
skipCounter = 0
}
body = enqueuedEmails.join('\n\n')
enqueuedEmails = []
emailer.send({subject: subject, body: body}) // TODO error handling when haraldops and emailer updated
lastSent = Date.now()
startSilentPeriod()
} | javascript | function sendQueue() {
var subject = ['Anomaly Report']
if (!opts.noSubjectApp && opts.app) subject.push(opts.app)
if (!opts.noSubjectHost) subject.push(os.hostname())
subject = subject.join(' ')
var body
if (skipCounter > 0) { // notify of skipped emails
enqueuedEmails.push('Skipped:' + skipCounter)
skipCounter = 0
}
body = enqueuedEmails.join('\n\n')
enqueuedEmails = []
emailer.send({subject: subject, body: body}) // TODO error handling when haraldops and emailer updated
lastSent = Date.now()
startSilentPeriod()
} | [
"function",
"sendQueue",
"(",
")",
"{",
"var",
"subject",
"=",
"[",
"'Anomaly Report'",
"]",
"if",
"(",
"!",
"opts",
".",
"noSubjectApp",
"&&",
"opts",
".",
"app",
")",
"subject",
".",
"push",
"(",
"opts",
".",
"app",
")",
"if",
"(",
"!",
"opts",
".",
"noSubjectHost",
")",
"subject",
".",
"push",
"(",
"os",
".",
"hostname",
"(",
")",
")",
"subject",
"=",
"subject",
".",
"join",
"(",
"' '",
")",
"var",
"body",
"if",
"(",
"skipCounter",
">",
"0",
")",
"{",
"// notify of skipped emails",
"enqueuedEmails",
".",
"push",
"(",
"'Skipped:'",
"+",
"skipCounter",
")",
"skipCounter",
"=",
"0",
"}",
"body",
"=",
"enqueuedEmails",
".",
"join",
"(",
"'\\n\\n'",
")",
"enqueuedEmails",
"=",
"[",
"]",
"emailer",
".",
"send",
"(",
"{",
"subject",
":",
"subject",
",",
"body",
":",
"body",
"}",
")",
"// TODO error handling when haraldops and emailer updated",
"lastSent",
"=",
"Date",
".",
"now",
"(",
")",
"startSilentPeriod",
"(",
")",
"}"
] | flush the send queue to an email | [
"flush",
"the",
"send",
"queue",
"to",
"an",
"email"
] | 8d7dead166c919d160b429e00c49a62027994c33 | https://github.com/haraldrudell/apprunner/blob/8d7dead166c919d160b429e00c49a62027994c33/lib/anomaly.js#L137-L155 |
50,914 | jm-root/core | packages/jm-event/dist/index.esm.js | EventEmitter | function EventEmitter() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, EventEmitter);
this._events = {};
if (opts.async) this.emit = emitAsync;
} | javascript | function EventEmitter() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, EventEmitter);
this._events = {};
if (opts.async) this.emit = emitAsync;
} | [
"function",
"EventEmitter",
"(",
")",
"{",
"var",
"opts",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"{",
"}",
";",
"_classCallCheck",
"(",
"this",
",",
"EventEmitter",
")",
";",
"this",
".",
"_events",
"=",
"{",
"}",
";",
"if",
"(",
"opts",
".",
"async",
")",
"this",
".",
"emit",
"=",
"emitAsync",
";",
"}"
] | Create an eventEmitter. | [
"Create",
"an",
"eventEmitter",
"."
] | d05c7356a2991edf861e5c1aac2d0bc971cfdff3 | https://github.com/jm-root/core/blob/d05c7356a2991edf861e5c1aac2d0bc971cfdff3/packages/jm-event/dist/index.esm.js#L346-L353 |
50,915 | Everyplay/backbone-db | lib/db.js | function(method, model, options) {
options = options || {};
var self = this;
var db;
if (!(self instanceof Db)) {
db = model.db || options.db;
debug('using db from model');
} else {
debug('using self as database');
db = self;
}
debug('sync %s %s %s %s',
method,
model.type,
JSON.stringify(model.toJSON(options)),
JSON.stringify(options)
);
var start = Date.now();
function callback(err, res, resp) {
debug('callback ' + err + ' ' + JSON.stringify(res));
var elapsed = Date.now() - start;
var syncInfo = {
method: method,
type: model.type,
elapsed: elapsed,
model: model.toJSON(options),
res: JSON.stringify(res)
};
if (err) {
syncInfo.error = err;
}
if (options && options.where) {
syncInfo.where = _.clone(options.where);
}
if (db.trigger) {
db.trigger('sync_info', syncInfo);
}
if ((err && options.error) || (!err && !res && options.error)) {
var errorMsg = pff('%s (%s) not found', model.type, model.id);
err = err || new errors.NotFoundError(errorMsg);
return options.error(err, resp);
} else if (options.success && res) {
debug('success %s', JSON.stringify(res));
return options.success(res, resp);
}
}
switch (method) {
case 'create':
return db.create(model, options, callback);
case 'update':
return db.update(model, options, callback);
case 'delete':
return db.destroy(model, options, callback);
case 'read':
if (typeof model.get(model.idAttribute) !== 'undefined') {
return db.find(model, options, callback);
}
return db.findAll(model, options, callback);
default:
throw new Error('method ' + method + ' not supported');
}
} | javascript | function(method, model, options) {
options = options || {};
var self = this;
var db;
if (!(self instanceof Db)) {
db = model.db || options.db;
debug('using db from model');
} else {
debug('using self as database');
db = self;
}
debug('sync %s %s %s %s',
method,
model.type,
JSON.stringify(model.toJSON(options)),
JSON.stringify(options)
);
var start = Date.now();
function callback(err, res, resp) {
debug('callback ' + err + ' ' + JSON.stringify(res));
var elapsed = Date.now() - start;
var syncInfo = {
method: method,
type: model.type,
elapsed: elapsed,
model: model.toJSON(options),
res: JSON.stringify(res)
};
if (err) {
syncInfo.error = err;
}
if (options && options.where) {
syncInfo.where = _.clone(options.where);
}
if (db.trigger) {
db.trigger('sync_info', syncInfo);
}
if ((err && options.error) || (!err && !res && options.error)) {
var errorMsg = pff('%s (%s) not found', model.type, model.id);
err = err || new errors.NotFoundError(errorMsg);
return options.error(err, resp);
} else if (options.success && res) {
debug('success %s', JSON.stringify(res));
return options.success(res, resp);
}
}
switch (method) {
case 'create':
return db.create(model, options, callback);
case 'update':
return db.update(model, options, callback);
case 'delete':
return db.destroy(model, options, callback);
case 'read':
if (typeof model.get(model.idAttribute) !== 'undefined') {
return db.find(model, options, callback);
}
return db.findAll(model, options, callback);
default:
throw new Error('method ' + method + ' not supported');
}
} | [
"function",
"(",
"method",
",",
"model",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"self",
"=",
"this",
";",
"var",
"db",
";",
"if",
"(",
"!",
"(",
"self",
"instanceof",
"Db",
")",
")",
"{",
"db",
"=",
"model",
".",
"db",
"||",
"options",
".",
"db",
";",
"debug",
"(",
"'using db from model'",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'using self as database'",
")",
";",
"db",
"=",
"self",
";",
"}",
"debug",
"(",
"'sync %s %s %s %s'",
",",
"method",
",",
"model",
".",
"type",
",",
"JSON",
".",
"stringify",
"(",
"model",
".",
"toJSON",
"(",
"options",
")",
")",
",",
"JSON",
".",
"stringify",
"(",
"options",
")",
")",
";",
"var",
"start",
"=",
"Date",
".",
"now",
"(",
")",
";",
"function",
"callback",
"(",
"err",
",",
"res",
",",
"resp",
")",
"{",
"debug",
"(",
"'callback '",
"+",
"err",
"+",
"' '",
"+",
"JSON",
".",
"stringify",
"(",
"res",
")",
")",
";",
"var",
"elapsed",
"=",
"Date",
".",
"now",
"(",
")",
"-",
"start",
";",
"var",
"syncInfo",
"=",
"{",
"method",
":",
"method",
",",
"type",
":",
"model",
".",
"type",
",",
"elapsed",
":",
"elapsed",
",",
"model",
":",
"model",
".",
"toJSON",
"(",
"options",
")",
",",
"res",
":",
"JSON",
".",
"stringify",
"(",
"res",
")",
"}",
";",
"if",
"(",
"err",
")",
"{",
"syncInfo",
".",
"error",
"=",
"err",
";",
"}",
"if",
"(",
"options",
"&&",
"options",
".",
"where",
")",
"{",
"syncInfo",
".",
"where",
"=",
"_",
".",
"clone",
"(",
"options",
".",
"where",
")",
";",
"}",
"if",
"(",
"db",
".",
"trigger",
")",
"{",
"db",
".",
"trigger",
"(",
"'sync_info'",
",",
"syncInfo",
")",
";",
"}",
"if",
"(",
"(",
"err",
"&&",
"options",
".",
"error",
")",
"||",
"(",
"!",
"err",
"&&",
"!",
"res",
"&&",
"options",
".",
"error",
")",
")",
"{",
"var",
"errorMsg",
"=",
"pff",
"(",
"'%s (%s) not found'",
",",
"model",
".",
"type",
",",
"model",
".",
"id",
")",
";",
"err",
"=",
"err",
"||",
"new",
"errors",
".",
"NotFoundError",
"(",
"errorMsg",
")",
";",
"return",
"options",
".",
"error",
"(",
"err",
",",
"resp",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"success",
"&&",
"res",
")",
"{",
"debug",
"(",
"'success %s'",
",",
"JSON",
".",
"stringify",
"(",
"res",
")",
")",
";",
"return",
"options",
".",
"success",
"(",
"res",
",",
"resp",
")",
";",
"}",
"}",
"switch",
"(",
"method",
")",
"{",
"case",
"'create'",
":",
"return",
"db",
".",
"create",
"(",
"model",
",",
"options",
",",
"callback",
")",
";",
"case",
"'update'",
":",
"return",
"db",
".",
"update",
"(",
"model",
",",
"options",
",",
"callback",
")",
";",
"case",
"'delete'",
":",
"return",
"db",
".",
"destroy",
"(",
"model",
",",
"options",
",",
"callback",
")",
";",
"case",
"'read'",
":",
"if",
"(",
"typeof",
"model",
".",
"get",
"(",
"model",
".",
"idAttribute",
")",
"!==",
"'undefined'",
")",
"{",
"return",
"db",
".",
"find",
"(",
"model",
",",
"options",
",",
"callback",
")",
";",
"}",
"return",
"db",
".",
"findAll",
"(",
"model",
",",
"options",
",",
"callback",
")",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'method '",
"+",
"method",
"+",
"' not supported'",
")",
";",
"}",
"}"
] | Default backbone sync which call the correct
database adapter function based on method.
@param {String} method (create, read, update, delete)
@param {Model} model instance of Backbone.Model
@param {Object} options options fon sync
@returns{Any} None | [
"Default",
"backbone",
"sync",
"which",
"call",
"the",
"correct",
"database",
"adapter",
"function",
"based",
"on",
"method",
"."
] | d68dd412f34a92fdfd91bb85668aceaf10d4fba4 | https://github.com/Everyplay/backbone-db/blob/d68dd412f34a92fdfd91bb85668aceaf10d4fba4/lib/db.js#L24-L89 |
|
50,916 | briancsparks/run-anywhere | lib/v2/express-host.js | hook | function hook(req, res, next) {
var _end = res.end;
var _write = res.write;
//var _on = res.on;
res.write = function(chunk, encoding) {
// ... other things
// Call the original
_write.call(this, chunk, encoding);
// Note: in some cases, you have to restore the function:
// res.write = _write;
};
res.end = function(chunk, encoding) {
// ... other things
// Call the original
_end.call(this, chunk, encoding);
// Note: in some cases, you have to restore the function:
// res.end = _end;
};
return next();
} | javascript | function hook(req, res, next) {
var _end = res.end;
var _write = res.write;
//var _on = res.on;
res.write = function(chunk, encoding) {
// ... other things
// Call the original
_write.call(this, chunk, encoding);
// Note: in some cases, you have to restore the function:
// res.write = _write;
};
res.end = function(chunk, encoding) {
// ... other things
// Call the original
_end.call(this, chunk, encoding);
// Note: in some cases, you have to restore the function:
// res.end = _end;
};
return next();
} | [
"function",
"hook",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"_end",
"=",
"res",
".",
"end",
";",
"var",
"_write",
"=",
"res",
".",
"write",
";",
"//var _on = res.on;",
"res",
".",
"write",
"=",
"function",
"(",
"chunk",
",",
"encoding",
")",
"{",
"// ... other things",
"// Call the original",
"_write",
".",
"call",
"(",
"this",
",",
"chunk",
",",
"encoding",
")",
";",
"// Note: in some cases, you have to restore the function:",
"// res.write = _write;",
"}",
";",
"res",
".",
"end",
"=",
"function",
"(",
"chunk",
",",
"encoding",
")",
"{",
"// ... other things",
"// Call the original",
"_end",
".",
"call",
"(",
"this",
",",
"chunk",
",",
"encoding",
")",
";",
"// Note: in some cases, you have to restore the function:",
"// res.end = _end;",
"}",
";",
"return",
"next",
"(",
")",
";",
"}"
] | Example of how to do Express.js middleware when you need to do something at the end
of the request.
@param {ServerRequest} req
@param {ServerResponse} res
@param {function} next | [
"Example",
"of",
"how",
"to",
"do",
"Express",
".",
"js",
"middleware",
"when",
"you",
"need",
"to",
"do",
"something",
"at",
"the",
"end",
"of",
"the",
"request",
"."
] | b73d170dc86cc00e6562ca8544fceb3478d51e20 | https://github.com/briancsparks/run-anywhere/blob/b73d170dc86cc00e6562ca8544fceb3478d51e20/lib/v2/express-host.js#L197-L223 |
50,917 | PanthR/panthrMath | panthrMath/utils.js | inferEndpoint | function inferEndpoint(f, y, lower, e) {
var comp; // comparison of f(e) and f(2*e)
if (e != null) { return e; }
e = lower ? -1 : 1;
comp = f(e) < f(2 * e);
while (f(e) > y !== comp) {
e *= 2;
if (-e > 1e200) {
throw new Error('Binary search: Cannot find ' + (lower ? 'lower' : 'upper') + ' endpoint.');
}
}
return e;
} | javascript | function inferEndpoint(f, y, lower, e) {
var comp; // comparison of f(e) and f(2*e)
if (e != null) { return e; }
e = lower ? -1 : 1;
comp = f(e) < f(2 * e);
while (f(e) > y !== comp) {
e *= 2;
if (-e > 1e200) {
throw new Error('Binary search: Cannot find ' + (lower ? 'lower' : 'upper') + ' endpoint.');
}
}
return e;
} | [
"function",
"inferEndpoint",
"(",
"f",
",",
"y",
",",
"lower",
",",
"e",
")",
"{",
"var",
"comp",
";",
"// comparison of f(e) and f(2*e)",
"if",
"(",
"e",
"!=",
"null",
")",
"{",
"return",
"e",
";",
"}",
"e",
"=",
"lower",
"?",
"-",
"1",
":",
"1",
";",
"comp",
"=",
"f",
"(",
"e",
")",
"<",
"f",
"(",
"2",
"*",
"e",
")",
";",
"while",
"(",
"f",
"(",
"e",
")",
">",
"y",
"!==",
"comp",
")",
"{",
"e",
"*=",
"2",
";",
"if",
"(",
"-",
"e",
">",
"1e200",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Binary search: Cannot find '",
"+",
"(",
"lower",
"?",
"'lower'",
":",
"'upper'",
")",
"+",
"' endpoint.'",
")",
";",
"}",
"}",
"return",
"e",
";",
"}"
] | lower = true means looking for lower endpoint = false means looking for upper endpoint if "e" is provided it is just returned | [
"lower",
"=",
"true",
"means",
"looking",
"for",
"lower",
"endpoint",
"=",
"false",
"means",
"looking",
"for",
"upper",
"endpoint",
"if",
"e",
"is",
"provided",
"it",
"is",
"just",
"returned"
] | 54d249ca9903a9535f963da711bd3a87fb229c0b | https://github.com/PanthR/panthrMath/blob/54d249ca9903a9535f963da711bd3a87fb229c0b/panthrMath/utils.js#L433-L448 |
50,918 | pattern-library/pattern-library-utilities | lib/logger.js | getLoggerOptions | function getLoggerOptions() {
'use strict';
var defaultOptions = {
logger: {
level: 'info',
silent: false,
exitOnError: true,
logFile: ''
}
};
var loggerOptions = {};
// get the project's options
var projectOptions = getOptions.getProjectOptions();
// merge project options with default options; project options take precedence
var options = getOptions.mergeOptions(defaultOptions, projectOptions);
// check if we're unit testing
if (isTest()) {
options.logger.level = 'warn';
}
// basic transports from options
loggerOptions.transports = [
new winston.transports.Console({
level: options.logger.level,
silent: options.logger.silent,
colorize: true
})
];
// check if we should add a log file
if (options.logger.logFile) {
loggerOptions.transports.push(
new winston.transports.File({
filename: options.logger.logFile,
level: options.logger.level
})
);
}
loggerOptions.exitOnError = options.logger.exitOnError;
return loggerOptions;
} | javascript | function getLoggerOptions() {
'use strict';
var defaultOptions = {
logger: {
level: 'info',
silent: false,
exitOnError: true,
logFile: ''
}
};
var loggerOptions = {};
// get the project's options
var projectOptions = getOptions.getProjectOptions();
// merge project options with default options; project options take precedence
var options = getOptions.mergeOptions(defaultOptions, projectOptions);
// check if we're unit testing
if (isTest()) {
options.logger.level = 'warn';
}
// basic transports from options
loggerOptions.transports = [
new winston.transports.Console({
level: options.logger.level,
silent: options.logger.silent,
colorize: true
})
];
// check if we should add a log file
if (options.logger.logFile) {
loggerOptions.transports.push(
new winston.transports.File({
filename: options.logger.logFile,
level: options.logger.level
})
);
}
loggerOptions.exitOnError = options.logger.exitOnError;
return loggerOptions;
} | [
"function",
"getLoggerOptions",
"(",
")",
"{",
"'use strict'",
";",
"var",
"defaultOptions",
"=",
"{",
"logger",
":",
"{",
"level",
":",
"'info'",
",",
"silent",
":",
"false",
",",
"exitOnError",
":",
"true",
",",
"logFile",
":",
"''",
"}",
"}",
";",
"var",
"loggerOptions",
"=",
"{",
"}",
";",
"// get the project's options",
"var",
"projectOptions",
"=",
"getOptions",
".",
"getProjectOptions",
"(",
")",
";",
"// merge project options with default options; project options take precedence",
"var",
"options",
"=",
"getOptions",
".",
"mergeOptions",
"(",
"defaultOptions",
",",
"projectOptions",
")",
";",
"// check if we're unit testing",
"if",
"(",
"isTest",
"(",
")",
")",
"{",
"options",
".",
"logger",
".",
"level",
"=",
"'warn'",
";",
"}",
"// basic transports from options",
"loggerOptions",
".",
"transports",
"=",
"[",
"new",
"winston",
".",
"transports",
".",
"Console",
"(",
"{",
"level",
":",
"options",
".",
"logger",
".",
"level",
",",
"silent",
":",
"options",
".",
"logger",
".",
"silent",
",",
"colorize",
":",
"true",
"}",
")",
"]",
";",
"// check if we should add a log file",
"if",
"(",
"options",
".",
"logger",
".",
"logFile",
")",
"{",
"loggerOptions",
".",
"transports",
".",
"push",
"(",
"new",
"winston",
".",
"transports",
".",
"File",
"(",
"{",
"filename",
":",
"options",
".",
"logger",
".",
"logFile",
",",
"level",
":",
"options",
".",
"logger",
".",
"level",
"}",
")",
")",
";",
"}",
"loggerOptions",
".",
"exitOnError",
"=",
"options",
".",
"logger",
".",
"exitOnError",
";",
"return",
"loggerOptions",
";",
"}"
] | Get options for logging system. Checks project's options against defaults, and sets up Winston's transport requirements
@return {Object} Contains Winston-specific options for transports and exiting on errors. | [
"Get",
"options",
"for",
"logging",
"system",
".",
"Checks",
"project",
"s",
"options",
"against",
"defaults",
"and",
"sets",
"up",
"Winston",
"s",
"transport",
"requirements"
] | a0198f7bb698eb5b859576b11afa3d0ebd3e5911 | https://github.com/pattern-library/pattern-library-utilities/blob/a0198f7bb698eb5b859576b11afa3d0ebd3e5911/lib/logger.js#L16-L64 |
50,919 | Nazariglez/perenquen | lib/pixi/src/mesh/Rope.js | Rope | function Rope(texture, points)
{
Mesh.call(this, texture);
/*
* @member {Array} An array of points that determine the rope
*/
this.points = points;
/*
* @member {Float32Array} An array of vertices used to construct this rope.
*/
this.vertices = new Float32Array(points.length * 4);
/*
* @member {Float32Array} The WebGL Uvs of the rope.
*/
this.uvs = new Float32Array(points.length * 4);
/*
* @member {Float32Array} An array containing the color components
*/
this.colors = new Float32Array(points.length * 2);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
this.indices = new Uint16Array(points.length * 2);
this.refresh();
} | javascript | function Rope(texture, points)
{
Mesh.call(this, texture);
/*
* @member {Array} An array of points that determine the rope
*/
this.points = points;
/*
* @member {Float32Array} An array of vertices used to construct this rope.
*/
this.vertices = new Float32Array(points.length * 4);
/*
* @member {Float32Array} The WebGL Uvs of the rope.
*/
this.uvs = new Float32Array(points.length * 4);
/*
* @member {Float32Array} An array containing the color components
*/
this.colors = new Float32Array(points.length * 2);
/*
* @member {Uint16Array} An array containing the indices of the vertices
*/
this.indices = new Uint16Array(points.length * 2);
this.refresh();
} | [
"function",
"Rope",
"(",
"texture",
",",
"points",
")",
"{",
"Mesh",
".",
"call",
"(",
"this",
",",
"texture",
")",
";",
"/*\n * @member {Array} An array of points that determine the rope\n */",
"this",
".",
"points",
"=",
"points",
";",
"/*\n * @member {Float32Array} An array of vertices used to construct this rope.\n */",
"this",
".",
"vertices",
"=",
"new",
"Float32Array",
"(",
"points",
".",
"length",
"*",
"4",
")",
";",
"/*\n * @member {Float32Array} The WebGL Uvs of the rope.\n */",
"this",
".",
"uvs",
"=",
"new",
"Float32Array",
"(",
"points",
".",
"length",
"*",
"4",
")",
";",
"/*\n * @member {Float32Array} An array containing the color components\n */",
"this",
".",
"colors",
"=",
"new",
"Float32Array",
"(",
"points",
".",
"length",
"*",
"2",
")",
";",
"/*\n * @member {Uint16Array} An array containing the indices of the vertices\n */",
"this",
".",
"indices",
"=",
"new",
"Uint16Array",
"(",
"points",
".",
"length",
"*",
"2",
")",
";",
"this",
".",
"refresh",
"(",
")",
";",
"}"
] | The rope allows you to draw a texture across several points and them manipulate these points
```js
for (var i = 0; i < 20; i++) {
points.push(new PIXI.Point(i * 50, 0));
};
var rope = new PIXI.Rope(PIXI.Texture.fromImage("snake.png"), points);
```
@class
@extends Mesh
@memberof PIXI.mesh
@param {Texture} texture - The texture to use on the rope.
@param {Array} points - An array of {Point} objects to construct this rope. | [
"The",
"rope",
"allows",
"you",
"to",
"draw",
"a",
"texture",
"across",
"several",
"points",
"and",
"them",
"manipulate",
"these",
"points"
] | e023964d05afeefebdcac4e2044819fdfa3899ae | https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/mesh/Rope.js#L20-L50 |
50,920 | erraroo/ember-cli-erraroo | vendor/timing.js | function(opts) {
var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
if (performance === undefined) {
//console.log('Unfortunately, your browser does not support the Navigation Timing API');
return;
}
var timing = performance.timing;
var api = {};
opts = opts || {};
if (timing) {
if(opts && !opts.simple) {
for (var k in timing) {
if (timing.hasOwnProperty(k)) {
api[k] = timing[k];
}
}
}
// Time to first paint
if (api.firstPaint === undefined) {
// All times are relative times to the start time within the
// same objects
var firstPaint = 0;
// Chrome
if (window.chrome && window.chrome.loadTimes) {
// Convert to ms
firstPaint = window.chrome.loadTimes().firstPaintTime * 1000;
api.firstPaintTime = firstPaint - (window.chrome.loadTimes().startLoadTime*1000);
}
// IE
else if (typeof window.performance.timing.msFirstPaint === 'number') {
firstPaint = window.performance.timing.msFirstPaint;
api.firstPaintTime = firstPaint - window.performance.timing.navigationStart;
}
// Firefox
// This will use the first times after MozAfterPaint fires
//else if (window.performance.timing.navigationStart && typeof InstallTrigger !== 'undefined') {
// api.firstPaint = window.performance.timing.navigationStart;
// api.firstPaintTime = mozFirstPaintTime - window.performance.timing.navigationStart;
//}
if (opts && !opts.simple) {
api.firstPaint = firstPaint;
}
}
// Total time from start to load
api.loadTime = timing.loadEventEnd - timing.fetchStart;
// Time spent constructing the DOM tree
api.domReadyTime = timing.domComplete - timing.domInteractive;
// Time consumed preparing the new page
api.readyStart = timing.fetchStart - timing.navigationStart;
// Time spent during redirection
api.redirectTime = timing.redirectEnd - timing.redirectStart;
// AppCache
api.appcacheTime = timing.domainLookupStart - timing.fetchStart;
// Time spent unloading documents
api.unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart;
// DNS query time
api.lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart;
// TCP connection time
api.connectTime = timing.connectEnd - timing.connectStart;
// Time spent during the request
api.requestTime = timing.responseEnd - timing.requestStart;
// Request to completion of the DOM loading
api.initDomTreeTime = timing.domInteractive - timing.responseEnd;
// Load event time
api.loadEventTime = timing.loadEventEnd - timing.loadEventStart;
}
return api;
} | javascript | function(opts) {
var performance = window.performance || window.webkitPerformance || window.msPerformance || window.mozPerformance;
if (performance === undefined) {
//console.log('Unfortunately, your browser does not support the Navigation Timing API');
return;
}
var timing = performance.timing;
var api = {};
opts = opts || {};
if (timing) {
if(opts && !opts.simple) {
for (var k in timing) {
if (timing.hasOwnProperty(k)) {
api[k] = timing[k];
}
}
}
// Time to first paint
if (api.firstPaint === undefined) {
// All times are relative times to the start time within the
// same objects
var firstPaint = 0;
// Chrome
if (window.chrome && window.chrome.loadTimes) {
// Convert to ms
firstPaint = window.chrome.loadTimes().firstPaintTime * 1000;
api.firstPaintTime = firstPaint - (window.chrome.loadTimes().startLoadTime*1000);
}
// IE
else if (typeof window.performance.timing.msFirstPaint === 'number') {
firstPaint = window.performance.timing.msFirstPaint;
api.firstPaintTime = firstPaint - window.performance.timing.navigationStart;
}
// Firefox
// This will use the first times after MozAfterPaint fires
//else if (window.performance.timing.navigationStart && typeof InstallTrigger !== 'undefined') {
// api.firstPaint = window.performance.timing.navigationStart;
// api.firstPaintTime = mozFirstPaintTime - window.performance.timing.navigationStart;
//}
if (opts && !opts.simple) {
api.firstPaint = firstPaint;
}
}
// Total time from start to load
api.loadTime = timing.loadEventEnd - timing.fetchStart;
// Time spent constructing the DOM tree
api.domReadyTime = timing.domComplete - timing.domInteractive;
// Time consumed preparing the new page
api.readyStart = timing.fetchStart - timing.navigationStart;
// Time spent during redirection
api.redirectTime = timing.redirectEnd - timing.redirectStart;
// AppCache
api.appcacheTime = timing.domainLookupStart - timing.fetchStart;
// Time spent unloading documents
api.unloadEventTime = timing.unloadEventEnd - timing.unloadEventStart;
// DNS query time
api.lookupDomainTime = timing.domainLookupEnd - timing.domainLookupStart;
// TCP connection time
api.connectTime = timing.connectEnd - timing.connectStart;
// Time spent during the request
api.requestTime = timing.responseEnd - timing.requestStart;
// Request to completion of the DOM loading
api.initDomTreeTime = timing.domInteractive - timing.responseEnd;
// Load event time
api.loadEventTime = timing.loadEventEnd - timing.loadEventStart;
}
return api;
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"performance",
"=",
"window",
".",
"performance",
"||",
"window",
".",
"webkitPerformance",
"||",
"window",
".",
"msPerformance",
"||",
"window",
".",
"mozPerformance",
";",
"if",
"(",
"performance",
"===",
"undefined",
")",
"{",
"//console.log('Unfortunately, your browser does not support the Navigation Timing API');",
"return",
";",
"}",
"var",
"timing",
"=",
"performance",
".",
"timing",
";",
"var",
"api",
"=",
"{",
"}",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"if",
"(",
"timing",
")",
"{",
"if",
"(",
"opts",
"&&",
"!",
"opts",
".",
"simple",
")",
"{",
"for",
"(",
"var",
"k",
"in",
"timing",
")",
"{",
"if",
"(",
"timing",
".",
"hasOwnProperty",
"(",
"k",
")",
")",
"{",
"api",
"[",
"k",
"]",
"=",
"timing",
"[",
"k",
"]",
";",
"}",
"}",
"}",
"// Time to first paint",
"if",
"(",
"api",
".",
"firstPaint",
"===",
"undefined",
")",
"{",
"// All times are relative times to the start time within the",
"// same objects",
"var",
"firstPaint",
"=",
"0",
";",
"// Chrome",
"if",
"(",
"window",
".",
"chrome",
"&&",
"window",
".",
"chrome",
".",
"loadTimes",
")",
"{",
"// Convert to ms",
"firstPaint",
"=",
"window",
".",
"chrome",
".",
"loadTimes",
"(",
")",
".",
"firstPaintTime",
"*",
"1000",
";",
"api",
".",
"firstPaintTime",
"=",
"firstPaint",
"-",
"(",
"window",
".",
"chrome",
".",
"loadTimes",
"(",
")",
".",
"startLoadTime",
"*",
"1000",
")",
";",
"}",
"// IE",
"else",
"if",
"(",
"typeof",
"window",
".",
"performance",
".",
"timing",
".",
"msFirstPaint",
"===",
"'number'",
")",
"{",
"firstPaint",
"=",
"window",
".",
"performance",
".",
"timing",
".",
"msFirstPaint",
";",
"api",
".",
"firstPaintTime",
"=",
"firstPaint",
"-",
"window",
".",
"performance",
".",
"timing",
".",
"navigationStart",
";",
"}",
"// Firefox",
"// This will use the first times after MozAfterPaint fires",
"//else if (window.performance.timing.navigationStart && typeof InstallTrigger !== 'undefined') {",
"// api.firstPaint = window.performance.timing.navigationStart;",
"// api.firstPaintTime = mozFirstPaintTime - window.performance.timing.navigationStart;",
"//}",
"if",
"(",
"opts",
"&&",
"!",
"opts",
".",
"simple",
")",
"{",
"api",
".",
"firstPaint",
"=",
"firstPaint",
";",
"}",
"}",
"// Total time from start to load",
"api",
".",
"loadTime",
"=",
"timing",
".",
"loadEventEnd",
"-",
"timing",
".",
"fetchStart",
";",
"// Time spent constructing the DOM tree",
"api",
".",
"domReadyTime",
"=",
"timing",
".",
"domComplete",
"-",
"timing",
".",
"domInteractive",
";",
"// Time consumed preparing the new page",
"api",
".",
"readyStart",
"=",
"timing",
".",
"fetchStart",
"-",
"timing",
".",
"navigationStart",
";",
"// Time spent during redirection",
"api",
".",
"redirectTime",
"=",
"timing",
".",
"redirectEnd",
"-",
"timing",
".",
"redirectStart",
";",
"// AppCache",
"api",
".",
"appcacheTime",
"=",
"timing",
".",
"domainLookupStart",
"-",
"timing",
".",
"fetchStart",
";",
"// Time spent unloading documents",
"api",
".",
"unloadEventTime",
"=",
"timing",
".",
"unloadEventEnd",
"-",
"timing",
".",
"unloadEventStart",
";",
"// DNS query time",
"api",
".",
"lookupDomainTime",
"=",
"timing",
".",
"domainLookupEnd",
"-",
"timing",
".",
"domainLookupStart",
";",
"// TCP connection time",
"api",
".",
"connectTime",
"=",
"timing",
".",
"connectEnd",
"-",
"timing",
".",
"connectStart",
";",
"// Time spent during the request",
"api",
".",
"requestTime",
"=",
"timing",
".",
"responseEnd",
"-",
"timing",
".",
"requestStart",
";",
"// Request to completion of the DOM loading",
"api",
".",
"initDomTreeTime",
"=",
"timing",
".",
"domInteractive",
"-",
"timing",
".",
"responseEnd",
";",
"// Load event time",
"api",
".",
"loadEventTime",
"=",
"timing",
".",
"loadEventEnd",
"-",
"timing",
".",
"loadEventStart",
";",
"}",
"return",
"api",
";",
"}"
] | Outputs extended measurements using Navigation Timing API
@param Object opts Options (simple (bool) - opts out of full data view)
@return Object measurements | [
"Outputs",
"extended",
"measurements",
"using",
"Navigation",
"Timing",
"API"
] | 1bd7d09f13e4c8f4394dc658314ed21f239741c7 | https://github.com/erraroo/ember-cli-erraroo/blob/1bd7d09f13e4c8f4394dc658314ed21f239741c7/vendor/timing.js#L18-L93 |
|
50,921 | xiamidaxia/xiami | xiami/webapp/Xiami.js | function(cb) {
var self = this
//set mainHtml
mainHtmlCache = fs.readFileSync(config.get('main_path'))
self.emit("STARTUP")
self.httpServer.listen(this.getConfig("port"), Meteor.bindEnvironment(function() {
Log.info('xiami server listeing at ' + self.getConfig('port'))
self.emit('STARTED')
self.isStarted = true
cb && cb()
}))
} | javascript | function(cb) {
var self = this
//set mainHtml
mainHtmlCache = fs.readFileSync(config.get('main_path'))
self.emit("STARTUP")
self.httpServer.listen(this.getConfig("port"), Meteor.bindEnvironment(function() {
Log.info('xiami server listeing at ' + self.getConfig('port'))
self.emit('STARTED')
self.isStarted = true
cb && cb()
}))
} | [
"function",
"(",
"cb",
")",
"{",
"var",
"self",
"=",
"this",
"//set mainHtml",
"mainHtmlCache",
"=",
"fs",
".",
"readFileSync",
"(",
"config",
".",
"get",
"(",
"'main_path'",
")",
")",
"self",
".",
"emit",
"(",
"\"STARTUP\"",
")",
"self",
".",
"httpServer",
".",
"listen",
"(",
"this",
".",
"getConfig",
"(",
"\"port\"",
")",
",",
"Meteor",
".",
"bindEnvironment",
"(",
"function",
"(",
")",
"{",
"Log",
".",
"info",
"(",
"'xiami server listeing at '",
"+",
"self",
".",
"getConfig",
"(",
"'port'",
")",
")",
"self",
".",
"emit",
"(",
"'STARTED'",
")",
"self",
".",
"isStarted",
"=",
"true",
"cb",
"&&",
"cb",
"(",
")",
"}",
")",
")",
"}"
] | start the server | [
"start",
"the",
"server"
] | 6fcee92c493c12bf8fd67c7068e67fa6a72a306b | https://github.com/xiamidaxia/xiami/blob/6fcee92c493c12bf8fd67c7068e67fa6a72a306b/xiami/webapp/Xiami.js#L42-L53 |
|
50,922 | PeerioTechnologies/peerio-updater | hash.js | verifyHash | function verifyHash(correctHash, filepath) {
return calculateHash(filepath).then(hash => {
if (hash !== correctHash) {
throw new Error(`Incorrect checksum: expected ${correctHash}, got ${hash}`);
}
return true;
});
} | javascript | function verifyHash(correctHash, filepath) {
return calculateHash(filepath).then(hash => {
if (hash !== correctHash) {
throw new Error(`Incorrect checksum: expected ${correctHash}, got ${hash}`);
}
return true;
});
} | [
"function",
"verifyHash",
"(",
"correctHash",
",",
"filepath",
")",
"{",
"return",
"calculateHash",
"(",
"filepath",
")",
".",
"then",
"(",
"hash",
"=>",
"{",
"if",
"(",
"hash",
"!==",
"correctHash",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"correctHash",
"}",
"${",
"hash",
"}",
"`",
")",
";",
"}",
"return",
"true",
";",
"}",
")",
";",
"}"
] | Calculates SHA512 hash of filepath and compares
it to the provided correctHash.
Returns a promise which rejects if the hash is
incorrect, otherwise resolves to true.
@param {string} correctHash expected hex-encoded SHA-512 hash
@param {string} filepath file path
@returns {Promise<boolean>} | [
"Calculates",
"SHA512",
"hash",
"of",
"filepath",
"and",
"compares",
"it",
"to",
"the",
"provided",
"correctHash",
"."
] | 9d6fedeec727f16a31653e4bbd4efe164e0957cb | https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/hash.js#L16-L23 |
50,923 | PeerioTechnologies/peerio-updater | hash.js | calculateHash | function calculateHash(filepath) {
return new Promise((fulfill, reject) => {
const file = fs.createReadStream(filepath);
const hash = crypto.createHash('sha512');
hash.setEncoding('hex');
file.on('error', err => {
reject(err);
});
file.on('end', () => {
hash.end();
fulfill(hash.read());
});
file.pipe(hash);
});
} | javascript | function calculateHash(filepath) {
return new Promise((fulfill, reject) => {
const file = fs.createReadStream(filepath);
const hash = crypto.createHash('sha512');
hash.setEncoding('hex');
file.on('error', err => {
reject(err);
});
file.on('end', () => {
hash.end();
fulfill(hash.read());
});
file.pipe(hash);
});
} | [
"function",
"calculateHash",
"(",
"filepath",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"fulfill",
",",
"reject",
")",
"=>",
"{",
"const",
"file",
"=",
"fs",
".",
"createReadStream",
"(",
"filepath",
")",
";",
"const",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha512'",
")",
";",
"hash",
".",
"setEncoding",
"(",
"'hex'",
")",
";",
"file",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"file",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"hash",
".",
"end",
"(",
")",
";",
"fulfill",
"(",
"hash",
".",
"read",
"(",
")",
")",
";",
"}",
")",
";",
"file",
".",
"pipe",
"(",
"hash",
")",
";",
"}",
")",
";",
"}"
] | Calculates hash of the file at the given path.
@param {string} filepath
@returns Promise<string> hex encoded hash | [
"Calculates",
"hash",
"of",
"the",
"file",
"at",
"the",
"given",
"path",
"."
] | 9d6fedeec727f16a31653e4bbd4efe164e0957cb | https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/hash.js#L31-L45 |
50,924 | wshager/js-rrb-vector | lib/util.js | getRoot | function getRoot(i, list) {
for (var x = list.height; x > 0; x--) {
var slot = i >> x * _const.B;
while (list.sizes[slot] <= i) {
slot++;
}
if (slot > 0) {
i -= list.sizes[slot - 1];
}
list = list[slot];
}
return list[i];
} | javascript | function getRoot(i, list) {
for (var x = list.height; x > 0; x--) {
var slot = i >> x * _const.B;
while (list.sizes[slot] <= i) {
slot++;
}
if (slot > 0) {
i -= list.sizes[slot - 1];
}
list = list[slot];
}
return list[i];
} | [
"function",
"getRoot",
"(",
"i",
",",
"list",
")",
"{",
"for",
"(",
"var",
"x",
"=",
"list",
".",
"height",
";",
"x",
">",
"0",
";",
"x",
"--",
")",
"{",
"var",
"slot",
"=",
"i",
">>",
"x",
"*",
"_const",
".",
"B",
";",
"while",
"(",
"list",
".",
"sizes",
"[",
"slot",
"]",
"<=",
"i",
")",
"{",
"slot",
"++",
";",
"}",
"if",
"(",
"slot",
">",
"0",
")",
"{",
"i",
"-=",
"list",
".",
"sizes",
"[",
"slot",
"-",
"1",
"]",
";",
"}",
"list",
"=",
"list",
"[",
"slot",
"]",
";",
"}",
"return",
"list",
"[",
"i",
"]",
";",
"}"
] | Calculates in which slot the item probably is, then find the exact slot in the sizes. Returns the index. | [
"Calculates",
"in",
"which",
"slot",
"the",
"item",
"probably",
"is",
"then",
"find",
"the",
"exact",
"slot",
"in",
"the",
"sizes",
".",
"Returns",
"the",
"index",
"."
] | 766c3c12f658cc251dce028460c4eca4e33d5254 | https://github.com/wshager/js-rrb-vector/blob/766c3c12f658cc251dce028460c4eca4e33d5254/lib/util.js#L96-L108 |
50,925 | r-park/images-ready | vendor/promise/core.js | Promise | function Promise(fn) {
if (typeof this !== 'object') {
throw new TypeError('Promises must be constructed via new');
}
if (typeof fn !== 'function') {
throw new TypeError('not a function');
}
this._37 = 0;
this._12 = null;
this._59 = [];
if (fn === noop) return;
doResolve(fn, this);
} | javascript | function Promise(fn) {
if (typeof this !== 'object') {
throw new TypeError('Promises must be constructed via new');
}
if (typeof fn !== 'function') {
throw new TypeError('not a function');
}
this._37 = 0;
this._12 = null;
this._59 = [];
if (fn === noop) return;
doResolve(fn, this);
} | [
"function",
"Promise",
"(",
"fn",
")",
"{",
"if",
"(",
"typeof",
"this",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Promises must be constructed via new'",
")",
";",
"}",
"if",
"(",
"typeof",
"fn",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'not a function'",
")",
";",
"}",
"this",
".",
"_37",
"=",
"0",
";",
"this",
".",
"_12",
"=",
"null",
";",
"this",
".",
"_59",
"=",
"[",
"]",
";",
"if",
"(",
"fn",
"===",
"noop",
")",
"return",
";",
"doResolve",
"(",
"fn",
",",
"this",
")",
";",
"}"
] | module.exports = Promise; | [
"module",
".",
"exports",
"=",
"Promise",
";"
] | 5167989c2af31f28f306cb683a522ab07c785dc8 | https://github.com/r-park/images-ready/blob/5167989c2af31f28f306cb683a522ab07c785dc8/vendor/promise/core.js#L55-L67 |
50,926 | AckerApple/ack-host | modules/webapp.js | host | function host(){
var app = leachApp(connect())
for(var x in host.prototype)app[x] = host.prototype[x]
return app
} | javascript | function host(){
var app = leachApp(connect())
for(var x in host.prototype)app[x] = host.prototype[x]
return app
} | [
"function",
"host",
"(",
")",
"{",
"var",
"app",
"=",
"leachApp",
"(",
"connect",
"(",
")",
")",
"for",
"(",
"var",
"x",
"in",
"host",
".",
"prototype",
")",
"app",
"[",
"x",
"]",
"=",
"host",
".",
"prototype",
"[",
"x",
"]",
"return",
"app",
"}"
] | one step above using http.createServer | [
"one",
"step",
"above",
"using",
"http",
".",
"createServer"
] | b8ff0563e236499a2b9add5bf1d3849b9137a520 | https://github.com/AckerApple/ack-host/blob/b8ff0563e236499a2b9add5bf1d3849b9137a520/modules/webapp.js#L29-L33 |
50,927 | iceroad/baresoil-server | lib/sandbox/SandboxDriver/main.js | relay | function relay(evtName) {
sbDriver.on(evtName, (...evtArgs) => {
evtArgs.splice(0, 0, evtName);
console.log(json(evtArgs));
});
} | javascript | function relay(evtName) {
sbDriver.on(evtName, (...evtArgs) => {
evtArgs.splice(0, 0, evtName);
console.log(json(evtArgs));
});
} | [
"function",
"relay",
"(",
"evtName",
")",
"{",
"sbDriver",
".",
"on",
"(",
"evtName",
",",
"(",
"...",
"evtArgs",
")",
"=>",
"{",
"evtArgs",
".",
"splice",
"(",
"0",
",",
"0",
",",
"evtName",
")",
";",
"console",
".",
"log",
"(",
"json",
"(",
"evtArgs",
")",
")",
";",
"}",
")",
";",
"}"
] | Emit sandbox driver's emitted events messages to stdout as JSON. | [
"Emit",
"sandbox",
"driver",
"s",
"emitted",
"events",
"messages",
"to",
"stdout",
"as",
"JSON",
"."
] | 8285f1647a81eb935331ea24491b38002b51278d | https://github.com/iceroad/baresoil-server/blob/8285f1647a81eb935331ea24491b38002b51278d/lib/sandbox/SandboxDriver/main.js#L16-L21 |
50,928 | Nazariglez/perenquen | lib/pixi/src/core/text/Text.js | Text | function Text(text, style, resolution)
{
/**
* The canvas element that everything is drawn to
*
* @member {HTMLCanvasElement}
*/
this.canvas = document.createElement('canvas');
/**
* The canvas 2d context that everything is drawn with
* @member {HTMLCanvasElement}
*/
this.context = this.canvas.getContext('2d');
/**
* The resolution of the canvas.
* @member {number}
*/
this.resolution = resolution || CONST.RESOLUTION;
/**
* Private tracker for the current text.
*
* @member {string}
* @private
*/
this._text = null;
/**
* Private tracker for the current style.
*
* @member {object}
* @private
*/
this._style = null;
var texture = Texture.fromCanvas(this.canvas);
texture.trim = new math.Rectangle();
Sprite.call(this, texture);
this.text = text;
this.style = style;
} | javascript | function Text(text, style, resolution)
{
/**
* The canvas element that everything is drawn to
*
* @member {HTMLCanvasElement}
*/
this.canvas = document.createElement('canvas');
/**
* The canvas 2d context that everything is drawn with
* @member {HTMLCanvasElement}
*/
this.context = this.canvas.getContext('2d');
/**
* The resolution of the canvas.
* @member {number}
*/
this.resolution = resolution || CONST.RESOLUTION;
/**
* Private tracker for the current text.
*
* @member {string}
* @private
*/
this._text = null;
/**
* Private tracker for the current style.
*
* @member {object}
* @private
*/
this._style = null;
var texture = Texture.fromCanvas(this.canvas);
texture.trim = new math.Rectangle();
Sprite.call(this, texture);
this.text = text;
this.style = style;
} | [
"function",
"Text",
"(",
"text",
",",
"style",
",",
"resolution",
")",
"{",
"/**\n * The canvas element that everything is drawn to\n *\n * @member {HTMLCanvasElement}\n */",
"this",
".",
"canvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"/**\n * The canvas 2d context that everything is drawn with\n * @member {HTMLCanvasElement}\n */",
"this",
".",
"context",
"=",
"this",
".",
"canvas",
".",
"getContext",
"(",
"'2d'",
")",
";",
"/**\n * The resolution of the canvas.\n * @member {number}\n */",
"this",
".",
"resolution",
"=",
"resolution",
"||",
"CONST",
".",
"RESOLUTION",
";",
"/**\n * Private tracker for the current text.\n *\n * @member {string}\n * @private\n */",
"this",
".",
"_text",
"=",
"null",
";",
"/**\n * Private tracker for the current style.\n *\n * @member {object}\n * @private\n */",
"this",
".",
"_style",
"=",
"null",
";",
"var",
"texture",
"=",
"Texture",
".",
"fromCanvas",
"(",
"this",
".",
"canvas",
")",
";",
"texture",
".",
"trim",
"=",
"new",
"math",
".",
"Rectangle",
"(",
")",
";",
"Sprite",
".",
"call",
"(",
"this",
",",
"texture",
")",
";",
"this",
".",
"text",
"=",
"text",
";",
"this",
".",
"style",
"=",
"style",
";",
"}"
] | A Text Object will create a line or multiple lines of text. To split a line you can use '\n' in your text string,
or add a wordWrap property set to true and and wordWrapWidth property with a value in the style object.
A Text can be created directly from a string and a style object
```js
var text = new PIXI.Text('This is a pixi text',{font : '24px Arial', fill : 0xff1010, align : 'center'});
```
@class
@extends Sprite
@memberof PIXI
@param text {string} The copy that you would like the text to display
@param [style] {object} The style parameters
@param [style.font] {string} default 'bold 20px Arial' The style and size of the font
@param [style.fill='black'] {String|Number} A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'
@param [style.align='left'] {string} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
@param [style.stroke] {String|Number} A canvas fillstyle that will be used on the text stroke e.g 'blue', '#FCFF00'
@param [style.strokeThickness=0] {number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
@param [style.wordWrap=false] {boolean} Indicates if word wrap should be used
@param [style.wordWrapWidth=100] {number} The width at which text will wrap, it needs wordWrap to be set to true
@param [style.lineHeight] {number} The line height, a number that represents the vertical space that a letter uses
@param [style.dropShadow=false] {boolean} Set a drop shadow for the text
@param [style.dropShadowColor='#000000'] {string} A fill style to be used on the dropshadow e.g 'red', '#00FF00'
@param [style.dropShadowAngle=Math.PI/4] {number} Set a angle of the drop shadow
@param [style.dropShadowDistance=5] {number} Set a distance of the drop shadow
@param [style.padding=0] {number} Occasionally some fonts are cropped. Adding some padding will prevent this from happening
@param [style.textBaseline='alphabetic'] {string} The baseline of the text that is rendered.
@param [style.lineJoin='miter'] {string} The lineJoin property sets the type of corner created, it can resolve
spiked text issues. Default is 'miter' (creates a sharp corner).
@param [style.miterLimit=10] {number} The miter limit to use when using the 'miter' lineJoin mode. This can reduce
or increase the spikiness of rendered text. | [
"A",
"Text",
"Object",
"will",
"create",
"a",
"line",
"or",
"multiple",
"lines",
"of",
"text",
".",
"To",
"split",
"a",
"line",
"you",
"can",
"use",
"\\",
"n",
"in",
"your",
"text",
"string",
"or",
"add",
"a",
"wordWrap",
"property",
"set",
"to",
"true",
"and",
"and",
"wordWrapWidth",
"property",
"with",
"a",
"value",
"in",
"the",
"style",
"object",
"."
] | e023964d05afeefebdcac4e2044819fdfa3899ae | https://github.com/Nazariglez/perenquen/blob/e023964d05afeefebdcac4e2044819fdfa3899ae/lib/pixi/src/core/text/Text.js#L40-L84 |
50,929 | andrewscwei/requiem | src/dom/getDataRegistry.js | getDataRegistry | function getDataRegistry(identifier) {
assert(!identifier || (typeof identifier === 'string'), `Invalid identifier specified: ${identifier}`);
if (!window.__private__) window.__private__ = {};
if (window.__private__.dataRegistry === undefined) window.__private__.dataRegistry = {};
if (identifier)
return namespace(identifier, window.__private__.dataRegistry);
else if (identifier === null)
return null
else
return window.__private__.dataRegistry;
} | javascript | function getDataRegistry(identifier) {
assert(!identifier || (typeof identifier === 'string'), `Invalid identifier specified: ${identifier}`);
if (!window.__private__) window.__private__ = {};
if (window.__private__.dataRegistry === undefined) window.__private__.dataRegistry = {};
if (identifier)
return namespace(identifier, window.__private__.dataRegistry);
else if (identifier === null)
return null
else
return window.__private__.dataRegistry;
} | [
"function",
"getDataRegistry",
"(",
"identifier",
")",
"{",
"assert",
"(",
"!",
"identifier",
"||",
"(",
"typeof",
"identifier",
"===",
"'string'",
")",
",",
"`",
"${",
"identifier",
"}",
"`",
")",
";",
"if",
"(",
"!",
"window",
".",
"__private__",
")",
"window",
".",
"__private__",
"=",
"{",
"}",
";",
"if",
"(",
"window",
".",
"__private__",
".",
"dataRegistry",
"===",
"undefined",
")",
"window",
".",
"__private__",
".",
"dataRegistry",
"=",
"{",
"}",
";",
"if",
"(",
"identifier",
")",
"return",
"namespace",
"(",
"identifier",
",",
"window",
".",
"__private__",
".",
"dataRegistry",
")",
";",
"else",
"if",
"(",
"identifier",
"===",
"null",
")",
"return",
"null",
"else",
"return",
"window",
".",
"__private__",
".",
"dataRegistry",
";",
"}"
] | Gets the data registry or a specific entry inside the data registry.
@param {string} [identifier] - The dot notated identifier.
@return {Object} The data registry.
@alias module:requiem~dom.getDataRegistry | [
"Gets",
"the",
"data",
"registry",
"or",
"a",
"specific",
"entry",
"inside",
"the",
"data",
"registry",
"."
] | c4182bfffc9841c6de5718f689ad3c2060511777 | https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/getDataRegistry.js#L17-L29 |
50,930 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (el, puzzle) {
var output = '';
// for each row in the puzzle
for (var i = 0, height = puzzle.length; i < height; i++) {
// append a div to represent a row in the puzzle
var row = puzzle[i];
output += '<div class="wordsRow">';
// for each element in that row
for (var j = 0, width = row.length; j < width; j++) {
// append our button with the appropriate class
output += '<button class="puzzleSquare" x="' + j + '" y="' + i + '">';
output += row[j] || ' ';
output += '</button>';
}
// close our div that represents a row
output += '</div>';
}
$(el).html(output);
} | javascript | function (el, puzzle) {
var output = '';
// for each row in the puzzle
for (var i = 0, height = puzzle.length; i < height; i++) {
// append a div to represent a row in the puzzle
var row = puzzle[i];
output += '<div class="wordsRow">';
// for each element in that row
for (var j = 0, width = row.length; j < width; j++) {
// append our button with the appropriate class
output += '<button class="puzzleSquare" x="' + j + '" y="' + i + '">';
output += row[j] || ' ';
output += '</button>';
}
// close our div that represents a row
output += '</div>';
}
$(el).html(output);
} | [
"function",
"(",
"el",
",",
"puzzle",
")",
"{",
"var",
"output",
"=",
"''",
";",
"// for each row in the puzzle",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"height",
"=",
"puzzle",
".",
"length",
";",
"i",
"<",
"height",
";",
"i",
"++",
")",
"{",
"// append a div to represent a row in the puzzle",
"var",
"row",
"=",
"puzzle",
"[",
"i",
"]",
";",
"output",
"+=",
"'<div class=\"wordsRow\">'",
";",
"// for each element in that row",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"width",
"=",
"row",
".",
"length",
";",
"j",
"<",
"width",
";",
"j",
"++",
")",
"{",
"// append our button with the appropriate class",
"output",
"+=",
"'<button class=\"puzzleSquare\" x=\"'",
"+",
"j",
"+",
"'\" y=\"'",
"+",
"i",
"+",
"'\">'",
";",
"output",
"+=",
"row",
"[",
"j",
"]",
"||",
"' '",
";",
"output",
"+=",
"'</button>'",
";",
"}",
"// close our div that represents a row",
"output",
"+=",
"'</div>'",
";",
"}",
"$",
"(",
"el",
")",
".",
"html",
"(",
"output",
")",
";",
"}"
] | Draws the puzzle by inserting rows of buttons into el.
@param {String} el: The jQuery element to write the puzzle to
@param {[[String]]} puzzle: The puzzle to draw | [
"Draws",
"the",
"puzzle",
"by",
"inserting",
"rows",
"of",
"buttons",
"into",
"el",
"."
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L32-L50 |
|
50,931 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (target) {
// if the user hasn't started a word yet, just return
if (!startSquare) {
return;
}
// if the new square is actually the previous square, just return
var lastSquare = selectedSquares[selectedSquares.length - 1];
if (lastSquare == target) {
return;
}
// see if the user backed up and correct the selectedSquares state if
// they did
var backTo;
for (var i = 0, len = selectedSquares.length; i < len; i++) {
if (selectedSquares[i] == target) {
backTo = i + 1;
break;
}
}
while (backTo < selectedSquares.length) {
$(selectedSquares[selectedSquares.length - 1]).removeClass('selected');
selectedSquares.splice(backTo, 1);
curWord = curWord.substr(0, curWord.length - 1);
}
// see if this is just a new orientation from the first square
// this is needed to make selecting diagonal words easier
var newOrientation = calcOrientation($(startSquare).attr('x') - 0, $(startSquare).attr('y') - 0, $(target).attr('x') - 0, $(target).attr('y') - 0);
if (newOrientation) {
selectedSquares = [startSquare];
curWord = $(startSquare).text();
if (lastSquare !== startSquare) {
$(lastSquare).removeClass('selected');
lastSquare = startSquare;
}
curOrientation = newOrientation;
}
// see if the move is along the same orientation as the last move
var orientation = calcOrientation($(lastSquare).attr('x') - 0, $(lastSquare).attr('y') - 0, $(target).attr('x') - 0, $(target).attr('y') - 0);
// if the new square isn't along a valid orientation, just ignore it.
// this makes selecting diagonal words less frustrating
if (!orientation) {
return;
}
// finally, if there was no previous orientation or this move is along
// the same orientation as the last move then play the move
if (!curOrientation || curOrientation === orientation) {
curOrientation = orientation;
playTurn(target);
}
} | javascript | function (target) {
// if the user hasn't started a word yet, just return
if (!startSquare) {
return;
}
// if the new square is actually the previous square, just return
var lastSquare = selectedSquares[selectedSquares.length - 1];
if (lastSquare == target) {
return;
}
// see if the user backed up and correct the selectedSquares state if
// they did
var backTo;
for (var i = 0, len = selectedSquares.length; i < len; i++) {
if (selectedSquares[i] == target) {
backTo = i + 1;
break;
}
}
while (backTo < selectedSquares.length) {
$(selectedSquares[selectedSquares.length - 1]).removeClass('selected');
selectedSquares.splice(backTo, 1);
curWord = curWord.substr(0, curWord.length - 1);
}
// see if this is just a new orientation from the first square
// this is needed to make selecting diagonal words easier
var newOrientation = calcOrientation($(startSquare).attr('x') - 0, $(startSquare).attr('y') - 0, $(target).attr('x') - 0, $(target).attr('y') - 0);
if (newOrientation) {
selectedSquares = [startSquare];
curWord = $(startSquare).text();
if (lastSquare !== startSquare) {
$(lastSquare).removeClass('selected');
lastSquare = startSquare;
}
curOrientation = newOrientation;
}
// see if the move is along the same orientation as the last move
var orientation = calcOrientation($(lastSquare).attr('x') - 0, $(lastSquare).attr('y') - 0, $(target).attr('x') - 0, $(target).attr('y') - 0);
// if the new square isn't along a valid orientation, just ignore it.
// this makes selecting diagonal words less frustrating
if (!orientation) {
return;
}
// finally, if there was no previous orientation or this move is along
// the same orientation as the last move then play the move
if (!curOrientation || curOrientation === orientation) {
curOrientation = orientation;
playTurn(target);
}
} | [
"function",
"(",
"target",
")",
"{",
"// if the user hasn't started a word yet, just return",
"if",
"(",
"!",
"startSquare",
")",
"{",
"return",
";",
"}",
"// if the new square is actually the previous square, just return",
"var",
"lastSquare",
"=",
"selectedSquares",
"[",
"selectedSquares",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"lastSquare",
"==",
"target",
")",
"{",
"return",
";",
"}",
"// see if the user backed up and correct the selectedSquares state if",
"// they did",
"var",
"backTo",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"selectedSquares",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"selectedSquares",
"[",
"i",
"]",
"==",
"target",
")",
"{",
"backTo",
"=",
"i",
"+",
"1",
";",
"break",
";",
"}",
"}",
"while",
"(",
"backTo",
"<",
"selectedSquares",
".",
"length",
")",
"{",
"$",
"(",
"selectedSquares",
"[",
"selectedSquares",
".",
"length",
"-",
"1",
"]",
")",
".",
"removeClass",
"(",
"'selected'",
")",
";",
"selectedSquares",
".",
"splice",
"(",
"backTo",
",",
"1",
")",
";",
"curWord",
"=",
"curWord",
".",
"substr",
"(",
"0",
",",
"curWord",
".",
"length",
"-",
"1",
")",
";",
"}",
"// see if this is just a new orientation from the first square",
"// this is needed to make selecting diagonal words easier",
"var",
"newOrientation",
"=",
"calcOrientation",
"(",
"$",
"(",
"startSquare",
")",
".",
"attr",
"(",
"'x'",
")",
"-",
"0",
",",
"$",
"(",
"startSquare",
")",
".",
"attr",
"(",
"'y'",
")",
"-",
"0",
",",
"$",
"(",
"target",
")",
".",
"attr",
"(",
"'x'",
")",
"-",
"0",
",",
"$",
"(",
"target",
")",
".",
"attr",
"(",
"'y'",
")",
"-",
"0",
")",
";",
"if",
"(",
"newOrientation",
")",
"{",
"selectedSquares",
"=",
"[",
"startSquare",
"]",
";",
"curWord",
"=",
"$",
"(",
"startSquare",
")",
".",
"text",
"(",
")",
";",
"if",
"(",
"lastSquare",
"!==",
"startSquare",
")",
"{",
"$",
"(",
"lastSquare",
")",
".",
"removeClass",
"(",
"'selected'",
")",
";",
"lastSquare",
"=",
"startSquare",
";",
"}",
"curOrientation",
"=",
"newOrientation",
";",
"}",
"// see if the move is along the same orientation as the last move",
"var",
"orientation",
"=",
"calcOrientation",
"(",
"$",
"(",
"lastSquare",
")",
".",
"attr",
"(",
"'x'",
")",
"-",
"0",
",",
"$",
"(",
"lastSquare",
")",
".",
"attr",
"(",
"'y'",
")",
"-",
"0",
",",
"$",
"(",
"target",
")",
".",
"attr",
"(",
"'x'",
")",
"-",
"0",
",",
"$",
"(",
"target",
")",
".",
"attr",
"(",
"'y'",
")",
"-",
"0",
")",
";",
"// if the new square isn't along a valid orientation, just ignore it.",
"// this makes selecting diagonal words less frustrating",
"if",
"(",
"!",
"orientation",
")",
"{",
"return",
";",
"}",
"// finally, if there was no previous orientation or this move is along",
"// the same orientation as the last move then play the move",
"if",
"(",
"!",
"curOrientation",
"||",
"curOrientation",
"===",
"orientation",
")",
"{",
"curOrientation",
"=",
"orientation",
";",
"playTurn",
"(",
"target",
")",
";",
"}",
"}"
] | Event that handles mouse over on a new square. Ensures that the new square
is adjacent to the previous square and the new square is along the path
of an actual word. | [
"Event",
"that",
"handles",
"mouse",
"over",
"on",
"a",
"new",
"square",
".",
"Ensures",
"that",
"the",
"new",
"square",
"is",
"adjacent",
"to",
"the",
"previous",
"square",
"and",
"the",
"new",
"square",
"is",
"along",
"the",
"path",
"of",
"an",
"actual",
"word",
"."
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L88-L137 |
|
50,932 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (square) {
// make sure we are still forming a valid word
for (var i = 0, len = wordList.length; i < len; i++) {
if (wordList[i].indexOf(curWord + $(square).text()) === 0) {
$(square).addClass('selected');
selectedSquares.push(square);
curWord += $(square).text();
break;
}
}
} | javascript | function (square) {
// make sure we are still forming a valid word
for (var i = 0, len = wordList.length; i < len; i++) {
if (wordList[i].indexOf(curWord + $(square).text()) === 0) {
$(square).addClass('selected');
selectedSquares.push(square);
curWord += $(square).text();
break;
}
}
} | [
"function",
"(",
"square",
")",
"{",
"// make sure we are still forming a valid word",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"wordList",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"wordList",
"[",
"i",
"]",
".",
"indexOf",
"(",
"curWord",
"+",
"$",
"(",
"square",
")",
".",
"text",
"(",
")",
")",
"===",
"0",
")",
"{",
"$",
"(",
"square",
")",
".",
"addClass",
"(",
"'selected'",
")",
";",
"selectedSquares",
".",
"push",
"(",
"square",
")",
";",
"curWord",
"+=",
"$",
"(",
"square",
")",
".",
"text",
"(",
")",
";",
"break",
";",
"}",
"}",
"}"
] | Updates the game state when the previous selection was valid.
@param {el} square: The jQuery element that was played | [
"Updates",
"the",
"game",
"state",
"when",
"the",
"previous",
"selection",
"was",
"valid",
"."
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L152-L162 |
|
50,933 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (e) {
// see if we formed a valid word
for (var i = 0, len = wordList.length; i < len; i++) {
if (wordList[i] === curWord) {
var selected = $('.selected');
selected.addClass('found');
wordList.splice(i, 1);
var color = e.data.colorHash.hex(curWord);
$('.' + curWord).addClass('wordFound');
for (var selectedIndex = 0, selectedLength = selected.length; selectedIndex < selectedLength; selectedIndex++) {
var current = $(selected[selectedIndex]), style = current.attr("style"), hasBC = style != undefined && style.search("background-color") != -1;
if (hasBC) {
current.css("border", "4px solid " + color);
}
else {
current.css("background-color", color);
}
}
$(e.data.puzzleEl).trigger("found", curWord);
$(e.data.wordsEl).append("<li class=\"" + curWord + " wordFound\"><i style=\"background-color:" + color + ";\"></i>" + curWord + "</li>");
}
if (wordList.length === 0) {
$('.puzzleSquare').off(".spl").addClass('complete');
$(e.data.puzzleEl).trigger("end");
}
}
// reset the turn
$('.selected').removeClass('selected');
startSquare = null;
selectedSquares = [];
curWord = '';
curOrientation = null;
} | javascript | function (e) {
// see if we formed a valid word
for (var i = 0, len = wordList.length; i < len; i++) {
if (wordList[i] === curWord) {
var selected = $('.selected');
selected.addClass('found');
wordList.splice(i, 1);
var color = e.data.colorHash.hex(curWord);
$('.' + curWord).addClass('wordFound');
for (var selectedIndex = 0, selectedLength = selected.length; selectedIndex < selectedLength; selectedIndex++) {
var current = $(selected[selectedIndex]), style = current.attr("style"), hasBC = style != undefined && style.search("background-color") != -1;
if (hasBC) {
current.css("border", "4px solid " + color);
}
else {
current.css("background-color", color);
}
}
$(e.data.puzzleEl).trigger("found", curWord);
$(e.data.wordsEl).append("<li class=\"" + curWord + " wordFound\"><i style=\"background-color:" + color + ";\"></i>" + curWord + "</li>");
}
if (wordList.length === 0) {
$('.puzzleSquare').off(".spl").addClass('complete');
$(e.data.puzzleEl).trigger("end");
}
}
// reset the turn
$('.selected').removeClass('selected');
startSquare = null;
selectedSquares = [];
curWord = '';
curOrientation = null;
} | [
"function",
"(",
"e",
")",
"{",
"// see if we formed a valid word",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"wordList",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"wordList",
"[",
"i",
"]",
"===",
"curWord",
")",
"{",
"var",
"selected",
"=",
"$",
"(",
"'.selected'",
")",
";",
"selected",
".",
"addClass",
"(",
"'found'",
")",
";",
"wordList",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"var",
"color",
"=",
"e",
".",
"data",
".",
"colorHash",
".",
"hex",
"(",
"curWord",
")",
";",
"$",
"(",
"'.'",
"+",
"curWord",
")",
".",
"addClass",
"(",
"'wordFound'",
")",
";",
"for",
"(",
"var",
"selectedIndex",
"=",
"0",
",",
"selectedLength",
"=",
"selected",
".",
"length",
";",
"selectedIndex",
"<",
"selectedLength",
";",
"selectedIndex",
"++",
")",
"{",
"var",
"current",
"=",
"$",
"(",
"selected",
"[",
"selectedIndex",
"]",
")",
",",
"style",
"=",
"current",
".",
"attr",
"(",
"\"style\"",
")",
",",
"hasBC",
"=",
"style",
"!=",
"undefined",
"&&",
"style",
".",
"search",
"(",
"\"background-color\"",
")",
"!=",
"-",
"1",
";",
"if",
"(",
"hasBC",
")",
"{",
"current",
".",
"css",
"(",
"\"border\"",
",",
"\"4px solid \"",
"+",
"color",
")",
";",
"}",
"else",
"{",
"current",
".",
"css",
"(",
"\"background-color\"",
",",
"color",
")",
";",
"}",
"}",
"$",
"(",
"e",
".",
"data",
".",
"puzzleEl",
")",
".",
"trigger",
"(",
"\"found\"",
",",
"curWord",
")",
";",
"$",
"(",
"e",
".",
"data",
".",
"wordsEl",
")",
".",
"append",
"(",
"\"<li class=\\\"\"",
"+",
"curWord",
"+",
"\" wordFound\\\"><i style=\\\"background-color:\"",
"+",
"color",
"+",
"\";\\\"></i>\"",
"+",
"curWord",
"+",
"\"</li>\"",
")",
";",
"}",
"if",
"(",
"wordList",
".",
"length",
"===",
"0",
")",
"{",
"$",
"(",
"'.puzzleSquare'",
")",
".",
"off",
"(",
"\".spl\"",
")",
".",
"addClass",
"(",
"'complete'",
")",
";",
"$",
"(",
"e",
".",
"data",
".",
"puzzleEl",
")",
".",
"trigger",
"(",
"\"end\"",
")",
";",
"}",
"}",
"// reset the turn",
"$",
"(",
"'.selected'",
")",
".",
"removeClass",
"(",
"'selected'",
")",
";",
"startSquare",
"=",
"null",
";",
"selectedSquares",
"=",
"[",
"]",
";",
"curWord",
"=",
"''",
";",
"curOrientation",
"=",
"null",
";",
"}"
] | Event that handles mouse up on a square. Checks to see if a valid word
was created and updates the class of the letters and word if it was. Then
resets the game state to start a new word. | [
"Event",
"that",
"handles",
"mouse",
"up",
"on",
"a",
"square",
".",
"Checks",
"to",
"see",
"if",
"a",
"valid",
"word",
"was",
"created",
"and",
"updates",
"the",
"class",
"of",
"the",
"letters",
"and",
"word",
"if",
"it",
"was",
".",
"Then",
"resets",
"the",
"game",
"state",
"to",
"start",
"a",
"new",
"word",
"."
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L169-L201 |
|
50,934 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (x1, y1, x2, y2) {
for (var orientation in wordfind.orientations) {
var nextFn = wordfind.orientations[orientation];
var nextPos = nextFn(x1, y1, 1);
if (nextPos.x === x2 && nextPos.y === y2) {
return orientation;
}
}
return null;
} | javascript | function (x1, y1, x2, y2) {
for (var orientation in wordfind.orientations) {
var nextFn = wordfind.orientations[orientation];
var nextPos = nextFn(x1, y1, 1);
if (nextPos.x === x2 && nextPos.y === y2) {
return orientation;
}
}
return null;
} | [
"function",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"{",
"for",
"(",
"var",
"orientation",
"in",
"wordfind",
".",
"orientations",
")",
"{",
"var",
"nextFn",
"=",
"wordfind",
".",
"orientations",
"[",
"orientation",
"]",
";",
"var",
"nextPos",
"=",
"nextFn",
"(",
"x1",
",",
"y1",
",",
"1",
")",
";",
"if",
"(",
"nextPos",
".",
"x",
"===",
"x2",
"&&",
"nextPos",
".",
"y",
"===",
"y2",
")",
"{",
"return",
"orientation",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Given two points, ensure that they are adjacent and determine what
orientation the second point is relative to the first
@param {int} x1: The x coordinate of the first point
@param {int} y1: The y coordinate of the first point
@param {int} x2: The x coordinate of the second point
@param {int} y2: The y coordinate of the second point | [
"Given",
"two",
"points",
"ensure",
"that",
"they",
"are",
"adjacent",
"and",
"determine",
"what",
"orientation",
"the",
"second",
"point",
"is",
"relative",
"to",
"the",
"first"
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L211-L220 |
|
50,935 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (words, puzzleEl, wordsEl, options, colorHash) {
wordList = words.slice(0).sort();
var puzzle = wordfind.newPuzzle(words, options);
// draw out all of the words
drawPuzzle(puzzleEl, puzzle);
var list = drawWords(wordsEl, wordList);
$('.puzzleSquare').on("mousedown.spl touchstart.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, startTurn)
.on("touchmove.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, touchMove)
.on("mouseup.spl touchend.spl", { puzzleEl: puzzleEl, wordsEl: list, colorHash: colorHash }, endTurn)
.on("mousemove.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, mouseMove);
return puzzle;
} | javascript | function (words, puzzleEl, wordsEl, options, colorHash) {
wordList = words.slice(0).sort();
var puzzle = wordfind.newPuzzle(words, options);
// draw out all of the words
drawPuzzle(puzzleEl, puzzle);
var list = drawWords(wordsEl, wordList);
$('.puzzleSquare').on("mousedown.spl touchstart.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, startTurn)
.on("touchmove.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, touchMove)
.on("mouseup.spl touchend.spl", { puzzleEl: puzzleEl, wordsEl: list, colorHash: colorHash }, endTurn)
.on("mousemove.spl", { puzzleEl: puzzleEl, colorHash: colorHash }, mouseMove);
return puzzle;
} | [
"function",
"(",
"words",
",",
"puzzleEl",
",",
"wordsEl",
",",
"options",
",",
"colorHash",
")",
"{",
"wordList",
"=",
"words",
".",
"slice",
"(",
"0",
")",
".",
"sort",
"(",
")",
";",
"var",
"puzzle",
"=",
"wordfind",
".",
"newPuzzle",
"(",
"words",
",",
"options",
")",
";",
"// draw out all of the words",
"drawPuzzle",
"(",
"puzzleEl",
",",
"puzzle",
")",
";",
"var",
"list",
"=",
"drawWords",
"(",
"wordsEl",
",",
"wordList",
")",
";",
"$",
"(",
"'.puzzleSquare'",
")",
".",
"on",
"(",
"\"mousedown.spl touchstart.spl\"",
",",
"{",
"puzzleEl",
":",
"puzzleEl",
",",
"colorHash",
":",
"colorHash",
"}",
",",
"startTurn",
")",
".",
"on",
"(",
"\"touchmove.spl\"",
",",
"{",
"puzzleEl",
":",
"puzzleEl",
",",
"colorHash",
":",
"colorHash",
"}",
",",
"touchMove",
")",
".",
"on",
"(",
"\"mouseup.spl touchend.spl\"",
",",
"{",
"puzzleEl",
":",
"puzzleEl",
",",
"wordsEl",
":",
"list",
",",
"colorHash",
":",
"colorHash",
"}",
",",
"endTurn",
")",
".",
"on",
"(",
"\"mousemove.spl\"",
",",
"{",
"puzzleEl",
":",
"puzzleEl",
",",
"colorHash",
":",
"colorHash",
"}",
",",
"mouseMove",
")",
";",
"return",
"puzzle",
";",
"}"
] | Creates a new word find game and draws the board and words.
Returns the puzzle that was created.
@param {[String]} words: The words to add to the puzzle
@param {String} puzzleEl: Selector to use when inserting the puzzle
@param {String} wordsEl: Selector to use when inserting the word list
@param {Options} options: WordFind options to use when creating the puzzle | [
"Creates",
"a",
"new",
"word",
"find",
"game",
"and",
"draws",
"the",
"board",
"and",
"words",
"."
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L232-L243 |
|
50,936 | haztivity/hz-soupletter | src/lib/wordfindgame.js | function (puzzle, words, list, colorHash) {
var solution = wordfind.solve(puzzle, words).found;
for (var i = 0, len = solution.length; i < len; i++) {
var word = solution[i].word, orientation = solution[i].orientation, x = solution[i].x, y = solution[i].y, next = wordfind.orientations[orientation];
if (!$('.' + word).hasClass('wordFound')) {
var color = colorHash.hex(word);
list.append("<li class=\"" + word + "\"><i style=\"background-color:" + color + ";\"></i>" + word + "</li>");
for (var j = 0, size = word.length; j < size; j++) {
var nextPos = next(x, y, j);
//por cada letra de la palabra
//si no tiene bc
//se añade bc
//si tiene bc
//se añade un elemento hijo
//se añade el bc
var selected = $('[x="' + nextPos.x + '"][y="' + nextPos.y + '"]');
for (var selectedIndex = 0, selectedLength = selected.length; selectedIndex < selectedLength; selectedIndex++) {
var current = $(selected[selectedIndex]), childrens = current.find(".puzzleSquare"), item = childrens.length == 0 ? current : childrens.last(), style = item.attr("style"), hasBC = style != undefined && style.indexOf("background-color") - 1;
if (hasBC) {
var subItem = $("<span class='puzzleSquare'>" + item.text() + "</span>")
.css("background-color", color);
item.text("");
item.append(subItem);
}
else {
current.css("background-color", color);
}
}
selected.addClass('solved');
}
$('.' + word).addClass('wordFound');
}
}
$('.puzzleSquare').off(".spl").trigger("end");
} | javascript | function (puzzle, words, list, colorHash) {
var solution = wordfind.solve(puzzle, words).found;
for (var i = 0, len = solution.length; i < len; i++) {
var word = solution[i].word, orientation = solution[i].orientation, x = solution[i].x, y = solution[i].y, next = wordfind.orientations[orientation];
if (!$('.' + word).hasClass('wordFound')) {
var color = colorHash.hex(word);
list.append("<li class=\"" + word + "\"><i style=\"background-color:" + color + ";\"></i>" + word + "</li>");
for (var j = 0, size = word.length; j < size; j++) {
var nextPos = next(x, y, j);
//por cada letra de la palabra
//si no tiene bc
//se añade bc
//si tiene bc
//se añade un elemento hijo
//se añade el bc
var selected = $('[x="' + nextPos.x + '"][y="' + nextPos.y + '"]');
for (var selectedIndex = 0, selectedLength = selected.length; selectedIndex < selectedLength; selectedIndex++) {
var current = $(selected[selectedIndex]), childrens = current.find(".puzzleSquare"), item = childrens.length == 0 ? current : childrens.last(), style = item.attr("style"), hasBC = style != undefined && style.indexOf("background-color") - 1;
if (hasBC) {
var subItem = $("<span class='puzzleSquare'>" + item.text() + "</span>")
.css("background-color", color);
item.text("");
item.append(subItem);
}
else {
current.css("background-color", color);
}
}
selected.addClass('solved');
}
$('.' + word).addClass('wordFound');
}
}
$('.puzzleSquare').off(".spl").trigger("end");
} | [
"function",
"(",
"puzzle",
",",
"words",
",",
"list",
",",
"colorHash",
")",
"{",
"var",
"solution",
"=",
"wordfind",
".",
"solve",
"(",
"puzzle",
",",
"words",
")",
".",
"found",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"solution",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"word",
"=",
"solution",
"[",
"i",
"]",
".",
"word",
",",
"orientation",
"=",
"solution",
"[",
"i",
"]",
".",
"orientation",
",",
"x",
"=",
"solution",
"[",
"i",
"]",
".",
"x",
",",
"y",
"=",
"solution",
"[",
"i",
"]",
".",
"y",
",",
"next",
"=",
"wordfind",
".",
"orientations",
"[",
"orientation",
"]",
";",
"if",
"(",
"!",
"$",
"(",
"'.'",
"+",
"word",
")",
".",
"hasClass",
"(",
"'wordFound'",
")",
")",
"{",
"var",
"color",
"=",
"colorHash",
".",
"hex",
"(",
"word",
")",
";",
"list",
".",
"append",
"(",
"\"<li class=\\\"\"",
"+",
"word",
"+",
"\"\\\"><i style=\\\"background-color:\"",
"+",
"color",
"+",
"\";\\\"></i>\"",
"+",
"word",
"+",
"\"</li>\"",
")",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"size",
"=",
"word",
".",
"length",
";",
"j",
"<",
"size",
";",
"j",
"++",
")",
"{",
"var",
"nextPos",
"=",
"next",
"(",
"x",
",",
"y",
",",
"j",
")",
";",
"//por cada letra de la palabra",
"//si no tiene bc",
"//se añade bc",
"//si tiene bc",
"//se añade un elemento hijo",
"//se añade el bc",
"var",
"selected",
"=",
"$",
"(",
"'[x=\"'",
"+",
"nextPos",
".",
"x",
"+",
"'\"][y=\"'",
"+",
"nextPos",
".",
"y",
"+",
"'\"]'",
")",
";",
"for",
"(",
"var",
"selectedIndex",
"=",
"0",
",",
"selectedLength",
"=",
"selected",
".",
"length",
";",
"selectedIndex",
"<",
"selectedLength",
";",
"selectedIndex",
"++",
")",
"{",
"var",
"current",
"=",
"$",
"(",
"selected",
"[",
"selectedIndex",
"]",
")",
",",
"childrens",
"=",
"current",
".",
"find",
"(",
"\".puzzleSquare\"",
")",
",",
"item",
"=",
"childrens",
".",
"length",
"==",
"0",
"?",
"current",
":",
"childrens",
".",
"last",
"(",
")",
",",
"style",
"=",
"item",
".",
"attr",
"(",
"\"style\"",
")",
",",
"hasBC",
"=",
"style",
"!=",
"undefined",
"&&",
"style",
".",
"indexOf",
"(",
"\"background-color\"",
")",
"-",
"1",
";",
"if",
"(",
"hasBC",
")",
"{",
"var",
"subItem",
"=",
"$",
"(",
"\"<span class='puzzleSquare'>\"",
"+",
"item",
".",
"text",
"(",
")",
"+",
"\"</span>\"",
")",
".",
"css",
"(",
"\"background-color\"",
",",
"color",
")",
";",
"item",
".",
"text",
"(",
"\"\"",
")",
";",
"item",
".",
"append",
"(",
"subItem",
")",
";",
"}",
"else",
"{",
"current",
".",
"css",
"(",
"\"background-color\"",
",",
"color",
")",
";",
"}",
"}",
"selected",
".",
"addClass",
"(",
"'solved'",
")",
";",
"}",
"$",
"(",
"'.'",
"+",
"word",
")",
".",
"addClass",
"(",
"'wordFound'",
")",
";",
"}",
"}",
"$",
"(",
"'.puzzleSquare'",
")",
".",
"off",
"(",
"\".spl\"",
")",
".",
"trigger",
"(",
"\"end\"",
")",
";",
"}"
] | Solves an existing puzzle.
@param {[[String]]} puzzle: The puzzle to solve
@param {[String]} words: The words to solve for | [
"Solves",
"an",
"existing",
"puzzle",
"."
] | 38cbcd0c6e9ad029b7e74ce9e9e75f8775870956 | https://github.com/haztivity/hz-soupletter/blob/38cbcd0c6e9ad029b7e74ce9e9e75f8775870956/src/lib/wordfindgame.js#L250-L284 |
|
50,937 | derdesign/protos | middleware/logger/transport-mongodb.js | initMongo | function initMongo(config, callback) {
var self = this;
// Set db
self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
// Get client
self.db.open(function(err, client) {
if (err) throw err;
else {
self.client = client;
client.collectionNames(function(err, names) {
if (err) throw err;
else {
var name = config.database + '.' + config.collection;
var exists = names.filter(function(col) {
if (col.name == name) return col;
});
// Collection options
var opts = {capped: true, size: config.logSize};
if (config.logLimit != null) opts.max = config.logLimit;
if (exists.length === 0) {
client.createCollection(config.collection, opts, function(err, collection) {
if (err) throw err;
else {
self.collection = collection;
callback.call(self);
}
});
} else {
// Get collection
client.collection(config.collection, function(err, collection) {
if (err) throw err;
else {
self.collection = collection;
// Get collection options » Check if collection has already been capped
collection.options(function(err, options) {
if (err) {
throw err;
} else {
// Check if collection's options match log requirements
var ready = (options.capped === true && options.size === opts.size);
if ('max' in opts) ready = (ready && options.max === opts.max);
if (!ready) {
// Convert collection to capped if it's not match log requirements
var cmd = {"convertToCapped": config.collection, size: opts.size};
if ('max' in opts) cmd.max = opts.max;
client.command(cmd, function(err) {
if (err) throw err;
else {
callback.call(self);
}
});
} else {
callback.call(self);
}
}
});
}
});
}
}
});
}
});
} | javascript | function initMongo(config, callback) {
var self = this;
// Set db
self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: true});
// Get client
self.db.open(function(err, client) {
if (err) throw err;
else {
self.client = client;
client.collectionNames(function(err, names) {
if (err) throw err;
else {
var name = config.database + '.' + config.collection;
var exists = names.filter(function(col) {
if (col.name == name) return col;
});
// Collection options
var opts = {capped: true, size: config.logSize};
if (config.logLimit != null) opts.max = config.logLimit;
if (exists.length === 0) {
client.createCollection(config.collection, opts, function(err, collection) {
if (err) throw err;
else {
self.collection = collection;
callback.call(self);
}
});
} else {
// Get collection
client.collection(config.collection, function(err, collection) {
if (err) throw err;
else {
self.collection = collection;
// Get collection options » Check if collection has already been capped
collection.options(function(err, options) {
if (err) {
throw err;
} else {
// Check if collection's options match log requirements
var ready = (options.capped === true && options.size === opts.size);
if ('max' in opts) ready = (ready && options.max === opts.max);
if (!ready) {
// Convert collection to capped if it's not match log requirements
var cmd = {"convertToCapped": config.collection, size: opts.size};
if ('max' in opts) cmd.max = opts.max;
client.command(cmd, function(err) {
if (err) throw err;
else {
callback.call(self);
}
});
} else {
callback.call(self);
}
}
});
}
});
}
}
});
}
});
} | [
"function",
"initMongo",
"(",
"config",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"// Set db",
"self",
".",
"db",
"=",
"new",
"Db",
"(",
"config",
".",
"database",
",",
"new",
"Server",
"(",
"config",
".",
"host",
",",
"config",
".",
"port",
",",
"{",
"}",
")",
",",
"{",
"safe",
":",
"true",
"}",
")",
";",
"// Get client",
"self",
".",
"db",
".",
"open",
"(",
"function",
"(",
"err",
",",
"client",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"else",
"{",
"self",
".",
"client",
"=",
"client",
";",
"client",
".",
"collectionNames",
"(",
"function",
"(",
"err",
",",
"names",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"else",
"{",
"var",
"name",
"=",
"config",
".",
"database",
"+",
"'.'",
"+",
"config",
".",
"collection",
";",
"var",
"exists",
"=",
"names",
".",
"filter",
"(",
"function",
"(",
"col",
")",
"{",
"if",
"(",
"col",
".",
"name",
"==",
"name",
")",
"return",
"col",
";",
"}",
")",
";",
"// Collection options",
"var",
"opts",
"=",
"{",
"capped",
":",
"true",
",",
"size",
":",
"config",
".",
"logSize",
"}",
";",
"if",
"(",
"config",
".",
"logLimit",
"!=",
"null",
")",
"opts",
".",
"max",
"=",
"config",
".",
"logLimit",
";",
"if",
"(",
"exists",
".",
"length",
"===",
"0",
")",
"{",
"client",
".",
"createCollection",
"(",
"config",
".",
"collection",
",",
"opts",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"else",
"{",
"self",
".",
"collection",
"=",
"collection",
";",
"callback",
".",
"call",
"(",
"self",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"// Get collection",
"client",
".",
"collection",
"(",
"config",
".",
"collection",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"else",
"{",
"self",
".",
"collection",
"=",
"collection",
";",
"// Get collection options » Check if collection has already been capped",
"collection",
".",
"options",
"(",
"function",
"(",
"err",
",",
"options",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"else",
"{",
"// Check if collection's options match log requirements",
"var",
"ready",
"=",
"(",
"options",
".",
"capped",
"===",
"true",
"&&",
"options",
".",
"size",
"===",
"opts",
".",
"size",
")",
";",
"if",
"(",
"'max'",
"in",
"opts",
")",
"ready",
"=",
"(",
"ready",
"&&",
"options",
".",
"max",
"===",
"opts",
".",
"max",
")",
";",
"if",
"(",
"!",
"ready",
")",
"{",
"// Convert collection to capped if it's not match log requirements",
"var",
"cmd",
"=",
"{",
"\"convertToCapped\"",
":",
"config",
".",
"collection",
",",
"size",
":",
"opts",
".",
"size",
"}",
";",
"if",
"(",
"'max'",
"in",
"opts",
")",
"cmd",
".",
"max",
"=",
"opts",
".",
"max",
";",
"client",
".",
"command",
"(",
"cmd",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"else",
"{",
"callback",
".",
"call",
"(",
"self",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"callback",
".",
"call",
"(",
"self",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
] | Initializes the MongoDB Client & Collection
@param {object} config
@param {function} callback
@private | [
"Initializes",
"the",
"MongoDB",
"Client",
"&",
"Collection"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/middleware/logger/transport-mongodb.js#L128-L196 |
50,938 | nomic/api-driver | lib/expector.js | checkJSONExpression | function checkJSONExpression(expression, json) {
if (! (expression && json)) {
return false;
}
// array expressions never match non-arrays or arrays of a different length.
if (_.isArray(expression) && !(_.isArray(json) && expression.length === json.length)) {
return false;
}
return _.all(expression, function(v, k) {
// check "$" properties
if (k === "$not") return (! checkJSONExpression(v, json));
if (k === "$unordered") {
return v.length === json.length && arrayContains(json, v);
}
if (k === "$contains") {
return arrayContains(json, v);
}
if (k === "$length" ) return(v === json.length);
if (k === "$gt") return (json > v);
if (k === "$gte") return (json >= v);
if (k === "$lt") return (json < v);
if (k === "$lte") return (json <= v);
// check $not-exists
if (! _.has(json, k)) return (v === "$not-exists");
// check rest of "$" values.
if (v === "$exists") return _.has(json, k);
if (v === "$string") return _.isString(json[k]);
if (_.isRegExp(v)) return v.test(json[k]);
if (_.isObject(v)) return checkJSONExpression(v, json[k]);
if (v === "$date") {
try {
new Date(json[k]);
return true;
} catch (e) {
return false;
}
}
if (v === "$int") {
//http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer
return (typeof json[k] === 'number' && json[k] % 1 === 0);
}
// check a strict equals
return (v === json[k]);
});
} | javascript | function checkJSONExpression(expression, json) {
if (! (expression && json)) {
return false;
}
// array expressions never match non-arrays or arrays of a different length.
if (_.isArray(expression) && !(_.isArray(json) && expression.length === json.length)) {
return false;
}
return _.all(expression, function(v, k) {
// check "$" properties
if (k === "$not") return (! checkJSONExpression(v, json));
if (k === "$unordered") {
return v.length === json.length && arrayContains(json, v);
}
if (k === "$contains") {
return arrayContains(json, v);
}
if (k === "$length" ) return(v === json.length);
if (k === "$gt") return (json > v);
if (k === "$gte") return (json >= v);
if (k === "$lt") return (json < v);
if (k === "$lte") return (json <= v);
// check $not-exists
if (! _.has(json, k)) return (v === "$not-exists");
// check rest of "$" values.
if (v === "$exists") return _.has(json, k);
if (v === "$string") return _.isString(json[k]);
if (_.isRegExp(v)) return v.test(json[k]);
if (_.isObject(v)) return checkJSONExpression(v, json[k]);
if (v === "$date") {
try {
new Date(json[k]);
return true;
} catch (e) {
return false;
}
}
if (v === "$int") {
//http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer
return (typeof json[k] === 'number' && json[k] % 1 === 0);
}
// check a strict equals
return (v === json[k]);
});
} | [
"function",
"checkJSONExpression",
"(",
"expression",
",",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"expression",
"&&",
"json",
")",
")",
"{",
"return",
"false",
";",
"}",
"// array expressions never match non-arrays or arrays of a different length.",
"if",
"(",
"_",
".",
"isArray",
"(",
"expression",
")",
"&&",
"!",
"(",
"_",
".",
"isArray",
"(",
"json",
")",
"&&",
"expression",
".",
"length",
"===",
"json",
".",
"length",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"_",
".",
"all",
"(",
"expression",
",",
"function",
"(",
"v",
",",
"k",
")",
"{",
"// check \"$\" properties",
"if",
"(",
"k",
"===",
"\"$not\"",
")",
"return",
"(",
"!",
"checkJSONExpression",
"(",
"v",
",",
"json",
")",
")",
";",
"if",
"(",
"k",
"===",
"\"$unordered\"",
")",
"{",
"return",
"v",
".",
"length",
"===",
"json",
".",
"length",
"&&",
"arrayContains",
"(",
"json",
",",
"v",
")",
";",
"}",
"if",
"(",
"k",
"===",
"\"$contains\"",
")",
"{",
"return",
"arrayContains",
"(",
"json",
",",
"v",
")",
";",
"}",
"if",
"(",
"k",
"===",
"\"$length\"",
")",
"return",
"(",
"v",
"===",
"json",
".",
"length",
")",
";",
"if",
"(",
"k",
"===",
"\"$gt\"",
")",
"return",
"(",
"json",
">",
"v",
")",
";",
"if",
"(",
"k",
"===",
"\"$gte\"",
")",
"return",
"(",
"json",
">=",
"v",
")",
";",
"if",
"(",
"k",
"===",
"\"$lt\"",
")",
"return",
"(",
"json",
"<",
"v",
")",
";",
"if",
"(",
"k",
"===",
"\"$lte\"",
")",
"return",
"(",
"json",
"<=",
"v",
")",
";",
"// check $not-exists",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"json",
",",
"k",
")",
")",
"return",
"(",
"v",
"===",
"\"$not-exists\"",
")",
";",
"// check rest of \"$\" values.",
"if",
"(",
"v",
"===",
"\"$exists\"",
")",
"return",
"_",
".",
"has",
"(",
"json",
",",
"k",
")",
";",
"if",
"(",
"v",
"===",
"\"$string\"",
")",
"return",
"_",
".",
"isString",
"(",
"json",
"[",
"k",
"]",
")",
";",
"if",
"(",
"_",
".",
"isRegExp",
"(",
"v",
")",
")",
"return",
"v",
".",
"test",
"(",
"json",
"[",
"k",
"]",
")",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"v",
")",
")",
"return",
"checkJSONExpression",
"(",
"v",
",",
"json",
"[",
"k",
"]",
")",
";",
"if",
"(",
"v",
"===",
"\"$date\"",
")",
"{",
"try",
"{",
"new",
"Date",
"(",
"json",
"[",
"k",
"]",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"v",
"===",
"\"$int\"",
")",
"{",
"//http://stackoverflow.com/questions/3885817/how-to-check-if-a-number-is-float-or-integer",
"return",
"(",
"typeof",
"json",
"[",
"k",
"]",
"===",
"'number'",
"&&",
"json",
"[",
"k",
"]",
"%",
"1",
"===",
"0",
")",
";",
"}",
"// check a strict equals",
"return",
"(",
"v",
"===",
"json",
"[",
"k",
"]",
")",
";",
"}",
")",
";",
"}"
] | Check the body expression matches matches the body. | [
"Check",
"the",
"body",
"expression",
"matches",
"matches",
"the",
"body",
"."
] | 9e1401d14113c0e7ba9fe7582f1beac315394a5b | https://github.com/nomic/api-driver/blob/9e1401d14113c0e7ba9fe7582f1beac315394a5b/lib/expector.js#L13-L63 |
50,939 | RekkyRek/RantScript | src/utilities/http.js | POST_FILE | function POST_FILE(uri, params, filepath) {
var form = new FormData();
for (var i in params) {
form.append(i, params[i]);
}
let contenttype = 'INVALID';
if(filepath.split('.').pop().toLowerCase() == 'jpg') { contenttype = 'image/jpg' }
if(filepath.split('.').pop().toLowerCase() == 'png') { contenttype = 'image/png' }
if(filepath.split('.').pop().toLowerCase() == 'gif') { contenttype = 'image/gif' }
if(contenttype == 'INVALID') { throw 'Invalid image type.' }
let imageData = fs.readFileSync(filepath);
form.append('image', imageData, {
filename: filepath.split('/').pop(),
filepath: filepath,
contentType: contenttype,
knownLength: imageData.length
});
const requestURL = `${uri}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
.then(function handleRequest(res) {
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${status}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | javascript | function POST_FILE(uri, params, filepath) {
var form = new FormData();
for (var i in params) {
form.append(i, params[i]);
}
let contenttype = 'INVALID';
if(filepath.split('.').pop().toLowerCase() == 'jpg') { contenttype = 'image/jpg' }
if(filepath.split('.').pop().toLowerCase() == 'png') { contenttype = 'image/png' }
if(filepath.split('.').pop().toLowerCase() == 'gif') { contenttype = 'image/gif' }
if(contenttype == 'INVALID') { throw 'Invalid image type.' }
let imageData = fs.readFileSync(filepath);
form.append('image', imageData, {
filename: filepath.split('/').pop(),
filepath: filepath,
contentType: contenttype,
knownLength: imageData.length
});
const requestURL = `${uri}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
.then(function handleRequest(res) {
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${status}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | [
"function",
"POST_FILE",
"(",
"uri",
",",
"params",
",",
"filepath",
")",
"{",
"var",
"form",
"=",
"new",
"FormData",
"(",
")",
";",
"for",
"(",
"var",
"i",
"in",
"params",
")",
"{",
"form",
".",
"append",
"(",
"i",
",",
"params",
"[",
"i",
"]",
")",
";",
"}",
"let",
"contenttype",
"=",
"'INVALID'",
";",
"if",
"(",
"filepath",
".",
"split",
"(",
"'.'",
")",
".",
"pop",
"(",
")",
".",
"toLowerCase",
"(",
")",
"==",
"'jpg'",
")",
"{",
"contenttype",
"=",
"'image/jpg'",
"}",
"if",
"(",
"filepath",
".",
"split",
"(",
"'.'",
")",
".",
"pop",
"(",
")",
".",
"toLowerCase",
"(",
")",
"==",
"'png'",
")",
"{",
"contenttype",
"=",
"'image/png'",
"}",
"if",
"(",
"filepath",
".",
"split",
"(",
"'.'",
")",
".",
"pop",
"(",
")",
".",
"toLowerCase",
"(",
")",
"==",
"'gif'",
")",
"{",
"contenttype",
"=",
"'image/gif'",
"}",
"if",
"(",
"contenttype",
"==",
"'INVALID'",
")",
"{",
"throw",
"'Invalid image type.'",
"}",
"let",
"imageData",
"=",
"fs",
".",
"readFileSync",
"(",
"filepath",
")",
";",
"form",
".",
"append",
"(",
"'image'",
",",
"imageData",
",",
"{",
"filename",
":",
"filepath",
".",
"split",
"(",
"'/'",
")",
".",
"pop",
"(",
")",
",",
"filepath",
":",
"filepath",
",",
"contentType",
":",
"contenttype",
",",
"knownLength",
":",
"imageData",
".",
"length",
"}",
")",
";",
"const",
"requestURL",
"=",
"`",
"${",
"uri",
"}",
"`",
";",
"log",
"(",
"`",
"${",
"requestURL",
"}",
"`",
")",
";",
"return",
"fetch",
"(",
"requestURL",
",",
"{",
"method",
":",
"'POST'",
",",
"compress",
":",
"compress",
",",
"body",
":",
"form",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'multipart/form-data; boundary='",
"+",
"form",
".",
"getBoundary",
"(",
")",
"}",
"}",
")",
".",
"then",
"(",
"function",
"handleRequest",
"(",
"res",
")",
"{",
"const",
"status",
"=",
"res",
".",
"status",
";",
"if",
"(",
"status",
"!=",
"200",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"status",
"}",
"`",
")",
";",
"error",
".",
"status",
"=",
"status",
";",
"throw",
"error",
";",
"}",
"return",
"res",
".",
"json",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"error",
"=>",
"{",
"log",
"(",
"`",
"${",
"error",
"}",
"`",
")",
";",
"throw",
"error",
";",
"}",
")",
";",
"}"
] | For posting a file using multipart formdata
@param {any} uri - request URL
@param {any} params - request parameters
@param {any} filepath - path to the file
@returns | [
"For",
"posting",
"a",
"file",
"using",
"multipart",
"formdata"
] | 58b6178e9e0b7e6b44c7c9657936dde1166e593f | https://github.com/RekkyRek/RantScript/blob/58b6178e9e0b7e6b44c7c9657936dde1166e593f/src/utilities/http.js#L59-L100 |
50,940 | RekkyRek/RantScript | src/utilities/http.js | POST | function POST(uri, params) {
var form = new FormData();
for (var i in params) {
form.append(i, params[i]);
}
const requestURL = `${uri}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
.then(function handleRequest(res) {
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${status}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | javascript | function POST(uri, params) {
var form = new FormData();
for (var i in params) {
form.append(i, params[i]);
}
const requestURL = `${uri}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'POST', compress: compress, body: form, headers: { 'Content-Type': 'multipart/form-data; boundary='+form.getBoundary() } })
.then(function handleRequest(res) {
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${status}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | [
"function",
"POST",
"(",
"uri",
",",
"params",
")",
"{",
"var",
"form",
"=",
"new",
"FormData",
"(",
")",
";",
"for",
"(",
"var",
"i",
"in",
"params",
")",
"{",
"form",
".",
"append",
"(",
"i",
",",
"params",
"[",
"i",
"]",
")",
";",
"}",
"const",
"requestURL",
"=",
"`",
"${",
"uri",
"}",
"`",
";",
"log",
"(",
"`",
"${",
"requestURL",
"}",
"`",
")",
";",
"return",
"fetch",
"(",
"requestURL",
",",
"{",
"method",
":",
"'POST'",
",",
"compress",
":",
"compress",
",",
"body",
":",
"form",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'multipart/form-data; boundary='",
"+",
"form",
".",
"getBoundary",
"(",
")",
"}",
"}",
")",
".",
"then",
"(",
"function",
"handleRequest",
"(",
"res",
")",
"{",
"const",
"status",
"=",
"res",
".",
"status",
";",
"if",
"(",
"status",
"!=",
"200",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"status",
"}",
"`",
")",
";",
"error",
".",
"status",
"=",
"status",
";",
"throw",
"error",
";",
"}",
"return",
"res",
".",
"json",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"error",
"=>",
"{",
"log",
"(",
"`",
"${",
"error",
"}",
"`",
")",
";",
"throw",
"error",
";",
"}",
")",
";",
"}"
] | Use this functions for HTTP POST request
@param {String} uri - request URL
@param {Object} params - request parameters
@return {Promise} HTTP response | [
"Use",
"this",
"functions",
"for",
"HTTP",
"POST",
"request"
] | 58b6178e9e0b7e6b44c7c9657936dde1166e593f | https://github.com/RekkyRek/RantScript/blob/58b6178e9e0b7e6b44c7c9657936dde1166e593f/src/utilities/http.js#L110-L134 |
50,941 | RekkyRek/RantScript | src/utilities/http.js | DELETE | function DELETE(uri, params) {
const requestURL = `${uri}${url.format({ query: params })}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'DELETE', compress: compress })
.then(function handleRequest(res) {
const statusText = res.statusText;
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${statusText}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | javascript | function DELETE(uri, params) {
const requestURL = `${uri}${url.format({ query: params })}`;
log(`request URL: ${requestURL}`);
return fetch(requestURL, { method: 'DELETE', compress: compress })
.then(function handleRequest(res) {
const statusText = res.statusText;
const status = res.status;
if (status != 200) {
const error = new Error(`Request failed: ${statusText}`);
error.status = status;
throw error;
}
return res.json();
})
.catch(error => {
log(`error: ${error}`);
throw error;
});
} | [
"function",
"DELETE",
"(",
"uri",
",",
"params",
")",
"{",
"const",
"requestURL",
"=",
"`",
"${",
"uri",
"}",
"${",
"url",
".",
"format",
"(",
"{",
"query",
":",
"params",
"}",
")",
"}",
"`",
";",
"log",
"(",
"`",
"${",
"requestURL",
"}",
"`",
")",
";",
"return",
"fetch",
"(",
"requestURL",
",",
"{",
"method",
":",
"'DELETE'",
",",
"compress",
":",
"compress",
"}",
")",
".",
"then",
"(",
"function",
"handleRequest",
"(",
"res",
")",
"{",
"const",
"statusText",
"=",
"res",
".",
"statusText",
";",
"const",
"status",
"=",
"res",
".",
"status",
";",
"if",
"(",
"status",
"!=",
"200",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"statusText",
"}",
"`",
")",
";",
"error",
".",
"status",
"=",
"status",
";",
"throw",
"error",
";",
"}",
"return",
"res",
".",
"json",
"(",
")",
";",
"}",
")",
".",
"catch",
"(",
"error",
"=>",
"{",
"log",
"(",
"`",
"${",
"error",
"}",
"`",
")",
";",
"throw",
"error",
";",
"}",
")",
";",
"}"
] | Use this functions for HTTP DELETE requst
@param {String} uri - request URL
@param {Object} params - request parameters
@return {Promise} HTTP response | [
"Use",
"this",
"functions",
"for",
"HTTP",
"DELETE",
"requst"
] | 58b6178e9e0b7e6b44c7c9657936dde1166e593f | https://github.com/RekkyRek/RantScript/blob/58b6178e9e0b7e6b44c7c9657936dde1166e593f/src/utilities/http.js#L144-L163 |
50,942 | jonschlinkert/inject-snippet | index.js | memoize | function memoize(key, val) {
if (cache.hasOwnProperty(key)) {
return cache[key];
}
return (cache[key] = val);
} | javascript | function memoize(key, val) {
if (cache.hasOwnProperty(key)) {
return cache[key];
}
return (cache[key] = val);
} | [
"function",
"memoize",
"(",
"key",
",",
"val",
")",
"{",
"if",
"(",
"cache",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"return",
"cache",
"[",
"key",
"]",
";",
"}",
"return",
"(",
"cache",
"[",
"key",
"]",
"=",
"val",
")",
";",
"}"
] | Delimiter-related utils | [
"Delimiter",
"-",
"related",
"utils"
] | 8272f3eb32dc31c145e5874fd9ee1ad5004f4d06 | https://github.com/jonschlinkert/inject-snippet/blob/8272f3eb32dc31c145e5874fd9ee1ad5004f4d06/index.js#L108-L113 |
50,943 | tjmehta/cast-buffer | index.js | castBuffer | function castBuffer (val) {
if (Buffer.isBuffer(val)) {
return val
}
val = toJSON(val)
var args = assertArgs([val], {
val: ['string', 'array', 'object', 'number', 'boolean']
})
val = args.val
var str
if (Array.isArray(val)) {
val = val.map(toJSON)
str = JSON.stringify(val)
} else if (isObject(val)) {
val = toJSON(val)
str = JSON.stringify(val)
} else { // val is a string, number, or boolean
str = val + ''
}
return new Buffer(str)
} | javascript | function castBuffer (val) {
if (Buffer.isBuffer(val)) {
return val
}
val = toJSON(val)
var args = assertArgs([val], {
val: ['string', 'array', 'object', 'number', 'boolean']
})
val = args.val
var str
if (Array.isArray(val)) {
val = val.map(toJSON)
str = JSON.stringify(val)
} else if (isObject(val)) {
val = toJSON(val)
str = JSON.stringify(val)
} else { // val is a string, number, or boolean
str = val + ''
}
return new Buffer(str)
} | [
"function",
"castBuffer",
"(",
"val",
")",
"{",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"val",
")",
")",
"{",
"return",
"val",
"}",
"val",
"=",
"toJSON",
"(",
"val",
")",
"var",
"args",
"=",
"assertArgs",
"(",
"[",
"val",
"]",
",",
"{",
"val",
":",
"[",
"'string'",
",",
"'array'",
",",
"'object'",
",",
"'number'",
",",
"'boolean'",
"]",
"}",
")",
"val",
"=",
"args",
".",
"val",
"var",
"str",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"{",
"val",
"=",
"val",
".",
"map",
"(",
"toJSON",
")",
"str",
"=",
"JSON",
".",
"stringify",
"(",
"val",
")",
"}",
"else",
"if",
"(",
"isObject",
"(",
"val",
")",
")",
"{",
"val",
"=",
"toJSON",
"(",
"val",
")",
"str",
"=",
"JSON",
".",
"stringify",
"(",
"val",
")",
"}",
"else",
"{",
"// val is a string, number, or boolean",
"str",
"=",
"val",
"+",
"''",
"}",
"return",
"new",
"Buffer",
"(",
"str",
")",
"}"
] | cast value to buffer
@param {Buffer|Object|Array|String|Boolean} val value to be casted
@return {Buffer} value as a Buffer | [
"cast",
"value",
"to",
"buffer"
] | 4abb132fc84d5ce15d83990ecc69232b7024cbec | https://github.com/tjmehta/cast-buffer/blob/4abb132fc84d5ce15d83990ecc69232b7024cbec/index.js#L15-L39 |
50,944 | le17i/ParseJS | parse.js | function (value) {
if(value === undefined) return null;
if(value instanceof Date) {
return value;
}
var date = null, replace, regex, a = 0, length = helpers.date.regex.length;
value = value.toString();
for(a; a < length; a++) {
regex = helpers.date.regex[a];
if(value.match(regex.test)) {
if(regex.replace.indexOf("-") > -1){
replace = value.replace(regex.test, regex.replace).split("-");
date = new Date(parseInt(replace[0]), parseInt(--replace[1]), parseInt(replace[2]));
}
else {
replace = parseInt(value.replace(regex.test, regex.replace));
date = new Date(replace);
}
break;
}
}
return date;
} | javascript | function (value) {
if(value === undefined) return null;
if(value instanceof Date) {
return value;
}
var date = null, replace, regex, a = 0, length = helpers.date.regex.length;
value = value.toString();
for(a; a < length; a++) {
regex = helpers.date.regex[a];
if(value.match(regex.test)) {
if(regex.replace.indexOf("-") > -1){
replace = value.replace(regex.test, regex.replace).split("-");
date = new Date(parseInt(replace[0]), parseInt(--replace[1]), parseInt(replace[2]));
}
else {
replace = parseInt(value.replace(regex.test, regex.replace));
date = new Date(replace);
}
break;
}
}
return date;
} | [
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"===",
"undefined",
")",
"return",
"null",
";",
"if",
"(",
"value",
"instanceof",
"Date",
")",
"{",
"return",
"value",
";",
"}",
"var",
"date",
"=",
"null",
",",
"replace",
",",
"regex",
",",
"a",
"=",
"0",
",",
"length",
"=",
"helpers",
".",
"date",
".",
"regex",
".",
"length",
";",
"value",
"=",
"value",
".",
"toString",
"(",
")",
";",
"for",
"(",
"a",
";",
"a",
"<",
"length",
";",
"a",
"++",
")",
"{",
"regex",
"=",
"helpers",
".",
"date",
".",
"regex",
"[",
"a",
"]",
";",
"if",
"(",
"value",
".",
"match",
"(",
"regex",
".",
"test",
")",
")",
"{",
"if",
"(",
"regex",
".",
"replace",
".",
"indexOf",
"(",
"\"-\"",
")",
">",
"-",
"1",
")",
"{",
"replace",
"=",
"value",
".",
"replace",
"(",
"regex",
".",
"test",
",",
"regex",
".",
"replace",
")",
".",
"split",
"(",
"\"-\"",
")",
";",
"date",
"=",
"new",
"Date",
"(",
"parseInt",
"(",
"replace",
"[",
"0",
"]",
")",
",",
"parseInt",
"(",
"--",
"replace",
"[",
"1",
"]",
")",
",",
"parseInt",
"(",
"replace",
"[",
"2",
"]",
")",
")",
";",
"}",
"else",
"{",
"replace",
"=",
"parseInt",
"(",
"value",
".",
"replace",
"(",
"regex",
".",
"test",
",",
"regex",
".",
"replace",
")",
")",
";",
"date",
"=",
"new",
"Date",
"(",
"replace",
")",
";",
"}",
"break",
";",
"}",
"}",
"return",
"date",
";",
"}"
] | Try convert the value on date object. If failed, return false | [
"Try",
"convert",
"the",
"value",
"on",
"date",
"object",
".",
"If",
"failed",
"return",
"false"
] | fcd17a78b1a9433a768e0f4fc9650f0df8a8404b | https://github.com/le17i/ParseJS/blob/fcd17a78b1a9433a768e0f4fc9650f0df8a8404b/parse.js#L128-L159 |
|
50,945 | le17i/ParseJS | parse.js | function(format, value) {
var date = helpers.date.parse(value);
if(date === false || date === undefined) return false;
var day = date.getDate().toString().replace(/(?=(^\d{1}$))/g, "0");
var month = (date.getMonth() + 1).toString().replace(/(?=(^\d{1}$))/g, "0");
var formatDate = format
.replace(/dd/gi, day)
.replace(/mm/gi, month)
.replace(/yyyy/gi, date.getFullYear());
return formatDate;
} | javascript | function(format, value) {
var date = helpers.date.parse(value);
if(date === false || date === undefined) return false;
var day = date.getDate().toString().replace(/(?=(^\d{1}$))/g, "0");
var month = (date.getMonth() + 1).toString().replace(/(?=(^\d{1}$))/g, "0");
var formatDate = format
.replace(/dd/gi, day)
.replace(/mm/gi, month)
.replace(/yyyy/gi, date.getFullYear());
return formatDate;
} | [
"function",
"(",
"format",
",",
"value",
")",
"{",
"var",
"date",
"=",
"helpers",
".",
"date",
".",
"parse",
"(",
"value",
")",
";",
"if",
"(",
"date",
"===",
"false",
"||",
"date",
"===",
"undefined",
")",
"return",
"false",
";",
"var",
"day",
"=",
"date",
".",
"getDate",
"(",
")",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"/",
"(?=(^\\d{1}$))",
"/",
"g",
",",
"\"0\"",
")",
";",
"var",
"month",
"=",
"(",
"date",
".",
"getMonth",
"(",
")",
"+",
"1",
")",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"/",
"(?=(^\\d{1}$))",
"/",
"g",
",",
"\"0\"",
")",
";",
"var",
"formatDate",
"=",
"format",
".",
"replace",
"(",
"/",
"dd",
"/",
"gi",
",",
"day",
")",
".",
"replace",
"(",
"/",
"mm",
"/",
"gi",
",",
"month",
")",
".",
"replace",
"(",
"/",
"yyyy",
"/",
"gi",
",",
"date",
".",
"getFullYear",
"(",
")",
")",
";",
"return",
"formatDate",
";",
"}"
] | Transform the date object to format string | [
"Transform",
"the",
"date",
"object",
"to",
"format",
"string"
] | fcd17a78b1a9433a768e0f4fc9650f0df8a8404b | https://github.com/le17i/ParseJS/blob/fcd17a78b1a9433a768e0f4fc9650f0df8a8404b/parse.js#L162-L176 |
|
50,946 | appcelerator-archive/appc-connector-utils | lib/utils/fs.js | saveModelSync | function saveModelSync (modelName, modelMetadata, modelDir) {
const buffer = `const Arrow = require('arrow')
var Model = Arrow.Model.extend('${modelName}', ${JSON.stringify(modelMetadata, null, '\t')})
module.exports = Model`
fs.writeFileSync(path.join(modelDir, modelMetadata.name.toLowerCase() + '.js'), buffer)
} | javascript | function saveModelSync (modelName, modelMetadata, modelDir) {
const buffer = `const Arrow = require('arrow')
var Model = Arrow.Model.extend('${modelName}', ${JSON.stringify(modelMetadata, null, '\t')})
module.exports = Model`
fs.writeFileSync(path.join(modelDir, modelMetadata.name.toLowerCase() + '.js'), buffer)
} | [
"function",
"saveModelSync",
"(",
"modelName",
",",
"modelMetadata",
",",
"modelDir",
")",
"{",
"const",
"buffer",
"=",
"`",
"${",
"modelName",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"modelMetadata",
",",
"null",
",",
"'\\t'",
")",
"}",
"`",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"modelDir",
",",
"modelMetadata",
".",
"name",
".",
"toLowerCase",
"(",
")",
"+",
"'.js'",
")",
",",
"buffer",
")",
"}"
] | Saves model to disk
@param {string} modelName the name model
@param {object} modelMetadata metadata that describes the model
@param {string} modelDir the directory where to save the model | [
"Saves",
"model",
"to",
"disk"
] | 4af3bb7d24c5780270d7ba0ec98017b1f58f1aa8 | https://github.com/appcelerator-archive/appc-connector-utils/blob/4af3bb7d24c5780270d7ba0ec98017b1f58f1aa8/lib/utils/fs.js#L37-L42 |
50,947 | appcelerator-archive/appc-connector-utils | lib/utils/fs.js | ensureExistsAndClean | function ensureExistsAndClean (dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
} else {
cleanDir(dir)
}
} | javascript | function ensureExistsAndClean (dir) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
} else {
cleanDir(dir)
}
} | [
"function",
"ensureExistsAndClean",
"(",
"dir",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"dir",
")",
")",
"{",
"fs",
".",
"mkdirSync",
"(",
"dir",
")",
"}",
"else",
"{",
"cleanDir",
"(",
"dir",
")",
"}",
"}"
] | Makes sure that the specified directory exists.
@param dir | [
"Makes",
"sure",
"that",
"the",
"specified",
"directory",
"exists",
"."
] | 4af3bb7d24c5780270d7ba0ec98017b1f58f1aa8 | https://github.com/appcelerator-archive/appc-connector-utils/blob/4af3bb7d24c5780270d7ba0ec98017b1f58f1aa8/lib/utils/fs.js#L48-L54 |
50,948 | kawanet/promisen | promisen.js | executable | function executable(value) {
var result;
try {
result = resolve(task.apply(this, arguments));
} catch (e) {
result = reject(e);
}
return result;
} | javascript | function executable(value) {
var result;
try {
result = resolve(task.apply(this, arguments));
} catch (e) {
result = reject(e);
}
return result;
} | [
"function",
"executable",
"(",
"value",
")",
"{",
"var",
"result",
";",
"try",
"{",
"result",
"=",
"resolve",
"(",
"task",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"result",
"=",
"reject",
"(",
"e",
")",
";",
"}",
"return",
"result",
";",
"}"
] | return a result from the function | [
"return",
"a",
"result",
"from",
"the",
"function"
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L132-L140 |
50,949 | kawanet/promisen | promisen.js | parallel | function parallel(tasks) {
if (tasks == null) return promisen([]);
tasks = Array.prototype.map.call(tasks, wrap);
return all;
function all(value) {
var boundTasks = Array.prototype.map.call(tasks, run.bind(this, value));
return promisen.Promise.all(boundTasks);
}
// apply the first argument only. ignore rest.
function wrap(task) {
return promisen(task);
}
function run(value, func) {
return func.call(this, value);
}
} | javascript | function parallel(tasks) {
if (tasks == null) return promisen([]);
tasks = Array.prototype.map.call(tasks, wrap);
return all;
function all(value) {
var boundTasks = Array.prototype.map.call(tasks, run.bind(this, value));
return promisen.Promise.all(boundTasks);
}
// apply the first argument only. ignore rest.
function wrap(task) {
return promisen(task);
}
function run(value, func) {
return func.call(this, value);
}
} | [
"function",
"parallel",
"(",
"tasks",
")",
"{",
"if",
"(",
"tasks",
"==",
"null",
")",
"return",
"promisen",
"(",
"[",
"]",
")",
";",
"tasks",
"=",
"Array",
".",
"prototype",
".",
"map",
".",
"call",
"(",
"tasks",
",",
"wrap",
")",
";",
"return",
"all",
";",
"function",
"all",
"(",
"value",
")",
"{",
"var",
"boundTasks",
"=",
"Array",
".",
"prototype",
".",
"map",
".",
"call",
"(",
"tasks",
",",
"run",
".",
"bind",
"(",
"this",
",",
"value",
")",
")",
";",
"return",
"promisen",
".",
"Promise",
".",
"all",
"(",
"boundTasks",
")",
";",
"}",
"// apply the first argument only. ignore rest.",
"function",
"wrap",
"(",
"task",
")",
"{",
"return",
"promisen",
"(",
"task",
")",
";",
"}",
"function",
"run",
"(",
"value",
",",
"func",
")",
"{",
"return",
"func",
".",
"call",
"(",
"this",
",",
"value",
")",
";",
"}",
"}"
] | creates a promise-returning function which runs multiple tasks in parallel.
@class promisen
@static
@function parallel
@param tasks {Array|Array-like} list of tasks
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
// generate a promise-returning function
var task = promisen.parallel([task1, task2, task3,...]);
// execute it
task(value).then(function(array) {...}); // array of results
// execute it with target object which is passed to every tasks
task.call(target, value).then(function(result) {...}); | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"runs",
"multiple",
"tasks",
"in",
"parallel",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L268-L286 |
50,950 | kawanet/promisen | promisen.js | IF | function IF(condTask, trueTask, falseTask) {
condTask = (condTask != null) ? promisen(condTask) : promisen();
trueTask = (trueTask != null) ? promisen(trueTask) : promisen();
falseTask = (falseTask != null) ? promisen(falseTask) : promisen();
return conditional;
function conditional(value) {
var condFunc = condTask.bind(this, value);
var trueFunc = trueTask.bind(this, value);
var falseFunc = falseTask.bind(this, value);
return condFunc().then(switching);
function switching(condition) {
return condition ? trueFunc() : falseFunc();
}
}
} | javascript | function IF(condTask, trueTask, falseTask) {
condTask = (condTask != null) ? promisen(condTask) : promisen();
trueTask = (trueTask != null) ? promisen(trueTask) : promisen();
falseTask = (falseTask != null) ? promisen(falseTask) : promisen();
return conditional;
function conditional(value) {
var condFunc = condTask.bind(this, value);
var trueFunc = trueTask.bind(this, value);
var falseFunc = falseTask.bind(this, value);
return condFunc().then(switching);
function switching(condition) {
return condition ? trueFunc() : falseFunc();
}
}
} | [
"function",
"IF",
"(",
"condTask",
",",
"trueTask",
",",
"falseTask",
")",
"{",
"condTask",
"=",
"(",
"condTask",
"!=",
"null",
")",
"?",
"promisen",
"(",
"condTask",
")",
":",
"promisen",
"(",
")",
";",
"trueTask",
"=",
"(",
"trueTask",
"!=",
"null",
")",
"?",
"promisen",
"(",
"trueTask",
")",
":",
"promisen",
"(",
")",
";",
"falseTask",
"=",
"(",
"falseTask",
"!=",
"null",
")",
"?",
"promisen",
"(",
"falseTask",
")",
":",
"promisen",
"(",
")",
";",
"return",
"conditional",
";",
"function",
"conditional",
"(",
"value",
")",
"{",
"var",
"condFunc",
"=",
"condTask",
".",
"bind",
"(",
"this",
",",
"value",
")",
";",
"var",
"trueFunc",
"=",
"trueTask",
".",
"bind",
"(",
"this",
",",
"value",
")",
";",
"var",
"falseFunc",
"=",
"falseTask",
".",
"bind",
"(",
"this",
",",
"value",
")",
";",
"return",
"condFunc",
"(",
")",
".",
"then",
"(",
"switching",
")",
";",
"function",
"switching",
"(",
"condition",
")",
"{",
"return",
"condition",
"?",
"trueFunc",
"(",
")",
":",
"falseFunc",
"(",
")",
";",
"}",
"}",
"}"
] | creates a promise-returning function which runs a task assigned by a conditional task.
When null or undefined is given as a task, it will do nothing for value and just passes it.
@class promisen
@static
@function if
@param [condTask] {Boolean|Function|Promise|thenable|*|null} boolean or function returns boolean
@param [trueTask] {Function|Promise|thenable|*|null} task runs when true
@param [falseTask] {Function|Promise|thenable|*|null} task runs when false
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
// generate a promise-returning function
var task = promisen.if(condTask, trueTask, falseTask);
// execute itl[pi?K jk ln lml;/, m /P/.[h
task().then(function(result) {...});
// execute it with target object which is passed to every tasks
task.call(target).then(function(result) {...});
// all three arguments are optional.
var runWhenTrueTask = promisen.if(null, trueTask);
Promise.resolve(value).then(runWhenTrueTask).then(function(result) {...});
// conditional task are also available in a waterfall of promisen tasks
var joined = promisen(task1, runWhenTrueTask, task2);
joined().then(function(result) {...});
// use uglify --compress (or UPPERCASE property name) for IE8
var task = promisen["if"](condTask, trueTask, falseTask);
var task = promisen.IF(condTask, trueTask, falseTask); | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"runs",
"a",
"task",
"assigned",
"by",
"a",
"conditional",
"task",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L325-L341 |
50,951 | kawanet/promisen | promisen.js | WHILE | function WHILE(condTask, runTask) {
var runTasks = Array.prototype.slice.call(arguments, 1);
runTasks.push(nextTask);
runTask = waterfall(runTasks);
var whileTask = IF(condTask, runTask);
return whileTask;
function nextTask(value) {
return whileTask.call(this, value);
}
} | javascript | function WHILE(condTask, runTask) {
var runTasks = Array.prototype.slice.call(arguments, 1);
runTasks.push(nextTask);
runTask = waterfall(runTasks);
var whileTask = IF(condTask, runTask);
return whileTask;
function nextTask(value) {
return whileTask.call(this, value);
}
} | [
"function",
"WHILE",
"(",
"condTask",
",",
"runTask",
")",
"{",
"var",
"runTasks",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"runTasks",
".",
"push",
"(",
"nextTask",
")",
";",
"runTask",
"=",
"waterfall",
"(",
"runTasks",
")",
";",
"var",
"whileTask",
"=",
"IF",
"(",
"condTask",
",",
"runTask",
")",
";",
"return",
"whileTask",
";",
"function",
"nextTask",
"(",
"value",
")",
"{",
"return",
"whileTask",
".",
"call",
"(",
"this",
",",
"value",
")",
";",
"}",
"}"
] | creates a promise-returning function which runs a task repeatedly while the condition is true.
When null or undefined is given as condTask, it will do nothing for value and just passes it.
@class promisen
@static
@function while
@param condTask {Boolean|Function|Promise|thenable|*|null} boolean or function returns boolean
@param runTask {...(Function|Promise|thenable|*)} task runs while true
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
// counter = 8; while (--counter) { runTask }
var counter = promisen.number(8);
var whileTask = promisen.while(counter.decr, runTask);
// for (initTask; condTask; afterTask) { runTask }
var forTask = promisen(initTask, promisen.while(condTask, runTask, afterTask));
// do { runTask } while (condTask)
var doWhileTask = promisen.while(null, runTask, condTask)); | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"runs",
"a",
"task",
"repeatedly",
"while",
"the",
"condition",
"is",
"true",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L368-L378 |
50,952 | kawanet/promisen | promisen.js | eachSeries | function eachSeries(arrayTask, iteratorTask) {
if (arrayTask == null) arrayTask = promisen();
iteratorTask = promisen(iteratorTask);
return waterfall([arrayTask, loopTask]);
// composite multiple tasks
function loopTask(arrayResults) {
arrayResults = Array.prototype.map.call(arrayResults, wrap);
return series(arrayResults).call(this);
}
function wrap(value) {
return iterator;
function iterator() {
return iteratorTask.call(this, value);
}
}
} | javascript | function eachSeries(arrayTask, iteratorTask) {
if (arrayTask == null) arrayTask = promisen();
iteratorTask = promisen(iteratorTask);
return waterfall([arrayTask, loopTask]);
// composite multiple tasks
function loopTask(arrayResults) {
arrayResults = Array.prototype.map.call(arrayResults, wrap);
return series(arrayResults).call(this);
}
function wrap(value) {
return iterator;
function iterator() {
return iteratorTask.call(this, value);
}
}
} | [
"function",
"eachSeries",
"(",
"arrayTask",
",",
"iteratorTask",
")",
"{",
"if",
"(",
"arrayTask",
"==",
"null",
")",
"arrayTask",
"=",
"promisen",
"(",
")",
";",
"iteratorTask",
"=",
"promisen",
"(",
"iteratorTask",
")",
";",
"return",
"waterfall",
"(",
"[",
"arrayTask",
",",
"loopTask",
"]",
")",
";",
"// composite multiple tasks",
"function",
"loopTask",
"(",
"arrayResults",
")",
"{",
"arrayResults",
"=",
"Array",
".",
"prototype",
".",
"map",
".",
"call",
"(",
"arrayResults",
",",
"wrap",
")",
";",
"return",
"series",
"(",
"arrayResults",
")",
".",
"call",
"(",
"this",
")",
";",
"}",
"function",
"wrap",
"(",
"value",
")",
"{",
"return",
"iterator",
";",
"function",
"iterator",
"(",
")",
"{",
"return",
"iteratorTask",
".",
"call",
"(",
"this",
",",
"value",
")",
";",
"}",
"}",
"}"
] | creates a promise-returning function which runs task repeatedly for each value of array in order.
@class promisen
@static
@function eachSeries
@param arrayTask {Array|Function|Promise|thenable} array or task returns array for iteration
@param iteratorTask {Function} task runs repeatedly for each of array values
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var task = promisen.eachSeries([1, 2, 3], mul2);
task.call(target).then(function(array) {...}); // => [2, 4, 6]
function mul2(value) {
return value * 2;
} | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"runs",
"task",
"repeatedly",
"for",
"each",
"value",
"of",
"array",
"in",
"order",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L401-L418 |
50,953 | kawanet/promisen | promisen.js | each | function each(arrayTask, iteratorTask) {
if (arrayTask == null) arrayTask = promisen();
iteratorTask = promisen(iteratorTask);
return waterfall([arrayTask, loopTask]);
// composite multiple tasks
function loopTask(arrayResults) {
arrayResults = Array.prototype.map.call(arrayResults, wrap);
return parallel(arrayResults).call(this);
}
// apply the first argument only. ignore rest.
function wrap(value) {
return iterator;
function iterator() {
return iteratorTask.call(this, value);
}
}
} | javascript | function each(arrayTask, iteratorTask) {
if (arrayTask == null) arrayTask = promisen();
iteratorTask = promisen(iteratorTask);
return waterfall([arrayTask, loopTask]);
// composite multiple tasks
function loopTask(arrayResults) {
arrayResults = Array.prototype.map.call(arrayResults, wrap);
return parallel(arrayResults).call(this);
}
// apply the first argument only. ignore rest.
function wrap(value) {
return iterator;
function iterator() {
return iteratorTask.call(this, value);
}
}
} | [
"function",
"each",
"(",
"arrayTask",
",",
"iteratorTask",
")",
"{",
"if",
"(",
"arrayTask",
"==",
"null",
")",
"arrayTask",
"=",
"promisen",
"(",
")",
";",
"iteratorTask",
"=",
"promisen",
"(",
"iteratorTask",
")",
";",
"return",
"waterfall",
"(",
"[",
"arrayTask",
",",
"loopTask",
"]",
")",
";",
"// composite multiple tasks",
"function",
"loopTask",
"(",
"arrayResults",
")",
"{",
"arrayResults",
"=",
"Array",
".",
"prototype",
".",
"map",
".",
"call",
"(",
"arrayResults",
",",
"wrap",
")",
";",
"return",
"parallel",
"(",
"arrayResults",
")",
".",
"call",
"(",
"this",
")",
";",
"}",
"// apply the first argument only. ignore rest.",
"function",
"wrap",
"(",
"value",
")",
"{",
"return",
"iterator",
";",
"function",
"iterator",
"(",
")",
"{",
"return",
"iteratorTask",
".",
"call",
"(",
"this",
",",
"value",
")",
";",
"}",
"}",
"}"
] | creates a promise-returning function which runs task repeatedly for each value of array in parallel.
@class promisen
@static
@function each
@param arrayTask {Array|Function|Promise|thenable} array or task returns array for iteration
@param iteratorTask {Function} task runs repeatedly for each of array values
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var task = promisen.each([2, 4, 6], div2);
task.call(target).then(function(array) {...}); // => [1, 2, 3]
function div2(value) {
return value / 2;
} | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"runs",
"task",
"repeatedly",
"for",
"each",
"value",
"of",
"array",
"in",
"parallel",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L441-L459 |
50,954 | kawanet/promisen | promisen.js | incr | function incr(array) {
return incrTask;
function incrTask() {
if (!array.length) {
Array.prototype.push.call(array, 0 | 0);
}
return resolve(++array[array.length - 1]);
}
} | javascript | function incr(array) {
return incrTask;
function incrTask() {
if (!array.length) {
Array.prototype.push.call(array, 0 | 0);
}
return resolve(++array[array.length - 1]);
}
} | [
"function",
"incr",
"(",
"array",
")",
"{",
"return",
"incrTask",
";",
"function",
"incrTask",
"(",
")",
"{",
"if",
"(",
"!",
"array",
".",
"length",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"call",
"(",
"array",
",",
"0",
"|",
"0",
")",
";",
"}",
"return",
"resolve",
"(",
"++",
"array",
"[",
"array",
".",
"length",
"-",
"1",
"]",
")",
";",
"}",
"}"
] | creates a promise-returning function which increments a counter on top of stack.
@class promisen
@static
@function incr
@param array {Array|Array-like} counter holder
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var counter = [123];
console.log("count: " + counter); // => count: 123
var incrTask = counter.incr();
incrTask().then(function(value) {...}); // => count: 124
// incrTask is available in a series of tasks.
var task = promisen(otherTask, incrTask); | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"increments",
"a",
"counter",
"on",
"top",
"of",
"stack",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L482-L491 |
50,955 | kawanet/promisen | promisen.js | push | function push(array) {
return pushTask;
function pushTask(value) {
Array.prototype.push.call(array, value); // copy
return resolve(value); // through
}
} | javascript | function push(array) {
return pushTask;
function pushTask(value) {
Array.prototype.push.call(array, value); // copy
return resolve(value); // through
}
} | [
"function",
"push",
"(",
"array",
")",
"{",
"return",
"pushTask",
";",
"function",
"pushTask",
"(",
"value",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"call",
"(",
"array",
",",
"value",
")",
";",
"// copy",
"return",
"resolve",
"(",
"value",
")",
";",
"// through",
"}",
"}"
] | creates a promise-returning function which stores a value into the array.
@class promisen
@static
@function push
@param array {Array|Array-like}
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var stack = []; // stack is an array
var task2 = promisen(task1, promisen.push(stack));
task2().then(function() {...}); // stack.length == 2 | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"stores",
"a",
"value",
"into",
"the",
"array",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L543-L550 |
50,956 | kawanet/promisen | promisen.js | pop | function pop(array) {
return popTask;
function popTask() {
var value = Array.prototype.pop.call(array);
return resolve(value);
}
} | javascript | function pop(array) {
return popTask;
function popTask() {
var value = Array.prototype.pop.call(array);
return resolve(value);
}
} | [
"function",
"pop",
"(",
"array",
")",
"{",
"return",
"popTask",
";",
"function",
"popTask",
"(",
")",
"{",
"var",
"value",
"=",
"Array",
".",
"prototype",
".",
"pop",
".",
"call",
"(",
"array",
")",
";",
"return",
"resolve",
"(",
"value",
")",
";",
"}",
"}"
] | creates a promise-returning function which fetches the last value on the array.
@class promisen
@static
@function pop
@param array {Array|Array-like}
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var stack = ["foo", "bar"]; // stack is an array
var task2 = promisen(promisen.pop(stack), task1);
task2().then(function() {...}); // stack.length == 1 | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"fetches",
"the",
"last",
"value",
"on",
"the",
"array",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L570-L577 |
50,957 | kawanet/promisen | promisen.js | top | function top(array) {
return topTask;
function topTask() {
var value = array[array.length - 1];
return resolve(value);
}
} | javascript | function top(array) {
return topTask;
function topTask() {
var value = array[array.length - 1];
return resolve(value);
}
} | [
"function",
"top",
"(",
"array",
")",
"{",
"return",
"topTask",
";",
"function",
"topTask",
"(",
")",
"{",
"var",
"value",
"=",
"array",
"[",
"array",
".",
"length",
"-",
"1",
"]",
";",
"return",
"resolve",
"(",
"value",
")",
";",
"}",
"}"
] | creates a promise-returning function which inspects the last value on the array.
@class promisen
@static
@function push
@param array {Array|Array-like}
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var stack = ["foo", "bar"]; // stack is an array
var task2 = promisen(promisen.top(stack), task1);
task2().then(function() {...}); // stack.length == 2 | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"inspects",
"the",
"last",
"value",
"on",
"the",
"array",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L597-L604 |
50,958 | kawanet/promisen | promisen.js | wait | function wait(msec) {
return waitTask;
function waitTask(value) {
var that = this;
return new promisen.Promise(function(resolve) {
setTimeout(function() {
resolve.call(that, value);
}, msec);
});
}
} | javascript | function wait(msec) {
return waitTask;
function waitTask(value) {
var that = this;
return new promisen.Promise(function(resolve) {
setTimeout(function() {
resolve.call(that, value);
}, msec);
});
}
} | [
"function",
"wait",
"(",
"msec",
")",
"{",
"return",
"waitTask",
";",
"function",
"waitTask",
"(",
"value",
")",
"{",
"var",
"that",
"=",
"this",
";",
"return",
"new",
"promisen",
".",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"resolve",
".",
"call",
"(",
"that",
",",
"value",
")",
";",
"}",
",",
"msec",
")",
";",
"}",
")",
";",
"}",
"}"
] | creates a promise-returning function which does just sleep for given milliseconds.
@class promisen
@static
@function wait
@param msec {Number}
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var sleep = promisen.wait(1000); // 1 sec
sleep(value).then(function(value) {...});
// similar to below
setTimeout(function() {...}, 1000); | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"does",
"just",
"sleep",
"for",
"given",
"milliseconds",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L686-L697 |
50,959 | kawanet/promisen | promisen.js | throttle | function throttle(task, concurrency, timeout) {
if (!concurrency) concurrency = 1;
task = promisen(task);
var queue = singleTask.queue = [];
var running = singleTask.running = {};
var serial = 0;
return singleTask;
function singleTask(value) {
var that = this;
var args = arguments;
var Promise = promisen.Promise;
var seq = ++serial;
return new Promise(function(resolve, reject) {
queue.push(job);
var timer = timeout && setTimeout(onTimeout, timeout);
next();
function job() {
if (timer) clearTimeout(timer);
running[seq] = true;
task.apply(that, args).then(onResolve, onReject);
}
function onTimeout() {
onReject(new Error("timeout: " + timeout + "ms"));
}
function onResolve(value) {
delete running[seq];
setTimeout(next, 0);
resolve(value);
}
function onReject(value) {
delete running[seq];
setTimeout(next, 0);
reject(value);
}
});
}
function next() {
if (Object.keys(running).length >= concurrency) return;
var job = queue.pop();
if (job) job();
}
} | javascript | function throttle(task, concurrency, timeout) {
if (!concurrency) concurrency = 1;
task = promisen(task);
var queue = singleTask.queue = [];
var running = singleTask.running = {};
var serial = 0;
return singleTask;
function singleTask(value) {
var that = this;
var args = arguments;
var Promise = promisen.Promise;
var seq = ++serial;
return new Promise(function(resolve, reject) {
queue.push(job);
var timer = timeout && setTimeout(onTimeout, timeout);
next();
function job() {
if (timer) clearTimeout(timer);
running[seq] = true;
task.apply(that, args).then(onResolve, onReject);
}
function onTimeout() {
onReject(new Error("timeout: " + timeout + "ms"));
}
function onResolve(value) {
delete running[seq];
setTimeout(next, 0);
resolve(value);
}
function onReject(value) {
delete running[seq];
setTimeout(next, 0);
reject(value);
}
});
}
function next() {
if (Object.keys(running).length >= concurrency) return;
var job = queue.pop();
if (job) job();
}
} | [
"function",
"throttle",
"(",
"task",
",",
"concurrency",
",",
"timeout",
")",
"{",
"if",
"(",
"!",
"concurrency",
")",
"concurrency",
"=",
"1",
";",
"task",
"=",
"promisen",
"(",
"task",
")",
";",
"var",
"queue",
"=",
"singleTask",
".",
"queue",
"=",
"[",
"]",
";",
"var",
"running",
"=",
"singleTask",
".",
"running",
"=",
"{",
"}",
";",
"var",
"serial",
"=",
"0",
";",
"return",
"singleTask",
";",
"function",
"singleTask",
"(",
"value",
")",
"{",
"var",
"that",
"=",
"this",
";",
"var",
"args",
"=",
"arguments",
";",
"var",
"Promise",
"=",
"promisen",
".",
"Promise",
";",
"var",
"seq",
"=",
"++",
"serial",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"queue",
".",
"push",
"(",
"job",
")",
";",
"var",
"timer",
"=",
"timeout",
"&&",
"setTimeout",
"(",
"onTimeout",
",",
"timeout",
")",
";",
"next",
"(",
")",
";",
"function",
"job",
"(",
")",
"{",
"if",
"(",
"timer",
")",
"clearTimeout",
"(",
"timer",
")",
";",
"running",
"[",
"seq",
"]",
"=",
"true",
";",
"task",
".",
"apply",
"(",
"that",
",",
"args",
")",
".",
"then",
"(",
"onResolve",
",",
"onReject",
")",
";",
"}",
"function",
"onTimeout",
"(",
")",
"{",
"onReject",
"(",
"new",
"Error",
"(",
"\"timeout: \"",
"+",
"timeout",
"+",
"\"ms\"",
")",
")",
";",
"}",
"function",
"onResolve",
"(",
"value",
")",
"{",
"delete",
"running",
"[",
"seq",
"]",
";",
"setTimeout",
"(",
"next",
",",
"0",
")",
";",
"resolve",
"(",
"value",
")",
";",
"}",
"function",
"onReject",
"(",
"value",
")",
"{",
"delete",
"running",
"[",
"seq",
"]",
";",
"setTimeout",
"(",
"next",
",",
"0",
")",
";",
"reject",
"(",
"value",
")",
";",
"}",
"}",
")",
";",
"}",
"function",
"next",
"(",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"running",
")",
".",
"length",
">=",
"concurrency",
")",
"return",
";",
"var",
"job",
"=",
"queue",
".",
"pop",
"(",
")",
";",
"if",
"(",
"job",
")",
"job",
"(",
")",
";",
"}",
"}"
] | creates a promise-returning function which limits number of concurrent job workers run in parallel.
@class promisen
@static
@function throttle
@param task {Function} the job
@param concurrency {Number} number of job workers run in parallel (default: 1)
@param timeout {Number} timeout in millisecond until job started (default: no timeout)
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var serialAjaxTask = promisen.throttle(ajaxTask, 1, 10000); // 1 worker, 10 seconds
serialAjaxTask(req).then(function(res) {...}); | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"limits",
"number",
"of",
"concurrent",
"job",
"workers",
"run",
"in",
"parallel",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L717-L765 |
50,960 | kawanet/promisen | promisen.js | nodeify | function nodeify(task) {
task = promisen(task);
return nodeifyTask;
function nodeifyTask(args, callback) {
args = Array.prototype.slice.call(arguments);
callback = (args[args.length - 1] instanceof Function) && args.pop();
if (!callback) callback = NOP;
var onResolve = callback.bind(this, null);
var onReject = callback.bind(this);
task.apply(this, args).then(onResolve, onReject);
}
} | javascript | function nodeify(task) {
task = promisen(task);
return nodeifyTask;
function nodeifyTask(args, callback) {
args = Array.prototype.slice.call(arguments);
callback = (args[args.length - 1] instanceof Function) && args.pop();
if (!callback) callback = NOP;
var onResolve = callback.bind(this, null);
var onReject = callback.bind(this);
task.apply(this, args).then(onResolve, onReject);
}
} | [
"function",
"nodeify",
"(",
"task",
")",
"{",
"task",
"=",
"promisen",
"(",
"task",
")",
";",
"return",
"nodeifyTask",
";",
"function",
"nodeifyTask",
"(",
"args",
",",
"callback",
")",
"{",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"callback",
"=",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
"instanceof",
"Function",
")",
"&&",
"args",
".",
"pop",
"(",
")",
";",
"if",
"(",
"!",
"callback",
")",
"callback",
"=",
"NOP",
";",
"var",
"onResolve",
"=",
"callback",
".",
"bind",
"(",
"this",
",",
"null",
")",
";",
"var",
"onReject",
"=",
"callback",
".",
"bind",
"(",
"this",
")",
";",
"task",
".",
"apply",
"(",
"this",
",",
"args",
")",
".",
"then",
"(",
"onResolve",
",",
"onReject",
")",
";",
"}",
"}"
] | creates a Node.js-style function from a promise-returning function or any object.
@class promisen
@static
@function nodeify
@param task {Function|Promise|thenable|*} promise-returning function or any object
@returns {Function} Node.js-style function
@example
var promisen = require("promisen");
var task = nodeify(func);
task(value, function(err, res) {...});
function func(value) {
return new Promise(function(resolve, reject) {...});
} | [
"creates",
"a",
"Node",
".",
"js",
"-",
"style",
"function",
"from",
"a",
"promise",
"-",
"returning",
"function",
"or",
"any",
"object",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L830-L842 |
50,961 | kawanet/promisen | promisen.js | memoize | function memoize(task, expire, hasher) {
var memo = memoizeTask.memo = {};
expire -= 0;
var timers = {};
if (!hasher) hasher = JSON.stringify.bind(JSON);
return memoizeTask;
function memoizeTask(value) {
return waterfall([hasher, readCache]).call(this, value);
// read previous result from cache
function readCache(hash) {
if (hash in memo) return memo[hash];
return waterfall([task, writeCache]).call(this, value);
// write new result to cache
function writeCache(result) {
result = memo[hash] = resolve(result);
if (expire) {
// cancel previous timer
if (timers[hash]) clearTimeout(timers[hash]);
// add new timer
timers[hash] = setTimeout(clearCache, expire);
}
return result;
}
// clear expired result
function clearCache() {
delete memo[hash];
delete timers[hash];
}
}
}
} | javascript | function memoize(task, expire, hasher) {
var memo = memoizeTask.memo = {};
expire -= 0;
var timers = {};
if (!hasher) hasher = JSON.stringify.bind(JSON);
return memoizeTask;
function memoizeTask(value) {
return waterfall([hasher, readCache]).call(this, value);
// read previous result from cache
function readCache(hash) {
if (hash in memo) return memo[hash];
return waterfall([task, writeCache]).call(this, value);
// write new result to cache
function writeCache(result) {
result = memo[hash] = resolve(result);
if (expire) {
// cancel previous timer
if (timers[hash]) clearTimeout(timers[hash]);
// add new timer
timers[hash] = setTimeout(clearCache, expire);
}
return result;
}
// clear expired result
function clearCache() {
delete memo[hash];
delete timers[hash];
}
}
}
} | [
"function",
"memoize",
"(",
"task",
",",
"expire",
",",
"hasher",
")",
"{",
"var",
"memo",
"=",
"memoizeTask",
".",
"memo",
"=",
"{",
"}",
";",
"expire",
"-=",
"0",
";",
"var",
"timers",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"hasher",
")",
"hasher",
"=",
"JSON",
".",
"stringify",
".",
"bind",
"(",
"JSON",
")",
";",
"return",
"memoizeTask",
";",
"function",
"memoizeTask",
"(",
"value",
")",
"{",
"return",
"waterfall",
"(",
"[",
"hasher",
",",
"readCache",
"]",
")",
".",
"call",
"(",
"this",
",",
"value",
")",
";",
"// read previous result from cache",
"function",
"readCache",
"(",
"hash",
")",
"{",
"if",
"(",
"hash",
"in",
"memo",
")",
"return",
"memo",
"[",
"hash",
"]",
";",
"return",
"waterfall",
"(",
"[",
"task",
",",
"writeCache",
"]",
")",
".",
"call",
"(",
"this",
",",
"value",
")",
";",
"// write new result to cache",
"function",
"writeCache",
"(",
"result",
")",
"{",
"result",
"=",
"memo",
"[",
"hash",
"]",
"=",
"resolve",
"(",
"result",
")",
";",
"if",
"(",
"expire",
")",
"{",
"// cancel previous timer",
"if",
"(",
"timers",
"[",
"hash",
"]",
")",
"clearTimeout",
"(",
"timers",
"[",
"hash",
"]",
")",
";",
"// add new timer",
"timers",
"[",
"hash",
"]",
"=",
"setTimeout",
"(",
"clearCache",
",",
"expire",
")",
";",
"}",
"return",
"result",
";",
"}",
"// clear expired result",
"function",
"clearCache",
"(",
")",
"{",
"delete",
"memo",
"[",
"hash",
"]",
";",
"delete",
"timers",
"[",
"hash",
"]",
";",
"}",
"}",
"}",
"}"
] | creates a promise-returning function which caches a result of task.
The cache of result is exposed as the memo property of the function returned by memoize.
@class promisen
@static
@function memoize
@param task {Function} task to wrap
@param expire {Number} millisecond until cache expired
@param [hasher] {Function} default: JSON.stringify()
@returns {Function} promise-returning function
@example
var promisen = require("promisen");
var request = require("request");
var ajaxGet = promisen.denodeify(request);
var cachedAjax = promisen.memoize(ajaxGet);
var req = {url: "http://www.example.com/"};
cachedAjax(req).then(function(res) {...}); // res.body contains response body | [
"creates",
"a",
"promise",
"-",
"returning",
"function",
"which",
"caches",
"a",
"result",
"of",
"task",
"."
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L904-L938 |
50,962 | kawanet/promisen | promisen.js | writeCache | function writeCache(result) {
result = memo[hash] = resolve(result);
if (expire) {
// cancel previous timer
if (timers[hash]) clearTimeout(timers[hash]);
// add new timer
timers[hash] = setTimeout(clearCache, expire);
}
return result;
} | javascript | function writeCache(result) {
result = memo[hash] = resolve(result);
if (expire) {
// cancel previous timer
if (timers[hash]) clearTimeout(timers[hash]);
// add new timer
timers[hash] = setTimeout(clearCache, expire);
}
return result;
} | [
"function",
"writeCache",
"(",
"result",
")",
"{",
"result",
"=",
"memo",
"[",
"hash",
"]",
"=",
"resolve",
"(",
"result",
")",
";",
"if",
"(",
"expire",
")",
"{",
"// cancel previous timer",
"if",
"(",
"timers",
"[",
"hash",
"]",
")",
"clearTimeout",
"(",
"timers",
"[",
"hash",
"]",
")",
";",
"// add new timer",
"timers",
"[",
"hash",
"]",
"=",
"setTimeout",
"(",
"clearCache",
",",
"expire",
")",
";",
"}",
"return",
"result",
";",
"}"
] | write new result to cache | [
"write",
"new",
"result",
"to",
"cache"
] | 71093972cf8d3cfb8e316f48498f1aa9999f169c | https://github.com/kawanet/promisen/blob/71093972cf8d3cfb8e316f48498f1aa9999f169c/promisen.js#L920-L929 |
50,963 | tolokoban/ToloFrameWork | ker/mod/tfw.view.combo.js | manageIfFewItems | function manageIfFewItems() {
const itemsCount = getLength.call( this, this.items );
if ( itemsCount < 2 ) return true;
if ( itemsCount === 2 ) {
this.index = 1 - this.index;
this.expanded = false;
return true;
}
// More than 2 items to manage.
return false;
} | javascript | function manageIfFewItems() {
const itemsCount = getLength.call( this, this.items );
if ( itemsCount < 2 ) return true;
if ( itemsCount === 2 ) {
this.index = 1 - this.index;
this.expanded = false;
return true;
}
// More than 2 items to manage.
return false;
} | [
"function",
"manageIfFewItems",
"(",
")",
"{",
"const",
"itemsCount",
"=",
"getLength",
".",
"call",
"(",
"this",
",",
"this",
".",
"items",
")",
";",
"if",
"(",
"itemsCount",
"<",
"2",
")",
"return",
"true",
";",
"if",
"(",
"itemsCount",
"===",
"2",
")",
"{",
"this",
".",
"index",
"=",
"1",
"-",
"this",
".",
"index",
";",
"this",
".",
"expanded",
"=",
"false",
";",
"return",
"true",
";",
"}",
"// More than 2 items to manage.",
"return",
"false",
";",
"}"
] | For two items, we never show the whole list, but we just change the selection on click.
@this ViewXJS
@returns {boolean} `true` if there are at most 2 items. | [
"For",
"two",
"items",
"we",
"never",
"show",
"the",
"whole",
"list",
"but",
"we",
"just",
"change",
"the",
"selection",
"on",
"click",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.combo.js#L50-L60 |
50,964 | tolokoban/ToloFrameWork | ker/mod/tfw.view.combo.js | moveList | function moveList( collapsedList, expandedList ) {
const
rect = collapsedList.getBoundingClientRect(),
left = rect.left;
let top = rect.top;
while ( top <= 0 ) top += ITEM_HEIGHT;
Dom.css( expandedList, {
left: `${left}px`,
top: `${top}px`
} );
} | javascript | function moveList( collapsedList, expandedList ) {
const
rect = collapsedList.getBoundingClientRect(),
left = rect.left;
let top = rect.top;
while ( top <= 0 ) top += ITEM_HEIGHT;
Dom.css( expandedList, {
left: `${left}px`,
top: `${top}px`
} );
} | [
"function",
"moveList",
"(",
"collapsedList",
",",
"expandedList",
")",
"{",
"const",
"rect",
"=",
"collapsedList",
".",
"getBoundingClientRect",
"(",
")",
",",
"left",
"=",
"rect",
".",
"left",
";",
"let",
"top",
"=",
"rect",
".",
"top",
";",
"while",
"(",
"top",
"<=",
"0",
")",
"top",
"+=",
"ITEM_HEIGHT",
";",
"Dom",
".",
"css",
"(",
"expandedList",
",",
"{",
"left",
":",
"`",
"${",
"left",
"}",
"`",
",",
"top",
":",
"`",
"${",
"top",
"}",
"`",
"}",
")",
";",
"}"
] | Try to move `expandedList` to make the selected item be exactly above the same item in
`collapsedItem`. If it is not possible, a scroll bar will appear.
@param {DOMElement} collapsedList - DIV showing only one item bcause the rest is hidden.
@param {DOMElement} expandedList - DIV showing the most items as it can.
@returns {undefined} | [
"Try",
"to",
"move",
"expandedList",
"to",
"make",
"the",
"selected",
"item",
"be",
"exactly",
"above",
"the",
"same",
"item",
"in",
"collapsedItem",
".",
"If",
"it",
"is",
"not",
"possible",
"a",
"scroll",
"bar",
"will",
"appear",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.combo.js#L169-L179 |
50,965 | tolokoban/ToloFrameWork | ker/mod/tfw.view.combo.js | copyContentOf | function copyContentOf() {
const
that = this,
items = this.items,
div = Dom.div( "thm-ele8" );
items.forEach( function ( item, index ) {
const clonedItem = Dom.div( that.index === index ? "thm-bgSL" : "thm-bg3" );
if ( typeof item === 'string' ) {
clonedItem.textContent = item;
} else {
clonedItem.innerHTML = Dom( item ).innerHTML;
}
Dom.add( div, clonedItem );
const touchable = new Touchable( clonedItem );
touchable.tap.add( () => {
that.expanded = false;
that.index = index;
} );
} );
return div;
} | javascript | function copyContentOf() {
const
that = this,
items = this.items,
div = Dom.div( "thm-ele8" );
items.forEach( function ( item, index ) {
const clonedItem = Dom.div( that.index === index ? "thm-bgSL" : "thm-bg3" );
if ( typeof item === 'string' ) {
clonedItem.textContent = item;
} else {
clonedItem.innerHTML = Dom( item ).innerHTML;
}
Dom.add( div, clonedItem );
const touchable = new Touchable( clonedItem );
touchable.tap.add( () => {
that.expanded = false;
that.index = index;
} );
} );
return div;
} | [
"function",
"copyContentOf",
"(",
")",
"{",
"const",
"that",
"=",
"this",
",",
"items",
"=",
"this",
".",
"items",
",",
"div",
"=",
"Dom",
".",
"div",
"(",
"\"thm-ele8\"",
")",
";",
"items",
".",
"forEach",
"(",
"function",
"(",
"item",
",",
"index",
")",
"{",
"const",
"clonedItem",
"=",
"Dom",
".",
"div",
"(",
"that",
".",
"index",
"===",
"index",
"?",
"\"thm-bgSL\"",
":",
"\"thm-bg3\"",
")",
";",
"if",
"(",
"typeof",
"item",
"===",
"'string'",
")",
"{",
"clonedItem",
".",
"textContent",
"=",
"item",
";",
"}",
"else",
"{",
"clonedItem",
".",
"innerHTML",
"=",
"Dom",
"(",
"item",
")",
".",
"innerHTML",
";",
"}",
"Dom",
".",
"add",
"(",
"div",
",",
"clonedItem",
")",
";",
"const",
"touchable",
"=",
"new",
"Touchable",
"(",
"clonedItem",
")",
";",
"touchable",
".",
"tap",
".",
"add",
"(",
"(",
")",
"=>",
"{",
"that",
".",
"expanded",
"=",
"false",
";",
"that",
".",
"index",
"=",
"index",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"div",
";",
"}"
] | We sill copy the innerHTML of items and add a Touchable behaviour on each of them.
@this ViewXJS
@returns {DOMElement} DIV with all cloned items. | [
"We",
"sill",
"copy",
"the",
"innerHTML",
"of",
"items",
"and",
"add",
"a",
"Touchable",
"behaviour",
"on",
"each",
"of",
"them",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.combo.js#L186-L206 |
50,966 | tolokoban/ToloFrameWork | ker/mod/tfw.view.combo.js | onKeyDown | function onKeyDown( evt ) {
switch ( evt.key ) {
case 'Space':
this.expanded = !this.expanded;
evt.preventDefault();
break;
case 'Enter':
this.action = this.value;
break;
case 'ArrowDown':
selectNext.call( this );
evt.preventDefault();
break;
case 'ArrowUp':
selectPrev.call( this );
evt.preventDefault();
break;
case 'Escape':
if ( this.expanded ) {
this.expanded = false;
// Set the value as it was when we expanded the combo.
this.value = this._valueWhenExpanded;
evt.preventDefault();
}
break;
default:
// Do nothing.
}
} | javascript | function onKeyDown( evt ) {
switch ( evt.key ) {
case 'Space':
this.expanded = !this.expanded;
evt.preventDefault();
break;
case 'Enter':
this.action = this.value;
break;
case 'ArrowDown':
selectNext.call( this );
evt.preventDefault();
break;
case 'ArrowUp':
selectPrev.call( this );
evt.preventDefault();
break;
case 'Escape':
if ( this.expanded ) {
this.expanded = false;
// Set the value as it was when we expanded the combo.
this.value = this._valueWhenExpanded;
evt.preventDefault();
}
break;
default:
// Do nothing.
}
} | [
"function",
"onKeyDown",
"(",
"evt",
")",
"{",
"switch",
"(",
"evt",
".",
"key",
")",
"{",
"case",
"'Space'",
":",
"this",
".",
"expanded",
"=",
"!",
"this",
".",
"expanded",
";",
"evt",
".",
"preventDefault",
"(",
")",
";",
"break",
";",
"case",
"'Enter'",
":",
"this",
".",
"action",
"=",
"this",
".",
"value",
";",
"break",
";",
"case",
"'ArrowDown'",
":",
"selectNext",
".",
"call",
"(",
"this",
")",
";",
"evt",
".",
"preventDefault",
"(",
")",
";",
"break",
";",
"case",
"'ArrowUp'",
":",
"selectPrev",
".",
"call",
"(",
"this",
")",
";",
"evt",
".",
"preventDefault",
"(",
")",
";",
"break",
";",
"case",
"'Escape'",
":",
"if",
"(",
"this",
".",
"expanded",
")",
"{",
"this",
".",
"expanded",
"=",
"false",
";",
"// Set the value as it was when we expanded the combo.",
"this",
".",
"value",
"=",
"this",
".",
"_valueWhenExpanded",
";",
"evt",
".",
"preventDefault",
"(",
")",
";",
"}",
"break",
";",
"default",
":",
"// Do nothing.",
"}",
"}"
] | Space will expand the combo, Escape will collapse it and Enter will trigger an action.
@this ViewXJS
@param {[type]} evt [description]
@returns {[type]} [description] | [
"Space",
"will",
"expand",
"the",
"combo",
"Escape",
"will",
"collapse",
"it",
"and",
"Enter",
"will",
"trigger",
"an",
"action",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.combo.js#L253-L281 |
50,967 | tolokoban/ToloFrameWork | ker/mod/tfw.view.combo.js | selectNext | function selectNext() {
this.index = ( this.index + 1 ) % this.items.length;
if ( this.expanded ) {
collapse.call( this );
expand.call( this, false );
}
} | javascript | function selectNext() {
this.index = ( this.index + 1 ) % this.items.length;
if ( this.expanded ) {
collapse.call( this );
expand.call( this, false );
}
} | [
"function",
"selectNext",
"(",
")",
"{",
"this",
".",
"index",
"=",
"(",
"this",
".",
"index",
"+",
"1",
")",
"%",
"this",
".",
"items",
".",
"length",
";",
"if",
"(",
"this",
".",
"expanded",
")",
"{",
"collapse",
".",
"call",
"(",
"this",
")",
";",
"expand",
".",
"call",
"(",
"this",
",",
"false",
")",
";",
"}",
"}"
] | Select next item.
@this ViewXJS
@returns {undefined} | [
"Select",
"next",
"item",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/mod/tfw.view.combo.js#L289-L295 |
50,968 | JohnnieFucker/dreamix-rpc | lib/rpc-client/mailstation.js | doFilter | function doFilter(tracer, err, serverId, msg, opts, filters, index, operate, cb) {
if (index < filters.length) {
tracer.info('client', __filename, 'doFilter', `do ${operate} filter ${filters[index].name}`);
}
if (index >= filters.length || !!err) {
utils.invokeCallback(cb, tracer, err, serverId, msg, opts);
return;
}
const filter = filters[index];
if (typeof filter === 'function') {
filter(serverId, msg, opts, (target, message, options) => {
index++;
// compatible for pomelo filter next(err) method
if (utils.getObjectClass(target) === 'Error') {
doFilter(tracer, target, serverId, msg, opts, filters, index, operate, cb);
} else {
doFilter(tracer, null, target || serverId, message || msg, options || opts, filters, index, operate, cb);
}
});
return;
}
if (typeof filter[operate] === 'function') {
filter[operate](serverId, msg, opts, (target, message, options) => {
index++;
if (utils.getObjectClass(target) === 'Error') {
doFilter(tracer, target, serverId, msg, opts, filters, index, operate, cb);
} else {
doFilter(tracer, null, target || serverId, message || msg, options || opts, filters, index, operate, cb);
}
});
return;
}
index++;
doFilter(tracer, err, serverId, msg, opts, filters, index, operate, cb);
} | javascript | function doFilter(tracer, err, serverId, msg, opts, filters, index, operate, cb) {
if (index < filters.length) {
tracer.info('client', __filename, 'doFilter', `do ${operate} filter ${filters[index].name}`);
}
if (index >= filters.length || !!err) {
utils.invokeCallback(cb, tracer, err, serverId, msg, opts);
return;
}
const filter = filters[index];
if (typeof filter === 'function') {
filter(serverId, msg, opts, (target, message, options) => {
index++;
// compatible for pomelo filter next(err) method
if (utils.getObjectClass(target) === 'Error') {
doFilter(tracer, target, serverId, msg, opts, filters, index, operate, cb);
} else {
doFilter(tracer, null, target || serverId, message || msg, options || opts, filters, index, operate, cb);
}
});
return;
}
if (typeof filter[operate] === 'function') {
filter[operate](serverId, msg, opts, (target, message, options) => {
index++;
if (utils.getObjectClass(target) === 'Error') {
doFilter(tracer, target, serverId, msg, opts, filters, index, operate, cb);
} else {
doFilter(tracer, null, target || serverId, message || msg, options || opts, filters, index, operate, cb);
}
});
return;
}
index++;
doFilter(tracer, err, serverId, msg, opts, filters, index, operate, cb);
} | [
"function",
"doFilter",
"(",
"tracer",
",",
"err",
",",
"serverId",
",",
"msg",
",",
"opts",
",",
"filters",
",",
"index",
",",
"operate",
",",
"cb",
")",
"{",
"if",
"(",
"index",
"<",
"filters",
".",
"length",
")",
"{",
"tracer",
".",
"info",
"(",
"'client'",
",",
"__filename",
",",
"'doFilter'",
",",
"`",
"${",
"operate",
"}",
"${",
"filters",
"[",
"index",
"]",
".",
"name",
"}",
"`",
")",
";",
"}",
"if",
"(",
"index",
">=",
"filters",
".",
"length",
"||",
"!",
"!",
"err",
")",
"{",
"utils",
".",
"invokeCallback",
"(",
"cb",
",",
"tracer",
",",
"err",
",",
"serverId",
",",
"msg",
",",
"opts",
")",
";",
"return",
";",
"}",
"const",
"filter",
"=",
"filters",
"[",
"index",
"]",
";",
"if",
"(",
"typeof",
"filter",
"===",
"'function'",
")",
"{",
"filter",
"(",
"serverId",
",",
"msg",
",",
"opts",
",",
"(",
"target",
",",
"message",
",",
"options",
")",
"=>",
"{",
"index",
"++",
";",
"// compatible for pomelo filter next(err) method",
"if",
"(",
"utils",
".",
"getObjectClass",
"(",
"target",
")",
"===",
"'Error'",
")",
"{",
"doFilter",
"(",
"tracer",
",",
"target",
",",
"serverId",
",",
"msg",
",",
"opts",
",",
"filters",
",",
"index",
",",
"operate",
",",
"cb",
")",
";",
"}",
"else",
"{",
"doFilter",
"(",
"tracer",
",",
"null",
",",
"target",
"||",
"serverId",
",",
"message",
"||",
"msg",
",",
"options",
"||",
"opts",
",",
"filters",
",",
"index",
",",
"operate",
",",
"cb",
")",
";",
"}",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"typeof",
"filter",
"[",
"operate",
"]",
"===",
"'function'",
")",
"{",
"filter",
"[",
"operate",
"]",
"(",
"serverId",
",",
"msg",
",",
"opts",
",",
"(",
"target",
",",
"message",
",",
"options",
")",
"=>",
"{",
"index",
"++",
";",
"if",
"(",
"utils",
".",
"getObjectClass",
"(",
"target",
")",
"===",
"'Error'",
")",
"{",
"doFilter",
"(",
"tracer",
",",
"target",
",",
"serverId",
",",
"msg",
",",
"opts",
",",
"filters",
",",
"index",
",",
"operate",
",",
"cb",
")",
";",
"}",
"else",
"{",
"doFilter",
"(",
"tracer",
",",
"null",
",",
"target",
"||",
"serverId",
",",
"message",
"||",
"msg",
",",
"options",
"||",
"opts",
",",
"filters",
",",
"index",
",",
"operate",
",",
"cb",
")",
";",
"}",
"}",
")",
";",
"return",
";",
"}",
"index",
"++",
";",
"doFilter",
"(",
"tracer",
",",
"err",
",",
"serverId",
",",
"msg",
",",
"opts",
",",
"filters",
",",
"index",
",",
"operate",
",",
"cb",
")",
";",
"}"
] | Do before or after filter | [
"Do",
"before",
"or",
"after",
"filter"
] | eb29e247214148c025456b2bb0542e1094fd2edb | https://github.com/JohnnieFucker/dreamix-rpc/blob/eb29e247214148c025456b2bb0542e1094fd2edb/lib/rpc-client/mailstation.js#L74-L108 |
50,969 | koop-retired/koop-server | lib/PostGIS.js | function(err, data){
if (err) error = err;
allLayers.push(data);
if (allLayers.length == totalLayers){
callback(error, allLayers);
}
} | javascript | function(err, data){
if (err) error = err;
allLayers.push(data);
if (allLayers.length == totalLayers){
callback(error, allLayers);
}
} | [
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"error",
"=",
"err",
";",
"allLayers",
".",
"push",
"(",
"data",
")",
";",
"if",
"(",
"allLayers",
".",
"length",
"==",
"totalLayers",
")",
"{",
"callback",
"(",
"error",
",",
"allLayers",
")",
";",
"}",
"}"
] | closure to check each layer and send back when done | [
"closure",
"to",
"check",
"each",
"layer",
"and",
"send",
"back",
"when",
"done"
] | 7b4404aa0db92023bfd59b475ad43aa36e02aee8 | https://github.com/koop-retired/koop-server/blob/7b4404aa0db92023bfd59b475ad43aa36e02aee8/lib/PostGIS.js#L196-L202 |
|
50,970 | fernandofranca/launchpod | lib/utils.js | readConfigFile | function readConfigFile(configJSONPath) {
var confiJSONFullPath = path.join(process.cwd(), configJSONPath);
try{
var configStr = fs.readFileSync(confiJSONFullPath, {encoding:'utf8'});
return JSON.parse(configStr);
} catch (err){
throw new Error(`Invalid launcher configuration file: ${confiJSONFullPath}
${err.toString()}`);
}
} | javascript | function readConfigFile(configJSONPath) {
var confiJSONFullPath = path.join(process.cwd(), configJSONPath);
try{
var configStr = fs.readFileSync(confiJSONFullPath, {encoding:'utf8'});
return JSON.parse(configStr);
} catch (err){
throw new Error(`Invalid launcher configuration file: ${confiJSONFullPath}
${err.toString()}`);
}
} | [
"function",
"readConfigFile",
"(",
"configJSONPath",
")",
"{",
"var",
"confiJSONFullPath",
"=",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"configJSONPath",
")",
";",
"try",
"{",
"var",
"configStr",
"=",
"fs",
".",
"readFileSync",
"(",
"confiJSONFullPath",
",",
"{",
"encoding",
":",
"'utf8'",
"}",
")",
";",
"return",
"JSON",
".",
"parse",
"(",
"configStr",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"confiJSONFullPath",
"}",
"${",
"err",
".",
"toString",
"(",
")",
"}",
"`",
")",
";",
"}",
"}"
] | When a simple require will reload the targeted file | [
"When",
"a",
"simple",
"require",
"will",
"reload",
"the",
"targeted",
"file"
] | 882d614a4271846e17b3ba0ca319340a607580bc | https://github.com/fernandofranca/launchpod/blob/882d614a4271846e17b3ba0ca319340a607580bc/lib/utils.js#L8-L18 |
50,971 | lui89/postcss-sass-colors | index.js | colorConvert | function colorConvert( percentage, option, colorValue ) {
var color = require( 'color' );
var newColor = color( colorValue.trim() );
var newValue = '';
switch ( option.trim() ) {
case 'darken':
newValue = newColor.darken( percentage ).hexString();
break;
case 'lighten':
newValue = newColor.lighten( percentage ).hexString();
break;
case 'rgb':
newValue = newColor.clearer( percentage ).rgbString();
break;
default:
return '';
}
return newValue;
} | javascript | function colorConvert( percentage, option, colorValue ) {
var color = require( 'color' );
var newColor = color( colorValue.trim() );
var newValue = '';
switch ( option.trim() ) {
case 'darken':
newValue = newColor.darken( percentage ).hexString();
break;
case 'lighten':
newValue = newColor.lighten( percentage ).hexString();
break;
case 'rgb':
newValue = newColor.clearer( percentage ).rgbString();
break;
default:
return '';
}
return newValue;
} | [
"function",
"colorConvert",
"(",
"percentage",
",",
"option",
",",
"colorValue",
")",
"{",
"var",
"color",
"=",
"require",
"(",
"'color'",
")",
";",
"var",
"newColor",
"=",
"color",
"(",
"colorValue",
".",
"trim",
"(",
")",
")",
";",
"var",
"newValue",
"=",
"''",
";",
"switch",
"(",
"option",
".",
"trim",
"(",
")",
")",
"{",
"case",
"'darken'",
":",
"newValue",
"=",
"newColor",
".",
"darken",
"(",
"percentage",
")",
".",
"hexString",
"(",
")",
";",
"break",
";",
"case",
"'lighten'",
":",
"newValue",
"=",
"newColor",
".",
"lighten",
"(",
"percentage",
")",
".",
"hexString",
"(",
")",
";",
"break",
";",
"case",
"'rgb'",
":",
"newValue",
"=",
"newColor",
".",
"clearer",
"(",
"percentage",
")",
".",
"rgbString",
"(",
")",
";",
"break",
";",
"default",
":",
"return",
"''",
";",
"}",
"return",
"newValue",
";",
"}"
] | Calls the Color.js library for the conversion | [
"Calls",
"the",
"Color",
".",
"js",
"library",
"for",
"the",
"conversion"
] | 0b116e65c15bfabe1b4766b9f6cc787c7c896421 | https://github.com/lui89/postcss-sass-colors/blob/0b116e65c15bfabe1b4766b9f6cc787c7c896421/index.js#L7-L30 |
50,972 | lui89/postcss-sass-colors | index.js | colorInit | function colorInit( oldValue ) {
var color, percentage, colorArgs, colorValue, cssString;
var balanced = require( 'balanced-match' );
//
cssString = balanced( '(', ')', oldValue );
colorArgs = balanced( '(', ')', cssString.body );
colorValue = balanced( '(', ')', colorArgs.body );
// If colorValue is undefined, the value is an rbg or similar color.
if ( undefined !== colorValue ) {
color = colorValue.pre + '( ' + colorValue.body + ' )';
percentage = colorValue.post;
} else {
// The value is an hexadecimal sting or html color
var hexColor = colorArgs.body.split( ',' );
color = hexColor[0].trim();
if ( undefined === hexColor[1] ) {
percentage = '';
} else {
percentage = hexColor[1].trim();
}
}
// Cleans the variable
if ( percentage ) {
percentage = percentage.replace( ',', '' ).trim();
percentage = percentage.replace( '%', '' ) / 100;
} else {
// Check if the percentage is undefine or empty and set it to 0
percentage = '0';
}
return colorConvert( percentage, colorArgs.pre, color );
} | javascript | function colorInit( oldValue ) {
var color, percentage, colorArgs, colorValue, cssString;
var balanced = require( 'balanced-match' );
//
cssString = balanced( '(', ')', oldValue );
colorArgs = balanced( '(', ')', cssString.body );
colorValue = balanced( '(', ')', colorArgs.body );
// If colorValue is undefined, the value is an rbg or similar color.
if ( undefined !== colorValue ) {
color = colorValue.pre + '( ' + colorValue.body + ' )';
percentage = colorValue.post;
} else {
// The value is an hexadecimal sting or html color
var hexColor = colorArgs.body.split( ',' );
color = hexColor[0].trim();
if ( undefined === hexColor[1] ) {
percentage = '';
} else {
percentage = hexColor[1].trim();
}
}
// Cleans the variable
if ( percentage ) {
percentage = percentage.replace( ',', '' ).trim();
percentage = percentage.replace( '%', '' ) / 100;
} else {
// Check if the percentage is undefine or empty and set it to 0
percentage = '0';
}
return colorConvert( percentage, colorArgs.pre, color );
} | [
"function",
"colorInit",
"(",
"oldValue",
")",
"{",
"var",
"color",
",",
"percentage",
",",
"colorArgs",
",",
"colorValue",
",",
"cssString",
";",
"var",
"balanced",
"=",
"require",
"(",
"'balanced-match'",
")",
";",
"//",
"cssString",
"=",
"balanced",
"(",
"'('",
",",
"')'",
",",
"oldValue",
")",
";",
"colorArgs",
"=",
"balanced",
"(",
"'('",
",",
"')'",
",",
"cssString",
".",
"body",
")",
";",
"colorValue",
"=",
"balanced",
"(",
"'('",
",",
"')'",
",",
"colorArgs",
".",
"body",
")",
";",
"// If colorValue is undefined, the value is an rbg or similar color.",
"if",
"(",
"undefined",
"!==",
"colorValue",
")",
"{",
"color",
"=",
"colorValue",
".",
"pre",
"+",
"'( '",
"+",
"colorValue",
".",
"body",
"+",
"' )'",
";",
"percentage",
"=",
"colorValue",
".",
"post",
";",
"}",
"else",
"{",
"// The value is an hexadecimal sting or html color",
"var",
"hexColor",
"=",
"colorArgs",
".",
"body",
".",
"split",
"(",
"','",
")",
";",
"color",
"=",
"hexColor",
"[",
"0",
"]",
".",
"trim",
"(",
")",
";",
"if",
"(",
"undefined",
"===",
"hexColor",
"[",
"1",
"]",
")",
"{",
"percentage",
"=",
"''",
";",
"}",
"else",
"{",
"percentage",
"=",
"hexColor",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"}",
"}",
"// Cleans the variable",
"if",
"(",
"percentage",
")",
"{",
"percentage",
"=",
"percentage",
".",
"replace",
"(",
"','",
",",
"''",
")",
".",
"trim",
"(",
")",
";",
"percentage",
"=",
"percentage",
".",
"replace",
"(",
"'%'",
",",
"''",
")",
"/",
"100",
";",
"}",
"else",
"{",
"// Check if the percentage is undefine or empty and set it to 0",
"percentage",
"=",
"'0'",
";",
"}",
"return",
"colorConvert",
"(",
"percentage",
",",
"colorArgs",
".",
"pre",
",",
"color",
")",
";",
"}"
] | Gets the type of conversion is needed for the current string | [
"Gets",
"the",
"type",
"of",
"conversion",
"is",
"needed",
"for",
"the",
"current",
"string"
] | 0b116e65c15bfabe1b4766b9f6cc787c7c896421 | https://github.com/lui89/postcss-sass-colors/blob/0b116e65c15bfabe1b4766b9f6cc787c7c896421/index.js#L33-L70 |
50,973 | Insorum/hubot-youtube-feed | src/lib/video-fetcher.js | function(username) {
var result = q.defer();
this.robot.http('https://gdata.youtube.com/feeds/api/users/' + username + '/uploads?alt=json')
.header('Accept', 'application/json')
.get()(function (err, res, body) {
if (err) {
result.reject(err);
return;
}
if(res.statusCode >= 400) {
result.reject(body);
return;
}
var parsed;
try {
parsed = JSON.parse(body);
} catch (e) {
result.reject(e);
}
if(!parsed.feed || !parsed.feed.entry) {
result.reject('invalid format of youtube data');
return;
}
var videos = parsed.feed.entry.map(function(element) {
return {
id: element.id.$t,
link: element.link[0].href
}
});
result.resolve(videos);
});
return result.promise;
} | javascript | function(username) {
var result = q.defer();
this.robot.http('https://gdata.youtube.com/feeds/api/users/' + username + '/uploads?alt=json')
.header('Accept', 'application/json')
.get()(function (err, res, body) {
if (err) {
result.reject(err);
return;
}
if(res.statusCode >= 400) {
result.reject(body);
return;
}
var parsed;
try {
parsed = JSON.parse(body);
} catch (e) {
result.reject(e);
}
if(!parsed.feed || !parsed.feed.entry) {
result.reject('invalid format of youtube data');
return;
}
var videos = parsed.feed.entry.map(function(element) {
return {
id: element.id.$t,
link: element.link[0].href
}
});
result.resolve(videos);
});
return result.promise;
} | [
"function",
"(",
"username",
")",
"{",
"var",
"result",
"=",
"q",
".",
"defer",
"(",
")",
";",
"this",
".",
"robot",
".",
"http",
"(",
"'https://gdata.youtube.com/feeds/api/users/'",
"+",
"username",
"+",
"'/uploads?alt=json'",
")",
".",
"header",
"(",
"'Accept'",
",",
"'application/json'",
")",
".",
"get",
"(",
")",
"(",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"result",
".",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"if",
"(",
"res",
".",
"statusCode",
">=",
"400",
")",
"{",
"result",
".",
"reject",
"(",
"body",
")",
";",
"return",
";",
"}",
"var",
"parsed",
";",
"try",
"{",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"result",
".",
"reject",
"(",
"e",
")",
";",
"}",
"if",
"(",
"!",
"parsed",
".",
"feed",
"||",
"!",
"parsed",
".",
"feed",
".",
"entry",
")",
"{",
"result",
".",
"reject",
"(",
"'invalid format of youtube data'",
")",
";",
"return",
";",
"}",
"var",
"videos",
"=",
"parsed",
".",
"feed",
".",
"entry",
".",
"map",
"(",
"function",
"(",
"element",
")",
"{",
"return",
"{",
"id",
":",
"element",
".",
"id",
".",
"$t",
",",
"link",
":",
"element",
".",
"link",
"[",
"0",
"]",
".",
"href",
"}",
"}",
")",
";",
"result",
".",
"resolve",
"(",
"videos",
")",
";",
"}",
")",
";",
"return",
"result",
".",
"promise",
";",
"}"
] | Fetches latest video list for the given user
@param {string} username - The account to check
@returns {promise} promise that resolves to {id: string, link: string}[], a list of id's and links for each video | [
"Fetches",
"latest",
"video",
"list",
"for",
"the",
"given",
"user"
] | 6f55979733fd75c3bb7b8ba0b15ed8da99f85d4b | https://github.com/Insorum/hubot-youtube-feed/blob/6f55979733fd75c3bb7b8ba0b15ed8da99f85d4b/src/lib/video-fetcher.js#L13-L50 |
|
50,974 | tyler-johnson/assign-props | index.js | assignProps | function assignProps(obj, key, val, opts) {
var k;
// accept object syntax
if (typeof key === "object") {
for (k in key) {
if (hasOwn.call(key, k)) assignProps(obj, k, key[k], val);
}
return;
}
var desc = {};
opts = opts || {};
// build base descriptor
for (k in defaults) {
desc[k] = typeof opts[k] === "boolean" ? opts[k] : defaults[k];
}
// set descriptor props based on value
if (!opts.forceStatic && typeof val === "function") {
desc.get = val;
} else {
desc.value = val;
desc.writable = false;
}
// define the property
Object.defineProperty(obj, key, desc);
} | javascript | function assignProps(obj, key, val, opts) {
var k;
// accept object syntax
if (typeof key === "object") {
for (k in key) {
if (hasOwn.call(key, k)) assignProps(obj, k, key[k], val);
}
return;
}
var desc = {};
opts = opts || {};
// build base descriptor
for (k in defaults) {
desc[k] = typeof opts[k] === "boolean" ? opts[k] : defaults[k];
}
// set descriptor props based on value
if (!opts.forceStatic && typeof val === "function") {
desc.get = val;
} else {
desc.value = val;
desc.writable = false;
}
// define the property
Object.defineProperty(obj, key, desc);
} | [
"function",
"assignProps",
"(",
"obj",
",",
"key",
",",
"val",
",",
"opts",
")",
"{",
"var",
"k",
";",
"// accept object syntax",
"if",
"(",
"typeof",
"key",
"===",
"\"object\"",
")",
"{",
"for",
"(",
"k",
"in",
"key",
")",
"{",
"if",
"(",
"hasOwn",
".",
"call",
"(",
"key",
",",
"k",
")",
")",
"assignProps",
"(",
"obj",
",",
"k",
",",
"key",
"[",
"k",
"]",
",",
"val",
")",
";",
"}",
"return",
";",
"}",
"var",
"desc",
"=",
"{",
"}",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"// build base descriptor",
"for",
"(",
"k",
"in",
"defaults",
")",
"{",
"desc",
"[",
"k",
"]",
"=",
"typeof",
"opts",
"[",
"k",
"]",
"===",
"\"boolean\"",
"?",
"opts",
"[",
"k",
"]",
":",
"defaults",
"[",
"k",
"]",
";",
"}",
"// set descriptor props based on value",
"if",
"(",
"!",
"opts",
".",
"forceStatic",
"&&",
"typeof",
"val",
"===",
"\"function\"",
")",
"{",
"desc",
".",
"get",
"=",
"val",
";",
"}",
"else",
"{",
"desc",
".",
"value",
"=",
"val",
";",
"desc",
".",
"writable",
"=",
"false",
";",
"}",
"// define the property",
"Object",
".",
"defineProperty",
"(",
"obj",
",",
"key",
",",
"desc",
")",
";",
"}"
] | defines protected, immutable properties | [
"defines",
"protected",
"immutable",
"properties"
] | b88543c5e1a850f8a5400f554935d1eddd8f891e | https://github.com/tyler-johnson/assign-props/blob/b88543c5e1a850f8a5400f554935d1eddd8f891e/index.js#L9-L38 |
50,975 | fiveisprime/iron-cache | lib/ironcache.js | handleResponse | function handleResponse(done, err, response, body) {
if (err) return done(err, null);
if (response.statusCode !== 200) return done(new Error(body.msg || 'Unknown error'), null);
done(null, body);
} | javascript | function handleResponse(done, err, response, body) {
if (err) return done(err, null);
if (response.statusCode !== 200) return done(new Error(body.msg || 'Unknown error'), null);
done(null, body);
} | [
"function",
"handleResponse",
"(",
"done",
",",
"err",
",",
"response",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
",",
"null",
")",
";",
"if",
"(",
"response",
".",
"statusCode",
"!==",
"200",
")",
"return",
"done",
"(",
"new",
"Error",
"(",
"body",
".",
"msg",
"||",
"'Unknown error'",
")",
",",
"null",
")",
";",
"done",
"(",
"null",
",",
"body",
")",
";",
"}"
] | Generic handler for API responses. Includes default error handling. | [
"Generic",
"handler",
"for",
"API",
"responses",
".",
"Includes",
"default",
"error",
"handling",
"."
] | 2ce8b12e52d14ee908787552cf32f5f8d3109e24 | https://github.com/fiveisprime/iron-cache/blob/2ce8b12e52d14ee908787552cf32f5f8d3109e24/lib/ironcache.js#L12-L17 |
50,976 | hbouvier/node-diagnostics | lib/diagnostics.js | setLevel | function setLevel(level) {
if (typeof(level) === "number") {
if (level >= 0 && level <= 5) {
_level = level;
} else {
invalidParameter(level);
}
} else if (typeof(level) === 'string') {
if (Level.hasOwnProperty(level)) {
_level = Level[level];
} else {
invalidParameter(level);
}
} else {
invalidParameter(level);
}
return createObject();
} | javascript | function setLevel(level) {
if (typeof(level) === "number") {
if (level >= 0 && level <= 5) {
_level = level;
} else {
invalidParameter(level);
}
} else if (typeof(level) === 'string') {
if (Level.hasOwnProperty(level)) {
_level = Level[level];
} else {
invalidParameter(level);
}
} else {
invalidParameter(level);
}
return createObject();
} | [
"function",
"setLevel",
"(",
"level",
")",
"{",
"if",
"(",
"typeof",
"(",
"level",
")",
"===",
"\"number\"",
")",
"{",
"if",
"(",
"level",
">=",
"0",
"&&",
"level",
"<=",
"5",
")",
"{",
"_level",
"=",
"level",
";",
"}",
"else",
"{",
"invalidParameter",
"(",
"level",
")",
";",
"}",
"}",
"else",
"if",
"(",
"typeof",
"(",
"level",
")",
"===",
"'string'",
")",
"{",
"if",
"(",
"Level",
".",
"hasOwnProperty",
"(",
"level",
")",
")",
"{",
"_level",
"=",
"Level",
"[",
"level",
"]",
";",
"}",
"else",
"{",
"invalidParameter",
"(",
"level",
")",
";",
"}",
"}",
"else",
"{",
"invalidParameter",
"(",
"level",
")",
";",
"}",
"return",
"createObject",
"(",
")",
";",
"}"
] | set the logging level
@param: level The verbosity of the logger. | [
"set",
"the",
"logging",
"level"
] | 0e03567662960b9ae710cc2effb2214aa90c0b1d | https://github.com/hbouvier/node-diagnostics/blob/0e03567662960b9ae710cc2effb2214aa90c0b1d/lib/diagnostics.js#L28-L45 |
50,977 | jmendiara/gitftw | src/resolvable.js | resolveArray | function resolveArray(arg) {
var resolvedArray = new Array(arg.length);
return arg
.reduce(function(soFar, value, index) {
return soFar
.then(resolveItem.bind(null, value))
.then(function(value) {
resolvedArray[index] = value;
});
}, Promise.resolve())
.then(function() {
return resolvedArray;
});
} | javascript | function resolveArray(arg) {
var resolvedArray = new Array(arg.length);
return arg
.reduce(function(soFar, value, index) {
return soFar
.then(resolveItem.bind(null, value))
.then(function(value) {
resolvedArray[index] = value;
});
}, Promise.resolve())
.then(function() {
return resolvedArray;
});
} | [
"function",
"resolveArray",
"(",
"arg",
")",
"{",
"var",
"resolvedArray",
"=",
"new",
"Array",
"(",
"arg",
".",
"length",
")",
";",
"return",
"arg",
".",
"reduce",
"(",
"function",
"(",
"soFar",
",",
"value",
",",
"index",
")",
"{",
"return",
"soFar",
".",
"then",
"(",
"resolveItem",
".",
"bind",
"(",
"null",
",",
"value",
")",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"resolvedArray",
"[",
"index",
"]",
"=",
"value",
";",
"}",
")",
";",
"}",
",",
"Promise",
".",
"resolve",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"resolvedArray",
";",
"}",
")",
";",
"}"
] | Resolves an array
@private
@param {Array} arg The array to resolve
@returns {Promise} The resolved array | [
"Resolves",
"an",
"array"
] | ba91b0d68b7791b5b557addc685737f6c912b4f3 | https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/resolvable.js#L71-L84 |
50,978 | jmendiara/gitftw | src/resolvable.js | resolveObject | function resolveObject(arg) {
var resolvedObject = {};
return Object.keys(arg)
.reduce(function(soFar, key) {
return soFar
.then(resolveItem.bind(null, arg[key]))
.then(function(value) {
resolvedObject[key] = value;
});
}, Promise.resolve())
.then(function() {
return resolvedObject;
});
} | javascript | function resolveObject(arg) {
var resolvedObject = {};
return Object.keys(arg)
.reduce(function(soFar, key) {
return soFar
.then(resolveItem.bind(null, arg[key]))
.then(function(value) {
resolvedObject[key] = value;
});
}, Promise.resolve())
.then(function() {
return resolvedObject;
});
} | [
"function",
"resolveObject",
"(",
"arg",
")",
"{",
"var",
"resolvedObject",
"=",
"{",
"}",
";",
"return",
"Object",
".",
"keys",
"(",
"arg",
")",
".",
"reduce",
"(",
"function",
"(",
"soFar",
",",
"key",
")",
"{",
"return",
"soFar",
".",
"then",
"(",
"resolveItem",
".",
"bind",
"(",
"null",
",",
"arg",
"[",
"key",
"]",
")",
")",
".",
"then",
"(",
"function",
"(",
"value",
")",
"{",
"resolvedObject",
"[",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"}",
",",
"Promise",
".",
"resolve",
"(",
")",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"resolvedObject",
";",
"}",
")",
";",
"}"
] | Resolves an object
@private
@param {Object} arg The object to resolve
@returns {Promise} The resolved object | [
"Resolves",
"an",
"object"
] | ba91b0d68b7791b5b557addc685737f6c912b4f3 | https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/resolvable.js#L93-L106 |
50,979 | jmendiara/gitftw | src/resolvable.js | resolveItem | function resolveItem(arg) {
if (Array.isArray(arg)) {
return resolveArray(arg);
} else if (Object.prototype.toString.call(arg) === '[object Function]') {
//is a function
return Promise.method(arg)().then(resolveItem);
} else if (isThenable(arg)) {
//is a promise
return arg.then(resolveItem);
} else if (arg && typeof arg === 'object') {
//is an object
if (typeof arg.toString === 'function') {
var value = arg.toString();
if (value !== '[object Object]') {
//with a valid toString
return Promise.resolve(value);
}
}
return resolveObject(arg);
} else {
//Yeah! a value
return Promise.resolve(arg);
}
} | javascript | function resolveItem(arg) {
if (Array.isArray(arg)) {
return resolveArray(arg);
} else if (Object.prototype.toString.call(arg) === '[object Function]') {
//is a function
return Promise.method(arg)().then(resolveItem);
} else if (isThenable(arg)) {
//is a promise
return arg.then(resolveItem);
} else if (arg && typeof arg === 'object') {
//is an object
if (typeof arg.toString === 'function') {
var value = arg.toString();
if (value !== '[object Object]') {
//with a valid toString
return Promise.resolve(value);
}
}
return resolveObject(arg);
} else {
//Yeah! a value
return Promise.resolve(arg);
}
} | [
"function",
"resolveItem",
"(",
"arg",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"arg",
")",
")",
"{",
"return",
"resolveArray",
"(",
"arg",
")",
";",
"}",
"else",
"if",
"(",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"arg",
")",
"===",
"'[object Function]'",
")",
"{",
"//is a function",
"return",
"Promise",
".",
"method",
"(",
"arg",
")",
"(",
")",
".",
"then",
"(",
"resolveItem",
")",
";",
"}",
"else",
"if",
"(",
"isThenable",
"(",
"arg",
")",
")",
"{",
"//is a promise",
"return",
"arg",
".",
"then",
"(",
"resolveItem",
")",
";",
"}",
"else",
"if",
"(",
"arg",
"&&",
"typeof",
"arg",
"===",
"'object'",
")",
"{",
"//is an object",
"if",
"(",
"typeof",
"arg",
".",
"toString",
"===",
"'function'",
")",
"{",
"var",
"value",
"=",
"arg",
".",
"toString",
"(",
")",
";",
"if",
"(",
"value",
"!==",
"'[object Object]'",
")",
"{",
"//with a valid toString",
"return",
"Promise",
".",
"resolve",
"(",
"value",
")",
";",
"}",
"}",
"return",
"resolveObject",
"(",
"arg",
")",
";",
"}",
"else",
"{",
"//Yeah! a value",
"return",
"Promise",
".",
"resolve",
"(",
"arg",
")",
";",
"}",
"}"
] | Resolves something resolvable
@private
@param {*} arg The argument to resolve
@returns {Promise} The resolved | [
"Resolves",
"something",
"resolvable"
] | ba91b0d68b7791b5b557addc685737f6c912b4f3 | https://github.com/jmendiara/gitftw/blob/ba91b0d68b7791b5b557addc685737f6c912b4f3/src/resolvable.js#L115-L138 |
50,980 | doctape/doctape-client-js | src/core.js | function (path, data, cb) {
var lines = [];
var field;
for (field in data) {
lines.push(field + '=' + encodeURIComponent(data[field]));
}
this.env.req({
method: 'POST',
protocol: this.options.authPt.protocol,
host: this.options.authPt.host,
port: this.options.authPt.port,
path: this.options.authPt.base + path,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
postData: lines.join('&')
}, cb);
} | javascript | function (path, data, cb) {
var lines = [];
var field;
for (field in data) {
lines.push(field + '=' + encodeURIComponent(data[field]));
}
this.env.req({
method: 'POST',
protocol: this.options.authPt.protocol,
host: this.options.authPt.host,
port: this.options.authPt.port,
path: this.options.authPt.base + path,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
postData: lines.join('&')
}, cb);
} | [
"function",
"(",
"path",
",",
"data",
",",
"cb",
")",
"{",
"var",
"lines",
"=",
"[",
"]",
";",
"var",
"field",
";",
"for",
"(",
"field",
"in",
"data",
")",
"{",
"lines",
".",
"push",
"(",
"field",
"+",
"'='",
"+",
"encodeURIComponent",
"(",
"data",
"[",
"field",
"]",
")",
")",
";",
"}",
"this",
".",
"env",
".",
"req",
"(",
"{",
"method",
":",
"'POST'",
",",
"protocol",
":",
"this",
".",
"options",
".",
"authPt",
".",
"protocol",
",",
"host",
":",
"this",
".",
"options",
".",
"authPt",
".",
"host",
",",
"port",
":",
"this",
".",
"options",
".",
"authPt",
".",
"port",
",",
"path",
":",
"this",
".",
"options",
".",
"authPt",
".",
"base",
"+",
"path",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
"}",
",",
"postData",
":",
"lines",
".",
"join",
"(",
"'&'",
")",
"}",
",",
"cb",
")",
";",
"}"
] | Not for direct use.
Perform a standard POST-request to the auth point with raw form post data.
@param {string} path
@param {Object} data
@param {function (Object, Object=)} cb | [
"Not",
"for",
"direct",
"use",
".",
"Perform",
"a",
"standard",
"POST",
"-",
"request",
"to",
"the",
"auth",
"point",
"with",
"raw",
"form",
"post",
"data",
"."
] | 3052007a55a45e0b654d572f68473250daab83bb | https://github.com/doctape/doctape-client-js/blob/3052007a55a45e0b654d572f68473250daab83bb/src/core.js#L120-L135 |
|
50,981 | doctape/doctape-client-js | src/core.js | function (error_msg) {
var self = this;
return function (err, resp) {
self._lock_refresh = undefined;
if (!err) {
var auth = JSON.parse(resp);
if (!auth.error) {
setToken.call(self, auth);
return emit.call(self, 'auth.refresh', token.call(self));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(auth.error));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(err));
};
} | javascript | function (error_msg) {
var self = this;
return function (err, resp) {
self._lock_refresh = undefined;
if (!err) {
var auth = JSON.parse(resp);
if (!auth.error) {
setToken.call(self, auth);
return emit.call(self, 'auth.refresh', token.call(self));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(auth.error));
}
return emit.call(self, 'auth.fail', error_msg + ': ' + JSON.stringify(err));
};
} | [
"function",
"(",
"error_msg",
")",
"{",
"var",
"self",
"=",
"this",
";",
"return",
"function",
"(",
"err",
",",
"resp",
")",
"{",
"self",
".",
"_lock_refresh",
"=",
"undefined",
";",
"if",
"(",
"!",
"err",
")",
"{",
"var",
"auth",
"=",
"JSON",
".",
"parse",
"(",
"resp",
")",
";",
"if",
"(",
"!",
"auth",
".",
"error",
")",
"{",
"setToken",
".",
"call",
"(",
"self",
",",
"auth",
")",
";",
"return",
"emit",
".",
"call",
"(",
"self",
",",
"'auth.refresh'",
",",
"token",
".",
"call",
"(",
"self",
")",
")",
";",
"}",
"return",
"emit",
".",
"call",
"(",
"self",
",",
"'auth.fail'",
",",
"error_msg",
"+",
"': '",
"+",
"JSON",
".",
"stringify",
"(",
"auth",
".",
"error",
")",
")",
";",
"}",
"return",
"emit",
".",
"call",
"(",
"self",
",",
"'auth.fail'",
",",
"error_msg",
"+",
"': '",
"+",
"JSON",
".",
"stringify",
"(",
"err",
")",
")",
";",
"}",
";",
"}"
] | Private helper function for registering a new token.
@param {string} error_msg | [
"Private",
"helper",
"function",
"for",
"registering",
"a",
"new",
"token",
"."
] | 3052007a55a45e0b654d572f68473250daab83bb | https://github.com/doctape/doctape-client-js/blob/3052007a55a45e0b654d572f68473250daab83bb/src/core.js#L240-L254 |
|
50,982 | sendanor/nor-nopg | src/nopg.js | _get_ms | function _get_ms(a, b) {
debug.assert(a).is('date');
debug.assert(b).is('date');
if(a < b) {
return b.getTime() - a.getTime();
}
return a.getTime() - b.getTime();
} | javascript | function _get_ms(a, b) {
debug.assert(a).is('date');
debug.assert(b).is('date');
if(a < b) {
return b.getTime() - a.getTime();
}
return a.getTime() - b.getTime();
} | [
"function",
"_get_ms",
"(",
"a",
",",
"b",
")",
"{",
"debug",
".",
"assert",
"(",
"a",
")",
".",
"is",
"(",
"'date'",
")",
";",
"debug",
".",
"assert",
"(",
"b",
")",
".",
"is",
"(",
"'date'",
")",
";",
"if",
"(",
"a",
"<",
"b",
")",
"{",
"return",
"b",
".",
"getTime",
"(",
")",
"-",
"a",
".",
"getTime",
"(",
")",
";",
"}",
"return",
"a",
".",
"getTime",
"(",
")",
"-",
"b",
".",
"getTime",
"(",
")",
";",
"}"
] | Returns seconds between two date values
@returns {number} Time between two values (ms) | [
"Returns",
"seconds",
"between",
"two",
"date",
"values"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L80-L87 |
50,983 | sendanor/nor-nopg | src/nopg.js | _log_time | function _log_time(sample) {
debug.assert(sample).is('object');
debug.assert(sample.event).is('string');
debug.assert(sample.start).is('date');
debug.assert(sample.end).is('date');
debug.assert(sample.duration).ignore(undefined).is('number');
debug.assert(sample.query).ignore(undefined).is('string');
debug.assert(sample.params).ignore(undefined).is('array');
var msg = 'NoPg event ' + sample.event + ' in ' + sample.duration + ' ms';
if(sample.query || sample.params) {
msg += ': ';
}
if(sample.query) {
msg += 'query=' + util.inspect(sample.query);
if(sample.params) {
msg += ', ';
}
}
if(sample.params) {
msg += 'params=' + util.inspect(sample.params);
}
debug.log(msg);
} | javascript | function _log_time(sample) {
debug.assert(sample).is('object');
debug.assert(sample.event).is('string');
debug.assert(sample.start).is('date');
debug.assert(sample.end).is('date');
debug.assert(sample.duration).ignore(undefined).is('number');
debug.assert(sample.query).ignore(undefined).is('string');
debug.assert(sample.params).ignore(undefined).is('array');
var msg = 'NoPg event ' + sample.event + ' in ' + sample.duration + ' ms';
if(sample.query || sample.params) {
msg += ': ';
}
if(sample.query) {
msg += 'query=' + util.inspect(sample.query);
if(sample.params) {
msg += ', ';
}
}
if(sample.params) {
msg += 'params=' + util.inspect(sample.params);
}
debug.log(msg);
} | [
"function",
"_log_time",
"(",
"sample",
")",
"{",
"debug",
".",
"assert",
"(",
"sample",
")",
".",
"is",
"(",
"'object'",
")",
";",
"debug",
".",
"assert",
"(",
"sample",
".",
"event",
")",
".",
"is",
"(",
"'string'",
")",
";",
"debug",
".",
"assert",
"(",
"sample",
".",
"start",
")",
".",
"is",
"(",
"'date'",
")",
";",
"debug",
".",
"assert",
"(",
"sample",
".",
"end",
")",
".",
"is",
"(",
"'date'",
")",
";",
"debug",
".",
"assert",
"(",
"sample",
".",
"duration",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'number'",
")",
";",
"debug",
".",
"assert",
"(",
"sample",
".",
"query",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'string'",
")",
";",
"debug",
".",
"assert",
"(",
"sample",
".",
"params",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'array'",
")",
";",
"var",
"msg",
"=",
"'NoPg event '",
"+",
"sample",
".",
"event",
"+",
"' in '",
"+",
"sample",
".",
"duration",
"+",
"' ms'",
";",
"if",
"(",
"sample",
".",
"query",
"||",
"sample",
".",
"params",
")",
"{",
"msg",
"+=",
"': '",
";",
"}",
"if",
"(",
"sample",
".",
"query",
")",
"{",
"msg",
"+=",
"'query='",
"+",
"util",
".",
"inspect",
"(",
"sample",
".",
"query",
")",
";",
"if",
"(",
"sample",
".",
"params",
")",
"{",
"msg",
"+=",
"', '",
";",
"}",
"}",
"if",
"(",
"sample",
".",
"params",
")",
"{",
"msg",
"+=",
"'params='",
"+",
"util",
".",
"inspect",
"(",
"sample",
".",
"params",
")",
";",
"}",
"debug",
".",
"log",
"(",
"msg",
")",
";",
"}"
] | Optionally log time | [
"Optionally",
"log",
"time"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L90-L115 |
50,984 | sendanor/nor-nopg | src/nopg.js | _get_result | function _get_result(Type) {
return function(rows) {
if(!rows) { throw new TypeError("failed to parse result"); }
var doc = rows.shift();
if(!doc) { return; }
if(doc instanceof Type) {
return doc;
}
var obj = {};
ARRAY(Object.keys(doc)).forEach(function(key) {
if(key === 'documents') {
obj['$'+key] = {};
ARRAY(Object.keys(doc[key])).forEach(function(k) {
if(is.uuid(k)) {
obj['$'+key][k] = _get_result(NoPg.Document)([doc[key][k]]);
} else {
obj['$'+key][k] = doc[key][k];
}
});
return;
}
obj['$'+key] = doc[key];
});
_parse_object_expressions(obj);
return new Type(obj);
};
} | javascript | function _get_result(Type) {
return function(rows) {
if(!rows) { throw new TypeError("failed to parse result"); }
var doc = rows.shift();
if(!doc) { return; }
if(doc instanceof Type) {
return doc;
}
var obj = {};
ARRAY(Object.keys(doc)).forEach(function(key) {
if(key === 'documents') {
obj['$'+key] = {};
ARRAY(Object.keys(doc[key])).forEach(function(k) {
if(is.uuid(k)) {
obj['$'+key][k] = _get_result(NoPg.Document)([doc[key][k]]);
} else {
obj['$'+key][k] = doc[key][k];
}
});
return;
}
obj['$'+key] = doc[key];
});
_parse_object_expressions(obj);
return new Type(obj);
};
} | [
"function",
"_get_result",
"(",
"Type",
")",
"{",
"return",
"function",
"(",
"rows",
")",
"{",
"if",
"(",
"!",
"rows",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"failed to parse result\"",
")",
";",
"}",
"var",
"doc",
"=",
"rows",
".",
"shift",
"(",
")",
";",
"if",
"(",
"!",
"doc",
")",
"{",
"return",
";",
"}",
"if",
"(",
"doc",
"instanceof",
"Type",
")",
"{",
"return",
"doc",
";",
"}",
"var",
"obj",
"=",
"{",
"}",
";",
"ARRAY",
"(",
"Object",
".",
"keys",
"(",
"doc",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"key",
"===",
"'documents'",
")",
"{",
"obj",
"[",
"'$'",
"+",
"key",
"]",
"=",
"{",
"}",
";",
"ARRAY",
"(",
"Object",
".",
"keys",
"(",
"doc",
"[",
"key",
"]",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"k",
")",
"{",
"if",
"(",
"is",
".",
"uuid",
"(",
"k",
")",
")",
"{",
"obj",
"[",
"'$'",
"+",
"key",
"]",
"[",
"k",
"]",
"=",
"_get_result",
"(",
"NoPg",
".",
"Document",
")",
"(",
"[",
"doc",
"[",
"key",
"]",
"[",
"k",
"]",
"]",
")",
";",
"}",
"else",
"{",
"obj",
"[",
"'$'",
"+",
"key",
"]",
"[",
"k",
"]",
"=",
"doc",
"[",
"key",
"]",
"[",
"k",
"]",
";",
"}",
"}",
")",
";",
"return",
";",
"}",
"obj",
"[",
"'$'",
"+",
"key",
"]",
"=",
"doc",
"[",
"key",
"]",
";",
"}",
")",
";",
"_parse_object_expressions",
"(",
"obj",
")",
";",
"return",
"new",
"Type",
"(",
"obj",
")",
";",
"}",
";",
"}"
] | Take first result from the database query and returns new instance of `Type` | [
"Take",
"first",
"result",
"from",
"the",
"database",
"query",
"and",
"returns",
"new",
"instance",
"of",
"Type"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L195-L227 |
50,985 | sendanor/nor-nopg | src/nopg.js | parse_predicate_pgtype | function parse_predicate_pgtype(ObjType, document_type, key) {
debug.assert(ObjType).is('function');
debug.assert(document_type).ignore(undefined).is('object');
var schema = (document_type && document_type.$schema) || {};
debug.assert(schema).is('object');
if(key[0] === '$') {
// FIXME: Change this to do direct for everything else but JSON types!
if(key === '$version') { return 'direct'; }
if(key === '$created') { return 'direct'; }
if(key === '$modified') { return 'direct'; }
if(key === '$name') { return 'direct'; }
if(key === '$type') { return 'direct'; }
if(key === '$validator') { return 'direct'; }
if(key === '$id') { return 'direct'; }
if(key === '$types_id') { return 'direct'; }
if(key === '$documents_id') { return 'direct'; }
} else {
var type;
if(schema && schema.properties && schema.properties.hasOwnProperty(key) && schema.properties[key].type) {
type = schema.properties[key].type;
}
if(type === 'number') {
return 'numeric';
}
if(type === 'boolean') {
return 'boolean';
}
}
return 'text';
} | javascript | function parse_predicate_pgtype(ObjType, document_type, key) {
debug.assert(ObjType).is('function');
debug.assert(document_type).ignore(undefined).is('object');
var schema = (document_type && document_type.$schema) || {};
debug.assert(schema).is('object');
if(key[0] === '$') {
// FIXME: Change this to do direct for everything else but JSON types!
if(key === '$version') { return 'direct'; }
if(key === '$created') { return 'direct'; }
if(key === '$modified') { return 'direct'; }
if(key === '$name') { return 'direct'; }
if(key === '$type') { return 'direct'; }
if(key === '$validator') { return 'direct'; }
if(key === '$id') { return 'direct'; }
if(key === '$types_id') { return 'direct'; }
if(key === '$documents_id') { return 'direct'; }
} else {
var type;
if(schema && schema.properties && schema.properties.hasOwnProperty(key) && schema.properties[key].type) {
type = schema.properties[key].type;
}
if(type === 'number') {
return 'numeric';
}
if(type === 'boolean') {
return 'boolean';
}
}
return 'text';
} | [
"function",
"parse_predicate_pgtype",
"(",
"ObjType",
",",
"document_type",
",",
"key",
")",
"{",
"debug",
".",
"assert",
"(",
"ObjType",
")",
".",
"is",
"(",
"'function'",
")",
";",
"debug",
".",
"assert",
"(",
"document_type",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'object'",
")",
";",
"var",
"schema",
"=",
"(",
"document_type",
"&&",
"document_type",
".",
"$schema",
")",
"||",
"{",
"}",
";",
"debug",
".",
"assert",
"(",
"schema",
")",
".",
"is",
"(",
"'object'",
")",
";",
"if",
"(",
"key",
"[",
"0",
"]",
"===",
"'$'",
")",
"{",
"// FIXME: Change this to do direct for everything else but JSON types!",
"if",
"(",
"key",
"===",
"'$version'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$created'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$modified'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$name'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$type'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$validator'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$id'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$types_id'",
")",
"{",
"return",
"'direct'",
";",
"}",
"if",
"(",
"key",
"===",
"'$documents_id'",
")",
"{",
"return",
"'direct'",
";",
"}",
"}",
"else",
"{",
"var",
"type",
";",
"if",
"(",
"schema",
"&&",
"schema",
".",
"properties",
"&&",
"schema",
".",
"properties",
".",
"hasOwnProperty",
"(",
"key",
")",
"&&",
"schema",
".",
"properties",
"[",
"key",
"]",
".",
"type",
")",
"{",
"type",
"=",
"schema",
".",
"properties",
"[",
"key",
"]",
".",
"type",
";",
"}",
"if",
"(",
"type",
"===",
"'number'",
")",
"{",
"return",
"'numeric'",
";",
"}",
"if",
"(",
"type",
"===",
"'boolean'",
")",
"{",
"return",
"'boolean'",
";",
"}",
"}",
"return",
"'text'",
";",
"}"
] | Returns PostgreSQL type for key based on the schema
@FIXME Detect correct types for all keys | [
"Returns",
"PostgreSQL",
"type",
"for",
"key",
"based",
"on",
"the",
"schema"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L710-L750 |
50,986 | sendanor/nor-nopg | src/nopg.js | _parse_function_predicate | function _parse_function_predicate(ObjType, q, def_op, o, ret_type, traits) {
debug.assert(o).is('array');
ret_type = ret_type || 'boolean';
var func = ARRAY(o).find(is.func);
debug.assert(func).is('function');
var i = o.indexOf(func);
debug.assert(i).is('number');
var input_nopg_keys = o.slice(0, i);
var js_input_params = o.slice(i+1);
debug.assert(input_nopg_keys).is('array');
debug.assert(js_input_params).is('array');
//debug.log('input_nopg_keys = ', input_nopg_keys);
//debug.log('func = ', func);
//debug.log('js_input_params = ', js_input_params);
var _parse_predicate_key_epoch = FUNCTION(_parse_predicate_key).curry(ObjType, {'traits': traits, 'epoch':true});
var input_pg_keys = ARRAY(input_nopg_keys).map(_parse_predicate_key_epoch);
var pg_items = input_pg_keys.map(function(i) { return i.getString(); }).valueOf();
var pg_params = input_pg_keys.map(function(i) { return i.getParams(); }).reduce(function(a, b) { return a.concat(b); });
debug.assert(pg_items).is('array');
debug.assert(pg_params).is('array');
//debug.log('input_pg_keys = ', input_pg_keys);
//var n = arg_params.length;
//arg_params.push(JSON.stringify(FUNCTION(func).stringify()));
//arg_params.push(JSON.stringify(js_input_params));
var call_func = 'nopg.call_func(array_to_json(ARRAY['+pg_items.join(', ')+"]), $::json, $::json)";
var type_cast = parse_predicate_pgcast_by_type(ret_type);
return new Predicate(type_cast(call_func), pg_params.concat( [JSON.stringify(FUNCTION(func).stringify()), JSON.stringify(js_input_params)] ));
} | javascript | function _parse_function_predicate(ObjType, q, def_op, o, ret_type, traits) {
debug.assert(o).is('array');
ret_type = ret_type || 'boolean';
var func = ARRAY(o).find(is.func);
debug.assert(func).is('function');
var i = o.indexOf(func);
debug.assert(i).is('number');
var input_nopg_keys = o.slice(0, i);
var js_input_params = o.slice(i+1);
debug.assert(input_nopg_keys).is('array');
debug.assert(js_input_params).is('array');
//debug.log('input_nopg_keys = ', input_nopg_keys);
//debug.log('func = ', func);
//debug.log('js_input_params = ', js_input_params);
var _parse_predicate_key_epoch = FUNCTION(_parse_predicate_key).curry(ObjType, {'traits': traits, 'epoch':true});
var input_pg_keys = ARRAY(input_nopg_keys).map(_parse_predicate_key_epoch);
var pg_items = input_pg_keys.map(function(i) { return i.getString(); }).valueOf();
var pg_params = input_pg_keys.map(function(i) { return i.getParams(); }).reduce(function(a, b) { return a.concat(b); });
debug.assert(pg_items).is('array');
debug.assert(pg_params).is('array');
//debug.log('input_pg_keys = ', input_pg_keys);
//var n = arg_params.length;
//arg_params.push(JSON.stringify(FUNCTION(func).stringify()));
//arg_params.push(JSON.stringify(js_input_params));
var call_func = 'nopg.call_func(array_to_json(ARRAY['+pg_items.join(', ')+"]), $::json, $::json)";
var type_cast = parse_predicate_pgcast_by_type(ret_type);
return new Predicate(type_cast(call_func), pg_params.concat( [JSON.stringify(FUNCTION(func).stringify()), JSON.stringify(js_input_params)] ));
} | [
"function",
"_parse_function_predicate",
"(",
"ObjType",
",",
"q",
",",
"def_op",
",",
"o",
",",
"ret_type",
",",
"traits",
")",
"{",
"debug",
".",
"assert",
"(",
"o",
")",
".",
"is",
"(",
"'array'",
")",
";",
"ret_type",
"=",
"ret_type",
"||",
"'boolean'",
";",
"var",
"func",
"=",
"ARRAY",
"(",
"o",
")",
".",
"find",
"(",
"is",
".",
"func",
")",
";",
"debug",
".",
"assert",
"(",
"func",
")",
".",
"is",
"(",
"'function'",
")",
";",
"var",
"i",
"=",
"o",
".",
"indexOf",
"(",
"func",
")",
";",
"debug",
".",
"assert",
"(",
"i",
")",
".",
"is",
"(",
"'number'",
")",
";",
"var",
"input_nopg_keys",
"=",
"o",
".",
"slice",
"(",
"0",
",",
"i",
")",
";",
"var",
"js_input_params",
"=",
"o",
".",
"slice",
"(",
"i",
"+",
"1",
")",
";",
"debug",
".",
"assert",
"(",
"input_nopg_keys",
")",
".",
"is",
"(",
"'array'",
")",
";",
"debug",
".",
"assert",
"(",
"js_input_params",
")",
".",
"is",
"(",
"'array'",
")",
";",
"//debug.log('input_nopg_keys = ', input_nopg_keys);",
"//debug.log('func = ', func);",
"//debug.log('js_input_params = ', js_input_params);",
"var",
"_parse_predicate_key_epoch",
"=",
"FUNCTION",
"(",
"_parse_predicate_key",
")",
".",
"curry",
"(",
"ObjType",
",",
"{",
"'traits'",
":",
"traits",
",",
"'epoch'",
":",
"true",
"}",
")",
";",
"var",
"input_pg_keys",
"=",
"ARRAY",
"(",
"input_nopg_keys",
")",
".",
"map",
"(",
"_parse_predicate_key_epoch",
")",
";",
"var",
"pg_items",
"=",
"input_pg_keys",
".",
"map",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"i",
".",
"getString",
"(",
")",
";",
"}",
")",
".",
"valueOf",
"(",
")",
";",
"var",
"pg_params",
"=",
"input_pg_keys",
".",
"map",
"(",
"function",
"(",
"i",
")",
"{",
"return",
"i",
".",
"getParams",
"(",
")",
";",
"}",
")",
".",
"reduce",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"concat",
"(",
"b",
")",
";",
"}",
")",
";",
"debug",
".",
"assert",
"(",
"pg_items",
")",
".",
"is",
"(",
"'array'",
")",
";",
"debug",
".",
"assert",
"(",
"pg_params",
")",
".",
"is",
"(",
"'array'",
")",
";",
"//debug.log('input_pg_keys = ', input_pg_keys);",
"//var n = arg_params.length;",
"//arg_params.push(JSON.stringify(FUNCTION(func).stringify()));",
"//arg_params.push(JSON.stringify(js_input_params));",
"var",
"call_func",
"=",
"'nopg.call_func(array_to_json(ARRAY['",
"+",
"pg_items",
".",
"join",
"(",
"', '",
")",
"+",
"\"]), $::json, $::json)\"",
";",
"var",
"type_cast",
"=",
"parse_predicate_pgcast_by_type",
"(",
"ret_type",
")",
";",
"return",
"new",
"Predicate",
"(",
"type_cast",
"(",
"call_func",
")",
",",
"pg_params",
".",
"concat",
"(",
"[",
"JSON",
".",
"stringify",
"(",
"FUNCTION",
"(",
"func",
")",
".",
"stringify",
"(",
")",
")",
",",
"JSON",
".",
"stringify",
"(",
"js_input_params",
")",
"]",
")",
")",
";",
"}"
] | Parse array predicate | [
"Parse",
"array",
"predicate"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L759-L801 |
50,987 | sendanor/nor-nopg | src/nopg.js | parse_operator_type | function parse_operator_type(op, def) {
op = ''+op;
if(op.indexOf(':') === -1) {
return def || 'boolean';
}
return op.split(':')[1];
} | javascript | function parse_operator_type(op, def) {
op = ''+op;
if(op.indexOf(':') === -1) {
return def || 'boolean';
}
return op.split(':')[1];
} | [
"function",
"parse_operator_type",
"(",
"op",
",",
"def",
")",
"{",
"op",
"=",
"''",
"+",
"op",
";",
"if",
"(",
"op",
".",
"indexOf",
"(",
"':'",
")",
"===",
"-",
"1",
")",
"{",
"return",
"def",
"||",
"'boolean'",
";",
"}",
"return",
"op",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
";",
"}"
] | Returns true if op is AND, OR or BIND | [
"Returns",
"true",
"if",
"op",
"is",
"AND",
"OR",
"or",
"BIND"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L811-L817 |
50,988 | sendanor/nor-nopg | src/nopg.js | parse_search_traits | function parse_search_traits(traits) {
traits = traits || {};
// Initialize fields as all fields
if(!traits.fields) {
traits.fields = ['$*'];
}
// If fields was not an array (but is not negative -- check previous if clause), lets make it that.
if(!is.array(traits.fields)) {
traits.fields = [traits.fields];
}
debug.assert(traits.fields).is('array');
// Order by $created by default
if(!traits.order) {
// FIXME: Check if `$created` exists in the ObjType!
traits.order = ['$created'];
}
// Enable group by
if(traits.hasOwnProperty('group')) {
traits.group = [].concat(traits.group);
}
if(!is.array(traits.order)) {
traits.order = [traits.order];
}
debug.assert(traits.order).is('array');
if(traits.limit) {
if(!traits.order) {
debug.warn('Limit without ordering will yeald unpredictable results!');
}
if((''+traits.limit).toLowerCase() === 'all') {
traits.limit = 'ALL';
} else {
traits.limit = '' + parseInt(traits.limit, 10);
}
}
if(traits.offset) {
traits.offset = parseInt(traits.offset, 10);
}
if(traits.hasOwnProperty('prepareOnly')) {
traits.prepareOnly = traits.prepareOnly === true;
}
if(traits.hasOwnProperty('typeAwareness')) {
traits.typeAwareness = traits.typeAwareness === true;
} else {
traits.typeAwareness = NoPg.defaults.enableTypeAwareness === true;
}
// Append '$documents' to fields if traits.documents is specified and it is missing from there
if((traits.documents || traits.typeAwareness) && (traits.fields.indexOf('$documents') === -1) ) {
traits.fields = traits.fields.concat(['$documents']);
}
if(traits.hasOwnProperty('count')) {
traits.count = traits.count === true;
traits.fields = ['count'];
delete traits.order;
}
return traits;
} | javascript | function parse_search_traits(traits) {
traits = traits || {};
// Initialize fields as all fields
if(!traits.fields) {
traits.fields = ['$*'];
}
// If fields was not an array (but is not negative -- check previous if clause), lets make it that.
if(!is.array(traits.fields)) {
traits.fields = [traits.fields];
}
debug.assert(traits.fields).is('array');
// Order by $created by default
if(!traits.order) {
// FIXME: Check if `$created` exists in the ObjType!
traits.order = ['$created'];
}
// Enable group by
if(traits.hasOwnProperty('group')) {
traits.group = [].concat(traits.group);
}
if(!is.array(traits.order)) {
traits.order = [traits.order];
}
debug.assert(traits.order).is('array');
if(traits.limit) {
if(!traits.order) {
debug.warn('Limit without ordering will yeald unpredictable results!');
}
if((''+traits.limit).toLowerCase() === 'all') {
traits.limit = 'ALL';
} else {
traits.limit = '' + parseInt(traits.limit, 10);
}
}
if(traits.offset) {
traits.offset = parseInt(traits.offset, 10);
}
if(traits.hasOwnProperty('prepareOnly')) {
traits.prepareOnly = traits.prepareOnly === true;
}
if(traits.hasOwnProperty('typeAwareness')) {
traits.typeAwareness = traits.typeAwareness === true;
} else {
traits.typeAwareness = NoPg.defaults.enableTypeAwareness === true;
}
// Append '$documents' to fields if traits.documents is specified and it is missing from there
if((traits.documents || traits.typeAwareness) && (traits.fields.indexOf('$documents') === -1) ) {
traits.fields = traits.fields.concat(['$documents']);
}
if(traits.hasOwnProperty('count')) {
traits.count = traits.count === true;
traits.fields = ['count'];
delete traits.order;
}
return traits;
} | [
"function",
"parse_search_traits",
"(",
"traits",
")",
"{",
"traits",
"=",
"traits",
"||",
"{",
"}",
";",
"// Initialize fields as all fields",
"if",
"(",
"!",
"traits",
".",
"fields",
")",
"{",
"traits",
".",
"fields",
"=",
"[",
"'$*'",
"]",
";",
"}",
"// If fields was not an array (but is not negative -- check previous if clause), lets make it that.",
"if",
"(",
"!",
"is",
".",
"array",
"(",
"traits",
".",
"fields",
")",
")",
"{",
"traits",
".",
"fields",
"=",
"[",
"traits",
".",
"fields",
"]",
";",
"}",
"debug",
".",
"assert",
"(",
"traits",
".",
"fields",
")",
".",
"is",
"(",
"'array'",
")",
";",
"// Order by $created by default",
"if",
"(",
"!",
"traits",
".",
"order",
")",
"{",
"// FIXME: Check if `$created` exists in the ObjType!",
"traits",
".",
"order",
"=",
"[",
"'$created'",
"]",
";",
"}",
"// Enable group by",
"if",
"(",
"traits",
".",
"hasOwnProperty",
"(",
"'group'",
")",
")",
"{",
"traits",
".",
"group",
"=",
"[",
"]",
".",
"concat",
"(",
"traits",
".",
"group",
")",
";",
"}",
"if",
"(",
"!",
"is",
".",
"array",
"(",
"traits",
".",
"order",
")",
")",
"{",
"traits",
".",
"order",
"=",
"[",
"traits",
".",
"order",
"]",
";",
"}",
"debug",
".",
"assert",
"(",
"traits",
".",
"order",
")",
".",
"is",
"(",
"'array'",
")",
";",
"if",
"(",
"traits",
".",
"limit",
")",
"{",
"if",
"(",
"!",
"traits",
".",
"order",
")",
"{",
"debug",
".",
"warn",
"(",
"'Limit without ordering will yeald unpredictable results!'",
")",
";",
"}",
"if",
"(",
"(",
"''",
"+",
"traits",
".",
"limit",
")",
".",
"toLowerCase",
"(",
")",
"===",
"'all'",
")",
"{",
"traits",
".",
"limit",
"=",
"'ALL'",
";",
"}",
"else",
"{",
"traits",
".",
"limit",
"=",
"''",
"+",
"parseInt",
"(",
"traits",
".",
"limit",
",",
"10",
")",
";",
"}",
"}",
"if",
"(",
"traits",
".",
"offset",
")",
"{",
"traits",
".",
"offset",
"=",
"parseInt",
"(",
"traits",
".",
"offset",
",",
"10",
")",
";",
"}",
"if",
"(",
"traits",
".",
"hasOwnProperty",
"(",
"'prepareOnly'",
")",
")",
"{",
"traits",
".",
"prepareOnly",
"=",
"traits",
".",
"prepareOnly",
"===",
"true",
";",
"}",
"if",
"(",
"traits",
".",
"hasOwnProperty",
"(",
"'typeAwareness'",
")",
")",
"{",
"traits",
".",
"typeAwareness",
"=",
"traits",
".",
"typeAwareness",
"===",
"true",
";",
"}",
"else",
"{",
"traits",
".",
"typeAwareness",
"=",
"NoPg",
".",
"defaults",
".",
"enableTypeAwareness",
"===",
"true",
";",
"}",
"// Append '$documents' to fields if traits.documents is specified and it is missing from there",
"if",
"(",
"(",
"traits",
".",
"documents",
"||",
"traits",
".",
"typeAwareness",
")",
"&&",
"(",
"traits",
".",
"fields",
".",
"indexOf",
"(",
"'$documents'",
")",
"===",
"-",
"1",
")",
")",
"{",
"traits",
".",
"fields",
"=",
"traits",
".",
"fields",
".",
"concat",
"(",
"[",
"'$documents'",
"]",
")",
";",
"}",
"if",
"(",
"traits",
".",
"hasOwnProperty",
"(",
"'count'",
")",
")",
"{",
"traits",
".",
"count",
"=",
"traits",
".",
"count",
"===",
"true",
";",
"traits",
".",
"fields",
"=",
"[",
"'count'",
"]",
";",
"delete",
"traits",
".",
"order",
";",
"}",
"return",
"traits",
";",
"}"
] | Parse traits object | [
"Parse",
"traits",
"object"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L877-L947 |
50,989 | sendanor/nor-nopg | src/nopg.js | parse_select_fields | function parse_select_fields(ObjType, traits) {
debug.assert(ObjType).is('function');
debug.assert(traits).ignore(undefined).is('object');
return ARRAY(traits.fields).map(function(f) {
return _parse_predicate_key(ObjType, {'traits': traits, 'epoch':false}, f);
}).valueOf();
} | javascript | function parse_select_fields(ObjType, traits) {
debug.assert(ObjType).is('function');
debug.assert(traits).ignore(undefined).is('object');
return ARRAY(traits.fields).map(function(f) {
return _parse_predicate_key(ObjType, {'traits': traits, 'epoch':false}, f);
}).valueOf();
} | [
"function",
"parse_select_fields",
"(",
"ObjType",
",",
"traits",
")",
"{",
"debug",
".",
"assert",
"(",
"ObjType",
")",
".",
"is",
"(",
"'function'",
")",
";",
"debug",
".",
"assert",
"(",
"traits",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'object'",
")",
";",
"return",
"ARRAY",
"(",
"traits",
".",
"fields",
")",
".",
"map",
"(",
"function",
"(",
"f",
")",
"{",
"return",
"_parse_predicate_key",
"(",
"ObjType",
",",
"{",
"'traits'",
":",
"traits",
",",
"'epoch'",
":",
"false",
"}",
",",
"f",
")",
";",
"}",
")",
".",
"valueOf",
"(",
")",
";",
"}"
] | Parses internal fields from nopg style fields | [
"Parses",
"internal",
"fields",
"from",
"nopg",
"style",
"fields"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L952-L958 |
50,990 | sendanor/nor-nopg | src/nopg.js | parse_search_opts | function parse_search_opts(opts, traits) {
if(opts === undefined) {
return;
}
if(is.array(opts)) {
if( (opts.length >= 1) && is.obj(opts[0]) ) {
return [ ((traits.match === 'any') ? 'OR' : 'AND') ].concat(opts);
}
return opts;
}
if(opts instanceof NoPg.Type) {
return [ "AND", { "$id": opts.$id } ];
}
if(is.obj(opts)) {
return [ ((traits.match === 'any') ? 'OR' : 'AND') , opts];
}
return [ "AND", {"$name": ''+opts} ];
} | javascript | function parse_search_opts(opts, traits) {
if(opts === undefined) {
return;
}
if(is.array(opts)) {
if( (opts.length >= 1) && is.obj(opts[0]) ) {
return [ ((traits.match === 'any') ? 'OR' : 'AND') ].concat(opts);
}
return opts;
}
if(opts instanceof NoPg.Type) {
return [ "AND", { "$id": opts.$id } ];
}
if(is.obj(opts)) {
return [ ((traits.match === 'any') ? 'OR' : 'AND') , opts];
}
return [ "AND", {"$name": ''+opts} ];
} | [
"function",
"parse_search_opts",
"(",
"opts",
",",
"traits",
")",
"{",
"if",
"(",
"opts",
"===",
"undefined",
")",
"{",
"return",
";",
"}",
"if",
"(",
"is",
".",
"array",
"(",
"opts",
")",
")",
"{",
"if",
"(",
"(",
"opts",
".",
"length",
">=",
"1",
")",
"&&",
"is",
".",
"obj",
"(",
"opts",
"[",
"0",
"]",
")",
")",
"{",
"return",
"[",
"(",
"(",
"traits",
".",
"match",
"===",
"'any'",
")",
"?",
"'OR'",
":",
"'AND'",
")",
"]",
".",
"concat",
"(",
"opts",
")",
";",
"}",
"return",
"opts",
";",
"}",
"if",
"(",
"opts",
"instanceof",
"NoPg",
".",
"Type",
")",
"{",
"return",
"[",
"\"AND\"",
",",
"{",
"\"$id\"",
":",
"opts",
".",
"$id",
"}",
"]",
";",
"}",
"if",
"(",
"is",
".",
"obj",
"(",
"opts",
")",
")",
"{",
"return",
"[",
"(",
"(",
"traits",
".",
"match",
"===",
"'any'",
")",
"?",
"'OR'",
":",
"'AND'",
")",
",",
"opts",
"]",
";",
"}",
"return",
"[",
"\"AND\"",
",",
"{",
"\"$name\"",
":",
"''",
"+",
"opts",
"}",
"]",
";",
"}"
] | Parse opts object | [
"Parse",
"opts",
"object"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L961-L983 |
50,991 | sendanor/nor-nopg | src/nopg.js | _parse_select_order | function _parse_select_order(ObjType, document_type, order, q, traits) {
debug.assert(ObjType).is('function');
debug.assert(document_type).ignore(undefined).is('object');
debug.assert(order).is('array');
return ARRAY(order).map(function(o) {
var key, type, rest;
if(is.array(o)) {
key = parse_operator_name(o[0]);
type = parse_operator_type(o[0], 'text');
rest = o.slice(1);
} else {
key = parse_operator_name(o);
type = parse_operator_type(o, 'text');
rest = [];
}
if(key === 'BIND') {
return _parse_function_predicate(ObjType, q, undefined, rest, type, traits);
}
//debug.log('key = ', key);
var parsed_key = _parse_predicate_key(ObjType, {'traits': traits, 'epoch':true}, key);
//debug.log('parsed_key = ', parsed_key);
var pgcast = parse_predicate_pgcast(ObjType, document_type, key);
//debug.log('pgcast = ', pgcast);
return new Predicate( [pgcast(parsed_key.getString())].concat(rest).join(' '), parsed_key.getParams(), parsed_key.getMetaObject() );
}).valueOf();
} | javascript | function _parse_select_order(ObjType, document_type, order, q, traits) {
debug.assert(ObjType).is('function');
debug.assert(document_type).ignore(undefined).is('object');
debug.assert(order).is('array');
return ARRAY(order).map(function(o) {
var key, type, rest;
if(is.array(o)) {
key = parse_operator_name(o[0]);
type = parse_operator_type(o[0], 'text');
rest = o.slice(1);
} else {
key = parse_operator_name(o);
type = parse_operator_type(o, 'text');
rest = [];
}
if(key === 'BIND') {
return _parse_function_predicate(ObjType, q, undefined, rest, type, traits);
}
//debug.log('key = ', key);
var parsed_key = _parse_predicate_key(ObjType, {'traits': traits, 'epoch':true}, key);
//debug.log('parsed_key = ', parsed_key);
var pgcast = parse_predicate_pgcast(ObjType, document_type, key);
//debug.log('pgcast = ', pgcast);
return new Predicate( [pgcast(parsed_key.getString())].concat(rest).join(' '), parsed_key.getParams(), parsed_key.getMetaObject() );
}).valueOf();
} | [
"function",
"_parse_select_order",
"(",
"ObjType",
",",
"document_type",
",",
"order",
",",
"q",
",",
"traits",
")",
"{",
"debug",
".",
"assert",
"(",
"ObjType",
")",
".",
"is",
"(",
"'function'",
")",
";",
"debug",
".",
"assert",
"(",
"document_type",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'object'",
")",
";",
"debug",
".",
"assert",
"(",
"order",
")",
".",
"is",
"(",
"'array'",
")",
";",
"return",
"ARRAY",
"(",
"order",
")",
".",
"map",
"(",
"function",
"(",
"o",
")",
"{",
"var",
"key",
",",
"type",
",",
"rest",
";",
"if",
"(",
"is",
".",
"array",
"(",
"o",
")",
")",
"{",
"key",
"=",
"parse_operator_name",
"(",
"o",
"[",
"0",
"]",
")",
";",
"type",
"=",
"parse_operator_type",
"(",
"o",
"[",
"0",
"]",
",",
"'text'",
")",
";",
"rest",
"=",
"o",
".",
"slice",
"(",
"1",
")",
";",
"}",
"else",
"{",
"key",
"=",
"parse_operator_name",
"(",
"o",
")",
";",
"type",
"=",
"parse_operator_type",
"(",
"o",
",",
"'text'",
")",
";",
"rest",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"key",
"===",
"'BIND'",
")",
"{",
"return",
"_parse_function_predicate",
"(",
"ObjType",
",",
"q",
",",
"undefined",
",",
"rest",
",",
"type",
",",
"traits",
")",
";",
"}",
"//debug.log('key = ', key);",
"var",
"parsed_key",
"=",
"_parse_predicate_key",
"(",
"ObjType",
",",
"{",
"'traits'",
":",
"traits",
",",
"'epoch'",
":",
"true",
"}",
",",
"key",
")",
";",
"//debug.log('parsed_key = ', parsed_key);",
"var",
"pgcast",
"=",
"parse_predicate_pgcast",
"(",
"ObjType",
",",
"document_type",
",",
"key",
")",
";",
"//debug.log('pgcast = ', pgcast);",
"return",
"new",
"Predicate",
"(",
"[",
"pgcast",
"(",
"parsed_key",
".",
"getString",
"(",
")",
")",
"]",
".",
"concat",
"(",
"rest",
")",
".",
"join",
"(",
"' '",
")",
",",
"parsed_key",
".",
"getParams",
"(",
")",
",",
"parsed_key",
".",
"getMetaObject",
"(",
")",
")",
";",
"}",
")",
".",
"valueOf",
"(",
")",
";",
"}"
] | Generate ORDER BY using `traits.order` | [
"Generate",
"ORDER",
"BY",
"using",
"traits",
".",
"order"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L986-L1016 |
50,992 | sendanor/nor-nopg | src/nopg.js | do_select | function do_select(self, types, search_opts, traits) {
return nr_fcall("nopg:do_select", function() {
return prepare_select_query(self, types, search_opts, traits).then(function(q) {
var result = q.compile();
// Unnecessary since do_query() does it too
//if(NoPg.debug) {
// debug.log('query = ', result.query);
// debug.log('params = ', result.params);
//}
debug.assert(result).is('object');
debug.assert(result.query).is('string');
debug.assert(result.params).is('array');
var builder;
var type = result.documentType;
if( (result.ObjType === NoPg.Document) &&
is.string(type) &&
self._documentBuilders &&
self._documentBuilders.hasOwnProperty(type) &&
is.func(self._documentBuilders[type]) ) {
builder = self._documentBuilders[type];
}
debug.assert(builder).ignore(undefined).is('function');
return do_query(self, result.query, result.params ).then(get_results(result.ObjType, {
'fieldMap': result.fieldMap
})).then(function(data) {
if(!builder) {
return data;
}
debug.log('data = ', data);
return builder(data);
});
});
});
} | javascript | function do_select(self, types, search_opts, traits) {
return nr_fcall("nopg:do_select", function() {
return prepare_select_query(self, types, search_opts, traits).then(function(q) {
var result = q.compile();
// Unnecessary since do_query() does it too
//if(NoPg.debug) {
// debug.log('query = ', result.query);
// debug.log('params = ', result.params);
//}
debug.assert(result).is('object');
debug.assert(result.query).is('string');
debug.assert(result.params).is('array');
var builder;
var type = result.documentType;
if( (result.ObjType === NoPg.Document) &&
is.string(type) &&
self._documentBuilders &&
self._documentBuilders.hasOwnProperty(type) &&
is.func(self._documentBuilders[type]) ) {
builder = self._documentBuilders[type];
}
debug.assert(builder).ignore(undefined).is('function');
return do_query(self, result.query, result.params ).then(get_results(result.ObjType, {
'fieldMap': result.fieldMap
})).then(function(data) {
if(!builder) {
return data;
}
debug.log('data = ', data);
return builder(data);
});
});
});
} | [
"function",
"do_select",
"(",
"self",
",",
"types",
",",
"search_opts",
",",
"traits",
")",
"{",
"return",
"nr_fcall",
"(",
"\"nopg:do_select\"",
",",
"function",
"(",
")",
"{",
"return",
"prepare_select_query",
"(",
"self",
",",
"types",
",",
"search_opts",
",",
"traits",
")",
".",
"then",
"(",
"function",
"(",
"q",
")",
"{",
"var",
"result",
"=",
"q",
".",
"compile",
"(",
")",
";",
"// Unnecessary since do_query() does it too",
"//if(NoPg.debug) {",
"//\tdebug.log('query = ', result.query);",
"//\tdebug.log('params = ', result.params);",
"//}",
"debug",
".",
"assert",
"(",
"result",
")",
".",
"is",
"(",
"'object'",
")",
";",
"debug",
".",
"assert",
"(",
"result",
".",
"query",
")",
".",
"is",
"(",
"'string'",
")",
";",
"debug",
".",
"assert",
"(",
"result",
".",
"params",
")",
".",
"is",
"(",
"'array'",
")",
";",
"var",
"builder",
";",
"var",
"type",
"=",
"result",
".",
"documentType",
";",
"if",
"(",
"(",
"result",
".",
"ObjType",
"===",
"NoPg",
".",
"Document",
")",
"&&",
"is",
".",
"string",
"(",
"type",
")",
"&&",
"self",
".",
"_documentBuilders",
"&&",
"self",
".",
"_documentBuilders",
".",
"hasOwnProperty",
"(",
"type",
")",
"&&",
"is",
".",
"func",
"(",
"self",
".",
"_documentBuilders",
"[",
"type",
"]",
")",
")",
"{",
"builder",
"=",
"self",
".",
"_documentBuilders",
"[",
"type",
"]",
";",
"}",
"debug",
".",
"assert",
"(",
"builder",
")",
".",
"ignore",
"(",
"undefined",
")",
".",
"is",
"(",
"'function'",
")",
";",
"return",
"do_query",
"(",
"self",
",",
"result",
".",
"query",
",",
"result",
".",
"params",
")",
".",
"then",
"(",
"get_results",
"(",
"result",
".",
"ObjType",
",",
"{",
"'fieldMap'",
":",
"result",
".",
"fieldMap",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"builder",
")",
"{",
"return",
"data",
";",
"}",
"debug",
".",
"log",
"(",
"'data = '",
",",
"data",
")",
";",
"return",
"builder",
"(",
"data",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Generic SELECT query
@param self {object} The NoPg connection/transaction object
@param types {}
@param search_opts {}
@param traits {object} | [
"Generic",
"SELECT",
"query"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1177-L1215 |
50,993 | sendanor/nor-nopg | src/nopg.js | do_insert | function do_insert(self, ObjType, data) {
return nr_fcall("nopg:do_insert", function() {
return prepare_insert_query(self, ObjType, data).then(function(q) {
var result = q.compile();
return do_query(self, result.query, result.params);
});
});
} | javascript | function do_insert(self, ObjType, data) {
return nr_fcall("nopg:do_insert", function() {
return prepare_insert_query(self, ObjType, data).then(function(q) {
var result = q.compile();
return do_query(self, result.query, result.params);
});
});
} | [
"function",
"do_insert",
"(",
"self",
",",
"ObjType",
",",
"data",
")",
"{",
"return",
"nr_fcall",
"(",
"\"nopg:do_insert\"",
",",
"function",
"(",
")",
"{",
"return",
"prepare_insert_query",
"(",
"self",
",",
"ObjType",
",",
"data",
")",
".",
"then",
"(",
"function",
"(",
"q",
")",
"{",
"var",
"result",
"=",
"q",
".",
"compile",
"(",
")",
";",
"return",
"do_query",
"(",
"self",
",",
"result",
".",
"query",
",",
"result",
".",
"params",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Internal INSERT query | [
"Internal",
"INSERT",
"query"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1256-L1263 |
50,994 | sendanor/nor-nopg | src/nopg.js | json_cmp | function json_cmp(a, b) {
a = JSON.stringify(a);
b = JSON.stringify(b);
var ret = (a === b) ? true : false;
return ret;
} | javascript | function json_cmp(a, b) {
a = JSON.stringify(a);
b = JSON.stringify(b);
var ret = (a === b) ? true : false;
return ret;
} | [
"function",
"json_cmp",
"(",
"a",
",",
"b",
")",
"{",
"a",
"=",
"JSON",
".",
"stringify",
"(",
"a",
")",
";",
"b",
"=",
"JSON",
".",
"stringify",
"(",
"b",
")",
";",
"var",
"ret",
"=",
"(",
"a",
"===",
"b",
")",
"?",
"true",
":",
"false",
";",
"return",
"ret",
";",
"}"
] | Compare two variables as JSON strings | [
"Compare",
"two",
"variables",
"as",
"JSON",
"strings"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1266-L1271 |
50,995 | sendanor/nor-nopg | src/nopg.js | do_update | function do_update(self, ObjType, obj, orig_data) {
return nr_fcall("nopg:do_update", function() {
var query, params, data, where = {};
if(obj.$id) {
where.$id = obj.$id;
} else if(obj.$name) {
where.$name = obj.$name;
} else {
throw new TypeError("Cannot know what to update!");
}
if(orig_data === undefined) {
// FIXME: Check that `obj` is an ORM object
data = obj.valueOf();
} else {
data = (new ObjType(obj)).update(orig_data).valueOf();
}
//debug.log('data = ', data);
// Select only keys that start with $
var keys = ARRAY(ObjType.meta.keys)
// Remove leading '$' character from keys
.filter(first_letter_is_dollar)
.map( parse_keyword_name )
// Ignore keys that aren't going to be changed
.filter(function(key) {
return data.hasOwnProperty(key);
// Ignore keys that were not changed
}).filter(function(key) {
return json_cmp(data[key], obj['$'+key]) ? false : true;
});
//debug.log('keys = ', keys.valueOf());
// Return with the current object if there is no keys to update
if(keys.valueOf().length === 0) {
return do_select(self, ObjType, where);
}
// FIXME: Implement binary content support
query = "UPDATE " + (ObjType.meta.table) + " SET "+ keys.map(function(k, i) { return k + ' = $' + (i+1); }).join(', ') +" WHERE ";
if(where.$id) {
query += "id = $"+ (keys.valueOf().length+1);
} else if(where.$name) {
query += "name = $"+ (keys.valueOf().length+1);
} else {
throw new TypeError("Cannot know what to update!");
}
query += " RETURNING *";
params = keys.map(function(key) {
return data[key];
}).valueOf();
if(where.$id) {
params.push(where.$id);
} else if(where.$name){
params.push(where.$name);
}
return do_query(self, query, params);
});
} | javascript | function do_update(self, ObjType, obj, orig_data) {
return nr_fcall("nopg:do_update", function() {
var query, params, data, where = {};
if(obj.$id) {
where.$id = obj.$id;
} else if(obj.$name) {
where.$name = obj.$name;
} else {
throw new TypeError("Cannot know what to update!");
}
if(orig_data === undefined) {
// FIXME: Check that `obj` is an ORM object
data = obj.valueOf();
} else {
data = (new ObjType(obj)).update(orig_data).valueOf();
}
//debug.log('data = ', data);
// Select only keys that start with $
var keys = ARRAY(ObjType.meta.keys)
// Remove leading '$' character from keys
.filter(first_letter_is_dollar)
.map( parse_keyword_name )
// Ignore keys that aren't going to be changed
.filter(function(key) {
return data.hasOwnProperty(key);
// Ignore keys that were not changed
}).filter(function(key) {
return json_cmp(data[key], obj['$'+key]) ? false : true;
});
//debug.log('keys = ', keys.valueOf());
// Return with the current object if there is no keys to update
if(keys.valueOf().length === 0) {
return do_select(self, ObjType, where);
}
// FIXME: Implement binary content support
query = "UPDATE " + (ObjType.meta.table) + " SET "+ keys.map(function(k, i) { return k + ' = $' + (i+1); }).join(', ') +" WHERE ";
if(where.$id) {
query += "id = $"+ (keys.valueOf().length+1);
} else if(where.$name) {
query += "name = $"+ (keys.valueOf().length+1);
} else {
throw new TypeError("Cannot know what to update!");
}
query += " RETURNING *";
params = keys.map(function(key) {
return data[key];
}).valueOf();
if(where.$id) {
params.push(where.$id);
} else if(where.$name){
params.push(where.$name);
}
return do_query(self, query, params);
});
} | [
"function",
"do_update",
"(",
"self",
",",
"ObjType",
",",
"obj",
",",
"orig_data",
")",
"{",
"return",
"nr_fcall",
"(",
"\"nopg:do_update\"",
",",
"function",
"(",
")",
"{",
"var",
"query",
",",
"params",
",",
"data",
",",
"where",
"=",
"{",
"}",
";",
"if",
"(",
"obj",
".",
"$id",
")",
"{",
"where",
".",
"$id",
"=",
"obj",
".",
"$id",
";",
"}",
"else",
"if",
"(",
"obj",
".",
"$name",
")",
"{",
"where",
".",
"$name",
"=",
"obj",
".",
"$name",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Cannot know what to update!\"",
")",
";",
"}",
"if",
"(",
"orig_data",
"===",
"undefined",
")",
"{",
"// FIXME: Check that `obj` is an ORM object",
"data",
"=",
"obj",
".",
"valueOf",
"(",
")",
";",
"}",
"else",
"{",
"data",
"=",
"(",
"new",
"ObjType",
"(",
"obj",
")",
")",
".",
"update",
"(",
"orig_data",
")",
".",
"valueOf",
"(",
")",
";",
"}",
"//debug.log('data = ', data);",
"// Select only keys that start with $",
"var",
"keys",
"=",
"ARRAY",
"(",
"ObjType",
".",
"meta",
".",
"keys",
")",
"// Remove leading '$' character from keys",
".",
"filter",
"(",
"first_letter_is_dollar",
")",
".",
"map",
"(",
"parse_keyword_name",
")",
"// Ignore keys that aren't going to be changed",
".",
"filter",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"data",
".",
"hasOwnProperty",
"(",
"key",
")",
";",
"// Ignore keys that were not changed",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"json_cmp",
"(",
"data",
"[",
"key",
"]",
",",
"obj",
"[",
"'$'",
"+",
"key",
"]",
")",
"?",
"false",
":",
"true",
";",
"}",
")",
";",
"//debug.log('keys = ', keys.valueOf());",
"// Return with the current object if there is no keys to update",
"if",
"(",
"keys",
".",
"valueOf",
"(",
")",
".",
"length",
"===",
"0",
")",
"{",
"return",
"do_select",
"(",
"self",
",",
"ObjType",
",",
"where",
")",
";",
"}",
"// FIXME: Implement binary content support",
"query",
"=",
"\"UPDATE \"",
"+",
"(",
"ObjType",
".",
"meta",
".",
"table",
")",
"+",
"\" SET \"",
"+",
"keys",
".",
"map",
"(",
"function",
"(",
"k",
",",
"i",
")",
"{",
"return",
"k",
"+",
"' = $'",
"+",
"(",
"i",
"+",
"1",
")",
";",
"}",
")",
".",
"join",
"(",
"', '",
")",
"+",
"\" WHERE \"",
";",
"if",
"(",
"where",
".",
"$id",
")",
"{",
"query",
"+=",
"\"id = $\"",
"+",
"(",
"keys",
".",
"valueOf",
"(",
")",
".",
"length",
"+",
"1",
")",
";",
"}",
"else",
"if",
"(",
"where",
".",
"$name",
")",
"{",
"query",
"+=",
"\"name = $\"",
"+",
"(",
"keys",
".",
"valueOf",
"(",
")",
".",
"length",
"+",
"1",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Cannot know what to update!\"",
")",
";",
"}",
"query",
"+=",
"\" RETURNING *\"",
";",
"params",
"=",
"keys",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"data",
"[",
"key",
"]",
";",
"}",
")",
".",
"valueOf",
"(",
")",
";",
"if",
"(",
"where",
".",
"$id",
")",
"{",
"params",
".",
"push",
"(",
"where",
".",
"$id",
")",
";",
"}",
"else",
"if",
"(",
"where",
".",
"$name",
")",
"{",
"params",
".",
"push",
"(",
"where",
".",
"$name",
")",
";",
"}",
"return",
"do_query",
"(",
"self",
",",
"query",
",",
"params",
")",
";",
"}",
")",
";",
"}"
] | Internal UPDATE query | [
"Internal",
"UPDATE",
"query"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1274-L1340 |
50,996 | sendanor/nor-nopg | src/nopg.js | do_delete | function do_delete(self, ObjType, obj) {
return nr_fcall("nopg:do_delete", function() {
if(!(obj && obj.$id)) { throw new TypeError("opts.$id invalid: " + util.inspect(obj) ); }
var query, params;
query = "DELETE FROM " + (ObjType.meta.table) + " WHERE id = $1";
params = [obj.$id];
return do_query(self, query, params);
});
} | javascript | function do_delete(self, ObjType, obj) {
return nr_fcall("nopg:do_delete", function() {
if(!(obj && obj.$id)) { throw new TypeError("opts.$id invalid: " + util.inspect(obj) ); }
var query, params;
query = "DELETE FROM " + (ObjType.meta.table) + " WHERE id = $1";
params = [obj.$id];
return do_query(self, query, params);
});
} | [
"function",
"do_delete",
"(",
"self",
",",
"ObjType",
",",
"obj",
")",
"{",
"return",
"nr_fcall",
"(",
"\"nopg:do_delete\"",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"(",
"obj",
"&&",
"obj",
".",
"$id",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"opts.$id invalid: \"",
"+",
"util",
".",
"inspect",
"(",
"obj",
")",
")",
";",
"}",
"var",
"query",
",",
"params",
";",
"query",
"=",
"\"DELETE FROM \"",
"+",
"(",
"ObjType",
".",
"meta",
".",
"table",
")",
"+",
"\" WHERE id = $1\"",
";",
"params",
"=",
"[",
"obj",
".",
"$id",
"]",
";",
"return",
"do_query",
"(",
"self",
",",
"query",
",",
"params",
")",
";",
"}",
")",
";",
"}"
] | Internal DELETE query | [
"Internal",
"DELETE",
"query"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1343-L1351 |
50,997 | sendanor/nor-nopg | src/nopg.js | pg_table_exists | function pg_table_exists(self, name) {
return do_query(self, 'SELECT * FROM information_schema.tables WHERE table_name = $1 LIMIT 1', [name]).then(function(rows) {
if(!rows) { throw new TypeError("Unexpected result from query: " + util.inspect(rows)); }
return rows.length !== 0;
});
} | javascript | function pg_table_exists(self, name) {
return do_query(self, 'SELECT * FROM information_schema.tables WHERE table_name = $1 LIMIT 1', [name]).then(function(rows) {
if(!rows) { throw new TypeError("Unexpected result from query: " + util.inspect(rows)); }
return rows.length !== 0;
});
} | [
"function",
"pg_table_exists",
"(",
"self",
",",
"name",
")",
"{",
"return",
"do_query",
"(",
"self",
",",
"'SELECT * FROM information_schema.tables WHERE table_name = $1 LIMIT 1'",
",",
"[",
"name",
"]",
")",
".",
"then",
"(",
"function",
"(",
"rows",
")",
"{",
"if",
"(",
"!",
"rows",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Unexpected result from query: \"",
"+",
"util",
".",
"inspect",
"(",
"rows",
")",
")",
";",
"}",
"return",
"rows",
".",
"length",
"!==",
"0",
";",
"}",
")",
";",
"}"
] | Returns `true` if PostgreSQL database table exists.
@todo Implement this in nor-pg and use here. | [
"Returns",
"true",
"if",
"PostgreSQL",
"database",
"table",
"exists",
"."
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1357-L1362 |
50,998 | sendanor/nor-nopg | src/nopg.js | pg_get_indexdef | function pg_get_indexdef(self, name) {
return do_query(self, 'SELECT indexdef FROM pg_indexes WHERE indexname = $1 LIMIT 1', [name]).then(function(rows) {
if(!rows) { throw new TypeError("Unexpected result from query: " + util.inspect(rows)); }
if(rows.length === 0) {
throw new TypeError("Index does not exist: " + name);
}
return (rows.shift()||{}).indexdef;
});
} | javascript | function pg_get_indexdef(self, name) {
return do_query(self, 'SELECT indexdef FROM pg_indexes WHERE indexname = $1 LIMIT 1', [name]).then(function(rows) {
if(!rows) { throw new TypeError("Unexpected result from query: " + util.inspect(rows)); }
if(rows.length === 0) {
throw new TypeError("Index does not exist: " + name);
}
return (rows.shift()||{}).indexdef;
});
} | [
"function",
"pg_get_indexdef",
"(",
"self",
",",
"name",
")",
"{",
"return",
"do_query",
"(",
"self",
",",
"'SELECT indexdef FROM pg_indexes WHERE indexname = $1 LIMIT 1'",
",",
"[",
"name",
"]",
")",
".",
"then",
"(",
"function",
"(",
"rows",
")",
"{",
"if",
"(",
"!",
"rows",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Unexpected result from query: \"",
"+",
"util",
".",
"inspect",
"(",
"rows",
")",
")",
";",
"}",
"if",
"(",
"rows",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Index does not exist: \"",
"+",
"name",
")",
";",
"}",
"return",
"(",
"rows",
".",
"shift",
"(",
")",
"||",
"{",
"}",
")",
".",
"indexdef",
";",
"}",
")",
";",
"}"
] | Returns `true` if PostgreSQL database table has index like this one.
@todo Implement this in nor-pg and use here. | [
"Returns",
"true",
"if",
"PostgreSQL",
"database",
"table",
"has",
"index",
"like",
"this",
"one",
"."
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1379-L1387 |
50,999 | sendanor/nor-nopg | src/nopg.js | pg_create_index_name | function pg_create_index_name(self, ObjType, type, field, typefield) {
var name;
var colname = _parse_predicate_key(ObjType, {'epoch':false}, field);
var datakey = colname.getMeta('datakey');
var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key');
if( (ObjType === NoPg.Document) && (typefield !== undefined)) {
if(!typefield) {
throw new TypeError("No typefield set for NoPg.Document!");
}
name = pg_convert_index_name(ObjType.meta.table) + "_" + typefield + "_" + pg_convert_index_name(field_name) + "_index";
} else {
name = pg_convert_index_name(ObjType.meta.table) + "_" + pg_convert_index_name(field_name) + "_index";
}
return name;
} | javascript | function pg_create_index_name(self, ObjType, type, field, typefield) {
var name;
var colname = _parse_predicate_key(ObjType, {'epoch':false}, field);
var datakey = colname.getMeta('datakey');
var field_name = (datakey ? datakey + '.' : '' ) + colname.getMeta('key');
if( (ObjType === NoPg.Document) && (typefield !== undefined)) {
if(!typefield) {
throw new TypeError("No typefield set for NoPg.Document!");
}
name = pg_convert_index_name(ObjType.meta.table) + "_" + typefield + "_" + pg_convert_index_name(field_name) + "_index";
} else {
name = pg_convert_index_name(ObjType.meta.table) + "_" + pg_convert_index_name(field_name) + "_index";
}
return name;
} | [
"function",
"pg_create_index_name",
"(",
"self",
",",
"ObjType",
",",
"type",
",",
"field",
",",
"typefield",
")",
"{",
"var",
"name",
";",
"var",
"colname",
"=",
"_parse_predicate_key",
"(",
"ObjType",
",",
"{",
"'epoch'",
":",
"false",
"}",
",",
"field",
")",
";",
"var",
"datakey",
"=",
"colname",
".",
"getMeta",
"(",
"'datakey'",
")",
";",
"var",
"field_name",
"=",
"(",
"datakey",
"?",
"datakey",
"+",
"'.'",
":",
"''",
")",
"+",
"colname",
".",
"getMeta",
"(",
"'key'",
")",
";",
"if",
"(",
"(",
"ObjType",
"===",
"NoPg",
".",
"Document",
")",
"&&",
"(",
"typefield",
"!==",
"undefined",
")",
")",
"{",
"if",
"(",
"!",
"typefield",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"\"No typefield set for NoPg.Document!\"",
")",
";",
"}",
"name",
"=",
"pg_convert_index_name",
"(",
"ObjType",
".",
"meta",
".",
"table",
")",
"+",
"\"_\"",
"+",
"typefield",
"+",
"\"_\"",
"+",
"pg_convert_index_name",
"(",
"field_name",
")",
"+",
"\"_index\"",
";",
"}",
"else",
"{",
"name",
"=",
"pg_convert_index_name",
"(",
"ObjType",
".",
"meta",
".",
"table",
")",
"+",
"\"_\"",
"+",
"pg_convert_index_name",
"(",
"field_name",
")",
"+",
"\"_index\"",
";",
"}",
"return",
"name",
";",
"}"
] | Returns index name
@param self
@param ObjType
@param type
@param field
@param typefield
@return {*} | [
"Returns",
"index",
"name"
] | 0d99b86c1a1996b5828b56de8de23700df8bbc0c | https://github.com/sendanor/nor-nopg/blob/0d99b86c1a1996b5828b56de8de23700df8bbc0c/src/nopg.js#L1405-L1419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.