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
byu-oit/fully-typed
bin/schema.js
Schema
function Schema(config, data) { const controllers = data.controllers; const length = controllers.length; this.FullyTyped = FullyTyped; // apply controllers to this schema for (let i = 0; i < length; i++) controllers[i].call(this, config); // add additional properties if (config._extension_ && typeof config._extension_ === 'object') { const self = this; Object.keys(config._extension_).forEach(function(key) { self[key] = config._extension_[key]; }); } // store protected data with schema const protect = Object.assign({}, data); // create and store hash const options = getNormalizedSchemaConfiguration(this); protect.hash = crypto .createHash('sha256') .update(JSON.stringify(prepareForHash(options))) .digest('hex'); instances.set(this, protect); /** * @name Schema#config * @type {object} */ Object.defineProperty(this, 'config', { get: function() { return util.copy(config); } }); }
javascript
function Schema(config, data) { const controllers = data.controllers; const length = controllers.length; this.FullyTyped = FullyTyped; // apply controllers to this schema for (let i = 0; i < length; i++) controllers[i].call(this, config); // add additional properties if (config._extension_ && typeof config._extension_ === 'object') { const self = this; Object.keys(config._extension_).forEach(function(key) { self[key] = config._extension_[key]; }); } // store protected data with schema const protect = Object.assign({}, data); // create and store hash const options = getNormalizedSchemaConfiguration(this); protect.hash = crypto .createHash('sha256') .update(JSON.stringify(prepareForHash(options))) .digest('hex'); instances.set(this, protect); /** * @name Schema#config * @type {object} */ Object.defineProperty(this, 'config', { get: function() { return util.copy(config); } }); }
[ "function", "Schema", "(", "config", ",", "data", ")", "{", "const", "controllers", "=", "data", ".", "controllers", ";", "const", "length", "=", "controllers", ".", "length", ";", "this", ".", "FullyTyped", "=", "FullyTyped", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "controllers", "[", "i", "]", ".", "call", "(", "this", ",", "config", ")", ";", "if", "(", "config", ".", "_extension_", "&&", "typeof", "config", ".", "_extension_", "===", "'object'", ")", "{", "const", "self", "=", "this", ";", "Object", ".", "keys", "(", "config", ".", "_extension_", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "self", "[", "key", "]", "=", "config", ".", "_extension_", "[", "key", "]", ";", "}", ")", ";", "}", "const", "protect", "=", "Object", ".", "assign", "(", "{", "}", ",", "data", ")", ";", "const", "options", "=", "getNormalizedSchemaConfiguration", "(", "this", ")", ";", "protect", ".", "hash", "=", "crypto", ".", "createHash", "(", "'sha256'", ")", ".", "update", "(", "JSON", ".", "stringify", "(", "prepareForHash", "(", "options", ")", ")", ")", ".", "digest", "(", "'hex'", ")", ";", "instances", ".", "set", "(", "this", ",", "protect", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'config'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "util", ".", "copy", "(", "config", ")", ";", "}", "}", ")", ";", "}" ]
Create a schema instance. @param {Object} config The configuration for the schema. @param {ControllerData} data @constructor
[ "Create", "a", "schema", "instance", "." ]
ed6b3ed88ffc72990acffb765232eaaee261afef
https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/schema.js#L32-L69
train
victorherraiz/xreq
index.js
build
function build(base, config) { var result = resolver(base); Object.keys(config).forEach(function (key) { var value = config[key]; if (typeof value === "string") { result[key] = resolver(result(value, true)); } else if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "object") { result[key] = build(result(value[0], true), value[1]); } else { throw new TypeError("Invalid value at: " + key); } }); return result; }
javascript
function build(base, config) { var result = resolver(base); Object.keys(config).forEach(function (key) { var value = config[key]; if (typeof value === "string") { result[key] = resolver(result(value, true)); } else if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "object") { result[key] = build(result(value[0], true), value[1]); } else { throw new TypeError("Invalid value at: " + key); } }); return result; }
[ "function", "build", "(", "base", ",", "config", ")", "{", "var", "result", "=", "resolver", "(", "base", ")", ";", "Object", ".", "keys", "(", "config", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "value", "=", "config", "[", "key", "]", ";", "if", "(", "typeof", "value", "===", "\"string\"", ")", "{", "result", "[", "key", "]", "=", "resolver", "(", "result", "(", "value", ",", "true", ")", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", "&&", "value", ".", "length", "===", "2", "&&", "typeof", "value", "[", "0", "]", "===", "\"string\"", "&&", "typeof", "value", "[", "1", "]", "===", "\"object\"", ")", "{", "result", "[", "key", "]", "=", "build", "(", "result", "(", "value", "[", "0", "]", ",", "true", ")", ",", "value", "[", "1", "]", ")", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "\"Invalid value at: \"", "+", "key", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Process configuration file
[ "Process", "configuration", "file" ]
fa45fd135753bb4295dbc87ddcad5c9f1fd47bba
https://github.com/victorherraiz/xreq/blob/fa45fd135753bb4295dbc87ddcad5c9f1fd47bba/index.js#L48-L62
train
groundwater/node-lib-http-rpc
index.js
populateApiFromInterface
function populateApiFromInterface(api, iface) { Object.keys(iface).forEach(function (key) { api.add(key, iface[key]); }); }
javascript
function populateApiFromInterface(api, iface) { Object.keys(iface).forEach(function (key) { api.add(key, iface[key]); }); }
[ "function", "populateApiFromInterface", "(", "api", ",", "iface", ")", "{", "Object", ".", "keys", "(", "iface", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "api", ".", "add", "(", "key", ",", "iface", "[", "key", "]", ")", ";", "}", ")", ";", "}" ]
fill api from interface
[ "fill", "api", "from", "interface" ]
02dc58fad64a80184b22886417e1e1701667716b
https://github.com/groundwater/node-lib-http-rpc/blob/02dc58fad64a80184b22886417e1e1701667716b/index.js#L138-L142
train
groundwater/node-lib-http-rpc
index.js
router
function router(rpc, handlers, req, res) { var $ = rpc.$; var api = rpc.api; var request = api.handle(req.method, req.url); var dom = domain.create(); // the request handler doesn't exit // TODO: hoist response logic if (!request) { res.statusCode = 404; res.end(); return; } var context = new Context(); // TODO: hoist to own module var handle = request.handle; var params = {}; // TODO: hoist logic to 'union' module var key; for(key in request.params) params[key] = request.params[key]; for(key in request.query) params[key] = request.query[key]; var future = $.future(); future.setWritable(res); future.setReadable(req); // TODO: extract request making logic res.setHeader('Transfer-Encoding' , 'chunked'); res.setHeader('Content-Type' , 'application/json'); dom.on('error', function (err) { var statusCode = err.statusCode; // only catch known errors, re-throw unexpected errors if (!statusCode) throw err; // TODO: hoist response logic res.statusCode = statusCode; res.write(JSON.stringify(err)); res.end(); }); // domain should handle all route errors dom.run(function () { handlers[handle](future, params, context); }); }
javascript
function router(rpc, handlers, req, res) { var $ = rpc.$; var api = rpc.api; var request = api.handle(req.method, req.url); var dom = domain.create(); // the request handler doesn't exit // TODO: hoist response logic if (!request) { res.statusCode = 404; res.end(); return; } var context = new Context(); // TODO: hoist to own module var handle = request.handle; var params = {}; // TODO: hoist logic to 'union' module var key; for(key in request.params) params[key] = request.params[key]; for(key in request.query) params[key] = request.query[key]; var future = $.future(); future.setWritable(res); future.setReadable(req); // TODO: extract request making logic res.setHeader('Transfer-Encoding' , 'chunked'); res.setHeader('Content-Type' , 'application/json'); dom.on('error', function (err) { var statusCode = err.statusCode; // only catch known errors, re-throw unexpected errors if (!statusCode) throw err; // TODO: hoist response logic res.statusCode = statusCode; res.write(JSON.stringify(err)); res.end(); }); // domain should handle all route errors dom.run(function () { handlers[handle](future, params, context); }); }
[ "function", "router", "(", "rpc", ",", "handlers", ",", "req", ",", "res", ")", "{", "var", "$", "=", "rpc", ".", "$", ";", "var", "api", "=", "rpc", ".", "api", ";", "var", "request", "=", "api", ".", "handle", "(", "req", ".", "method", ",", "req", ".", "url", ")", ";", "var", "dom", "=", "domain", ".", "create", "(", ")", ";", "if", "(", "!", "request", ")", "{", "res", ".", "statusCode", "=", "404", ";", "res", ".", "end", "(", ")", ";", "return", ";", "}", "var", "context", "=", "new", "Context", "(", ")", ";", "var", "handle", "=", "request", ".", "handle", ";", "var", "params", "=", "{", "}", ";", "var", "key", ";", "for", "(", "key", "in", "request", ".", "params", ")", "params", "[", "key", "]", "=", "request", ".", "params", "[", "key", "]", ";", "for", "(", "key", "in", "request", ".", "query", ")", "params", "[", "key", "]", "=", "request", ".", "query", "[", "key", "]", ";", "var", "future", "=", "$", ".", "future", "(", ")", ";", "future", ".", "setWritable", "(", "res", ")", ";", "future", ".", "setReadable", "(", "req", ")", ";", "res", ".", "setHeader", "(", "'Transfer-Encoding'", ",", "'chunked'", ")", ";", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "dom", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "var", "statusCode", "=", "err", ".", "statusCode", ";", "if", "(", "!", "statusCode", ")", "throw", "err", ";", "res", ".", "statusCode", "=", "statusCode", ";", "res", ".", "write", "(", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "res", ".", "end", "(", ")", ";", "}", ")", ";", "dom", ".", "run", "(", "function", "(", ")", "{", "handlers", "[", "handle", "]", "(", "future", ",", "params", ",", "context", ")", ";", "}", ")", ";", "}" ]
make http router use Function.bind to create a router given an rpc, and set of handlers
[ "make", "http", "router", "use", "Function", ".", "bind", "to", "create", "a", "router", "given", "an", "rpc", "and", "set", "of", "handlers" ]
02dc58fad64a80184b22886417e1e1701667716b
https://github.com/groundwater/node-lib-http-rpc/blob/02dc58fad64a80184b22886417e1e1701667716b/index.js#L146-L194
train
nylen/lockd
client/index.js
addSimpleMethod
function addSimpleMethod(name, msg, failureIsError) { LockdClient.prototype[name] = function(objName, cb) { var self = this; self.transport.request(util.format(msg, objName), 1, function(err, lines) { self._processResponseLine(cb, err, lines && lines[0], failureIsError); }); }; }
javascript
function addSimpleMethod(name, msg, failureIsError) { LockdClient.prototype[name] = function(objName, cb) { var self = this; self.transport.request(util.format(msg, objName), 1, function(err, lines) { self._processResponseLine(cb, err, lines && lines[0], failureIsError); }); }; }
[ "function", "addSimpleMethod", "(", "name", ",", "msg", ",", "failureIsError", ")", "{", "LockdClient", ".", "prototype", "[", "name", "]", "=", "function", "(", "objName", ",", "cb", ")", "{", "var", "self", "=", "this", ";", "self", ".", "transport", ".", "request", "(", "util", ".", "format", "(", "msg", ",", "objName", ")", ",", "1", ",", "function", "(", "err", ",", "lines", ")", "{", "self", ".", "_processResponseLine", "(", "cb", ",", "err", ",", "lines", "&&", "lines", "[", "0", "]", ",", "failureIsError", ")", ";", "}", ")", ";", "}", ";", "}" ]
Add a simple method to the client prototype which sends a message to the lockd server and expects a single line back in response.
[ "Add", "a", "simple", "method", "to", "the", "client", "prototype", "which", "sends", "a", "message", "to", "the", "lockd", "server", "and", "expects", "a", "single", "line", "back", "in", "response", "." ]
352e663c81355d5b1b7837ae1afb97d50f39b196
https://github.com/nylen/lockd/blob/352e663c81355d5b1b7837ae1afb97d50f39b196/client/index.js#L49-L57
train
ForbesLindesay-Unmaintained/sauce-test
lib/run-single-browser.js
runSingleBrowser
function runSingleBrowser(location, remote, platform, options) { var capabilities = {}; Object.keys(platform).forEach(function (key) { capabilities[key] = platform[key]; }); var extraCapabilities = typeof options.capabilities === 'function' ? options.capabilities(platform) : (options.capabilities || {}); Object.keys(extraCapabilities).forEach(function (key) { capabilities[key] = extraCapabilities[key]; }); return retry(function (err) { var driver = getDriver(remote, capabilities, { mode: 'async', debug: options.debug, httpDebug: options.httpDebug, }); return driver._session().then(function () { return driver; }); }, 4, function (attempt) { return attempt * attempt * 5000; }, {debug: options.debug}).then(function (driver) { return runDriver(location, driver, { name: options.name, jobInfo: typeof options.jobInfo === 'function' ? options.jobInfo(platform) : options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout, debug: options.debug }).then(function (result) { return result; }); }); }
javascript
function runSingleBrowser(location, remote, platform, options) { var capabilities = {}; Object.keys(platform).forEach(function (key) { capabilities[key] = platform[key]; }); var extraCapabilities = typeof options.capabilities === 'function' ? options.capabilities(platform) : (options.capabilities || {}); Object.keys(extraCapabilities).forEach(function (key) { capabilities[key] = extraCapabilities[key]; }); return retry(function (err) { var driver = getDriver(remote, capabilities, { mode: 'async', debug: options.debug, httpDebug: options.httpDebug, }); return driver._session().then(function () { return driver; }); }, 4, function (attempt) { return attempt * attempt * 5000; }, {debug: options.debug}).then(function (driver) { return runDriver(location, driver, { name: options.name, jobInfo: typeof options.jobInfo === 'function' ? options.jobInfo(platform) : options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout, debug: options.debug }).then(function (result) { return result; }); }); }
[ "function", "runSingleBrowser", "(", "location", ",", "remote", ",", "platform", ",", "options", ")", "{", "var", "capabilities", "=", "{", "}", ";", "Object", ".", "keys", "(", "platform", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "capabilities", "[", "key", "]", "=", "platform", "[", "key", "]", ";", "}", ")", ";", "var", "extraCapabilities", "=", "typeof", "options", ".", "capabilities", "===", "'function'", "?", "options", ".", "capabilities", "(", "platform", ")", ":", "(", "options", ".", "capabilities", "||", "{", "}", ")", ";", "Object", ".", "keys", "(", "extraCapabilities", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "capabilities", "[", "key", "]", "=", "extraCapabilities", "[", "key", "]", ";", "}", ")", ";", "return", "retry", "(", "function", "(", "err", ")", "{", "var", "driver", "=", "getDriver", "(", "remote", ",", "capabilities", ",", "{", "mode", ":", "'async'", ",", "debug", ":", "options", ".", "debug", ",", "httpDebug", ":", "options", ".", "httpDebug", ",", "}", ")", ";", "return", "driver", ".", "_session", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "driver", ";", "}", ")", ";", "}", ",", "4", ",", "function", "(", "attempt", ")", "{", "return", "attempt", "*", "attempt", "*", "5000", ";", "}", ",", "{", "debug", ":", "options", ".", "debug", "}", ")", ".", "then", "(", "function", "(", "driver", ")", "{", "return", "runDriver", "(", "location", ",", "driver", ",", "{", "name", ":", "options", ".", "name", ",", "jobInfo", ":", "typeof", "options", ".", "jobInfo", "===", "'function'", "?", "options", ".", "jobInfo", "(", "platform", ")", ":", "options", ".", "jobInfo", ",", "allowExceptions", ":", "options", ".", "allowExceptions", ",", "testComplete", ":", "options", ".", "testComplete", ",", "testPassed", ":", "options", ".", "testPassed", ",", "timeout", ":", "options", ".", "timeout", ",", "debug", ":", "options", ".", "debug", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "return", "result", ";", "}", ")", ";", "}", ")", ";", "}" ]
Run a test in a single browser, then return the result @option {Object} capabilities @option {Boolean} debug @option {Object|Function} jobInfo @option {Boolean} allowExceptions @option {String|Function} testComplete @option {String|Function} testPassed @option {String} timeout Returns: ```js { "passed": true, "duration": "3000" } ``` @param {Location} location @param {Object} remote @param {Object} platform @param {Options} options @returns {Promise}
[ "Run", "a", "test", "in", "a", "single", "browser", "then", "return", "the", "result" ]
7c671b3321dc63aefc00c1c8d49e943ead2e7f5e
https://github.com/ForbesLindesay-Unmaintained/sauce-test/blob/7c671b3321dc63aefc00c1c8d49e943ead2e7f5e/lib/run-single-browser.js#L31-L64
train
doowb/transform-cache
index.js
Cache
function Cache (cache, options) { if (arguments.length === 1) { if (cache.hasOwnProperty('normalizeKey') || cache.hasOwnProperty('transform')) { options = cache; cache = {}; } } options = options || {}; this.cache = cache || {}; this.normalizeKey = options.normalizeKey || function (key) { return key; }; this.transform = options.transform || function (value) { return value; }; }
javascript
function Cache (cache, options) { if (arguments.length === 1) { if (cache.hasOwnProperty('normalizeKey') || cache.hasOwnProperty('transform')) { options = cache; cache = {}; } } options = options || {}; this.cache = cache || {}; this.normalizeKey = options.normalizeKey || function (key) { return key; }; this.transform = options.transform || function (value) { return value; }; }
[ "function", "Cache", "(", "cache", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "if", "(", "cache", ".", "hasOwnProperty", "(", "'normalizeKey'", ")", "||", "cache", ".", "hasOwnProperty", "(", "'transform'", ")", ")", "{", "options", "=", "cache", ";", "cache", "=", "{", "}", ";", "}", "}", "options", "=", "options", "||", "{", "}", ";", "this", ".", "cache", "=", "cache", "||", "{", "}", ";", "this", ".", "normalizeKey", "=", "options", ".", "normalizeKey", "||", "function", "(", "key", ")", "{", "return", "key", ";", "}", ";", "this", ".", "transform", "=", "options", ".", "transform", "||", "function", "(", "value", ")", "{", "return", "value", ";", "}", ";", "}" ]
Create a cache that transforms values when setting. ```js function makeKey = function (key) { return key.toUpperCase(); }; function transform = function (value) { return value.toUpperCase(); }; var cache = new Cache(makeKey, tranform); ``` @param {Object} `cache` Object to store the cache on. @param {Object} `options` @option {Function} `normalizeKey` normalize the `key` when getting and setting @option {Function} `transform` transform the `value` when setting @api public
[ "Create", "a", "cache", "that", "transforms", "values", "when", "setting", "." ]
cbdffe256c4f4c2e96a2f50b3f7ecb86cd7b1415
https://github.com/doowb/transform-cache/blob/cbdffe256c4f4c2e96a2f50b3f7ecb86cd7b1415/index.js#L31-L42
train
jsguy/mithril.component.mdl
mithril.component.mdl.js
function(attrs) { attrs = attrs || {}; attrs.state = attrs.state || {}; // Build our class name var cName = cfgClasses("mdl-button--", ["raised", "fab", "mini-fab", "icon", "colored", "primary", "accent"], attrs.state) + cfgClasses("mdl-js-", ["ripple-effect"], attrs.state); return attrsConfig({ className: "mdl-button mdl-js-button" + cName }, attrs); }
javascript
function(attrs) { attrs = attrs || {}; attrs.state = attrs.state || {}; // Build our class name var cName = cfgClasses("mdl-button--", ["raised", "fab", "mini-fab", "icon", "colored", "primary", "accent"], attrs.state) + cfgClasses("mdl-js-", ["ripple-effect"], attrs.state); return attrsConfig({ className: "mdl-button mdl-js-button" + cName }, attrs); }
[ "function", "(", "attrs", ")", "{", "attrs", "=", "attrs", "||", "{", "}", ";", "attrs", ".", "state", "=", "attrs", ".", "state", "||", "{", "}", ";", "var", "cName", "=", "cfgClasses", "(", "\"mdl-button--\"", ",", "[", "\"raised\"", ",", "\"fab\"", ",", "\"mini-fab\"", ",", "\"icon\"", ",", "\"colored\"", ",", "\"primary\"", ",", "\"accent\"", "]", ",", "attrs", ".", "state", ")", "+", "cfgClasses", "(", "\"mdl-js-\"", ",", "[", "\"ripple-effect\"", "]", ",", "attrs", ".", "state", ")", ";", "return", "attrsConfig", "(", "{", "className", ":", "\"mdl-button mdl-js-button\"", "+", "cName", "}", ",", "attrs", ")", ";", "}" ]
Set button class names
[ "Set", "button", "class", "names" ]
89a132fd475e55a98b239a229842661745a53372
https://github.com/jsguy/mithril.component.mdl/blob/89a132fd475e55a98b239a229842661745a53372/mithril.component.mdl.js#L173-L184
train
jsguy/mithril.component.mdl
mithril.component.mdl.js
function(ctrl, attrs) { attrs = mButton.attrs(attrs); // If there is a href, we assume this is a link button return m(attrs.cfg.href? 'a': 'button', attrExclude(attrs.cfg, ['text']), (attrs.state.fab || attrs.state.icon? m('i', {className: "material-icons"}, attrs.cfg.text): attrs.cfg.text) ); }
javascript
function(ctrl, attrs) { attrs = mButton.attrs(attrs); // If there is a href, we assume this is a link button return m(attrs.cfg.href? 'a': 'button', attrExclude(attrs.cfg, ['text']), (attrs.state.fab || attrs.state.icon? m('i', {className: "material-icons"}, attrs.cfg.text): attrs.cfg.text) ); }
[ "function", "(", "ctrl", ",", "attrs", ")", "{", "attrs", "=", "mButton", ".", "attrs", "(", "attrs", ")", ";", "return", "m", "(", "attrs", ".", "cfg", ".", "href", "?", "'a'", ":", "'button'", ",", "attrExclude", "(", "attrs", ".", "cfg", ",", "[", "'text'", "]", ")", ",", "(", "attrs", ".", "state", ".", "fab", "||", "attrs", ".", "state", ".", "icon", "?", "m", "(", "'i'", ",", "{", "className", ":", "\"material-icons\"", "}", ",", "attrs", ".", "cfg", ".", "text", ")", ":", "attrs", ".", "cfg", ".", "text", ")", ")", ";", "}" ]
Always use the attrs, not ctrl, as it isn't returned from the default controller.
[ "Always", "use", "the", "attrs", "not", "ctrl", "as", "it", "isn", "t", "returned", "from", "the", "default", "controller", "." ]
89a132fd475e55a98b239a229842661745a53372
https://github.com/jsguy/mithril.component.mdl/blob/89a132fd475e55a98b239a229842661745a53372/mithril.component.mdl.js#L187-L195
train
jsguy/mithril.component.mdl
mithril.component.mdl.js
function(attrs) { attrs = attrs || {}; attrs.state = attrs.state || {}; return attrsConfig({ className: "mdl-js-snackbar mdl-snackbar" }, attrs); }
javascript
function(attrs) { attrs = attrs || {}; attrs.state = attrs.state || {}; return attrsConfig({ className: "mdl-js-snackbar mdl-snackbar" }, attrs); }
[ "function", "(", "attrs", ")", "{", "attrs", "=", "attrs", "||", "{", "}", ";", "attrs", ".", "state", "=", "attrs", ".", "state", "||", "{", "}", ";", "return", "attrsConfig", "(", "{", "className", ":", "\"mdl-js-snackbar mdl-snackbar\"", "}", ",", "attrs", ")", ";", "}" ]
Set the default attrs here
[ "Set", "the", "default", "attrs", "here" ]
89a132fd475e55a98b239a229842661745a53372
https://github.com/jsguy/mithril.component.mdl/blob/89a132fd475e55a98b239a229842661745a53372/mithril.component.mdl.js#L384-L391
train
tlid/tlid
src/nodejs/tlid/tlid.js
tlid__xtro
function tlid__xtro(str) { var r = new Object(); r.tlid = "-1"; r.src = str; r.txt = ""; // r.deco = ""; if (tlid__has(str)) { r.tlid = tlid__xtr(str); r.txt = str.replace(r.tlid + " ", "") // try to clear out the double space .replace(r.tlid, "") // if ending the string, well we remove it .replace("@tlid ", ""); //remove the decorator } return r; }
javascript
function tlid__xtro(str) { var r = new Object(); r.tlid = "-1"; r.src = str; r.txt = ""; // r.deco = ""; if (tlid__has(str)) { r.tlid = tlid__xtr(str); r.txt = str.replace(r.tlid + " ", "") // try to clear out the double space .replace(r.tlid, "") // if ending the string, well we remove it .replace("@tlid ", ""); //remove the decorator } return r; }
[ "function", "tlid__xtro", "(", "str", ")", "{", "var", "r", "=", "new", "Object", "(", ")", ";", "r", ".", "tlid", "=", "\"-1\"", ";", "r", ".", "src", "=", "str", ";", "r", ".", "txt", "=", "\"\"", ";", "if", "(", "tlid__has", "(", "str", ")", ")", "{", "r", ".", "tlid", "=", "tlid__xtr", "(", "str", ")", ";", "r", ".", "txt", "=", "str", ".", "replace", "(", "r", ".", "tlid", "+", "\" \"", ",", "\"\"", ")", ".", "replace", "(", "r", ".", "tlid", ",", "\"\"", ")", ".", "replace", "(", "\"@tlid \"", ",", "\"\"", ")", ";", "}", "return", "r", ";", "}" ]
Extract a structure from the string @param {*} str
[ "Extract", "a", "structure", "from", "the", "string" ]
ddfab991965c1cf01abdde0311e1ee96f8defab3
https://github.com/tlid/tlid/blob/ddfab991965c1cf01abdde0311e1ee96f8defab3/src/nodejs/tlid/tlid.js#L192-L209
train
yoannmoinet/requirejs-i18njs
src/i18njs-builder.js
function (obj, fn) { for (var i in obj) { if (typeof obj[i] === 'object') { obj[i] = parse(obj[i], fn); } else { obj[i] = fn(obj[i], i); } } return obj; }
javascript
function (obj, fn) { for (var i in obj) { if (typeof obj[i] === 'object') { obj[i] = parse(obj[i], fn); } else { obj[i] = fn(obj[i], i); } } return obj; }
[ "function", "(", "obj", ",", "fn", ")", "{", "for", "(", "var", "i", "in", "obj", ")", "{", "if", "(", "typeof", "obj", "[", "i", "]", "===", "'object'", ")", "{", "obj", "[", "i", "]", "=", "parse", "(", "obj", "[", "i", "]", ",", "fn", ")", ";", "}", "else", "{", "obj", "[", "i", "]", "=", "fn", "(", "obj", "[", "i", "]", ",", "i", ")", ";", "}", "}", "return", "obj", ";", "}" ]
Simple self iterative function
[ "Simple", "self", "iterative", "function" ]
e33610f8b8d6cf46f9e473c5ffe39b24c277f73e
https://github.com/yoannmoinet/requirejs-i18njs/blob/e33610f8b8d6cf46f9e473c5ffe39b24c277f73e/src/i18njs-builder.js#L11-L20
train
yoannmoinet/requirejs-i18njs
src/i18njs-builder.js
changeKeys
function changeKeys (src, dest) { for (var i in src) { if (typeof src[i] === 'object') { dest[escapedSingleQuotes + i + escapedSingleQuotes] = {}; changeKeys(src[i], dest[escapedSingleQuotes + i + escapedSingleQuotes]); } else { dest[escapedSingleQuotes + i + escapedSingleQuotes] = src[i]; } } return dest; }
javascript
function changeKeys (src, dest) { for (var i in src) { if (typeof src[i] === 'object') { dest[escapedSingleQuotes + i + escapedSingleQuotes] = {}; changeKeys(src[i], dest[escapedSingleQuotes + i + escapedSingleQuotes]); } else { dest[escapedSingleQuotes + i + escapedSingleQuotes] = src[i]; } } return dest; }
[ "function", "changeKeys", "(", "src", ",", "dest", ")", "{", "for", "(", "var", "i", "in", "src", ")", "{", "if", "(", "typeof", "src", "[", "i", "]", "===", "'object'", ")", "{", "dest", "[", "escapedSingleQuotes", "+", "i", "+", "escapedSingleQuotes", "]", "=", "{", "}", ";", "changeKeys", "(", "src", "[", "i", "]", ",", "dest", "[", "escapedSingleQuotes", "+", "i", "+", "escapedSingleQuotes", "]", ")", ";", "}", "else", "{", "dest", "[", "escapedSingleQuotes", "+", "i", "+", "escapedSingleQuotes", "]", "=", "src", "[", "i", "]", ";", "}", "}", "return", "dest", ";", "}" ]
Little hack to keep quotes on key names.
[ "Little", "hack", "to", "keep", "quotes", "on", "key", "names", "." ]
e33610f8b8d6cf46f9e473c5ffe39b24c277f73e
https://github.com/yoannmoinet/requirejs-i18njs/blob/e33610f8b8d6cf46f9e473c5ffe39b24c277f73e/src/i18njs-builder.js#L84-L97
train
mozilla-services/connect-validation
index.js
errorsMiddleware
function errorsMiddleware(req, res, next) { var errors = []; res.addError = function(location, name, description) { if (["body", "header", "url", "querystring"].indexOf(location) === -1) { throw new Error('"' + location + '" is not a valid location. ' + 'Should be one of "header", "body", "url" or ' + '"querystring".'); } errors.push({ location: location, name: name, description: description }); }; res.sendError = function(location, name, description) { if (typeof location !== "undefined") { res.addError(location, name, description); } res.json(400, {status: "errors", errors: errors}); }; res.hasErrors = function() { return errors.length !== 0; }; next(); }
javascript
function errorsMiddleware(req, res, next) { var errors = []; res.addError = function(location, name, description) { if (["body", "header", "url", "querystring"].indexOf(location) === -1) { throw new Error('"' + location + '" is not a valid location. ' + 'Should be one of "header", "body", "url" or ' + '"querystring".'); } errors.push({ location: location, name: name, description: description }); }; res.sendError = function(location, name, description) { if (typeof location !== "undefined") { res.addError(location, name, description); } res.json(400, {status: "errors", errors: errors}); }; res.hasErrors = function() { return errors.length !== 0; }; next(); }
[ "function", "errorsMiddleware", "(", "req", ",", "res", ",", "next", ")", "{", "var", "errors", "=", "[", "]", ";", "res", ".", "addError", "=", "function", "(", "location", ",", "name", ",", "description", ")", "{", "if", "(", "[", "\"body\"", ",", "\"header\"", ",", "\"url\"", ",", "\"querystring\"", "]", ".", "indexOf", "(", "location", ")", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "'\"'", "+", "location", "+", "'\" is not a valid location. '", "+", "'Should be one of \"header\", \"body\", \"url\" or '", "+", "'\"querystring\".'", ")", ";", "}", "errors", ".", "push", "(", "{", "location", ":", "location", ",", "name", ":", "name", ",", "description", ":", "description", "}", ")", ";", "}", ";", "res", ".", "sendError", "=", "function", "(", "location", ",", "name", ",", "description", ")", "{", "if", "(", "typeof", "location", "!==", "\"undefined\"", ")", "{", "res", ".", "addError", "(", "location", ",", "name", ",", "description", ")", ";", "}", "res", ".", "json", "(", "400", ",", "{", "status", ":", "\"errors\"", ",", "errors", ":", "errors", "}", ")", ";", "}", ";", "res", ".", "hasErrors", "=", "function", "(", ")", "{", "return", "errors", ".", "length", "!==", "0", ";", "}", ";", "next", "(", ")", ";", "}" ]
The "errors" middleware adds two functions to the response object in order to handle validation. - "addError" adds a new validation error to the response. Should be followed by "sendError()" in order to send the response. - "sendError" adds a new validation error and sends the response right after. Response will be a `400 BAD REQUEST` JSON response. @param {String} location Location where the parameter had been looked for. Should be one of "header", "body", "url" or "querystring". @param {String} name Name of the faulty parameter. @param {String} description Description of the error. You can use directly "sendError" without any parameters to trigger the response.
[ "The", "errors", "middleware", "adds", "two", "functions", "to", "the", "response", "object", "in", "order", "to", "handle", "validation", "." ]
aa32a818b9d744f8f3fb61eb753f099535f3ab33
https://github.com/mozilla-services/connect-validation/blob/aa32a818b9d744f8f3fb61eb753f099535f3ab33/index.js#L24-L48
train
Biyaheroes/bh-mj-issue
dependency-react.support.js
function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }
javascript
function (internalInstance, transaction, updateBatchNumber) { if (internalInstance._updateBatchNumber !== updateBatchNumber) { // The component's enqueued batch number should always be the current // batch or the following one. process.env.NODE_ENV !== 'production' ? warning(internalInstance._updateBatchNumber == null || internalInstance._updateBatchNumber === updateBatchNumber + 1, 'performUpdateIfNecessary: Unexpected batch number (current %s, ' + 'pending %s)', updateBatchNumber, internalInstance._updateBatchNumber) : void 0; return; } if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onBeforeUpdateComponent(internalInstance._debugID, internalInstance._currentElement); } } internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { if (internalInstance._debugID !== 0) { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance._debugID); } } }
[ "function", "(", "internalInstance", ",", "transaction", ",", "updateBatchNumber", ")", "{", "if", "(", "internalInstance", ".", "_updateBatchNumber", "!==", "updateBatchNumber", ")", "{", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", "?", "warning", "(", "internalInstance", ".", "_updateBatchNumber", "==", "null", "||", "internalInstance", ".", "_updateBatchNumber", "===", "updateBatchNumber", "+", "1", ",", "'performUpdateIfNecessary: Unexpected batch number (current %s, '", "+", "'pending %s)'", ",", "updateBatchNumber", ",", "internalInstance", ".", "_updateBatchNumber", ")", ":", "void", "0", ";", "return", ";", "}", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "internalInstance", ".", "_debugID", "!==", "0", ")", "{", "ReactInstrumentation", ".", "debugTool", ".", "onBeforeUpdateComponent", "(", "internalInstance", ".", "_debugID", ",", "internalInstance", ".", "_currentElement", ")", ";", "}", "}", "internalInstance", ".", "performUpdateIfNecessary", "(", "transaction", ")", ";", "if", "(", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "if", "(", "internalInstance", ".", "_debugID", "!==", "0", ")", "{", "ReactInstrumentation", ".", "debugTool", ".", "onUpdateComponent", "(", "internalInstance", ".", "_debugID", ")", ";", "}", "}", "}" ]
Flush any dirty changes in a component. @param {ReactComponent} internalInstance @param {ReactReconcileTransaction} transaction @internal
[ "Flush", "any", "dirty", "changes", "in", "a", "component", "." ]
878be949e0a142139e75f579bdaed2cb43511008
https://github.com/Biyaheroes/bh-mj-issue/blob/878be949e0a142139e75f579bdaed2cb43511008/dependency-react.support.js#L2224-L2242
train
Biyaheroes/bh-mj-issue
dependency-react.support.js
function (publicInstance, completeState, callback) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; // Future-proof 15.5 if (callback !== undefined && callback !== null) { ReactUpdateQueue.validateCallback(callback, 'replaceState'); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }
javascript
function (publicInstance, completeState, callback) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; // Future-proof 15.5 if (callback !== undefined && callback !== null) { ReactUpdateQueue.validateCallback(callback, 'replaceState'); if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } } enqueueUpdate(internalInstance); }
[ "function", "(", "publicInstance", ",", "completeState", ",", "callback", ")", "{", "var", "internalInstance", "=", "getInternalInstanceReadyForUpdate", "(", "publicInstance", ",", "'replaceState'", ")", ";", "if", "(", "!", "internalInstance", ")", "{", "return", ";", "}", "internalInstance", ".", "_pendingStateQueue", "=", "[", "completeState", "]", ";", "internalInstance", ".", "_pendingReplaceState", "=", "true", ";", "if", "(", "callback", "!==", "undefined", "&&", "callback", "!==", "null", ")", "{", "ReactUpdateQueue", ".", "validateCallback", "(", "callback", ",", "'replaceState'", ")", ";", "if", "(", "internalInstance", ".", "_pendingCallbacks", ")", "{", "internalInstance", ".", "_pendingCallbacks", ".", "push", "(", "callback", ")", ";", "}", "else", "{", "internalInstance", ".", "_pendingCallbacks", "=", "[", "callback", "]", ";", "}", "}", "enqueueUpdate", "(", "internalInstance", ")", ";", "}" ]
Replaces all of the state. Always use this or `setState` to mutate state. You should treat `this.state` as immutable. There is no guarantee that `this.state` will be immediately updated, so accessing `this.state` after calling this method may return the old value. @param {ReactClass} publicInstance The instance that should rerender. @param {object} completeState Next state. @internal
[ "Replaces", "all", "of", "the", "state", ".", "Always", "use", "this", "or", "setState", "to", "mutate", "state", ".", "You", "should", "treat", "this", ".", "state", "as", "immutable", "." ]
878be949e0a142139e75f579bdaed2cb43511008
https://github.com/Biyaheroes/bh-mj-issue/blob/878be949e0a142139e75f579bdaed2cb43511008/dependency-react.support.js#L5635-L5656
train
franza/continuate
index.js
cps
function cps(fun) { /** * @param {...*} args * @param {Function} callback */ return function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var result; try { result = fun.apply(this, args); } catch (err) { callback(err); return; } callback(null, result); } }
javascript
function cps(fun) { /** * @param {...*} args * @param {Function} callback */ return function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var result; try { result = fun.apply(this, args); } catch (err) { callback(err); return; } callback(null, result); } }
[ "function", "cps", "(", "fun", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "callback", "=", "args", ".", "pop", "(", ")", ";", "var", "result", ";", "try", "{", "result", "=", "fun", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "result", ")", ";", "}", "}" ]
Returns function that provides results of fun in continuation-passing style @param fun @returns {Function}
[ "Returns", "function", "that", "provides", "results", "of", "fun", "in", "continuation", "-", "passing", "style" ]
008a8a84bb8c89a1f58cd2f6ad3da4bfd73d7d21
https://github.com/franza/continuate/blob/008a8a84bb8c89a1f58cd2f6ad3da4bfd73d7d21/index.js#L6-L23
train
AlphaReplica/Connecta
lib/client/source/connectaPeer.js
setIceServers
function setIceServers() { if(stunServers) { for(var num = 0; num < stunServers.length; num++) { connConfig['iceServers'].push({'urls':'stun:'+stunServers[num]}); } } }
javascript
function setIceServers() { if(stunServers) { for(var num = 0; num < stunServers.length; num++) { connConfig['iceServers'].push({'urls':'stun:'+stunServers[num]}); } } }
[ "function", "setIceServers", "(", ")", "{", "if", "(", "stunServers", ")", "{", "for", "(", "var", "num", "=", "0", ";", "num", "<", "stunServers", ".", "length", ";", "num", "++", ")", "{", "connConfig", "[", "'iceServers'", "]", ".", "push", "(", "{", "'urls'", ":", "'stun:'", "+", "stunServers", "[", "num", "]", "}", ")", ";", "}", "}", "}" ]
parses stun server array and returns rtc friendly object
[ "parses", "stun", "server", "array", "and", "returns", "rtc", "friendly", "object" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaPeer.js#L23-L32
train
AlphaReplica/Connecta
lib/client/source/connectaPeer.js
iceCandidateCallback
function iceCandidateCallback(e) { if(e.candidate != null) { if(scope.onIceCandidate) { scope.onIceCandidate(scope,JSON.stringify({'ice': e.candidate})); } } }
javascript
function iceCandidateCallback(e) { if(e.candidate != null) { if(scope.onIceCandidate) { scope.onIceCandidate(scope,JSON.stringify({'ice': e.candidate})); } } }
[ "function", "iceCandidateCallback", "(", "e", ")", "{", "if", "(", "e", ".", "candidate", "!=", "null", ")", "{", "if", "(", "scope", ".", "onIceCandidate", ")", "{", "scope", ".", "onIceCandidate", "(", "scope", ",", "JSON", ".", "stringify", "(", "{", "'ice'", ":", "e", ".", "candidate", "}", ")", ")", ";", "}", "}", "}" ]
callback for ice candidate
[ "callback", "for", "ice", "candidate" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaPeer.js#L35-L44
train
AlphaReplica/Connecta
lib/client/source/connectaPeer.js
onStateChange
function onStateChange(e) { if(scope._conn) { if(scope._conn.iceConnectionState == "connected") { if(scope.onConnected) { scope.onConnected(scope); } } if(scope._conn.iceConnectionState == "failed" || scope._conn.iceConnectionState == "disconnected") { if(scope.onConnectionFail) { scope.onConnectionFail(scope); } if(scope.type == "offer") { scope.createOffer(); } } if(scope._conn.iceConnectionState == "closed") { if(scope.onClosed) { scope.onClosed(scope); } scope.dispose(); } } }
javascript
function onStateChange(e) { if(scope._conn) { if(scope._conn.iceConnectionState == "connected") { if(scope.onConnected) { scope.onConnected(scope); } } if(scope._conn.iceConnectionState == "failed" || scope._conn.iceConnectionState == "disconnected") { if(scope.onConnectionFail) { scope.onConnectionFail(scope); } if(scope.type == "offer") { scope.createOffer(); } } if(scope._conn.iceConnectionState == "closed") { if(scope.onClosed) { scope.onClosed(scope); } scope.dispose(); } } }
[ "function", "onStateChange", "(", "e", ")", "{", "if", "(", "scope", ".", "_conn", ")", "{", "if", "(", "scope", ".", "_conn", ".", "iceConnectionState", "==", "\"connected\"", ")", "{", "if", "(", "scope", ".", "onConnected", ")", "{", "scope", ".", "onConnected", "(", "scope", ")", ";", "}", "}", "if", "(", "scope", ".", "_conn", ".", "iceConnectionState", "==", "\"failed\"", "||", "scope", ".", "_conn", ".", "iceConnectionState", "==", "\"disconnected\"", ")", "{", "if", "(", "scope", ".", "onConnectionFail", ")", "{", "scope", ".", "onConnectionFail", "(", "scope", ")", ";", "}", "if", "(", "scope", ".", "type", "==", "\"offer\"", ")", "{", "scope", ".", "createOffer", "(", ")", ";", "}", "}", "if", "(", "scope", ".", "_conn", ".", "iceConnectionState", "==", "\"closed\"", ")", "{", "if", "(", "scope", ".", "onClosed", ")", "{", "scope", ".", "onClosed", "(", "scope", ")", ";", "}", "scope", ".", "dispose", "(", ")", ";", "}", "}", "}" ]
called when ice connection state is changed
[ "called", "when", "ice", "connection", "state", "is", "changed" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaPeer.js#L61-L92
train
AlphaReplica/Connecta
lib/client/source/connectaPeer.js
remoteStreamCallback
function remoteStreamCallback(e) { scope.remoteStream = e.stream; if(scope.onRemoteStream) { scope.onRemoteStream(scope.remoteStream); } }
javascript
function remoteStreamCallback(e) { scope.remoteStream = e.stream; if(scope.onRemoteStream) { scope.onRemoteStream(scope.remoteStream); } }
[ "function", "remoteStreamCallback", "(", "e", ")", "{", "scope", ".", "remoteStream", "=", "e", ".", "stream", ";", "if", "(", "scope", ".", "onRemoteStream", ")", "{", "scope", ".", "onRemoteStream", "(", "scope", ".", "remoteStream", ")", ";", "}", "}" ]
called when remote stream is connected
[ "called", "when", "remote", "stream", "is", "connected" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaPeer.js#L104-L111
train
AlphaReplica/Connecta
lib/client/source/connectaPeer.js
ondatachannel
function ondatachannel(e) { if(e) { scope._data = e.channel; } else { scope._data = scope._conn.createDataChannel("data"); } scope._data.onopen = function() { if(scope._data) { if(scope._data.readyState == "open") { if(scope.onChannelState) { scope.onChannelState(scope,'open'); } } } }; scope._data.onmessage = function(e) { if(e.data instanceof ArrayBuffer) { if(scope.onBytesMessage) { scope.onBytesMessage(scope,e.data); } } else { if(scope.onMessage) { var char = Number(e.data[0]); if(char == MessageType.MESSAGE) { scope.onMessage(scope,JSON.parse(e.data.substring(1,e.data.length))); } else { scope.onMessage(scope,e.data); } } } } scope._data.onclose = function(e) { if(scope.onChannelState) { scope.onChannelState(scope,'closed'); } } scope._data.onerror = function(e) { if(scope.onError) { scope.onError(e); } } }
javascript
function ondatachannel(e) { if(e) { scope._data = e.channel; } else { scope._data = scope._conn.createDataChannel("data"); } scope._data.onopen = function() { if(scope._data) { if(scope._data.readyState == "open") { if(scope.onChannelState) { scope.onChannelState(scope,'open'); } } } }; scope._data.onmessage = function(e) { if(e.data instanceof ArrayBuffer) { if(scope.onBytesMessage) { scope.onBytesMessage(scope,e.data); } } else { if(scope.onMessage) { var char = Number(e.data[0]); if(char == MessageType.MESSAGE) { scope.onMessage(scope,JSON.parse(e.data.substring(1,e.data.length))); } else { scope.onMessage(scope,e.data); } } } } scope._data.onclose = function(e) { if(scope.onChannelState) { scope.onChannelState(scope,'closed'); } } scope._data.onerror = function(e) { if(scope.onError) { scope.onError(e); } } }
[ "function", "ondatachannel", "(", "e", ")", "{", "if", "(", "e", ")", "{", "scope", ".", "_data", "=", "e", ".", "channel", ";", "}", "else", "{", "scope", ".", "_data", "=", "scope", ".", "_conn", ".", "createDataChannel", "(", "\"data\"", ")", ";", "}", "scope", ".", "_data", ".", "onopen", "=", "function", "(", ")", "{", "if", "(", "scope", ".", "_data", ")", "{", "if", "(", "scope", ".", "_data", ".", "readyState", "==", "\"open\"", ")", "{", "if", "(", "scope", ".", "onChannelState", ")", "{", "scope", ".", "onChannelState", "(", "scope", ",", "'open'", ")", ";", "}", "}", "}", "}", ";", "scope", ".", "_data", ".", "onmessage", "=", "function", "(", "e", ")", "{", "if", "(", "e", ".", "data", "instanceof", "ArrayBuffer", ")", "{", "if", "(", "scope", ".", "onBytesMessage", ")", "{", "scope", ".", "onBytesMessage", "(", "scope", ",", "e", ".", "data", ")", ";", "}", "}", "else", "{", "if", "(", "scope", ".", "onMessage", ")", "{", "var", "char", "=", "Number", "(", "e", ".", "data", "[", "0", "]", ")", ";", "if", "(", "char", "==", "MessageType", ".", "MESSAGE", ")", "{", "scope", ".", "onMessage", "(", "scope", ",", "JSON", ".", "parse", "(", "e", ".", "data", ".", "substring", "(", "1", ",", "e", ".", "data", ".", "length", ")", ")", ")", ";", "}", "else", "{", "scope", ".", "onMessage", "(", "scope", ",", "e", ".", "data", ")", ";", "}", "}", "}", "}", "scope", ".", "_data", ".", "onclose", "=", "function", "(", "e", ")", "{", "if", "(", "scope", ".", "onChannelState", ")", "{", "scope", ".", "onChannelState", "(", "scope", ",", "'closed'", ")", ";", "}", "}", "scope", ".", "_data", ".", "onerror", "=", "function", "(", "e", ")", "{", "if", "(", "scope", ".", "onError", ")", "{", "scope", ".", "onError", "(", "e", ")", ";", "}", "}", "}" ]
called when datachannel event is invoked, also called manually from offer to create new datachannel
[ "called", "when", "datachannel", "event", "is", "invoked", "also", "called", "manually", "from", "offer", "to", "create", "new", "datachannel" ]
bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0
https://github.com/AlphaReplica/Connecta/blob/bc0ce3fa1ef5ef07526633da5668dcaff5ef29e0/lib/client/source/connectaPeer.js#L114-L179
train
ustbhuangyi/gulp-her-templateBuilder
index.js
expandSmartyPathAttr
function expandSmartyPathAttr(content, tagName, attrName, file) { var attrReg = new RegExp('((?:^|\\s)' + her.util.pregQuote(attrName) + '\\s*=\\s*)(([\"\']).*?\\3)', 'ig'); content = tagFilter.filterTag(content, tagName, smarty_left_delimiter, smarty_right_delimiter, function (outter, attr) { attr = attr.replace(attrReg, function (all, preCodeHolder, valueCodeHolder) { var info = her.util.stringQuote(valueCodeHolder); var path = info.rest; var ret = info.quote + her.uri.getId(path, file.dirname).id + info.quote; return preCodeHolder + ret; }); outter = smarty_left_delimiter + tagName + attr + smarty_right_delimiter; return outter; }); return content; }
javascript
function expandSmartyPathAttr(content, tagName, attrName, file) { var attrReg = new RegExp('((?:^|\\s)' + her.util.pregQuote(attrName) + '\\s*=\\s*)(([\"\']).*?\\3)', 'ig'); content = tagFilter.filterTag(content, tagName, smarty_left_delimiter, smarty_right_delimiter, function (outter, attr) { attr = attr.replace(attrReg, function (all, preCodeHolder, valueCodeHolder) { var info = her.util.stringQuote(valueCodeHolder); var path = info.rest; var ret = info.quote + her.uri.getId(path, file.dirname).id + info.quote; return preCodeHolder + ret; }); outter = smarty_left_delimiter + tagName + attr + smarty_right_delimiter; return outter; }); return content; }
[ "function", "expandSmartyPathAttr", "(", "content", ",", "tagName", ",", "attrName", ",", "file", ")", "{", "var", "attrReg", "=", "new", "RegExp", "(", "'((?:^|\\\\s)'", "+", "\\\\", "+", "her", ".", "util", ".", "pregQuote", "(", "attrName", ")", ",", "'\\\\s*=\\\\s*)(([\\\"\\']).*?\\\\3)'", ")", ";", "\\\\", "\\\\", "}" ]
expand smarty template resource path
[ "expand", "smarty", "template", "resource", "path" ]
9d24217db63efe2f24ed80697ec24ae6d13f9a23
https://github.com/ustbhuangyi/gulp-her-templateBuilder/blob/9d24217db63efe2f24ed80697ec24ae6d13f9a23/index.js#L123-L148
train
byu-oit/sans-server-swagger
bin/normalize-request.js
deserializeParameter
function deserializeParameter(server, name, value, schema) { if (!schema) return value; const type = schemaType(schema); if (!type) server.log('req-params', 'Indeterminate schema type for parameter ' + name, schema); if (type === 'array') { const format = schema.hasOwnProperty('collectionFormat') ? schema.collectionFormat : 'csv'; const delimiter = format === 'csv' ? ',' : format === 'ssv' ? ' ' : format === 'tsv' ? '\t' : format === 'pipes' ? '|' : ','; value = value.split(delimiter); if (!schema.items) return value; return value.map(item => { return deserializeParameter(server, 'items for ' + name, item, schema.items); }); } else if (type === 'boolean') { return !(value === 'false' || value === 'null' || value === '0' || value === ''); } else if (type === 'integer' && rxInteger.test(value)) { return parseInt(value); } else if (type === 'number' && rxNumber.test(value)) { return parseFloat(value); } else { return value; } }
javascript
function deserializeParameter(server, name, value, schema) { if (!schema) return value; const type = schemaType(schema); if (!type) server.log('req-params', 'Indeterminate schema type for parameter ' + name, schema); if (type === 'array') { const format = schema.hasOwnProperty('collectionFormat') ? schema.collectionFormat : 'csv'; const delimiter = format === 'csv' ? ',' : format === 'ssv' ? ' ' : format === 'tsv' ? '\t' : format === 'pipes' ? '|' : ','; value = value.split(delimiter); if (!schema.items) return value; return value.map(item => { return deserializeParameter(server, 'items for ' + name, item, schema.items); }); } else if (type === 'boolean') { return !(value === 'false' || value === 'null' || value === '0' || value === ''); } else if (type === 'integer' && rxInteger.test(value)) { return parseInt(value); } else if (type === 'number' && rxNumber.test(value)) { return parseFloat(value); } else { return value; } }
[ "function", "deserializeParameter", "(", "server", ",", "name", ",", "value", ",", "schema", ")", "{", "if", "(", "!", "schema", ")", "return", "value", ";", "const", "type", "=", "schemaType", "(", "schema", ")", ";", "if", "(", "!", "type", ")", "server", ".", "log", "(", "'req-params'", ",", "'Indeterminate schema type for parameter '", "+", "name", ",", "schema", ")", ";", "if", "(", "type", "===", "'array'", ")", "{", "const", "format", "=", "schema", ".", "hasOwnProperty", "(", "'collectionFormat'", ")", "?", "schema", ".", "collectionFormat", ":", "'csv'", ";", "const", "delimiter", "=", "format", "===", "'csv'", "?", "','", ":", "format", "===", "'ssv'", "?", "' '", ":", "format", "===", "'tsv'", "?", "'\\t'", ":", "\\t", ";", "format", "===", "'pipes'", "?", "'|'", ":", "','", "value", "=", "value", ".", "split", "(", "delimiter", ")", ";", "if", "(", "!", "schema", ".", "items", ")", "return", "value", ";", "}", "else", "return", "value", ".", "map", "(", "item", "=>", "{", "return", "deserializeParameter", "(", "server", ",", "'items for '", "+", "name", ",", "item", ",", "schema", ".", "items", ")", ";", "}", ")", ";", "}" ]
Deserialize a single parameter. @param {SansServer} server @param {string} name @param {*} value @param {*} schema @returns {*}
[ "Deserialize", "a", "single", "parameter", "." ]
455e76b8d65451e606e3c7894ff08affbeb447f1
https://github.com/byu-oit/sans-server-swagger/blob/455e76b8d65451e606e3c7894ff08affbeb447f1/bin/normalize-request.js#L150-L180
train
byu-oit/sans-server-swagger
bin/normalize-request.js
schemaType
function schemaType(schema) { let type; if (schema.hasOwnProperty('type')) { type = schema.type; } else if (schema.hasOwnProperty('properties') || schema.hasOwnProperty('allOf') || schema.hasOwnProperty('additionalProperties')) { type = 'object'; } else if (schema.hasOwnProperty('items')) { type = 'array'; } switch (type) { case 'array': case 'boolean': case 'file': case 'integer': case 'number': case 'object': case 'string': return type; } }
javascript
function schemaType(schema) { let type; if (schema.hasOwnProperty('type')) { type = schema.type; } else if (schema.hasOwnProperty('properties') || schema.hasOwnProperty('allOf') || schema.hasOwnProperty('additionalProperties')) { type = 'object'; } else if (schema.hasOwnProperty('items')) { type = 'array'; } switch (type) { case 'array': case 'boolean': case 'file': case 'integer': case 'number': case 'object': case 'string': return type; } }
[ "function", "schemaType", "(", "schema", ")", "{", "let", "type", ";", "if", "(", "schema", ".", "hasOwnProperty", "(", "'type'", ")", ")", "{", "type", "=", "schema", ".", "type", ";", "}", "else", "if", "(", "schema", ".", "hasOwnProperty", "(", "'properties'", ")", "||", "schema", ".", "hasOwnProperty", "(", "'allOf'", ")", "||", "schema", ".", "hasOwnProperty", "(", "'additionalProperties'", ")", ")", "{", "type", "=", "'object'", ";", "}", "else", "if", "(", "schema", ".", "hasOwnProperty", "(", "'items'", ")", ")", "{", "type", "=", "'array'", ";", "}", "switch", "(", "type", ")", "{", "case", "'array'", ":", "case", "'boolean'", ":", "case", "'file'", ":", "case", "'integer'", ":", "case", "'number'", ":", "case", "'object'", ":", "case", "'string'", ":", "return", "type", ";", "}", "}" ]
Detect the schema type. @param {Object} schema @returns {string,undefined}
[ "Detect", "the", "schema", "type", "." ]
455e76b8d65451e606e3c7894ff08affbeb447f1
https://github.com/byu-oit/sans-server-swagger/blob/455e76b8d65451e606e3c7894ff08affbeb447f1/bin/normalize-request.js#L187-L207
train
eventEmitter/ee-mysql
dep/node-buffalo/lib/objectid.js
ObjectId
function ObjectId(bytes) { if (Buffer.isBuffer(bytes)) { if (bytes.length != 12) throw new Error("Buffer-based ObjectId must be 12 bytes") this.bytes = bytes } else if (typeof bytes == 'string') { if (bytes.length != 24) throw new Error("String-based ObjectId must be 24 bytes") if (!/^[0-9a-f]{24}$/i.test(bytes)) throw new Error("String-based ObjectId must in hex-format:" + bytes) this.bytes = fromHex(bytes) } else if (typeof bytes !== 'undefined') { throw new Error("Unrecognized type: "+bytes) } else { var timestamp = (Date.now() / 1000) & 0xFFFFFFFF inc = ~~inc+1 // keep as integer this.bytes = new Buffer([ timestamp>>24, timestamp>>16, timestamp>>8, timestamp, machineAndPid[0], machineAndPid[1], machineAndPid[2], machineAndPid[3], machineAndPid[4], inc>>16, inc>>8, inc ]) } }
javascript
function ObjectId(bytes) { if (Buffer.isBuffer(bytes)) { if (bytes.length != 12) throw new Error("Buffer-based ObjectId must be 12 bytes") this.bytes = bytes } else if (typeof bytes == 'string') { if (bytes.length != 24) throw new Error("String-based ObjectId must be 24 bytes") if (!/^[0-9a-f]{24}$/i.test(bytes)) throw new Error("String-based ObjectId must in hex-format:" + bytes) this.bytes = fromHex(bytes) } else if (typeof bytes !== 'undefined') { throw new Error("Unrecognized type: "+bytes) } else { var timestamp = (Date.now() / 1000) & 0xFFFFFFFF inc = ~~inc+1 // keep as integer this.bytes = new Buffer([ timestamp>>24, timestamp>>16, timestamp>>8, timestamp, machineAndPid[0], machineAndPid[1], machineAndPid[2], machineAndPid[3], machineAndPid[4], inc>>16, inc>>8, inc ]) } }
[ "function", "ObjectId", "(", "bytes", ")", "{", "if", "(", "Buffer", ".", "isBuffer", "(", "bytes", ")", ")", "{", "if", "(", "bytes", ".", "length", "!=", "12", ")", "throw", "new", "Error", "(", "\"Buffer-based ObjectId must be 12 bytes\"", ")", "this", ".", "bytes", "=", "bytes", "}", "else", "if", "(", "typeof", "bytes", "==", "'string'", ")", "{", "if", "(", "bytes", ".", "length", "!=", "24", ")", "throw", "new", "Error", "(", "\"String-based ObjectId must be 24 bytes\"", ")", "if", "(", "!", "/", "^[0-9a-f]{24}$", "/", "i", ".", "test", "(", "bytes", ")", ")", "throw", "new", "Error", "(", "\"String-based ObjectId must in hex-format:\"", "+", "bytes", ")", "this", ".", "bytes", "=", "fromHex", "(", "bytes", ")", "}", "else", "if", "(", "typeof", "bytes", "!==", "'undefined'", ")", "{", "throw", "new", "Error", "(", "\"Unrecognized type: \"", "+", "bytes", ")", "}", "else", "{", "var", "timestamp", "=", "(", "Date", ".", "now", "(", ")", "/", "1000", ")", "&", "0xFFFFFFFF", "inc", "=", "~", "~", "inc", "+", "1", "this", ".", "bytes", "=", "new", "Buffer", "(", "[", "timestamp", ">>", "24", ",", "timestamp", ">>", "16", ",", "timestamp", ">>", "8", ",", "timestamp", ",", "machineAndPid", "[", "0", "]", ",", "machineAndPid", "[", "1", "]", ",", "machineAndPid", "[", "2", "]", ",", "machineAndPid", "[", "3", "]", ",", "machineAndPid", "[", "4", "]", ",", "inc", ">>", "16", ",", "inc", ">>", "8", ",", "inc", "]", ")", "}", "}" ]
32 bit time 24 bit machine id 16 bit pid 24 bit increment
[ "32", "bit", "time", "24", "bit", "machine", "id", "16", "bit", "pid", "24", "bit", "increment" ]
9797bff09a21157fb1dddb68275b01f282a184af
https://github.com/eventEmitter/ee-mysql/blob/9797bff09a21157fb1dddb68275b01f282a184af/dep/node-buffalo/lib/objectid.js#L32-L60
train
codenothing/munit
lib/munit.js
function( path ) { var parts = path.split( rpathsplit ), ns = munit.ns, assert; // Grep for nested path module munit.each( parts, function( part ) { if ( assert = ns[ part ] ) { ns = assert.ns; } else { throw new munit.AssertionError( "Module path not found '" + path + "'", munit._getModule ); } }); return assert; }
javascript
function( path ) { var parts = path.split( rpathsplit ), ns = munit.ns, assert; // Grep for nested path module munit.each( parts, function( part ) { if ( assert = ns[ part ] ) { ns = assert.ns; } else { throw new munit.AssertionError( "Module path not found '" + path + "'", munit._getModule ); } }); return assert; }
[ "function", "(", "path", ")", "{", "var", "parts", "=", "path", ".", "split", "(", "rpathsplit", ")", ",", "ns", "=", "munit", ".", "ns", ",", "assert", ";", "munit", ".", "each", "(", "parts", ",", "function", "(", "part", ")", "{", "if", "(", "assert", "=", "ns", "[", "part", "]", ")", "{", "ns", "=", "assert", ".", "ns", ";", "}", "else", "{", "throw", "new", "munit", ".", "AssertionError", "(", "\"Module path not found '\"", "+", "path", "+", "\"'\"", ",", "munit", ".", "_getModule", ")", ";", "}", "}", ")", ";", "return", "assert", ";", "}" ]
Gets module on path
[ "Gets", "module", "on", "path" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L274-L288
train
codenothing/munit
lib/munit.js
function( name, options, callback ) { var ns = munit.ns, parts = name.split( rpathsplit ), finalPart = parts.pop(), opts = munit.extend( true, {}, munit.defaults.settings ), assert = null, path = ''; // Filter through all parents parts.forEach(function( mod ) { // Update the path if ( path.length ) { path += '.'; } path += mod; // Assign assert module if ( ! ns[ mod ] ) { assert = ns[ mod ] = new munit.Assert( path, assert, opts ); } // Trickle down the path assert = ns[ mod ]; ns = assert.ns; opts = munit.extend( true, {}, opts, assert.options ); }); // Module already exists, update it if ( ns[ finalPart ] ) { assert = ns[ finalPart ]; // Test module is already in use, code setup is wrong if ( assert.callback ) { throw new munit.AssertionError( "'" + name + "' module has already been created", munit._createModule ); } assert.options = munit.extend( true, {}, opts, options ); assert.callback = callback; } else { options = munit.extend( true, {}, opts, options ); assert = ns[ finalPart ] = new munit.Assert( name, assert, options, callback ); } // Return the assertion module for use return assert; }
javascript
function( name, options, callback ) { var ns = munit.ns, parts = name.split( rpathsplit ), finalPart = parts.pop(), opts = munit.extend( true, {}, munit.defaults.settings ), assert = null, path = ''; // Filter through all parents parts.forEach(function( mod ) { // Update the path if ( path.length ) { path += '.'; } path += mod; // Assign assert module if ( ! ns[ mod ] ) { assert = ns[ mod ] = new munit.Assert( path, assert, opts ); } // Trickle down the path assert = ns[ mod ]; ns = assert.ns; opts = munit.extend( true, {}, opts, assert.options ); }); // Module already exists, update it if ( ns[ finalPart ] ) { assert = ns[ finalPart ]; // Test module is already in use, code setup is wrong if ( assert.callback ) { throw new munit.AssertionError( "'" + name + "' module has already been created", munit._createModule ); } assert.options = munit.extend( true, {}, opts, options ); assert.callback = callback; } else { options = munit.extend( true, {}, opts, options ); assert = ns[ finalPart ] = new munit.Assert( name, assert, options, callback ); } // Return the assertion module for use return assert; }
[ "function", "(", "name", ",", "options", ",", "callback", ")", "{", "var", "ns", "=", "munit", ".", "ns", ",", "parts", "=", "name", ".", "split", "(", "rpathsplit", ")", ",", "finalPart", "=", "parts", ".", "pop", "(", ")", ",", "opts", "=", "munit", ".", "extend", "(", "true", ",", "{", "}", ",", "munit", ".", "defaults", ".", "settings", ")", ",", "assert", "=", "null", ",", "path", "=", "''", ";", "parts", ".", "forEach", "(", "function", "(", "mod", ")", "{", "if", "(", "path", ".", "length", ")", "{", "path", "+=", "'.'", ";", "}", "path", "+=", "mod", ";", "if", "(", "!", "ns", "[", "mod", "]", ")", "{", "assert", "=", "ns", "[", "mod", "]", "=", "new", "munit", ".", "Assert", "(", "path", ",", "assert", ",", "opts", ")", ";", "}", "assert", "=", "ns", "[", "mod", "]", ";", "ns", "=", "assert", ".", "ns", ";", "opts", "=", "munit", ".", "extend", "(", "true", ",", "{", "}", ",", "opts", ",", "assert", ".", "options", ")", ";", "}", ")", ";", "if", "(", "ns", "[", "finalPart", "]", ")", "{", "assert", "=", "ns", "[", "finalPart", "]", ";", "if", "(", "assert", ".", "callback", ")", "{", "throw", "new", "munit", ".", "AssertionError", "(", "\"'\"", "+", "name", "+", "\"' module has already been created\"", ",", "munit", ".", "_createModule", ")", ";", "}", "assert", ".", "options", "=", "munit", ".", "extend", "(", "true", ",", "{", "}", ",", "opts", ",", "options", ")", ";", "assert", ".", "callback", "=", "callback", ";", "}", "else", "{", "options", "=", "munit", ".", "extend", "(", "true", ",", "{", "}", ",", "opts", ",", "options", ")", ";", "assert", "=", "ns", "[", "finalPart", "]", "=", "new", "munit", ".", "Assert", "(", "name", ",", "assert", ",", "options", ",", "callback", ")", ";", "}", "return", "assert", ";", "}" ]
Internal module creation
[ "Internal", "module", "creation" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L291-L337
train
codenothing/munit
lib/munit.js
function( name, depends, callback ) { if ( ( ! munit.isString( depends ) && ! munit.isArray( depends ) ) || ! depends.length ) { throw new Error( "Depends argument not found" ); } return munit._module( name, { depends: depends }, callback ); }
javascript
function( name, depends, callback ) { if ( ( ! munit.isString( depends ) && ! munit.isArray( depends ) ) || ! depends.length ) { throw new Error( "Depends argument not found" ); } return munit._module( name, { depends: depends }, callback ); }
[ "function", "(", "name", ",", "depends", ",", "callback", ")", "{", "if", "(", "(", "!", "munit", ".", "isString", "(", "depends", ")", "&&", "!", "munit", ".", "isArray", "(", "depends", ")", ")", "||", "!", "depends", ".", "length", ")", "{", "throw", "new", "Error", "(", "\"Depends argument not found\"", ")", ";", "}", "return", "munit", ".", "_module", "(", "name", ",", "{", "depends", ":", "depends", "}", ",", "callback", ")", ";", "}" ]
Creating module with dependencies
[ "Creating", "module", "with", "dependencies" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L345-L351
train
codenothing/munit
lib/munit.js
function( name, handle ) { if ( munit.isObject( name ) ) { return munit.each( name, function( fn, method ) { munit.custom( method, fn ); }); } // Ensure that name can be used if ( munit.customReserved.indexOf( name ) > -1 ) { throw new Error( "'" + name + "' is a reserved name and cannot be added as a custom assertion test" ); } // Send off to assertion module for attachment munit.Assert.prototype[ name ] = handle; munit.each( munit.ns, function( mod ) { mod.custom( name, handle ); }); }
javascript
function( name, handle ) { if ( munit.isObject( name ) ) { return munit.each( name, function( fn, method ) { munit.custom( method, fn ); }); } // Ensure that name can be used if ( munit.customReserved.indexOf( name ) > -1 ) { throw new Error( "'" + name + "' is a reserved name and cannot be added as a custom assertion test" ); } // Send off to assertion module for attachment munit.Assert.prototype[ name ] = handle; munit.each( munit.ns, function( mod ) { mod.custom( name, handle ); }); }
[ "function", "(", "name", ",", "handle", ")", "{", "if", "(", "munit", ".", "isObject", "(", "name", ")", ")", "{", "return", "munit", ".", "each", "(", "name", ",", "function", "(", "fn", ",", "method", ")", "{", "munit", ".", "custom", "(", "method", ",", "fn", ")", ";", "}", ")", ";", "}", "if", "(", "munit", ".", "customReserved", ".", "indexOf", "(", "name", ")", ">", "-", "1", ")", "{", "throw", "new", "Error", "(", "\"'\"", "+", "name", "+", "\"' is a reserved name and cannot be added as a custom assertion test\"", ")", ";", "}", "munit", ".", "Assert", ".", "prototype", "[", "name", "]", "=", "handle", ";", "munit", ".", "each", "(", "munit", ".", "ns", ",", "function", "(", "mod", ")", "{", "mod", ".", "custom", "(", "name", ",", "handle", ")", ";", "}", ")", ";", "}" ]
Adding custom test comparisons
[ "Adding", "custom", "test", "comparisons" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L354-L371
train
codenothing/munit
lib/munit.js
function( time ) { var h, m, s; if ( time > TIME_MINUTE ) { m = parseInt( time / TIME_MINUTE, 10 ); s = ( time % TIME_MINUTE ) / TIME_SECOND; return m + 'mins, ' + s + 's'; } else if ( time > TIME_SECOND ) { return ( time / TIME_SECOND ) + 's'; } else { return time + 'ms'; } }
javascript
function( time ) { var h, m, s; if ( time > TIME_MINUTE ) { m = parseInt( time / TIME_MINUTE, 10 ); s = ( time % TIME_MINUTE ) / TIME_SECOND; return m + 'mins, ' + s + 's'; } else if ( time > TIME_SECOND ) { return ( time / TIME_SECOND ) + 's'; } else { return time + 'ms'; } }
[ "function", "(", "time", ")", "{", "var", "h", ",", "m", ",", "s", ";", "if", "(", "time", ">", "TIME_MINUTE", ")", "{", "m", "=", "parseInt", "(", "time", "/", "TIME_MINUTE", ",", "10", ")", ";", "s", "=", "(", "time", "%", "TIME_MINUTE", ")", "/", "TIME_SECOND", ";", "return", "m", "+", "'mins, '", "+", "s", "+", "'s'", ";", "}", "else", "if", "(", "time", ">", "TIME_SECOND", ")", "{", "return", "(", "time", "/", "TIME_SECOND", ")", "+", "'s'", ";", "}", "else", "{", "return", "time", "+", "'ms'", ";", "}", "}" ]
Better timestamp readability
[ "Better", "timestamp", "readability" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L374-L388
train
codenothing/munit
lib/munit.js
function( string ) { return ( string || '' ).replace( ramp, "&amp;" ) .replace( rquote, "&quot;" ) .replace( rsquote, "&#039;" ) .replace( rlt, "&lt;" ) .replace( rgt, "&gt;" ); }
javascript
function( string ) { return ( string || '' ).replace( ramp, "&amp;" ) .replace( rquote, "&quot;" ) .replace( rsquote, "&#039;" ) .replace( rlt, "&lt;" ) .replace( rgt, "&gt;" ); }
[ "function", "(", "string", ")", "{", "return", "(", "string", "||", "''", ")", ".", "replace", "(", "ramp", ",", "\"&amp;\"", ")", ".", "replace", "(", "rquote", ",", "\"&quot;\"", ")", ".", "replace", "(", "rsquote", ",", "\"&#039;\"", ")", ".", "replace", "(", "rlt", ",", "\"&lt;\"", ")", ".", "replace", "(", "rgt", ",", "\"&gt;\"", ")", ";", "}" ]
Converts strings to be xml safe
[ "Converts", "strings", "to", "be", "xml", "safe" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L391-L397
train
codenothing/munit
lib/munit.js
function( code, e, message ) { var callback = munit.render.callback; // Force a numeric code for the first parameter if ( ! munit.isNumber( code ) ) { throw new Error( "Numeric code parameter required for munit.exit" ); } // Allow code, message only arguments if ( message === undefined && munit.isString( e ) ) { message = e; e = null; } // Messaging if ( munit.isString( message ) ) { munit.color.red( message ); } // Force an error object for callbacks if ( ! munit.isError( e ) ) { e = new Error( message || 'munit exited' ); } e.code = code; // Only print out stack trace on an active process if ( munit.render.state !== munit.RENDER_STATE_COMPLETE ) { munit.log( e.stack ); } // Callback takes priority if ( callback ) { munit.render.callback = undefined; callback( e, munit ); } // No callback, end the process else { munit._exit( code ); } }
javascript
function( code, e, message ) { var callback = munit.render.callback; // Force a numeric code for the first parameter if ( ! munit.isNumber( code ) ) { throw new Error( "Numeric code parameter required for munit.exit" ); } // Allow code, message only arguments if ( message === undefined && munit.isString( e ) ) { message = e; e = null; } // Messaging if ( munit.isString( message ) ) { munit.color.red( message ); } // Force an error object for callbacks if ( ! munit.isError( e ) ) { e = new Error( message || 'munit exited' ); } e.code = code; // Only print out stack trace on an active process if ( munit.render.state !== munit.RENDER_STATE_COMPLETE ) { munit.log( e.stack ); } // Callback takes priority if ( callback ) { munit.render.callback = undefined; callback( e, munit ); } // No callback, end the process else { munit._exit( code ); } }
[ "function", "(", "code", ",", "e", ",", "message", ")", "{", "var", "callback", "=", "munit", ".", "render", ".", "callback", ";", "if", "(", "!", "munit", ".", "isNumber", "(", "code", ")", ")", "{", "throw", "new", "Error", "(", "\"Numeric code parameter required for munit.exit\"", ")", ";", "}", "if", "(", "message", "===", "undefined", "&&", "munit", ".", "isString", "(", "e", ")", ")", "{", "message", "=", "e", ";", "e", "=", "null", ";", "}", "if", "(", "munit", ".", "isString", "(", "message", ")", ")", "{", "munit", ".", "color", ".", "red", "(", "message", ")", ";", "}", "if", "(", "!", "munit", ".", "isError", "(", "e", ")", ")", "{", "e", "=", "new", "Error", "(", "message", "||", "'munit exited'", ")", ";", "}", "e", ".", "code", "=", "code", ";", "if", "(", "munit", ".", "render", ".", "state", "!==", "munit", ".", "RENDER_STATE_COMPLETE", ")", "{", "munit", ".", "log", "(", "e", ".", "stack", ")", ";", "}", "if", "(", "callback", ")", "{", "munit", ".", "render", ".", "callback", "=", "undefined", ";", "callback", "(", "e", ",", "munit", ")", ";", "}", "else", "{", "munit", ".", "_exit", "(", "code", ")", ";", "}", "}" ]
Helper for printing out errors before exiting
[ "Helper", "for", "printing", "out", "errors", "before", "exiting" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L400-L439
train
codenothing/munit
lib/munit.js
AssertionError
function AssertionError( message, startFunc ) { var self = this; self.name = 'Assertion Error'; self.message = message; if ( Error.captureStackTrace ) { Error.captureStackTrace( self, startFunc ); } }
javascript
function AssertionError( message, startFunc ) { var self = this; self.name = 'Assertion Error'; self.message = message; if ( Error.captureStackTrace ) { Error.captureStackTrace( self, startFunc ); } }
[ "function", "AssertionError", "(", "message", ",", "startFunc", ")", "{", "var", "self", "=", "this", ";", "self", ".", "name", "=", "'Assertion Error'", ";", "self", ".", "message", "=", "message", ";", "if", "(", "Error", ".", "captureStackTrace", ")", "{", "Error", ".", "captureStackTrace", "(", "self", ",", "startFunc", ")", ";", "}", "}" ]
AssertionError stolen from node src for throwing
[ "AssertionError", "stolen", "from", "node", "src", "for", "throwing" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/munit.js#L460-L469
train
ilkkahanninen/petiole
packages/petiole/src/actionCreatorBuilders.js
buildFromString
function buildFromString({ declaration, name, mapActionType }) { if (typeof declaration === 'string') { return arg => ({ type: mapActionType(name), [declaration]: arg, }); } return null; }
javascript
function buildFromString({ declaration, name, mapActionType }) { if (typeof declaration === 'string') { return arg => ({ type: mapActionType(name), [declaration]: arg, }); } return null; }
[ "function", "buildFromString", "(", "{", "declaration", ",", "name", ",", "mapActionType", "}", ")", "{", "if", "(", "typeof", "declaration", "===", "'string'", ")", "{", "return", "arg", "=>", "(", "{", "type", ":", "mapActionType", "(", "name", ")", ",", "[", "declaration", "]", ":", "arg", ",", "}", ")", ";", "}", "return", "null", ";", "}" ]
Strings -> simple action creatos with one argument
[ "Strings", "-", ">", "simple", "action", "creatos", "with", "one", "argument" ]
3ec52be7ad159dcf015efc9035a801fa3b52f8a2
https://github.com/ilkkahanninen/petiole/blob/3ec52be7ad159dcf015efc9035a801fa3b52f8a2/packages/petiole/src/actionCreatorBuilders.js#L10-L18
train
ilkkahanninen/petiole
packages/petiole/src/actionCreatorBuilders.js
buildFromArray
function buildFromArray({ declaration, name, mapActionType }) { if (Array.isArray(declaration)) { return (...args) => declaration.reduce( (result, key, index) => Object.assign( result, { [key]: args[index] } ), { type: mapActionType(name) } ); } return null; }
javascript
function buildFromArray({ declaration, name, mapActionType }) { if (Array.isArray(declaration)) { return (...args) => declaration.reduce( (result, key, index) => Object.assign( result, { [key]: args[index] } ), { type: mapActionType(name) } ); } return null; }
[ "function", "buildFromArray", "(", "{", "declaration", ",", "name", ",", "mapActionType", "}", ")", "{", "if", "(", "Array", ".", "isArray", "(", "declaration", ")", ")", "{", "return", "(", "...", "args", ")", "=>", "declaration", ".", "reduce", "(", "(", "result", ",", "key", ",", "index", ")", "=>", "Object", ".", "assign", "(", "result", ",", "{", "[", "key", "]", ":", "args", "[", "index", "]", "}", ")", ",", "{", "type", ":", "mapActionType", "(", "name", ")", "}", ")", ";", "}", "return", "null", ";", "}" ]
Arrays -> simple action creators with multiple arguments
[ "Arrays", "-", ">", "simple", "action", "creators", "with", "multiple", "arguments" ]
3ec52be7ad159dcf015efc9035a801fa3b52f8a2
https://github.com/ilkkahanninen/petiole/blob/3ec52be7ad159dcf015efc9035a801fa3b52f8a2/packages/petiole/src/actionCreatorBuilders.js#L21-L32
train
ilkkahanninen/petiole
packages/petiole/src/actionCreatorBuilders.js
buildFromObject
function buildFromObject({ declaration, name, mapActionType }) { if (typeof declaration === 'object') { return () => ensureActionType(declaration, name, mapActionType); } return null; }
javascript
function buildFromObject({ declaration, name, mapActionType }) { if (typeof declaration === 'object') { return () => ensureActionType(declaration, name, mapActionType); } return null; }
[ "function", "buildFromObject", "(", "{", "declaration", ",", "name", ",", "mapActionType", "}", ")", "{", "if", "(", "typeof", "declaration", "===", "'object'", ")", "{", "return", "(", ")", "=>", "ensureActionType", "(", "declaration", ",", "name", ",", "mapActionType", ")", ";", "}", "return", "null", ";", "}" ]
Objects -> simplea action creator with fixed payload
[ "Objects", "-", ">", "simplea", "action", "creator", "with", "fixed", "payload" ]
3ec52be7ad159dcf015efc9035a801fa3b52f8a2
https://github.com/ilkkahanninen/petiole/blob/3ec52be7ad159dcf015efc9035a801fa3b52f8a2/packages/petiole/src/actionCreatorBuilders.js#L35-L40
train
edcs/searchbar
src/searchbar.js
function () { var html = template(); var div = document.createElement('div'); div.innerHTML = html.trim(); var searchBar = this.applySearcbarEvents(div.firstChild); searchBar = this.setDefaultSearchTerm(searchBar); return searchBar; }
javascript
function () { var html = template(); var div = document.createElement('div'); div.innerHTML = html.trim(); var searchBar = this.applySearcbarEvents(div.firstChild); searchBar = this.setDefaultSearchTerm(searchBar); return searchBar; }
[ "function", "(", ")", "{", "var", "html", "=", "template", "(", ")", ";", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "innerHTML", "=", "html", ".", "trim", "(", ")", ";", "var", "searchBar", "=", "this", ".", "applySearcbarEvents", "(", "div", ".", "firstChild", ")", ";", "searchBar", "=", "this", ".", "setDefaultSearchTerm", "(", "searchBar", ")", ";", "return", "searchBar", ";", "}" ]
Parses the searchbar template into an HTML string. @returns {*}
[ "Parses", "the", "searchbar", "template", "into", "an", "HTML", "string", "." ]
0734208cd098e6ddb00343a6b14c962c3b74749b
https://github.com/edcs/searchbar/blob/0734208cd098e6ddb00343a6b14c962c3b74749b/src/searchbar.js#L32-L42
train
edcs/searchbar
src/searchbar.js
function (searchbar) { var that = this; var button = searchbar.querySelector('button[type=submit]'); var search = searchbar.querySelector('input[type=search]'); if (typeof button === 'undefined') { return searchbar; } button.onclick = function (ev) { ev.preventDefault(); that.emitter.emit('search-request', search); }; return searchbar; }
javascript
function (searchbar) { var that = this; var button = searchbar.querySelector('button[type=submit]'); var search = searchbar.querySelector('input[type=search]'); if (typeof button === 'undefined') { return searchbar; } button.onclick = function (ev) { ev.preventDefault(); that.emitter.emit('search-request', search); }; return searchbar; }
[ "function", "(", "searchbar", ")", "{", "var", "that", "=", "this", ";", "var", "button", "=", "searchbar", ".", "querySelector", "(", "'button[type=submit]'", ")", ";", "var", "search", "=", "searchbar", ".", "querySelector", "(", "'input[type=search]'", ")", ";", "if", "(", "typeof", "button", "===", "'undefined'", ")", "{", "return", "searchbar", ";", "}", "button", ".", "onclick", "=", "function", "(", "ev", ")", "{", "ev", ".", "preventDefault", "(", ")", ";", "that", ".", "emitter", ".", "emit", "(", "'search-request'", ",", "search", ")", ";", "}", ";", "return", "searchbar", ";", "}" ]
Applies onclick events to this searchbar. @param searchbar @returns {*}
[ "Applies", "onclick", "events", "to", "this", "searchbar", "." ]
0734208cd098e6ddb00343a6b14c962c3b74749b
https://github.com/edcs/searchbar/blob/0734208cd098e6ddb00343a6b14c962c3b74749b/src/searchbar.js#L50-L65
train
bredele/vomit-markdown
index.js
render
function render(code, data) { var js = '```js' + code + '```' return `<div class="vomit-snippet"><div class="column">${marked(js)}</div><div class="column"><script> (function() {${code}document.currentScript.parentElement.appendChild(component(${JSON.stringify(data.data)})) })()</script></div></div>` }
javascript
function render(code, data) { var js = '```js' + code + '```' return `<div class="vomit-snippet"><div class="column">${marked(js)}</div><div class="column"><script> (function() {${code}document.currentScript.parentElement.appendChild(component(${JSON.stringify(data.data)})) })()</script></div></div>` }
[ "function", "render", "(", "code", ",", "data", ")", "{", "var", "js", "=", "'```js'", "+", "code", "+", "'```'", "return", "`", "${", "marked", "(", "js", ")", "}", "${", "code", "}", "${", "JSON", ".", "stringify", "(", "data", ".", "data", ")", "}", "`", "}" ]
Render code and live example. @param {String} code @param {Object} data @api private
[ "Render", "code", "and", "live", "example", "." ]
6ec3ff809167cabe6f0a03464a06d470dbdc9219
https://github.com/bredele/vomit-markdown/blob/6ec3ff809167cabe6f0a03464a06d470dbdc9219/index.js#L41-L46
train
huafu/ember-enhanced-router
addon/route.js
route
function route(name, titleToken, options) { var path, match; if (name instanceof RouteMeta) { return name; } if (name) { match = name.match(/^([^@]+)(?:@(.*))?$/); name = match[1]; path = match[2]; if (path === undefined) { path = name === 'index' ? '/' : name; } else if (path === '') { path = '/'; } else if (path === '*') { path = '/*wildcard'; } } else { path = '/'; } return RouteMeta.create({ name: name || 'application', path: path, routerTitleToken: {value: titleToken}, options: options || {} }); }
javascript
function route(name, titleToken, options) { var path, match; if (name instanceof RouteMeta) { return name; } if (name) { match = name.match(/^([^@]+)(?:@(.*))?$/); name = match[1]; path = match[2]; if (path === undefined) { path = name === 'index' ? '/' : name; } else if (path === '') { path = '/'; } else if (path === '*') { path = '/*wildcard'; } } else { path = '/'; } return RouteMeta.create({ name: name || 'application', path: path, routerTitleToken: {value: titleToken}, options: options || {} }); }
[ "function", "route", "(", "name", ",", "titleToken", ",", "options", ")", "{", "var", "path", ",", "match", ";", "if", "(", "name", "instanceof", "RouteMeta", ")", "{", "return", "name", ";", "}", "if", "(", "name", ")", "{", "match", "=", "name", ".", "match", "(", "/", "^([^@]+)(?:@(.*))?$", "/", ")", ";", "name", "=", "match", "[", "1", "]", ";", "path", "=", "match", "[", "2", "]", ";", "if", "(", "path", "===", "undefined", ")", "{", "path", "=", "name", "===", "'index'", "?", "'/'", ":", "name", ";", "}", "else", "if", "(", "path", "===", "''", ")", "{", "path", "=", "'/'", ";", "}", "else", "if", "(", "path", "===", "'*'", ")", "{", "path", "=", "'/*wildcard'", ";", "}", "}", "else", "{", "path", "=", "'/'", ";", "}", "return", "RouteMeta", ".", "create", "(", "{", "name", ":", "name", "||", "'application'", ",", "path", ":", "path", ",", "routerTitleToken", ":", "{", "value", ":", "titleToken", "}", ",", "options", ":", "options", "||", "{", "}", "}", ")", ";", "}" ]
Build the Ember expected map for a route @module ember-enhanced-router @function route @param {string|RouteMeta} [name=null] The name of the route with an optional path after `@`, or null for application route @param {string|Function} [titleToken] The title token for that route, or a function to create it @param {{resetTitle: boolean}} [options] Options @return {RouteMeta}
[ "Build", "the", "Ember", "expected", "map", "for", "a", "route" ]
47aa023dd5069de18ad4dd116ef18dd1f2160fbb
https://github.com/huafu/ember-enhanced-router/blob/47aa023dd5069de18ad4dd116ef18dd1f2160fbb/addon/route.js#L32-L60
train
huafu/ember-enhanced-router
addon/route.js
function (target) { if (this.get('isResource') && !this.get('indexChild')) { // add index route if it does not exist this._route('index'); } this.get('children').forEach(function (meta) { var args, methodName, isResource; args = [meta.get('name'), {path: meta.get('path')}]; methodName = meta.get('methodName'); isResource = meta.get('isResource'); if (isResource) { args.push(meta.get('mapFunction')); } console[isResource && console.group ? 'group' : 'log']( '[enhanced-router] defining ' + meta ); target[methodName].apply(target, args); if (isResource && console.group) { console.groupEnd(); } }); }
javascript
function (target) { if (this.get('isResource') && !this.get('indexChild')) { // add index route if it does not exist this._route('index'); } this.get('children').forEach(function (meta) { var args, methodName, isResource; args = [meta.get('name'), {path: meta.get('path')}]; methodName = meta.get('methodName'); isResource = meta.get('isResource'); if (isResource) { args.push(meta.get('mapFunction')); } console[isResource && console.group ? 'group' : 'log']( '[enhanced-router] defining ' + meta ); target[methodName].apply(target, args); if (isResource && console.group) { console.groupEnd(); } }); }
[ "function", "(", "target", ")", "{", "if", "(", "this", ".", "get", "(", "'isResource'", ")", "&&", "!", "this", ".", "get", "(", "'indexChild'", ")", ")", "{", "this", ".", "_route", "(", "'index'", ")", ";", "}", "this", ".", "get", "(", "'children'", ")", ".", "forEach", "(", "function", "(", "meta", ")", "{", "var", "args", ",", "methodName", ",", "isResource", ";", "args", "=", "[", "meta", ".", "get", "(", "'name'", ")", ",", "{", "path", ":", "meta", ".", "get", "(", "'path'", ")", "}", "]", ";", "methodName", "=", "meta", ".", "get", "(", "'methodName'", ")", ";", "isResource", "=", "meta", ".", "get", "(", "'isResource'", ")", ";", "if", "(", "isResource", ")", "{", "args", ".", "push", "(", "meta", ".", "get", "(", "'mapFunction'", ")", ")", ";", "}", "console", "[", "isResource", "&&", "console", ".", "group", "?", "'group'", ":", "'log'", "]", "(", "'[enhanced-router] defining '", "+", "meta", ")", ";", "target", "[", "methodName", "]", ".", "apply", "(", "target", ",", "args", ")", ";", "if", "(", "isResource", "&&", "console", ".", "group", ")", "{", "console", ".", "groupEnd", "(", ")", ";", "}", "}", ")", ";", "}" ]
The method doing the call as Router.map is expecting @method map @param {Ember.Router.recognizer} target
[ "The", "method", "doing", "the", "call", "as", "Router", ".", "map", "is", "expecting" ]
47aa023dd5069de18ad4dd116ef18dd1f2160fbb
https://github.com/huafu/ember-enhanced-router/blob/47aa023dd5069de18ad4dd116ef18dd1f2160fbb/addon/route.js#L304-L325
train
huafu/ember-enhanced-router
addon/route.js
function (name, titleToken, options) { var child; if (!this.get('isResource')) { this.set('isResource', true); } child = route(name, titleToken, options, this); child.set('parent', this); this.get('children').pushObject(child); return this; }
javascript
function (name, titleToken, options) { var child; if (!this.get('isResource')) { this.set('isResource', true); } child = route(name, titleToken, options, this); child.set('parent', this); this.get('children').pushObject(child); return this; }
[ "function", "(", "name", ",", "titleToken", ",", "options", ")", "{", "var", "child", ";", "if", "(", "!", "this", ".", "get", "(", "'isResource'", ")", ")", "{", "this", ".", "set", "(", "'isResource'", ",", "true", ")", ";", "}", "child", "=", "route", "(", "name", ",", "titleToken", ",", "options", ",", "this", ")", ";", "child", ".", "set", "(", "'parent'", ",", "this", ")", ";", "this", ".", "get", "(", "'children'", ")", ".", "pushObject", "(", "child", ")", ";", "return", "this", ";", "}" ]
Define a child-route to this route @method route @param {string|RouteMeta} name @param {string} [titleToken] @param {{resetTitle: boolean}} [options] @chainable
[ "Define", "a", "child", "-", "route", "to", "this", "route" ]
47aa023dd5069de18ad4dd116ef18dd1f2160fbb
https://github.com/huafu/ember-enhanced-router/blob/47aa023dd5069de18ad4dd116ef18dd1f2160fbb/addon/route.js#L403-L412
train
huafu/ember-enhanced-router
addon/route.js
function () { var routes = Array.prototype.slice.call(arguments); if (routes.length) { Ember.A(routes).forEach(function (child) { this._route(child); }, this); } else { if (!this.get('isResource')) { this.set('isResource', true); } } return this; }
javascript
function () { var routes = Array.prototype.slice.call(arguments); if (routes.length) { Ember.A(routes).forEach(function (child) { this._route(child); }, this); } else { if (!this.get('isResource')) { this.set('isResource', true); } } return this; }
[ "function", "(", ")", "{", "var", "routes", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "routes", ".", "length", ")", "{", "Ember", ".", "A", "(", "routes", ")", ".", "forEach", "(", "function", "(", "child", ")", "{", "this", ".", "_route", "(", "child", ")", ";", "}", ",", "this", ")", ";", "}", "else", "{", "if", "(", "!", "this", ".", "get", "(", "'isResource'", ")", ")", "{", "this", ".", "set", "(", "'isResource'", ",", "true", ")", ";", "}", "}", "return", "this", ";", "}" ]
Define many child-routes to this route @method routes @params {RouteMeta} [meta...] @chainable
[ "Define", "many", "child", "-", "routes", "to", "this", "route" ]
47aa023dd5069de18ad4dd116ef18dd1f2160fbb
https://github.com/huafu/ember-enhanced-router/blob/47aa023dd5069de18ad4dd116ef18dd1f2160fbb/addon/route.js#L421-L434
train
huafu/ember-enhanced-router
addon/route.js
function (options) { var Router, args; if (this.get('parent')) { throw new Error('Only the root route may be exported as an Ember router.'); } args = slice.call(arguments); if (!args.length || args[args.length - 1] instanceof Ember.Mixin) { args.push(options = {}); } else { options = args[args.length - 1]; } options._enhancedRouterRootMeta = this; Router = Ember.Router.extend.apply(Ember.Router, args); Router.map(this.get('mapFunction')); return Router; }
javascript
function (options) { var Router, args; if (this.get('parent')) { throw new Error('Only the root route may be exported as an Ember router.'); } args = slice.call(arguments); if (!args.length || args[args.length - 1] instanceof Ember.Mixin) { args.push(options = {}); } else { options = args[args.length - 1]; } options._enhancedRouterRootMeta = this; Router = Ember.Router.extend.apply(Ember.Router, args); Router.map(this.get('mapFunction')); return Router; }
[ "function", "(", "options", ")", "{", "var", "Router", ",", "args", ";", "if", "(", "this", ".", "get", "(", "'parent'", ")", ")", "{", "throw", "new", "Error", "(", "'Only the root route may be exported as an Ember router.'", ")", ";", "}", "args", "=", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "!", "args", ".", "length", "||", "args", "[", "args", ".", "length", "-", "1", "]", "instanceof", "Ember", ".", "Mixin", ")", "{", "args", ".", "push", "(", "options", "=", "{", "}", ")", ";", "}", "else", "{", "options", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "}", "options", ".", "_enhancedRouterRootMeta", "=", "this", ";", "Router", "=", "Ember", ".", "Router", ".", "extend", ".", "apply", "(", "Ember", ".", "Router", ",", "args", ")", ";", "Router", ".", "map", "(", "this", ".", "get", "(", "'mapFunction'", ")", ")", ";", "return", "Router", ";", "}" ]
Transforms this RouteMeta into an Ember router @method toRouter @param {Object} options @return {Ember.Router}
[ "Transforms", "this", "RouteMeta", "into", "an", "Ember", "router" ]
47aa023dd5069de18ad4dd116ef18dd1f2160fbb
https://github.com/huafu/ember-enhanced-router/blob/47aa023dd5069de18ad4dd116ef18dd1f2160fbb/addon/route.js#L452-L468
train
rmariuzzo/fuf
fuf.js
fuf
function fuf(target, source, options = {}) { return new Promise((resolve, reject) => { if (!target) { return reject(new Error('the target path is required')) } if (!source) { return reject(new Error('the source path is required')) } if (options && MATCHES.indexOf(options.match) === -1) { return reject(new Error(`options.match should be one of the following values: ${MATCHES.join(', ')}.`)) } options = { ...defaults, ...options } Promise.all([ pglob(target, { nodir: true, ignore: source }), findSourceFiles(source), ]).then(([targetFiles, sourceFiles]) => { // By default all source files are considered unused. const unused = sourceFiles.map(file => ({ ...file })) // We loop through all files looking for unused files matches, when we // found a match we removed it from the unused bag. const results = targetFiles.map(file => { return fs.readFile(file) .then(data => { const matches = findMatches(data.toString(), unused.map(u => u[options.match])) matches.forEach(match => { // Remove match from unused. unused.splice(unused.findIndex(u => u[options.match] === match.needle), 1) // Remove match from source files. sourceFiles.splice(sourceFiles.findIndex(f => f[options.match] === match.needle), 1) }) }) }) Promise .all(results) .then(() => { resolve({ unused }) }) }).catch(reject) }) }
javascript
function fuf(target, source, options = {}) { return new Promise((resolve, reject) => { if (!target) { return reject(new Error('the target path is required')) } if (!source) { return reject(new Error('the source path is required')) } if (options && MATCHES.indexOf(options.match) === -1) { return reject(new Error(`options.match should be one of the following values: ${MATCHES.join(', ')}.`)) } options = { ...defaults, ...options } Promise.all([ pglob(target, { nodir: true, ignore: source }), findSourceFiles(source), ]).then(([targetFiles, sourceFiles]) => { // By default all source files are considered unused. const unused = sourceFiles.map(file => ({ ...file })) // We loop through all files looking for unused files matches, when we // found a match we removed it from the unused bag. const results = targetFiles.map(file => { return fs.readFile(file) .then(data => { const matches = findMatches(data.toString(), unused.map(u => u[options.match])) matches.forEach(match => { // Remove match from unused. unused.splice(unused.findIndex(u => u[options.match] === match.needle), 1) // Remove match from source files. sourceFiles.splice(sourceFiles.findIndex(f => f[options.match] === match.needle), 1) }) }) }) Promise .all(results) .then(() => { resolve({ unused }) }) }).catch(reject) }) }
[ "function", "fuf", "(", "target", ",", "source", ",", "options", "=", "{", "}", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "!", "target", ")", "{", "return", "reject", "(", "new", "Error", "(", "'the target path is required'", ")", ")", "}", "if", "(", "!", "source", ")", "{", "return", "reject", "(", "new", "Error", "(", "'the source path is required'", ")", ")", "}", "if", "(", "options", "&&", "MATCHES", ".", "indexOf", "(", "options", ".", "match", ")", "===", "-", "1", ")", "{", "return", "reject", "(", "new", "Error", "(", "`", "${", "MATCHES", ".", "join", "(", "', '", ")", "}", "`", ")", ")", "}", "options", "=", "{", "...", "defaults", ",", "...", "options", "}", "Promise", ".", "all", "(", "[", "pglob", "(", "target", ",", "{", "nodir", ":", "true", ",", "ignore", ":", "source", "}", ")", ",", "findSourceFiles", "(", "source", ")", ",", "]", ")", ".", "then", "(", "(", "[", "targetFiles", ",", "sourceFiles", "]", ")", "=>", "{", "const", "unused", "=", "sourceFiles", ".", "map", "(", "file", "=>", "(", "{", "...", "file", "}", ")", ")", "const", "results", "=", "targetFiles", ".", "map", "(", "file", "=>", "{", "return", "fs", ".", "readFile", "(", "file", ")", ".", "then", "(", "data", "=>", "{", "const", "matches", "=", "findMatches", "(", "data", ".", "toString", "(", ")", ",", "unused", ".", "map", "(", "u", "=>", "u", "[", "options", ".", "match", "]", ")", ")", "matches", ".", "forEach", "(", "match", "=>", "{", "unused", ".", "splice", "(", "unused", ".", "findIndex", "(", "u", "=>", "u", "[", "options", ".", "match", "]", "===", "match", ".", "needle", ")", ",", "1", ")", "sourceFiles", ".", "splice", "(", "sourceFiles", ".", "findIndex", "(", "f", "=>", "f", "[", "options", ".", "match", "]", "===", "match", ".", "needle", ")", ",", "1", ")", "}", ")", "}", ")", "}", ")", "Promise", ".", "all", "(", "results", ")", ".", "then", "(", "(", ")", "=>", "{", "resolve", "(", "{", "unused", "}", ")", "}", ")", "}", ")", ".", "catch", "(", "reject", ")", "}", ")", "}" ]
Find unused files. @param {string} target The target directory containing files that will be used to look for usage. @param {string} source The source directory containing files that will be determined if unused. @param {FufOptions} options The options. @return {Promise<FindSourceFilesResult[]> Error>}
[ "Find", "unused", "files", "." ]
77743e94fd1df628beee0126fc6ce000b7f7814b
https://github.com/rmariuzzo/fuf/blob/77743e94fd1df628beee0126fc6ce000b7f7814b/fuf.js#L40-L86
train
rmariuzzo/fuf
fuf.js
pglob
function pglob(pattern, options) { return new Promise((resolve, reject) => { glob(pattern, options, (error, files) => { if (error) { return reject(error) } resolve(files) }) }) }
javascript
function pglob(pattern, options) { return new Promise((resolve, reject) => { glob(pattern, options, (error, files) => { if (error) { return reject(error) } resolve(files) }) }) }
[ "function", "pglob", "(", "pattern", ",", "options", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "glob", "(", "pattern", ",", "options", ",", "(", "error", ",", "files", ")", "=>", "{", "if", "(", "error", ")", "{", "return", "reject", "(", "error", ")", "}", "resolve", "(", "files", ")", "}", ")", "}", ")", "}" ]
Promisify version of glob. @param {string} pattern The glob pattern. @param {Object} options The hash of options. @return {Promise<string[], Error>}
[ "Promisify", "version", "of", "glob", "." ]
77743e94fd1df628beee0126fc6ce000b7f7814b
https://github.com/rmariuzzo/fuf/blob/77743e94fd1df628beee0126fc6ce000b7f7814b/fuf.js#L127-L136
train
piranna/jocker
lib/index.js
chrootSpawn
function chrootSpawn(command, argv, opts, callback) { argv = [opts.uid, opts.gid, command].concat(argv) const options = { cwd: opts.cwd, env: opts.env, stdio: 'inherit' } proc.spawn(`${__dirname}/chrootSpawn`, argv, options).on('exit', callback) }
javascript
function chrootSpawn(command, argv, opts, callback) { argv = [opts.uid, opts.gid, command].concat(argv) const options = { cwd: opts.cwd, env: opts.env, stdio: 'inherit' } proc.spawn(`${__dirname}/chrootSpawn`, argv, options).on('exit', callback) }
[ "function", "chrootSpawn", "(", "command", ",", "argv", ",", "opts", ",", "callback", ")", "{", "argv", "=", "[", "opts", ".", "uid", ",", "opts", ".", "gid", ",", "command", "]", ".", "concat", "(", "argv", ")", "const", "options", "=", "{", "cwd", ":", "opts", ".", "cwd", ",", "env", ":", "opts", ".", "env", ",", "stdio", ":", "'inherit'", "}", "proc", ".", "spawn", "(", "`", "${", "__dirname", "}", "`", ",", "argv", ",", "options", ")", ".", "on", "(", "'exit'", ",", "callback", ")", "}" ]
Exec a command on a `chroot`ed directory with un-priviledged permissions @param {String} command Path of the command file inside the home folder @param {String[]} [argv] Command arguments @param {Object} [opts] Extra options @param {Function} callback
[ "Exec", "a", "command", "on", "a", "chroot", "ed", "directory", "with", "un", "-", "priviledged", "permissions" ]
a4c53fb5c1de65a4a490fd04bdae4d03a7f9ca54
https://github.com/piranna/jocker/blob/a4c53fb5c1de65a4a490fd04bdae4d03a7f9ca54/lib/index.js#L26-L38
train
piranna/jocker
lib/index.js
mkdirMountInfo
function mkdirMountInfo(info, callback) { utils.mkdirMount(info.path, info.type, info.flags, info.extras, callback) }
javascript
function mkdirMountInfo(info, callback) { utils.mkdirMount(info.path, info.type, info.flags, info.extras, callback) }
[ "function", "mkdirMountInfo", "(", "info", ",", "callback", ")", "{", "utils", ".", "mkdirMount", "(", "info", ".", "path", ",", "info", ".", "type", ",", "info", ".", "flags", ",", "info", ".", "extras", ",", "callback", ")", "}" ]
Mounts the provided path to the device If no device is available then it uses the type @access private @param {Object} info This object holds information about the folder to create @property {String} info.dev Device-File being mounted (located in `/dev`) a.k.a. devFile. @property {String} info.path Directory to mount the device to. @property {String} info.type Filesystem identificator (one of `/proc/filesystems`). @property {Array|Number} info.[flags] Flags for mounting @property {String} info.[extras] The data argument is interpreted by the different file systems. Typically it is a string of comma-separated options understood by this file system @param {Function} callback Function called after the mount operation finishes. Receives only one argument err.
[ "Mounts", "the", "provided", "path", "to", "the", "device" ]
a4c53fb5c1de65a4a490fd04bdae4d03a7f9ca54
https://github.com/piranna/jocker/blob/a4c53fb5c1de65a4a490fd04bdae4d03a7f9ca54/lib/index.js#L62-L65
train
piranna/jocker
lib/index.js
create
function create(upperdir, callback) { var workdir = upperdir.split('/') var user = workdir.pop() var workdir = workdir.join('/')+'/.workdirs/'+user mkdirp(workdir, '0100', function(error) { if(error && error.code !== 'EEXIST') return callback(error) // Craft overlayed filesystem var type = 'overlay' var extras = { lowerdir: '/', upperdir: upperdir, workdir : workdir } utils.mkdirMount(upperdir, type, MS_NOSUID, extras, function(error) { if(error) return callback(error) var arr = [ { path: upperdir+'/dev', flags: MS_BIND, extras: {devFile: '/tmp/dev'} }, { path: upperdir+'/proc', flags: MS_BIND, extras: {devFile: '/proc'} }, { path: upperdir+'/tmp', type: 'tmpfs', flags: MS_NODEV | MS_NOSUID } ] each(arr, mkdirMountInfo, callback) }) }) }
javascript
function create(upperdir, callback) { var workdir = upperdir.split('/') var user = workdir.pop() var workdir = workdir.join('/')+'/.workdirs/'+user mkdirp(workdir, '0100', function(error) { if(error && error.code !== 'EEXIST') return callback(error) // Craft overlayed filesystem var type = 'overlay' var extras = { lowerdir: '/', upperdir: upperdir, workdir : workdir } utils.mkdirMount(upperdir, type, MS_NOSUID, extras, function(error) { if(error) return callback(error) var arr = [ { path: upperdir+'/dev', flags: MS_BIND, extras: {devFile: '/tmp/dev'} }, { path: upperdir+'/proc', flags: MS_BIND, extras: {devFile: '/proc'} }, { path: upperdir+'/tmp', type: 'tmpfs', flags: MS_NODEV | MS_NOSUID } ] each(arr, mkdirMountInfo, callback) }) }) }
[ "function", "create", "(", "upperdir", ",", "callback", ")", "{", "var", "workdir", "=", "upperdir", ".", "split", "(", "'/'", ")", "var", "user", "=", "workdir", ".", "pop", "(", ")", "var", "workdir", "=", "workdir", ".", "join", "(", "'/'", ")", "+", "'/.workdirs/'", "+", "user", "mkdirp", "(", "workdir", ",", "'0100'", ",", "function", "(", "error", ")", "{", "if", "(", "error", "&&", "error", ".", "code", "!==", "'EEXIST'", ")", "return", "callback", "(", "error", ")", "var", "type", "=", "'overlay'", "var", "extras", "=", "{", "lowerdir", ":", "'/'", ",", "upperdir", ":", "upperdir", ",", "workdir", ":", "workdir", "}", "utils", ".", "mkdirMount", "(", "upperdir", ",", "type", ",", "MS_NOSUID", ",", "extras", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "return", "callback", "(", "error", ")", "var", "arr", "=", "[", "{", "path", ":", "upperdir", "+", "'/dev'", ",", "flags", ":", "MS_BIND", ",", "extras", ":", "{", "devFile", ":", "'/tmp/dev'", "}", "}", ",", "{", "path", ":", "upperdir", "+", "'/proc'", ",", "flags", ":", "MS_BIND", ",", "extras", ":", "{", "devFile", ":", "'/proc'", "}", "}", ",", "{", "path", ":", "upperdir", "+", "'/tmp'", ",", "type", ":", "'tmpfs'", ",", "flags", ":", "MS_NODEV", "|", "MS_NOSUID", "}", "]", "each", "(", "arr", ",", "mkdirMountInfo", ",", "callback", ")", "}", ")", "}", ")", "}" ]
Public API Execute the command file @param {String} upperdir Path of the root of the container @param {Function} callback
[ "Public", "API", "Execute", "the", "command", "file" ]
a4c53fb5c1de65a4a490fd04bdae4d03a7f9ca54
https://github.com/piranna/jocker/blob/a4c53fb5c1de65a4a490fd04bdae4d03a7f9ca54/lib/index.js#L78-L123
train
richRemer/twixt-class
class.js
clas
function clas(elem, className) { /** * @param {boolean} [val] * @returns {boolean|undefined} */ return function() { if (arguments.length) { elem.classList[arguments[0] ? "add" : "remove"](className); } else { return elem.classList.has(className); } } }
javascript
function clas(elem, className) { /** * @param {boolean} [val] * @returns {boolean|undefined} */ return function() { if (arguments.length) { elem.classList[arguments[0] ? "add" : "remove"](className); } else { return elem.classList.has(className); } } }
[ "function", "clas", "(", "elem", ",", "className", ")", "{", "return", "function", "(", ")", "{", "if", "(", "arguments", ".", "length", ")", "{", "elem", ".", "classList", "[", "arguments", "[", "0", "]", "?", "\"add\"", ":", "\"remove\"", "]", "(", "className", ")", ";", "}", "else", "{", "return", "elem", ".", "classList", ".", "has", "(", "className", ")", ";", "}", "}", "}" ]
Create function bound to DOM class. Class will be enabled when function is called with truthy value and disabled when called with falsey value. When called without an argument, the function will return a boolean indicating if the class is set. @param {Element} elem @param {string} className @returns {function}
[ "Create", "function", "bound", "to", "DOM", "class", ".", "Class", "will", "be", "enabled", "when", "function", "is", "called", "with", "truthy", "value", "and", "disabled", "when", "called", "with", "falsey", "value", ".", "When", "called", "without", "an", "argument", "the", "function", "will", "return", "a", "boolean", "indicating", "if", "the", "class", "is", "set", "." ]
1ab36fd6aa7a6bc385e43ba2dbe5b36d5770f658
https://github.com/richRemer/twixt-class/blob/1ab36fd6aa7a6bc385e43ba2dbe5b36d5770f658/class.js#L10-L22
train
tamtakoe/validators-constructor
src/validators-constructor.js
formatStr
function formatStr(str, values) { values = values || {}; if (typeof str !== 'string') { return str; } return str.replace(FORMAT_REGEXP, (m0, m1, m2) => (m1 === '%' ? "%{" + m2 + "}" : values[m2])); }
javascript
function formatStr(str, values) { values = values || {}; if (typeof str !== 'string') { return str; } return str.replace(FORMAT_REGEXP, (m0, m1, m2) => (m1 === '%' ? "%{" + m2 + "}" : values[m2])); }
[ "function", "formatStr", "(", "str", ",", "values", ")", "{", "values", "=", "values", "||", "{", "}", ";", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "return", "str", ";", "}", "return", "str", ".", "replace", "(", "FORMAT_REGEXP", ",", "(", "m0", ",", "m1", ",", "m2", ")", "=>", "(", "m1", "===", "'%'", "?", "\"%{\"", "+", "m2", "+", "\"}\"", ":", "values", "[", "m2", "]", ")", ")", ";", "}" ]
Format string with patterns @param {String} str ("I'm %{age} years old") @param {Object} [values] ({age: 21}) @returns {String} formatted string ("I'm 21 years old")
[ "Format", "string", "with", "patterns" ]
4fa201d6c58da7232633c6b1820dd9d81cd13432
https://github.com/tamtakoe/validators-constructor/blob/4fa201d6c58da7232633c6b1820dd9d81cd13432/src/validators-constructor.js#L117-L125
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( keyCode, strokesPerSnapshotExceeded ) { var keyGroup = UndoManager.getKeyGroup( keyCode ), // Count of keystrokes in current a row. // Note if strokesPerSnapshotExceeded will be exceeded, it'll be restarted. strokesRecorded = this.strokesRecorded[ keyGroup ] + 1; strokesPerSnapshotExceeded = ( strokesPerSnapshotExceeded || strokesRecorded >= this.strokesLimit ); if ( !this.typing ) onTypingStart( this ); if ( strokesPerSnapshotExceeded ) { // Reset the count of strokes, so it'll be later assigned to this.strokesRecorded. strokesRecorded = 0; this.editor.fire( 'saveSnapshot' ); } else { // Fire change event. this.editor.fire( 'change' ); } // Store recorded strokes count. this.strokesRecorded[ keyGroup ] = strokesRecorded; // This prop will tell in next itaration what kind of group was processed previously. this.previousKeyGroup = keyGroup; }
javascript
function( keyCode, strokesPerSnapshotExceeded ) { var keyGroup = UndoManager.getKeyGroup( keyCode ), // Count of keystrokes in current a row. // Note if strokesPerSnapshotExceeded will be exceeded, it'll be restarted. strokesRecorded = this.strokesRecorded[ keyGroup ] + 1; strokesPerSnapshotExceeded = ( strokesPerSnapshotExceeded || strokesRecorded >= this.strokesLimit ); if ( !this.typing ) onTypingStart( this ); if ( strokesPerSnapshotExceeded ) { // Reset the count of strokes, so it'll be later assigned to this.strokesRecorded. strokesRecorded = 0; this.editor.fire( 'saveSnapshot' ); } else { // Fire change event. this.editor.fire( 'change' ); } // Store recorded strokes count. this.strokesRecorded[ keyGroup ] = strokesRecorded; // This prop will tell in next itaration what kind of group was processed previously. this.previousKeyGroup = keyGroup; }
[ "function", "(", "keyCode", ",", "strokesPerSnapshotExceeded", ")", "{", "var", "keyGroup", "=", "UndoManager", ".", "getKeyGroup", "(", "keyCode", ")", ",", "strokesRecorded", "=", "this", ".", "strokesRecorded", "[", "keyGroup", "]", "+", "1", ";", "strokesPerSnapshotExceeded", "=", "(", "strokesPerSnapshotExceeded", "||", "strokesRecorded", ">=", "this", ".", "strokesLimit", ")", ";", "if", "(", "!", "this", ".", "typing", ")", "onTypingStart", "(", "this", ")", ";", "if", "(", "strokesPerSnapshotExceeded", ")", "{", "strokesRecorded", "=", "0", ";", "this", ".", "editor", ".", "fire", "(", "'saveSnapshot'", ")", ";", "}", "else", "{", "this", ".", "editor", ".", "fire", "(", "'change'", ")", ";", "}", "this", ".", "strokesRecorded", "[", "keyGroup", "]", "=", "strokesRecorded", ";", "this", ".", "previousKeyGroup", "=", "keyGroup", ";", "}" ]
Handles keystroke support for the undo manager. It is called on `keyup` event for keystrokes that can change the editor content. @param {Number} keyCode The key code. @param {Boolean} [strokesPerSnapshotExceeded] When set to `true`, the method will behave as if the strokes limit was exceeded regardless of the {@link #strokesRecorded} value.
[ "Handles", "keystroke", "support", "for", "the", "undo", "manager", ".", "It", "is", "called", "on", "keyup", "event", "for", "keystrokes", "that", "can", "change", "the", "editor", "content", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L258-L284
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function() { // Stack for all the undo and redo snapshots, they're always created/removed // in consistency. this.snapshots = []; // Current snapshot history index. this.index = -1; this.currentImage = null; this.hasUndo = false; this.hasRedo = false; this.locked = null; this.resetType(); }
javascript
function() { // Stack for all the undo and redo snapshots, they're always created/removed // in consistency. this.snapshots = []; // Current snapshot history index. this.index = -1; this.currentImage = null; this.hasUndo = false; this.hasRedo = false; this.locked = null; this.resetType(); }
[ "function", "(", ")", "{", "this", ".", "snapshots", "=", "[", "]", ";", "this", ".", "index", "=", "-", "1", ";", "this", ".", "currentImage", "=", "null", ";", "this", ".", "hasUndo", "=", "false", ";", "this", ".", "hasRedo", "=", "false", ";", "this", ".", "locked", "=", "null", ";", "this", ".", "resetType", "(", ")", ";", "}" ]
Resets the undo stack.
[ "Resets", "the", "undo", "stack", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L300-L315
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( onContentOnly, image, autoFireChange ) { var editor = this.editor; // Do not change snapshots stack when locked, editor is not ready, // editable is not ready or when editor is in mode difference than 'wysiwyg'. if ( this.locked || editor.status != 'ready' || editor.mode != 'wysiwyg' ) return false; var editable = editor.editable(); if ( !editable || editable.status != 'ready' ) return false; var snapshots = this.snapshots; // Get a content image. if ( !image ) image = new Image( editor ); // Do nothing if it was not possible to retrieve an image. if ( image.contents === false ) return false; // Check if this is a duplicate. In such case, do nothing. if ( this.currentImage ) { if ( image.equalsContent( this.currentImage ) ) { if ( onContentOnly ) return false; if ( image.equalsSelection( this.currentImage ) ) return false; } else if ( autoFireChange !== false ) { editor.fire( 'change' ); } } // Drop future snapshots. snapshots.splice( this.index + 1, snapshots.length - this.index - 1 ); // If we have reached the limit, remove the oldest one. if ( snapshots.length == this.limit ) snapshots.shift(); // Add the new image, updating the current index. this.index = snapshots.push( image ) - 1; this.currentImage = image; if ( autoFireChange !== false ) this.refreshState(); return true; }
javascript
function( onContentOnly, image, autoFireChange ) { var editor = this.editor; // Do not change snapshots stack when locked, editor is not ready, // editable is not ready or when editor is in mode difference than 'wysiwyg'. if ( this.locked || editor.status != 'ready' || editor.mode != 'wysiwyg' ) return false; var editable = editor.editable(); if ( !editable || editable.status != 'ready' ) return false; var snapshots = this.snapshots; // Get a content image. if ( !image ) image = new Image( editor ); // Do nothing if it was not possible to retrieve an image. if ( image.contents === false ) return false; // Check if this is a duplicate. In such case, do nothing. if ( this.currentImage ) { if ( image.equalsContent( this.currentImage ) ) { if ( onContentOnly ) return false; if ( image.equalsSelection( this.currentImage ) ) return false; } else if ( autoFireChange !== false ) { editor.fire( 'change' ); } } // Drop future snapshots. snapshots.splice( this.index + 1, snapshots.length - this.index - 1 ); // If we have reached the limit, remove the oldest one. if ( snapshots.length == this.limit ) snapshots.shift(); // Add the new image, updating the current index. this.index = snapshots.push( image ) - 1; this.currentImage = image; if ( autoFireChange !== false ) this.refreshState(); return true; }
[ "function", "(", "onContentOnly", ",", "image", ",", "autoFireChange", ")", "{", "var", "editor", "=", "this", ".", "editor", ";", "if", "(", "this", ".", "locked", "||", "editor", ".", "status", "!=", "'ready'", "||", "editor", ".", "mode", "!=", "'wysiwyg'", ")", "return", "false", ";", "var", "editable", "=", "editor", ".", "editable", "(", ")", ";", "if", "(", "!", "editable", "||", "editable", ".", "status", "!=", "'ready'", ")", "return", "false", ";", "var", "snapshots", "=", "this", ".", "snapshots", ";", "if", "(", "!", "image", ")", "image", "=", "new", "Image", "(", "editor", ")", ";", "if", "(", "image", ".", "contents", "===", "false", ")", "return", "false", ";", "if", "(", "this", ".", "currentImage", ")", "{", "if", "(", "image", ".", "equalsContent", "(", "this", ".", "currentImage", ")", ")", "{", "if", "(", "onContentOnly", ")", "return", "false", ";", "if", "(", "image", ".", "equalsSelection", "(", "this", ".", "currentImage", ")", ")", "return", "false", ";", "}", "else", "if", "(", "autoFireChange", "!==", "false", ")", "{", "editor", ".", "fire", "(", "'change'", ")", ";", "}", "}", "snapshots", ".", "splice", "(", "this", ".", "index", "+", "1", ",", "snapshots", ".", "length", "-", "this", ".", "index", "-", "1", ")", ";", "if", "(", "snapshots", ".", "length", "==", "this", ".", "limit", ")", "snapshots", ".", "shift", "(", ")", ";", "this", ".", "index", "=", "snapshots", ".", "push", "(", "image", ")", "-", "1", ";", "this", ".", "currentImage", "=", "image", ";", "if", "(", "autoFireChange", "!==", "false", ")", "this", ".", "refreshState", "(", ")", ";", "return", "true", ";", "}" ]
Saves a snapshot of the document image for later retrieval. @param {Boolean} onContentOnly If set to `true`, the snapshot will be saved only if the content has changed. @param {CKEDITOR.plugins.undo.Image} image An optional image to save. If skipped, current editor will be used. @param {Boolean} autoFireChange If set to `false`, will not trigger the {@link CKEDITOR.editor#change} event to editor.
[ "Saves", "a", "snapshot", "of", "the", "document", "image", "for", "later", "retrieval", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L348-L397
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( isUndo ) { var snapshots = this.snapshots, currentImage = this.currentImage, image, i; if ( currentImage ) { if ( isUndo ) { for ( i = this.index - 1; i >= 0; i-- ) { image = snapshots[ i ]; if ( !currentImage.equalsContent( image ) ) { image.index = i; return image; } } } else { for ( i = this.index + 1; i < snapshots.length; i++ ) { image = snapshots[ i ]; if ( !currentImage.equalsContent( image ) ) { image.index = i; return image; } } } } return null; }
javascript
function( isUndo ) { var snapshots = this.snapshots, currentImage = this.currentImage, image, i; if ( currentImage ) { if ( isUndo ) { for ( i = this.index - 1; i >= 0; i-- ) { image = snapshots[ i ]; if ( !currentImage.equalsContent( image ) ) { image.index = i; return image; } } } else { for ( i = this.index + 1; i < snapshots.length; i++ ) { image = snapshots[ i ]; if ( !currentImage.equalsContent( image ) ) { image.index = i; return image; } } } } return null; }
[ "function", "(", "isUndo", ")", "{", "var", "snapshots", "=", "this", ".", "snapshots", ",", "currentImage", "=", "this", ".", "currentImage", ",", "image", ",", "i", ";", "if", "(", "currentImage", ")", "{", "if", "(", "isUndo", ")", "{", "for", "(", "i", "=", "this", ".", "index", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "image", "=", "snapshots", "[", "i", "]", ";", "if", "(", "!", "currentImage", ".", "equalsContent", "(", "image", ")", ")", "{", "image", ".", "index", "=", "i", ";", "return", "image", ";", "}", "}", "}", "else", "{", "for", "(", "i", "=", "this", ".", "index", "+", "1", ";", "i", "<", "snapshots", ".", "length", ";", "i", "++", ")", "{", "image", "=", "snapshots", "[", "i", "]", ";", "if", "(", "!", "currentImage", ".", "equalsContent", "(", "image", ")", ")", "{", "image", ".", "index", "=", "i", ";", "return", "image", ";", "}", "}", "}", "}", "return", "null", ";", "}" ]
Gets the closest available image. @param {Boolean} isUndo If `true`, it will return the previous image. @returns {CKEDITOR.plugins.undo.Image} Next image or `null`.
[ "Gets", "the", "closest", "available", "image", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L453-L479
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( newImage ) { // Do not change snapshots stack is locked. if ( this.locked ) return; if ( !newImage ) newImage = new Image( this.editor ); var i = this.index, snapshots = this.snapshots; // Find all previous snapshots made for the same content (which differ // only by selection) and replace all of them with the current image. while ( i > 0 && this.currentImage.equalsContent( snapshots[ i - 1 ] ) ) i -= 1; snapshots.splice( i, this.index - i + 1, newImage ); this.index = i; this.currentImage = newImage; }
javascript
function( newImage ) { // Do not change snapshots stack is locked. if ( this.locked ) return; if ( !newImage ) newImage = new Image( this.editor ); var i = this.index, snapshots = this.snapshots; // Find all previous snapshots made for the same content (which differ // only by selection) and replace all of them with the current image. while ( i > 0 && this.currentImage.equalsContent( snapshots[ i - 1 ] ) ) i -= 1; snapshots.splice( i, this.index - i + 1, newImage ); this.index = i; this.currentImage = newImage; }
[ "function", "(", "newImage", ")", "{", "if", "(", "this", ".", "locked", ")", "return", ";", "if", "(", "!", "newImage", ")", "newImage", "=", "new", "Image", "(", "this", ".", "editor", ")", ";", "var", "i", "=", "this", ".", "index", ",", "snapshots", "=", "this", ".", "snapshots", ";", "while", "(", "i", ">", "0", "&&", "this", ".", "currentImage", ".", "equalsContent", "(", "snapshots", "[", "i", "-", "1", "]", ")", ")", "i", "-=", "1", ";", "snapshots", ".", "splice", "(", "i", ",", "this", ".", "index", "-", "i", "+", "1", ",", "newImage", ")", ";", "this", ".", "index", "=", "i", ";", "this", ".", "currentImage", "=", "newImage", ";", "}" ]
Updates the last snapshot of the undo stack with the current editor content. @param {CKEDITOR.plugins.undo.Image} [newImage] The image which will replace the current one. If it is not set, it defaults to the image taken from the editor.
[ "Updates", "the", "last", "snapshot", "of", "the", "undo", "stack", "with", "the", "current", "editor", "content", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L540-L559
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function() { if ( this.locked ) { // Decrease level of lock and check if equals 0, what means that undoM is completely unlocked. if ( !--this.locked.level ) { var update = this.locked.update; this.locked = null; // forceUpdate was passed to lock(). if ( update === true ) this.update(); // update is instance of Image. else if ( update ) { var newImage = new Image( this.editor, true ); if ( !update.equalsContent( newImage ) ) this.update(); } } } }
javascript
function() { if ( this.locked ) { // Decrease level of lock and check if equals 0, what means that undoM is completely unlocked. if ( !--this.locked.level ) { var update = this.locked.update; this.locked = null; // forceUpdate was passed to lock(). if ( update === true ) this.update(); // update is instance of Image. else if ( update ) { var newImage = new Image( this.editor, true ); if ( !update.equalsContent( newImage ) ) this.update(); } } } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "locked", ")", "{", "if", "(", "!", "--", "this", ".", "locked", ".", "level", ")", "{", "var", "update", "=", "this", ".", "locked", ".", "update", ";", "this", ".", "locked", "=", "null", ";", "if", "(", "update", "===", "true", ")", "this", ".", "update", "(", ")", ";", "else", "if", "(", "update", ")", "{", "var", "newImage", "=", "new", "Image", "(", "this", ".", "editor", ",", "true", ")", ";", "if", "(", "!", "update", ".", "equalsContent", "(", "newImage", ")", ")", "this", ".", "update", "(", ")", ";", "}", "}", "}", "}" ]
Unlocks the snapshot stack and checks to amend the last snapshot. See {@link #lock} for more details. @since 4.0
[ "Unlocks", "the", "snapshot", "stack", "and", "checks", "to", "amend", "the", "last", "snapshot", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L650-L670
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
onTypingStart
function onTypingStart( undoManager ) { // It's safe to now indicate typing state. undoManager.typing = true; // Manually mark snapshot as available. undoManager.hasUndo = true; undoManager.hasRedo = false; undoManager.onChange(); }
javascript
function onTypingStart( undoManager ) { // It's safe to now indicate typing state. undoManager.typing = true; // Manually mark snapshot as available. undoManager.hasUndo = true; undoManager.hasRedo = false; undoManager.onChange(); }
[ "function", "onTypingStart", "(", "undoManager", ")", "{", "undoManager", ".", "typing", "=", "true", ";", "undoManager", ".", "hasUndo", "=", "true", ";", "undoManager", ".", "hasRedo", "=", "false", ";", "undoManager", ".", "onChange", "(", ")", ";", "}" ]
Helper method called when undoManager.typing val was changed to true.
[ "Helper", "method", "called", "when", "undoManager", ".", "typing", "val", "was", "changed", "to", "true", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L759-L768
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( evt ) { // Block undo/redo keystrokes when at the bottom/top of the undo stack (#11126 and #11677). if ( CKEDITOR.tools.indexOf( keystrokes, evt.data.getKeystroke() ) > -1 ) { evt.data.preventDefault(); return; } // Cleaning tab functional keys. this.keyEventsStack.cleanUp( evt ); var keyCode = evt.data.getKey(), undoManager = this.undoManager; // Gets last record for provided keyCode. If not found will create one. var last = this.keyEventsStack.getLast( keyCode ); if ( !last ) { this.keyEventsStack.push( keyCode ); } // We need to store an image which will be used in case of key group // change. this.lastKeydownImage = new Image( undoManager.editor ); if ( UndoManager.isNavigationKey( keyCode ) || this.undoManager.keyGroupChanged( keyCode ) ) { if ( undoManager.strokesRecorded[ 0 ] || undoManager.strokesRecorded[ 1 ] ) { // We already have image, so we'd like to reuse it. undoManager.save( false, this.lastKeydownImage ); undoManager.resetType(); } } }
javascript
function( evt ) { // Block undo/redo keystrokes when at the bottom/top of the undo stack (#11126 and #11677). if ( CKEDITOR.tools.indexOf( keystrokes, evt.data.getKeystroke() ) > -1 ) { evt.data.preventDefault(); return; } // Cleaning tab functional keys. this.keyEventsStack.cleanUp( evt ); var keyCode = evt.data.getKey(), undoManager = this.undoManager; // Gets last record for provided keyCode. If not found will create one. var last = this.keyEventsStack.getLast( keyCode ); if ( !last ) { this.keyEventsStack.push( keyCode ); } // We need to store an image which will be used in case of key group // change. this.lastKeydownImage = new Image( undoManager.editor ); if ( UndoManager.isNavigationKey( keyCode ) || this.undoManager.keyGroupChanged( keyCode ) ) { if ( undoManager.strokesRecorded[ 0 ] || undoManager.strokesRecorded[ 1 ] ) { // We already have image, so we'd like to reuse it. undoManager.save( false, this.lastKeydownImage ); undoManager.resetType(); } } }
[ "function", "(", "evt", ")", "{", "if", "(", "CKEDITOR", ".", "tools", ".", "indexOf", "(", "keystrokes", ",", "evt", ".", "data", ".", "getKeystroke", "(", ")", ")", ">", "-", "1", ")", "{", "evt", ".", "data", ".", "preventDefault", "(", ")", ";", "return", ";", "}", "this", ".", "keyEventsStack", ".", "cleanUp", "(", "evt", ")", ";", "var", "keyCode", "=", "evt", ".", "data", ".", "getKey", "(", ")", ",", "undoManager", "=", "this", ".", "undoManager", ";", "var", "last", "=", "this", ".", "keyEventsStack", ".", "getLast", "(", "keyCode", ")", ";", "if", "(", "!", "last", ")", "{", "this", ".", "keyEventsStack", ".", "push", "(", "keyCode", ")", ";", "}", "this", ".", "lastKeydownImage", "=", "new", "Image", "(", "undoManager", ".", "editor", ")", ";", "if", "(", "UndoManager", ".", "isNavigationKey", "(", "keyCode", ")", "||", "this", ".", "undoManager", ".", "keyGroupChanged", "(", "keyCode", ")", ")", "{", "if", "(", "undoManager", ".", "strokesRecorded", "[", "0", "]", "||", "undoManager", ".", "strokesRecorded", "[", "1", "]", ")", "{", "undoManager", ".", "save", "(", "false", ",", "this", ".", "lastKeydownImage", ")", ";", "undoManager", ".", "resetType", "(", ")", ";", "}", "}", "}" ]
The `keydown` event listener. @param {CKEDITOR.dom.event} evt
[ "The", "keydown", "event", "listener", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L923-L953
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function() { // Input event is ignored if paste/drop event were fired before. if ( this.ignoreInputEvent ) { // Reset flag - ignore only once. this.ignoreInputEvent = false; return; } var lastInput = this.keyEventsStack.getLast(); // Nothing in key events stack, but input event called. Interesting... // That's because on Android order of events is buggy and also keyCode is set to 0. if ( !lastInput ) { lastInput = this.keyEventsStack.push( 0 ); } // Increment inputs counter for provided key code. this.keyEventsStack.increment( lastInput.keyCode ); // Exceeded limit. if ( this.keyEventsStack.getTotalInputs() >= this.undoManager.strokesLimit ) { this.undoManager.type( lastInput.keyCode, true ); this.keyEventsStack.resetInputs(); } }
javascript
function() { // Input event is ignored if paste/drop event were fired before. if ( this.ignoreInputEvent ) { // Reset flag - ignore only once. this.ignoreInputEvent = false; return; } var lastInput = this.keyEventsStack.getLast(); // Nothing in key events stack, but input event called. Interesting... // That's because on Android order of events is buggy and also keyCode is set to 0. if ( !lastInput ) { lastInput = this.keyEventsStack.push( 0 ); } // Increment inputs counter for provided key code. this.keyEventsStack.increment( lastInput.keyCode ); // Exceeded limit. if ( this.keyEventsStack.getTotalInputs() >= this.undoManager.strokesLimit ) { this.undoManager.type( lastInput.keyCode, true ); this.keyEventsStack.resetInputs(); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "ignoreInputEvent", ")", "{", "this", ".", "ignoreInputEvent", "=", "false", ";", "return", ";", "}", "var", "lastInput", "=", "this", ".", "keyEventsStack", ".", "getLast", "(", ")", ";", "if", "(", "!", "lastInput", ")", "{", "lastInput", "=", "this", ".", "keyEventsStack", ".", "push", "(", "0", ")", ";", "}", "this", ".", "keyEventsStack", ".", "increment", "(", "lastInput", ".", "keyCode", ")", ";", "if", "(", "this", ".", "keyEventsStack", ".", "getTotalInputs", "(", ")", ">=", "this", ".", "undoManager", ".", "strokesLimit", ")", "{", "this", ".", "undoManager", ".", "type", "(", "lastInput", ".", "keyCode", ",", "true", ")", ";", "this", ".", "keyEventsStack", ".", "resetInputs", "(", ")", ";", "}", "}" ]
The `input` event listener.
[ "The", "input", "event", "listener", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L958-L981
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( evt ) { var undoManager = this.undoManager, keyCode = evt.data.getKey(), totalInputs = this.keyEventsStack.getTotalInputs(); // Remove record from stack for provided key code. this.keyEventsStack.remove( keyCode ); // Second part of the workaround for IEs functional keys bug. We need to check whether something has really // changed because we blindly mocked the keypress event. // Also we need to be aware that lastKeydownImage might not be available (#12327). if ( UndoManager.ieFunctionalKeysBug( keyCode ) && this.lastKeydownImage && this.lastKeydownImage.equalsContent( new Image( undoManager.editor, true ) ) ) { return; } if ( totalInputs > 0 ) { undoManager.type( keyCode ); } else if ( UndoManager.isNavigationKey( keyCode ) ) { // Note content snapshot has been checked in keydown. this.onNavigationKey( true ); } }
javascript
function( evt ) { var undoManager = this.undoManager, keyCode = evt.data.getKey(), totalInputs = this.keyEventsStack.getTotalInputs(); // Remove record from stack for provided key code. this.keyEventsStack.remove( keyCode ); // Second part of the workaround for IEs functional keys bug. We need to check whether something has really // changed because we blindly mocked the keypress event. // Also we need to be aware that lastKeydownImage might not be available (#12327). if ( UndoManager.ieFunctionalKeysBug( keyCode ) && this.lastKeydownImage && this.lastKeydownImage.equalsContent( new Image( undoManager.editor, true ) ) ) { return; } if ( totalInputs > 0 ) { undoManager.type( keyCode ); } else if ( UndoManager.isNavigationKey( keyCode ) ) { // Note content snapshot has been checked in keydown. this.onNavigationKey( true ); } }
[ "function", "(", "evt", ")", "{", "var", "undoManager", "=", "this", ".", "undoManager", ",", "keyCode", "=", "evt", ".", "data", ".", "getKey", "(", ")", ",", "totalInputs", "=", "this", ".", "keyEventsStack", ".", "getTotalInputs", "(", ")", ";", "this", ".", "keyEventsStack", ".", "remove", "(", "keyCode", ")", ";", "if", "(", "UndoManager", ".", "ieFunctionalKeysBug", "(", "keyCode", ")", "&&", "this", ".", "lastKeydownImage", "&&", "this", ".", "lastKeydownImage", ".", "equalsContent", "(", "new", "Image", "(", "undoManager", ".", "editor", ",", "true", ")", ")", ")", "{", "return", ";", "}", "if", "(", "totalInputs", ">", "0", ")", "{", "undoManager", ".", "type", "(", "keyCode", ")", ";", "}", "else", "if", "(", "UndoManager", ".", "isNavigationKey", "(", "keyCode", ")", ")", "{", "this", ".", "onNavigationKey", "(", "true", ")", ";", "}", "}" ]
The `keyup` event listener. @param {CKEDITOR.dom.event} evt
[ "The", "keyup", "event", "listener", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L988-L1010
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( skipContentCompare ) { var undoManager = this.undoManager; // We attempt to save content snapshot, if content didn't change, we'll // only amend selection. if ( skipContentCompare || !undoManager.save( true, null, false ) ) undoManager.updateSelection( new Image( undoManager.editor ) ); undoManager.resetType(); }
javascript
function( skipContentCompare ) { var undoManager = this.undoManager; // We attempt to save content snapshot, if content didn't change, we'll // only amend selection. if ( skipContentCompare || !undoManager.save( true, null, false ) ) undoManager.updateSelection( new Image( undoManager.editor ) ); undoManager.resetType(); }
[ "function", "(", "skipContentCompare", ")", "{", "var", "undoManager", "=", "this", ".", "undoManager", ";", "if", "(", "skipContentCompare", "||", "!", "undoManager", ".", "save", "(", "true", ",", "null", ",", "false", ")", ")", "undoManager", ".", "updateSelection", "(", "new", "Image", "(", "undoManager", ".", "editor", ")", ")", ";", "undoManager", ".", "resetType", "(", ")", ";", "}" ]
Method called for navigation change. At first it will check if current content does not differ from the last saved snapshot. * If the content is different, the method creates a standard, extra snapshot. * If the content is not different, the method will compare the selection, and will amend the last snapshot selection if it changed. @param {Boolean} skipContentCompare If set to `true`, it will not compare content, and only do a selection check.
[ "Method", "called", "for", "navigation", "change", ".", "At", "first", "it", "will", "check", "if", "current", "content", "does", "not", "differ", "from", "the", "last", "saved", "snapshot", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L1022-L1031
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function() { var editor = this.undoManager.editor, editable = editor.editable(), that = this; // We'll create a snapshot here (before DOM modification), because we'll // need unmodified content when we got keygroup toggled in keyup. editable.attachListener( editable, 'keydown', function( evt ) { that.onKeydown( evt ); // On IE keypress isn't fired for functional (backspace/delete) keys. // Let's pretend that something's changed. if ( UndoManager.ieFunctionalKeysBug( evt.data.getKey() ) ) { that.onInput(); } }, null, null, 999 ); // Only IE can't use input event, because it's not fired in contenteditable. editable.attachListener( editable, ( CKEDITOR.env.ie ? 'keypress' : 'input' ), that.onInput, that, null, 999 ); // Keyup executes main snapshot logic. editable.attachListener( editable, 'keyup', that.onKeyup, that, null, 999 ); // On paste and drop we need to ignore input event. // It would result with calling undoManager.type() on any following key. editable.attachListener( editable, 'paste', that.ignoreInputEventListener, that, null, 999 ); editable.attachListener( editable, 'drop', that.ignoreInputEventListener, that, null, 999 ); // Click should create a snapshot if needed, but shouldn't cause change event. // Don't pass onNavigationKey directly as a listener because it accepts one argument which // will conflict with evt passed to listener. // #12324 comment:4 editable.attachListener( editable.isInline() ? editable : editor.document.getDocumentElement(), 'click', function() { that.onNavigationKey(); }, null, null, 999 ); // When pressing `Tab` key while editable is focused, `keyup` event is not fired. // Which means that record for `tab` key stays in key events stack. // We assume that when editor is blurred `tab` key is already up. editable.attachListener( this.undoManager.editor, 'blur', function() { that.keyEventsStack.remove( 9 /*Tab*/ ); }, null, null, 999 ); }
javascript
function() { var editor = this.undoManager.editor, editable = editor.editable(), that = this; // We'll create a snapshot here (before DOM modification), because we'll // need unmodified content when we got keygroup toggled in keyup. editable.attachListener( editable, 'keydown', function( evt ) { that.onKeydown( evt ); // On IE keypress isn't fired for functional (backspace/delete) keys. // Let's pretend that something's changed. if ( UndoManager.ieFunctionalKeysBug( evt.data.getKey() ) ) { that.onInput(); } }, null, null, 999 ); // Only IE can't use input event, because it's not fired in contenteditable. editable.attachListener( editable, ( CKEDITOR.env.ie ? 'keypress' : 'input' ), that.onInput, that, null, 999 ); // Keyup executes main snapshot logic. editable.attachListener( editable, 'keyup', that.onKeyup, that, null, 999 ); // On paste and drop we need to ignore input event. // It would result with calling undoManager.type() on any following key. editable.attachListener( editable, 'paste', that.ignoreInputEventListener, that, null, 999 ); editable.attachListener( editable, 'drop', that.ignoreInputEventListener, that, null, 999 ); // Click should create a snapshot if needed, but shouldn't cause change event. // Don't pass onNavigationKey directly as a listener because it accepts one argument which // will conflict with evt passed to listener. // #12324 comment:4 editable.attachListener( editable.isInline() ? editable : editor.document.getDocumentElement(), 'click', function() { that.onNavigationKey(); }, null, null, 999 ); // When pressing `Tab` key while editable is focused, `keyup` event is not fired. // Which means that record for `tab` key stays in key events stack. // We assume that when editor is blurred `tab` key is already up. editable.attachListener( this.undoManager.editor, 'blur', function() { that.keyEventsStack.remove( 9 /*Tab*/ ); }, null, null, 999 ); }
[ "function", "(", ")", "{", "var", "editor", "=", "this", ".", "undoManager", ".", "editor", ",", "editable", "=", "editor", ".", "editable", "(", ")", ",", "that", "=", "this", ";", "editable", ".", "attachListener", "(", "editable", ",", "'keydown'", ",", "function", "(", "evt", ")", "{", "that", ".", "onKeydown", "(", "evt", ")", ";", "if", "(", "UndoManager", ".", "ieFunctionalKeysBug", "(", "evt", ".", "data", ".", "getKey", "(", ")", ")", ")", "{", "that", ".", "onInput", "(", ")", ";", "}", "}", ",", "null", ",", "null", ",", "999", ")", ";", "editable", ".", "attachListener", "(", "editable", ",", "(", "CKEDITOR", ".", "env", ".", "ie", "?", "'keypress'", ":", "'input'", ")", ",", "that", ".", "onInput", ",", "that", ",", "null", ",", "999", ")", ";", "editable", ".", "attachListener", "(", "editable", ",", "'keyup'", ",", "that", ".", "onKeyup", ",", "that", ",", "null", ",", "999", ")", ";", "editable", ".", "attachListener", "(", "editable", ",", "'paste'", ",", "that", ".", "ignoreInputEventListener", ",", "that", ",", "null", ",", "999", ")", ";", "editable", ".", "attachListener", "(", "editable", ",", "'drop'", ",", "that", ".", "ignoreInputEventListener", ",", "that", ",", "null", ",", "999", ")", ";", "editable", ".", "attachListener", "(", "editable", ".", "isInline", "(", ")", "?", "editable", ":", "editor", ".", "document", ".", "getDocumentElement", "(", ")", ",", "'click'", ",", "function", "(", ")", "{", "that", ".", "onNavigationKey", "(", ")", ";", "}", ",", "null", ",", "null", ",", "999", ")", ";", "editable", ".", "attachListener", "(", "this", ".", "undoManager", ".", "editor", ",", "'blur'", ",", "function", "(", ")", "{", "that", ".", "keyEventsStack", ".", "remove", "(", "9", ")", ";", "}", ",", "null", ",", "null", ",", "999", ")", ";", "}" ]
Attaches editable listeners required to provide the undo functionality.
[ "Attaches", "editable", "listeners", "required", "to", "provide", "the", "undo", "functionality", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L1043-L1085
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( keyCode ) { if ( typeof keyCode != 'number' ) { return this.stack.length - 1; // Last index or -1. } else { var i = this.stack.length; while ( i-- ) { if ( this.stack[ i ].keyCode == keyCode ) { return i; } } return -1; } }
javascript
function( keyCode ) { if ( typeof keyCode != 'number' ) { return this.stack.length - 1; // Last index or -1. } else { var i = this.stack.length; while ( i-- ) { if ( this.stack[ i ].keyCode == keyCode ) { return i; } } return -1; } }
[ "function", "(", "keyCode", ")", "{", "if", "(", "typeof", "keyCode", "!=", "'number'", ")", "{", "return", "this", ".", "stack", ".", "length", "-", "1", ";", "}", "else", "{", "var", "i", "=", "this", ".", "stack", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "this", ".", "stack", "[", "i", "]", ".", "keyCode", "==", "keyCode", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}", "}" ]
Returns the index of the last registered `keyCode` in the stack. If no `keyCode` is provided, then the function will return the index of the last item. If an item is not found, it will return `-1`. @param {Number} [keyCode] @returns {Number}
[ "Returns", "the", "index", "of", "the", "last", "registered", "keyCode", "in", "the", "stack", ".", "If", "no", "keyCode", "is", "provided", "then", "the", "function", "will", "return", "the", "index", "of", "the", "last", "item", ".", "If", "an", "item", "is", "not", "found", "it", "will", "return", "-", "1", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L1124-L1136
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function( keyCode ) { if ( typeof keyCode == 'number' ) { var last = this.getLast( keyCode ); if ( !last ) { // %REMOVE_LINE% throw new Error( 'Trying to reset inputs count, but could not found by keyCode: ' + keyCode + '.' ); // %REMOVE_LINE% } // %REMOVE_LINE% last.inputs = 0; } else { var i = this.stack.length; while ( i-- ) { this.stack[ i ].inputs = 0; } } }
javascript
function( keyCode ) { if ( typeof keyCode == 'number' ) { var last = this.getLast( keyCode ); if ( !last ) { // %REMOVE_LINE% throw new Error( 'Trying to reset inputs count, but could not found by keyCode: ' + keyCode + '.' ); // %REMOVE_LINE% } // %REMOVE_LINE% last.inputs = 0; } else { var i = this.stack.length; while ( i-- ) { this.stack[ i ].inputs = 0; } } }
[ "function", "(", "keyCode", ")", "{", "if", "(", "typeof", "keyCode", "==", "'number'", ")", "{", "var", "last", "=", "this", ".", "getLast", "(", "keyCode", ")", ";", "if", "(", "!", "last", ")", "{", "throw", "new", "Error", "(", "'Trying to reset inputs count, but could not found by keyCode: '", "+", "keyCode", "+", "'.'", ")", ";", "}", "last", ".", "inputs", "=", "0", ";", "}", "else", "{", "var", "i", "=", "this", ".", "stack", ".", "length", ";", "while", "(", "i", "--", ")", "{", "this", ".", "stack", "[", "i", "]", ".", "inputs", "=", "0", ";", "}", "}", "}" ]
Resets the `inputs` value to `0` for a given `keyCode` or in entire stack if a `keyCode` is not specified. @param {Number} [keyCode]
[ "Resets", "the", "inputs", "value", "to", "0", "for", "a", "given", "keyCode", "or", "in", "entire", "stack", "if", "a", "keyCode", "is", "not", "specified", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L1187-L1202
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/undo/plugin.js
function() { var i = this.stack.length, total = 0; while ( i-- ) { total += this.stack[ i ].inputs; } return total; }
javascript
function() { var i = this.stack.length, total = 0; while ( i-- ) { total += this.stack[ i ].inputs; } return total; }
[ "function", "(", ")", "{", "var", "i", "=", "this", ".", "stack", ".", "length", ",", "total", "=", "0", ";", "while", "(", "i", "--", ")", "{", "total", "+=", "this", ".", "stack", "[", "i", "]", ".", "inputs", ";", "}", "return", "total", ";", "}" ]
Sums up inputs number for each key code and returns it. @returns {Number}
[ "Sums", "up", "inputs", "number", "for", "each", "key", "code", "and", "returns", "it", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/undo/plugin.js#L1209-L1217
train
skerit/alchemy-styleboost
assets/scripts/medium-insert/insert-plugin.js
function () { $.fn.mediumInsert.settings.enabled = false; $.fn.mediumInsert.insert.$el.find('.mediumInsert-buttons').addClass('hide'); }
javascript
function () { $.fn.mediumInsert.settings.enabled = false; $.fn.mediumInsert.insert.$el.find('.mediumInsert-buttons').addClass('hide'); }
[ "function", "(", ")", "{", "$", ".", "fn", ".", "mediumInsert", ".", "settings", ".", "enabled", "=", "false", ";", "$", ".", "fn", ".", "mediumInsert", ".", "insert", ".", "$el", ".", "find", "(", "'.mediumInsert-buttons'", ")", ".", "addClass", "(", "'hide'", ")", ";", "}" ]
Disable the plugin @return {void}
[ "Disable", "the", "plugin" ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/assets/scripts/medium-insert/insert-plugin.js#L211-L215
train
skerit/alchemy-styleboost
assets/scripts/medium-insert/insert-plugin.js
function () { $.fn.mediumInsert.settings.enabled = true; $.fn.mediumInsert.insert.$el.find('.mediumInsert-buttons').removeClass('hide'); }
javascript
function () { $.fn.mediumInsert.settings.enabled = true; $.fn.mediumInsert.insert.$el.find('.mediumInsert-buttons').removeClass('hide'); }
[ "function", "(", ")", "{", "$", ".", "fn", ".", "mediumInsert", ".", "settings", ".", "enabled", "=", "true", ";", "$", ".", "fn", ".", "mediumInsert", ".", "insert", ".", "$el", ".", "find", "(", "'.mediumInsert-buttons'", ")", ".", "removeClass", "(", "'hide'", ")", ";", "}" ]
Enable the plugin @return {void}
[ "Enable", "the", "plugin" ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/assets/scripts/medium-insert/insert-plugin.js#L223-L227
train
skerit/alchemy-styleboost
assets/scripts/medium-insert/insert-plugin.js
function (addon) { var editor = $.fn.mediumInsert.settings.editor, buttonLabels = (editor && editor.options) ? editor.options.buttonLabels : ''; var buttons; if($.fn.mediumInsert.settings.enabled) { buttons = '<div class="mediumInsert-buttons">'+ '<a class="mediumInsert-buttonsShow">+</a>'+ '<ul class="mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active">'; } else { buttons = '<div class="mediumInsert-buttons hide">'+ '<a class="mediumInsert-buttonsShow">+</a>'+ '<ul class="mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active">'; } if (Object.keys($.fn.mediumInsert.settings.addons).length === 0) { return false; } if (typeof addon === 'undefined') { $.each($.fn.mediumInsert.settings.addons, function (i) { buttons += '<li>' + addons[i].insertButton(buttonLabels) + '</li>'; }); } else { buttons += '<li>' + addons[addon].insertButton(buttonLabels) + '</li>'; } buttons += '</ul></div>'; return buttons; }
javascript
function (addon) { var editor = $.fn.mediumInsert.settings.editor, buttonLabels = (editor && editor.options) ? editor.options.buttonLabels : ''; var buttons; if($.fn.mediumInsert.settings.enabled) { buttons = '<div class="mediumInsert-buttons">'+ '<a class="mediumInsert-buttonsShow">+</a>'+ '<ul class="mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active">'; } else { buttons = '<div class="mediumInsert-buttons hide">'+ '<a class="mediumInsert-buttonsShow">+</a>'+ '<ul class="mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active">'; } if (Object.keys($.fn.mediumInsert.settings.addons).length === 0) { return false; } if (typeof addon === 'undefined') { $.each($.fn.mediumInsert.settings.addons, function (i) { buttons += '<li>' + addons[i].insertButton(buttonLabels) + '</li>'; }); } else { buttons += '<li>' + addons[addon].insertButton(buttonLabels) + '</li>'; } buttons += '</ul></div>'; return buttons; }
[ "function", "(", "addon", ")", "{", "var", "editor", "=", "$", ".", "fn", ".", "mediumInsert", ".", "settings", ".", "editor", ",", "buttonLabels", "=", "(", "editor", "&&", "editor", ".", "options", ")", "?", "editor", ".", "options", ".", "buttonLabels", ":", "''", ";", "var", "buttons", ";", "if", "(", "$", ".", "fn", ".", "mediumInsert", ".", "settings", ".", "enabled", ")", "{", "buttons", "=", "'<div class=\"mediumInsert-buttons\">'", "+", "'<a class=\"mediumInsert-buttonsShow\">+</a>'", "+", "'<ul class=\"mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active\">'", ";", "}", "else", "{", "buttons", "=", "'<div class=\"mediumInsert-buttons hide\">'", "+", "'<a class=\"mediumInsert-buttonsShow\">+</a>'", "+", "'<ul class=\"mediumInsert-buttonsOptions medium-editor-toolbar medium-editor-toolbar-active\">'", ";", "}", "if", "(", "Object", ".", "keys", "(", "$", ".", "fn", ".", "mediumInsert", ".", "settings", ".", "addons", ")", ".", "length", "===", "0", ")", "{", "return", "false", ";", "}", "if", "(", "typeof", "addon", "===", "'undefined'", ")", "{", "$", ".", "each", "(", "$", ".", "fn", ".", "mediumInsert", ".", "settings", ".", "addons", ",", "function", "(", "i", ")", "{", "buttons", "+=", "'<li>'", "+", "addons", "[", "i", "]", ".", "insertButton", "(", "buttonLabels", ")", "+", "'</li>'", ";", "}", ")", ";", "}", "else", "{", "buttons", "+=", "'<li>'", "+", "addons", "[", "addon", "]", ".", "insertButton", "(", "buttonLabels", ")", "+", "'</li>'", ";", "}", "buttons", "+=", "'</ul></div>'", ";", "return", "buttons", ";", "}" ]
Return insert buttons optionally filtered by addon name @param {string} addon Addon name of addon to display only @return {void}
[ "Return", "insert", "buttons", "optionally", "filtered", "by", "addon", "name" ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/assets/scripts/medium-insert/insert-plugin.js#L253-L283
train
mrfishie/starmap
lib/modelItem.js
update
function update(item, model, data, funcParams) { var working = []; var definedByData = []; _.forEach(data, function(value, key) { if (_.isFunction(value)) { working.push(Promise.resolve(value()).then(function(val) { item[key] = val; })); } else item[key] = value; definedByData.push(value); }); _.forEach(model.itemDef, function(value, key) { if (value && value.__precalc) { var func = value.__precalc, previousVal = data[key]; working.push(Promise.resolve(func.call(item, previousVal, funcParams || {})).then(function(val) { item[key] = (val && val._stWrapped) ? val.val : val; })); } // if the property has not been set from the itemDef yet. This allows item def properties to be changed else if (!_.has(item, key) || definedByData.indexOf(key) !== -1) item[key] = value; }); return Promise.all(working); }
javascript
function update(item, model, data, funcParams) { var working = []; var definedByData = []; _.forEach(data, function(value, key) { if (_.isFunction(value)) { working.push(Promise.resolve(value()).then(function(val) { item[key] = val; })); } else item[key] = value; definedByData.push(value); }); _.forEach(model.itemDef, function(value, key) { if (value && value.__precalc) { var func = value.__precalc, previousVal = data[key]; working.push(Promise.resolve(func.call(item, previousVal, funcParams || {})).then(function(val) { item[key] = (val && val._stWrapped) ? val.val : val; })); } // if the property has not been set from the itemDef yet. This allows item def properties to be changed else if (!_.has(item, key) || definedByData.indexOf(key) !== -1) item[key] = value; }); return Promise.all(working); }
[ "function", "update", "(", "item", ",", "model", ",", "data", ",", "funcParams", ")", "{", "var", "working", "=", "[", "]", ";", "var", "definedByData", "=", "[", "]", ";", "_", ".", "forEach", "(", "data", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "_", ".", "isFunction", "(", "value", ")", ")", "{", "working", ".", "push", "(", "Promise", ".", "resolve", "(", "value", "(", ")", ")", ".", "then", "(", "function", "(", "val", ")", "{", "item", "[", "key", "]", "=", "val", ";", "}", ")", ")", ";", "}", "else", "item", "[", "key", "]", "=", "value", ";", "definedByData", ".", "push", "(", "value", ")", ";", "}", ")", ";", "_", ".", "forEach", "(", "model", ".", "itemDef", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "value", "&&", "value", ".", "__precalc", ")", "{", "var", "func", "=", "value", ".", "__precalc", ",", "previousVal", "=", "data", "[", "key", "]", ";", "working", ".", "push", "(", "Promise", ".", "resolve", "(", "func", ".", "call", "(", "item", ",", "previousVal", ",", "funcParams", "||", "{", "}", ")", ")", ".", "then", "(", "function", "(", "val", ")", "{", "item", "[", "key", "]", "=", "(", "val", "&&", "val", ".", "_stWrapped", ")", "?", "val", ".", "val", ":", "val", ";", "}", ")", ")", ";", "}", "else", "if", "(", "!", "_", ".", "has", "(", "item", ",", "key", ")", "||", "definedByData", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "item", "[", "key", "]", "=", "value", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "working", ")", ";", "}" ]
Updates the model to represent the given data @param {object} item @param {Model} model @param {object} data the data to add to the model @param {object?} funcParams parameters to pass to any precalc functions @returns {Promise}
[ "Updates", "the", "model", "to", "represent", "the", "given", "data" ]
0d2637e7863d65c165abf63766605e6a643d2580
https://github.com/mrfishie/starmap/blob/0d2637e7863d65c165abf63766605e6a643d2580/lib/modelItem.js#L14-L38
train
mrfishie/starmap
lib/modelItem.js
serverProperties
function serverProperties(item, model, props) { var result = {}; var toRefresh = []; _.forEach(props || item, function(val, key) { if (val == null) return; if (val._isModelItem) { result[key] = val.id; toRefresh.push(val); } else if (_.isArray(val)) { result[key] = _.map(val, function(item) { if (item._isModelItem) { toRefresh.push(item); return item.id; } return item; }); } else if (_.has(model.itemDef, key)) { if (_.has(model.itemDef[key], '__connection')) result[key] = val; } else result[key] = val; }); return { properties: result, refresh: toRefresh }; }
javascript
function serverProperties(item, model, props) { var result = {}; var toRefresh = []; _.forEach(props || item, function(val, key) { if (val == null) return; if (val._isModelItem) { result[key] = val.id; toRefresh.push(val); } else if (_.isArray(val)) { result[key] = _.map(val, function(item) { if (item._isModelItem) { toRefresh.push(item); return item.id; } return item; }); } else if (_.has(model.itemDef, key)) { if (_.has(model.itemDef[key], '__connection')) result[key] = val; } else result[key] = val; }); return { properties: result, refresh: toRefresh }; }
[ "function", "serverProperties", "(", "item", ",", "model", ",", "props", ")", "{", "var", "result", "=", "{", "}", ";", "var", "toRefresh", "=", "[", "]", ";", "_", ".", "forEach", "(", "props", "||", "item", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "val", "==", "null", ")", "return", ";", "if", "(", "val", ".", "_isModelItem", ")", "{", "result", "[", "key", "]", "=", "val", ".", "id", ";", "toRefresh", ".", "push", "(", "val", ")", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "val", ")", ")", "{", "result", "[", "key", "]", "=", "_", ".", "map", "(", "val", ",", "function", "(", "item", ")", "{", "if", "(", "item", ".", "_isModelItem", ")", "{", "toRefresh", ".", "push", "(", "item", ")", ";", "return", "item", ".", "id", ";", "}", "return", "item", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "has", "(", "model", ".", "itemDef", ",", "key", ")", ")", "{", "if", "(", "_", ".", "has", "(", "model", ".", "itemDef", "[", "key", "]", ",", "'__connection'", ")", ")", "result", "[", "key", "]", "=", "val", ";", "}", "else", "result", "[", "key", "]", "=", "val", ";", "}", ")", ";", "return", "{", "properties", ":", "result", ",", "refresh", ":", "toRefresh", "}", ";", "}" ]
Gets properties to be synced with the server @param {object} item @param {Model} model @param {object?} props @returns {object}
[ "Gets", "properties", "to", "be", "synced", "with", "the", "server" ]
0d2637e7863d65c165abf63766605e6a643d2580
https://github.com/mrfishie/starmap/blob/0d2637e7863d65c165abf63766605e6a643d2580/lib/modelItem.js#L48-L74
train
mrfishie/starmap
lib/modelItem.js
create
function create(item, model, data) { var serverProps = serverProperties(item, model, data).properties; return utils.socketPut(model.io, model.url + '/create/', serverProps).then(function(response) { _.merge(serverProps, response); return update(item, model, serverProps); }).then(function() { // Refresh all items that were referenced - some of their properties might change return Promise.all(_.map(serverProps.refresh, function(item) { return item.refresh(); })); }); }
javascript
function create(item, model, data) { var serverProps = serverProperties(item, model, data).properties; return utils.socketPut(model.io, model.url + '/create/', serverProps).then(function(response) { _.merge(serverProps, response); return update(item, model, serverProps); }).then(function() { // Refresh all items that were referenced - some of their properties might change return Promise.all(_.map(serverProps.refresh, function(item) { return item.refresh(); })); }); }
[ "function", "create", "(", "item", ",", "model", ",", "data", ")", "{", "var", "serverProps", "=", "serverProperties", "(", "item", ",", "model", ",", "data", ")", ".", "properties", ";", "return", "utils", ".", "socketPut", "(", "model", ".", "io", ",", "model", ".", "url", "+", "'/create/'", ",", "serverProps", ")", ".", "then", "(", "function", "(", "response", ")", "{", "_", ".", "merge", "(", "serverProps", ",", "response", ")", ";", "return", "update", "(", "item", ",", "model", ",", "serverProps", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "Promise", ".", "all", "(", "_", ".", "map", "(", "serverProps", ".", "refresh", ",", "function", "(", "item", ")", "{", "return", "item", ".", "refresh", "(", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Creates the item on the server @param {object} item @param {Model} model @param {object?} data @returns {Promise}
[ "Creates", "the", "item", "on", "the", "server" ]
0d2637e7863d65c165abf63766605e6a643d2580
https://github.com/mrfishie/starmap/blob/0d2637e7863d65c165abf63766605e6a643d2580/lib/modelItem.js#L84-L95
train
mrfishie/starmap
lib/modelItem.js
modelItem
function modelItem(data, model) { var res = {}; utils.defineProperties(res, { _isModelItem: { value: true }, model: { value: model.value }, update: { value: function(data, sync) { if (sync == null) sync = true; return update(res, model, data).then(function() { if (!sync) return; return res.save(); }); } }, save: { value: function() { if (_.has(res, 'id')) { var props = serverProperties(res, model); return utils.socketPost(model.io, model.url + '/update/' + res.id, props.properties).then(function() { return Promise.all(_.map(props.refresh, function(item) { return item.refresh(); })); }); } return create(res, model); } }, refresh: { value: function() { if (!_.has(res, 'id')) return create(res, model); return utils.socketGet(model.io, model.url + '/' + res.id).then(function(data) { return update(res, model, data, { noRefresh: true }); }); } }, delete: { value: function() { model._removeItem(res); return utils.socketDelete(model.io, model.url, { id: res.id }); } }, matches: { value: function(query) { return utils.socketGet(model.io, model.url, query).then(function(r) { for (var i = 0; i < r.length; i++) { if (r[i].id === res.id) return true; } return false; }); } }, then: { value: function() { return res.ready.then.apply(res.ready, arguments); } }, catch: { value: function() { return res.ready.catch.apply(res.ready, arguments); } } }); res.ready = Promise.resolve(); update(res, model, data || {}); return res; }
javascript
function modelItem(data, model) { var res = {}; utils.defineProperties(res, { _isModelItem: { value: true }, model: { value: model.value }, update: { value: function(data, sync) { if (sync == null) sync = true; return update(res, model, data).then(function() { if (!sync) return; return res.save(); }); } }, save: { value: function() { if (_.has(res, 'id')) { var props = serverProperties(res, model); return utils.socketPost(model.io, model.url + '/update/' + res.id, props.properties).then(function() { return Promise.all(_.map(props.refresh, function(item) { return item.refresh(); })); }); } return create(res, model); } }, refresh: { value: function() { if (!_.has(res, 'id')) return create(res, model); return utils.socketGet(model.io, model.url + '/' + res.id).then(function(data) { return update(res, model, data, { noRefresh: true }); }); } }, delete: { value: function() { model._removeItem(res); return utils.socketDelete(model.io, model.url, { id: res.id }); } }, matches: { value: function(query) { return utils.socketGet(model.io, model.url, query).then(function(r) { for (var i = 0; i < r.length; i++) { if (r[i].id === res.id) return true; } return false; }); } }, then: { value: function() { return res.ready.then.apply(res.ready, arguments); } }, catch: { value: function() { return res.ready.catch.apply(res.ready, arguments); } } }); res.ready = Promise.resolve(); update(res, model, data || {}); return res; }
[ "function", "modelItem", "(", "data", ",", "model", ")", "{", "var", "res", "=", "{", "}", ";", "utils", ".", "defineProperties", "(", "res", ",", "{", "_isModelItem", ":", "{", "value", ":", "true", "}", ",", "model", ":", "{", "value", ":", "model", ".", "value", "}", ",", "update", ":", "{", "value", ":", "function", "(", "data", ",", "sync", ")", "{", "if", "(", "sync", "==", "null", ")", "sync", "=", "true", ";", "return", "update", "(", "res", ",", "model", ",", "data", ")", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "sync", ")", "return", ";", "return", "res", ".", "save", "(", ")", ";", "}", ")", ";", "}", "}", ",", "save", ":", "{", "value", ":", "function", "(", ")", "{", "if", "(", "_", ".", "has", "(", "res", ",", "'id'", ")", ")", "{", "var", "props", "=", "serverProperties", "(", "res", ",", "model", ")", ";", "return", "utils", ".", "socketPost", "(", "model", ".", "io", ",", "model", ".", "url", "+", "'/update/'", "+", "res", ".", "id", ",", "props", ".", "properties", ")", ".", "then", "(", "function", "(", ")", "{", "return", "Promise", ".", "all", "(", "_", ".", "map", "(", "props", ".", "refresh", ",", "function", "(", "item", ")", "{", "return", "item", ".", "refresh", "(", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}", "return", "create", "(", "res", ",", "model", ")", ";", "}", "}", ",", "refresh", ":", "{", "value", ":", "function", "(", ")", "{", "if", "(", "!", "_", ".", "has", "(", "res", ",", "'id'", ")", ")", "return", "create", "(", "res", ",", "model", ")", ";", "return", "utils", ".", "socketGet", "(", "model", ".", "io", ",", "model", ".", "url", "+", "'/'", "+", "res", ".", "id", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "update", "(", "res", ",", "model", ",", "data", ",", "{", "noRefresh", ":", "true", "}", ")", ";", "}", ")", ";", "}", "}", ",", "delete", ":", "{", "value", ":", "function", "(", ")", "{", "model", ".", "_removeItem", "(", "res", ")", ";", "return", "utils", ".", "socketDelete", "(", "model", ".", "io", ",", "model", ".", "url", ",", "{", "id", ":", "res", ".", "id", "}", ")", ";", "}", "}", ",", "matches", ":", "{", "value", ":", "function", "(", "query", ")", "{", "return", "utils", ".", "socketGet", "(", "model", ".", "io", ",", "model", ".", "url", ",", "query", ")", ".", "then", "(", "function", "(", "r", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "r", ".", "length", ";", "i", "++", ")", "{", "if", "(", "r", "[", "i", "]", ".", "id", "===", "res", ".", "id", ")", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "}", "}", ",", "then", ":", "{", "value", ":", "function", "(", ")", "{", "return", "res", ".", "ready", ".", "then", ".", "apply", "(", "res", ".", "ready", ",", "arguments", ")", ";", "}", "}", ",", "catch", ":", "{", "value", ":", "function", "(", ")", "{", "return", "res", ".", "ready", ".", "catch", ".", "apply", "(", "res", ".", "ready", ",", "arguments", ")", ";", "}", "}", "}", ")", ";", "res", ".", "ready", "=", "Promise", ".", "resolve", "(", ")", ";", "update", "(", "res", ",", "model", ",", "data", "||", "{", "}", ")", ";", "return", "res", ";", "}" ]
A single model item that is synced with the server @param {object} data @param {Model} model
[ "A", "single", "model", "item", "that", "is", "synced", "with", "the", "server" ]
0d2637e7863d65c165abf63766605e6a643d2580
https://github.com/mrfishie/starmap/blob/0d2637e7863d65c165abf63766605e6a643d2580/lib/modelItem.js#L103-L168
train
greggman/hft-sample-ui
src/hft/scripts/misc/cookies.js
function(name, opt_path) { var path = opt_path || "/"; /** * Sets the cookie * @param {string} value value for cookie * @param {number?} opt_days number of days until cookie * expires. Default = none */ this.set = function(value, opt_days) { if (value === undefined) { this.erase(); return; } // Cordova/Phonegap doesn't support cookies so use localStorage? if (window.hftSettings && window.hftSettings.inApp) { window.localStorage.setItem(name, value); return; } var expires = ""; opt_days = opt_days || 9999; var date = new Date(); date.setTime(Date.now() + Math.floor(opt_days * 24 * 60 * 60 * 1000)); // > 32bits. Don't use | 0 expires = "; expires=" + date.toGMTString(); var cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=" + path; document.cookie = cookie; }; /** * Gets the value of the cookie * @return {string?} value of cookie */ this.get = function() { // Cordova/Phonegap doesn't support cookies so use localStorage? if (window.hftSettings && window.hftSettings.inApp) { return window.localStorage.getItem(name); } var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; ++i) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return decodeURIComponent(c.substring(nameEQ.length, c.length)); } } }; /** * Erases the cookie. */ this.erase = function() { if (window.hftSettings && window.hftSettings.inApp) { return window.localStorage.removeItem(name); } document.cookie = this.set(" ", -1); }; }
javascript
function(name, opt_path) { var path = opt_path || "/"; /** * Sets the cookie * @param {string} value value for cookie * @param {number?} opt_days number of days until cookie * expires. Default = none */ this.set = function(value, opt_days) { if (value === undefined) { this.erase(); return; } // Cordova/Phonegap doesn't support cookies so use localStorage? if (window.hftSettings && window.hftSettings.inApp) { window.localStorage.setItem(name, value); return; } var expires = ""; opt_days = opt_days || 9999; var date = new Date(); date.setTime(Date.now() + Math.floor(opt_days * 24 * 60 * 60 * 1000)); // > 32bits. Don't use | 0 expires = "; expires=" + date.toGMTString(); var cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=" + path; document.cookie = cookie; }; /** * Gets the value of the cookie * @return {string?} value of cookie */ this.get = function() { // Cordova/Phonegap doesn't support cookies so use localStorage? if (window.hftSettings && window.hftSettings.inApp) { return window.localStorage.getItem(name); } var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; ++i) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return decodeURIComponent(c.substring(nameEQ.length, c.length)); } } }; /** * Erases the cookie. */ this.erase = function() { if (window.hftSettings && window.hftSettings.inApp) { return window.localStorage.removeItem(name); } document.cookie = this.set(" ", -1); }; }
[ "function", "(", "name", ",", "opt_path", ")", "{", "var", "path", "=", "opt_path", "||", "\"/\"", ";", "this", ".", "set", "=", "function", "(", "value", ",", "opt_days", ")", "{", "if", "(", "value", "===", "undefined", ")", "{", "this", ".", "erase", "(", ")", ";", "return", ";", "}", "if", "(", "window", ".", "hftSettings", "&&", "window", ".", "hftSettings", ".", "inApp", ")", "{", "window", ".", "localStorage", ".", "setItem", "(", "name", ",", "value", ")", ";", "return", ";", "}", "var", "expires", "=", "\"\"", ";", "opt_days", "=", "opt_days", "||", "9999", ";", "var", "date", "=", "new", "Date", "(", ")", ";", "date", ".", "setTime", "(", "Date", ".", "now", "(", ")", "+", "Math", ".", "floor", "(", "opt_days", "*", "24", "*", "60", "*", "60", "*", "1000", ")", ")", ";", "expires", "=", "\"; expires=\"", "+", "date", ".", "toGMTString", "(", ")", ";", "var", "cookie", "=", "encodeURIComponent", "(", "name", ")", "+", "\"=\"", "+", "encodeURIComponent", "(", "value", ")", "+", "expires", "+", "\"; path=\"", "+", "path", ";", "document", ".", "cookie", "=", "cookie", ";", "}", ";", "this", ".", "get", "=", "function", "(", ")", "{", "if", "(", "window", ".", "hftSettings", "&&", "window", ".", "hftSettings", ".", "inApp", ")", "{", "return", "window", ".", "localStorage", ".", "getItem", "(", "name", ")", ";", "}", "var", "nameEQ", "=", "encodeURIComponent", "(", "name", ")", "+", "\"=\"", ";", "var", "ca", "=", "document", ".", "cookie", ".", "split", "(", "';'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ca", ".", "length", ";", "++", "i", ")", "{", "var", "c", "=", "ca", "[", "i", "]", ";", "while", "(", "c", ".", "charAt", "(", "0", ")", "===", "' '", ")", "{", "c", "=", "c", ".", "substring", "(", "1", ",", "c", ".", "length", ")", ";", "}", "if", "(", "c", ".", "indexOf", "(", "nameEQ", ")", "===", "0", ")", "{", "return", "decodeURIComponent", "(", "c", ".", "substring", "(", "nameEQ", ".", "length", ",", "c", ".", "length", ")", ")", ";", "}", "}", "}", ";", "this", ".", "erase", "=", "function", "(", ")", "{", "if", "(", "window", ".", "hftSettings", "&&", "window", ".", "hftSettings", ".", "inApp", ")", "{", "return", "window", ".", "localStorage", ".", "removeItem", "(", "name", ")", ";", "}", "document", ".", "cookie", "=", "this", ".", "set", "(", "\" \"", ",", "-", "1", ")", ";", "}", ";", "}" ]
Represents a cookie. This is an object, that way you set the name just once so calling set or get you don't have to worry about getting the name wrong. @example var fooCookie = new Cookie("foo"); var value = fooCookie.get(); fooCookie.set(newValue); fooCookie.erase(); @constructor @alias Cookie @param {string} name of cookie @param {string?} opt_path path for cookie. Default "/"
[ "Represents", "a", "cookie", "." ]
b9e20afd5183db73522bcfae48225c87e01f68c0
https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/cookies.js#L54-L114
train
sax1johno/simple-logger
lib/simple_logger.js
SimpleLogger
function SimpleLogger() { /* This class is a singleton */ if (arguments.callee._singletonInstance) { return arguments.callee._singletonInstance; } arguments.callee._singletonInstance = this; EventEmitter.call(this); // First, some basic loglevels. These can be overridden by the developer if desired. this.LOGLEVELS = { 'fatal': 0, 'error': 100, 'warning': 200, 'debug': 300, 'info': 400, 'trace': 500 }; // defaults to debug. this.loglevel = 'debug'; this.getLogLevelValue = function() { return this.LOGLEVELS[this.loglevel]; }; this.log = function(level, message, fn) { var logNumber = this.LOGLEVELS[level]; if (logNumber <= this.getLogLevelValue()) { this.emit('log', level, message); this.emit(level, message); if (!_.isUndefined(fn) && !_.isNull(fn)) { fn(message); } } }; this.on('log', function(level, message) { console.log(level + ": " + message); }) }
javascript
function SimpleLogger() { /* This class is a singleton */ if (arguments.callee._singletonInstance) { return arguments.callee._singletonInstance; } arguments.callee._singletonInstance = this; EventEmitter.call(this); // First, some basic loglevels. These can be overridden by the developer if desired. this.LOGLEVELS = { 'fatal': 0, 'error': 100, 'warning': 200, 'debug': 300, 'info': 400, 'trace': 500 }; // defaults to debug. this.loglevel = 'debug'; this.getLogLevelValue = function() { return this.LOGLEVELS[this.loglevel]; }; this.log = function(level, message, fn) { var logNumber = this.LOGLEVELS[level]; if (logNumber <= this.getLogLevelValue()) { this.emit('log', level, message); this.emit(level, message); if (!_.isUndefined(fn) && !_.isNull(fn)) { fn(message); } } }; this.on('log', function(level, message) { console.log(level + ": " + message); }) }
[ "function", "SimpleLogger", "(", ")", "{", "if", "(", "arguments", ".", "callee", ".", "_singletonInstance", ")", "{", "return", "arguments", ".", "callee", ".", "_singletonInstance", ";", "}", "arguments", ".", "callee", ".", "_singletonInstance", "=", "this", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "LOGLEVELS", "=", "{", "'fatal'", ":", "0", ",", "'error'", ":", "100", ",", "'warning'", ":", "200", ",", "'debug'", ":", "300", ",", "'info'", ":", "400", ",", "'trace'", ":", "500", "}", ";", "this", ".", "loglevel", "=", "'debug'", ";", "this", ".", "getLogLevelValue", "=", "function", "(", ")", "{", "return", "this", ".", "LOGLEVELS", "[", "this", ".", "loglevel", "]", ";", "}", ";", "this", ".", "log", "=", "function", "(", "level", ",", "message", ",", "fn", ")", "{", "var", "logNumber", "=", "this", ".", "LOGLEVELS", "[", "level", "]", ";", "if", "(", "logNumber", "<=", "this", ".", "getLogLevelValue", "(", ")", ")", "{", "this", ".", "emit", "(", "'log'", ",", "level", ",", "message", ")", ";", "this", ".", "emit", "(", "level", ",", "message", ")", ";", "if", "(", "!", "_", ".", "isUndefined", "(", "fn", ")", "&&", "!", "_", ".", "isNull", "(", "fn", ")", ")", "{", "fn", "(", "message", ")", ";", "}", "}", "}", ";", "this", ".", "on", "(", "'log'", ",", "function", "(", "level", ",", "message", ")", "{", "console", ".", "log", "(", "level", "+", "\": \"", "+", "message", ")", ";", "}", ")", "}" ]
SimpleLogger is a basic logging utility that uses events to let developers manage logging facilities. By default, events are merely fired when the appropriate loglevels are encountered and provides a basic console logger that can be used by the developer. Logging functionality can be overridden by removing the listeners that are attached to this EventEmitter. By default, a catchall logging event called 'log' provides a console message with the loglevel and message. To disable the default catchall logger, remove the 'log' listener from this object using the following the following: MyLog.removeListener('log'); You can also register for the "log" event if you want to be notified when a log is fired.
[ "SimpleLogger", "is", "a", "basic", "logging", "utility", "that", "uses", "events", "to", "let", "developers", "manage", "logging", "facilities", ".", "By", "default", "events", "are", "merely", "fired", "when", "the", "appropriate", "loglevels", "are", "encountered", "and", "provides", "a", "basic", "console", "logger", "that", "can", "be", "used", "by", "the", "developer", ".", "Logging", "functionality", "can", "be", "overridden", "by", "removing", "the", "listeners", "that", "are", "attached", "to", "this", "EventEmitter", "." ]
e58f2f575198e165721f8fdd0457be3c74b0c4b7
https://github.com/sax1johno/simple-logger/blob/e58f2f575198e165721f8fdd0457be3c74b0c4b7/lib/simple_logger.js#L16-L56
train
gtriggiano/dnsmq-messagebus
src/Node.js
activate
function activate () { if (_active) return node _active = true debug('activated') if (!external) { _masterBroker.bind() _masterResolver.bind() } if (!node.isReady) _seekForMaster() return node }
javascript
function activate () { if (_active) return node _active = true debug('activated') if (!external) { _masterBroker.bind() _masterResolver.bind() } if (!node.isReady) _seekForMaster() return node }
[ "function", "activate", "(", ")", "{", "if", "(", "_active", ")", "return", "node", "_active", "=", "true", "debug", "(", "'activated'", ")", "if", "(", "!", "external", ")", "{", "_masterBroker", ".", "bind", "(", ")", "_masterResolver", ".", "bind", "(", ")", "}", "if", "(", "!", "node", ".", "isReady", ")", "_seekForMaster", "(", ")", "return", "node", "}" ]
Activates the node @return {object} node instance
[ "Activates", "the", "node" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/Node.js#L150-L161
train
gtriggiano/dnsmq-messagebus
src/Node.js
deactivate
function deactivate () { if (!_active || _deactivating) return node debug('deactivating') if (external) { _active = false _subConnection.disconnect() _pubConnection.disconnect() node.emit('deactivated') } else { _deactivating = true let ensuredMaster = Promise.resolve() const isMaster = _subConnection.master && _subConnection.master.name === _name if (isMaster) { debug(`I'm the master node. I will try to elect another master before disconnecting.`) let advertiseId = `zz-zzzzzzzz-${_id}` ensuredMaster = _masterResolver .resolve(advertiseId) .then(master => { debug(`successfully elected a new master: ${master.name}`) try { _masterBroker.signalNewMaster(master) } catch (e) { console.log(e) } }) .catch(() => { debug(`failed to elect a new master. Disconnecting anyway.`) }) } ensuredMaster .then(() => { _subConnection.disconnect() _pubConnection.disconnect() _masterResolver.unbind() let timeout = isMaster ? 1000 : 1 setTimeout(() => { debug('deactivated') node.emit('deactivated') _masterBroker.unbind() }, timeout) }) } return node }
javascript
function deactivate () { if (!_active || _deactivating) return node debug('deactivating') if (external) { _active = false _subConnection.disconnect() _pubConnection.disconnect() node.emit('deactivated') } else { _deactivating = true let ensuredMaster = Promise.resolve() const isMaster = _subConnection.master && _subConnection.master.name === _name if (isMaster) { debug(`I'm the master node. I will try to elect another master before disconnecting.`) let advertiseId = `zz-zzzzzzzz-${_id}` ensuredMaster = _masterResolver .resolve(advertiseId) .then(master => { debug(`successfully elected a new master: ${master.name}`) try { _masterBroker.signalNewMaster(master) } catch (e) { console.log(e) } }) .catch(() => { debug(`failed to elect a new master. Disconnecting anyway.`) }) } ensuredMaster .then(() => { _subConnection.disconnect() _pubConnection.disconnect() _masterResolver.unbind() let timeout = isMaster ? 1000 : 1 setTimeout(() => { debug('deactivated') node.emit('deactivated') _masterBroker.unbind() }, timeout) }) } return node }
[ "function", "deactivate", "(", ")", "{", "if", "(", "!", "_active", "||", "_deactivating", ")", "return", "node", "debug", "(", "'deactivating'", ")", "if", "(", "external", ")", "{", "_active", "=", "false", "_subConnection", ".", "disconnect", "(", ")", "_pubConnection", ".", "disconnect", "(", ")", "node", ".", "emit", "(", "'deactivated'", ")", "}", "else", "{", "_deactivating", "=", "true", "let", "ensuredMaster", "=", "Promise", ".", "resolve", "(", ")", "const", "isMaster", "=", "_subConnection", ".", "master", "&&", "_subConnection", ".", "master", ".", "name", "===", "_name", "if", "(", "isMaster", ")", "{", "debug", "(", "`", "`", ")", "let", "advertiseId", "=", "`", "${", "_id", "}", "`", "ensuredMaster", "=", "_masterResolver", ".", "resolve", "(", "advertiseId", ")", ".", "then", "(", "master", "=>", "{", "debug", "(", "`", "${", "master", ".", "name", "}", "`", ")", "try", "{", "_masterBroker", ".", "signalNewMaster", "(", "master", ")", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "e", ")", "}", "}", ")", ".", "catch", "(", "(", ")", "=>", "{", "debug", "(", "`", "`", ")", "}", ")", "}", "ensuredMaster", ".", "then", "(", "(", ")", "=>", "{", "_subConnection", ".", "disconnect", "(", ")", "_pubConnection", ".", "disconnect", "(", ")", "_masterResolver", ".", "unbind", "(", ")", "let", "timeout", "=", "isMaster", "?", "1000", ":", "1", "setTimeout", "(", "(", ")", "=>", "{", "debug", "(", "'deactivated'", ")", "node", ".", "emit", "(", "'deactivated'", ")", "_masterBroker", ".", "unbind", "(", ")", "}", ",", "timeout", ")", "}", ")", "}", "return", "node", "}" ]
Starts the node's deactivation routine @return {object} node instance
[ "Starts", "the", "node", "s", "deactivation", "routine" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/Node.js#L166-L215
train
gtriggiano/dnsmq-messagebus
src/Node.js
publish
function publish (channel, ...args) { if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`) if (~internalChannels.indexOf(channel)) { console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`) return node } if (!_pubConnection.connected) { console.warn(`${_debugStr} cannot publish on bus.`) return node } _pubConnection.publish(channel, ...args) return node }
javascript
function publish (channel, ...args) { if (!isString(channel)) throw new TypeError(`${_debugStr}: .publish(channel, [...args]) channel MUST be a string`) if (~internalChannels.indexOf(channel)) { console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot publish in it`) return node } if (!_pubConnection.connected) { console.warn(`${_debugStr} cannot publish on bus.`) return node } _pubConnection.publish(channel, ...args) return node }
[ "function", "publish", "(", "channel", ",", "...", "args", ")", "{", "if", "(", "!", "isString", "(", "channel", ")", ")", "throw", "new", "TypeError", "(", "`", "${", "_debugStr", "}", "`", ")", "if", "(", "~", "internalChannels", ".", "indexOf", "(", "channel", ")", ")", "{", "console", ".", "warn", "(", "`", "${", "_debugStr", "}", "${", "channel", "}", "`", ")", "return", "node", "}", "if", "(", "!", "_pubConnection", ".", "connected", ")", "{", "console", ".", "warn", "(", "`", "${", "_debugStr", "}", "`", ")", "return", "node", "}", "_pubConnection", ".", "publish", "(", "channel", ",", "...", "args", ")", "return", "node", "}" ]
Sends a message through the bus, published on a particular channel @param {string} channel @param {array} args @return {object} node instance
[ "Sends", "a", "message", "through", "the", "bus", "published", "on", "a", "particular", "channel" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/Node.js#L222-L234
train
gtriggiano/dnsmq-messagebus
src/Node.js
unsubscribe
function unsubscribe (channels) { if (!isArray(channels)) channels = [channels] if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`) channels.forEach(channel => { if (~internalChannels.indexOf(channel)) { console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`) return } _subConnection.unsubscribe([channel]) }) return node }
javascript
function unsubscribe (channels) { if (!isArray(channels)) channels = [channels] if (!every(channels, isString)) throw new TypeError(`${_debugStr}: .unsubscribe([channels]) channels must be represented by strings`) channels.forEach(channel => { if (~internalChannels.indexOf(channel)) { console.warn(`${_debugStr} channel '${channel}' is used internally and you cannot unsubscribe from it.`) return } _subConnection.unsubscribe([channel]) }) return node }
[ "function", "unsubscribe", "(", "channels", ")", "{", "if", "(", "!", "isArray", "(", "channels", ")", ")", "channels", "=", "[", "channels", "]", "if", "(", "!", "every", "(", "channels", ",", "isString", ")", ")", "throw", "new", "TypeError", "(", "`", "${", "_debugStr", "}", "`", ")", "channels", ".", "forEach", "(", "channel", "=>", "{", "if", "(", "~", "internalChannels", ".", "indexOf", "(", "channel", ")", ")", "{", "console", ".", "warn", "(", "`", "${", "_debugStr", "}", "${", "channel", "}", "`", ")", "return", "}", "_subConnection", ".", "unsubscribe", "(", "[", "channel", "]", ")", "}", ")", "return", "node", "}" ]
Unsubscribes the node from the provided channels @param {string|array<string>} channels @return {object} node instance
[ "Unsubscribes", "the", "node", "from", "the", "provided", "channels" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/Node.js#L258-L270
train
gtriggiano/dnsmq-messagebus
src/Node.js
_validateSettings
function _validateSettings (settings) { let { host, external, voteTimeout, electionPriority, coordinationPort } = settings if (!host || !isString(host)) throw new TypeError(ctorMessage('host is mandatory and should be a string.')) if (!isInteger(coordinationPort) || coordinationPort <= 0) throw new TypeError(ctorMessage('settings.coordinationPort should be a positive integer.')) if (!external) { if (!isInteger(voteTimeout) || voteTimeout <= 0) throw new TypeError(ctorMessage('settings.voteTimeout should be a positive integer.')) if (!isInteger(electionPriority) || electionPriority < 0 || electionPriority > 99) throw new TypeError(ctorMessage('settings.electionPriority should be an integer between 0 and 99.')) } }
javascript
function _validateSettings (settings) { let { host, external, voteTimeout, electionPriority, coordinationPort } = settings if (!host || !isString(host)) throw new TypeError(ctorMessage('host is mandatory and should be a string.')) if (!isInteger(coordinationPort) || coordinationPort <= 0) throw new TypeError(ctorMessage('settings.coordinationPort should be a positive integer.')) if (!external) { if (!isInteger(voteTimeout) || voteTimeout <= 0) throw new TypeError(ctorMessage('settings.voteTimeout should be a positive integer.')) if (!isInteger(electionPriority) || electionPriority < 0 || electionPriority > 99) throw new TypeError(ctorMessage('settings.electionPriority should be an integer between 0 and 99.')) } }
[ "function", "_validateSettings", "(", "settings", ")", "{", "let", "{", "host", ",", "external", ",", "voteTimeout", ",", "electionPriority", ",", "coordinationPort", "}", "=", "settings", "if", "(", "!", "host", "||", "!", "isString", "(", "host", ")", ")", "throw", "new", "TypeError", "(", "ctorMessage", "(", "'host is mandatory and should be a string.'", ")", ")", "if", "(", "!", "isInteger", "(", "coordinationPort", ")", "||", "coordinationPort", "<=", "0", ")", "throw", "new", "TypeError", "(", "ctorMessage", "(", "'settings.coordinationPort should be a positive integer.'", ")", ")", "if", "(", "!", "external", ")", "{", "if", "(", "!", "isInteger", "(", "voteTimeout", ")", "||", "voteTimeout", "<=", "0", ")", "throw", "new", "TypeError", "(", "ctorMessage", "(", "'settings.voteTimeout should be a positive integer.'", ")", ")", "if", "(", "!", "isInteger", "(", "electionPriority", ")", "||", "electionPriority", "<", "0", "||", "electionPriority", ">", "99", ")", "throw", "new", "TypeError", "(", "ctorMessage", "(", "'settings.electionPriority should be an integer between 0 and 99.'", ")", ")", "}", "}" ]
Validates a map of node settings @param {object} settings
[ "Validates", "a", "map", "of", "node", "settings" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/Node.js#L302-L319
train
kvnneff/deku-component-find-all
index.js
findAll
function findAll (tree, test) { var found = test(tree) ? [tree] : [] if (isNode(tree)) { if (tree.children.length > 0) { tree.children.forEach(function (child) { found = found.concat(findAll(child, test)) }) } } return found }
javascript
function findAll (tree, test) { var found = test(tree) ? [tree] : [] if (isNode(tree)) { if (tree.children.length > 0) { tree.children.forEach(function (child) { found = found.concat(findAll(child, test)) }) } } return found }
[ "function", "findAll", "(", "tree", ",", "test", ")", "{", "var", "found", "=", "test", "(", "tree", ")", "?", "[", "tree", "]", ":", "[", "]", "if", "(", "isNode", "(", "tree", ")", ")", "{", "if", "(", "tree", ".", "children", ".", "length", ">", "0", ")", "{", "tree", ".", "children", ".", "forEach", "(", "function", "(", "child", ")", "{", "found", "=", "found", ".", "concat", "(", "findAll", "(", "child", ",", "test", ")", ")", "}", ")", "}", "}", "return", "found", "}" ]
Traverses the tree and returns all components that satisfy the function `test`. @param {DekuComponent} tree the tree to traverse @param {Function} test the test for each component @return {Array} the components that satisfied `test`
[ "Traverses", "the", "tree", "and", "returns", "all", "components", "that", "satisfy", "the", "function", "test", "." ]
dd18baf93fc036c61b5e081d06227f89a0697ee1
https://github.com/kvnneff/deku-component-find-all/blob/dd18baf93fc036c61b5e081d06227f89a0697ee1/index.js#L10-L21
train
imcuttle/quote-it
index.es5.js
quote
function quote(string) { var _Object$assign var quoteChar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '"' if (quoteChar.length > 1 && process.env.NODE_ENV !== 'production') { console.error('quote: `quoteChar` is recommended as single character, but ' + JSON.stringify(quoteChar) + '.') } return _quote( string, quoteChar, getEscapable(quoteChar), Object.assign( {}, commonMeta, ((_Object$assign = {}), (_Object$assign[quoteChar] = '\\' + quoteChar), _Object$assign) ) ) }
javascript
function quote(string) { var _Object$assign var quoteChar = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '"' if (quoteChar.length > 1 && process.env.NODE_ENV !== 'production') { console.error('quote: `quoteChar` is recommended as single character, but ' + JSON.stringify(quoteChar) + '.') } return _quote( string, quoteChar, getEscapable(quoteChar), Object.assign( {}, commonMeta, ((_Object$assign = {}), (_Object$assign[quoteChar] = '\\' + quoteChar), _Object$assign) ) ) }
[ "function", "quote", "(", "string", ")", "{", "var", "_Object$assign", "var", "quoteChar", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "'\"'", "if", "(", "quoteChar", ".", "length", ">", "1", "&&", "process", ".", "env", ".", "NODE_ENV", "!==", "'production'", ")", "{", "console", ".", "error", "(", "'quote: `quoteChar` is recommended as single character, but '", "+", "JSON", ".", "stringify", "(", "quoteChar", ")", "+", "'.'", ")", "}", "return", "_quote", "(", "string", ",", "quoteChar", ",", "getEscapable", "(", "quoteChar", ")", ",", "Object", ".", "assign", "(", "{", "}", ",", "commonMeta", ",", "(", "(", "_Object$assign", "=", "{", "}", ")", ",", "(", "_Object$assign", "[", "quoteChar", "]", "=", "'\\\\'", "+", "\\\\", ")", ",", "quoteChar", ")", ")", ")", "}" ]
Uses `quoteChar` to wrap string. @public @param string {string} @param quoteChar {string} @return {string} @example import quote from 'quote-it' quote("abc", "'") === "'abc'"
[ "Uses", "quoteChar", "to", "wrap", "string", "." ]
51c020b78f020f7e6c89352a2807342631bf3b7e
https://github.com/imcuttle/quote-it/blob/51c020b78f020f7e6c89352a2807342631bf3b7e/index.es5.js#L56-L75
train
jurca/idb-entity
es2015/clone.js
cloneValue
function cloneValue(value, traversedValues) { if (!(value instanceof Object)) { return value } if (value instanceof Boolean) { return new Boolean(value.valueOf()) } if (value instanceof Number) { return new Number(value.valueOf()) } if (value instanceof String) { return new String(value.valueOf()) } if (value instanceof Date) { return new Date(value.valueOf()) } if (value instanceof RegExp) { return new RegExp(value.source, value.flags) } if ((typeof Blob === "function") && (value instanceof Blob)) { return value // immutable } if ((typeof File === "function") && (value instanceof File)) { return value // immutable } if ((typeof FileList === "function") && (value instanceof FileList)) { return value // immutable } if ((typeof ArrayBuffer === "function") && (value instanceof ArrayBuffer)) { return value.slice() } if ((typeof DataView === "function") && (value instanceof DataView)) { return new DataView( value.buffer.slice(), value.byteOffset, value.byteLength ) } let isTypedArray = TYPED_ARRAY_TYPES.some(type => value instanceof type) if (isTypedArray) { return value.subarray() } if ((typeof ImageData === "function") && (value instanceof ImageData)) { return new ImageData(value.data, value.width, value.height) } if ((typeof ImageBitmap === "function") && (value instanceof ImageBitmap)) { return value } if (value instanceof Array) { return cloneArray(value, traversedValues) } if (value instanceof Map) { return cloneMap(value, traversedValues) } if (value instanceof Set) { return cloneSet(value, traversedValues) } if (isPlainObjectOrEntity(value)) { return cloneObject(value, traversedValues) } throw new Error(`Unsupported argument type: ${value}`) }
javascript
function cloneValue(value, traversedValues) { if (!(value instanceof Object)) { return value } if (value instanceof Boolean) { return new Boolean(value.valueOf()) } if (value instanceof Number) { return new Number(value.valueOf()) } if (value instanceof String) { return new String(value.valueOf()) } if (value instanceof Date) { return new Date(value.valueOf()) } if (value instanceof RegExp) { return new RegExp(value.source, value.flags) } if ((typeof Blob === "function") && (value instanceof Blob)) { return value // immutable } if ((typeof File === "function") && (value instanceof File)) { return value // immutable } if ((typeof FileList === "function") && (value instanceof FileList)) { return value // immutable } if ((typeof ArrayBuffer === "function") && (value instanceof ArrayBuffer)) { return value.slice() } if ((typeof DataView === "function") && (value instanceof DataView)) { return new DataView( value.buffer.slice(), value.byteOffset, value.byteLength ) } let isTypedArray = TYPED_ARRAY_TYPES.some(type => value instanceof type) if (isTypedArray) { return value.subarray() } if ((typeof ImageData === "function") && (value instanceof ImageData)) { return new ImageData(value.data, value.width, value.height) } if ((typeof ImageBitmap === "function") && (value instanceof ImageBitmap)) { return value } if (value instanceof Array) { return cloneArray(value, traversedValues) } if (value instanceof Map) { return cloneMap(value, traversedValues) } if (value instanceof Set) { return cloneSet(value, traversedValues) } if (isPlainObjectOrEntity(value)) { return cloneObject(value, traversedValues) } throw new Error(`Unsupported argument type: ${value}`) }
[ "function", "cloneValue", "(", "value", ",", "traversedValues", ")", "{", "if", "(", "!", "(", "value", "instanceof", "Object", ")", ")", "{", "return", "value", "}", "if", "(", "value", "instanceof", "Boolean", ")", "{", "return", "new", "Boolean", "(", "value", ".", "valueOf", "(", ")", ")", "}", "if", "(", "value", "instanceof", "Number", ")", "{", "return", "new", "Number", "(", "value", ".", "valueOf", "(", ")", ")", "}", "if", "(", "value", "instanceof", "String", ")", "{", "return", "new", "String", "(", "value", ".", "valueOf", "(", ")", ")", "}", "if", "(", "value", "instanceof", "Date", ")", "{", "return", "new", "Date", "(", "value", ".", "valueOf", "(", ")", ")", "}", "if", "(", "value", "instanceof", "RegExp", ")", "{", "return", "new", "RegExp", "(", "value", ".", "source", ",", "value", ".", "flags", ")", "}", "if", "(", "(", "typeof", "Blob", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "Blob", ")", ")", "{", "return", "value", "}", "if", "(", "(", "typeof", "File", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "File", ")", ")", "{", "return", "value", "}", "if", "(", "(", "typeof", "FileList", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "FileList", ")", ")", "{", "return", "value", "}", "if", "(", "(", "typeof", "ArrayBuffer", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "ArrayBuffer", ")", ")", "{", "return", "value", ".", "slice", "(", ")", "}", "if", "(", "(", "typeof", "DataView", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "DataView", ")", ")", "{", "return", "new", "DataView", "(", "value", ".", "buffer", ".", "slice", "(", ")", ",", "value", ".", "byteOffset", ",", "value", ".", "byteLength", ")", "}", "let", "isTypedArray", "=", "TYPED_ARRAY_TYPES", ".", "some", "(", "type", "=>", "value", "instanceof", "type", ")", "if", "(", "isTypedArray", ")", "{", "return", "value", ".", "subarray", "(", ")", "}", "if", "(", "(", "typeof", "ImageData", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "ImageData", ")", ")", "{", "return", "new", "ImageData", "(", "value", ".", "data", ",", "value", ".", "width", ",", "value", ".", "height", ")", "}", "if", "(", "(", "typeof", "ImageBitmap", "===", "\"function\"", ")", "&&", "(", "value", "instanceof", "ImageBitmap", ")", ")", "{", "return", "value", "}", "if", "(", "value", "instanceof", "Array", ")", "{", "return", "cloneArray", "(", "value", ",", "traversedValues", ")", "}", "if", "(", "value", "instanceof", "Map", ")", "{", "return", "cloneMap", "(", "value", ",", "traversedValues", ")", "}", "if", "(", "value", "instanceof", "Set", ")", "{", "return", "cloneSet", "(", "value", ",", "traversedValues", ")", "}", "if", "(", "isPlainObjectOrEntity", "(", "value", ")", ")", "{", "return", "cloneObject", "(", "value", ",", "traversedValues", ")", "}", "throw", "new", "Error", "(", "`", "${", "value", "}", "`", ")", "}" ]
Clones the provided value using the structured clone algorithm. @param {*} value The value to clone. @param {Map<Object, Object>} traversedValues A map of traversed non-primitive keys and values. The keys are the keys and values traversed in the source structure or structures referencing this structure, the values are the clones of the keys and values. @return {*} The value clone.
[ "Clones", "the", "provided", "value", "using", "the", "structured", "clone", "algorithm", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/clone.js#L33-L112
train
jurca/idb-entity
es2015/clone.js
cloneArray
function cloneArray(source, traversedValues) { let clone = [] traversedValues.set(source, clone) cloneStructure( source.keys(), key => source[key], (key, value) => clone[key] = value, traversedValues ) return clone }
javascript
function cloneArray(source, traversedValues) { let clone = [] traversedValues.set(source, clone) cloneStructure( source.keys(), key => source[key], (key, value) => clone[key] = value, traversedValues ) return clone }
[ "function", "cloneArray", "(", "source", ",", "traversedValues", ")", "{", "let", "clone", "=", "[", "]", "traversedValues", ".", "set", "(", "source", ",", "clone", ")", "cloneStructure", "(", "source", ".", "keys", "(", ")", ",", "key", "=>", "source", "[", "key", "]", ",", "(", "key", ",", "value", ")", "=>", "clone", "[", "key", "]", "=", "value", ",", "traversedValues", ")", "return", "clone", "}" ]
Clones the provided array. @param {*[]} source The array to clone. @param {Map<Object, Object>} traversedValues A map of traversed non-primitive keys and values. The keys are the keys and values traversed in the source structure or structures referencing this structure, the values are the clones of the keys and values. @return {*[]} Source array clone.
[ "Clones", "the", "provided", "array", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/clone.js#L124-L136
train
jurca/idb-entity
es2015/clone.js
cloneMap
function cloneMap(source, traversedValues) { let clone = new Map() traversedValues.set(source, clone) cloneStructure( source.keys(), key => source.get(key), (key, value) => clone.set(key, value), traversedValues ) return clone }
javascript
function cloneMap(source, traversedValues) { let clone = new Map() traversedValues.set(source, clone) cloneStructure( source.keys(), key => source.get(key), (key, value) => clone.set(key, value), traversedValues ) return clone }
[ "function", "cloneMap", "(", "source", ",", "traversedValues", ")", "{", "let", "clone", "=", "new", "Map", "(", ")", "traversedValues", ".", "set", "(", "source", ",", "clone", ")", "cloneStructure", "(", "source", ".", "keys", "(", ")", ",", "key", "=>", "source", ".", "get", "(", "key", ")", ",", "(", "key", ",", "value", ")", "=>", "clone", ".", "set", "(", "key", ",", "value", ")", ",", "traversedValues", ")", "return", "clone", "}" ]
Clones the provided map. @param {Map<*, *>} source The map to clone. @param {Map<Object, Object>} traversedValues A map of traversed non-primitive keys and values. The keys are the keys and values traversed in the source structure or structures referencing this structure, the values are the clones of the keys and values. @return {Map<*, *>} Source map clone.
[ "Clones", "the", "provided", "map", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/clone.js#L148-L160
train
jurca/idb-entity
es2015/clone.js
cloneSet
function cloneSet(source, traversedValues) { let clone = new Set() traversedValues.set(source, clone) cloneStructure( source.values(), entry => undefined, entry => clone.add(entry), traversedValues ) return clone }
javascript
function cloneSet(source, traversedValues) { let clone = new Set() traversedValues.set(source, clone) cloneStructure( source.values(), entry => undefined, entry => clone.add(entry), traversedValues ) return clone }
[ "function", "cloneSet", "(", "source", ",", "traversedValues", ")", "{", "let", "clone", "=", "new", "Set", "(", ")", "traversedValues", ".", "set", "(", "source", ",", "clone", ")", "cloneStructure", "(", "source", ".", "values", "(", ")", ",", "entry", "=>", "undefined", ",", "entry", "=>", "clone", ".", "add", "(", "entry", ")", ",", "traversedValues", ")", "return", "clone", "}" ]
Clones the provided set. @param {Set<*>} source The set to clone. @param {Map<Object, Object>} traversedValues A map of traversed non-primitive keys and values. The keys are the keys and values traversed in the source structure or structures referencing this structure, the values are the clones of the keys and values. @return {Set<*>} Source set clone.
[ "Clones", "the", "provided", "set", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/clone.js#L172-L184
train
jurca/idb-entity
es2015/clone.js
cloneObject
function cloneObject(source, traversedValues) { let clone = {} traversedValues.set(source, clone) cloneStructure( Object.keys(source), key => source[key], (key, value) => clone[key] = value, traversedValues ) return clone }
javascript
function cloneObject(source, traversedValues) { let clone = {} traversedValues.set(source, clone) cloneStructure( Object.keys(source), key => source[key], (key, value) => clone[key] = value, traversedValues ) return clone }
[ "function", "cloneObject", "(", "source", ",", "traversedValues", ")", "{", "let", "clone", "=", "{", "}", "traversedValues", ".", "set", "(", "source", ",", "clone", ")", "cloneStructure", "(", "Object", ".", "keys", "(", "source", ")", ",", "key", "=>", "source", "[", "key", "]", ",", "(", "key", ",", "value", ")", "=>", "clone", "[", "key", "]", "=", "value", ",", "traversedValues", ")", "return", "clone", "}" ]
Clones the provided plain object. Symbol and prototype properties are not copied. @param {Object<string, *>} source The object to clone. @param {Map<Object, Object>} traversedValues A map of traversed non-primitive keys and values. The keys are the keys and values traversed in the source structure or structures referencing this structure, the values are the clones of the keys and values. @return {Object<string, *>} Source object clone.
[ "Clones", "the", "provided", "plain", "object", ".", "Symbol", "and", "prototype", "properties", "are", "not", "copied", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/clone.js#L197-L209
train
jurca/idb-entity
es2015/clone.js
cloneStructure
function cloneStructure(keys, getter, setter, traversedValues) { for (let key of keys) { let value = getter(key) let keyClone if (key instanceof Object) { if (traversedValues.has(key)) { keyClone = traversedValues.get(key) } else { keyClone = cloneValue(key, traversedValues) traversedValues.set(key, keyClone) } } else { keyClone = key } if (value instanceof Object) { if (traversedValues.has(value)) { setter(keyClone, traversedValues.get(value)) } else { let clonedValue = cloneValue(value, traversedValues) traversedValues.set(value, clonedValue) setter(keyClone, clonedValue) } } else { setter(keyClone, value) } } }
javascript
function cloneStructure(keys, getter, setter, traversedValues) { for (let key of keys) { let value = getter(key) let keyClone if (key instanceof Object) { if (traversedValues.has(key)) { keyClone = traversedValues.get(key) } else { keyClone = cloneValue(key, traversedValues) traversedValues.set(key, keyClone) } } else { keyClone = key } if (value instanceof Object) { if (traversedValues.has(value)) { setter(keyClone, traversedValues.get(value)) } else { let clonedValue = cloneValue(value, traversedValues) traversedValues.set(value, clonedValue) setter(keyClone, clonedValue) } } else { setter(keyClone, value) } } }
[ "function", "cloneStructure", "(", "keys", ",", "getter", ",", "setter", ",", "traversedValues", ")", "{", "for", "(", "let", "key", "of", "keys", ")", "{", "let", "value", "=", "getter", "(", "key", ")", "let", "keyClone", "if", "(", "key", "instanceof", "Object", ")", "{", "if", "(", "traversedValues", ".", "has", "(", "key", ")", ")", "{", "keyClone", "=", "traversedValues", ".", "get", "(", "key", ")", "}", "else", "{", "keyClone", "=", "cloneValue", "(", "key", ",", "traversedValues", ")", "traversedValues", ".", "set", "(", "key", ",", "keyClone", ")", "}", "}", "else", "{", "keyClone", "=", "key", "}", "if", "(", "value", "instanceof", "Object", ")", "{", "if", "(", "traversedValues", ".", "has", "(", "value", ")", ")", "{", "setter", "(", "keyClone", ",", "traversedValues", ".", "get", "(", "value", ")", ")", "}", "else", "{", "let", "clonedValue", "=", "cloneValue", "(", "value", ",", "traversedValues", ")", "traversedValues", ".", "set", "(", "value", ",", "clonedValue", ")", "setter", "(", "keyClone", ",", "clonedValue", ")", "}", "}", "else", "{", "setter", "(", "keyClone", ",", "value", ")", "}", "}", "}" ]
Clones the structure having the specified property keys, using the provided getters and setters. The function clones the keys and values before setting them using the setters. The cloned structure may contain circular references, the function keeps track of those using the {@code traversedValues} map. @param {(*[]|{[Symbol.iterator]: function(): {next: function(): *}})} keys The keys or iterator or iterable object generating the keys to properties to clone. @param {function(*): *} getter A callback that returns the value of the source structure for the provided key. @param {function(*, *)} setter A callback that sets the provided value (2nd argument) to the property identified by the specified key (1st argument) in the structure clone. @param {Map<Object, Object>} traversedValues A map of traversed non-primitive keys and values. The keys are the keys and values traversed in the source structure or structures referencing this structure, the values are the clones of the keys and values.
[ "Clones", "the", "structure", "having", "the", "specified", "property", "keys", "using", "the", "provided", "getters", "and", "setters", ".", "The", "function", "clones", "the", "keys", "and", "values", "before", "setting", "them", "using", "the", "setters", "." ]
361ef8482872d9fc9a0d83b86970d49d391dc276
https://github.com/jurca/idb-entity/blob/361ef8482872d9fc9a0d83b86970d49d391dc276/es2015/clone.js#L232-L260
train
labs42/prelint
src/prelint.js
getStagedFiles
function getStagedFiles(callback) { const options = [ 'diff', '--cached', '--name-only', '--diff-filter=ACM' ] execFile('git', options, (err, stdout) => { if (err) return callback(err) const stagedFiles = stdout .split('\n') .filter(filename => filename.match(/.js$/)) callback(null, stagedFiles) }) }
javascript
function getStagedFiles(callback) { const options = [ 'diff', '--cached', '--name-only', '--diff-filter=ACM' ] execFile('git', options, (err, stdout) => { if (err) return callback(err) const stagedFiles = stdout .split('\n') .filter(filename => filename.match(/.js$/)) callback(null, stagedFiles) }) }
[ "function", "getStagedFiles", "(", "callback", ")", "{", "const", "options", "=", "[", "'diff'", ",", "'--cached'", ",", "'--name-only'", ",", "'--diff-filter=ACM'", "]", "execFile", "(", "'git'", ",", "options", ",", "(", "err", ",", "stdout", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", "const", "stagedFiles", "=", "stdout", ".", "split", "(", "'\\n'", ")", ".", "\\n", "filter", "(", "filename", "=>", "filename", ".", "match", "(", "/", ".js$", "/", ")", ")", "}", ")", "}" ]
Calls callback with list of staged files @param {Function} callback @returns {void}
[ "Calls", "callback", "with", "list", "of", "staged", "files" ]
94d81bb786ae3a7ec759a1ba2c10461b34f6a15f
https://github.com/labs42/prelint/blob/94d81bb786ae3a7ec759a1ba2c10461b34f6a15f/src/prelint.js#L15-L31
train
labs42/prelint
src/prelint.js
lintFiles
function lintFiles(files) { const eslint = new CLIEngine() const report = eslint.executeOnFiles(files) return { text: friendlyFormatter(report.results), errorCount: report.errorCount, } }
javascript
function lintFiles(files) { const eslint = new CLIEngine() const report = eslint.executeOnFiles(files) return { text: friendlyFormatter(report.results), errorCount: report.errorCount, } }
[ "function", "lintFiles", "(", "files", ")", "{", "const", "eslint", "=", "new", "CLIEngine", "(", ")", "const", "report", "=", "eslint", ".", "executeOnFiles", "(", "files", ")", "return", "{", "text", ":", "friendlyFormatter", "(", "report", ".", "results", ")", ",", "errorCount", ":", "report", ".", "errorCount", ",", "}", "}" ]
Perform ESLint validation on list of files @param {Array<string>} files @returns {Object} report
[ "Perform", "ESLint", "validation", "on", "list", "of", "files" ]
94d81bb786ae3a7ec759a1ba2c10461b34f6a15f
https://github.com/labs42/prelint/blob/94d81bb786ae3a7ec759a1ba2c10461b34f6a15f/src/prelint.js#L38-L49
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editor.js
isSupportedElement
function isSupportedElement( element, mode ) { if ( mode == CKEDITOR.ELEMENT_MODE_INLINE ) return element.is( CKEDITOR.dtd.$editable ) || element.is( 'textarea' ); else if ( mode == CKEDITOR.ELEMENT_MODE_REPLACE ) return !element.is( CKEDITOR.dtd.$nonBodyContent ); return 1; }
javascript
function isSupportedElement( element, mode ) { if ( mode == CKEDITOR.ELEMENT_MODE_INLINE ) return element.is( CKEDITOR.dtd.$editable ) || element.is( 'textarea' ); else if ( mode == CKEDITOR.ELEMENT_MODE_REPLACE ) return !element.is( CKEDITOR.dtd.$nonBodyContent ); return 1; }
[ "function", "isSupportedElement", "(", "element", ",", "mode", ")", "{", "if", "(", "mode", "==", "CKEDITOR", ".", "ELEMENT_MODE_INLINE", ")", "return", "element", ".", "is", "(", "CKEDITOR", ".", "dtd", ".", "$editable", ")", "||", "element", ".", "is", "(", "'textarea'", ")", ";", "else", "if", "(", "mode", "==", "CKEDITOR", ".", "ELEMENT_MODE_REPLACE", ")", "return", "!", "element", ".", "is", "(", "CKEDITOR", ".", "dtd", ".", "$nonBodyContent", ")", ";", "return", "1", ";", "}" ]
Asserting element DTD depending on mode.
[ "Asserting", "element", "DTD", "depending", "on", "mode", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editor.js#L200-L206
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editor.js
initComponents
function initComponents( editor ) { // Documented in dataprocessor.js. editor.dataProcessor = new CKEDITOR.htmlDataProcessor( editor ); // Set activeFilter directly to avoid firing event. editor.filter = editor.activeFilter = new CKEDITOR.filter( editor ); loadSkin( editor ); }
javascript
function initComponents( editor ) { // Documented in dataprocessor.js. editor.dataProcessor = new CKEDITOR.htmlDataProcessor( editor ); // Set activeFilter directly to avoid firing event. editor.filter = editor.activeFilter = new CKEDITOR.filter( editor ); loadSkin( editor ); }
[ "function", "initComponents", "(", "editor", ")", "{", "editor", ".", "dataProcessor", "=", "new", "CKEDITOR", ".", "htmlDataProcessor", "(", "editor", ")", ";", "editor", ".", "filter", "=", "editor", ".", "activeFilter", "=", "new", "CKEDITOR", ".", "filter", "(", "editor", ")", ";", "loadSkin", "(", "editor", ")", ";", "}" ]
Various other core components that read editor configuration.
[ "Various", "other", "core", "components", "that", "read", "editor", "configuration", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editor.js#L389-L397
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editor.js
updateEditorElement
function updateEditorElement() { var element = this.element; // Some editor creation mode will not have the // associated element. if ( element && this.elementMode != CKEDITOR.ELEMENT_MODE_APPENDTO ) { var data = this.getData(); if ( this.config.htmlEncodeOutput ) data = CKEDITOR.tools.htmlEncode( data ); if ( element.is( 'textarea' ) ) element.setValue( data ); else element.setHtml( data ); return true; } return false; }
javascript
function updateEditorElement() { var element = this.element; // Some editor creation mode will not have the // associated element. if ( element && this.elementMode != CKEDITOR.ELEMENT_MODE_APPENDTO ) { var data = this.getData(); if ( this.config.htmlEncodeOutput ) data = CKEDITOR.tools.htmlEncode( data ); if ( element.is( 'textarea' ) ) element.setValue( data ); else element.setHtml( data ); return true; } return false; }
[ "function", "updateEditorElement", "(", ")", "{", "var", "element", "=", "this", ".", "element", ";", "if", "(", "element", "&&", "this", ".", "elementMode", "!=", "CKEDITOR", ".", "ELEMENT_MODE_APPENDTO", ")", "{", "var", "data", "=", "this", ".", "getData", "(", ")", ";", "if", "(", "this", ".", "config", ".", "htmlEncodeOutput", ")", "data", "=", "CKEDITOR", ".", "tools", ".", "htmlEncode", "(", "data", ")", ";", "if", "(", "element", ".", "is", "(", "'textarea'", ")", ")", "element", ".", "setValue", "(", "data", ")", ";", "else", "element", ".", "setHtml", "(", "data", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Send to data output back to editor's associated element.
[ "Send", "to", "data", "output", "back", "to", "editor", "s", "associated", "element", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editor.js#L625-L644
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editor.js
function( commandName, data ) { var command = this.getCommand( commandName ); var eventData = { name: commandName, commandData: data, command: command }; if ( command && command.state != CKEDITOR.TRISTATE_DISABLED ) { if ( this.fire( 'beforeCommandExec', eventData ) !== false ) { eventData.returnValue = command.exec( eventData.commandData ); // Fire the 'afterCommandExec' immediately if command is synchronous. if ( !command.async && this.fire( 'afterCommandExec', eventData ) !== false ) return eventData.returnValue; } } // throw 'Unknown command name "' + commandName + '"'; return false; }
javascript
function( commandName, data ) { var command = this.getCommand( commandName ); var eventData = { name: commandName, commandData: data, command: command }; if ( command && command.state != CKEDITOR.TRISTATE_DISABLED ) { if ( this.fire( 'beforeCommandExec', eventData ) !== false ) { eventData.returnValue = command.exec( eventData.commandData ); // Fire the 'afterCommandExec' immediately if command is synchronous. if ( !command.async && this.fire( 'afterCommandExec', eventData ) !== false ) return eventData.returnValue; } } // throw 'Unknown command name "' + commandName + '"'; return false; }
[ "function", "(", "commandName", ",", "data", ")", "{", "var", "command", "=", "this", ".", "getCommand", "(", "commandName", ")", ";", "var", "eventData", "=", "{", "name", ":", "commandName", ",", "commandData", ":", "data", ",", "command", ":", "command", "}", ";", "if", "(", "command", "&&", "command", ".", "state", "!=", "CKEDITOR", ".", "TRISTATE_DISABLED", ")", "{", "if", "(", "this", ".", "fire", "(", "'beforeCommandExec'", ",", "eventData", ")", "!==", "false", ")", "{", "eventData", ".", "returnValue", "=", "command", ".", "exec", "(", "eventData", ".", "commandData", ")", ";", "if", "(", "!", "command", ".", "async", "&&", "this", ".", "fire", "(", "'afterCommandExec'", ",", "eventData", ")", "!==", "false", ")", "return", "eventData", ".", "returnValue", ";", "}", "}", "return", "false", ";", "}" ]
Executes a command associated with the editor. editorInstance.execCommand( 'bold' ); @param {String} commandName The indentifier name of the command. @param {Object} [data] Data to be passed to the command. @returns {Boolean} `true` if the command was executed successfully, otherwise `false`. @see CKEDITOR.editor#addCommand
[ "Executes", "a", "command", "associated", "with", "the", "editor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editor.js#L819-L840
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editor.js
function() { var keystrokes = this.keystrokeHandler.keystrokes, newKeystrokes = CKEDITOR.tools.isArray( arguments[ 0 ] ) ? arguments[ 0 ] : [ [].slice.call( arguments, 0 ) ], keystroke, behavior; for ( var i = newKeystrokes.length; i--; ) { keystroke = newKeystrokes[ i ]; behavior = 0; // It may be a pair of: [ key, command ] if ( CKEDITOR.tools.isArray( keystroke ) ) { behavior = keystroke[ 1 ]; keystroke = keystroke[ 0 ]; } if ( behavior ) keystrokes[ keystroke ] = behavior; else delete keystrokes[ keystroke ]; } }
javascript
function() { var keystrokes = this.keystrokeHandler.keystrokes, newKeystrokes = CKEDITOR.tools.isArray( arguments[ 0 ] ) ? arguments[ 0 ] : [ [].slice.call( arguments, 0 ) ], keystroke, behavior; for ( var i = newKeystrokes.length; i--; ) { keystroke = newKeystrokes[ i ]; behavior = 0; // It may be a pair of: [ key, command ] if ( CKEDITOR.tools.isArray( keystroke ) ) { behavior = keystroke[ 1 ]; keystroke = keystroke[ 0 ]; } if ( behavior ) keystrokes[ keystroke ] = behavior; else delete keystrokes[ keystroke ]; } }
[ "function", "(", ")", "{", "var", "keystrokes", "=", "this", ".", "keystrokeHandler", ".", "keystrokes", ",", "newKeystrokes", "=", "CKEDITOR", ".", "tools", ".", "isArray", "(", "arguments", "[", "0", "]", ")", "?", "arguments", "[", "0", "]", ":", "[", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "0", ")", "]", ",", "keystroke", ",", "behavior", ";", "for", "(", "var", "i", "=", "newKeystrokes", ".", "length", ";", "i", "--", ";", ")", "{", "keystroke", "=", "newKeystrokes", "[", "i", "]", ";", "behavior", "=", "0", ";", "if", "(", "CKEDITOR", ".", "tools", ".", "isArray", "(", "keystroke", ")", ")", "{", "behavior", "=", "keystroke", "[", "1", "]", ";", "keystroke", "=", "keystroke", "[", "0", "]", ";", "}", "if", "(", "behavior", ")", "keystrokes", "[", "keystroke", "]", "=", "behavior", ";", "else", "delete", "keystrokes", "[", "keystroke", "]", ";", "}", "}" ]
Assigns keystrokes associated to editor commands. editor.setKeystroke( CKEDITOR.CTRL + 115, 'save' ); // Assigned CTRL+S to "save" command. editor.setKeystroke( CKEDITOR.CTRL + 115, false ); // Disabled CTRL+S keystroke assignment. editor.setKeystroke( [ [ CKEDITOR.ALT + 122, false ], [ CKEDITOR.CTRL + 121, 'link' ], [ CKEDITOR.SHIFT + 120, 'bold' ] ] ); This method may be used in the following cases: * By plugins (like `link` or `basicstyles`) to set their keystrokes when plugins are being loaded. * During the runtime to modify existing keystrokes. The editor handles keystroke configuration in the following order: 1. Plugins use this method to define default keystrokes. 2. Editor extends default keystrokes with {@link CKEDITOR.config#keystrokes}. 3. Editor blocks keystrokes defined in {@link CKEDITOR.config#blockedKeystrokes}. After all, you can still set new keystrokes using this method during the runtime. @since 4.0 @param {Number/Array} keystroke Keystroke or an array of keystroke definitions. @param {String/Boolean} [behavior] A command to be executed on the keystroke.
[ "Assigns", "keystrokes", "associated", "to", "editor", "commands", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editor.js#L1153-L1173
train
pinyin/outline
vendor/transformation-matrix/transform.js
transform
function transform() { for (var _len = arguments.length, matrices = Array(_len), _key = 0; _key < _len; _key++) { matrices[_key] = arguments[_key]; } matrices = Array.isArray(matrices[0]) ? matrices[0] : matrices; var multiply = function multiply(m1, m2) { return { a: m1.a * m2.a + m1.c * m2.b, c: m1.a * m2.c + m1.c * m2.d, e: m1.a * m2.e + m1.c * m2.f + m1.e, b: m1.b * m2.a + m1.d * m2.b, d: m1.b * m2.c + m1.d * m2.d, f: m1.b * m2.e + m1.d * m2.f + m1.f }; }; switch (matrices.length) { case 0: throw new Error('no matrices provided'); case 1: return matrices[0]; case 2: return multiply(matrices[0], matrices[1]); default: var _matrices = matrices, _matrices2 = _toArray(_matrices), m1 = _matrices2[0], m2 = _matrices2[1], rest = _matrices2.slice(2); var m = multiply(m1, m2); return transform.apply(undefined, [m].concat(_toConsumableArray(rest))); } }
javascript
function transform() { for (var _len = arguments.length, matrices = Array(_len), _key = 0; _key < _len; _key++) { matrices[_key] = arguments[_key]; } matrices = Array.isArray(matrices[0]) ? matrices[0] : matrices; var multiply = function multiply(m1, m2) { return { a: m1.a * m2.a + m1.c * m2.b, c: m1.a * m2.c + m1.c * m2.d, e: m1.a * m2.e + m1.c * m2.f + m1.e, b: m1.b * m2.a + m1.d * m2.b, d: m1.b * m2.c + m1.d * m2.d, f: m1.b * m2.e + m1.d * m2.f + m1.f }; }; switch (matrices.length) { case 0: throw new Error('no matrices provided'); case 1: return matrices[0]; case 2: return multiply(matrices[0], matrices[1]); default: var _matrices = matrices, _matrices2 = _toArray(_matrices), m1 = _matrices2[0], m2 = _matrices2[1], rest = _matrices2.slice(2); var m = multiply(m1, m2); return transform.apply(undefined, [m].concat(_toConsumableArray(rest))); } }
[ "function", "transform", "(", ")", "{", "for", "(", "var", "_len", "=", "arguments", ".", "length", ",", "matrices", "=", "Array", "(", "_len", ")", ",", "_key", "=", "0", ";", "_key", "<", "_len", ";", "_key", "++", ")", "{", "matrices", "[", "_key", "]", "=", "arguments", "[", "_key", "]", ";", "}", "matrices", "=", "Array", ".", "isArray", "(", "matrices", "[", "0", "]", ")", "?", "matrices", "[", "0", "]", ":", "matrices", ";", "var", "multiply", "=", "function", "multiply", "(", "m1", ",", "m2", ")", "{", "return", "{", "a", ":", "m1", ".", "a", "*", "m2", ".", "a", "+", "m1", ".", "c", "*", "m2", ".", "b", ",", "c", ":", "m1", ".", "a", "*", "m2", ".", "c", "+", "m1", ".", "c", "*", "m2", ".", "d", ",", "e", ":", "m1", ".", "a", "*", "m2", ".", "e", "+", "m1", ".", "c", "*", "m2", ".", "f", "+", "m1", ".", "e", ",", "b", ":", "m1", ".", "b", "*", "m2", ".", "a", "+", "m1", ".", "d", "*", "m2", ".", "b", ",", "d", ":", "m1", ".", "b", "*", "m2", ".", "c", "+", "m1", ".", "d", "*", "m2", ".", "d", ",", "f", ":", "m1", ".", "b", "*", "m2", ".", "e", "+", "m1", ".", "d", "*", "m2", ".", "f", "+", "m1", ".", "f", "}", ";", "}", ";", "switch", "(", "matrices", ".", "length", ")", "{", "case", "0", ":", "throw", "new", "Error", "(", "'no matrices provided'", ")", ";", "case", "1", ":", "return", "matrices", "[", "0", "]", ";", "case", "2", ":", "return", "multiply", "(", "matrices", "[", "0", "]", ",", "matrices", "[", "1", "]", ")", ";", "default", ":", "var", "_matrices", "=", "matrices", ",", "_matrices2", "=", "_toArray", "(", "_matrices", ")", ",", "m1", "=", "_matrices2", "[", "0", "]", ",", "m2", "=", "_matrices2", "[", "1", "]", ",", "rest", "=", "_matrices2", ".", "slice", "(", "2", ")", ";", "var", "m", "=", "multiply", "(", "m1", ",", "m2", ")", ";", "return", "transform", ".", "apply", "(", "undefined", ",", "[", "m", "]", ".", "concat", "(", "_toConsumableArray", "(", "rest", ")", ")", ")", ";", "}", "}" ]
Merge multiple matrices into one @param matrices {...object} list of matrices @returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix
[ "Merge", "multiple", "matrices", "into", "one" ]
e49f05d2f8ab384f5b1d71b2b10875cd48d41051
https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/transform.js#L28-L62
train
stadt-bielefeld/wms-capabilities-tools
baseUrl.js
correctQuestionMarkAndAnd
function correctQuestionMarkAndAnd(url) { var baseURL = url; // Remove && mistake baseURL = baseURL.replace(new RegExp('&&', 'g'), '&'); // Ends width ? if (new RegExp('[\?]$').test(baseURL)) { // Do nothing } else { // Does not end on ? // Contains ? if (baseURL.includes('?')) { // Ends width & if (new RegExp('[\&]$').test(baseURL)) { // Do nothing } else { // Does not end on & // Add & baseURL += '&'; } } else { // Does not contain on ? // Count of & var countOfAnd = baseURL.split('&').length - 1; // Ends with & if (new RegExp('[\&]$').test(baseURL)) { if (countOfAnd === 1) { // Remove & baseURL = baseURL.slice(0, -1); // Add ? baseURL += '?'; } else { // Replace first & with ? baseURL = baseURL.replace('&', '?'); } } else { // Does not contain on ? ends not on & // Contains one or more & if (countOfAnd > 1) { // Replace first & with ? baseURL = baseURL.replace('&', '?'); // Add & baseURL += '&'; } else { // Does not contain & // Add ? baseURL += '?'; } } } } return baseURL; }
javascript
function correctQuestionMarkAndAnd(url) { var baseURL = url; // Remove && mistake baseURL = baseURL.replace(new RegExp('&&', 'g'), '&'); // Ends width ? if (new RegExp('[\?]$').test(baseURL)) { // Do nothing } else { // Does not end on ? // Contains ? if (baseURL.includes('?')) { // Ends width & if (new RegExp('[\&]$').test(baseURL)) { // Do nothing } else { // Does not end on & // Add & baseURL += '&'; } } else { // Does not contain on ? // Count of & var countOfAnd = baseURL.split('&').length - 1; // Ends with & if (new RegExp('[\&]$').test(baseURL)) { if (countOfAnd === 1) { // Remove & baseURL = baseURL.slice(0, -1); // Add ? baseURL += '?'; } else { // Replace first & with ? baseURL = baseURL.replace('&', '?'); } } else { // Does not contain on ? ends not on & // Contains one or more & if (countOfAnd > 1) { // Replace first & with ? baseURL = baseURL.replace('&', '?'); // Add & baseURL += '&'; } else { // Does not contain & // Add ? baseURL += '?'; } } } } return baseURL; }
[ "function", "correctQuestionMarkAndAnd", "(", "url", ")", "{", "var", "baseURL", "=", "url", ";", "baseURL", "=", "baseURL", ".", "replace", "(", "new", "RegExp", "(", "'&&'", ",", "'g'", ")", ",", "'&'", ")", ";", "if", "(", "new", "RegExp", "(", "'[\\?]$'", ")", ".", "\\?", "test", ")", "(", "baseURL", ")", "else", "{", "}", "{", "if", "(", "baseURL", ".", "includes", "(", "'?'", ")", ")", "{", "if", "(", "new", "RegExp", "(", "'[\\&]$'", ")", ".", "\\&", "test", ")", "(", "baseURL", ")", "else", "{", "}", "}", "else", "{", "baseURL", "+=", "'&'", ";", "}", "}", "}" ]
Correct mistakes with the characters '?' and '&'. @param {string} url URL with mistakes with the characters '?' and '&'. @returns {string} URL without mistakes with the characters '?' and '&'.
[ "Correct", "mistakes", "with", "the", "characters", "?", "and", "&", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/baseUrl.js#L96-L160
train
stadt-bielefeld/wms-capabilities-tools
baseUrl.js
removeParameters
function removeParameters(url) { var baseURL = url; // Iterate over all parameters for (var int = 0; int < params.length; int++) { // Remove parameter baseURL = baseURL.replace(new RegExp(params[int] + '=[^&]*&', 'ig'), ''); } return baseURL; }
javascript
function removeParameters(url) { var baseURL = url; // Iterate over all parameters for (var int = 0; int < params.length; int++) { // Remove parameter baseURL = baseURL.replace(new RegExp(params[int] + '=[^&]*&', 'ig'), ''); } return baseURL; }
[ "function", "removeParameters", "(", "url", ")", "{", "var", "baseURL", "=", "url", ";", "for", "(", "var", "int", "=", "0", ";", "int", "<", "params", ".", "length", ";", "int", "++", ")", "{", "baseURL", "=", "baseURL", ".", "replace", "(", "new", "RegExp", "(", "params", "[", "int", "]", "+", "'=[^&]*&'", ",", "'ig'", ")", ",", "''", ")", ";", "}", "return", "baseURL", ";", "}" ]
Removes OWS-Parameters from URL. The Parameters are defined at removeParameters.json. @param {string} url URL with OWS-Parameters. @returns {string} URL without OWS-Parameters.
[ "Removes", "OWS", "-", "Parameters", "from", "URL", ".", "The", "Parameters", "are", "defined", "at", "removeParameters", ".", "json", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/baseUrl.js#L170-L181
train
stadt-bielefeld/wms-capabilities-tools
baseUrl.js
determineBaseURL
function determineBaseURL(url) { var baseURL; // Check if url is set if (url) { // Remove whitespace baseURL = url.trim(); baseURL = correctHttpAndHttps(baseURL); baseURL = correctQuestionMarkAndAnd(baseURL); baseURL = removeParameters(baseURL); } else { // Throw error (no url) throw new Error('The url parameter is not set.'); } return baseURL; }
javascript
function determineBaseURL(url) { var baseURL; // Check if url is set if (url) { // Remove whitespace baseURL = url.trim(); baseURL = correctHttpAndHttps(baseURL); baseURL = correctQuestionMarkAndAnd(baseURL); baseURL = removeParameters(baseURL); } else { // Throw error (no url) throw new Error('The url parameter is not set.'); } return baseURL; }
[ "function", "determineBaseURL", "(", "url", ")", "{", "var", "baseURL", ";", "if", "(", "url", ")", "{", "baseURL", "=", "url", ".", "trim", "(", ")", ";", "baseURL", "=", "correctHttpAndHttps", "(", "baseURL", ")", ";", "baseURL", "=", "correctQuestionMarkAndAnd", "(", "baseURL", ")", ";", "baseURL", "=", "removeParameters", "(", "baseURL", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'The url parameter is not set.'", ")", ";", "}", "return", "baseURL", ";", "}" ]
Corrects all mistakes in a URL. @param {string} url URL with mistakes. @returns {string} URL without mistakes.
[ "Corrects", "all", "mistakes", "in", "a", "URL", "." ]
647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1
https://github.com/stadt-bielefeld/wms-capabilities-tools/blob/647321bc7fb9a50a5fdc6c3424ede3d9c0fd1cb1/baseUrl.js#L190-L210
train