id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
24,900
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
24,901
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
24,902
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", "(", ")", "{", "// 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", ";", "}" ]
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
24,903
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
24,904
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", "[", ",", "// 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", "(", "`", "${", "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
24,905
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", "{", "// 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", "(", "`", "${", "tagFrom", "}", "`", ")", ";", "const", "prevTag", "=", "stdout", ".", "trim", "(", ")", ";", "const", "nextVersion", "=", "parseVersion", "(", "argv", "[", "releaseNameParam", "]", ")", ";", "// Normalize the given \"release-name\" for the tile (strip out pre-release information).", "const", "nextVersionString", "=", "`", "${", "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", "}", "${", "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'", ",", "`", "\\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", ";", "}", "}" ]
Main async method
[ "Main", "async", "method" ]
db0859bfdcf75bc7e68244d09171654a7a4ed562
https://github.com/shopgate/pwa/blob/db0859bfdcf75bc7e68244d09171654a7a4ed562/scripts/build-changelog.js#L189-L248
24,906
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
24,907
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", ")", ";", "/** 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", ")", ")", ";", "}", ")", ";", "/**\n * Expire products after checkout, fetch updated data\n */", "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
24,908
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", ")", "{", "// 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", "+=", "`", "\\\\", "${", "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", ",", "}", ";", "}" ]
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
24,909
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", ")", "{", "// 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", ";", "}", "/**\n * Recursive callable function to traverse through a complex object\n *\n * @param {Object} currentData The current data that shall be investigated\n * @param {number} currentPathSegmentIndex The current index within the path segment list\n * @returns {*} The value at the end of the path or the default one\n */", "function", "checkPathSegment", "(", "currentData", ",", "currentPathSegmentIndex", ")", "{", "// Get the current segment within the path", "const", "currentPathSegment", "=", "pathSegments", "[", "currentPathSegmentIndex", "]", ";", "const", "nextPathSegmentIndex", "=", "currentPathSegmentIndex", "+", "1", ";", "/**\n * Prepare the default value as return value for the case that no matching property was\n * found for the current path segment. In that case the path must be wrong.\n */", "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", ")", ";", "}" ]
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
24,910
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", ")", "{", "// Get the current segment within the path", "const", "currentPathSegment", "=", "pathSegments", "[", "currentPathSegmentIndex", "]", ";", "const", "nextPathSegmentIndex", "=", "currentPathSegmentIndex", "+", "1", ";", "/**\n * Prepare the default value as return value for the case that no matching property was\n * found for the current path segment. In that case the path must be wrong.\n */", "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", ";", "}" ]
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
24,911
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", ")", "{", "// Take care that the parameters don't contain leading or trailing spaces", "let", "trimmedTitle", "=", "title", ".", "trim", "(", ")", ";", "const", "trimmedShopName", "=", "shopName", ".", "trim", "(", ")", ";", "if", "(", "!", "trimmedShopName", ")", "{", "/**\n * If no shop name is available, it doesn't make sense to replace it.\n * So we return the the trimmed title directly.\n */", "return", "trimmedTitle", ";", "}", "/**\n * Setup the RegExp. It matches leading and trailing occurrences\n * of known patterns for generically added shop names within page title\n */", "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", "(", ")", ";", "}" ]
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
24,912
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
24,913
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
24,914
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
24,915
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
24,916
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
24,917
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", "(", ")", ";", "// 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", ";", "}" ]
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
24,918
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
24,919
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
24,920
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
24,921
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
24,922
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
24,923
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
24,924
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
24,925
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 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", "(", ")", ";", "}", "}" ]
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
24,926
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
24,927
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
24,928
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", "(", "(", ")", "=>", "{", "// 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'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
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
24,929
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
24,930
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", "+", "'\" '", "+", "// '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", ";", "}" ]
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
24,931
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", "}", "}", ";", "}", ")", ";", "// 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", ";", "}" ]
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
24,932
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
24,933
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", ";", "}", "// 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", ";", "}" ]
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
24,934
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
24,935
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", ")", ";", "// x² + y² = distance²", "$event", ".", "add", "(", "this", ",", "\"mousedown\"", ",", "handler", ",", "data", ")", ";", "if", "(", "this", ".", "attachEvent", ")", "this", ".", "attachEvent", "(", "\"ondragstart\"", ",", "dontStart", ")", ";", "// prevent image dragging in IE...", "}" ]
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
24,936
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", ";", "// force the event 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
24,937
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", ";", "// 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", "}" ]
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
24,938
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", "(", ")", "{", "// *** 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", ")", ")", ";", "}" ]
- 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
24,939
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
24,940
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
24,941
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", ",", "'\\\\,'", ")", ";", "return", "result", ";", "}" ]
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
24,942
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", "=", "{", "}", ";", "}", "// 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", "(", "`", "${", "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
24,943
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", "(", "{", "// service: 'tia',", "host", ":", "gT", ".", "suiteConfig", ".", "mailSmtpHost", ",", "secure", ":", "true", ",", "// secure : false,", "// port: 25,", "auth", ":", "{", "user", ":", "gT", ".", "suiteConfig", ".", "mailUser", ",", "pass", ":", "gT", ".", "suiteConfig", ".", "mailPassword", ",", "}", ",", "// , tls: {", "// rejectUnauthorized: false", "// }", "}", ")", ")", ";", "}" ]
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
24,944
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
24,945
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", ";", "// eslint-disable-line no-param-reassign", "}", "}" ]
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
24,946
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
24,947
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
24,948
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
24,949
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", ")", "{", "// 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", ";", "}" ]
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
24,950
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.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", ")", ";", "}" ]
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
24,951
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", ";", "// O", "}" ]
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
24,952
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'", "+", "res", ".", "join", "(", "'\\n'", ")", "+", "'\\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
24,953
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", "(", "', '", ")", ";", "// 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", ",", "'++++++++++'", ",", "]", ")", ";", "}" ]
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
24,954
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
24,955
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", ")", "{", "// 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", ",", "}", ")", ";", "}", "}" ]
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
24,956
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
24,957
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
24,958
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
24,959
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
24,960
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", ";", "// 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", "(", "`", "${", "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
24,961
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
24,962
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", ";", "// To next record.", "}", "}", "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
24,963
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
24,964
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
24,965
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
24,966
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
24,967
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
24,968
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 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", "}", ")", ")", ";", "}", "}" ]
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
24,969
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
24,970
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", ")", "{", "// 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", "(", "''", ")", ";", "}" ]
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
24,971
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
24,972
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", ";", "//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", ";", "}" ]
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
24,973
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
24,974
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", ":", "{", "}", "}", ";", "// 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", ";", "}" ]
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
24,975
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", ")", "||", "// 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", ";", "}" ]
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
24,976
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
24,977
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
24,978
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
24,979
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", ")", "{", "// 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", ";", "}" ]
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
24,980
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", ")", ";", "}", "}", ";", "// use the backbone verbs", "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
24,981
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
24,982
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
24,983
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
24,984
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", ")", "{", "}", "// 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", ";", "}" ]
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
24,985
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
24,986
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
24,987
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
24,988
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", "}", "// 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", "}", "}" ]
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
24,989
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
24,990
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", "}", "// eslint-disable-next-line no-console", "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
24,991
armed/gulp-flatten
lib/flatten-path.js
flattenPath
function flattenPath(file, opts) { var fileName = path.basename(file.path); var dirs; if (!opts.includeParents && !opts.subPath) { return fileName; } dirs = path.dirname(file.relative).split(path.sep); if (opts.includeParents) { dirs = includeParents(dirs, opts.includeParents); } if (opts.subPath) { dirs = subPath(dirs, opts.subPath); } dirs.push(fileName); return path.join.apply(path, dirs); }
javascript
function flattenPath(file, opts) { var fileName = path.basename(file.path); var dirs; if (!opts.includeParents && !opts.subPath) { return fileName; } dirs = path.dirname(file.relative).split(path.sep); if (opts.includeParents) { dirs = includeParents(dirs, opts.includeParents); } if (opts.subPath) { dirs = subPath(dirs, opts.subPath); } dirs.push(fileName); return path.join.apply(path, dirs); }
[ "function", "flattenPath", "(", "file", ",", "opts", ")", "{", "var", "fileName", "=", "path", ".", "basename", "(", "file", ".", "path", ")", ";", "var", "dirs", ";", "if", "(", "!", "opts", ".", "includeParents", "&&", "!", "opts", ".", "subPath", ")", "{", "return", "fileName", ";", "}", "dirs", "=", "path", ".", "dirname", "(", "file", ".", "relative", ")", ".", "split", "(", "path", ".", "sep", ")", ";", "if", "(", "opts", ".", "includeParents", ")", "{", "dirs", "=", "includeParents", "(", "dirs", ",", "opts", ".", "includeParents", ")", ";", "}", "if", "(", "opts", ".", "subPath", ")", "{", "dirs", "=", "subPath", "(", "dirs", ",", "opts", ".", "subPath", ")", ";", "}", "dirs", ".", "push", "(", "fileName", ")", ";", "return", "path", ".", "join", ".", "apply", "(", "path", ",", "dirs", ")", ";", "}" ]
Flatten the path to the desired depth @param {File} file - vinyl file @param {Object} options @return {String}
[ "Flatten", "the", "path", "to", "the", "desired", "depth" ]
aa164976236a44a7f7f31de58d57c71384ae2c26
https://github.com/armed/gulp-flatten/blob/aa164976236a44a7f7f31de58d57c71384ae2c26/lib/flatten-path.js#L49-L67
24,992
giseburt/TinyG-node
tinyg.js
function(r) { if (!seenConnectionBanner) { self.emit('connected', r); seenConnectionBanner = true; deferredSetup.resolve(r); return; } if (r.hasOwnProperty("rx") && self.serialPortData === null) { self.ignoredResponses--; if (!self.timedSendsOnly) { self.linesRequested = r.rx - 1; } // -1 is okay, that just means wait until we've sent two lines to send again } else if (self.ignoredResponses > 0) { self.ignoredResponses--; return; } else { if (!self.timedSendsOnly) { self.linesRequested++; } } self._sendLines(); }
javascript
function(r) { if (!seenConnectionBanner) { self.emit('connected', r); seenConnectionBanner = true; deferredSetup.resolve(r); return; } if (r.hasOwnProperty("rx") && self.serialPortData === null) { self.ignoredResponses--; if (!self.timedSendsOnly) { self.linesRequested = r.rx - 1; } // -1 is okay, that just means wait until we've sent two lines to send again } else if (self.ignoredResponses > 0) { self.ignoredResponses--; return; } else { if (!self.timedSendsOnly) { self.linesRequested++; } } self._sendLines(); }
[ "function", "(", "r", ")", "{", "if", "(", "!", "seenConnectionBanner", ")", "{", "self", ".", "emit", "(", "'connected'", ",", "r", ")", ";", "seenConnectionBanner", "=", "true", ";", "deferredSetup", ".", "resolve", "(", "r", ")", ";", "return", ";", "}", "if", "(", "r", ".", "hasOwnProperty", "(", "\"rx\"", ")", "&&", "self", ".", "serialPortData", "===", "null", ")", "{", "self", ".", "ignoredResponses", "--", ";", "if", "(", "!", "self", ".", "timedSendsOnly", ")", "{", "self", ".", "linesRequested", "=", "r", ".", "rx", "-", "1", ";", "}", "// -1 is okay, that just means wait until we've sent two lines to send again", "}", "else", "if", "(", "self", ".", "ignoredResponses", ">", "0", ")", "{", "self", ".", "ignoredResponses", "--", ";", "return", ";", "}", "else", "{", "if", "(", "!", "self", ".", "timedSendsOnly", ")", "{", "self", ".", "linesRequested", "++", ";", "}", "}", "self", ".", "_sendLines", "(", ")", ";", "}" ]
Prepare the event listeners
[ "Prepare", "the", "event", "listeners" ]
1bf51558e4e6b8165fdc7ed09f80782ab81834f1
https://github.com/giseburt/TinyG-node/blob/1bf51558e4e6b8165fdc7ed09f80782ab81834f1/tinyg.js#L252-L276
24,993
giseburt/TinyG-node
tinyg.js
function (k, v) { promiseChain = promiseChain.then(function() { return self.set(k, v); }).catch(function (e) { // console.log("Caught error setting {", k, ":", v, "}: ", e); self.emit('error', e); return Q.fcall(function () {}); }); }
javascript
function (k, v) { promiseChain = promiseChain.then(function() { return self.set(k, v); }).catch(function (e) { // console.log("Caught error setting {", k, ":", v, "}: ", e); self.emit('error', e); return Q.fcall(function () {}); }); }
[ "function", "(", "k", ",", "v", ")", "{", "promiseChain", "=", "promiseChain", ".", "then", "(", "function", "(", ")", "{", "return", "self", ".", "set", "(", "k", ",", "v", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "// console.log(\"Caught error setting {\", k, \":\", v, \"}: \", e);", "self", ".", "emit", "(", "'error'", ",", "e", ")", ";", "return", "Q", ".", "fcall", "(", "function", "(", ")", "{", "}", ")", ";", "}", ")", ";", "}" ]
We have to artificially create a function context to hold the values so we make a closure function, assign the variables, and immediately call it.
[ "We", "have", "to", "artificially", "create", "a", "function", "context", "to", "hold", "the", "values", "so", "we", "make", "a", "closure", "function", "assign", "the", "variables", "and", "immediately", "call", "it", "." ]
1bf51558e4e6b8165fdc7ed09f80782ab81834f1
https://github.com/giseburt/TinyG-node/blob/1bf51558e4e6b8165fdc7ed09f80782ab81834f1/tinyg.js#L866-L874
24,994
audiojs/pcm-util
index.js
getFormat
function getFormat (obj) { //undefined format - no format-related props, for sure if (!obj) return {} //if is string - parse format if (typeof obj === 'string' || obj.id) { return parse(obj.id || obj) } //if audio buffer - we know it’s format else if (isAudioBuffer(obj)) { var arrayFormat = fromTypedArray(obj.getChannelData(0)) return { sampleRate: obj.sampleRate, channels: obj.numberOfChannels, samplesPerFrame: obj.length, float: true, signed: true, bitDepth: arrayFormat.bitDepth } } //if is array - detect format else if (ArrayBuffer.isView(obj)) { return fromTypedArray(obj) } //FIXME: add AudioNode, stream detection //else detect from obhect return fromObject(obj) }
javascript
function getFormat (obj) { //undefined format - no format-related props, for sure if (!obj) return {} //if is string - parse format if (typeof obj === 'string' || obj.id) { return parse(obj.id || obj) } //if audio buffer - we know it’s format else if (isAudioBuffer(obj)) { var arrayFormat = fromTypedArray(obj.getChannelData(0)) return { sampleRate: obj.sampleRate, channels: obj.numberOfChannels, samplesPerFrame: obj.length, float: true, signed: true, bitDepth: arrayFormat.bitDepth } } //if is array - detect format else if (ArrayBuffer.isView(obj)) { return fromTypedArray(obj) } //FIXME: add AudioNode, stream detection //else detect from obhect return fromObject(obj) }
[ "function", "getFormat", "(", "obj", ")", "{", "//undefined format - no format-related props, for sure", "if", "(", "!", "obj", ")", "return", "{", "}", "//if is string - parse format", "if", "(", "typeof", "obj", "===", "'string'", "||", "obj", ".", "id", ")", "{", "return", "parse", "(", "obj", ".", "id", "||", "obj", ")", "}", "//if audio buffer - we know it’s format", "else", "if", "(", "isAudioBuffer", "(", "obj", ")", ")", "{", "var", "arrayFormat", "=", "fromTypedArray", "(", "obj", ".", "getChannelData", "(", "0", ")", ")", "return", "{", "sampleRate", ":", "obj", ".", "sampleRate", ",", "channels", ":", "obj", ".", "numberOfChannels", ",", "samplesPerFrame", ":", "obj", ".", "length", ",", "float", ":", "true", ",", "signed", ":", "true", ",", "bitDepth", ":", "arrayFormat", ".", "bitDepth", "}", "}", "//if is array - detect format", "else", "if", "(", "ArrayBuffer", ".", "isView", "(", "obj", ")", ")", "{", "return", "fromTypedArray", "(", "obj", ")", "}", "//FIXME: add AudioNode, stream detection", "//else detect from obhect", "return", "fromObject", "(", "obj", ")", "}" ]
Get format info from any object, unnormalized.
[ "Get", "format", "info", "from", "any", "object", "unnormalized", "." ]
d4e949178e61a2c297d7d38df6da0ee325524e2f
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L43-L74
24,995
audiojs/pcm-util
index.js
equal
function equal (a, b) { return (a.id || stringify(a)) === (b.id || stringify(b)) }
javascript
function equal (a, b) { return (a.id || stringify(a)) === (b.id || stringify(b)) }
[ "function", "equal", "(", "a", ",", "b", ")", "{", "return", "(", "a", ".", "id", "||", "stringify", "(", "a", ")", ")", "===", "(", "b", ".", "id", "||", "stringify", "(", "b", ")", ")", "}" ]
Whether one format is equal to another
[ "Whether", "one", "format", "is", "equal", "to", "another" ]
d4e949178e61a2c297d7d38df6da0ee325524e2f
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L119-L121
24,996
audiojs/pcm-util
index.js
toArrayBuffer
function toArrayBuffer (audioBuffer, format) { if (!isNormalized(format)) format = normalize(format) var data //convert to arraybuffer if (audioBuffer._data) data = audioBuffer._data.buffer; else { var floatArray = audioBuffer.getChannelData(0).constructor; data = new floatArray(audioBuffer.length * audioBuffer.numberOfChannels); for (var channel = 0; channel < audioBuffer.numberOfChannels; channel++) { data.set(audioBuffer.getChannelData(channel), channel * audioBuffer.length); } } var arrayFormat = fromTypedArray(audioBuffer.getChannelData(0)) var buffer = convert(data, { float: true, channels: audioBuffer.numberOfChannels, sampleRate: audioBuffer.sampleRate, interleaved: false, bitDepth: arrayFormat.bitDepth }, format) return buffer }
javascript
function toArrayBuffer (audioBuffer, format) { if (!isNormalized(format)) format = normalize(format) var data //convert to arraybuffer if (audioBuffer._data) data = audioBuffer._data.buffer; else { var floatArray = audioBuffer.getChannelData(0).constructor; data = new floatArray(audioBuffer.length * audioBuffer.numberOfChannels); for (var channel = 0; channel < audioBuffer.numberOfChannels; channel++) { data.set(audioBuffer.getChannelData(channel), channel * audioBuffer.length); } } var arrayFormat = fromTypedArray(audioBuffer.getChannelData(0)) var buffer = convert(data, { float: true, channels: audioBuffer.numberOfChannels, sampleRate: audioBuffer.sampleRate, interleaved: false, bitDepth: arrayFormat.bitDepth }, format) return buffer }
[ "function", "toArrayBuffer", "(", "audioBuffer", ",", "format", ")", "{", "if", "(", "!", "isNormalized", "(", "format", ")", ")", "format", "=", "normalize", "(", "format", ")", "var", "data", "//convert to arraybuffer", "if", "(", "audioBuffer", ".", "_data", ")", "data", "=", "audioBuffer", ".", "_data", ".", "buffer", ";", "else", "{", "var", "floatArray", "=", "audioBuffer", ".", "getChannelData", "(", "0", ")", ".", "constructor", ";", "data", "=", "new", "floatArray", "(", "audioBuffer", ".", "length", "*", "audioBuffer", ".", "numberOfChannels", ")", ";", "for", "(", "var", "channel", "=", "0", ";", "channel", "<", "audioBuffer", ".", "numberOfChannels", ";", "channel", "++", ")", "{", "data", ".", "set", "(", "audioBuffer", ".", "getChannelData", "(", "channel", ")", ",", "channel", "*", "audioBuffer", ".", "length", ")", ";", "}", "}", "var", "arrayFormat", "=", "fromTypedArray", "(", "audioBuffer", ".", "getChannelData", "(", "0", ")", ")", "var", "buffer", "=", "convert", "(", "data", ",", "{", "float", ":", "true", ",", "channels", ":", "audioBuffer", ".", "numberOfChannels", ",", "sampleRate", ":", "audioBuffer", ".", "sampleRate", ",", "interleaved", ":", "false", ",", "bitDepth", ":", "arrayFormat", ".", "bitDepth", "}", ",", "format", ")", "return", "buffer", "}" ]
Convert AudioBuffer to Buffer with specified format
[ "Convert", "AudioBuffer", "to", "Buffer", "with", "specified", "format" ]
d4e949178e61a2c297d7d38df6da0ee325524e2f
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L170-L198
24,997
audiojs/pcm-util
index.js
toAudioBuffer
function toAudioBuffer (buffer, format) { if (!isNormalized(format)) format = normalize(format) buffer = convert(buffer, format, { channels: format.channels, sampleRate: format.sampleRate, interleaved: false, float: true }) var len = Math.floor(buffer.byteLength * .25 / format.channels) var audioBuffer = new AudioBuffer(null, { length: len, numberOfChannels: format.channels, sampleRate: format.sampleRate }) var step = len * 4 for (var channel = 0; channel < format.channels; channel++) { var offset = channel * step var data = new Float32Array(buffer.slice(offset, offset + step)) audioBuffer.getChannelData(channel).set(data) } return audioBuffer }
javascript
function toAudioBuffer (buffer, format) { if (!isNormalized(format)) format = normalize(format) buffer = convert(buffer, format, { channels: format.channels, sampleRate: format.sampleRate, interleaved: false, float: true }) var len = Math.floor(buffer.byteLength * .25 / format.channels) var audioBuffer = new AudioBuffer(null, { length: len, numberOfChannels: format.channels, sampleRate: format.sampleRate }) var step = len * 4 for (var channel = 0; channel < format.channels; channel++) { var offset = channel * step var data = new Float32Array(buffer.slice(offset, offset + step)) audioBuffer.getChannelData(channel).set(data) } return audioBuffer }
[ "function", "toAudioBuffer", "(", "buffer", ",", "format", ")", "{", "if", "(", "!", "isNormalized", "(", "format", ")", ")", "format", "=", "normalize", "(", "format", ")", "buffer", "=", "convert", "(", "buffer", ",", "format", ",", "{", "channels", ":", "format", ".", "channels", ",", "sampleRate", ":", "format", ".", "sampleRate", ",", "interleaved", ":", "false", ",", "float", ":", "true", "}", ")", "var", "len", "=", "Math", ".", "floor", "(", "buffer", ".", "byteLength", "*", ".25", "/", "format", ".", "channels", ")", "var", "audioBuffer", "=", "new", "AudioBuffer", "(", "null", ",", "{", "length", ":", "len", ",", "numberOfChannels", ":", "format", ".", "channels", ",", "sampleRate", ":", "format", ".", "sampleRate", "}", ")", "var", "step", "=", "len", "*", "4", "for", "(", "var", "channel", "=", "0", ";", "channel", "<", "format", ".", "channels", ";", "channel", "++", ")", "{", "var", "offset", "=", "channel", "*", "step", "var", "data", "=", "new", "Float32Array", "(", "buffer", ".", "slice", "(", "offset", ",", "offset", "+", "step", ")", ")", "audioBuffer", ".", "getChannelData", "(", "channel", ")", ".", "set", "(", "data", ")", "}", "return", "audioBuffer", "}" ]
Convert Buffer to AudioBuffer with specified format
[ "Convert", "Buffer", "to", "AudioBuffer", "with", "specified", "format" ]
d4e949178e61a2c297d7d38df6da0ee325524e2f
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L202-L228
24,998
audiojs/pcm-util
index.js
convert
function convert (buffer, from, to) { //ensure formats are full if (!isNormalized(from)) from = normalize(from) if (!isNormalized(to)) to = normalize(to) //convert buffer/alike to arrayBuffer var data if (buffer instanceof ArrayBuffer) { data = buffer } else if (ArrayBuffer.isView(buffer)) { if (buffer.byteOffset != null) data = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); else data = buffer.buffer; } else { data = (new Uint8Array(buffer.length != null ? buffer : [buffer])).buffer } //ignore needless conversion if (equal(from ,to)) { return data } //create containers for conversion var fromArray = new (arrayClass(from))(data) //toArray is automatically filled with mapped values //but in some cases mapped badly, e. g. float → int(round + rotate) var toArray = new (arrayClass(to))(fromArray) //if range differ, we should apply more thoughtful mapping if (from.max !== to.max) { fromArray.forEach(function (value, idx) { //ignore not changed range //bring to 0..1 var normalValue = (value - from.min) / (from.max - from.min) //bring to new format ranges value = normalValue * (to.max - to.min) + to.min //clamp (buffers does not like values outside of bounds) toArray[idx] = Math.max(to.min, Math.min(to.max, value)) }) } //reinterleave, if required if (from.interleaved != to.interleaved) { var channels = from.channels var len = Math.floor(fromArray.length / channels) //deinterleave if (from.interleaved && !to.interleaved) { toArray = toArray.map(function (value, idx, data) { var targetOffset = idx % len var targetChannel = ~~(idx / len) return data[targetOffset * channels + targetChannel] }) } //interleave else if (!from.interleaved && to.interleaved) { toArray = toArray.map(function (value, idx, data) { var targetOffset = ~~(idx / channels) var targetChannel = idx % channels return data[targetChannel * len + targetOffset] }) } } //ensure endianness if (!to.float && from.byteOrder !== to.byteOrder) { var le = to.byteOrder === 'LE' var view = new DataView(toArray.buffer) var step = to.bitDepth / 8 var methodName = 'set' + getDataViewSuffix(to) for (var i = 0, l = toArray.length; i < l; i++) { view[methodName](i*step, toArray[i], le) } } return toArray.buffer }
javascript
function convert (buffer, from, to) { //ensure formats are full if (!isNormalized(from)) from = normalize(from) if (!isNormalized(to)) to = normalize(to) //convert buffer/alike to arrayBuffer var data if (buffer instanceof ArrayBuffer) { data = buffer } else if (ArrayBuffer.isView(buffer)) { if (buffer.byteOffset != null) data = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); else data = buffer.buffer; } else { data = (new Uint8Array(buffer.length != null ? buffer : [buffer])).buffer } //ignore needless conversion if (equal(from ,to)) { return data } //create containers for conversion var fromArray = new (arrayClass(from))(data) //toArray is automatically filled with mapped values //but in some cases mapped badly, e. g. float → int(round + rotate) var toArray = new (arrayClass(to))(fromArray) //if range differ, we should apply more thoughtful mapping if (from.max !== to.max) { fromArray.forEach(function (value, idx) { //ignore not changed range //bring to 0..1 var normalValue = (value - from.min) / (from.max - from.min) //bring to new format ranges value = normalValue * (to.max - to.min) + to.min //clamp (buffers does not like values outside of bounds) toArray[idx] = Math.max(to.min, Math.min(to.max, value)) }) } //reinterleave, if required if (from.interleaved != to.interleaved) { var channels = from.channels var len = Math.floor(fromArray.length / channels) //deinterleave if (from.interleaved && !to.interleaved) { toArray = toArray.map(function (value, idx, data) { var targetOffset = idx % len var targetChannel = ~~(idx / len) return data[targetOffset * channels + targetChannel] }) } //interleave else if (!from.interleaved && to.interleaved) { toArray = toArray.map(function (value, idx, data) { var targetOffset = ~~(idx / channels) var targetChannel = idx % channels return data[targetChannel * len + targetOffset] }) } } //ensure endianness if (!to.float && from.byteOrder !== to.byteOrder) { var le = to.byteOrder === 'LE' var view = new DataView(toArray.buffer) var step = to.bitDepth / 8 var methodName = 'set' + getDataViewSuffix(to) for (var i = 0, l = toArray.length; i < l; i++) { view[methodName](i*step, toArray[i], le) } } return toArray.buffer }
[ "function", "convert", "(", "buffer", ",", "from", ",", "to", ")", "{", "//ensure formats are full", "if", "(", "!", "isNormalized", "(", "from", ")", ")", "from", "=", "normalize", "(", "from", ")", "if", "(", "!", "isNormalized", "(", "to", ")", ")", "to", "=", "normalize", "(", "to", ")", "//convert buffer/alike to arrayBuffer", "var", "data", "if", "(", "buffer", "instanceof", "ArrayBuffer", ")", "{", "data", "=", "buffer", "}", "else", "if", "(", "ArrayBuffer", ".", "isView", "(", "buffer", ")", ")", "{", "if", "(", "buffer", ".", "byteOffset", "!=", "null", ")", "data", "=", "buffer", ".", "buffer", ".", "slice", "(", "buffer", ".", "byteOffset", ",", "buffer", ".", "byteOffset", "+", "buffer", ".", "byteLength", ")", ";", "else", "data", "=", "buffer", ".", "buffer", ";", "}", "else", "{", "data", "=", "(", "new", "Uint8Array", "(", "buffer", ".", "length", "!=", "null", "?", "buffer", ":", "[", "buffer", "]", ")", ")", ".", "buffer", "}", "//ignore needless conversion", "if", "(", "equal", "(", "from", ",", "to", ")", ")", "{", "return", "data", "}", "//create containers for conversion", "var", "fromArray", "=", "new", "(", "arrayClass", "(", "from", ")", ")", "(", "data", ")", "//toArray is automatically filled with mapped values", "//but in some cases mapped badly, e. g. float → int(round + rotate)", "var", "toArray", "=", "new", "(", "arrayClass", "(", "to", ")", ")", "(", "fromArray", ")", "//if range differ, we should apply more thoughtful mapping", "if", "(", "from", ".", "max", "!==", "to", ".", "max", ")", "{", "fromArray", ".", "forEach", "(", "function", "(", "value", ",", "idx", ")", "{", "//ignore not changed range", "//bring to 0..1", "var", "normalValue", "=", "(", "value", "-", "from", ".", "min", ")", "/", "(", "from", ".", "max", "-", "from", ".", "min", ")", "//bring to new format ranges", "value", "=", "normalValue", "*", "(", "to", ".", "max", "-", "to", ".", "min", ")", "+", "to", ".", "min", "//clamp (buffers does not like values outside of bounds)", "toArray", "[", "idx", "]", "=", "Math", ".", "max", "(", "to", ".", "min", ",", "Math", ".", "min", "(", "to", ".", "max", ",", "value", ")", ")", "}", ")", "}", "//reinterleave, if required", "if", "(", "from", ".", "interleaved", "!=", "to", ".", "interleaved", ")", "{", "var", "channels", "=", "from", ".", "channels", "var", "len", "=", "Math", ".", "floor", "(", "fromArray", ".", "length", "/", "channels", ")", "//deinterleave", "if", "(", "from", ".", "interleaved", "&&", "!", "to", ".", "interleaved", ")", "{", "toArray", "=", "toArray", ".", "map", "(", "function", "(", "value", ",", "idx", ",", "data", ")", "{", "var", "targetOffset", "=", "idx", "%", "len", "var", "targetChannel", "=", "~", "~", "(", "idx", "/", "len", ")", "return", "data", "[", "targetOffset", "*", "channels", "+", "targetChannel", "]", "}", ")", "}", "//interleave", "else", "if", "(", "!", "from", ".", "interleaved", "&&", "to", ".", "interleaved", ")", "{", "toArray", "=", "toArray", ".", "map", "(", "function", "(", "value", ",", "idx", ",", "data", ")", "{", "var", "targetOffset", "=", "~", "~", "(", "idx", "/", "channels", ")", "var", "targetChannel", "=", "idx", "%", "channels", "return", "data", "[", "targetChannel", "*", "len", "+", "targetOffset", "]", "}", ")", "}", "}", "//ensure endianness", "if", "(", "!", "to", ".", "float", "&&", "from", ".", "byteOrder", "!==", "to", ".", "byteOrder", ")", "{", "var", "le", "=", "to", ".", "byteOrder", "===", "'LE'", "var", "view", "=", "new", "DataView", "(", "toArray", ".", "buffer", ")", "var", "step", "=", "to", ".", "bitDepth", "/", "8", "var", "methodName", "=", "'set'", "+", "getDataViewSuffix", "(", "to", ")", "for", "(", "var", "i", "=", "0", ",", "l", "=", "toArray", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "view", "[", "methodName", "]", "(", "i", "*", "step", ",", "toArray", "[", "i", "]", ",", "le", ")", "}", "}", "return", "toArray", ".", "buffer", "}" ]
Convert buffer from format A to format B.
[ "Convert", "buffer", "from", "format", "A", "to", "format", "B", "." ]
d4e949178e61a2c297d7d38df6da0ee325524e2f
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L234-L316
24,999
audiojs/pcm-util
index.js
fromTypedArray
function fromTypedArray (array) { if (array instanceof Int8Array) { return { float: false, signed: true, bitDepth: 8 } } if ((array instanceof Uint8Array) || (array instanceof Uint8ClampedArray)) { return { float: false, signed: false, bitDepth: 8 } } if (array instanceof Int16Array) { return { float: false, signed: true, bitDepth: 16 } } if (array instanceof Uint16Array) { return { float: false, signed: false, bitDepth: 16 } } if (array instanceof Int32Array) { return { float: false, signed: true, bitDepth: 32 } } if (array instanceof Uint32Array) { return { float: false, signed: false, bitDepth: 32 } } if (array instanceof Float32Array) { return { float: true, signed: false, bitDepth: 32 } } if (array instanceof Float64Array) { return { float: true, signed: false, bitDepth: 64 } } //other dataview types are Uint8Arrays return { float: false, signed: false, bitDepth: 8 } }
javascript
function fromTypedArray (array) { if (array instanceof Int8Array) { return { float: false, signed: true, bitDepth: 8 } } if ((array instanceof Uint8Array) || (array instanceof Uint8ClampedArray)) { return { float: false, signed: false, bitDepth: 8 } } if (array instanceof Int16Array) { return { float: false, signed: true, bitDepth: 16 } } if (array instanceof Uint16Array) { return { float: false, signed: false, bitDepth: 16 } } if (array instanceof Int32Array) { return { float: false, signed: true, bitDepth: 32 } } if (array instanceof Uint32Array) { return { float: false, signed: false, bitDepth: 32 } } if (array instanceof Float32Array) { return { float: true, signed: false, bitDepth: 32 } } if (array instanceof Float64Array) { return { float: true, signed: false, bitDepth: 64 } } //other dataview types are Uint8Arrays return { float: false, signed: false, bitDepth: 8 } }
[ "function", "fromTypedArray", "(", "array", ")", "{", "if", "(", "array", "instanceof", "Int8Array", ")", "{", "return", "{", "float", ":", "false", ",", "signed", ":", "true", ",", "bitDepth", ":", "8", "}", "}", "if", "(", "(", "array", "instanceof", "Uint8Array", ")", "||", "(", "array", "instanceof", "Uint8ClampedArray", ")", ")", "{", "return", "{", "float", ":", "false", ",", "signed", ":", "false", ",", "bitDepth", ":", "8", "}", "}", "if", "(", "array", "instanceof", "Int16Array", ")", "{", "return", "{", "float", ":", "false", ",", "signed", ":", "true", ",", "bitDepth", ":", "16", "}", "}", "if", "(", "array", "instanceof", "Uint16Array", ")", "{", "return", "{", "float", ":", "false", ",", "signed", ":", "false", ",", "bitDepth", ":", "16", "}", "}", "if", "(", "array", "instanceof", "Int32Array", ")", "{", "return", "{", "float", ":", "false", ",", "signed", ":", "true", ",", "bitDepth", ":", "32", "}", "}", "if", "(", "array", "instanceof", "Uint32Array", ")", "{", "return", "{", "float", ":", "false", ",", "signed", ":", "false", ",", "bitDepth", ":", "32", "}", "}", "if", "(", "array", "instanceof", "Float32Array", ")", "{", "return", "{", "float", ":", "true", ",", "signed", ":", "false", ",", "bitDepth", ":", "32", "}", "}", "if", "(", "array", "instanceof", "Float64Array", ")", "{", "return", "{", "float", ":", "true", ",", "signed", ":", "false", ",", "bitDepth", ":", "64", "}", "}", "//other dataview types are Uint8Arrays", "return", "{", "float", ":", "false", ",", "signed", ":", "false", ",", "bitDepth", ":", "8", "}", "}" ]
Get format info from the array type
[ "Get", "format", "info", "from", "the", "array", "type" ]
d4e949178e61a2c297d7d38df6da0ee325524e2f
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L359-L423