_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q45900
removeMirageIndices
train
function removeMirageIndices(countMax, indexFirstKnown) { var placeholdersAtEnd = 0; function removePlaceholdersAfterSlot(slotRemoveAfter) { for (var slot2 = slotListEnd.prev; !(slot2.index < countMax) && slot2 !== slotRemoveAfter;) { var slotPrev2 = slot2.prev; if (slot2.index !== undefined) { deleteSlot(slot2, true); } slot2 = slotPrev2; } placeholdersAtEnd = 0; } for (var slot = slotListEnd.prev; !(slot.index < countMax) || placeholdersAtEnd > 0;) { var slotPrev = slot.prev; if (slot === slotsStart) { removePlaceholdersAfterSlot(slotsStart); break; } else if (slot.key) { if (slot.index >= countMax) { beginRefresh(); return false; } else if (slot.index >= indexFirstKnown) { removePlaceholdersAfterSlot(slot); } else { if (itemsFromKey) { fetchItemsFromKey(slot, 0, placeholdersAtEnd); } else { fetchItemsFromIndex(slot, 0, placeholdersAtEnd); } // Wait until the fetch has completed before doing anything return false; } } else if (slot.indexRequested || slot.firstInSequence) { removePlaceholdersAfterSlot(slotPrev); } else { placeholdersAtEnd++; } slot = slotPrev; } return true; }
javascript
{ "resource": "" }
q45901
lastRefreshInsertionPoint
train
function lastRefreshInsertionPoint() { var slotNext = refreshEnd; while (!slotNext.firstInSequence) { slotNext = slotNext.prev; if (slotNext === refreshStart) { return null; } } return slotNext; }
javascript
{ "resource": "" }
q45902
queueEdit
train
function queueEdit(applyEdit, editType, complete, error, keyUpdate, updateSlots, undo) { var editQueueTail = editQueue.prev, edit = { prev: editQueueTail, next: editQueue, applyEdit: applyEdit, editType: editType, complete: complete, error: error, keyUpdate: keyUpdate }; editQueueTail.next = edit; editQueue.prev = edit; editsQueued = true; // If there's a refresh in progress, abandon it, but request that a new one be started once the edits complete if (refreshRequested || refreshInProgress) { currentRefreshID++; refreshInProgress = false; refreshRequested = true; } if (editQueue.next === edit) { // Attempt the edit immediately, in case it completes synchronously applyNextEdit(); } // If the edit succeeded or is still pending, apply it to the slots (in the latter case, "optimistically") if (!edit.failed) { updateSlots(); // Supply the undo function now edit.undo = undo; } if (!editsInProgress) { completeEdits(); } }
javascript
{ "resource": "" }
q45903
discardEditQueue
train
function discardEditQueue() { while (editQueue.prev !== editQueue) { var editLast = editQueue.prev; if (editLast.error) { editLast.error(new _ErrorFromName(EditError.canceled)); } // Edits that haven't been applied to the slots yet don't need to be undone if (editLast.undo && !refreshRequested) { editLast.undo(); } editQueue.prev = editLast.prev; } editQueue.next = editQueue; editsInProgress = false; completeEdits(); }
javascript
{ "resource": "" }
q45904
concludeEdits
train
function concludeEdits() { editsQueued = false; if (listDataAdapter.endEdits && beginEditsCalled && !editsInProgress) { beginEditsCalled = false; listDataAdapter.endEdits(); } // See if there's a refresh that needs to begin if (refreshRequested) { refreshRequested = false; beginRefresh(); } else { // Otherwise, see if anything needs to be fetched postFetch(); } }
javascript
{ "resource": "" }
q45905
train
function (incomingPromise, dataSource) { var signal = new _Signal(); incomingPromise.then( function (v) { signal.complete(v); }, function (e) { signal.error(e); } ); var resultPromise = signal.promise.then(null, function (e) { if (e.name === "WinJS.UI.VirtualizedDataSource.resetCount") { getCountPromise = null; return incomingPromise = dataSource.getCount(); } return Promise.wrapError(e); }); var count = 0; var currentGetCountPromise = { get: function () { count++; return new Promise( function (c, e) { resultPromise.then(c, e); }, function () { if (--count === 0) { // when the count reaches zero cancel the incoming promise signal.promise.cancel(); incomingPromise.cancel(); if (currentGetCountPromise === getCountPromise) { getCountPromise = null; } } } ); }, reset: function () { signal.error(new _ErrorFromName("WinJS.UI.VirtualizedDataSource.resetCount")); }, cancel: function () { // if explicitly asked to cancel the incoming promise signal.promise.cancel(); incomingPromise.cancel(); if (currentGetCountPromise === getCountPromise) { getCountPromise = null; } } }; return currentGetCountPromise; }
javascript
{ "resource": "" }
q45906
ItemEventsHandler_toggleItemSelection
train
function ItemEventsHandler_toggleItemSelection(itemIndex) { var site = this._site, selection = site.selection, selected = selection._isIncluded(itemIndex); if (site.selectionMode === _UI.SelectionMode.single) { if (!selected) { selection.set(itemIndex); } else { selection.clear(); } } else { if (!selected) { selection.add(itemIndex); } else { selection.remove(itemIndex); } } }
javascript
{ "resource": "" }
q45907
train
function (groupKey, itemKey, itemIndex) { this._lastFocusedItemKey = itemKey; this._lastFocusedItemIndex = itemIndex; itemIndex = "" + itemIndex; this._itemToIndex[itemKey] = itemIndex; this._groupToItem[groupKey] = itemKey; }
javascript
{ "resource": "" }
q45908
flushDynamicCssRules
train
function flushDynamicCssRules() { var rules = layoutStyleElem.sheet.cssRules, classCount = staleClassNames.length, i, j, ruleSuffix; for (i = 0; i < classCount; i++) { ruleSuffix = "." + staleClassNames[i] + " "; for (j = rules.length - 1; j >= 0; j--) { if (rules[j].selectorText.indexOf(ruleSuffix) !== -1) { layoutStyleElem.sheet.deleteRule(j); } } } staleClassNames = []; }
javascript
{ "resource": "" }
q45909
addDynamicCssRule
train
function addDynamicCssRule(uniqueToken, site, selector, body) { flushDynamicCssRules(); var rule = "." + _Constants._listViewClass + " ." + uniqueToken + " " + selector + " { " + body + "}"; var perfId = "_addDynamicCssRule:" + uniqueToken + ",info"; if (site) { site._writeProfilerMark(perfId); } else { _WriteProfilerMark("WinJS.UI.ListView:Layout" + perfId); } layoutStyleElem.sheet.insertRule(rule, 0); }
javascript
{ "resource": "" }
q45910
getOuter
train
function getOuter(side, element) { return getDimension(element, "margin" + side) + getDimension(element, "border" + side + "Width") + getDimension(element, "padding" + side); }
javascript
{ "resource": "" }
q45911
_LayoutCommon_initialize
train
function _LayoutCommon_initialize(site, groupsEnabled) { site._writeProfilerMark("Layout:initialize,info"); if (!this._inListMode) { _ElementUtilities.addClass(site.surface, _Constants._gridLayoutClass); } if (this._backdropColorClassName) { _ElementUtilities.addClass(site.surface, this._backdropColorClassName); } if (this._disableBackdropClassName) { _ElementUtilities.addClass(site.surface, this._disableBackdropClassName); } this._groups = []; this._groupMap = {}; this._oldGroupHeaderPosition = null; this._usingStructuralNodes = false; this._site = site; this._groupsEnabled = groupsEnabled; this._resetAnimationCaches(true); }
javascript
{ "resource": "" }
q45912
updateGroups
train
function updateGroups() { function createGroup(groupInfo, itemsContainer) { var GroupType = (groupInfo.enableCellSpanning ? Groups.CellSpanningGroup : Groups.UniformGroup); return new GroupType(that, itemsContainer); } var oldRealizedItemRange = (that._groups.length > 0 ? that._getRealizationRange() : null), newGroups = [], prepared = [], cleanUpDom = {}, newGroupMap = {}, currentIndex = 0, len = tree.length, i; for (i = 0; i < len; i++) { var oldChangedRealizedRangeInGroup = null, groupInfo = that._getGroupInfo(i), groupKey = that._site.groupFromIndex(i).key, oldGroup = that._groupMap[groupKey], wasCellSpanning = oldGroup instanceof Groups.CellSpanningGroup, isCellSpanning = groupInfo.enableCellSpanning; if (oldGroup) { if (wasCellSpanning !== isCellSpanning) { // The group has changed types so DOM needs to be cleaned up cleanUpDom[groupKey] = true; } else { // Compute the range of changed items that is within the group's realized range var firstChangedIndexInGroup = Math.max(0, changedRange.firstIndex - oldGroup.startIndex), oldRealizedItemRangeInGroup = that._rangeForGroup(oldGroup, oldRealizedItemRange); if (oldRealizedItemRangeInGroup && firstChangedIndexInGroup <= oldRealizedItemRangeInGroup.lastIndex) { // The old changed realized range is non-empty oldChangedRealizedRangeInGroup = { firstIndex: Math.max(firstChangedIndexInGroup, oldRealizedItemRangeInGroup.firstIndex), lastIndex: oldRealizedItemRangeInGroup.lastIndex }; } } } var group = createGroup(groupInfo, tree[i].itemsContainer.element); var prepareLayoutPromise; if (group.prepareLayoutWithCopyOfTree) { prepareLayoutPromise = group.prepareLayoutWithCopyOfTree(copyItemsContainerTree(tree[i].itemsContainer), oldChangedRealizedRangeInGroup, oldGroup, { groupInfo: groupInfo, startIndex: currentIndex, }); } else { prepareLayoutPromise = group.prepareLayout(getItemsContainerLength(tree[i].itemsContainer), oldChangedRealizedRangeInGroup, oldGroup, { groupInfo: groupInfo, startIndex: currentIndex, }); } prepared.push(prepareLayoutPromise); currentIndex += group.count; newGroups.push(group); newGroupMap[groupKey] = group; } return Promise.join(prepared).then(function () { var currentOffset = 0; for (var i = 0, len = newGroups.length; i < len; i++) { var group = newGroups[i]; group.offset = currentOffset; currentOffset += that._getGroupSize(group); } // Clean up deleted groups Object.keys(that._groupMap).forEach(function (deletedKey) { var skipDomCleanUp = !cleanUpDom[deletedKey]; that._groupMap[deletedKey].cleanUp(skipDomCleanUp); }); that._groups = newGroups; that._groupMap = newGroupMap; }); }
javascript
{ "resource": "" }
q45913
layoutGroupContent
train
function layoutGroupContent(groupIndex, realizedItemRange, doRealizedRange) { var group = that._groups[groupIndex], firstChangedIndexInGroup = Math.max(0, changedRange.firstIndex - group.startIndex), realizedItemRangeInGroup = that._rangeForGroup(group, realizedItemRange), beforeRealizedRange; if (doRealizedRange) { group.layoutRealizedRange(firstChangedIndexInGroup, realizedItemRangeInGroup); } else { if (!realizedItemRangeInGroup) { beforeRealizedRange = (group.startIndex + group.count - 1 < realizedItemRange.firstIndex); } return group.layoutUnrealizedRange(firstChangedIndexInGroup, realizedItemRangeInGroup, beforeRealizedRange); } }
javascript
{ "resource": "" }
q45914
layoutUnrealizedRange
train
function layoutUnrealizedRange() { if (that._groups.length === 0) { return Promise.wrap(); } var realizedItemRange = that._getRealizationRange(), // Last group before the realized range which contains 1 or more unrealized items lastGroupBefore = site.groupIndexFromItemIndex(realizedItemRange.firstIndex - 1), // First group after the realized range which contains 1 or more unrealized items firstGroupAfter = site.groupIndexFromItemIndex(realizedItemRange.lastIndex + 1), firstChangedGroup = site.groupIndexFromItemIndex(changedRange.firstIndex), layoutPromises = [], groupCount = that._groups.length; var stop = false; var before = lastGroupBefore; var after = Math.max(firstChangedGroup, firstGroupAfter); after = Math.max(before + 1, after); while (!stop) { stop = true; if (before >= firstChangedGroup) { layoutPromises.push(layoutGroupContent(before, realizedItemRange, false)); stop = false; before--; } if (after < groupCount) { layoutPromises.push(layoutGroupContent(after, realizedItemRange, false)); stop = false; after++; } } return Promise.join(layoutPromises); }
javascript
{ "resource": "" }
q45915
updateIndicies
train
function updateIndicies(modifiedElements, cachedRecords) { var updatedCachedRecords = {}; for (var i = 0, len = modifiedElements.length; i < len; i++) { var modifiedElementLookup = modifiedElements[i]; var cachedRecord = cachedRecords[modifiedElementLookup.oldIndex]; if (cachedRecord) { updatedCachedRecords[modifiedElementLookup.newIndex] = cachedRecord; cachedRecord.element = modifiedElementLookup.element; delete cachedRecords[modifiedElementLookup.oldIndex]; } } var cachedRecordKeys = Object.keys(cachedRecords); for (var i = 0, len = cachedRecordKeys.length; i < len; i++) { var key = cachedRecordKeys[i], record = cachedRecords[key]; // We need to filter out containers which were removed from the DOM. If container's item // wasn't realized container can be removed without adding record to modifiedItems. if (!record.element || existingContainers[uniqueID(record.element)]) { updatedCachedRecords[key] = record; } } return updatedCachedRecords; }
javascript
{ "resource": "" }
q45916
assignGroupMarginsAndHeaders
train
function assignGroupMarginsAndHeaders(offset) { if (options.last) { // When looking for the *last* group, the *trailing* header and margin belong to the group. return offset - that._getHeaderSizeGroupAdjustment() - that._sizes.itemsContainerOuterStart; } else { // When looking for the *first* group, the *leading* header and margin belong to the group. // No need to make any adjustments to offset because the correct header and margin // already belong to the group. return offset; } }
javascript
{ "resource": "" }
q45917
_LayoutCommon_getGroupInfo
train
function _LayoutCommon_getGroupInfo(groupIndex) { var group = this._site.groupFromIndex(groupIndex), groupInfo = this._groupInfo, margins = this._sizes.containerMargins, adjustedInfo = { enableCellSpanning: false }; groupInfo = (typeof groupInfo === "function" ? groupInfo(group) : groupInfo); if (groupInfo) { if (groupInfo.enableCellSpanning && (+groupInfo.cellWidth !== groupInfo.cellWidth || +groupInfo.cellHeight !== groupInfo.cellHeight)) { throw new _ErrorFromName("WinJS.UI.GridLayout.GroupInfoResultIsInvalid", strings.groupInfoResultIsInvalid); } adjustedInfo = { enableCellSpanning: !!groupInfo.enableCellSpanning, cellWidth: groupInfo.cellWidth + margins.left + margins.right, cellHeight: groupInfo.cellHeight + margins.top + margins.bottom }; } return adjustedInfo; }
javascript
{ "resource": "" }
q45918
_LayoutCommon_getItemInfo
train
function _LayoutCommon_getItemInfo(itemIndex) { var result; if (!this._itemInfo || typeof this._itemInfo !== "function") { if (this._useDefaultItemInfo) { result = this._defaultItemInfo(itemIndex); } else { throw new _ErrorFromName("WinJS.UI.GridLayout.ItemInfoIsInvalid", strings.itemInfoIsInvalid); } } else { result = this._itemInfo(itemIndex); } return Promise.as(result).then(function (size) { if (!size || +size.width !== size.width || +size.height !== size.height) { throw new _ErrorFromName("WinJS.UI.GridLayout.ItemInfoIsInvalid", strings.itemInfoIsInvalid); } return size; }); }
javascript
{ "resource": "" }
q45919
_LayoutCommon_groupFromOffset
train
function _LayoutCommon_groupFromOffset(offset) { return offset < this._groups[0].offset ? 0 : this._groupFrom(function (group) { return offset < group.offset; }); }
javascript
{ "resource": "" }
q45920
_LayoutCommon_viewportSizeChanged
train
function _LayoutCommon_viewportSizeChanged(viewportContentSize) { var sizes = this._sizes; sizes.viewportContentSize = viewportContentSize; sizes.surfaceContentSize = viewportContentSize - sizes.surfaceOuterCrossSize; sizes.maxItemsContainerContentSize = sizes.surfaceContentSize - sizes.itemsContainerOuterCrossSize - this._getHeaderSizeContentAdjustment(); // This calculation is for uniform layouts if (sizes.containerSizeLoaded && !this._inListMode) { this._itemsPerBar = Math.floor(sizes.maxItemsContainerContentSize / sizes.containerCrossSize); if (this.maximumRowsOrColumns) { this._itemsPerBar = Math.min(this._itemsPerBar, this.maximumRowsOrColumns); } this._itemsPerBar = Math.max(1, this._itemsPerBar); } else { if (this._inListMode) { sizes[this._horizontal ? "containerHeight" : "containerWidth"] = sizes.maxItemsContainerContentSize; } this._itemsPerBar = 1; } // Ignore animations if height changed this._resetAnimationCaches(); }
javascript
{ "resource": "" }
q45921
_LayoutCommon_ensureContainerSize
train
function _LayoutCommon_ensureContainerSize(group) { var sizes = this._sizes; if (!sizes.containerSizeLoaded && !this._ensuringContainerSize) { var promise; if ((!this._itemInfo || typeof this._itemInfo !== "function") && this._useDefaultItemInfo) { var margins = sizes.containerMargins; promise = Promise.wrap({ width: group.groupInfo.cellWidth - margins.left - margins.right, height: group.groupInfo.cellHeight - margins.top - margins.bottom }); } else { promise = this._getItemInfo(); } var that = this; this._ensuringContainerSize = promise.then(function (itemSize) { sizes.containerSizeLoaded = true; sizes.containerWidth = itemSize.width + sizes.itemBoxOuterWidth + sizes.containerOuterWidth; sizes.containerHeight = itemSize.height + sizes.itemBoxOuterHeight + sizes.containerOuterHeight; if (!that._inListMode) { that._itemsPerBar = Math.floor(sizes.maxItemsContainerContentSize / sizes.containerCrossSize); if (that.maximumRowsOrColumns) { that._itemsPerBar = Math.min(that._itemsPerBar, that.maximumRowsOrColumns); } that._itemsPerBar = Math.max(1, that._itemsPerBar); } else { that._itemsPerBar = 1; } that._createContainerStyleRule(); }); promise.done( function () { that._ensuringContainerSize = null; }, function () { that._ensuringContainerSize = null; } ); return promise; } else { return this._ensuringContainerSize ? this._ensuringContainerSize : Promise.wrap(); } }
javascript
{ "resource": "" }
q45922
VirtualizeContentsView_updateAriaMarkers
train
function VirtualizeContentsView_updateAriaMarkers(listViewIsEmpty, firstIndexDisplayed, lastIndexDisplayed) { var that = this; if (this._listView._isZombie()) { return; } function getFirstVisibleItem() { return that.items.itemAt(firstIndexDisplayed); } // At a certain index, the VDS may return null for all items at that index and // higher. When this is the case, the end marker should point to the last // non-null item in the visible range. function getLastVisibleItem() { for (var i = lastIndexDisplayed; i >= firstIndexDisplayed; i--) { if (that.items.itemAt(i)) { return that.items.itemAt(i); } } return null; } this._listView._createAriaMarkers(); var startMarker = this._listView._ariaStartMarker, endMarker = this._listView._ariaEndMarker, firstVisibleItem, lastVisibleItem; if (firstIndexDisplayed !== -1 && lastIndexDisplayed !== -1 && firstIndexDisplayed <= lastIndexDisplayed) { firstVisibleItem = getFirstVisibleItem(); lastVisibleItem = getLastVisibleItem(); } if (listViewIsEmpty || !firstVisibleItem || !lastVisibleItem) { setFlow(startMarker, endMarker); this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1); } else { _ElementUtilities._ensureId(firstVisibleItem); _ElementUtilities._ensureId(lastVisibleItem); // Set startMarker's flowto if (this._listView._groupsEnabled()) { var groups = this._listView._groups, firstVisibleGroup = groups.group(groups.groupFromItem(firstIndexDisplayed)); if (firstVisibleGroup.header) { _ElementUtilities._ensureId(firstVisibleGroup.header); if (firstIndexDisplayed === firstVisibleGroup.startIndex) { _ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleGroup.header.id); } else { _ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id); } } } else { _ElementUtilities._setAttribute(startMarker, "aria-flowto", firstVisibleItem.id); } // Set endMarker's flowfrom _ElementUtilities._setAttribute(endMarker, "x-ms-aria-flowfrom", lastVisibleItem.id); } }
javascript
{ "resource": "" }
q45923
getLastVisibleItem
train
function getLastVisibleItem() { for (var i = lastIndexDisplayed; i >= firstIndexDisplayed; i--) { if (that.items.itemAt(i)) { return that.items.itemAt(i); } } return null; }
javascript
{ "resource": "" }
q45924
VirtualizeContentsView_updateAriaForAnnouncement
train
function VirtualizeContentsView_updateAriaForAnnouncement(item, count) { if (item === this._listView.header || item === this._listView.footer) { return; } var index = -1; var type = _UI.ObjectType.item; if (_ElementUtilities.hasClass(item, _Constants._headerClass)) { index = this._listView._groups.index(item); type = _UI.ObjectType.groupHeader; _ElementUtilities._setAttribute(item, "role", this._listView._headerRole); _ElementUtilities._setAttribute(item, "tabindex", this._listView._tabIndex); } else { index = this.items.index(item); _ElementUtilities._setAttribute(item, "aria-setsize", count); _ElementUtilities._setAttribute(item, "aria-posinset", index + 1); _ElementUtilities._setAttribute(item, "role", this._listView._itemRole); _ElementUtilities._setAttribute(item, "tabindex", this._listView._tabIndex); } if (type === _UI.ObjectType.groupHeader) { this._listView._fireAccessibilityAnnotationCompleteEvent(-1, -1, index, index); } else { this._listView._fireAccessibilityAnnotationCompleteEvent(index, index, -1, -1); } }
javascript
{ "resource": "" }
q45925
VirtualizeContentsView_createChunk
train
function VirtualizeContentsView_createChunk(groups, count, chunkSize) { var that = this; this._listView._writeProfilerMark("createChunk,StartTM"); function addToGroup(itemsContainer, groupSize) { var children = itemsContainer.element.children, oldSize = children.length, toAdd = Math.min(groupSize - itemsContainer.items.length, chunkSize); _SafeHtml.insertAdjacentHTMLUnsafe(itemsContainer.element, "beforeend", _Helpers._repeat("<div class='win-container win-backdrop'></div>", toAdd)); for (var i = 0; i < toAdd; i++) { var container = children[oldSize + i]; itemsContainer.items.push(container); that.containers.push(container); } } function newGroup(group) { var node = { header: that._listView._groupDataSource ? that._createHeaderContainer() : null, itemsContainer: { element: that._createItemsContainer(), items: [] } }; that.tree.push(node); that.keyToGroupIndex[group.key] = that.tree.length - 1; addToGroup(node.itemsContainer, group.size); } if (this.tree.length && this.tree.length <= groups.length) { var last = this.tree[this.tree.length - 1], finalSize = groups[this.tree.length - 1].size; // check if the last group in the tree already has all items. If not add items to this group if (last.itemsContainer.items.length < finalSize) { addToGroup(last.itemsContainer, finalSize); this._listView._writeProfilerMark("createChunk,StopTM"); return; } } if (this.tree.length < groups.length) { newGroup(groups[this.tree.length]); } this._listView._writeProfilerMark("createChunk,StopTM"); }
javascript
{ "resource": "" }
q45926
train
function (range, itemsCount) { range._lastKnownSizeOfData = itemsCount; // store this in order to make unions. if (!this._range) { this._range = range; } else { // Take the union of these two ranges. this._range.start = Math.min(this._range.start, range.start); // To accurately calculate the new unioned range 'end' value, we need to convert the current and new range end // positions into values that represent the remaining number of un-modified items in between the end of the range // and the end of the list of data. var previousUnmodifiedItemsFromEnd = (this._range._lastKnownSizeOfData - this._range.end); var newUnmodifiedItemsFromEnd = (range._lastKnownSizeOfData - range.end); var finalUnmodifiedItemsFromEnd = Math.min(previousUnmodifiedItemsFromEnd, newUnmodifiedItemsFromEnd); this._range._lastKnownSizeOfData = range._lastKnownSizeOfData; // Convert representation of the unioned end position back into a value which matches the above definition of _affecteRange.end this._range.end = this._range._lastKnownSizeOfData - finalUnmodifiedItemsFromEnd; } }
javascript
{ "resource": "" }
q45927
ListView_convertCoordinatesByCanvasMargins
train
function ListView_convertCoordinatesByCanvasMargins(coordinates, conversionCallback) { function fix(field, offset) { if (coordinates[field] !== undefined) { coordinates[field] = conversionCallback(coordinates[field], offset); } } var offset; if (this._horizontal()) { offset = this._getCanvasMargins()[this._rtl() ? "right" : "left"]; fix("left", offset); } else { offset = this._getCanvasMargins().top; fix("top", offset); } fix("begin", offset); fix("end", offset); return coordinates; }
javascript
{ "resource": "" }
q45928
ListView_getViewportSize
train
function ListView_getViewportSize() { if (this._viewportWidth === _Constants._UNINITIALIZED || this._viewportHeight === _Constants._UNINITIALIZED) { this._viewportWidth = Math.max(0, _ElementUtilities.getContentWidth(this._element)); this._viewportHeight = Math.max(0, _ElementUtilities.getContentHeight(this._element)); this._writeProfilerMark("viewportSizeDetected width:" + this._viewportWidth + " height:" + this._viewportHeight); this._previousWidth = this._element.offsetWidth; this._previousHeight = this._element.offsetHeight; } return { width: this._viewportWidth, height: this._viewportHeight }; }
javascript
{ "resource": "" }
q45929
ListView_updateSelection
train
function ListView_updateSelection() { var indices = this._selection.getIndices(), selectAll = this._selection.isEverything(), selectionMap = {}; if (!selectAll) { for (var i = 0, len = indices.length ; i < len; i++) { var index = indices[i]; selectionMap[index] = true; } } this._view.items.each(function (index, element, itemData) { if (itemData.itemBox) { var selected = selectAll || !!selectionMap[index]; _ItemEventsHandler._ItemEventsHandler.renderSelection(itemData.itemBox, element, selected, true); if (itemData.container) { _ElementUtilities[selected ? "addClass" : "removeClass"](itemData.container, _Constants._selectedClass); } } }); }
javascript
{ "resource": "" }
q45930
FlipView_inserted
train
function FlipView_inserted(itemPromise, previousHandle, nextHandle) { that._itemsManager._itemFromPromise(itemPromise).then(function (element) { var previous = that._itemsManager._elementFromHandle(previousHandle); var next = that._itemsManager._elementFromHandle(nextHandle); that._pageManager.inserted(element, previous, next, true); }); }
javascript
{ "resource": "" }
q45931
train
function (date1, date2) { return date1.getHours() === date2.getHours() && date1.getMinutes() === date2.getMinutes(); }
javascript
{ "resource": "" }
q45932
train
function (event) { this._lastKeyOrBlurEvent = this._currentKeyOrBlurEvent; switch (event.type) { case "keyup": if (event.keyCode === Key.shift) { this._currentKeyOrBlurEvent = null; } else { this._currentKeyOrBlurEvent = "keyboard"; } break; case "focusout": //anchor element no longer in focus, clear up the stack this._currentKeyOrBlurEvent = null; break; default: break; } }
javascript
{ "resource": "" }
q45933
train
function () { var rect = this._anchorElement.getBoundingClientRect(); return { x: rect.left, y: rect.top, width: rect.width, height: rect.height }; }
javascript
{ "resource": "" }
q45934
train
function () { this._closeTooltip(); var firePreviewChange = true; if (this._tentativeRating <= 0) { firePreviewChange = false; } else { if (this._tentativeRating > 0) { this._tentativeRating--; } else if (this._tentativeRating === -1) { if (this._userRating !== 0) { if (this._userRating > 0) { this._tentativeRating = this._userRating - 1; } else { this._tentativeRating = 0; } } else { this._tentativeRating = 0; } } if ((this._tentativeRating === 0) && !this._enableClear) { this._tentativeRating = 1; firePreviewChange = false; } } this._showTentativeRating(firePreviewChange, "keyboard"); }
javascript
{ "resource": "" }
q45935
train
function () { this._closeTooltip(); var firePreviewChange = true; if (this._tentativeRating < 0 || this._tentativeRating >= this._maxRating) { firePreviewChange = false; } if (this._tentativeRating !== -1) { if (this._tentativeRating < this._maxRating) { this._tentativeRating++; } } else { if (this._userRating !== 0) { if (this._userRating < this._maxRating) { this._tentativeRating = this._userRating + 1; } else { this._tentativeRating = this._maxRating; } } else { this._tentativeRating = 1; } } this._showTentativeRating(firePreviewChange, "keyboard"); }
javascript
{ "resource": "" }
q45936
filterOnScreen
train
function filterOnScreen(element) { var elementBoundingClientRect = element.getBoundingClientRect(); // Can't check left/right since it might be scrolled off. return elementBoundingClientRect.top < viewportBoundingClientRect.bottom && elementBoundingClientRect.bottom > viewportBoundingClientRect.top; }
javascript
{ "resource": "" }
q45937
_allOverlaysCallback
train
function _allOverlaysCallback(event, nameOfFunctionCall, stopImmediatePropagationWhenHandled) { var elements = _Global.document.querySelectorAll("." + _Constants.overlayClass); if (elements) { var len = elements.length; for (var i = 0; i < len; i++) { var element = elements[i]; var overlay = element.winControl; if (!overlay._disposed) { if (overlay) { var handled = overlay[nameOfFunctionCall](event); if (stopImmediatePropagationWhenHandled && handled) { // The caller has indicated we should exit as soon as the event is handled. return handled; } } } } } }
javascript
{ "resource": "" }
q45938
_Overlay_sendEvent
train
function _Overlay_sendEvent(eventName, detail) { if (this._disposed) { return; } var event = _Global.document.createEvent("CustomEvent"); event.initEvent(eventName, true, true, (detail || {})); this._element.dispatchEvent(event); }
javascript
{ "resource": "" }
q45939
_Overlay_showAndHideQueue
train
function _Overlay_showAndHideQueue() { // Only called if not currently animating. // We'll be done with the queued stuff when we return. this._queuedCommandAnimation = false; // Shortcut if hidden if (this.hidden) { this._showAndHideFast(this._queuedToShow, this._queuedToHide); // Might be something else to do Scheduler.schedule(this._checkDoNext, Scheduler.Priority.normal, this, "WinJS.UI._Overlay._checkDoNext"); } else { // Animation has 3 parts: "hiding", "showing", and "moving" // PVL has "addToList" and "deleteFromList", both of which allow moving parts. // So we'll set up "add" for showing, and use "delete" for "hiding" + moving, // then trigger both at the same time. var showCommands = this._queuedToShow; var hideCommands = this._queuedToHide; var siblings = this._findSiblings(showCommands.concat(hideCommands)); // Filter out the commands queued for animation that don't need to be animated. var count; for (count = 0; count < showCommands.length; count++) { // If this one's not real or not attached, skip it if (!showCommands[count] || !showCommands[count].style || !_Global.document.body.contains(showCommands[count])) { // Not real, skip it showCommands.splice(count, 1); count--; } else if (showCommands[count].style.visibility !== "hidden" && showCommands[count].style.opacity !== "0") { // Don't need to animate showing this one, already visible, so now it's a sibling siblings.push(showCommands[count]); showCommands.splice(count, 1); count--; } } for (count = 0; count < hideCommands.length; count++) { // If this one's not real or not attached, skip it if (!hideCommands[count] || !hideCommands[count].style || !_Global.document.body.contains(hideCommands[count]) || hideCommands[count].style.visibility === "hidden" || hideCommands[count].style.opacity === "0") { // Don't need to animate hiding this one, not real, or it's hidden, // so don't even need it as a sibling. hideCommands.splice(count, 1); count--; } } // Start command animations. var commandsAnimationPromise = this._baseBeginAnimateCommands(showCommands, hideCommands, siblings); // Hook end animations var that = this; if (commandsAnimationPromise) { // Needed to animate commandsAnimationPromise.done( function () { that._baseEndAnimateCommands(hideCommands); }, function () { that._baseEndAnimateCommands(hideCommands); } ); } else { // Already positioned correctly Scheduler.schedule(function Overlay_async_baseEndAnimationCommands() { that._baseEndAnimateCommands([]); }, Scheduler.Priority.normal, null, "WinJS.UI._Overlay._endAnimateCommandsWithoutAnimation"); } } // Done, clear queues this._queuedToShow = []; this._queuedToHide = []; }
javascript
{ "resource": "" }
q45940
_Overlay_resolveCommands
train
function _Overlay_resolveCommands(commands) { // First make sure they're all DOM elements. commands = _resolveElements(commands); // Now make sure they're all in this container var result = {}; result.commands = []; result.others = []; var allCommands = this.element.querySelectorAll(".win-command"); var countAll, countIn; for (countAll = 0; countAll < allCommands.length; countAll++) { var found = false; for (countIn = 0; countIn < commands.length; countIn++) { if (commands[countIn] === allCommands[countAll]) { result.commands.push(allCommands[countAll]); commands.splice(countIn, 1); found = true; break; } } if (!found) { result.others.push(allCommands[countAll]); } } return result; }
javascript
{ "resource": "" }
q45941
_Overlay_findSiblings
train
function _Overlay_findSiblings(commands) { // Now make sure they're all in this container var siblings = []; var allCommands = this.element.querySelectorAll(".win-command"); var countAll, countIn; for (countAll = 0; countAll < allCommands.length; countAll++) { var found = false; for (countIn = 0; countIn < commands.length; countIn++) { if (commands[countIn] === allCommands[countAll]) { commands.splice(countIn, 1); found = true; break; } } if (!found) { siblings.push(allCommands[countAll]); } } return siblings; }
javascript
{ "resource": "" }
q45942
_Overlay_focusOnLastFocusableElement
train
function _Overlay_focusOnLastFocusableElement() { if (this._element.firstElementChild) { var oldFirstTabIndex = this._element.firstElementChild.tabIndex; var oldLastTabIndex = this._element.lastElementChild.tabIndex; this._element.firstElementChild.tabIndex = -1; this._element.lastElementChild.tabIndex = -1; var tabResult = _ElementUtilities._focusLastFocusableElement(this._element); if (tabResult) { _Overlay._trySelect(_Global.document.activeElement); } this._element.firstElementChild.tabIndex = oldFirstTabIndex; this._element.lastElementChild.tabIndex = oldLastTabIndex; return tabResult; } else { return false; } }
javascript
{ "resource": "" }
q45943
_Overlay__focusOnFirstFocusableElement
train
function _Overlay__focusOnFirstFocusableElement(useSetActive, scroller) { if (this._element.firstElementChild) { var oldFirstTabIndex = this._element.firstElementChild.tabIndex; var oldLastTabIndex = this._element.lastElementChild.tabIndex; this._element.firstElementChild.tabIndex = -1; this._element.lastElementChild.tabIndex = -1; var tabResult = _ElementUtilities._focusFirstFocusableElement(this._element, useSetActive, scroller); if (tabResult) { _Overlay._trySelect(_Global.document.activeElement); } this._element.firstElementChild.tabIndex = oldFirstTabIndex; this._element.lastElementChild.tabIndex = oldLastTabIndex; return tabResult; } else { return false; } }
javascript
{ "resource": "" }
q45944
train
function (element, scroller) { if (!element || !_Global.document.body || !_Global.document.body.contains(element)) { return false; } if (!_ElementUtilities._setActive(element, scroller)) { return false; } return (element === _Global.document.activeElement); }
javascript
{ "resource": "" }
q45945
_LightDismissableLayer_hiding
train
function _LightDismissableLayer_hiding(client /*: ILightDismissable */) { var index = this._clients.indexOf(client); if (index !== -1) { this._clients[index]._focusable = false; this._activateTopFocusableClientIfNeeded(); } }
javascript
{ "resource": "" }
q45946
fitsVerticallyWithCenteredAnchor
train
function fitsVerticallyWithCenteredAnchor(anchorBorderBox, flyoutMeasurements) { // Returns true if the flyout would always fit at least top // or bottom of its anchor, regardless of the position of the anchor, // as long as the anchor never changed its height, nor did the height of // the visualViewport change. return ((_Overlay._Overlay._keyboardInfo._visibleDocHeight - anchorBorderBox.height) / 2) >= flyoutMeasurements.totalHeight; }
javascript
{ "resource": "" }
q45947
fitTop
train
function fitTop(bottomConstraint, flyoutMeasurements) { nextTop = bottomConstraint - flyoutMeasurements.totalHeight; nextAnimOffset = AnimationOffsets.top; return (nextTop >= _Overlay._Overlay._keyboardInfo._visibleDocTop && nextTop + flyoutMeasurements.totalHeight <= _Overlay._Overlay._keyboardInfo._visibleDocBottom); }
javascript
{ "resource": "" }
q45948
Flyout_ensurePosition
train
function Flyout_ensurePosition() { this._keyboardMovedUs = false; // Remove old height restrictions and scrolling. this._clearAdjustedStyles(); this._setAlignment(); // Set up the new position, and prep the offset for showPopup. var flyoutMeasurements = measureElement(this._element); var isRtl = _ElementUtilities._getComputedStyle(this._element).direction === "rtl"; this._currentPosition = this._positionRequest.getTopLeft(flyoutMeasurements, isRtl); // Adjust position if (this._currentPosition.top < 0) { // Overran bottom, attach to bottom. this._element.style.bottom = _Overlay._Overlay._keyboardInfo._visibleDocBottomOffset + "px"; this._element.style.top = "auto"; } else { // Normal, set top this._element.style.top = this._currentPosition.top + "px"; this._element.style.bottom = "auto"; } if (this._currentPosition.left < 0) { // Overran right, attach to right this._element.style.right = "0px"; this._element.style.left = "auto"; } else { // Normal, set left this._element.style.left = this._currentPosition.left + "px"; this._element.style.right = "auto"; } // Adjust height/scrollbar if (this._currentPosition.doesScroll) { _ElementUtilities.addClass(this._element, _Constants.scrollsClass); this._lastMaxHeight = this._element.style.maxHeight; this._element.style.maxHeight = this._currentPosition.contentHeight + "px"; } // May need to adjust if the IHM is showing. if (_Overlay._Overlay._keyboardInfo._visible) { // Use keyboard logic this._checkKeyboardFit(); if (this._keyboardMovedUs) { this._adjustForKeyboard(); } } }
javascript
{ "resource": "" }
q45949
Flyout_checkKeyboardFit
train
function Flyout_checkKeyboardFit() { // Special Flyout positioning rules to determine if the Flyout needs to adjust its // position because of the IHM. If the Flyout needs to adjust for the IHM, it will reposition // itself to be pinned to either the top or bottom edge of the visual viewport. // - Too Tall, above top, or below bottom. var keyboardMovedUs = false; var viewportHeight = _Overlay._Overlay._keyboardInfo._visibleDocHeight; var adjustedMarginBoxHeight = this._currentPosition.contentHeight + this._currentPosition.verticalMarginBorderPadding; if (adjustedMarginBoxHeight > viewportHeight) { // The Flyout is now too tall to fit in the viewport, pin to top and adjust height. keyboardMovedUs = true; this._currentPosition.top = _Constants.pinToBottomEdge; this._currentPosition.contentHeight = viewportHeight - this._currentPosition.verticalMarginBorderPadding; this._currentPosition.doesScroll = true; } else if (this._currentPosition.top >= 0 && this._currentPosition.top + adjustedMarginBoxHeight > _Overlay._Overlay._keyboardInfo._visibleDocBottom) { // Flyout clips the bottom of the viewport. Pin to bottom. this._currentPosition.top = _Constants.pinToBottomEdge; keyboardMovedUs = true; } else if (this._currentPosition.top === _Constants.pinToBottomEdge) { // We were already pinned to the bottom, so our position on screen will change keyboardMovedUs = true; } // Signals use of basic fadein animation this._keyboardMovedUs = keyboardMovedUs; }
javascript
{ "resource": "" }
q45950
Flyout_flyoutAnimateIn
train
function Flyout_flyoutAnimateIn() { if (this._keyboardMovedUs) { return this._baseAnimateIn(); } else { this._element.style.opacity = 1; this._element.style.visibility = "visible"; return Animations.showPopup(this._element, (typeof this._currentPosition !== 'undefined') ? this._currentPosition.animOffset : 0); } }
javascript
{ "resource": "" }
q45951
Flyout_hideAllOtherFlyouts
train
function Flyout_hideAllOtherFlyouts(thisFlyout) { var flyouts = _Global.document.querySelectorAll("." + _Constants.flyoutClass); for (var i = 0; i < flyouts.length; i++) { var flyoutControl = flyouts[i].winControl; if (flyoutControl && !flyoutControl.hidden && (flyoutControl !== thisFlyout)) { flyoutControl.hide(); } } }
javascript
{ "resource": "" }
q45952
Flyout_addFirstDiv
train
function Flyout_addFirstDiv() { var firstDiv = _Global.document.createElement("div"); firstDiv.className = _Constants.firstDivClass; firstDiv.style.display = "inline"; firstDiv.setAttribute("role", "menuitem"); firstDiv.setAttribute("aria-hidden", "true"); // add to beginning if (this._element.children[0]) { this._element.insertBefore(firstDiv, this._element.children[0]); } else { this._element.appendChild(firstDiv); } var that = this; _ElementUtilities._addEventListener(firstDiv, "focusin", function () { that._focusOnLastFocusableElementOrThis(); }, false); return firstDiv; }
javascript
{ "resource": "" }
q45953
Flyout_addFinalDiv
train
function Flyout_addFinalDiv() { var finalDiv = _Global.document.createElement("div"); finalDiv.className = _Constants.finalDivClass; finalDiv.style.display = "inline"; finalDiv.setAttribute("role", "menuitem"); finalDiv.setAttribute("aria-hidden", "true"); this._element.appendChild(finalDiv); var that = this; _ElementUtilities._addEventListener(finalDiv, "focusin", function () { that._focusOnFirstFocusableElementOrThis(); }, false); return finalDiv; }
javascript
{ "resource": "" }
q45954
_LegacyAppBar_setFocusToAppBar
train
function _LegacyAppBar_setFocusToAppBar(useSetActive, scroller) { if (!this._focusOnFirstFocusableElement(useSetActive, scroller)) { // No first element, set it to appbar itself _Overlay._Overlay._trySetActive(this._element, scroller); } }
javascript
{ "resource": "" }
q45955
_LegacyAppBar_updateFirstAndFinalDiv
train
function _LegacyAppBar_updateFirstAndFinalDiv() { var appBarFirstDiv = this._element.querySelectorAll("." + _Constants.firstDivClass); appBarFirstDiv = appBarFirstDiv.length >= 1 ? appBarFirstDiv[0] : null; var appBarFinalDiv = this._element.querySelectorAll("." + _Constants.finalDivClass); appBarFinalDiv = appBarFinalDiv.length >= 1 ? appBarFinalDiv[0] : null; // Remove the firstDiv & finalDiv if they are not at the appropriate locations if (appBarFirstDiv && (this._element.children[0] !== appBarFirstDiv)) { appBarFirstDiv.parentNode.removeChild(appBarFirstDiv); appBarFirstDiv = null; } if (appBarFinalDiv && (this._element.children[this._element.children.length - 1] !== appBarFinalDiv)) { appBarFinalDiv.parentNode.removeChild(appBarFinalDiv); appBarFinalDiv = null; } // Create and add the firstDiv & finalDiv if they don't already exist if (!appBarFirstDiv) { // Add a firstDiv that will be the first child of the appBar. // On focus set focus to the last element of the AppBar. appBarFirstDiv = _Global.document.createElement("div"); // display: inline is needed so that the div doesn't take up space and cause the page to scroll on focus appBarFirstDiv.style.display = "inline"; appBarFirstDiv.className = _Constants.firstDivClass; appBarFirstDiv.tabIndex = -1; appBarFirstDiv.setAttribute("aria-hidden", "true"); _ElementUtilities._addEventListener(appBarFirstDiv, "focusin", this._focusOnLastFocusableElementOrThis.bind(this), false); // add to beginning if (this._element.children[0]) { this._element.insertBefore(appBarFirstDiv, this._element.children[0]); } else { this._element.appendChild(appBarFirstDiv); } } if (!appBarFinalDiv) { // Add a finalDiv that will be the last child of the appBar. // On focus set focus to the first element of the AppBar. appBarFinalDiv = _Global.document.createElement("div"); // display: inline is needed so that the div doesn't take up space and cause the page to scroll on focus appBarFinalDiv.style.display = "inline"; appBarFinalDiv.className = _Constants.finalDivClass; appBarFinalDiv.tabIndex = -1; appBarFinalDiv.setAttribute("aria-hidden", "true"); _ElementUtilities._addEventListener(appBarFinalDiv, "focusin", this._focusOnFirstFocusableElementOrThis.bind(this), false); this._element.appendChild(appBarFinalDiv); } // invokeButton should be the second to last element in the _LegacyAppBar's tab order. Second to the finalDiv. if (this._element.children[this._element.children.length - 2] !== this._invokeButton) { this._element.insertBefore(this._invokeButton, appBarFinalDiv); } var elms = this._element.getElementsByTagName("*"); var highestTabIndex = _ElementUtilities._getHighestTabIndexInList(elms); this._invokeButton.tabIndex = highestTabIndex; // Update the tabIndex of the firstDiv & finalDiv if (appBarFirstDiv) { appBarFirstDiv.tabIndex = _ElementUtilities._getLowestTabIndexInList(elms); } if (appBarFinalDiv) { appBarFinalDiv.tabIndex = highestTabIndex; } }
javascript
{ "resource": "" }
q45956
createQueryLinguisticDetails
train
function createQueryLinguisticDetails(compositionAlternatives, compositionStartOffset, compositionLength, queryTextPrefix, queryTextSuffix) { var linguisticDetails = null; // The linguistic alternatives we receive are only for the composition string being composed. We need to provide the linguistic alternatives // in the form of the full query text with alternatives embedded. var fullCompositionAlternatives = []; for (var i = 0; i < compositionAlternatives.length; i++) { fullCompositionAlternatives[i] = queryTextPrefix + compositionAlternatives[i] + queryTextSuffix; } if (_WinRT.Windows.ApplicationModel.Search.SearchQueryLinguisticDetails) { try { linguisticDetails = new _WinRT.Windows.ApplicationModel.Search.SearchQueryLinguisticDetails(fullCompositionAlternatives, compositionStartOffset, compositionLength); } catch (e) { // WP10 currently exposes SQLD API but throws on instantiation. } } if (!linguisticDetails) { // If we're in web compartment, create a script version of the WinRT SearchQueryLinguisticDetails object linguisticDetails = { queryTextAlternatives: fullCompositionAlternatives, queryTextCompositionStart: compositionStartOffset, queryTextCompositionLength: compositionLength }; } return linguisticDetails; }
javascript
{ "resource": "" }
q45957
SearchBox_requestingFocusOnKeyboardInputHandler
train
function SearchBox_requestingFocusOnKeyboardInputHandler() { this._fireEvent(EventName.receivingfocusonkeyboardinput, null); if (_Global.document.activeElement !== this._inputElement) { try { this._inputElement.focus(); } catch (e) { } } }
javascript
{ "resource": "" }
q45958
_getChildSettingsControl
train
function _getChildSettingsControl(parentElement, id) { var settingElements = parentElement.querySelectorAll("." + _Constants.settingsFlyoutClass); var retValue, control; for (var i = 0; i < settingElements.length; i++) { control = settingElements[i].winControl; if (control) { if (control.settingsCommandId === id) { retValue = control; break; } if (settingElements[i].id === id) { retValue = retValue || control; } } } return retValue; }
javascript
{ "resource": "" }
q45959
SettingsFlyout_addFirstDiv
train
function SettingsFlyout_addFirstDiv() { var _elms = this._element.getElementsByTagName("*"); var _minTab = 0; for (var i = 0; i < _elms.length; i++) { if ((0 < _elms[i].tabIndex) && (_minTab === 0 || _elms[i].tabIndex < _minTab)) { _minTab = _elms[i].tabIndex; } } var firstDiv = _Global.document.createElement("div"); firstDiv.className = _Constants.firstDivClass; firstDiv.style.display = "inline"; firstDiv.setAttribute("role", "menuitem"); firstDiv.setAttribute("aria-hidden", "true"); firstDiv.tabIndex = _minTab; _ElementUtilities._addEventListener(firstDiv, "focusin", this._focusOnLastFocusableElementFromParent, false); // add to beginning if (this._element.children[0]) { this._element.insertBefore(firstDiv, this._element.children[0]); } else { this._element.appendChild(firstDiv); } }
javascript
{ "resource": "" }
q45960
SettingsFlyout_addFinalDiv
train
function SettingsFlyout_addFinalDiv() { var _elms = this._element.getElementsByTagName("*"); var _maxTab = 0; for (var i = 0; i < _elms.length; i++) { if (_elms[i].tabIndex > _maxTab) { _maxTab = _elms[i].tabIndex; } } var finalDiv = _Global.document.createElement("div"); finalDiv.className = _Constants.finalDivClass; finalDiv.style.display = "inline"; finalDiv.setAttribute("role", "menuitem"); finalDiv.setAttribute("aria-hidden", "true"); finalDiv.tabIndex = _maxTab; _ElementUtilities._addEventListener(finalDiv, "focusin", this._focusOnFirstFocusableElementFromParent, false); this._element.appendChild(finalDiv); }
javascript
{ "resource": "" }
q45961
ContentDialog_setState
train
function ContentDialog_setState(NewState, arg0) { if (!this._disposed) { this._state && this._state.exit(); this._state = new NewState(); this._state.dialog = this; this._state.enter(arg0); } }
javascript
{ "resource": "" }
q45962
ContentDialog_renderForInputPane
train
function ContentDialog_renderForInputPane() { var rendered = this._rendered; if (!rendered.registeredForResize) { _ElementUtilities._resizeNotifier.subscribe(this._dom.root, this._onUpdateInputPaneRenderingBound); rendered.registeredForResize = true; } if (this._shouldResizeForInputPane()) { // Lay the dialog out using its normal rules but restrict it to the *visible document* // rather than the *visual viewport*. // Essentially, the dialog should be in the center of the part of the app that the user // can see regardless of the state of the input pane. var top = _KeyboardInfo._KeyboardInfo._visibleDocTop + "px"; var bottom = _KeyboardInfo._KeyboardInfo._visibleDocBottomOffset + "px"; if (rendered.top !== top) { this._dom.root.style.top = top; rendered.top = top; } if (rendered.bottom !== bottom) { this._dom.root.style.bottom = bottom; rendered.bottom = bottom; } if (!rendered.resizedForInputPane) { // Put title into scroller so there's more screen real estate for the content this._dom.scroller.insertBefore(this._dom.title, this._dom.content); this._dom.root.style.height = "auto"; // Height will be determined by setting top & bottom // Ensure activeElement is scrolled into view var activeElement = _Global.document.activeElement; if (activeElement && this._dom.scroller.contains(activeElement)) { activeElement.scrollIntoView(); } rendered.resizedForInputPane = true; } } }
javascript
{ "resource": "" }
q45963
train
function (requestIndex, countBefore, countAfter) { if (requestIndex >= pages.length) return WinJS.Promise.wrapError( new WinJS.ErrorFromName( WinJS.UI.FetchError.doesNotExist)); // countBefore = Math.min(ctrl.options.pagesToLoad, // countBefore); // countAfter = Math.min(ctrl.options.pagesToLoad, // countAfter); var results = []; var fetchIndex = Math.max( requestIndex - countBefore, 0); var lastFetchIndex = Math.min( requestIndex + countAfter, pages.length - 1); pages[requestIndex].triggerLoad(); // trigger image generator on requested page first for (var i = fetchIndex; i <= lastFetchIndex; i++) { /** * @type Page */ var page = pages[i]; //page.triggerLoad(); // trigger image generator on requested pages results.push( {key: i.toString(), data: page}); } pdfViewer.setFocusedPageIndex(requestIndex); // implements IFetchResult return WinJS.Promise.wrap({ absoluteIndex: requestIndex, items: results, // The array of items. offset: requestIndex - fetchIndex, // The index of the requested item in the items array. totalCount: pages.length, // The total number of records. This is equal to total number of pages in a PDF file , atStart: fetchIndex === 0, atEnd: fetchIndex === pages.length - 1 }); }
javascript
{ "resource": "" }
q45964
getElementRoot
train
function getElementRoot(element) { var curr = element; while (curr.parentNode) { curr = curr.parentNode; } return curr; }
javascript
{ "resource": "" }
q45965
syllable
train
function syllable(value) { var count = 0 var index var length var singular var parts var addOne var subtractOne if (value.length === 0) { return count } // Return early when possible. if (value.length < 3) { return 1 } // If `value` is a hard to count, it might be in `problematic`. if (own.call(problematic, value)) { return problematic[value] } // Additionally, the singular word might be in `problematic`. singular = pluralize(value, 1) if (own.call(problematic, singular)) { return problematic[singular] } addOne = returnFactory(1) subtractOne = returnFactory(-1) // Count some prefixes and suffixes, and remove their matched ranges. value = value .replace(EXPRESSION_TRIPLE, countFactory(3)) .replace(EXPRESSION_DOUBLE, countFactory(2)) .replace(EXPRESSION_SINGLE, countFactory(1)) // Count multiple consonants. parts = value.split(/[^aeiouy]+/) index = -1 length = parts.length while (++index < length) { if (parts[index] !== '') { count++ } } // Subtract one for occurrences which should be counted as one (but are // counted as two). value .replace(EXPRESSION_MONOSYLLABIC_ONE, subtractOne) .replace(EXPRESSION_MONOSYLLABIC_TWO, subtractOne) // Add one for occurrences which should be counted as two (but are counted as // one). value .replace(EXPRESSION_DOUBLE_SYLLABIC_ONE, addOne) .replace(EXPRESSION_DOUBLE_SYLLABIC_TWO, addOne) .replace(EXPRESSION_DOUBLE_SYLLABIC_THREE, addOne) .replace(EXPRESSION_DOUBLE_SYLLABIC_FOUR, addOne) // Make sure at least on is returned. return count || 1 // Define scoped counters, to be used in `String#replace()` calls. // The scoped counter removes the matched value from the input. function countFactory(addition) { return counter function counter() { count += addition return '' } } // Define scoped counters, to be used in `String#replace()` calls. // The scoped counter does not remove the matched value from the input. function returnFactory(addition) { return returner function returner($0) { count += addition return $0 } } }
javascript
{ "resource": "" }
q45966
train
function(claims, callback){ if(typeof claims === "function" && !callback){ callback = claims; claims = {}; } var self = this, sid = uuid.v4(); var token = jwt.sign(_.extend({ jti: sid }, claims || {}), options.secret, { algorithm: options.algorithm }); options.client.setex(options.keyspace + sid, options.maxAge, JSON.stringify(serializeSession(self)), function(error){ self.id = sid; callback(error, token); }); }
javascript
{ "resource": "" }
q45967
train
function(callback){ if(!this.id){ return process.nextTick(function(){ callback(new Error("Invalid session ID")); }); } options.client.expire(options.keyspace + this.id, options.maxAge, callback); }
javascript
{ "resource": "" }
q45968
train
function(callback){ if(!this.id){ return process.nextTick(function(){ callback(new Error("Invalid session ID")); }); } options.client.setex(options.keyspace + this.id, options.maxAge, JSON.stringify(serializeSession(this)), callback); }
javascript
{ "resource": "" }
q45969
train
function(callback){ var self = this; if(!this.id){ return process.nextTick(function(){ callback(new Error("Invalid session ID")); }); } options.client.get(options.keyspace + self.id, function(error, resp){ if(error) return callback(error); try{ resp = JSON.parse(resp); }catch(e){ return callback(e); } extendSession(self, resp); callback(); }); }
javascript
{ "resource": "" }
q45970
train
function(callback){ if(!this.id){ return process.nextTick(function(){ callback(new Error("Invalid session ID")); }); } options.client.del(options.keyspace + this.id, callback); }
javascript
{ "resource": "" }
q45971
Gaze
train
function Gaze (patterns, opts, done) { EE.call(this); // If second arg is the callback if (typeof opts === 'function') { done = opts; opts = {}; } // Default options opts = opts || {}; opts.mark = true; opts.interval = opts.interval || 100; opts.debounceDelay = opts.debounceDelay || 500; opts.cwd = opts.cwd || process.cwd(); this.options = opts; // Default done callback done = done || emptyFunction; // Remember our watched dir:files this._watched = Object.create(null); // Store watchers this._watchers = Object.create(null); // Store watchFile listeners this._pollers = Object.create(null); // Store patterns this._patterns = []; // Cached events for debouncing this._cached = Object.create(null); // Set maxListeners if (this.options.maxListeners != null) { this.setMaxListeners(this.options.maxListeners); delete this.options.maxListeners; } // Initialize the watch on files if (patterns) { this.add(patterns, done); } // keep the process alive this._keepalive = setInterval(emptyFunction, 200); return this; }
javascript
{ "resource": "" }
q45972
LintDirtyModulesPlugin
train
function LintDirtyModulesPlugin(compiler, options) { this.startTime = Date.now(); this.prevTimestamps = {}; this.isFirstRun = true; this.compiler = compiler; this.options = options; // bind(this) is here to prevent context overriding by webpack compiler.plugin('emit', this.lint.bind(this)); }
javascript
{ "resource": "" }
q45973
getArticle
train
function getArticle (candidates, $) { let topCandidate = null candidates.forEach(elem => { const linkDensity = getLinkDensity(elem, $) const siblings = elem.children('p').length const score = elem.data('readabilityScore') elem.data( 'readabilityScore', Math.min(2, Math.max(siblings, 1)) * score * (1 - linkDensity) ) if ( !topCandidate || elem.data('readabilityScore') > topCandidate.data('readabilityScore') ) { topCandidate = elem } }) /** * If we still have no top candidate, just use the body as a last resort. * Should not happen. * */ if (topCandidate === null) { return $('body') } // Perhaps the topCandidate is the parent? let parent if ( !(parent = topCandidate.parent()) || parent.length === 0 || topCandidate.children('p').length > 5 ) { return filterCandidates(topCandidate, topCandidate.children(), $) } return filterCandidates(topCandidate, parent.children(), $) }
javascript
{ "resource": "" }
q45974
scoreCandidate
train
function scoreCandidate (node, contentScore, candidates) { let score if (typeof node.data('readabilityScore') === 'undefined') { score = initializeNode(node) candidates.push(node) } else { score = node.data('readabilityScore') || 0 } node.data('readabilityScore', score + contentScore) }
javascript
{ "resource": "" }
q45975
initializeNode
train
function initializeNode (node) { if (!node || node.length === 0) { return 0 } const tag = node.get(0).name if (nodeTypes.mostPositive.indexOf(tag) >= 0) { return 5 + getClassWeight(node) } if (nodeTypes.positive.indexOf(tag) >= 0) { return 3 + getClassWeight(node) } if (nodeTypes.negative.indexOf(tag) >= 0) { return -3 + getClassWeight(node) } if (nodeTypes.mostNegative.indexOf(tag) >= 0) { return -5 + getClassWeight(node) } return -1 }
javascript
{ "resource": "" }
q45976
getClassWeight
train
function getClassWeight (node) { if (node === null || node.length === 0) { return 0 } const name = node.get(0).name || '' const cls = node.attr('class') || '' const nid = node.attr('id') || '' let weight = 0 // Schema.org/Article if (node.attr('itemprop') && /articleBody/.test(node.attr('itemprop'))) { weight += 50 } // Nodes of type text if (node.attr('type') && node.attr('type') === 'text') { weight += 30 } // Special cases if (name === 'article') { weight += 25 } if (name === 'section') { weight += 10 } if (name === 'header' || name === 'aside' || name === 'footer') { weight -= 25 } if (cls === 'comments' && nid === 'comments') { weight -= 25 } if (cls.search(regexps.negativeRe) !== -1) { weight -= 25 } if (nid.search(regexps.negativeRe) !== -1) { weight -= 20 } if (cls.search(regexps.positiveRe) !== -1) { weight += 25 } if (nid.search(regexps.positiveRe) !== -1) { weight += 20 } return weight }
javascript
{ "resource": "" }
q45977
getLinkDensity
train
function getLinkDensity (node, $) { const links = node.find('a') const textLength = node.text().length let linkLength = 0 links.each(function (index, elem) { const href = $(this).attr('href') if (!href || (href.length > 0 && href[0] === '#')) { return } linkLength += $(this).text().length }) return linkLength / textLength || 0 }
javascript
{ "resource": "" }
q45978
extract
train
function extract ($, base) { const candidates = getCandidates($, base) let article = getArticle(candidates, $) if (article.length < 1) { article = getArticle([$('body')], $) } return article }
javascript
{ "resource": "" }
q45979
scrapeMetadata
train
function scrapeMetadata (html, rules) { rules = rules || RULES const keys = Object.keys(rules) const $ = cheerio.load(html) const promises = keys.map(function (key) { return scrapeMetadatum($, '', rules[key]) }) return Promise.all(promises).then(function (values) { return keys.reduce(function (memo, key, i) { memo[key] = values[i] return memo }, {}) }) }
javascript
{ "resource": "" }
q45980
scrapeMetadatum
train
function scrapeMetadatum ($, url, rules) { if (!Array.isArray(rules)) rules = [rules] return rules.reduce(function (promise, rule) { return promise.then(function (value) { if (value != null && value !== '') return value var next = rule($, url) if (next != null && next !== '') return next return null }) }, Promise.resolve()) }
javascript
{ "resource": "" }
q45981
AttemptRootSymlink
train
function AttemptRootSymlink() { if (process.platform === 'win32') { var curPath = resolve("./"); if (debugging) { console.log("RootSymlink Base path is", curPath); } cp.execSync("powershell -Command \"Start-Process 'node' -ArgumentList '"+curPath+"/install.js symlink' -verb runas\""); } else { console.log("To automatically create a SymLink between your web app and NativeScript, we need root for a second."); cp.execSync("sudo "+process.argv[0] + " " + process.argv[1] +" symlink"); } }
javascript
{ "resource": "" }
q45982
createRootSymLink
train
function createRootSymLink() { var li1 = process.argv[1].lastIndexOf('\\'), li2 = process.argv[1].lastIndexOf('/'); if (li2 > li1) { li1 = li2; } var AppPath = process.argv[1].substring(0,li1); var p1 = resolve(AppPath + "/" + nativescriptAppPath); var p2 = resolve(AppPath + "/" + webAppPath); if (debugging) { console.log("Path: ", p1, p2); } fs.symlinkSync(p2, p1, 'junction'); }
javascript
{ "resource": "" }
q45983
pagedGet
train
function pagedGet ({source, method, skip = 0, aggregatedResponse = null, query = null}) { const fullQuery = Object.assign({}, { skip: skip, limit: pageLimit, order: 'sys.createdAt,sys.id' }, query ) return source[method](fullQuery) .then((response) => { if (!aggregatedResponse) { aggregatedResponse = response } else { aggregatedResponse.items = aggregatedResponse.items.concat(response.items) } const page = Math.ceil(skip / pageLimit) + 1 const pages = Math.ceil(response.total / pageLimit) logEmitter.emit('info', `Fetched ${aggregatedResponse.items.length} of ${response.total} items (Page ${page}/${pages})`) if (skip + pageLimit <= response.total) { return pagedGet({source, method, skip: skip + pageLimit, aggregatedResponse, query}) } return aggregatedResponse }) }
javascript
{ "resource": "" }
q45984
parseObj
train
function parseObj (input) { try { return require(path.resolve(input)); } catch (e) { var str; try { str = fs.readFileSync(program.obj, 'utf8'); } catch (e) { str = program.obj; } try { return JSON.parse(str); } catch (e) { return eval('(' + str + ')'); } } }
javascript
{ "resource": "" }
q45985
watchFile
train
function watchFile(path, base, rootPath) { path = normalize(path); var log = ' ' + chalk.gray('watching') + ' ' + chalk.cyan(path); if (!base) { base = path; } else { base = normalize(base); log += '\n ' + chalk.gray('as a dependency of') + ' '; log += chalk.cyan(base); } if (watchList[path]) { if (watchList[path].indexOf(base) !== -1) return; consoleLog(log); watchList[path].push(base); return; } consoleLog(log); watchList[path] = [base]; fs.watchFile(path, {persistent: true, interval: 200}, function (curr, prev) { // File doesn't exist anymore. Keep watching. if (curr.mtime.getTime() === 0) return; // istanbul ignore if if (curr.mtime.getTime() === prev.mtime.getTime()) return; watchList[path].forEach(function(file) { tryRender(file, rootPath); }); }); }
javascript
{ "resource": "" }
q45986
tryRender
train
function tryRender(path, rootPath) { try { renderFile(path, rootPath); } catch (e) { // keep watching when error occured. console.error(errorToString(e) + '\x07'); } }
javascript
{ "resource": "" }
q45987
stdin
train
function stdin() { var buf = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', function(chunk){ buf += chunk; }); process.stdin.on('end', function(){ var output; if (options.client) { output = pug.compileClient(buf, options); } else { var fn = pug.compile(buf, options); var output = fn(options); } process.stdout.write(output); }).resume(); }
javascript
{ "resource": "" }
q45988
renderFile
train
function renderFile(path, rootPath) { var isPug = /\.(?:pug|jade)$/; var isIgnored = /([\/\\]_)|(^_)/; var stat = fs.lstatSync(path); // Found pug file if (stat.isFile() && isPug.test(path) && !isIgnored.test(path)) { // Try to watch the file if needed. watchFile takes care of duplicates. if (program.watch) watchFile(path, null, rootPath); if (program.nameAfterFile) { options.name = getNameFromFileName(path); } var fn = options.client ? pug.compileFileClient(path, options) : pug.compileFile(path, options); if (program.watch && fn.dependencies) { // watch dependencies, and recompile the base fn.dependencies.forEach(function (dep) { watchFile(dep, path, rootPath); }); } // --extension var extname; if (program.extension) extname = '.' + program.extension; else if (options.client) extname = '.js'; else if (program.extension === '') extname = ''; else extname = '.html'; // path: foo.pug -> foo.<ext> path = path.replace(isPug, extname); if (program.out) { // prepend output directory if (rootPath) { // replace the rootPath of the resolved path with output directory path = relative(rootPath, path); } else { // if no rootPath handling is needed path = basename(path); } path = resolve(program.out, path); } var dir = resolve(dirname(path)); mkdirp.sync(dir); var output = options.client ? fn : fn(options); fs.writeFileSync(path, output); consoleLog(' ' + chalk.gray('rendered') + ' ' + chalk.cyan('%s'), normalize(path)); // Found directory } else if (stat.isDirectory()) { var files = fs.readdirSync(path); files.map(function(filename) { return path + '/' + filename; }).forEach(function (file) { render(file, rootPath || path); }); } }
javascript
{ "resource": "" }
q45989
getNameFromFileName
train
function getNameFromFileName(filename) { var file = basename(filename).replace(/\.(?:pug|jade)$/, ''); return file.toLowerCase().replace(/[^a-z0-9]+([a-z])/g, function (_, character) { return character.toUpperCase(); }) + 'Template'; }
javascript
{ "resource": "" }
q45990
unParsePeople
train
function unParsePeople (data) { if (data.author) data.author = unParsePerson(data.author) ;["maintainers", "contributors"].forEach(function (set) { if (!Array.isArray(data[set])) return; data[set] = data[set].map(unParsePerson) }) return data }
javascript
{ "resource": "" }
q45991
collectNodeIds
train
function collectNodeIds(stmt) { var ids = {}, stack = [], curr; var push = stack.push.bind(stack); push(stmt); while(stack.length) { curr = stack.pop(); switch(curr.type) { case "node": ids[curr.id] = true; break; case "edge": _.each(curr.elems, push); break; case "subgraph": _.each(curr.stmts, push); break; } } return _.keys(ids); }
javascript
{ "resource": "" }
q45992
api
train
function api (obj, pointer, value) { // .set() if (arguments.length === 3) { return api.set(obj, pointer, value); } // .get() if (arguments.length === 2) { return api.get(obj, pointer); } // Return a partially applied function on `obj`. var wrapped = api.bind(api, obj); // Support for oo style for (var name in api) { if (api.hasOwnProperty(name)) { wrapped[name] = api[name].bind(wrapped, obj); } } return wrapped; }
javascript
{ "resource": "" }
q45993
getDependencies
train
function getDependencies(pkg) { if (!pkg) { return []; } if (!isObject(pkg)) { $.error('Content from `package.json` must be an `Object`!'); return []; } // get all possible dependencies const deps = [ 'dependencies', 'devDependencies', 'peerDependencies' ].filter(key => pkg[key] !== void 0).map(k => Object.keys(pkg[k])); return flatten(deps); }
javascript
{ "resource": "" }
q45994
gasToCost
train
function gasToCost (gas, ethPrice, gasPrice) { ethPrice = parseFloat(ethPrice) gasPrice = parseInt(gasPrice) return ((gasPrice / 1e9) * gas * ethPrice).toFixed(2) }
javascript
{ "resource": "" }
q45995
matchBinaries
train
function matchBinaries (input, binary) { const regExp = bytecodeToBytecodeRegex(binary); return (input.match(regExp) !== null); }
javascript
{ "resource": "" }
q45996
getContractNames
train
function getContractNames(filePath){ const names = []; const code = fs.readFileSync(filePath, 'utf-8'); const ast = parser.parse(code, {tolerant: true}); parser.visit(ast, { ContractDefinition: function(node) { names.push(node.name); } }); return names; }
javascript
{ "resource": "" }
q45997
typeis
train
function typeis (value, types_) { var i var types = types_ // remove parameters and normalize var val = tryNormalizeType(value) // no type or invalid if (!val) { return false } // support flattened arguments if (types && !Array.isArray(types)) { types = new Array(arguments.length - 1) for (i = 0; i < types.length; i++) { types[i] = arguments[i + 1] } } // no types, return the content type if (!types || !types.length) { return val } var type for (i = 0; i < types.length; i++) { if (mimeMatch(normalize(type = types[i]), val)) { return type[0] === '+' || type.indexOf('*') !== -1 ? val : type } } // no matches return false }
javascript
{ "resource": "" }
q45998
typeofrequest
train
function typeofrequest (req, types_) { var types = types_ // no body if (!hasbody(req)) { return null } // support flattened arguments if (arguments.length > 2) { types = new Array(arguments.length - 1) for (var i = 0; i < types.length; i++) { types[i] = arguments[i + 1] } } // request content type var value = req.headers['content-type'] return typeis(value, types) }
javascript
{ "resource": "" }
q45999
normalize
train
function normalize (type) { if (typeof type !== 'string') { // invalid type return false } switch (type) { case 'urlencoded': return 'application/x-www-form-urlencoded' case 'multipart': return 'multipart/*' } if (type[0] === '+') { // "+json" -> "*/*+json" expando return '*/*' + type } return type.indexOf('/') === -1 ? mime.lookup(type) : type }
javascript
{ "resource": "" }