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
stream-utils/unpipe
index.js
hasPipeDataListeners
function hasPipeDataListeners (stream) { var listeners = stream.listeners('data') for (var i = 0; i < listeners.length; i++) { if (listeners[i].name === 'ondata') { return true } } return false }
javascript
function hasPipeDataListeners (stream) { var listeners = stream.listeners('data') for (var i = 0; i < listeners.length; i++) { if (listeners[i].name === 'ondata') { return true } } return false }
[ "function", "hasPipeDataListeners", "(", "stream", ")", "{", "var", "listeners", "=", "stream", ".", "listeners", "(", "'data'", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "listeners", ".", "length", ";", "i", "++", ")", "{", "if", "(", "listeners", "[", "i", "]", ".", "name", "===", "'ondata'", ")", "{", "return", "true", "}", "}", "return", "false", "}" ]
Determine if there are Node.js pipe-like data listeners. @private
[ "Determine", "if", "there", "are", "Node", ".", "js", "pipe", "-", "like", "data", "listeners", "." ]
a69045d0f12752d64310eea365efa015cbfc97c5
https://github.com/stream-utils/unpipe/blob/a69045d0f12752d64310eea365efa015cbfc97c5/index.js#L21-L31
train
stream-utils/unpipe
index.js
unpipe
function unpipe (stream) { if (!stream) { throw new TypeError('argument stream is required') } if (typeof stream.unpipe === 'function') { // new-style stream.unpipe() return } // Node.js 0.8 hack if (!hasPipeDataListeners(stream)) { return } var listener var listeners = stream.listeners('close') for (var i = 0; i < listeners.length; i++) { listener = listeners[i] if (listener.name !== 'cleanup' && listener.name !== 'onclose') { continue } // invoke the listener listener.call(stream) } }
javascript
function unpipe (stream) { if (!stream) { throw new TypeError('argument stream is required') } if (typeof stream.unpipe === 'function') { // new-style stream.unpipe() return } // Node.js 0.8 hack if (!hasPipeDataListeners(stream)) { return } var listener var listeners = stream.listeners('close') for (var i = 0; i < listeners.length; i++) { listener = listeners[i] if (listener.name !== 'cleanup' && listener.name !== 'onclose') { continue } // invoke the listener listener.call(stream) } }
[ "function", "unpipe", "(", "stream", ")", "{", "if", "(", "!", "stream", ")", "{", "throw", "new", "TypeError", "(", "'argument stream is required'", ")", "}", "if", "(", "typeof", "stream", ".", "unpipe", "===", "'function'", ")", "{", "stream", ".", "unpipe", "(", ")", "return", "}", "if", "(", "!", "hasPipeDataListeners", "(", "stream", ")", ")", "{", "return", "}", "var", "listener", "var", "listeners", "=", "stream", ".", "listeners", "(", "'close'", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "listeners", ".", "length", ";", "i", "++", ")", "{", "listener", "=", "listeners", "[", "i", "]", "if", "(", "listener", ".", "name", "!==", "'cleanup'", "&&", "listener", ".", "name", "!==", "'onclose'", ")", "{", "continue", "}", "listener", ".", "call", "(", "stream", ")", "}", "}" ]
Unpipe a stream from all destinations. @param {object} stream @public
[ "Unpipe", "a", "stream", "from", "all", "destinations", "." ]
a69045d0f12752d64310eea365efa015cbfc97c5
https://github.com/stream-utils/unpipe/blob/a69045d0f12752d64310eea365efa015cbfc97c5/index.js#L40-L69
train
wikimedia/service-runner
lib/statsd.js
makeStatsD
function makeStatsD(options, logger) { let statsd; const srvName = options._prefix ? options._prefix : normalizeName(options.name); const statsdOptions = { host: options.host, port: options.port, prefix: `${srvName}.`, suffix: '', globalize: false, cacheDns: false, mock: false }; // Batch metrics unless `batch` option is `false` if (typeof options.batch !== 'boolean' || options.batch) { options.batch = options.batch || {}; statsdOptions.maxBufferSize = options.batch.max_size || DEFAULT_MAX_BATCH_SIZE; statsdOptions.bufferFlushInterval = options.batch.max_delay || 1000; } if (options.type === 'log') { statsd = new LogStatsD(logger, srvName); } else { statsd = new StatsD(statsdOptions); } // Support creating sub-metric clients with a fixed prefix. This is useful // for systematically categorizing metrics per-request, by using a // specific logger. statsd.makeChild = (name) => { const child = statsd.childClient(); // We can't use the prefix in clientOptions, // because it will be prepended to existing prefix. child.prefix = statsd.prefix + normalizeName(name) + '.'; // Attach normalizeName to make the childClient instance backwards-compatible // with the previously used StatsD instance child.normalizeName = normalizeName; return child; }; // Add a static utility method for stat name normalization statsd.normalizeName = normalizeName; return statsd; }
javascript
function makeStatsD(options, logger) { let statsd; const srvName = options._prefix ? options._prefix : normalizeName(options.name); const statsdOptions = { host: options.host, port: options.port, prefix: `${srvName}.`, suffix: '', globalize: false, cacheDns: false, mock: false }; // Batch metrics unless `batch` option is `false` if (typeof options.batch !== 'boolean' || options.batch) { options.batch = options.batch || {}; statsdOptions.maxBufferSize = options.batch.max_size || DEFAULT_MAX_BATCH_SIZE; statsdOptions.bufferFlushInterval = options.batch.max_delay || 1000; } if (options.type === 'log') { statsd = new LogStatsD(logger, srvName); } else { statsd = new StatsD(statsdOptions); } // Support creating sub-metric clients with a fixed prefix. This is useful // for systematically categorizing metrics per-request, by using a // specific logger. statsd.makeChild = (name) => { const child = statsd.childClient(); // We can't use the prefix in clientOptions, // because it will be prepended to existing prefix. child.prefix = statsd.prefix + normalizeName(name) + '.'; // Attach normalizeName to make the childClient instance backwards-compatible // with the previously used StatsD instance child.normalizeName = normalizeName; return child; }; // Add a static utility method for stat name normalization statsd.normalizeName = normalizeName; return statsd; }
[ "function", "makeStatsD", "(", "options", ",", "logger", ")", "{", "let", "statsd", ";", "const", "srvName", "=", "options", ".", "_prefix", "?", "options", ".", "_prefix", ":", "normalizeName", "(", "options", ".", "name", ")", ";", "const", "statsdOptions", "=", "{", "host", ":", "options", ".", "host", ",", "port", ":", "options", ".", "port", ",", "prefix", ":", "`", "${", "srvName", "}", "`", ",", "suffix", ":", "''", ",", "globalize", ":", "false", ",", "cacheDns", ":", "false", ",", "mock", ":", "false", "}", ";", "if", "(", "typeof", "options", ".", "batch", "!==", "'boolean'", "||", "options", ".", "batch", ")", "{", "options", ".", "batch", "=", "options", ".", "batch", "||", "{", "}", ";", "statsdOptions", ".", "maxBufferSize", "=", "options", ".", "batch", ".", "max_size", "||", "DEFAULT_MAX_BATCH_SIZE", ";", "statsdOptions", ".", "bufferFlushInterval", "=", "options", ".", "batch", ".", "max_delay", "||", "1000", ";", "}", "if", "(", "options", ".", "type", "===", "'log'", ")", "{", "statsd", "=", "new", "LogStatsD", "(", "logger", ",", "srvName", ")", ";", "}", "else", "{", "statsd", "=", "new", "StatsD", "(", "statsdOptions", ")", ";", "}", "statsd", ".", "makeChild", "=", "(", "name", ")", "=>", "{", "const", "child", "=", "statsd", ".", "childClient", "(", ")", ";", "child", ".", "prefix", "=", "statsd", ".", "prefix", "+", "normalizeName", "(", "name", ")", "+", "'.'", ";", "child", ".", "normalizeName", "=", "normalizeName", ";", "return", "child", ";", "}", ";", "statsd", ".", "normalizeName", "=", "normalizeName", ";", "return", "statsd", ";", "}" ]
Minimal StatsD wrapper
[ "Minimal", "StatsD", "wrapper" ]
c1188f540525d1662f0aab739804f2f9587b4ce1
https://github.com/wikimedia/service-runner/blob/c1188f540525d1662f0aab739804f2f9587b4ce1/lib/statsd.js#L68-L114
train
wikimedia/service-runner
lib/docker.js
promisedSpawn
function promisedSpawn(args, options) { options = options || {}; let promise = new P((resolve, reject) => { const argOpts = options.capture ? undefined : { stdio: 'inherit' }; let ret = ''; let err = ''; if (opts.verbose) { console.log(`# RUNNING: ${args.join(' ')}\n (in ${process.cwd()})`); } child = spawn('/usr/bin/env', args, argOpts); if (options.capture) { child.stdout.on('data', (data) => { ret += data.toString(); }); child.stderr.on('data', (data) => { err += data.toString(); }); } child.on('close', (code) => { child = undefined; ret = ret.trim(); if (ret === '') { ret = undefined; } if (code) { if (options.ignoreErr) { resolve(ret); } else { reject(new SpawnError(code, err.trim())); } } else { resolve(ret); } }); }); if (options.useErrHandler || options.errMessage) { promise = promise.catch((err) => { if (options.errMessage) { console.error(`ERROR: ${options.errMessage.split('\n').join('\nERROR: ')}`); } let msg = `ERROR: ${args.slice(0, 2).join(' ')} exited with code ${err.code}`; if (err.message) { msg += ` and message ${err.message}`; } console.error(msg); process.exit(err.code); }); } return promise; }
javascript
function promisedSpawn(args, options) { options = options || {}; let promise = new P((resolve, reject) => { const argOpts = options.capture ? undefined : { stdio: 'inherit' }; let ret = ''; let err = ''; if (opts.verbose) { console.log(`# RUNNING: ${args.join(' ')}\n (in ${process.cwd()})`); } child = spawn('/usr/bin/env', args, argOpts); if (options.capture) { child.stdout.on('data', (data) => { ret += data.toString(); }); child.stderr.on('data', (data) => { err += data.toString(); }); } child.on('close', (code) => { child = undefined; ret = ret.trim(); if (ret === '') { ret = undefined; } if (code) { if (options.ignoreErr) { resolve(ret); } else { reject(new SpawnError(code, err.trim())); } } else { resolve(ret); } }); }); if (options.useErrHandler || options.errMessage) { promise = promise.catch((err) => { if (options.errMessage) { console.error(`ERROR: ${options.errMessage.split('\n').join('\nERROR: ')}`); } let msg = `ERROR: ${args.slice(0, 2).join(' ')} exited with code ${err.code}`; if (err.message) { msg += ` and message ${err.message}`; } console.error(msg); process.exit(err.code); }); } return promise; }
[ "function", "promisedSpawn", "(", "args", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "let", "promise", "=", "new", "P", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "argOpts", "=", "options", ".", "capture", "?", "undefined", ":", "{", "stdio", ":", "'inherit'", "}", ";", "let", "ret", "=", "''", ";", "let", "err", "=", "''", ";", "if", "(", "opts", ".", "verbose", ")", "{", "console", ".", "log", "(", "`", "${", "args", ".", "join", "(", "' '", ")", "}", "\\n", "${", "process", ".", "cwd", "(", ")", "}", "`", ")", ";", "}", "child", "=", "spawn", "(", "'/usr/bin/env'", ",", "args", ",", "argOpts", ")", ";", "if", "(", "options", ".", "capture", ")", "{", "child", ".", "stdout", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "ret", "+=", "data", ".", "toString", "(", ")", ";", "}", ")", ";", "child", ".", "stderr", ".", "on", "(", "'data'", ",", "(", "data", ")", "=>", "{", "err", "+=", "data", ".", "toString", "(", ")", ";", "}", ")", ";", "}", "child", ".", "on", "(", "'close'", ",", "(", "code", ")", "=>", "{", "child", "=", "undefined", ";", "ret", "=", "ret", ".", "trim", "(", ")", ";", "if", "(", "ret", "===", "''", ")", "{", "ret", "=", "undefined", ";", "}", "if", "(", "code", ")", "{", "if", "(", "options", ".", "ignoreErr", ")", "{", "resolve", "(", "ret", ")", ";", "}", "else", "{", "reject", "(", "new", "SpawnError", "(", "code", ",", "err", ".", "trim", "(", ")", ")", ")", ";", "}", "}", "else", "{", "resolve", "(", "ret", ")", ";", "}", "}", ")", ";", "}", ")", ";", "if", "(", "options", ".", "useErrHandler", "||", "options", ".", "errMessage", ")", "{", "promise", "=", "promise", ".", "catch", "(", "(", "err", ")", "=>", "{", "if", "(", "options", ".", "errMessage", ")", "{", "console", ".", "error", "(", "`", "${", "options", ".", "errMessage", ".", "split", "(", "'\\n'", ")", ".", "\\n", "join", "}", "`", ")", ";", "}", "(", "'\\nERROR: '", ")", "\\n", "let", "msg", "=", "`", "${", "args", ".", "slice", "(", "0", ",", "2", ")", ".", "join", "(", "' '", ")", "}", "${", "err", ".", "code", "}", "`", ";", "if", "(", "err", ".", "message", ")", "{", "msg", "+=", "`", "${", "err", ".", "message", "}", "`", ";", "}", "}", ")", ";", "}", "console", ".", "error", "(", "msg", ")", ";", "}" ]
Wraps a child process spawn in a promise which resolves when the child process exists. @param {Array} args the command and its arguments to run (uses /usr/bin/env) @param {Object} options various execution options; attributes: - {Boolean} capture whether to capture stdout and return its contents - {Boolean} useErrHandler whether to use a generic error handler on failure - {string} errMessage additional error message to emit - {Boolean} ignoreErr whether to ignore the error code entirely @return {Promise} the promise which is fulfilled once the child exists
[ "Wraps", "a", "child", "process", "spawn", "in", "a", "promise", "which", "resolves", "when", "the", "child", "process", "exists", "." ]
c1188f540525d1662f0aab739804f2f9587b4ce1
https://github.com/wikimedia/service-runner/blob/c1188f540525d1662f0aab739804f2f9587b4ce1/lib/docker.js#L51-L105
train
wikimedia/service-runner
lib/docker.js
startContainer
function startContainer(args, hidePorts) { const cmd = ['docker', 'run', '--name', name, '--rm']; // add the extra args as well if (args && Array.isArray(args)) { Array.prototype.push.apply(cmd, args); } if (!hidePorts) { // list all of the ports defined in the config file config.services.forEach((srv) => { srv.conf = srv.conf || {}; srv.conf.port = srv.conf.port || 8888; cmd.push('-p', `${srv.conf.port}:${srv.conf.port}`); }); } // append the image name to create a container from cmd.push(imgName); // ok, start the container return promisedSpawn(cmd, { useErrHandler: true }); }
javascript
function startContainer(args, hidePorts) { const cmd = ['docker', 'run', '--name', name, '--rm']; // add the extra args as well if (args && Array.isArray(args)) { Array.prototype.push.apply(cmd, args); } if (!hidePorts) { // list all of the ports defined in the config file config.services.forEach((srv) => { srv.conf = srv.conf || {}; srv.conf.port = srv.conf.port || 8888; cmd.push('-p', `${srv.conf.port}:${srv.conf.port}`); }); } // append the image name to create a container from cmd.push(imgName); // ok, start the container return promisedSpawn(cmd, { useErrHandler: true }); }
[ "function", "startContainer", "(", "args", ",", "hidePorts", ")", "{", "const", "cmd", "=", "[", "'docker'", ",", "'run'", ",", "'--name'", ",", "name", ",", "'--rm'", "]", ";", "if", "(", "args", "&&", "Array", ".", "isArray", "(", "args", ")", ")", "{", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "cmd", ",", "args", ")", ";", "}", "if", "(", "!", "hidePorts", ")", "{", "config", ".", "services", ".", "forEach", "(", "(", "srv", ")", "=>", "{", "srv", ".", "conf", "=", "srv", ".", "conf", "||", "{", "}", ";", "srv", ".", "conf", ".", "port", "=", "srv", ".", "conf", ".", "port", "||", "8888", ";", "cmd", ".", "push", "(", "'-p'", ",", "`", "${", "srv", ".", "conf", ".", "port", "}", "${", "srv", ".", "conf", ".", "port", "}", "`", ")", ";", "}", ")", ";", "}", "cmd", ".", "push", "(", "imgName", ")", ";", "return", "promisedSpawn", "(", "cmd", ",", "{", "useErrHandler", ":", "true", "}", ")", ";", "}" ]
Starts the container and returns once it has finished executing @param {Array} args the array of extra parameters to pass, optional @param {boolean} hidePorts whether to keep the ports hidden inside the container, optional @return {Promise} the promise starting the container
[ "Starts", "the", "container", "and", "returns", "once", "it", "has", "finished", "executing" ]
c1188f540525d1662f0aab739804f2f9587b4ce1
https://github.com/wikimedia/service-runner/blob/c1188f540525d1662f0aab739804f2f9587b4ce1/lib/docker.js#L279-L303
train
wikimedia/service-runner
lib/docker.js
getUid
function getUid() { if (opts.deploy) { // get the deploy repo location return promisedSpawn( ['git', 'config', 'deploy.dir'], { capture: true, errMessage: 'You must set the location of the deploy repo!\n' + 'Use git config deploy.dir /full/path/to/deploy/dir' } ).then((dir) => { opts.dir = dir; // make sure that the dir exists and it is a git repo return fs.statAsync(`${dir}/.git`); }).then((stat) => { opts.uid = stat.uid; opts.gid = stat.gid; }).catch(() => { console.error(`ERROR: The deploy repo dir ${opts.dir} does not exist or is not a git repo!`); process.exit(3); }); } // get the uid/gid from statting package.json return fs.statAsync('package.json') .then((stat) => { opts.uid = stat.uid; opts.gid = stat.gid; }).catch(() => { console.error('ERROR: package.json does not exist!'); process.exit(4); }); }
javascript
function getUid() { if (opts.deploy) { // get the deploy repo location return promisedSpawn( ['git', 'config', 'deploy.dir'], { capture: true, errMessage: 'You must set the location of the deploy repo!\n' + 'Use git config deploy.dir /full/path/to/deploy/dir' } ).then((dir) => { opts.dir = dir; // make sure that the dir exists and it is a git repo return fs.statAsync(`${dir}/.git`); }).then((stat) => { opts.uid = stat.uid; opts.gid = stat.gid; }).catch(() => { console.error(`ERROR: The deploy repo dir ${opts.dir} does not exist or is not a git repo!`); process.exit(3); }); } // get the uid/gid from statting package.json return fs.statAsync('package.json') .then((stat) => { opts.uid = stat.uid; opts.gid = stat.gid; }).catch(() => { console.error('ERROR: package.json does not exist!'); process.exit(4); }); }
[ "function", "getUid", "(", ")", "{", "if", "(", "opts", ".", "deploy", ")", "{", "return", "promisedSpawn", "(", "[", "'git'", ",", "'config'", ",", "'deploy.dir'", "]", ",", "{", "capture", ":", "true", ",", "errMessage", ":", "'You must set the location of the deploy repo!\\n'", "+", "\\n", "}", ")", ".", "'Use git config deploy.dir /full/path/to/deploy/dir'", "then", ".", "(", "(", "dir", ")", "=>", "{", "opts", ".", "dir", "=", "dir", ";", "return", "fs", ".", "statAsync", "(", "`", "${", "dir", "}", "`", ")", ";", "}", ")", "then", ".", "(", "(", "stat", ")", "=>", "{", "opts", ".", "uid", "=", "stat", ".", "uid", ";", "opts", ".", "gid", "=", "stat", ".", "gid", ";", "}", ")", "catch", ";", "}", "(", "(", ")", "=>", "{", "console", ".", "error", "(", "`", "${", "opts", ".", "dir", "}", "`", ")", ";", "process", ".", "exit", "(", "3", ")", ";", "}", ")", "}" ]
Determines the UID and GID to run under in the container @return {Promise} a promise resolving when the check is done
[ "Determines", "the", "UID", "and", "GID", "to", "run", "under", "in", "the", "container" ]
c1188f540525d1662f0aab739804f2f9587b4ce1
https://github.com/wikimedia/service-runner/blob/c1188f540525d1662f0aab739804f2f9587b4ce1/lib/docker.js#L522-L555
train
shopgate/pwa
libraries/tracking-core/helpers/optOut.js
setLocalStorage
function setLocalStorage(optOutState) { if (!(localStorage && localStorage.setItem)) { return null; } if (typeof optOutState !== 'boolean') { console.warn('setCookie for outOut invalid param optOutState. Param must be boolean'); return null; } try { localStorage.setItem(disableStr, optOutState); } catch (e) { return null; } return optOutState; }
javascript
function setLocalStorage(optOutState) { if (!(localStorage && localStorage.setItem)) { return null; } if (typeof optOutState !== 'boolean') { console.warn('setCookie for outOut invalid param optOutState. Param must be boolean'); return null; } try { localStorage.setItem(disableStr, optOutState); } catch (e) { return null; } return optOutState; }
[ "function", "setLocalStorage", "(", "optOutState", ")", "{", "if", "(", "!", "(", "localStorage", "&&", "localStorage", ".", "setItem", ")", ")", "{", "return", "null", ";", "}", "if", "(", "typeof", "optOutState", "!==", "'boolean'", ")", "{", "console", ".", "warn", "(", "'setCookie for outOut invalid param optOutState. Param must be boolean'", ")", ";", "return", "null", ";", "}", "try", "{", "localStorage", ".", "setItem", "(", "disableStr", ",", "optOutState", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "null", ";", "}", "return", "optOutState", ";", "}" ]
Sets opt out state to localStorage @param {boolean} optOutState true - user opted out of tracking, false - user did not opted out @private @returns {boolean|null} Info about the success
[ "Sets", "opt", "out", "state", "to", "localStorage" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/optOut.js#L9-L26
train
shopgate/pwa
libraries/tracking-core/helpers/optOut.js
getLocalStorage
function getLocalStorage() { if (!(localStorage && localStorage.getItem)) { return null; } let state = localStorage.getItem(disableStr); if (state === 'false') { state = false; } else if (state === 'true') { state = true; } return state; }
javascript
function getLocalStorage() { if (!(localStorage && localStorage.getItem)) { return null; } let state = localStorage.getItem(disableStr); if (state === 'false') { state = false; } else if (state === 'true') { state = true; } return state; }
[ "function", "getLocalStorage", "(", ")", "{", "if", "(", "!", "(", "localStorage", "&&", "localStorage", ".", "getItem", ")", ")", "{", "return", "null", ";", "}", "let", "state", "=", "localStorage", ".", "getItem", "(", "disableStr", ")", ";", "if", "(", "state", "===", "'false'", ")", "{", "state", "=", "false", ";", "}", "else", "if", "(", "state", "===", "'true'", ")", "{", "state", "=", "true", ";", "}", "return", "state", ";", "}" ]
Gets optOut state from localStorage @private @returns {boolean|null} Opt out state in the localstorage
[ "Gets", "optOut", "state", "from", "localStorage" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/optOut.js#L33-L47
train
shopgate/pwa
libraries/tracking-core/helpers/optOut.js
setCookie
function setCookie(optOutState) { switch (optOutState) { case true: document.cookie = `${disableStr}=true; expires=Thu, 18 Jan 2038 03:13:59 UTC; path=/`; window[disableStr] = true; break; case false: document.cookie = `${disableStr}=false; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/`; window[disableStr] = false; break; default: console.warn('setCookie for outOut invalid param optOutState. Param must be boolean'); return false; } return true; }
javascript
function setCookie(optOutState) { switch (optOutState) { case true: document.cookie = `${disableStr}=true; expires=Thu, 18 Jan 2038 03:13:59 UTC; path=/`; window[disableStr] = true; break; case false: document.cookie = `${disableStr}=false; expires=Thu, 01 Jan 1970 00:00:01 UTC; path=/`; window[disableStr] = false; break; default: console.warn('setCookie for outOut invalid param optOutState. Param must be boolean'); return false; } return true; }
[ "function", "setCookie", "(", "optOutState", ")", "{", "switch", "(", "optOutState", ")", "{", "case", "true", ":", "document", ".", "cookie", "=", "`", "${", "disableStr", "}", "`", ";", "window", "[", "disableStr", "]", "=", "true", ";", "break", ";", "case", "false", ":", "document", ".", "cookie", "=", "`", "${", "disableStr", "}", "`", ";", "window", "[", "disableStr", "]", "=", "false", ";", "break", ";", "default", ":", "console", ".", "warn", "(", "'setCookie for outOut invalid param optOutState. Param must be boolean'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
Sets opt out cookie @param {boolean} optOutState true - user opted out of tracking, false - user did not opted out @private @returns {boolean} Info about the success
[ "Sets", "opt", "out", "cookie" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/optOut.js#L55-L73
train
shopgate/pwa
libraries/tracking-core/helpers/optOut.js
setOptOut
function setOptOut(optOutParam) { window[disableStr] = optOutParam; setCookie(optOutParam); setLocalStorage(optOutParam); return optOutParam; }
javascript
function setOptOut(optOutParam) { window[disableStr] = optOutParam; setCookie(optOutParam); setLocalStorage(optOutParam); return optOutParam; }
[ "function", "setOptOut", "(", "optOutParam", ")", "{", "window", "[", "disableStr", "]", "=", "optOutParam", ";", "setCookie", "(", "optOutParam", ")", ";", "setLocalStorage", "(", "optOutParam", ")", ";", "return", "optOutParam", ";", "}" ]
Set global + storages @param {boolean} optOutParam If false -> revert the opt out (enable tracking) @private @returns {boolean} optOut State which was set
[ "Set", "global", "+", "storages" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/optOut.js#L81-L87
train
shopgate/pwa
libraries/tracking-core/helpers/optOut.js
getCookie
function getCookie() { if (document.cookie.indexOf(`${disableStr}=true`) > -1) { return true; } else if (document.cookie.indexOf(`${disableStr}=false`) > -1) { return false; } return null; }
javascript
function getCookie() { if (document.cookie.indexOf(`${disableStr}=true`) > -1) { return true; } else if (document.cookie.indexOf(`${disableStr}=false`) > -1) { return false; } return null; }
[ "function", "getCookie", "(", ")", "{", "if", "(", "document", ".", "cookie", ".", "indexOf", "(", "`", "${", "disableStr", "}", "`", ")", ">", "-", "1", ")", "{", "return", "true", ";", "}", "else", "if", "(", "document", ".", "cookie", ".", "indexOf", "(", "`", "${", "disableStr", "}", "`", ")", ">", "-", "1", ")", "{", "return", "false", ";", "}", "return", "null", ";", "}" ]
Gets optout state from cookie @private @returns {boolean|null} OptOut state from the cookie
[ "Gets", "optout", "state", "from", "cookie" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/optOut.js#L113-L121
train
shopgate/pwa
libraries/tracking-core/helpers/optOut.js
isOptOut
function isOptOut() { // Check cookie first let optOutState = getCookie(); // No cookie info, check localStorage if (optOutState === null) { optOutState = getLocalStorage(); } // No localStorage, we get default value if (optOutState === null || typeof optOutState === 'undefined') { optOutState = false; } // Set global for the environment window[disableStr] = optOutState; return optOutState; }
javascript
function isOptOut() { // Check cookie first let optOutState = getCookie(); // No cookie info, check localStorage if (optOutState === null) { optOutState = getLocalStorage(); } // No localStorage, we get default value if (optOutState === null || typeof optOutState === 'undefined') { optOutState = false; } // Set global for the environment window[disableStr] = optOutState; return optOutState; }
[ "function", "isOptOut", "(", ")", "{", "let", "optOutState", "=", "getCookie", "(", ")", ";", "if", "(", "optOutState", "===", "null", ")", "{", "optOutState", "=", "getLocalStorage", "(", ")", ";", "}", "if", "(", "optOutState", "===", "null", "||", "typeof", "optOutState", "===", "'undefined'", ")", "{", "optOutState", "=", "false", ";", "}", "window", "[", "disableStr", "]", "=", "optOutState", ";", "return", "optOutState", ";", "}" ]
Check if the opt-out state is set Cookie is privileged. @returns {boolean} Information if the user opt out
[ "Check", "if", "the", "opt", "-", "out", "state", "is", "set" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/optOut.js#L130-L148
train
shopgate/pwa
libraries/common/store/index.js
getInitialState
function getInitialState() { if (!window.localStorage) { return undefined; } const storedState = window.localStorage.getItem(storeKey); if (!storedState) { return undefined; } const normalisedState = storedState.replace(new RegExp('"isFetching":true', 'g'), '"isFetching":false'); return JSON.parse(normalisedState); }
javascript
function getInitialState() { if (!window.localStorage) { return undefined; } const storedState = window.localStorage.getItem(storeKey); if (!storedState) { return undefined; } const normalisedState = storedState.replace(new RegExp('"isFetching":true', 'g'), '"isFetching":false'); return JSON.parse(normalisedState); }
[ "function", "getInitialState", "(", ")", "{", "if", "(", "!", "window", ".", "localStorage", ")", "{", "return", "undefined", ";", "}", "const", "storedState", "=", "window", ".", "localStorage", ".", "getItem", "(", "storeKey", ")", ";", "if", "(", "!", "storedState", ")", "{", "return", "undefined", ";", "}", "const", "normalisedState", "=", "storedState", ".", "replace", "(", "new", "RegExp", "(", "'\"isFetching\":true'", ",", "'g'", ")", ",", "'\"isFetching\":false'", ")", ";", "return", "JSON", ".", "parse", "(", "normalisedState", ")", ";", "}" ]
Returns a normalised initialState from the localstorage. @returns {Object}
[ "Returns", "a", "normalised", "initialState", "from", "the", "localstorage", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/common/store/index.js#L24-L37
train
shopgate/pwa
scripts/build-changelog.js
parseVersion
function parseVersion(v) { const [ , // Full match of no interest. major = null, sub = null, minor = null, ] = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-.*)?$/.exec(v); if (major === null || sub === null || minor === null) { const err = new Error(`Invalid version string (${v})!`); logger.error(err); throw err; } return { major, sub, minor, }; }
javascript
function parseVersion(v) { const [ , // Full match of no interest. major = null, sub = null, minor = null, ] = /^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-.*)?$/.exec(v); if (major === null || sub === null || minor === null) { const err = new Error(`Invalid version string (${v})!`); logger.error(err); throw err; } return { major, sub, minor, }; }
[ "function", "parseVersion", "(", "v", ")", "{", "const", "[", ",", "major", "=", "null", ",", "sub", "=", "null", ",", "minor", "=", "null", ",", "]", "=", "/", "^v?(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(-.*)?$", "/", ".", "exec", "(", "v", ")", ";", "if", "(", "major", "===", "null", "||", "sub", "===", "null", "||", "minor", "===", "null", ")", "{", "const", "err", "=", "new", "Error", "(", "`", "${", "v", "}", "`", ")", ";", "logger", ".", "error", "(", "err", ")", ";", "throw", "err", ";", "}", "return", "{", "major", ",", "sub", ",", "minor", ",", "}", ";", "}" ]
Parses a version into its components without prerelease information. @param {string} v The version to be parsed @return {{sub: number, major: number, minor: number}}
[ "Parses", "a", "version", "into", "its", "components", "without", "prerelease", "information", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/scripts/build-changelog.js#L94-L112
train
shopgate/pwa
scripts/build-changelog.js
run
async function run() { try { // Find last release: Get tags, filter out wrong tags and pre-releases, then take last one. const { stdout } = // get last filtered tag, sorted by version numbers in ascending order await exec(`git tag | grep '${tagFrom}' | grep -Ev '-' | sort -V | tail -1`); const prevTag = stdout.trim(); const nextVersion = parseVersion(argv[releaseNameParam]); // Normalize the given "release-name" for the tile (strip out pre-release information). const nextVersionString = `v${nextVersion.major}.${nextVersion.sub}.${nextVersion.minor}`; // Read previous changelog to extend it (remove ending line feeds -> added back in later) const changelogContent = fs.readFileSync('CHANGELOG.md', { encoding: 'utf8' }).trimRight(); const config = lernaConfiguration.load(); // This causes the "Unreleased" title to be replaced by a version that links to a github diff. config.nextVersion = `[${ nextVersionString }](https://github.com/shopgate/pwa/compare/${prevTag}...${nextVersionString})`; // Skip creation if the "nextVersion" title is already present. if (changelogContent.includes(config.nextVersion)) { // Output the already existing data when already is there already. logger.log(changelogContent); return; } const changelog = new Changelog(config); // The "release-name" param is not supposed to be used here. Instead use "HEAD". const latestChanges = await changelog.createMarkdown({ tagFrom: prevTag, tagTo, }); // Add changes to the top of the main changelog let newChangelog = '# Changelog\n'; if (appendPreviousChangelog) { newChangelog = changelogContent; } if (latestChanges.trim().length > 0) { newChangelog = newChangelog.replace( '# Changelog\n', `# Changelog\n\n${latestChanges.trim()}\n` ); if (tagTo !== 'HEAD') { newChangelog = newChangelog.replace( `## ${tagTo} `, `## ${config.nextVersion} ` ); } } // Print the output for the bash/makefile to read logger.log(newChangelog); } catch (error) { throw error; } }
javascript
async function run() { try { // Find last release: Get tags, filter out wrong tags and pre-releases, then take last one. const { stdout } = // get last filtered tag, sorted by version numbers in ascending order await exec(`git tag | grep '${tagFrom}' | grep -Ev '-' | sort -V | tail -1`); const prevTag = stdout.trim(); const nextVersion = parseVersion(argv[releaseNameParam]); // Normalize the given "release-name" for the tile (strip out pre-release information). const nextVersionString = `v${nextVersion.major}.${nextVersion.sub}.${nextVersion.minor}`; // Read previous changelog to extend it (remove ending line feeds -> added back in later) const changelogContent = fs.readFileSync('CHANGELOG.md', { encoding: 'utf8' }).trimRight(); const config = lernaConfiguration.load(); // This causes the "Unreleased" title to be replaced by a version that links to a github diff. config.nextVersion = `[${ nextVersionString }](https://github.com/shopgate/pwa/compare/${prevTag}...${nextVersionString})`; // Skip creation if the "nextVersion" title is already present. if (changelogContent.includes(config.nextVersion)) { // Output the already existing data when already is there already. logger.log(changelogContent); return; } const changelog = new Changelog(config); // The "release-name" param is not supposed to be used here. Instead use "HEAD". const latestChanges = await changelog.createMarkdown({ tagFrom: prevTag, tagTo, }); // Add changes to the top of the main changelog let newChangelog = '# Changelog\n'; if (appendPreviousChangelog) { newChangelog = changelogContent; } if (latestChanges.trim().length > 0) { newChangelog = newChangelog.replace( '# Changelog\n', `# Changelog\n\n${latestChanges.trim()}\n` ); if (tagTo !== 'HEAD') { newChangelog = newChangelog.replace( `## ${tagTo} `, `## ${config.nextVersion} ` ); } } // Print the output for the bash/makefile to read logger.log(newChangelog); } catch (error) { throw error; } }
[ "async", "function", "run", "(", ")", "{", "try", "{", "const", "{", "stdout", "}", "=", "await", "exec", "(", "`", "${", "tagFrom", "}", "`", ")", ";", "const", "prevTag", "=", "stdout", ".", "trim", "(", ")", ";", "const", "nextVersion", "=", "parseVersion", "(", "argv", "[", "releaseNameParam", "]", ")", ";", "const", "nextVersionString", "=", "`", "${", "nextVersion", ".", "major", "}", "${", "nextVersion", ".", "sub", "}", "${", "nextVersion", ".", "minor", "}", "`", ";", "const", "changelogContent", "=", "fs", ".", "readFileSync", "(", "'CHANGELOG.md'", ",", "{", "encoding", ":", "'utf8'", "}", ")", ".", "trimRight", "(", ")", ";", "const", "config", "=", "lernaConfiguration", ".", "load", "(", ")", ";", "config", ".", "nextVersion", "=", "`", "${", "nextVersionString", "}", "${", "prevTag", "}", "${", "nextVersionString", "}", "`", ";", "if", "(", "changelogContent", ".", "includes", "(", "config", ".", "nextVersion", ")", ")", "{", "logger", ".", "log", "(", "changelogContent", ")", ";", "return", ";", "}", "const", "changelog", "=", "new", "Changelog", "(", "config", ")", ";", "const", "latestChanges", "=", "await", "changelog", ".", "createMarkdown", "(", "{", "tagFrom", ":", "prevTag", ",", "tagTo", ",", "}", ")", ";", "let", "newChangelog", "=", "'# Changelog\\n'", ";", "\\n", "if", "(", "appendPreviousChangelog", ")", "{", "newChangelog", "=", "changelogContent", ";", "}", "if", "(", "latestChanges", ".", "trim", "(", ")", ".", "length", ">", "0", ")", "{", "newChangelog", "=", "newChangelog", ".", "replace", "(", "'# Changelog\\n'", ",", "\\n", ")", ";", "`", "\\n", "\\n", "${", "latestChanges", ".", "trim", "(", ")", "}", "\\n", "`", "}", "}", "if", "(", "tagTo", "!==", "'HEAD'", ")", "{", "newChangelog", "=", "newChangelog", ".", "replace", "(", "`", "${", "tagTo", "}", "`", ",", "`", "${", "config", ".", "nextVersion", "}", "`", ")", ";", "}", "}" ]
Main async method
[ "Main", "async", "method" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/scripts/build-changelog.js#L189-L248
train
shopgate/pwa
scripts/sync-remotes.js
synchRepo
async function synchRepo(remote, pathname) { const cmd = `git subtree push --prefix=${pathname} ${remote} master`; try { await exec(cmd); logger.log(`Synched master of ${pathname}`); } catch (error) { throw error; } }
javascript
async function synchRepo(remote, pathname) { const cmd = `git subtree push --prefix=${pathname} ${remote} master`; try { await exec(cmd); logger.log(`Synched master of ${pathname}`); } catch (error) { throw error; } }
[ "async", "function", "synchRepo", "(", "remote", ",", "pathname", ")", "{", "const", "cmd", "=", "`", "${", "pathname", "}", "${", "remote", "}", "`", ";", "try", "{", "await", "exec", "(", "cmd", ")", ";", "logger", ".", "log", "(", "`", "${", "pathname", "}", "`", ")", ";", "}", "catch", "(", "error", ")", "{", "throw", "error", ";", "}", "}" ]
Synch the current master with the remote @param {string} remote The remote name. @param {string} pathname The local pathname.
[ "Synch", "the", "current", "master", "with", "the", "remote" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/scripts/sync-remotes.js#L13-L22
train
shopgate/pwa
libraries/commerce/product/subscriptions/index.js
product
function product(subscribe) { const processProduct$ = productReceived$.merge(cachedProductReceived$); subscribe(productWillEnter$, ({ action, dispatch }) => { const { productId } = action.route.params; const { productId: variantId } = action.route.state; const id = variantId || hex2bin(productId); dispatch(fetchProduct(id)); dispatch(fetchProductDescription(id)); dispatch(fetchProductProperties(id)); dispatch(fetchProductImages(id, productImageFormats.getAllUniqueFormats())); dispatch(fetchProductShipping(id)); }); subscribe(processProduct$, ({ action, dispatch }) => { const { id, flags = { hasVariants: false, hasOptions: false, }, baseProductId, } = action.productData; if (baseProductId) { dispatch(fetchProduct(baseProductId)); dispatch(fetchProductImages(baseProductId, productImageFormats.getAllUniqueFormats())); } if (flags.hasVariants) { dispatch(fetchProductVariants(id)); } if (flags.hasOptions) { dispatch(fetchProductOptions(id)); } }); const receivedVisibleProductDebounced$ = receivedVisibleProduct$.debounceTime(500); /** Refresh product data after getting cache version for PDP */ subscribe(receivedVisibleProductDebounced$, ({ action, dispatch }) => { const { id } = action.productData; dispatch(fetchProduct(id, true)); }); /** Visible product is no more available */ subscribe(visibleProductNotFound$, ({ action, dispatch }) => { dispatch(showModal({ confirm: null, dismiss: 'modal.ok', title: 'modal.title_error', message: 'product.no_more_found', params: { name: action.productData.name, }, })); dispatch(historyPop()); dispatch(expireProductById(action.productData.id)); }); subscribe(productRelationsReceived$, ({ dispatch, getState, action }) => { const { hash } = action; const productIds = getProductRelationsByHash(hash)(getState()); dispatch(fetchProductsById(productIds)); }); /** * Expire products after checkout, fetch updated data */ subscribe(checkoutSucceeded$, ({ dispatch, action }) => { const { products } = action; const productIds = products.map(p => p.product.id); productIds.forEach(id => dispatch(expireProductById(id))); dispatch(fetchProductsById(productIds)); }); }
javascript
function product(subscribe) { const processProduct$ = productReceived$.merge(cachedProductReceived$); subscribe(productWillEnter$, ({ action, dispatch }) => { const { productId } = action.route.params; const { productId: variantId } = action.route.state; const id = variantId || hex2bin(productId); dispatch(fetchProduct(id)); dispatch(fetchProductDescription(id)); dispatch(fetchProductProperties(id)); dispatch(fetchProductImages(id, productImageFormats.getAllUniqueFormats())); dispatch(fetchProductShipping(id)); }); subscribe(processProduct$, ({ action, dispatch }) => { const { id, flags = { hasVariants: false, hasOptions: false, }, baseProductId, } = action.productData; if (baseProductId) { dispatch(fetchProduct(baseProductId)); dispatch(fetchProductImages(baseProductId, productImageFormats.getAllUniqueFormats())); } if (flags.hasVariants) { dispatch(fetchProductVariants(id)); } if (flags.hasOptions) { dispatch(fetchProductOptions(id)); } }); const receivedVisibleProductDebounced$ = receivedVisibleProduct$.debounceTime(500); /** Refresh product data after getting cache version for PDP */ subscribe(receivedVisibleProductDebounced$, ({ action, dispatch }) => { const { id } = action.productData; dispatch(fetchProduct(id, true)); }); /** Visible product is no more available */ subscribe(visibleProductNotFound$, ({ action, dispatch }) => { dispatch(showModal({ confirm: null, dismiss: 'modal.ok', title: 'modal.title_error', message: 'product.no_more_found', params: { name: action.productData.name, }, })); dispatch(historyPop()); dispatch(expireProductById(action.productData.id)); }); subscribe(productRelationsReceived$, ({ dispatch, getState, action }) => { const { hash } = action; const productIds = getProductRelationsByHash(hash)(getState()); dispatch(fetchProductsById(productIds)); }); /** * Expire products after checkout, fetch updated data */ subscribe(checkoutSucceeded$, ({ dispatch, action }) => { const { products } = action; const productIds = products.map(p => p.product.id); productIds.forEach(id => dispatch(expireProductById(id))); dispatch(fetchProductsById(productIds)); }); }
[ "function", "product", "(", "subscribe", ")", "{", "const", "processProduct$", "=", "productReceived$", ".", "merge", "(", "cachedProductReceived$", ")", ";", "subscribe", "(", "productWillEnter$", ",", "(", "{", "action", ",", "dispatch", "}", ")", "=>", "{", "const", "{", "productId", "}", "=", "action", ".", "route", ".", "params", ";", "const", "{", "productId", ":", "variantId", "}", "=", "action", ".", "route", ".", "state", ";", "const", "id", "=", "variantId", "||", "hex2bin", "(", "productId", ")", ";", "dispatch", "(", "fetchProduct", "(", "id", ")", ")", ";", "dispatch", "(", "fetchProductDescription", "(", "id", ")", ")", ";", "dispatch", "(", "fetchProductProperties", "(", "id", ")", ")", ";", "dispatch", "(", "fetchProductImages", "(", "id", ",", "productImageFormats", ".", "getAllUniqueFormats", "(", ")", ")", ")", ";", "dispatch", "(", "fetchProductShipping", "(", "id", ")", ")", ";", "}", ")", ";", "subscribe", "(", "processProduct$", ",", "(", "{", "action", ",", "dispatch", "}", ")", "=>", "{", "const", "{", "id", ",", "flags", "=", "{", "hasVariants", ":", "false", ",", "hasOptions", ":", "false", ",", "}", ",", "baseProductId", ",", "}", "=", "action", ".", "productData", ";", "if", "(", "baseProductId", ")", "{", "dispatch", "(", "fetchProduct", "(", "baseProductId", ")", ")", ";", "dispatch", "(", "fetchProductImages", "(", "baseProductId", ",", "productImageFormats", ".", "getAllUniqueFormats", "(", ")", ")", ")", ";", "}", "if", "(", "flags", ".", "hasVariants", ")", "{", "dispatch", "(", "fetchProductVariants", "(", "id", ")", ")", ";", "}", "if", "(", "flags", ".", "hasOptions", ")", "{", "dispatch", "(", "fetchProductOptions", "(", "id", ")", ")", ";", "}", "}", ")", ";", "const", "receivedVisibleProductDebounced$", "=", "receivedVisibleProduct$", ".", "debounceTime", "(", "500", ")", ";", "subscribe", "(", "receivedVisibleProductDebounced$", ",", "(", "{", "action", ",", "dispatch", "}", ")", "=>", "{", "const", "{", "id", "}", "=", "action", ".", "productData", ";", "dispatch", "(", "fetchProduct", "(", "id", ",", "true", ")", ")", ";", "}", ")", ";", "subscribe", "(", "visibleProductNotFound$", ",", "(", "{", "action", ",", "dispatch", "}", ")", "=>", "{", "dispatch", "(", "showModal", "(", "{", "confirm", ":", "null", ",", "dismiss", ":", "'modal.ok'", ",", "title", ":", "'modal.title_error'", ",", "message", ":", "'product.no_more_found'", ",", "params", ":", "{", "name", ":", "action", ".", "productData", ".", "name", ",", "}", ",", "}", ")", ")", ";", "dispatch", "(", "historyPop", "(", ")", ")", ";", "dispatch", "(", "expireProductById", "(", "action", ".", "productData", ".", "id", ")", ")", ";", "}", ")", ";", "subscribe", "(", "productRelationsReceived$", ",", "(", "{", "dispatch", ",", "getState", ",", "action", "}", ")", "=>", "{", "const", "{", "hash", "}", "=", "action", ";", "const", "productIds", "=", "getProductRelationsByHash", "(", "hash", ")", "(", "getState", "(", ")", ")", ";", "dispatch", "(", "fetchProductsById", "(", "productIds", ")", ")", ";", "}", ")", ";", "subscribe", "(", "checkoutSucceeded$", ",", "(", "{", "dispatch", ",", "action", "}", ")", "=>", "{", "const", "{", "products", "}", "=", "action", ";", "const", "productIds", "=", "products", ".", "map", "(", "p", "=>", "p", ".", "product", ".", "id", ")", ";", "productIds", ".", "forEach", "(", "id", "=>", "dispatch", "(", "expireProductById", "(", "id", ")", ")", ")", ";", "dispatch", "(", "fetchProductsById", "(", "productIds", ")", ")", ";", "}", ")", ";", "}" ]
Product subscriptions. @param {Function} subscribe The subscribe function.
[ "Product", "subscriptions", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/commerce/product/subscriptions/index.js#L29-L108
train
shopgate/pwa
libraries/tracking-core/helpers/urlMapping.js
sgTrackingUrlMapper
function sgTrackingUrlMapper(url, data) { // In our development system urls start with /php/shopgate/ always const developmentPath = '/php/shopgate/'; const appRegex = /sg_app_resources\/[0-9]*\//; // Build regex that will remove all blacklisted paramters let regex = ''; urlParameterBlacklist.forEach((entry) => { regex += `((\\?|^){0,1}(${entry}=.*?(&|$)))`; regex += '|'; }); const params = url.indexOf('?') !== -1 ? url.split('?')[1] : ''; let urlParams = params.replace(new RegExp(regex, 'g'), ''); urlParams = urlParams === '' ? '' : `?${urlParams.replace(/&$/, '')}`; // Get rid of hash and app urls let urlPath = url.split('?')[0].split('#')[0].replace(appRegex, ''); // Get path from url if (url.indexOf(developmentPath) !== -1) { urlPath = urlPath.substring(urlPath.indexOf(developmentPath) + developmentPath.length); } else if (urlPath.indexOf('http') !== -1) { urlPath = urlPath.substring(urlPath.indexOf('/', urlPath.indexOf('//') + 2) + 1); } else { urlPath = urlPath.substring(1); } // Get action from path const action = urlPath.substring( 0, ((urlPath.indexOf('/') !== -1) ? (urlPath.indexOf('/')) : undefined) ); // If no mapping function is available for the action, continue if (typeof mapping[action] === 'undefined') { return { public: urlPath + urlParams, private: action, }; } // Call mapping function and return its result const pathWithoutAction = urlPath.substring(action.length + 1); let pathWithoutActionArray = []; if (pathWithoutAction.length !== 0) { pathWithoutActionArray = pathWithoutAction.split('/'); } const mappedUrls = mapping[action](pathWithoutActionArray, data || {}); if (Array.isArray(mappedUrls)) { return { public: mappedUrls[1] + urlParams, private: mappedUrls[0], }; } return { public: mappedUrls + urlParams, private: mappedUrls, }; }
javascript
function sgTrackingUrlMapper(url, data) { // In our development system urls start with /php/shopgate/ always const developmentPath = '/php/shopgate/'; const appRegex = /sg_app_resources\/[0-9]*\//; // Build regex that will remove all blacklisted paramters let regex = ''; urlParameterBlacklist.forEach((entry) => { regex += `((\\?|^){0,1}(${entry}=.*?(&|$)))`; regex += '|'; }); const params = url.indexOf('?') !== -1 ? url.split('?')[1] : ''; let urlParams = params.replace(new RegExp(regex, 'g'), ''); urlParams = urlParams === '' ? '' : `?${urlParams.replace(/&$/, '')}`; // Get rid of hash and app urls let urlPath = url.split('?')[0].split('#')[0].replace(appRegex, ''); // Get path from url if (url.indexOf(developmentPath) !== -1) { urlPath = urlPath.substring(urlPath.indexOf(developmentPath) + developmentPath.length); } else if (urlPath.indexOf('http') !== -1) { urlPath = urlPath.substring(urlPath.indexOf('/', urlPath.indexOf('//') + 2) + 1); } else { urlPath = urlPath.substring(1); } // Get action from path const action = urlPath.substring( 0, ((urlPath.indexOf('/') !== -1) ? (urlPath.indexOf('/')) : undefined) ); // If no mapping function is available for the action, continue if (typeof mapping[action] === 'undefined') { return { public: urlPath + urlParams, private: action, }; } // Call mapping function and return its result const pathWithoutAction = urlPath.substring(action.length + 1); let pathWithoutActionArray = []; if (pathWithoutAction.length !== 0) { pathWithoutActionArray = pathWithoutAction.split('/'); } const mappedUrls = mapping[action](pathWithoutActionArray, data || {}); if (Array.isArray(mappedUrls)) { return { public: mappedUrls[1] + urlParams, private: mappedUrls[0], }; } return { public: mappedUrls + urlParams, private: mappedUrls, }; }
[ "function", "sgTrackingUrlMapper", "(", "url", ",", "data", ")", "{", "const", "developmentPath", "=", "'/php/shopgate/'", ";", "const", "appRegex", "=", "/", "sg_app_resources\\/[0-9]*\\/", "/", ";", "let", "regex", "=", "''", ";", "urlParameterBlacklist", ".", "forEach", "(", "(", "entry", ")", "=>", "{", "regex", "+=", "`", "\\\\", "${", "entry", "}", "`", ";", "regex", "+=", "'|'", ";", "}", ")", ";", "const", "params", "=", "url", ".", "indexOf", "(", "'?'", ")", "!==", "-", "1", "?", "url", ".", "split", "(", "'?'", ")", "[", "1", "]", ":", "''", ";", "let", "urlParams", "=", "params", ".", "replace", "(", "new", "RegExp", "(", "regex", ",", "'g'", ")", ",", "''", ")", ";", "urlParams", "=", "urlParams", "===", "''", "?", "''", ":", "`", "${", "urlParams", ".", "replace", "(", "/", "&$", "/", ",", "''", ")", "}", "`", ";", "let", "urlPath", "=", "url", ".", "split", "(", "'?'", ")", "[", "0", "]", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "replace", "(", "appRegex", ",", "''", ")", ";", "if", "(", "url", ".", "indexOf", "(", "developmentPath", ")", "!==", "-", "1", ")", "{", "urlPath", "=", "urlPath", ".", "substring", "(", "urlPath", ".", "indexOf", "(", "developmentPath", ")", "+", "developmentPath", ".", "length", ")", ";", "}", "else", "if", "(", "urlPath", ".", "indexOf", "(", "'http'", ")", "!==", "-", "1", ")", "{", "urlPath", "=", "urlPath", ".", "substring", "(", "urlPath", ".", "indexOf", "(", "'/'", ",", "urlPath", ".", "indexOf", "(", "'//'", ")", "+", "2", ")", "+", "1", ")", ";", "}", "else", "{", "urlPath", "=", "urlPath", ".", "substring", "(", "1", ")", ";", "}", "const", "action", "=", "urlPath", ".", "substring", "(", "0", ",", "(", "(", "urlPath", ".", "indexOf", "(", "'/'", ")", "!==", "-", "1", ")", "?", "(", "urlPath", ".", "indexOf", "(", "'/'", ")", ")", ":", "undefined", ")", ")", ";", "if", "(", "typeof", "mapping", "[", "action", "]", "===", "'undefined'", ")", "{", "return", "{", "public", ":", "urlPath", "+", "urlParams", ",", "private", ":", "action", ",", "}", ";", "}", "const", "pathWithoutAction", "=", "urlPath", ".", "substring", "(", "action", ".", "length", "+", "1", ")", ";", "let", "pathWithoutActionArray", "=", "[", "]", ";", "if", "(", "pathWithoutAction", ".", "length", "!==", "0", ")", "{", "pathWithoutActionArray", "=", "pathWithoutAction", ".", "split", "(", "'/'", ")", ";", "}", "const", "mappedUrls", "=", "mapping", "[", "action", "]", "(", "pathWithoutActionArray", ",", "data", "||", "{", "}", ")", ";", "if", "(", "Array", ".", "isArray", "(", "mappedUrls", ")", ")", "{", "return", "{", "public", ":", "mappedUrls", "[", "1", "]", "+", "urlParams", ",", "private", ":", "mappedUrls", "[", "0", "]", ",", "}", ";", "}", "return", "{", "public", ":", "mappedUrls", "+", "urlParams", ",", "private", ":", "mappedUrls", ",", "}", ";", "}" ]
Maps an internal url to an external url that we can send to tracking providers @param {string} url internal url @param {Object} [data] sgData object @returns {Object} external url
[ "Maps", "an", "internal", "url", "to", "an", "external", "url", "that", "we", "can", "send", "to", "tracking", "providers" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/urlMapping.js#L79-L141
train
shopgate/pwa
libraries/tracking-core/helpers/formatHelpers.js
get
function get(object, path, defaultValue) { // Initialize the parameters const data = object || {}; const dataPath = path || ''; const defaultReturnValue = defaultValue; // Get the segments of the path const pathSegments = dataPath.split('.'); if (!dataPath || !pathSegments.length) { // No path or path segments where determinable - return the default value return defaultReturnValue; } /** * Recursive callable function to traverse through a complex object * * @param {Object} currentData The current data that shall be investigated * @param {number} currentPathSegmentIndex The current index within the path segment list * @returns {*} The value at the end of the path or the default one */ function checkPathSegment(currentData, currentPathSegmentIndex) { // Get the current segment within the path const currentPathSegment = pathSegments[currentPathSegmentIndex]; const nextPathSegmentIndex = currentPathSegmentIndex + 1; /** * Prepare the default value as return value for the case that no matching property was * found for the current path segment. In that case the path must be wrong. */ let result = defaultReturnValue; if (currentData && currentData.hasOwnProperty(currentPathSegment)) { if ( typeof currentData[currentPathSegment] !== 'object' || pathSegments.length === nextPathSegmentIndex ) { // A final value was found result = currentData[currentPathSegment]; } else { // The value at the current step within the path is another object. Traverse through it result = checkPathSegment(currentData[currentPathSegment], nextPathSegmentIndex); } } return result; } // Start traversing the path within the data object return checkPathSegment(data, 0); }
javascript
function get(object, path, defaultValue) { // Initialize the parameters const data = object || {}; const dataPath = path || ''; const defaultReturnValue = defaultValue; // Get the segments of the path const pathSegments = dataPath.split('.'); if (!dataPath || !pathSegments.length) { // No path or path segments where determinable - return the default value return defaultReturnValue; } /** * Recursive callable function to traverse through a complex object * * @param {Object} currentData The current data that shall be investigated * @param {number} currentPathSegmentIndex The current index within the path segment list * @returns {*} The value at the end of the path or the default one */ function checkPathSegment(currentData, currentPathSegmentIndex) { // Get the current segment within the path const currentPathSegment = pathSegments[currentPathSegmentIndex]; const nextPathSegmentIndex = currentPathSegmentIndex + 1; /** * Prepare the default value as return value for the case that no matching property was * found for the current path segment. In that case the path must be wrong. */ let result = defaultReturnValue; if (currentData && currentData.hasOwnProperty(currentPathSegment)) { if ( typeof currentData[currentPathSegment] !== 'object' || pathSegments.length === nextPathSegmentIndex ) { // A final value was found result = currentData[currentPathSegment]; } else { // The value at the current step within the path is another object. Traverse through it result = checkPathSegment(currentData[currentPathSegment], nextPathSegmentIndex); } } return result; } // Start traversing the path within the data object return checkPathSegment(data, 0); }
[ "function", "get", "(", "object", ",", "path", ",", "defaultValue", ")", "{", "const", "data", "=", "object", "||", "{", "}", ";", "const", "dataPath", "=", "path", "||", "''", ";", "const", "defaultReturnValue", "=", "defaultValue", ";", "const", "pathSegments", "=", "dataPath", ".", "split", "(", "'.'", ")", ";", "if", "(", "!", "dataPath", "||", "!", "pathSegments", ".", "length", ")", "{", "return", "defaultReturnValue", ";", "}", "function", "checkPathSegment", "(", "currentData", ",", "currentPathSegmentIndex", ")", "{", "const", "currentPathSegment", "=", "pathSegments", "[", "currentPathSegmentIndex", "]", ";", "const", "nextPathSegmentIndex", "=", "currentPathSegmentIndex", "+", "1", ";", "let", "result", "=", "defaultReturnValue", ";", "if", "(", "currentData", "&&", "currentData", ".", "hasOwnProperty", "(", "currentPathSegment", ")", ")", "{", "if", "(", "typeof", "currentData", "[", "currentPathSegment", "]", "!==", "'object'", "||", "pathSegments", ".", "length", "===", "nextPathSegmentIndex", ")", "{", "result", "=", "currentData", "[", "currentPathSegment", "]", ";", "}", "else", "{", "result", "=", "checkPathSegment", "(", "currentData", "[", "currentPathSegment", "]", ",", "nextPathSegmentIndex", ")", ";", "}", "}", "return", "result", ";", "}", "return", "checkPathSegment", "(", "data", ",", "0", ")", ";", "}" ]
Gets the value at path of object. If the resolved value is undefined, the defaultValue is used in its place. @param {Object} object The object to query @param {string} path The path of the property to get @param {*} [defaultValue] The value returned for undefined resolved values @returns {*} Returns the resolved value
[ "Gets", "the", "value", "at", "path", "of", "object", ".", "If", "the", "resolved", "value", "is", "undefined", "the", "defaultValue", "is", "used", "in", "its", "place", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/formatHelpers.js#L14-L64
train
shopgate/pwa
libraries/tracking-core/helpers/formatHelpers.js
checkPathSegment
function checkPathSegment(currentData, currentPathSegmentIndex) { // Get the current segment within the path const currentPathSegment = pathSegments[currentPathSegmentIndex]; const nextPathSegmentIndex = currentPathSegmentIndex + 1; /** * Prepare the default value as return value for the case that no matching property was * found for the current path segment. In that case the path must be wrong. */ let result = defaultReturnValue; if (currentData && currentData.hasOwnProperty(currentPathSegment)) { if ( typeof currentData[currentPathSegment] !== 'object' || pathSegments.length === nextPathSegmentIndex ) { // A final value was found result = currentData[currentPathSegment]; } else { // The value at the current step within the path is another object. Traverse through it result = checkPathSegment(currentData[currentPathSegment], nextPathSegmentIndex); } } return result; }
javascript
function checkPathSegment(currentData, currentPathSegmentIndex) { // Get the current segment within the path const currentPathSegment = pathSegments[currentPathSegmentIndex]; const nextPathSegmentIndex = currentPathSegmentIndex + 1; /** * Prepare the default value as return value for the case that no matching property was * found for the current path segment. In that case the path must be wrong. */ let result = defaultReturnValue; if (currentData && currentData.hasOwnProperty(currentPathSegment)) { if ( typeof currentData[currentPathSegment] !== 'object' || pathSegments.length === nextPathSegmentIndex ) { // A final value was found result = currentData[currentPathSegment]; } else { // The value at the current step within the path is another object. Traverse through it result = checkPathSegment(currentData[currentPathSegment], nextPathSegmentIndex); } } return result; }
[ "function", "checkPathSegment", "(", "currentData", ",", "currentPathSegmentIndex", ")", "{", "const", "currentPathSegment", "=", "pathSegments", "[", "currentPathSegmentIndex", "]", ";", "const", "nextPathSegmentIndex", "=", "currentPathSegmentIndex", "+", "1", ";", "let", "result", "=", "defaultReturnValue", ";", "if", "(", "currentData", "&&", "currentData", ".", "hasOwnProperty", "(", "currentPathSegment", ")", ")", "{", "if", "(", "typeof", "currentData", "[", "currentPathSegment", "]", "!==", "'object'", "||", "pathSegments", ".", "length", "===", "nextPathSegmentIndex", ")", "{", "result", "=", "currentData", "[", "currentPathSegment", "]", ";", "}", "else", "{", "result", "=", "checkPathSegment", "(", "currentData", "[", "currentPathSegment", "]", ",", "nextPathSegmentIndex", ")", ";", "}", "}", "return", "result", ";", "}" ]
Recursive callable function to traverse through a complex object @param {Object} currentData The current data that shall be investigated @param {number} currentPathSegmentIndex The current index within the path segment list @returns {*} The value at the end of the path or the default one
[ "Recursive", "callable", "function", "to", "traverse", "through", "a", "complex", "object" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/formatHelpers.js#L35-L60
train
shopgate/pwa
libraries/tracking-core/helpers/formatHelpers.js
sanitizeTitle
function sanitizeTitle(title, shopName) { // Take care that the parameters don't contain leading or trailing spaces let trimmedTitle = title.trim(); const trimmedShopName = shopName.trim(); if (!trimmedShopName) { /** * If no shop name is available, it doesn't make sense to replace it. * So we return the the trimmed title directly. */ return trimmedTitle; } /** * Setup the RegExp. It matches leading and trailing occurrences * of known patterns for generically added shop names within page title */ const shopNameRegExp = new RegExp(`((^${trimmedShopName}:)|(- ${trimmedShopName}$))+`, 'ig'); if (trimmedTitle === trimmedShopName) { // Clear the page title if it only contains the shop name trimmedTitle = ''; } // Remove the shop name from the page title return trimmedTitle.replace(shopNameRegExp, '').trim(); }
javascript
function sanitizeTitle(title, shopName) { // Take care that the parameters don't contain leading or trailing spaces let trimmedTitle = title.trim(); const trimmedShopName = shopName.trim(); if (!trimmedShopName) { /** * If no shop name is available, it doesn't make sense to replace it. * So we return the the trimmed title directly. */ return trimmedTitle; } /** * Setup the RegExp. It matches leading and trailing occurrences * of known patterns for generically added shop names within page title */ const shopNameRegExp = new RegExp(`((^${trimmedShopName}:)|(- ${trimmedShopName}$))+`, 'ig'); if (trimmedTitle === trimmedShopName) { // Clear the page title if it only contains the shop name trimmedTitle = ''; } // Remove the shop name from the page title return trimmedTitle.replace(shopNameRegExp, '').trim(); }
[ "function", "sanitizeTitle", "(", "title", ",", "shopName", ")", "{", "let", "trimmedTitle", "=", "title", ".", "trim", "(", ")", ";", "const", "trimmedShopName", "=", "shopName", ".", "trim", "(", ")", ";", "if", "(", "!", "trimmedShopName", ")", "{", "return", "trimmedTitle", ";", "}", "const", "shopNameRegExp", "=", "new", "RegExp", "(", "`", "${", "trimmedShopName", "}", "${", "trimmedShopName", "}", "`", ",", "'ig'", ")", ";", "if", "(", "trimmedTitle", "===", "trimmedShopName", ")", "{", "trimmedTitle", "=", "''", ";", "}", "return", "trimmedTitle", ".", "replace", "(", "shopNameRegExp", ",", "''", ")", ".", "trim", "(", ")", ";", "}" ]
Removes shop names out of the page title @param {string} title The page title @param {string} shopName The shop name @returns {string} The sanitized page title
[ "Removes", "shop", "names", "out", "of", "the", "page", "title" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/formatHelpers.js#L99-L125
train
shopgate/pwa
libraries/tracking-core/helpers/formatHelpers.js
formatSgDataProduct
function formatSgDataProduct(product) { return { id: getProductIdentifier(product), type: 'product', name: get(product, 'name'), priceNet: getUnifiedNumber(get(product, 'amount.net')), priceGross: getUnifiedNumber(get(product, 'amount.gross')), quantity: getUnifiedNumber(get(product, 'quantity')), currency: get(product, 'amount.currency'), }; }
javascript
function formatSgDataProduct(product) { return { id: getProductIdentifier(product), type: 'product', name: get(product, 'name'), priceNet: getUnifiedNumber(get(product, 'amount.net')), priceGross: getUnifiedNumber(get(product, 'amount.gross')), quantity: getUnifiedNumber(get(product, 'quantity')), currency: get(product, 'amount.currency'), }; }
[ "function", "formatSgDataProduct", "(", "product", ")", "{", "return", "{", "id", ":", "getProductIdentifier", "(", "product", ")", ",", "type", ":", "'product'", ",", "name", ":", "get", "(", "product", ",", "'name'", ")", ",", "priceNet", ":", "getUnifiedNumber", "(", "get", "(", "product", ",", "'amount.net'", ")", ")", ",", "priceGross", ":", "getUnifiedNumber", "(", "get", "(", "product", ",", "'amount.gross'", ")", ")", ",", "quantity", ":", "getUnifiedNumber", "(", "get", "(", "product", ",", "'quantity'", ")", ")", ",", "currency", ":", "get", "(", "product", ",", "'amount.currency'", ")", ",", "}", ";", "}" ]
Convert sgData product to unified item @param {Object} product Item from sgData @returns {Object} Data for the unified item
[ "Convert", "sgData", "product", "to", "unified", "item" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/formatHelpers.js#L133-L143
train
shopgate/pwa
libraries/tracking-core/helpers/formatHelpers.js
formatFavouriteListItems
function formatFavouriteListItems(products) { if (!products || !Array.isArray(products)) { return []; } return products.map(product => ({ id: get(product, 'product_number_public') || get(product, 'product_number') || get(product, 'uid'), type: 'product', name: get(product, 'name'), priceNet: getUnifiedNumber(get(product, 'unit_amount_net')) / 100, priceGross: getUnifiedNumber(get(product, 'unit_amount_with_tax')) / 100, currency: get(product, 'currency_id'), })); }
javascript
function formatFavouriteListItems(products) { if (!products || !Array.isArray(products)) { return []; } return products.map(product => ({ id: get(product, 'product_number_public') || get(product, 'product_number') || get(product, 'uid'), type: 'product', name: get(product, 'name'), priceNet: getUnifiedNumber(get(product, 'unit_amount_net')) / 100, priceGross: getUnifiedNumber(get(product, 'unit_amount_with_tax')) / 100, currency: get(product, 'currency_id'), })); }
[ "function", "formatFavouriteListItems", "(", "products", ")", "{", "if", "(", "!", "products", "||", "!", "Array", ".", "isArray", "(", "products", ")", ")", "{", "return", "[", "]", ";", "}", "return", "products", ".", "map", "(", "product", "=>", "(", "{", "id", ":", "get", "(", "product", ",", "'product_number_public'", ")", "||", "get", "(", "product", ",", "'product_number'", ")", "||", "get", "(", "product", ",", "'uid'", ")", ",", "type", ":", "'product'", ",", "name", ":", "get", "(", "product", ",", "'name'", ")", ",", "priceNet", ":", "getUnifiedNumber", "(", "get", "(", "product", ",", "'unit_amount_net'", ")", ")", "/", "100", ",", "priceGross", ":", "getUnifiedNumber", "(", "get", "(", "product", ",", "'unit_amount_with_tax'", ")", ")", "/", "100", ",", "currency", ":", "get", "(", "product", ",", "'currency_id'", ")", ",", "}", ")", ")", ";", "}" ]
Convert products from the favouriteListItemAdded event to unified items @param {Array} products Items from sgData @returns {UnifiedAddToWishlistItem[]} Data for the unified items
[ "Convert", "products", "from", "the", "favouriteListItemAdded", "event", "to", "unified", "items" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/tracking-core/helpers/formatHelpers.js#L166-L179
train
shopgate/pwa
libraries/core/commands/unifiedTracking.js
executeCommand
function executeCommand(name = '', params = {}) { const command = new AppCommand(); command .setCommandName(name) .dispatch(params); }
javascript
function executeCommand(name = '', params = {}) { const command = new AppCommand(); command .setCommandName(name) .dispatch(params); }
[ "function", "executeCommand", "(", "name", "=", "''", ",", "params", "=", "{", "}", ")", "{", "const", "command", "=", "new", "AppCommand", "(", ")", ";", "command", ".", "setCommandName", "(", "name", ")", ".", "dispatch", "(", "params", ")", ";", "}" ]
Restrictions for a unified tracking command @typedef {Object} UnifiedRestrictions @property {boolean} blacklist If set to TRUE, this event is not sent to the trackers named in the tracker-array within this restriction object, if set to FALSE, this event is only sent to the trackers in the tracker-array. @property {Array} trackers List of tracker names that are concerned of this restriction Executes a unified tracking command @param {string} name The name of the command @param {Object} params The payload for the command
[ "Restrictions", "for", "a", "unified", "tracking", "command" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/core/commands/unifiedTracking.js#L140-L146
train
shopgate/pwa
libraries/common/components/Widgets/components/Widget/style.js
widgetCell
function widgetCell({ col, row, width, height, }) { return css({ gridColumnStart: col + 1, gridColumnEnd: col + width + 1, gridRowStart: row + 1, gridRowEnd: row + height + 1, }).toString(); }
javascript
function widgetCell({ col, row, width, height, }) { return css({ gridColumnStart: col + 1, gridColumnEnd: col + width + 1, gridRowStart: row + 1, gridRowEnd: row + height + 1, }).toString(); }
[ "function", "widgetCell", "(", "{", "col", ",", "row", ",", "width", ",", "height", ",", "}", ")", "{", "return", "css", "(", "{", "gridColumnStart", ":", "col", "+", "1", ",", "gridColumnEnd", ":", "col", "+", "width", "+", "1", ",", "gridRowStart", ":", "row", "+", "1", ",", "gridRowEnd", ":", "row", "+", "height", "+", "1", ",", "}", ")", ".", "toString", "(", ")", ";", "}" ]
Creates a widget cell grid style. @param {number} col Col index. @param {number} row Row index. @param {number} width Width. @param {number} height Height. @param {bool} visible Visible. @returns {string}
[ "Creates", "a", "widget", "cell", "grid", "style", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/common/components/Widgets/components/Widget/style.js#L12-L24
train
shopgate/pwa
libraries/common/actions/client/fetchClientInformation.js
fetchClientInformation
function fetchClientInformation() { return (dispatch) => { dispatch(requestClientInformation()); if (!hasSGJavaScriptBridge()) { dispatch(receiveClientInformation(defaultClientInformation)); return; } getWebStorageEntry({ name: 'clientInformation' }) .then(response => dispatch(receiveClientInformation(response.value))) .catch((error) => { logger.error(error); dispatch(errorClientInformation()); }); }; }
javascript
function fetchClientInformation() { return (dispatch) => { dispatch(requestClientInformation()); if (!hasSGJavaScriptBridge()) { dispatch(receiveClientInformation(defaultClientInformation)); return; } getWebStorageEntry({ name: 'clientInformation' }) .then(response => dispatch(receiveClientInformation(response.value))) .catch((error) => { logger.error(error); dispatch(errorClientInformation()); }); }; }
[ "function", "fetchClientInformation", "(", ")", "{", "return", "(", "dispatch", ")", "=>", "{", "dispatch", "(", "requestClientInformation", "(", ")", ")", ";", "if", "(", "!", "hasSGJavaScriptBridge", "(", ")", ")", "{", "dispatch", "(", "receiveClientInformation", "(", "defaultClientInformation", ")", ")", ";", "return", ";", "}", "getWebStorageEntry", "(", "{", "name", ":", "'clientInformation'", "}", ")", ".", "then", "(", "response", "=>", "dispatch", "(", "receiveClientInformation", "(", "response", ".", "value", ")", ")", ")", ".", "catch", "(", "(", "error", ")", "=>", "{", "logger", ".", "error", "(", "error", ")", ";", "dispatch", "(", "errorClientInformation", "(", ")", ")", ";", "}", ")", ";", "}", ";", "}" ]
Requests the client information from the web storage. @return {Function} A redux thunk.
[ "Requests", "the", "client", "information", "from", "the", "web", "storage", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/common/actions/client/fetchClientInformation.js#L14-L30
train
shopgate/pwa
libraries/common/components/Widgets/helpers/shouldShowWidget.js
shouldShowWidget
function shouldShowWidget(settings = {}) { const nowDate = new Date(); // Show widget if flag does not exist (old widgets) if (!settings.hasOwnProperty('published')) { return true; } if (settings.published === false) { return false; } // Defensive here since this data comes from the pipeline, it might be invalid for some reasons. if (settings.hasOwnProperty('plan') && settings.plan) { let startDate = null; let endDate = null; let notStartedYet = false; let finishedAlready = false; if (settings.planDate.valid_from) { startDate = new Date(settings.planDate.valid_from); notStartedYet = nowDate <= startDate; } if (settings.planDate.valid_to) { endDate = new Date(settings.planDate.valid_to); finishedAlready = nowDate >= endDate; } // Don't hide if no dates found if (!startDate && !endDate) { return true; } // Hide if some wrong dates are passed if (startDate && endDate && (startDate >= endDate)) { return false; } // Hide if start date is set but it is not there yet // Hide if end date is reached if ((startDate && notStartedYet) || (endDate && finishedAlready)) { return false; } } return true; }
javascript
function shouldShowWidget(settings = {}) { const nowDate = new Date(); // Show widget if flag does not exist (old widgets) if (!settings.hasOwnProperty('published')) { return true; } if (settings.published === false) { return false; } // Defensive here since this data comes from the pipeline, it might be invalid for some reasons. if (settings.hasOwnProperty('plan') && settings.plan) { let startDate = null; let endDate = null; let notStartedYet = false; let finishedAlready = false; if (settings.planDate.valid_from) { startDate = new Date(settings.planDate.valid_from); notStartedYet = nowDate <= startDate; } if (settings.planDate.valid_to) { endDate = new Date(settings.planDate.valid_to); finishedAlready = nowDate >= endDate; } // Don't hide if no dates found if (!startDate && !endDate) { return true; } // Hide if some wrong dates are passed if (startDate && endDate && (startDate >= endDate)) { return false; } // Hide if start date is set but it is not there yet // Hide if end date is reached if ((startDate && notStartedYet) || (endDate && finishedAlready)) { return false; } } return true; }
[ "function", "shouldShowWidget", "(", "settings", "=", "{", "}", ")", "{", "const", "nowDate", "=", "new", "Date", "(", ")", ";", "if", "(", "!", "settings", ".", "hasOwnProperty", "(", "'published'", ")", ")", "{", "return", "true", ";", "}", "if", "(", "settings", ".", "published", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "settings", ".", "hasOwnProperty", "(", "'plan'", ")", "&&", "settings", ".", "plan", ")", "{", "let", "startDate", "=", "null", ";", "let", "endDate", "=", "null", ";", "let", "notStartedYet", "=", "false", ";", "let", "finishedAlready", "=", "false", ";", "if", "(", "settings", ".", "planDate", ".", "valid_from", ")", "{", "startDate", "=", "new", "Date", "(", "settings", ".", "planDate", ".", "valid_from", ")", ";", "notStartedYet", "=", "nowDate", "<=", "startDate", ";", "}", "if", "(", "settings", ".", "planDate", ".", "valid_to", ")", "{", "endDate", "=", "new", "Date", "(", "settings", ".", "planDate", ".", "valid_to", ")", ";", "finishedAlready", "=", "nowDate", ">=", "endDate", ";", "}", "if", "(", "!", "startDate", "&&", "!", "endDate", ")", "{", "return", "true", ";", "}", "if", "(", "startDate", "&&", "endDate", "&&", "(", "startDate", ">=", "endDate", ")", ")", "{", "return", "false", ";", "}", "if", "(", "(", "startDate", "&&", "notStartedYet", ")", "||", "(", "endDate", "&&", "finishedAlready", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks widget setting and decides if widget should be shown at the moment. @param {Object} settings Widget setting object. @returns {boolean}
[ "Checks", "widget", "setting", "and", "decides", "if", "widget", "should", "be", "shown", "at", "the", "moment", "." ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/libraries/common/components/Widgets/helpers/shouldShowWidget.js#L6-L51
train
google/web-activities
build-system/tasks/check-rules.js
hasAnyTerms
function hasAnyTerms(file) { var pathname = file.path; var hasTerms = false; var hasSrcInclusiveTerms = false; hasTerms = matchTerms(file, forbiddenTerms); if (!isTestFile(file)) { hasSrcInclusiveTerms = matchTerms(file, forbiddenTermsSrcInclusive); } return hasTerms || hasSrcInclusiveTerms; }
javascript
function hasAnyTerms(file) { var pathname = file.path; var hasTerms = false; var hasSrcInclusiveTerms = false; hasTerms = matchTerms(file, forbiddenTerms); if (!isTestFile(file)) { hasSrcInclusiveTerms = matchTerms(file, forbiddenTermsSrcInclusive); } return hasTerms || hasSrcInclusiveTerms; }
[ "function", "hasAnyTerms", "(", "file", ")", "{", "var", "pathname", "=", "file", ".", "path", ";", "var", "hasTerms", "=", "false", ";", "var", "hasSrcInclusiveTerms", "=", "false", ";", "hasTerms", "=", "matchTerms", "(", "file", ",", "forbiddenTerms", ")", ";", "if", "(", "!", "isTestFile", "(", "file", ")", ")", "{", "hasSrcInclusiveTerms", "=", "matchTerms", "(", "file", ",", "forbiddenTermsSrcInclusive", ")", ";", "}", "return", "hasTerms", "||", "hasSrcInclusiveTerms", ";", "}" ]
Test if a file's contents match any of the forbidden terms @param {!File} file file is a vinyl file object @return {boolean} true if any of the terms match the file content, false otherwise
[ "Test", "if", "a", "file", "s", "contents", "match", "any", "of", "the", "forbidden", "terms" ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/check-rules.js#L316-L327
train
google/web-activities
build-system/tasks/check-rules.js
isMissingTerms
function isMissingTerms(file) { var contents = file.contents.toString(); return Object.keys(requiredTerms).map(function(term) { var filter = requiredTerms[term]; if (!filter.test(file.path)) { return false; } var matches = contents.match(new RegExp(term)); if (!matches) { util.log(util.colors.red('Did not find required: "' + term + '" in ' + file.relative)); util.log(util.colors.blue('==========')); return true; } return false; }).some(function(hasMissingTerm) { return hasMissingTerm; }); }
javascript
function isMissingTerms(file) { var contents = file.contents.toString(); return Object.keys(requiredTerms).map(function(term) { var filter = requiredTerms[term]; if (!filter.test(file.path)) { return false; } var matches = contents.match(new RegExp(term)); if (!matches) { util.log(util.colors.red('Did not find required: "' + term + '" in ' + file.relative)); util.log(util.colors.blue('==========')); return true; } return false; }).some(function(hasMissingTerm) { return hasMissingTerm; }); }
[ "function", "isMissingTerms", "(", "file", ")", "{", "var", "contents", "=", "file", ".", "contents", ".", "toString", "(", ")", ";", "return", "Object", ".", "keys", "(", "requiredTerms", ")", ".", "map", "(", "function", "(", "term", ")", "{", "var", "filter", "=", "requiredTerms", "[", "term", "]", ";", "if", "(", "!", "filter", ".", "test", "(", "file", ".", "path", ")", ")", "{", "return", "false", ";", "}", "var", "matches", "=", "contents", ".", "match", "(", "new", "RegExp", "(", "term", ")", ")", ";", "if", "(", "!", "matches", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "red", "(", "'Did not find required: \"'", "+", "term", "+", "'\" in '", "+", "file", ".", "relative", ")", ")", ";", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "'=========='", ")", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ".", "some", "(", "function", "(", "hasMissingTerm", ")", "{", "return", "hasMissingTerm", ";", "}", ")", ";", "}" ]
Test if a file's contents fail to match any of the required terms and log any missing terms @param {!File} file file is a vinyl file object @return {boolean} true if any of the terms are not matched in the file content, false otherwise
[ "Test", "if", "a", "file", "s", "contents", "fail", "to", "match", "any", "of", "the", "required", "terms", "and", "log", "any", "missing", "terms" ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/check-rules.js#L337-L356
train
google/web-activities
build-system/tasks/check-rules.js
checkForbiddenAndRequiredTerms
function checkForbiddenAndRequiredTerms() { var forbiddenFound = false; var missingRequirements = false; return gulp.src(srcGlobs) .pipe(through2.obj(function(file, enc, cb) { forbiddenFound = hasAnyTerms(file) || forbiddenFound; missingRequirements = isMissingTerms(file) || missingRequirements; cb(); })) .on('end', function() { if (forbiddenFound) { util.log(util.colors.blue( 'Please remove these usages or consult with the Web Activities team.')); } if (missingRequirements) { util.log(util.colors.blue( 'Adding these terms (e.g. by adding a required LICENSE ' + 'to the file)')); } if (forbiddenFound || missingRequirements) { process.exit(1); } }); }
javascript
function checkForbiddenAndRequiredTerms() { var forbiddenFound = false; var missingRequirements = false; return gulp.src(srcGlobs) .pipe(through2.obj(function(file, enc, cb) { forbiddenFound = hasAnyTerms(file) || forbiddenFound; missingRequirements = isMissingTerms(file) || missingRequirements; cb(); })) .on('end', function() { if (forbiddenFound) { util.log(util.colors.blue( 'Please remove these usages or consult with the Web Activities team.')); } if (missingRequirements) { util.log(util.colors.blue( 'Adding these terms (e.g. by adding a required LICENSE ' + 'to the file)')); } if (forbiddenFound || missingRequirements) { process.exit(1); } }); }
[ "function", "checkForbiddenAndRequiredTerms", "(", ")", "{", "var", "forbiddenFound", "=", "false", ";", "var", "missingRequirements", "=", "false", ";", "return", "gulp", ".", "src", "(", "srcGlobs", ")", ".", "pipe", "(", "through2", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "forbiddenFound", "=", "hasAnyTerms", "(", "file", ")", "||", "forbiddenFound", ";", "missingRequirements", "=", "isMissingTerms", "(", "file", ")", "||", "missingRequirements", ";", "cb", "(", ")", ";", "}", ")", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "forbiddenFound", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "'Please remove these usages or consult with the Web Activities team.'", ")", ")", ";", "}", "if", "(", "missingRequirements", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "'Adding these terms (e.g. by adding a required LICENSE '", "+", "'to the file)'", ")", ")", ";", "}", "if", "(", "forbiddenFound", "||", "missingRequirements", ")", "{", "process", ".", "exit", "(", "1", ")", ";", "}", "}", ")", ";", "}" ]
Check a file for all the required terms and any forbidden terms and log any errors found.
[ "Check", "a", "file", "for", "all", "the", "required", "terms", "and", "any", "forbidden", "terms", "and", "log", "any", "errors", "found", "." ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/check-rules.js#L362-L385
train
google/web-activities
activities.js
parseQueryString
function parseQueryString(query) { if (!query) { return {}; } return (/^[?#]/.test(query) ? query.slice(1) : query) .split('&') .reduce((params, param) => { const item = param.split('='); const key = decodeURIComponent(item[0] || ''); const value = decodeURIComponent(item[1] || ''); if (key) { params[key] = value; } return params; }, {}); }
javascript
function parseQueryString(query) { if (!query) { return {}; } return (/^[?#]/.test(query) ? query.slice(1) : query) .split('&') .reduce((params, param) => { const item = param.split('='); const key = decodeURIComponent(item[0] || ''); const value = decodeURIComponent(item[1] || ''); if (key) { params[key] = value; } return params; }, {}); }
[ "function", "parseQueryString", "(", "query", ")", "{", "if", "(", "!", "query", ")", "{", "return", "{", "}", ";", "}", "return", "(", "/", "^[?#]", "/", ".", "test", "(", "query", ")", "?", "query", ".", "slice", "(", "1", ")", ":", "query", ")", ".", "split", "(", "'&'", ")", ".", "reduce", "(", "(", "params", ",", "param", ")", "=>", "{", "const", "item", "=", "param", ".", "split", "(", "'='", ")", ";", "const", "key", "=", "decodeURIComponent", "(", "item", "[", "0", "]", "||", "''", ")", ";", "const", "value", "=", "decodeURIComponent", "(", "item", "[", "1", "]", "||", "''", ")", ";", "if", "(", "key", ")", "{", "params", "[", "key", "]", "=", "value", ";", "}", "return", "params", ";", "}", ",", "{", "}", ")", ";", "}" ]
Parses and builds Object of URL query string. @param {string} query The URL query string. @return {!Object<string, string>}
[ "Parses", "and", "builds", "Object", "of", "URL", "query", "string", "." ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/activities.js#L426-L441
train
google/web-activities
activities.js
addFragmentParam
function addFragmentParam(url, param, value) { return url + (url.indexOf('#') == -1 ? '#' : '&') + encodeURIComponent(param) + '=' + encodeURIComponent(value); }
javascript
function addFragmentParam(url, param, value) { return url + (url.indexOf('#') == -1 ? '#' : '&') + encodeURIComponent(param) + '=' + encodeURIComponent(value); }
[ "function", "addFragmentParam", "(", "url", ",", "param", ",", "value", ")", "{", "return", "url", "+", "(", "url", ".", "indexOf", "(", "'#'", ")", "==", "-", "1", "?", "'#'", ":", "'&'", ")", "+", "encodeURIComponent", "(", "param", ")", "+", "'='", "+", "encodeURIComponent", "(", "value", ")", ";", "}" ]
Add a query-like parameter to the fragment string. @param {string} url @param {string} param @param {string} value @return {string}
[ "Add", "a", "query", "-", "like", "parameter", "to", "the", "fragment", "string", "." ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/activities.js#L462-L466
train
ssbc/multiserver
index.js
function (str) { return str.split(';').map(function (e, i) { return plugs[i].parse(e) }) }
javascript
function (str) { return str.split(';').map(function (e, i) { return plugs[i].parse(e) }) }
[ "function", "(", "str", ")", "{", "return", "str", ".", "split", "(", "';'", ")", ".", "map", "(", "function", "(", "e", ",", "i", ")", "{", "return", "plugs", "[", "i", "]", ".", "parse", "(", "e", ")", "}", ")", "}" ]
parse doesn't really make sense here... like, what if you only have a partial match? maybe just parse the ones you understand?
[ "parse", "doesn", "t", "really", "make", "sense", "here", "...", "like", "what", "if", "you", "only", "have", "a", "partial", "match?", "maybe", "just", "parse", "the", "ones", "you", "understand?" ]
1fefc75e2423e00270f5f0d46fec3b485776d7fb
https://github.com/ssbc/multiserver/blob/1fefc75e2423e00270f5f0d46fec3b485776d7fb/index.js#L74-L78
train
google/web-activities
build-system/tasks/lint.js
lint
function lint() { var errorsFound = false; var stream = gulp.src(config.lintGlobs); if (isWatching) { stream = stream.pipe(watcher()); } if (argv.fix) { options.fix = true; } return stream.pipe(eslint(options)) .pipe(eslint.formatEach('stylish', function(msg) { errorsFound = true; util.log(util.colors.red(msg)); })) .pipe(gulpIf(isFixed, gulp.dest('.'))) .pipe(eslint.failAfterError()) .on('end', function() { if (errorsFound && !options.fix) { util.log(util.colors.blue('Run `gulp lint --fix` to automatically ' + 'fix some of these lint warnings/errors. This is a destructive ' + 'operation (operates on the file system) so please make sure ' + 'you commit before running.')); } }); }
javascript
function lint() { var errorsFound = false; var stream = gulp.src(config.lintGlobs); if (isWatching) { stream = stream.pipe(watcher()); } if (argv.fix) { options.fix = true; } return stream.pipe(eslint(options)) .pipe(eslint.formatEach('stylish', function(msg) { errorsFound = true; util.log(util.colors.red(msg)); })) .pipe(gulpIf(isFixed, gulp.dest('.'))) .pipe(eslint.failAfterError()) .on('end', function() { if (errorsFound && !options.fix) { util.log(util.colors.blue('Run `gulp lint --fix` to automatically ' + 'fix some of these lint warnings/errors. This is a destructive ' + 'operation (operates on the file system) so please make sure ' + 'you commit before running.')); } }); }
[ "function", "lint", "(", ")", "{", "var", "errorsFound", "=", "false", ";", "var", "stream", "=", "gulp", ".", "src", "(", "config", ".", "lintGlobs", ")", ";", "if", "(", "isWatching", ")", "{", "stream", "=", "stream", ".", "pipe", "(", "watcher", "(", ")", ")", ";", "}", "if", "(", "argv", ".", "fix", ")", "{", "options", ".", "fix", "=", "true", ";", "}", "return", "stream", ".", "pipe", "(", "eslint", "(", "options", ")", ")", ".", "pipe", "(", "eslint", ".", "formatEach", "(", "'stylish'", ",", "function", "(", "msg", ")", "{", "errorsFound", "=", "true", ";", "util", ".", "log", "(", "util", ".", "colors", ".", "red", "(", "msg", ")", ")", ";", "}", ")", ")", ".", "pipe", "(", "gulpIf", "(", "isFixed", ",", "gulp", ".", "dest", "(", "'.'", ")", ")", ")", ".", "pipe", "(", "eslint", ".", "failAfterError", "(", ")", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "if", "(", "errorsFound", "&&", "!", "options", ".", "fix", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "blue", "(", "'Run `gulp lint --fix` to automatically '", "+", "'fix some of these lint warnings/errors. This is a destructive '", "+", "'operation (operates on the file system) so please make sure '", "+", "'you commit before running.'", ")", ")", ";", "}", "}", ")", ";", "}" ]
Run the eslinter on the src javascript and log the output @return {!Stream} Readable stream
[ "Run", "the", "eslinter", "on", "the", "src", "javascript", "and", "log", "the", "output" ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/lint.js#L51-L78
train
google/web-activities
build-system/tasks/compile.js
compileJs
function compileJs(srcDir, srcFilename, destDir, options) { options = options || {}; if (options.minify) { const startTime = Date.now(); return closureCompile( srcDir + srcFilename + '.js', destDir, options.minifiedName, options) .then(function() { fs.writeFileSync(destDir + '/version.txt', internalRuntimeVersion); if (options.latestName) { fs.copySync( destDir + '/' + options.minifiedName, destDir + '/' + options.latestName); } }) .then(() => { endBuildStep('Minified', srcFilename + '.js', startTime); }); } var bundler = browserify(srcDir + srcFilename + '-babel.js', {debug: true}) .transform(babel, {loose: 'all'}); if (options.watch) { bundler = watchify(bundler); } var wrapper = options.wrapper || '<%= contents %>'; var lazybuild = lazypipe() .pipe(source, srcFilename + '-babel.js') .pipe(buffer) .pipe($$.replace, /\$internalRuntimeVersion\$/g, internalRuntimeVersion) .pipe($$.wrap, wrapper) .pipe($$.sourcemaps.init.bind($$.sourcemaps), {loadMaps: true}); var lazywrite = lazypipe() .pipe($$.sourcemaps.write.bind($$.sourcemaps), './') .pipe(gulp.dest.bind(gulp), destDir); var destFilename = options.toName || srcFilename + '.js'; function rebundle() { const startTime = Date.now(); return toPromise(bundler.bundle() .on('error', function(err) { if (err instanceof SyntaxError) { console.error($$.util.colors.red('Syntax error:', err.message)); } else { console.error($$.util.colors.red(err.message)); } }) .pipe(lazybuild()) .pipe($$.rename(destFilename)) .pipe(lazywrite()) .on('end', function() { })).then(() => { endBuildStep('Compiled', srcFilename, startTime); }); } if (options.watch) { bundler.on('update', function() { rebundle(); // Touch file in unit test set. This triggers rebundling of tests because // karma only considers changes to tests files themselves re-bundle // worthy. touch('test/_init_tests.js'); }); } if (options.watch === false) { // Due to the two step build process, compileJs() is called twice, once with // options.watch set to true and, once with it set to false. However, we do // not need to call rebundle() twice. This avoids the duplicate compile seen // when you run `gulp watch` and touch a file. return Promise.resolve(); } else { // This is the default options.watch === true case, and also covers the // `gulp build` / `gulp dist` cases where options.watch is undefined. return rebundle(); } }
javascript
function compileJs(srcDir, srcFilename, destDir, options) { options = options || {}; if (options.minify) { const startTime = Date.now(); return closureCompile( srcDir + srcFilename + '.js', destDir, options.minifiedName, options) .then(function() { fs.writeFileSync(destDir + '/version.txt', internalRuntimeVersion); if (options.latestName) { fs.copySync( destDir + '/' + options.minifiedName, destDir + '/' + options.latestName); } }) .then(() => { endBuildStep('Minified', srcFilename + '.js', startTime); }); } var bundler = browserify(srcDir + srcFilename + '-babel.js', {debug: true}) .transform(babel, {loose: 'all'}); if (options.watch) { bundler = watchify(bundler); } var wrapper = options.wrapper || '<%= contents %>'; var lazybuild = lazypipe() .pipe(source, srcFilename + '-babel.js') .pipe(buffer) .pipe($$.replace, /\$internalRuntimeVersion\$/g, internalRuntimeVersion) .pipe($$.wrap, wrapper) .pipe($$.sourcemaps.init.bind($$.sourcemaps), {loadMaps: true}); var lazywrite = lazypipe() .pipe($$.sourcemaps.write.bind($$.sourcemaps), './') .pipe(gulp.dest.bind(gulp), destDir); var destFilename = options.toName || srcFilename + '.js'; function rebundle() { const startTime = Date.now(); return toPromise(bundler.bundle() .on('error', function(err) { if (err instanceof SyntaxError) { console.error($$.util.colors.red('Syntax error:', err.message)); } else { console.error($$.util.colors.red(err.message)); } }) .pipe(lazybuild()) .pipe($$.rename(destFilename)) .pipe(lazywrite()) .on('end', function() { })).then(() => { endBuildStep('Compiled', srcFilename, startTime); }); } if (options.watch) { bundler.on('update', function() { rebundle(); // Touch file in unit test set. This triggers rebundling of tests because // karma only considers changes to tests files themselves re-bundle // worthy. touch('test/_init_tests.js'); }); } if (options.watch === false) { // Due to the two step build process, compileJs() is called twice, once with // options.watch set to true and, once with it set to false. However, we do // not need to call rebundle() twice. This avoids the duplicate compile seen // when you run `gulp watch` and touch a file. return Promise.resolve(); } else { // This is the default options.watch === true case, and also covers the // `gulp build` / `gulp dist` cases where options.watch is undefined. return rebundle(); } }
[ "function", "compileJs", "(", "srcDir", ",", "srcFilename", ",", "destDir", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "minify", ")", "{", "const", "startTime", "=", "Date", ".", "now", "(", ")", ";", "return", "closureCompile", "(", "srcDir", "+", "srcFilename", "+", "'.js'", ",", "destDir", ",", "options", ".", "minifiedName", ",", "options", ")", ".", "then", "(", "function", "(", ")", "{", "fs", ".", "writeFileSync", "(", "destDir", "+", "'/version.txt'", ",", "internalRuntimeVersion", ")", ";", "if", "(", "options", ".", "latestName", ")", "{", "fs", ".", "copySync", "(", "destDir", "+", "'/'", "+", "options", ".", "minifiedName", ",", "destDir", "+", "'/'", "+", "options", ".", "latestName", ")", ";", "}", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "endBuildStep", "(", "'Minified'", ",", "srcFilename", "+", "'.js'", ",", "startTime", ")", ";", "}", ")", ";", "}", "var", "bundler", "=", "browserify", "(", "srcDir", "+", "srcFilename", "+", "'-babel.js'", ",", "{", "debug", ":", "true", "}", ")", ".", "transform", "(", "babel", ",", "{", "loose", ":", "'all'", "}", ")", ";", "if", "(", "options", ".", "watch", ")", "{", "bundler", "=", "watchify", "(", "bundler", ")", ";", "}", "var", "wrapper", "=", "options", ".", "wrapper", "||", "'<%= contents %>'", ";", "var", "lazybuild", "=", "lazypipe", "(", ")", ".", "pipe", "(", "source", ",", "srcFilename", "+", "'-babel.js'", ")", ".", "pipe", "(", "buffer", ")", ".", "pipe", "(", "$$", ".", "replace", ",", "/", "\\$internalRuntimeVersion\\$", "/", "g", ",", "internalRuntimeVersion", ")", ".", "pipe", "(", "$$", ".", "wrap", ",", "wrapper", ")", ".", "pipe", "(", "$$", ".", "sourcemaps", ".", "init", ".", "bind", "(", "$$", ".", "sourcemaps", ")", ",", "{", "loadMaps", ":", "true", "}", ")", ";", "var", "lazywrite", "=", "lazypipe", "(", ")", ".", "pipe", "(", "$$", ".", "sourcemaps", ".", "write", ".", "bind", "(", "$$", ".", "sourcemaps", ")", ",", "'./'", ")", ".", "pipe", "(", "gulp", ".", "dest", ".", "bind", "(", "gulp", ")", ",", "destDir", ")", ";", "var", "destFilename", "=", "options", ".", "toName", "||", "srcFilename", "+", "'.js'", ";", "function", "rebundle", "(", ")", "{", "const", "startTime", "=", "Date", ".", "now", "(", ")", ";", "return", "toPromise", "(", "bundler", ".", "bundle", "(", ")", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "if", "(", "err", "instanceof", "SyntaxError", ")", "{", "console", ".", "error", "(", "$$", ".", "util", ".", "colors", ".", "red", "(", "'Syntax error:'", ",", "err", ".", "message", ")", ")", ";", "}", "else", "{", "console", ".", "error", "(", "$$", ".", "util", ".", "colors", ".", "red", "(", "err", ".", "message", ")", ")", ";", "}", "}", ")", ".", "pipe", "(", "lazybuild", "(", ")", ")", ".", "pipe", "(", "$$", ".", "rename", "(", "destFilename", ")", ")", ".", "pipe", "(", "lazywrite", "(", ")", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "}", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "endBuildStep", "(", "'Compiled'", ",", "srcFilename", ",", "startTime", ")", ";", "}", ")", ";", "}", "if", "(", "options", ".", "watch", ")", "{", "bundler", ".", "on", "(", "'update'", ",", "function", "(", ")", "{", "rebundle", "(", ")", ";", "touch", "(", "'test/_init_tests.js'", ")", ";", "}", ")", ";", "}", "if", "(", "options", ".", "watch", "===", "false", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ";", "}", "else", "{", "return", "rebundle", "(", ")", ";", "}", "}" ]
Compile a javascript file @param {string} srcDir Path to the src directory @param {string} srcFilename Name of the JS source file @param {string} destDir Destination folder for output script @param {?Object} options @return {!Promise}
[ "Compile", "a", "javascript", "file" ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/compile.js#L87-L167
train
google/web-activities
build-system/tasks/compile.js
endBuildStep
function endBuildStep(stepName, targetName, startTime) { const endTime = Date.now(); const executionTime = new Date(endTime - startTime); const secs = executionTime.getSeconds(); const ms = executionTime.getMilliseconds().toString(); var timeString = '('; if (secs === 0) { timeString += ms + ' ms)'; } else { timeString += secs + '.' + ms + ' s)'; } if (!process.env.TRAVIS) { $$.util.log( stepName, $$.util.colors.cyan(targetName), $$.util.colors.green(timeString)); } }
javascript
function endBuildStep(stepName, targetName, startTime) { const endTime = Date.now(); const executionTime = new Date(endTime - startTime); const secs = executionTime.getSeconds(); const ms = executionTime.getMilliseconds().toString(); var timeString = '('; if (secs === 0) { timeString += ms + ' ms)'; } else { timeString += secs + '.' + ms + ' s)'; } if (!process.env.TRAVIS) { $$.util.log( stepName, $$.util.colors.cyan(targetName), $$.util.colors.green(timeString)); } }
[ "function", "endBuildStep", "(", "stepName", ",", "targetName", ",", "startTime", ")", "{", "const", "endTime", "=", "Date", ".", "now", "(", ")", ";", "const", "executionTime", "=", "new", "Date", "(", "endTime", "-", "startTime", ")", ";", "const", "secs", "=", "executionTime", ".", "getSeconds", "(", ")", ";", "const", "ms", "=", "executionTime", ".", "getMilliseconds", "(", ")", ".", "toString", "(", ")", ";", "var", "timeString", "=", "'('", ";", "if", "(", "secs", "===", "0", ")", "{", "timeString", "+=", "ms", "+", "' ms)'", ";", "}", "else", "{", "timeString", "+=", "secs", "+", "'.'", "+", "ms", "+", "' s)'", ";", "}", "if", "(", "!", "process", ".", "env", ".", "TRAVIS", ")", "{", "$$", ".", "util", ".", "log", "(", "stepName", ",", "$$", ".", "util", ".", "colors", ".", "cyan", "(", "targetName", ")", ",", "$$", ".", "util", ".", "colors", ".", "green", "(", "timeString", ")", ")", ";", "}", "}" ]
Stops the timer for the given build step and prints the execution time, unless we are on Travis. @param {string} stepName Name of the action, like 'Compiled' or 'Minified' @param {string} targetName Name of the target, like a filename or path @param {DOMHighResTimeStamp} startTime Start time of build step
[ "Stops", "the", "timer", "for", "the", "given", "build", "step", "and", "prints", "the", "execution", "time", "unless", "we", "are", "on", "Travis", "." ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/compile.js#L184-L201
train
google/web-activities
build-system/tasks/serve.js
serve
function serve() { util.log(util.colors.green('Serving unminified js')); nodemon({ script: require.resolve('../server/server.js'), watch: [ require.resolve('../server/server.js') ], env: { 'NODE_ENV': 'development', 'SERVE_PORT': port, 'SERVE_HOST': host, 'SERVE_USEHTTPS': useHttps, 'SERVE_PROCESS_ID': process.pid, 'SERVE_QUIET': quiet }, }) .once('quit', function () { util.log(util.colors.green('Shutting down server')); }); if (!quiet) { util.log(util.colors.yellow('Run `gulp build` then go to ' + getHost())); } }
javascript
function serve() { util.log(util.colors.green('Serving unminified js')); nodemon({ script: require.resolve('../server/server.js'), watch: [ require.resolve('../server/server.js') ], env: { 'NODE_ENV': 'development', 'SERVE_PORT': port, 'SERVE_HOST': host, 'SERVE_USEHTTPS': useHttps, 'SERVE_PROCESS_ID': process.pid, 'SERVE_QUIET': quiet }, }) .once('quit', function () { util.log(util.colors.green('Shutting down server')); }); if (!quiet) { util.log(util.colors.yellow('Run `gulp build` then go to ' + getHost())); } }
[ "function", "serve", "(", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "green", "(", "'Serving unminified js'", ")", ")", ";", "nodemon", "(", "{", "script", ":", "require", ".", "resolve", "(", "'../server/server.js'", ")", ",", "watch", ":", "[", "require", ".", "resolve", "(", "'../server/server.js'", ")", "]", ",", "env", ":", "{", "'NODE_ENV'", ":", "'development'", ",", "'SERVE_PORT'", ":", "port", ",", "'SERVE_HOST'", ":", "host", ",", "'SERVE_USEHTTPS'", ":", "useHttps", ",", "'SERVE_PROCESS_ID'", ":", "process", ".", "pid", ",", "'SERVE_QUIET'", ":", "quiet", "}", ",", "}", ")", ".", "once", "(", "'quit'", ",", "function", "(", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "green", "(", "'Shutting down server'", ")", ")", ";", "}", ")", ";", "if", "(", "!", "quiet", ")", "{", "util", ".", "log", "(", "util", ".", "colors", ".", "yellow", "(", "'Run `gulp build` then go to '", "+", "getHost", "(", ")", ")", ")", ";", "}", "}" ]
Starts a simple http server at the repository root
[ "Starts", "a", "simple", "http", "server", "at", "the", "repository", "root" ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/serve.js#L31-L54
train
google/web-activities
build-system/tasks/builders.js
dist
function dist() { process.env.NODE_ENV = 'production'; return clean().then(() => { return Promise.all([ compile({minify: true, checkTypes: false, isProdBuild: true}), ]).then(() => { // Push main "min" files to root to make them available to npm package. fs.copySync('./dist/activities.min.js', './activities.min.js'); fs.copySync('./dist/activities.min.js.map', './activities.min.js.map'); // Check types now. return compile({minify: true, checkTypes: true}); }).then(() => { return rollupActivities('./index.js', 'activities.js'); }).then(() => { return rollupActivities('./index-ports.js', 'activity-ports.js'); }).then(() => { return rollupActivities('./index-hosts.js', 'activity-hosts.js'); }); }); }
javascript
function dist() { process.env.NODE_ENV = 'production'; return clean().then(() => { return Promise.all([ compile({minify: true, checkTypes: false, isProdBuild: true}), ]).then(() => { // Push main "min" files to root to make them available to npm package. fs.copySync('./dist/activities.min.js', './activities.min.js'); fs.copySync('./dist/activities.min.js.map', './activities.min.js.map'); // Check types now. return compile({minify: true, checkTypes: true}); }).then(() => { return rollupActivities('./index.js', 'activities.js'); }).then(() => { return rollupActivities('./index-ports.js', 'activity-ports.js'); }).then(() => { return rollupActivities('./index-hosts.js', 'activity-hosts.js'); }); }); }
[ "function", "dist", "(", ")", "{", "process", ".", "env", ".", "NODE_ENV", "=", "'production'", ";", "return", "clean", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "Promise", ".", "all", "(", "[", "compile", "(", "{", "minify", ":", "true", ",", "checkTypes", ":", "false", ",", "isProdBuild", ":", "true", "}", ")", ",", "]", ")", ".", "then", "(", "(", ")", "=>", "{", "fs", ".", "copySync", "(", "'./dist/activities.min.js'", ",", "'./activities.min.js'", ")", ";", "fs", ".", "copySync", "(", "'./dist/activities.min.js.map'", ",", "'./activities.min.js.map'", ")", ";", "return", "compile", "(", "{", "minify", ":", "true", ",", "checkTypes", ":", "true", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "rollupActivities", "(", "'./index.js'", ",", "'activities.js'", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "rollupActivities", "(", "'./index-ports.js'", ",", "'activity-ports.js'", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "rollupActivities", "(", "'./index-hosts.js'", ",", "'activity-hosts.js'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Dist build for prod. @return {!Promise}
[ "Dist", "build", "for", "prod", "." ]
c370f5cc2967c2eb65b71675b3dad5eaf2697fbf
https://github.com/google/web-activities/blob/c370f5cc2967c2eb65b71675b3dad5eaf2697fbf/build-system/tasks/builders.js#L73-L92
train
ni-kismet/engineering-flot
source/jquery.flot.composeImages.js
buildBinaryString
function buildBinaryString (arrayBuffer) { var binaryString = ""; const utf8Array = new Uint8Array(arrayBuffer); const blockSize = 16384; for (var i = 0; i < utf8Array.length; i = i + blockSize) { const binarySubString = String.fromCharCode.apply(null, utf8Array.subarray(i, i + blockSize)); binaryString = binaryString + binarySubString; } return binaryString; }
javascript
function buildBinaryString (arrayBuffer) { var binaryString = ""; const utf8Array = new Uint8Array(arrayBuffer); const blockSize = 16384; for (var i = 0; i < utf8Array.length; i = i + blockSize) { const binarySubString = String.fromCharCode.apply(null, utf8Array.subarray(i, i + blockSize)); binaryString = binaryString + binarySubString; } return binaryString; }
[ "function", "buildBinaryString", "(", "arrayBuffer", ")", "{", "var", "binaryString", "=", "\"\"", ";", "const", "utf8Array", "=", "new", "Uint8Array", "(", "arrayBuffer", ")", ";", "const", "blockSize", "=", "16384", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "utf8Array", ".", "length", ";", "i", "=", "i", "+", "blockSize", ")", "{", "const", "binarySubString", "=", "String", ".", "fromCharCode", ".", "apply", "(", "null", ",", "utf8Array", ".", "subarray", "(", "i", ",", "i", "+", "blockSize", ")", ")", ";", "binaryString", "=", "binaryString", "+", "binarySubString", ";", "}", "return", "binaryString", ";", "}" ]
Use this method to convert a string buffer array to a binary string. Do so by breaking up large strings into smaller substrings; this is necessary to avoid the "maximum call stack size exceeded" exception that can happen when calling 'String.fromCharCode.apply' with a very long array.
[ "Use", "this", "method", "to", "convert", "a", "string", "buffer", "array", "to", "a", "binary", "string", ".", "Do", "so", "by", "breaking", "up", "large", "strings", "into", "smaller", "substrings", ";", "this", "is", "necessary", "to", "avoid", "the", "maximum", "call", "stack", "size", "exceeded", "exception", "that", "can", "happen", "when", "calling", "String", ".", "fromCharCode", ".", "apply", "with", "a", "very", "long", "array", "." ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.composeImages.js#L157-L166
train
ni-kismet/engineering-flot
source/jquery.flot.legend.js
getEntryIconHtml
function getEntryIconHtml(shape) { var html = '', name = shape.name, x = shape.xPos, y = shape.yPos, fill = shape.fillColor, stroke = shape.strokeColor, width = shape.strokeWidth; switch (name) { case 'circle': html = '<use xlink:href="#circle" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'diamond': html = '<use xlink:href="#diamond" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'cross': html = '<use xlink:href="#cross" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + // 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'rectangle': html = '<use xlink:href="#rectangle" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'plus': html = '<use xlink:href="#plus" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + // 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'bar': html = '<use xlink:href="#bars" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + // 'stroke="' + stroke + '" ' + // 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'area': html = '<use xlink:href="#area" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + // 'stroke="' + stroke + '" ' + // 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'line': html = '<use xlink:href="#line" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + // 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; default: // default is circle html = '<use xlink:href="#circle" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; } return html; }
javascript
function getEntryIconHtml(shape) { var html = '', name = shape.name, x = shape.xPos, y = shape.yPos, fill = shape.fillColor, stroke = shape.strokeColor, width = shape.strokeWidth; switch (name) { case 'circle': html = '<use xlink:href="#circle" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'diamond': html = '<use xlink:href="#diamond" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'cross': html = '<use xlink:href="#cross" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + // 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'rectangle': html = '<use xlink:href="#rectangle" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'plus': html = '<use xlink:href="#plus" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + // 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'bar': html = '<use xlink:href="#bars" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + // 'stroke="' + stroke + '" ' + // 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'area': html = '<use xlink:href="#area" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + // 'stroke="' + stroke + '" ' + // 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; case 'line': html = '<use xlink:href="#line" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + // 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; break; default: // default is circle html = '<use xlink:href="#circle" class="legendIcon" ' + 'x="' + x + '" ' + 'y="' + y + '" ' + 'fill="' + fill + '" ' + 'stroke="' + stroke + '" ' + 'stroke-width="' + width + '" ' + 'width="1.5em" height="1.5em"' + '/>'; } return html; }
[ "function", "getEntryIconHtml", "(", "shape", ")", "{", "var", "html", "=", "''", ",", "name", "=", "shape", ".", "name", ",", "x", "=", "shape", ".", "xPos", ",", "y", "=", "shape", ".", "yPos", ",", "fill", "=", "shape", ".", "fillColor", ",", "stroke", "=", "shape", ".", "strokeColor", ",", "width", "=", "shape", ".", "strokeWidth", ";", "switch", "(", "name", ")", "{", "case", "'circle'", ":", "html", "=", "'<use xlink:href=\"#circle\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'fill=\"'", "+", "fill", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'diamond'", ":", "html", "=", "'<use xlink:href=\"#diamond\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'fill=\"'", "+", "fill", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'cross'", ":", "html", "=", "'<use xlink:href=\"#cross\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'rectangle'", ":", "html", "=", "'<use xlink:href=\"#rectangle\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'fill=\"'", "+", "fill", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'plus'", ":", "html", "=", "'<use xlink:href=\"#plus\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'bar'", ":", "html", "=", "'<use xlink:href=\"#bars\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'fill=\"'", "+", "fill", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'area'", ":", "html", "=", "'<use xlink:href=\"#area\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'fill=\"'", "+", "fill", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "case", "'line'", ":", "html", "=", "'<use xlink:href=\"#line\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "break", ";", "default", ":", "html", "=", "'<use xlink:href=\"#circle\" class=\"legendIcon\" '", "+", "'x=\"'", "+", "x", "+", "'\" '", "+", "'y=\"'", "+", "y", "+", "'\" '", "+", "'fill=\"'", "+", "fill", "+", "'\" '", "+", "'stroke=\"'", "+", "stroke", "+", "'\" '", "+", "'stroke-width=\"'", "+", "width", "+", "'\" '", "+", "'width=\"1.5em\" height=\"1.5em\"'", "+", "'/>'", ";", "}", "return", "html", ";", "}" ]
Generate html for a shape
[ "Generate", "html", "for", "a", "shape" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.legend.js#L123-L225
train
ni-kismet/engineering-flot
source/jquery.flot.legend.js
getLegendEntries
function getLegendEntries(series, labelFormatter, sorted) { var lf = labelFormatter, legendEntries = series.map(function(s, i) { return { label: (lf ? lf(s.label, s) : s.label) || 'Plot ' + (i + 1), color: s.color, options: { lines: s.lines, points: s.points, bars: s.bars } }; }); // Sort the legend using either the default or a custom comparator if (sorted) { if ($.isFunction(sorted)) { legendEntries.sort(sorted); } else if (sorted === 'reverse') { legendEntries.reverse(); } else { var ascending = (sorted !== 'descending'); legendEntries.sort(function(a, b) { return a.label === b.label ? 0 : ((a.label < b.label) !== ascending ? 1 : -1 // Logical XOR ); }); } } return legendEntries; }
javascript
function getLegendEntries(series, labelFormatter, sorted) { var lf = labelFormatter, legendEntries = series.map(function(s, i) { return { label: (lf ? lf(s.label, s) : s.label) || 'Plot ' + (i + 1), color: s.color, options: { lines: s.lines, points: s.points, bars: s.bars } }; }); // Sort the legend using either the default or a custom comparator if (sorted) { if ($.isFunction(sorted)) { legendEntries.sort(sorted); } else if (sorted === 'reverse') { legendEntries.reverse(); } else { var ascending = (sorted !== 'descending'); legendEntries.sort(function(a, b) { return a.label === b.label ? 0 : ((a.label < b.label) !== ascending ? 1 : -1 // Logical XOR ); }); } } return legendEntries; }
[ "function", "getLegendEntries", "(", "series", ",", "labelFormatter", ",", "sorted", ")", "{", "var", "lf", "=", "labelFormatter", ",", "legendEntries", "=", "series", ".", "map", "(", "function", "(", "s", ",", "i", ")", "{", "return", "{", "label", ":", "(", "lf", "?", "lf", "(", "s", ".", "label", ",", "s", ")", ":", "s", ".", "label", ")", "||", "'Plot '", "+", "(", "i", "+", "1", ")", ",", "color", ":", "s", ".", "color", ",", "options", ":", "{", "lines", ":", "s", ".", "lines", ",", "points", ":", "s", ".", "points", ",", "bars", ":", "s", ".", "bars", "}", "}", ";", "}", ")", ";", "if", "(", "sorted", ")", "{", "if", "(", "$", ".", "isFunction", "(", "sorted", ")", ")", "{", "legendEntries", ".", "sort", "(", "sorted", ")", ";", "}", "else", "if", "(", "sorted", "===", "'reverse'", ")", "{", "legendEntries", ".", "reverse", "(", ")", ";", "}", "else", "{", "var", "ascending", "=", "(", "sorted", "!==", "'descending'", ")", ";", "legendEntries", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "label", "===", "b", ".", "label", "?", "0", ":", "(", "(", "a", ".", "label", "<", "b", ".", "label", ")", "!==", "ascending", "?", "1", ":", "-", "1", ")", ";", "}", ")", ";", "}", "}", "return", "legendEntries", ";", "}" ]
Generate a list of legend entries in their final order
[ "Generate", "a", "list", "of", "legend", "entries", "in", "their", "final", "order" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.legend.js#L279-L311
train
ni-kismet/engineering-flot
source/jquery.flot.legend.js
checkOptions
function checkOptions(opts1, opts2) { for (var prop in opts1) { if (opts1.hasOwnProperty(prop)) { if (opts1[prop] !== opts2[prop]) { return true; } } } return false; }
javascript
function checkOptions(opts1, opts2) { for (var prop in opts1) { if (opts1.hasOwnProperty(prop)) { if (opts1[prop] !== opts2[prop]) { return true; } } } return false; }
[ "function", "checkOptions", "(", "opts1", ",", "opts2", ")", "{", "for", "(", "var", "prop", "in", "opts1", ")", "{", "if", "(", "opts1", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "if", "(", "opts1", "[", "prop", "]", "!==", "opts2", "[", "prop", "]", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
return false if opts1 same as opts2
[ "return", "false", "if", "opts1", "same", "as", "opts2" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.legend.js#L314-L323
train
ni-kismet/engineering-flot
source/jquery.flot.legend.js
shouldRedraw
function shouldRedraw(oldEntries, newEntries) { if (!oldEntries || !newEntries) { return true; } if (oldEntries.length !== newEntries.length) { return true; } var i, newEntry, oldEntry, newOpts, oldOpts; for (i = 0; i < newEntries.length; i++) { newEntry = newEntries[i]; oldEntry = oldEntries[i]; if (newEntry.label !== oldEntry.label) { return true; } if (newEntry.color !== oldEntry.color) { return true; } // check for changes in lines options newOpts = newEntry.options.lines; oldOpts = oldEntry.options.lines; if (checkOptions(newOpts, oldOpts)) { return true; } // check for changes in points options newOpts = newEntry.options.points; oldOpts = oldEntry.options.points; if (checkOptions(newOpts, oldOpts)) { return true; } // check for changes in bars options newOpts = newEntry.options.bars; oldOpts = oldEntry.options.bars; if (checkOptions(newOpts, oldOpts)) { return true; } } return false; }
javascript
function shouldRedraw(oldEntries, newEntries) { if (!oldEntries || !newEntries) { return true; } if (oldEntries.length !== newEntries.length) { return true; } var i, newEntry, oldEntry, newOpts, oldOpts; for (i = 0; i < newEntries.length; i++) { newEntry = newEntries[i]; oldEntry = oldEntries[i]; if (newEntry.label !== oldEntry.label) { return true; } if (newEntry.color !== oldEntry.color) { return true; } // check for changes in lines options newOpts = newEntry.options.lines; oldOpts = oldEntry.options.lines; if (checkOptions(newOpts, oldOpts)) { return true; } // check for changes in points options newOpts = newEntry.options.points; oldOpts = oldEntry.options.points; if (checkOptions(newOpts, oldOpts)) { return true; } // check for changes in bars options newOpts = newEntry.options.bars; oldOpts = oldEntry.options.bars; if (checkOptions(newOpts, oldOpts)) { return true; } } return false; }
[ "function", "shouldRedraw", "(", "oldEntries", ",", "newEntries", ")", "{", "if", "(", "!", "oldEntries", "||", "!", "newEntries", ")", "{", "return", "true", ";", "}", "if", "(", "oldEntries", ".", "length", "!==", "newEntries", ".", "length", ")", "{", "return", "true", ";", "}", "var", "i", ",", "newEntry", ",", "oldEntry", ",", "newOpts", ",", "oldOpts", ";", "for", "(", "i", "=", "0", ";", "i", "<", "newEntries", ".", "length", ";", "i", "++", ")", "{", "newEntry", "=", "newEntries", "[", "i", "]", ";", "oldEntry", "=", "oldEntries", "[", "i", "]", ";", "if", "(", "newEntry", ".", "label", "!==", "oldEntry", ".", "label", ")", "{", "return", "true", ";", "}", "if", "(", "newEntry", ".", "color", "!==", "oldEntry", ".", "color", ")", "{", "return", "true", ";", "}", "newOpts", "=", "newEntry", ".", "options", ".", "lines", ";", "oldOpts", "=", "oldEntry", ".", "options", ".", "lines", ";", "if", "(", "checkOptions", "(", "newOpts", ",", "oldOpts", ")", ")", "{", "return", "true", ";", "}", "newOpts", "=", "newEntry", ".", "options", ".", "points", ";", "oldOpts", "=", "oldEntry", ".", "options", ".", "points", ";", "if", "(", "checkOptions", "(", "newOpts", ",", "oldOpts", ")", ")", "{", "return", "true", ";", "}", "newOpts", "=", "newEntry", ".", "options", ".", "bars", ";", "oldOpts", "=", "oldEntry", ".", "options", ".", "bars", ";", "if", "(", "checkOptions", "(", "newOpts", ",", "oldOpts", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Compare two lists of legend entries
[ "Compare", "two", "lists", "of", "legend", "entries" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.legend.js#L326-L370
train
ni-kismet/engineering-flot
source/jquery.flot.js
function (value) { var bw = options.grid.borderWidth; return (((typeof bw === "object" && bw[axis.position] > 0) || bw > 0) && (value === axis.min || value === axis.max)); }
javascript
function (value) { var bw = options.grid.borderWidth; return (((typeof bw === "object" && bw[axis.position] > 0) || bw > 0) && (value === axis.min || value === axis.max)); }
[ "function", "(", "value", ")", "{", "var", "bw", "=", "options", ".", "grid", ".", "borderWidth", ";", "return", "(", "(", "(", "typeof", "bw", "===", "\"object\"", "&&", "bw", "[", "axis", ".", "position", "]", ">", "0", ")", "||", "bw", ">", "0", ")", "&&", "(", "value", "===", "axis", ".", "min", "||", "value", "===", "axis", ".", "max", ")", ")", ";", "}" ]
check if the line will be overlapped with a border
[ "check", "if", "the", "line", "will", "be", "overlapped", "with", "a", "border" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.js#L2111-L2114
train
ni-kismet/engineering-flot
lib/jquery.event.drag.js
function( data ){ data = $.extend({ distance: drag.distance, which: drag.which, not: drag.not, drop: drag.drop }, data || {}); data.distance = squared( data.distance ); // x² + y² = distance² $event.add( this, "mousedown", handler, data ); if ( this.attachEvent ) this.attachEvent("ondragstart", dontStart ); // prevent image dragging in IE... }
javascript
function( data ){ data = $.extend({ distance: drag.distance, which: drag.which, not: drag.not, drop: drag.drop }, data || {}); data.distance = squared( data.distance ); // x² + y² = distance² $event.add( this, "mousedown", handler, data ); if ( this.attachEvent ) this.attachEvent("ondragstart", dontStart ); // prevent image dragging in IE... }
[ "function", "(", "data", ")", "{", "data", "=", "$", ".", "extend", "(", "{", "distance", ":", "drag", ".", "distance", ",", "which", ":", "drag", ".", "which", ",", "not", ":", "drag", ".", "not", ",", "drop", ":", "drag", ".", "drop", "}", ",", "data", "||", "{", "}", ")", ";", "data", ".", "distance", "=", "squared", "(", "data", ".", "distance", ")", ";", "$event", ".", "add", "(", "this", ",", "\"mousedown\"", ",", "handler", ",", "data", ")", ";", "if", "(", "this", ".", "attachEvent", ")", "this", ".", "attachEvent", "(", "\"ondragstart\"", ",", "dontStart", ")", ";", "}" ]
hold the active target element
[ "hold", "the", "active", "target", "element" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/lib/jquery.event.drag.js#L37-L47
train
ni-kismet/engineering-flot
lib/jquery.event.drag.js
hijack
function hijack ( event, type, elem ){ event.type = type; // force the event type var result = ($.event.dispatch || $.event.handle).call( elem, event ); return result===false ? false : result || event.result; }
javascript
function hijack ( event, type, elem ){ event.type = type; // force the event type var result = ($.event.dispatch || $.event.handle).call( elem, event ); return result===false ? false : result || event.result; }
[ "function", "hijack", "(", "event", ",", "type", ",", "elem", ")", "{", "event", ".", "type", "=", "type", ";", "var", "result", "=", "(", "$", ".", "event", ".", "dispatch", "||", "$", ".", "event", ".", "handle", ")", ".", "call", "(", "elem", ",", "event", ")", ";", "return", "result", "===", "false", "?", "false", ":", "result", "||", "event", ".", "result", ";", "}" ]
set event type to custom value, and handle it
[ "set", "event", "type", "to", "custom", "value", "and", "handle", "it" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/lib/jquery.event.drag.js#L123-L127
train
ni-kismet/engineering-flot
lib/jquery.event.drag.js
selectable
function selectable ( elem, bool ){ if ( !elem ) return; // maybe element was removed ? elem = elem.ownerDocument ? elem.ownerDocument : elem; elem.unselectable = bool ? "off" : "on"; // IE if ( elem.style ) elem.style.MozUserSelect = bool ? "" : "none"; // FF $.event[ bool ? "remove" : "add" ]( elem, "selectstart mousedown", dontStart ); // IE/Opera }
javascript
function selectable ( elem, bool ){ if ( !elem ) return; // maybe element was removed ? elem = elem.ownerDocument ? elem.ownerDocument : elem; elem.unselectable = bool ? "off" : "on"; // IE if ( elem.style ) elem.style.MozUserSelect = bool ? "" : "none"; // FF $.event[ bool ? "remove" : "add" ]( elem, "selectstart mousedown", dontStart ); // IE/Opera }
[ "function", "selectable", "(", "elem", ",", "bool", ")", "{", "if", "(", "!", "elem", ")", "return", ";", "elem", "=", "elem", ".", "ownerDocument", "?", "elem", ".", "ownerDocument", ":", "elem", ";", "elem", ".", "unselectable", "=", "bool", "?", "\"off\"", ":", "\"on\"", ";", "if", "(", "elem", ".", "style", ")", "elem", ".", "style", ".", "MozUserSelect", "=", "bool", "?", "\"\"", ":", "\"none\"", ";", "$", ".", "event", "[", "bool", "?", "\"remove\"", ":", "\"add\"", "]", "(", "elem", ",", "\"selectstart mousedown\"", ",", "dontStart", ")", ";", "}" ]
toggles text selection attributes
[ "toggles", "text", "selection", "attributes" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/lib/jquery.event.drag.js#L136-L142
train
ni-kismet/engineering-flot
source/jquery.flot.browser.js
function() { // *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser // Safari 3.0+ "[object HTMLElementConstructor]" return /constructor/i.test(window.top.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.top['safari'] || (typeof window.top.safari !== 'undefined' && window.top.safari.pushNotification)); }
javascript
function() { // *** https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser // Safari 3.0+ "[object HTMLElementConstructor]" return /constructor/i.test(window.top.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.top['safari'] || (typeof window.top.safari !== 'undefined' && window.top.safari.pushNotification)); }
[ "function", "(", ")", "{", "return", "/", "constructor", "/", "i", ".", "test", "(", "window", ".", "top", ".", "HTMLElement", ")", "||", "(", "function", "(", "p", ")", "{", "return", "p", ".", "toString", "(", ")", "===", "\"[object SafariRemoteNotification]\"", ";", "}", ")", "(", "!", "window", ".", "top", "[", "'safari'", "]", "||", "(", "typeof", "window", ".", "top", ".", "safari", "!==", "'undefined'", "&&", "window", ".", "top", ".", "safari", ".", "pushNotification", ")", ")", ";", "}" ]
- isSafari, isMobileSafari, isOpera, isFirefox, isIE, isEdge, isChrome, isBlink This is a collection of functions, used to check if the code is running in a particular browser or Javascript engine.
[ "-", "isSafari", "isMobileSafari", "isOpera", "isFirefox", "isIE", "isEdge", "isChrome", "isBlink" ]
65afa46ca42cd2b385ab5de460550e4734f43705
https://github.com/ni-kismet/engineering-flot/blob/65afa46ca42cd2b385ab5de460550e4734f43705/source/jquery.flot.browser.js#L50-L54
train
Dzenly/tia
api/extjs/browser-part/e-br.js
isExtJsReady
function isExtJsReady() { return !(typeof Ext === 'undefined' || !Ext.isReady || typeof Ext.onReady === 'undefined' || typeof Ext.Ajax === 'undefined' || typeof Ext.Ajax.on === 'undefined'); }
javascript
function isExtJsReady() { return !(typeof Ext === 'undefined' || !Ext.isReady || typeof Ext.onReady === 'undefined' || typeof Ext.Ajax === 'undefined' || typeof Ext.Ajax.on === 'undefined'); }
[ "function", "isExtJsReady", "(", ")", "{", "return", "!", "(", "typeof", "Ext", "===", "'undefined'", "||", "!", "Ext", ".", "isReady", "||", "typeof", "Ext", ".", "onReady", "===", "'undefined'", "||", "typeof", "Ext", ".", "Ajax", "===", "'undefined'", "||", "typeof", "Ext", ".", "Ajax", ".", "on", "===", "'undefined'", ")", ";", "}" ]
It if returns true there is not a bad chance that ExtJs application is ready to use. Deprecated.
[ "It", "if", "returns", "true", "there", "is", "not", "a", "bad", "chance", "that", "ExtJs", "application", "is", "ready", "to", "use", ".", "Deprecated", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br.js#L113-L116
train
Dzenly/tia
api/extjs/browser-part/e-br.js
getStoreData
function getStoreData(storeId, field) { var arr = Ext.StoreManager.get(storeId).getRange(); var res = arr.map(function (elem) { return elem[field]; }); return res; }
javascript
function getStoreData(storeId, field) { var arr = Ext.StoreManager.get(storeId).getRange(); var res = arr.map(function (elem) { return elem[field]; }); return res; }
[ "function", "getStoreData", "(", "storeId", ",", "field", ")", "{", "var", "arr", "=", "Ext", ".", "StoreManager", ".", "get", "(", "storeId", ")", ".", "getRange", "(", ")", ";", "var", "res", "=", "arr", ".", "map", "(", "function", "(", "elem", ")", "{", "return", "elem", "[", "field", "]", ";", "}", ")", ";", "return", "res", ";", "}" ]
If field is omited - all data will be fetched.
[ "If", "field", "is", "omited", "-", "all", "data", "will", "be", "fetched", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br.js#L152-L158
train
Dzenly/tia
api/extjs/browser-part/e-br.js
replaceLocKeys
function replaceLocKeys(str) { var reExtra = /el"(.*?)"/g; var result = str.replace(reExtra, function (m, key) { return '"' + tiaEJ.getLocaleValue(key, true) + '"'; }); var re = /l"(.*?)"/g; result = result.replace(re, function (m, key) { return '"' + tiaEJ.getLocaleValue(key) + '"'; }); result = result.replace(/,/g, '\\,'); return result; }
javascript
function replaceLocKeys(str) { var reExtra = /el"(.*?)"/g; var result = str.replace(reExtra, function (m, key) { return '"' + tiaEJ.getLocaleValue(key, true) + '"'; }); var re = /l"(.*?)"/g; result = result.replace(re, function (m, key) { return '"' + tiaEJ.getLocaleValue(key) + '"'; }); result = result.replace(/,/g, '\\,'); return result; }
[ "function", "replaceLocKeys", "(", "str", ")", "{", "var", "reExtra", "=", "/", "el\"(.*?)\"", "/", "g", ";", "var", "result", "=", "str", ".", "replace", "(", "reExtra", ",", "function", "(", "m", ",", "key", ")", "{", "return", "'\"'", "+", "tiaEJ", ".", "getLocaleValue", "(", "key", ",", "true", ")", "+", "'\"'", ";", "}", ")", ";", "var", "re", "=", "/", "l\"(.*?)\"", "/", "g", ";", "result", "=", "result", ".", "replace", "(", "re", ",", "function", "(", "m", ",", "key", ")", "{", "return", "'\"'", "+", "tiaEJ", ".", "getLocaleValue", "(", "key", ")", "+", "'\"'", ";", "}", ")", ";", "result", "=", "result", ".", "replace", "(", "/", ",", "/", "g", ",", "'\\\\,'", ")", ";", "\\\\", "}" ]
Replaces 'l"locale_key"' by '"text"', where text is the locale value for the given key. @param {String} str - input string. @return {String} - string with replaced text.
[ "Replaces", "l", "locale_key", "by", "text", "where", "text", "is", "the", "locale", "value", "for", "the", "given", "key", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br.js#L253-L266
train
Dzenly/tia
engine/runner.js
handleDirConfig
function handleDirConfig(dir, files, parentDirConfig) { let config; if (files.includes(gT.engineConsts.dirConfigName)) { config = nodeUtils.requireEx(path.join(dir, gT.engineConsts.dirConfigName), true).result; } else { config = {}; } // TODO: some error when suite configs or root configs is met in wrong places. _.pullAll(files, [ gT.engineConsts.suiteConfigName, gT.engineConsts.dirConfigName, gT.engineConsts.suiteResDirName, gT.engineConsts.rootResDirName, gT.engineConsts.dirRootConfigName, gT.engineConsts.suiteRootConfigName, ]); if (config.require) { nodeUtils.requireArray(config.require); } const dirCfg = _.merge(_.cloneDeep(parentDirConfig), config); if (dirCfg.ignoreNames) { _.pullAll(files, dirCfg.ignoreNames); } if (config.browserProfileDir) { dirCfg.browserProfilePath = path.join(gIn.suite.browserProfilesPath, config.browserProfileDir); } else { dirCfg.browserProfilePath = gT.defaultRootProfile; } gIn.tracer.msg2(`Profile path: ${dirCfg.browserProfilePath}`); return dirCfg; }
javascript
function handleDirConfig(dir, files, parentDirConfig) { let config; if (files.includes(gT.engineConsts.dirConfigName)) { config = nodeUtils.requireEx(path.join(dir, gT.engineConsts.dirConfigName), true).result; } else { config = {}; } // TODO: some error when suite configs or root configs is met in wrong places. _.pullAll(files, [ gT.engineConsts.suiteConfigName, gT.engineConsts.dirConfigName, gT.engineConsts.suiteResDirName, gT.engineConsts.rootResDirName, gT.engineConsts.dirRootConfigName, gT.engineConsts.suiteRootConfigName, ]); if (config.require) { nodeUtils.requireArray(config.require); } const dirCfg = _.merge(_.cloneDeep(parentDirConfig), config); if (dirCfg.ignoreNames) { _.pullAll(files, dirCfg.ignoreNames); } if (config.browserProfileDir) { dirCfg.browserProfilePath = path.join(gIn.suite.browserProfilesPath, config.browserProfileDir); } else { dirCfg.browserProfilePath = gT.defaultRootProfile; } gIn.tracer.msg2(`Profile path: ${dirCfg.browserProfilePath}`); return dirCfg; }
[ "function", "handleDirConfig", "(", "dir", ",", "files", ",", "parentDirConfig", ")", "{", "let", "config", ";", "if", "(", "files", ".", "includes", "(", "gT", ".", "engineConsts", ".", "dirConfigName", ")", ")", "{", "config", "=", "nodeUtils", ".", "requireEx", "(", "path", ".", "join", "(", "dir", ",", "gT", ".", "engineConsts", ".", "dirConfigName", ")", ",", "true", ")", ".", "result", ";", "}", "else", "{", "config", "=", "{", "}", ";", "}", "_", ".", "pullAll", "(", "files", ",", "[", "gT", ".", "engineConsts", ".", "suiteConfigName", ",", "gT", ".", "engineConsts", ".", "dirConfigName", ",", "gT", ".", "engineConsts", ".", "suiteResDirName", ",", "gT", ".", "engineConsts", ".", "rootResDirName", ",", "gT", ".", "engineConsts", ".", "dirRootConfigName", ",", "gT", ".", "engineConsts", ".", "suiteRootConfigName", ",", "]", ")", ";", "if", "(", "config", ".", "require", ")", "{", "nodeUtils", ".", "requireArray", "(", "config", ".", "require", ")", ";", "}", "const", "dirCfg", "=", "_", ".", "merge", "(", "_", ".", "cloneDeep", "(", "parentDirConfig", ")", ",", "config", ")", ";", "if", "(", "dirCfg", ".", "ignoreNames", ")", "{", "_", ".", "pullAll", "(", "files", ",", "dirCfg", ".", "ignoreNames", ")", ";", "}", "if", "(", "config", ".", "browserProfileDir", ")", "{", "dirCfg", ".", "browserProfilePath", "=", "path", ".", "join", "(", "gIn", ".", "suite", ".", "browserProfilesPath", ",", "config", ".", "browserProfileDir", ")", ";", "}", "else", "{", "dirCfg", ".", "browserProfilePath", "=", "gT", ".", "defaultRootProfile", ";", "}", "gIn", ".", "tracer", ".", "msg2", "(", "`", "${", "dirCfg", ".", "browserProfilePath", "}", "`", ")", ";", "return", "dirCfg", ";", "}" ]
Removes config from files. Merges current config to parrent config. Also removes names specified by config.ignoreNames. @param {String} dir @param {Array<String>} files @param {Object} parentDirConfig @return {Object} directory config.
[ "Removes", "config", "from", "files", ".", "Merges", "current", "config", "to", "parrent", "config", ".", "Also", "removes", "names", "specified", "by", "config", ".", "ignoreNames", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/engine/runner.js#L150-L187
train
Dzenly/tia
utils/mail-utils.js
getSmtpTransporter
function getSmtpTransporter() { return nodemailer.createTransport( smtpTransport({ // service: 'tia', host: gT.suiteConfig.mailSmtpHost, secure: true, // secure : false, // port: 25, auth: { user: gT.suiteConfig.mailUser, pass: gT.suiteConfig.mailPassword, }, // , tls: { // rejectUnauthorized: false // } }) ); }
javascript
function getSmtpTransporter() { return nodemailer.createTransport( smtpTransport({ // service: 'tia', host: gT.suiteConfig.mailSmtpHost, secure: true, // secure : false, // port: 25, auth: { user: gT.suiteConfig.mailUser, pass: gT.suiteConfig.mailPassword, }, // , tls: { // rejectUnauthorized: false // } }) ); }
[ "function", "getSmtpTransporter", "(", ")", "{", "return", "nodemailer", ".", "createTransport", "(", "smtpTransport", "(", "{", "host", ":", "gT", ".", "suiteConfig", ".", "mailSmtpHost", ",", "secure", ":", "true", ",", "auth", ":", "{", "user", ":", "gT", ".", "suiteConfig", ".", "mailUser", ",", "pass", ":", "gT", ".", "suiteConfig", ".", "mailPassword", ",", "}", ",", "}", ")", ")", ";", "}" ]
create reusable transporter object using SMTP transport Some antiviruses can block sending with self signed certificate. If this is your case -
[ "create", "reusable", "transporter", "object", "using", "SMTP", "transport", "Some", "antiviruses", "can", "block", "sending", "with", "self", "signed", "certificate", ".", "If", "this", "is", "your", "case", "-" ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/utils/mail-utils.js#L16-L35
train
Dzenly/tia
engine/loggers/console-logger.js
trackEOL
function trackEOL(msg) { if (msg === true || Boolean(msg.match(/(\n|\r)$/))) { gIn.tracePrefix = ''; } else { gIn.tracePrefix = '\n'; } }
javascript
function trackEOL(msg) { if (msg === true || Boolean(msg.match(/(\n|\r)$/))) { gIn.tracePrefix = ''; } else { gIn.tracePrefix = '\n'; } }
[ "function", "trackEOL", "(", "msg", ")", "{", "if", "(", "msg", "===", "true", "||", "Boolean", "(", "msg", ".", "match", "(", "/", "(\\n|\\r)$", "/", ")", ")", ")", "{", "gIn", ".", "tracePrefix", "=", "''", ";", "}", "else", "{", "gIn", ".", "tracePrefix", "=", "'\\n'", ";", "}", "}" ]
Tracks EOL of last message printed to console. Also msg can be boolean - true means there is EOL. @param msg
[ "Tracks", "EOL", "of", "last", "message", "printed", "to", "console", ".", "Also", "msg", "can", "be", "boolean", "-", "true", "means", "there", "is", "EOL", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/engine/loggers/console-logger.js#L24-L30
train
Dzenly/tia
api/assertions.js
failWrapper
function failWrapper(msg, mode) { gT.l.fail(msg); if (mode && mode.accName) { mode.accName = false; // eslint-disable-line no-param-reassign } }
javascript
function failWrapper(msg, mode) { gT.l.fail(msg); if (mode && mode.accName) { mode.accName = false; // eslint-disable-line no-param-reassign } }
[ "function", "failWrapper", "(", "msg", ",", "mode", ")", "{", "gT", ".", "l", ".", "fail", "(", "msg", ")", ";", "if", "(", "mode", "&&", "mode", ".", "accName", ")", "{", "mode", ".", "accName", "=", "false", ";", "}", "}" ]
For shortening the code. Adds result accumulators usage to fail call. @param msg @param mode
[ "For", "shortening", "the", "code", ".", "Adds", "result", "accumulators", "usage", "to", "fail", "call", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/assertions.js#L45-L50
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
doesStoreContainField
function doesStoreContainField(store, fieldName) { var model = store.first(); if (typeof model.get(fieldName) !== 'undefined') { return true; } return model.getField(fieldName) != null; }
javascript
function doesStoreContainField(store, fieldName) { var model = store.first(); if (typeof model.get(fieldName) !== 'undefined') { return true; } return model.getField(fieldName) != null; }
[ "function", "doesStoreContainField", "(", "store", ",", "fieldName", ")", "{", "var", "model", "=", "store", ".", "first", "(", ")", ";", "if", "(", "typeof", "model", ".", "get", "(", "fieldName", ")", "!==", "'undefined'", ")", "{", "return", "true", ";", "}", "return", "model", ".", "getField", "(", "fieldName", ")", "!=", "null", ";", "}" ]
Store must contain at least one record.
[ "Store", "must", "contain", "at", "least", "one", "record", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L72-L78
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
getCols
function getCols(table) { var panel = tiaEJ.search.parentPanel(table); var columns = panel.getVisibleColumns(); return columns; }
javascript
function getCols(table) { var panel = tiaEJ.search.parentPanel(table); var columns = panel.getVisibleColumns(); return columns; }
[ "function", "getCols", "(", "table", ")", "{", "var", "panel", "=", "tiaEJ", ".", "search", ".", "parentPanel", "(", "table", ")", ";", "var", "columns", "=", "panel", ".", "getVisibleColumns", "(", ")", ";", "return", "columns", ";", "}" ]
Gets columns objects for a table. @param {Ext.view.Table} table - the table. @returns {Array} - columns.
[ "Gets", "columns", "objects", "for", "a", "table", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L285-L289
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
getColSelectors
function getColSelectors(table) { var cols = this.getCols(table); var selectors = cols.map(function (col) { return table.getCellSelector(col); }); return selectors; }
javascript
function getColSelectors(table) { var cols = this.getCols(table); var selectors = cols.map(function (col) { return table.getCellSelector(col); }); return selectors; }
[ "function", "getColSelectors", "(", "table", ")", "{", "var", "cols", "=", "this", ".", "getCols", "(", "table", ")", ";", "var", "selectors", "=", "cols", ".", "map", "(", "function", "(", "col", ")", "{", "return", "table", ".", "getCellSelector", "(", "col", ")", ";", "}", ")", ";", "return", "selectors", ";", "}" ]
Gets column selectors for a table. @param {Ext.view.Table} table - the table. @returns {Array} - strings with selectors.
[ "Gets", "column", "selectors", "for", "a", "table", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L296-L302
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
getColHeaderInfos
function getColHeaderInfos(table) { var cols = this.getCols(table); var arr = cols.map(function (col) { // col.textEl.dom.textContent // slower but more honest. // TODO: getConfig().tooltip - проверить. var text = tiaEJ.convertTextToFirstLocKey(col.text); if (text === col.emptyCellText) { text = ''; // <emptyCell> } var info = col.getConfig('xtype') + ': "' + text + '"'; var toolTip = col.getConfig().toolTip; if (toolTip) { info += ', toolTip: ' + tiaEJ.convertTextToFirstLocKey(toolTip); } // if (col.items) { // info += ', items: ' + JSON.stringify(col.items); // } // if (col.getConfig('xtype') === 'actioncolumn') { // // console.dir(col); // window.c2 = col; // } return info; }); return arr; }
javascript
function getColHeaderInfos(table) { var cols = this.getCols(table); var arr = cols.map(function (col) { // col.textEl.dom.textContent // slower but more honest. // TODO: getConfig().tooltip - проверить. var text = tiaEJ.convertTextToFirstLocKey(col.text); if (text === col.emptyCellText) { text = ''; // <emptyCell> } var info = col.getConfig('xtype') + ': "' + text + '"'; var toolTip = col.getConfig().toolTip; if (toolTip) { info += ', toolTip: ' + tiaEJ.convertTextToFirstLocKey(toolTip); } // if (col.items) { // info += ', items: ' + JSON.stringify(col.items); // } // if (col.getConfig('xtype') === 'actioncolumn') { // // console.dir(col); // window.c2 = col; // } return info; }); return arr; }
[ "function", "getColHeaderInfos", "(", "table", ")", "{", "var", "cols", "=", "this", ".", "getCols", "(", "table", ")", ";", "var", "arr", "=", "cols", ".", "map", "(", "function", "(", "col", ")", "{", "var", "text", "=", "tiaEJ", ".", "convertTextToFirstLocKey", "(", "col", ".", "text", ")", ";", "if", "(", "text", "===", "col", ".", "emptyCellText", ")", "{", "text", "=", "''", ";", "}", "var", "info", "=", "col", ".", "getConfig", "(", "'xtype'", ")", "+", "': \"'", "+", "text", "+", "'\"'", ";", "var", "toolTip", "=", "col", ".", "getConfig", "(", ")", ".", "toolTip", ";", "if", "(", "toolTip", ")", "{", "info", "+=", "', toolTip: '", "+", "tiaEJ", ".", "convertTextToFirstLocKey", "(", "toolTip", ")", ";", "}", "return", "info", ";", "}", ")", ";", "return", "arr", ";", "}" ]
Gets texts from a table header @param {Ext.view.Table} table - the table. @returns {Array} - texts.
[ "Gets", "texts", "from", "a", "table", "header" ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L309-L333
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
getCB
function getCB(cb) { var str = ''; // str += this.getIdItemIdReference(cb) + '\n'; str += this.getCompDispIdProps(cb) + '\n'; str += 'Selected vals: \'' + this.getCBSelectedVals(cb) + '\'\n'; var displayField = this.safeGetConfig(cb, 'displayField'); // str += 'displayField: ' + displayField + '\n'; str += tiaEJ.ctMisc.stringifyStoreField(cb.getStore(), displayField).join('\n') + '\n'; return tia.cC.content.wrap(str); }
javascript
function getCB(cb) { var str = ''; // str += this.getIdItemIdReference(cb) + '\n'; str += this.getCompDispIdProps(cb) + '\n'; str += 'Selected vals: \'' + this.getCBSelectedVals(cb) + '\'\n'; var displayField = this.safeGetConfig(cb, 'displayField'); // str += 'displayField: ' + displayField + '\n'; str += tiaEJ.ctMisc.stringifyStoreField(cb.getStore(), displayField).join('\n') + '\n'; return tia.cC.content.wrap(str); }
[ "function", "getCB", "(", "cb", ")", "{", "var", "str", "=", "''", ";", "str", "+=", "this", ".", "getCompDispIdProps", "(", "cb", ")", "+", "'\\n'", ";", "\\n", "str", "+=", "'Selected vals: \\''", "+", "\\'", "+", "this", ".", "getCBSelectedVals", "(", "cb", ")", ";", "'\\'\\n'", "\\'", "}" ]
Gets text from a ComboBox @param cb @returns {*}
[ "Gets", "text", "from", "a", "ComboBox" ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L454-L465
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
getFormSubmitValues
function getFormSubmitValues(form) { var fields = form.getValues(false, false, false, false); return fields; // O }
javascript
function getFormSubmitValues(form) { var fields = form.getValues(false, false, false, false); return fields; // O }
[ "function", "getFormSubmitValues", "(", "form", ")", "{", "var", "fields", "=", "form", ".", "getValues", "(", "false", ",", "false", ",", "false", ",", "false", ")", ";", "return", "fields", ";", "}" ]
Not very useful. Because it is hard for user, to check values in log. @param form - Ext.form.Panel @returns {Object} - Object with key/value pairs.
[ "Not", "very", "useful", ".", "Because", "it", "is", "hard", "for", "user", "to", "check", "values", "in", "log", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L533-L536
train
Dzenly/tia
api/extjs/browser-part/e-br-content.js
getTree
function getTree(table, options) { if (table.isPanel) { table = table.getView(); } function getDefOpts() { return { throwIfInvisible: false, allFields: false }; } var isVisible = table.isVisible(true); options = tiaEJ.ctMisc.checkVisibilityAndFillOptions(isVisible, options, getDefOpts); var panel = tiaEJ.search.parentPanel(table); var root = panel.getRootNode(); var res = []; function traverseSubTree(node, indent) { var fieldsToPrint = ['text', 'checked', 'id']; if (tia.debugMode) { fieldsToPrint = [ 'text', 'checked', 'id', 'visible', 'expanded', 'leaf', 'expandable', 'index', 'depth', 'qtip', 'qtitle', 'cls' ]; } if (options.allFields) { res.push(indent + tiaEJ.ctMisc.stringifyAllRecord(node, fieldsToPrint, true)); } else { res.push(indent + tiaEJ.ctMisc.stringifyRecord(node, fieldsToPrint, true)); } if (node.hasChildNodes()) { indent += tia.cC.content.indent; node.eachChild(function (curNode) { traverseSubTree(curNode, indent); }); } } traverseSubTree(root, ''); return tia.cC.content.wrap('Tree content: \n' + res.join('\n') + '\n'); }
javascript
function getTree(table, options) { if (table.isPanel) { table = table.getView(); } function getDefOpts() { return { throwIfInvisible: false, allFields: false }; } var isVisible = table.isVisible(true); options = tiaEJ.ctMisc.checkVisibilityAndFillOptions(isVisible, options, getDefOpts); var panel = tiaEJ.search.parentPanel(table); var root = panel.getRootNode(); var res = []; function traverseSubTree(node, indent) { var fieldsToPrint = ['text', 'checked', 'id']; if (tia.debugMode) { fieldsToPrint = [ 'text', 'checked', 'id', 'visible', 'expanded', 'leaf', 'expandable', 'index', 'depth', 'qtip', 'qtitle', 'cls' ]; } if (options.allFields) { res.push(indent + tiaEJ.ctMisc.stringifyAllRecord(node, fieldsToPrint, true)); } else { res.push(indent + tiaEJ.ctMisc.stringifyRecord(node, fieldsToPrint, true)); } if (node.hasChildNodes()) { indent += tia.cC.content.indent; node.eachChild(function (curNode) { traverseSubTree(curNode, indent); }); } } traverseSubTree(root, ''); return tia.cC.content.wrap('Tree content: \n' + res.join('\n') + '\n'); }
[ "function", "getTree", "(", "table", ",", "options", ")", "{", "if", "(", "table", ".", "isPanel", ")", "{", "table", "=", "table", ".", "getView", "(", ")", ";", "}", "function", "getDefOpts", "(", ")", "{", "return", "{", "throwIfInvisible", ":", "false", ",", "allFields", ":", "false", "}", ";", "}", "var", "isVisible", "=", "table", ".", "isVisible", "(", "true", ")", ";", "options", "=", "tiaEJ", ".", "ctMisc", ".", "checkVisibilityAndFillOptions", "(", "isVisible", ",", "options", ",", "getDefOpts", ")", ";", "var", "panel", "=", "tiaEJ", ".", "search", ".", "parentPanel", "(", "table", ")", ";", "var", "root", "=", "panel", ".", "getRootNode", "(", ")", ";", "var", "res", "=", "[", "]", ";", "function", "traverseSubTree", "(", "node", ",", "indent", ")", "{", "var", "fieldsToPrint", "=", "[", "'text'", ",", "'checked'", ",", "'id'", "]", ";", "if", "(", "tia", ".", "debugMode", ")", "{", "fieldsToPrint", "=", "[", "'text'", ",", "'checked'", ",", "'id'", ",", "'visible'", ",", "'expanded'", ",", "'leaf'", ",", "'expandable'", ",", "'index'", ",", "'depth'", ",", "'qtip'", ",", "'qtitle'", ",", "'cls'", "]", ";", "}", "if", "(", "options", ".", "allFields", ")", "{", "res", ".", "push", "(", "indent", "+", "tiaEJ", ".", "ctMisc", ".", "stringifyAllRecord", "(", "node", ",", "fieldsToPrint", ",", "true", ")", ")", ";", "}", "else", "{", "res", ".", "push", "(", "indent", "+", "tiaEJ", ".", "ctMisc", ".", "stringifyRecord", "(", "node", ",", "fieldsToPrint", ",", "true", ")", ")", ";", "}", "if", "(", "node", ".", "hasChildNodes", "(", ")", ")", "{", "indent", "+=", "tia", ".", "cC", ".", "content", ".", "indent", ";", "node", ".", "eachChild", "(", "function", "(", "curNode", ")", "{", "traverseSubTree", "(", "curNode", ",", "indent", ")", ";", "}", ")", ";", "}", "}", "traverseSubTree", "(", "root", ",", "''", ")", ";", "return", "tia", ".", "cC", ".", "content", ".", "wrap", "(", "'Tree content: \\n'", "+", "\\n", "+", "res", ".", "join", "(", "'\\n'", ")", ")", ";", "}" ]
Gets entire tree content. Collapsed nodes are also included in results. @param table @param options @returns {string}
[ "Gets", "entire", "tree", "content", ".", "Collapsed", "nodes", "are", "also", "included", "in", "results", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-content.js#L831-L889
train
Dzenly/tia
api/extjs/browser-part/e-br-explore.js
getControllerInfo
function getControllerInfo(controller, msg) { var res = ['++++++++++', 'CONTROLLER INFO (' + msg + '):', ]; if (!controller) { res.push('N/A'); return res; } var modelStr = ''; var refsObj = controller.getReferences(); var refsStr = Ext.Object.getKeys(refsObj).join(', '); var routesObj = controller.getRoutes(); var routesStr = Ext.Object.getKeys(routesObj).join(', '); // TODO: getStore ?? или это есть во ViewModel? var viewModel = controller.getViewModel(); if (viewModel) { modelStr += 'viewModel.$className: ' + viewModel.$className; } var view = controller.getView(); var viewStr = ''; if (view) { viewStr += 'view.$className: ' + view.$className + ', getConfig("xtype"): ' + view.getConfig('xtype') + ' ' + this.formGetIdStr(view, '18px'); var itemId = view.getConfig('itemId'); if (!autoGenRE.test(itemId)) { viewStr += ', itemId: ' + itemId; } var reference = view.getConfig('reference'); if (reference) { viewStr += ', reference: ' + reference; } } this.pushTextProp(controller, 'alias', res); return res.concat([ 'controller: isViewController: ' + controller.isViewController, 'clName: ' + controller.$className, 'getId(): ' + controller.getId(), 'getReferences(): ' + refsStr, 'routes: ' + routesStr, modelStr, viewStr, '++++++++++', ]); }
javascript
function getControllerInfo(controller, msg) { var res = ['++++++++++', 'CONTROLLER INFO (' + msg + '):', ]; if (!controller) { res.push('N/A'); return res; } var modelStr = ''; var refsObj = controller.getReferences(); var refsStr = Ext.Object.getKeys(refsObj).join(', '); var routesObj = controller.getRoutes(); var routesStr = Ext.Object.getKeys(routesObj).join(', '); // TODO: getStore ?? или это есть во ViewModel? var viewModel = controller.getViewModel(); if (viewModel) { modelStr += 'viewModel.$className: ' + viewModel.$className; } var view = controller.getView(); var viewStr = ''; if (view) { viewStr += 'view.$className: ' + view.$className + ', getConfig("xtype"): ' + view.getConfig('xtype') + ' ' + this.formGetIdStr(view, '18px'); var itemId = view.getConfig('itemId'); if (!autoGenRE.test(itemId)) { viewStr += ', itemId: ' + itemId; } var reference = view.getConfig('reference'); if (reference) { viewStr += ', reference: ' + reference; } } this.pushTextProp(controller, 'alias', res); return res.concat([ 'controller: isViewController: ' + controller.isViewController, 'clName: ' + controller.$className, 'getId(): ' + controller.getId(), 'getReferences(): ' + refsStr, 'routes: ' + routesStr, modelStr, viewStr, '++++++++++', ]); }
[ "function", "getControllerInfo", "(", "controller", ",", "msg", ")", "{", "var", "res", "=", "[", "'++++++++++'", ",", "'CONTROLLER INFO ('", "+", "msg", "+", "'):'", ",", "]", ";", "if", "(", "!", "controller", ")", "{", "res", ".", "push", "(", "'N/A'", ")", ";", "return", "res", ";", "}", "var", "modelStr", "=", "''", ";", "var", "refsObj", "=", "controller", ".", "getReferences", "(", ")", ";", "var", "refsStr", "=", "Ext", ".", "Object", ".", "getKeys", "(", "refsObj", ")", ".", "join", "(", "', '", ")", ";", "var", "routesObj", "=", "controller", ".", "getRoutes", "(", ")", ";", "var", "routesStr", "=", "Ext", ".", "Object", ".", "getKeys", "(", "routesObj", ")", ".", "join", "(", "', '", ")", ";", "var", "viewModel", "=", "controller", ".", "getViewModel", "(", ")", ";", "if", "(", "viewModel", ")", "{", "modelStr", "+=", "'viewModel.$className: '", "+", "viewModel", ".", "$className", ";", "}", "var", "view", "=", "controller", ".", "getView", "(", ")", ";", "var", "viewStr", "=", "''", ";", "if", "(", "view", ")", "{", "viewStr", "+=", "'view.$className: '", "+", "view", ".", "$className", "+", "', getConfig(\"xtype\"): '", "+", "view", ".", "getConfig", "(", "'xtype'", ")", "+", "' '", "+", "this", ".", "formGetIdStr", "(", "view", ",", "'18px'", ")", ";", "var", "itemId", "=", "view", ".", "getConfig", "(", "'itemId'", ")", ";", "if", "(", "!", "autoGenRE", ".", "test", "(", "itemId", ")", ")", "{", "viewStr", "+=", "', itemId: '", "+", "itemId", ";", "}", "var", "reference", "=", "view", ".", "getConfig", "(", "'reference'", ")", ";", "if", "(", "reference", ")", "{", "viewStr", "+=", "', reference: '", "+", "reference", ";", "}", "}", "this", ".", "pushTextProp", "(", "controller", ",", "'alias'", ",", "res", ")", ";", "return", "res", ".", "concat", "(", "[", "'controller: isViewController: '", "+", "controller", ".", "isViewController", ",", "'clName: '", "+", "controller", ".", "$className", ",", "'getId(): '", "+", "controller", ".", "getId", "(", ")", ",", "'getReferences(): '", "+", "refsStr", ",", "'routes: '", "+", "routesStr", ",", "modelStr", ",", "viewStr", ",", "'++++++++++'", ",", "]", ")", ";", "}" ]
Returns array with strings about controller. It is for caller to join them or to add indent to each. @param controller @returns {Array}
[ "Returns", "array", "with", "strings", "about", "controller", ".", "It", "is", "for", "caller", "to", "join", "them", "or", "to", "add", "indent", "to", "each", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-explore.js#L310-L364
train
Dzenly/tia
api/extjs/browser-part/e-br-explore.js
getFormFieldInfo
function getFormFieldInfo(field) { var formFieldArr = [ this.consts.avgSep, 'Form Field Info: ', ]; var name = field.getName() || ''; if (!Boolean(autoGenRE.test(name))) { formFieldArr.push('getName(): ' + this.boldIf(name, name, 'darkgreen')); } tia.cU.dumpObj(field, [ 'getValue()', 'getRawValue()', 'getSubmitValue()', 'getModelData()', 'getSubmitData()', 'getInputId()', 'initialConfig.inputType', 'initialConfig.boxLabel', 'boxLabel', 'inputType', 'getFieldLabel()', 'getActiveError()', 'getErrors()', ], formFieldArr); var store; if (field.isPickerField) { var pickerComp = field.getPicker(); formFieldArr = formFieldArr.concat([ this.consts.tinySep, 'Picker field info:']); tia.cU.dumpObj(pickerComp, ['$className'], formFieldArr); tia.cU.dumpObj(field, [ 'getConfig().displayField', 'initialConfig.hiddenName', ], formFieldArr); formFieldArr.push(this.consts.tinySep); if (field.getStore) { store = field.getStore(); formFieldArr = formFieldArr.concat(this.getStoreContent(store)); } } else if (field.displayField) { formFieldArr = formFieldArr.concat([ this.consts.tinySep, 'Form field containing "displayField" info:']); tia.cU.dumpObj(field, ['$className'], formFieldArr); tia.cU.dumpObj(field, [ 'getConfig().displayField', 'initialConfig.hiddenName', ], formFieldArr); formFieldArr.push(this.consts.tinySep); if (field.getStore) { store = field.getStore(); formFieldArr = formFieldArr.concat(this.getStoreContent(store)); } } formFieldArr.push(this.consts.avgSep); return formFieldArr; }
javascript
function getFormFieldInfo(field) { var formFieldArr = [ this.consts.avgSep, 'Form Field Info: ', ]; var name = field.getName() || ''; if (!Boolean(autoGenRE.test(name))) { formFieldArr.push('getName(): ' + this.boldIf(name, name, 'darkgreen')); } tia.cU.dumpObj(field, [ 'getValue()', 'getRawValue()', 'getSubmitValue()', 'getModelData()', 'getSubmitData()', 'getInputId()', 'initialConfig.inputType', 'initialConfig.boxLabel', 'boxLabel', 'inputType', 'getFieldLabel()', 'getActiveError()', 'getErrors()', ], formFieldArr); var store; if (field.isPickerField) { var pickerComp = field.getPicker(); formFieldArr = formFieldArr.concat([ this.consts.tinySep, 'Picker field info:']); tia.cU.dumpObj(pickerComp, ['$className'], formFieldArr); tia.cU.dumpObj(field, [ 'getConfig().displayField', 'initialConfig.hiddenName', ], formFieldArr); formFieldArr.push(this.consts.tinySep); if (field.getStore) { store = field.getStore(); formFieldArr = formFieldArr.concat(this.getStoreContent(store)); } } else if (field.displayField) { formFieldArr = formFieldArr.concat([ this.consts.tinySep, 'Form field containing "displayField" info:']); tia.cU.dumpObj(field, ['$className'], formFieldArr); tia.cU.dumpObj(field, [ 'getConfig().displayField', 'initialConfig.hiddenName', ], formFieldArr); formFieldArr.push(this.consts.tinySep); if (field.getStore) { store = field.getStore(); formFieldArr = formFieldArr.concat(this.getStoreContent(store)); } } formFieldArr.push(this.consts.avgSep); return formFieldArr; }
[ "function", "getFormFieldInfo", "(", "field", ")", "{", "var", "formFieldArr", "=", "[", "this", ".", "consts", ".", "avgSep", ",", "'Form Field Info: '", ",", "]", ";", "var", "name", "=", "field", ".", "getName", "(", ")", "||", "''", ";", "if", "(", "!", "Boolean", "(", "autoGenRE", ".", "test", "(", "name", ")", ")", ")", "{", "formFieldArr", ".", "push", "(", "'getName(): '", "+", "this", ".", "boldIf", "(", "name", ",", "name", ",", "'darkgreen'", ")", ")", ";", "}", "tia", ".", "cU", ".", "dumpObj", "(", "field", ",", "[", "'getValue()'", ",", "'getRawValue()'", ",", "'getSubmitValue()'", ",", "'getModelData()'", ",", "'getSubmitData()'", ",", "'getInputId()'", ",", "'initialConfig.inputType'", ",", "'initialConfig.boxLabel'", ",", "'boxLabel'", ",", "'inputType'", ",", "'getFieldLabel()'", ",", "'getActiveError()'", ",", "'getErrors()'", ",", "]", ",", "formFieldArr", ")", ";", "var", "store", ";", "if", "(", "field", ".", "isPickerField", ")", "{", "var", "pickerComp", "=", "field", ".", "getPicker", "(", ")", ";", "formFieldArr", "=", "formFieldArr", ".", "concat", "(", "[", "this", ".", "consts", ".", "tinySep", ",", "'Picker field info:'", "]", ")", ";", "tia", ".", "cU", ".", "dumpObj", "(", "pickerComp", ",", "[", "'$className'", "]", ",", "formFieldArr", ")", ";", "tia", ".", "cU", ".", "dumpObj", "(", "field", ",", "[", "'getConfig().displayField'", ",", "'initialConfig.hiddenName'", ",", "]", ",", "formFieldArr", ")", ";", "formFieldArr", ".", "push", "(", "this", ".", "consts", ".", "tinySep", ")", ";", "if", "(", "field", ".", "getStore", ")", "{", "store", "=", "field", ".", "getStore", "(", ")", ";", "formFieldArr", "=", "formFieldArr", ".", "concat", "(", "this", ".", "getStoreContent", "(", "store", ")", ")", ";", "}", "}", "else", "if", "(", "field", ".", "displayField", ")", "{", "formFieldArr", "=", "formFieldArr", ".", "concat", "(", "[", "this", ".", "consts", ".", "tinySep", ",", "'Form field containing \"displayField\" info:'", "]", ")", ";", "tia", ".", "cU", ".", "dumpObj", "(", "field", ",", "[", "'$className'", "]", ",", "formFieldArr", ")", ";", "tia", ".", "cU", ".", "dumpObj", "(", "field", ",", "[", "'getConfig().displayField'", ",", "'initialConfig.hiddenName'", ",", "]", ",", "formFieldArr", ")", ";", "formFieldArr", ".", "push", "(", "this", ".", "consts", ".", "tinySep", ")", ";", "if", "(", "field", ".", "getStore", ")", "{", "store", "=", "field", ".", "getStore", "(", ")", ";", "formFieldArr", "=", "formFieldArr", ".", "concat", "(", "this", ".", "getStoreContent", "(", "store", ")", ")", ";", "}", "}", "formFieldArr", ".", "push", "(", "this", ".", "consts", ".", "avgSep", ")", ";", "return", "formFieldArr", ";", "}" ]
Returns array of strings with info about form field. @param field
[ "Returns", "array", "of", "strings", "with", "info", "about", "form", "field", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-explore.js#L385-L457
train
Dzenly/tia
api/extjs/browser-part/e-br-search.js
parseSearchString
function parseSearchString(str) { str = tia.cU.replaceXTypesInTeq(str); var re = /&(\w|\d|_|-)+/g; var searchData = []; var prevLastIndex = 0; var query; while (true) { var reResult = re.exec(str); if (reResult === null) { // Only query string. query = str.slice(prevLastIndex).trim(); if (query) { searchData.push({ query: query, }); } return searchData; } query = str.slice(prevLastIndex, reResult.index).trim(); var reference = str.slice(reResult.index + 1, re.lastIndex).trim(); prevLastIndex = re.lastIndex; if (query) { searchData.push({ query: query, }); } searchData.push({ reference: reference, }); } }
javascript
function parseSearchString(str) { str = tia.cU.replaceXTypesInTeq(str); var re = /&(\w|\d|_|-)+/g; var searchData = []; var prevLastIndex = 0; var query; while (true) { var reResult = re.exec(str); if (reResult === null) { // Only query string. query = str.slice(prevLastIndex).trim(); if (query) { searchData.push({ query: query, }); } return searchData; } query = str.slice(prevLastIndex, reResult.index).trim(); var reference = str.slice(reResult.index + 1, re.lastIndex).trim(); prevLastIndex = re.lastIndex; if (query) { searchData.push({ query: query, }); } searchData.push({ reference: reference, }); } }
[ "function", "parseSearchString", "(", "str", ")", "{", "str", "=", "tia", ".", "cU", ".", "replaceXTypesInTeq", "(", "str", ")", ";", "var", "re", "=", "/", "&(\\w|\\d|_|-)+", "/", "g", ";", "var", "searchData", "=", "[", "]", ";", "var", "prevLastIndex", "=", "0", ";", "var", "query", ";", "while", "(", "true", ")", "{", "var", "reResult", "=", "re", ".", "exec", "(", "str", ")", ";", "if", "(", "reResult", "===", "null", ")", "{", "query", "=", "str", ".", "slice", "(", "prevLastIndex", ")", ".", "trim", "(", ")", ";", "if", "(", "query", ")", "{", "searchData", ".", "push", "(", "{", "query", ":", "query", ",", "}", ")", ";", "}", "return", "searchData", ";", "}", "query", "=", "str", ".", "slice", "(", "prevLastIndex", ",", "reResult", ".", "index", ")", ".", "trim", "(", ")", ";", "var", "reference", "=", "str", ".", "slice", "(", "reResult", ".", "index", "+", "1", ",", "re", ".", "lastIndex", ")", ".", "trim", "(", ")", ";", "prevLastIndex", "=", "re", ".", "lastIndex", ";", "if", "(", "query", ")", "{", "searchData", ".", "push", "(", "{", "query", ":", "query", ",", "}", ")", ";", "}", "searchData", ".", "push", "(", "{", "reference", ":", "reference", ",", "}", ")", ";", "}", "}" ]
Parses search string into tokens with query and reference. @param str @return {Array}
[ "Parses", "search", "string", "into", "tokens", "with", "query", "and", "reference", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-search.js#L14-L53
train
Dzenly/tia
api/extjs/browser-part/e-br-search.js
byIdRef
function byIdRef(id, ref) { var cmp = this.byId(id).lookupReferenceHolder(false).lookupReference(ref); if (!cmp) { throw new Error('Component not found for container id: ' + id + ', reference: ' + ref); } return cmp; }
javascript
function byIdRef(id, ref) { var cmp = this.byId(id).lookupReferenceHolder(false).lookupReference(ref); if (!cmp) { throw new Error('Component not found for container id: ' + id + ', reference: ' + ref); } return cmp; }
[ "function", "byIdRef", "(", "id", ",", "ref", ")", "{", "var", "cmp", "=", "this", ".", "byId", "(", "id", ")", ".", "lookupReferenceHolder", "(", "false", ")", ".", "lookupReference", "(", "ref", ")", ";", "if", "(", "!", "cmp", ")", "{", "throw", "new", "Error", "(", "'Component not found for container id: '", "+", "id", "+", "', reference: '", "+", "ref", ")", ";", "}", "return", "cmp", ";", "}" ]
Gets component using id and reference. @param id - component HTML id. @param ref - reference inside component found by id.
[ "Gets", "component", "using", "id", "and", "reference", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-search.js#L114-L120
train
Dzenly/tia
api/extjs/browser-part/e-br-search.js
byIdRefKey
function byIdRefKey(id, ref, key, extra) { var text = tiaEJ.getTextByLocKey(key, extra); var cmp = this.search.byIdRef(id, ref); var resItem = this.search.byText(cmp, text, 'container id: ' + id + ', reference: ' + ref); return resItem; }
javascript
function byIdRefKey(id, ref, key, extra) { var text = tiaEJ.getTextByLocKey(key, extra); var cmp = this.search.byIdRef(id, ref); var resItem = this.search.byText(cmp, text, 'container id: ' + id + ', reference: ' + ref); return resItem; }
[ "function", "byIdRefKey", "(", "id", ",", "ref", ",", "key", ",", "extra", ")", "{", "var", "text", "=", "tiaEJ", ".", "getTextByLocKey", "(", "key", ",", "extra", ")", ";", "var", "cmp", "=", "this", ".", "search", ".", "byIdRef", "(", "id", ",", "ref", ")", ";", "var", "resItem", "=", "this", ".", "search", ".", "byText", "(", "cmp", ",", "text", ",", "'container id: '", "+", "id", "+", "', reference: '", "+", "ref", ")", ";", "return", "resItem", ";", "}" ]
Gets component using id, reference, localization key. @param id - component HTML id. @param ref - reference inside component found by id. @param key - key in locale.
[ "Gets", "component", "using", "id", "reference", "localization", "key", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-search.js#L142-L147
train
Dzenly/tia
engine/wrap.js
stopTimer
function stopTimer(startTime) { if (gT.config.enableTimings) { const dif = process.hrtime(startTime); return ` (${dif[0] * 1000 + dif[1] / 1e6} ms)`; } return ''; }
javascript
function stopTimer(startTime) { if (gT.config.enableTimings) { const dif = process.hrtime(startTime); return ` (${dif[0] * 1000 + dif[1] / 1e6} ms)`; } return ''; }
[ "function", "stopTimer", "(", "startTime", ")", "{", "if", "(", "gT", ".", "config", ".", "enableTimings", ")", "{", "const", "dif", "=", "process", ".", "hrtime", "(", "startTime", ")", ";", "return", "`", "${", "dif", "[", "0", "]", "*", "1000", "+", "dif", "[", "1", "]", "/", "1e6", "}", "`", ";", "}", "return", "''", ";", "}" ]
Stops the timer which tracks action time. @param startTime @returns {*} - time dif in milliseconds @private
[ "Stops", "the", "timer", "which", "tracks", "action", "time", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/engine/wrap.js#L25-L31
train
Dzenly/tia
engine/wrap.js
pause
async function pause() { if (gT.cLParams.selActsDelay) { await gT.u.promise.delayed(gT.cLParams.selActsDelay); } }
javascript
async function pause() { if (gT.cLParams.selActsDelay) { await gT.u.promise.delayed(gT.cLParams.selActsDelay); } }
[ "async", "function", "pause", "(", ")", "{", "if", "(", "gT", ".", "cLParams", ".", "selActsDelay", ")", "{", "await", "gT", ".", "u", ".", "promise", ".", "delayed", "(", "gT", ".", "cLParams", ".", "selActsDelay", ")", ";", "}", "}" ]
Pause. Time interval is specified in config.
[ "Pause", ".", "Time", "interval", "is", "specified", "in", "config", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/engine/wrap.js#L36-L40
train
Dzenly/tia
engine/wrap.js
handleErrorWhenDriverExistsAndRecCountZero
async function handleErrorWhenDriverExistsAndRecCountZero() { gIn.errRecursionCount = 1; // To prevent recursive error report on error report. /* Here we use selenium GUI stuff when there was gT.s.driver.init call */ gIn.tracer.msg1('A.W.: Error report: printSelDriverLogs'); await gT.s.driver.printSelDriverLogs(900).catch(() => { gIn.tracer.msg1( `Error at printSelDriverLogs at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); if (!gIn.brHelpersInitiated) { gIn.tracer.msg1('A.W.: Error report: initTiaBrHelpers'); await gT.s.browser.initTiaBrHelpers(true).catch(() => { gIn.tracer.msg1( `Error at initTiaBrHelpers at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); } gIn.tracer.msg1('A.W.: Error report: printCaughtExceptions'); await gT.s.browser.printCaughtExceptions(true).catch(() => { gIn.tracer.msg1( `Error at logExceptions at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); gIn.tracer.msg1('A.W.: Error report: printSelBrowserLogs'); await gT.s.browser.printSelBrowserLogs().catch(() => { gIn.tracer.msg1( `Error at logConsoleContent at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); gIn.tracer.msg1('A.W.: Error report: screenshot'); await gT.s.browser.screenshot().catch(() => { gIn.tracer.msg1( `Error at screenshot at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); await quitDriver(); throw new Error(gT.engineConsts.CANCELLING_THE_TEST); }
javascript
async function handleErrorWhenDriverExistsAndRecCountZero() { gIn.errRecursionCount = 1; // To prevent recursive error report on error report. /* Here we use selenium GUI stuff when there was gT.s.driver.init call */ gIn.tracer.msg1('A.W.: Error report: printSelDriverLogs'); await gT.s.driver.printSelDriverLogs(900).catch(() => { gIn.tracer.msg1( `Error at printSelDriverLogs at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); if (!gIn.brHelpersInitiated) { gIn.tracer.msg1('A.W.: Error report: initTiaBrHelpers'); await gT.s.browser.initTiaBrHelpers(true).catch(() => { gIn.tracer.msg1( `Error at initTiaBrHelpers at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); } gIn.tracer.msg1('A.W.: Error report: printCaughtExceptions'); await gT.s.browser.printCaughtExceptions(true).catch(() => { gIn.tracer.msg1( `Error at logExceptions at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); gIn.tracer.msg1('A.W.: Error report: printSelBrowserLogs'); await gT.s.browser.printSelBrowserLogs().catch(() => { gIn.tracer.msg1( `Error at logConsoleContent at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); gIn.tracer.msg1('A.W.: Error report: screenshot'); await gT.s.browser.screenshot().catch(() => { gIn.tracer.msg1( `Error at screenshot at error handling, driver exists: ${Boolean(gT.sOrig.driver)}` ); }); await quitDriver(); throw new Error(gT.engineConsts.CANCELLING_THE_TEST); }
[ "async", "function", "handleErrorWhenDriverExistsAndRecCountZero", "(", ")", "{", "gIn", ".", "errRecursionCount", "=", "1", ";", "gIn", ".", "tracer", ".", "msg1", "(", "'A.W.: Error report: printSelDriverLogs'", ")", ";", "await", "gT", ".", "s", ".", "driver", ".", "printSelDriverLogs", "(", "900", ")", ".", "catch", "(", "(", ")", "=>", "{", "gIn", ".", "tracer", ".", "msg1", "(", "`", "${", "Boolean", "(", "gT", ".", "sOrig", ".", "driver", ")", "}", "`", ")", ";", "}", ")", ";", "if", "(", "!", "gIn", ".", "brHelpersInitiated", ")", "{", "gIn", ".", "tracer", ".", "msg1", "(", "'A.W.: Error report: initTiaBrHelpers'", ")", ";", "await", "gT", ".", "s", ".", "browser", ".", "initTiaBrHelpers", "(", "true", ")", ".", "catch", "(", "(", ")", "=>", "{", "gIn", ".", "tracer", ".", "msg1", "(", "`", "${", "Boolean", "(", "gT", ".", "sOrig", ".", "driver", ")", "}", "`", ")", ";", "}", ")", ";", "}", "gIn", ".", "tracer", ".", "msg1", "(", "'A.W.: Error report: printCaughtExceptions'", ")", ";", "await", "gT", ".", "s", ".", "browser", ".", "printCaughtExceptions", "(", "true", ")", ".", "catch", "(", "(", ")", "=>", "{", "gIn", ".", "tracer", ".", "msg1", "(", "`", "${", "Boolean", "(", "gT", ".", "sOrig", ".", "driver", ")", "}", "`", ")", ";", "}", ")", ";", "gIn", ".", "tracer", ".", "msg1", "(", "'A.W.: Error report: printSelBrowserLogs'", ")", ";", "await", "gT", ".", "s", ".", "browser", ".", "printSelBrowserLogs", "(", ")", ".", "catch", "(", "(", ")", "=>", "{", "gIn", ".", "tracer", ".", "msg1", "(", "`", "${", "Boolean", "(", "gT", ".", "sOrig", ".", "driver", ")", "}", "`", ")", ";", "}", ")", ";", "gIn", ".", "tracer", ".", "msg1", "(", "'A.W.: Error report: screenshot'", ")", ";", "await", "gT", ".", "s", ".", "browser", ".", "screenshot", "(", ")", ".", "catch", "(", "(", ")", "=>", "{", "gIn", ".", "tracer", ".", "msg1", "(", "`", "${", "Boolean", "(", "gT", ".", "sOrig", ".", "driver", ")", "}", "`", ")", ";", "}", ")", ";", "await", "quitDriver", "(", ")", ";", "throw", "new", "Error", "(", "gT", ".", "engineConsts", ".", "CANCELLING_THE_TEST", ")", ";", "}" ]
Handles an error when webdriver exists and recursion count is zero. Reports various info about the error and quits the driver if there is not keepBrowserAtError flag. Also see gT.s.driver.quit code for conditions when driver will not quit. Then tries to stop the current test case by throwing according error.
[ "Handles", "an", "error", "when", "webdriver", "exists", "and", "recursion", "count", "is", "zero", ".", "Reports", "various", "info", "about", "the", "error", "and", "quits", "the", "driver", "if", "there", "is", "not", "keepBrowserAtError", "flag", ".", "Also", "see", "gT", ".", "s", ".", "driver", ".", "quit", "code", "for", "conditions", "when", "driver", "will", "not", "quit", ".", "Then", "tries", "to", "stop", "the", "current", "test", "case", "by", "throwing", "according", "error", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/engine/wrap.js#L119-L162
train
Dzenly/tia
api/extjs/browser-part/e-br-get-html-els.js
getTableItemByIndex
function getTableItemByIndex(table, index) { if (table.isPanel) { table = table.getView(); } var el = table.getRow(index); return el; }
javascript
function getTableItemByIndex(table, index) { if (table.isPanel) { table = table.getView(); } var el = table.getRow(index); return el; }
[ "function", "getTableItemByIndex", "(", "table", ",", "index", ")", "{", "if", "(", "table", ".", "isPanel", ")", "{", "table", "=", "table", ".", "getView", "(", ")", ";", "}", "var", "el", "=", "table", ".", "getRow", "(", "index", ")", ";", "return", "el", ";", "}" ]
Note that for tree only expanded nodes are taking into account.
[ "Note", "that", "for", "tree", "only", "expanded", "nodes", "are", "taking", "into", "account", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-get-html-els.js#L11-L17
train
Dzenly/tia
api/extjs/browser-part/e-br-actions.js
findRecordIds
function findRecordIds(store, rowData) { var internalIds = []; store.each(function (m) { for (var i = 0; i < rowData.length; i++) { var item = rowData[i]; var dataIndex = item[0]; var value = item[1]; var fieldValue = m.get(dataIndex); if (fieldValue !== value) { return true; // To next record. } } internalIds.push(m.internalId); return true; }); if (!internalIds.length) { throw new Error('Record not found for ' + JSON.stringify(rowData)); } return internalIds; }
javascript
function findRecordIds(store, rowData) { var internalIds = []; store.each(function (m) { for (var i = 0; i < rowData.length; i++) { var item = rowData[i]; var dataIndex = item[0]; var value = item[1]; var fieldValue = m.get(dataIndex); if (fieldValue !== value) { return true; // To next record. } } internalIds.push(m.internalId); return true; }); if (!internalIds.length) { throw new Error('Record not found for ' + JSON.stringify(rowData)); } return internalIds; }
[ "function", "findRecordIds", "(", "store", ",", "rowData", ")", "{", "var", "internalIds", "=", "[", "]", ";", "store", ".", "each", "(", "function", "(", "m", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rowData", ".", "length", ";", "i", "++", ")", "{", "var", "item", "=", "rowData", "[", "i", "]", ";", "var", "dataIndex", "=", "item", "[", "0", "]", ";", "var", "value", "=", "item", "[", "1", "]", ";", "var", "fieldValue", "=", "m", ".", "get", "(", "dataIndex", ")", ";", "if", "(", "fieldValue", "!==", "value", ")", "{", "return", "true", ";", "}", "}", "internalIds", ".", "push", "(", "m", ".", "internalId", ")", ";", "return", "true", ";", "}", ")", ";", "if", "(", "!", "internalIds", ".", "length", ")", "{", "throw", "new", "Error", "(", "'Record not found for '", "+", "JSON", ".", "stringify", "(", "rowData", ")", ")", ";", "}", "return", "internalIds", ";", "}" ]
Finds record internalId's. @param {Ext.data.Store} store @param {Object} rowData [[dataIndex, value], [dataIndex, value]] @return {number[]}
[ "Finds", "record", "internalId", "s", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-actions.js#L15-L38
train
Dzenly/tia
api/extjs/browser-part/e-br-actions.js
findRecord
function findRecord(store, fieldName, text) { var index = store.find(fieldName, text); if (index === -1) { throw new Error('Text: ' + text + ' not found for fieldName: ' + fieldName); } return index; }
javascript
function findRecord(store, fieldName, text) { var index = store.find(fieldName, text); if (index === -1) { throw new Error('Text: ' + text + ' not found for fieldName: ' + fieldName); } return index; }
[ "function", "findRecord", "(", "store", ",", "fieldName", ",", "text", ")", "{", "var", "index", "=", "store", ".", "find", "(", "fieldName", ",", "text", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "'Text: '", "+", "text", "+", "' not found for fieldName: '", "+", "fieldName", ")", ";", "}", "return", "index", ";", "}" ]
Record for text for specific field. Only the first found result is used. @param store @param fieldName @param text @return {*}
[ "Record", "for", "text", "for", "specific", "field", ".", "Only", "the", "first", "found", "result", "is", "used", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-actions.js#L48-L54
train
Dzenly/tia
api/extjs/browser-part/e-br-actions.js
findRecords
function findRecords(store, fieldName, texts) { var records = []; texts.forEach(function (text) { var index = store.find(fieldName, text); if (index === -1) { throw new Error('Text: ' + text + ' not found for fieldName: ' + fieldName); } records.push(index); }); return records; }
javascript
function findRecords(store, fieldName, texts) { var records = []; texts.forEach(function (text) { var index = store.find(fieldName, text); if (index === -1) { throw new Error('Text: ' + text + ' not found for fieldName: ' + fieldName); } records.push(index); }); return records; }
[ "function", "findRecords", "(", "store", ",", "fieldName", ",", "texts", ")", "{", "var", "records", "=", "[", "]", ";", "texts", ".", "forEach", "(", "function", "(", "text", ")", "{", "var", "index", "=", "store", ".", "find", "(", "fieldName", ",", "text", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "'Text: '", "+", "text", "+", "' not found for fieldName: '", "+", "fieldName", ")", ";", "}", "records", ".", "push", "(", "index", ")", ";", "}", ")", ";", "return", "records", ";", "}" ]
Records for texts for specific field. Only the first found result is used. @param store @param fieldName @param texts @return {Array}
[ "Records", "for", "texts", "for", "specific", "field", ".", "Only", "the", "first", "found", "result", "is", "used", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-actions.js#L64-L74
train
Dzenly/tia
api/extjs/browser-part/e-br-actions.js
setTableSelection
function setTableSelection(table, rowData) { if (table.isPanel) { table = table.getView(); } var model = this.findRecord(table.getStore(), rowData); table.setSelection(model); }
javascript
function setTableSelection(table, rowData) { if (table.isPanel) { table = table.getView(); } var model = this.findRecord(table.getStore(), rowData); table.setSelection(model); }
[ "function", "setTableSelection", "(", "table", ",", "rowData", ")", "{", "if", "(", "table", ".", "isPanel", ")", "{", "table", "=", "table", ".", "getView", "(", ")", ";", "}", "var", "model", "=", "this", ".", "findRecord", "(", "table", ".", "getStore", "(", ")", ",", "rowData", ")", ";", "table", ".", "setSelection", "(", "model", ")", ";", "}" ]
Sets table selection by ExtJs API. @param table - table View or table Panel. @param {Object} rowData - fieldName/fieldValue pairs.
[ "Sets", "table", "selection", "by", "ExtJs", "API", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-actions.js#L81-L88
train
Dzenly/tia
api/extjs/browser-part/e-br-actions.js
getRowDomId
function getRowDomId(table, internalId) { if (table.isPanel) { table = table.getView(); } var tableId = table.getId(); var gridRowid = tableId + '-record-' + internalId; return gridRowid; }
javascript
function getRowDomId(table, internalId) { if (table.isPanel) { table = table.getView(); } var tableId = table.getId(); var gridRowid = tableId + '-record-' + internalId; return gridRowid; }
[ "function", "getRowDomId", "(", "table", ",", "internalId", ")", "{", "if", "(", "table", ".", "isPanel", ")", "{", "table", "=", "table", ".", "getView", "(", ")", ";", "}", "var", "tableId", "=", "table", ".", "getId", "(", ")", ";", "var", "gridRowid", "=", "tableId", "+", "'-record-'", "+", "internalId", ";", "return", "gridRowid", ";", "}" ]
Gets row DOM element, to click by webdriver. @param table @param internalId
[ "Gets", "row", "DOM", "element", "to", "click", "by", "webdriver", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-actions.js#L95-L102
train
Dzenly/tia
api/extjs/browser-part/e-br-actions.js
getTableCellByColumnTexts
function getTableCellByColumnTexts(table, cellData) { if (table.isPanel) { table = table.getView(); } if (typeof cellData.one === 'undefined') { cellData.one = true; } if (typeof cellData.index === 'undefined') { cellData.index = 0; } var panel = table.ownerGrid; var visColumns = panel.getVisibleColumns(); var text2DataIndex = {}; var cellSelector = null; visColumns.forEach(function (col) { var key = col.text || col.tooltip; text2DataIndex[key] = col.dataIndex; if (key === cellData.column) { cellSelector = table.getCellSelector(col); } }); if (!cellSelector) { throw new Error('Column ' + cellData.column + ' not found in visible columns'); } var row = cellData.row.slice(0); row = row.map(function (tup) { var tmpTup = tup.slice(0); tmpTup[0] = text2DataIndex[tup[0]]; if (!tmpTup[0]) { throw new Error('getTableCellByColumnTexts: No such column text: ' + tup[0]); } return tmpTup; }); var internalIds = this.findRecordIds(table.getStore(), row); console.log(internalIds); if (cellData.one && (internalIds.length > 1)) { throw new Error('getTableCellByColumnTexts: one is true, but found ' + internalIds.length + ' records.'); } var internalId = (cellData.index < 0) ? internalIds[internalIds.length + cellData.index] : internalIds[cellData.index]; var rowDomId = this.getRowDomId(table, internalId); var rowDom = document.getElementById(rowDomId); var cellDom = rowDom.querySelector(cellSelector); return cellDom; }
javascript
function getTableCellByColumnTexts(table, cellData) { if (table.isPanel) { table = table.getView(); } if (typeof cellData.one === 'undefined') { cellData.one = true; } if (typeof cellData.index === 'undefined') { cellData.index = 0; } var panel = table.ownerGrid; var visColumns = panel.getVisibleColumns(); var text2DataIndex = {}; var cellSelector = null; visColumns.forEach(function (col) { var key = col.text || col.tooltip; text2DataIndex[key] = col.dataIndex; if (key === cellData.column) { cellSelector = table.getCellSelector(col); } }); if (!cellSelector) { throw new Error('Column ' + cellData.column + ' not found in visible columns'); } var row = cellData.row.slice(0); row = row.map(function (tup) { var tmpTup = tup.slice(0); tmpTup[0] = text2DataIndex[tup[0]]; if (!tmpTup[0]) { throw new Error('getTableCellByColumnTexts: No such column text: ' + tup[0]); } return tmpTup; }); var internalIds = this.findRecordIds(table.getStore(), row); console.log(internalIds); if (cellData.one && (internalIds.length > 1)) { throw new Error('getTableCellByColumnTexts: one is true, but found ' + internalIds.length + ' records.'); } var internalId = (cellData.index < 0) ? internalIds[internalIds.length + cellData.index] : internalIds[cellData.index]; var rowDomId = this.getRowDomId(table, internalId); var rowDom = document.getElementById(rowDomId); var cellDom = rowDom.querySelector(cellSelector); return cellDom; }
[ "function", "getTableCellByColumnTexts", "(", "table", ",", "cellData", ")", "{", "if", "(", "table", ".", "isPanel", ")", "{", "table", "=", "table", ".", "getView", "(", ")", ";", "}", "if", "(", "typeof", "cellData", ".", "one", "===", "'undefined'", ")", "{", "cellData", ".", "one", "=", "true", ";", "}", "if", "(", "typeof", "cellData", ".", "index", "===", "'undefined'", ")", "{", "cellData", ".", "index", "=", "0", ";", "}", "var", "panel", "=", "table", ".", "ownerGrid", ";", "var", "visColumns", "=", "panel", ".", "getVisibleColumns", "(", ")", ";", "var", "text2DataIndex", "=", "{", "}", ";", "var", "cellSelector", "=", "null", ";", "visColumns", ".", "forEach", "(", "function", "(", "col", ")", "{", "var", "key", "=", "col", ".", "text", "||", "col", ".", "tooltip", ";", "text2DataIndex", "[", "key", "]", "=", "col", ".", "dataIndex", ";", "if", "(", "key", "===", "cellData", ".", "column", ")", "{", "cellSelector", "=", "table", ".", "getCellSelector", "(", "col", ")", ";", "}", "}", ")", ";", "if", "(", "!", "cellSelector", ")", "{", "throw", "new", "Error", "(", "'Column '", "+", "cellData", ".", "column", "+", "' not found in visible columns'", ")", ";", "}", "var", "row", "=", "cellData", ".", "row", ".", "slice", "(", "0", ")", ";", "row", "=", "row", ".", "map", "(", "function", "(", "tup", ")", "{", "var", "tmpTup", "=", "tup", ".", "slice", "(", "0", ")", ";", "tmpTup", "[", "0", "]", "=", "text2DataIndex", "[", "tup", "[", "0", "]", "]", ";", "if", "(", "!", "tmpTup", "[", "0", "]", ")", "{", "throw", "new", "Error", "(", "'getTableCellByColumnTexts: No such column text: '", "+", "tup", "[", "0", "]", ")", ";", "}", "return", "tmpTup", ";", "}", ")", ";", "var", "internalIds", "=", "this", ".", "findRecordIds", "(", "table", ".", "getStore", "(", ")", ",", "row", ")", ";", "console", ".", "log", "(", "internalIds", ")", ";", "if", "(", "cellData", ".", "one", "&&", "(", "internalIds", ".", "length", ">", "1", ")", ")", "{", "throw", "new", "Error", "(", "'getTableCellByColumnTexts: one is true, but found '", "+", "internalIds", ".", "length", "+", "' records.'", ")", ";", "}", "var", "internalId", "=", "(", "cellData", ".", "index", "<", "0", ")", "?", "internalIds", "[", "internalIds", ".", "length", "+", "cellData", ".", "index", "]", ":", "internalIds", "[", "cellData", ".", "index", "]", ";", "var", "rowDomId", "=", "this", ".", "getRowDomId", "(", "table", ",", "internalId", ")", ";", "var", "rowDom", "=", "document", ".", "getElementById", "(", "rowDomId", ")", ";", "var", "cellDom", "=", "rowDom", ".", "querySelector", "(", "cellSelector", ")", ";", "return", "cellDom", ";", "}" ]
Gets table cell DOM element.
[ "Gets", "table", "cell", "DOM", "element", "." ]
1f5108fc6a47d7c37ab8db45eef518f1ed6165ef
https://github.com/Dzenly/tia/blob/1f5108fc6a47d7c37ab8db45eef518f1ed6165ef/api/extjs/browser-part/e-br-actions.js#L129-L186
train
MadisonReed/amazon-payments
lib/amazon.js
parseMwsResponse
function parseMwsResponse(method, headers, response, callback) { // if it's XML, then we an parse correctly if (headers && headers['content-type'] == 'text/xml') { xml2js.parseString(response, {explicitArray: false}, function(err, result) { if (err) { return callback(err); } if (result.ErrorResponse) { err = { Code: 'Unknown', Message: 'Unknown MWS error' }; if (result.ErrorResponse.Error) { err = result.ErrorResponse.Error; } return callback(error.apiError(err.Code, err.Message, result)); } else { callback(null, new Response(method, result)); } }); } else { callback(null, new Response(method, { "Response": response })); } }
javascript
function parseMwsResponse(method, headers, response, callback) { // if it's XML, then we an parse correctly if (headers && headers['content-type'] == 'text/xml') { xml2js.parseString(response, {explicitArray: false}, function(err, result) { if (err) { return callback(err); } if (result.ErrorResponse) { err = { Code: 'Unknown', Message: 'Unknown MWS error' }; if (result.ErrorResponse.Error) { err = result.ErrorResponse.Error; } return callback(error.apiError(err.Code, err.Message, result)); } else { callback(null, new Response(method, result)); } }); } else { callback(null, new Response(method, { "Response": response })); } }
[ "function", "parseMwsResponse", "(", "method", ",", "headers", ",", "response", ",", "callback", ")", "{", "if", "(", "headers", "&&", "headers", "[", "'content-type'", "]", "==", "'text/xml'", ")", "{", "xml2js", ".", "parseString", "(", "response", ",", "{", "explicitArray", ":", "false", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "result", ".", "ErrorResponse", ")", "{", "err", "=", "{", "Code", ":", "'Unknown'", ",", "Message", ":", "'Unknown MWS error'", "}", ";", "if", "(", "result", ".", "ErrorResponse", ".", "Error", ")", "{", "err", "=", "result", ".", "ErrorResponse", ".", "Error", ";", "}", "return", "callback", "(", "error", ".", "apiError", "(", "err", ".", "Code", ",", "err", ".", "Message", ",", "result", ")", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "new", "Response", "(", "method", ",", "result", ")", ")", ";", "}", "}", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "new", "Response", "(", "method", ",", "{", "\"Response\"", ":", "response", "}", ")", ")", ";", "}", "}" ]
Parse the MWS response. @param {string} method @param {Object[]} headers @param {string} response @param {function} callback
[ "Parse", "the", "MWS", "response", "." ]
f2017b4642d65c9c2ffcf689486249746c93dbe0
https://github.com/MadisonReed/amazon-payments/blob/f2017b4642d65c9c2ffcf689486249746c93dbe0/lib/amazon.js#L192-L218
train
Esri/ember-cli-amd
index.js
write
function write(arr, str, range) { const offset = range[0]; arr[offset] = str; for (let i = offset + 1; i < range[1]; i++) { arr[i] = undefined; } }
javascript
function write(arr, str, range) { const offset = range[0]; arr[offset] = str; for (let i = offset + 1; i < range[1]; i++) { arr[i] = undefined; } }
[ "function", "write", "(", "arr", ",", "str", ",", "range", ")", "{", "const", "offset", "=", "range", "[", "0", "]", ";", "arr", "[", "offset", "]", "=", "str", ";", "for", "(", "let", "i", "=", "offset", "+", "1", ";", "i", "<", "range", "[", "1", "]", ";", "i", "++", ")", "{", "arr", "[", "i", "]", "=", "undefined", ";", "}", "}" ]
Write the new string into the range provided without modifying the size of arr. If the size of arr changes, then ranges from the parsed code would be invalidated. Since str.length can be shorter or longer than the range it is overwriting, write str into the first position of the range and then fill the remainder of the range with undefined. We know that a range will only be written to once. And since the array is used for positioning and then joined, this method of overwriting works.
[ "Write", "the", "new", "string", "into", "the", "range", "provided", "without", "modifying", "the", "size", "of", "arr", ".", "If", "the", "size", "of", "arr", "changes", "then", "ranges", "from", "the", "parsed", "code", "would", "be", "invalidated", ".", "Since", "str", ".", "length", "can", "be", "shorter", "or", "longer", "than", "the", "range", "it", "is", "overwriting", "write", "str", "into", "the", "first", "position", "of", "the", "range", "and", "then", "fill", "the", "remainder", "of", "the", "range", "with", "undefined", ".", "We", "know", "that", "a", "range", "will", "only", "be", "written", "to", "once", ".", "And", "since", "the", "array", "is", "used", "for", "positioning", "and", "then", "joined", "this", "method", "of", "overwriting", "works", "." ]
6fe2154792c3ec8c7eff3807e755a96657079663
https://github.com/Esri/ember-cli-amd/blob/6fe2154792c3ec8c7eff3807e755a96657079663/index.js#L310-L316
train
Esri/ember-cli-amd
index.js
replaceRequireAndDefine
function replaceRequireAndDefine(code, amdPackages, amdModules) { // Parse the code as an AST const ast = esprima.parseScript(code, { range: true }); // Split the code into an array for easier substitutions const buffer = code.split(''); // Walk thru the tree, find and replace our targets eswalk(ast, function(node) { if (!node) { return; } switch (node.type) { case 'CallExpression': if (!amdPackages || !amdModules) { // If not provided then we don't need to track them break; } // Collect the AMD modules // Looking for something like define(<name>, [<module1>, <module2>, ...], <function>) // This is the way ember defines a module if (node.callee.name === 'define') { if (node.arguments.length < 2 || node.arguments[1].type !== 'ArrayExpression' || !node.arguments[1].elements) { return; } node.arguments[1].elements.forEach(function(element) { if (element.type !== 'Literal') { return; } const isAMD = amdPackages.some(function(amdPackage) { if (typeof element.value !== 'string') { return false; } return element.value.indexOf(amdPackage + '/') === 0 || element.value === amdPackage; }); if (!isAMD) { return; } amdModules.add(element.value); }); return; } // Dealing with ember-auto-import eval if (node.callee.name === 'eval' && node.arguments[0].type === 'Literal' && typeof node.arguments[0].value === 'string') { const evalCode = node.arguments[0].value; const evalCodeAfter = replaceRequireAndDefine(evalCode, amdPackages, amdModules); if (evalCode !== evalCodeAfter) { write(buffer, "eval(" + JSON.stringify(evalCodeAfter) + ");", node.range); } } return; case 'Identifier': { // We are dealing with code, make sure the node.name is not inherited from object if (!identifiers.hasOwnProperty(node.name)) { return; } const identifier = identifiers[node.name]; if (!identifier) { return; } write(buffer, identifier, node.range); } return; case 'Literal': { // We are dealing with code, make sure the node.name is not inherited from object if (!literals.hasOwnProperty(node.value)) { return; } const literal = literals[node.value]; if (!literal) { return; } write(buffer, literal, node.range); } return; } }); // Return the new code return buffer.join(''); }
javascript
function replaceRequireAndDefine(code, amdPackages, amdModules) { // Parse the code as an AST const ast = esprima.parseScript(code, { range: true }); // Split the code into an array for easier substitutions const buffer = code.split(''); // Walk thru the tree, find and replace our targets eswalk(ast, function(node) { if (!node) { return; } switch (node.type) { case 'CallExpression': if (!amdPackages || !amdModules) { // If not provided then we don't need to track them break; } // Collect the AMD modules // Looking for something like define(<name>, [<module1>, <module2>, ...], <function>) // This is the way ember defines a module if (node.callee.name === 'define') { if (node.arguments.length < 2 || node.arguments[1].type !== 'ArrayExpression' || !node.arguments[1].elements) { return; } node.arguments[1].elements.forEach(function(element) { if (element.type !== 'Literal') { return; } const isAMD = amdPackages.some(function(amdPackage) { if (typeof element.value !== 'string') { return false; } return element.value.indexOf(amdPackage + '/') === 0 || element.value === amdPackage; }); if (!isAMD) { return; } amdModules.add(element.value); }); return; } // Dealing with ember-auto-import eval if (node.callee.name === 'eval' && node.arguments[0].type === 'Literal' && typeof node.arguments[0].value === 'string') { const evalCode = node.arguments[0].value; const evalCodeAfter = replaceRequireAndDefine(evalCode, amdPackages, amdModules); if (evalCode !== evalCodeAfter) { write(buffer, "eval(" + JSON.stringify(evalCodeAfter) + ");", node.range); } } return; case 'Identifier': { // We are dealing with code, make sure the node.name is not inherited from object if (!identifiers.hasOwnProperty(node.name)) { return; } const identifier = identifiers[node.name]; if (!identifier) { return; } write(buffer, identifier, node.range); } return; case 'Literal': { // We are dealing with code, make sure the node.name is not inherited from object if (!literals.hasOwnProperty(node.value)) { return; } const literal = literals[node.value]; if (!literal) { return; } write(buffer, literal, node.range); } return; } }); // Return the new code return buffer.join(''); }
[ "function", "replaceRequireAndDefine", "(", "code", ",", "amdPackages", ",", "amdModules", ")", "{", "const", "ast", "=", "esprima", ".", "parseScript", "(", "code", ",", "{", "range", ":", "true", "}", ")", ";", "const", "buffer", "=", "code", ".", "split", "(", "''", ")", ";", "eswalk", "(", "ast", ",", "function", "(", "node", ")", "{", "if", "(", "!", "node", ")", "{", "return", ";", "}", "switch", "(", "node", ".", "type", ")", "{", "case", "'CallExpression'", ":", "if", "(", "!", "amdPackages", "||", "!", "amdModules", ")", "{", "break", ";", "}", "if", "(", "node", ".", "callee", ".", "name", "===", "'define'", ")", "{", "if", "(", "node", ".", "arguments", ".", "length", "<", "2", "||", "node", ".", "arguments", "[", "1", "]", ".", "type", "!==", "'ArrayExpression'", "||", "!", "node", ".", "arguments", "[", "1", "]", ".", "elements", ")", "{", "return", ";", "}", "node", ".", "arguments", "[", "1", "]", ".", "elements", ".", "forEach", "(", "function", "(", "element", ")", "{", "if", "(", "element", ".", "type", "!==", "'Literal'", ")", "{", "return", ";", "}", "const", "isAMD", "=", "amdPackages", ".", "some", "(", "function", "(", "amdPackage", ")", "{", "if", "(", "typeof", "element", ".", "value", "!==", "'string'", ")", "{", "return", "false", ";", "}", "return", "element", ".", "value", ".", "indexOf", "(", "amdPackage", "+", "'/'", ")", "===", "0", "||", "element", ".", "value", "===", "amdPackage", ";", "}", ")", ";", "if", "(", "!", "isAMD", ")", "{", "return", ";", "}", "amdModules", ".", "add", "(", "element", ".", "value", ")", ";", "}", ")", ";", "return", ";", "}", "if", "(", "node", ".", "callee", ".", "name", "===", "'eval'", "&&", "node", ".", "arguments", "[", "0", "]", ".", "type", "===", "'Literal'", "&&", "typeof", "node", ".", "arguments", "[", "0", "]", ".", "value", "===", "'string'", ")", "{", "const", "evalCode", "=", "node", ".", "arguments", "[", "0", "]", ".", "value", ";", "const", "evalCodeAfter", "=", "replaceRequireAndDefine", "(", "evalCode", ",", "amdPackages", ",", "amdModules", ")", ";", "if", "(", "evalCode", "!==", "evalCodeAfter", ")", "{", "write", "(", "buffer", ",", "\"eval(\"", "+", "JSON", ".", "stringify", "(", "evalCodeAfter", ")", "+", "\");\"", ",", "node", ".", "range", ")", ";", "}", "}", "return", ";", "case", "'Identifier'", ":", "{", "if", "(", "!", "identifiers", ".", "hasOwnProperty", "(", "node", ".", "name", ")", ")", "{", "return", ";", "}", "const", "identifier", "=", "identifiers", "[", "node", ".", "name", "]", ";", "if", "(", "!", "identifier", ")", "{", "return", ";", "}", "write", "(", "buffer", ",", "identifier", ",", "node", ".", "range", ")", ";", "}", "return", ";", "case", "'Literal'", ":", "{", "if", "(", "!", "literals", ".", "hasOwnProperty", "(", "node", ".", "value", ")", ")", "{", "return", ";", "}", "const", "literal", "=", "literals", "[", "node", ".", "value", "]", ";", "if", "(", "!", "literal", ")", "{", "return", ";", "}", "write", "(", "buffer", ",", "literal", ",", "node", ".", "range", ")", ";", "}", "return", ";", "}", "}", ")", ";", "return", "buffer", ".", "join", "(", "''", ")", ";", "}" ]
Use Esprima to parse the code and eswalk to walk thru the code Replace require and define by non-conflicting verbs
[ "Use", "Esprima", "to", "parse", "the", "code", "and", "eswalk", "to", "walk", "thru", "the", "code", "Replace", "require", "and", "define", "by", "non", "-", "conflicting", "verbs" ]
6fe2154792c3ec8c7eff3807e755a96657079663
https://github.com/Esri/ember-cli-amd/blob/6fe2154792c3ec8c7eff3807e755a96657079663/index.js#L320-L422
train
lazojs/lazo
run.js
getStartEnvOptions
function getStartEnvOptions() { var options = {}; for (var k in args) { switch (k) { case 'daemon': case 'robust': options[k] = args[k] === true ? '1' : '0'; break; case 'cluster': options[k] = args[k] ? args[k] : os.cpus().length; break; case 'port': options[k] = args[k]; break; } } return options; }
javascript
function getStartEnvOptions() { var options = {}; for (var k in args) { switch (k) { case 'daemon': case 'robust': options[k] = args[k] === true ? '1' : '0'; break; case 'cluster': options[k] = args[k] ? args[k] : os.cpus().length; break; case 'port': options[k] = args[k]; break; } } return options; }
[ "function", "getStartEnvOptions", "(", ")", "{", "var", "options", "=", "{", "}", ";", "for", "(", "var", "k", "in", "args", ")", "{", "switch", "(", "k", ")", "{", "case", "'daemon'", ":", "case", "'robust'", ":", "options", "[", "k", "]", "=", "args", "[", "k", "]", "===", "true", "?", "'1'", ":", "'0'", ";", "break", ";", "case", "'cluster'", ":", "options", "[", "k", "]", "=", "args", "[", "k", "]", "?", "args", "[", "k", "]", ":", "os", ".", "cpus", "(", ")", ".", "length", ";", "break", ";", "case", "'port'", ":", "options", "[", "k", "]", "=", "args", "[", "k", "]", ";", "break", ";", "}", "}", "return", "options", ";", "}" ]
get the options for a lazo command
[ "get", "the", "options", "for", "a", "lazo", "command" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/run.js#L28-L47
train
lazojs/lazo
lib/common/utils/dataschema-json.js
function(value, field) { if(field.parser) { var parser = (isFunction(field.parser)) ? field.parser : null;//Y.Parsers[field.parser+'']; if(parser) { value = parser.call(this, value); } else { //Y.log("Could not find parser for field " + Y.dump(field), "warn", "dataschema-json"); } } return value; }
javascript
function(value, field) { if(field.parser) { var parser = (isFunction(field.parser)) ? field.parser : null;//Y.Parsers[field.parser+'']; if(parser) { value = parser.call(this, value); } else { //Y.log("Could not find parser for field " + Y.dump(field), "warn", "dataschema-json"); } } return value; }
[ "function", "(", "value", ",", "field", ")", "{", "if", "(", "field", ".", "parser", ")", "{", "var", "parser", "=", "(", "isFunction", "(", "field", ".", "parser", ")", ")", "?", "field", ".", "parser", ":", "null", ";", "if", "(", "parser", ")", "{", "value", "=", "parser", ".", "call", "(", "this", ",", "value", ")", ";", "}", "else", "{", "}", "}", "return", "value", ";", "}" ]
Applies field parser, if defined @method parse @param value {Object} Original value. @param field {Object} Field. @return {Object} Type-converted value.
[ "Applies", "field", "parser", "if", "defined" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/common/utils/dataschema-json.js#L85-L97
train
lazojs/lazo
lib/common/utils/dataschema-json.js
function (path, data) { var i = 0, len = path.length; for (;i<len;i++) { if (isObject(data) && (path[i] in data)) { data = data[path[i]]; } else { data = undefined; break; } } return data; }
javascript
function (path, data) { var i = 0, len = path.length; for (;i<len;i++) { if (isObject(data) && (path[i] in data)) { data = data[path[i]]; } else { data = undefined; break; } } return data; }
[ "function", "(", "path", ",", "data", ")", "{", "var", "i", "=", "0", ",", "len", "=", "path", ".", "length", ";", "for", "(", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "isObject", "(", "data", ")", "&&", "(", "path", "[", "i", "]", "in", "data", ")", ")", "{", "data", "=", "data", "[", "path", "[", "i", "]", "]", ";", "}", "else", "{", "data", "=", "undefined", ";", "break", ";", "}", "}", "return", "data", ";", "}" ]
Utility function to walk a path and return the value located there. @method getLocationValue @param path {String[]} Locator path. @param data {String} Data to traverse. @return {Object} Data value at location. @static
[ "Utility", "function", "to", "walk", "a", "path", "and", "return", "the", "value", "located", "there", "." ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/common/utils/dataschema-json.js#L156-L168
train
lazojs/lazo
lib/common/utils/dataschema-json.js
function(schema, data) { var data_in = data, data_out = { results: [], meta: {} }; // Convert incoming JSON strings if (!isObject(data)) { try { data_in = JSON.parse(data); } catch(e) { data_out.error = e; return data_out; } } if (isObject(data_in) && schema) { // Parse results data data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out); // Parse meta data if (schema.metaFields !== undefined) { data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out); } } else { //Y.log("JSON data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-json"); data_out.error = new Error("JSON schema parse failure"); } return data_out; }
javascript
function(schema, data) { var data_in = data, data_out = { results: [], meta: {} }; // Convert incoming JSON strings if (!isObject(data)) { try { data_in = JSON.parse(data); } catch(e) { data_out.error = e; return data_out; } } if (isObject(data_in) && schema) { // Parse results data data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out); // Parse meta data if (schema.metaFields !== undefined) { data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out); } } else { //Y.log("JSON data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-json"); data_out.error = new Error("JSON schema parse failure"); } return data_out; }
[ "function", "(", "schema", ",", "data", ")", "{", "var", "data_in", "=", "data", ",", "data_out", "=", "{", "results", ":", "[", "]", ",", "meta", ":", "{", "}", "}", ";", "if", "(", "!", "isObject", "(", "data", ")", ")", "{", "try", "{", "data_in", "=", "JSON", ".", "parse", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "data_out", ".", "error", "=", "e", ";", "return", "data_out", ";", "}", "}", "if", "(", "isObject", "(", "data_in", ")", "&&", "schema", ")", "{", "data_out", "=", "SchemaJSON", ".", "_parseResults", ".", "call", "(", "this", ",", "schema", ",", "data_in", ",", "data_out", ")", ";", "if", "(", "schema", ".", "metaFields", "!==", "undefined", ")", "{", "data_out", "=", "SchemaJSON", ".", "_parseMeta", "(", "schema", ".", "metaFields", ",", "data_in", ",", "data_out", ")", ";", "}", "}", "else", "{", "data_out", ".", "error", "=", "new", "Error", "(", "\"JSON schema parse failure\"", ")", ";", "}", "return", "data_out", ";", "}" ]
Applies a schema to an array of data located in a JSON structure, returning a normalized object with results in the `results` property. Additional information can be parsed out of the JSON for inclusion in the `meta` property of the response object. If an error is encountered during processing, an `error` property will be added. The input _data_ is expected to be an object or array. If it is a string, it will be passed through `Y.JSON.parse()`. If _data_ contains an array of data records to normalize, specify the _schema.resultListLocator_ as a dot separated path string just as you would reference it in JavaScript. So if your _data_ object has a record array at _data.response.results_, use _schema.resultListLocator_ = "response.results". Bracket notation can also be used for array indices or object properties (e.g. "response['results']"); This is called a "path locator" Field data in the result list is extracted with field identifiers in _schema.resultFields_. Field identifiers are objects with the following properties: `key` : <strong>(required)</strong> The path locator (String) `parser`: A function or the name of a function on `Y.Parsers` used to convert the input value into a normalized type. Parser functions are passed the value as input and are expected to return a value. If no value parsing is needed, you can use path locators (strings) instead of field identifiers (objects) -- see example below. If no processing of the result list array is needed, _schema.resultFields_ can be omitted; the `response.results` will point directly to the array. If the result list contains arrays, `response.results` will contain an array of objects with key:value pairs assuming the fields in _schema.resultFields_ are ordered in accordance with the data array values. If the result list contains objects, the identified _schema.resultFields_ will be used to extract a value from those objects for the output result. To extract additional information from the JSON, include an array of path locators in _schema.metaFields_. The collected values will be stored in `response.meta`. @example Process array of arrays var schema = { resultListLocator: 'produce.fruit', resultFields: [ 'name', 'color' ] }, data = { produce: { fruit: [ [ 'Banana', 'yellow' ], [ 'Orange', 'orange' ], [ 'Eggplant', 'purple' ] ] } }; var response = Y.DataSchema.JSON.apply(schema, data); response.results[0] is { name: "Banana", color: "yellow" } Process array of objects + some metadata schema.metaFields = [ 'lastInventory' ]; data = { produce: { fruit: [ { name: 'Banana', color: 'yellow', price: '1.96' }, { name: 'Orange', color: 'orange', price: '2.04' }, { name: 'Eggplant', color: 'purple', price: '4.31' } ] }, lastInventory: '2011-07-19' }; response = Y.DataSchema.JSON.apply(schema, data); response.results[0] is { name: "Banana", color: "yellow" } response.meta.lastInventory is '2001-07-19' Use parsers schema.resultFields = [ { key: 'name', parser: function (val) { return val.toUpperCase(); } }, { key: 'price', parser: 'number' // Uses Y.Parsers.number } ]; response = Y.DataSchema.JSON.apply(schema, data); Note price was converted from a numeric string to a number response.results[0] looks like { fruit: "BANANA", price: 1.96 } @method apply @param {Object} [schema] Schema to apply. Supported configuration properties are: @param {String} [schema.resultListLocator] Path locator for the location of the array of records to flatten into `response.results` @param {Array} [schema.resultFields] Field identifiers to locate/assign values in the response records. See above for details. @param {Array} [schema.metaFields] Path locators to extract extra non-record related information from the data object. @param {Object|Array|String} data JSON data or its string serialization. @return {Object} An Object with properties `results` and `meta` @static
[ "Applies", "a", "schema", "to", "an", "array", "of", "data", "located", "in", "a", "JSON", "structure", "returning", "a", "normalized", "object", "with", "results", "in", "the", "results", "property", ".", "Additional", "information", "can", "be", "parsed", "out", "of", "the", "JSON", "for", "inclusion", "in", "the", "meta", "property", "of", "the", "response", "object", ".", "If", "an", "error", "is", "encountered", "during", "processing", "an", "error", "property", "will", "be", "added", "." ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/common/utils/dataschema-json.js#L309-L339
train
lazojs/lazo
lib/common/utils/dataschema-json.js
function(schema, json_in, data_out) { var getPath = SchemaJSON.getPath, getValue = SchemaJSON.getLocationValue, path = getPath(schema.resultListLocator), results = path ? (getValue(path, json_in) || // Fall back to treat resultListLocator as a simple key json_in[schema.resultListLocator]) : // Or if no resultListLocator is supplied, use the input json_in; if (isArray(results)) { // if no result fields are passed in, then just take // the results array whole-hog Sometimes you're getting // an array of strings, or want the whole object, so // resultFields don't make sense. if (isArray(schema.resultFields)) { data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out); } else { data_out.results = results; } } else if (!results) { //else if (schema.resultListLocator) { data_out.results = []; data_out.error = new Error("JSON results retrieval failure"); //Y.log("JSON data could not be parsed: " + Y.dump(json_in), "error", "dataschema-json"); } else { data_out.results = results; } return data_out; }
javascript
function(schema, json_in, data_out) { var getPath = SchemaJSON.getPath, getValue = SchemaJSON.getLocationValue, path = getPath(schema.resultListLocator), results = path ? (getValue(path, json_in) || // Fall back to treat resultListLocator as a simple key json_in[schema.resultListLocator]) : // Or if no resultListLocator is supplied, use the input json_in; if (isArray(results)) { // if no result fields are passed in, then just take // the results array whole-hog Sometimes you're getting // an array of strings, or want the whole object, so // resultFields don't make sense. if (isArray(schema.resultFields)) { data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out); } else { data_out.results = results; } } else if (!results) { //else if (schema.resultListLocator) { data_out.results = []; data_out.error = new Error("JSON results retrieval failure"); //Y.log("JSON data could not be parsed: " + Y.dump(json_in), "error", "dataschema-json"); } else { data_out.results = results; } return data_out; }
[ "function", "(", "schema", ",", "json_in", ",", "data_out", ")", "{", "var", "getPath", "=", "SchemaJSON", ".", "getPath", ",", "getValue", "=", "SchemaJSON", ".", "getLocationValue", ",", "path", "=", "getPath", "(", "schema", ".", "resultListLocator", ")", ",", "results", "=", "path", "?", "(", "getValue", "(", "path", ",", "json_in", ")", "||", "json_in", "[", "schema", ".", "resultListLocator", "]", ")", ":", "json_in", ";", "if", "(", "isArray", "(", "results", ")", ")", "{", "if", "(", "isArray", "(", "schema", ".", "resultFields", ")", ")", "{", "data_out", "=", "SchemaJSON", ".", "_getFieldValues", ".", "call", "(", "this", ",", "schema", ".", "resultFields", ",", "results", ",", "data_out", ")", ";", "}", "else", "{", "data_out", ".", "results", "=", "results", ";", "}", "}", "else", "if", "(", "!", "results", ")", "{", "data_out", ".", "results", "=", "[", "]", ";", "data_out", ".", "error", "=", "new", "Error", "(", "\"JSON results retrieval failure\"", ")", ";", "}", "else", "{", "data_out", ".", "results", "=", "results", ";", "}", "return", "data_out", ";", "}" ]
Schema-parsed list of results from full data @method _parseResults @param schema {Object} Schema to parse against. @param json_in {Object} JSON to parse. @param data_out {Object} In-progress parsed data to update. @return {Object} Parsed data object. @static @protected
[ "Schema", "-", "parsed", "list", "of", "results", "from", "full", "data" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/common/utils/dataschema-json.js#L352-L383
train
lazojs/lazo
lib/common/utils/dataschema-json.js
function(metaFields, json_in, data_out) { if (isObject(metaFields)) { var key, path; for(key in metaFields) { if (metaFields.hasOwnProperty(key)) { path = SchemaJSON.getPath(metaFields[key]); if (path && json_in) { data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in); } } } } else { data_out.error = new Error("JSON meta data retrieval failure"); } return data_out; }
javascript
function(metaFields, json_in, data_out) { if (isObject(metaFields)) { var key, path; for(key in metaFields) { if (metaFields.hasOwnProperty(key)) { path = SchemaJSON.getPath(metaFields[key]); if (path && json_in) { data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in); } } } } else { data_out.error = new Error("JSON meta data retrieval failure"); } return data_out; }
[ "function", "(", "metaFields", ",", "json_in", ",", "data_out", ")", "{", "if", "(", "isObject", "(", "metaFields", ")", ")", "{", "var", "key", ",", "path", ";", "for", "(", "key", "in", "metaFields", ")", "{", "if", "(", "metaFields", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "path", "=", "SchemaJSON", ".", "getPath", "(", "metaFields", "[", "key", "]", ")", ";", "if", "(", "path", "&&", "json_in", ")", "{", "data_out", ".", "meta", "[", "key", "]", "=", "SchemaJSON", ".", "getLocationValue", "(", "path", ",", "json_in", ")", ";", "}", "}", "}", "}", "else", "{", "data_out", ".", "error", "=", "new", "Error", "(", "\"JSON meta data retrieval failure\"", ")", ";", "}", "return", "data_out", ";", "}" ]
Parses results data according to schema @method _parseMeta @param metaFields {Object} Metafields definitions. @param json_in {Object} JSON to parse. @param data_out {Object} In-progress parsed data to update. @return {Object} Schema-parsed meta data. @static @protected
[ "Parses", "results", "data", "according", "to", "schema" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/common/utils/dataschema-json.js#L510-L526
train
lazojs/lazo
lib/client/viewManager.js
function (rootNode, viewKey) { var views = this.getList('view', rootNode); var self = this; _.each(views, function (view) { view.remove(); }); return this; }
javascript
function (rootNode, viewKey) { var views = this.getList('view', rootNode); var self = this; _.each(views, function (view) { view.remove(); }); return this; }
[ "function", "(", "rootNode", ",", "viewKey", ")", "{", "var", "views", "=", "this", ".", "getList", "(", "'view'", ",", "rootNode", ")", ";", "var", "self", "=", "this", ";", "_", ".", "each", "(", "views", ",", "function", "(", "view", ")", "{", "view", ".", "remove", "(", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Clean up view DOM bindings and event listeners.
[ "Clean", "up", "view", "DOM", "bindings", "and", "event", "listeners", "." ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/client/viewManager.js#L8-L17
train
lazojs/lazo
lib/client/execute.js
onLinksDone
function onLinksDone(loaded) { if (loaded === 2) { if (hasLayoutChanged) { $target.find('[lazo-cmp-name]').remove(); $target.append(html); } else { $target.html(html); } setTimeout(function () { LAZO.error.clear(); $target.css({ 'visibility': 'visible'} ); viewManager.attachViews(ctl, function (err, success) { if (err) { LAZO.logger.error('[LAZO.navigate] Error attaching views', err); } doc.updatePageTags(LAZO.ctl.ctx, function (err) { if (err) { LAZO.logger.error('[LAZO.navigate] Error updating page tags', err); } doc.setTitle(LAZO.ctl.ctx._rootCtx.pageTitle); LAZO.app.trigger('navigate:application:complete', eventData); }); }); }, 0); } }
javascript
function onLinksDone(loaded) { if (loaded === 2) { if (hasLayoutChanged) { $target.find('[lazo-cmp-name]').remove(); $target.append(html); } else { $target.html(html); } setTimeout(function () { LAZO.error.clear(); $target.css({ 'visibility': 'visible'} ); viewManager.attachViews(ctl, function (err, success) { if (err) { LAZO.logger.error('[LAZO.navigate] Error attaching views', err); } doc.updatePageTags(LAZO.ctl.ctx, function (err) { if (err) { LAZO.logger.error('[LAZO.navigate] Error updating page tags', err); } doc.setTitle(LAZO.ctl.ctx._rootCtx.pageTitle); LAZO.app.trigger('navigate:application:complete', eventData); }); }); }, 0); } }
[ "function", "onLinksDone", "(", "loaded", ")", "{", "if", "(", "loaded", "===", "2", ")", "{", "if", "(", "hasLayoutChanged", ")", "{", "$target", ".", "find", "(", "'[lazo-cmp-name]'", ")", ".", "remove", "(", ")", ";", "$target", ".", "append", "(", "html", ")", ";", "}", "else", "{", "$target", ".", "html", "(", "html", ")", ";", "}", "setTimeout", "(", "function", "(", ")", "{", "LAZO", ".", "error", ".", "clear", "(", ")", ";", "$target", ".", "css", "(", "{", "'visibility'", ":", "'visible'", "}", ")", ";", "viewManager", ".", "attachViews", "(", "ctl", ",", "function", "(", "err", ",", "success", ")", "{", "if", "(", "err", ")", "{", "LAZO", ".", "logger", ".", "error", "(", "'[LAZO.navigate] Error attaching views'", ",", "err", ")", ";", "}", "doc", ".", "updatePageTags", "(", "LAZO", ".", "ctl", ".", "ctx", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "LAZO", ".", "logger", ".", "error", "(", "'[LAZO.navigate] Error updating page tags'", ",", "err", ")", ";", "}", "doc", ".", "setTitle", "(", "LAZO", ".", "ctl", ".", "ctx", ".", "_rootCtx", ".", "pageTitle", ")", ";", "LAZO", ".", "app", ".", "trigger", "(", "'navigate:application:complete'", ",", "eventData", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "0", ")", ";", "}", "}" ]
remove orphaned models
[ "remove", "orphaned", "models" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/client/execute.js#L120-L147
train
lazojs/lazo
lib/public/collection.js
function(attrs, options) { // begin lazo specific overrides var modelName = null; if (this.modelName) { if (_.isFunction(this.modelName)) { modelName = this.modelName(attrs, options); } else { modelName = this.modelName; } } // end lazo specific overrides if (attrs instanceof Backbone.Model) { if (!attrs.collection) attrs.collection = this; if (!attrs.name && modelName) attrs.name = modelName; // lazo specific return attrs; } options || (options = {}); options.collection = this; // begin lazo specific overrides if (modelName) { options.name = modelName; } options.ctx = this.ctx; // end lazo specific overrides var model = new this.model(attrs, options); if (!model._validate(attrs, options)) { this.trigger('invalid', this, attrs, options); return false; } return model; }
javascript
function(attrs, options) { // begin lazo specific overrides var modelName = null; if (this.modelName) { if (_.isFunction(this.modelName)) { modelName = this.modelName(attrs, options); } else { modelName = this.modelName; } } // end lazo specific overrides if (attrs instanceof Backbone.Model) { if (!attrs.collection) attrs.collection = this; if (!attrs.name && modelName) attrs.name = modelName; // lazo specific return attrs; } options || (options = {}); options.collection = this; // begin lazo specific overrides if (modelName) { options.name = modelName; } options.ctx = this.ctx; // end lazo specific overrides var model = new this.model(attrs, options); if (!model._validate(attrs, options)) { this.trigger('invalid', this, attrs, options); return false; } return model; }
[ "function", "(", "attrs", ",", "options", ")", "{", "var", "modelName", "=", "null", ";", "if", "(", "this", ".", "modelName", ")", "{", "if", "(", "_", ".", "isFunction", "(", "this", ".", "modelName", ")", ")", "{", "modelName", "=", "this", ".", "modelName", "(", "attrs", ",", "options", ")", ";", "}", "else", "{", "modelName", "=", "this", ".", "modelName", ";", "}", "}", "if", "(", "attrs", "instanceof", "Backbone", ".", "Model", ")", "{", "if", "(", "!", "attrs", ".", "collection", ")", "attrs", ".", "collection", "=", "this", ";", "if", "(", "!", "attrs", ".", "name", "&&", "modelName", ")", "attrs", ".", "name", "=", "modelName", ";", "return", "attrs", ";", "}", "options", "||", "(", "options", "=", "{", "}", ")", ";", "options", ".", "collection", "=", "this", ";", "if", "(", "modelName", ")", "{", "options", ".", "name", "=", "modelName", ";", "}", "options", ".", "ctx", "=", "this", ".", "ctx", ";", "var", "model", "=", "new", "this", ".", "model", "(", "attrs", ",", "options", ")", ";", "if", "(", "!", "model", ".", "_validate", "(", "attrs", ",", "options", ")", ")", "{", "this", ".", "trigger", "(", "'invalid'", ",", "this", ",", "attrs", ",", "options", ")", ";", "return", "false", ";", "}", "return", "model", ";", "}" ]
taken directly from Backbone.Collection._prepareModel, except where noted by comments
[ "taken", "directly", "from", "Backbone", ".", "Collection", ".", "_prepareModel", "except", "where", "noted", "by", "comments" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/public/collection.js#L57-L93
train
lazojs/lazo
lib/server/serviceProxy.js
function (svc, attributes, options) { options = options || {}; if (!options.success) { throw new Error('Success callback undefined for service call svc: ' + svc); } var error = options.error; options.error = function (err) { if (error) { error(err); } }; // use the backbone verbs return this.sync( 'update', { name: svc, url: svc, params: options.params, ctx: this.ctx, toJSON: function () { return attributes; } }, options); }
javascript
function (svc, attributes, options) { options = options || {}; if (!options.success) { throw new Error('Success callback undefined for service call svc: ' + svc); } var error = options.error; options.error = function (err) { if (error) { error(err); } }; // use the backbone verbs return this.sync( 'update', { name: svc, url: svc, params: options.params, ctx: this.ctx, toJSON: function () { return attributes; } }, options); }
[ "function", "(", "svc", ",", "attributes", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "options", ".", "success", ")", "{", "throw", "new", "Error", "(", "'Success callback undefined for service call svc: '", "+", "svc", ")", ";", "}", "var", "error", "=", "options", ".", "error", ";", "options", ".", "error", "=", "function", "(", "err", ")", "{", "if", "(", "error", ")", "{", "error", "(", "err", ")", ";", "}", "}", ";", "return", "this", ".", "sync", "(", "'update'", ",", "{", "name", ":", "svc", ",", "url", ":", "svc", ",", "params", ":", "options", ".", "params", ",", "ctx", ":", "this", ".", "ctx", ",", "toJSON", ":", "function", "(", ")", "{", "return", "attributes", ";", "}", "}", ",", "options", ")", ";", "}" ]
Used to send a PUT request to a service @method put @param {String} svc The url for a given service endpoint @param {Object} attributes A hash containing name-value pairs used to be sent as the payload to the server @param {Object} options @param {Object} [options.params] A hash containing name-value pairs used in url substitution. @param {Function} options.success Callback function to be called when fetch succeeds, passed <code>(response)</code> as argument. @param {Function} options.error Callback function to be called when fetch fails, passed <code>(response)</code> as argument. @async
[ "Used", "to", "send", "a", "PUT", "request", "to", "a", "service" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/server/serviceProxy.js#L105-L130
train
lazojs/lazo
lib/server/server.js
setTags
function setTags(routeDefs) { for (var k in routeDefs) { if (_.isObject(routeDefs[k])) { if (!_.isArray(routeDefs[k].servers)) { routeDefs[k].servers = ['primary']; } } else { routeDefs[k] = { component: routeDefs[k], servers: ['primary'] }; } } return routeDefs; }
javascript
function setTags(routeDefs) { for (var k in routeDefs) { if (_.isObject(routeDefs[k])) { if (!_.isArray(routeDefs[k].servers)) { routeDefs[k].servers = ['primary']; } } else { routeDefs[k] = { component: routeDefs[k], servers: ['primary'] }; } } return routeDefs; }
[ "function", "setTags", "(", "routeDefs", ")", "{", "for", "(", "var", "k", "in", "routeDefs", ")", "{", "if", "(", "_", ".", "isObject", "(", "routeDefs", "[", "k", "]", ")", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "routeDefs", "[", "k", "]", ".", "servers", ")", ")", "{", "routeDefs", "[", "k", "]", ".", "servers", "=", "[", "'primary'", "]", ";", "}", "}", "else", "{", "routeDefs", "[", "k", "]", "=", "{", "component", ":", "routeDefs", "[", "k", "]", ",", "servers", ":", "[", "'primary'", "]", "}", ";", "}", "}", "return", "routeDefs", ";", "}" ]
add default server tag if it does not exist
[ "add", "default", "server", "tag", "if", "it", "does", "not", "exist" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/server/server.js#L162-L177
train
lazojs/lazo
lib/server/assetsProvider.js
function (component) { var pathParts = component === 'app' ? ['app'] : ['components']; if (component !== 'app') { pathParts.push(component); } pathParts.push('assets'); return path.resolve(LAZO.FILE_REPO_PATH + path.sep + path.join.apply(this, pathParts)); }
javascript
function (component) { var pathParts = component === 'app' ? ['app'] : ['components']; if (component !== 'app') { pathParts.push(component); } pathParts.push('assets'); return path.resolve(LAZO.FILE_REPO_PATH + path.sep + path.join.apply(this, pathParts)); }
[ "function", "(", "component", ")", "{", "var", "pathParts", "=", "component", "===", "'app'", "?", "[", "'app'", "]", ":", "[", "'components'", "]", ";", "if", "(", "component", "!==", "'app'", ")", "{", "pathParts", ".", "push", "(", "component", ")", ";", "}", "pathParts", ".", "push", "(", "'assets'", ")", ";", "return", "path", ".", "resolve", "(", "LAZO", ".", "FILE_REPO_PATH", "+", "path", ".", "sep", "+", "path", ".", "join", ".", "apply", "(", "this", ",", "pathParts", ")", ")", ";", "}" ]
resolve component path for listing assets directory contents
[ "resolve", "component", "path", "for", "listing", "assets", "directory", "contents" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/server/assetsProvider.js#L13-L21
train
lazojs/lazo
lib/server/assetsProvider.js
function (map, ctx) { for (var k in map) { map[k] = this.resolveAssets(map[k], ctx); } return map; }
javascript
function (map, ctx) { for (var k in map) { map[k] = this.resolveAssets(map[k], ctx); } return map; }
[ "function", "(", "map", ",", "ctx", ")", "{", "for", "(", "var", "k", "in", "map", ")", "{", "map", "[", "k", "]", "=", "this", ".", "resolveAssets", "(", "map", "[", "k", "]", ",", "ctx", ")", ";", "}", "return", "map", ";", "}" ]
iterate over component map and resolve assets
[ "iterate", "over", "component", "map", "and", "resolve", "assets" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/server/assetsProvider.js#L42-L48
train
lazojs/lazo
lib/common/config.js
function (key, options) { var ret; if (this.data && key in this.data) { ret = this.data[key]; try { ret = JSON.parse(ret); } catch (e) {} // ignore JSON parse errors since we only want to parse it if it is JSON } if (options && _.isFunction(options.success)) { options.success(ret); } return ret; }
javascript
function (key, options) { var ret; if (this.data && key in this.data) { ret = this.data[key]; try { ret = JSON.parse(ret); } catch (e) {} // ignore JSON parse errors since we only want to parse it if it is JSON } if (options && _.isFunction(options.success)) { options.success(ret); } return ret; }
[ "function", "(", "key", ",", "options", ")", "{", "var", "ret", ";", "if", "(", "this", ".", "data", "&&", "key", "in", "this", ".", "data", ")", "{", "ret", "=", "this", ".", "data", "[", "key", "]", ";", "try", "{", "ret", "=", "JSON", ".", "parse", "(", "ret", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "if", "(", "options", "&&", "_", ".", "isFunction", "(", "options", ".", "success", ")", ")", "{", "options", ".", "success", "(", "ret", ")", ";", "}", "return", "ret", ";", "}" ]
Gets the value for a key @param key @return {*}
[ "Gets", "the", "value", "for", "a", "key" ]
0b91b8b3b9f5246414b23458e8202fc4940ebd45
https://github.com/lazojs/lazo/blob/0b91b8b3b9f5246414b23458e8202fc4940ebd45/lib/common/config.js#L140-L153
train
gridgrid/grid
src/modules/mousewheel/index.js
function(elem, listener) { var normalizedListener = function(e) { listener(normalizeWheelEvent(e)); }; EVENT_NAMES.forEach(function(name) { elem.addEventListener(name, normalizedListener); }); return function() { EVENT_NAMES.forEach(function(name) { elem.removeEventListener(name, normalizedListener); }); }; }
javascript
function(elem, listener) { var normalizedListener = function(e) { listener(normalizeWheelEvent(e)); }; EVENT_NAMES.forEach(function(name) { elem.addEventListener(name, normalizedListener); }); return function() { EVENT_NAMES.forEach(function(name) { elem.removeEventListener(name, normalizedListener); }); }; }
[ "function", "(", "elem", ",", "listener", ")", "{", "var", "normalizedListener", "=", "function", "(", "e", ")", "{", "listener", "(", "normalizeWheelEvent", "(", "e", ")", ")", ";", "}", ";", "EVENT_NAMES", ".", "forEach", "(", "function", "(", "name", ")", "{", "elem", ".", "addEventListener", "(", "name", ",", "normalizedListener", ")", ";", "}", ")", ";", "return", "function", "(", ")", "{", "EVENT_NAMES", ".", "forEach", "(", "function", "(", "name", ")", "{", "elem", ".", "removeEventListener", "(", "name", ",", "normalizedListener", ")", ";", "}", ")", ";", "}", ";", "}" ]
binds a cross browser normalized mousewheel event, and returns a function that will unbind the listener;
[ "binds", "a", "cross", "browser", "normalized", "mousewheel", "event", "and", "returns", "a", "function", "that", "will", "unbind", "the", "listener", ";" ]
c7ef254498624f56ed6a2df6cfb2ef695afcd0fd
https://github.com/gridgrid/grid/blob/c7ef254498624f56ed6a2df6cfb2ef695afcd0fd/src/modules/mousewheel/index.js#L27-L42
train
gridgrid/grid
src/modules/range-util/index.js
function(r1, c1, r2, c2) { var range = {}; if (r1 < r2) { range.top = r1; range.height = r2 - r1 + 1; } else { range.top = r2; range.height = r1 - r2 + 1; } if (c1 < c2) { range.left = c1; range.width = c2 - c1 + 1; } else { range.left = c2; range.width = c1 - c2 + 1; } return range; }
javascript
function(r1, c1, r2, c2) { var range = {}; if (r1 < r2) { range.top = r1; range.height = r2 - r1 + 1; } else { range.top = r2; range.height = r1 - r2 + 1; } if (c1 < c2) { range.left = c1; range.width = c2 - c1 + 1; } else { range.left = c2; range.width = c1 - c2 + 1; } return range; }
[ "function", "(", "r1", ",", "c1", ",", "r2", ",", "c2", ")", "{", "var", "range", "=", "{", "}", ";", "if", "(", "r1", "<", "r2", ")", "{", "range", ".", "top", "=", "r1", ";", "range", ".", "height", "=", "r2", "-", "r1", "+", "1", ";", "}", "else", "{", "range", ".", "top", "=", "r2", ";", "range", ".", "height", "=", "r1", "-", "r2", "+", "1", ";", "}", "if", "(", "c1", "<", "c2", ")", "{", "range", ".", "left", "=", "c1", ";", "range", ".", "width", "=", "c2", "-", "c1", "+", "1", ";", "}", "else", "{", "range", ".", "left", "=", "c2", ";", "range", ".", "width", "=", "c1", "-", "c2", "+", "1", ";", "}", "return", "range", ";", "}" ]
takes two row, col points and creates a normal position range
[ "takes", "two", "row", "col", "points", "and", "creates", "a", "normal", "position", "range" ]
c7ef254498624f56ed6a2df6cfb2ef695afcd0fd
https://github.com/gridgrid/grid/blob/c7ef254498624f56ed6a2df6cfb2ef695afcd0fd/src/modules/range-util/index.js#L37-L55
train
gridgrid/grid
src/modules/navigation-model/index.js
handleRowColSelectionChange
function handleRowColSelectionChange(rowOrCol) { var decoratorsField = ('_' + rowOrCol + 'SelectionClasses'); model[decoratorsField].forEach(function (selectionDecorator) { grid.cellClasses.remove(selectionDecorator); }); model[decoratorsField] = []; if (grid[rowOrCol + 'Model'].allSelected()) { var top = rowOrCol === 'row' ? Infinity : 0; var left = rowOrCol === 'col' ? Infinity : 0; var decorator = grid.cellClasses.create(top, left, 'selected', 1, 1, 'virtual'); grid.cellClasses.add(decorator); model[decoratorsField].push(decorator); } else { grid[rowOrCol + 'Model'].getSelected().forEach(function (index) { var virtualIndex = grid[rowOrCol + 'Model'].toVirtual(index); var top = rowOrCol === 'row' ? virtualIndex : 0; var left = rowOrCol === 'col' ? virtualIndex : 0; var decorator = grid.cellClasses.create(top, left, 'selected', 1, 1, 'virtual'); grid.cellClasses.add(decorator); model[decoratorsField].push(decorator); }); } }
javascript
function handleRowColSelectionChange(rowOrCol) { var decoratorsField = ('_' + rowOrCol + 'SelectionClasses'); model[decoratorsField].forEach(function (selectionDecorator) { grid.cellClasses.remove(selectionDecorator); }); model[decoratorsField] = []; if (grid[rowOrCol + 'Model'].allSelected()) { var top = rowOrCol === 'row' ? Infinity : 0; var left = rowOrCol === 'col' ? Infinity : 0; var decorator = grid.cellClasses.create(top, left, 'selected', 1, 1, 'virtual'); grid.cellClasses.add(decorator); model[decoratorsField].push(decorator); } else { grid[rowOrCol + 'Model'].getSelected().forEach(function (index) { var virtualIndex = grid[rowOrCol + 'Model'].toVirtual(index); var top = rowOrCol === 'row' ? virtualIndex : 0; var left = rowOrCol === 'col' ? virtualIndex : 0; var decorator = grid.cellClasses.create(top, left, 'selected', 1, 1, 'virtual'); grid.cellClasses.add(decorator); model[decoratorsField].push(decorator); }); } }
[ "function", "handleRowColSelectionChange", "(", "rowOrCol", ")", "{", "var", "decoratorsField", "=", "(", "'_'", "+", "rowOrCol", "+", "'SelectionClasses'", ")", ";", "model", "[", "decoratorsField", "]", ".", "forEach", "(", "function", "(", "selectionDecorator", ")", "{", "grid", ".", "cellClasses", ".", "remove", "(", "selectionDecorator", ")", ";", "}", ")", ";", "model", "[", "decoratorsField", "]", "=", "[", "]", ";", "if", "(", "grid", "[", "rowOrCol", "+", "'Model'", "]", ".", "allSelected", "(", ")", ")", "{", "var", "top", "=", "rowOrCol", "===", "'row'", "?", "Infinity", ":", "0", ";", "var", "left", "=", "rowOrCol", "===", "'col'", "?", "Infinity", ":", "0", ";", "var", "decorator", "=", "grid", ".", "cellClasses", ".", "create", "(", "top", ",", "left", ",", "'selected'", ",", "1", ",", "1", ",", "'virtual'", ")", ";", "grid", ".", "cellClasses", ".", "add", "(", "decorator", ")", ";", "model", "[", "decoratorsField", "]", ".", "push", "(", "decorator", ")", ";", "}", "else", "{", "grid", "[", "rowOrCol", "+", "'Model'", "]", ".", "getSelected", "(", ")", ".", "forEach", "(", "function", "(", "index", ")", "{", "var", "virtualIndex", "=", "grid", "[", "rowOrCol", "+", "'Model'", "]", ".", "toVirtual", "(", "index", ")", ";", "var", "top", "=", "rowOrCol", "===", "'row'", "?", "virtualIndex", ":", "0", ";", "var", "left", "=", "rowOrCol", "===", "'col'", "?", "virtualIndex", ":", "0", ";", "var", "decorator", "=", "grid", ".", "cellClasses", ".", "create", "(", "top", ",", "left", ",", "'selected'", ",", "1", ",", "1", ",", "'virtual'", ")", ";", "grid", ".", "cellClasses", ".", "add", "(", "decorator", ")", ";", "model", "[", "decoratorsField", "]", ".", "push", "(", "decorator", ")", ";", "}", ")", ";", "}", "}" ]
row col selection
[ "row", "col", "selection" ]
c7ef254498624f56ed6a2df6cfb2ef695afcd0fd
https://github.com/gridgrid/grid/blob/c7ef254498624f56ed6a2df6cfb2ef695afcd0fd/src/modules/navigation-model/index.js#L412-L435
train
konnectors/libs
packages/cozy-konnector-libs/src/libs/categorization/index.js
createCategorizer
async function createCategorizer() { const classifierOptions = { tokenizer } // We can't initialize the model in parallel using `Promise.all` because with // it is not possible to manage errors separately let globalModel, localModel try { globalModel = await createGlobalModel(classifierOptions) } catch (e) { log('info', 'Failed to create global model:') log('info', e.message) } try { localModel = await createLocalModel(classifierOptions) } catch (e) { log('info', 'Failed to create local model:') log('info', e.message) } const modelsToApply = [globalModel, localModel].filter(Boolean) const categorize = transactions => { modelsToApply.forEach(model => model.categorize(transactions)) return transactions } return { categorize } }
javascript
async function createCategorizer() { const classifierOptions = { tokenizer } // We can't initialize the model in parallel using `Promise.all` because with // it is not possible to manage errors separately let globalModel, localModel try { globalModel = await createGlobalModel(classifierOptions) } catch (e) { log('info', 'Failed to create global model:') log('info', e.message) } try { localModel = await createLocalModel(classifierOptions) } catch (e) { log('info', 'Failed to create local model:') log('info', e.message) } const modelsToApply = [globalModel, localModel].filter(Boolean) const categorize = transactions => { modelsToApply.forEach(model => model.categorize(transactions)) return transactions } return { categorize } }
[ "async", "function", "createCategorizer", "(", ")", "{", "const", "classifierOptions", "=", "{", "tokenizer", "}", "let", "globalModel", ",", "localModel", "try", "{", "globalModel", "=", "await", "createGlobalModel", "(", "classifierOptions", ")", "}", "catch", "(", "e", ")", "{", "log", "(", "'info'", ",", "'Failed to create global model:'", ")", "log", "(", "'info'", ",", "e", ".", "message", ")", "}", "try", "{", "localModel", "=", "await", "createLocalModel", "(", "classifierOptions", ")", "}", "catch", "(", "e", ")", "{", "log", "(", "'info'", ",", "'Failed to create local model:'", ")", "log", "(", "'info'", ",", "e", ".", "message", ")", "}", "const", "modelsToApply", "=", "[", "globalModel", ",", "localModel", "]", ".", "filter", "(", "Boolean", ")", "const", "categorize", "=", "transactions", "=>", "{", "modelsToApply", ".", "forEach", "(", "model", "=>", "model", ".", "categorize", "(", "transactions", ")", ")", "return", "transactions", "}", "return", "{", "categorize", "}", "}" ]
Initialize global and local models and return an object exposing a `categorize` function that applies both models on an array of transactions The global model is a model specific to hosted Cozy instances. It is not available for self-hosted instances. It will just do nothing in that case. The local model is based on the user manual categorizations. Each model adds two properties to the transactions: * The global model adds `cozyCategoryId` and `cozyCategoryProba` * The local model adds `localCategoryId` and `localCategoryProba` In the end, each transaction can have up to four different categories. An application can use these categories to show the most significant for the user. See https://github.com/cozy/cozy-doctypes/blob/master/docs/io.cozy.bank.md#categories for more informations. @return {Object} an object with a `categorize` method @example const { BaseKonnector, createCategorizer } = require('cozy-konnector-libs') class BankingKonnector extends BaseKonnector { async saveTransactions() { const transactions = await this.fetchTransactions() const categorizer = await createCategorizer const categorizedTransactions = await categorizer.categorize(transactions) // Save categorizedTransactions } }
[ "Initialize", "global", "and", "local", "models", "and", "return", "an", "object", "exposing", "a", "categorize", "function", "that", "applies", "both", "models", "on", "an", "array", "of", "transactions" ]
a58f80984e9e0d160a5ae2ce892e4e55c656ddf1
https://github.com/konnectors/libs/blob/a58f80984e9e0d160a5ae2ce892e4e55c656ddf1/packages/cozy-konnector-libs/src/libs/categorization/index.js#L42-L72
train
konnectors/libs
packages/cozy-jobs-cli/src/cozy-authenticate.js
onRegistered
function onRegistered(client, url) { let server return new Promise(resolve => { server = http.createServer((request, response) => { if (request.url.indexOf('/do_access') === 0) { log('debug', request.url, 'url received') resolve(request.url) response.end( 'Authorization registered, you can close this page and go back to the cli' ) } }) server.listen(3333, () => { require('opn')(url, { wait: false }) console.log( 'A new tab just opened in your browser to require the right authorizations for this connector in your cozy. Waiting for it...' ) console.log( 'If your browser does not open (maybe your are in a headless virtual machine...), then paste this url in your browser' ) console.log(url) }) }).then( url => { server.close() return url }, err => { server.close() log('error', err, 'registration error') throw err } ) }
javascript
function onRegistered(client, url) { let server return new Promise(resolve => { server = http.createServer((request, response) => { if (request.url.indexOf('/do_access') === 0) { log('debug', request.url, 'url received') resolve(request.url) response.end( 'Authorization registered, you can close this page and go back to the cli' ) } }) server.listen(3333, () => { require('opn')(url, { wait: false }) console.log( 'A new tab just opened in your browser to require the right authorizations for this connector in your cozy. Waiting for it...' ) console.log( 'If your browser does not open (maybe your are in a headless virtual machine...), then paste this url in your browser' ) console.log(url) }) }).then( url => { server.close() return url }, err => { server.close() log('error', err, 'registration error') throw err } ) }
[ "function", "onRegistered", "(", "client", ",", "url", ")", "{", "let", "server", "return", "new", "Promise", "(", "resolve", "=>", "{", "server", "=", "http", ".", "createServer", "(", "(", "request", ",", "response", ")", "=>", "{", "if", "(", "request", ".", "url", ".", "indexOf", "(", "'/do_access'", ")", "===", "0", ")", "{", "log", "(", "'debug'", ",", "request", ".", "url", ",", "'url received'", ")", "resolve", "(", "request", ".", "url", ")", "response", ".", "end", "(", "'Authorization registered, you can close this page and go back to the cli'", ")", "}", "}", ")", "server", ".", "listen", "(", "3333", ",", "(", ")", "=>", "{", "require", "(", "'opn'", ")", "(", "url", ",", "{", "wait", ":", "false", "}", ")", "console", ".", "log", "(", "'A new tab just opened in your browser to require the right authorizations for this connector in your cozy. Waiting for it...'", ")", "console", ".", "log", "(", "'If your browser does not open (maybe your are in a headless virtual machine...), then paste this url in your browser'", ")", "console", ".", "log", "(", "url", ")", "}", ")", "}", ")", ".", "then", "(", "url", "=>", "{", "server", ".", "close", "(", ")", "return", "url", "}", ",", "err", "=>", "{", "server", ".", "close", "(", ")", "log", "(", "'error'", ",", "err", ",", "'registration error'", ")", "throw", "err", "}", ")", "}" ]
check if we have a token file if any return a promise with the credentials
[ "check", "if", "we", "have", "a", "token", "file", "if", "any", "return", "a", "promise", "with", "the", "credentials" ]
a58f80984e9e0d160a5ae2ce892e4e55c656ddf1
https://github.com/konnectors/libs/blob/a58f80984e9e0d160a5ae2ce892e4e55c656ddf1/packages/cozy-jobs-cli/src/cozy-authenticate.js#L18-L51
train
konnectors/libs
packages/cozy-logger/src/index.js
log
function log(type, message, label, namespace) { if (filterOut(level, type, message, label, namespace)) { return } // eslint-disable-next-line no-console console.log(format(type, message, label, namespace)) }
javascript
function log(type, message, label, namespace) { if (filterOut(level, type, message, label, namespace)) { return } // eslint-disable-next-line no-console console.log(format(type, message, label, namespace)) }
[ "function", "log", "(", "type", ",", "message", ",", "label", ",", "namespace", ")", "{", "if", "(", "filterOut", "(", "level", ",", "type", ",", "message", ",", "label", ",", "namespace", ")", ")", "{", "return", "}", "console", ".", "log", "(", "format", "(", "type", ",", "message", ",", "label", ",", "namespace", ")", ")", "}" ]
Use it to log messages in your konnector. Typical types are - `debug` - `warning` - `info` - `error` - `ok` @example They will be colored in development mode. In production mode, those logs are formatted in JSON to be interpreted by the stack and possibly sent to the client. `error` will stop the konnector. ```js logger = log('my-namespace') logger('debug', '365 bills') // my-namespace : debug : 365 bills logger('info', 'Page fetched') // my-namespace : info : Page fetched ``` @param {string} type @param {string} message @param {string} label @param {string} namespace
[ "Use", "it", "to", "log", "messages", "in", "your", "konnector", ".", "Typical", "types", "are" ]
a58f80984e9e0d160a5ae2ce892e4e55c656ddf1
https://github.com/konnectors/libs/blob/a58f80984e9e0d160a5ae2ce892e4e55c656ddf1/packages/cozy-logger/src/index.js#L46-L52
train