repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
clay/amphora-storage-postgres
|
postgres/client.js
|
raw
|
function raw(cmd, args = []) {
if (!Array.isArray(args)) throw new Error('`args` must be an array!');
return knex.raw(cmd, args);
}
|
javascript
|
function raw(cmd, args = []) {
if (!Array.isArray(args)) throw new Error('`args` must be an array!');
return knex.raw(cmd, args);
}
|
[
"function",
"raw",
"(",
"cmd",
",",
"args",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"args",
")",
")",
"throw",
"new",
"Error",
"(",
"'`args` must be an array!'",
")",
";",
"return",
"knex",
".",
"raw",
"(",
"cmd",
",",
"args",
")",
";",
"}"
] |
Executes a raw query against the database
@param {String} cmd
@param {Array<Any>} args
@return {Promise<Object>}
|
[
"Executes",
"a",
"raw",
"query",
"against",
"the",
"database"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/client.js#L327-L331
|
train
|
clay/amphora-storage-postgres
|
postgres/index.js
|
createTables
|
function createTables() {
return bluebird.all(getComponents().map(component => client.createTable(`components.${component}`)))
.then(() => bluebird.all(getLayouts().map(layout => client.createTableWithMeta(`layouts.${layout}`))))
.then(() => client.createTableWithMeta('pages'))
.then(() => client.raw('CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );', ['uris']))
.then(() => createRemainingTables());
}
|
javascript
|
function createTables() {
return bluebird.all(getComponents().map(component => client.createTable(`components.${component}`)))
.then(() => bluebird.all(getLayouts().map(layout => client.createTableWithMeta(`layouts.${layout}`))))
.then(() => client.createTableWithMeta('pages'))
.then(() => client.raw('CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );', ['uris']))
.then(() => createRemainingTables());
}
|
[
"function",
"createTables",
"(",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"getComponents",
"(",
")",
".",
"map",
"(",
"component",
"=>",
"client",
".",
"createTable",
"(",
"`",
"${",
"component",
"}",
"`",
")",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"bluebird",
".",
"all",
"(",
"getLayouts",
"(",
")",
".",
"map",
"(",
"layout",
"=>",
"client",
".",
"createTableWithMeta",
"(",
"`",
"${",
"layout",
"}",
"`",
")",
")",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"client",
".",
"createTableWithMeta",
"(",
"'pages'",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"client",
".",
"raw",
"(",
"'CREATE TABLE IF NOT EXISTS ?? ( id TEXT PRIMARY KEY NOT NULL, data TEXT NOT NULL, url TEXT );'",
",",
"[",
"'uris'",
"]",
")",
")",
".",
"then",
"(",
"(",
")",
"=>",
"createRemainingTables",
"(",
")",
")",
";",
"}"
] |
Create all tables needed
@return {Promise}
|
[
"Create",
"all",
"tables",
"needed"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/postgres/index.js#L30-L36
|
train
|
clay/amphora-storage-postgres
|
redis/index.js
|
createClient
|
function createClient(testRedisUrl) {
const redisUrl = testRedisUrl || REDIS_URL;
if (!redisUrl) {
return bluebird.reject(new Error('No Redis URL set'));
}
log('debug', `Connecting to Redis at ${redisUrl}`);
return new bluebird(resolve => {
module.exports.client = bluebird.promisifyAll(new Redis(redisUrl));
module.exports.client.on('error', logGenericError(__filename));
resolve({ server: redisUrl });
});
}
|
javascript
|
function createClient(testRedisUrl) {
const redisUrl = testRedisUrl || REDIS_URL;
if (!redisUrl) {
return bluebird.reject(new Error('No Redis URL set'));
}
log('debug', `Connecting to Redis at ${redisUrl}`);
return new bluebird(resolve => {
module.exports.client = bluebird.promisifyAll(new Redis(redisUrl));
module.exports.client.on('error', logGenericError(__filename));
resolve({ server: redisUrl });
});
}
|
[
"function",
"createClient",
"(",
"testRedisUrl",
")",
"{",
"const",
"redisUrl",
"=",
"testRedisUrl",
"||",
"REDIS_URL",
";",
"if",
"(",
"!",
"redisUrl",
")",
"{",
"return",
"bluebird",
".",
"reject",
"(",
"new",
"Error",
"(",
"'No Redis URL set'",
")",
")",
";",
"}",
"log",
"(",
"'debug'",
",",
"`",
"${",
"redisUrl",
"}",
"`",
")",
";",
"return",
"new",
"bluebird",
"(",
"resolve",
"=>",
"{",
"module",
".",
"exports",
".",
"client",
"=",
"bluebird",
".",
"promisifyAll",
"(",
"new",
"Redis",
"(",
"redisUrl",
")",
")",
";",
"module",
".",
"exports",
".",
"client",
".",
"on",
"(",
"'error'",
",",
"logGenericError",
"(",
"__filename",
")",
")",
";",
"resolve",
"(",
"{",
"server",
":",
"redisUrl",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Connect to Redis and store the client
@param {String} testRedisUrl, used for testing only
@return {Promise}
|
[
"Connect",
"to",
"Redis",
"and",
"store",
"the",
"client"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/redis/index.js#L16-L31
|
train
|
clay/amphora-storage-postgres
|
redis/index.js
|
put
|
function put(key, value) {
if (!shouldProcess(key)) return bluebird.resolve();
return module.exports.client.hsetAsync(REDIS_HASH, key, value);
}
|
javascript
|
function put(key, value) {
if (!shouldProcess(key)) return bluebird.resolve();
return module.exports.client.hsetAsync(REDIS_HASH, key, value);
}
|
[
"function",
"put",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"!",
"shouldProcess",
"(",
"key",
")",
")",
"return",
"bluebird",
".",
"resolve",
"(",
")",
";",
"return",
"module",
".",
"exports",
".",
"client",
".",
"hsetAsync",
"(",
"REDIS_HASH",
",",
"key",
",",
"value",
")",
";",
"}"
] |
Write a single value to a hash
@param {String} key
@param {String} value
@return {Promise}
|
[
"Write",
"a",
"single",
"value",
"to",
"a",
"hash"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/redis/index.js#L50-L54
|
train
|
clay/amphora-storage-postgres
|
redis/index.js
|
get
|
function get(key) {
if (!module.exports.client) {
return bluebird.reject(notFoundError(key));
}
return module.exports.client.hgetAsync(REDIS_HASH, key)
.then(data => data || bluebird.reject(notFoundError(key)));
}
|
javascript
|
function get(key) {
if (!module.exports.client) {
return bluebird.reject(notFoundError(key));
}
return module.exports.client.hgetAsync(REDIS_HASH, key)
.then(data => data || bluebird.reject(notFoundError(key)));
}
|
[
"function",
"get",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"module",
".",
"exports",
".",
"client",
")",
"{",
"return",
"bluebird",
".",
"reject",
"(",
"notFoundError",
"(",
"key",
")",
")",
";",
"}",
"return",
"module",
".",
"exports",
".",
"client",
".",
"hgetAsync",
"(",
"REDIS_HASH",
",",
"key",
")",
".",
"then",
"(",
"data",
"=>",
"data",
"||",
"bluebird",
".",
"reject",
"(",
"notFoundError",
"(",
"key",
")",
")",
")",
";",
"}"
] |
Read a single value from a hash
@param {String} key
@return {Promise}
|
[
"Read",
"a",
"single",
"value",
"from",
"a",
"hash"
] |
4279f932eed660737f5e2565d8e6cc3349d2776b
|
https://github.com/clay/amphora-storage-postgres/blob/4279f932eed660737f5e2565d8e6cc3349d2776b/redis/index.js#L62-L69
|
train
|
ngryman/gulp-bro
|
index.js
|
createBundler
|
function createBundler(opts, file, transform) {
// omit file contents to make browserify-incremental work propery
// on main entry (#4)
opts.entries = file.path
opts.basedir = path.dirname(file.path)
let bundler = bundlers[file.path]
if (bundler) {
bundler.removeAllListeners('log')
bundler.removeAllListeners('time')
}
else {
bundler = browserify(Object.assign(opts, incremental.args))
// only available via method call (#25)
if (opts.external) {
bundler.external(opts.external)
}
incremental(bundler)
bundlers[file.path] = bundler
}
bundler.on('log', message => transform.emit('log', message))
bundler.on('time', time => transform.emit('time', time))
return bundler
}
|
javascript
|
function createBundler(opts, file, transform) {
// omit file contents to make browserify-incremental work propery
// on main entry (#4)
opts.entries = file.path
opts.basedir = path.dirname(file.path)
let bundler = bundlers[file.path]
if (bundler) {
bundler.removeAllListeners('log')
bundler.removeAllListeners('time')
}
else {
bundler = browserify(Object.assign(opts, incremental.args))
// only available via method call (#25)
if (opts.external) {
bundler.external(opts.external)
}
incremental(bundler)
bundlers[file.path] = bundler
}
bundler.on('log', message => transform.emit('log', message))
bundler.on('time', time => transform.emit('time', time))
return bundler
}
|
[
"function",
"createBundler",
"(",
"opts",
",",
"file",
",",
"transform",
")",
"{",
"opts",
".",
"entries",
"=",
"file",
".",
"path",
"opts",
".",
"basedir",
"=",
"path",
".",
"dirname",
"(",
"file",
".",
"path",
")",
"let",
"bundler",
"=",
"bundlers",
"[",
"file",
".",
"path",
"]",
"if",
"(",
"bundler",
")",
"{",
"bundler",
".",
"removeAllListeners",
"(",
"'log'",
")",
"bundler",
".",
"removeAllListeners",
"(",
"'time'",
")",
"}",
"else",
"{",
"bundler",
"=",
"browserify",
"(",
"Object",
".",
"assign",
"(",
"opts",
",",
"incremental",
".",
"args",
")",
")",
"if",
"(",
"opts",
".",
"external",
")",
"{",
"bundler",
".",
"external",
"(",
"opts",
".",
"external",
")",
"}",
"incremental",
"(",
"bundler",
")",
"bundlers",
"[",
"file",
".",
"path",
"]",
"=",
"bundler",
"}",
"bundler",
".",
"on",
"(",
"'log'",
",",
"message",
"=>",
"transform",
".",
"emit",
"(",
"'log'",
",",
"message",
")",
")",
"bundler",
".",
"on",
"(",
"'time'",
",",
"time",
"=>",
"transform",
".",
"emit",
"(",
"'time'",
",",
"time",
")",
")",
"return",
"bundler",
"}"
] |
Return a new browserify bundler.
@param {object} opts
@param {vinyl} file
@param {stream.Transform} transform
@return {Browserify}
|
[
"Return",
"a",
"new",
"browserify",
"bundler",
"."
] |
4b9deb5f90242ba352317d879268bfaedc5133de
|
https://github.com/ngryman/gulp-bro/blob/4b9deb5f90242ba352317d879268bfaedc5133de/index.js#L56-L82
|
train
|
ngryman/gulp-bro
|
index.js
|
createErrorHandler
|
function createErrorHandler(opts, transform) {
return err => {
if ('emit' === opts.error) {
transform.emit('error', err)
}
else if ('function' === typeof opts.error) {
opts.error(err)
}
else {
const message = colors.red(err.name) + '\n' + err.toString()
.replace(/(ParseError.*)/, colors.red('$1'))
log(message)
}
transform.emit('end')
if (opts.callback) {
opts.callback(through2())
}
}
}
|
javascript
|
function createErrorHandler(opts, transform) {
return err => {
if ('emit' === opts.error) {
transform.emit('error', err)
}
else if ('function' === typeof opts.error) {
opts.error(err)
}
else {
const message = colors.red(err.name) + '\n' + err.toString()
.replace(/(ParseError.*)/, colors.red('$1'))
log(message)
}
transform.emit('end')
if (opts.callback) {
opts.callback(through2())
}
}
}
|
[
"function",
"createErrorHandler",
"(",
"opts",
",",
"transform",
")",
"{",
"return",
"err",
"=>",
"{",
"if",
"(",
"'emit'",
"===",
"opts",
".",
"error",
")",
"{",
"transform",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
"}",
"else",
"if",
"(",
"'function'",
"===",
"typeof",
"opts",
".",
"error",
")",
"{",
"opts",
".",
"error",
"(",
"err",
")",
"}",
"else",
"{",
"const",
"message",
"=",
"colors",
".",
"red",
"(",
"err",
".",
"name",
")",
"+",
"'\\n'",
"+",
"\\n",
"err",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"/",
"(ParseError.*)",
"/",
",",
"colors",
".",
"red",
"(",
"'$1'",
")",
")",
"}",
"log",
"(",
"message",
")",
"transform",
".",
"emit",
"(",
"'end'",
")",
"}",
"}"
] |
Return a new error handler.
@param {object} opts
@param {stream.Transform} transform
@return {function}
|
[
"Return",
"a",
"new",
"error",
"handler",
"."
] |
4b9deb5f90242ba352317d879268bfaedc5133de
|
https://github.com/ngryman/gulp-bro/blob/4b9deb5f90242ba352317d879268bfaedc5133de/index.js#L91-L111
|
train
|
ngnjs/NGN
|
lib/Utility.js
|
function (options, callback) {
let me = this
let tunnel
let sshcfg = {
host: this.host + ':' + (options.sshport || 22),
user: options.username,
remoteport: this.port
}
if (options.password) {
sshcfg.password = options.password
}
if (options.key) {
sshcfg.key = options.key
}
// Dynamically determine port by availability or via option.
// Then open the tunnel.
if (options.port) {
sshcfg.port = options.port
tunnel = new NGN.Tunnel(sshcfg)
tunnel.on('ready', function () {
NGN.BUS.emit('sshtunnel.create', tunnel)
callback && callback(me.host, options.port)
})
tunnel.connect()
} else {
// Create a quick TCP server on random port to secure the port,
// then shut it down and use the newly freed port.
let tmp = net.createServer().listen(0, '127.0.0.1', function () {
sshcfg.port = this.address().port
tmp.close()
})
tmp.on('close', function () {
// Launch the tunnel
tunnel = new NGN.Tunnel(sshcfg)
tunnel.on('ready', function () {
callback && callback('127.0.0.1', sshcfg.port)
})
tunnel.connect()
})
}
}
|
javascript
|
function (options, callback) {
let me = this
let tunnel
let sshcfg = {
host: this.host + ':' + (options.sshport || 22),
user: options.username,
remoteport: this.port
}
if (options.password) {
sshcfg.password = options.password
}
if (options.key) {
sshcfg.key = options.key
}
// Dynamically determine port by availability or via option.
// Then open the tunnel.
if (options.port) {
sshcfg.port = options.port
tunnel = new NGN.Tunnel(sshcfg)
tunnel.on('ready', function () {
NGN.BUS.emit('sshtunnel.create', tunnel)
callback && callback(me.host, options.port)
})
tunnel.connect()
} else {
// Create a quick TCP server on random port to secure the port,
// then shut it down and use the newly freed port.
let tmp = net.createServer().listen(0, '127.0.0.1', function () {
sshcfg.port = this.address().port
tmp.close()
})
tmp.on('close', function () {
// Launch the tunnel
tunnel = new NGN.Tunnel(sshcfg)
tunnel.on('ready', function () {
callback && callback('127.0.0.1', sshcfg.port)
})
tunnel.connect()
})
}
}
|
[
"function",
"(",
"options",
",",
"callback",
")",
"{",
"let",
"me",
"=",
"this",
"let",
"tunnel",
"let",
"sshcfg",
"=",
"{",
"host",
":",
"this",
".",
"host",
"+",
"':'",
"+",
"(",
"options",
".",
"sshport",
"||",
"22",
")",
",",
"user",
":",
"options",
".",
"username",
",",
"remoteport",
":",
"this",
".",
"port",
"}",
"if",
"(",
"options",
".",
"password",
")",
"{",
"sshcfg",
".",
"password",
"=",
"options",
".",
"password",
"}",
"if",
"(",
"options",
".",
"key",
")",
"{",
"sshcfg",
".",
"key",
"=",
"options",
".",
"key",
"}",
"if",
"(",
"options",
".",
"port",
")",
"{",
"sshcfg",
".",
"port",
"=",
"options",
".",
"port",
"tunnel",
"=",
"new",
"NGN",
".",
"Tunnel",
"(",
"sshcfg",
")",
"tunnel",
".",
"on",
"(",
"'ready'",
",",
"function",
"(",
")",
"{",
"NGN",
".",
"BUS",
".",
"emit",
"(",
"'sshtunnel.create'",
",",
"tunnel",
")",
"callback",
"&&",
"callback",
"(",
"me",
".",
"host",
",",
"options",
".",
"port",
")",
"}",
")",
"tunnel",
".",
"connect",
"(",
")",
"}",
"else",
"{",
"let",
"tmp",
"=",
"net",
".",
"createServer",
"(",
")",
".",
"listen",
"(",
"0",
",",
"'127.0.0.1'",
",",
"function",
"(",
")",
"{",
"sshcfg",
".",
"port",
"=",
"this",
".",
"address",
"(",
")",
".",
"port",
"tmp",
".",
"close",
"(",
")",
"}",
")",
"tmp",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"tunnel",
"=",
"new",
"NGN",
".",
"Tunnel",
"(",
"sshcfg",
")",
"tunnel",
".",
"on",
"(",
"'ready'",
",",
"function",
"(",
")",
"{",
"callback",
"&&",
"callback",
"(",
"'127.0.0.1'",
",",
"sshcfg",
".",
"port",
")",
"}",
")",
"tunnel",
".",
"connect",
"(",
")",
"}",
")",
"}",
"}"
] |
Creates an SSH Tunnel
|
[
"Creates",
"an",
"SSH",
"Tunnel"
] |
b18c73b87051a742dbebe9335ebbec030ceabac6
|
https://github.com/ngnjs/NGN/blob/b18c73b87051a742dbebe9335ebbec030ceabac6/lib/Utility.js#L10-L54
|
train
|
|
wayfair/tungstenjs
|
src/template/compiler/index.js
|
getTemplate
|
function getTemplate(template, options) {
stack.clear();
parser.reset();
let opts = typeof options === 'undefined' ? {} : options;
opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
opts.logger = opts.logger != null ? opts.logger : {};
let lambdas = {};
if (_.isArray(opts.lambdas)) {
for (let i = 0; i < opts.lambdas.length; i++) {
lambdas[opts.lambdas[i]] = true;
}
}
opts.lambdas = lambdas;
opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true;
compilerLogger.setStrictMode(opts.strict);
compilerLogger.setOverrides(opts.logger);
stack.setHtmlValidation(opts.validateHtml);
let templateStr = template.toString();
processTemplate(templateStr, opts);
let output = {};
if (stack.stack.length > 0) {
compilerErrors.notAllTagsWereClosedProperly(stack.stack);
}
parser.end();
output.templateObj = stack.getOutput();
const Template = require('../template');
output.template = new Template(output.templateObj);
output.source = template;
output.tokens = {};
_.each(stack.tokens, function(values, type) {
output.tokens[type] = _.keys(values);
});
return output;
}
|
javascript
|
function getTemplate(template, options) {
stack.clear();
parser.reset();
let opts = typeof options === 'undefined' ? {} : options;
opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
opts.logger = opts.logger != null ? opts.logger : {};
let lambdas = {};
if (_.isArray(opts.lambdas)) {
for (let i = 0; i < opts.lambdas.length; i++) {
lambdas[opts.lambdas[i]] = true;
}
}
opts.lambdas = lambdas;
opts.processingHTML = typeof opts.processingHTML === 'boolean' ? opts.processingHTML : true;
compilerLogger.setStrictMode(opts.strict);
compilerLogger.setOverrides(opts.logger);
stack.setHtmlValidation(opts.validateHtml);
let templateStr = template.toString();
processTemplate(templateStr, opts);
let output = {};
if (stack.stack.length > 0) {
compilerErrors.notAllTagsWereClosedProperly(stack.stack);
}
parser.end();
output.templateObj = stack.getOutput();
const Template = require('../template');
output.template = new Template(output.templateObj);
output.source = template;
output.tokens = {};
_.each(stack.tokens, function(values, type) {
output.tokens[type] = _.keys(values);
});
return output;
}
|
[
"function",
"getTemplate",
"(",
"template",
",",
"options",
")",
"{",
"stack",
".",
"clear",
"(",
")",
";",
"parser",
".",
"reset",
"(",
")",
";",
"let",
"opts",
"=",
"typeof",
"options",
"===",
"'undefined'",
"?",
"{",
"}",
":",
"options",
";",
"opts",
".",
"strict",
"=",
"typeof",
"opts",
".",
"strict",
"===",
"'boolean'",
"?",
"opts",
".",
"strict",
":",
"true",
";",
"opts",
".",
"preserveWhitespace",
"=",
"typeof",
"opts",
".",
"preserveWhitespace",
"===",
"'boolean'",
"?",
"opts",
".",
"preserveWhitespace",
":",
"false",
";",
"opts",
".",
"validateHtml",
"=",
"opts",
".",
"validateHtml",
"!=",
"null",
"?",
"opts",
".",
"validateHtml",
":",
"'strict'",
";",
"opts",
".",
"logger",
"=",
"opts",
".",
"logger",
"!=",
"null",
"?",
"opts",
".",
"logger",
":",
"{",
"}",
";",
"let",
"lambdas",
"=",
"{",
"}",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"opts",
".",
"lambdas",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"opts",
".",
"lambdas",
".",
"length",
";",
"i",
"++",
")",
"{",
"lambdas",
"[",
"opts",
".",
"lambdas",
"[",
"i",
"]",
"]",
"=",
"true",
";",
"}",
"}",
"opts",
".",
"lambdas",
"=",
"lambdas",
";",
"opts",
".",
"processingHTML",
"=",
"typeof",
"opts",
".",
"processingHTML",
"===",
"'boolean'",
"?",
"opts",
".",
"processingHTML",
":",
"true",
";",
"compilerLogger",
".",
"setStrictMode",
"(",
"opts",
".",
"strict",
")",
";",
"compilerLogger",
".",
"setOverrides",
"(",
"opts",
".",
"logger",
")",
";",
"stack",
".",
"setHtmlValidation",
"(",
"opts",
".",
"validateHtml",
")",
";",
"let",
"templateStr",
"=",
"template",
".",
"toString",
"(",
")",
";",
"processTemplate",
"(",
"templateStr",
",",
"opts",
")",
";",
"let",
"output",
"=",
"{",
"}",
";",
"if",
"(",
"stack",
".",
"stack",
".",
"length",
">",
"0",
")",
"{",
"compilerErrors",
".",
"notAllTagsWereClosedProperly",
"(",
"stack",
".",
"stack",
")",
";",
"}",
"parser",
".",
"end",
"(",
")",
";",
"output",
".",
"templateObj",
"=",
"stack",
".",
"getOutput",
"(",
")",
";",
"const",
"Template",
"=",
"require",
"(",
"'../template'",
")",
";",
"output",
".",
"template",
"=",
"new",
"Template",
"(",
"output",
".",
"templateObj",
")",
";",
"output",
".",
"source",
"=",
"template",
";",
"output",
".",
"tokens",
"=",
"{",
"}",
";",
"_",
".",
"each",
"(",
"stack",
".",
"tokens",
",",
"function",
"(",
"values",
",",
"type",
")",
"{",
"output",
".",
"tokens",
"[",
"type",
"]",
"=",
"_",
".",
"keys",
"(",
"values",
")",
";",
"}",
")",
";",
"return",
"output",
";",
"}"
] |
Processes a template string into a Template
@param {string} template Mustache template string
@return {Object} Processed template object
|
[
"Processes",
"a",
"template",
"string",
"into",
"a",
"Template"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/compiler/index.js#L17-L60
|
train
|
wayfair/tungstenjs
|
src/debug/timer.js
|
function(name, absoluteTime) {
this.name = name;
this.startTime = now();
this.absoluteTime = !!absoluteTime;
this.adjust = 0;
this.running = true;
}
|
javascript
|
function(name, absoluteTime) {
this.name = name;
this.startTime = now();
this.absoluteTime = !!absoluteTime;
this.adjust = 0;
this.running = true;
}
|
[
"function",
"(",
"name",
",",
"absoluteTime",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"startTime",
"=",
"now",
"(",
")",
";",
"this",
".",
"absoluteTime",
"=",
"!",
"!",
"absoluteTime",
";",
"this",
".",
"adjust",
"=",
"0",
";",
"this",
".",
"running",
"=",
"true",
";",
"}"
] |
Timing helper to performance test functionality
@param {String} name Name of this time for tracking purposes
@param {Boolean} absoluteTime Whether to use absolute times or relative
|
[
"Timing",
"helper",
"to",
"performance",
"test",
"functionality"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/timer.js#L32-L38
|
train
|
|
wayfair/tungstenjs
|
src/debug/timer.js
|
logStat
|
function logStat(stat, value) {
if (!statsTracker[stat]) {
statsTracker[stat] = [];
}
statsTracker[stat].push(value);
clearTimeout(statsTimer);
statsTimer = setTimeout(printStats, 100);
}
|
javascript
|
function logStat(stat, value) {
if (!statsTracker[stat]) {
statsTracker[stat] = [];
}
statsTracker[stat].push(value);
clearTimeout(statsTimer);
statsTimer = setTimeout(printStats, 100);
}
|
[
"function",
"logStat",
"(",
"stat",
",",
"value",
")",
"{",
"if",
"(",
"!",
"statsTracker",
"[",
"stat",
"]",
")",
"{",
"statsTracker",
"[",
"stat",
"]",
"=",
"[",
"]",
";",
"}",
"statsTracker",
"[",
"stat",
"]",
".",
"push",
"(",
"value",
")",
";",
"clearTimeout",
"(",
"statsTimer",
")",
";",
"statsTimer",
"=",
"setTimeout",
"(",
"printStats",
",",
"100",
")",
";",
"}"
] |
Add data point to stats
@param {String} stat Full name of the stat
@param {Number} value Run time to track
|
[
"Add",
"data",
"point",
"to",
"stats"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/timer.js#L93-L100
|
train
|
wayfair/tungstenjs
|
src/debug/timer.js
|
printStats
|
function printStats() {
_.each(statsTracker, function(vals, stat) {
var numStats = vals.length;
var total = _.reduce(vals, function(memo, num) {
return memo + num;
}, 0);
var avg = parseFloat(total / numStats).toFixed(4) + 'ms';
var printableTotal = parseFloat(total).toFixed(4) + 'ms';
logger.log(stat + ': ' + avg + ' (' + printableTotal + ' / ' + numStats + ')');
});
statsTracker = {};
}
|
javascript
|
function printStats() {
_.each(statsTracker, function(vals, stat) {
var numStats = vals.length;
var total = _.reduce(vals, function(memo, num) {
return memo + num;
}, 0);
var avg = parseFloat(total / numStats).toFixed(4) + 'ms';
var printableTotal = parseFloat(total).toFixed(4) + 'ms';
logger.log(stat + ': ' + avg + ' (' + printableTotal + ' / ' + numStats + ')');
});
statsTracker = {};
}
|
[
"function",
"printStats",
"(",
")",
"{",
"_",
".",
"each",
"(",
"statsTracker",
",",
"function",
"(",
"vals",
",",
"stat",
")",
"{",
"var",
"numStats",
"=",
"vals",
".",
"length",
";",
"var",
"total",
"=",
"_",
".",
"reduce",
"(",
"vals",
",",
"function",
"(",
"memo",
",",
"num",
")",
"{",
"return",
"memo",
"+",
"num",
";",
"}",
",",
"0",
")",
";",
"var",
"avg",
"=",
"parseFloat",
"(",
"total",
"/",
"numStats",
")",
".",
"toFixed",
"(",
"4",
")",
"+",
"'ms'",
";",
"var",
"printableTotal",
"=",
"parseFloat",
"(",
"total",
")",
".",
"toFixed",
"(",
"4",
")",
"+",
"'ms'",
";",
"logger",
".",
"log",
"(",
"stat",
"+",
"': '",
"+",
"avg",
"+",
"' ('",
"+",
"printableTotal",
"+",
"' / '",
"+",
"numStats",
"+",
"')'",
")",
";",
"}",
")",
";",
"statsTracker",
"=",
"{",
"}",
";",
"}"
] |
Output the average stats to logger
|
[
"Output",
"the",
"average",
"stats",
"to",
"logger"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/timer.js#L105-L116
|
train
|
wayfair/tungstenjs
|
src/event/tungsten_event.js
|
WEvent
|
function WEvent(evt) {
if (evt) {
this.originalEvent = evt;
this.type = evt.type;
this.which = evt.which || evt.charCode || evt.keyCode;
if (!this.which && evt.button !== undefined) {
this.which = ( evt.button & 1 ? 1 : ( evt.button & 2 ? 3 : ( evt.button & 4 ? 2 : 0 ) ) );
}
this.button = evt.button;
this.currentTarget = evt.currentTarget;
this.delegateTarget = null;
this.target = evt.target || evt.srcElement;
this.shiftKey = evt.shiftKey;
this.altKey = evt.altKey;
this.ctrlKey = evt.ctrlKey;
this.metaKey = evt.metaKey;
}
this.current = undefined;
this.previous = undefined;
this.eventId = _.uniqueId('e');
this.propagationStopped = false;
this.immediatePropagationStopped = false;
}
|
javascript
|
function WEvent(evt) {
if (evt) {
this.originalEvent = evt;
this.type = evt.type;
this.which = evt.which || evt.charCode || evt.keyCode;
if (!this.which && evt.button !== undefined) {
this.which = ( evt.button & 1 ? 1 : ( evt.button & 2 ? 3 : ( evt.button & 4 ? 2 : 0 ) ) );
}
this.button = evt.button;
this.currentTarget = evt.currentTarget;
this.delegateTarget = null;
this.target = evt.target || evt.srcElement;
this.shiftKey = evt.shiftKey;
this.altKey = evt.altKey;
this.ctrlKey = evt.ctrlKey;
this.metaKey = evt.metaKey;
}
this.current = undefined;
this.previous = undefined;
this.eventId = _.uniqueId('e');
this.propagationStopped = false;
this.immediatePropagationStopped = false;
}
|
[
"function",
"WEvent",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
")",
"{",
"this",
".",
"originalEvent",
"=",
"evt",
";",
"this",
".",
"type",
"=",
"evt",
".",
"type",
";",
"this",
".",
"which",
"=",
"evt",
".",
"which",
"||",
"evt",
".",
"charCode",
"||",
"evt",
".",
"keyCode",
";",
"if",
"(",
"!",
"this",
".",
"which",
"&&",
"evt",
".",
"button",
"!==",
"undefined",
")",
"{",
"this",
".",
"which",
"=",
"(",
"evt",
".",
"button",
"&",
"1",
"?",
"1",
":",
"(",
"evt",
".",
"button",
"&",
"2",
"?",
"3",
":",
"(",
"evt",
".",
"button",
"&",
"4",
"?",
"2",
":",
"0",
")",
")",
")",
";",
"}",
"this",
".",
"button",
"=",
"evt",
".",
"button",
";",
"this",
".",
"currentTarget",
"=",
"evt",
".",
"currentTarget",
";",
"this",
".",
"delegateTarget",
"=",
"null",
";",
"this",
".",
"target",
"=",
"evt",
".",
"target",
"||",
"evt",
".",
"srcElement",
";",
"this",
".",
"shiftKey",
"=",
"evt",
".",
"shiftKey",
";",
"this",
".",
"altKey",
"=",
"evt",
".",
"altKey",
";",
"this",
".",
"ctrlKey",
"=",
"evt",
".",
"ctrlKey",
";",
"this",
".",
"metaKey",
"=",
"evt",
".",
"metaKey",
";",
"}",
"this",
".",
"current",
"=",
"undefined",
";",
"this",
".",
"previous",
"=",
"undefined",
";",
"this",
".",
"eventId",
"=",
"_",
".",
"uniqueId",
"(",
"'e'",
")",
";",
"this",
".",
"propagationStopped",
"=",
"false",
";",
"this",
".",
"immediatePropagationStopped",
"=",
"false",
";",
"}"
] |
Wrapper function for the event object
@param {Object} evt Native event to wrap
|
[
"Wrapper",
"function",
"for",
"the",
"event",
"object"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/event/tungsten_event.js#L8-L30
|
train
|
wayfair/tungstenjs
|
src/utils/logger.js
|
getDefaultConsole
|
function getDefaultConsole() {
if (console && typeof console.log === 'function') {
return console.log;
} else {
return function() {
// Console isn't available until dev tools is open in old IE, so keep checking
if (console && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
};
}
}
|
javascript
|
function getDefaultConsole() {
if (console && typeof console.log === 'function') {
return console.log;
} else {
return function() {
// Console isn't available until dev tools is open in old IE, so keep checking
if (console && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
};
}
}
|
[
"function",
"getDefaultConsole",
"(",
")",
"{",
"if",
"(",
"console",
"&&",
"typeof",
"console",
".",
"log",
"===",
"'function'",
")",
"{",
"return",
"console",
".",
"log",
";",
"}",
"else",
"{",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"console",
"&&",
"typeof",
"console",
".",
"log",
"===",
"'function'",
")",
"{",
"console",
".",
"log",
".",
"apply",
"(",
"console",
",",
"arguments",
")",
";",
"}",
"}",
";",
"}",
"}"
] |
Gets a bound console method, falls back to log for unavailable functions
@param {String} name Name of the method to get
@return {Function} Bound console function
/* eslint-disable no-console
|
[
"Gets",
"a",
"bound",
"console",
"method",
"falls",
"back",
"to",
"log",
"for",
"unavailable",
"functions"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/utils/logger.js#L16-L27
|
train
|
wayfair/tungstenjs
|
src/debug/registry.js
|
updateNestedModels
|
function updateNestedModels() {
nestedRegistry.models = [];
_.each(nestedRegistry.views, function(view) {
var data = (view.obj.model || view.obj.collection);
if (data) {
nestedRegistry.models.push(flatRegistry.models[data.getDebugName()]);
}
});
}
|
javascript
|
function updateNestedModels() {
nestedRegistry.models = [];
_.each(nestedRegistry.views, function(view) {
var data = (view.obj.model || view.obj.collection);
if (data) {
nestedRegistry.models.push(flatRegistry.models[data.getDebugName()]);
}
});
}
|
[
"function",
"updateNestedModels",
"(",
")",
"{",
"nestedRegistry",
".",
"models",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"nestedRegistry",
".",
"views",
",",
"function",
"(",
"view",
")",
"{",
"var",
"data",
"=",
"(",
"view",
".",
"obj",
".",
"model",
"||",
"view",
".",
"obj",
".",
"collection",
")",
";",
"if",
"(",
"data",
")",
"{",
"nestedRegistry",
".",
"models",
".",
"push",
"(",
"flatRegistry",
".",
"models",
"[",
"data",
".",
"getDebugName",
"(",
")",
"]",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Updates nestedRegistry.models using the top level view's models to get nesting
|
[
"Updates",
"nestedRegistry",
".",
"models",
"using",
"the",
"top",
"level",
"view",
"s",
"models",
"to",
"get",
"nesting"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/registry.js#L27-L35
|
train
|
wayfair/tungstenjs
|
src/debug/registry.js
|
registerView
|
function registerView(view) {
var name = view.getDebugName();
var wrapped = new RegistryWrapper(view, 'views');
flatRegistry.views[name] = wrapped;
if (!view.parentView && !view.isComponentView) {
nestedRegistry.views[name] = wrapped;
}
if (typeof view.destroy === 'function') {
wrapped.destroy = _.bind(view.destroy, view);
view.destroy = _.bind(function() {
var name = this.obj.getDebugName();
delete nestedRegistry.views[name];
delete flatRegistry.views[name];
updateNestedModels();
triggerChange();
this.destroy();
}, wrapped);
}
updateNestedModels();
triggerChange();
}
|
javascript
|
function registerView(view) {
var name = view.getDebugName();
var wrapped = new RegistryWrapper(view, 'views');
flatRegistry.views[name] = wrapped;
if (!view.parentView && !view.isComponentView) {
nestedRegistry.views[name] = wrapped;
}
if (typeof view.destroy === 'function') {
wrapped.destroy = _.bind(view.destroy, view);
view.destroy = _.bind(function() {
var name = this.obj.getDebugName();
delete nestedRegistry.views[name];
delete flatRegistry.views[name];
updateNestedModels();
triggerChange();
this.destroy();
}, wrapped);
}
updateNestedModels();
triggerChange();
}
|
[
"function",
"registerView",
"(",
"view",
")",
"{",
"var",
"name",
"=",
"view",
".",
"getDebugName",
"(",
")",
";",
"var",
"wrapped",
"=",
"new",
"RegistryWrapper",
"(",
"view",
",",
"'views'",
")",
";",
"flatRegistry",
".",
"views",
"[",
"name",
"]",
"=",
"wrapped",
";",
"if",
"(",
"!",
"view",
".",
"parentView",
"&&",
"!",
"view",
".",
"isComponentView",
")",
"{",
"nestedRegistry",
".",
"views",
"[",
"name",
"]",
"=",
"wrapped",
";",
"}",
"if",
"(",
"typeof",
"view",
".",
"destroy",
"===",
"'function'",
")",
"{",
"wrapped",
".",
"destroy",
"=",
"_",
".",
"bind",
"(",
"view",
".",
"destroy",
",",
"view",
")",
";",
"view",
".",
"destroy",
"=",
"_",
".",
"bind",
"(",
"function",
"(",
")",
"{",
"var",
"name",
"=",
"this",
".",
"obj",
".",
"getDebugName",
"(",
")",
";",
"delete",
"nestedRegistry",
".",
"views",
"[",
"name",
"]",
";",
"delete",
"flatRegistry",
".",
"views",
"[",
"name",
"]",
";",
"updateNestedModels",
"(",
")",
";",
"triggerChange",
"(",
")",
";",
"this",
".",
"destroy",
"(",
")",
";",
"}",
",",
"wrapped",
")",
";",
"}",
"updateNestedModels",
"(",
")",
";",
"triggerChange",
"(",
")",
";",
"}"
] |
Adds a View to the registry
@param {Object} view View to register
|
[
"Adds",
"a",
"View",
"to",
"the",
"registry"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/registry.js#L42-L62
|
train
|
wayfair/tungstenjs
|
src/debug/registry.js
|
registerModel
|
function registerModel(model) {
var name = model.getDebugName();
var wrapped = flatRegistry.models[name] = new RegistryWrapper(model, 'models');
if (typeof model.destroy === 'function') {
wrapped.destroy = _.bind(model.destroy, model);
model.destroy = _.bind(function() {
var name = this.obj.getDebugName();
delete flatRegistry.models[name];
updateNestedModels();
triggerChange();
this.destroy();
}, wrapped);
}
triggerChange();
}
|
javascript
|
function registerModel(model) {
var name = model.getDebugName();
var wrapped = flatRegistry.models[name] = new RegistryWrapper(model, 'models');
if (typeof model.destroy === 'function') {
wrapped.destroy = _.bind(model.destroy, model);
model.destroy = _.bind(function() {
var name = this.obj.getDebugName();
delete flatRegistry.models[name];
updateNestedModels();
triggerChange();
this.destroy();
}, wrapped);
}
triggerChange();
}
|
[
"function",
"registerModel",
"(",
"model",
")",
"{",
"var",
"name",
"=",
"model",
".",
"getDebugName",
"(",
")",
";",
"var",
"wrapped",
"=",
"flatRegistry",
".",
"models",
"[",
"name",
"]",
"=",
"new",
"RegistryWrapper",
"(",
"model",
",",
"'models'",
")",
";",
"if",
"(",
"typeof",
"model",
".",
"destroy",
"===",
"'function'",
")",
"{",
"wrapped",
".",
"destroy",
"=",
"_",
".",
"bind",
"(",
"model",
".",
"destroy",
",",
"model",
")",
";",
"model",
".",
"destroy",
"=",
"_",
".",
"bind",
"(",
"function",
"(",
")",
"{",
"var",
"name",
"=",
"this",
".",
"obj",
".",
"getDebugName",
"(",
")",
";",
"delete",
"flatRegistry",
".",
"models",
"[",
"name",
"]",
";",
"updateNestedModels",
"(",
")",
";",
"triggerChange",
"(",
")",
";",
"this",
".",
"destroy",
"(",
")",
";",
"}",
",",
"wrapped",
")",
";",
"}",
"triggerChange",
"(",
")",
";",
"}"
] |
Adds a Model to the registry
@param {Object} model Model to register
|
[
"Adds",
"a",
"Model",
"to",
"the",
"registry"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/registry.js#L69-L83
|
train
|
buttonwoodcx/bcx-aurelia-dnd
|
src/dnd-service.js
|
injectStyles
|
function injectStyles() {
if (_stylesInjected) return;
_stylesInjected = true;
let node = doc.createElement('style');
node.innerHTML = css;
node.type = 'text/css';
if (doc.head.childNodes.length > 0) {
doc.head.insertBefore(node, doc.head.childNodes[0]);
} else {
doc.head.appendChild(node);
}
}
|
javascript
|
function injectStyles() {
if (_stylesInjected) return;
_stylesInjected = true;
let node = doc.createElement('style');
node.innerHTML = css;
node.type = 'text/css';
if (doc.head.childNodes.length > 0) {
doc.head.insertBefore(node, doc.head.childNodes[0]);
} else {
doc.head.appendChild(node);
}
}
|
[
"function",
"injectStyles",
"(",
")",
"{",
"if",
"(",
"_stylesInjected",
")",
"return",
";",
"_stylesInjected",
"=",
"true",
";",
"let",
"node",
"=",
"doc",
".",
"createElement",
"(",
"'style'",
")",
";",
"node",
".",
"innerHTML",
"=",
"css",
";",
"node",
".",
"type",
"=",
"'text/css'",
";",
"if",
"(",
"doc",
".",
"head",
".",
"childNodes",
".",
"length",
">",
"0",
")",
"{",
"doc",
".",
"head",
".",
"insertBefore",
"(",
"node",
",",
"doc",
".",
"head",
".",
"childNodes",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"doc",
".",
"head",
".",
"appendChild",
"(",
"node",
")",
";",
"}",
"}"
] |
copied from aurelia-pal-browser
|
[
"copied",
"from",
"aurelia",
"-",
"pal",
"-",
"browser"
] |
55f90a9cb3e234591dec8aa27bf080ad5473b6fb
|
https://github.com/buttonwoodcx/bcx-aurelia-dnd/blob/55f90a9cb3e234591dec8aa27bf080ad5473b6fb/src/dnd-service.js#L59-L72
|
train
|
wayfair/tungstenjs
|
plugins/tungsten-event-outside/index.js
|
getOutsideHandler
|
function getOutsideHandler(method) {
var lastEventId = null;
/**
* If the event that is firing is not the same as the event that was fired on the element
* execute the method
* @param {object} evt the event that's firing
*/
var documentHandler = function(evt) {
if (evt.eventId !== lastEventId) {
method(evt);
}
};
/**
* Store the id of the event for comparison when documentHandler fires
* @param {object} evt the event firing on the element
*/
var elementHandler = function(evt) {
lastEventId = evt.eventId;
};
return {
documentHandler: documentHandler,
elementHandler: elementHandler
};
}
|
javascript
|
function getOutsideHandler(method) {
var lastEventId = null;
/**
* If the event that is firing is not the same as the event that was fired on the element
* execute the method
* @param {object} evt the event that's firing
*/
var documentHandler = function(evt) {
if (evt.eventId !== lastEventId) {
method(evt);
}
};
/**
* Store the id of the event for comparison when documentHandler fires
* @param {object} evt the event firing on the element
*/
var elementHandler = function(evt) {
lastEventId = evt.eventId;
};
return {
documentHandler: documentHandler,
elementHandler: elementHandler
};
}
|
[
"function",
"getOutsideHandler",
"(",
"method",
")",
"{",
"var",
"lastEventId",
"=",
"null",
";",
"var",
"documentHandler",
"=",
"function",
"(",
"evt",
")",
"{",
"if",
"(",
"evt",
".",
"eventId",
"!==",
"lastEventId",
")",
"{",
"method",
"(",
"evt",
")",
";",
"}",
"}",
";",
"var",
"elementHandler",
"=",
"function",
"(",
"evt",
")",
"{",
"lastEventId",
"=",
"evt",
".",
"eventId",
";",
"}",
";",
"return",
"{",
"documentHandler",
":",
"documentHandler",
",",
"elementHandler",
":",
"elementHandler",
"}",
";",
"}"
] |
Track events firing on the element and document to determine if event is outside
@param {Function} method handler to execute when event fires outside of the element
@return {object} document and element handlers
|
[
"Track",
"events",
"firing",
"on",
"the",
"element",
"and",
"document",
"to",
"determine",
"if",
"event",
"is",
"outside"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/plugins/tungsten-event-outside/index.js#L12-L38
|
train
|
wayfair/tungstenjs
|
plugins/tungsten-event-intent/index.js
|
getIntentHandler
|
function getIntentHandler(method, options) {
var lastEvent = null;
var timeout = null;
var opts = extend({
intentDelay: 200
}, options);
var triggerIntent = function() {
method(lastEvent);
};
var startIntent = function(evt) {
lastEvent = evt;
clearTimeout(timeout);
timeout = setTimeout(triggerIntent, opts.intentDelay);
};
var stopIntent = function() {
lastEvent = null;
clearTimeout(timeout);
};
return {
startIntent: startIntent,
stopIntent: stopIntent
};
}
|
javascript
|
function getIntentHandler(method, options) {
var lastEvent = null;
var timeout = null;
var opts = extend({
intentDelay: 200
}, options);
var triggerIntent = function() {
method(lastEvent);
};
var startIntent = function(evt) {
lastEvent = evt;
clearTimeout(timeout);
timeout = setTimeout(triggerIntent, opts.intentDelay);
};
var stopIntent = function() {
lastEvent = null;
clearTimeout(timeout);
};
return {
startIntent: startIntent,
stopIntent: stopIntent
};
}
|
[
"function",
"getIntentHandler",
"(",
"method",
",",
"options",
")",
"{",
"var",
"lastEvent",
"=",
"null",
";",
"var",
"timeout",
"=",
"null",
";",
"var",
"opts",
"=",
"extend",
"(",
"{",
"intentDelay",
":",
"200",
"}",
",",
"options",
")",
";",
"var",
"triggerIntent",
"=",
"function",
"(",
")",
"{",
"method",
"(",
"lastEvent",
")",
";",
"}",
";",
"var",
"startIntent",
"=",
"function",
"(",
"evt",
")",
"{",
"lastEvent",
"=",
"evt",
";",
"clearTimeout",
"(",
"timeout",
")",
";",
"timeout",
"=",
"setTimeout",
"(",
"triggerIntent",
",",
"opts",
".",
"intentDelay",
")",
";",
"}",
";",
"var",
"stopIntent",
"=",
"function",
"(",
")",
"{",
"lastEvent",
"=",
"null",
";",
"clearTimeout",
"(",
"timeout",
")",
";",
"}",
";",
"return",
"{",
"startIntent",
":",
"startIntent",
",",
"stopIntent",
":",
"stopIntent",
"}",
";",
"}"
] |
Get handler for start and stop of intent events
@param {function} method [description]
@param {object} options - intent options
@return {object} - the start and stop intent events
|
[
"Get",
"handler",
"for",
"start",
"and",
"stop",
"of",
"intent",
"events"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/plugins/tungsten-event-intent/index.js#L25-L52
|
train
|
wayfair/tungstenjs
|
src/template/compiler/parser.js
|
function(text) {
let el = stack.peek();
if (el && el.type === types.COMMENT) {
stack.createObject(text);
stack.closeElement(el);
} else {
stack.createComment(text);
}
}
|
javascript
|
function(text) {
let el = stack.peek();
if (el && el.type === types.COMMENT) {
stack.createObject(text);
stack.closeElement(el);
} else {
stack.createComment(text);
}
}
|
[
"function",
"(",
"text",
")",
"{",
"let",
"el",
"=",
"stack",
".",
"peek",
"(",
")",
";",
"if",
"(",
"el",
"&&",
"el",
".",
"type",
"===",
"types",
".",
"COMMENT",
")",
"{",
"stack",
".",
"createObject",
"(",
"text",
")",
";",
"stack",
".",
"closeElement",
"(",
"el",
")",
";",
"}",
"else",
"{",
"stack",
".",
"createComment",
"(",
"text",
")",
";",
"}",
"}"
] |
Handles HTML comments
@param {} text [description]
|
[
"Handles",
"HTML",
"comments"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/compiler/parser.js#L303-L311
|
train
|
|
wayfair/tungstenjs
|
src/debug/window_manager.js
|
pollForParentOpen
|
function pollForParentOpen() {
/* jshint validthis:true */
if (this.pollNum > 0) {
if (this.opener && !this.opener.OLD_TUNGSTEN_MASTER && typeof this.opener.attachTungstenDebugPane === 'function') {
this.opener.attachTungstenDebugPane(this);
} else {
this.pollNum -= 1;
this.loadingCounter.textContent = '' + this.pollNum;
this.setTimeout(pollForParentOpen, POLL_INTERVAL);
}
} else {
this.window.close();
}
}
|
javascript
|
function pollForParentOpen() {
/* jshint validthis:true */
if (this.pollNum > 0) {
if (this.opener && !this.opener.OLD_TUNGSTEN_MASTER && typeof this.opener.attachTungstenDebugPane === 'function') {
this.opener.attachTungstenDebugPane(this);
} else {
this.pollNum -= 1;
this.loadingCounter.textContent = '' + this.pollNum;
this.setTimeout(pollForParentOpen, POLL_INTERVAL);
}
} else {
this.window.close();
}
}
|
[
"function",
"pollForParentOpen",
"(",
")",
"{",
"if",
"(",
"this",
".",
"pollNum",
">",
"0",
")",
"{",
"if",
"(",
"this",
".",
"opener",
"&&",
"!",
"this",
".",
"opener",
".",
"OLD_TUNGSTEN_MASTER",
"&&",
"typeof",
"this",
".",
"opener",
".",
"attachTungstenDebugPane",
"===",
"'function'",
")",
"{",
"this",
".",
"opener",
".",
"attachTungstenDebugPane",
"(",
"this",
")",
";",
"}",
"else",
"{",
"this",
".",
"pollNum",
"-=",
"1",
";",
"this",
".",
"loadingCounter",
".",
"textContent",
"=",
"''",
"+",
"this",
".",
"pollNum",
";",
"this",
".",
"setTimeout",
"(",
"pollForParentOpen",
",",
"POLL_INTERVAL",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"window",
".",
"close",
"(",
")",
";",
"}",
"}"
] |
When the parent window unloads, the debug window polls to reattach
Will auto-close if the parent window hasn't reappeared after 30s
|
[
"When",
"the",
"parent",
"window",
"unloads",
"the",
"debug",
"window",
"polls",
"to",
"reattach",
"Will",
"auto",
"-",
"close",
"if",
"the",
"parent",
"window",
"hasn",
"t",
"reappeared",
"after",
"30s"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/window_manager.js#L191-L204
|
train
|
wayfair/tungstenjs
|
src/event/events_core.js
|
function(nativeEvent, typeOverride) {
var evt = eventWrapper(nativeEvent);
if (typeOverride !== undefined) {
evt.type = typeOverride;
}
var activePath = [];
var elem = evt.target;
var events;
/**
* Handle calling bound functions with the proper targets set
* @TODO move this outside eventHandler
* @param {Element} elem DOM element to trigger events on
* @param {Array<Function>} funcArr Array of bound functions to trigger
* @param {String} selector Selector string that the event was bound to
* @param {Element} delegate DOM element this event was bound to for delegation
*/
var triggerEventFunctions = function(elem, funcArr, selector, delegate) {
var result;
evt.currentTarget = elem;
evt.delegateTarget = delegate;
for (var i = 0; i < funcArr.length; i++) {
if (!evt.isImmediatePropagationStopped()) {
evt.vEvent = {
handler: funcArr[i].method,
selector: selector
};
result = funcArr[i].method(evt);
if (result === false) {
falseHandler(evt);
}
}
}
};
/**
* Checks if bound events should fire
* @param {Object} typeEvents Event object of events to check if should fire
*/
var checkEvents = function(typeEvents) {
var elemClasses, elemClass;
// Iterate over previously passed elements to check for any delegated events
var activePathLength = activePath.length;
for (var i = 0; i < activePathLength; i++) {
elemClasses = activePath[i].classes;
// Once stopPropagation is called stop
if (!evt.isPropagationStopped()) {
var elemClassesLength = elemClasses.length;
for (var j = 0; j < elemClassesLength; j++) {
elemClass = elemClasses[j];
if (typeEvents[elemClass]) {
triggerEventFunctions(activePath[i].element, typeEvents[elemClass], elemClass, elem);
}
}
}
}
// Check for any non-delegated events
if (!evt.isPropagationStopped() && typeEvents.self) {
triggerEventFunctions(elem, typeEvents.self);
}
};
while (elem && !evt.isPropagationStopped()) {
events = module.exports.getEvents(elem);
if (events) {
// Generic events
if (events[evt.type]) {
checkEvents(events[evt.type]);
}
}
// Create array of class names that match our pattern to check for delegation later
var elemActiveClasses = module.exports.getActiveClasses(elem);
if (elemActiveClasses.length) {
activePath.push({
element: elem,
classes: elemActiveClasses
});
}
elem = elem.parentNode;
}
}
|
javascript
|
function(nativeEvent, typeOverride) {
var evt = eventWrapper(nativeEvent);
if (typeOverride !== undefined) {
evt.type = typeOverride;
}
var activePath = [];
var elem = evt.target;
var events;
/**
* Handle calling bound functions with the proper targets set
* @TODO move this outside eventHandler
* @param {Element} elem DOM element to trigger events on
* @param {Array<Function>} funcArr Array of bound functions to trigger
* @param {String} selector Selector string that the event was bound to
* @param {Element} delegate DOM element this event was bound to for delegation
*/
var triggerEventFunctions = function(elem, funcArr, selector, delegate) {
var result;
evt.currentTarget = elem;
evt.delegateTarget = delegate;
for (var i = 0; i < funcArr.length; i++) {
if (!evt.isImmediatePropagationStopped()) {
evt.vEvent = {
handler: funcArr[i].method,
selector: selector
};
result = funcArr[i].method(evt);
if (result === false) {
falseHandler(evt);
}
}
}
};
/**
* Checks if bound events should fire
* @param {Object} typeEvents Event object of events to check if should fire
*/
var checkEvents = function(typeEvents) {
var elemClasses, elemClass;
// Iterate over previously passed elements to check for any delegated events
var activePathLength = activePath.length;
for (var i = 0; i < activePathLength; i++) {
elemClasses = activePath[i].classes;
// Once stopPropagation is called stop
if (!evt.isPropagationStopped()) {
var elemClassesLength = elemClasses.length;
for (var j = 0; j < elemClassesLength; j++) {
elemClass = elemClasses[j];
if (typeEvents[elemClass]) {
triggerEventFunctions(activePath[i].element, typeEvents[elemClass], elemClass, elem);
}
}
}
}
// Check for any non-delegated events
if (!evt.isPropagationStopped() && typeEvents.self) {
triggerEventFunctions(elem, typeEvents.self);
}
};
while (elem && !evt.isPropagationStopped()) {
events = module.exports.getEvents(elem);
if (events) {
// Generic events
if (events[evt.type]) {
checkEvents(events[evt.type]);
}
}
// Create array of class names that match our pattern to check for delegation later
var elemActiveClasses = module.exports.getActiveClasses(elem);
if (elemActiveClasses.length) {
activePath.push({
element: elem,
classes: elemActiveClasses
});
}
elem = elem.parentNode;
}
}
|
[
"function",
"(",
"nativeEvent",
",",
"typeOverride",
")",
"{",
"var",
"evt",
"=",
"eventWrapper",
"(",
"nativeEvent",
")",
";",
"if",
"(",
"typeOverride",
"!==",
"undefined",
")",
"{",
"evt",
".",
"type",
"=",
"typeOverride",
";",
"}",
"var",
"activePath",
"=",
"[",
"]",
";",
"var",
"elem",
"=",
"evt",
".",
"target",
";",
"var",
"events",
";",
"var",
"triggerEventFunctions",
"=",
"function",
"(",
"elem",
",",
"funcArr",
",",
"selector",
",",
"delegate",
")",
"{",
"var",
"result",
";",
"evt",
".",
"currentTarget",
"=",
"elem",
";",
"evt",
".",
"delegateTarget",
"=",
"delegate",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"funcArr",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"evt",
".",
"isImmediatePropagationStopped",
"(",
")",
")",
"{",
"evt",
".",
"vEvent",
"=",
"{",
"handler",
":",
"funcArr",
"[",
"i",
"]",
".",
"method",
",",
"selector",
":",
"selector",
"}",
";",
"result",
"=",
"funcArr",
"[",
"i",
"]",
".",
"method",
"(",
"evt",
")",
";",
"if",
"(",
"result",
"===",
"false",
")",
"{",
"falseHandler",
"(",
"evt",
")",
";",
"}",
"}",
"}",
"}",
";",
"var",
"checkEvents",
"=",
"function",
"(",
"typeEvents",
")",
"{",
"var",
"elemClasses",
",",
"elemClass",
";",
"var",
"activePathLength",
"=",
"activePath",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"activePathLength",
";",
"i",
"++",
")",
"{",
"elemClasses",
"=",
"activePath",
"[",
"i",
"]",
".",
"classes",
";",
"if",
"(",
"!",
"evt",
".",
"isPropagationStopped",
"(",
")",
")",
"{",
"var",
"elemClassesLength",
"=",
"elemClasses",
".",
"length",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"elemClassesLength",
";",
"j",
"++",
")",
"{",
"elemClass",
"=",
"elemClasses",
"[",
"j",
"]",
";",
"if",
"(",
"typeEvents",
"[",
"elemClass",
"]",
")",
"{",
"triggerEventFunctions",
"(",
"activePath",
"[",
"i",
"]",
".",
"element",
",",
"typeEvents",
"[",
"elemClass",
"]",
",",
"elemClass",
",",
"elem",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"evt",
".",
"isPropagationStopped",
"(",
")",
"&&",
"typeEvents",
".",
"self",
")",
"{",
"triggerEventFunctions",
"(",
"elem",
",",
"typeEvents",
".",
"self",
")",
";",
"}",
"}",
";",
"while",
"(",
"elem",
"&&",
"!",
"evt",
".",
"isPropagationStopped",
"(",
")",
")",
"{",
"events",
"=",
"module",
".",
"exports",
".",
"getEvents",
"(",
"elem",
")",
";",
"if",
"(",
"events",
")",
"{",
"if",
"(",
"events",
"[",
"evt",
".",
"type",
"]",
")",
"{",
"checkEvents",
"(",
"events",
"[",
"evt",
".",
"type",
"]",
")",
";",
"}",
"}",
"var",
"elemActiveClasses",
"=",
"module",
".",
"exports",
".",
"getActiveClasses",
"(",
"elem",
")",
";",
"if",
"(",
"elemActiveClasses",
".",
"length",
")",
"{",
"activePath",
".",
"push",
"(",
"{",
"element",
":",
"elem",
",",
"classes",
":",
"elemActiveClasses",
"}",
")",
";",
"}",
"elem",
"=",
"elem",
".",
"parentNode",
";",
"}",
"}"
] |
Function bound to all global level events
|
[
"Function",
"bound",
"to",
"all",
"global",
"level",
"events"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/event/events_core.js#L186-L269
|
train
|
|
wayfair/tungstenjs
|
src/event/events_core.js
|
function(elem, funcArr, selector, delegate) {
var result;
evt.currentTarget = elem;
evt.delegateTarget = delegate;
for (var i = 0; i < funcArr.length; i++) {
if (!evt.isImmediatePropagationStopped()) {
evt.vEvent = {
handler: funcArr[i].method,
selector: selector
};
result = funcArr[i].method(evt);
if (result === false) {
falseHandler(evt);
}
}
}
}
|
javascript
|
function(elem, funcArr, selector, delegate) {
var result;
evt.currentTarget = elem;
evt.delegateTarget = delegate;
for (var i = 0; i < funcArr.length; i++) {
if (!evt.isImmediatePropagationStopped()) {
evt.vEvent = {
handler: funcArr[i].method,
selector: selector
};
result = funcArr[i].method(evt);
if (result === false) {
falseHandler(evt);
}
}
}
}
|
[
"function",
"(",
"elem",
",",
"funcArr",
",",
"selector",
",",
"delegate",
")",
"{",
"var",
"result",
";",
"evt",
".",
"currentTarget",
"=",
"elem",
";",
"evt",
".",
"delegateTarget",
"=",
"delegate",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"funcArr",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"evt",
".",
"isImmediatePropagationStopped",
"(",
")",
")",
"{",
"evt",
".",
"vEvent",
"=",
"{",
"handler",
":",
"funcArr",
"[",
"i",
"]",
".",
"method",
",",
"selector",
":",
"selector",
"}",
";",
"result",
"=",
"funcArr",
"[",
"i",
"]",
".",
"method",
"(",
"evt",
")",
";",
"if",
"(",
"result",
"===",
"false",
")",
"{",
"falseHandler",
"(",
"evt",
")",
";",
"}",
"}",
"}",
"}"
] |
Handle calling bound functions with the proper targets set
@TODO move this outside eventHandler
@param {Element} elem DOM element to trigger events on
@param {Array<Function>} funcArr Array of bound functions to trigger
@param {String} selector Selector string that the event was bound to
@param {Element} delegate DOM element this event was bound to for delegation
|
[
"Handle",
"calling",
"bound",
"functions",
"with",
"the",
"proper",
"targets",
"set"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/event/events_core.js#L203-L220
|
train
|
|
wayfair/tungstenjs
|
src/event/events_core.js
|
function(typeEvents) {
var elemClasses, elemClass;
// Iterate over previously passed elements to check for any delegated events
var activePathLength = activePath.length;
for (var i = 0; i < activePathLength; i++) {
elemClasses = activePath[i].classes;
// Once stopPropagation is called stop
if (!evt.isPropagationStopped()) {
var elemClassesLength = elemClasses.length;
for (var j = 0; j < elemClassesLength; j++) {
elemClass = elemClasses[j];
if (typeEvents[elemClass]) {
triggerEventFunctions(activePath[i].element, typeEvents[elemClass], elemClass, elem);
}
}
}
}
// Check for any non-delegated events
if (!evt.isPropagationStopped() && typeEvents.self) {
triggerEventFunctions(elem, typeEvents.self);
}
}
|
javascript
|
function(typeEvents) {
var elemClasses, elemClass;
// Iterate over previously passed elements to check for any delegated events
var activePathLength = activePath.length;
for (var i = 0; i < activePathLength; i++) {
elemClasses = activePath[i].classes;
// Once stopPropagation is called stop
if (!evt.isPropagationStopped()) {
var elemClassesLength = elemClasses.length;
for (var j = 0; j < elemClassesLength; j++) {
elemClass = elemClasses[j];
if (typeEvents[elemClass]) {
triggerEventFunctions(activePath[i].element, typeEvents[elemClass], elemClass, elem);
}
}
}
}
// Check for any non-delegated events
if (!evt.isPropagationStopped() && typeEvents.self) {
triggerEventFunctions(elem, typeEvents.self);
}
}
|
[
"function",
"(",
"typeEvents",
")",
"{",
"var",
"elemClasses",
",",
"elemClass",
";",
"var",
"activePathLength",
"=",
"activePath",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"activePathLength",
";",
"i",
"++",
")",
"{",
"elemClasses",
"=",
"activePath",
"[",
"i",
"]",
".",
"classes",
";",
"if",
"(",
"!",
"evt",
".",
"isPropagationStopped",
"(",
")",
")",
"{",
"var",
"elemClassesLength",
"=",
"elemClasses",
".",
"length",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"elemClassesLength",
";",
"j",
"++",
")",
"{",
"elemClass",
"=",
"elemClasses",
"[",
"j",
"]",
";",
"if",
"(",
"typeEvents",
"[",
"elemClass",
"]",
")",
"{",
"triggerEventFunctions",
"(",
"activePath",
"[",
"i",
"]",
".",
"element",
",",
"typeEvents",
"[",
"elemClass",
"]",
",",
"elemClass",
",",
"elem",
")",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"evt",
".",
"isPropagationStopped",
"(",
")",
"&&",
"typeEvents",
".",
"self",
")",
"{",
"triggerEventFunctions",
"(",
"elem",
",",
"typeEvents",
".",
"self",
")",
";",
"}",
"}"
] |
Checks if bound events should fire
@param {Object} typeEvents Event object of events to check if should fire
|
[
"Checks",
"if",
"bound",
"events",
"should",
"fire"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/event/events_core.js#L226-L249
|
train
|
|
wayfair/tungstenjs
|
src/event/events_core.js
|
function(eventName, handler, elem) {
if (elem.addEventListener) {
// Setting useCapture to true so that this virtual handler is always fired first
// Also handles events that don't bubble correctly like focus/blur
elem.addEventListener(eventName, handler, true);
} else {
elem.attachEvent('on' + eventName, handler);
}
}
|
javascript
|
function(eventName, handler, elem) {
if (elem.addEventListener) {
// Setting useCapture to true so that this virtual handler is always fired first
// Also handles events that don't bubble correctly like focus/blur
elem.addEventListener(eventName, handler, true);
} else {
elem.attachEvent('on' + eventName, handler);
}
}
|
[
"function",
"(",
"eventName",
",",
"handler",
",",
"elem",
")",
"{",
"if",
"(",
"elem",
".",
"addEventListener",
")",
"{",
"elem",
".",
"addEventListener",
"(",
"eventName",
",",
"handler",
",",
"true",
")",
";",
"}",
"else",
"{",
"elem",
".",
"attachEvent",
"(",
"'on'",
"+",
"eventName",
",",
"handler",
")",
";",
"}",
"}"
] |
Wrapper to add event listener
@param {String} eventName Name of event to attach
@param {Function} handler Function to bind
@param {Element} elem Element to bind to
|
[
"Wrapper",
"to",
"add",
"event",
"listener"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/event/events_core.js#L278-L286
|
train
|
|
wayfair/tungstenjs
|
src/debug/registry_wrapper.js
|
getTrackableFunction
|
function getTrackableFunction(obj, name, trackedFunctions) {
var debugName = obj.getDebugName();
var originalFn = obj[name];
var fnName = `${debugName}.${name}`;
var instrumentedFn = instrumentFunction(fnName, originalFn);
var fn = function tungstenTrackingPassthrough() {
// Since objects are passed by reference, it can be updated without loosing reference
if (trackedFunctions[name]) {
return instrumentedFn.apply(this, arguments);
} else {
return originalFn.apply(this, arguments);
}
};
fn.original = originalFn;
return fn;
}
|
javascript
|
function getTrackableFunction(obj, name, trackedFunctions) {
var debugName = obj.getDebugName();
var originalFn = obj[name];
var fnName = `${debugName}.${name}`;
var instrumentedFn = instrumentFunction(fnName, originalFn);
var fn = function tungstenTrackingPassthrough() {
// Since objects are passed by reference, it can be updated without loosing reference
if (trackedFunctions[name]) {
return instrumentedFn.apply(this, arguments);
} else {
return originalFn.apply(this, arguments);
}
};
fn.original = originalFn;
return fn;
}
|
[
"function",
"getTrackableFunction",
"(",
"obj",
",",
"name",
",",
"trackedFunctions",
")",
"{",
"var",
"debugName",
"=",
"obj",
".",
"getDebugName",
"(",
")",
";",
"var",
"originalFn",
"=",
"obj",
"[",
"name",
"]",
";",
"var",
"fnName",
"=",
"`",
"${",
"debugName",
"}",
"${",
"name",
"}",
"`",
";",
"var",
"instrumentedFn",
"=",
"instrumentFunction",
"(",
"fnName",
",",
"originalFn",
")",
";",
"var",
"fn",
"=",
"function",
"tungstenTrackingPassthrough",
"(",
")",
"{",
"if",
"(",
"trackedFunctions",
"[",
"name",
"]",
")",
"{",
"return",
"instrumentedFn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"return",
"originalFn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"}",
";",
"fn",
".",
"original",
"=",
"originalFn",
";",
"return",
"fn",
";",
"}"
] |
Returns a passthrough function wrapping the passed in one
@param {Object} obj Class to override function for
@param {string} name Name of the function to override
@param {Object} trackedFunctions Object that maps which functions are currently tracked
@return {Function} Passthrough function
|
[
"Returns",
"a",
"passthrough",
"function",
"wrapping",
"the",
"passed",
"in",
"one"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/registry_wrapper.js#L16-L31
|
train
|
wayfair/tungstenjs
|
src/debug/registry_wrapper.js
|
RegistryWrapper
|
function RegistryWrapper(obj, type) {
this.obj = obj;
this.type = type;
this.selected = false;
this.collapsed = false;
this.customEvents = [];
this.debugName = obj.getDebugName();
if (obj.el) {
this.elString = Object.prototype.toString.call(obj.el);
}
if (typeof obj.getFunctions === 'function') {
this.trackedFunctions = {};
this.objectFunctions = obj.getFunctions(this.trackedFunctions, getTrackableFunction);
}
// Add history tracking to top level views
if (type === 'views' && typeof obj.getState === 'function' && !obj.parentView) {
this.state = new StateHistory(obj);
}
if (typeof obj.getEvents === 'function') {
this.objectEvents = obj.getEvents();
}
_.bindAll(this, 'isParent', 'getChildren');
}
|
javascript
|
function RegistryWrapper(obj, type) {
this.obj = obj;
this.type = type;
this.selected = false;
this.collapsed = false;
this.customEvents = [];
this.debugName = obj.getDebugName();
if (obj.el) {
this.elString = Object.prototype.toString.call(obj.el);
}
if (typeof obj.getFunctions === 'function') {
this.trackedFunctions = {};
this.objectFunctions = obj.getFunctions(this.trackedFunctions, getTrackableFunction);
}
// Add history tracking to top level views
if (type === 'views' && typeof obj.getState === 'function' && !obj.parentView) {
this.state = new StateHistory(obj);
}
if (typeof obj.getEvents === 'function') {
this.objectEvents = obj.getEvents();
}
_.bindAll(this, 'isParent', 'getChildren');
}
|
[
"function",
"RegistryWrapper",
"(",
"obj",
",",
"type",
")",
"{",
"this",
".",
"obj",
"=",
"obj",
";",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"selected",
"=",
"false",
";",
"this",
".",
"collapsed",
"=",
"false",
";",
"this",
".",
"customEvents",
"=",
"[",
"]",
";",
"this",
".",
"debugName",
"=",
"obj",
".",
"getDebugName",
"(",
")",
";",
"if",
"(",
"obj",
".",
"el",
")",
"{",
"this",
".",
"elString",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"obj",
".",
"el",
")",
";",
"}",
"if",
"(",
"typeof",
"obj",
".",
"getFunctions",
"===",
"'function'",
")",
"{",
"this",
".",
"trackedFunctions",
"=",
"{",
"}",
";",
"this",
".",
"objectFunctions",
"=",
"obj",
".",
"getFunctions",
"(",
"this",
".",
"trackedFunctions",
",",
"getTrackableFunction",
")",
";",
"}",
"if",
"(",
"type",
"===",
"'views'",
"&&",
"typeof",
"obj",
".",
"getState",
"===",
"'function'",
"&&",
"!",
"obj",
".",
"parentView",
")",
"{",
"this",
".",
"state",
"=",
"new",
"StateHistory",
"(",
"obj",
")",
";",
"}",
"if",
"(",
"typeof",
"obj",
".",
"getEvents",
"===",
"'function'",
")",
"{",
"this",
".",
"objectEvents",
"=",
"obj",
".",
"getEvents",
"(",
")",
";",
"}",
"_",
".",
"bindAll",
"(",
"this",
",",
"'isParent'",
",",
"'getChildren'",
")",
";",
"}"
] |
Object to wrap Tungsten adaptor objects
Allows us to modify data without risk of overriding adaptor properties
@param {Object} obj Adaptor object to wrap
@param {string} type Type of wrapped object
|
[
"Object",
"to",
"wrap",
"Tungsten",
"adaptor",
"objects",
"Allows",
"us",
"to",
"modify",
"data",
"without",
"risk",
"of",
"overriding",
"adaptor",
"properties"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/registry_wrapper.js#L40-L69
|
train
|
wayfair/tungstenjs
|
src/template/process_properties.js
|
transformPropertyName
|
function transformPropertyName(attributeName) {
if (propertiesToTransform[attributeName]) {
return propertiesToTransform[attributeName];
}
if (nonTransformedProperties[attributeName] !== true) {
return false;
}
return attributeName;
}
|
javascript
|
function transformPropertyName(attributeName) {
if (propertiesToTransform[attributeName]) {
return propertiesToTransform[attributeName];
}
if (nonTransformedProperties[attributeName] !== true) {
return false;
}
return attributeName;
}
|
[
"function",
"transformPropertyName",
"(",
"attributeName",
")",
"{",
"if",
"(",
"propertiesToTransform",
"[",
"attributeName",
"]",
")",
"{",
"return",
"propertiesToTransform",
"[",
"attributeName",
"]",
";",
"}",
"if",
"(",
"nonTransformedProperties",
"[",
"attributeName",
"]",
"!==",
"true",
")",
"{",
"return",
"false",
";",
"}",
"return",
"attributeName",
";",
"}"
] |
Returns property name to use or false if it should be treated as attribute
@param {String} attributeName Attribute to assign
@return {String|Boolean} False if it should be an attribute, otherwise property name
|
[
"Returns",
"property",
"name",
"to",
"use",
"or",
"false",
"if",
"it",
"should",
"be",
"treated",
"as",
"attribute"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/process_properties.js#L97-L105
|
train
|
wayfair/tungstenjs
|
src/template/adaptor.js
|
registerWidget
|
function registerWidget(name, constructor) {
if (typeof name !== 'string' ||
typeof constructor !== 'function' ||
typeof constructor.getTemplate !== 'function' ||
constructor.prototype.type !== 'Widget') {
throw 'Invalid arguments passed for registerWidget';
}
widgets[name] = constructor;
}
|
javascript
|
function registerWidget(name, constructor) {
if (typeof name !== 'string' ||
typeof constructor !== 'function' ||
typeof constructor.getTemplate !== 'function' ||
constructor.prototype.type !== 'Widget') {
throw 'Invalid arguments passed for registerWidget';
}
widgets[name] = constructor;
}
|
[
"function",
"registerWidget",
"(",
"name",
",",
"constructor",
")",
"{",
"if",
"(",
"typeof",
"name",
"!==",
"'string'",
"||",
"typeof",
"constructor",
"!==",
"'function'",
"||",
"typeof",
"constructor",
".",
"getTemplate",
"!==",
"'function'",
"||",
"constructor",
".",
"prototype",
".",
"type",
"!==",
"'Widget'",
")",
"{",
"throw",
"'Invalid arguments passed for registerWidget'",
";",
"}",
"widgets",
"[",
"name",
"]",
"=",
"constructor",
";",
"}"
] |
Public function to register Widgets for the template
These are similiar to child views, but don't have their own views or models
These are transformed on the template during the attach phase
@param {String} name Mustache key to intercept
@param {Function} constructor Widget constructor to inject
|
[
"Public",
"function",
"to",
"register",
"Widgets",
"for",
"the",
"template",
"These",
"are",
"similiar",
"to",
"child",
"views",
"but",
"don",
"t",
"have",
"their",
"own",
"views",
"or",
"models",
"These",
"are",
"transformed",
"on",
"the",
"template",
"during",
"the",
"attach",
"phase"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/adaptor.js#L24-L32
|
train
|
wayfair/tungstenjs
|
src/template/adaptor.js
|
parseStringAttrs
|
function parseStringAttrs(templates, context) {
var stringAttrs = '';
var toString = new ToString(true, true);
for (var i = 0; i < templates.length; i++) {
toString.clear();
render(toString, templates[i], context);
stringAttrs += ' ' + toString.getOutput() + ' ';
}
if (whitespaceOnlyRegex.test(stringAttrs)) {
return null;
}
var node = htmlParser('<div ' + stringAttrs + '></div>');
return node.properties.attributes;
}
|
javascript
|
function parseStringAttrs(templates, context) {
var stringAttrs = '';
var toString = new ToString(true, true);
for (var i = 0; i < templates.length; i++) {
toString.clear();
render(toString, templates[i], context);
stringAttrs += ' ' + toString.getOutput() + ' ';
}
if (whitespaceOnlyRegex.test(stringAttrs)) {
return null;
}
var node = htmlParser('<div ' + stringAttrs + '></div>');
return node.properties.attributes;
}
|
[
"function",
"parseStringAttrs",
"(",
"templates",
",",
"context",
")",
"{",
"var",
"stringAttrs",
"=",
"''",
";",
"var",
"toString",
"=",
"new",
"ToString",
"(",
"true",
",",
"true",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"templates",
".",
"length",
";",
"i",
"++",
")",
"{",
"toString",
".",
"clear",
"(",
")",
";",
"render",
"(",
"toString",
",",
"templates",
"[",
"i",
"]",
",",
"context",
")",
";",
"stringAttrs",
"+=",
"' '",
"+",
"toString",
".",
"getOutput",
"(",
")",
"+",
"' '",
";",
"}",
"if",
"(",
"whitespaceOnlyRegex",
".",
"test",
"(",
"stringAttrs",
")",
")",
"{",
"return",
"null",
";",
"}",
"var",
"node",
"=",
"htmlParser",
"(",
"'<div '",
"+",
"stringAttrs",
"+",
"'></div>'",
")",
";",
"return",
"node",
".",
"properties",
".",
"attributes",
";",
"}"
] |
Used to parse loose interpolators inside a opening tag
@param {Object} templates Template object
@param {Context} context current Context to evaluate in
@return {Object} Parsed dictionary of attribute names/values
|
[
"Used",
"to",
"parse",
"loose",
"interpolators",
"inside",
"a",
"opening",
"tag"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/adaptor.js#L43-L56
|
train
|
wayfair/tungstenjs
|
src/template/adaptor.js
|
renderAttributeString
|
function renderAttributeString(values, context) {
if (typeof values === 'string' || typeof values === 'boolean') {
return values;
}
var buffer = '';
var toString = new ToString();
for (var i = 0; i < values.length; i++) {
toString.clear();
render(toString, values[i], context);
buffer += toString.getOutput();
}
return buffer;
}
|
javascript
|
function renderAttributeString(values, context) {
if (typeof values === 'string' || typeof values === 'boolean') {
return values;
}
var buffer = '';
var toString = new ToString();
for (var i = 0; i < values.length; i++) {
toString.clear();
render(toString, values[i], context);
buffer += toString.getOutput();
}
return buffer;
}
|
[
"function",
"renderAttributeString",
"(",
"values",
",",
"context",
")",
"{",
"if",
"(",
"typeof",
"values",
"===",
"'string'",
"||",
"typeof",
"values",
"===",
"'boolean'",
")",
"{",
"return",
"values",
";",
"}",
"var",
"buffer",
"=",
"''",
";",
"var",
"toString",
"=",
"new",
"ToString",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"values",
".",
"length",
";",
"i",
"++",
")",
"{",
"toString",
".",
"clear",
"(",
")",
";",
"render",
"(",
"toString",
",",
"values",
"[",
"i",
"]",
",",
"context",
")",
";",
"buffer",
"+=",
"toString",
".",
"getOutput",
"(",
")",
";",
"}",
"return",
"buffer",
";",
"}"
] |
Render the value of an element's attribute
@param {String|Object} values VTree object for the attribute value
@param {Context} context current Context to evaluate in
@return {String} String value for the attribute
|
[
"Render",
"the",
"value",
"of",
"an",
"element",
"s",
"attribute"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/adaptor.js#L64-L78
|
train
|
wayfair/tungstenjs
|
adaptors/backbone/base_model.js
|
function() {
var properties = {
normal: [],
relational: [],
derived: []
};
var privateProps = this._private || {};
var relations = _.result(this, 'relations') || {};
var derived = _.result(this, 'derived') || {};
var isEditable = function(value) {
if (!_.isObject(value)) {
return true;
} else if (_.isArray(value)) {
var result = true;
_.each(value, function(i) {
result = result && isEditable(i);
});
return result;
} else {
try {
JSON.stringify(value);
return true;
} catch (ex) {
return false;
}
}
};
_.each(this.attributes, function(value, key) {
if (privateProps[key]) {
return;
}
var prop;
if (relations && relations[key]) {
properties.relational.push({
key: key,
data: {
isRelation: true,
name: value.getDebugName()
}
});
} else if (derived && derived[key]) {
properties.derived.push({
key: key,
data: {
isDerived: derived[key],
value: value,
displayValue: isEditable(value) ? JSON.stringify(value) : Object.prototype.toString.call(value)
}
});
} else {
prop = {
key: key,
data: {
isEditable: isEditable(value),
isEditing: false,
isRemovable: true,
value: value
}
};
prop.data.displayValue = prop.data.isEditable ? JSON.stringify(value) : Object.prototype.toString.call(value);
properties.normal.push(prop);
}
});
properties.normal = _.sortBy(properties.normal, 'key');
properties.relational = _.sortBy(properties.relational, 'key');
properties.derived = _.sortBy(properties.derived, 'key');
return properties;
}
|
javascript
|
function() {
var properties = {
normal: [],
relational: [],
derived: []
};
var privateProps = this._private || {};
var relations = _.result(this, 'relations') || {};
var derived = _.result(this, 'derived') || {};
var isEditable = function(value) {
if (!_.isObject(value)) {
return true;
} else if (_.isArray(value)) {
var result = true;
_.each(value, function(i) {
result = result && isEditable(i);
});
return result;
} else {
try {
JSON.stringify(value);
return true;
} catch (ex) {
return false;
}
}
};
_.each(this.attributes, function(value, key) {
if (privateProps[key]) {
return;
}
var prop;
if (relations && relations[key]) {
properties.relational.push({
key: key,
data: {
isRelation: true,
name: value.getDebugName()
}
});
} else if (derived && derived[key]) {
properties.derived.push({
key: key,
data: {
isDerived: derived[key],
value: value,
displayValue: isEditable(value) ? JSON.stringify(value) : Object.prototype.toString.call(value)
}
});
} else {
prop = {
key: key,
data: {
isEditable: isEditable(value),
isEditing: false,
isRemovable: true,
value: value
}
};
prop.data.displayValue = prop.data.isEditable ? JSON.stringify(value) : Object.prototype.toString.call(value);
properties.normal.push(prop);
}
});
properties.normal = _.sortBy(properties.normal, 'key');
properties.relational = _.sortBy(properties.relational, 'key');
properties.derived = _.sortBy(properties.derived, 'key');
return properties;
}
|
[
"function",
"(",
")",
"{",
"var",
"properties",
"=",
"{",
"normal",
":",
"[",
"]",
",",
"relational",
":",
"[",
"]",
",",
"derived",
":",
"[",
"]",
"}",
";",
"var",
"privateProps",
"=",
"this",
".",
"_private",
"||",
"{",
"}",
";",
"var",
"relations",
"=",
"_",
".",
"result",
"(",
"this",
",",
"'relations'",
")",
"||",
"{",
"}",
";",
"var",
"derived",
"=",
"_",
".",
"result",
"(",
"this",
",",
"'derived'",
")",
"||",
"{",
"}",
";",
"var",
"isEditable",
"=",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"_",
".",
"isObject",
"(",
"value",
")",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"var",
"result",
"=",
"true",
";",
"_",
".",
"each",
"(",
"value",
",",
"function",
"(",
"i",
")",
"{",
"result",
"=",
"result",
"&&",
"isEditable",
"(",
"i",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}",
"else",
"{",
"try",
"{",
"JSON",
".",
"stringify",
"(",
"value",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
";",
"_",
".",
"each",
"(",
"this",
".",
"attributes",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"if",
"(",
"privateProps",
"[",
"key",
"]",
")",
"{",
"return",
";",
"}",
"var",
"prop",
";",
"if",
"(",
"relations",
"&&",
"relations",
"[",
"key",
"]",
")",
"{",
"properties",
".",
"relational",
".",
"push",
"(",
"{",
"key",
":",
"key",
",",
"data",
":",
"{",
"isRelation",
":",
"true",
",",
"name",
":",
"value",
".",
"getDebugName",
"(",
")",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"derived",
"&&",
"derived",
"[",
"key",
"]",
")",
"{",
"properties",
".",
"derived",
".",
"push",
"(",
"{",
"key",
":",
"key",
",",
"data",
":",
"{",
"isDerived",
":",
"derived",
"[",
"key",
"]",
",",
"value",
":",
"value",
",",
"displayValue",
":",
"isEditable",
"(",
"value",
")",
"?",
"JSON",
".",
"stringify",
"(",
"value",
")",
":",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
")",
"}",
"}",
")",
";",
"}",
"else",
"{",
"prop",
"=",
"{",
"key",
":",
"key",
",",
"data",
":",
"{",
"isEditable",
":",
"isEditable",
"(",
"value",
")",
",",
"isEditing",
":",
"false",
",",
"isRemovable",
":",
"true",
",",
"value",
":",
"value",
"}",
"}",
";",
"prop",
".",
"data",
".",
"displayValue",
"=",
"prop",
".",
"data",
".",
"isEditable",
"?",
"JSON",
".",
"stringify",
"(",
"value",
")",
":",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
")",
";",
"properties",
".",
"normal",
".",
"push",
"(",
"prop",
")",
";",
"}",
"}",
")",
";",
"properties",
".",
"normal",
"=",
"_",
".",
"sortBy",
"(",
"properties",
".",
"normal",
",",
"'key'",
")",
";",
"properties",
".",
"relational",
"=",
"_",
".",
"sortBy",
"(",
"properties",
".",
"relational",
",",
"'key'",
")",
";",
"properties",
".",
"derived",
"=",
"_",
".",
"sortBy",
"(",
"properties",
".",
"derived",
",",
"'key'",
")",
";",
"return",
"properties",
";",
"}"
] |
Get array of attributes, so it can be iterated on
@return {Array<Object>} List of attribute key/values
|
[
"Get",
"array",
"of",
"attributes",
"so",
"it",
"can",
"be",
"iterated",
"on"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/adaptors/backbone/base_model.js#L209-L281
|
train
|
|
wayfair/tungstenjs
|
adaptors/backbone/base_model.js
|
hasAtLeastOneKey
|
function hasAtLeastOneKey(target, attrs) {
var attrsLen = attrs.length;
var i = 0;
var counter = 0;
for (; i < attrsLen; i++) {
if (target[attrs[i]] !== undefined) {
counter++;
}
}
return !!counter;
}
|
javascript
|
function hasAtLeastOneKey(target, attrs) {
var attrsLen = attrs.length;
var i = 0;
var counter = 0;
for (; i < attrsLen; i++) {
if (target[attrs[i]] !== undefined) {
counter++;
}
}
return !!counter;
}
|
[
"function",
"hasAtLeastOneKey",
"(",
"target",
",",
"attrs",
")",
"{",
"var",
"attrsLen",
"=",
"attrs",
".",
"length",
";",
"var",
"i",
"=",
"0",
";",
"var",
"counter",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"attrsLen",
";",
"i",
"++",
")",
"{",
"if",
"(",
"target",
"[",
"attrs",
"[",
"i",
"]",
"]",
"!==",
"undefined",
")",
"{",
"counter",
"++",
";",
"}",
"}",
"return",
"!",
"!",
"counter",
";",
"}"
] |
Checks if target object has at least one attribute from attrs array.
@param {Object} target Object to check for attributes
@param {Array} attrs Array of attributes
@return {Boolean}
|
[
"Checks",
"if",
"target",
"object",
"has",
"at",
"least",
"one",
"attribute",
"from",
"attrs",
"array",
"."
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/adaptors/backbone/base_model.js#L489-L499
|
train
|
wayfair/tungstenjs
|
src/event/handlers/window_events.js
|
function() {
var doc = document.documentElement;
return {
x: (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
y: (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
};
}
|
javascript
|
function() {
var doc = document.documentElement;
return {
x: (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0),
y: (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
};
}
|
[
"function",
"(",
")",
"{",
"var",
"doc",
"=",
"document",
".",
"documentElement",
";",
"return",
"{",
"x",
":",
"(",
"window",
".",
"pageXOffset",
"||",
"doc",
".",
"scrollLeft",
")",
"-",
"(",
"doc",
".",
"clientLeft",
"||",
"0",
")",
",",
"y",
":",
"(",
"window",
".",
"pageYOffset",
"||",
"doc",
".",
"scrollTop",
")",
"-",
"(",
"doc",
".",
"clientTop",
"||",
"0",
")",
"}",
";",
"}"
] |
Read data to pass through for Scroll event to prevent repeated reads
@return {Object} Scroll properties of element
|
[
"Read",
"data",
"to",
"pass",
"through",
"for",
"Scroll",
"event",
"to",
"prevent",
"repeated",
"reads"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/event/handlers/window_events.js#L15-L21
|
train
|
|
wayfair/tungstenjs
|
src/template/compiler/stack.js
|
processAttributeArray
|
function processAttributeArray(attrArray) {
let attrs = {
'static': {},
'dynamic': []
};
let name = [];
let value = [];
let item;
let pushingTo = name;
for (let i = 0; i < attrArray.length; i++) {
item = attrArray[i];
if (item.type === 'attributenameend') {
pushingTo = value;
} else if (item.type === 'attributeend') {
// Ensure there are no tokens in a non-dynamic attribute name
for (let j = 0; j < name.length; j++) {
if (typeof name[j] !== 'string') {
compilerErrors.mustacheTokenCannotBeInAttributeNames(name[j]);
}
}
if (name.length === 1) {
if (value.length) {
if (value.length === 1 && typeof value[0] === 'string') {
value = value[0];
}
} else {
value = true;
}
attrs.static[name[0]] = flattenAttributeValues(value);
} else {
attrs.dynamic = attrs.dynamic.concat(_.map(name, flattenAttributeValues));
if (value.length) {
attrs.dynamic.push('="');
attrs.dynamic = attrs.dynamic.concat(_.map(value, flattenAttributeValues));
attrs.dynamic.push('"');
}
}
name = [];
value = [];
pushingTo = name;
} else if (item.type === 'attributename' || item.type === 'attributevalue') {
pushingTo.push(item.value);
} else if (pushingTo === name) {
if (name.length === 0) {
if (item.type === types.INTERPOLATOR) {
compilerErrors.doubleCurlyInterpolatorsCannotBeInAttributes(item.value);
} else if (item.type === types.SECTION) {
attrs.dynamic.push(templateStack.processObject(item));
continue;
}
}
pushingTo.push(item);
} else {
pushingTo.push(item);
}
}
attrs.dynamic = attrs.dynamic.concat(_.map(name, flattenAttributeValues));
attrs.dynamic = attrs.dynamic.concat(_.map(value, flattenAttributeValues));
mergeStrings(attrs.dynamic);
return attrs;
}
|
javascript
|
function processAttributeArray(attrArray) {
let attrs = {
'static': {},
'dynamic': []
};
let name = [];
let value = [];
let item;
let pushingTo = name;
for (let i = 0; i < attrArray.length; i++) {
item = attrArray[i];
if (item.type === 'attributenameend') {
pushingTo = value;
} else if (item.type === 'attributeend') {
// Ensure there are no tokens in a non-dynamic attribute name
for (let j = 0; j < name.length; j++) {
if (typeof name[j] !== 'string') {
compilerErrors.mustacheTokenCannotBeInAttributeNames(name[j]);
}
}
if (name.length === 1) {
if (value.length) {
if (value.length === 1 && typeof value[0] === 'string') {
value = value[0];
}
} else {
value = true;
}
attrs.static[name[0]] = flattenAttributeValues(value);
} else {
attrs.dynamic = attrs.dynamic.concat(_.map(name, flattenAttributeValues));
if (value.length) {
attrs.dynamic.push('="');
attrs.dynamic = attrs.dynamic.concat(_.map(value, flattenAttributeValues));
attrs.dynamic.push('"');
}
}
name = [];
value = [];
pushingTo = name;
} else if (item.type === 'attributename' || item.type === 'attributevalue') {
pushingTo.push(item.value);
} else if (pushingTo === name) {
if (name.length === 0) {
if (item.type === types.INTERPOLATOR) {
compilerErrors.doubleCurlyInterpolatorsCannotBeInAttributes(item.value);
} else if (item.type === types.SECTION) {
attrs.dynamic.push(templateStack.processObject(item));
continue;
}
}
pushingTo.push(item);
} else {
pushingTo.push(item);
}
}
attrs.dynamic = attrs.dynamic.concat(_.map(name, flattenAttributeValues));
attrs.dynamic = attrs.dynamic.concat(_.map(value, flattenAttributeValues));
mergeStrings(attrs.dynamic);
return attrs;
}
|
[
"function",
"processAttributeArray",
"(",
"attrArray",
")",
"{",
"let",
"attrs",
"=",
"{",
"'static'",
":",
"{",
"}",
",",
"'dynamic'",
":",
"[",
"]",
"}",
";",
"let",
"name",
"=",
"[",
"]",
";",
"let",
"value",
"=",
"[",
"]",
";",
"let",
"item",
";",
"let",
"pushingTo",
"=",
"name",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"attrArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"item",
"=",
"attrArray",
"[",
"i",
"]",
";",
"if",
"(",
"item",
".",
"type",
"===",
"'attributenameend'",
")",
"{",
"pushingTo",
"=",
"value",
";",
"}",
"else",
"if",
"(",
"item",
".",
"type",
"===",
"'attributeend'",
")",
"{",
"for",
"(",
"let",
"j",
"=",
"0",
";",
"j",
"<",
"name",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"typeof",
"name",
"[",
"j",
"]",
"!==",
"'string'",
")",
"{",
"compilerErrors",
".",
"mustacheTokenCannotBeInAttributeNames",
"(",
"name",
"[",
"j",
"]",
")",
";",
"}",
"}",
"if",
"(",
"name",
".",
"length",
"===",
"1",
")",
"{",
"if",
"(",
"value",
".",
"length",
")",
"{",
"if",
"(",
"value",
".",
"length",
"===",
"1",
"&&",
"typeof",
"value",
"[",
"0",
"]",
"===",
"'string'",
")",
"{",
"value",
"=",
"value",
"[",
"0",
"]",
";",
"}",
"}",
"else",
"{",
"value",
"=",
"true",
";",
"}",
"attrs",
".",
"static",
"[",
"name",
"[",
"0",
"]",
"]",
"=",
"flattenAttributeValues",
"(",
"value",
")",
";",
"}",
"else",
"{",
"attrs",
".",
"dynamic",
"=",
"attrs",
".",
"dynamic",
".",
"concat",
"(",
"_",
".",
"map",
"(",
"name",
",",
"flattenAttributeValues",
")",
")",
";",
"if",
"(",
"value",
".",
"length",
")",
"{",
"attrs",
".",
"dynamic",
".",
"push",
"(",
"'=\"'",
")",
";",
"attrs",
".",
"dynamic",
"=",
"attrs",
".",
"dynamic",
".",
"concat",
"(",
"_",
".",
"map",
"(",
"value",
",",
"flattenAttributeValues",
")",
")",
";",
"attrs",
".",
"dynamic",
".",
"push",
"(",
"'\"'",
")",
";",
"}",
"}",
"name",
"=",
"[",
"]",
";",
"value",
"=",
"[",
"]",
";",
"pushingTo",
"=",
"name",
";",
"}",
"else",
"if",
"(",
"item",
".",
"type",
"===",
"'attributename'",
"||",
"item",
".",
"type",
"===",
"'attributevalue'",
")",
"{",
"pushingTo",
".",
"push",
"(",
"item",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"pushingTo",
"===",
"name",
")",
"{",
"if",
"(",
"name",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"item",
".",
"type",
"===",
"types",
".",
"INTERPOLATOR",
")",
"{",
"compilerErrors",
".",
"doubleCurlyInterpolatorsCannotBeInAttributes",
"(",
"item",
".",
"value",
")",
";",
"}",
"else",
"if",
"(",
"item",
".",
"type",
"===",
"types",
".",
"SECTION",
")",
"{",
"attrs",
".",
"dynamic",
".",
"push",
"(",
"templateStack",
".",
"processObject",
"(",
"item",
")",
")",
";",
"continue",
";",
"}",
"}",
"pushingTo",
".",
"push",
"(",
"item",
")",
";",
"}",
"else",
"{",
"pushingTo",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
"attrs",
".",
"dynamic",
"=",
"attrs",
".",
"dynamic",
".",
"concat",
"(",
"_",
".",
"map",
"(",
"name",
",",
"flattenAttributeValues",
")",
")",
";",
"attrs",
".",
"dynamic",
"=",
"attrs",
".",
"dynamic",
".",
"concat",
"(",
"_",
".",
"map",
"(",
"value",
",",
"flattenAttributeValues",
")",
")",
";",
"mergeStrings",
"(",
"attrs",
".",
"dynamic",
")",
";",
"return",
"attrs",
";",
"}"
] |
Processes attributes into static and dynamic values
@param {Array<Object>} attrArray Attribute array built during parsing
@return {Object}
|
[
"Processes",
"attributes",
"into",
"static",
"and",
"dynamic",
"values"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/compiler/stack.js#L373-L436
|
train
|
wayfair/tungstenjs
|
src/utils/errors.js
|
loggerize
|
function loggerize(message, type) {
return function() {
let output = message.apply(message, arguments);
if (_.isArray(output)) {
logger[type].apply(logger, output);
} else {
logger[type](output);
}
// Return the message in case it's needed. (I.E. for utils.alert)
return output;
};
}
|
javascript
|
function loggerize(message, type) {
return function() {
let output = message.apply(message, arguments);
if (_.isArray(output)) {
logger[type].apply(logger, output);
} else {
logger[type](output);
}
// Return the message in case it's needed. (I.E. for utils.alert)
return output;
};
}
|
[
"function",
"loggerize",
"(",
"message",
",",
"type",
")",
"{",
"return",
"function",
"(",
")",
"{",
"let",
"output",
"=",
"message",
".",
"apply",
"(",
"message",
",",
"arguments",
")",
";",
"if",
"(",
"_",
".",
"isArray",
"(",
"output",
")",
")",
"{",
"logger",
"[",
"type",
"]",
".",
"apply",
"(",
"logger",
",",
"output",
")",
";",
"}",
"else",
"{",
"logger",
"[",
"type",
"]",
"(",
"output",
")",
";",
"}",
"return",
"output",
";",
"}",
";",
"}"
] |
Returns a logger call with the provided message and type
@param {function} message function that returns a string, or an array containing
a string and additional arguments for logger.
@param {string} type The type of log to make (warning, error, exception, etc...)
@return {function} Function that calls logger with the provided message and type
|
[
"Returns",
"a",
"logger",
"call",
"with",
"the",
"provided",
"message",
"and",
"type"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/utils/errors.js#L58-L69
|
train
|
wayfair/tungstenjs
|
src/debug/diff_dom_and_vdom.js
|
recursiveDiff
|
function recursiveDiff(vtree, elem) {
var output = '';
if (vtree == null && elem != null) {
// If the VTree ran out but DOM still exists
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
} else if (isVNode(vtree)) {
if (!elem || elem.nodeType !== utils.NODE_TYPES.ELEMENT) {
// If vtree is a VNode, but elem isn't an Element
output += '<del>' + vNodeToString(vtree, true, false) + '</del>';
if (elem) {
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
} else {
// Diff elements and recurse
output += diffElements(vtree, elem);
}
} else if (isVText(vtree)) {
if (!elem || elem.nodeType !== utils.NODE_TYPES.TEXT) {
// If vtree is a VText, but elem isn't a textNode
output += '<del>' + escapeString(vtree.text) + '</del>';
if (elem) {
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
} else {
output += textDiff(vtree.text, elem.textContent);
}
} else if (isWidget(vtree)) {
var widgetName;
// Widgets are the construct that hold childViews
if (vtree.constructor === HTMLCommentWidget) {
// HTMLCommentWidget is a special case
if (!elem || elem.nodeType !== utils.NODE_TYPES.COMMENT) {
output += '<del>' + utils.getCommentString(escapeString(vtree.text), chars) + '</del>';
if (elem) {
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
} else {
output += utils.getCommentString(textDiff(escapeString(vtree.text), elem.textContent), chars);
}
} else if (vtree && vtree.view) {
widgetName = vtree.view.getDebugName();
if (typeof vtree.templateToString === 'function') {
widgetName = vtree.templateToString(recursiveDiff);
}
if (vtree.view.el !== elem) {
// If the view at this position isn't bound to elem, something has gone terribly wrong
output += '<del><ins>' + widgetName + '</ins></del>';
} else {
output += widgetName;
}
} else if (vtree && typeof vtree.diff === 'function') {
output += vtree.diff(elem, recursiveDiff);
} else {
output += '<del>[Uninitialized child view]</del>';
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
}
return output;
}
|
javascript
|
function recursiveDiff(vtree, elem) {
var output = '';
if (vtree == null && elem != null) {
// If the VTree ran out but DOM still exists
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
} else if (isVNode(vtree)) {
if (!elem || elem.nodeType !== utils.NODE_TYPES.ELEMENT) {
// If vtree is a VNode, but elem isn't an Element
output += '<del>' + vNodeToString(vtree, true, false) + '</del>';
if (elem) {
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
} else {
// Diff elements and recurse
output += diffElements(vtree, elem);
}
} else if (isVText(vtree)) {
if (!elem || elem.nodeType !== utils.NODE_TYPES.TEXT) {
// If vtree is a VText, but elem isn't a textNode
output += '<del>' + escapeString(vtree.text) + '</del>';
if (elem) {
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
} else {
output += textDiff(vtree.text, elem.textContent);
}
} else if (isWidget(vtree)) {
var widgetName;
// Widgets are the construct that hold childViews
if (vtree.constructor === HTMLCommentWidget) {
// HTMLCommentWidget is a special case
if (!elem || elem.nodeType !== utils.NODE_TYPES.COMMENT) {
output += '<del>' + utils.getCommentString(escapeString(vtree.text), chars) + '</del>';
if (elem) {
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
} else {
output += utils.getCommentString(textDiff(escapeString(vtree.text), elem.textContent), chars);
}
} else if (vtree && vtree.view) {
widgetName = vtree.view.getDebugName();
if (typeof vtree.templateToString === 'function') {
widgetName = vtree.templateToString(recursiveDiff);
}
if (vtree.view.el !== elem) {
// If the view at this position isn't bound to elem, something has gone terribly wrong
output += '<del><ins>' + widgetName + '</ins></del>';
} else {
output += widgetName;
}
} else if (vtree && typeof vtree.diff === 'function') {
output += vtree.diff(elem, recursiveDiff);
} else {
output += '<del>[Uninitialized child view]</del>';
output += '<ins>' + utils.elementToString(elem, chars) + '</ins>';
}
}
return output;
}
|
[
"function",
"recursiveDiff",
"(",
"vtree",
",",
"elem",
")",
"{",
"var",
"output",
"=",
"''",
";",
"if",
"(",
"vtree",
"==",
"null",
"&&",
"elem",
"!=",
"null",
")",
"{",
"output",
"+=",
"'<ins>'",
"+",
"utils",
".",
"elementToString",
"(",
"elem",
",",
"chars",
")",
"+",
"'</ins>'",
";",
"}",
"else",
"if",
"(",
"isVNode",
"(",
"vtree",
")",
")",
"{",
"if",
"(",
"!",
"elem",
"||",
"elem",
".",
"nodeType",
"!==",
"utils",
".",
"NODE_TYPES",
".",
"ELEMENT",
")",
"{",
"output",
"+=",
"'<del>'",
"+",
"vNodeToString",
"(",
"vtree",
",",
"true",
",",
"false",
")",
"+",
"'</del>'",
";",
"if",
"(",
"elem",
")",
"{",
"output",
"+=",
"'<ins>'",
"+",
"utils",
".",
"elementToString",
"(",
"elem",
",",
"chars",
")",
"+",
"'</ins>'",
";",
"}",
"}",
"else",
"{",
"output",
"+=",
"diffElements",
"(",
"vtree",
",",
"elem",
")",
";",
"}",
"}",
"else",
"if",
"(",
"isVText",
"(",
"vtree",
")",
")",
"{",
"if",
"(",
"!",
"elem",
"||",
"elem",
".",
"nodeType",
"!==",
"utils",
".",
"NODE_TYPES",
".",
"TEXT",
")",
"{",
"output",
"+=",
"'<del>'",
"+",
"escapeString",
"(",
"vtree",
".",
"text",
")",
"+",
"'</del>'",
";",
"if",
"(",
"elem",
")",
"{",
"output",
"+=",
"'<ins>'",
"+",
"utils",
".",
"elementToString",
"(",
"elem",
",",
"chars",
")",
"+",
"'</ins>'",
";",
"}",
"}",
"else",
"{",
"output",
"+=",
"textDiff",
"(",
"vtree",
".",
"text",
",",
"elem",
".",
"textContent",
")",
";",
"}",
"}",
"else",
"if",
"(",
"isWidget",
"(",
"vtree",
")",
")",
"{",
"var",
"widgetName",
";",
"if",
"(",
"vtree",
".",
"constructor",
"===",
"HTMLCommentWidget",
")",
"{",
"if",
"(",
"!",
"elem",
"||",
"elem",
".",
"nodeType",
"!==",
"utils",
".",
"NODE_TYPES",
".",
"COMMENT",
")",
"{",
"output",
"+=",
"'<del>'",
"+",
"utils",
".",
"getCommentString",
"(",
"escapeString",
"(",
"vtree",
".",
"text",
")",
",",
"chars",
")",
"+",
"'</del>'",
";",
"if",
"(",
"elem",
")",
"{",
"output",
"+=",
"'<ins>'",
"+",
"utils",
".",
"elementToString",
"(",
"elem",
",",
"chars",
")",
"+",
"'</ins>'",
";",
"}",
"}",
"else",
"{",
"output",
"+=",
"utils",
".",
"getCommentString",
"(",
"textDiff",
"(",
"escapeString",
"(",
"vtree",
".",
"text",
")",
",",
"elem",
".",
"textContent",
")",
",",
"chars",
")",
";",
"}",
"}",
"else",
"if",
"(",
"vtree",
"&&",
"vtree",
".",
"view",
")",
"{",
"widgetName",
"=",
"vtree",
".",
"view",
".",
"getDebugName",
"(",
")",
";",
"if",
"(",
"typeof",
"vtree",
".",
"templateToString",
"===",
"'function'",
")",
"{",
"widgetName",
"=",
"vtree",
".",
"templateToString",
"(",
"recursiveDiff",
")",
";",
"}",
"if",
"(",
"vtree",
".",
"view",
".",
"el",
"!==",
"elem",
")",
"{",
"output",
"+=",
"'<del><ins>'",
"+",
"widgetName",
"+",
"'</ins></del>'",
";",
"}",
"else",
"{",
"output",
"+=",
"widgetName",
";",
"}",
"}",
"else",
"if",
"(",
"vtree",
"&&",
"typeof",
"vtree",
".",
"diff",
"===",
"'function'",
")",
"{",
"output",
"+=",
"vtree",
".",
"diff",
"(",
"elem",
",",
"recursiveDiff",
")",
";",
"}",
"else",
"{",
"output",
"+=",
"'<del>[Uninitialized child view]</del>'",
";",
"output",
"+=",
"'<ins>'",
"+",
"utils",
".",
"elementToString",
"(",
"elem",
",",
"chars",
")",
"+",
"'</ins>'",
";",
"}",
"}",
"return",
"output",
";",
"}"
] |
Iterates over a VirtualDOM and DOM structure to create a diff string
@param {Object} vtree VirtualDOM object
@param {Element} elem DOM object
@return {string} Diff string
|
[
"Iterates",
"over",
"a",
"VirtualDOM",
"and",
"DOM",
"structure",
"to",
"create",
"a",
"diff",
"string"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/debug/diff_dom_and_vdom.js#L124-L182
|
train
|
wayfair/tungstenjs
|
adaptors/backbone/base_collection.js
|
function(model, options) {
Backbone.Collection.prototype._addReference.call(this, model, options);
if (ComponentWidget.isComponent(model) && model.exposedEvents) {
var events = model.exposedEvents;
if (events === true) {
model.model.on('all', this._onModelEvent, this);
} else if (events.length) {
for (let i = 0; i < events.length; i++) {
this.bindExposedEvent(events[i], model);
}
}
}
}
|
javascript
|
function(model, options) {
Backbone.Collection.prototype._addReference.call(this, model, options);
if (ComponentWidget.isComponent(model) && model.exposedEvents) {
var events = model.exposedEvents;
if (events === true) {
model.model.on('all', this._onModelEvent, this);
} else if (events.length) {
for (let i = 0; i < events.length; i++) {
this.bindExposedEvent(events[i], model);
}
}
}
}
|
[
"function",
"(",
"model",
",",
"options",
")",
"{",
"Backbone",
".",
"Collection",
".",
"prototype",
".",
"_addReference",
".",
"call",
"(",
"this",
",",
"model",
",",
"options",
")",
";",
"if",
"(",
"ComponentWidget",
".",
"isComponent",
"(",
"model",
")",
"&&",
"model",
".",
"exposedEvents",
")",
"{",
"var",
"events",
"=",
"model",
".",
"exposedEvents",
";",
"if",
"(",
"events",
"===",
"true",
")",
"{",
"model",
".",
"model",
".",
"on",
"(",
"'all'",
",",
"this",
".",
"_onModelEvent",
",",
"this",
")",
";",
"}",
"else",
"if",
"(",
"events",
".",
"length",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"bindExposedEvent",
"(",
"events",
"[",
"i",
"]",
",",
"model",
")",
";",
"}",
"}",
"}",
"}"
] |
Binds events when a model is added to a collection
@param {Object} model
@param {Object} options
|
[
"Binds",
"events",
"when",
"a",
"model",
"is",
"added",
"to",
"a",
"collection"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/adaptors/backbone/base_collection.js#L59-L71
|
train
|
|
wayfair/tungstenjs
|
adaptors/backbone/base_collection.js
|
function(model, options) {
if (ComponentWidget.isComponent(model) && model.model && model.exposedEvents) {
var events = model.exposedEvents;
if (events === true) {
model.model.off('all', this._onModelEvent, this);
} else if (events.length) {
for (let i = 0; i < events.length; i++) {
this.stopListening(model.model, events[i]);
}
}
}
Backbone.Collection.prototype._removeReference.call(this, model, options);
}
|
javascript
|
function(model, options) {
if (ComponentWidget.isComponent(model) && model.model && model.exposedEvents) {
var events = model.exposedEvents;
if (events === true) {
model.model.off('all', this._onModelEvent, this);
} else if (events.length) {
for (let i = 0; i < events.length; i++) {
this.stopListening(model.model, events[i]);
}
}
}
Backbone.Collection.prototype._removeReference.call(this, model, options);
}
|
[
"function",
"(",
"model",
",",
"options",
")",
"{",
"if",
"(",
"ComponentWidget",
".",
"isComponent",
"(",
"model",
")",
"&&",
"model",
".",
"model",
"&&",
"model",
".",
"exposedEvents",
")",
"{",
"var",
"events",
"=",
"model",
".",
"exposedEvents",
";",
"if",
"(",
"events",
"===",
"true",
")",
"{",
"model",
".",
"model",
".",
"off",
"(",
"'all'",
",",
"this",
".",
"_onModelEvent",
",",
"this",
")",
";",
"}",
"else",
"if",
"(",
"events",
".",
"length",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"events",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"stopListening",
"(",
"model",
".",
"model",
",",
"events",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"Backbone",
".",
"Collection",
".",
"prototype",
".",
"_removeReference",
".",
"call",
"(",
"this",
",",
"model",
",",
"options",
")",
";",
"}"
] |
Unbinds events when a model is removed from a collection
@param {Object} model
@param {Object} options
|
[
"Unbinds",
"events",
"when",
"a",
"model",
"is",
"removed",
"from",
"a",
"collection"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/adaptors/backbone/base_collection.js#L79-L91
|
train
|
|
wayfair/tungstenjs
|
adaptors/backbone/base_collection.js
|
function() {
if (!this.cid) {
this.cid = _.uniqueId('collection');
}
return this.constructor.debugName ? this.constructor.debugName + this.cid.replace('collection', '') : this.cid;
}
|
javascript
|
function() {
if (!this.cid) {
this.cid = _.uniqueId('collection');
}
return this.constructor.debugName ? this.constructor.debugName + this.cid.replace('collection', '') : this.cid;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"cid",
")",
"{",
"this",
".",
"cid",
"=",
"_",
".",
"uniqueId",
"(",
"'collection'",
")",
";",
"}",
"return",
"this",
".",
"constructor",
".",
"debugName",
"?",
"this",
".",
"constructor",
".",
"debugName",
"+",
"this",
".",
"cid",
".",
"replace",
"(",
"'collection'",
",",
"''",
")",
":",
"this",
".",
"cid",
";",
"}"
] |
Debug name of this object, using declared debugName, falling back to cid
@return {string} Debug name
|
[
"Debug",
"name",
"of",
"this",
"object",
"using",
"declared",
"debugName",
"falling",
"back",
"to",
"cid"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/adaptors/backbone/base_collection.js#L139-L144
|
train
|
|
wayfair/tungstenjs
|
src/template/compiler/languages/mustache.js
|
atDelim
|
function atDelim(str, position, delim) {
if (str.charAt(position) !== delim.charAt(0)) {
return false;
}
for (let i = 1, l = delim.length; i < l; i++) {
if (str.charAt(position + i) !== delim.charAt(i)) {
return false;
}
}
return true;
}
|
javascript
|
function atDelim(str, position, delim) {
if (str.charAt(position) !== delim.charAt(0)) {
return false;
}
for (let i = 1, l = delim.length; i < l; i++) {
if (str.charAt(position + i) !== delim.charAt(i)) {
return false;
}
}
return true;
}
|
[
"function",
"atDelim",
"(",
"str",
",",
"position",
",",
"delim",
")",
"{",
"if",
"(",
"str",
".",
"charAt",
"(",
"position",
")",
"!==",
"delim",
".",
"charAt",
"(",
"0",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"1",
",",
"l",
"=",
"delim",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"str",
".",
"charAt",
"(",
"position",
"+",
"i",
")",
"!==",
"delim",
".",
"charAt",
"(",
"i",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] |
Checks if the string has a delimiter at the given position
@param {String} str String to check
@param {Number} position Position to start at
@param {String} delim Delimiter to check for
@return {Boolean}
|
[
"Checks",
"if",
"the",
"string",
"has",
"a",
"delimiter",
"at",
"the",
"given",
"position"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/compiler/languages/mustache.js#L35-L46
|
train
|
wayfair/tungstenjs
|
src/template/compiler/languages/mustache.js
|
trimWhitespace
|
function trimWhitespace(line) {
let whitespaceIndicies = [];
let allWhitespace = true;
let seenAnyTag = false;
let newLine = new Array(line.length);
for (let i = 0; i < line.length; i++) {
let obj = line[i];
newLine[i] = obj;
if (typeof obj === 'string') {
if (!nonWhitespace.test(obj)) {
whitespaceIndicies.push(i);
} else {
allWhitespace = false;
}
} else {
seenAnyTag = true;
if (nonWhitespaceNodes[obj.type] === true) {
allWhitespace = false;
}
}
// Bail out if we've seen a non-whitespace
if (!allWhitespace) {
return line;
}
}
// Remove the whitespace nodes if this line consists of:
// - only whitespace text
// - no Interpolators or Unescaped Interpolators
// - at least one Mustache tag
if (allWhitespace && seenAnyTag) {
for (let i = 0; i < whitespaceIndicies.length; i++) {
let index = whitespaceIndicies[i];
let obj = newLine[index];
newLine[index] = {
type: types.TEXT,
original: obj,
length: obj.length
};
}
}
return newLine;
}
|
javascript
|
function trimWhitespace(line) {
let whitespaceIndicies = [];
let allWhitespace = true;
let seenAnyTag = false;
let newLine = new Array(line.length);
for (let i = 0; i < line.length; i++) {
let obj = line[i];
newLine[i] = obj;
if (typeof obj === 'string') {
if (!nonWhitespace.test(obj)) {
whitespaceIndicies.push(i);
} else {
allWhitespace = false;
}
} else {
seenAnyTag = true;
if (nonWhitespaceNodes[obj.type] === true) {
allWhitespace = false;
}
}
// Bail out if we've seen a non-whitespace
if (!allWhitespace) {
return line;
}
}
// Remove the whitespace nodes if this line consists of:
// - only whitespace text
// - no Interpolators or Unescaped Interpolators
// - at least one Mustache tag
if (allWhitespace && seenAnyTag) {
for (let i = 0; i < whitespaceIndicies.length; i++) {
let index = whitespaceIndicies[i];
let obj = newLine[index];
newLine[index] = {
type: types.TEXT,
original: obj,
length: obj.length
};
}
}
return newLine;
}
|
[
"function",
"trimWhitespace",
"(",
"line",
")",
"{",
"let",
"whitespaceIndicies",
"=",
"[",
"]",
";",
"let",
"allWhitespace",
"=",
"true",
";",
"let",
"seenAnyTag",
"=",
"false",
";",
"let",
"newLine",
"=",
"new",
"Array",
"(",
"line",
".",
"length",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"line",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"obj",
"=",
"line",
"[",
"i",
"]",
";",
"newLine",
"[",
"i",
"]",
"=",
"obj",
";",
"if",
"(",
"typeof",
"obj",
"===",
"'string'",
")",
"{",
"if",
"(",
"!",
"nonWhitespace",
".",
"test",
"(",
"obj",
")",
")",
"{",
"whitespaceIndicies",
".",
"push",
"(",
"i",
")",
";",
"}",
"else",
"{",
"allWhitespace",
"=",
"false",
";",
"}",
"}",
"else",
"{",
"seenAnyTag",
"=",
"true",
";",
"if",
"(",
"nonWhitespaceNodes",
"[",
"obj",
".",
"type",
"]",
"===",
"true",
")",
"{",
"allWhitespace",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"!",
"allWhitespace",
")",
"{",
"return",
"line",
";",
"}",
"}",
"if",
"(",
"allWhitespace",
"&&",
"seenAnyTag",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"whitespaceIndicies",
".",
"length",
";",
"i",
"++",
")",
"{",
"let",
"index",
"=",
"whitespaceIndicies",
"[",
"i",
"]",
";",
"let",
"obj",
"=",
"newLine",
"[",
"index",
"]",
";",
"newLine",
"[",
"index",
"]",
"=",
"{",
"type",
":",
"types",
".",
"TEXT",
",",
"original",
":",
"obj",
",",
"length",
":",
"obj",
".",
"length",
"}",
";",
"}",
"}",
"return",
"newLine",
";",
"}"
] |
Trims whitespace in accordance with Mustache rules
Leaves reference nodes behind for lambdas and the debugger
@param {Array<String>} line Symbols for this line
@return {Array<String>} Trimmed symbols for this line
|
[
"Trims",
"whitespace",
"in",
"accordance",
"with",
"Mustache",
"rules",
"Leaves",
"reference",
"nodes",
"behind",
"for",
"lambdas",
"and",
"the",
"debugger"
] |
556689ffb669fb1bc0a7ba32e3b1c9530de896b9
|
https://github.com/wayfair/tungstenjs/blob/556689ffb669fb1bc0a7ba32e3b1c9530de896b9/src/template/compiler/languages/mustache.js#L55-L98
|
train
|
contra/captchagen
|
index.js
|
function (opt) {
var cap = new Captcha(opt);
cap.use(drawBackground);
cap.use(drawLines);
cap.use(drawText);
cap.use(drawLines);
return cap;
}
|
javascript
|
function (opt) {
var cap = new Captcha(opt);
cap.use(drawBackground);
cap.use(drawLines);
cap.use(drawText);
cap.use(drawLines);
return cap;
}
|
[
"function",
"(",
"opt",
")",
"{",
"var",
"cap",
"=",
"new",
"Captcha",
"(",
"opt",
")",
";",
"cap",
".",
"use",
"(",
"drawBackground",
")",
";",
"cap",
".",
"use",
"(",
"drawLines",
")",
";",
"cap",
".",
"use",
"(",
"drawText",
")",
";",
"cap",
".",
"use",
"(",
"drawLines",
")",
";",
"return",
"cap",
";",
"}"
] |
use default settings
|
[
"use",
"default",
"settings"
] |
ab10471bd6efcc22543a064aedcc48598dc9e40c
|
https://github.com/contra/captchagen/blob/ab10471bd6efcc22543a064aedcc48598dc9e40c/index.js#L24-L31
|
train
|
|
shipshapecode/ember-cli-release
|
lib/commands/release.js
|
function() {
this._super.init && this._super.init.apply(this, arguments);
var baseOptions = this.baseOptions();
var optionsFromConfig = this.config().options;
var mergedOptions = baseOptions.map(function(availableOption) {
var option = merge(true, availableOption);
if ((optionsFromConfig[option.name] !== undefined) && (option.default !== undefined)) {
option.default = optionsFromConfig[option.name];
option.description = option.description + ' (configured in ' + configPath + ')';
}
return option;
});
// Merge custom strategy options if specified
var strategy = optionsFromConfig.strategy;
if (typeof strategy === 'object' && Array.isArray(strategy.availableOptions)) {
mergedOptions = mergedOptions.concat(strategy.availableOptions);
}
this.registerOptions({
availableOptions: mergedOptions
});
}
|
javascript
|
function() {
this._super.init && this._super.init.apply(this, arguments);
var baseOptions = this.baseOptions();
var optionsFromConfig = this.config().options;
var mergedOptions = baseOptions.map(function(availableOption) {
var option = merge(true, availableOption);
if ((optionsFromConfig[option.name] !== undefined) && (option.default !== undefined)) {
option.default = optionsFromConfig[option.name];
option.description = option.description + ' (configured in ' + configPath + ')';
}
return option;
});
// Merge custom strategy options if specified
var strategy = optionsFromConfig.strategy;
if (typeof strategy === 'object' && Array.isArray(strategy.availableOptions)) {
mergedOptions = mergedOptions.concat(strategy.availableOptions);
}
this.registerOptions({
availableOptions: mergedOptions
});
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"_super",
".",
"init",
"&&",
"this",
".",
"_super",
".",
"init",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"var",
"baseOptions",
"=",
"this",
".",
"baseOptions",
"(",
")",
";",
"var",
"optionsFromConfig",
"=",
"this",
".",
"config",
"(",
")",
".",
"options",
";",
"var",
"mergedOptions",
"=",
"baseOptions",
".",
"map",
"(",
"function",
"(",
"availableOption",
")",
"{",
"var",
"option",
"=",
"merge",
"(",
"true",
",",
"availableOption",
")",
";",
"if",
"(",
"(",
"optionsFromConfig",
"[",
"option",
".",
"name",
"]",
"!==",
"undefined",
")",
"&&",
"(",
"option",
".",
"default",
"!==",
"undefined",
")",
")",
"{",
"option",
".",
"default",
"=",
"optionsFromConfig",
"[",
"option",
".",
"name",
"]",
";",
"option",
".",
"description",
"=",
"option",
".",
"description",
"+",
"' (configured in '",
"+",
"configPath",
"+",
"')'",
";",
"}",
"return",
"option",
";",
"}",
")",
";",
"var",
"strategy",
"=",
"optionsFromConfig",
".",
"strategy",
";",
"if",
"(",
"typeof",
"strategy",
"===",
"'object'",
"&&",
"Array",
".",
"isArray",
"(",
"strategy",
".",
"availableOptions",
")",
")",
"{",
"mergedOptions",
"=",
"mergedOptions",
".",
"concat",
"(",
"strategy",
".",
"availableOptions",
")",
";",
"}",
"this",
".",
"registerOptions",
"(",
"{",
"availableOptions",
":",
"mergedOptions",
"}",
")",
";",
"}"
] |
Merge options specified on the command line with those defined in the config
|
[
"Merge",
"options",
"specified",
"on",
"the",
"command",
"line",
"with",
"those",
"defined",
"in",
"the",
"config"
] |
e17d8305470e2a873cf3abfa0bdadefb4094bbba
|
https://github.com/shipshapecode/ember-cli-release/blob/e17d8305470e2a873cf3abfa0bdadefb4094bbba/lib/commands/release.js#L395-L419
|
train
|
|
shipshapecode/ember-cli-release
|
lib/commands/release.js
|
function() {
if (this._baseOptions) {
return this._baseOptions;
}
var strategies = this.strategies();
var strategyOptions = Object.keys(strategies).reduce(function(result, strategyName) {
var options = strategies[strategyName].availableOptions;
if (Array.isArray(options)) {
// Add strategy qualifier to option descriptions
options.forEach(function(option) {
option.description = "when strategy is '" + strategyName + "', " + option.description;
});
result = result.concat(options);
}
return result;
}, []);
return this._baseOptions = availableOptions.concat(strategyOptions);
}
|
javascript
|
function() {
if (this._baseOptions) {
return this._baseOptions;
}
var strategies = this.strategies();
var strategyOptions = Object.keys(strategies).reduce(function(result, strategyName) {
var options = strategies[strategyName].availableOptions;
if (Array.isArray(options)) {
// Add strategy qualifier to option descriptions
options.forEach(function(option) {
option.description = "when strategy is '" + strategyName + "', " + option.description;
});
result = result.concat(options);
}
return result;
}, []);
return this._baseOptions = availableOptions.concat(strategyOptions);
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_baseOptions",
")",
"{",
"return",
"this",
".",
"_baseOptions",
";",
"}",
"var",
"strategies",
"=",
"this",
".",
"strategies",
"(",
")",
";",
"var",
"strategyOptions",
"=",
"Object",
".",
"keys",
"(",
"strategies",
")",
".",
"reduce",
"(",
"function",
"(",
"result",
",",
"strategyName",
")",
"{",
"var",
"options",
"=",
"strategies",
"[",
"strategyName",
"]",
".",
"availableOptions",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"options",
")",
")",
"{",
"options",
".",
"forEach",
"(",
"function",
"(",
"option",
")",
"{",
"option",
".",
"description",
"=",
"\"when strategy is '\"",
"+",
"strategyName",
"+",
"\"', \"",
"+",
"option",
".",
"description",
";",
"}",
")",
";",
"result",
"=",
"result",
".",
"concat",
"(",
"options",
")",
";",
"}",
"return",
"result",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"this",
".",
"_baseOptions",
"=",
"availableOptions",
".",
"concat",
"(",
"strategyOptions",
")",
";",
"}"
] |
Combine base options with strategy specific options
|
[
"Combine",
"base",
"options",
"with",
"strategy",
"specific",
"options"
] |
e17d8305470e2a873cf3abfa0bdadefb4094bbba
|
https://github.com/shipshapecode/ember-cli-release/blob/e17d8305470e2a873cf3abfa0bdadefb4094bbba/lib/commands/release.js#L422-L444
|
train
|
|
taskcluster/azure-entities
|
src/entity.js
|
function(entity) {
assert(entity.PartitionKey, 'entity is missing \'PartitionKey\'');
assert(entity.RowKey, 'entity is missing \'RowKey\'');
assert(entity['odata.etag'], 'entity is missing \'odata.etag\'');
assert(entity.Version, 'entity is missing \'Version\'');
this._partitionKey = entity.PartitionKey;
this._rowKey = entity.RowKey;
this._version = entity.Version;
this._properties = this.__deserialize(entity);
this._etag = entity['odata.etag'];
}
|
javascript
|
function(entity) {
assert(entity.PartitionKey, 'entity is missing \'PartitionKey\'');
assert(entity.RowKey, 'entity is missing \'RowKey\'');
assert(entity['odata.etag'], 'entity is missing \'odata.etag\'');
assert(entity.Version, 'entity is missing \'Version\'');
this._partitionKey = entity.PartitionKey;
this._rowKey = entity.RowKey;
this._version = entity.Version;
this._properties = this.__deserialize(entity);
this._etag = entity['odata.etag'];
}
|
[
"function",
"(",
"entity",
")",
"{",
"assert",
"(",
"entity",
".",
"PartitionKey",
",",
"'entity is missing \\'PartitionKey\\''",
")",
";",
"\\'",
"\\'",
"assert",
"(",
"entity",
".",
"RowKey",
",",
"'entity is missing \\'RowKey\\''",
")",
";",
"\\'",
"\\'",
"assert",
"(",
"entity",
"[",
"'odata.etag'",
"]",
",",
"'entity is missing \\'odata.etag\\''",
")",
";",
"\\'",
"\\'",
"}"
] |
Base class of all entity
This constructor will wrap a raw azure-table-node entity.
|
[
"Base",
"class",
"of",
"all",
"entity"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entity.js#L84-L95
|
train
|
|
taskcluster/azure-entities
|
src/entity.js
|
function(b1, b2) {
var mismatch = 0;
mismatch |= !(b1 instanceof Buffer);
mismatch |= !(b2 instanceof Buffer);
mismatch |= b1.length !== b2.length;
if (mismatch === 1) {
return false;
}
var n = b1.length;
for (var i = 0; i < n; i++) {
mismatch |= b1[i] ^ b2[i];
}
return mismatch === 0;
}
|
javascript
|
function(b1, b2) {
var mismatch = 0;
mismatch |= !(b1 instanceof Buffer);
mismatch |= !(b2 instanceof Buffer);
mismatch |= b1.length !== b2.length;
if (mismatch === 1) {
return false;
}
var n = b1.length;
for (var i = 0; i < n; i++) {
mismatch |= b1[i] ^ b2[i];
}
return mismatch === 0;
}
|
[
"function",
"(",
"b1",
",",
"b2",
")",
"{",
"var",
"mismatch",
"=",
"0",
";",
"mismatch",
"|=",
"!",
"(",
"b1",
"instanceof",
"Buffer",
")",
";",
"mismatch",
"|=",
"!",
"(",
"b2",
"instanceof",
"Buffer",
")",
";",
"mismatch",
"|=",
"b1",
".",
"length",
"!==",
"b2",
".",
"length",
";",
"if",
"(",
"mismatch",
"===",
"1",
")",
"{",
"return",
"false",
";",
"}",
"var",
"n",
"=",
"b1",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"mismatch",
"|=",
"b1",
"[",
"i",
"]",
"^",
"b2",
"[",
"i",
"]",
";",
"}",
"return",
"mismatch",
"===",
"0",
";",
"}"
] |
Fixed time comparison of two buffers
|
[
"Fixed",
"time",
"comparison",
"of",
"two",
"buffers"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entity.js#L165-L178
|
train
|
|
taskcluster/azure-entities
|
src/entity.js
|
function(result) {
if (!result.nextPartitionKey && !result.nextRowKey) {
return null;
}
return (
encodeURIComponent(result.nextPartitionKey || '').replace(/~/g, '%7e') +
'~' +
encodeURIComponent(result.nextRowKey || '').replace(/~/g, '%7e')
);
}
|
javascript
|
function(result) {
if (!result.nextPartitionKey && !result.nextRowKey) {
return null;
}
return (
encodeURIComponent(result.nextPartitionKey || '').replace(/~/g, '%7e') +
'~' +
encodeURIComponent(result.nextRowKey || '').replace(/~/g, '%7e')
);
}
|
[
"function",
"(",
"result",
")",
"{",
"if",
"(",
"!",
"result",
".",
"nextPartitionKey",
"&&",
"!",
"result",
".",
"nextRowKey",
")",
"{",
"return",
"null",
";",
"}",
"return",
"(",
"encodeURIComponent",
"(",
"result",
".",
"nextPartitionKey",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"~",
"/",
"g",
",",
"'%7e'",
")",
"+",
"'~'",
"+",
"encodeURIComponent",
"(",
"result",
".",
"nextRowKey",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"~",
"/",
"g",
",",
"'%7e'",
")",
")",
";",
"}"
] |
Encode continuation token as single string using tilde as separator
|
[
"Encode",
"continuation",
"token",
"as",
"single",
"string",
"using",
"tilde",
"as",
"separator"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entity.js#L1065-L1074
|
train
|
|
taskcluster/azure-entities
|
src/entity.js
|
function(token) {
if (token === undefined || token === null) {
return {
nextPartitionKey: undefined,
nextRowKey: undefined,
};
}
assert(typeof token === 'string', 'Continuation token must be a string if ' +
'not undefined');
// Split at tilde (~)
token = token.split('~');
assert(token.length === 2, 'Expected an encoded continuation token with ' +
'a single tilde as separator');
return {
nextPartitionKey: decodeURIComponent(token[0]),
nextRowKey: decodeURIComponent(token[1]),
};
}
|
javascript
|
function(token) {
if (token === undefined || token === null) {
return {
nextPartitionKey: undefined,
nextRowKey: undefined,
};
}
assert(typeof token === 'string', 'Continuation token must be a string if ' +
'not undefined');
// Split at tilde (~)
token = token.split('~');
assert(token.length === 2, 'Expected an encoded continuation token with ' +
'a single tilde as separator');
return {
nextPartitionKey: decodeURIComponent(token[0]),
nextRowKey: decodeURIComponent(token[1]),
};
}
|
[
"function",
"(",
"token",
")",
"{",
"if",
"(",
"token",
"===",
"undefined",
"||",
"token",
"===",
"null",
")",
"{",
"return",
"{",
"nextPartitionKey",
":",
"undefined",
",",
"nextRowKey",
":",
"undefined",
",",
"}",
";",
"}",
"assert",
"(",
"typeof",
"token",
"===",
"'string'",
",",
"'Continuation token must be a string if '",
"+",
"'not undefined'",
")",
";",
"token",
"=",
"token",
".",
"split",
"(",
"'~'",
")",
";",
"assert",
"(",
"token",
".",
"length",
"===",
"2",
",",
"'Expected an encoded continuation token with '",
"+",
"'a single tilde as separator'",
")",
";",
"return",
"{",
"nextPartitionKey",
":",
"decodeURIComponent",
"(",
"token",
"[",
"0",
"]",
")",
",",
"nextRowKey",
":",
"decodeURIComponent",
"(",
"token",
"[",
"1",
"]",
")",
",",
"}",
";",
"}"
] |
Decode continuation token, inverse of encodeContinuationToken
|
[
"Decode",
"continuation",
"token",
"inverse",
"of",
"encodeContinuationToken"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entity.js#L1077-L1094
|
train
|
|
taskcluster/azure-entities
|
src/entity.js
|
function(continuation) {
var continuation = decodeContinuationToken(continuation);
return ClassProps.__aux.queryEntities({
filter: filter,
top: Math.min(options.limit, 1000),
nextPartitionKey: continuation.nextPartitionKey,
nextRowKey: continuation.nextRowKey,
}).then(function(data) {
return {
entries: data.entities.map(function(entity) {
return new Class(entity);
}),
continuation: encodeContinuationToken(data),
};
});
}
|
javascript
|
function(continuation) {
var continuation = decodeContinuationToken(continuation);
return ClassProps.__aux.queryEntities({
filter: filter,
top: Math.min(options.limit, 1000),
nextPartitionKey: continuation.nextPartitionKey,
nextRowKey: continuation.nextRowKey,
}).then(function(data) {
return {
entries: data.entities.map(function(entity) {
return new Class(entity);
}),
continuation: encodeContinuationToken(data),
};
});
}
|
[
"function",
"(",
"continuation",
")",
"{",
"var",
"continuation",
"=",
"decodeContinuationToken",
"(",
"continuation",
")",
";",
"return",
"ClassProps",
".",
"__aux",
".",
"queryEntities",
"(",
"{",
"filter",
":",
"filter",
",",
"top",
":",
"Math",
".",
"min",
"(",
"options",
".",
"limit",
",",
"1000",
")",
",",
"nextPartitionKey",
":",
"continuation",
".",
"nextPartitionKey",
",",
"nextRowKey",
":",
"continuation",
".",
"nextRowKey",
",",
"}",
")",
".",
"then",
"(",
"function",
"(",
"data",
")",
"{",
"return",
"{",
"entries",
":",
"data",
".",
"entities",
".",
"map",
"(",
"function",
"(",
"entity",
")",
"{",
"return",
"new",
"Class",
"(",
"entity",
")",
";",
"}",
")",
",",
"continuation",
":",
"encodeContinuationToken",
"(",
"data",
")",
",",
"}",
";",
"}",
")",
";",
"}"
] |
Fetch results with operational continuation token
|
[
"Fetch",
"results",
"with",
"operational",
"continuation",
"token"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entity.js#L1257-L1272
|
train
|
|
bakjs/bak
|
packages/bak/lib/utils.js
|
realIP
|
function realIP (request) {
return request.ip || request.headers['x-real-ip'] || request.headers['x-forwarded-for'] || request.info['remoteAddress']
}
|
javascript
|
function realIP (request) {
return request.ip || request.headers['x-real-ip'] || request.headers['x-forwarded-for'] || request.info['remoteAddress']
}
|
[
"function",
"realIP",
"(",
"request",
")",
"{",
"return",
"request",
".",
"ip",
"||",
"request",
".",
"headers",
"[",
"'x-real-ip'",
"]",
"||",
"request",
".",
"headers",
"[",
"'x-forwarded-for'",
"]",
"||",
"request",
".",
"info",
"[",
"'remoteAddress'",
"]",
"}"
] |
Try to detect request real ip
@param request
@returns string
|
[
"Try",
"to",
"detect",
"request",
"real",
"ip"
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/bak/lib/utils.js#L45-L47
|
train
|
bakjs/bak
|
packages/route-table/lib/table.js
|
getAllKeys
|
function getAllKeys (objArray) {
let keys = []
_.forEach(objArray, function (row) {
if (!row || typeof row === 'string') return
keys = keys.concat(Object.keys(row))
})
return _.union(keys)
}
|
javascript
|
function getAllKeys (objArray) {
let keys = []
_.forEach(objArray, function (row) {
if (!row || typeof row === 'string') return
keys = keys.concat(Object.keys(row))
})
return _.union(keys)
}
|
[
"function",
"getAllKeys",
"(",
"objArray",
")",
"{",
"let",
"keys",
"=",
"[",
"]",
"_",
".",
"forEach",
"(",
"objArray",
",",
"function",
"(",
"row",
")",
"{",
"if",
"(",
"!",
"row",
"||",
"typeof",
"row",
"===",
"'string'",
")",
"return",
"keys",
"=",
"keys",
".",
"concat",
"(",
"Object",
".",
"keys",
"(",
"row",
")",
")",
"}",
")",
"return",
"_",
".",
"union",
"(",
"keys",
")",
"}"
] |
Returns all keys for a given object.
@param objArray Object to get the keys of.
@returns {*} Array, containing all keys as string values.
|
[
"Returns",
"all",
"keys",
"for",
"a",
"given",
"object",
"."
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/route-table/lib/table.js#L83-L90
|
train
|
bakjs/bak
|
packages/route-table/lib/table.js
|
getMaxLength
|
function getMaxLength (keys, objArray) {
const maxRowLength = {}
_.forEach(keys, function (key) {
maxRowLength[key] = cleanString(key).length
})
_.forEach(objArray, function (objRow) {
_.forEach(objRow, function (val, key) {
const rowLength = cleanString(val).length
if (maxRowLength[key] < rowLength) {
maxRowLength[key] = rowLength
}
})
})
return maxRowLength
}
|
javascript
|
function getMaxLength (keys, objArray) {
const maxRowLength = {}
_.forEach(keys, function (key) {
maxRowLength[key] = cleanString(key).length
})
_.forEach(objArray, function (objRow) {
_.forEach(objRow, function (val, key) {
const rowLength = cleanString(val).length
if (maxRowLength[key] < rowLength) {
maxRowLength[key] = rowLength
}
})
})
return maxRowLength
}
|
[
"function",
"getMaxLength",
"(",
"keys",
",",
"objArray",
")",
"{",
"const",
"maxRowLength",
"=",
"{",
"}",
"_",
".",
"forEach",
"(",
"keys",
",",
"function",
"(",
"key",
")",
"{",
"maxRowLength",
"[",
"key",
"]",
"=",
"cleanString",
"(",
"key",
")",
".",
"length",
"}",
")",
"_",
".",
"forEach",
"(",
"objArray",
",",
"function",
"(",
"objRow",
")",
"{",
"_",
".",
"forEach",
"(",
"objRow",
",",
"function",
"(",
"val",
",",
"key",
")",
"{",
"const",
"rowLength",
"=",
"cleanString",
"(",
"val",
")",
".",
"length",
"if",
"(",
"maxRowLength",
"[",
"key",
"]",
"<",
"rowLength",
")",
"{",
"maxRowLength",
"[",
"key",
"]",
"=",
"rowLength",
"}",
"}",
")",
"}",
")",
"return",
"maxRowLength",
"}"
] |
Determines the longest value for each key.
@param keys The keys of the objects within the array.
@param objArray The object array.
@returns {Object} JSON object containing the max length for each key.
|
[
"Determines",
"the",
"longest",
"value",
"for",
"each",
"key",
"."
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/route-table/lib/table.js#L99-L115
|
train
|
bakjs/bak
|
packages/route-table/lib/table.js
|
function (printArray, format, preProcessor, settings) {
format = format || ''
preProcessor = preProcessor || []
settings = settings || defaultSettings
const INDENT = emptyString(settings.indent)
const ROW_SPACER = emptyString(settings.rowSpace)
const headings = getAllKeys(printArray)
const maxLength = getMaxLength(headings, printArray)
const maxLengths = Object.keys(maxLength).reduce((s, k) => s + maxLength[k], 0)
// print headline
const headline = []
const seperator = []
_.forEach(headings, function (header, i) {
headline.push(toLength(header, maxLength[header], 'c'))
seperator.push(new Array(maxLength[header] + 1).join('-'))
})
console.log(INDENT + seperator.join(ROW_SPACER))
console.log(INDENT + headline.join(ROW_SPACER))
console.log(INDENT + seperator.join(ROW_SPACER))
// print rows
_.forEach(printArray, function (row) {
const line = []
if (row === null || typeof row === 'string') {
if (row === null || row === '') {
return console.log('')
}
return console.log(chalk.grey.bold(toLength(row || '', maxLengths, 'l')))
}
_.forEach(headings, function (header, i) {
let str = row[header] || ''
if (_.isFunction(preProcessor[i])) {
str = preProcessor[i](str) || str
}
line.push(toLength(str, maxLength[header], format.substr(i, 1)))
})
console.log(INDENT + line.join(ROW_SPACER))
})
}
|
javascript
|
function (printArray, format, preProcessor, settings) {
format = format || ''
preProcessor = preProcessor || []
settings = settings || defaultSettings
const INDENT = emptyString(settings.indent)
const ROW_SPACER = emptyString(settings.rowSpace)
const headings = getAllKeys(printArray)
const maxLength = getMaxLength(headings, printArray)
const maxLengths = Object.keys(maxLength).reduce((s, k) => s + maxLength[k], 0)
// print headline
const headline = []
const seperator = []
_.forEach(headings, function (header, i) {
headline.push(toLength(header, maxLength[header], 'c'))
seperator.push(new Array(maxLength[header] + 1).join('-'))
})
console.log(INDENT + seperator.join(ROW_SPACER))
console.log(INDENT + headline.join(ROW_SPACER))
console.log(INDENT + seperator.join(ROW_SPACER))
// print rows
_.forEach(printArray, function (row) {
const line = []
if (row === null || typeof row === 'string') {
if (row === null || row === '') {
return console.log('')
}
return console.log(chalk.grey.bold(toLength(row || '', maxLengths, 'l')))
}
_.forEach(headings, function (header, i) {
let str = row[header] || ''
if (_.isFunction(preProcessor[i])) {
str = preProcessor[i](str) || str
}
line.push(toLength(str, maxLength[header], format.substr(i, 1)))
})
console.log(INDENT + line.join(ROW_SPACER))
})
}
|
[
"function",
"(",
"printArray",
",",
"format",
",",
"preProcessor",
",",
"settings",
")",
"{",
"format",
"=",
"format",
"||",
"''",
"preProcessor",
"=",
"preProcessor",
"||",
"[",
"]",
"settings",
"=",
"settings",
"||",
"defaultSettings",
"const",
"INDENT",
"=",
"emptyString",
"(",
"settings",
".",
"indent",
")",
"const",
"ROW_SPACER",
"=",
"emptyString",
"(",
"settings",
".",
"rowSpace",
")",
"const",
"headings",
"=",
"getAllKeys",
"(",
"printArray",
")",
"const",
"maxLength",
"=",
"getMaxLength",
"(",
"headings",
",",
"printArray",
")",
"const",
"maxLengths",
"=",
"Object",
".",
"keys",
"(",
"maxLength",
")",
".",
"reduce",
"(",
"(",
"s",
",",
"k",
")",
"=>",
"s",
"+",
"maxLength",
"[",
"k",
"]",
",",
"0",
")",
"const",
"headline",
"=",
"[",
"]",
"const",
"seperator",
"=",
"[",
"]",
"_",
".",
"forEach",
"(",
"headings",
",",
"function",
"(",
"header",
",",
"i",
")",
"{",
"headline",
".",
"push",
"(",
"toLength",
"(",
"header",
",",
"maxLength",
"[",
"header",
"]",
",",
"'c'",
")",
")",
"seperator",
".",
"push",
"(",
"new",
"Array",
"(",
"maxLength",
"[",
"header",
"]",
"+",
"1",
")",
".",
"join",
"(",
"'-'",
")",
")",
"}",
")",
"console",
".",
"log",
"(",
"INDENT",
"+",
"seperator",
".",
"join",
"(",
"ROW_SPACER",
")",
")",
"console",
".",
"log",
"(",
"INDENT",
"+",
"headline",
".",
"join",
"(",
"ROW_SPACER",
")",
")",
"console",
".",
"log",
"(",
"INDENT",
"+",
"seperator",
".",
"join",
"(",
"ROW_SPACER",
")",
")",
"_",
".",
"forEach",
"(",
"printArray",
",",
"function",
"(",
"row",
")",
"{",
"const",
"line",
"=",
"[",
"]",
"if",
"(",
"row",
"===",
"null",
"||",
"typeof",
"row",
"===",
"'string'",
")",
"{",
"if",
"(",
"row",
"===",
"null",
"||",
"row",
"===",
"''",
")",
"{",
"return",
"console",
".",
"log",
"(",
"''",
")",
"}",
"return",
"console",
".",
"log",
"(",
"chalk",
".",
"grey",
".",
"bold",
"(",
"toLength",
"(",
"row",
"||",
"''",
",",
"maxLengths",
",",
"'l'",
")",
")",
")",
"}",
"_",
".",
"forEach",
"(",
"headings",
",",
"function",
"(",
"header",
",",
"i",
")",
"{",
"let",
"str",
"=",
"row",
"[",
"header",
"]",
"||",
"''",
"if",
"(",
"_",
".",
"isFunction",
"(",
"preProcessor",
"[",
"i",
"]",
")",
")",
"{",
"str",
"=",
"preProcessor",
"[",
"i",
"]",
"(",
"str",
")",
"||",
"str",
"}",
"line",
".",
"push",
"(",
"toLength",
"(",
"str",
",",
"maxLength",
"[",
"header",
"]",
",",
"format",
".",
"substr",
"(",
"i",
",",
"1",
")",
")",
")",
"}",
")",
"console",
".",
"log",
"(",
"INDENT",
"+",
"line",
".",
"join",
"(",
"ROW_SPACER",
")",
")",
"}",
")",
"}"
] |
Prints a given array of json objects.
@param printArray The array of json objects to be printed.
@param format
@param preProcessor
@param settings
|
[
"Prints",
"a",
"given",
"array",
"of",
"json",
"objects",
"."
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/route-table/lib/table.js#L153-L200
|
train
|
|
bakjs/bak
|
packages/ratelimit/lib/index.js
|
setHeaders
|
function setHeaders (headers, ratelimit, XHeaders = false) {
if (XHeaders) {
headers['X-Rate-Limit-Limit'] = ratelimit.limit
headers['X-Rate-Limit-Remaining'] = ratelimit.remaining > 0 ? ratelimit.remaining : 0
headers['X-Rate-Limit-Reset'] = ratelimit.reset
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
headers['Retry-After'] = Math.ceil(ratelimit.reset / 1000)
}
|
javascript
|
function setHeaders (headers, ratelimit, XHeaders = false) {
if (XHeaders) {
headers['X-Rate-Limit-Limit'] = ratelimit.limit
headers['X-Rate-Limit-Remaining'] = ratelimit.remaining > 0 ? ratelimit.remaining : 0
headers['X-Rate-Limit-Reset'] = ratelimit.reset
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
headers['Retry-After'] = Math.ceil(ratelimit.reset / 1000)
}
|
[
"function",
"setHeaders",
"(",
"headers",
",",
"ratelimit",
",",
"XHeaders",
"=",
"false",
")",
"{",
"if",
"(",
"XHeaders",
")",
"{",
"headers",
"[",
"'X-Rate-Limit-Limit'",
"]",
"=",
"ratelimit",
".",
"limit",
"headers",
"[",
"'X-Rate-Limit-Remaining'",
"]",
"=",
"ratelimit",
".",
"remaining",
">",
"0",
"?",
"ratelimit",
".",
"remaining",
":",
"0",
"headers",
"[",
"'X-Rate-Limit-Reset'",
"]",
"=",
"ratelimit",
".",
"reset",
"}",
"headers",
"[",
"'Retry-After'",
"]",
"=",
"Math",
".",
"ceil",
"(",
"ratelimit",
".",
"reset",
"/",
"1000",
")",
"}"
] |
Set rate-limit headers
|
[
"Set",
"rate",
"-",
"limit",
"headers"
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/ratelimit/lib/index.js#L71-L80
|
train
|
taskcluster/azure-entities
|
src/entitytypes.js
|
function(name, property, value, types) {
if (!(types instanceof Array)) {
types = [types];
}
if (types.indexOf(typeof value) === -1) {
debug('%s \'%s\' expected %j got: %j', name, property, types, value);
throw new Error(name + ' \'' + property + '\' expected one of type(s): \'' +
types.join(',') + '\' got type: \'' + typeof value + '\'');
}
}
|
javascript
|
function(name, property, value, types) {
if (!(types instanceof Array)) {
types = [types];
}
if (types.indexOf(typeof value) === -1) {
debug('%s \'%s\' expected %j got: %j', name, property, types, value);
throw new Error(name + ' \'' + property + '\' expected one of type(s): \'' +
types.join(',') + '\' got type: \'' + typeof value + '\'');
}
}
|
[
"function",
"(",
"name",
",",
"property",
",",
"value",
",",
"types",
")",
"{",
"if",
"(",
"!",
"(",
"types",
"instanceof",
"Array",
")",
")",
"{",
"types",
"=",
"[",
"types",
"]",
";",
"}",
"if",
"(",
"types",
".",
"indexOf",
"(",
"typeof",
"value",
")",
"===",
"-",
"1",
")",
"{",
"debug",
"(",
"'%s \\'%s\\' expected %j got: %j'",
",",
"\\'",
",",
"\\'",
",",
"name",
",",
"property",
")",
";",
"types",
"}",
"}"
] |
Check that value is of types for name and property Print messages and throw an error if the check fails
|
[
"Check",
"that",
"value",
"is",
"of",
"types",
"for",
"name",
"and",
"property",
"Print",
"messages",
"and",
"throw",
"an",
"error",
"if",
"the",
"check",
"fails"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entitytypes.js#L15-L24
|
train
|
|
taskcluster/azure-entities
|
src/entitytypes.js
|
function(slug) {
var base64 = slug
.replace(/-/g, '+')
.replace(/_/g, '/')
+ '==';
return Buffer.from(base64, 'base64');
}
|
javascript
|
function(slug) {
var base64 = slug
.replace(/-/g, '+')
.replace(/_/g, '/')
+ '==';
return Buffer.from(base64, 'base64');
}
|
[
"function",
"(",
"slug",
")",
"{",
"var",
"base64",
"=",
"slug",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'+'",
")",
".",
"replace",
"(",
"/",
"_",
"/",
"g",
",",
"'/'",
")",
"+",
"'=='",
";",
"return",
"Buffer",
".",
"from",
"(",
"base64",
",",
"'base64'",
")",
";",
"}"
] |
Convert slugid to buffer
|
[
"Convert",
"slugid",
"to",
"buffer"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entitytypes.js#L893-L899
|
train
|
|
taskcluster/azure-entities
|
src/entitytypes.js
|
function(bufferView, entryIndex) {
return bufferView.toString('base64', entryIndex * SLUGID_SIZE, SLUGID_SIZE * (entryIndex + 1))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/==/g, '');
}
|
javascript
|
function(bufferView, entryIndex) {
return bufferView.toString('base64', entryIndex * SLUGID_SIZE, SLUGID_SIZE * (entryIndex + 1))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/==/g, '');
}
|
[
"function",
"(",
"bufferView",
",",
"entryIndex",
")",
"{",
"return",
"bufferView",
".",
"toString",
"(",
"'base64'",
",",
"entryIndex",
"*",
"SLUGID_SIZE",
",",
"SLUGID_SIZE",
"*",
"(",
"entryIndex",
"+",
"1",
")",
")",
".",
"replace",
"(",
"/",
"\\+",
"/",
"g",
",",
"'-'",
")",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'_'",
")",
".",
"replace",
"(",
"/",
"==",
"/",
"g",
",",
"''",
")",
";",
"}"
] |
Convert buffer to slugId where `entryIndex` is the slugId entry index to retrieve
|
[
"Convert",
"buffer",
"to",
"slugId",
"where",
"entryIndex",
"is",
"the",
"slugId",
"entry",
"index",
"to",
"retrieve"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entitytypes.js#L902-L907
|
train
|
|
taskcluster/azure-entities
|
src/entitykeys.js
|
function(str) {
// Check for empty string
if (str === '') {
return '!';
}
// 1. URL encode
// 2. URL encode all exclamation marks (replace ! with %21)
// 3. URL encode all tilde (replace ~ with %7e)
// This ensures that when using ~ as separator in CompositeKey we can
// do prefix matching
// 4. Replace % with exclamation marks for Azure compatibility
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/~/g, '%7e')
.replace(/%/g, '!');
}
|
javascript
|
function(str) {
// Check for empty string
if (str === '') {
return '!';
}
// 1. URL encode
// 2. URL encode all exclamation marks (replace ! with %21)
// 3. URL encode all tilde (replace ~ with %7e)
// This ensures that when using ~ as separator in CompositeKey we can
// do prefix matching
// 4. Replace % with exclamation marks for Azure compatibility
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/~/g, '%7e')
.replace(/%/g, '!');
}
|
[
"function",
"(",
"str",
")",
"{",
"if",
"(",
"str",
"===",
"''",
")",
"{",
"return",
"'!'",
";",
"}",
"return",
"encodeURIComponent",
"(",
"str",
")",
".",
"replace",
"(",
"/",
"!",
"/",
"g",
",",
"'%21'",
")",
".",
"replace",
"(",
"/",
"~",
"/",
"g",
",",
"'%7e'",
")",
".",
"replace",
"(",
"/",
"%",
"/",
"g",
",",
"'!'",
")",
";",
"}"
] |
Encode string-key, to escape characters for Azure Table Storage and replace
empty strings with a single '!', so that empty strings can be allowed.
|
[
"Encode",
"string",
"-",
"key",
"to",
"escape",
"characters",
"for",
"Azure",
"Table",
"Storage",
"and",
"replace",
"empty",
"strings",
"with",
"a",
"single",
"!",
"so",
"that",
"empty",
"strings",
"can",
"be",
"allowed",
"."
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entitykeys.js#L32-L47
|
train
|
|
taskcluster/azure-entities
|
src/entitykeys.js
|
function(mapping, key) {
// Set key
this.key = key;
// Set key type
assert(mapping[this.key], 'key \'' + key + '\' is not defined in mapping');
assert(mapping[this.key] instanceof Types.PositiveInteger,
'key \'' + key + '\' must be a PositiveInteger type');
this.type = mapping[this.key];
// Set covers
this.covers = [key];
}
|
javascript
|
function(mapping, key) {
// Set key
this.key = key;
// Set key type
assert(mapping[this.key], 'key \'' + key + '\' is not defined in mapping');
assert(mapping[this.key] instanceof Types.PositiveInteger,
'key \'' + key + '\' must be a PositiveInteger type');
this.type = mapping[this.key];
// Set covers
this.covers = [key];
}
|
[
"function",
"(",
"mapping",
",",
"key",
")",
"{",
"this",
".",
"key",
"=",
"key",
";",
"assert",
"(",
"mapping",
"[",
"this",
".",
"key",
"]",
",",
"'key \\''",
"+",
"\\'",
"+",
"key",
")",
";",
"'\\' is not defined in mapping'",
"\\'",
"assert",
"(",
"mapping",
"[",
"this",
".",
"key",
"]",
"instanceof",
"Types",
".",
"PositiveInteger",
",",
"'key \\''",
"+",
"\\'",
"+",
"key",
")",
";",
"}"
] |
Construct a DescendingIntegerKey
|
[
"Construct",
"a",
"DescendingIntegerKey"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entitykeys.js#L112-L124
|
train
|
|
taskcluster/azure-entities
|
src/entitykeys.js
|
function(mapping, keys) {
assert(keys instanceof Array, 'keys must be an array');
assert(keys.length > 0, 'CompositeKey needs at least one key');
// Set keys
this.keys = keys;
// Set key types
this.types = [];
for (var i = 0; i < keys.length; i++) {
assert(mapping[keys[i]], 'key \'' + keys[i] + '\' is not defined in mapping');
this.types[i] = mapping[keys[i]];
}
// Set covers
this.covers = keys;
}
|
javascript
|
function(mapping, keys) {
assert(keys instanceof Array, 'keys must be an array');
assert(keys.length > 0, 'CompositeKey needs at least one key');
// Set keys
this.keys = keys;
// Set key types
this.types = [];
for (var i = 0; i < keys.length; i++) {
assert(mapping[keys[i]], 'key \'' + keys[i] + '\' is not defined in mapping');
this.types[i] = mapping[keys[i]];
}
// Set covers
this.covers = keys;
}
|
[
"function",
"(",
"mapping",
",",
"keys",
")",
"{",
"assert",
"(",
"keys",
"instanceof",
"Array",
",",
"'keys must be an array'",
")",
";",
"assert",
"(",
"keys",
".",
"length",
">",
"0",
",",
"'CompositeKey needs at least one key'",
")",
";",
"this",
".",
"keys",
"=",
"keys",
";",
"this",
".",
"types",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"assert",
"(",
"mapping",
"[",
"keys",
"[",
"i",
"]",
"]",
",",
"'key \\''",
"+",
"\\'",
"+",
"keys",
"[",
"i",
"]",
")",
";",
"'\\' is not defined in mapping'",
"}",
"\\'",
"}"
] |
Construct a CompositeKey
|
[
"Construct",
"a",
"CompositeKey"
] |
1f756c0abd4b3429cabe6e11e9258c2005fd8f3a
|
https://github.com/taskcluster/azure-entities/blob/1f756c0abd4b3429cabe6e11e9258c2005fd8f3a/src/entitykeys.js#L244-L260
|
train
|
|
Esri/torii-provider-arcgis
|
addon/utils/url-utils.js
|
assembleUrl
|
function assembleUrl (parts, insertPort = false) {
let result;
if (insertPort) {
result = `${parts.protocol}://${parts.host}:${parts.port}`;
} else {
result = `${parts.protocol}://${parts.host}`;
}
if (parts.path) {
result = `${result}/${parts.path}`;
}
return result;
}
|
javascript
|
function assembleUrl (parts, insertPort = false) {
let result;
if (insertPort) {
result = `${parts.protocol}://${parts.host}:${parts.port}`;
} else {
result = `${parts.protocol}://${parts.host}`;
}
if (parts.path) {
result = `${result}/${parts.path}`;
}
return result;
}
|
[
"function",
"assembleUrl",
"(",
"parts",
",",
"insertPort",
"=",
"false",
")",
"{",
"let",
"result",
";",
"if",
"(",
"insertPort",
")",
"{",
"result",
"=",
"`",
"${",
"parts",
".",
"protocol",
"}",
"${",
"parts",
".",
"host",
"}",
"${",
"parts",
".",
"port",
"}",
"`",
";",
"}",
"else",
"{",
"result",
"=",
"`",
"${",
"parts",
".",
"protocol",
"}",
"${",
"parts",
".",
"host",
"}",
"`",
";",
"}",
"if",
"(",
"parts",
".",
"path",
")",
"{",
"result",
"=",
"`",
"${",
"result",
"}",
"${",
"parts",
".",
"path",
"}",
"`",
";",
"}",
"return",
"result",
";",
"}"
] |
Assemble a full url from a hash of parts, optionally forcing a port
|
[
"Assemble",
"a",
"full",
"url",
"from",
"a",
"hash",
"of",
"parts",
"optionally",
"forcing",
"a",
"port"
] |
8ea7c34ddca6197a5114d9fb1a5b5d9a2035f3fe
|
https://github.com/Esri/torii-provider-arcgis/blob/8ea7c34ddca6197a5114d9fb1a5b5d9a2035f3fe/addon/utils/url-utils.js#L76-L88
|
train
|
bakjs/bak
|
packages/mongo/lib/utils.js
|
logConnectionEvents
|
function logConnectionEvents (conn) {
// Emitted after getting disconnected from the db.
// _readyState: 0
conn.on('disconnected', () => {
conn.$logger.debug('Disconnected!')
})
// Emitted when this connection successfully connects to the db.
// May be emitted multiple times in reconnected scenarios.
// _readyState: 1
conn.on('connected', () => {
conn.$logger.success('Connected!')
})
// Emitted when connection.{open,openSet}() is executed on this connection.
// _readyState: 2
conn.on('connecting', () => {
conn.$logger.info('Connecting...')
})
// Emitted when connection.close() was executed.
// _readyState: 3
conn.on('disconnecting', () => {
conn.$logger.debug('Disconnecting...')
})
// Emitted when an error occurs on this connection.
conn.on('error', (error) => {
conn.$logger.error(error)
})
// Emitted after we connected and onOpen is executed
// on all of this connections models.
conn.on('open', () => {
conn.$logger.debug('Connection opened!')
})
// Emitted after we connected and subsequently disconnected,
// followed by successfully another successfull connection.
conn.on('reconnected', () => {
conn.$logger.debug('Reconnected!')
})
// Emitted in a replica-set scenario, when all nodes specified
// in the connection string are connected.
conn.on('fullsetup', () => {
conn.$logger.debug('ReplicaSet ready!')
})
}
|
javascript
|
function logConnectionEvents (conn) {
// Emitted after getting disconnected from the db.
// _readyState: 0
conn.on('disconnected', () => {
conn.$logger.debug('Disconnected!')
})
// Emitted when this connection successfully connects to the db.
// May be emitted multiple times in reconnected scenarios.
// _readyState: 1
conn.on('connected', () => {
conn.$logger.success('Connected!')
})
// Emitted when connection.{open,openSet}() is executed on this connection.
// _readyState: 2
conn.on('connecting', () => {
conn.$logger.info('Connecting...')
})
// Emitted when connection.close() was executed.
// _readyState: 3
conn.on('disconnecting', () => {
conn.$logger.debug('Disconnecting...')
})
// Emitted when an error occurs on this connection.
conn.on('error', (error) => {
conn.$logger.error(error)
})
// Emitted after we connected and onOpen is executed
// on all of this connections models.
conn.on('open', () => {
conn.$logger.debug('Connection opened!')
})
// Emitted after we connected and subsequently disconnected,
// followed by successfully another successfull connection.
conn.on('reconnected', () => {
conn.$logger.debug('Reconnected!')
})
// Emitted in a replica-set scenario, when all nodes specified
// in the connection string are connected.
conn.on('fullsetup', () => {
conn.$logger.debug('ReplicaSet ready!')
})
}
|
[
"function",
"logConnectionEvents",
"(",
"conn",
")",
"{",
"conn",
".",
"on",
"(",
"'disconnected'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"debug",
"(",
"'Disconnected!'",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'connected'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"success",
"(",
"'Connected!'",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'connecting'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"info",
"(",
"'Connecting...'",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'disconnecting'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"debug",
"(",
"'Disconnecting...'",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'error'",
",",
"(",
"error",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"error",
"(",
"error",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'open'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"debug",
"(",
"'Connection opened!'",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'reconnected'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"debug",
"(",
"'Reconnected!'",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'fullsetup'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"$logger",
".",
"debug",
"(",
"'ReplicaSet ready!'",
")",
"}",
")",
"}"
] |
Utiliy function to setup logger on db
|
[
"Utiliy",
"function",
"to",
"setup",
"logger",
"on",
"db"
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/mongo/lib/utils.js#L4-L52
|
train
|
bakjs/bak
|
packages/mongo/lib/utils.js
|
connect
|
async function connect (mongoose, connectionName, connectionOpts) {
const isDefault = connectionName === 'default'
// Normalize and destructure connection options
if (typeof connectionOpts === 'string') {
connectionOpts = { uri: connectionOpts }
}
let { uri, options, forceReconnect } = connectionOpts
// Apply default options
// https://mongoosejs.com/docs/connections.html#options
options = {
useNewUrlParser: true,
useCreateIndex: true,
...options
}
// Manualy create connection
let conn
if (isDefault) {
conn = mongoose.connection
} else {
conn = new mongoose.Connection(mongoose)
mongoose.connections.push(conn)
}
// $logger helper
conn.$logger = isDefault
? consola
: consola.withTag(connectionName)
// Log connection events
logConnectionEvents(conn)
// $connect helper
conn.$connect = () => {
return new Promise((resolve, reject) => {
conn.openUri(uri, options, (error) => {
if (error) {
reject(error)
} else {
resolve(conn)
}
})
})
}
// Make accessable via mongoose.$connectionName
mongoose['$' + connectionName] = conn
// Setup force reconnect
if (forceReconnect) {
const timeout = forceReconnect === true ? 1000 : forceReconnect
conn.on('error', () => {
conn.close()
})
conn.on('disconnected', () => {
setTimeout(() => { conn.$connect() }, timeout)
})
}
// Connect
await conn.$connect()
await conn.$initialConnection
}
|
javascript
|
async function connect (mongoose, connectionName, connectionOpts) {
const isDefault = connectionName === 'default'
// Normalize and destructure connection options
if (typeof connectionOpts === 'string') {
connectionOpts = { uri: connectionOpts }
}
let { uri, options, forceReconnect } = connectionOpts
// Apply default options
// https://mongoosejs.com/docs/connections.html#options
options = {
useNewUrlParser: true,
useCreateIndex: true,
...options
}
// Manualy create connection
let conn
if (isDefault) {
conn = mongoose.connection
} else {
conn = new mongoose.Connection(mongoose)
mongoose.connections.push(conn)
}
// $logger helper
conn.$logger = isDefault
? consola
: consola.withTag(connectionName)
// Log connection events
logConnectionEvents(conn)
// $connect helper
conn.$connect = () => {
return new Promise((resolve, reject) => {
conn.openUri(uri, options, (error) => {
if (error) {
reject(error)
} else {
resolve(conn)
}
})
})
}
// Make accessable via mongoose.$connectionName
mongoose['$' + connectionName] = conn
// Setup force reconnect
if (forceReconnect) {
const timeout = forceReconnect === true ? 1000 : forceReconnect
conn.on('error', () => {
conn.close()
})
conn.on('disconnected', () => {
setTimeout(() => { conn.$connect() }, timeout)
})
}
// Connect
await conn.$connect()
await conn.$initialConnection
}
|
[
"async",
"function",
"connect",
"(",
"mongoose",
",",
"connectionName",
",",
"connectionOpts",
")",
"{",
"const",
"isDefault",
"=",
"connectionName",
"===",
"'default'",
"if",
"(",
"typeof",
"connectionOpts",
"===",
"'string'",
")",
"{",
"connectionOpts",
"=",
"{",
"uri",
":",
"connectionOpts",
"}",
"}",
"let",
"{",
"uri",
",",
"options",
",",
"forceReconnect",
"}",
"=",
"connectionOpts",
"options",
"=",
"{",
"useNewUrlParser",
":",
"true",
",",
"useCreateIndex",
":",
"true",
",",
"...",
"options",
"}",
"let",
"conn",
"if",
"(",
"isDefault",
")",
"{",
"conn",
"=",
"mongoose",
".",
"connection",
"}",
"else",
"{",
"conn",
"=",
"new",
"mongoose",
".",
"Connection",
"(",
"mongoose",
")",
"mongoose",
".",
"connections",
".",
"push",
"(",
"conn",
")",
"}",
"conn",
".",
"$logger",
"=",
"isDefault",
"?",
"consola",
":",
"consola",
".",
"withTag",
"(",
"connectionName",
")",
"logConnectionEvents",
"(",
"conn",
")",
"conn",
".",
"$connect",
"=",
"(",
")",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"conn",
".",
"openUri",
"(",
"uri",
",",
"options",
",",
"(",
"error",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
"}",
"else",
"{",
"resolve",
"(",
"conn",
")",
"}",
"}",
")",
"}",
")",
"}",
"mongoose",
"[",
"'$'",
"+",
"connectionName",
"]",
"=",
"conn",
"if",
"(",
"forceReconnect",
")",
"{",
"const",
"timeout",
"=",
"forceReconnect",
"===",
"true",
"?",
"1000",
":",
"forceReconnect",
"conn",
".",
"on",
"(",
"'error'",
",",
"(",
")",
"=>",
"{",
"conn",
".",
"close",
"(",
")",
"}",
")",
"conn",
".",
"on",
"(",
"'disconnected'",
",",
"(",
")",
"=>",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"conn",
".",
"$connect",
"(",
")",
"}",
",",
"timeout",
")",
"}",
")",
"}",
"await",
"conn",
".",
"$connect",
"(",
")",
"await",
"conn",
".",
"$initialConnection",
"}"
] |
Utility function to setup a connection
|
[
"Utility",
"function",
"to",
"setup",
"a",
"connection"
] |
b7a0d95cc60bca992c00effcb85a10999c57b6f5
|
https://github.com/bakjs/bak/blob/b7a0d95cc60bca992c00effcb85a10999c57b6f5/packages/mongo/lib/utils.js#L55-L119
|
train
|
afloyd/mongo-migrate
|
lib/set.js
|
positionOfMigration
|
function positionOfMigration(migrations, filename) {
for (var i = 0; i < migrations.length; ++i) {
if (migrations[i].title == filename) {
return i;
}
}
return -1;
}
|
javascript
|
function positionOfMigration(migrations, filename) {
for (var i = 0; i < migrations.length; ++i) {
if (migrations[i].title == filename) {
return i;
}
}
return -1;
}
|
[
"function",
"positionOfMigration",
"(",
"migrations",
",",
"filename",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"migrations",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"migrations",
"[",
"i",
"]",
".",
"title",
"==",
"filename",
")",
"{",
"return",
"i",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] |
Get index of given migration in list of migrations
@api private
|
[
"Get",
"index",
"of",
"given",
"migration",
"in",
"list",
"of",
"migrations"
] |
eaeb7baebe9028a8b733871de4f5df7e7004401f
|
https://github.com/afloyd/mongo-migrate/blob/eaeb7baebe9028a8b733871de4f5df7e7004401f/lib/set.js#L111-L118
|
train
|
afloyd/mongo-migrate
|
index.js
|
migrations
|
function migrations(direction, lastMigrationNum, migrateTo) {
var isDirectionUp = direction === 'up',
hasMigrateTo = !!migrateTo,
migrateToNum = hasMigrateTo ? parseInt(migrateTo, 10) : undefined,
migrateToFound = !hasMigrateTo;
var migrationsToRun = fs.readdirSync('migrations')
.filter(function (file) {
var formatCorrect = file.match(/^\d+.*\.js$/),
migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum,
isFile = fs.statSync(path.join('migrations', file)).isFile();
if (isFile && !formatCorrect) {
console.log('"' + file + '" ignored. Does not match migration naming schema');
}
return formatCorrect && isRunnable && isFile;
}).sort(function (a, b) {
var aMigrationNum = parseInt(a.match(/^\d+/)[0], 10),
bMigrationNum = parseInt(b.match(/^\d+/)[0], 10);
if (aMigrationNum > bMigrationNum) {
return isDirectionUp ? 1 : -1;
}
if (aMigrationNum < bMigrationNum) {
return isDirectionUp ? -1 : 1;
}
return 0;
}).filter(function(file){
var formatCorrect = file.match(/^\d+.*\.js$/),
migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum;
if (hasMigrateTo) {
if (migrateToNum === migrationNum) {
migrateToFound = true;
}
if (isDirectionUp) {
isRunnable = isRunnable && migrateToNum >= migrationNum;
} else {
isRunnable = isRunnable && migrateToNum < migrationNum;
}
}
return formatCorrect && isRunnable;
}).map(function(file){
return 'migrations/' + file;
});
if (!migrateToFound) {
return abort('migration `'+ migrateTo + '` not found!');
}
return migrationsToRun;
}
|
javascript
|
function migrations(direction, lastMigrationNum, migrateTo) {
var isDirectionUp = direction === 'up',
hasMigrateTo = !!migrateTo,
migrateToNum = hasMigrateTo ? parseInt(migrateTo, 10) : undefined,
migrateToFound = !hasMigrateTo;
var migrationsToRun = fs.readdirSync('migrations')
.filter(function (file) {
var formatCorrect = file.match(/^\d+.*\.js$/),
migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum,
isFile = fs.statSync(path.join('migrations', file)).isFile();
if (isFile && !formatCorrect) {
console.log('"' + file + '" ignored. Does not match migration naming schema');
}
return formatCorrect && isRunnable && isFile;
}).sort(function (a, b) {
var aMigrationNum = parseInt(a.match(/^\d+/)[0], 10),
bMigrationNum = parseInt(b.match(/^\d+/)[0], 10);
if (aMigrationNum > bMigrationNum) {
return isDirectionUp ? 1 : -1;
}
if (aMigrationNum < bMigrationNum) {
return isDirectionUp ? -1 : 1;
}
return 0;
}).filter(function(file){
var formatCorrect = file.match(/^\d+.*\.js$/),
migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum;
if (hasMigrateTo) {
if (migrateToNum === migrationNum) {
migrateToFound = true;
}
if (isDirectionUp) {
isRunnable = isRunnable && migrateToNum >= migrationNum;
} else {
isRunnable = isRunnable && migrateToNum < migrationNum;
}
}
return formatCorrect && isRunnable;
}).map(function(file){
return 'migrations/' + file;
});
if (!migrateToFound) {
return abort('migration `'+ migrateTo + '` not found!');
}
return migrationsToRun;
}
|
[
"function",
"migrations",
"(",
"direction",
",",
"lastMigrationNum",
",",
"migrateTo",
")",
"{",
"var",
"isDirectionUp",
"=",
"direction",
"===",
"'up'",
",",
"hasMigrateTo",
"=",
"!",
"!",
"migrateTo",
",",
"migrateToNum",
"=",
"hasMigrateTo",
"?",
"parseInt",
"(",
"migrateTo",
",",
"10",
")",
":",
"undefined",
",",
"migrateToFound",
"=",
"!",
"hasMigrateTo",
";",
"var",
"migrationsToRun",
"=",
"fs",
".",
"readdirSync",
"(",
"'migrations'",
")",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"formatCorrect",
"=",
"file",
".",
"match",
"(",
"/",
"^\\d+.*\\.js$",
"/",
")",
",",
"migrationNum",
"=",
"formatCorrect",
"&&",
"parseInt",
"(",
"file",
".",
"match",
"(",
"/",
"^\\d+",
"/",
")",
"[",
"0",
"]",
",",
"10",
")",
",",
"isRunnable",
"=",
"formatCorrect",
"&&",
"isDirectionUp",
"?",
"migrationNum",
">",
"lastMigrationNum",
":",
"migrationNum",
"<=",
"lastMigrationNum",
",",
"isFile",
"=",
"fs",
".",
"statSync",
"(",
"path",
".",
"join",
"(",
"'migrations'",
",",
"file",
")",
")",
".",
"isFile",
"(",
")",
";",
"if",
"(",
"isFile",
"&&",
"!",
"formatCorrect",
")",
"{",
"console",
".",
"log",
"(",
"'\"'",
"+",
"file",
"+",
"'\" ignored. Does not match migration naming schema'",
")",
";",
"}",
"return",
"formatCorrect",
"&&",
"isRunnable",
"&&",
"isFile",
";",
"}",
")",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"aMigrationNum",
"=",
"parseInt",
"(",
"a",
".",
"match",
"(",
"/",
"^\\d+",
"/",
")",
"[",
"0",
"]",
",",
"10",
")",
",",
"bMigrationNum",
"=",
"parseInt",
"(",
"b",
".",
"match",
"(",
"/",
"^\\d+",
"/",
")",
"[",
"0",
"]",
",",
"10",
")",
";",
"if",
"(",
"aMigrationNum",
">",
"bMigrationNum",
")",
"{",
"return",
"isDirectionUp",
"?",
"1",
":",
"-",
"1",
";",
"}",
"if",
"(",
"aMigrationNum",
"<",
"bMigrationNum",
")",
"{",
"return",
"isDirectionUp",
"?",
"-",
"1",
":",
"1",
";",
"}",
"return",
"0",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"formatCorrect",
"=",
"file",
".",
"match",
"(",
"/",
"^\\d+.*\\.js$",
"/",
")",
",",
"migrationNum",
"=",
"formatCorrect",
"&&",
"parseInt",
"(",
"file",
".",
"match",
"(",
"/",
"^\\d+",
"/",
")",
"[",
"0",
"]",
",",
"10",
")",
",",
"isRunnable",
"=",
"formatCorrect",
"&&",
"isDirectionUp",
"?",
"migrationNum",
">",
"lastMigrationNum",
":",
"migrationNum",
"<=",
"lastMigrationNum",
";",
"if",
"(",
"hasMigrateTo",
")",
"{",
"if",
"(",
"migrateToNum",
"===",
"migrationNum",
")",
"{",
"migrateToFound",
"=",
"true",
";",
"}",
"if",
"(",
"isDirectionUp",
")",
"{",
"isRunnable",
"=",
"isRunnable",
"&&",
"migrateToNum",
">=",
"migrationNum",
";",
"}",
"else",
"{",
"isRunnable",
"=",
"isRunnable",
"&&",
"migrateToNum",
"<",
"migrationNum",
";",
"}",
"}",
"return",
"formatCorrect",
"&&",
"isRunnable",
";",
"}",
")",
".",
"map",
"(",
"function",
"(",
"file",
")",
"{",
"return",
"'migrations/'",
"+",
"file",
";",
"}",
")",
";",
"if",
"(",
"!",
"migrateToFound",
")",
"{",
"return",
"abort",
"(",
"'migration `'",
"+",
"migrateTo",
"+",
"'` not found!'",
")",
";",
"}",
"return",
"migrationsToRun",
";",
"}"
] |
Load migrations.
@param {String} direction
@param {Number} lastMigrationNum
@param {Number} migrateTo
|
[
"Load",
"migrations",
"."
] |
eaeb7baebe9028a8b733871de4f5df7e7004401f
|
https://github.com/afloyd/mongo-migrate/blob/eaeb7baebe9028a8b733871de4f5df7e7004401f/index.js#L131-L188
|
train
|
afloyd/mongo-migrate
|
index.js
|
create
|
function create(name) {
var path = 'migrations/' + name + '.js';
log('create', join(process.cwd(), path));
fs.writeFileSync(path, template);
}
|
javascript
|
function create(name) {
var path = 'migrations/' + name + '.js';
log('create', join(process.cwd(), path));
fs.writeFileSync(path, template);
}
|
[
"function",
"create",
"(",
"name",
")",
"{",
"var",
"path",
"=",
"'migrations/'",
"+",
"name",
"+",
"'.js'",
";",
"log",
"(",
"'create'",
",",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"path",
")",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"path",
",",
"template",
")",
";",
"}"
] |
Create a migration with the given `name`.
@param {String} name
|
[
"Create",
"a",
"migration",
"with",
"the",
"given",
"name",
"."
] |
eaeb7baebe9028a8b733871de4f5df7e7004401f
|
https://github.com/afloyd/mongo-migrate/blob/eaeb7baebe9028a8b733871de4f5df7e7004401f/index.js#L239-L243
|
train
|
afloyd/mongo-migrate
|
index.js
|
performMigration
|
function performMigration(direction, migrateTo, next) {
if (!next &&
Object.prototype.toString.call(migrateTo) === '[object Function]') {
next = migrateTo;
migrateTo = undefined;
}
if (!next) {
next = function(err) {
if (err) {
console.error(err);
process.exit(1);
} else {
process.exit();
}
}
}
var db = require('./lib/db');
db.getConnection(dbConfig || require(process.cwd() + path.sep + configFileName)[dbProperty], function (err, db) {
if (err) {
return next(new verror.WError(err, 'Error connecting to database'));
}
var migrationCollection = db.migrationCollection,
dbConnection = db.connection;
migrationCollection.find({}).sort({num: -1}).limit(1).toArray(function (err, migrationsRun) {
if (err) {
return next(new verror.WError(err, 'Error querying migration collection'));
}
var lastMigration = migrationsRun[0],
lastMigrationNum = lastMigration ? lastMigration.num : 0;
migrate({
migrationTitle: 'migrations/.migrate',
db: dbConnection,
migrationCollection: migrationCollection
});
migrations(direction, lastMigrationNum, migrateTo).forEach(function(path){
var mod = require(process.cwd() + '/' + path);
migrate({
num: parseInt(path.split('/')[1].match(/^(\d+)/)[0], 10),
title: path,
up: mod.up,
down: mod.down});
});
//Revert working directory to previous state
process.chdir(previousWorkingDirectory);
var set = migrate();
set.on('migration', function(migration, direction){
log(direction, migration.title);
});
set.on('save', function(){
log('migration', 'complete');
return next();
});
set[direction](null, lastMigrationNum);
});
});
}
|
javascript
|
function performMigration(direction, migrateTo, next) {
if (!next &&
Object.prototype.toString.call(migrateTo) === '[object Function]') {
next = migrateTo;
migrateTo = undefined;
}
if (!next) {
next = function(err) {
if (err) {
console.error(err);
process.exit(1);
} else {
process.exit();
}
}
}
var db = require('./lib/db');
db.getConnection(dbConfig || require(process.cwd() + path.sep + configFileName)[dbProperty], function (err, db) {
if (err) {
return next(new verror.WError(err, 'Error connecting to database'));
}
var migrationCollection = db.migrationCollection,
dbConnection = db.connection;
migrationCollection.find({}).sort({num: -1}).limit(1).toArray(function (err, migrationsRun) {
if (err) {
return next(new verror.WError(err, 'Error querying migration collection'));
}
var lastMigration = migrationsRun[0],
lastMigrationNum = lastMigration ? lastMigration.num : 0;
migrate({
migrationTitle: 'migrations/.migrate',
db: dbConnection,
migrationCollection: migrationCollection
});
migrations(direction, lastMigrationNum, migrateTo).forEach(function(path){
var mod = require(process.cwd() + '/' + path);
migrate({
num: parseInt(path.split('/')[1].match(/^(\d+)/)[0], 10),
title: path,
up: mod.up,
down: mod.down});
});
//Revert working directory to previous state
process.chdir(previousWorkingDirectory);
var set = migrate();
set.on('migration', function(migration, direction){
log(direction, migration.title);
});
set.on('save', function(){
log('migration', 'complete');
return next();
});
set[direction](null, lastMigrationNum);
});
});
}
|
[
"function",
"performMigration",
"(",
"direction",
",",
"migrateTo",
",",
"next",
")",
"{",
"if",
"(",
"!",
"next",
"&&",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"migrateTo",
")",
"===",
"'[object Function]'",
")",
"{",
"next",
"=",
"migrateTo",
";",
"migrateTo",
"=",
"undefined",
";",
"}",
"if",
"(",
"!",
"next",
")",
"{",
"next",
"=",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"else",
"{",
"process",
".",
"exit",
"(",
")",
";",
"}",
"}",
"}",
"var",
"db",
"=",
"require",
"(",
"'./lib/db'",
")",
";",
"db",
".",
"getConnection",
"(",
"dbConfig",
"||",
"require",
"(",
"process",
".",
"cwd",
"(",
")",
"+",
"path",
".",
"sep",
"+",
"configFileName",
")",
"[",
"dbProperty",
"]",
",",
"function",
"(",
"err",
",",
"db",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"new",
"verror",
".",
"WError",
"(",
"err",
",",
"'Error connecting to database'",
")",
")",
";",
"}",
"var",
"migrationCollection",
"=",
"db",
".",
"migrationCollection",
",",
"dbConnection",
"=",
"db",
".",
"connection",
";",
"migrationCollection",
".",
"find",
"(",
"{",
"}",
")",
".",
"sort",
"(",
"{",
"num",
":",
"-",
"1",
"}",
")",
".",
"limit",
"(",
"1",
")",
".",
"toArray",
"(",
"function",
"(",
"err",
",",
"migrationsRun",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"new",
"verror",
".",
"WError",
"(",
"err",
",",
"'Error querying migration collection'",
")",
")",
";",
"}",
"var",
"lastMigration",
"=",
"migrationsRun",
"[",
"0",
"]",
",",
"lastMigrationNum",
"=",
"lastMigration",
"?",
"lastMigration",
".",
"num",
":",
"0",
";",
"migrate",
"(",
"{",
"migrationTitle",
":",
"'migrations/.migrate'",
",",
"db",
":",
"dbConnection",
",",
"migrationCollection",
":",
"migrationCollection",
"}",
")",
";",
"migrations",
"(",
"direction",
",",
"lastMigrationNum",
",",
"migrateTo",
")",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"var",
"mod",
"=",
"require",
"(",
"process",
".",
"cwd",
"(",
")",
"+",
"'/'",
"+",
"path",
")",
";",
"migrate",
"(",
"{",
"num",
":",
"parseInt",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
".",
"match",
"(",
"/",
"^(\\d+)",
"/",
")",
"[",
"0",
"]",
",",
"10",
")",
",",
"title",
":",
"path",
",",
"up",
":",
"mod",
".",
"up",
",",
"down",
":",
"mod",
".",
"down",
"}",
")",
";",
"}",
")",
";",
"process",
".",
"chdir",
"(",
"previousWorkingDirectory",
")",
";",
"var",
"set",
"=",
"migrate",
"(",
")",
";",
"set",
".",
"on",
"(",
"'migration'",
",",
"function",
"(",
"migration",
",",
"direction",
")",
"{",
"log",
"(",
"direction",
",",
"migration",
".",
"title",
")",
";",
"}",
")",
";",
"set",
".",
"on",
"(",
"'save'",
",",
"function",
"(",
")",
"{",
"log",
"(",
"'migration'",
",",
"'complete'",
")",
";",
"return",
"next",
"(",
")",
";",
"}",
")",
";",
"set",
"[",
"direction",
"]",
"(",
"null",
",",
"lastMigrationNum",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Perform a migration in the given `direction`.
@param {String} direction
|
[
"Perform",
"a",
"migration",
"in",
"the",
"given",
"direction",
"."
] |
eaeb7baebe9028a8b733871de4f5df7e7004401f
|
https://github.com/afloyd/mongo-migrate/blob/eaeb7baebe9028a8b733871de4f5df7e7004401f/index.js#L250-L315
|
train
|
jasonslyvia/react-menu-aim
|
index.js
|
on
|
function on(el, eventName, callback) {
if (el.addEventListener) {
el.addEventListener(eventName, callback, false);
}
else if (el.attachEvent) {
el.attachEvent('on'+eventName, function(e) {
callback.call(el, e || window.event);
});
}
}
|
javascript
|
function on(el, eventName, callback) {
if (el.addEventListener) {
el.addEventListener(eventName, callback, false);
}
else if (el.attachEvent) {
el.attachEvent('on'+eventName, function(e) {
callback.call(el, e || window.event);
});
}
}
|
[
"function",
"on",
"(",
"el",
",",
"eventName",
",",
"callback",
")",
"{",
"if",
"(",
"el",
".",
"addEventListener",
")",
"{",
"el",
".",
"addEventListener",
"(",
"eventName",
",",
"callback",
",",
"false",
")",
";",
"}",
"else",
"if",
"(",
"el",
".",
"attachEvent",
")",
"{",
"el",
".",
"attachEvent",
"(",
"'on'",
"+",
"eventName",
",",
"function",
"(",
"e",
")",
"{",
"callback",
".",
"call",
"(",
"el",
",",
"e",
"||",
"window",
".",
"event",
")",
";",
"}",
")",
";",
"}",
"}"
] |
bigger = more forgivey when entering submenu
DOM helpers
|
[
"bigger",
"=",
"more",
"forgivey",
"when",
"entering",
"submenu"
] |
88b25db1dbd3d217f91cbf2128c150d95bc7cb89
|
https://github.com/jasonslyvia/react-menu-aim/blob/88b25db1dbd3d217f91cbf2128c150d95bc7cb89/index.js#L20-L29
|
train
|
mikeric/sightglass
|
index.js
|
sightglass
|
function sightglass(obj, keypath, callback, options) {
return new Observer(obj, keypath, callback, options)
}
|
javascript
|
function sightglass(obj, keypath, callback, options) {
return new Observer(obj, keypath, callback, options)
}
|
[
"function",
"sightglass",
"(",
"obj",
",",
"keypath",
",",
"callback",
",",
"options",
")",
"{",
"return",
"new",
"Observer",
"(",
"obj",
",",
"keypath",
",",
"callback",
",",
"options",
")",
"}"
] |
Public sightglass interface.
|
[
"Public",
"sightglass",
"interface",
"."
] |
814dbcb0ee7ed970fa607108dc79474a795070f9
|
https://github.com/mikeric/sightglass/blob/814dbcb0ee7ed970fa607108dc79474a795070f9/index.js#L3-L5
|
train
|
mikeric/sightglass
|
index.js
|
Observer
|
function Observer(obj, keypath, callback, options) {
this.options = options || {}
this.options.adapters = this.options.adapters || {}
this.obj = obj
this.keypath = keypath
this.callback = callback
this.objectPath = []
this.update = this.update.bind(this)
this.parse()
if (isObject(this.target = this.realize())) {
this.set(true, this.key, this.target, this.callback)
}
}
|
javascript
|
function Observer(obj, keypath, callback, options) {
this.options = options || {}
this.options.adapters = this.options.adapters || {}
this.obj = obj
this.keypath = keypath
this.callback = callback
this.objectPath = []
this.update = this.update.bind(this)
this.parse()
if (isObject(this.target = this.realize())) {
this.set(true, this.key, this.target, this.callback)
}
}
|
[
"function",
"Observer",
"(",
"obj",
",",
"keypath",
",",
"callback",
",",
"options",
")",
"{",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
"this",
".",
"options",
".",
"adapters",
"=",
"this",
".",
"options",
".",
"adapters",
"||",
"{",
"}",
"this",
".",
"obj",
"=",
"obj",
"this",
".",
"keypath",
"=",
"keypath",
"this",
".",
"callback",
"=",
"callback",
"this",
".",
"objectPath",
"=",
"[",
"]",
"this",
".",
"update",
"=",
"this",
".",
"update",
".",
"bind",
"(",
"this",
")",
"this",
".",
"parse",
"(",
")",
"if",
"(",
"isObject",
"(",
"this",
".",
"target",
"=",
"this",
".",
"realize",
"(",
")",
")",
")",
"{",
"this",
".",
"set",
"(",
"true",
",",
"this",
".",
"key",
",",
"this",
".",
"target",
",",
"this",
".",
"callback",
")",
"}",
"}"
] |
Constructs a new keypath observer and kicks things off.
|
[
"Constructs",
"a",
"new",
"keypath",
"observer",
"and",
"kicks",
"things",
"off",
"."
] |
814dbcb0ee7ed970fa607108dc79474a795070f9
|
https://github.com/mikeric/sightglass/blob/814dbcb0ee7ed970fa607108dc79474a795070f9/index.js#L11-L24
|
train
|
leapmotion/leapjs-plugins
|
main/leap-plugins-0.1.12.js
|
function () {
var player = this;
// This is the original normal protocol, used while in record mode but not recording.
this.stopProtocol = this.controller.connection.protocol;
// This consumes all frame data, making the device act as if not streaming
this.playbackProtocol = function (data) {
// The old protocol still needs to emit events, so we use it, but intercept Frames
var eventOrFrame = player.stopProtocol(data);
if (eventOrFrame instanceof Leap.Frame) {
if (player.pauseOnHand) {
if (data.hands.length > 0) {
player.userHasControl = true;
player.controller.emit('playback.userTakeControl');
player.setGraphic();
player.idle();
} else if (data.hands.length == 0) {
if (player.userHasControl && player.resumeOnHandLost) {
player.userHasControl = false;
player.controller.emit('playback.userReleaseControl');
player.setGraphic('wave');
}
}
}
// prevent the actual frame from getting through
return {type: 'playback'}
} else {
return eventOrFrame;
}
};
// This pushes frame data, and watches for hands to auto change state.
// Returns the eventOrFrame without modifying it.
this.recordProtocol = function (data) {
var eventOrFrame = player.stopProtocol(data);
if (eventOrFrame instanceof Leap.Frame) {
player.recordFrameHandler(data);
}
return eventOrFrame;
};
// Copy methods/properties from the default protocol over
for (var property in this.stopProtocol) {
if (this.stopProtocol.hasOwnProperty(property)) {
this.playbackProtocol[property] = this.stopProtocol[property]
this.recordProtocol[property] = this.stopProtocol[property]
}
}
// todo: this is messy. Should cover all cases, not just active playback!
if (this.state == 'playing') {
this.controller.connection.protocol = this.playbackProtocol
}
}
|
javascript
|
function () {
var player = this;
// This is the original normal protocol, used while in record mode but not recording.
this.stopProtocol = this.controller.connection.protocol;
// This consumes all frame data, making the device act as if not streaming
this.playbackProtocol = function (data) {
// The old protocol still needs to emit events, so we use it, but intercept Frames
var eventOrFrame = player.stopProtocol(data);
if (eventOrFrame instanceof Leap.Frame) {
if (player.pauseOnHand) {
if (data.hands.length > 0) {
player.userHasControl = true;
player.controller.emit('playback.userTakeControl');
player.setGraphic();
player.idle();
} else if (data.hands.length == 0) {
if (player.userHasControl && player.resumeOnHandLost) {
player.userHasControl = false;
player.controller.emit('playback.userReleaseControl');
player.setGraphic('wave');
}
}
}
// prevent the actual frame from getting through
return {type: 'playback'}
} else {
return eventOrFrame;
}
};
// This pushes frame data, and watches for hands to auto change state.
// Returns the eventOrFrame without modifying it.
this.recordProtocol = function (data) {
var eventOrFrame = player.stopProtocol(data);
if (eventOrFrame instanceof Leap.Frame) {
player.recordFrameHandler(data);
}
return eventOrFrame;
};
// Copy methods/properties from the default protocol over
for (var property in this.stopProtocol) {
if (this.stopProtocol.hasOwnProperty(property)) {
this.playbackProtocol[property] = this.stopProtocol[property]
this.recordProtocol[property] = this.stopProtocol[property]
}
}
// todo: this is messy. Should cover all cases, not just active playback!
if (this.state == 'playing') {
this.controller.connection.protocol = this.playbackProtocol
}
}
|
[
"function",
"(",
")",
"{",
"var",
"player",
"=",
"this",
";",
"this",
".",
"stopProtocol",
"=",
"this",
".",
"controller",
".",
"connection",
".",
"protocol",
";",
"this",
".",
"playbackProtocol",
"=",
"function",
"(",
"data",
")",
"{",
"var",
"eventOrFrame",
"=",
"player",
".",
"stopProtocol",
"(",
"data",
")",
";",
"if",
"(",
"eventOrFrame",
"instanceof",
"Leap",
".",
"Frame",
")",
"{",
"if",
"(",
"player",
".",
"pauseOnHand",
")",
"{",
"if",
"(",
"data",
".",
"hands",
".",
"length",
">",
"0",
")",
"{",
"player",
".",
"userHasControl",
"=",
"true",
";",
"player",
".",
"controller",
".",
"emit",
"(",
"'playback.userTakeControl'",
")",
";",
"player",
".",
"setGraphic",
"(",
")",
";",
"player",
".",
"idle",
"(",
")",
";",
"}",
"else",
"if",
"(",
"data",
".",
"hands",
".",
"length",
"==",
"0",
")",
"{",
"if",
"(",
"player",
".",
"userHasControl",
"&&",
"player",
".",
"resumeOnHandLost",
")",
"{",
"player",
".",
"userHasControl",
"=",
"false",
";",
"player",
".",
"controller",
".",
"emit",
"(",
"'playback.userReleaseControl'",
")",
";",
"player",
".",
"setGraphic",
"(",
"'wave'",
")",
";",
"}",
"}",
"}",
"return",
"{",
"type",
":",
"'playback'",
"}",
"}",
"else",
"{",
"return",
"eventOrFrame",
";",
"}",
"}",
";",
"this",
".",
"recordProtocol",
"=",
"function",
"(",
"data",
")",
"{",
"var",
"eventOrFrame",
"=",
"player",
".",
"stopProtocol",
"(",
"data",
")",
";",
"if",
"(",
"eventOrFrame",
"instanceof",
"Leap",
".",
"Frame",
")",
"{",
"player",
".",
"recordFrameHandler",
"(",
"data",
")",
";",
"}",
"return",
"eventOrFrame",
";",
"}",
";",
"for",
"(",
"var",
"property",
"in",
"this",
".",
"stopProtocol",
")",
"{",
"if",
"(",
"this",
".",
"stopProtocol",
".",
"hasOwnProperty",
"(",
"property",
")",
")",
"{",
"this",
".",
"playbackProtocol",
"[",
"property",
"]",
"=",
"this",
".",
"stopProtocol",
"[",
"property",
"]",
"this",
".",
"recordProtocol",
"[",
"property",
"]",
"=",
"this",
".",
"stopProtocol",
"[",
"property",
"]",
"}",
"}",
"if",
"(",
"this",
".",
"state",
"==",
"'playing'",
")",
"{",
"this",
".",
"controller",
".",
"connection",
".",
"protocol",
"=",
"this",
".",
"playbackProtocol",
"}",
"}"
] |
This is how we intercept frame data early By hooking in before Frame creation, we get data exactly as the frame sends it.
|
[
"This",
"is",
"how",
"we",
"intercept",
"frame",
"data",
"early",
"By",
"hooking",
"in",
"before",
"Frame",
"creation",
"we",
"get",
"data",
"exactly",
"as",
"the",
"frame",
"sends",
"it",
"."
] |
dcaaafe3bc6a583d1dc06cb81741dcbea8fb7700
|
https://github.com/leapmotion/leapjs-plugins/blob/dcaaafe3bc6a583d1dc06cb81741dcbea8fb7700/main/leap-plugins-0.1.12.js#L1926-L1982
|
train
|
|
leapmotion/leapjs-plugins
|
main/leap-plugins-0.1.12.js
|
function (options) {
var player = this;
// otherwise, the animation loop may try and play non-existant frames:
this.pause();
// this is called on the context of the recording
var loadComplete = function (frames) {
this.setFrames(frames);
if (player.recording != this){
console.log('recordings changed during load');
return
}
if (player.autoPlay) {
player.play();
if (player.pauseOnHand && !player.controller.streaming() ) {
player.setGraphic('connect');
}
}
player.controller.emit('playback.recordingSet', this);
};
this.recording = options;
// Here we turn the existing argument in to a recording
// this allows frames to be added to the existing object via ajax
// saving ajax requests
if (!(options instanceof Recording)){
this.recording.__proto__ = Recording.prototype;
Recording.call(this.recording, {
timeBetweenLoops: this.options.timeBetweenLoops,
loop: this.options.loop,
loadProgress: function(recording, percentage, oEvent){
player.controller.emit('playback.ajax:progress', recording, percentage, oEvent);
}
});
}
if ( this.recording.loaded() ) {
loadComplete.call(this.recording, this.recording.frameData);
} else if (options.url) {
this.controller.emit('playback.ajax:begin', this, this.recording);
// called in the context of the recording
this.recording.loadFrameData(function(frames){
loadComplete.call(this, frames);
player.controller.emit('playback.ajax:complete', player, this);
});
} else if (options.compressedRecording) {
this.recording.loadCompressedRecording(options.compressedRecording, function(frames){
loadComplete.call(this, frames);
});
}
return this;
}
|
javascript
|
function (options) {
var player = this;
// otherwise, the animation loop may try and play non-existant frames:
this.pause();
// this is called on the context of the recording
var loadComplete = function (frames) {
this.setFrames(frames);
if (player.recording != this){
console.log('recordings changed during load');
return
}
if (player.autoPlay) {
player.play();
if (player.pauseOnHand && !player.controller.streaming() ) {
player.setGraphic('connect');
}
}
player.controller.emit('playback.recordingSet', this);
};
this.recording = options;
// Here we turn the existing argument in to a recording
// this allows frames to be added to the existing object via ajax
// saving ajax requests
if (!(options instanceof Recording)){
this.recording.__proto__ = Recording.prototype;
Recording.call(this.recording, {
timeBetweenLoops: this.options.timeBetweenLoops,
loop: this.options.loop,
loadProgress: function(recording, percentage, oEvent){
player.controller.emit('playback.ajax:progress', recording, percentage, oEvent);
}
});
}
if ( this.recording.loaded() ) {
loadComplete.call(this.recording, this.recording.frameData);
} else if (options.url) {
this.controller.emit('playback.ajax:begin', this, this.recording);
// called in the context of the recording
this.recording.loadFrameData(function(frames){
loadComplete.call(this, frames);
player.controller.emit('playback.ajax:complete', player, this);
});
} else if (options.compressedRecording) {
this.recording.loadCompressedRecording(options.compressedRecording, function(frames){
loadComplete.call(this, frames);
});
}
return this;
}
|
[
"function",
"(",
"options",
")",
"{",
"var",
"player",
"=",
"this",
";",
"this",
".",
"pause",
"(",
")",
";",
"var",
"loadComplete",
"=",
"function",
"(",
"frames",
")",
"{",
"this",
".",
"setFrames",
"(",
"frames",
")",
";",
"if",
"(",
"player",
".",
"recording",
"!=",
"this",
")",
"{",
"console",
".",
"log",
"(",
"'recordings changed during load'",
")",
";",
"return",
"}",
"if",
"(",
"player",
".",
"autoPlay",
")",
"{",
"player",
".",
"play",
"(",
")",
";",
"if",
"(",
"player",
".",
"pauseOnHand",
"&&",
"!",
"player",
".",
"controller",
".",
"streaming",
"(",
")",
")",
"{",
"player",
".",
"setGraphic",
"(",
"'connect'",
")",
";",
"}",
"}",
"player",
".",
"controller",
".",
"emit",
"(",
"'playback.recordingSet'",
",",
"this",
")",
";",
"}",
";",
"this",
".",
"recording",
"=",
"options",
";",
"if",
"(",
"!",
"(",
"options",
"instanceof",
"Recording",
")",
")",
"{",
"this",
".",
"recording",
".",
"__proto__",
"=",
"Recording",
".",
"prototype",
";",
"Recording",
".",
"call",
"(",
"this",
".",
"recording",
",",
"{",
"timeBetweenLoops",
":",
"this",
".",
"options",
".",
"timeBetweenLoops",
",",
"loop",
":",
"this",
".",
"options",
".",
"loop",
",",
"loadProgress",
":",
"function",
"(",
"recording",
",",
"percentage",
",",
"oEvent",
")",
"{",
"player",
".",
"controller",
".",
"emit",
"(",
"'playback.ajax:progress'",
",",
"recording",
",",
"percentage",
",",
"oEvent",
")",
";",
"}",
"}",
")",
";",
"}",
"if",
"(",
"this",
".",
"recording",
".",
"loaded",
"(",
")",
")",
"{",
"loadComplete",
".",
"call",
"(",
"this",
".",
"recording",
",",
"this",
".",
"recording",
".",
"frameData",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"url",
")",
"{",
"this",
".",
"controller",
".",
"emit",
"(",
"'playback.ajax:begin'",
",",
"this",
",",
"this",
".",
"recording",
")",
";",
"this",
".",
"recording",
".",
"loadFrameData",
"(",
"function",
"(",
"frames",
")",
"{",
"loadComplete",
".",
"call",
"(",
"this",
",",
"frames",
")",
";",
"player",
".",
"controller",
".",
"emit",
"(",
"'playback.ajax:complete'",
",",
"player",
",",
"this",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"compressedRecording",
")",
"{",
"this",
".",
"recording",
".",
"loadCompressedRecording",
"(",
"options",
".",
"compressedRecording",
",",
"function",
"(",
"frames",
")",
"{",
"loadComplete",
".",
"call",
"(",
"this",
",",
"frames",
")",
";",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Accepts a hash with any of URL, recording, metadata, compressedRecording once loaded, the recording is immediately activated
|
[
"Accepts",
"a",
"hash",
"with",
"any",
"of",
"URL",
"recording",
"metadata",
"compressedRecording",
"once",
"loaded",
"the",
"recording",
"is",
"immediately",
"activated"
] |
dcaaafe3bc6a583d1dc06cb81741dcbea8fb7700
|
https://github.com/leapmotion/leapjs-plugins/blob/dcaaafe3bc6a583d1dc06cb81741dcbea8fb7700/main/leap-plugins-0.1.12.js#L2192-L2259
|
train
|
|
GitbookIO/styleguide
|
src/Badge.js
|
createBadgeStyle
|
function createBadgeStyle(style) {
return React.createClass({
displayName: Badge.displayName + style,
render() {
return <Badge {...this.props} style={style.toLowerCase()} />;
}
});
}
|
javascript
|
function createBadgeStyle(style) {
return React.createClass({
displayName: Badge.displayName + style,
render() {
return <Badge {...this.props} style={style.toLowerCase()} />;
}
});
}
|
[
"function",
"createBadgeStyle",
"(",
"style",
")",
"{",
"return",
"React",
".",
"createClass",
"(",
"{",
"displayName",
":",
"Badge",
".",
"displayName",
"+",
"style",
",",
"render",
"(",
")",
"{",
"return",
"<",
"Badge",
"{",
"...",
"this",
".",
"props",
"}",
"style",
"=",
"{",
"style",
".",
"toLowerCase",
"(",
")",
"}",
"/",
">",
";",
"}",
"}",
")",
";",
"}"
] |
Create a style for badges
@param {String} style
@return {React.Component}
|
[
"Create",
"a",
"style",
"for",
"badges"
] |
fd6259b1788cc7e288316711cdc3bb6162698506
|
https://github.com/GitbookIO/styleguide/blob/fd6259b1788cc7e288316711cdc3bb6162698506/src/Badge.js#L36-L43
|
train
|
GitbookIO/styleguide
|
src/Label.js
|
createLabelStyle
|
function createLabelStyle(style) {
return React.createClass({
displayName: Label.displayName + style,
render() {
return <Label {...this.props} style={style.toLowerCase()} />;
}
});
}
|
javascript
|
function createLabelStyle(style) {
return React.createClass({
displayName: Label.displayName + style,
render() {
return <Label {...this.props} style={style.toLowerCase()} />;
}
});
}
|
[
"function",
"createLabelStyle",
"(",
"style",
")",
"{",
"return",
"React",
".",
"createClass",
"(",
"{",
"displayName",
":",
"Label",
".",
"displayName",
"+",
"style",
",",
"render",
"(",
")",
"{",
"return",
"<",
"Label",
"{",
"...",
"this",
".",
"props",
"}",
"style",
"=",
"{",
"style",
".",
"toLowerCase",
"(",
")",
"}",
"/",
">",
";",
"}",
"}",
")",
";",
"}"
] |
Create a style for labels
@param {String} style
@return {React.Component}
|
[
"Create",
"a",
"style",
"for",
"labels"
] |
fd6259b1788cc7e288316711cdc3bb6162698506
|
https://github.com/GitbookIO/styleguide/blob/fd6259b1788cc7e288316711cdc3bb6162698506/src/Label.js#L36-L43
|
train
|
Yuffster/discord-engine
|
classes/English.js
|
function() {
var str = this.trim();
str = this.charAt(0).toUpperCase() + this.slice(1);
if (!str.match(/[?!\.]$/)) str = str+'.';
return str;
}
|
javascript
|
function() {
var str = this.trim();
str = this.charAt(0).toUpperCase() + this.slice(1);
if (!str.match(/[?!\.]$/)) str = str+'.';
return str;
}
|
[
"function",
"(",
")",
"{",
"var",
"str",
"=",
"this",
".",
"trim",
"(",
")",
";",
"str",
"=",
"this",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"this",
".",
"slice",
"(",
"1",
")",
";",
"if",
"(",
"!",
"str",
".",
"match",
"(",
"/",
"[?!\\.]$",
"/",
")",
")",
"str",
"=",
"str",
"+",
"'.'",
";",
"return",
"str",
";",
"}"
] |
Ensures that a given string is a "sentence" by enforcing a capital
beginning letter and a punctuation mark at the end. Will default to a
period as ending punctuation for now, until I can get the irony mark
to render correctly.
|
[
"Ensures",
"that",
"a",
"given",
"string",
"is",
"a",
"sentence",
"by",
"enforcing",
"a",
"capital",
"beginning",
"letter",
"and",
"a",
"punctuation",
"mark",
"at",
"the",
"end",
".",
"Will",
"default",
"to",
"a",
"period",
"as",
"ending",
"punctuation",
"for",
"now",
"until",
"I",
"can",
"get",
"the",
"irony",
"mark",
"to",
"render",
"correctly",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/English.js#L20-L25
|
train
|
|
Yuffster/discord-engine
|
classes/English.js
|
function() {
//Pluralizes the first part in "<x> of <y>"
var bundle = this.match(/(\w+)\sof\s\w+/);
if (bundle) return this.replace(bundle[1], bundle[1].getPlural());
str = this.replace(/([^aeiou])y$/, '$1ies');
if (str==this) str = str.replace(/([ch|sh|x|s|o])$/, '$1es');
if (str==this) str += 's';
return str;
}
|
javascript
|
function() {
//Pluralizes the first part in "<x> of <y>"
var bundle = this.match(/(\w+)\sof\s\w+/);
if (bundle) return this.replace(bundle[1], bundle[1].getPlural());
str = this.replace(/([^aeiou])y$/, '$1ies');
if (str==this) str = str.replace(/([ch|sh|x|s|o])$/, '$1es');
if (str==this) str += 's';
return str;
}
|
[
"function",
"(",
")",
"{",
"var",
"bundle",
"=",
"this",
".",
"match",
"(",
"/",
"(\\w+)\\sof\\s\\w+",
"/",
")",
";",
"if",
"(",
"bundle",
")",
"return",
"this",
".",
"replace",
"(",
"bundle",
"[",
"1",
"]",
",",
"bundle",
"[",
"1",
"]",
".",
"getPlural",
"(",
")",
")",
";",
"str",
"=",
"this",
".",
"replace",
"(",
"/",
"([^aeiou])y$",
"/",
",",
"'$1ies'",
")",
";",
"if",
"(",
"str",
"==",
"this",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"([ch|sh|x|s|o])$",
"/",
",",
"'$1es'",
")",
";",
"if",
"(",
"str",
"==",
"this",
")",
"str",
"+=",
"'s'",
";",
"return",
"str",
";",
"}"
] |
Determines the plural form of the singular short.
For exceptional cases, it is necessary to manually set the plural
form using set_plural().
|
[
"Determines",
"the",
"plural",
"form",
"of",
"the",
"singular",
"short",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/English.js#L33-L41
|
train
|
|
Yuffster/discord-engine
|
classes/English.js
|
function() {
var n = this;
if (n<20) {
return [
'zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen' ][n];
} else if (n<100) {
var tens = Math.floor(n/10);
var ones = n%10;
return [
'twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety'
][tens-2]+((ones>0) ? '-'+ones.toWord() : '');
} else if (n<1000) {
var hundreds = Math.floor(n/100);
var tens = n%100;
return hundreds.toWord()+' hundred and '+tens.toWord();
}
var places = ['thousand', 'million', 'billion', 'trillion'];
var d = Math.floor(new String(n).length/3);
var pow = Math.pow(1000, d);
var principle = Math.floor(n/pow);
var remainder = n%pow;
return principle.toWord()+' '+places[d-1]+' '+remainder.toWord();
}
|
javascript
|
function() {
var n = this;
if (n<20) {
return [
'zero', 'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen' ][n];
} else if (n<100) {
var tens = Math.floor(n/10);
var ones = n%10;
return [
'twenty', 'thirty', 'forty', 'fifty', 'sixty',
'seventy', 'eighty', 'ninety'
][tens-2]+((ones>0) ? '-'+ones.toWord() : '');
} else if (n<1000) {
var hundreds = Math.floor(n/100);
var tens = n%100;
return hundreds.toWord()+' hundred and '+tens.toWord();
}
var places = ['thousand', 'million', 'billion', 'trillion'];
var d = Math.floor(new String(n).length/3);
var pow = Math.pow(1000, d);
var principle = Math.floor(n/pow);
var remainder = n%pow;
return principle.toWord()+' '+places[d-1]+' '+remainder.toWord();
}
|
[
"function",
"(",
")",
"{",
"var",
"n",
"=",
"this",
";",
"if",
"(",
"n",
"<",
"20",
")",
"{",
"return",
"[",
"'zero'",
",",
"'one'",
",",
"'two'",
",",
"'three'",
",",
"'four'",
",",
"'five'",
",",
"'six'",
",",
"'seven'",
",",
"'eight'",
",",
"'nine'",
",",
"'ten'",
",",
"'eleven'",
",",
"'twelve'",
",",
"'thirteen'",
",",
"'fourteen'",
",",
"'fifteen'",
",",
"'sixteen'",
",",
"'seventeen'",
",",
"'eighteen'",
",",
"'nineteen'",
"]",
"[",
"n",
"]",
";",
"}",
"else",
"if",
"(",
"n",
"<",
"100",
")",
"{",
"var",
"tens",
"=",
"Math",
".",
"floor",
"(",
"n",
"/",
"10",
")",
";",
"var",
"ones",
"=",
"n",
"%",
"10",
";",
"return",
"[",
"'twenty'",
",",
"'thirty'",
",",
"'forty'",
",",
"'fifty'",
",",
"'sixty'",
",",
"'seventy'",
",",
"'eighty'",
",",
"'ninety'",
"]",
"[",
"tens",
"-",
"2",
"]",
"+",
"(",
"(",
"ones",
">",
"0",
")",
"?",
"'-'",
"+",
"ones",
".",
"toWord",
"(",
")",
":",
"''",
")",
";",
"}",
"else",
"if",
"(",
"n",
"<",
"1000",
")",
"{",
"var",
"hundreds",
"=",
"Math",
".",
"floor",
"(",
"n",
"/",
"100",
")",
";",
"var",
"tens",
"=",
"n",
"%",
"100",
";",
"return",
"hundreds",
".",
"toWord",
"(",
")",
"+",
"' hundred and '",
"+",
"tens",
".",
"toWord",
"(",
")",
";",
"}",
"var",
"places",
"=",
"[",
"'thousand'",
",",
"'million'",
",",
"'billion'",
",",
"'trillion'",
"]",
";",
"var",
"d",
"=",
"Math",
".",
"floor",
"(",
"new",
"String",
"(",
"n",
")",
".",
"length",
"/",
"3",
")",
";",
"var",
"pow",
"=",
"Math",
".",
"pow",
"(",
"1000",
",",
"d",
")",
";",
"var",
"principle",
"=",
"Math",
".",
"floor",
"(",
"n",
"/",
"pow",
")",
";",
"var",
"remainder",
"=",
"n",
"%",
"pow",
";",
"return",
"principle",
".",
"toWord",
"(",
")",
"+",
"' '",
"+",
"places",
"[",
"d",
"-",
"1",
"]",
"+",
"' '",
"+",
"remainder",
".",
"toWord",
"(",
")",
";",
"}"
] |
Converts a number up to whatever comes after the trillions into English.
|
[
"Converts",
"a",
"number",
"up",
"to",
"whatever",
"comes",
"after",
"the",
"trillions",
"into",
"English",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/English.js#L191-L218
|
train
|
|
Yuffster/discord-engine
|
classes/English.js
|
function() {
if (this.length==0) return false;
//Don't want to modify the list!
var items = this;
if (items.length>1) items[items.length-1] = 'and '+items.getLast();
if (items.length>2) return items.join(', ');
return items.join(' ');
}
|
javascript
|
function() {
if (this.length==0) return false;
//Don't want to modify the list!
var items = this;
if (items.length>1) items[items.length-1] = 'and '+items.getLast();
if (items.length>2) return items.join(', ');
return items.join(' ');
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"length",
"==",
"0",
")",
"return",
"false",
";",
"var",
"items",
"=",
"this",
";",
"if",
"(",
"items",
".",
"length",
">",
"1",
")",
"items",
"[",
"items",
".",
"length",
"-",
"1",
"]",
"=",
"'and '",
"+",
"items",
".",
"getLast",
"(",
")",
";",
"if",
"(",
"items",
".",
"length",
">",
"2",
")",
"return",
"items",
".",
"join",
"(",
"', '",
")",
";",
"return",
"items",
".",
"join",
"(",
"' '",
")",
";",
"}"
] |
Serializes the array with commas, topped off ith an 'and' at the end.
|
[
"Serializes",
"the",
"array",
"with",
"commas",
"topped",
"off",
"ith",
"an",
"and",
"at",
"the",
"end",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/English.js#L227-L234
|
train
|
|
Yuffster/discord-engine
|
classes/World.js
|
function(config) {
var required = ['world_path', 'start_room'];
required.each(function(key) {
if (!config[key]) {
sys.puts("Required config option \""+key+"\" not supplied.");
process.exit();
}
});
this.set('name', config.world_name);
this.config = config;
this.worldPath = require('path').join(config.world_path);
this.defaultRoom = config.start_room;
this.players = this.players;
this.rooms = this.rooms;
this.items = this.items;
this.initializeRooms();
}
|
javascript
|
function(config) {
var required = ['world_path', 'start_room'];
required.each(function(key) {
if (!config[key]) {
sys.puts("Required config option \""+key+"\" not supplied.");
process.exit();
}
});
this.set('name', config.world_name);
this.config = config;
this.worldPath = require('path').join(config.world_path);
this.defaultRoom = config.start_room;
this.players = this.players;
this.rooms = this.rooms;
this.items = this.items;
this.initializeRooms();
}
|
[
"function",
"(",
"config",
")",
"{",
"var",
"required",
"=",
"[",
"'world_path'",
",",
"'start_room'",
"]",
";",
"required",
".",
"each",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"!",
"config",
"[",
"key",
"]",
")",
"{",
"sys",
".",
"puts",
"(",
"\"Required config option \\\"\"",
"+",
"\\\"",
"+",
"key",
")",
";",
"\"\\\" not supplied.\"",
"}",
"}",
")",
";",
"\\\"",
"process",
".",
"exit",
"(",
")",
";",
"this",
".",
"set",
"(",
"'name'",
",",
"config",
".",
"world_name",
")",
";",
"this",
".",
"config",
"=",
"config",
";",
"this",
".",
"worldPath",
"=",
"require",
"(",
"'path'",
")",
".",
"join",
"(",
"config",
".",
"world_path",
")",
";",
"this",
".",
"defaultRoom",
"=",
"config",
".",
"start_room",
";",
"this",
".",
"players",
"=",
"this",
".",
"players",
";",
"this",
".",
"rooms",
"=",
"this",
".",
"rooms",
";",
"}"
] |
The name of the world will determine the path to the world's room and
object files.
|
[
"The",
"name",
"of",
"the",
"world",
"will",
"determine",
"the",
"path",
"to",
"the",
"world",
"s",
"room",
"and",
"object",
"files",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/World.js#L44-L61
|
train
|
|
Yuffster/discord-engine
|
classes/World.js
|
function(player) {
player.world = this;
this.players[player.name.toLowerCase()] = player;
this.announce(player.name+" has entered the world.");
this.loadPlayerData(player);
}
|
javascript
|
function(player) {
player.world = this;
this.players[player.name.toLowerCase()] = player;
this.announce(player.name+" has entered the world.");
this.loadPlayerData(player);
}
|
[
"function",
"(",
"player",
")",
"{",
"player",
".",
"world",
"=",
"this",
";",
"this",
".",
"players",
"[",
"player",
".",
"name",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"player",
";",
"this",
".",
"announce",
"(",
"player",
".",
"name",
"+",
"\" has entered the world.\"",
")",
";",
"this",
".",
"loadPlayerData",
"(",
"player",
")",
";",
"}"
] |
Adds the player to the world.
|
[
"Adds",
"the",
"player",
"to",
"the",
"world",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/World.js#L95-L100
|
train
|
|
Yuffster/discord-engine
|
classes/World.js
|
function(name, player, target) {
if (!name) return;
var that = this;
if (!this.menus[name]) {
var path;
//If there's a target, we'll assume it's a conversation.
if (target) path = this.scriptPath+name;
else path = this.menuPath+name;
this.loadFile(path, function(e,menu) {
if (e) log_error(e);
if (!menu) return;
that.menus[name] = menu;
player.enterMenu(menu, target);
});
} else {
player.enterMenu(this.menus[name], target);
}
}
|
javascript
|
function(name, player, target) {
if (!name) return;
var that = this;
if (!this.menus[name]) {
var path;
//If there's a target, we'll assume it's a conversation.
if (target) path = this.scriptPath+name;
else path = this.menuPath+name;
this.loadFile(path, function(e,menu) {
if (e) log_error(e);
if (!menu) return;
that.menus[name] = menu;
player.enterMenu(menu, target);
});
} else {
player.enterMenu(this.menus[name], target);
}
}
|
[
"function",
"(",
"name",
",",
"player",
",",
"target",
")",
"{",
"if",
"(",
"!",
"name",
")",
"return",
";",
"var",
"that",
"=",
"this",
";",
"if",
"(",
"!",
"this",
".",
"menus",
"[",
"name",
"]",
")",
"{",
"var",
"path",
";",
"if",
"(",
"target",
")",
"path",
"=",
"this",
".",
"scriptPath",
"+",
"name",
";",
"else",
"path",
"=",
"this",
".",
"menuPath",
"+",
"name",
";",
"this",
".",
"loadFile",
"(",
"path",
",",
"function",
"(",
"e",
",",
"menu",
")",
"{",
"if",
"(",
"e",
")",
"log_error",
"(",
"e",
")",
";",
"if",
"(",
"!",
"menu",
")",
"return",
";",
"that",
".",
"menus",
"[",
"name",
"]",
"=",
"menu",
";",
"player",
".",
"enterMenu",
"(",
"menu",
",",
"target",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"player",
".",
"enterMenu",
"(",
"this",
".",
"menus",
"[",
"name",
"]",
",",
"target",
")",
";",
"}",
"}"
] |
Target is optional. In the event of a conversation, the target is
the NPC being conversed with.
|
[
"Target",
"is",
"optional",
".",
"In",
"the",
"event",
"of",
"a",
"conversation",
"the",
"target",
"is",
"the",
"NPC",
"being",
"conversed",
"with",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/World.js#L189-L206
|
train
|
|
Yuffster/discord-engine
|
classes/World.js
|
function(path, callback, opts) {
if (!callback) callback = function() { };
var fallbacks = [];
if (path.each) {
if (path.length==0) return;
fallbacks = path;
path = fallbacks.shift()+"";
}
//Stuff that will make us not want to load files.
if (this.failedFiles.contains(path)) return;
opts = opts || {};
var file = this.worldPath+path+'.js';
if (opts.rootPath) file = path+'.js';
var my = this;
var err;
var handleData = function(e,raw) {
data = false;
if (!raw) {
err = e;
my.failedFiles.push(path);
/* Continue down our list of fallbacks. */
if (fallbacks.length>0) {
my.loadFile(fallbacks, callback, opts);
} else {
log_error("File not found: "+file);
}
} else {
try { eval('data='+raw); }
catch (e) { log_error(e); }
} callback(err, data);
return data;
};
if (opts.sync) {
try {
var data = fs.readFileSync(file);
} catch (e) {
this.failedFiles.push(path);
/* Continue down our list of fallbacks. */
if (fallbacks.length>0) {
return this.loadFile(fallbacks, callback, opts);
} else return e;
} return handleData(false,data);
} else {
fs.readFile(file, handleData);
}
}
|
javascript
|
function(path, callback, opts) {
if (!callback) callback = function() { };
var fallbacks = [];
if (path.each) {
if (path.length==0) return;
fallbacks = path;
path = fallbacks.shift()+"";
}
//Stuff that will make us not want to load files.
if (this.failedFiles.contains(path)) return;
opts = opts || {};
var file = this.worldPath+path+'.js';
if (opts.rootPath) file = path+'.js';
var my = this;
var err;
var handleData = function(e,raw) {
data = false;
if (!raw) {
err = e;
my.failedFiles.push(path);
/* Continue down our list of fallbacks. */
if (fallbacks.length>0) {
my.loadFile(fallbacks, callback, opts);
} else {
log_error("File not found: "+file);
}
} else {
try { eval('data='+raw); }
catch (e) { log_error(e); }
} callback(err, data);
return data;
};
if (opts.sync) {
try {
var data = fs.readFileSync(file);
} catch (e) {
this.failedFiles.push(path);
/* Continue down our list of fallbacks. */
if (fallbacks.length>0) {
return this.loadFile(fallbacks, callback, opts);
} else return e;
} return handleData(false,data);
} else {
fs.readFile(file, handleData);
}
}
|
[
"function",
"(",
"path",
",",
"callback",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"callback",
")",
"callback",
"=",
"function",
"(",
")",
"{",
"}",
";",
"var",
"fallbacks",
"=",
"[",
"]",
";",
"if",
"(",
"path",
".",
"each",
")",
"{",
"if",
"(",
"path",
".",
"length",
"==",
"0",
")",
"return",
";",
"fallbacks",
"=",
"path",
";",
"path",
"=",
"fallbacks",
".",
"shift",
"(",
")",
"+",
"\"\"",
";",
"}",
"if",
"(",
"this",
".",
"failedFiles",
".",
"contains",
"(",
"path",
")",
")",
"return",
";",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"file",
"=",
"this",
".",
"worldPath",
"+",
"path",
"+",
"'.js'",
";",
"if",
"(",
"opts",
".",
"rootPath",
")",
"file",
"=",
"path",
"+",
"'.js'",
";",
"var",
"my",
"=",
"this",
";",
"var",
"err",
";",
"var",
"handleData",
"=",
"function",
"(",
"e",
",",
"raw",
")",
"{",
"data",
"=",
"false",
";",
"if",
"(",
"!",
"raw",
")",
"{",
"err",
"=",
"e",
";",
"my",
".",
"failedFiles",
".",
"push",
"(",
"path",
")",
";",
"if",
"(",
"fallbacks",
".",
"length",
">",
"0",
")",
"{",
"my",
".",
"loadFile",
"(",
"fallbacks",
",",
"callback",
",",
"opts",
")",
";",
"}",
"else",
"{",
"log_error",
"(",
"\"File not found: \"",
"+",
"file",
")",
";",
"}",
"}",
"else",
"{",
"try",
"{",
"eval",
"(",
"'data='",
"+",
"raw",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"log_error",
"(",
"e",
")",
";",
"}",
"}",
"callback",
"(",
"err",
",",
"data",
")",
";",
"return",
"data",
";",
"}",
";",
"if",
"(",
"opts",
".",
"sync",
")",
"{",
"try",
"{",
"var",
"data",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"this",
".",
"failedFiles",
".",
"push",
"(",
"path",
")",
";",
"if",
"(",
"fallbacks",
".",
"length",
">",
"0",
")",
"{",
"return",
"this",
".",
"loadFile",
"(",
"fallbacks",
",",
"callback",
",",
"opts",
")",
";",
"}",
"else",
"return",
"e",
";",
"}",
"return",
"handleData",
"(",
"false",
",",
"data",
")",
";",
"}",
"else",
"{",
"fs",
".",
"readFile",
"(",
"file",
",",
"handleData",
")",
";",
"}",
"}"
] |
I'm putting this function last because it's the ugliest.
|
[
"I",
"m",
"putting",
"this",
"function",
"last",
"because",
"it",
"s",
"the",
"ugliest",
"."
] |
7ca5052915dc1d986b533b30f4e5d19f90026b44
|
https://github.com/Yuffster/discord-engine/blob/7ca5052915dc1d986b533b30f4e5d19f90026b44/classes/World.js#L388-L439
|
train
|
|
thlorenz/d3-gauge
|
d3-gauge.js
|
Gauge
|
function Gauge (el, opts) {
if (!(this instanceof Gauge)) return new Gauge(el, opts);
this._el = el;
this._opts = xtend(defaultOpts, opts);
this._size = this._opts.size;
this._radius = this._size * 0.9 / 2;
this._cx = this._size / 2;
this._cy = this._cx;
this._preserveAspectRatio = this._opts.preserveAspectRatio;
this._min = this._opts.min;
this._max = this._opts.max;
this._range = this._max - this._min;
this._majorTicks = this._opts.majorTicks;
this._minorTicks = this._opts.minorTicks;
this._needleWidthRatio = this._opts.needleWidthRatio;
this._needleContainerRadiusRatio = this._opts.needleContainerRadiusRatio;
this._transitionDuration = this._opts.transitionDuration;
this._label = this._opts.label;
this._zones = this._opts.zones || [];
this._clazz = opts.clazz;
this._initZones();
this._render();
}
|
javascript
|
function Gauge (el, opts) {
if (!(this instanceof Gauge)) return new Gauge(el, opts);
this._el = el;
this._opts = xtend(defaultOpts, opts);
this._size = this._opts.size;
this._radius = this._size * 0.9 / 2;
this._cx = this._size / 2;
this._cy = this._cx;
this._preserveAspectRatio = this._opts.preserveAspectRatio;
this._min = this._opts.min;
this._max = this._opts.max;
this._range = this._max - this._min;
this._majorTicks = this._opts.majorTicks;
this._minorTicks = this._opts.minorTicks;
this._needleWidthRatio = this._opts.needleWidthRatio;
this._needleContainerRadiusRatio = this._opts.needleContainerRadiusRatio;
this._transitionDuration = this._opts.transitionDuration;
this._label = this._opts.label;
this._zones = this._opts.zones || [];
this._clazz = opts.clazz;
this._initZones();
this._render();
}
|
[
"function",
"Gauge",
"(",
"el",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Gauge",
")",
")",
"return",
"new",
"Gauge",
"(",
"el",
",",
"opts",
")",
";",
"this",
".",
"_el",
"=",
"el",
";",
"this",
".",
"_opts",
"=",
"xtend",
"(",
"defaultOpts",
",",
"opts",
")",
";",
"this",
".",
"_size",
"=",
"this",
".",
"_opts",
".",
"size",
";",
"this",
".",
"_radius",
"=",
"this",
".",
"_size",
"*",
"0.9",
"/",
"2",
";",
"this",
".",
"_cx",
"=",
"this",
".",
"_size",
"/",
"2",
";",
"this",
".",
"_cy",
"=",
"this",
".",
"_cx",
";",
"this",
".",
"_preserveAspectRatio",
"=",
"this",
".",
"_opts",
".",
"preserveAspectRatio",
";",
"this",
".",
"_min",
"=",
"this",
".",
"_opts",
".",
"min",
";",
"this",
".",
"_max",
"=",
"this",
".",
"_opts",
".",
"max",
";",
"this",
".",
"_range",
"=",
"this",
".",
"_max",
"-",
"this",
".",
"_min",
";",
"this",
".",
"_majorTicks",
"=",
"this",
".",
"_opts",
".",
"majorTicks",
";",
"this",
".",
"_minorTicks",
"=",
"this",
".",
"_opts",
".",
"minorTicks",
";",
"this",
".",
"_needleWidthRatio",
"=",
"this",
".",
"_opts",
".",
"needleWidthRatio",
";",
"this",
".",
"_needleContainerRadiusRatio",
"=",
"this",
".",
"_opts",
".",
"needleContainerRadiusRatio",
";",
"this",
".",
"_transitionDuration",
"=",
"this",
".",
"_opts",
".",
"transitionDuration",
";",
"this",
".",
"_label",
"=",
"this",
".",
"_opts",
".",
"label",
";",
"this",
".",
"_zones",
"=",
"this",
".",
"_opts",
".",
"zones",
"||",
"[",
"]",
";",
"this",
".",
"_clazz",
"=",
"opts",
".",
"clazz",
";",
"this",
".",
"_initZones",
"(",
")",
";",
"this",
".",
"_render",
"(",
")",
";",
"}"
] |
Creates a gauge appended to the given DOM element.
Example:
```js
var simpleOpts = {
size : 100
, min : 0
, max : 50
, transitionDuration : 500
, label : 'label.text'
, minorTicks : 4
, majorTicks : 5
, needleWidthRatio : 0.6
, needleContainerRadiusRatio : 0.7
, zones: [
{ clazz: 'yellow-zone', from: 0.73, to: 0.9 }
, { clazz: 'red-zone', from: 0.9, to: 1.0 }
]
}
var gauge = Gauge(document.getElementById('simple-gauge'), simpleOpts);
gauge.write(39);
```
@name Gauge
@function
@param el {DOMElement} to which the gauge is appended
@param opts {Object} gauge configuration with the following properties all of which have sensible defaults:
- label {String} that appears in the top portion of the gauge
- clazz {String} class to apply to the gauge element in order to support custom styling
- size {Number} the over all size (radius) of the gauge
- preserveAspectRatio {String} default 'xMinYMin meet', see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio
- min {Number} the minimum value that the gauge measures
- max {Number} the maximum value that the gauge measures
- majorTicks {Number} the number of major ticks to draw
- minorTicks {Number} the number of minor ticks to draw in between two major ticks
- needleWidthRatio {Number} tweaks the gauge's needle width
- needleConatinerRadiusRatio {Number} tweaks the gauge's needle container circumference
- transitionDuration {Number} the time in ms it takes for the needle to move to a new position
- zones {Array[Object]} each with the following properties
- clazz {String} class to apply to the zone element in order to style its fill
- from {Number} between 0 and 1 to determine zone's start
- to {Number} between 0 and 1 to determine zone's end
@return {Object} the gauge with a `write` method
|
[
"Creates",
"a",
"gauge",
"appended",
"to",
"the",
"given",
"DOM",
"element",
"."
] |
94cdaaf7d669047f2e46ec74f127ef2ed379e09b
|
https://github.com/thlorenz/d3-gauge/blob/94cdaaf7d669047f2e46ec74f127ef2ed379e09b/d3-gauge.js#L60-L94
|
train
|
rpbouman/xmla4js
|
src/Xmla.js
|
_parseSoapFaultDetail
|
function _parseSoapFaultDetail(detailNode){
var errors = [];
var i, childNodes = detailNode.childNodes, n = childNodes.length, childNode;
for (i = 0; i < n; i++) {
childNode = childNodes[i];
if (childNode.nodeType !== 1) {
continue;
}
switch (childNode.nodeName){
case "Error":
errors.push({
ErrorCode: _getAttribute(childNode, "ErrorCode"),
Description: _getAttribute(childNode, "Description"),
Source: _getAttribute(childNode, "Source"),
HelpFile: _getAttribute(childNode, "HelpFile")
});
break;
default:
}
}
return errors;
}
|
javascript
|
function _parseSoapFaultDetail(detailNode){
var errors = [];
var i, childNodes = detailNode.childNodes, n = childNodes.length, childNode;
for (i = 0; i < n; i++) {
childNode = childNodes[i];
if (childNode.nodeType !== 1) {
continue;
}
switch (childNode.nodeName){
case "Error":
errors.push({
ErrorCode: _getAttribute(childNode, "ErrorCode"),
Description: _getAttribute(childNode, "Description"),
Source: _getAttribute(childNode, "Source"),
HelpFile: _getAttribute(childNode, "HelpFile")
});
break;
default:
}
}
return errors;
}
|
[
"function",
"_parseSoapFaultDetail",
"(",
"detailNode",
")",
"{",
"var",
"errors",
"=",
"[",
"]",
";",
"var",
"i",
",",
"childNodes",
"=",
"detailNode",
".",
"childNodes",
",",
"n",
"=",
"childNodes",
".",
"length",
",",
"childNode",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"childNode",
"=",
"childNodes",
"[",
"i",
"]",
";",
"if",
"(",
"childNode",
".",
"nodeType",
"!==",
"1",
")",
"{",
"continue",
";",
"}",
"switch",
"(",
"childNode",
".",
"nodeName",
")",
"{",
"case",
"\"Error\"",
":",
"errors",
".",
"push",
"(",
"{",
"ErrorCode",
":",
"_getAttribute",
"(",
"childNode",
",",
"\"ErrorCode\"",
")",
",",
"Description",
":",
"_getAttribute",
"(",
"childNode",
",",
"\"Description\"",
")",
",",
"Source",
":",
"_getAttribute",
"(",
"childNode",
",",
"\"Source\"",
")",
",",
"HelpFile",
":",
"_getAttribute",
"(",
"childNode",
",",
"\"HelpFile\"",
")",
"}",
")",
";",
"break",
";",
"default",
":",
"}",
"}",
"return",
"errors",
";",
"}"
] |
Get faultactor, faultstring, faultcode and detail elements
|
[
"Get",
"faultactor",
"faultstring",
"faultcode",
"and",
"detail",
"elements"
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L2130-L2151
|
train
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(){
var fieldNames = [], i, n = this._fieldCount;
for (i = 0; i < n; i++) fieldNames[i] = this.fieldOrder[i];
return fieldNames;
}
|
javascript
|
function(){
var fieldNames = [], i, n = this._fieldCount;
for (i = 0; i < n; i++) fieldNames[i] = this.fieldOrder[i];
return fieldNames;
}
|
[
"function",
"(",
")",
"{",
"var",
"fieldNames",
"=",
"[",
"]",
",",
"i",
",",
"n",
"=",
"this",
".",
"_fieldCount",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"fieldNames",
"[",
"i",
"]",
"=",
"this",
".",
"fieldOrder",
"[",
"i",
"]",
";",
"return",
"fieldNames",
";",
"}"
] |
Retrieve an array of field names.
The position of the names in the array corresponds to the column order of the rowset.
@method getFieldNames
@return {[string]} An (ordered) array of field names.
|
[
"Retrieve",
"an",
"array",
"of",
"field",
"names",
".",
"The",
"position",
"of",
"the",
"names",
"in",
"the",
"array",
"corresponds",
"to",
"the",
"column",
"order",
"of",
"the",
"rowset",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L6078-L6082
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(index){
var fieldName = this.fieldOrder[index];
if (!fieldName)
Xmla.Exception._newError(
"INVALID_FIELD",
"Xmla.Rowset.fieldDef",
index
)._throw();
return fieldName;
}
|
javascript
|
function(index){
var fieldName = this.fieldOrder[index];
if (!fieldName)
Xmla.Exception._newError(
"INVALID_FIELD",
"Xmla.Rowset.fieldDef",
index
)._throw();
return fieldName;
}
|
[
"function",
"(",
"index",
")",
"{",
"var",
"fieldName",
"=",
"this",
".",
"fieldOrder",
"[",
"index",
"]",
";",
"if",
"(",
"!",
"fieldName",
")",
"Xmla",
".",
"Exception",
".",
"_newError",
"(",
"\"INVALID_FIELD\"",
",",
"\"Xmla.Rowset.fieldDef\"",
",",
"index",
")",
".",
"_throw",
"(",
")",
";",
"return",
"fieldName",
";",
"}"
] |
Retrieves the name of a field by field Index.
Field indexes start at 0.
@method fieldName
@param {string} name The name of the field for which you want to retrieve the index.
@return {int} The ordinal position (starting at 0) of the field that matches the argument.
|
[
"Retrieves",
"the",
"name",
"of",
"a",
"field",
"by",
"field",
"Index",
".",
"Field",
"indexes",
"start",
"at",
"0",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L6227-L6236
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(name){
if (_isNum(name)) name = this.fieldName(name);
return this.fieldDef(name).getter.call(this);
}
|
javascript
|
function(name){
if (_isNum(name)) name = this.fieldName(name);
return this.fieldDef(name).getter.call(this);
}
|
[
"function",
"(",
"name",
")",
"{",
"if",
"(",
"_isNum",
"(",
"name",
")",
")",
"name",
"=",
"this",
".",
"fieldName",
"(",
"name",
")",
";",
"return",
"this",
".",
"fieldDef",
"(",
"name",
")",
".",
"getter",
".",
"call",
"(",
"this",
")",
";",
"}"
] |
Retrieves a value from the current row for the field having the name specified by the argument.
@method fieldVal
@param {string | int} name The name or the index of the field for which you want to retrieve the value.
@return {array|boolean|float|int|string} From the current row, the value of the field that matches the argument.
|
[
"Retrieves",
"a",
"value",
"from",
"the",
"current",
"row",
"for",
"the",
"field",
"having",
"the",
"name",
"specified",
"by",
"the",
"argument",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L6243-L6246
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(){
if (this._cellset) this._cellset.reset();
if (this._axes) {
var i, n, axis;
for (i = 0, n = this.axisCount(); i < n; i++){
this.getAxis(i).reset();
}
}
}
|
javascript
|
function(){
if (this._cellset) this._cellset.reset();
if (this._axes) {
var i, n, axis;
for (i = 0, n = this.axisCount(); i < n; i++){
this.getAxis(i).reset();
}
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_cellset",
")",
"this",
".",
"_cellset",
".",
"reset",
"(",
")",
";",
"if",
"(",
"this",
".",
"_axes",
")",
"{",
"var",
"i",
",",
"n",
",",
"axis",
";",
"for",
"(",
"i",
"=",
"0",
",",
"n",
"=",
"this",
".",
"axisCount",
"(",
")",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"this",
".",
"getAxis",
"(",
"i",
")",
".",
"reset",
"(",
")",
";",
"}",
"}",
"}"
] |
Reset this object so it can be used again.
@method reset
@return void
|
[
"Reset",
"this",
"object",
"so",
"it",
"can",
"be",
"used",
"again",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L6906-L6914
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(){
if (this._slicer) {
this._slicer.close();
}
var i, n = this._numAxes;
for (i = 0; i < n; i++) {
this.getAxis(i).close();
}
this._cellset.close();
this._cellset = null;
this._root = null;
this._axes = null;
this._axesOrder = null;
this._numAxes = null;
this._slicer = null;
}
|
javascript
|
function(){
if (this._slicer) {
this._slicer.close();
}
var i, n = this._numAxes;
for (i = 0; i < n; i++) {
this.getAxis(i).close();
}
this._cellset.close();
this._cellset = null;
this._root = null;
this._axes = null;
this._axesOrder = null;
this._numAxes = null;
this._slicer = null;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_slicer",
")",
"{",
"this",
".",
"_slicer",
".",
"close",
"(",
")",
";",
"}",
"var",
"i",
",",
"n",
"=",
"this",
".",
"_numAxes",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"this",
".",
"getAxis",
"(",
"i",
")",
".",
"close",
"(",
")",
";",
"}",
"this",
".",
"_cellset",
".",
"close",
"(",
")",
";",
"this",
".",
"_cellset",
"=",
"null",
";",
"this",
".",
"_root",
"=",
"null",
";",
"this",
".",
"_axes",
"=",
"null",
";",
"this",
".",
"_axesOrder",
"=",
"null",
";",
"this",
".",
"_numAxes",
"=",
"null",
";",
"this",
".",
"_slicer",
"=",
"null",
";",
"}"
] |
Cleanup this Dataset object.
@method close
@return void
|
[
"Cleanup",
"this",
"Dataset",
"object",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L6920-L6935
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(){
var hierarchyNames = [], i, n = this.numHierarchies;
for (i = 0; i < n; i++) hierarchyNames[i] = this._hierarchyOrder[i];
return hierarchyNames;
}
|
javascript
|
function(){
var hierarchyNames = [], i, n = this.numHierarchies;
for (i = 0; i < n; i++) hierarchyNames[i] = this._hierarchyOrder[i];
return hierarchyNames;
}
|
[
"function",
"(",
")",
"{",
"var",
"hierarchyNames",
"=",
"[",
"]",
",",
"i",
",",
"n",
"=",
"this",
".",
"numHierarchies",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"hierarchyNames",
"[",
"i",
"]",
"=",
"this",
".",
"_hierarchyOrder",
"[",
"i",
"]",
";",
"return",
"hierarchyNames",
";",
"}"
] |
Returns the names of the hierarchies of this Axis object.
@method getHierarchyNames
@return {array} An array of names of the hierarchies contained in this Axis.
|
[
"Returns",
"the",
"names",
"of",
"the",
"hierarchies",
"of",
"this",
"Axis",
"object",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L7398-L7402
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(callback, scope, args) {
var mArgs = [null];
if (!scope) {
scope = this;
}
if (args) {
if (!_isArr(args)) {
args = [args];
}
mArgs = mArgs.concat(args);
}
var ord;
while (ord !== -1 && this.hasMoreCells()){
ord = this.nextCell();
mArgs[0] = this.readCell();
if (callback.apply(scope, mArgs)===false) {
return false;
}
}
this._idx = 0;
return true;
}
|
javascript
|
function(callback, scope, args) {
var mArgs = [null];
if (!scope) {
scope = this;
}
if (args) {
if (!_isArr(args)) {
args = [args];
}
mArgs = mArgs.concat(args);
}
var ord;
while (ord !== -1 && this.hasMoreCells()){
ord = this.nextCell();
mArgs[0] = this.readCell();
if (callback.apply(scope, mArgs)===false) {
return false;
}
}
this._idx = 0;
return true;
}
|
[
"function",
"(",
"callback",
",",
"scope",
",",
"args",
")",
"{",
"var",
"mArgs",
"=",
"[",
"null",
"]",
";",
"if",
"(",
"!",
"scope",
")",
"{",
"scope",
"=",
"this",
";",
"}",
"if",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"_isArr",
"(",
"args",
")",
")",
"{",
"args",
"=",
"[",
"args",
"]",
";",
"}",
"mArgs",
"=",
"mArgs",
".",
"concat",
"(",
"args",
")",
";",
"}",
"var",
"ord",
";",
"while",
"(",
"ord",
"!==",
"-",
"1",
"&&",
"this",
".",
"hasMoreCells",
"(",
")",
")",
"{",
"ord",
"=",
"this",
".",
"nextCell",
"(",
")",
";",
"mArgs",
"[",
"0",
"]",
"=",
"this",
".",
"readCell",
"(",
")",
";",
"if",
"(",
"callback",
".",
"apply",
"(",
"scope",
",",
"mArgs",
")",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"}",
"this",
".",
"_idx",
"=",
"0",
";",
"return",
"true",
";",
"}"
] |
Iterate through each cell.
@method eachCell
@param {function()} callback
@param {object} scope
@param {object} args
@return {boolean}
|
[
"Iterate",
"through",
"each",
"cell",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L7945-L7966
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(){
var cell, cells = {}, i = 0, count = this._cellCount;
for (i = 0; i < count; i++){
cell = this.readCell();
cells[cell.ordinal] = cell;
this.nextCell();
}
return cells;
}
|
javascript
|
function(){
var cell, cells = {}, i = 0, count = this._cellCount;
for (i = 0; i < count; i++){
cell = this.readCell();
cells[cell.ordinal] = cell;
this.nextCell();
}
return cells;
}
|
[
"function",
"(",
")",
"{",
"var",
"cell",
",",
"cells",
"=",
"{",
"}",
",",
"i",
"=",
"0",
",",
"count",
"=",
"this",
".",
"_cellCount",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"count",
";",
"i",
"++",
")",
"{",
"cell",
"=",
"this",
".",
"readCell",
"(",
")",
";",
"cells",
"[",
"cell",
".",
"ordinal",
"]",
"=",
"cell",
";",
"this",
".",
"nextCell",
"(",
")",
";",
"}",
"return",
"cells",
";",
"}"
] |
Iterate through each cell and return them all as a object by cell ordinal.
@method fetchAllAsObject
@return {object}
|
[
"Iterate",
"through",
"each",
"cell",
"and",
"return",
"them",
"all",
"as",
"a",
"object",
"by",
"cell",
"ordinal",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L7972-L7980
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(ordinal, object) {
var node, ord, idx, lastIndex = this.cellCount() - 1;
idx = ordinal > lastIndex ? lastIndex : ordinal;
while(true) {
node = this._cellNodes[idx];
ord = this._getCellOrdinal(node);
if (ord === ordinal) return this.getByIndex(idx, object);
else
if (ord > ordinal) idx--;
else return null;
}
}
|
javascript
|
function(ordinal, object) {
var node, ord, idx, lastIndex = this.cellCount() - 1;
idx = ordinal > lastIndex ? lastIndex : ordinal;
while(true) {
node = this._cellNodes[idx];
ord = this._getCellOrdinal(node);
if (ord === ordinal) return this.getByIndex(idx, object);
else
if (ord > ordinal) idx--;
else return null;
}
}
|
[
"function",
"(",
"ordinal",
",",
"object",
")",
"{",
"var",
"node",
",",
"ord",
",",
"idx",
",",
"lastIndex",
"=",
"this",
".",
"cellCount",
"(",
")",
"-",
"1",
";",
"idx",
"=",
"ordinal",
">",
"lastIndex",
"?",
"lastIndex",
":",
"ordinal",
";",
"while",
"(",
"true",
")",
"{",
"node",
"=",
"this",
".",
"_cellNodes",
"[",
"idx",
"]",
";",
"ord",
"=",
"this",
".",
"_getCellOrdinal",
"(",
"node",
")",
";",
"if",
"(",
"ord",
"===",
"ordinal",
")",
"return",
"this",
".",
"getByIndex",
"(",
"idx",
",",
"object",
")",
";",
"else",
"if",
"(",
"ord",
">",
"ordinal",
")",
"idx",
"--",
";",
"else",
"return",
"null",
";",
"}",
"}"
] |
Get a cell by its logical index.
@method getByOrdinal
@param {int} ordinal - the ordinal number of the cell to retrieve.
@param {object} object - optional. An object to copy the properties of the specified cell to. If omitted, a new object will be returned instead.
@return {object} An object that represents the cell.
|
[
"Get",
"a",
"cell",
"by",
"its",
"logical",
"index",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L8001-L8012
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(ordinal){
var cellNodes = this._cellNodes,
n = cellNodes.length,
index = Math.min(ordinal, n-1),
cellOrdinal, node
;
while(index >= 0) {
//get the node at the current index
node = cellNodes[index];
cellOrdinal = this._getCellOrdinal(node);
if (cellOrdinal === ordinal) {
return index;
}
else
if (cellOrdinal > ordinal) {
index--;
}
else {
return -1;
}
}
return -1;
}
|
javascript
|
function(ordinal){
var cellNodes = this._cellNodes,
n = cellNodes.length,
index = Math.min(ordinal, n-1),
cellOrdinal, node
;
while(index >= 0) {
//get the node at the current index
node = cellNodes[index];
cellOrdinal = this._getCellOrdinal(node);
if (cellOrdinal === ordinal) {
return index;
}
else
if (cellOrdinal > ordinal) {
index--;
}
else {
return -1;
}
}
return -1;
}
|
[
"function",
"(",
"ordinal",
")",
"{",
"var",
"cellNodes",
"=",
"this",
".",
"_cellNodes",
",",
"n",
"=",
"cellNodes",
".",
"length",
",",
"index",
"=",
"Math",
".",
"min",
"(",
"ordinal",
",",
"n",
"-",
"1",
")",
",",
"cellOrdinal",
",",
"node",
";",
"while",
"(",
"index",
">=",
"0",
")",
"{",
"node",
"=",
"cellNodes",
"[",
"index",
"]",
";",
"cellOrdinal",
"=",
"this",
".",
"_getCellOrdinal",
"(",
"node",
")",
";",
"if",
"(",
"cellOrdinal",
"===",
"ordinal",
")",
"{",
"return",
"index",
";",
"}",
"else",
"if",
"(",
"cellOrdinal",
">",
"ordinal",
")",
"{",
"index",
"--",
";",
"}",
"else",
"{",
"return",
"-",
"1",
";",
"}",
"}",
"return",
"-",
"1",
";",
"}"
] |
Get the physical cell index for the specified ordinal number.
This method is useful to calculate boundaries to retrieve a range of cells.
@method indexForOrdinal
@param {int} ordinal - the ordinal number for which the index shoul dbe returned
@return {int} The physical index.
|
[
"Get",
"the",
"physical",
"cell",
"index",
"for",
"the",
"specified",
"ordinal",
"number",
".",
"This",
"method",
"is",
"useful",
"to",
"calculate",
"boundaries",
"to",
"retrieve",
"a",
"range",
"of",
"cells",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L8020-L8042
|
train
|
|
rpbouman/xmla4js
|
src/Xmla.js
|
function(){
var funcstring, stack = "";
if (this.args) {
var func = this.args.callee;
while (func){
funcstring = String(func);
func = func.caller;
}
}
return stack;
}
|
javascript
|
function(){
var funcstring, stack = "";
if (this.args) {
var func = this.args.callee;
while (func){
funcstring = String(func);
func = func.caller;
}
}
return stack;
}
|
[
"function",
"(",
")",
"{",
"var",
"funcstring",
",",
"stack",
"=",
"\"\"",
";",
"if",
"(",
"this",
".",
"args",
")",
"{",
"var",
"func",
"=",
"this",
".",
"args",
".",
"callee",
";",
"while",
"(",
"func",
")",
"{",
"funcstring",
"=",
"String",
"(",
"func",
")",
";",
"func",
"=",
"func",
".",
"caller",
";",
"}",
"}",
"return",
"stack",
";",
"}"
] |
Get a stack trace.
@method getStackTrace
@return an array of objects describing the function on the stack
|
[
"Get",
"a",
"stack",
"trace",
"."
] |
96dfba5642c84ebccdf121616d6ec99931cf00d9
|
https://github.com/rpbouman/xmla4js/blob/96dfba5642c84ebccdf121616d6ec99931cf00d9/src/Xmla.js#L8518-L8528
|
train
|
|
tritech/node-icalendar
|
lib/rrule.js
|
wk
|
function wk(dt) {
var jan1 = new Date(Date.UTC(y(dt), 0, 1));
return trunc(daydiff(jan1, dt)/7);
}
|
javascript
|
function wk(dt) {
var jan1 = new Date(Date.UTC(y(dt), 0, 1));
return trunc(daydiff(jan1, dt)/7);
}
|
[
"function",
"wk",
"(",
"dt",
")",
"{",
"var",
"jan1",
"=",
"new",
"Date",
"(",
"Date",
".",
"UTC",
"(",
"y",
"(",
"dt",
")",
",",
"0",
",",
"1",
")",
")",
";",
"return",
"trunc",
"(",
"daydiff",
"(",
"jan1",
",",
"dt",
")",
"/",
"7",
")",
";",
"}"
] |
Week of year
|
[
"Week",
"of",
"year"
] |
afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6
|
https://github.com/tritech/node-icalendar/blob/afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6/lib/rrule.js#L101-L104
|
train
|
tritech/node-icalendar
|
lib/rrule.js
|
check_bymonth
|
function check_bymonth(rules, dt) {
if(!rules || !rules.length) return true;
return rules.indexOf(m(dt)) !== -1;
}
|
javascript
|
function check_bymonth(rules, dt) {
if(!rules || !rules.length) return true;
return rules.indexOf(m(dt)) !== -1;
}
|
[
"function",
"check_bymonth",
"(",
"rules",
",",
"dt",
")",
"{",
"if",
"(",
"!",
"rules",
"||",
"!",
"rules",
".",
"length",
")",
"return",
"true",
";",
"return",
"rules",
".",
"indexOf",
"(",
"m",
"(",
"dt",
")",
")",
"!==",
"-",
"1",
";",
"}"
] |
Check that a particular date is within the limits designated by the BYMONTH rule
|
[
"Check",
"that",
"a",
"particular",
"date",
"is",
"within",
"the",
"limits",
"designated",
"by",
"the",
"BYMONTH",
"rule"
] |
afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6
|
https://github.com/tritech/node-icalendar/blob/afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6/lib/rrule.js#L503-L506
|
train
|
tritech/node-icalendar
|
lib/rrule.js
|
bymonth
|
function bymonth(rules, dt) {
if(!rules || !rules.length) return dt;
var candidates = rules.map(function(rule) {
var delta = rule-m(dt);
if(delta < 0) delta += 12;
var newdt = add_m(new Date(dt), delta);
set_d(newdt, 1);
return newdt;
});
var newdt = sort_dates(candidates).shift();
return newdt || dt;
}
|
javascript
|
function bymonth(rules, dt) {
if(!rules || !rules.length) return dt;
var candidates = rules.map(function(rule) {
var delta = rule-m(dt);
if(delta < 0) delta += 12;
var newdt = add_m(new Date(dt), delta);
set_d(newdt, 1);
return newdt;
});
var newdt = sort_dates(candidates).shift();
return newdt || dt;
}
|
[
"function",
"bymonth",
"(",
"rules",
",",
"dt",
")",
"{",
"if",
"(",
"!",
"rules",
"||",
"!",
"rules",
".",
"length",
")",
"return",
"dt",
";",
"var",
"candidates",
"=",
"rules",
".",
"map",
"(",
"function",
"(",
"rule",
")",
"{",
"var",
"delta",
"=",
"rule",
"-",
"m",
"(",
"dt",
")",
";",
"if",
"(",
"delta",
"<",
"0",
")",
"delta",
"+=",
"12",
";",
"var",
"newdt",
"=",
"add_m",
"(",
"new",
"Date",
"(",
"dt",
")",
",",
"delta",
")",
";",
"set_d",
"(",
"newdt",
",",
"1",
")",
";",
"return",
"newdt",
";",
"}",
")",
";",
"var",
"newdt",
"=",
"sort_dates",
"(",
"candidates",
")",
".",
"shift",
"(",
")",
";",
"return",
"newdt",
"||",
"dt",
";",
"}"
] |
Advance to the next month that satisfies the rule...
|
[
"Advance",
"to",
"the",
"next",
"month",
"that",
"satisfies",
"the",
"rule",
"..."
] |
afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6
|
https://github.com/tritech/node-icalendar/blob/afe4df6ffcf3ab03f2a854c25c50b1420cf5b4f6/lib/rrule.js#L509-L523
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.