_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q18200
report
train
function report(node) { const parent = node.parent; const locationNode = node.type === "MemberExpression" ? node.property : node; const reportNode = parent.type === "CallExpression" && parent.callee === node ? parent : node; context.report({ node: reportNode, loc: locationNode.loc.start, messageId: "unexpected" }); }
javascript
{ "resource": "" }
q18201
reportAccessingEvalViaGlobalObject
train
function reportAccessingEvalViaGlobalObject(globalScope) { for (let i = 0; i < candidatesOfGlobalObject.length; ++i) { const name = candidatesOfGlobalObject[i]; const variable = astUtils.getVariableByName(globalScope, name); if (!variable) { continue; } const references = variable.references; for (let j = 0; j < references.length; ++j) { const identifier = references[j].identifier; let node = identifier.parent; // To detect code like `window.window.eval`. while (isMember(node, name)) { node = node.parent; } // Reports. if (isMember(node, "eval")) { report(node); } } } }
javascript
{ "resource": "" }
q18202
getShorthandName
train
function getShorthandName(fullname, prefix) { if (fullname[0] === "@") { let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname); if (matchResult) { return matchResult[1]; } matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname); if (matchResult) { return `${matchResult[1]}/${matchResult[2]}`; } } else if (fullname.startsWith(`${prefix}-`)) { return fullname.slice(prefix.length + 1); } return fullname; }
javascript
{ "resource": "" }
q18203
isStringContained
train
function isStringContained(compare, compareWith) { const curatedCompareWith = curateString(compareWith); const curatedCompare = curateString(compare); if (!curatedCompareWith || !curatedCompare) { return false; } return curatedCompareWith.includes(curatedCompare); }
javascript
{ "resource": "" }
q18204
curateString
train
function curateString(str) { const noUnicodeStr = text.removeUnicode(str, { emoji: true, nonBmp: true, punctuations: true }); return text.sanitize(noUnicodeStr); }
javascript
{ "resource": "" }
q18205
findTextMethods
train
function findTextMethods(virtualNode) { const { nativeElementType, nativeTextMethods } = text; const nativeType = nativeElementType.find(({ matches }) => { return axe.commons.matches(virtualNode, matches); }); // Use concat because namingMethods can be a string or an array of strings const methods = nativeType ? [].concat(nativeType.namingMethods) : []; return methods.map(methodName => nativeTextMethods[methodName]); }
javascript
{ "resource": "" }
q18206
shouldMatchElement
train
function shouldMatchElement(el) { if (!el) { return true; } if (el.getAttribute('aria-hidden') === 'true') { return false; } return shouldMatchElement(getComposedParent(el)); }
javascript
{ "resource": "" }
q18207
getAttributeNameValue
train
function getAttributeNameValue(node, at) { const name = at.name; let atnv; if (name.indexOf('href') !== -1 || name.indexOf('src') !== -1) { let friendly = axe.utils.getFriendlyUriEnd(node.getAttribute(name)); if (friendly) { let value = encodeURI(friendly); if (value) { atnv = escapeSelector(at.name) + '$="' + escapeSelector(value) + '"'; } else { return; } } else { atnv = escapeSelector(at.name) + '="' + escapeSelector(node.getAttribute(name)) + '"'; } } else { atnv = escapeSelector(name) + '="' + escapeSelector(at.value) + '"'; } return atnv; }
javascript
{ "resource": "" }
q18208
filterAttributes
train
function filterAttributes(at) { return ( !ignoredAttributes.includes(at.name) && at.name.indexOf(':') === -1 && (!at.value || at.value.length < MAXATTRIBUTELENGTH) ); }
javascript
{ "resource": "" }
q18209
uncommonClasses
train
function uncommonClasses(node, selectorData) { // eslint no-loop-func:false let retVal = []; let classData = selectorData.classes; let tagData = selectorData.tags; if (node.classList) { Array.from(node.classList).forEach(cl => { let ind = escapeSelector(cl); if (classData[ind] < tagData[node.nodeName]) { retVal.push({ name: ind, count: classData[ind], species: 'class' }); } }); } return retVal.sort(countSort); }
javascript
{ "resource": "" }
q18210
getElmId
train
function getElmId(elm) { if (!elm.getAttribute('id')) { return; } let doc = (elm.getRootNode && elm.getRootNode()) || document; const id = '#' + escapeSelector(elm.getAttribute('id') || ''); if ( // Don't include youtube's uid values, they change on reload !id.match(/player_uid_/) && // Don't include IDs that occur more then once on the page doc.querySelectorAll(id).length === 1 ) { return id; } }
javascript
{ "resource": "" }
q18211
getBaseSelector
train
function getBaseSelector(elm) { if (typeof isXHTML === 'undefined') { isXHTML = axe.utils.isXHTML(document); } return escapeSelector(isXHTML ? elm.localName : elm.nodeName.toLowerCase()); }
javascript
{ "resource": "" }
q18212
uncommonAttributes
train
function uncommonAttributes(node, selectorData) { let retVal = []; let attData = selectorData.attributes; let tagData = selectorData.tags; if (node.hasAttributes()) { Array.from(axe.utils.getNodeAttributes(node)) .filter(filterAttributes) .forEach(at => { const atnv = getAttributeNameValue(node, at); if (atnv && attData[atnv] < tagData[node.nodeName]) { retVal.push({ name: atnv, count: attData[atnv], species: 'attribute' }); } }); } return retVal.sort(countSort); }
javascript
{ "resource": "" }
q18213
generateSelector
train
function generateSelector(elm, options, doc) { /*eslint no-loop-func:0*/ if (!axe._selectorData) { throw new Error('Expect axe._selectorData to be set up'); } const { toRoot = false } = options; let selector; let similar; /** * Try to find a unique selector by filtering out all the clashing * nodes by adding ancestor selectors iteratively. * This loop is much faster than recursing and using querySelectorAll */ do { let features = getElmId(elm); if (!features) { features = getThreeLeastCommonFeatures(elm, axe._selectorData); features += getNthChildString(elm, features); } if (selector) { selector = features + ' > ' + selector; } else { selector = features; } if (!similar) { similar = Array.from(doc.querySelectorAll(selector)); } else { similar = similar.filter(item => { return axe.utils.matchesSelector(item, selector); }); } elm = elm.parentElement; } while ((similar.length > 1 || toRoot) && elm && elm.nodeType !== 11); if (similar.length === 1) { return selector; } else if (selector.indexOf(' > ') !== -1) { // For the odd case that document doesn't have a unique selector return ':root' + selector.substring(selector.indexOf(' > ')); } return ':root'; }
javascript
{ "resource": "" }
q18214
matchTags
train
function matchTags(rule, runOnly) { 'use strict'; var include, exclude, matching; var defaultExclude = axe._audit && axe._audit.tagExclude ? axe._audit.tagExclude : []; // normalize include/exclude if (runOnly.hasOwnProperty('include') || runOnly.hasOwnProperty('exclude')) { // Wrap include and exclude if it's not already an array include = runOnly.include || []; include = Array.isArray(include) ? include : [include]; exclude = runOnly.exclude || []; exclude = Array.isArray(exclude) ? exclude : [exclude]; // add defaults, unless mentioned in include exclude = exclude.concat( defaultExclude.filter(function(tag) { return include.indexOf(tag) === -1; }) ); // Otherwise, only use the include value, ignore exclude } else { include = Array.isArray(runOnly) ? runOnly : [runOnly]; // exclude the defaults not included exclude = defaultExclude.filter(function(tag) { return include.indexOf(tag) === -1; }); } matching = include.some(function(tag) { return rule.tags.indexOf(tag) !== -1; }); if (matching || (include.length === 0 && rule.enabled !== false)) { return exclude.every(function(tag) { return rule.tags.indexOf(tag) === -1; }); } else { return false; } }
javascript
{ "resource": "" }
q18215
getDeepest
train
function getDeepest(collection) { 'use strict'; return collection.sort(function(a, b) { if (axe.utils.contains(a, b)) { return 1; } return -1; })[0]; }
javascript
{ "resource": "" }
q18216
isNodeInContext
train
function isNodeInContext(node, context) { 'use strict'; var include = context.include && getDeepest( context.include.filter(function(candidate) { return axe.utils.contains(candidate, node); }) ); var exclude = context.exclude && getDeepest( context.exclude.filter(function(candidate) { return axe.utils.contains(candidate, node); }) ); if ( (!exclude && include) || (exclude && axe.utils.contains(exclude, include)) ) { return true; } return false; }
javascript
{ "resource": "" }
q18217
pushNode
train
function pushNode(result, nodes) { 'use strict'; var temp; if (result.length === 0) { return nodes; } if (result.length < nodes.length) { // switch so the comparison is shortest temp = result; result = nodes; nodes = temp; } for (var i = 0, l = nodes.length; i < l; i++) { if (!result.includes(nodes[i])) { result.push(nodes[i]); } } return result; }
javascript
{ "resource": "" }
q18218
reduceIncludes
train
function reduceIncludes(includes) { return includes.reduce((res, el) => { if ( !res.length || !res[res.length - 1].actualNode.contains(el.actualNode) ) { res.push(el); } return res; }, []); }
javascript
{ "resource": "" }
q18219
getExplicitLabels
train
function getExplicitLabels({ actualNode }) { if (!actualNode.id) { return []; } return dom.findElmsInContext({ elm: 'label', attr: 'for', value: actualNode.id, context: actualNode }); }
javascript
{ "resource": "" }
q18220
sortPageBackground
train
function sortPageBackground(elmStack) { let bodyIndex = elmStack.indexOf(document.body); let bgNodes = elmStack; if ( // Check that the body background is the page's background bodyIndex > 1 && // only if there are negative z-index elements !color.elementHasImage(document.documentElement) && color.getOwnBackgroundColor( window.getComputedStyle(document.documentElement) ).alpha === 0 ) { // Remove body and html from it's current place bgNodes.splice(bodyIndex, 1); bgNodes.splice(elmStack.indexOf(document.documentElement), 1); // Put the body background as the lowest element bgNodes.push(document.body); } return bgNodes; }
javascript
{ "resource": "" }
q18221
elmPartiallyObscured
train
function elmPartiallyObscured(elm, bgElm, bgColor) { var obscured = elm !== bgElm && !dom.visuallyContains(elm, bgElm) && bgColor.alpha !== 0; if (obscured) { axe.commons.color.incompleteData.set('bgColor', 'elmPartiallyObscured'); } return obscured; }
javascript
{ "resource": "" }
q18222
calculateObscuringAlpha
train
function calculateObscuringAlpha(elmIndex, elmStack, originalElm) { var totalAlpha = 0; if (elmIndex > 0) { // there are elements above our element, check if they contribute to the background for (var i = elmIndex - 1; i >= 0; i--) { let bgElm = elmStack[i]; let bgElmStyle = window.getComputedStyle(bgElm); let bgColor = color.getOwnBackgroundColor(bgElmStyle); if (bgColor.alpha && contentOverlapping(originalElm, bgElm)) { totalAlpha += bgColor.alpha; } else { // remove elements not contributing to the background elmStack.splice(i, 1); } } } return totalAlpha; }
javascript
{ "resource": "" }
q18223
contentOverlapping
train
function contentOverlapping(targetElement, bgNode) { // get content box of target element // check to see if the current bgNode is overlapping var targetRect = targetElement.getClientRects()[0]; var obscuringElements = dom.shadowElementsFromPoint( targetRect.left, targetRect.top ); if (obscuringElements) { for (var i = 0; i < obscuringElements.length; i++) { if ( obscuringElements[i] !== targetElement && obscuringElements[i] === bgNode ) { return true; } } } return false; }
javascript
{ "resource": "" }
q18224
train
function(key, reason) { if (typeof key !== 'string') { throw new Error('Incomplete data: key must be a string'); } if (reason) { data[key] = reason; } return data[key]; }
javascript
{ "resource": "" }
q18225
nativeSelectValue
train
function nativeSelectValue(node) { node = node.actualNode || node; if (node.nodeName.toUpperCase() !== 'SELECT') { return ''; } return ( Array.from(node.options) .filter(option => option.selected) .map(option => option.text) .join(' ') || '' ); }
javascript
{ "resource": "" }
q18226
ariaTextboxValue
train
function ariaTextboxValue(virtualNode) { const { actualNode } = virtualNode; const role = aria.getRole(actualNode); if (role !== 'textbox') { return ''; } if (!dom.isHiddenWithCSS(actualNode)) { return text.visibleVirtual(virtualNode, true); } else { return actualNode.textContent; } }
javascript
{ "resource": "" }
q18227
ariaRangeValue
train
function ariaRangeValue(node) { node = node.actualNode || node; const role = aria.getRole(node); if (!rangeRoles.includes(role) || !node.hasAttribute('aria-valuenow')) { return ''; } // Validate the number, if not, return 0. // Chrome 70 typecasts this, Firefox 62 does not const valueNow = +node.getAttribute('aria-valuenow'); return !isNaN(valueNow) ? String(valueNow) : '0'; }
javascript
{ "resource": "" }
q18228
train
function(e) { err = e; setTimeout(function() { if (err !== undefined && err !== null) { axe.log('Uncaught error (of queue)', err); } }, 1); }
javascript
{ "resource": "" }
q18229
train
function(fn) { if (typeof fn === 'object' && fn.then && fn.catch) { var defer = fn; fn = function(resolve, reject) { defer.then(resolve).catch(reject); }; } funcGuard(fn); if (err !== undefined) { return; } else if (complete) { throw new Error('Queue already completed'); } tasks.push(fn); ++remaining; pop(); return q; }
javascript
{ "resource": "" }
q18230
train
function(fn) { funcGuard(fn); if (completeQueue !== noop) { throw new Error('queue `then` already set'); } if (!err) { completeQueue = fn; if (!remaining) { complete = true; completeQueue(tasks); } } return q; }
javascript
{ "resource": "" }
q18231
getAriaQueryAttributes
train
function getAriaQueryAttributes() { const ariaKeys = Array.from(props).map(([key]) => key); const roleAriaKeys = Array.from(roles).reduce((out, [name, rule]) => { return [...out, ...Object.keys(rule.props)]; }, []); return new Set(axe.utils.uniqueArray(roleAriaKeys, ariaKeys)); }
javascript
{ "resource": "" }
q18232
getDiff
train
function getDiff(base, subject, type) { const diff = []; const notes = []; const sortedBase = Array.from(base.entries()).sort(); sortedBase.forEach(([key] = item) => { switch (type) { case 'supported': if ( subject.hasOwnProperty(key) && subject[key].unsupported === false ) { diff.push([`${key}`, 'Yes']); } break; case 'unsupported': if ( (subject[key] && subject[key].unsupported === true) || !subject.hasOwnProperty(key) ) { diff.push([`${key}`, 'No']); } else if ( subject[key] && subject[key].unsupported && subject[key].unsupported.exceptions ) { diff.push([`${key}`, `Mixed[^${notes.length + 1}]`]); notes.push( getSupportedElementsAsFootnote( subject[key].unsupported.exceptions ) ); } break; case 'all': default: diff.push([ `${key}`, subject.hasOwnProperty(key) && subject[key].unsupported === false ? 'Yes' : 'No' ]); break; } }); return { diff, notes }; }
javascript
{ "resource": "" }
q18233
getSupportedElementsAsFootnote
train
function getSupportedElementsAsFootnote(elements) { const notes = []; const supportedElements = elements.map(element => { if (typeof element === 'string') { return `\`<${element}>\``; } /** * if element is not a string it will be an object with structure: { nodeName: string, properties: { type: {string|string[]} } } */ return Object.keys(element.properties).map(prop => { const value = element.properties[prop]; // the 'type' property can be a string or an array if (typeof value === 'string') { return `\`<${element.nodeName} ${prop}="${value}">\``; } // output format for an array of types: // <input type="button" | "checkbox"> const values = value.map(v => `"${v}"`).join(' | '); return `\`<${element.nodeName} ${prop}=${values}>\``; }); }); notes.push('Supported on elements: ' + supportedElements.join(', ')); return notes; }
javascript
{ "resource": "" }
q18234
shouldIgnoreHidden
train
function shouldIgnoreHidden({ actualNode }, context) { if ( // If the parent isn't ignored, the text node should not be either actualNode.nodeType !== 1 || // If the target of aria-labelledby is hidden, ignore all descendents context.includeHidden ) { return false; } return !dom.isVisible(actualNode, true); }
javascript
{ "resource": "" }
q18235
prepareContext
train
function prepareContext(virtualNode, context) { const { actualNode } = virtualNode; if (!context.startNode) { context = { startNode: virtualNode, ...context }; } /** * When `aria-labelledby` directly references a `hidden` element * the element needs to be included in the accessible name. * * When a descendent of the `aria-labelledby` reference is `hidden` * the element should not be included in the accessible name. * * This is done by setting `includeHidden` for the `aria-labelledby` reference. */ if ( actualNode.nodeType === 1 && context.inLabelledByContext && context.includeHidden === undefined ) { context = { includeHidden: !dom.isVisible(actualNode, true), ...context }; } return context; }
javascript
{ "resource": "" }
q18236
findAfterChecks
train
function findAfterChecks(rule) { 'use strict'; return axe.utils .getAllChecks(rule) .map(function(c) { var check = rule._audit.checks[c.id || c]; return check && typeof check.after === 'function' ? check : null; }) .filter(Boolean); }
javascript
{ "resource": "" }
q18237
findCheckResults
train
function findCheckResults(nodes, checkID) { 'use strict'; var checkResults = []; nodes.forEach(function(nodeResult) { var checks = axe.utils.getAllChecks(nodeResult); checks.forEach(function(checkResult) { if (checkResult.id === checkID) { checkResults.push(checkResult); } }); }); return checkResults; }
javascript
{ "resource": "" }
q18238
getScroll
train
function getScroll(elm) { const style = window.getComputedStyle(elm); const visibleOverflowY = style.getPropertyValue('overflow-y') === 'visible'; const visibleOverflowX = style.getPropertyValue('overflow-x') === 'visible'; if ( // See if the element hides overflowing content (!visibleOverflowY && elm.scrollHeight > elm.clientHeight) || (!visibleOverflowX && elm.scrollWidth > elm.clientWidth) ) { return { elm, top: elm.scrollTop, left: elm.scrollLeft }; } }
javascript
{ "resource": "" }
q18239
setScroll
train
function setScroll(elm, top, left) { if (elm === window) { return elm.scroll(left, top); } else { elm.scrollTop = top; elm.scrollLeft = left; } }
javascript
{ "resource": "" }
q18240
getElmScrollRecursive
train
function getElmScrollRecursive(root) { return Array.from(root.children).reduce((scrolls, elm) => { const scroll = getScroll(elm); if (scroll) { scrolls.push(scroll); } return scrolls.concat(getElmScrollRecursive(elm)); }, []); }
javascript
{ "resource": "" }
q18241
pushFrame
train
function pushFrame(resultSet, options, frameElement, frameSelector) { 'use strict'; var frameXpath = axe.utils.getXpath(frameElement); var frameSpec = { element: frameElement, selector: frameSelector, xpath: frameXpath }; resultSet.forEach(function(res) { res.node = axe.utils.DqElement.fromFrame(res.node, options, frameSpec); var checks = axe.utils.getAllChecks(res); if (checks.length) { checks.forEach(function(check) { check.relatedNodes = check.relatedNodes.map(node => axe.utils.DqElement.fromFrame(node, options, frameSpec) ); }); } }); }
javascript
{ "resource": "" }
q18242
spliceNodes
train
function spliceNodes(target, to) { 'use strict'; var firstFromFrame = to[0].node, sorterResult, t; for (var i = 0, l = target.length; i < l; i++) { t = target[i].node; sorterResult = axe.utils.nodeSorter( { actualNode: t.element }, { actualNode: firstFromFrame.element } ); if ( sorterResult > 0 || (sorterResult === 0 && firstFromFrame.selector.length < t.selector.length) ) { target.splice.apply(target, [i, 0].concat(to)); return; } } target.push.apply(target, to); }
javascript
{ "resource": "" }
q18243
isRegion
train
function isRegion(virtualNode) { const node = virtualNode.actualNode; const explicitRole = axe.commons.aria.getRole(node, { noImplicit: true }); const ariaLive = (node.getAttribute('aria-live') || '').toLowerCase().trim(); if (explicitRole) { return explicitRole === 'dialog' || landmarkRoles.includes(explicitRole); } // Ignore content inside of aria-live if (['assertive', 'polite'].includes(ariaLive)) { return true; } // Check if the node matches any of the CSS selectors of implicit landmarks return implicitLandmarks.some(implicitSelector => { let matches = axe.utils.matchesSelector(node, implicitSelector); if (node.nodeName.toUpperCase() === 'FORM') { let titleAttr = node.getAttribute('title'); let title = titleAttr && titleAttr.trim() !== '' ? axe.commons.text.sanitize(titleAttr) : null; return matches && (!!aria.labelVirtual(virtualNode) || !!title); } return matches; }); }
javascript
{ "resource": "" }
q18244
findRegionlessElms
train
function findRegionlessElms(virtualNode) { const node = virtualNode.actualNode; // End recursion if the element is a landmark, skiplink, or hidden content if ( isRegion(virtualNode) || (dom.isSkipLink(virtualNode.actualNode) && dom.getElementByReference(virtualNode.actualNode, 'href')) || !dom.isVisible(node, true) ) { return []; // Return the node is a content element } else if (dom.hasContent(node, /* noRecursion: */ true)) { return [node]; // Recursively look at all child elements } else { return virtualNode.children .filter(({ actualNode }) => actualNode.nodeType === 1) .map(findRegionlessElms) .reduce((a, b) => a.concat(b), []); // flatten the results } }
javascript
{ "resource": "" }
q18245
_getSource
train
function _getSource() { var application = 'axeAPI', version = '', src; if (typeof axe !== 'undefined' && axe._audit && axe._audit.application) { application = axe._audit.application; } if (typeof axe !== 'undefined') { version = axe.version; } src = application + '.' + version; return src; }
javascript
{ "resource": "" }
q18246
verify
train
function verify(postedMessage) { if ( // Check incoming message is valid typeof postedMessage === 'object' && typeof postedMessage.uuid === 'string' && postedMessage._respondable === true ) { var messageSource = _getSource(); return ( // Check the version matches postedMessage._source === messageSource || // Allow free communication with axe test postedMessage._source === 'axeAPI.x.y.z' || messageSource === 'axeAPI.x.y.z' ); } return false; }
javascript
{ "resource": "" }
q18247
post
train
function post(win, topic, message, uuid, keepalive, callback) { var error; if (message instanceof Error) { error = { name: message.name, message: message.message, stack: message.stack }; message = undefined; } var data = { uuid: uuid, topic: topic, message: message, error: error, _respondable: true, _source: _getSource(), _keepalive: keepalive }; if (typeof callback === 'function') { messages[uuid] = callback; } win.postMessage(JSON.stringify(data), '*'); }
javascript
{ "resource": "" }
q18248
respondable
train
function respondable(win, topic, message, keepalive, callback) { var id = uuid.v1(); post(win, topic, message, id, keepalive, callback); }
javascript
{ "resource": "" }
q18249
createResponder
train
function createResponder(source, topic, uuid) { return function(message, keepalive, callback) { post(source, topic, message, uuid, keepalive, callback); }; }
javascript
{ "resource": "" }
q18250
publish
train
function publish(source, data, keepalive) { var topic = data.topic; var subscriber = subscribers[topic]; if (subscriber) { var responder = createResponder(source, null, data.uuid); subscriber(data.message, keepalive, responder); } }
javascript
{ "resource": "" }
q18251
buildErrorObject
train
function buildErrorObject(error) { var msg = error.message || 'Unknown error occurred'; var errorName = errorTypes.includes(error.name) ? error.name : 'Error'; var ErrConstructor = window[errorName] || Error; if (error.stack) { msg += '\n' + error.stack.replace(error.message, ''); } return new ErrConstructor(msg); }
javascript
{ "resource": "" }
q18252
parseMessage
train
function parseMessage(dataString) { /*eslint no-empty: 0*/ var data; if (typeof dataString !== 'string') { return; } try { data = JSON.parse(dataString); } catch (ex) {} if (!verify(data)) { return; } if (typeof data.error === 'object') { data.error = buildErrorObject(data.error); } else { data.error = undefined; } return data; }
javascript
{ "resource": "" }
q18253
getAllRootNodesInTree
train
function getAllRootNodesInTree(tree) { let ids = []; const rootNodes = axe.utils .querySelectorAllFilter(tree, '*', node => { if (ids.includes(node.shadowId)) { return false; } ids.push(node.shadowId); return true; }) .map(node => { return { shadowId: node.shadowId, rootNode: axe.utils.getRootNode(node.actualNode) }; }); return axe.utils.uniqueArray(rootNodes, []); }
javascript
{ "resource": "" }
q18254
getCssomForAllRootNodes
train
function getCssomForAllRootNodes(rootNodes, convertDataToStylesheet, timeout) { const q = axe.utils.queue(); rootNodes.forEach(({ rootNode, shadowId }, index) => q.defer((resolve, reject) => loadCssom({ rootNode, shadowId, timeout, convertDataToStylesheet, rootIndex: index + 1 }) .then(resolve) .catch(reject) ) ); return q; }
javascript
{ "resource": "" }
q18255
parseNonCrossOriginStylesheet
train
function parseNonCrossOriginStylesheet(sheet, options, priority) { const q = axe.utils.queue(); /** * `sheet.cssRules` throws an error on `cross-origin` stylesheets */ const cssRules = sheet.cssRules; const rules = Array.from(cssRules); if (!rules) { return q; } /** * reference -> https://developer.mozilla.org/en-US/docs/Web/API/CSSRule#Type_constants */ const cssImportRules = rules.filter(r => r.type === 3); // type === 3 -> CSSRule.IMPORT_RULE /** * when no `@import` rules in given sheet * -> resolve the current `sheet` & exit */ if (!cssImportRules.length) { q.defer(resolve => resolve({ isExternal: false, priority, root: options.rootNode, shadowId: options.shadowId, sheet }) ); // exit return q; } /** * iterate `@import` rules and fetch styles */ cssImportRules.forEach((importRule, cssRuleIndex) => q.defer((resolve, reject) => { const importUrl = importRule.href; const newPriority = [...priority, cssRuleIndex]; const axiosOptions = { method: 'get', url: importUrl, timeout: options.timeout }; axe.imports .axios(axiosOptions) .then(({ data }) => resolve( options.convertDataToStylesheet({ data, isExternal: true, priority: newPriority, root: options.rootNode, shadowId: options.shadowId }) ) ) .catch(reject); }) ); const nonImportCSSRules = rules.filter(r => r.type !== 3); // no further rules to process in this sheet if (!nonImportCSSRules.length) { return q; } // convert all `nonImportCSSRules` style rules into `text` and defer into queue q.defer(resolve => resolve( options.convertDataToStylesheet({ data: nonImportCSSRules.map(rule => rule.cssText).join(), isExternal: false, priority, root: options.rootNode, shadowId: options.shadowId }) ) ); return q; }
javascript
{ "resource": "" }
q18256
parseCrossOriginStylesheet
train
function parseCrossOriginStylesheet(url, options, priority) { const q = axe.utils.queue(); if (!url) { return q; } const axiosOptions = { method: 'get', url, timeout: options.timeout }; q.defer((resolve, reject) => { axe.imports .axios(axiosOptions) .then(({ data }) => resolve( options.convertDataToStylesheet({ data, isExternal: true, priority, root: options.rootNode, shadowId: options.shadowId }) ) ) .catch(reject); }); return q; }
javascript
{ "resource": "" }
q18257
getStylesheetsFromDocumentFragment
train
function getStylesheetsFromDocumentFragment(options) { const { rootNode, convertDataToStylesheet } = options; return ( Array.from(rootNode.children) .filter(filerStyleAndLinkAttributesInDocumentFragment) // Reducer to convert `<style></style>` and `<link>` references to `CSSStyleSheet` object .reduce((out, node) => { const nodeName = node.nodeName.toUpperCase(); const data = nodeName === 'STYLE' ? node.textContent : node; const isLink = nodeName === 'LINK'; const stylesheet = convertDataToStylesheet({ data, isLink, root: rootNode }); out.push(stylesheet.sheet); return out; }, []) ); }
javascript
{ "resource": "" }
q18258
getStylesheetsFromDocument
train
function getStylesheetsFromDocument(rootNode) { return Array.from(rootNode.styleSheets).filter(sheet => filterMediaIsPrint(sheet.media.mediaText) ); }
javascript
{ "resource": "" }
q18259
filterStylesheetsWithSameHref
train
function filterStylesheetsWithSameHref(sheets) { let hrefs = []; return sheets.filter(sheet => { if (!sheet.href) { // include sheets without `href` return true; } // if `href` is present, ensure they are not duplicates if (hrefs.includes(sheet.href)) { return false; } hrefs.push(sheet.href); return true; }); }
javascript
{ "resource": "" }
q18260
runSample
train
async function runSample() { const res = await youtube.search.list({ part: 'id,snippet', q: 'Node.js on Google Cloud', }); console.log(res.data); }
javascript
{ "resource": "" }
q18261
runSample
train
async function runSample(fileName) { const fileSize = fs.statSync(fileName).size; const res = await youtube.videos.insert( { part: 'id,snippet,status', notifySubscribers: false, requestBody: { snippet: { title: 'Node.js YouTube Upload Test', description: 'Testing YouTube upload via Google APIs Node.js Client', }, status: { privacyStatus: 'private', }, }, media: { body: fs.createReadStream(fileName), }, }, { // Use the `onUploadProgress` event from Axios to track the // number of bytes uploaded to this point. onUploadProgress: evt => { const progress = (evt.bytesRead / fileSize) * 100; readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0, null); process.stdout.write(`${Math.round(progress)}% complete`); }, } ); console.log('\n\n'); console.log(res.data); return res.data; }
javascript
{ "resource": "" }
q18262
runSample
train
async function runSample() { // the first query will return data with an etag const res = await getPlaylistData(null); const etag = res.data.etag; console.log(`etag: ${etag}`); // the second query will (likely) return no data, and an HTTP 304 // since the If-None-Match header was set with a matching eTag const res2 = await getPlaylistData(etag); console.log(res2.status); }
javascript
{ "resource": "" }
q18263
runSample
train
async function runSample() { const res = await mirror.locations.list({}); console.log(res.data); }
javascript
{ "resource": "" }
q18264
runSample
train
async function runSample() { // Create a new JWT client using the key file downloaded from the Google Developer Console const client = await google.auth.getClient({ keyFile: path.join(__dirname, 'jwt.keys.json'), scopes: 'https://www.googleapis.com/auth/drive.readonly', }); // Obtain a new drive client, making sure you pass along the auth client const drive = google.drive({ version: 'v2', auth: client, }); // Make an authorized request to list Drive files. const res = await drive.files.list(); console.log(res.data); return res.data; }
javascript
{ "resource": "" }
q18265
main
train
async function main() { // The `getClient` method will choose a service based authentication model const auth = await google.auth.getClient({ // Scopes can be specified either as an array or as a single, space-delimited string. scopes: ['https://www.googleapis.com/auth/compute'], }); // Obtain the current project Id const project = await google.auth.getProjectId(); // Get the list of available compute zones for your project const res = await compute.zones.list({project, auth}); console.log(res.data); }
javascript
{ "resource": "" }
q18266
train
function(tag, attrs, children){ var el = document.createElement(tag); if(attrs != null && typeof attrs === typeof {}){ Object.keys(attrs).forEach(function(key){ var val = attrs[key]; el.setAttribute(key, val); }); } else if(typeof attrs === typeof []){ children = attrs; } if(children != null && typeof children === typeof []){ children.forEach(function(child){ el.appendChild(child); }); } else if(children != null && typeof children === typeof ''){ el.appendChild(document.createTextNode(children)); } return el; }
javascript
{ "resource": "" }
q18267
train
function( options ){ this.options = options; registrant.call( this, options ); // make sure layout has _private for use w/ std apis like .on() if( !is.plainObject( this._private ) ){ this._private = {}; } this._private.cy = options.cy; this._private.listeners = []; this.createEmitter(); }
javascript
{ "resource": "" }
q18268
memoize
train
function memoize(fn, keyFn) { if (!keyFn) { keyFn = function keyFn() { if (arguments.length === 1) { return arguments[0]; } else if (arguments.length === 0) { return 'undefined'; } var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } return args.join('$'); }; } var memoizedFn = function memoizedFn() { var self = this; var args = arguments; var ret; var k = keyFn.apply(self, args); var cache = memoizedFn.cache; if (!(ret = cache[k])) { ret = cache[k] = fn.apply(self, args); } return ret; }; memoizedFn.cache = {}; return memoizedFn; }
javascript
{ "resource": "" }
q18269
getMap
train
function getMap(options) { var obj = options.map; var keys = options.keys; var l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (plainObject(key)) { throw Error('Tried to get map with object key'); } obj = obj[key]; if (obj == null) { return obj; } } return obj; }
javascript
{ "resource": "" }
q18270
contractUntil
train
function contractUntil(metaNodeMap, remainingEdges, size, sizeLimit) { while (size > sizeLimit) { // Choose an edge randomly var edgeIndex = Math.floor(Math.random() * remainingEdges.length); // Collapse graph based on edge remainingEdges = collapse(edgeIndex, metaNodeMap, remainingEdges); size--; } return remainingEdges; }
javascript
{ "resource": "" }
q18271
removeData
train
function removeData(params) { var defaults$$1 = { field: 'data', event: 'data', triggerFnName: 'trigger', triggerEvent: false, immutableKeys: {} // key => true if immutable }; params = extend({}, defaults$$1, params); return function removeDataImpl(names) { var p = params; var self = this; var selfIsArrayLike = self.length !== undefined; var all = selfIsArrayLike ? self : [self]; // put in array if not array-like // .removeData('foo bar') if (string(names)) { // then get the list of keys, and delete them var keys = names.split(/\s+/); var l = keys.length; for (var i = 0; i < l; i++) { // delete each non-empty key var key = keys[i]; if (emptyString(key)) { continue; } var valid = !p.immutableKeys[key]; // not valid if immutable if (valid) { for (var i_a = 0, l_a = all.length; i_a < l_a; i_a++) { all[i_a]._private[p.field][key] = undefined; } } } if (p.triggerEvent) { self[p.triggerFnName](p.event); } // .removeData() } else if (names === undefined) { // then delete all keys for (var _i_a = 0, _l_a = all.length; _i_a < _l_a; _i_a++) { var _privateFields = all[_i_a]._private[p.field]; var _keys = Object.keys(_privateFields); for (var _i2 = 0; _i2 < _keys.length; _i2++) { var _key = _keys[_i2]; var validKeyToDelete = !p.immutableKeys[_key]; if (validKeyToDelete) { _privateFields[_key] = undefined; } } } if (p.triggerEvent) { self[p.triggerFnName](p.event); } } return self; // maintain chaining }; // function }
javascript
{ "resource": "" }
q18272
consumeExpr
train
function consumeExpr(remaining) { var expr; var match; var name; for (var j = 0; j < exprs.length; j++) { var e = exprs[j]; var n = e.name; var m = remaining.match(e.regexObj); if (m != null) { match = m; expr = e; name = n; var consumed = m[0]; remaining = remaining.substring(consumed.length); break; // we've consumed one expr, so we can return now } } return { expr: expr, match: match, name: name, remaining: remaining }; }
javascript
{ "resource": "" }
q18273
consumeWhitespace
train
function consumeWhitespace(remaining) { var match = remaining.match(/^\s+/); if (match) { var consumed = match[0]; remaining = remaining.substring(consumed.length); } return remaining; }
javascript
{ "resource": "" }
q18274
parse
train
function parse(selector) { var self = this; var remaining = self.inputText = selector; var currentQuery = self[0] = newQuery(); self.length = 1; remaining = consumeWhitespace(remaining); // get rid of leading whitespace for (;;) { var exprInfo = consumeExpr(remaining); if (exprInfo.expr == null) { warn('The selector `' + selector + '`is invalid'); return false; } else { var args = exprInfo.match.slice(1); // let the token populate the selector object in currentQuery var ret = exprInfo.expr.populate(self, currentQuery, args); if (ret === false) { return false; // exit if population failed } else if (ret != null) { currentQuery = ret; // change the current query to be filled if the expr specifies } } remaining = exprInfo.remaining; // we're done when there's nothing left to parse if (remaining.match(/^\s*$/)) { break; } } var lastQ = self[self.length - 1]; if (self.currentSubject != null) { lastQ.subject = self.currentSubject; } lastQ.edgeCount = self.edgeCount; lastQ.compoundCount = self.compoundCount; for (var i = 0; i < self.length; i++) { var q = self[i]; // in future, this could potentially be allowed if there were operator precedence and detection of invalid combinations if (q.compoundCount > 0 && q.edgeCount > 0) { warn('The selector `' + selector + '` is invalid because it uses both a compound selector and an edge selector'); return false; } if (q.edgeCount > 1) { warn('The selector `' + selector + '` is invalid because it uses multiple edge selectors'); return false; } else if (q.edgeCount === 1) { warn('The selector `' + selector + '` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.'); } } return true; // success }
javascript
{ "resource": "" }
q18275
matches
train
function matches(query, ele) { return query.checks.every(function (chk) { return match[chk.type](chk, ele); }); }
javascript
{ "resource": "" }
q18276
matches$$1
train
function matches$$1(ele) { var self = this; for (var j = 0; j < self.length; j++) { var query = self[j]; if (matches(query, ele)) { return true; } } return false; }
javascript
{ "resource": "" }
q18277
byGroup
train
function byGroup() { var nodes = this.spawn(); var edges = this.spawn(); for (var i = 0; i < this.length; i++) { var ele = this[i]; if (ele.isNode()) { nodes.merge(ele); } else { edges.merge(ele); } } return { nodes: nodes, edges: edges }; }
javascript
{ "resource": "" }
q18278
merge
train
function merge(toAdd) { var _p = this._private; var cy = _p.cy; if (!toAdd) { return this; } if (toAdd && string(toAdd)) { var selector = toAdd; toAdd = cy.mutableElements().filter(selector); } var map = _p.map; for (var i = 0; i < toAdd.length; i++) { var toAddEle = toAdd[i]; var id = toAddEle._private.data.id; var add = !map.has(id); if (add) { var index = this.length++; this[index] = toAddEle; map.set(id, { ele: toAddEle, index: index }); } else { // replace var _index = map.get(id).index; this[_index] = toAddEle; map.set(id, { ele: toAddEle, index: _index }); } } return this; // chaining }
javascript
{ "resource": "" }
q18279
unmergeOne
train
function unmergeOne(ele) { ele = ele[0]; var _p = this._private; var id = ele._private.data.id; var map = _p.map; var entry = map.get(id); if (!entry) { return this; // no need to remove } var i = entry.index; this.unmergeAt(i); return this; }
javascript
{ "resource": "" }
q18280
unmerge
train
function unmerge(toRemove) { var cy = this._private.cy; if (!toRemove) { return this; } if (toRemove && string(toRemove)) { var selector = toRemove; toRemove = cy.mutableElements().filter(selector); } for (var i = 0; i < toRemove.length; i++) { this.unmergeOne(toRemove[i]); } return this; // chaining }
javascript
{ "resource": "" }
q18281
addConnectedEdges
train
function addConnectedEdges(node) { var edges = node._private.edges; for (var i = 0; i < edges.length; i++) { add(edges[i]); } }
javascript
{ "resource": "" }
q18282
addChildren
train
function addChildren(node) { var children = node._private.children; for (var i = 0; i < children.length; i++) { add(children[i]); } }
javascript
{ "resource": "" }
q18283
spring
train
function spring(tension, friction, duration) { if (duration === 0) { // can't get a spring w/ duration 0 return easings.linear; // duration 0 => jump to end so impl doesn't matter } var spring = generateSpringRK4(tension, friction, duration); return function (start, end, percent) { return start + (end - start) * spring(percent); }; }
javascript
{ "resource": "" }
q18284
batchData
train
function batchData(map) { var cy = this; return this.batch(function () { var ids = Object.keys(map); for (var i = 0; i < ids.length; i++) { var id = ids[i]; var data = map[id]; var ele = cy.getElementById(id); ele.data(data); } }); }
javascript
{ "resource": "" }
q18285
sortFn
train
function sortFn(a, b) { var apct = getWeightedPercent(a); var bpct = getWeightedPercent(b); var diff = apct - bpct; if (diff === 0) { return ascending(a.id(), b.id()); // make sure sort doesn't have don't-care comparisons } else { return diff; } }
javascript
{ "resource": "" }
q18286
addNodesToDrag
train
function addNodesToDrag(nodes, opts) { opts = opts || {}; var hasCompoundNodes = nodes.cy().hasCompoundNodes(); if (opts.inDragLayer) { nodes.forEach(setInDragLayer); nodes.neighborhood().stdFilter(function (ele) { return !hasCompoundNodes || ele.isEdge(); }).forEach(setInDragLayer); } if (opts.addToList) { nodes.forEach(function (ele) { addToDragList(ele, opts); }); } addDescendantsToDrag(nodes, opts); // always add to drag // also add nodes and edges related to the topmost ancestor updateAncestorsInDragLayer(nodes, { inDragLayer: opts.inDragLayer }); r.updateCachedGrabbedEles(); }
javascript
{ "resource": "" }
q18287
setupShapeColor
train
function setupShapeColor() { var bgOpy = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : bgOpacity; r.eleFillStyle(context, node, bgOpy); }
javascript
{ "resource": "" }
q18288
convert
train
function convert( name, _path, contents ) { var rDefine = /(define\s*\(\s*('|").*?\2\s*,\s*\[)([\s\S]*?)\]/ig, rDeps = /('|")(.*?)\1/g, root = _path.substr( 0, _path.length - name.length - 3 ), dir = path.dirname( _path ), m, m2, deps, dep, _path2; contents = contents.replace( rDefine, function( m, m1, m2, m3 ) { return m1 + m3.replace( rDeps, function( m, m1, m2 ) { m2 = path.join( dir, m2 ); m2 = path.relative( root, m2 ); m2 = m2.replace(/\\/g, '/'); return m1 + m2 + m1; }) + ']'; }); return contents; }
javascript
{ "resource": "" }
q18289
detectSubsampling
train
function detectSubsampling( img ) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas, ctx; // subsampling may happen overmegapixel image if ( iw * ih > 1024 * 1024 ) { canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; ctx = canvas.getContext('2d'); ctx.drawImage( img, -iw + 1, 0 ); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering // edge pixel or not. if alpha value is 0 // image is not covering, hence subsampled. return ctx.getImageData( 0, 0, 1, 1 ).data[ 3 ] === 0; } else { return false; } }
javascript
{ "resource": "" }
q18290
nextSortDir
train
function nextSortDir(sortType, current) { if (sortType === types_1.SortType.single) { if (current === types_1.SortDirection.asc) { return types_1.SortDirection.desc; } else { return types_1.SortDirection.asc; } } else { if (!current) { return types_1.SortDirection.asc; } else if (current === types_1.SortDirection.asc) { return types_1.SortDirection.desc; } else if (current === types_1.SortDirection.desc) { return undefined; } // avoid TS7030: Not all code paths return a value. return undefined; } }
javascript
{ "resource": "" }
q18291
sortRows
train
function sortRows(rows, columns, dirs) { if (!rows) return []; if (!dirs || !dirs.length || !columns) return rows.slice(); /** * record the row ordering of results from prior sort operations (if applicable) * this is necessary to guarantee stable sorting behavior */ var rowToIndexMap = new Map(); rows.forEach(function (row, index) { return rowToIndexMap.set(row, index); }); var temp = rows.slice(); var cols = columns.reduce(function (obj, col) { if (col.comparator && typeof col.comparator === 'function') { obj[col.prop] = col.comparator; } return obj; }, {}); // cache valueGetter and compareFn so that they // do not need to be looked-up in the sort function body var cachedDirs = dirs.map(function (dir) { var prop = dir.prop; return { prop: prop, dir: dir.dir, valueGetter: column_prop_getters_1.getterForProp(prop), compareFn: cols[prop] || orderByComparator }; }); return temp.sort(function (rowA, rowB) { for (var _i = 0, cachedDirs_1 = cachedDirs; _i < cachedDirs_1.length; _i++) { var cachedDir = cachedDirs_1[_i]; // Get property and valuegetters for column to be sorted var prop = cachedDir.prop, valueGetter = cachedDir.valueGetter; // Get A and B cell values from rows based on properties of the columns var propA = valueGetter(rowA, prop); var propB = valueGetter(rowB, prop); // Compare function gets five parameters: // Two cell values to be compared as propA and propB // Two rows corresponding to the cells as rowA and rowB // Direction of the sort for this column as SortDirection // Compare can be a standard JS comparison function (a,b) => -1|0|1 // as additional parameters are silently ignored. The whole row and sort // direction enable more complex sort logic. var comparison = cachedDir.dir !== types_1.SortDirection.desc ? cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir) : -cachedDir.compareFn(propA, propB, rowA, rowB, cachedDir.dir); // Don't return 0 yet in case of needing to sort by next property if (comparison !== 0) return comparison; } if (!(rowToIndexMap.has(rowA) && rowToIndexMap.has(rowB))) return 0; /** * all else being equal, preserve original order of the rows (stable sort) */ return rowToIndexMap.get(rowA) < rowToIndexMap.get(rowB) ? -1 : 1; }); }
javascript
{ "resource": "" }
q18292
columnsByPin
train
function columnsByPin(cols) { var ret = { left: [], center: [], right: [] }; if (cols) { for (var _i = 0, cols_1 = cols; _i < cols_1.length; _i++) { var col = cols_1[_i]; if (col.frozenLeft) { ret.left.push(col); } else if (col.frozenRight) { ret.right.push(col); } else { ret.center.push(col); } } } return ret; }
javascript
{ "resource": "" }
q18293
columnGroupWidths
train
function columnGroupWidths(groups, all) { return { left: columnTotalWidth(groups.left), center: columnTotalWidth(groups.center), right: columnTotalWidth(groups.right), total: Math.floor(columnTotalWidth(all)) }; }
javascript
{ "resource": "" }
q18294
getTotalFlexGrow
train
function getTotalFlexGrow(columns) { var totalFlexGrow = 0; for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) { var c = columns_1[_i]; totalFlexGrow += c.flexGrow || 0; } return totalFlexGrow; }
javascript
{ "resource": "" }
q18295
scaleColumns
train
function scaleColumns(colsByGroup, maxWidth, totalFlexGrow) { // calculate total width and flexgrow points for coulumns that can be resized for (var attr in colsByGroup) { for (var _i = 0, _a = colsByGroup[attr]; _i < _a.length; _i++) { var column = _a[_i]; if (!column.canAutoResize) { maxWidth -= column.width; totalFlexGrow -= column.flexGrow ? column.flexGrow : 0; } else { column.width = 0; } } } var hasMinWidth = {}; var remainingWidth = maxWidth; // resize columns until no width is left to be distributed do { var widthPerFlexPoint = remainingWidth / totalFlexGrow; remainingWidth = 0; for (var attr in colsByGroup) { for (var _b = 0, _c = colsByGroup[attr]; _b < _c.length; _b++) { var column = _c[_b]; // if the column can be resize and it hasn't reached its minimum width yet if (column.canAutoResize && !hasMinWidth[column.prop]) { var newWidth = column.width + column.flexGrow * widthPerFlexPoint; if (column.minWidth !== undefined && newWidth < column.minWidth) { remainingWidth += newWidth - column.minWidth; column.width = column.minWidth; hasMinWidth[column.prop] = true; } else { column.width = newWidth; } } } } } while (remainingWidth !== 0); }
javascript
{ "resource": "" }
q18296
forceFillColumnWidths
train
function forceFillColumnWidths(allColumns, expectedWidth, startIdx, allowBleed, defaultColWidth) { if (defaultColWidth === void 0) { defaultColWidth = 300; } var columnsToResize = allColumns .slice(startIdx + 1, allColumns.length) .filter(function (c) { return c.canAutoResize !== false; }); for (var _i = 0, columnsToResize_1 = columnsToResize; _i < columnsToResize_1.length; _i++) { var column = columnsToResize_1[_i]; if (!column.$$oldWidth) { column.$$oldWidth = column.width; } } var additionWidthPerColumn = 0; var exceedsWindow = false; var contentWidth = getContentWidth(allColumns, defaultColWidth); var remainingWidth = expectedWidth - contentWidth; var columnsProcessed = []; // This loop takes care of the do { additionWidthPerColumn = remainingWidth / columnsToResize.length; exceedsWindow = contentWidth >= expectedWidth; for (var _a = 0, columnsToResize_2 = columnsToResize; _a < columnsToResize_2.length; _a++) { var column = columnsToResize_2[_a]; if (exceedsWindow && allowBleed) { column.width = column.$$oldWidth || column.width || defaultColWidth; } else { var newSize = (column.width || defaultColWidth) + additionWidthPerColumn; if (column.minWidth && newSize < column.minWidth) { column.width = column.minWidth; columnsProcessed.push(column); } else if (column.maxWidth && newSize > column.maxWidth) { column.width = column.maxWidth; columnsProcessed.push(column); } else { column.width = newSize; } } column.width = Math.max(0, column.width); } contentWidth = getContentWidth(allColumns); remainingWidth = expectedWidth - contentWidth; removeProcessedColumns(columnsToResize, columnsProcessed); } while (remainingWidth > 0 && columnsToResize.length !== 0); }
javascript
{ "resource": "" }
q18297
removeProcessedColumns
train
function removeProcessedColumns(columnsToResize, columnsProcessed) { for (var _i = 0, columnsProcessed_1 = columnsProcessed; _i < columnsProcessed_1.length; _i++) { var column = columnsProcessed_1[_i]; var index = columnsToResize.indexOf(column); columnsToResize.splice(index, 1); } }
javascript
{ "resource": "" }
q18298
getContentWidth
train
function getContentWidth(allColumns, defaultColWidth) { if (defaultColWidth === void 0) { defaultColWidth = 300; } var contentWidth = 0; for (var _i = 0, allColumns_1 = allColumns; _i < allColumns_1.length; _i++) { var column = allColumns_1[_i]; contentWidth += (column.width || defaultColWidth); } return contentWidth; }
javascript
{ "resource": "" }
q18299
groupRowsByParents
train
function groupRowsByParents(rows, from, to) { if (from && to) { var nodeById = {}; var l = rows.length; var node = null; nodeById[0] = new TreeNode(); // that's the root node var uniqIDs = rows.reduce(function (arr, item) { var toValue = to(item); if (arr.indexOf(toValue) === -1) { arr.push(toValue); } return arr; }, []); for (var i = 0; i < l; i++) { // make TreeNode objects for each item nodeById[to(rows[i])] = new TreeNode(rows[i]); } for (var i = 0; i < l; i++) { // link all TreeNode objects node = nodeById[to(rows[i])]; var parent_1 = 0; var fromValue = from(node.row); if (!!fromValue && (uniqIDs.indexOf(fromValue) > -1)) { parent_1 = fromValue; } node.parent = nodeById[parent_1]; node.row['level'] = node.parent.row['level'] + 1; node.parent.children.push(node); } var resolvedRows_1 = []; nodeById[0].flatten(function () { resolvedRows_1 = resolvedRows_1.concat([this.row]); }, true); return resolvedRows_1; } else { return rows; } }
javascript
{ "resource": "" }