_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q12600
mapValues
train
function mapValues (obj, mapFn) { return Object.keys(obj).reduce(function (result, key) { result[key] = mapFn(obj[key], key, obj) return result }, {}) }
javascript
{ "resource": "" }
q12601
anyApplies
train
function anyApplies (array, predicate) { for (var i = 0; i < array.length; i++) { if (predicate(array[i])) { return true } } return false }
javascript
{ "resource": "" }
q12602
prepareAndResolveMarkers
train
function prepareAndResolveMarkers (fn, args) { if (markers) { // The Markers-object has already been created for this cycle of the event loop: // Just run the wraped function return fn.apply(this, args) } try { // No Markers yet. This is the initial call or some call that occured during a promise resolution // Create markers, apply the function and resolve placeholders (i.e. promises) created during the // function execution markers = new Markers(engine, options.placeholder) var resultWithPlaceholders = fn.apply(this, args) return markers.resolve(resultWithPlaceholders) } finally { // Reset promises for the next execution run markers = null } }
javascript
{ "resource": "" }
q12603
Markers
train
function Markers (engine, prefix) { /** * This array stores the promises created in the current event-loop cycle * @type {Promise[]} */ this.promiseStore = [] this.engine = engine this.prefix = prefix // one line from substack's quotemeta-package var placeHolderRegexEscaped = String(this.prefix).replace(/(\W)/g, '\\$1') this.regex = new RegExp(placeHolderRegexEscaped + '(\\d+)(>|&gt;)', 'g') }
javascript
{ "resource": "" }
q12604
each
train
function each(collection, fn, scope) { var i = 0, cont; for (i; i < collection.length; i++) { cont = fn.call(scope, collection[i], i); if (cont === false) { break; //allow early exit } } }
javascript
{ "resource": "" }
q12605
train
function(element) { this.columns = null; this.element = element; this.filtered = document.createDocumentFragment(); this.status = false; this.columnClasses = null; }
javascript
{ "resource": "" }
q12606
setStyle
train
function setStyle(element, styleProps, savedStyleProps, propNames) { var style = element.style; (propNames || Object.keys(styleProps)).forEach(function (prop) { if (styleProps[prop] != null) { if (savedStyleProps && savedStyleProps[prop] == null) { savedStyleProps[prop] = style[prop]; } style[prop] = styleProps[prop]; styleProps[prop] = null; } }); return element; }
javascript
{ "resource": "" }
q12607
getDocClientWH
train
function getDocClientWH(props) { var elmTarget = props.elmTarget, width = elmTarget.clientWidth, height = elmTarget.clientHeight; if (IS_TRIDENT || IS_EDGE) { var targetBodyCmpStyle = props.window.getComputedStyle(props.elmTargetBody, ''), wMode = targetBodyCmpStyle.writingMode || targetBodyCmpStyle['writing-mode'], // Trident bug direction = targetBodyCmpStyle.direction; return wMode === 'tb-rl' || wMode === 'bt-rl' || wMode === 'tb-lr' || wMode === 'bt-lr' || IS_EDGE && (direction === 'ltr' && (wMode === 'vertical-rl' || wMode === 'vertical-lr') || direction === 'rtl' && (wMode === 'vertical-rl' || wMode === 'vertical-lr')) ? { width: height, height: width } : // interchange { width: width, height: height }; } return { width: width, height: height }; }
javascript
{ "resource": "" }
q12608
nodeContainsSel
train
function nodeContainsSel(node, selection) { var nodeRange = node.ownerDocument.createRange(), iLen = selection.rangeCount; nodeRange.selectNode(node); for (var i = 0; i < iLen; i++) { var selRange = selection.getRangeAt(i); if (selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 || selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) { return false; } } return true; }
javascript
{ "resource": "" }
q12609
train
function (str) { return _(str).chain() .unescapeHTML() .stripTags() .clean() .value() .replace( matchJunk, '' ) .toLowerCase(); }
javascript
{ "resource": "" }
q12610
selContainsNode
train
function selContainsNode(selection, node, partialContainment) { const nodeRange = node.ownerDocument.createRange(), iLen = selection.rangeCount; nodeRange.selectNodeContents(node); for (let i = 0; i < iLen; i++) { const selRange = selection.getRangeAt(i); // Edge bug (Issue #7321753); getRangeAt returns empty (collapsed) range // NOTE: It can not recover when the selection has multiple ranges. if (!selRange.toString().length && selection.toString().length && iLen === 1) { console.log('Edge bug (Issue #7321753)'); // [DEBUG/] selRange.setStart(selection.anchorNode, selection.anchorOffset); selRange.setEnd(selection.focusNode, selection.focusOffset); // Edge doesn't throw when end is upper than start. if (selRange.toString() !== selection.toString()) { selRange.setStart(selection.focusNode, selection.focusOffset); selRange.setEnd(selection.anchorNode, selection.anchorOffset); if (selRange.toString() !== selection.toString()) { throw new Error('Edge bug (Issue #7321753); Couldn\'t recover'); } } } if (partialContainment ? selRange.compareBoundaryPoints(Range.START_TO_END, nodeRange) >= 0 && selRange.compareBoundaryPoints(Range.END_TO_START, nodeRange) <= 0 : selRange.compareBoundaryPoints(Range.START_TO_START, nodeRange) < 0 && selRange.compareBoundaryPoints(Range.END_TO_END, nodeRange) > 0) { return true; } } return false; }
javascript
{ "resource": "" }
q12611
getMatchingParenthesis
train
function getMatchingParenthesis(string, startPos) { var length = string.length; var bracket = 1; for (var i=startPos+1; i<=length; i++) { if (string[i] == '(') { bracket += 1; } else if (string[i] == ')') { bracket -= 1; } if (bracket == 0) { return i; } } }
javascript
{ "resource": "" }
q12612
train
function (length, options) { length = length || 10 var generateOptions = options || {} generateOptions.digits = generateOptions.hasOwnProperty('digits') ? options.digits : true generateOptions.alphabets = generateOptions.hasOwnProperty('alphabets') ? options.alphabets : true generateOptions.upperCase = generateOptions.hasOwnProperty('upperCase') ? options.upperCase : true generateOptions.specialChars = generateOptions.hasOwnProperty('specialChars') ? options.specialChars : true var allowsChars = ((generateOptions.digits || '') && digits) + ((generateOptions.alphabets || '') && alphabets) + ((generateOptions.upperCase || '') && upperCase) + ((generateOptions.specialChars || '') && specialChars) var password = '' for (var index = 0; index < length; ++index) { var charIndex = rand(0, allowsChars.length - 1) password += allowsChars[charIndex] } return password }
javascript
{ "resource": "" }
q12613
getSelectableElements
train
function getSelectableElements(element) { var out = []; var childs = element.children(); for (var i = 0; i < childs.length; i++) { var child = angular.element(childs[i]); if (child.scope().isSelectable) { out.push(child); } else { if (child.scope().$id!=element.scope().$id && child.scope().isSelectableZone === true) { } else { out = out.concat(getSelectableElements(child)); } } } return out; }
javascript
{ "resource": "" }
q12614
checkElementHitting
train
function checkElementHitting(box1, box2) { return (box2.beginX <= box1.beginX && box1.beginX <= box2.endX || box1.beginX <= box2.beginX && box2.beginX <= box1.endX) && (box2.beginY <= box1.beginY && box1.beginY <= box2.endY || box1.beginY <= box2.beginY && box2.beginY <= box1.endY); }
javascript
{ "resource": "" }
q12615
moveSelectionHelper
train
function moveSelectionHelper(hepler, startX, startY, endX, endY) { var box = transformBox(startX, startY, endX, endY); helper.css({ "top": box.beginY + "px", "left": box.beginX + "px", "width": (box.endX - box.beginX) + "px", "height": (box.endY - box.beginY) + "px" }); }
javascript
{ "resource": "" }
q12616
mousemove
train
function mousemove(event) { // Prevent default dragging of selected content event.preventDefault(); // Move helper moveSelectionHelper(helper, startX, startY, event.pageX, event.pageY); // Check items is selecting var childs = getSelectableElements(element); for (var i = 0; i < childs.length; i++) { if (checkElementHitting(transformBox(offset(childs[i][0]).left, offset(childs[i][0]).top, offset(childs[i][0]).left + childs[i].prop('offsetWidth'), offset(childs[i][0]).top + childs[i].prop('offsetHeight')), transformBox(startX, startY, event.pageX, event.pageY))) { if (childs[i].scope().isSelecting === false) { childs[i].scope().isSelecting = true; childs[i].scope().$apply(); } } else { if (childs[i].scope().isSelecting === true) { childs[i].scope().isSelecting = false; childs[i].scope().$apply(); } } } }
javascript
{ "resource": "" }
q12617
mouseup
train
function mouseup(event) { // Prevent default dragging of selected content event.preventDefault(); // Remove helper helper.remove(); // Change all selecting items to selected var childs = getSelectableElements(element); for (var i = 0; i < childs.length; i++) { if (childs[i].scope().isSelecting === true) { childs[i].scope().isSelecting = false; childs[i].scope().isSelected = event.ctrlKey ? !childs[i].scope().isSelected : true; childs[i].scope().$apply(); } else { if (checkElementHitting(transformBox(childs[i].prop('offsetLeft'), childs[i].prop('offsetTop'), childs[i].prop('offsetLeft') + childs[i].prop('offsetWidth'), childs[i].prop('offsetTop') + childs[i].prop('offsetHeight')), transformBox(event.pageX, event.pageY, event.pageX, event.pageY))) { if (childs[i].scope().isSelected === false) { childs[i].scope().isSelected = true; childs[i].scope().$apply(); } } } } // Remove listeners $document.off('mousemove', mousemove); $document.off('mouseup', mouseup); }
javascript
{ "resource": "" }
q12618
train
function(verb) { var matches = verb.value.match(/^VB[^P\s]+ (\S+)$/); if (matches) { var index = s.indexOf(matches[1]); this._log('Use imperative present tense, eg. "Fix bug" not ' + '"Fixed bug" or "Fixes bug". To get it right ask yourself: "If applied, ' + 'this patch will <YOUR-COMMIT-MESSAGE-HERE>"', cfg.imperativeVerbsInSubject.type, [1, index+1+this._colOffset]); hasError = true; return false; // stop loop } return true; }
javascript
{ "resource": "" }
q12619
animate
train
function animate( dragon, itemElm, destElm, duration ) { duration = duration || 2; let getOffset = dragon.space.utils.getOffset let itemOffset = getOffset( itemElm, true ) let destOffset = getOffset( destElm, true ) let startX = itemOffset.left + ( itemOffset.width / 2 ) let startY = itemOffset.top + ( itemOffset.height / 2 ) let destX = destOffset.left + ( destOffset.width / 2 ) let destY = destOffset.top + ( destOffset.height / 2 ) let distanceX = destX - startX let distanceY = destY - startY let steps = duration * 60 let i = 0 animationRunning = true; let drag = dragon.grab( itemElm ) drag.start( itemOffset.width / 2, itemOffset.height / 2 ) let cb = () => { drag.release(); animationRunning = false; } step( 16 ) function step( time ) { // console.log( 'step', drag.x, drag.y ); if ( i < steps ) { setTimeout( () => { let ease = easeInOutQuadDiff( i++ / steps, i-- / steps ) let ease2 = easeInOutQuartDiff( i++ / steps, i / steps ) // console.log( 'step', distanceX * ease, distanceY * ease2 ) drag.drag( drag.x + distanceX * ease, drag.y + distanceY * ease2 ) step( time ) }, time ) return } else drag.drag( destX, destY ) if ( cb ) setTimeout( cb, 500 ) } }
javascript
{ "resource": "" }
q12620
fft
train
function fft(re, im, inv) { var d, h, ik, m, tmp, wr, wi, xr, xi, n4 = _n >> 2; // bit reversal for(var l=0; l<_n; l++) { m = _bitrev[l]; if(l < m) { tmp = re[l]; re[l] = re[m]; re[m] = tmp; tmp = im[l]; im[l] = im[m]; im[m] = tmp; } } // butterfly operation for(var k=1; k<_n; k<<=1) { h = 0; d = _n/(k << 1); for(var j=0; j<k; j++) { wr = _cstb[h + n4]; wi = inv*_cstb[h]; for(var i=j; i<_n; i+=(k<<1)) { ik = i + k; xr = wr*re[ik] + wi*im[ik]; xi = wr*im[ik] - wi*re[ik]; re[ik] = re[i] - xr; re[i] += xr; im[ik] = im[i] - xi; im[i] += xi; } h += d; } } }
javascript
{ "resource": "" }
q12621
_makeBitReversal
train
function _makeBitReversal() { var i = 0, j = 0, k = 0; _bitrev[0] = 0; while(++i < _n) { k = _n >> 1; while(k <= j) { j -= k; k >>= 1; } j += k; _bitrev[i] = j; } }
javascript
{ "resource": "" }
q12622
_makeCosSinTable
train
function _makeCosSinTable() { var n2 = _n >> 1, n4 = _n >> 2, n8 = _n >> 3, n2p4 = n2 + n4, t = Math.sin(Math.PI/_n), dc = 2*t*t, ds = Math.sqrt(dc*(2 - dc)), c = _cstb[n4] = 1, s = _cstb[0] = 0; t = 2*dc; for(var i=1; i<n8; i++) { c -= dc; dc += t*c; s += ds; ds -= t*s; _cstb[i] = s; _cstb[n4 - i] = c; } if(n8 !== 0) { _cstb[n8] = Math.sqrt(0.5); } for(var j=0; j<n4; j++) { _cstb[n2 - j] = _cstb[j]; } for(var k=0; k<n2p4; k++) { _cstb[k + n2] = -_cstb[k]; } }
javascript
{ "resource": "" }
q12623
train
function (name, imageCount, textCount) { // contains placeholder for optional binding attributes // contains placeholder for each text and image payload var template = '<binding template="' + name + '"%s>'; for (var i = 0; i < imageCount; i++) template += '<image id="' + (i + 1) + '" src="%s" alt="%s"/>'; for (var i = 0; i < textCount; i++) template += '<text id="' + (i + 1) + '">%s</text>'; template += '</binding>'; return template; }
javascript
{ "resource": "" }
q12624
usage
train
function usage (exitCode) { const rs = fs.createReadStream(path.join(__dirname, '/usage.txt')) const ws = process.stdout rs.pipe(ws) ws.on('finish', process.exit.bind(null, exitCode)) }
javascript
{ "resource": "" }
q12625
predict
train
function predict(word, amount) { if (!word) { return []; } amount = amount || this.config.maxAmount; var currentWord = false; var initialBranchResult = this._findInitialBranch(word); if(!initialBranchResult) { return []; } if (initialBranchResult.currentBranch.$ === true) { currentWord = initialBranchResult.baseWord; } var predictedList = this._exploreBranch(initialBranchResult.baseWord, initialBranchResult.currentBranch); if (currentWord) { predictedList.push(currentWord); } predictedList.sort(this.config.sort); return predictedList.slice(0, amount); }
javascript
{ "resource": "" }
q12626
addWord
train
function addWord(word) { var branch = this.root; var stopSearchOnCurrentBranch = false; var newNode; while (!stopSearchOnCurrentBranch) { var wordContainsThePrefix = false; var isCase3 = false; var case2Result; //Looks for how branch it should follow for (var b in branch.branches) { //Case 1: current node prefix == `word` if(this._tryCase1(branch, word, b)) { return; } //Case 2: `word` begins with current node prefix to add //Cuts the word and goes to the next branch case2Result = this._tryCase2(branch, word, b); if(case2Result) { word = case2Result.word; branch = case2Result.branch; wordContainsThePrefix = true; break; } //Case 3: current node prefix begins with part of or whole `word` if(this._tryCase3(branch, word, b)) { isCase3 = stopSearchOnCurrentBranch = wordContainsThePrefix = true; break; } } //Case 4: current node prefix doesn't have intersection with `word` if(this._tryCase4(branch, word, wordContainsThePrefix)) { stopSearchOnCurrentBranch = true; } } }
javascript
{ "resource": "" }
q12627
_exploreBranch
train
function _exploreBranch(baseWord, currentBranch) { var predictedList = []; for (var b in currentBranch.branches) { //For each branch forking from the branch var prefix = currentBranch.branches[b].prefix; //Get the leading character of the current branch if (currentBranch.branches[b].$ === true) { //If the current leaf ends a word, puts the word on the list predictedList.push(baseWord + prefix); } //Recursively calls the function, passing the forking branches as parameter var predictedWords = this._exploreBranch(baseWord + prefix, currentBranch.branches[b]); predictedList = predictedList.concat(predictedWords); } return predictedList; }
javascript
{ "resource": "" }
q12628
_getWordList
train
function _getWordList(_wordList, callback) { if(Array.isArray(_wordList)) { callback(_wordList); } else if ((typeof _wordList) === 'string') { this._fetchWordList(_wordList, callback); } else { console.error((typeof _wordList) + ' variable is not supported as data source'); callback([]); } }
javascript
{ "resource": "" }
q12629
_fetchWordList
train
function _fetchWordList(path, callback) { var words = []; axios.get(path) .then(function(response) { var jsonData = response.data; if(response.responseType === 'text') { jsonData = JSON.parse(jsonData); } if(Array.isArray(jsonData.words)) { words = jsonData.words; } callback(words); }.bind(this)) .catch(function(error) { callback(words); }.bind(this)); }
javascript
{ "resource": "" }
q12630
main
train
function main (options, done) { const token = options.token const filename = options.filename assert.equal(typeof token, 'string', 'markdown-to-medium: token should be a string') const client = new medium.MediumClient({ clientId: token, clientSecret: token }) client.setAccessToken(token) var src try { src = fs.readFileSync(filename, 'utf8') } catch (e) { throw new Error('Could not read file ' + filename) } const matter = frontMatter(src) let title = options.title || matter.attributes.title const tags = (options.tags && options.tags.split(',')) || matter.attributes.tags const publication = options.publication || matter.attributes.publication const canonicalUrl = options.canonicalUrl || matter.attributes.canonicalUrl || '' const license = checkLicense(options.license || matter.attributes.license) var content = ` # ${title} ${matter.body} ` if (!title && getTitle(src)) { title = getTitle(src).text content = matter.body } if (canonicalUrl.length) { content += ` *Cross-posted from [${canonicalUrl}](${canonicalUrl}).* ` } client.getUser((err, user) => { if (err) { throw new Error(err) } console.log(`Authenticated as ${user.username}`.blue) const options = { userId: user.id, title, tags, content, canonicalUrl, license, contentFormat: 'markdown', publishStatus: 'draft' } const successMsg = `Draft post "${title}" published to Medium.com`.green if (publication) { client.getPublicationsForUser({userId: user.id}, (err, publications) => { if (err) { throw new Error(err) } const myPub = publications.filter((val) => { return val.name === publication }) if (myPub.length === 0) { throw new Error('No publication by that name!') } client.createPostInPublication(Object.assign(options, {publicationId: myPub[0].id}), (err, post) => { if (err) { throw new Error(err) } console.log(successMsg) open(post.url) }) }) } else { client.createPost(options, (err, post) => { if (err) { throw new Error(err) } console.log(successMsg) open(post.url) }) } }) }
javascript
{ "resource": "" }
q12631
flag
train
function flag(input) { if (!CODE_RE.test(input) || input === 'UK') { input = nameToCode(input); } return codeToFlag(input); }
javascript
{ "resource": "" }
q12632
name
train
function name(input) { if (FLAG_RE.test(input)) { input = flagToCode(input); } return codeToName(input); }
javascript
{ "resource": "" }
q12633
runScriptFile
train
function runScriptFile(scriptFile) { //node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away! scriptArgs = scriptArgs.slice(scriptArgs.indexOf(scriptFile) + 1); if (shell.verbose()) console.warn("Starting nscript " + scriptFile + scriptArgs.join(" ")); runNscriptFunction(require(path.resolve(process.cwd(), scriptFile))); //nscript scripts should always export a single function that is the main }
javascript
{ "resource": "" }
q12634
initializeMimeticPartial
train
function initializeMimeticPartial( document, getRootREMValue, // CSSUnitsToPixels, setRootFontSize, resizilla, ) { // A resize object to store MIMETIC's resizilla's requirements. const resize = {}; /** * The intializeMimetic function. * @param {object} config - The API parameters. */ function initalizeMimeticFinal(config) { // Destructured API parameters. const { scaleDelay, } = config; // Store the scaleDelay for kill and revive. resize.scaleDelay = scaleDelay; // The intial root font size. const rootFontSize = getRootREMValue(document); // // mobileWidth in pixels. // const mobileWidthPX = CSSUnitsToPixels(mobileWidth); // Cut off width in pixels. // const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth); // Provide parameters to setRootFontSize. @TODO remove config, only use what is needed. const settings = Object.assign({ initialOuterHeight: window.outerHeight, initialOuterWidth: window.outerWidth, rootFontSize, // mobileWidthPX, // cutOffWidthPX, }, config); // Store the settings for kill and revive. resize.settings = settings; // Immediately set the root font size according to MIMETIC. const setRootFontSizeScope = () => setRootFontSize(settings); resize.setRootFontSizeScope = setRootFontSizeScope; setRootFontSizeScope(); // On window resize set the root font size according to MIMETIC. resize.resizilla = resizilla(() => { setRootFontSize(settings, setRootFontSizeScope); }, scaleDelay, false); } /** * Remove both event listeners set via resizilla. */ initalizeMimeticFinal.prototype.kill = () => resize.resizilla.destroy(); /** * Re-instate resizilla. */ initalizeMimeticFinal.prototype.revive = function revive() { resize.resizilla = resizilla(() => { setRootFontSize(resize.settings, resize.setRootFontSizeScope); }, resize.scaleDelay, false); }; return initalizeMimeticFinal; }
javascript
{ "resource": "" }
q12635
initalizeMimeticFinal
train
function initalizeMimeticFinal(config) { // Destructured API parameters. const { scaleDelay, } = config; // Store the scaleDelay for kill and revive. resize.scaleDelay = scaleDelay; // The intial root font size. const rootFontSize = getRootREMValue(document); // // mobileWidth in pixels. // const mobileWidthPX = CSSUnitsToPixels(mobileWidth); // Cut off width in pixels. // const cutOffWidthPX = CSSUnitsToPixels(cutOffWidth); // Provide parameters to setRootFontSize. @TODO remove config, only use what is needed. const settings = Object.assign({ initialOuterHeight: window.outerHeight, initialOuterWidth: window.outerWidth, rootFontSize, // mobileWidthPX, // cutOffWidthPX, }, config); // Store the settings for kill and revive. resize.settings = settings; // Immediately set the root font size according to MIMETIC. const setRootFontSizeScope = () => setRootFontSize(settings); resize.setRootFontSizeScope = setRootFontSizeScope; setRootFontSizeScope(); // On window resize set the root font size according to MIMETIC. resize.resizilla = resizilla(() => { setRootFontSize(settings, setRootFontSizeScope); }, scaleDelay, false); }
javascript
{ "resource": "" }
q12636
RPCserver
train
function RPCserver () { var server if (typeof arguments[0] === 'number') { server = require('http').createServer() server.listen.apply(server, arguments) } else { server = arguments[0] } var io = socketIO(server, arguments[1]) var rpcServer = { io: io.of('/rpc'), /** * @param toExtendWith {Object} */ expose: function (toExtendWith) { if (typeof toExtendWith !== 'object') { throw new TypeError('object expected as first argument') } Object.extend(tree, toExtendWith) }, server: server } var tree = {} rpcServer.io.on('connect', function (socket) { socketEventHandlers(socket, tree, 'server') }) return rpcServer }
javascript
{ "resource": "" }
q12637
checkFilter
train
function checkFilter(filter, type, test, real) { if (type == Table.TYPE_DATETIME) { if (typeof real != 'object') real = new Date(real * 1000); if (filter == Table.FILTER_BETWEEN && Array.isArray(test) && test.length == 2) { test = [ test[0] ? moment.unix(test[0]) : null, test[1] ? moment.unix(test[1]) : null, ]; } else if (filter != Table.FILTER_BETWEEN) { test = moment.unix(test); } else { return null; } } else { if (filter == Table.FILTER_BETWEEN) { if (!Array.isArray(test) || test.length != 2) return null; } } switch (filter) { case Table.FILTER_LIKE: return real !== null && real.indexOf(test) != -1; case Table.FILTER_EQUAL: return real !== null && test == real; case Table.FILTER_BETWEEN: if (real === null) return false; if (test[0] !== null && real < test[0]) return false; if (test[1] !== null && real > test[1]) return false; return true; case Table.FILTER_NULL: return real === null; default: throw new Error("Unknown filter: " + filter); } return false; }
javascript
{ "resource": "" }
q12638
train
function(evt, id, fnc) { var elem = $(id); if (elem.addEventListener) // W3C DOM elem.addEventListener(evt, fnc, false); else if (elem.attachEvent) { // IE DOM elem.attachEvent('on' + evt, fnc); } else { // No much to do elem[evt] = fnc; } }
javascript
{ "resource": "" }
q12639
train
function(evt) { $('output').innerHTML = ''; $('result').innerHTML = ''; oMX.Init(); /* begin with new objects */ fls = []; var cnt = 0; var files = evt.target.files; /* FileList object */ for (var i = 0; i < files.length; i++) { /* loop the selected files */ var reader = new FileReader(); reader.onload = function(file) { fls[cnt + 1] = oMX.AddFile(file) ? true : false; /* get a file */ var c = $('result').innerHTML; if (c !== '') { c += ', '; } $('result').innerHTML = c + fls[cnt]; cnt += 2; }; fls.push(files[i].name, null); reader.readAsText(files[i]); } }
javascript
{ "resource": "" }
q12640
train
function(searchPaths, sourceFoundCallback) { this.sourceFoundCallback = sourceFoundCallback; if(searchPaths) { searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths]; // For windows, convert to forward slashes this.searchPaths = searchPaths.map(path.normalize); } else { this.searchPaths = ['.']; } }
javascript
{ "resource": "" }
q12641
train
function (preserveExistingProperties) { var result = undefined; for (var i = 1; i < arguments.length; i++) { obj = arguments[i]; // set initial result object to the first argument given if (!result) { result = obj; continue; } for (prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { // preserve preexisting child properties if specified if (preserveExistingProperties && Object.prototype.hasOwnProperty.call(result, prop)) { continue; } result[prop] = obj[prop]; } } } return result; }
javascript
{ "resource": "" }
q12642
mergeAst
train
function mergeAst(schemaAst) { var typeDefs = {}; // Go through the AST and extract/merge type definitions. var editedAst = (0, _language.visit)(schemaAst, { enter: function enter(node) { var nodeName = node.name ? node.name.value : null; // Don't transform TypeDefinitions directly if (!nodeName || !node.kind.endsWith('TypeDefinition')) { return; } var oldNode = typeDefs[nodeName]; if (!oldNode) { // First time seeing this type so just store the value. typeDefs[nodeName] = node; return null; } // This type is defined multiple times, so merge the fields and values. var concatProps = ['fields', 'values', 'types']; concatProps.forEach(function (propName) { if (node[propName] && oldNode[propName]) { node[propName] = oldNode[propName].concat(node[propName]); } }); typeDefs[nodeName] = node; return null; } }); var remainingNodesStr = (0, _gqlFormat.formatAst)(editedAst); var typeDefsStr = (0, _values2.default)(typeDefs).map(_gqlFormat.formatAst).join('\n'); var fullSchemaStr = remainingNodesStr + '\n\n' + typeDefsStr; return (0, _gqlFormat.formatString)(fullSchemaStr); }
javascript
{ "resource": "" }
q12643
getRecordingName
train
function getRecordingName(spec, suite) { const descriptions = [spec.description]; while (suite) { suite.description && descriptions.push(suite.description); suite = suite.parentSuite; } return descriptions.reverse().join('/'); }
javascript
{ "resource": "" }
q12644
findSuiteRec
train
function findSuiteRec(suite, findFn) { if (findFn(suite)) return suite; for (const child of suite.children || []) { const result = findSuiteRec(child, findFn); if (result !== null) { return result; } } return null; }
javascript
{ "resource": "" }
q12645
strSplice
train
function strSplice(str, index, count, add) { return str.slice(0, index) + add + str.slice(index + count); }
javascript
{ "resource": "" }
q12646
SchemaDefinition
train
function SchemaDefinition(_ref24) { var directives = _ref24.directives, operationTypes = _ref24.operationTypes; return join(['schema', join(directives, ' '), block(operationTypes)], ' '); }
javascript
{ "resource": "" }
q12647
join
train
function join(maybeArray, separator) { return maybeArray ? maybeArray.filter(function (x) { return x; }).join(separator || '') : ''; }
javascript
{ "resource": "" }
q12648
createResponse
train
function createResponse(xhr, request){ // XHR header processing borrowed from jQuery var responseHeaders = {}, match; while ((match = headersRegex.exec(xhr.getAllResponseHeaders()))) { responseHeaders[match[1].toLowerCase()] = match[2]; } return { statusCode: xhr.status, statusText: xhr.statusText, headers: responseHeaders, originalUrl: request.url, effectiveUrl: request.url, redirected: false, requestMethod: request.method, requestHeaders: request.headers, body: xhr.responseText, retries: 0, throttled: false }; }
javascript
{ "resource": "" }
q12649
train
function(options){ // Set the default options this.appKey = ''; this.environment = 'integration'; this.redirectUri = ''; this.tokenCookie = 'FS_AUTH_TOKEN'; this.maxThrottledRetries = 10; this.saveAccessToken = false; this.accessToken = ''; this.jwt = ''; this.middleware = { request: [ requestMiddleware.url, requestMiddleware.defaultAcceptHeader, requestMiddleware.authorizationHeader, requestMiddleware.disableAutomaticRedirects, requestMiddleware.body ], response: [ responseMiddleware.redirect, responseMiddleware.throttling, responseMiddleware.json ] }; // Process options this.config(options); }
javascript
{ "resource": "" }
q12650
createKey
train
function createKey(factory){ // Create the factory based on the type of object passed. factory = typeof factory == 'function' ? factory : createBound(factory); // Store is used to map public objects to private objects. var store = new WeakMap(); // Seen is used to track existing private objects. var seen = new WeakMap(); /** * An accessor function to get private instances from the store. * @param {Object} key The public object that is associated with a private * object in the store. */ return function(key) { if (typeof key != 'object') return; var value = store.get(key); if (!value) { // Make sure key isn't already the private instance of some existing key. // This check helps prevent accidental double privatizing. if (seen.has(key)) { value = key; } else { value = factory(key); store.set(key, value); seen.set(value, true); } } return value; }; }
javascript
{ "resource": "" }
q12651
makeRequest
train
function makeRequest(){ output('Sending the request...'); var options = { method: $method.value, headers: { Accept: document.getElementById('accept').value }, followRedirect: $followRedirect.checked }; if(options.method === 'POST'){ options.body = $requestBody.value; } client.request($url.value, options, function(error, response){ if(error){ genericError(); } else { displayResponse(response); if(response.statusCode === 401){ $authStatus.classList.remove('loggedin'); $tokenDisplay.value = ''; } else { $authStatus.classList.add('loggedin'); $tokenDisplay.value = 'Bearer ' + client.getAccessToken(); } } }); }
javascript
{ "resource": "" }
q12652
displayResponse
train
function displayResponse(response){ // Gather and display HTTP response data var lines = [ response.statusCode + ' ' + response.statusText, headersToString(response.headers) ]; if(response.data){ lines.push(''); lines.push(prettyPrint(response.data)); } output(lines.join('\n')); // Attach listeners to links so that clicking a link will auto-populate // the url field Array.from($output.querySelectorAll('.link')).forEach(function(link){ link.addEventListener('click', function(){ // Remove leading and trailing " $url.value = link.innerHTML.slice(1,-1); window.scrollTo(0, 0); }); }); }
javascript
{ "resource": "" }
q12653
headersToString
train
function headersToString(headers){ var lines = []; for(var name in headers){ lines.push(name + ': ' + headers[name]); } return lines.join('\n'); }
javascript
{ "resource": "" }
q12654
syntaxHighlight
train
function syntaxHighlight(json) { json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { var cls = 'number', url = false; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key'; } else { cls = 'string'; if(match.indexOf('"https://') === 0){ // url = true; cls += ' link'; } } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } var html = '<span class="' + cls + '">' + match + '</span>'; if(url){ html = '<a href>' + html + '</a>'; } return html; }); }
javascript
{ "resource": "" }
q12655
getScriptFromUrl
train
function getScriptFromUrl(url, eligibleScripts) { var i, script = null; eligibleScripts = eligibleScripts || scripts; if (typeof url === "string" && url) { for (i = eligibleScripts.length; i--; ) { if (eligibleScripts[i].src === url) { // NOTE: Could check if the same script URL is used by more than one `script` element // here... but let's not. That would yield less useful results in "loose" detection. ;) script = eligibleScripts[i]; break; } } } return script; }
javascript
{ "resource": "" }
q12656
getSoleInlineScript
train
function getSoleInlineScript(eligibleScripts) { var i, len, script = null; eligibleScripts = eligibleScripts || scripts; for (i = 0, len = eligibleScripts.length; i < len; i++) { if (!eligibleScripts[i].hasAttribute("src")) { if (script) { script = null; break; } script = eligibleScripts[i]; } } return script; }
javascript
{ "resource": "" }
q12657
getScriptUrlFromStack
train
function getScriptUrlFromStack(stack, skipStackDepth) { var matches, remainingStack, url = null, ignoreMessage = typeof skipStackDepth === "number"; skipStackDepth = ignoreMessage ? Math.round(skipStackDepth) : 0; if (typeof stack === "string" && stack) { if (ignoreMessage) { matches = stack.match(/(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); } else { matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=data:text\/javascript|blob|http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (!(matches && matches[1])) { matches = stack.match(/\)@(data:text\/javascript(?:;[^,]+)?,.+?|(?:|blob:)(?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); } } if (matches && matches[1]) { if (skipStackDepth > 0) { remainingStack = stack.slice(stack.indexOf(matches[0]) + matches[0].length); url = getScriptUrlFromStack(remainingStack, (skipStackDepth - 1)); } else { url = matches[1]; } } // TODO: Handle more edge cases! // Fixes #1 // See https://github.com/JamesMGreene/currentExecutingScript/issues/1 // ??? } return url; }
javascript
{ "resource": "" }
q12658
createResponse
train
function createResponse(request, response, body){ return { statusCode: response.statusCode, statusText: response.statusMessage, headers: response.headers, originalUrl: request.url, effectiveUrl: request.url, redirected: false, requestMethod: request.method, requestHeaders: request.headers, body: body, retries: 0, throttled: false }; }
javascript
{ "resource": "" }
q12659
callback
train
function callback (start, end, props) { if (props === undefined) { props = {}; } key = blockKey + KEY_SEPARATOR + decorationId; decorated[blockKey][decorationId] = props; decorateRange(decorations, start, end, key); decorationId++; }
javascript
{ "resource": "" }
q12660
handleThenable
train
function handleThenable(promise, value) { var done, then; // Attempt to get the `then` method from the thenable (if it is a thenable) try { if (! (then = utils.thenable(value))) { return false; } } catch (err) { rejectPromise(promise, err); return true; } // Ensure that the promise did not attempt to fulfill with itself if (promise === value) { rejectPromise(promise, new TypeError('Circular resolution of promises')); return true; } try { // Wait for the thenable to fulfill/reject before moving on then.call(value, function(subValue) { if (! done) { done = true; // Once again look for circular promise resolution if (value === subValue) { rejectPromise(promise, new TypeError('Circular resolution of promises')); return; } resolvePromise(promise, subValue); } }, function(subValue) { if (! done) { done = true; rejectPromise(promise, subValue); } } ); } catch (err) { if (! done) { done = true; rejectPromise(promise, err); } } return true; }
javascript
{ "resource": "" }
q12661
fulfillPromise
train
function fulfillPromise(promise, value) { if (promise.state !== PENDING) {return;} setValue(promise, value); setState(promise, UNFULFILLED); setImmediate(function() { setState(promise, FULFILLED); invokeFunctions(promise); }); }
javascript
{ "resource": "" }
q12662
rejectPromise
train
function rejectPromise(promise, value) { if (promise.state !== PENDING) {return;} setValue(promise, value); setState(promise, UNFULFILLED); setImmediate(function() { setState(promise, FAILED); invokeFunctions(promise); }); }
javascript
{ "resource": "" }
q12663
setState
train
function setState(promise, state) { utils.defineProperty(promise, 'state', { enumerable: false, // According to the spec: If the state is UNFULFILLED (0), the state can be changed; // If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we // lock the property configurable: (! state), writable: false, value: state }); }
javascript
{ "resource": "" }
q12664
setValue
train
function setValue(promise, value) { utils.defineProperty(promise, 'value', { enumerable: false, configurable: false, writable: false, value: value }); }
javascript
{ "resource": "" }
q12665
invokeFunctions
train
function invokeFunctions(promise) { var funcs = promise.funcs; for (var i = 0, c = funcs.length; i < c; i += 3) { invokeFunction(promise, funcs[i], funcs[i + promise.state]); } // Empty out this list of functions as no one function will be called // more than once, and we don't want to hold them in memory longer than needed promise.funcs.length = 0; }
javascript
{ "resource": "" }
q12666
invokeFunction
train
function invokeFunction(promise, child, func) { var value = promise.value; var state = promise.state; // If we have a function to run, run it if (typeof func === 'function') { try { value = func(value); } catch (err) { rejectPromise(child, err); return; } resolvePromise(child, value); } else if (state === FULFILLED) { resolvePromise(child, value); } else if (state === FAILED) { rejectPromise(child, value); } }
javascript
{ "resource": "" }
q12667
train
function () { // Existing active nodes var allNodes = this.graphRoot.selectAll('g').filter('.active_node') .data(this.nodeModels, function (n) { return n.id; }); return allNodes; }
javascript
{ "resource": "" }
q12668
checkQueue
train
function checkQueue() { if(!inInterval()) { if(requestQueue.length) { var next = requestQueue.shift(); sendRequest(next); } else if(timer) { clearInterval(timer); // No need to leave the timer running if we don't have any requests. } } }
javascript
{ "resource": "" }
q12669
Input
train
function Input(el, validatorsNameOptionsTuples, onInputValidationResult, isBlurOnly) { if (validInputTagNames.indexOf(el.nodeName.toLowerCase()) === -1) { throw 'only operates on the following html tags: ' + validInputTagNames.toString(); } this._el = el; this._validatorsNameOptionsTuples = validatorsNameOptionsTuples; this._onInputValidationResult = onInputValidationResult || defaultOnInputValidationResult; this._isBlurOnly = isBlurOnly; this._validators = buildValidators(); this._inputState = new InputState(); this._elName = el.nodeName.toLowerCase(); this._elType = el.type; this._isKeyed = (this._elName === 'textarea' || keyStrokedInputTypes.indexOf(this._elType) > -1); this._runValidatorsBounded = this._runValidators.bind(this); this._initListeners(); function buildValidators() { var result = []; validatorsNameOptionsTuples.forEach(function(validatorsNameOptionsTuple) { var validatorName = validatorsNameOptionsTuple[0]; var validatorOptions = validatorsNameOptionsTuple[1]; result.push({ name: validatorName, run: validatorRepo.build(validatorName, validatorOptions) }); }); return result; } /** The default {@link _internal.onInputValidationResult onInputValidationResult} used when {@link vivalid.Input} is initiated without a 3rd parameter * @name defaultOnInputValidationResult * @function * @memberof! _internal */ function defaultOnInputValidationResult(el, validationsResult, validatorName, stateEnum) { var errorDiv; // for radio buttons and checkboxes: get the last element in group by name if ((el.nodeName.toLowerCase() === 'input' && (el.type === 'radio' || el.type === 'checkbox'))) { var getAllByName = el.parentNode.querySelectorAll('input[name="' + el.name + '"]'); el = getAllByName.item(getAllByName.length - 1); } if (validationsResult.stateEnum === stateEnum.invalid) { errorDiv = getExistingErrorDiv(el); if (errorDiv) { errorDiv.textContent = validationsResult.message; } else { appendNewErrorDiv(el, validationsResult.message); } el.style.borderStyle = "solid"; el.style.borderColor = "#ff0000"; $$.addClass(el, "vivalid-error-input"); } else { errorDiv = getExistingErrorDiv(el); if (errorDiv) { errorDiv.parentNode.removeChild(errorDiv); el.style.borderStyle = ""; el.style.borderColor = ""; $$.removeClass(el, "vivalid-error-input"); } } function getExistingErrorDiv(el) { if (el.nextElementSibling && el.nextElementSibling.className === "vivalid-error") { return el.nextElementSibling; } } function appendNewErrorDiv(el, message) { errorDiv = document.createElement("DIV"); errorDiv.className = "vivalid-error"; errorDiv.style.color = "#ff0000"; var t = document.createTextNode(validationsResult.message); errorDiv.appendChild(t); el.parentNode.insertBefore(errorDiv, el.nextElementSibling); } } }
javascript
{ "resource": "" }
q12670
selectNextWithWrap
train
function selectNextWithWrap(element) { const items = element.items; if (items && items.length > 0) { if (element.selectedIndex == null || element.selectedIndex === items.length - 1) { element.selectFirst(); } else { element.selectNext(); } } }
javascript
{ "resource": "" }
q12671
printFailureMessages
train
function printFailureMessages(results) { if (!results.numTotalTests || !results.numFailedTests) { return; } console.log(color('bright fail', ` ${symbols.err} Failed Tests:`)); console.log('\n'); results.testResults.forEach(({failureMessage}) => { if (failureMessage) { console.log(failureMessage); } }); process.stdout.write('\n'); }
javascript
{ "resource": "" }
q12672
buildDocsList
train
function buildDocsList() { const packagesWithoutBuiltDocs = [ 'basic-component-mixins', 'basic-web-components' ]; const ary = allPackages.filter(item => { return packagesWithoutBuiltDocs.indexOf(item) < 0; }).map(item => { return { src: `packages/${item}/src/*.js`, dest: `packages/${item}/README.md`}; }); return ary.concat(buildMixinsDocsList()); }
javascript
{ "resource": "" }
q12673
buildMixinsDocsList
train
function buildMixinsDocsList() { return fs.readdirSync('packages/basic-component-mixins/src').filter(file => { return file.indexOf('.js') == file.length - 3; }).map(file => { const fileRoot = file.replace('.js', ''); return { src: `packages/basic-component-mixins/src/${file}`, dest: `packages/basic-component-mixins/docs/${fileRoot}.md` }; }); }
javascript
{ "resource": "" }
q12674
_createElement
train
function _createElement(doc, tagName, options, callConstructor) { const customElements = _customElements(); const element = options ? _origCreateElement.call(doc, tagName, options) : _origCreateElement.call(doc, tagName); const definition = customElements._definitions.get(tagName.toLowerCase()); if (definition) { customElements._upgradeElement(element, definition, callConstructor); } customElements._observeRoot(element); return element; }
javascript
{ "resource": "" }
q12675
dotdir
train
function dotdir(base) { if (base.indexOf('/.') !== -1) { return true; } if (base.charAt(0) === '.' && base.charAt(1) !== '/') { return true; } return false; }
javascript
{ "resource": "" }
q12676
formatAddress
train
function formatAddress(address) { const result = address if (result) { result.formatted = `${result.street_address}\n${result.postal_code} ${result.locality}\n${result.country}` return result } return null }
javascript
{ "resource": "" }
q12677
arrayCopyChildNodes
train
function arrayCopyChildNodes(parent) { var copy=[], i=0; for (var n=parent.firstChild; n; n=n.nextSibling) { copy[i++] = n; } return copy; }
javascript
{ "resource": "" }
q12678
saveChildNodes$1
train
function saveChildNodes$1(node) { if (!this.hasChildNodes(node)) { node.__dom = node.__dom || {}; node.__dom.firstChild = node.firstChild; node.__dom.lastChild = node.lastChild; var c$ = node.__dom.childNodes = tree.arrayCopyChildNodes(node); for (var i=0, n; (i<c$.length) && (n=c$[i]); i++) { n.__dom = n.__dom || {}; n.__dom.parentNode = node; n.__dom.nextSibling = c$[i+1] || null; n.__dom.previousSibling = c$[i-1] || null; common.patchNode(n); } } }
javascript
{ "resource": "" }
q12679
_elementNeedsDistribution
train
function _elementNeedsDistribution(element) { var this$1 = this; var c$ = tree.Logical.getChildNodes(element); for (var i=0, c; i < c$.length; i++) { c = c$[i]; if (this$1._distributor.isInsertionPoint(c)) { return element.getRootNode(); } } }
javascript
{ "resource": "" }
q12680
_composeTree
train
function _composeTree() { var this$1 = this; this._updateChildNodes(this.host, this._composeNode(this.host)); var p$ = this._insertionPoints || []; for (var i=0, l=p$.length, p, parent; (i<l) && (p=p$[i]); i++) { parent = tree.Logical.getParentNode(p); if ((parent !== this$1.host) && (parent !== this$1)) { this$1._updateChildNodes(parent, this$1._composeNode(parent)); } } }
javascript
{ "resource": "" }
q12681
_composeNode
train
function _composeNode(node) { var this$1 = this; var children = []; var c$ = tree.Logical.getChildNodes(node.shadyRoot || node); for (var i = 0; i < c$.length; i++) { var child = c$[i]; if (this$1._distributor.isInsertionPoint(child)) { var distributedNodes = child._distributedNodes || (child._distributedNodes = []); for (var j = 0; j < distributedNodes.length; j++) { var distributedNode = distributedNodes[j]; if (this$1.isFinalDestination(child, distributedNode)) { children.push(distributedNode); } } } else { children.push(child); } } return children; }
javascript
{ "resource": "" }
q12682
_updateChildNodes
train
function _updateChildNodes(container, children) { var composed = tree.Composed.getChildNodes(container); var splices = calculateSplices(children, composed); // process removals for (var i=0, d=0, s; (i<splices.length) && (s=splices[i]); i++) { for (var j=0, n; (j < s.removed.length) && (n=s.removed[j]); j++) { // check if the node is still where we expect it is before trying // to remove it; this can happen if we move a node and // then schedule its previous host for distribution resulting in // the node being removed here. if (tree.Composed.getParentNode(n) === container) { tree.Composed.removeChild(container, n); } composed.splice(s.index + d, 1); } d -= s.addedCount; } // process adds for (var i$1=0, s$1, next; (i$1<splices.length) && (s$1=splices[i$1]); i$1++) { //eslint-disable-line no-redeclare next = composed[s$1.index]; for (var j$1=s$1.index, n$1; j$1 < s$1.index + s$1.addedCount; j$1++) { n$1 = children[j$1]; tree.Composed.insertBefore(container, n$1, next); // TODO(sorvell): is this splice strictly needed? composed.splice(j$1, 0, n$1); } } }
javascript
{ "resource": "" }
q12683
addNode
train
function addNode(container, node, ref_node) { var ownerRoot = this.ownerShadyRootForNode(container); if (ownerRoot) { // optimization: special insertion point tracking if (node.__noInsertionPoint && ownerRoot._clean) { ownerRoot._skipUpdateInsertionPoints = true; } // note: we always need to see if an insertion point is added // since this saves logical tree info; however, invalidation state // needs var ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot); // invalidate insertion points IFF not already invalid! if (ipAdded) { ownerRoot._skipUpdateInsertionPoints = false; } } if (tree.Logical.hasChildNodes(container)) { tree.Logical.recordInsertBefore(node, container, ref_node); } // if not distributing and not adding to host, do a fast path addition var handled = this._maybeDistribute(node, container, ownerRoot) || container.shadyRoot; return handled; }
javascript
{ "resource": "" }
q12684
removeChild
train
function removeChild(node) { if (tree.Logical.getParentNode(node) !== this) { throw Error('The node to be removed is not a child of this node: ' + node); } if (!mixinImpl.removeNode(node)) { // if removing from a shadyRoot, remove form host instead var container = isShadyRoot(this) ? this.host : this; // not guaranteed to physically be in container; e.g. // undistributed nodes. var parent = tree.Composed.getParentNode(node); if (container === parent) { tree.Composed.removeChild(container, node); } } mixinImpl._scheduleObserver(this, null, node); return node; }
javascript
{ "resource": "" }
q12685
get_jwt_token
train
function get_jwt_token(ctx) { // Parses "Authorization: Bearer ${token}" if (ctx.header.authorization) { const match = ctx.header.authorization.match(/^Bearer (.+)$/i) if (match) { return match[1] } } // (doesn't read cookies anymore to protect users from CSRF attacks) // // Tries the "authentication" cookie // if (ctx.cookies.get('authentication')) // { // return ctx.cookies.get('authentication') // } }
javascript
{ "resource": "" }
q12686
authenticate
train
async function authenticate({ options, keys, log }) { // A little helper which can be called from routes // as `ctx.role('administrator')` // which will throw if the user isn't administrator. // The `roles` are taken from JWT payload. this.role = (...roles) => { if (!this.user) { throw new errors.Unauthenticated() } for (const role of roles) { for (const user_role of this.user.roles) { if (user_role === role) { return true } } } throw new errors.Unauthorized(`One of the following roles is required: ${roles}`) } // Get JWT token from incoming HTTP request let token = get_jwt_token(this) // If no JWT token was found, then done if (!token) { return } // JWT token (is now accessible from Koa's `ctx`) this.accessToken = token // Verify JWT token integrity // by checking its signature using the supplied `keys` let payload for (const secret of keys) { try { payload = jwt.verify(token, secret) break } catch (error) { // If authentication token expired if (error.name === 'TokenExpiredError') { if (options.refreshAccessToken) { // If refreshing an access token fails // then don't prevent the user from at least seeing a page // therefore catching an error here. try { token = await options.refreshAccessToken(this) } catch (error) { log.error(error) } if (token) { for (const secret of keys) { try { payload = jwt.verify(token, secret) break } catch (error) { // Try another `secret` if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature') { continue } // Some other non-JWT-related error log.error(error) break } } } } if (payload) { break } throw new errors.Access_token_expired() } // Try another `secret` if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature') { continue } // Some other non-JWT-related error. // Shouldn't prevent the user from at least seeing a page // therefore not rethrowing this error. log.error(error) break } } // If JWT token signature was unable to be verified, then exit if (!payload) { return } // If the access token isn't valid for access to this server // (e.g. it's a "refresh token") then exit. if (options.validateAccessToken) { if (!options.validateAccessToken(payload, this)) { return } } // Token payload can be accessed through `ctx` this.accessTokenPayload = payload // Fire "on user request" hook if (options.onUserRequest) { options.onUserRequest(token, this) } // JWT token ID const jwt_id = payload.jti // `subject` // (which is a user id) const user_id = payload.sub // // Optional JWT token validation (by id) // // (for example, that it has not been revoked) // if (validateToken) // { // // Can validate the token via a request to a database, for example. // // Checks for `valid` property value inside the result object. // // (There can possibly be other properties such as `reason`) // const is_valid = (await validateToken(token, this)).valid // // // If the JWT token happens to be invalid // // (expired or revoked, for example), then exit. // if (!is_valid) // { // // this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked') // return // } // } // JWT token ID is now accessible via Koa's `ctx` this.accessTokenId = jwt_id // Extracts user data (description) from JWT token payload // (`user` is now accessible via Koa's `ctx`) this.user = options.userInfo ? options.userInfo(payload) : {} // Sets user id this.user.id = user_id // Extra payload fields: // // 'iss' // Issuer // 'sub' // Subject // 'aud' // Audience // 'exp' // Expiration time // 'nbf' // Not before // 'iat' // Issued at // 'jti' // JWT ID // JWT token payload is accessible via Koa's `ctx` this.accessTokenPayload = payload }
javascript
{ "resource": "" }
q12687
setMinimumHeight
train
function setMinimumHeight(element) { const copyContainer = element.$.copyContainer; const outerHeight = copyContainer.getBoundingClientRect().height; const style = getComputedStyle(copyContainer); const paddingTop = parseFloat(style.paddingTop); const paddingBottom = parseFloat(style.paddingBottom); const innerHeight = copyContainer.clientHeight - paddingTop - paddingBottom; const bordersPlusPadding = outerHeight - innerHeight; let minHeight = (element.minimumRows * element[lineHeightSymbol]) + bordersPlusPadding; minHeight = Math.ceil(minHeight); copyContainer.style.minHeight = minHeight + 'px'; }
javascript
{ "resource": "" }
q12688
extractRgbValues
train
function extractRgbValues(rgbString) { const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/; const match = rgbRegex.exec(rgbString); if (match) { return { r: parseInt(match[1]), g: parseInt(match[2]), b: parseInt(match[3]) }; } else { return null; } }
javascript
{ "resource": "" }
q12689
filterAuxiliaryElements
train
function filterAuxiliaryElements(items) { const auxiliaryTags = [ 'link', 'script', 'style', 'template' ]; return [].filter.call(items, function(item) { return !item.localName || auxiliaryTags.indexOf(item.localName) < 0; }); }
javascript
{ "resource": "" }
q12690
setAttributeToElement
train
function setAttributeToElement(element, attributeName, value) { if (value === null || typeof value === 'undefined') { element.removeAttribute(attributeName); } else { const text = String(value); // Avoid recursive attributeChangedCallback calls. if (element.getAttribute(attributeName) !== text) { element.setAttribute(attributeName, value); } } }
javascript
{ "resource": "" }
q12691
renderArrayAsElements
train
function renderArrayAsElements(items, container, renderItem) { // Create a new set of elements for the current items. items.forEach((item, index) => { const oldElement = container.childNodes[index]; const newElement = renderItem(item, oldElement); if (newElement) { if (!oldElement) { container.appendChild(newElement); } else if (newElement !== oldElement) { container.replaceChild(newElement, oldElement); } } }); // If the array shrank, remove the extra elements which are no longer needed. while (container.childNodes.length > items.length) { container.removeChild(container.childNodes[items.length]); } }
javascript
{ "resource": "" }
q12692
upload_file
train
async function upload_file(file, { upload_folder, log }) { if (log) { log.debug(`Uploading: ${file.filename}`) } // Generate random unique filename const file_name = await generate_unique_filename(upload_folder, { on_collision: (file_name) => { log.info(`Generate unique file name: collision for "${file_name}". Taking another try.`) } }) // dot_extension: path.extname(file.filename) const output_file = path.join(upload_folder, file_name) // Write the file to disk return await new Promise((resolve, reject) => { // Ensure the `upload_folder` exists // (just an extra precaution) fs.ensureDir(upload_folder, (error) => { if (error) { return reject(error) } // Open output file stream const stream = fs.createWriteStream(output_file) // Pipe file contents to disk file.pipe(stream) .on('finish', () => resolve(path.relative(upload_folder, output_file))) .on('error', error => reject(error)) }) }) }
javascript
{ "resource": "" }
q12693
assertNative
train
function assertNative(element, property, tracked) { let native = getNativeProperty(element, property); if (native != tracked && element.__patched) { window.console.warn('tracked', tracked, 'native', native); } return tracked; }
javascript
{ "resource": "" }
q12694
build
train
function build(validatorName, validatorOptions) { if (typeof validatorBuildersRepository[validatorName] !== 'function') { throw validatorName + ' does not exists. use addValidatorBuilder to add a new validation rule'; } return validatorBuildersRepository[validatorName](ValidationState, stateEnum, validatorOptions); }
javascript
{ "resource": "" }
q12695
addCallback
train
function addCallback(name, fn) { if (typeof fn !== 'function') throw 'error while trying to add a custom callback: argument must be a function'; if (callbacks[name]) throw 'error while trying to add a custom callback: ' + name + ' already exists'; callbacks[name] = fn; }
javascript
{ "resource": "" }
q12696
initGroup
train
function initGroup(groupElem) { $$.ready(registerGroupFromDataAttribtues); function registerGroupFromDataAttribtues() { inputElems = $$.getElementsByTagNames(validInputTagNames, groupElem) .filter(function(el) { return $$.hasDataSet(el, 'vivalidTuples'); }); var vivalidGroup = createGroupFromDataAttribtues(groupElem, inputElems); addToGroupNameDictionairy(groupElem, vivalidGroup); } }
javascript
{ "resource": "" }
q12697
initAll
train
function initAll() { $$.ready(registerAllFromDataAttribtues); function registerAllFromDataAttribtues() { var _nextGroupId = 1; // es6 map would have been nice here, but this lib is intended to run on es5 browsers. integrating Babel might work. var groupIdToInputs = {}; var groupIdToGroup = {}; $$.getElementsByTagNames(validInputTagNames) .filter(function(el) { return $$.hasDataSet(el, 'vivalidTuples'); }) .forEach(function(el) { addGroupInputs($$.getClosestParentByAttribute(el, 'vivalidGroup'), el); }); for (var groupId in groupIdToInputs) { var vivalidGroup = createGroupFromDataAttribtues(groupIdToGroup[groupId], groupIdToInputs[groupId]); addToGroupNameDictionairy(groupIdToGroup[groupId], vivalidGroup); } function addGroupInputs(group, input) { if (!group) { throw 'an input validation is missing a group, input id: ' + input.id; } if (!group._groupId) group._groupId = _nextGroupId++; if (!groupIdToInputs[group._groupId]) { groupIdToInputs[group._groupId] = []; groupIdToGroup[group._groupId] = group; } groupIdToInputs[group._groupId].push(input); } } }
javascript
{ "resource": "" }
q12698
resetGroup
train
function resetGroup(groupName) { var vivalidGroup = groupNameToVivalidGroup[groupName]; if (vivalidGroup) { vivalidGroup.reset(); } else { console.log('could not find group named ' + groupName); } }
javascript
{ "resource": "" }
q12699
getIndexOfItemWithTextPrefix
train
function getIndexOfItemWithTextPrefix(element, prefix) { const itemTextContents = getItemTextContents(element); const prefixLength = prefix.length; for (let i = 0; i < itemTextContents.length; i++) { const itemTextContent = itemTextContents[i]; if (itemTextContent.substr(0, prefixLength) === prefix) { return i; } } return -1; }
javascript
{ "resource": "" }