_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49500
train
function(libraries) { var deferred = null, promiseWrapper = null, $ = null; promiseWrapper = new this.Deferred(); if (mixitup.features.has.promises) { // ES6 native promise or polyfill promiseWrapper.promise = new Promise(function(resolve, reject) { promiseWrapper.resolve = resolve; promiseWrapper.reject = reject; }); } else if (($ = (window.jQuery || libraries.$)) && typeof $.Deferred === 'function') { // jQuery deferred = $.Deferred(); promiseWrapper.promise = deferred.promise(); promiseWrapper.resolve = deferred.resolve; promiseWrapper.reject = deferred.reject; } else if (window.console) { // No implementation console.warn(mixitup.messages.warningNoPromiseImplementation()); } return promiseWrapper; }
javascript
{ "resource": "" }
q49501
train
function(obj, stringKey) { var parts = stringKey.split('.'), returnCurrent = null, current = '', i = 0; if (!stringKey) { return obj; } returnCurrent = function(obj) { if (!obj) { return null; } else { return obj[current]; } }; while (i < parts.length) { current = parts[i]; obj = returnCurrent(obj); i++; } if (typeof obj !== 'undefined') { return obj; } else { return null; } }
javascript
{ "resource": "" }
q49502
train
function(actionName, args) { var self = this, hooks = self.constructor.actions[actionName], extensionName = ''; if (!hooks || h.isEmptyObject(hooks)) return; for (extensionName in hooks) { hooks[extensionName].apply(self, args); } }
javascript
{ "resource": "" }
q49503
train
function(filterName, input, args) { var self = this, hooks = self.constructor.filters[filterName], output = input, extensionName = ''; if (!hooks || h.isEmptyObject(hooks)) return output; args = args || []; for (extensionName in hooks) { args = h.arrayFromList(args); args.unshift(output); output = hooks[extensionName].apply(self, args); } return output; }
javascript
{ "resource": "" }
q49504
train
function(el, document) { var self = this; self.callActions('beforeCacheDom', arguments); self.dom.document = document; self.dom.body = self.dom.document.querySelector('body'); self.dom.container = el; self.dom.parent = el; self.callActions('afterCacheDom', arguments); }
javascript
{ "resource": "" }
q49505
train
function() { var self = this, target = null, el = null, dataset = null, i = -1; self.callActions('beforeIndexTargets', arguments); self.dom.targets = self.config.layout.allowNestedTargets ? self.dom.container.querySelectorAll(self.config.selectors.target) : h.children(self.dom.container, self.config.selectors.target, self.dom.document); self.dom.targets = h.arrayFromList(self.dom.targets); self.targets = []; if ((dataset = self.config.load.dataset) && dataset.length !== self.dom.targets.length) { throw new Error(mixitup.messages.errorDatasetPrerenderedMismatch()); } if (self.dom.targets.length) { for (i = 0; el = self.dom.targets[i]; i++) { target = new mixitup.Target(); target.init(el, self, dataset ? dataset[i] : void(0)); target.isInDom = true; self.targets.push(target); } self.dom.parent = self.dom.targets[0].parentElement === self.dom.container ? self.dom.container : self.dom.targets[0].parentElement; } self.origOrder = self.targets; self.callActions('afterIndexTargets', arguments); }
javascript
{ "resource": "" }
q49506
train
function() { var self = this, delineator = self.config.controls.toggleLogic === 'or' ? ', ' : '', toggleSelector = ''; self.callActions('beforeGetToggleSelector', arguments); self.toggleArray = h.clean(self.toggleArray); toggleSelector = self.toggleArray.join(delineator); if (toggleSelector === '') { toggleSelector = self.config.controls.toggleDefault; } return self.callFilters('selectorGetToggleSelector', toggleSelector, arguments); }
javascript
{ "resource": "" }
q49507
train
function(command, state) { var self = this, activeFilterSelector = ''; self.callActions('beforeBuildToggleArray', arguments); if (command && command.filter) { activeFilterSelector = command.filter.selector.replace(/\s/g, ''); } else if (state) { activeFilterSelector = state.activeFilter.selector.replace(/\s/g, ''); } else { return; } if (activeFilterSelector === self.config.selectors.target || activeFilterSelector === 'all') { activeFilterSelector = ''; } if (self.config.controls.toggleLogic === 'or') { self.toggleArray = activeFilterSelector.split(','); } else { self.toggleArray = self.splitCompoundSelector(activeFilterSelector); } self.toggleArray = h.clean(self.toggleArray); self.callActions('afterBuildToggleArray', arguments); }
javascript
{ "resource": "" }
q49508
train
function(target, attribute) { var self = this, value = ''; value = target.dom.el.getAttribute('data-' + attribute); if (value === null) { if (self.config.debug.showWarnings) { // Encourage users to assign values to all targets to avoid erroneous sorting // when types are mixed console.warn(mixitup.messages.warningInconsistentSortingAttributes({ attribute: 'data-' + attribute })); } } // If an attribute is not present, return 0 as a safety value return self.callFilters('valueGetAttributeValue', value || 0, arguments); }
javascript
{ "resource": "" }
q49509
train
function(isResetting, operation) { var self = this, startOrder = isResetting ? operation.newOrder : operation.startOrder, newOrder = isResetting ? operation.startOrder : operation.newOrder, nextSibling = startOrder.length ? startOrder[startOrder.length - 1].dom.el.nextElementSibling : null, frag = window.document.createDocumentFragment(), whitespace = null, target = null, el = null, i = -1; self.callActions('beforePrintSort', arguments); // Empty the container for (i = 0; target = startOrder[i]; i++) { el = target.dom.el; if (el.style.position === 'absolute') continue; h.removeWhitespace(el.previousSibling); el.parentElement.removeChild(el); } whitespace = nextSibling ? nextSibling.previousSibling : self.dom.parent.lastChild; if (whitespace && whitespace.nodeName === '#text') { h.removeWhitespace(whitespace); } for (i = 0; target = newOrder[i]; i++) { // Add targets into a document fragment el = target.dom.el; if (h.isElement(frag.lastChild)) { frag.appendChild(window.document.createTextNode(' ')); } frag.appendChild(el); } // Insert the document fragment into the container // before any other non-target elements if (self.dom.parent.firstChild && self.dom.parent.firstChild !== nextSibling) { frag.insertBefore(window.document.createTextNode(' '), frag.childNodes[0]); } if (nextSibling) { frag.appendChild(window.document.createTextNode(' ')); self.dom.parent.insertBefore(frag, nextSibling); } else { self.dom.parent.appendChild(frag); } self.callActions('afterPrintSort', arguments); }
javascript
{ "resource": "" }
q49510
train
function() { var self = this, transformName = '', effectsIn = self.config.animation.effectsIn || self.config.animation.effects, effectsOut = self.config.animation.effectsOut || self.config.animation.effects; self.callActions('beforeParseEffects', arguments); self.effectsIn = new mixitup.StyleData(); self.effectsOut = new mixitup.StyleData(); self.transformIn = []; self.transformOut = []; self.effectsIn.opacity = self.effectsOut.opacity = 1; self.parseEffect('fade', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('fade', effectsOut, self.effectsOut, self.transformOut, true); for (transformName in mixitup.transformDefaults) { if (!(mixitup.transformDefaults[transformName] instanceof mixitup.TransformData)) { continue; } self.parseEffect(transformName, effectsIn, self.effectsIn, self.transformIn); self.parseEffect(transformName, effectsOut, self.effectsOut, self.transformOut, true); } self.parseEffect('stagger', effectsIn, self.effectsIn, self.transformIn); self.parseEffect('stagger', effectsOut, self.effectsOut, self.transformOut, true); self.callActions('afterParseEffects', arguments); }
javascript
{ "resource": "" }
q49511
train
function(statusChange, hasEffect, posIn, posOut) { var self = this, result = false; if (!h.isVisible(self.dom.container)) { // If the container is not visible, the transitionEnd // event will not occur and MixItUp will hang result = false; } else if ( (statusChange !== 'none' && hasEffect) || posIn.x !== posOut.x || posIn.y !== posOut.y ) { // If opacity and/or translate will change result = true; } else if (self.config.animation.animateResizeTargets) { // Check if width, height or margins will change result = ( posIn.width !== posOut.width || posIn.height !== posOut.height || posIn.marginRight !== posOut.marginRight || posIn.marginTop !== posOut.marginTop ); } else { result = false; } return self.callFilters('resultWillTransition', result, arguments); }
javascript
{ "resource": "" }
q49512
train
function() { var self = this, instruction = self.parseFilterArgs(arguments); return self.multimix({ filter: instruction.command }, instruction.animate, instruction.callback); }
javascript
{ "resource": "" }
q49513
train
function() { var self = this, instruction = self.parseFilterArgs(arguments), selector = instruction.command.selector, toggleSelector = ''; self.isToggling = true; if (self.toggleArray.indexOf(selector) < 0) { self.toggleArray.push(selector); } toggleSelector = self.getToggleSelector(); return self.multimix({ filter: toggleSelector }, instruction.animate, instruction.callback); }
javascript
{ "resource": "" }
q49514
train
function() { var self = this, instruction = self.parseSortArgs(arguments); return self.multimix({ sort: instruction.command }, instruction.animate, instruction.callback); }
javascript
{ "resource": "" }
q49515
train
function() { var self = this, instruction = self.parseChangeLayoutArgs(arguments); return self.multimix({ changeLayout: instruction.command }, instruction.animate, instruction.callback); }
javascript
{ "resource": "" }
q49516
train
function() { var self = this, instruction = self.parseDatasetArgs(arguments), operation = null, queueItem = null, animate = false; self.callActions('beforeDataset', arguments); if (!self.isBusy) { if (instruction.callback) self.userCallback = instruction.callback; animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; operation = self.getDataOperation(instruction.command.dataset); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; return self.queueMix(queueItem); } }
javascript
{ "resource": "" }
q49517
train
function() { var self = this, operation = null, animate = false, queueItem = null, instruction = self.parseMultimixArgs(arguments); self.callActions('beforeMultimix', arguments); if (!self.isBusy) { operation = self.getOperation(instruction.command); if (self.config.controls.enable) { // Update controls for API calls if (instruction.command.filter && !self.isToggling) { // As we are not toggling, reset the toggle array // so new filter overrides existing toggles self.toggleArray.length = 0; self.buildToggleArray(operation.command); } if (self.queue.length < 1) { self.updateControls(operation.command); } } if (instruction.callback) self.userCallback = instruction.callback; // Always allow the instruction to override the instance setting animate = (instruction.animate ^ self.config.animation.enable) ? instruction.animate : self.config.animation.enable; self.callFilters('operationMultimix', operation, arguments); return self.goMix(animate, operation); } else { queueItem = new mixitup.QueueItem(); queueItem.args = arguments; queueItem.instruction = instruction; queueItem.triggerElement = self.lastClicked; queueItem.isToggling = self.isToggling; return self.queueMix(queueItem); } }
javascript
{ "resource": "" }
q49518
train
function(operation, multiplier) { var target = null, posData = null, toHideIndex = -1, i = -1; multiplier = Math.min(multiplier, 1); multiplier = Math.max(multiplier, 0); for (i = 0; target = operation.show[i]; i++) { posData = operation.showPosData[i]; target.applyTween(posData, multiplier); } for (i = 0; target = operation.hide[i]; i++) { if (target.isShown) { target.hide(); } if ((toHideIndex = operation.toHide.indexOf(target)) > -1) { posData = operation.toHidePosData[toHideIndex]; if (!target.isShown) { target.show(); } target.applyTween(posData, multiplier); } } }
javascript
{ "resource": "" }
q49519
train
function() { var self = this, args = self.parseInsertArgs(arguments); return self.multimix({ insert: args.command }, args.animate, args.callback); }
javascript
{ "resource": "" }
q49520
train
function() { var self = this, args = self.parseRemoveArgs(arguments); return self.multimix({ remove: args.command }, args.animate, args.callback); }
javascript
{ "resource": "" }
q49521
train
function(stringKey) { var self = this, value = null; if (!stringKey) { value = self.config; } else { value = h.getProperty(self.config, stringKey); } return self.callFilters('valueGetConfig', value, arguments); }
javascript
{ "resource": "" }
q49522
train
function(config) { var self = this; self.callActions('beforeConfigure', arguments); h.extend(self.config, config, true, true); self.callActions('afterConfigure', arguments); }
javascript
{ "resource": "" }
q49523
train
function() { var self = this, state = null; state = new mixitup.State(); h.extend(state, self.state); h.freeze(state); return self.callFilters('stateGetState', state, arguments); }
javascript
{ "resource": "" }
q49524
train
function(cleanUp) { var self = this, control = null, target = null, i = 0; self.callActions('beforeDestroy', arguments); for (i = 0; control = self.controls[i]; i++) { control.removeBinding(self); } for (i = 0; target = self.targets[i]; i++) { if (cleanUp) { target.show(); } target.unbindEvents(); } if (self.dom.container.id.match(/^MixItUp/)) { self.dom.container.removeAttribute('id'); } delete mixitup.instances[self.id]; self.callActions('afterDestroy', arguments); }
javascript
{ "resource": "" }
q49525
train
function(el, mixer, data) { var self = this, id = ''; self.callActions('beforeInit', arguments); self.mixer = mixer; if (!el) { // If no element is provided, render it el = self.render(data); } self.cacheDom(el); self.bindEvents(); if (self.dom.el.style.display !== 'none') { self.isShown = true; } if (data && mixer.config.data.uidKey) { if (typeof (id = data[mixer.config.data.uidKey]) === 'undefined' || id.toString().length < 1) { throw new TypeError(mixitup.messages.errorDatasetInvalidUidKey({ uidKey: mixer.config.data.uidKey })); } self.id = id; self.data = data; mixer.cache[id] = self; } self.callActions('afterInit', arguments); }
javascript
{ "resource": "" }
q49526
train
function(data) { var self = this, render = null, el = null, temp = null, output = ''; self.callActions('beforeRender', arguments); render = self.callFilters('renderRender', self.mixer.config.render.target, arguments); if (typeof render !== 'function') { throw new TypeError(mixitup.messages.errorDatasetRendererNotSet()); } output = render(data); if (output && typeof output === 'object' && h.isElement(output)) { el = output; } else if (typeof output === 'string') { temp = document.createElement('div'); temp.innerHTML = output; el = temp.firstElementChild; } return self.callFilters('elRender', el, arguments); }
javascript
{ "resource": "" }
q49527
train
function(el) { var self = this; self.callActions('beforeCacheDom', arguments); self.dom.el = el; self.callActions('afterCacheDom', arguments); }
javascript
{ "resource": "" }
q49528
train
function(moveData) { var self = this, posIn = moveData.posIn, isFading = self.mixer.effectsIn.opacity !== 1, transformValues = []; self.callActions('beforeApplyStylesIn', arguments); transformValues.push('translate(' + posIn.x + 'px, ' + posIn.y + 'px)'); if (self.mixer.config.animation.animateResizeTargets) { if (moveData.statusChange !== 'show') { // Don't apply posIn width or height or showing, as will be 0 self.dom.el.style.width = posIn.width + 'px'; self.dom.el.style.height = posIn.height + 'px'; } self.dom.el.style.marginRight = posIn.marginRight + 'px'; self.dom.el.style.marginBottom = posIn.marginBottom + 'px'; } isFading && (self.dom.el.style.opacity = posIn.opacity); if (moveData.statusChange === 'show') { transformValues = transformValues.concat(self.mixer.transformIn); } self.dom.el.style[mixitup.features.transformProp] = transformValues.join(' '); self.callActions('afterApplyStylesIn', arguments); }
javascript
{ "resource": "" }
q49529
train
function(property, staggerIndex, duration) { var self = this, delay = self.getDelay(staggerIndex), rule = ''; rule = property + ' ' + (duration > 0 ? duration : self.mixer.config.animation.duration) + 'ms ' + delay + 'ms ' + (property === 'opacity' ? 'linear' : self.mixer.config.animation.easing); return self.callFilters('ruleWriteTransitionRule', rule, arguments); }
javascript
{ "resource": "" }
q49530
train
function(methodName) { var self = this, instance = null, args = Array.prototype.slice.call(arguments), tasks = [], i = -1; this.callActions('beforeMixitup'); args.shift(); for (i = 0; instance = self[i]; i++) { tasks.push(instance[methodName].apply(instance, args)); } return self.callFilters('promiseMixitup', h.all(tasks, mixitup.libraries), arguments); }
javascript
{ "resource": "" }
q49531
buildModelWithBias
train
function buildModelWithBias(inputArray, bias, rowLabels, colLabels) { var model = new Model($M(inputArray), rowLabels, colLabels); model.estimated = train(sylvester.Matrix.create(inputArray), bias); return model }
javascript
{ "resource": "" }
q49532
train
train
function train(inputMatrix, bias) { N = inputMatrix.rows(); // number of rows M = inputMatrix.cols(); // number of columns // Generate random P and Q based on the dimensions of inputMatrix var P_model = generateRandomMatrix(N, K); var Q_model = generateRandomMatrix(K, M); var i = 0 for(i = 0; i < DESCENT_STEPS; i++) { //console.log('------------------ Iteration --------------------'); // Calculate error var error = calculateError(P_model.x(Q_model), inputMatrix, bias); P_prime = P_model.elements; Q_prime = Q_model.elements; // For debugging //console.log('P: ' + JSON.stringify(P_prime)); //console.log('Q: ' + JSON.stringify(Q_prime)); // Update P and Q to reduce error for (var row = 0; row < N; row++) { for (var col = 0; col < M; col++) { for(var feature = 0; feature < K; feature++) { // update formulas will change values in the opposite direction of the gradient. // P Update Formula // p_ik = p_ik + alpha * (e_ij * q_kj - beta * p_ik) // Reverse Gradient: alpha * e_ij * q_kj -- Note that we omit the 2* factor since it's not necessary for convergence. // Regularization factor: alpha * beta * p_ik var p_prev = P_prime[row][feature]; P_prime[row][feature] = P_prime[row][feature] + ALPHA*(error.e(row+1, col+1)*Q_prime[feature][col] - BETA * P_prime[row][feature]); //console.log('P['+row+']['+feature+'] ('+p_prev+') <- ('+P_prime[row][feature]+')'); // Q Update Formula // q_kj = q_kj + alpha x (e_ij x p_ik - beta x q_kj) // Reverse Gradient: alpha * e_ij * p_ik -- Note that we omit the 2* factor since it's not necessary for convergence. // Regularization factor: alpha * beta * q_kj var q_prev = Q_prime[feature][col]; Q_prime[feature][col] = Q_prime[feature][col] + ALPHA *(error.e(row+1, col+1)*P_prime[row][feature] - BETA * Q_prime[feature][col]); //console.log('Q['+feature+']['+col+'] ('+q_prev+') <- ('+Q_prime[feature][col]+')'); } } } // if we've already reached the error threshold, no need to descend further var totError = calculateTotalError(error); if(totError < MAX_ERROR) { //console.log('Reached error threshold early, no more descent needed.'); break; } } //console.log('Descent steps used: ' + i); // produce the final estimation by multiplying P and Q var finalModel = P_model.x(Q_model); // if we were considering bias, we have to add it back in if(bias) { // add back the overall average finalModel = finalModel.map(function(x) { return x + bias.average; }); var finalElements = finalModel.elements; // add back the row bias from each row for(var i = 1; i <= finalModel.rows(); i++) { for(var j = 1; j <= finalModel.cols(); j++) { finalElements[i-1][j-1] += bias.rowBiases.e(i); } } // add back the column bias from each column for(var i = 1; i <= finalModel.rows(); i++) { for(var j = 1; j <= finalModel.cols(); j++) { finalElements[i-1][j-1] += bias.colBiases.e(j); } } } return finalModel; }
javascript
{ "resource": "" }
q49533
calculateError
train
function calculateError(estimated, input, bias) { var adjustedInput = input.dup(); var adjustedElements = adjustedInput.elements; // If bias adjustment is provided, adjust for it if(bias) { // subtract the row and column bias from each row for(var i = 0; i <= adjustedInput.rows()-1; i++) { for(var j = 0; j <= adjustedInput.cols()-1; j++) { if(adjustedElements[i][j] == 0) continue; // skip zeroes adjustedElements[i][j] -= bias.average; adjustedElements[i][j] -= bias.rowBiases.e(i+1); adjustedElements[i][j] -= bias.colBiases.e(j+1); } } } var estimatedElements = estimated.elements; // Error is (R - R') // (but we ignore error on the zero entries since they are unknown) for(var i = 0; i <= adjustedInput.rows()-1; i++) { for(var j = 0; j <= adjustedInput.cols()-1; j++) { if(adjustedElements[i][j] == 0) continue; // skip zeroes adjustedElements[i][j] -= estimatedElements[i][j]; } } // Error is (R - R') return adjustedInput; }
javascript
{ "resource": "" }
q49534
calculateTotalError
train
function calculateTotalError(errorMatrix) { var totError = 0.0; for(var i = 1; i <= errorMatrix.rows(); i++) { for(var j = 1; j <= errorMatrix.cols(); j++) { totError += Math.pow(errorMatrix.e(i, j), 2); } } return totError; }
javascript
{ "resource": "" }
q49535
calculateBias
train
function calculateBias(input) { var inputMatrix = $M(input); var average = calculateMatrixAverage(inputMatrix); var rowAverages = calculateRowAverage(inputMatrix); var colAverages = calculateColumnAverage(inputMatrix); var rowBiases = new Array(); var colBiases = new Array(); // The row bias is the difference between the row average and the overall average for(var i = 1; i <= rowAverages.dimensions().cols; i++) { rowBiases[i-1] = rowAverages.e(i) - average; } // the column bias is the difference between the column average and the overall average for(var i = 1; i <= colAverages.dimensions().cols; i++) { colBiases[i-1] = colAverages.e(i) - average; } var biases = new Bias(average, $V(rowBiases), $V(colBiases)); return biases; }
javascript
{ "resource": "" }
q49536
Bias
train
function Bias(average, rowBiases, colBiases) { this.average = average; // Overall value average this.rowBiases = rowBiases; // Bias for each row this.colBiases = colBiases; // Bias for each column }
javascript
{ "resource": "" }
q49537
calculateMatrixAverage
train
function calculateMatrixAverage(inputMatrix) { var cells = inputMatrix.rows() * inputMatrix.cols(); var sum = 0; for(var i = 1; i <= inputMatrix.rows(); i++) { for(var j = 1; j <= inputMatrix.cols(); j++) { sum += inputMatrix.e(i, j); } } return sum/cells; }
javascript
{ "resource": "" }
q49538
calculateColumnAverage
train
function calculateColumnAverage(inputMatrix) { var rows = inputMatrix.rows(); var averages = new Array(); for(var i = 1; i <= inputMatrix.cols(); i++) { var sum = 0; for(var j = 1; j <= inputMatrix.rows(); j++) { sum += inputMatrix.e(j, i); } averages[i-1] = sum/rows; } return $V(averages); }
javascript
{ "resource": "" }
q49539
Model
train
function Model(inputMatrix, rowLabels, colLabels) { this.rowLabels = rowLabels; // labels for the rows this.colLabels = colLabels; // labels for the columns this.input = inputMatrix; // input data // estimated data, initialized to all zeros this.estimated = sylvester.Matrix.Zeros(this.input.rows(),this.input.cols()); }
javascript
{ "resource": "" }
q49540
train
function(row) { var rowIndex = row; // assume row is a number // If we're using labels we have to look up the row index if(this.rowLabels) { rowIndex = findInArray(this.rowLabels, row); } // estimates for this user var ratingElements = this.estimated.row(rowIndex+1).elements; // build a two dimensional array from the ratings and indexes // [[index, rating], [index, rating]] var outputArray = new Array(); for(var i=0; i<ratingElements.length; i++) { outputArray[i] = [i, ratingElements[i]]; // if we have column labels, use those if(this.colLabels) { outputArray[i][0] = this.colLabels[i]; } } // Sort the array by index return outputArray.sort(function(a, b) {return a[1] < b[1]}) }
javascript
{ "resource": "" }
q49541
train
function(row) { var recommendedItems = new Array(); var allItems = this.rankAllItems(row); var rowIndex = row; // assume row is a number // If we're using labels we have to look up the row index if(this.rowLabels) { rowIndex = findInArray(this.rowLabels, row); } for(var i=0; i< allItems.length; i++) { // look up the value in the input var colIndex = allItems[i][0]; // see if we're using column labels or not if(this.colLabels) { colIndex = findInArray(this.colLabels, allItems[i][0]); } var inputRating = this.input.e(rowIndex+1, colIndex+1); // if there was no rating its a recommendation so add it if(inputRating == 0) { recommendedItems.push(allItems[i]); } } return recommendedItems; }
javascript
{ "resource": "" }
q49542
createCsvDelimiterDetector
train
function createCsvDelimiterDetector(csvParser) { const detector = PassThrough() const sniffer = new CSVSniffer() let done = false detector.on('data', (chunk) => { if (!done) { const result = sniffer.sniff(chunk.toString()) csvParser.options.delimiter = result.delimiter done = true } }) return detector }
javascript
{ "resource": "" }
q49543
getComponentsInEventRegistry
train
function getComponentsInEventRegistry(eventRegistry, namespace) { var selector = Object.keys(eventRegistry) .map(function (componentName) { return "[data-" + namespace + "-name=\"" + componentName + "\"]"; }) .join(","); if (!selector) { return []; } var componentElements = document.documentElement.querySelectorAll(selector); var components = []; for (var i = 0; i < componentElements.length; i++) { var component = getComponentByDomNode(componentElements[i], namespace); if (component) { components.push(component); } } return components; }
javascript
{ "resource": "" }
q49544
fireViewportChangeEvent
train
function fireViewportChangeEvent(viewport, eventRegistry, namespace) { var components = getComponentsInEventRegistry(eventRegistry, namespace); var handlerResults = []; components.forEach(function (component) { Object.keys(eventRegistry[component._componentName]).forEach(function (selector) { if (selector === "" || viewport === selector) { eventRegistry[component._componentName][selector].forEach(function (handlerOption) { handlerResults.push(component[handlerOption.handlerName].call(component, { viewport: viewport })); }); } }); }); handlerResults.forEach(function (handlerResults) { return function () { if (typeof handlerResults === "function") { handlerResults(); } }; }); }
javascript
{ "resource": "" }
q49545
convertBreakpointsToEm
train
function convertBreakpointsToEm(breakpointsInPx) { var breakpointsInEm = {}; var breakpointNames = Object.keys(breakpointsInPx); breakpointNames.forEach(function (breakpointName) { breakpointsInEm[breakpointName] = px2em(breakpointsInPx[breakpointName]); }); return breakpointsInEm; }
javascript
{ "resource": "" }
q49546
generateMediaQueries
train
function generateMediaQueries(breakPoints, unit) { // Sort breakpoints by size var breakpointNames = Object.keys(breakPoints).sort(function (breakpointNameA, breakpointNameB) { if (breakPoints[breakpointNameA] > breakPoints[breakpointNameB]) { return 1; } if (breakPoints[breakpointNameA] < breakPoints[breakpointNameB]) { return -1; } return 0; }); // Convert breakpoints from 980 into (min-width: 700) and (max-width: 980) // by using the previous breakpoint return breakpointNames.map(function (breakpointName, i) { // If this is the first breakpoint we don't need a min value var min = breakpointNames[i - 1] === undefined ? undefined : breakPoints[breakpointNames[i - 1]] + 1; // If this is the last breakpoint we don't need a max value var max = breakPoints[breakpointName] === Infinity ? undefined : breakPoints[breakpointName]; var queryString; if (min && max) { queryString = "(min-width: " + min + unit + ") and (max-width: " + max + unit + ")"; } else if (min) { queryString = "(min-width: " + min + unit + ")"; } else if (max) { queryString = "(max-width: " + max + unit + ")"; } else { // This should only happen if the user did a miss configuration // with only a single breakpoint which is set to infinity throw new Error("The smallest provided viewport must not be set to Infinity"); } return { name: breakpointName, query: queryString, min: min, max: max }; }); }
javascript
{ "resource": "" }
q49547
setupViewportChangeEvent
train
function setupViewportChangeEvent(mediaQueries, eventRegistry, namespace) { var _loop_1 = function (viewport) { matchMedia(viewport.query).addListener(function (mediaQueryList) { if (mediaQueryList.matches) { fireViewportChangeEvent(viewport.name, eventRegistry, namespace); } }); }; for (var _i = 0, mediaQueries_1 = mediaQueries; _i < mediaQueries_1.length; _i++) { var viewport = mediaQueries_1[_i]; _loop_1(viewport); } }
javascript
{ "resource": "" }
q49548
setupCurrentViewportHelper
train
function setupCurrentViewportHelper(mediaQueries) { var _loop_2 = function (viewport) { var viewportMediaQueryList = matchMedia(viewport.query); // Set initial viewport if (viewportMediaQueryList.matches) { currentViewport = viewport.name; } // Watch for media query changes viewportMediaQueryList.addListener(function (mediaQueryList) { if (mediaQueryList.matches) { currentViewport = viewport.name; } }); }; for (var _i = 0, mediaQueries_2 = mediaQueries; _i < mediaQueries_2.length; _i++) { var viewport = mediaQueries_2[_i]; _loop_2(viewport); } }
javascript
{ "resource": "" }
q49549
startResizeWatching
train
function startResizeWatching(event) { var components = getComponentsInEventRegistry(eventRegistry, namespace); isRunning = true; // The resize listener is fired very often // for performance optimisations we search and store // all components during the initial start event componentInformation = components.map(function (component) { var size = component.__resizeSize || { width: 0, height: 0 }; var gondelComponentHandlers = eventRegistry[component._componentName]; return { component: component, node: component._ctx, selectors: Object.keys(gondelComponentHandlers).map(function (selector) { return gondelComponentHandlers[selector].map(function (handlerOption) { return component[handlerOption.handlerName]; }); }), width: size.width, height: size.height }; }); fireResizeEvent(event); }
javascript
{ "resource": "" }
q49550
fireComponentResizeEvent
train
function fireComponentResizeEvent(event) { frameIsRequested = false; if (!componentInformation) { return; } var newSizes = componentInformation.map(function (_a) { var node = _a.node; return ({ width: node.clientWidth, height: node.clientHeight }); }); var handlerResults = []; componentInformation.forEach(function (componentInformation, i) { var newSize = newSizes[i]; // Skip if the size did not change if (newSize.width === componentInformation.width && newSize.height === componentInformation.height) { return; } // Skip if the component is not running anymore if (componentInformation.component._stopped) { return; } componentInformation.component.__resizeSize = newSize; componentInformation.width = newSize.width; componentInformation.height = newSize.height; componentInformation.selectors.forEach(function (selector) { return selector.forEach(function (handler) { return handlerResults.push(handler.call(componentInformation.component, event, newSize)); }); }); }); handlerResults.forEach(function (handlerResult) { if (typeof handlerResult === "function") { handlerResult(); } }); }
javascript
{ "resource": "" }
q49551
fireWindowResizeEvent
train
function fireWindowResizeEvent(event) { frameIsRequested = false; if (!componentInformation) { return; } var handlerResults = []; componentInformation.forEach(function (componentInformation, i) { // Skip if the component is not running anymore if (componentInformation.component._stopped) { return; } componentInformation.selectors.forEach(function (selector) { return selector.forEach(function (handler) { return handlerResults.push(handler.call(componentInformation.component, event)); }); }); }); handlerResults.forEach(function (handlerResult) { if (typeof handlerResult === "function") { handlerResult(); } }); }
javascript
{ "resource": "" }
q49552
convertPropertyKeyToDataAttributeKey
train
function convertPropertyKeyToDataAttributeKey(propertyKey) { if (propertyKey.substr(0, 1) === "_") { propertyKey = propertyKey.substr(1); } if (propertyKey.substr(0, 4) !== "data") { throw new Error(propertyKey + "\" has an invalid format please use @data dataSomeProp (data-some-prop) for valid bindings."); } return propertyKey.replace(/([a-zA-Z])(?=[A-Z])/g, "$1-").toLowerCase(); }
javascript
{ "resource": "" }
q49553
train
function (element, selector) { var elementPrototype = window.Element.prototype; /* istanbul ignore next : Browser polyfill can't be tested */ var elementMatches = elementPrototype.matches || elementPrototype.matchesSelector || elementPrototype.mozMatchesSelector || elementPrototype.msMatchesSelector || elementPrototype.webkitMatchesSelector; // Cache the function and call it return (matchesCssSelector = function (element, selector) { return elementMatches.call(element, selector); })(element, selector); }
javascript
{ "resource": "" }
q49554
handleEvent
train
function handleEvent(namespace, attributeName, eventHandlerRegistry, event) { var target = event.target; var handlers = getHandlers(attributeName, eventHandlerRegistry, target); executeHandlers(handlers, event, namespace); }
javascript
{ "resource": "" }
q49555
getNewComponents
train
function getNewComponents(components, registry) { var componentNameHelper = {}; components.forEach(function (component) { return (componentNameHelper[component._componentName] = true); }); var componentNames = Object.keys(componentNameHelper); return componentNames.filter(function (componentName) { return !registry._activeComponents[componentName]; }); }
javascript
{ "resource": "" }
q49556
getAll
train
async function getAll(options) { const data = {}; const keys = filterPaths(await module.exports.keys(), options); for (let key of keys) { data[key] = await module.exports.get(key, { before: options.before, after: options.after, }); } await Promise.all(keys); return data; }
javascript
{ "resource": "" }
q49557
bufferToString
train
function bufferToString (buf) { const a = bufferToTuples(buf) const b = tuplesToStringTuples(a) return stringTuplesToString(b) }
javascript
{ "resource": "" }
q49558
stringToBuffer
train
function stringToBuffer (str) { str = cleanPath(str) const a = stringToStringTuples(str) const b = stringTuplesToTuples(a) return tuplesToBuffer(b) }
javascript
{ "resource": "" }
q49559
fromBuffer
train
function fromBuffer (buf) { const err = validateBuffer(buf) if (err) throw err return Buffer.from(buf) // copy }
javascript
{ "resource": "" }
q49560
decrypt
train
function decrypt(buffer, params, keyLookupCallback) { var header = parseParams(params); if (header.version === 'aes128gcm') { var headerLength = readHeader(buffer, header); buffer = buffer.slice(headerLength); } var key = deriveKeyAndNonce(header, MODE_DECRYPT, keyLookupCallback); var start = 0; var result = new Buffer(0); var chunkSize = header.rs; if (header.version !== 'aes128gcm') { chunkSize += TAG_LENGTH; } for (var i = 0; start < buffer.length; ++i) { var end = start + chunkSize; if (header.version !== 'aes128gcm' && end === buffer.length) { throw new Error('Truncated payload'); } end = Math.min(end, buffer.length); if (end - start <= TAG_LENGTH) { throw new Error('Invalid block: too small at ' + i); } var block = decryptRecord(key, i, buffer.slice(start, end), header, end >= buffer.length); result = Buffer.concat([result, block]); start = end; } return result; }
javascript
{ "resource": "" }
q49561
encrypt
train
function encrypt(buffer, params, keyLookupCallback) { if (!Buffer.isBuffer(buffer)) { throw new Error('buffer argument must be a Buffer'); } var header = parseParams(params); if (!header.salt) { header.salt = crypto.randomBytes(KEY_LENGTH); } var result; if (header.version === 'aes128gcm') { // Save the DH public key in the header unless keyid is set. if (header.privateKey && !header.keyid) { header.keyid = header.privateKey.getPublicKey(); } result = writeHeader(header); } else { // No header on other versions result = new Buffer(0); } var key = deriveKeyAndNonce(header, MODE_ENCRYPT, keyLookupCallback); var start = 0; var padSize = PAD_SIZE[header.version]; var overhead = padSize; if (header.version === 'aes128gcm') { overhead += TAG_LENGTH; } var pad = isNaN(parseInt(params.pad, 10)) ? 0 : parseInt(params.pad, 10); var counter = 0; var last = false; while (!last) { // Pad so that at least one data byte is in a block. var recordPad = Math.min(header.rs - overhead - 1, pad); if (header.version !== 'aes128gcm') { recordPad = Math.min((1 << (padSize * 8)) - 1, recordPad); } if (pad > 0 && recordPad === 0) { ++recordPad; // Deal with perverse case of rs=overhead+1 with padding. } pad -= recordPad; var end = start + header.rs - overhead - recordPad; if (header.version !== 'aes128gcm') { // The > here ensures that we write out a padding-only block at the end // of a buffer. last = end > buffer.length; } else { last = end >= buffer.length; } last = last && pad <= 0; var block = encryptRecord(key, counter, buffer.slice(start, end), recordPad, header, last); result = Buffer.concat([result, block]); start = end; ++counter; } return result; }
javascript
{ "resource": "" }
q49562
train
function(path, interval, fn) { if(typeof fn === 'undefined') { fn = interval; interval = 100; } if(typeof interval !== 'number') return false; if(typeof fn !== 'function') return false; var value; var readTimer = setInterval(function() { _read(path, function(val) { if(value !== val) { if(typeof value !== 'undefined') fn(val); value = val; } }); }, interval); this.stop = function() { clearInterval(readTimer); }; }
javascript
{ "resource": "" }
q49563
parse_description
train
function parse_description(str, data) { if (data.errors && data.errors.length) { return null; } var result = str.match(/^\s+([\s\S]+)?/); if (result) { return { source: result[0], data: {description: result[1] === undefined ? '' : result[1].replace(trimNewlineRegex, '')} }; } return null; }
javascript
{ "resource": "" }
q49564
generate
train
function generate(dest, template, context, options) { options = options || {}; // find all root sections (sections with no parent) by removing all number // indices but keeping the named indices for (var i = 0; i < context.sections.length; ) { if (context.sections[i].parent) { context.sections.splice(i, 1); } else { i++; } } // sort root sections by section order if (context.sectionOrder) { utils.sortCategoryBy(context.sections, context.sectionOrder); } if (typeof options.preprocess !== 'undefined' && typeof options.preprocess !== 'function') { throw new SyntaxError('options.preprocess must be a function'); } // if no preprocess function then resolve a promise var preprocess = (options.preprocess ? options.preprocess(context, template, Handlebars) : Promise.resolve()); // if the user returned anything but false we'll resolve a promise if (!(preprocess instanceof Promise)) { preprocess = (preprocess !== false ? Promise.resolve() : Promise.reject()); } return preprocess .then(function() { // inline all stylesheets for polymer shared styles to work // @see https://www.polymer-project.org/1.0/docs/devguide/styling#style-modules return utils.readFiles(context.stylesheets, function(data, file) { context.parsedStylesheets = context.parsedStylesheets || []; context.parsedStylesheets.push(utils.fixSVGIssue(data)); }); }) .then(function success() { var html = Handlebars.compile(template)(context); if (options.minify) { html = minify(html, { collapseWhitespace: true }); } // output the file and create any necessary directories // @see http://stackoverflow.com/questions/16316330/how-to-write-file-if-parent-folder-dosent-exists mkdirp(path.dirname(dest), function(err) { if (err) { throw err; } fs.writeFile(dest, html, 'utf8', function(err) { if (err) { throw err; } }); }); }) .catch(function(err) { if (err) { console.error(err.stack); } }); }
javascript
{ "resource": "" }
q49565
globWithPromsie
train
function globWithPromsie(pattern) { return new Promise((resolve, reject) => { glob(pattern, function(err, files) { if (err) { reject(err); } if (files.length === 0) { console.warn('pattern "' + pattern + '" does not match any file'); } resolve(files); }); }); }
javascript
{ "resource": "" }
q49566
getProp
train
function getProp(obj, key) { var path = [].concat(key); var val = obj; for (var _i = 0, path_1 = path; _i < path_1.length; _i++) { var pathKey = path_1[_i]; if (val[pathKey] === undefined) { return undefined; } val = val[pathKey]; } return val; }
javascript
{ "resource": "" }
q49567
setProp
train
function setProp(obj, key, value) { var path = [].concat(key); var lastKey = path.pop(); var val = obj; for (var _i = 0, path_2 = path; _i < path_2.length; _i++) { var pathKey = path_2[_i]; if (typeof val[pathKey] !== 'object') { val[pathKey] = {}; } val = val[pathKey]; } val[lastKey] = value; return obj; }
javascript
{ "resource": "" }
q49568
matchModel
train
function matchModel(item, type, id) { /* istanbul ignore next */ return getType(item) === type && getProp(item, item.static.idAttribute) === id; }
javascript
{ "resource": "" }
q49569
train
function() { var script = doc.createElement('script'); script.onreadystatechange = function() { script.parentNode.removeChild(script); script = script.onreadystatechange = null; callFns(); }; (doc.documentElement || doc.body).appendChild(script); }
javascript
{ "resource": "" }
q49570
train
function(reason) { if(this._promise.isResolved()) { return; } if(vow.isPromise(reason)) { reason = reason.then(function(val) { var defer = vow.defer(); defer.reject(val); return defer.promise(); }); this._promise._resolve(reason); } else { this._promise._reject(reason); } }
javascript
{ "resource": "" }
q49571
train
function(onFulfilled, onRejected, onProgress, ctx) { this._shouldEmitUnhandledRejection = false; var defer = new Deferred(); this._addCallbacks(defer, onFulfilled, onRejected, onProgress, ctx); return defer.promise(); }
javascript
{ "resource": "" }
q49572
train
function(onFulfilled, onRejected, ctx) { return this.then( function(val) { return onFulfilled.apply(this, val); }, onRejected, ctx); }
javascript
{ "resource": "" }
q49573
train
function(onFulfilled, onRejected, onProgress, ctx) { this .then(onFulfilled, onRejected, onProgress, ctx) .fail(throwException); }
javascript
{ "resource": "" }
q49574
train
function(delay) { var timer, promise = this.then(function(val) { var defer = new Deferred(); timer = setTimeout( function() { defer.resolve(val); }, delay); return defer.promise(); }); promise.always(function() { clearTimeout(timer); }); return promise; }
javascript
{ "resource": "" }
q49575
train
function(timeout) { var defer = new Deferred(), timer = setTimeout( function() { defer.reject(new vow.TimedOutError('timed out')); }, timeout); this.then( function(val) { defer.resolve(val); }, function(reason) { defer.reject(reason); }); defer.promise().always(function() { clearTimeout(timer); }); return defer.promise(); }
javascript
{ "resource": "" }
q49576
train
function(value, onFulfilled, onRejected, onProgress, ctx) { return vow.cast(value).then(onFulfilled, onRejected, onProgress, ctx); }
javascript
{ "resource": "" }
q49577
train
function(value, onFulfilled, onRejected, ctx) { return vow.when(value).spread(onFulfilled, onRejected, ctx); }
javascript
{ "resource": "" }
q49578
train
function(value, onFulfilled, onRejected, onProgress, ctx) { vow.when(value).done(onFulfilled, onRejected, onProgress, ctx); }
javascript
{ "resource": "" }
q49579
train
function(fn, args) { var len = Math.max(arguments.length - 1, 0), callArgs; if(len) { // optimization for V8 callArgs = Array(len); var i = 0; while(i < len) { callArgs[i++] = arguments[i]; } } try { return vow.resolve(callArgs? fn.apply(global, callArgs) : fn.call(global)); } catch(e) { return vow.reject(e); } }
javascript
{ "resource": "" }
q49580
train
function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), len = keys.length, res = isPromisesArray? [] : {}; if(!len) { defer.resolve(res); return defer.promise(); } var i = len; vow._forEach( iterable, function(value, idx) { res[keys[idx]] = value; if(!--i) { defer.resolve(res); } }, defer.reject, defer.notify, defer, keys); return defer.promise(); }
javascript
{ "resource": "" }
q49581
train
function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), i = keys.length, res = isPromisesArray? [] : {}; if(!i) { defer.resolve(res); return defer.promise(); } var onResolved = function() { --i || defer.resolve(iterable); }; vow._forEach( iterable, onResolved, onResolved, defer.notify, defer, keys); return defer.promise(); }
javascript
{ "resource": "" }
q49582
compilePlainObject
train
function compilePlainObject (schema, options) { class PlainModelInstance extends PlainBaseModel { constructor (data, options = {}) { super(data, options, schema) } } PlainModelInstance.schema = schema // if the user wants to allow modifications if (options.freeze !== false) { Object.freeze(PlainModelInstance) } return PlainModelInstance }
javascript
{ "resource": "" }
q49583
get_sequence
train
function get_sequence(self, weight) { if (undefined === self.__sequences__[weight]) { self.__sequences__[weight] = []; } return self.__sequences__[weight]; }
javascript
{ "resource": "" }
q49584
waitForEvaluate
train
async function waitForEvaluate(env, evalFunction, checkerFunction, breakerFunction, args, timeout, interval) { args = args || []; checkerFunction = checkerFunction || function(result) { return !!result }; timeout = timeout || 5000; interval = interval || 10; let timeoutId, intervalId; return new Promise((resolve, reject) => { const errorCallback = { fn: ({ error }) => { clearTimeout(timeoutId); clearInterval(intervalId); reject(new Error(`Error during wait with args ${args.toString()}, ${error}`)); }, }; timeoutId = setTimeout(() => { env.removeCallback('error', errorCallback); clearInterval(intervalId); reject(new Error(`Timeout for wait with args ${args.toString()}`)); }, timeout); env.addCallback('error', errorCallback); const evalArgs = args.slice(0); evalArgs.push(evalFunction); intervalId = setInterval(() => { env.evaluateJs(...evalArgs) .then((result) => { if (checkerFunction(result)) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback('error', errorCallback); resolve(); return; } if (breakerFunction()) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback('error', errorCallback); reject(new Error('Function was terminated by breaker')); } }); }, interval); }); }
javascript
{ "resource": "" }
q49585
waitForEvent
train
async function waitForEvent(env, event, breakerFunction, timeout = 5000, interval = 10) { const { type, urlPattern } = event; let intervalId, timeoutId; await new Promise((resolve, reject) => { const callback = { fn: ({ error }) => { clearTimeout(timeoutId); clearInterval(intervalId); if (error) { reject(error); } else { resolve(); } }, urlPattern, }; timeoutId = setTimeout(() => { env.removeCallback(type, callback); clearInterval(intervalId); reject(new Error('Page navigation timeout')); }, timeout); intervalId = setInterval(() => { if (breakerFunction()) { clearTimeout(timeoutId); clearInterval(intervalId); env.removeCallback(type, callback); reject(new Error('Function was terminated by breaker')) } }, interval); env.addCallback(type, callback); }); if (type === 'navigation') { await env._injectFiles(env._getVendors()); } }
javascript
{ "resource": "" }
q49586
train
function () { var write = function (node, enc, cb) { node.value = encoder.encode(node.value, dag.valueEncoding) stream.node(node, cb) } stream.emit('live') pipe(dag.createReadStream({since: changes, live: true}), through.obj(write)) }
javascript
{ "resource": "" }
q49587
train
function (cb) { if (done || !localSentWants || !localSentHeads || !remoteSentWants || !remoteSentHeads) return cb() done = true if (!live) return stream.finalize(cb) sendChanges() cb() }
javascript
{ "resource": "" }
q49588
train
function (log, seq, cb) { dag.logs.get(log, seq, function (err, entry) { if (err && err.notFound) return cb() if (err) return cb(err) if (entry.change > changes) return cb() // ensure snapshot entry.log = log entry.seq = seq var i = 0 var loop = function () { if (i < entry.links.length) return sendHave(entry.links[i++], loop) entry.links = noarr // premature opt: less mem yo outgoing.push(entry, cb) } loop() }) }
javascript
{ "resource": "" }
q49589
train
function (dag, node, logLinks, batch, opts, cb) { if (opts.hash && node.key !== opts.hash) return cb(CHECKSUM_MISMATCH) if (opts.seq && node.seq !== opts.seq) return cb(INVALID_LOG) var log = { change: node.change, node: node.key, links: logLinks } var onclone = function (clone) { if (!opts.log) return cb(null, clone, []) batch.push({type: 'put', key: dag.logs.key(node.log, node.seq), value: messages.Entry.encode(log)}) cb(null, clone) } var done = function () { dag.get(node.key, { valueEncoding: 'binary' }, function (_, clone) { // This node already exists somewhere in the hyperlog; add it to the // log's append-only log, but don't insert it again. if (clone) return onclone(clone) var links = node.links for (var i = 0; i < links.length; i++) batch.push({type: 'del', key: HEADS + links[i]}) batch.push({type: 'put', key: CHANGES + lexint.pack(node.change, 'hex'), value: node.key}) batch.push({type: 'put', key: NODES + node.key, value: messages.Node.encode(node)}) batch.push({type: 'put', key: HEADS + node.key, value: node.key}) batch.push({type: 'put', key: dag.logs.key(node.log, node.seq), value: messages.Entry.encode(log)}) cb(null, node) }) } // Local node; sign it. if (node.log === dag.id) { if (!dag.sign || node.signature) return done() dag.sign(node, function (err, sig) { if (err) return cb(err) if (!node.identity) node.identity = dag.identity node.signature = sig done() }) // Remote node; verify it. } else { if (!dag.verify) return done() dag.verify(node, function (err, valid) { if (err) return cb(err) if (!valid) return cb(INVALID_SIGNATURE) done() }) } }
javascript
{ "resource": "" }
q49590
train
function (dag, opts) { var since = opts.since || 0 var limit = opts.limit || -1 var wait = null var read = function (size, cb) { if (dag.changes <= since) { wait = cb return } if (!limit) return cb(null, null) dag.db.get(CHANGES + lexint.pack(since + 1, 'hex'), function (err, hash) { if (err) return cb(err) dag.get(hash, opts, function (err, node) { if (err) return cb(err) since = node.change if (limit !== -1) limit-- cb(null, node) }) }) } var kick = function () { if (!wait) return var cb = wait wait = null read(0, cb) } dag.on('add', kick) dag.ready(kick) var rs = from.obj(read) rs.once('close', function () { dag.removeListener('add', kick) }) return rs }
javascript
{ "resource": "" }
q49591
train
function (nodes, batchOps, done) { self.db.batch(batchOps, function (err) { if (err) { nodes.forEach(rejectNode) return done(err) } done(null, nodes) }) }
javascript
{ "resource": "" }
q49592
computeNodeBatchOp
train
function computeNodeBatchOp (node, done) { var batch = [] var links = logLinks[node.key] addBatchAndDedupe(self, node, links, batch, opts, function (err, newNode) { if (err) return done(err) newNode.value = encoder.decode(newNode.value, opts.valueEncoding || self.valueEncoding) done(null, batch) }) }
javascript
{ "resource": "" }
q49593
train
function() { var args = slice.call(arguments); var object = args.shift(); for (var i = 0, l = args.length; i < l; i++) { var props = args[i]; for (var key in props) { object[key] = props[key]; } } return object; }
javascript
{ "resource": "" }
q49594
train
function() { var args = slice.call(arguments); args.unshift(this); return _.extend.apply(this, args); }
javascript
{ "resource": "" }
q49595
compare
train
function compare(pathData,opts={}) { var polys = svgPathToPolygons(pathData,opts); var minX=Infinity, maxX=-Infinity, minY=Infinity, maxY=-Infinity; polys.forEach(poly => { poly.forEach(pt => { if (pt[0]<minX) minX=pt[0]; if (pt[1]<minY) minY=pt[1]; if (pt[0]>maxX) maxX=pt[0]; if (pt[1]>maxY) maxY=pt[1]; }); }); let dx=maxX-minX, dy=maxY-minY; console.log(` <svg xmlns="http://www.w3.org/2000/svg" width="${dx}px" height="${dy}px" viewBox="${minX} ${minY} ${dx*2} ${dy}"> <style>path,polygon,polyline { fill-opacity:0.2; stroke:black }</style> <path d="${pathData}"/> <g transform="translate(${dx},0)"> ${polys.map(poly => ` <${poly.closed ? 'polygon' : 'polyline'} points="${poly.join(' ')}"/>`).join("\n")} </g> </svg> `.trim()); }
javascript
{ "resource": "" }
q49596
_getUserOption
train
function _getUserOption(userOptions, optToGet, isBool) { const envVar = `MOCHAWESOME_${optToGet.toUpperCase()}`; if (userOptions && typeof userOptions[optToGet] !== 'undefined') { return (isBool && typeof userOptions[optToGet] === 'string') ? userOptions[optToGet] === 'true' : userOptions[optToGet]; } if (typeof process.env[envVar] !== 'undefined') { return isBool ? process.env[envVar] === 'true' : process.env[envVar]; } return undefined; }
javascript
{ "resource": "" }
q49597
saveFile
train
function saveFile(filename, data, overwrite) { if (overwrite) { return fs.outputFile(filename, data) .then(() => filename); } else { return new Promise((resolve, reject) => { fsu.writeFileUnique( filename.replace(fileExtRegex, '{_###}$&'), data, { force: true }, (err, savedFile) => err === null ? resolve(savedFile) : reject(err) ); }); } }
javascript
{ "resource": "" }
q49598
openFile
train
function openFile(filename) { return new Promise((resolve, reject) => { opener(filename, null, err => err === null ? resolve(filename) : reject(err)); }); }
javascript
{ "resource": "" }
q49599
getOptions
train
function getOptions(opts) { const mergedOptions = getMergedOptions(opts || {}); // For saving JSON from mochawesome reporter if (mergedOptions.saveJson) { mergedOptions.jsonFile = `${getFilename(mergedOptions)}.json`; } mergedOptions.htmlFile = `${getFilename(mergedOptions)}.html`; return mergedOptions; }
javascript
{ "resource": "" }