language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
attributeChangedCallback(attributeName, oldValue, newValue) { if (super.attributeChangedCallback) { super.attributeChangedCallback(); } const propertyName = attributeToPropertyName(attributeName); // If the attribute name corresponds to a property name, set the property. // Ignore standard HTMLElement properties handled by the DOM. if (propertyName in this && !(propertyName in HTMLElement.prototype)) { this[propertyName] = newValue; } }
attributeChangedCallback(attributeName, oldValue, newValue) { if (super.attributeChangedCallback) { super.attributeChangedCallback(); } const propertyName = attributeToPropertyName(attributeName); // If the attribute name corresponds to a property name, set the property. // Ignore standard HTMLElement properties handled by the DOM. if (propertyName in this && !(propertyName in HTMLElement.prototype)) { this[propertyName] = newValue; } }
JavaScript
function attributeToPropertyName(attributeName) { let propertyName = attributeToPropertyNames[attributeName]; if (!propertyName) { // Convert and memoize. const hypenRegEx = /-([a-z])/g; propertyName = attributeName.replace(hypenRegEx, match => match[1].toUpperCase()); attributeToPropertyNames[attributeName] = propertyName; } return propertyName; }
function attributeToPropertyName(attributeName) { let propertyName = attributeToPropertyNames[attributeName]; if (!propertyName) { // Convert and memoize. const hypenRegEx = /-([a-z])/g; propertyName = attributeName.replace(hypenRegEx, match => match[1].toUpperCase()); attributeToPropertyNames[attributeName] = propertyName; } return propertyName; }
JavaScript
function findBackgroundColor(element) { if (element == null || typeof element.style === 'undefined') { // This element has no background, assume white. return 'rgb(255,255,255)'; } const backgroundColor = getComputedStyle(element).backgroundColor; if (backgroundColor === 'transparent' || backgroundColor === 'rgba(0, 0, 0, 0)') { return findBackgroundColor(element.parentNode); } else { return backgroundColor; } }
function findBackgroundColor(element) { if (element == null || typeof element.style === 'undefined') { // This element has no background, assume white. return 'rgb(255,255,255)'; } const backgroundColor = getComputedStyle(element).backgroundColor; if (backgroundColor === 'transparent' || backgroundColor === 'rgba(0, 0, 0, 0)') { return findBackgroundColor(element.parentNode); } else { return backgroundColor; } }
JavaScript
function extractRgbValues(rgbString) { const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/; const match = rgbRegex.exec(rgbString); if (match) { return { r: parseInt(match[1]), g: parseInt(match[2]), b: parseInt(match[3]) }; } else { return null; } }
function extractRgbValues(rgbString) { const rgbRegex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*[\d\.]+\s*)?\)/; const match = rgbRegex.exec(rgbString); if (match) { return { r: parseInt(match[1]), g: parseInt(match[2]), b: parseInt(match[3]) }; } else { return null; } }
JavaScript
addNode(container, node, ref_node) { let ownerRoot = this.ownerShadyRootForNode(container); if (ownerRoot) { // optimization: special insertion point tracking if (node.__noInsertionPoint && ownerRoot._clean) { ownerRoot._skipUpdateInsertionPoints = true; } // note: we always need to see if an insertion point is added // since this saves logical tree info; however, invalidation state // needs let ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot); // invalidate insertion points IFF not already invalid! if (ipAdded) { ownerRoot._skipUpdateInsertionPoints = false; } } if (tree.Logical.hasChildNodes(container)) { tree.Logical.recordInsertBefore(node, container, ref_node); } // if not distributing and not adding to host, do a fast path addition let handled = this._maybeDistribute(node, container, ownerRoot) || container.shadyRoot; return handled; }
addNode(container, node, ref_node) { let ownerRoot = this.ownerShadyRootForNode(container); if (ownerRoot) { // optimization: special insertion point tracking if (node.__noInsertionPoint && ownerRoot._clean) { ownerRoot._skipUpdateInsertionPoints = true; } // note: we always need to see if an insertion point is added // since this saves logical tree info; however, invalidation state // needs let ipAdded = this._maybeAddInsertionPoint(node, container, ownerRoot); // invalidate insertion points IFF not already invalid! if (ipAdded) { ownerRoot._skipUpdateInsertionPoints = false; } } if (tree.Logical.hasChildNodes(container)) { tree.Logical.recordInsertBefore(node, container, ref_node); } // if not distributing and not adding to host, do a fast path addition let handled = this._maybeDistribute(node, container, ownerRoot) || container.shadyRoot; return handled; }
JavaScript
removeNode(node) { // important that we want to do this only if the node has a logical parent let logicalParent = tree.Logical.hasParentNode(node) && tree.Logical.getParentNode(node); let distributed; let ownerRoot = this.ownerShadyRootForNode(node); if (logicalParent) { // distribute node's parent iff needed distributed = this.maybeDistributeParent(node); tree.Logical.recordRemoveChild(node, logicalParent); // remove node from root and distribute it iff needed if (ownerRoot && (this._removeDistributedChildren(ownerRoot, node) || logicalParent.localName === ownerRoot.getInsertionPointTag())) { ownerRoot._skipUpdateInsertionPoints = false; ownerRoot.update(); } } this._removeOwnerShadyRoot(node); return distributed; }
removeNode(node) { // important that we want to do this only if the node has a logical parent let logicalParent = tree.Logical.hasParentNode(node) && tree.Logical.getParentNode(node); let distributed; let ownerRoot = this.ownerShadyRootForNode(node); if (logicalParent) { // distribute node's parent iff needed distributed = this.maybeDistributeParent(node); tree.Logical.recordRemoveChild(node, logicalParent); // remove node from root and distribute it iff needed if (ownerRoot && (this._removeDistributedChildren(ownerRoot, node) || logicalParent.localName === ownerRoot.getInsertionPointTag())) { ownerRoot._skipUpdateInsertionPoints = false; ownerRoot.update(); } } this._removeOwnerShadyRoot(node); return distributed; }
JavaScript
_maybeAddInsertionPoint(node, parent, root) { let added; let insertionPointTag = root.getInsertionPointTag(); if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE && !node.__noInsertionPoint) { let c$ = node.querySelectorAll(insertionPointTag); for (let i=0, n, np, na; (i<c$.length) && (n=c$[i]); i++) { np = tree.Logical.getParentNode(n); // don't allow node's parent to be fragment itself if (np === node) { np = parent; } na = this._maybeAddInsertionPoint(n, np, root); added = added || na; } } else if (node.localName === insertionPointTag) { tree.Logical.saveChildNodes(parent); tree.Logical.saveChildNodes(node); added = true; } return added; }
_maybeAddInsertionPoint(node, parent, root) { let added; let insertionPointTag = root.getInsertionPointTag(); if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE && !node.__noInsertionPoint) { let c$ = node.querySelectorAll(insertionPointTag); for (let i=0, n, np, na; (i<c$.length) && (n=c$[i]); i++) { np = tree.Logical.getParentNode(n); // don't allow node's parent to be fragment itself if (np === node) { np = parent; } na = this._maybeAddInsertionPoint(n, np, root); added = added || na; } } else if (node.localName === insertionPointTag) { tree.Logical.saveChildNodes(parent); tree.Logical.saveChildNodes(node); added = true; } return added; }
JavaScript
query(node, matcher, halter) { let list = []; this._queryElements(tree.Logical.getChildNodes(node), matcher, halter, list); return list; }
query(node, matcher, halter) { let list = []; this._queryElements(tree.Logical.getChildNodes(node), matcher, halter, list); return list; }
JavaScript
insertBefore(node, ref_node) { if (ref_node && tree.Logical.getParentNode(ref_node) !== this) { throw Error('The ref_node to be inserted before is not a child ' + 'of this node'); } // remove node from its current position iff it's in a tree. if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { let parent = tree.Logical.getParentNode(node); mixinImpl.removeNodeFromParent(node, parent); } if (!mixinImpl.addNode(this, node, ref_node)) { if (ref_node) { // if ref_node is an insertion point replace with first distributed node let root = mixinImpl.ownerShadyRootForNode(ref_node); if (root) { ref_node = ref_node.localName === root.getInsertionPointTag() ? mixinImpl.firstComposedNode(ref_node) : ref_node; } } // if adding to a shadyRoot, add to host instead let container = utils.isShadyRoot(this) ? this.host : this; if (ref_node) { tree.Composed.insertBefore(container, node, ref_node); } else { tree.Composed.appendChild(container, node); } } mixinImpl._scheduleObserver(this, node); return node; }
insertBefore(node, ref_node) { if (ref_node && tree.Logical.getParentNode(ref_node) !== this) { throw Error('The ref_node to be inserted before is not a child ' + 'of this node'); } // remove node from its current position iff it's in a tree. if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { let parent = tree.Logical.getParentNode(node); mixinImpl.removeNodeFromParent(node, parent); } if (!mixinImpl.addNode(this, node, ref_node)) { if (ref_node) { // if ref_node is an insertion point replace with first distributed node let root = mixinImpl.ownerShadyRootForNode(ref_node); if (root) { ref_node = ref_node.localName === root.getInsertionPointTag() ? mixinImpl.firstComposedNode(ref_node) : ref_node; } } // if adding to a shadyRoot, add to host instead let container = utils.isShadyRoot(this) ? this.host : this; if (ref_node) { tree.Composed.insertBefore(container, node, ref_node); } else { tree.Composed.appendChild(container, node); } } mixinImpl._scheduleObserver(this, node); return node; }
JavaScript
removeChild(node) { if (tree.Logical.getParentNode(node) !== this) { throw Error('The node to be removed is not a child of this node: ' + node); } if (!mixinImpl.removeNode(node)) { // if removing from a shadyRoot, remove form host instead let container = utils.isShadyRoot(this) ? this.host : this; // not guaranteed to physically be in container; e.g. // undistributed nodes. let parent = tree.Composed.getParentNode(node); if (container === parent) { tree.Composed.removeChild(container, node); } } mixinImpl._scheduleObserver(this, null, node); return node; }
removeChild(node) { if (tree.Logical.getParentNode(node) !== this) { throw Error('The node to be removed is not a child of this node: ' + node); } if (!mixinImpl.removeNode(node)) { // if removing from a shadyRoot, remove form host instead let container = utils.isShadyRoot(this) ? this.host : this; // not guaranteed to physically be in container; e.g. // undistributed nodes. let parent = tree.Composed.getParentNode(node); if (container === parent) { tree.Composed.removeChild(container, node); } } mixinImpl._scheduleObserver(this, null, node); return node; }
JavaScript
querySelector(selector) { // match selector and halt on first result. let result = mixinImpl.query(this, function(n) { return utils.matchesSelector(n, selector); }, function(n) { return Boolean(n); })[0]; return result || null; }
querySelector(selector) { // match selector and halt on first result. let result = mixinImpl.query(this, function(n) { return utils.matchesSelector(n, selector); }, function(n) { return Boolean(n); })[0]; return result || null; }
JavaScript
get value() { return this.selectedItem == null || this.selectedItem.textContent == null ? '' : this.selectedItem.textContent; }
get value() { return this.selectedItem == null || this.selectedItem.textContent == null ? '' : this.selectedItem.textContent; }
JavaScript
function touchEnd(element, clientX, clientY) { element[symbols.dragging] = false; if (element[deltaXSymbol] >= 20) { // Finished going right at high speed. element[symbols.goLeft](); } else if (element[deltaXSymbol] <= -20) { // Finished going left at high speed. element[symbols.goRight](); } else { // Finished at low speed. trackTo(element, clientX); const travelFraction = element.travelFraction; if (travelFraction >= 0.5) { element[symbols.goRight](); } else if (travelFraction <= -0.5) { element[symbols.goLeft](); } } element.travelFraction = 0; element[deltaXSymbol] = null; element[deltaYSymbol] = null; }
function touchEnd(element, clientX, clientY) { element[symbols.dragging] = false; if (element[deltaXSymbol] >= 20) { // Finished going right at high speed. element[symbols.goLeft](); } else if (element[deltaXSymbol] <= -20) { // Finished going left at high speed. element[symbols.goRight](); } else { // Finished at low speed. trackTo(element, clientX); const travelFraction = element.travelFraction; if (travelFraction >= 0.5) { element[symbols.goRight](); } else if (travelFraction <= -0.5) { element[symbols.goLeft](); } } element.travelFraction = 0; element[deltaXSymbol] = null; element[deltaYSymbol] = null; }
JavaScript
function touchMove(element, clientX, clientY) { element[deltaXSymbol] = clientX - element[previousXSymbol]; element[deltaYSymbol] = clientY - element[previousYSymbol]; element[previousXSymbol] = clientX; element[previousYSymbol] = clientY; if (Math.abs(element[deltaXSymbol]) > Math.abs(element[deltaYSymbol])) { // Move was mostly horizontal. trackTo(element, clientX); // Indicate that the event was handled. It'd be nicer if we didn't have // to do this so that, e.g., a user could be swiping left and right // while simultaneously scrolling up and down. (Native touch apps can do // that.) However, Mobile Safari wants to handle swipe events near the // page and interpret them as navigations. To avoid having a horiziontal // swipe misintepreted as a navigation, we indicate that we've handled // the event, and prevent default behavior. return true; } else { // Move was mostly vertical. return false; // Not handled } }
function touchMove(element, clientX, clientY) { element[deltaXSymbol] = clientX - element[previousXSymbol]; element[deltaYSymbol] = clientY - element[previousYSymbol]; element[previousXSymbol] = clientX; element[previousYSymbol] = clientY; if (Math.abs(element[deltaXSymbol]) > Math.abs(element[deltaYSymbol])) { // Move was mostly horizontal. trackTo(element, clientX); // Indicate that the event was handled. It'd be nicer if we didn't have // to do this so that, e.g., a user could be swiping left and right // while simultaneously scrolling up and down. (Native touch apps can do // that.) However, Mobile Safari wants to handle swipe events near the // page and interpret them as navigations. To avoid having a horiziontal // swipe misintepreted as a navigation, we indicate that we've handled // the event, and prevent default behavior. return true; } else { // Move was mostly vertical. return false; // Not handled } }
JavaScript
function touchStart(element, clientX, clientY) { element[symbols.dragging] = true; element[startXSymbol] = clientX; element[previousXSymbol] = clientX; element[previousYSymbol] = clientY; element[deltaXSymbol] = 0; element[deltaYSymbol] = 0; }
function touchStart(element, clientX, clientY) { element[symbols.dragging] = true; element[startXSymbol] = clientX; element[previousXSymbol] = clientX; element[previousYSymbol] = clientY; element[deltaXSymbol] = 0; element[deltaYSymbol] = 0; }
JavaScript
function scrollOnePage(element, downward) { // Determine the item visible just at the edge of direction we're heading. // We'll select that item if it's not already selected. const scrollTarget = element.scrollTarget; const edge = scrollTarget.scrollTop + (downward ? scrollTarget.clientHeight : 0); const indexOfItemAtEdge = getIndexOfItemAtY(element, edge, downward); const selectedIndex = element.selectedIndex; let newIndex; if (indexOfItemAtEdge && selectedIndex === indexOfItemAtEdge) { // The item at the edge was already selected, so scroll in the indicated // direction by one page. Leave the new item at that edge selected. const delta = (downward ? 1 : -1) * scrollTarget.clientHeight; newIndex = getIndexOfItemAtY(element, edge + delta, downward); } else { // The item at the edge wasn't selected yet. Instead of scrolling, we'll // just select that item. That is, the first attempt to page up/down // usually just moves the selection to the edge in that direction. newIndex = indexOfItemAtEdge; } if (!newIndex) { // We can't find an item in the direction we want to travel. Select the // last item (if moving downward) or first item (if moving upward). newIndex = (downward ? element.items.length - 1 : 0); } if (newIndex !== selectedIndex) { element.selectedIndex = newIndex; return true; // We handled the page up/down ourselves. } else { return false; // We didn't do anything. } }
function scrollOnePage(element, downward) { // Determine the item visible just at the edge of direction we're heading. // We'll select that item if it's not already selected. const scrollTarget = element.scrollTarget; const edge = scrollTarget.scrollTop + (downward ? scrollTarget.clientHeight : 0); const indexOfItemAtEdge = getIndexOfItemAtY(element, edge, downward); const selectedIndex = element.selectedIndex; let newIndex; if (indexOfItemAtEdge && selectedIndex === indexOfItemAtEdge) { // The item at the edge was already selected, so scroll in the indicated // direction by one page. Leave the new item at that edge selected. const delta = (downward ? 1 : -1) * scrollTarget.clientHeight; newIndex = getIndexOfItemAtY(element, edge + delta, downward); } else { // The item at the edge wasn't selected yet. Instead of scrolling, we'll // just select that item. That is, the first attempt to page up/down // usually just moves the selection to the edge in that direction. newIndex = indexOfItemAtEdge; } if (!newIndex) { // We can't find an item in the direction we want to travel. Select the // last item (if moving downward) or first item (if moving upward). newIndex = (downward ? element.items.length - 1 : 0); } if (newIndex !== selectedIndex) { element.selectedIndex = newIndex; return true; // We handled the page up/down ourselves. } else { return false; // We didn't do anything. } }
JavaScript
get selectedIndex() { return this[externalSelectedIndexSymbol] != null ? this[externalSelectedIndexSymbol] : -1; }
get selectedIndex() { return this[externalSelectedIndexSymbol] != null ? this[externalSelectedIndexSymbol] : -1; }
JavaScript
selectPrevious() { if (super.selectPrevious) { super.selectPrevious(); } const newIndex = this.selectedIndex < 0 ? this.items.length - 1 : // No selection yet; select last item. this.selectedIndex - 1; return selectIndex(this, newIndex); }
selectPrevious() { if (super.selectPrevious) { super.selectPrevious(); } const newIndex = this.selectedIndex < 0 ? this.items.length - 1 : // No selection yet; select last item. this.selectedIndex - 1; return selectIndex(this, newIndex); }
JavaScript
function trackSelectedItem(element) { const items = element.items; const itemCount = items ? items.length : 0; const previousSelectedItem = element.selectedItem; if (!previousSelectedItem) { // No item was previously selected. if (element.selectionRequired) { // Select the first item by default. element.selectedIndex = 0; } } else if (itemCount === 0) { // We've lost the selection, and there's nothing left to select. element.selectedItem = null; } else { // Try to find the previously-selected item in the current set of items. const indexInCurrentItems = Array.prototype.indexOf.call(items, previousSelectedItem); const previousSelectedIndex = element.selectedIndex; if (indexInCurrentItems < 0) { // Previously-selected item was removed from the items. // Select the item at the same index (if it exists) or as close as possible. const newSelectedIndex = Math.min(previousSelectedIndex, itemCount - 1); // Select by item, since index may be the same, and we want to raise the // selected-item-changed event. element.selectedItem = items[newSelectedIndex]; } else if (indexInCurrentItems !== previousSelectedIndex) { // Previously-selected item still there, but changed position. element.selectedIndex = indexInCurrentItems; } } }
function trackSelectedItem(element) { const items = element.items; const itemCount = items ? items.length : 0; const previousSelectedItem = element.selectedItem; if (!previousSelectedItem) { // No item was previously selected. if (element.selectionRequired) { // Select the first item by default. element.selectedIndex = 0; } } else if (itemCount === 0) { // We've lost the selection, and there's nothing left to select. element.selectedItem = null; } else { // Try to find the previously-selected item in the current set of items. const indexInCurrentItems = Array.prototype.indexOf.call(items, previousSelectedItem); const previousSelectedIndex = element.selectedIndex; if (indexInCurrentItems < 0) { // Previously-selected item was removed from the items. // Select the item at the same index (if it exists) or as close as possible. const newSelectedIndex = Math.min(previousSelectedIndex, itemCount - 1); // Select by item, since index may be the same, and we want to raise the // selected-item-changed event. element.selectedItem = items[newSelectedIndex]; } else if (indexInCurrentItems !== previousSelectedIndex) { // Previously-selected item still there, but changed position. element.selectedIndex = indexInCurrentItems; } } }
JavaScript
function updatePossibleNavigations(element) { let canSelectNext; let canSelectPrevious; const items = element.items; if (items == null || items.length === 0) { // No items to select. canSelectNext = false; canSelectPrevious = false; } if (element.selectionWraps) { // Since there are items, can always go next/previous. canSelectNext = true; canSelectPrevious = true; } else { const index = element.selectedIndex; if (index < 0 && items.length > 0) { // Special case. If there are items but no selection, declare that it's // always possible to go next/previous to create a selection. canSelectNext = true; canSelectPrevious = true; } else { // Normal case: we have an index in a list that has items. canSelectPrevious = (index > 0); canSelectNext = (index < items.length - 1); } } if (element.canSelectNext !== canSelectNext) { element.canSelectNext = canSelectNext; } if (element.canSelectPrevious !== canSelectPrevious) { element.canSelectPrevious = canSelectPrevious; } }
function updatePossibleNavigations(element) { let canSelectNext; let canSelectPrevious; const items = element.items; if (items == null || items.length === 0) { // No items to select. canSelectNext = false; canSelectPrevious = false; } if (element.selectionWraps) { // Since there are items, can always go next/previous. canSelectNext = true; canSelectPrevious = true; } else { const index = element.selectedIndex; if (index < 0 && items.length > 0) { // Special case. If there are items but no selection, declare that it's // always possible to go next/previous to create a selection. canSelectNext = true; canSelectPrevious = true; } else { // Normal case: we have an index in a list that has items. canSelectPrevious = (index > 0); canSelectNext = (index < items.length - 1); } } if (element.canSelectNext !== canSelectNext) { element.canSelectNext = canSelectNext; } if (element.canSelectPrevious !== canSelectPrevious) { element.canSelectPrevious = canSelectPrevious; } }
JavaScript
connected(element) { element[safeToSetAttributesSymbol] = true; // Set any pending attributes. if (element[pendingAttributesSymbol]) { for (let attribute in element[pendingAttributesSymbol]) { const value = element[pendingAttributesSymbol][attribute]; setAttributeToElement(element, attribute, value); } element[pendingAttributesSymbol] = null; } // Set any pending classes. if (element[pendingClassesSymbol]) { for (let className in element[pendingClassesSymbol]) { const value = element[pendingClassesSymbol][className]; toggleClass(element, className, value); } element[pendingClassesSymbol] = null; } }
connected(element) { element[safeToSetAttributesSymbol] = true; // Set any pending attributes. if (element[pendingAttributesSymbol]) { for (let attribute in element[pendingAttributesSymbol]) { const value = element[pendingAttributesSymbol][attribute]; setAttributeToElement(element, attribute, value); } element[pendingAttributesSymbol] = null; } // Set any pending classes. if (element[pendingClassesSymbol]) { for (let className in element[pendingClassesSymbol]) { const value = element[pendingClassesSymbol][className]; toggleClass(element, className, value); } element[pendingClassesSymbol] = null; } }
JavaScript
toggleClass(element, className, value) { if (element[safeToSetAttributesSymbol]) { // Safe to set class immediately. toggleClass(element, className, value); } else { // Defer setting class until the first time we're connected. if (!element[pendingClassesSymbol]) { element[pendingClassesSymbol] = {}; } element[pendingClassesSymbol][className] = value; } }
toggleClass(element, className, value) { if (element[safeToSetAttributesSymbol]) { // Safe to set class immediately. toggleClass(element, className, value); } else { // Defer setting class until the first time we're connected. if (!element[pendingClassesSymbol]) { element[pendingClassesSymbol] = {}; } element[pendingClassesSymbol][className] = value; } }
JavaScript
function renderArrayAsElements(items, container, renderItem) { // Create a new set of elements for the current items. items.forEach((item, index) => { const oldElement = container.childNodes[index]; const newElement = renderItem(item, oldElement); if (newElement) { if (!oldElement) { container.appendChild(newElement); } else if (newElement !== oldElement) { container.replaceChild(newElement, oldElement); } } }); // If the array shrank, remove the extra elements which are no longer needed. while (container.childNodes.length > items.length) { container.removeChild(container.childNodes[items.length]); } }
function renderArrayAsElements(items, container, renderItem) { // Create a new set of elements for the current items. items.forEach((item, index) => { const oldElement = container.childNodes[index]; const newElement = renderItem(item, oldElement); if (newElement) { if (!oldElement) { container.appendChild(newElement); } else if (newElement !== oldElement) { container.replaceChild(newElement, oldElement); } } }); // If the array shrank, remove the extra elements which are no longer needed. while (container.childNodes.length > items.length) { container.removeChild(container.childNodes[items.length]); } }
JavaScript
scrollItemIntoView(item) { if (super.scrollItemIntoView) { super.scrollItemIntoView(); } // Get the relative position of the item with respect to the top of the // list's scrollable canvas. An item at the top of the list will have a // elementTop of 0. const scrollTarget = this.scrollTarget; const elementTop = item.offsetTop - scrollTarget.offsetTop - scrollTarget.clientTop; const elementBottom = elementTop + item.offsetHeight; // Determine the bottom of the scrollable canvas. const scrollBottom = scrollTarget.scrollTop + scrollTarget.clientHeight; if (elementBottom > scrollBottom) { // Scroll up until item is entirely visible. scrollTarget.scrollTop += elementBottom - scrollBottom; } else if (elementTop < scrollTarget.scrollTop) { // Scroll down until item is entirely visible. scrollTarget.scrollTop = elementTop; } }
scrollItemIntoView(item) { if (super.scrollItemIntoView) { super.scrollItemIntoView(); } // Get the relative position of the item with respect to the top of the // list's scrollable canvas. An item at the top of the list will have a // elementTop of 0. const scrollTarget = this.scrollTarget; const elementTop = item.offsetTop - scrollTarget.offsetTop - scrollTarget.clientTop; const elementBottom = elementTop + item.offsetHeight; // Determine the bottom of the scrollable canvas. const scrollBottom = scrollTarget.scrollTop + scrollTarget.clientHeight; if (elementBottom > scrollBottom) { // Scroll up until item is entirely visible. scrollTarget.scrollTop += elementBottom - scrollBottom; } else if (elementTop < scrollTarget.scrollTop) { // Scroll down until item is entirely visible. scrollTarget.scrollTop = elementTop; } }
JavaScript
autoSize() { // If we had speculatively added an extra line because of an Enter keypress, // we can now hide the extra line. this.$.extraLine.style.display = 'none'; // We resize by copying the textarea contents to the element itself; the // text will then appear (via <slot>) inside the invisible div. If // we've set things up correctly, this new content should take up the same // amount of room as the same text in the textarea. Updating the element's // content adjusts the element's size, which in turn will make the textarea // the correct height. this.$.textCopy.textContent = this.value; }
autoSize() { // If we had speculatively added an extra line because of an Enter keypress, // we can now hide the extra line. this.$.extraLine.style.display = 'none'; // We resize by copying the textarea contents to the element itself; the // text will then appear (via <slot>) inside the invisible div. If // we've set things up correctly, this new content should take up the same // amount of room as the same text in the textarea. Updating the element's // content adjusts the element's size, which in turn will make the textarea // the correct height. this.$.textCopy.textContent = this.value; }
JavaScript
function mixin(base) { /** * Adds support for fractional selection: treating a selection as a real * number that combines an integer portion (an index into a list), and a * fraction (indicating how far of the way we are to the next or previous * item). * * This is useful in components that support incremental operations during * dragging and swiping. Example: a carousel component has several items, and the * currently selected item is item 3. The user begins swiping to the left, * moving towards selecting item 4. Halfway through this operation, the * fractional selection value is 3.5. * * This value permits communication between mixins like * [SwipeDirectionMixin](./SwipeDirectionMixin.md) and * [TrackpadDirectionMixin](./TrackpadDirectionMixin.md), which generate * fractional selection values, and mixins like * [SelectionAnimationMixin](./SelectionAnimationMixin.md), which can render * selection at a fractional value. */ class FractionalSelection extends base { connectedCallback() { if (super.connectedCallback) { super.connectedCallback(); } this.selectedFraction = 0; } /** * A fractional value indicating how far the user has currently advanced to * the next/previous item. E.g., a `selectedFraction` of 3.5 indicates the * user is halfway between items 3 and 4. * * @type {number} */ get selectedFraction() { return this[selectedFractionSymbol]; } set selectedFraction(value) { this[selectedFractionSymbol] = value; if ('selectedFraction' in base.prototype) { super.selectedFraction = value; } const event = new CustomEvent('selected-fraction-changed'); this.dispatchEvent(event); } } return FractionalSelection; }
function mixin(base) { /** * Adds support for fractional selection: treating a selection as a real * number that combines an integer portion (an index into a list), and a * fraction (indicating how far of the way we are to the next or previous * item). * * This is useful in components that support incremental operations during * dragging and swiping. Example: a carousel component has several items, and the * currently selected item is item 3. The user begins swiping to the left, * moving towards selecting item 4. Halfway through this operation, the * fractional selection value is 3.5. * * This value permits communication between mixins like * [SwipeDirectionMixin](./SwipeDirectionMixin.md) and * [TrackpadDirectionMixin](./TrackpadDirectionMixin.md), which generate * fractional selection values, and mixins like * [SelectionAnimationMixin](./SelectionAnimationMixin.md), which can render * selection at a fractional value. */ class FractionalSelection extends base { connectedCallback() { if (super.connectedCallback) { super.connectedCallback(); } this.selectedFraction = 0; } /** * A fractional value indicating how far the user has currently advanced to * the next/previous item. E.g., a `selectedFraction` of 3.5 indicates the * user is halfway between items 3 and 4. * * @type {number} */ get selectedFraction() { return this[selectedFractionSymbol]; } set selectedFraction(value) { this[selectedFractionSymbol] = value; if ('selectedFraction' in base.prototype) { super.selectedFraction = value; } const event = new CustomEvent('selected-fraction-changed'); this.dispatchEvent(event); } } return FractionalSelection; }
JavaScript
dampedSelection(selection, itemCount) { const bound = itemCount - 1; let damped; if (selection < 0) { // Trying to go past beginning of list. Apply tension from the left edge. damped = -mixin.helpers.damping(-selection); } else if (selection >= bound) { // Trying to go past end of list. Apply tension from the right edge. damped = bound + mixin.helpers.damping(selection - bound); } else { // No damping required. damped = selection; } return damped; }
dampedSelection(selection, itemCount) { const bound = itemCount - 1; let damped; if (selection < 0) { // Trying to go past beginning of list. Apply tension from the left edge. damped = -mixin.helpers.damping(-selection); } else if (selection >= bound) { // Trying to go past end of list. Apply tension from the right edge. damped = bound + mixin.helpers.damping(selection - bound); } else { // No damping required. damped = selection; } return damped; }
JavaScript
elementSelection(element) { const selectedIndex = element.selectedIndex; if (selectedIndex < 0) { // No selection return; } const selectedFraction = element.selectedFraction || 0; return selectedIndex + selectedFraction; }
elementSelection(element) { const selectedIndex = element.selectedIndex; if (selectedIndex < 0) { // No selection return; } const selectedFraction = element.selectedFraction || 0; return selectedIndex + selectedFraction; }
JavaScript
wrappedSelection(selection, itemCount) { // Handles possibility of negative mod. // See http://stackoverflow.com/a/18618250/76472 return ((selection % itemCount) + itemCount) % itemCount; }
wrappedSelection(selection, itemCount) { // Handles possibility of negative mod. // See http://stackoverflow.com/a/18618250/76472 return ((selection % itemCount) + itemCount) % itemCount; }
JavaScript
recordInsertBefore(node, container, ref_node) { container.__dom.childNodes = null; // handle document fragments if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { let c$ = tree.arrayCopyChildNodes(node); for (let i=0; i < c$.length; i++) { this._linkNode(c$[i], container, ref_node); } // cleanup logical dom in doc fragment. node.__dom = node.__dom || {}; node.__dom.firstChild = node.__dom.lastChild = null; node.__dom.childNodes = null; } else { this._linkNode(node, container, ref_node); } }
recordInsertBefore(node, container, ref_node) { container.__dom.childNodes = null; // handle document fragments if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { let c$ = tree.arrayCopyChildNodes(node); for (let i=0; i < c$.length; i++) { this._linkNode(c$[i], container, ref_node); } // cleanup logical dom in doc fragment. node.__dom = node.__dom || {}; node.__dom.firstChild = node.__dom.lastChild = null; node.__dom.childNodes = null; } else { this._linkNode(node, container, ref_node); } }
JavaScript
get distributedTextContent() { const strings = this.distributedChildNodes.map(function(child) { return child.textContent; }); return strings.join(''); }
get distributedTextContent() { const strings = this.distributedChildNodes.map(function(child) { return child.textContent; }); return strings.join(''); }
JavaScript
function expandContentElements(nodes, includeTextNodes) { const expanded = Array.prototype.map.call(nodes, node => { // We want to see if the node is an instanceof HTMLSlotELement, but // that class won't exist if the browser that doesn't support native // Shadow DOM and if the Shadow DOM polyfill hasn't been loaded. Instead, // we do a simplistic check to see if the tag name is "slot". const isSlot = typeof HTMLSlotElement !== 'undefined' ? node instanceof HTMLSlotElement : node.localName === 'slot'; if (isSlot) { // Use the nodes assigned to this node instead. const assignedNodes = node.assignedNodes({ flatten: true }); return assignedNodes ? expandContentElements(assignedNodes, includeTextNodes) : []; } else if (node instanceof HTMLElement) { // Plain element; use as is. return [node]; } else if (node instanceof Text && includeTextNodes) { // Text node. return [node]; } else { // Comment, processing instruction, etc.; skip. return []; } }); const flattened = [].concat(...expanded); return flattened; }
function expandContentElements(nodes, includeTextNodes) { const expanded = Array.prototype.map.call(nodes, node => { // We want to see if the node is an instanceof HTMLSlotELement, but // that class won't exist if the browser that doesn't support native // Shadow DOM and if the Shadow DOM polyfill hasn't been loaded. Instead, // we do a simplistic check to see if the tag name is "slot". const isSlot = typeof HTMLSlotElement !== 'undefined' ? node instanceof HTMLSlotElement : node.localName === 'slot'; if (isSlot) { // Use the nodes assigned to this node instead. const assignedNodes = node.assignedNodes({ flatten: true }); return assignedNodes ? expandContentElements(assignedNodes, includeTextNodes) : []; } else if (node instanceof HTMLElement) { // Plain element; use as is. return [node]; } else if (node instanceof Text && includeTextNodes) { // Text node. return [node]; } else { // Comment, processing instruction, etc.; skip. return []; } }); const flattened = [].concat(...expanded); return flattened; }
JavaScript
static wrap(extendsTag) { // Create the new class. class Wrapped extends WrappedStandardElement {} // Indicate which tag it wraps. Wrapped.prototype.extends = extendsTag; // Create getter/setters that delegate to the wrapped element. const element = document.createElement(extendsTag); const extendsPrototype = element.constructor.prototype; const names = Object.getOwnPropertyNames(extendsPrototype); names.forEach(name => { const descriptor = Object.getOwnPropertyDescriptor(extendsPrototype, name); const delegate = createPropertyDelegate(name, descriptor); Object.defineProperty(Wrapped.prototype, name, delegate); }); return Wrapped; }
static wrap(extendsTag) { // Create the new class. class Wrapped extends WrappedStandardElement {} // Indicate which tag it wraps. Wrapped.prototype.extends = extendsTag; // Create getter/setters that delegate to the wrapped element. const element = document.createElement(extendsTag); const extendsPrototype = element.constructor.prototype; const names = Object.getOwnPropertyNames(extendsPrototype); names.forEach(name => { const descriptor = Object.getOwnPropertyDescriptor(extendsPrototype, name); const delegate = createPropertyDelegate(name, descriptor); Object.defineProperty(Wrapped.prototype, name, delegate); }); return Wrapped; }
JavaScript
function mixin(base) { /** * Mixin which uses animation to show transitions between selection states. * * This mixin can be used by components that want to provide visible * animations when changing the selection. For example, a carousel component * may want to define a sliding animation effect shown when moving between * items. * * The animation is defined by a `selectionAnimationKeyframes` property; see * that property for details on how to define these keyframes. This animation * will be used in two ways. First, when moving strictly between items, the * animation will play smoothly to show the selection changing. Second, the * animation can be used to render the selection at a fixed point in the * transition between states. E.g., if the user pauses halfway through * dragging an element using [SwipeDirectionMixin](SwipeDirectionMixin.md) * or [TrackpadDirectionMixin](TrackpadDirectionMixin.md)s, then the selection * animation will be shown at the point exactly halfway through. * * This mixin expects a component to provide an `items` array of all elements * in the list, which can be provided via * [ContentItemsMixin](ContentItemsMixin.md). This mixin also expects * `selectedIndex` and `selectedItem` properties, which can be provided via * [SingleSelectionMixin](SingleSelectionMixin.md). * * This mixin supports a `selectionWraps` property. When true, the user can * navigate forward from the last item in the list and wrap around to the * first item, or navigate backward from the first item and wrap around to the * last item. * * This mixin uses the Web Animations API. For use on browsers which * do not support that API natively, you will need to load the * [Web Animations polyfill](https://github.com/web-animations/web-animations-js). */ class SelectionAnimation extends base { constructor() { super(); // Set defaults. if (typeof this.selectionAnimationDuration === 'undefined') { this.selectionAnimationDuration = this[symbols.defaults].selectionAnimationDuration; } if (typeof this.selectionAnimationEffect === 'undefined' && this.selectionAnimationKeyframes == null) { this.selectionAnimationEffect = this[symbols.defaults].selectionAnimationEffect; } this[symbols.dragging] = false; } get [symbols.defaults]() { const defaults = super[symbols.defaults] || {}; defaults.selectionAnimationDuration = 250; defaults.selectionAnimationEffect = 'slide'; return defaults; } /* * Provide backing for the dragging property. * Also, when a drag begins, reset the animations. */ get [symbols.dragging]() { return this[draggingSymbol]; } set [symbols.dragging](value) { const previousValue = this[symbols.dragging]; this[draggingSymbol] = value; if (symbols.dragging in base.prototype) { super[symbols.dragging] = value; } if (value && !previousValue) { // Have begun a drag. this[resetAnimationsOnNextRenderSymbol] = true; } } [symbols.itemAdded](item) { // We mark new items in the list as explicitly visible to ARIA. Otherwise, // when an item isn't visible on the screen, ARIA will assume the item is // of no interest to the user, and leave it out of the accessibility tree. // If the list contains 10 items, but only 3 are visible, a screen reader // might then announce the list only has 3 items. To ensure that screen // readers and other assistive technologies announce the correct total // number of items, we explicitly mark all items as not hidden. This will // expose them all in the accessibility tree, even the items which are // currently not rendered. // // TODO: Generally speaking, this entire mixin assumes that the user can // navigate through all items in a list. But an app could style an item as // display:none or visibility:hidden because the user is not allowed to // interact with that item at the moment. Support for this scenario should // be added. This would entail changing all locations where a mixin // function is counting items, iterating over the (visible) items, and // showing or hiding items. Among other things, the code below to make // items visible to ARIA would need to discriminate between items which // are invisible because of animation state, or invisible because the user // shouldn't interact with them. item.setAttribute('aria-hidden', false); } [symbols.itemsChanged]() { if (super[symbols.itemsChanged]) { super[symbols.itemsChanged](); } resetAnimations(this); // TODO: Also reset our notion of the last rendered selection? This comes // up when a DOM removal causes the selected item to change position. // this[previousSelectionSymbol] = null; renderSelection(this); } resetAnimations() { resetAnimations(this); } /** * A fractional value indicating how far the user has currently advanced to * the next/previous item. E.g., a `selectedFraction` of 3.5 indicates the * user is halfway between items 3 and 4. * * For more details, see [FractionalSelectionMixin](FractionalSelectionMixin.md) * mixin. * * @type {number} */ get selectedFraction() { return super.selectedFraction || 0; } set selectedFraction(value) { if ('selectedFraction' in base.prototype) { super.selectedFraction = value; } renderSelection(this, this.selectedIndex, value); } get selectedIndex() { return super.selectedIndex; } set selectedIndex(index) { if ('selectedIndex' in base.prototype) { super.selectedIndex = index; } renderSelection(this, index, 0); } /** * The duration of a selection animation in milliseconds. * * This measures the amount of time required for a selection animation to * complete. This number remains constant, even if the number of items being * animated increases. * * The default value is 250 milliseconds (a quarter a second). * * @type {number} * @default 250 */ get selectionAnimationDuration() { return this[selectionAnimationDurationSymbol]; } set selectionAnimationDuration(value) { this[selectionAnimationDurationSymbol] = value; if ('selectionAnimationDuration' in base.prototype) { super.selectionAnimationDuration = value; } } /** * The name of a standard selection animation effect. * * This is a shorthand for setting the `selectionAnimationKeyframes` * property to standard keyframes. Supported string values: * * * "crossfade" * * "reveal" * * "revealWithFade" * * "showAdjacent" * * "slide" * * "slideWithGap" * * @type {string} * @default "slide" */ get selectionAnimationEffect() { return this[selectionAnimationEffectSymbol]; } set selectionAnimationEffect(value) { this[selectionAnimationEffectSymbol] = value; if ('selectionAnimationEffect' in base.prototype) { super.selectionAnimationEffect = value; } this.selectionAnimationKeyframes = mixin.standardEffectKeyframes[value]; } /** * The keyframes that define an animation that plays for an item when moving * forward in the sequence. * * This is an array of CSS rules that will be applied. These are used as * [keyframes](http://w3c.github.io/web-animations/#keyframes-section) * to animate the item with the * [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/animation). * * The animation represents the state of the next item as it moves from * completely unselected (offstage, usually right), to selected (center * stage), to completely unselected (offstage, usually left). The center time * of the animation should correspond to the item's quiscent selected state, * typically in the center of the stage and at the item's largest size. * * The default forward animation is a smooth slide at full size from right to * left. * * When moving the selection backward, this animation is played in reverse. * * @type {cssRules[]} */ get selectionAnimationKeyframes() { // Standard animation slides left/right, keeps adjacent items out of view. return this[selectionAnimationKeyframesSymbol]; } set selectionAnimationKeyframes(value) { this[selectionAnimationKeyframesSymbol] = value; if ('selectionAnimationKeyframes' in base.prototype) { super.selectionAnimationKeyframes = value; } resetAnimations(this); renderSelection(this); } get selectionWraps() { return super.selectionWraps; } set selectionWraps(value) { if ('selectionWraps' in base.prototype) { super.selectionWraps = value; } resetAnimations(this); renderSelection(this); } } return SelectionAnimation; }
function mixin(base) { /** * Mixin which uses animation to show transitions between selection states. * * This mixin can be used by components that want to provide visible * animations when changing the selection. For example, a carousel component * may want to define a sliding animation effect shown when moving between * items. * * The animation is defined by a `selectionAnimationKeyframes` property; see * that property for details on how to define these keyframes. This animation * will be used in two ways. First, when moving strictly between items, the * animation will play smoothly to show the selection changing. Second, the * animation can be used to render the selection at a fixed point in the * transition between states. E.g., if the user pauses halfway through * dragging an element using [SwipeDirectionMixin](SwipeDirectionMixin.md) * or [TrackpadDirectionMixin](TrackpadDirectionMixin.md)s, then the selection * animation will be shown at the point exactly halfway through. * * This mixin expects a component to provide an `items` array of all elements * in the list, which can be provided via * [ContentItemsMixin](ContentItemsMixin.md). This mixin also expects * `selectedIndex` and `selectedItem` properties, which can be provided via * [SingleSelectionMixin](SingleSelectionMixin.md). * * This mixin supports a `selectionWraps` property. When true, the user can * navigate forward from the last item in the list and wrap around to the * first item, or navigate backward from the first item and wrap around to the * last item. * * This mixin uses the Web Animations API. For use on browsers which * do not support that API natively, you will need to load the * [Web Animations polyfill](https://github.com/web-animations/web-animations-js). */ class SelectionAnimation extends base { constructor() { super(); // Set defaults. if (typeof this.selectionAnimationDuration === 'undefined') { this.selectionAnimationDuration = this[symbols.defaults].selectionAnimationDuration; } if (typeof this.selectionAnimationEffect === 'undefined' && this.selectionAnimationKeyframes == null) { this.selectionAnimationEffect = this[symbols.defaults].selectionAnimationEffect; } this[symbols.dragging] = false; } get [symbols.defaults]() { const defaults = super[symbols.defaults] || {}; defaults.selectionAnimationDuration = 250; defaults.selectionAnimationEffect = 'slide'; return defaults; } /* * Provide backing for the dragging property. * Also, when a drag begins, reset the animations. */ get [symbols.dragging]() { return this[draggingSymbol]; } set [symbols.dragging](value) { const previousValue = this[symbols.dragging]; this[draggingSymbol] = value; if (symbols.dragging in base.prototype) { super[symbols.dragging] = value; } if (value && !previousValue) { // Have begun a drag. this[resetAnimationsOnNextRenderSymbol] = true; } } [symbols.itemAdded](item) { // We mark new items in the list as explicitly visible to ARIA. Otherwise, // when an item isn't visible on the screen, ARIA will assume the item is // of no interest to the user, and leave it out of the accessibility tree. // If the list contains 10 items, but only 3 are visible, a screen reader // might then announce the list only has 3 items. To ensure that screen // readers and other assistive technologies announce the correct total // number of items, we explicitly mark all items as not hidden. This will // expose them all in the accessibility tree, even the items which are // currently not rendered. // // TODO: Generally speaking, this entire mixin assumes that the user can // navigate through all items in a list. But an app could style an item as // display:none or visibility:hidden because the user is not allowed to // interact with that item at the moment. Support for this scenario should // be added. This would entail changing all locations where a mixin // function is counting items, iterating over the (visible) items, and // showing or hiding items. Among other things, the code below to make // items visible to ARIA would need to discriminate between items which // are invisible because of animation state, or invisible because the user // shouldn't interact with them. item.setAttribute('aria-hidden', false); } [symbols.itemsChanged]() { if (super[symbols.itemsChanged]) { super[symbols.itemsChanged](); } resetAnimations(this); // TODO: Also reset our notion of the last rendered selection? This comes // up when a DOM removal causes the selected item to change position. // this[previousSelectionSymbol] = null; renderSelection(this); } resetAnimations() { resetAnimations(this); } /** * A fractional value indicating how far the user has currently advanced to * the next/previous item. E.g., a `selectedFraction` of 3.5 indicates the * user is halfway between items 3 and 4. * * For more details, see [FractionalSelectionMixin](FractionalSelectionMixin.md) * mixin. * * @type {number} */ get selectedFraction() { return super.selectedFraction || 0; } set selectedFraction(value) { if ('selectedFraction' in base.prototype) { super.selectedFraction = value; } renderSelection(this, this.selectedIndex, value); } get selectedIndex() { return super.selectedIndex; } set selectedIndex(index) { if ('selectedIndex' in base.prototype) { super.selectedIndex = index; } renderSelection(this, index, 0); } /** * The duration of a selection animation in milliseconds. * * This measures the amount of time required for a selection animation to * complete. This number remains constant, even if the number of items being * animated increases. * * The default value is 250 milliseconds (a quarter a second). * * @type {number} * @default 250 */ get selectionAnimationDuration() { return this[selectionAnimationDurationSymbol]; } set selectionAnimationDuration(value) { this[selectionAnimationDurationSymbol] = value; if ('selectionAnimationDuration' in base.prototype) { super.selectionAnimationDuration = value; } } /** * The name of a standard selection animation effect. * * This is a shorthand for setting the `selectionAnimationKeyframes` * property to standard keyframes. Supported string values: * * * "crossfade" * * "reveal" * * "revealWithFade" * * "showAdjacent" * * "slide" * * "slideWithGap" * * @type {string} * @default "slide" */ get selectionAnimationEffect() { return this[selectionAnimationEffectSymbol]; } set selectionAnimationEffect(value) { this[selectionAnimationEffectSymbol] = value; if ('selectionAnimationEffect' in base.prototype) { super.selectionAnimationEffect = value; } this.selectionAnimationKeyframes = mixin.standardEffectKeyframes[value]; } /** * The keyframes that define an animation that plays for an item when moving * forward in the sequence. * * This is an array of CSS rules that will be applied. These are used as * [keyframes](http://w3c.github.io/web-animations/#keyframes-section) * to animate the item with the * [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/animation). * * The animation represents the state of the next item as it moves from * completely unselected (offstage, usually right), to selected (center * stage), to completely unselected (offstage, usually left). The center time * of the animation should correspond to the item's quiscent selected state, * typically in the center of the stage and at the item's largest size. * * The default forward animation is a smooth slide at full size from right to * left. * * When moving the selection backward, this animation is played in reverse. * * @type {cssRules[]} */ get selectionAnimationKeyframes() { // Standard animation slides left/right, keeps adjacent items out of view. return this[selectionAnimationKeyframesSymbol]; } set selectionAnimationKeyframes(value) { this[selectionAnimationKeyframesSymbol] = value; if ('selectionAnimationKeyframes' in base.prototype) { super.selectionAnimationKeyframes = value; } resetAnimations(this); renderSelection(this); } get selectionWraps() { return super.selectionWraps; } set selectionWraps(value) { if ('selectionWraps' in base.prototype) { super.selectionWraps = value; } resetAnimations(this); renderSelection(this); } } return SelectionAnimation; }
JavaScript
animationFractionsForSelection(element, selection) { const items = element.items; if (!items) { return; } const itemCount = items.length; const selectionWraps = element.selectionWraps; return items.map((item, itemIndex) => { // How many steps from the selection point to this item? const steps = stepsToIndex(itemCount, selectionWraps, selection, itemIndex); // To convert steps to animation fraction: // steps animation fraction // 1 0 (stage right) // 0 0.5 (center stage) // -1 1 (stage left) const animationFraction = (1 - steps) / 2; return (animationFraction >= 0 && animationFraction <= 1) ? animationFraction : null; // Outside animation range }); }
animationFractionsForSelection(element, selection) { const items = element.items; if (!items) { return; } const itemCount = items.length; const selectionWraps = element.selectionWraps; return items.map((item, itemIndex) => { // How many steps from the selection point to this item? const steps = stepsToIndex(itemCount, selectionWraps, selection, itemIndex); // To convert steps to animation fraction: // steps animation fraction // 1 0 (stage right) // 0 0.5 (center stage) // -1 1 (stage left) const animationFraction = (1 - steps) / 2; return (animationFraction >= 0 && animationFraction <= 1) ? animationFraction : null; // Outside animation range }); }
JavaScript
effectTimingsForSelectionAnimation(element, fromSelection, toSelection) { const items = element.items; if (!items) { return; } const itemCount = items.length; const selectionWraps = element.selectionWraps; const toIndex = FractionalSelectionMixin.helpers.wrappedSelectionParts(toSelection, itemCount, selectionWraps).index; const totalSteps = stepsToIndex(itemCount, selectionWraps, fromSelection, toSelection); const direction = totalSteps >= 0 ? 'normal': 'reverse'; const fill = 'both'; const totalDuration = element.selectionAnimationDuration; const stepDuration = totalSteps !== 0 ? totalDuration * 2 / Math.ceil(Math.abs(totalSteps)) : 0; // No steps required, animation will be instantenous. const timings = items.map((item, itemIndex) => { const steps = stepsToIndex(itemCount, selectionWraps, itemIndex, toSelection); // If we include this item in the staggered sequence of animations we're // creating, where would the item appear in the sequence? let positionInSequence = totalSteps - steps; if (totalSteps < 0) { positionInSequence = -positionInSequence; } // So, is this item really included in the sequence? if (Math.ceil(positionInSequence) >= 0 && positionInSequence <= Math.abs(totalSteps)) { // Note that delay for first item will be negative. That will cause // the animation to start halfway through, which is what we want. const delay = stepDuration * (positionInSequence - 1)/2; const endDelay = itemIndex === toIndex ? -stepDuration/2 : // Stop halfway through. 0; // Play animation until end. return { duration: stepDuration, direction, fill, delay, endDelay }; } else { return null; } }); return timings; }
effectTimingsForSelectionAnimation(element, fromSelection, toSelection) { const items = element.items; if (!items) { return; } const itemCount = items.length; const selectionWraps = element.selectionWraps; const toIndex = FractionalSelectionMixin.helpers.wrappedSelectionParts(toSelection, itemCount, selectionWraps).index; const totalSteps = stepsToIndex(itemCount, selectionWraps, fromSelection, toSelection); const direction = totalSteps >= 0 ? 'normal': 'reverse'; const fill = 'both'; const totalDuration = element.selectionAnimationDuration; const stepDuration = totalSteps !== 0 ? totalDuration * 2 / Math.ceil(Math.abs(totalSteps)) : 0; // No steps required, animation will be instantenous. const timings = items.map((item, itemIndex) => { const steps = stepsToIndex(itemCount, selectionWraps, itemIndex, toSelection); // If we include this item in the staggered sequence of animations we're // creating, where would the item appear in the sequence? let positionInSequence = totalSteps - steps; if (totalSteps < 0) { positionInSequence = -positionInSequence; } // So, is this item really included in the sequence? if (Math.ceil(positionInSequence) >= 0 && positionInSequence <= Math.abs(totalSteps)) { // Note that delay for first item will be negative. That will cause // the animation to start halfway through, which is what we want. const delay = stepDuration * (positionInSequence - 1)/2; const endDelay = itemIndex === toIndex ? -stepDuration/2 : // Stop halfway through. 0; // Play animation until end. return { duration: stepDuration, direction, fill, delay, endDelay }; } else { return null; } }); return timings; }
JavaScript
function animateSelection(element, fromSelection, toSelection) { resetAnimations(element); // Calculate the animation timings. const items = element.items; const keyframes = element.selectionAnimationKeyframes; element[playingAnimationSymbol] = true; const timings = mixin.helpers.effectTimingsForSelectionAnimation(element, fromSelection, toSelection); // Figure out which item will be the one *after* the one we're selecting. const itemCount = items.length; const selectionWraps = element.selectionWraps; const selectionIndex = FractionalSelectionMixin.helpers.selectionParts(toSelection, itemCount, selectionWraps).index; const totalSteps = stepsToIndex(itemCount, selectionWraps, fromSelection, toSelection); const forward = totalSteps >= 0; let nextUpIndex = selectionIndex + (forward ? 1 : - 1); if (selectionWraps) { nextUpIndex = FractionalSelectionMixin.helpers.wrappedSelection(nextUpIndex, itemCount); } else if (!isItemIndexInBounds(element, nextUpIndex)) { nextUpIndex = null; // At start/end of list; don't have a next item to show. } // Play the animations using those timings. let lastAnimationDetails; timings.forEach((timing, index) => { const item = items[index]; if (timing) { showItem(item, true); const animation = item.animate(keyframes, timing); element[animationSymbol][index] = animation; if (index === nextUpIndex) { // This item will be animated, so will already be in the desired state // after the animation completes. nextUpIndex = null; } if (timing.endDelay !== 0) { // This is the animation for the item that will be left selected. // We want to clean up when this animation completes. lastAnimationDetails = { animation, index, timing, forward }; } } else { // This item doesn't participate in the animation. showItem(item, false); } }); if (lastAnimationDetails != null) { // Arrange for clean-up work to be performed. lastAnimationDetails.nextUpIndex = nextUpIndex; lastAnimationDetails.animation.onfinish = event => selectionAnimationFinished(element, lastAnimationDetails); element[lastAnimationSymbol] = lastAnimationDetails.animation; } else { // Shouldn't happen -- we should always have at least one animation. element[playingAnimationSymbol] = false; } }
function animateSelection(element, fromSelection, toSelection) { resetAnimations(element); // Calculate the animation timings. const items = element.items; const keyframes = element.selectionAnimationKeyframes; element[playingAnimationSymbol] = true; const timings = mixin.helpers.effectTimingsForSelectionAnimation(element, fromSelection, toSelection); // Figure out which item will be the one *after* the one we're selecting. const itemCount = items.length; const selectionWraps = element.selectionWraps; const selectionIndex = FractionalSelectionMixin.helpers.selectionParts(toSelection, itemCount, selectionWraps).index; const totalSteps = stepsToIndex(itemCount, selectionWraps, fromSelection, toSelection); const forward = totalSteps >= 0; let nextUpIndex = selectionIndex + (forward ? 1 : - 1); if (selectionWraps) { nextUpIndex = FractionalSelectionMixin.helpers.wrappedSelection(nextUpIndex, itemCount); } else if (!isItemIndexInBounds(element, nextUpIndex)) { nextUpIndex = null; // At start/end of list; don't have a next item to show. } // Play the animations using those timings. let lastAnimationDetails; timings.forEach((timing, index) => { const item = items[index]; if (timing) { showItem(item, true); const animation = item.animate(keyframes, timing); element[animationSymbol][index] = animation; if (index === nextUpIndex) { // This item will be animated, so will already be in the desired state // after the animation completes. nextUpIndex = null; } if (timing.endDelay !== 0) { // This is the animation for the item that will be left selected. // We want to clean up when this animation completes. lastAnimationDetails = { animation, index, timing, forward }; } } else { // This item doesn't participate in the animation. showItem(item, false); } }); if (lastAnimationDetails != null) { // Arrange for clean-up work to be performed. lastAnimationDetails.nextUpIndex = nextUpIndex; lastAnimationDetails.animation.onfinish = event => selectionAnimationFinished(element, lastAnimationDetails); element[lastAnimationSymbol] = lastAnimationDetails.animation; } else { // Shouldn't happen -- we should always have at least one animation. element[playingAnimationSymbol] = false; } }
JavaScript
function renderSelection(element, selectedIndex=element.selectedIndex, selectedFraction=element.selectedFraction) { const itemCount = element.items ? element.items.length : 0; if (itemCount === 0) { // Nothing to render. return; } if (selectedIndex < 0) { // TODO: Handle no selection. return; } let selection = selectedIndex + selectedFraction; if (element.selectionWraps) { // Apply wrapping to ensure consistent representation of selection. selection = FractionalSelectionMixin.helpers.wrappedSelection(selection, itemCount); } else { // Apply damping if necessary. selection = FractionalSelectionMixin.helpers.dampedSelection(selection, itemCount); } const previousSelection = element[previousSelectionSymbol]; // TODO: If an item changes position in the DOM, we end up animating from // its old index to its new index, but we really don't want to animate at all. if (!element[symbols.dragging] && previousSelection != null && previousSelection !== selection) { // Animate selection from previous state to new state. animateSelection(element, previousSelection, selection); } else if (selectedFraction === 0 && element[playingAnimationSymbol]) { // Already in process of animating to fraction 0. During that process, // ignore subsequent attempts to renderSelection to fraction 0. return; } else { // Render current selection state instantly. renderSelectionInstantly(element, selection); } element[previousSelectionSymbol] = selection; }
function renderSelection(element, selectedIndex=element.selectedIndex, selectedFraction=element.selectedFraction) { const itemCount = element.items ? element.items.length : 0; if (itemCount === 0) { // Nothing to render. return; } if (selectedIndex < 0) { // TODO: Handle no selection. return; } let selection = selectedIndex + selectedFraction; if (element.selectionWraps) { // Apply wrapping to ensure consistent representation of selection. selection = FractionalSelectionMixin.helpers.wrappedSelection(selection, itemCount); } else { // Apply damping if necessary. selection = FractionalSelectionMixin.helpers.dampedSelection(selection, itemCount); } const previousSelection = element[previousSelectionSymbol]; // TODO: If an item changes position in the DOM, we end up animating from // its old index to its new index, but we really don't want to animate at all. if (!element[symbols.dragging] && previousSelection != null && previousSelection !== selection) { // Animate selection from previous state to new state. animateSelection(element, previousSelection, selection); } else if (selectedFraction === 0 && element[playingAnimationSymbol]) { // Already in process of animating to fraction 0. During that process, // ignore subsequent attempts to renderSelection to fraction 0. return; } else { // Render current selection state instantly. renderSelectionInstantly(element, selection); } element[previousSelectionSymbol] = selection; }
JavaScript
function renderSelectionInstantly(element, toSelection) { if (element[resetAnimationsOnNextRenderSymbol]) { resetAnimations(element); element[resetAnimationsOnNextRenderSymbol] = false; } const animationFractions = mixin.helpers.animationFractionsForSelection(element, toSelection); animationFractions.map((animationFraction, index) => { const item = element.items[index]; if (animationFraction != null) { showItem(item, true); setAnimationFraction(element, index, animationFraction); } else { showItem(item, false); } }); }
function renderSelectionInstantly(element, toSelection) { if (element[resetAnimationsOnNextRenderSymbol]) { resetAnimations(element); element[resetAnimationsOnNextRenderSymbol] = false; } const animationFractions = mixin.helpers.animationFractionsForSelection(element, toSelection); animationFractions.map((animationFraction, index) => { const item = element.items[index]; if (animationFraction != null) { showItem(item, true); setAnimationFraction(element, index, animationFraction); } else { showItem(item, false); } }); }
JavaScript
function selectionAnimationFinished(element, details) { // When the last animation completes, show the next item in the direction // we're going. Waiting to that until this point is a bit of a hack to avoid // having a next item that's higher in the natural z-order obscure other items // during animation. const nextUpIndex = details.nextUpIndex; if (nextUpIndex != null) { if (element[animationSymbol][nextUpIndex]) { // Cancel existing selection animation so we can construct a new one. element[animationSymbol][nextUpIndex].cancel(); element[animationSymbol][nextUpIndex] = null; } const animationFraction = details.forward ? 0 : 1; setAnimationFraction(element, nextUpIndex, animationFraction); showItem(element.items[nextUpIndex], true); } element[lastAnimationSymbol].onfinish = null; element[playingAnimationSymbol] = false; }
function selectionAnimationFinished(element, details) { // When the last animation completes, show the next item in the direction // we're going. Waiting to that until this point is a bit of a hack to avoid // having a next item that's higher in the natural z-order obscure other items // during animation. const nextUpIndex = details.nextUpIndex; if (nextUpIndex != null) { if (element[animationSymbol][nextUpIndex]) { // Cancel existing selection animation so we can construct a new one. element[animationSymbol][nextUpIndex].cancel(); element[animationSymbol][nextUpIndex] = null; } const animationFraction = details.forward ? 0 : 1; setAnimationFraction(element, nextUpIndex, animationFraction); showItem(element.items[nextUpIndex], true); } element[lastAnimationSymbol].onfinish = null; element[playingAnimationSymbol] = false; }
JavaScript
function stepsToIndex(length, allowWrap, fromSelection, toSelection) { let steps = toSelection - fromSelection; // Wrapping only kicks in when list has more than 1 item. if (allowWrap && length > 1) { const wrapSteps = length - Math.abs(steps); if (wrapSteps <= 1) { // Special case steps = steps < 0 ? wrapSteps : // Wrap forward from last item to first. -wrapSteps; // Wrap backward from first item to last. } } return steps; }
function stepsToIndex(length, allowWrap, fromSelection, toSelection) { let steps = toSelection - fromSelection; // Wrapping only kicks in when list has more than 1 item. if (allowWrap && length > 1) { const wrapSteps = length - Math.abs(steps); if (wrapSteps <= 1) { // Special case steps = steps < 0 ? wrapSteps : // Wrap forward from last item to first. -wrapSteps; // Wrap backward from first item to last. } } return steps; }
JavaScript
selectItemWithTextPrefix(prefix) { if (super.selectItemWithTextPrefix) { super.selectItemWithTextPrefix(prefix); } if (prefix == null || prefix.length === 0) { return; } const index = getIndexOfItemWithTextPrefix(this, prefix); if (index >= 0) { this.selectedIndex = index; } }
selectItemWithTextPrefix(prefix) { if (super.selectItemWithTextPrefix) { super.selectItemWithTextPrefix(prefix); } if (prefix == null || prefix.length === 0) { return; } const index = getIndexOfItemWithTextPrefix(this, prefix); if (index >= 0) { this.selectedIndex = index; } }
JavaScript
function createSymbol(description) { return typeof Symbol === 'function' ? Symbol(description) : `_${description}`; }
function createSymbol(description) { return typeof Symbol === 'function' ? Symbol(description) : `_${description}`; }
JavaScript
get items() { let items; if (this[itemsSymbol] == null) { items = filterAuxiliaryElements(this.content); // Note: test for *equality* with null; don't treat undefined as a match. if (this[itemsSymbol] === null) { // Memoize the set of items. this[itemsSymbol] = items; } } else { // Return the memoized items. items = this[itemsSymbol]; } return items; }
get items() { let items; if (this[itemsSymbol] == null) { items = filterAuxiliaryElements(this.content); // Note: test for *equality* with null; don't treat undefined as a match. if (this[itemsSymbol] === null) { // Memoize the set of items. this[itemsSymbol] = items; } } else { // Return the memoized items. items = this[itemsSymbol]; } return items; }
JavaScript
function filterAuxiliaryElements(items) { const auxiliaryTags = [ 'link', 'script', 'style', 'template' ]; return [].filter.call(items, function(item) { return !item.localName || auxiliaryTags.indexOf(item.localName) < 0; }); }
function filterAuxiliaryElements(items) { const auxiliaryTags = [ 'link', 'script', 'style', 'template' ]; return [].filter.call(items, function(item) { return !item.localName || auxiliaryTags.indexOf(item.localName) < 0; }); }
JavaScript
function createTemplateWithInnerHTML(innerHTML) { const template = document.createElement('template'); // REVIEW: Is there an easier way to do this? // We'd like to just set innerHTML on the template content, but since it's // a DocumentFragment, that doesn't work. const div = document.createElement('div'); div.innerHTML = innerHTML; while (div.childNodes.length > 0) { template.content.appendChild(div.childNodes[0]); } return template; }
function createTemplateWithInnerHTML(innerHTML) { const template = document.createElement('template'); // REVIEW: Is there an easier way to do this? // We'd like to just set innerHTML on the template content, but since it's // a DocumentFragment, that doesn't work. const div = document.createElement('div'); div.innerHTML = innerHTML; while (div.childNodes.length > 0) { template.content.appendChild(div.childNodes[0]); } return template; }
JavaScript
dragEnter (cmp) { try { /* dragenter event */ let eff = this.effect(); for (let eff_idx in eff) { eff[eff_idx][0].execute(true); } } catch (e) { console.error(e.stack); throw e; } }
dragEnter (cmp) { try { /* dragenter event */ let eff = this.effect(); for (let eff_idx in eff) { eff[eff_idx][0].execute(true); } } catch (e) { console.error(e.stack); throw e; } }
JavaScript
dragLeave (cmp) { try { /* dragleave event */ let eff = this.effect(); for (let eff_idx in eff) { eff[eff_idx][0].execute(false); } } catch (e) { console.error(e.stack); throw e; } }
dragLeave (cmp) { try { /* dragleave event */ let eff = this.effect(); for (let eff_idx in eff) { eff[eff_idx][0].execute(false); } } catch (e) { console.error(e.stack); throw e; } }
JavaScript
function PinkNoise (context, opts) { // Defaults opts = opts || {}; var p = this.meta.params; this.noise = new WhiteNoise(context, opts); this.source = this.output = this.noise.source; }
function PinkNoise (context, opts) { // Defaults opts = opts || {}; var p = this.meta.params; this.noise = new WhiteNoise(context, opts); this.source = this.output = this.noise.source; }
JavaScript
function pinkify (module) { var buffer = module.source.buffer, b = [0,0,0,0,0,0,0], channelData, white, i, j, pink = []; for (i = 0; i < module.channels; i++) { pink[i] = new Float32Array(module.bufferSize); channelData = buffer.getChannelData(i); for (j = 0; j < module.bufferSize; j++) { white = channelData[j]; b[0] = 0.99886 * b[0] + white * 0.0555179; b[1] = 0.99332 * b[1] + white * 0.0750759; b[2] = 0.96900 * b[2] + white * 0.1538520; b[3] = 0.86650 * b[3] + white * 0.3104856; b[4] = 0.55000 * b[4] + white * 0.5329522; b[5] = -0.7616 * b[5] - white * 0.0168980; pink[i][j] = b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6] + white * 0.5362; b[6] = white * 0.115926; } b = [0,0,0,0,0,0,0]; } // Normalize to +/- 1 and prevent positive saturation var t = minMax(pink); var coefficient = (2147483647 / 2147483648) / Math.max(Math.abs(t.min), t.max); pink.map(function (channel) { for (var k = 0; k < channel.length; k++) { channel[i] = channel[i] * coefficient; } return channel; }); for (i = 0; i < module.channels; i++) { for (j = 0; j < module.bufferSize; j++) { buffer.getChannelData(i)[j] = pink[i][j]; } } }
function pinkify (module) { var buffer = module.source.buffer, b = [0,0,0,0,0,0,0], channelData, white, i, j, pink = []; for (i = 0; i < module.channels; i++) { pink[i] = new Float32Array(module.bufferSize); channelData = buffer.getChannelData(i); for (j = 0; j < module.bufferSize; j++) { white = channelData[j]; b[0] = 0.99886 * b[0] + white * 0.0555179; b[1] = 0.99332 * b[1] + white * 0.0750759; b[2] = 0.96900 * b[2] + white * 0.1538520; b[3] = 0.86650 * b[3] + white * 0.3104856; b[4] = 0.55000 * b[4] + white * 0.5329522; b[5] = -0.7616 * b[5] - white * 0.0168980; pink[i][j] = b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6] + white * 0.5362; b[6] = white * 0.115926; } b = [0,0,0,0,0,0,0]; } // Normalize to +/- 1 and prevent positive saturation var t = minMax(pink); var coefficient = (2147483647 / 2147483648) / Math.max(Math.abs(t.min), t.max); pink.map(function (channel) { for (var k = 0; k < channel.length; k++) { channel[i] = channel[i] * coefficient; } return channel; }); for (i = 0; i < module.channels; i++) { for (j = 0; j < module.bufferSize; j++) { buffer.getChannelData(i)[j] = pink[i][j]; } } }
JavaScript
function minMax (pink) { var min = []; var max = []; for (var i = 0; i < pink.length; i++) { min.push(Math.min.apply(null, pink[i])); max.push(Math.max.apply(null, pink[i])); } return { min: Math.min.apply(null, min), max: Math.max.apply(null, max) }; }
function minMax (pink) { var min = []; var max = []; for (var i = 0; i < pink.length; i++) { min.push(Math.min.apply(null, pink[i])); max.push(Math.max.apply(null, pink[i])); } return { min: Math.min.apply(null, min), max: Math.max.apply(null, max) }; }
JavaScript
function check(){ if (document.getElementById('pw1').value == document.getElementById('pw2').value){ //disabled to prevent submitting if passwords dont match document.getElementById('submitregister').disabled = false; alert("passwords match!") }else { document.getElementById('submitregister').disabled = true; alert("passwords do not match, please enter again") } }
function check(){ if (document.getElementById('pw1').value == document.getElementById('pw2').value){ //disabled to prevent submitting if passwords dont match document.getElementById('submitregister').disabled = false; alert("passwords match!") }else { document.getElementById('submitregister').disabled = true; alert("passwords do not match, please enter again") } }
JavaScript
function display(input){ if (input.files && input.files[0]) { document.getElementById('holderpic').hidden = true; var reader = new FileReader(); reader.onload = function(e) { $('#itemImg') .attr('src', e.target.result) .width(500) .height(400); }; reader.readAsDataURL(input.files[0]); } }
function display(input){ if (input.files && input.files[0]) { document.getElementById('holderpic').hidden = true; var reader = new FileReader(); reader.onload = function(e) { $('#itemImg') .attr('src', e.target.result) .width(500) .height(400); }; reader.readAsDataURL(input.files[0]); } }
JavaScript
function updateImage(fileName, userID){ return new Promise(((resolve, reject) => { let baseSQL = `UPDATE user SET image = ? WHERE id = ?` db.query(baseSQL, [fileName, userID]) .then((myPromise) =>{ resolve(myPromise) }) .catch((err) =>{ reject(err.errno) }) })) }
function updateImage(fileName, userID){ return new Promise(((resolve, reject) => { let baseSQL = `UPDATE user SET image = ? WHERE id = ?` db.query(baseSQL, [fileName, userID]) .then((myPromise) =>{ resolve(myPromise) }) .catch((err) =>{ reject(err.errno) }) })) }
JavaScript
function newProfileImage(req, res) { return new Promise(((resolve, reject) => { let uploader = multer({storage: storage}).single('uploadImage'); uploader(req, res, ()=>{ let fileName = req.file.filename; let userID = req.user.id; req.session.passport.user.image = fileName; updateImage(fileName, userID).then((myPromise) => { resolve(myPromise)}) }); })) }
function newProfileImage(req, res) { return new Promise(((resolve, reject) => { let uploader = multer({storage: storage}).single('uploadImage'); uploader(req, res, ()=>{ let fileName = req.file.filename; let userID = req.user.id; req.session.passport.user.image = fileName; updateImage(fileName, userID).then((myPromise) => { resolve(myPromise)}) }); })) }
JavaScript
function encryptPassword(password) { return new Promise((resolve, reject) => { bcrypt.hash(password, saltRounds) .then(function(hash) { resolve(hash) }) .catch((error) => { reject(`Failed to encrypt password: ${error}`) }) }) }
function encryptPassword(password) { return new Promise((resolve, reject) => { bcrypt.hash(password, saltRounds) .then(function(hash) { resolve(hash) }) .catch((error) => { reject(`Failed to encrypt password: ${error}`) }) }) }
JavaScript
function newUser(name, email, password) { return new Promise((resolve, reject) => { console.log(password) encryptPassword(password) .then((hash) => { let sqlCommand = `INSERT INTO user (name, email, password, image) VALUES (?, ?, ?, 'none.png');` db.query(sqlCommand, [name, email, hash]) .then(() => { resolve('ok') }) .catch((err) => { // failed to query DB reject(err.errno) }) }) .catch((error) => { // failed to hash password reject(error) }) }); }
function newUser(name, email, password) { return new Promise((resolve, reject) => { console.log(password) encryptPassword(password) .then((hash) => { let sqlCommand = `INSERT INTO user (name, email, password, image) VALUES (?, ?, ?, 'none.png');` db.query(sqlCommand, [name, email, hash]) .then(() => { resolve('ok') }) .catch((err) => { // failed to query DB reject(err.errno) }) }) .catch((error) => { // failed to hash password reject(error) }) }); }
JavaScript
function check(){ if (document.getElementById('pw1').value === document.getElementById('pw2').value){ //disabled to prevent submitting if passwords dont match document.getElementById('passChange').disabled = false; alert("passwords match!") }else { document.getElementById('passChange').disabled = true; alert("passwords do not match, please enter again") } }
function check(){ if (document.getElementById('pw1').value === document.getElementById('pw2').value){ //disabled to prevent submitting if passwords dont match document.getElementById('passChange').disabled = false; alert("passwords match!") }else { document.getElementById('passChange').disabled = true; alert("passwords do not match, please enter again") } }
JavaScript
function numItems_N_days() { return new Promise((resolve, reject) => { let sqlCommand = `SELECT COUNT(*) AS number FROM item WHERE created > (NOW() - INTERVAL 7 DAY) AND item.available = 1 AND item.approved = 1` db.query(sqlCommand) .then(Result => { resolve(Result) }).catch((err) => { reject(`(${err}) ERROR --> DB call failed`) }) }) }
function numItems_N_days() { return new Promise((resolve, reject) => { let sqlCommand = `SELECT COUNT(*) AS number FROM item WHERE created > (NOW() - INTERVAL 7 DAY) AND item.available = 1 AND item.approved = 1` db.query(sqlCommand) .then(Result => { resolve(Result) }).catch((err) => { reject(`(${err}) ERROR --> DB call failed`) }) }) }
JavaScript
function dumpDataSet(dataSet, output) { // the dataSet.elements object contains properties for each element parsed. The name of the property // is based on the elements tag and looks like 'xGGGGEEEE' where GGGG is the group number and EEEE is the // element number both with lowercase hexadecimal letters. For example, the Series Description DICOM element 0008,103E would // be named 'x0008103e'. Here we iterate over each property (element) so we can build a string describing its // contents to add to the output array try { for (var propertyName in dataSet.elements) { var element = dataSet.elements[propertyName]; // The output string begins with the element tag, length and VR (if present). VR is undefined for // implicit transfer syntaxes var text = element.tag; text += " length=" + element.length; if (element.hadUndefinedLength) { text += " <strong>(-1)</strong>"; } text += "; "; if (element.vr) { text += " VR=" + element.vr + "; "; } var color = 'black'; // Here we check for Sequence items and iterate over them if present. items will not be set in the // element object for elements that don't have SQ VR type. Note that implicit little endian // sequences will are currently not parsed. if (element.items) { output.push('<li>' + text + '</li>'); output.push('<ul>'); // each item contains its own data set so we iterate over the items // and recursively call this function var itemNumber = 0; element.items.forEach(function (item) { output.push('<li>Item #' + itemNumber++ + ' ' + item.tag + '</li>') output.push('<ul>'); dumpDataSet(item.dataSet, output); output.push('</ul>'); }); output.push('</ul>'); } else if (element.fragments) { output.push('<li>' + text + '</li>'); output.push('<ul>'); // each item contains its own data set so we iterate over the items // and recursively call this function var itemNumber = 0; element.fragments.forEach(function (fragment) { var basicOffset; if(element.basicOffsetTable) { basicOffset = element.basicOffsetTable[itemNumber]; } var str = '<li>Fragment #' + itemNumber++ + ' offset = ' + fragment.offset; str += '(' + basicOffset + ')'; str += '; length = ' + fragment.length + '</li>'; output.push(str); }); output.push('</ul>'); } else { // if the length of the element is less than 512 we try to show it. We put this check in // to avoid displaying large strings which makes it harder to use. if (element.length < 512) { // Since the dataset might be encoded using implicit transfer syntax and we aren't using // a data dictionary, we need some simple logic to figure out what data types these // elements might be. Since the dataset might also be explicit we could be switch on the // VR and do a better job on this, perhaps we can do that in another example // First we check to see if the element's length is appropriate for a UI or US VR. // US is an important type because it is used for the // image Rows and Columns so that is why those are assumed over other VR types. if (element.length === 2) { text += " (" + dataSet.uint16(propertyName) + ")"; } else if (element.length === 4) { text += " (" + dataSet.uint32(propertyName) + ")"; } // Next we ask the dataset to give us the element's data in string form. Most elements are // strings but some aren't so we do a quick check to make sure it actually has all ascii // characters so we know it is reasonable to display it. var str = dataSet.string(propertyName); var stringIsAscii = isASCII(str); if (stringIsAscii) { // the string will be undefined if the element is present but has no data // (i.e. attribute is of type 2 or 3 ) so we only display the string if it has // data. Note that the length of the element will be 0 to indicate "no data" // so we don't put anything here for the value in that case. if (str !== undefined) { text += '"' + str + '"'; } } else { if (element.length !== 2 && element.length !== 4) { color = '#C8C8C8'; // If it is some other length and we have no string text += "<i>binary data</i>"; } } if (element.length === 0) { color = '#C8C8C8'; } } else { color = '#C8C8C8'; // Add text saying the data is too long to show... text += "<i>data too long to show</i>"; } // finally we add the string to our output array surrounded by li elements so it shows up in the // DOM as a list output.push('<li style="color:' + color + ';">' + text + '</li>'); } } } catch(err) { var ex = { exception: err, output: output } throw ex; } }
function dumpDataSet(dataSet, output) { // the dataSet.elements object contains properties for each element parsed. The name of the property // is based on the elements tag and looks like 'xGGGGEEEE' where GGGG is the group number and EEEE is the // element number both with lowercase hexadecimal letters. For example, the Series Description DICOM element 0008,103E would // be named 'x0008103e'. Here we iterate over each property (element) so we can build a string describing its // contents to add to the output array try { for (var propertyName in dataSet.elements) { var element = dataSet.elements[propertyName]; // The output string begins with the element tag, length and VR (if present). VR is undefined for // implicit transfer syntaxes var text = element.tag; text += " length=" + element.length; if (element.hadUndefinedLength) { text += " <strong>(-1)</strong>"; } text += "; "; if (element.vr) { text += " VR=" + element.vr + "; "; } var color = 'black'; // Here we check for Sequence items and iterate over them if present. items will not be set in the // element object for elements that don't have SQ VR type. Note that implicit little endian // sequences will are currently not parsed. if (element.items) { output.push('<li>' + text + '</li>'); output.push('<ul>'); // each item contains its own data set so we iterate over the items // and recursively call this function var itemNumber = 0; element.items.forEach(function (item) { output.push('<li>Item #' + itemNumber++ + ' ' + item.tag + '</li>') output.push('<ul>'); dumpDataSet(item.dataSet, output); output.push('</ul>'); }); output.push('</ul>'); } else if (element.fragments) { output.push('<li>' + text + '</li>'); output.push('<ul>'); // each item contains its own data set so we iterate over the items // and recursively call this function var itemNumber = 0; element.fragments.forEach(function (fragment) { var basicOffset; if(element.basicOffsetTable) { basicOffset = element.basicOffsetTable[itemNumber]; } var str = '<li>Fragment #' + itemNumber++ + ' offset = ' + fragment.offset; str += '(' + basicOffset + ')'; str += '; length = ' + fragment.length + '</li>'; output.push(str); }); output.push('</ul>'); } else { // if the length of the element is less than 512 we try to show it. We put this check in // to avoid displaying large strings which makes it harder to use. if (element.length < 512) { // Since the dataset might be encoded using implicit transfer syntax and we aren't using // a data dictionary, we need some simple logic to figure out what data types these // elements might be. Since the dataset might also be explicit we could be switch on the // VR and do a better job on this, perhaps we can do that in another example // First we check to see if the element's length is appropriate for a UI or US VR. // US is an important type because it is used for the // image Rows and Columns so that is why those are assumed over other VR types. if (element.length === 2) { text += " (" + dataSet.uint16(propertyName) + ")"; } else if (element.length === 4) { text += " (" + dataSet.uint32(propertyName) + ")"; } // Next we ask the dataset to give us the element's data in string form. Most elements are // strings but some aren't so we do a quick check to make sure it actually has all ascii // characters so we know it is reasonable to display it. var str = dataSet.string(propertyName); var stringIsAscii = isASCII(str); if (stringIsAscii) { // the string will be undefined if the element is present but has no data // (i.e. attribute is of type 2 or 3 ) so we only display the string if it has // data. Note that the length of the element will be 0 to indicate "no data" // so we don't put anything here for the value in that case. if (str !== undefined) { text += '"' + str + '"'; } } else { if (element.length !== 2 && element.length !== 4) { color = '#C8C8C8'; // If it is some other length and we have no string text += "<i>binary data</i>"; } } if (element.length === 0) { color = '#C8C8C8'; } } else { color = '#C8C8C8'; // Add text saying the data is too long to show... text += "<i>data too long to show</i>"; } // finally we add the string to our output array surrounded by li elements so it shows up in the // DOM as a list output.push('<li style="color:' + color + ';">' + text + '</li>'); } } } catch(err) { var ex = { exception: err, output: output } throw ex; } }
JavaScript
function expect(actual) { return { toBe(expected) { if (actual !== expected) { throw new Error(`${actual} is not a ${expected}`); } }, }; }
function expect(actual) { return { toBe(expected) { if (actual !== expected) { throw new Error(`${actual} is not a ${expected}`); } }, }; }
JavaScript
function expect(actual) { return { toBe(expected) { if (actual !== expected) { throw new Error(`${actual} is not equal to ${expected}`); } }, }; }
function expect(actual) { return { toBe(expected) { if (actual !== expected) { throw new Error(`${actual} is not equal to ${expected}`); } }, }; }
JavaScript
function test(title, callback) { try { callback(); console.log(`✓ ${title}`); } catch (error) { console.error(`✕ ${title}`); console.error(error); } }
function test(title, callback) { try { callback(); console.log(`✓ ${title}`); } catch (error) { console.error(`✕ ${title}`); console.error(error); } }
JavaScript
function install(Vue) { if (install.installed) { return; } install.installed = true; Vue.component('VueDirection', component); }
function install(Vue) { if (install.installed) { return; } install.installed = true; Vue.component('VueDirection', component); }
JavaScript
function menuRender(data) { for (var i = 0; i < data.length; i++) { var menu = data[i]; var subMenu = menu.children; var str = '<li url="' + menu.url + '" tabindex=' + menu.title + ' ><i class="fa fa-caret-right" style="visibility:hidden"></i><i class="fa fa-circle" style="color: green"></i><i class="' + menu.icon + '"></i><span>' + menu.title + '</span></li>'; if (subMenu != null && subMenu.length != 0) { var second_level_menu = ""; for (var j = 0; j < subMenu.length; j++) { second_level_menu += '<li url="' + subMenu[j].url + '" tabindex=' + subMenu[j].title + '><span></span><i class="' + subMenu[j].icon + '"></i><span>' + subMenu[j].title + '<span></li>'; } str = '<li children="true"><i class="fa fa-caret-right"></i><i class="' + menu.icon + '"></i><span>' + menu.title + '</span></li><div class="second_level" style="display:none"><ul>' + second_level_menu + '</ul></div>'; $(".sidebar ul:first").append(str); continue; } $(".sidebar ul:first").append(str); } //bind menu event of click $(".sidebar li").on('click', function (event) { event.stopPropagation();//prevent event propagate to parent node when click on current node //if not leaf node,expand current node. if ($(this).attr("children") == "true") { //toggle menu icon when expand current node. $(this).find("i:first").toggleClass(function () { if ($(this).hasClass("fa fa-caret-right")) { $(this).removeClass(); return 'fa fa-caret-down'; } else { $(this).removeClass(); return 'fa fa-caret-right'; } }); $(this).next("div.second_level").slideToggle("normal"); return; } // $(".sidebar li").not($(this)).css({color:'',borderBottom: '',borderBottomColor:''}); // $(this).css({color:'#339933',borderBottom: '2px solid',borderBottomColor:'#339933'}); $(".sidebar li").not($(this)).css({ color: '', borderBottom: '', borderBottomColor: '', backgroundColor: '' }); $(this).css({ color: '#339933', borderBottom: '', backgroundColor: 'rgba(51, 153, 51, 0.5)' }); //if current node is leaf node,load html resource. var tabindex = $(this).attr("tabindex"); var url = $(this).attr("url"); createTabByTitle(tabindex, url); checkServicesHealthy(this,tabindex); }); }
function menuRender(data) { for (var i = 0; i < data.length; i++) { var menu = data[i]; var subMenu = menu.children; var str = '<li url="' + menu.url + '" tabindex=' + menu.title + ' ><i class="fa fa-caret-right" style="visibility:hidden"></i><i class="fa fa-circle" style="color: green"></i><i class="' + menu.icon + '"></i><span>' + menu.title + '</span></li>'; if (subMenu != null && subMenu.length != 0) { var second_level_menu = ""; for (var j = 0; j < subMenu.length; j++) { second_level_menu += '<li url="' + subMenu[j].url + '" tabindex=' + subMenu[j].title + '><span></span><i class="' + subMenu[j].icon + '"></i><span>' + subMenu[j].title + '<span></li>'; } str = '<li children="true"><i class="fa fa-caret-right"></i><i class="' + menu.icon + '"></i><span>' + menu.title + '</span></li><div class="second_level" style="display:none"><ul>' + second_level_menu + '</ul></div>'; $(".sidebar ul:first").append(str); continue; } $(".sidebar ul:first").append(str); } //bind menu event of click $(".sidebar li").on('click', function (event) { event.stopPropagation();//prevent event propagate to parent node when click on current node //if not leaf node,expand current node. if ($(this).attr("children") == "true") { //toggle menu icon when expand current node. $(this).find("i:first").toggleClass(function () { if ($(this).hasClass("fa fa-caret-right")) { $(this).removeClass(); return 'fa fa-caret-down'; } else { $(this).removeClass(); return 'fa fa-caret-right'; } }); $(this).next("div.second_level").slideToggle("normal"); return; } // $(".sidebar li").not($(this)).css({color:'',borderBottom: '',borderBottomColor:''}); // $(this).css({color:'#339933',borderBottom: '2px solid',borderBottomColor:'#339933'}); $(".sidebar li").not($(this)).css({ color: '', borderBottom: '', borderBottomColor: '', backgroundColor: '' }); $(this).css({ color: '#339933', borderBottom: '', backgroundColor: 'rgba(51, 153, 51, 0.5)' }); //if current node is leaf node,load html resource. var tabindex = $(this).attr("tabindex"); var url = $(this).attr("url"); createTabByTitle(tabindex, url); checkServicesHealthy(this,tabindex); }); }
JavaScript
function addIndicesAndRemoveCloud(image) { var ndvi = image.normalizedDifference([nir, red]); var ndwi = image.normalizedDifference([green, nir]); var mndwi = image.normalizedDifference([green, swir1]); image = image.addBands([ndvi.rename('ndvi'), ndwi.rename('ndwi'), mndwi.rename('mndwi')]); var cloud = image.select('cfmask').lt(2); return image.updateMask(cloud); }
function addIndicesAndRemoveCloud(image) { var ndvi = image.normalizedDifference([nir, red]); var ndwi = image.normalizedDifference([green, nir]); var mndwi = image.normalizedDifference([green, swir1]); image = image.addBands([ndvi.rename('ndvi'), ndwi.rename('ndwi'), mndwi.rename('mndwi')]); var cloud = image.select('cfmask').lt(2); return image.updateMask(cloud); }
JavaScript
function addIndicesAndRemoveCloud1995(image) { var ndvi = image.normalizedDifference(['B4', 'B3']); var ndwi = image.normalizedDifference(['B2', 'B4']); var mndwi = image.normalizedDifference(['B2', 'B5']); image = image.addBands([ndvi.rename('ndvi'), ndwi.rename('ndwi'), mndwi.rename('mndwi')]); var cloud = image.select('cfmask').lt(2); return image.updateMask(cloud); }
function addIndicesAndRemoveCloud1995(image) { var ndvi = image.normalizedDifference(['B4', 'B3']); var ndwi = image.normalizedDifference(['B2', 'B4']); var mndwi = image.normalizedDifference(['B2', 'B5']); image = image.addBands([ndvi.rename('ndvi'), ndwi.rename('ndwi'), mndwi.rename('mndwi')]); var cloud = image.select('cfmask').lt(2); return image.updateMask(cloud); }
JavaScript
function identifyChange(waterLoss, newClassified) { // water to exposed lake bed var first = waterLoss.eq(1).and(newClassified.eq(5)).remap([1], [5]); // water to dead vegetation var second = waterLoss.eq(1).and(newClassified.eq(3)).remap([1], [3]); // water to riparian sediment var third = waterLoss.eq(1).and(newClassified.eq(2)).remap([1], [2]); // water to riparian vegetation var fourth = waterLoss.eq(1).and(newClassified.eq(1)).remap([1], [1]); var fifth = waterLoss.remap([0,1], [0, 6]) var change = fifth.addBands([first, second, third, fourth]); change = change.reduce(ee.Reducer.min()) return change; }
function identifyChange(waterLoss, newClassified) { // water to exposed lake bed var first = waterLoss.eq(1).and(newClassified.eq(5)).remap([1], [5]); // water to dead vegetation var second = waterLoss.eq(1).and(newClassified.eq(3)).remap([1], [3]); // water to riparian sediment var third = waterLoss.eq(1).and(newClassified.eq(2)).remap([1], [2]); // water to riparian vegetation var fourth = waterLoss.eq(1).and(newClassified.eq(1)).remap([1], [1]); var fifth = waterLoss.remap([0,1], [0, 6]) var change = fifth.addBands([first, second, third, fourth]); change = change.reduce(ee.Reducer.min()) return change; }
JavaScript
function identifyFullChange(oldClassified, newClassified) { var waterToRS = oldClassified.eq(0).and(newClassified.eq(2)).remap([0, 1], [0, 1]); var waterToRV = oldClassified.eq(0).and(newClassified.eq(1)).remap([0, 1], [0, 2]); var waterToELB = oldClassified.neq(0).and(newClassified.eq(5)).remap([0, 1], [0, 3]); var RSToRV = oldClassified.eq(2).and(newClassified.eq(1)).remap([0, 1], [0, 4]); var RSToDV = oldClassified.eq(2).and(newClassified.eq(3)).remap([0, 1], [0, 5]); var RSToELB = oldClassified.eq(2).and(newClassified.eq(5)).remap([0, 1], [0, 6]); var RVToDV = oldClassified.eq(1).and(newClassified.eq(3)).remap([0, 1], [0, 7]); var RVToELB = oldClassified.eq(1).and(newClassified.eq(5)).remap([0, 1], [0, 8]); var waterToDV = oldClassified.eq(0).and(newClassified.eq(3)).remap([0, 1], [0, 9]); var change = waterToRS.addBands([waterToRV, waterToELB, RSToRV, RSToDV, RSToELB, RVToELB, RVToDV, waterToDV]) change = change.reduce(ee.Reducer.max()) return change; }
function identifyFullChange(oldClassified, newClassified) { var waterToRS = oldClassified.eq(0).and(newClassified.eq(2)).remap([0, 1], [0, 1]); var waterToRV = oldClassified.eq(0).and(newClassified.eq(1)).remap([0, 1], [0, 2]); var waterToELB = oldClassified.neq(0).and(newClassified.eq(5)).remap([0, 1], [0, 3]); var RSToRV = oldClassified.eq(2).and(newClassified.eq(1)).remap([0, 1], [0, 4]); var RSToDV = oldClassified.eq(2).and(newClassified.eq(3)).remap([0, 1], [0, 5]); var RSToELB = oldClassified.eq(2).and(newClassified.eq(5)).remap([0, 1], [0, 6]); var RVToDV = oldClassified.eq(1).and(newClassified.eq(3)).remap([0, 1], [0, 7]); var RVToELB = oldClassified.eq(1).and(newClassified.eq(5)).remap([0, 1], [0, 8]); var waterToDV = oldClassified.eq(0).and(newClassified.eq(3)).remap([0, 1], [0, 9]); var change = waterToRS.addBands([waterToRV, waterToELB, RSToRV, RSToDV, RSToELB, RVToELB, RVToDV, waterToDV]) change = change.reduce(ee.Reducer.max()) return change; }
JavaScript
_analyse(msg) { if (this.startTime == null) { this.startTime = new Date().getTime(); } // Register the time when the last message has arrived (or when the last timer was called, when no message has arrived) this.endTime = new Date().getTime(); // Calculate the seconds since the last time we arrived here var seconds = (this.endTime - this.startTime) / 1000; var remainder = (seconds - Math.floor(seconds)) * 1000; seconds = Math.floor(seconds); // Correct the end time with the remainder, since the time interval since the last message (until now) is skipped in the current calculation. // Otherwise timeslices will get behind, and the curve would have some overshoot (at startup) period before reaching the final speed. this.endTime -= remainder; //console.log(seconds + " seconds between " + new Date(this.startTime).toISOString().slice(11, 23) + " and " + new Date(this.endTime).toISOString().slice(11, 23)); // Normally we will arrive here at least once every second. However the timer can be delayed, which means it is N seconds ago since we last arrived here. // In that case an output message needs to be send for every second cell in the ring buffer. // We need to do this, before we can handle the new msg (because that belongs to the next cell second). // In the first second we store (the count of) all received messages, except the last one (that has been received in the next second). // Indeed all messages belong to the first second. Because when - after that second - a new msg would have arrived, that second bucket // would have been processed immediately. So all msg statistics that are currently cached, belong to that first second bucket... // In the next second we store that last message (if available). In all later seconds (of this loop) we will store 0. // This will be arranged at the end of the first loop (because we might not have a second loop ...). for(var i = 0; i < seconds; i++) { // Check the content of the tail buffer cell (before it is being removed by inserting a new cell at the head), if available already. // When no cell available, then 0 messages will be removed from the buffer... var originalCellContent = { msgCount: 0, msgStatistic: 0 } if (this.circularBuffer.size() >= this.bufferSize) { originalCellContent = this.circularBuffer.get(this.bufferSize-1); } // The total msg count is the sum of all message counts in the circular buffer. Instead of summing all those buffer cells continiously // (over and over again), we will update the sum together with the buffer content: this is much FASTER. // Sum = previous sum + message count of last second (which is going to be added to the buffer) // - message count of the first second (which is going to be removed from the buffer). this.msgCountInBuffer = this.msgCountInBuffer + this.newMsgCount - originalCellContent.msgCount; // Same way of working for the msg statistic ... this.msgStatisticInBuffer = this.msgStatisticInBuffer + this.newMsgStatistic - originalCellContent.msgStatistic; // Store the new msg count in the circular buffer (which will also trigger deletion of the oldest cell at the buffer trail), together with the msg data this.circularBuffer.enq({ msgCount: this.newMsgCount, msgStatistic: this.newMsgStatistic }); var msgCountInBuffer = this.msgCountInBuffer; var msgStatisticInBuffer = this.msgStatisticInBuffer; var isStartup = false; // Do a linear interpolation if required (only relevant in the startup period) if (this.circularBuffer.size() < this.circularBuffer.capacity()) { isStartup = true; if (this.estimationStartup == true && this.circularBuffer.size() > 0) { msgCountInBuffer = Math.floor(msgCountInBuffer * this.circularBuffer.capacity() / this.circularBuffer.size()); msgStatisticInBuffer = Math.floor(msgStatisticInBuffer * this.circularBuffer.capacity() / this.circularBuffer.size()); } } // Update the status in the editor with the last message count (only if it has changed), or when switching between startup and real if (this.prevTotalMsgCount != this.msgCountInBuffer || this.prevMsgStatisticInBuffer != this.msgStatisticInBuffer || this.prevStartup != isStartup) { this.changeStatus(msgCountInBuffer, msgStatisticInBuffer, isStartup); this.prevTotalMsgCount = msgCountInBuffer; this.prevMsgStatisticInBuffer = msgStatisticInBuffer; } // Send a message on the first output port, when not ignored during the startup period if (this.ignoreStartup == false || isStartup == false) { this.sendMsg(msgCountInBuffer, msgStatisticInBuffer); } // When everything has been send (in the first second), start from 0 again this.newMsgCount = 0; this.newMsgStatistic = 0; // Our new second starts at the end of the previous second this.startTime = this.endTime; this.prevStartup = isStartup; } // When there is a message, it's statistics needs to be added to the NEXT second cell. if (msg) { this.newMsgCount += 1; this.newMsgStatistic += this.calculateMsgStatistic(msg); } }
_analyse(msg) { if (this.startTime == null) { this.startTime = new Date().getTime(); } // Register the time when the last message has arrived (or when the last timer was called, when no message has arrived) this.endTime = new Date().getTime(); // Calculate the seconds since the last time we arrived here var seconds = (this.endTime - this.startTime) / 1000; var remainder = (seconds - Math.floor(seconds)) * 1000; seconds = Math.floor(seconds); // Correct the end time with the remainder, since the time interval since the last message (until now) is skipped in the current calculation. // Otherwise timeslices will get behind, and the curve would have some overshoot (at startup) period before reaching the final speed. this.endTime -= remainder; //console.log(seconds + " seconds between " + new Date(this.startTime).toISOString().slice(11, 23) + " and " + new Date(this.endTime).toISOString().slice(11, 23)); // Normally we will arrive here at least once every second. However the timer can be delayed, which means it is N seconds ago since we last arrived here. // In that case an output message needs to be send for every second cell in the ring buffer. // We need to do this, before we can handle the new msg (because that belongs to the next cell second). // In the first second we store (the count of) all received messages, except the last one (that has been received in the next second). // Indeed all messages belong to the first second. Because when - after that second - a new msg would have arrived, that second bucket // would have been processed immediately. So all msg statistics that are currently cached, belong to that first second bucket... // In the next second we store that last message (if available). In all later seconds (of this loop) we will store 0. // This will be arranged at the end of the first loop (because we might not have a second loop ...). for(var i = 0; i < seconds; i++) { // Check the content of the tail buffer cell (before it is being removed by inserting a new cell at the head), if available already. // When no cell available, then 0 messages will be removed from the buffer... var originalCellContent = { msgCount: 0, msgStatistic: 0 } if (this.circularBuffer.size() >= this.bufferSize) { originalCellContent = this.circularBuffer.get(this.bufferSize-1); } // The total msg count is the sum of all message counts in the circular buffer. Instead of summing all those buffer cells continiously // (over and over again), we will update the sum together with the buffer content: this is much FASTER. // Sum = previous sum + message count of last second (which is going to be added to the buffer) // - message count of the first second (which is going to be removed from the buffer). this.msgCountInBuffer = this.msgCountInBuffer + this.newMsgCount - originalCellContent.msgCount; // Same way of working for the msg statistic ... this.msgStatisticInBuffer = this.msgStatisticInBuffer + this.newMsgStatistic - originalCellContent.msgStatistic; // Store the new msg count in the circular buffer (which will also trigger deletion of the oldest cell at the buffer trail), together with the msg data this.circularBuffer.enq({ msgCount: this.newMsgCount, msgStatistic: this.newMsgStatistic }); var msgCountInBuffer = this.msgCountInBuffer; var msgStatisticInBuffer = this.msgStatisticInBuffer; var isStartup = false; // Do a linear interpolation if required (only relevant in the startup period) if (this.circularBuffer.size() < this.circularBuffer.capacity()) { isStartup = true; if (this.estimationStartup == true && this.circularBuffer.size() > 0) { msgCountInBuffer = Math.floor(msgCountInBuffer * this.circularBuffer.capacity() / this.circularBuffer.size()); msgStatisticInBuffer = Math.floor(msgStatisticInBuffer * this.circularBuffer.capacity() / this.circularBuffer.size()); } } // Update the status in the editor with the last message count (only if it has changed), or when switching between startup and real if (this.prevTotalMsgCount != this.msgCountInBuffer || this.prevMsgStatisticInBuffer != this.msgStatisticInBuffer || this.prevStartup != isStartup) { this.changeStatus(msgCountInBuffer, msgStatisticInBuffer, isStartup); this.prevTotalMsgCount = msgCountInBuffer; this.prevMsgStatisticInBuffer = msgStatisticInBuffer; } // Send a message on the first output port, when not ignored during the startup period if (this.ignoreStartup == false || isStartup == false) { this.sendMsg(msgCountInBuffer, msgStatisticInBuffer); } // When everything has been send (in the first second), start from 0 again this.newMsgCount = 0; this.newMsgStatistic = 0; // Our new second starts at the end of the previous second this.startTime = this.endTime; this.prevStartup = isStartup; } // When there is a message, it's statistics needs to be added to the NEXT second cell. if (msg) { this.newMsgCount += 1; this.newMsgStatistic += this.calculateMsgStatistic(msg); } }
JavaScript
function onSaving(newPage, attr, options) { var self = this, tasks = []; ghostBookshelf.Model.prototype.onSaving.apply(this, arguments); if (self.hasChanged('email')) { tasks.gravatar = (function lookUpGravatar() { return gravatar.lookup({ email: self.get('email') }).then(function (response) { if (response && response.image) { self.set('image', response.image); } }); })(); } if (this.hasChanged('slug') || !this.get('slug')) { tasks.slug = (function generateSlug() { return ghostBookshelf.Model.generateSlug( User, self.get('slug') || self.get('name'), { status: 'all', transacting: options.transacting, shortSlug: !self.get('slug') }) .then(function then(slug) { self.set({slug: slug}); }); })(); } /** * CASE: add model, hash password * CASE: update model, hash password * * Important: * - Password hashing happens when we import a database * - we do some pre-validation checks, because onValidate is called AFTER onSaving */ if (self.isNew() || self.hasChanged('password')) { this.set('password', String(this.get('password'))); if (!validatePasswordLength(this.get('password'))) { return Promise.reject(new errors.ValidationError({message: i18n.t('errors.models.user.passwordDoesNotComplyLength')})); } tasks.hashPassword = (function hashPassword() { return generatePasswordHash(self.get('password')) .then(function (hash) { self.set('password', hash); }); })(); } return Promise.props(tasks); }
function onSaving(newPage, attr, options) { var self = this, tasks = []; ghostBookshelf.Model.prototype.onSaving.apply(this, arguments); if (self.hasChanged('email')) { tasks.gravatar = (function lookUpGravatar() { return gravatar.lookup({ email: self.get('email') }).then(function (response) { if (response && response.image) { self.set('image', response.image); } }); })(); } if (this.hasChanged('slug') || !this.get('slug')) { tasks.slug = (function generateSlug() { return ghostBookshelf.Model.generateSlug( User, self.get('slug') || self.get('name'), { status: 'all', transacting: options.transacting, shortSlug: !self.get('slug') }) .then(function then(slug) { self.set({slug: slug}); }); })(); } /** * CASE: add model, hash password * CASE: update model, hash password * * Important: * - Password hashing happens when we import a database * - we do some pre-validation checks, because onValidate is called AFTER onSaving */ if (self.isNew() || self.hasChanged('password')) { this.set('password', String(this.get('password'))); if (!validatePasswordLength(this.get('password'))) { return Promise.reject(new errors.ValidationError({message: i18n.t('errors.models.user.passwordDoesNotComplyLength')})); } tasks.hashPassword = (function hashPassword() { return generatePasswordHash(self.get('password')) .then(function (hash) { self.set('password', hash); }); })(); } return Promise.props(tasks); }
JavaScript
function contextUser(options) { // Default to context user if (options.context && options.context.user) { return options.context.user; // Other wise use the internal override } else if (options.context && options.context.internal) { return 1; // This is the user object, so try using this user's id } else if (this.get('id')) { return this.get('id'); } else { throw new errors.NotFoundError({ message: i18n.t('errors.models.user.missingContext') }); } }
function contextUser(options) { // Default to context user if (options.context && options.context.user) { return options.context.user; // Other wise use the internal override } else if (options.context && options.context.internal) { return 1; // This is the user object, so try using this user's id } else if (this.get('id')) { return this.get('id'); } else { throw new errors.NotFoundError({ message: i18n.t('errors.models.user.missingContext') }); } }
JavaScript
function permittedOptions(methodName) { var options = ghostBookshelf.Model.permittedOptions(), // whitelists for the `options` hash argument on methods, by method name. // these are the only options that can be passed to Bookshelf / Knex. validOptions = { findOne: ['withRelated', 'status'], setup: ['id'], edit: ['withRelated', 'id'], findPage: ['page', 'limit', 'columns', 'filter', 'order', 'status'], findAll: ['filter'] }; if (validOptions[methodName]) { options = options.concat(validOptions[methodName]); } return options; }
function permittedOptions(methodName) { var options = ghostBookshelf.Model.permittedOptions(), // whitelists for the `options` hash argument on methods, by method name. // these are the only options that can be passed to Bookshelf / Knex. validOptions = { findOne: ['withRelated', 'status'], setup: ['id'], edit: ['withRelated', 'id'], findPage: ['page', 'limit', 'columns', 'filter', 'order', 'status'], findAll: ['filter'] }; if (validOptions[methodName]) { options = options.concat(validOptions[methodName]); } return options; }
JavaScript
function findOne(dataToClone, options) { var query, status, optInc, data = _.cloneDeep(dataToClone), lookupRole = data.role; delete data.role; data = _.defaults(data || {}, { status: 'active' }); status = data.status; delete data.status; options = options || {}; optInc = options.include; options.withRelated = _.union(options.withRelated, options.include); data = this.filterData(data); // Support finding by role if (lookupRole) { options.withRelated = _.union(options.withRelated, ['roles']); options.include = _.union(options.include, ['roles']); query = this.forge(data, {include: options.include}); query.query('join', 'roles_users', 'users.id', '=', 'roles_users.user_id'); query.query('join', 'roles', 'roles_users.role_id', '=', 'roles.id'); query.query('where', 'roles.name', '=', lookupRole); } else { // We pass include to forge so that toJSON has access query = this.forge(data, {include: options.include}); } if (status === 'active') { query.query('whereIn', 'status', activeStates); } else if (status !== 'all') { query.query('where', {status: status}); } options = this.filterOptions(options, 'findOne'); delete options.include; options.include = optInc; return query.fetch(options); }
function findOne(dataToClone, options) { var query, status, optInc, data = _.cloneDeep(dataToClone), lookupRole = data.role; delete data.role; data = _.defaults(data || {}, { status: 'active' }); status = data.status; delete data.status; options = options || {}; optInc = options.include; options.withRelated = _.union(options.withRelated, options.include); data = this.filterData(data); // Support finding by role if (lookupRole) { options.withRelated = _.union(options.withRelated, ['roles']); options.include = _.union(options.include, ['roles']); query = this.forge(data, {include: options.include}); query.query('join', 'roles_users', 'users.id', '=', 'roles_users.user_id'); query.query('join', 'roles', 'roles_users.role_id', '=', 'roles.id'); query.query('where', 'roles.name', '=', lookupRole); } else { // We pass include to forge so that toJSON has access query = this.forge(data, {include: options.include}); } if (status === 'active') { query.query('whereIn', 'status', activeStates); } else if (status !== 'all') { query.query('where', {status: status}); } options = this.filterOptions(options, 'findOne'); delete options.include; options.include = optInc; return query.fetch(options); }
JavaScript
function handleClick(event, container, options) { options = optionsFor(container, options) var link = event.currentTarget if (link.tagName.toUpperCase() !== 'A') throw "$.fn.pjax or $.pjax.click requires an anchor element" // Middle click, cmd click, and ctrl click should open // links in a new tab as normal. if ( event.which > 1 || event.metaKey ) return // Ignore cross origin links if ( location.protocol !== link.protocol || location.host !== link.host ) return // Ignore anchors on the same page if ( link.hash && link.href.replace(link.hash, '') === location.href.replace(location.hash, '') ) return var defaults = { url: link.href, container: $(link).attr('data-pjax'), target: link, clickedElement: $(link), // DEPRECATED: use target fragment: null } $.pjax($.extend({}, defaults, options)) event.preventDefault() return false }
function handleClick(event, container, options) { options = optionsFor(container, options) var link = event.currentTarget if (link.tagName.toUpperCase() !== 'A') throw "$.fn.pjax or $.pjax.click requires an anchor element" // Middle click, cmd click, and ctrl click should open // links in a new tab as normal. if ( event.which > 1 || event.metaKey ) return // Ignore cross origin links if ( location.protocol !== link.protocol || location.host !== link.host ) return // Ignore anchors on the same page if ( link.hash && link.href.replace(link.hash, '') === location.href.replace(location.hash, '') ) return var defaults = { url: link.href, container: $(link).attr('data-pjax'), target: link, clickedElement: $(link), // DEPRECATED: use target fragment: null } $.pjax($.extend({}, defaults, options)) event.preventDefault() return false }
JavaScript
function extractContainer(data, xhr, options) { var obj = {} // Prefer X-PJAX-URL header if it was set, otherwise fallback to // using the original requested url. obj.url = stripPjaxParam(xhr.getResponseHeader('X-PJAX-URL') || options.url) // Attempt to parse response html into elements var $data = $(data) // If response data is empty, return fast if ($data.length === 0) return obj // If there's a <title> tag in the response, use it as // the page's title. obj.title = findAll($data, 'title').last().text() if (options.fragment) { // If they specified a fragment, look for it in the response // and pull it out. var $fragment = findAll($data, options.fragment).first() if ($fragment.length) { obj.contents = $fragment.contents() // If there's no title, look for data-title and title attributes // on the fragment if (!obj.title) obj.title = $fragment.attr('title') || $fragment.data('title') } } else if (!/<html/i.test(data)) { obj.contents = $data } // Clean up any <title> tags if (obj.contents) { // Remove any parent title elements obj.contents = obj.contents.not('title') // Then scrub any titles from their descendents obj.contents.find('title').remove() } // Trim any whitespace off the title if (obj.title) obj.title = $.trim(obj.title) return obj }
function extractContainer(data, xhr, options) { var obj = {} // Prefer X-PJAX-URL header if it was set, otherwise fallback to // using the original requested url. obj.url = stripPjaxParam(xhr.getResponseHeader('X-PJAX-URL') || options.url) // Attempt to parse response html into elements var $data = $(data) // If response data is empty, return fast if ($data.length === 0) return obj // If there's a <title> tag in the response, use it as // the page's title. obj.title = findAll($data, 'title').last().text() if (options.fragment) { // If they specified a fragment, look for it in the response // and pull it out. var $fragment = findAll($data, options.fragment).first() if ($fragment.length) { obj.contents = $fragment.contents() // If there's no title, look for data-title and title attributes // on the fragment if (!obj.title) obj.title = $fragment.attr('title') || $fragment.data('title') } } else if (!/<html/i.test(data)) { obj.contents = $data } // Clean up any <title> tags if (obj.contents) { // Remove any parent title elements obj.contents = obj.contents.not('title') // Then scrub any titles from their descendents obj.contents.find('title').remove() } // Trim any whitespace off the title if (obj.title) obj.title = $.trim(obj.title) return obj }
JavaScript
function validateObject(obj, properties) { if (typeof obj === 'undefined') { return false; } for (var i = 0; i < properties.length; i++) { var property = properties[i]; if (typeof obj[property] === 'undefined') { return false; } } return true; }
function validateObject(obj, properties) { if (typeof obj === 'undefined') { return false; } for (var i = 0; i < properties.length; i++) { var property = properties[i]; if (typeof obj[property] === 'undefined') { return false; } } return true; }
JavaScript
add_disease(disease_name, date_sick, date_healthy, username, symptoms) { return this.pool.getConnection().then(con => { return add_disease_with_connection(disease_name, date_sick, date_healthy, username, symptoms, true, con); }); }
add_disease(disease_name, date_sick, date_healthy, username, symptoms) { return this.pool.getConnection().then(con => { return add_disease_with_connection(disease_name, date_sick, date_healthy, username, symptoms, true, con); }); }
JavaScript
delete_disease(diseaseID) { var delete_sym_query = mysql.format(delete_disease_sym_sql, [diseaseID]); var delete_disease_query = mysql.format(delete_disease_sql, [diseaseID]); return this.pool.getConnection().then(connection => { var res = Promise.all( [connection.query(delete_sym_query), connection.query(delete_disease_query) ]); connection.release(); return res; }); }
delete_disease(diseaseID) { var delete_sym_query = mysql.format(delete_disease_sym_sql, [diseaseID]); var delete_disease_query = mysql.format(delete_disease_sql, [diseaseID]); return this.pool.getConnection().then(connection => { var res = Promise.all( [connection.query(delete_sym_query), connection.query(delete_disease_query) ]); connection.release(); return res; }); }
JavaScript
delete_symptom(symID) { var delete_sym_query = mysql.format(delete_single_symptom_sql, [symID]); return this.pool.getConnection().then(connection => { var res = connection.query(delete_sym_query); connection.release(); return res; }) }
delete_symptom(symID) { var delete_sym_query = mysql.format(delete_single_symptom_sql, [symID]); return this.pool.getConnection().then(connection => { var res = connection.query(delete_sym_query); connection.release(); return res; }) }
JavaScript
add_symptom(userID, symID) { var add_sym_query = mysql.format(add_sym_sql, [symID, userID]); return this.pool.getConnection().then(connection => { var res = connection.query(add_sym_query); connection.release(); return res; }).then(result => { if (result.affectedRows === 0) { throw new Error("You must be sick"); } else { return symID; s } }) }
add_symptom(userID, symID) { var add_sym_query = mysql.format(add_sym_sql, [symID, userID]); return this.pool.getConnection().then(connection => { var res = connection.query(add_sym_query); connection.release(); return res; }).then(result => { if (result.affectedRows === 0) { throw new Error("You must be sick"); } else { return symID; s } }) }
JavaScript
delete_healthy_diseases(username) { var delete_query = mysql.format(delete_user_healthy, [username, username]); return this.pool.getConnection().then(connection => { var res = connection.query(delete_query); connection.release(); return res; }); }
delete_healthy_diseases(username) { var delete_query = mysql.format(delete_user_healthy, [username, username]); return this.pool.getConnection().then(connection => { var res = connection.query(delete_query); connection.release(); return res; }); }
JavaScript
add_diagnosis_diseases() { var connection; return this.pool.getConnection().then(con => { connection = con; var res = connection.query(remove_diag_disease_sql); return res; }).then(result => { var num_to_add = 15; var promises = []; var diseases = symptom_info.disease_list; var disease_symptoms = symptom_info.disease_question_map; for(var i = 0; i < diseases.length; i++) { if(diseases[i] === "Other") { continue; } var cur_syms = disease_symptoms[diseases[i]]; for(var x = 0; x < num_to_add; x++) { promises.push(add_disease_with_connection(diseases[i], "1800-01-01", "1800-01-01", "admin", cur_syms, false, connection)); } } return Promise.all(promises); }).then(result => { connection.release(); return; }) }
add_diagnosis_diseases() { var connection; return this.pool.getConnection().then(con => { connection = con; var res = connection.query(remove_diag_disease_sql); return res; }).then(result => { var num_to_add = 15; var promises = []; var diseases = symptom_info.disease_list; var disease_symptoms = symptom_info.disease_question_map; for(var i = 0; i < diseases.length; i++) { if(diseases[i] === "Other") { continue; } var cur_syms = disease_symptoms[diseases[i]]; for(var x = 0; x < num_to_add; x++) { promises.push(add_disease_with_connection(diseases[i], "1800-01-01", "1800-01-01", "admin", cur_syms, false, connection)); } } return Promise.all(promises); }).then(result => { connection.release(); return; }) }
JavaScript
function diagnose_user(username, connection) { var user_score_query = mysql.format(get_user_score_sql, [username]); return connection.query(user_score_query).then(result => { if(result.length > 0) { var update_query = mysql.format(update_disease_sql, [result[0].disease_name, username]); connection.query(update_query); } connection.release(); return result; }); }
function diagnose_user(username, connection) { var user_score_query = mysql.format(get_user_score_sql, [username]); return connection.query(user_score_query).then(result => { if(result.length > 0) { var update_query = mysql.format(update_disease_sql, [result[0].disease_name, username]); connection.query(update_query); } connection.release(); return result; }); }
JavaScript
function add_disease_with_connection(disease_name, date_sick, date_healthy, username, symptoms, should_diagnose, connection) { if(disease_name != null) { disease_name = disease_name.replace(/-/g, " "); } var add_disease_query = mysql.format(add_disease_sql, [disease_name, date_sick, date_healthy, username]); return connection.query(add_disease_query).then(result => { var disID = result.insertId; var toPromise = []; for (var symptom in symptoms) { var add_sym_query = mysql.format(add_symptom_sql, [disID, symptoms[symptom]]) toPromise.push(connection.query(add_sym_query)); } return Promise.all(toPromise); }).then(res => { if(should_diagnose && disease_name === null) { return diagnose_user(username, connection); } else { if(disease_name === null) { connection.release(); } return []; } }); }
function add_disease_with_connection(disease_name, date_sick, date_healthy, username, symptoms, should_diagnose, connection) { if(disease_name != null) { disease_name = disease_name.replace(/-/g, " "); } var add_disease_query = mysql.format(add_disease_sql, [disease_name, date_sick, date_healthy, username]); return connection.query(add_disease_query).then(result => { var disID = result.insertId; var toPromise = []; for (var symptom in symptoms) { var add_sym_query = mysql.format(add_symptom_sql, [disID, symptoms[symptom]]) toPromise.push(connection.query(add_sym_query)); } return Promise.all(toPromise); }).then(res => { if(should_diagnose && disease_name === null) { return diagnose_user(username, connection); } else { if(disease_name === null) { connection.release(); } return []; } }); }
JavaScript
can_view_disease(userID, diseaseID) { var can_view_query = mysql.format(get_disease_sql, [userID, diseaseID]); return this.pool.getConnection().then(connection => { var res = connection.query(can_view_query); connection.release(); return res; }).then(users => { if(users.length == 0) { throw new Error("Cannot view"); } else { return; } }); }
can_view_disease(userID, diseaseID) { var can_view_query = mysql.format(get_disease_sql, [userID, diseaseID]); return this.pool.getConnection().then(connection => { var res = connection.query(can_view_query); connection.release(); return res; }).then(users => { if(users.length == 0) { throw new Error("Cannot view"); } else { return; } }); }
JavaScript
function canViewUser(req, res, next) { const can_view = req.verified === req.params.userID || req.verified === "admin" if (can_view) { next(); } else { req.http_responses.report_not_authorized(req, res); } }
function canViewUser(req, res, next) { const can_view = req.verified === req.params.userID || req.verified === "admin" if (can_view) { next(); } else { req.http_responses.report_not_authorized(req, res); } }
JavaScript
function verifyJWT(req, res, next) { req.authDB.verifyJWT(req).then(verified => { req.verified = verified; next(); }).catch(error => { req.http_responses.report_bad_token(req, res); }); }
function verifyJWT(req, res, next) { req.authDB.verifyJWT(req).then(verified => { req.verified = verified; next(); }).catch(error => { req.http_responses.report_bad_token(req, res); }); }
JavaScript
login_user(username, password, callback) { var get_salt_query = mysql.format(get_user_salt_sql, [username]); var connection; var password; this.pool.getConnection().then(con => { connection = con; return connection.query(get_salt_query);; }).then(result => { if (result == undefined || result.length == 0) { connection.release(); callback(false); return; } var password1 = bcrypt.hashSync(password, result[0].salt); var directory = __dirname + "/login_helper.php"; directory = directory.split(' ').join('\\ '); exec("php " + directory + " " + password, (error, stdout, stderr) => { var password2 = stdout; var user_exists_query = mysql.format(user_exists_sql, [username, password1]); connection.query(user_exists_query).then(result => { if (result.length > 0) { connection.release(); var token = jwt.sign({ data: { username: username, password_hash: password1 } }, process.env.JWT_SECRET, { expiresIn: '10d' }); callback(token); } else { var user_exists_query = mysql.format(user_exists_sql, [username, password2]); connection.query(user_exists_query).then(result => { connection.release(); if (result.length > 0) { var token = jwt.sign({ data: { username: username, password_hash: password2 } }, process.env.JWT_SECRET, { expiresIn: '10d' }); callback(token); } else { callback(false); } }); } }); }); }); }
login_user(username, password, callback) { var get_salt_query = mysql.format(get_user_salt_sql, [username]); var connection; var password; this.pool.getConnection().then(con => { connection = con; return connection.query(get_salt_query);; }).then(result => { if (result == undefined || result.length == 0) { connection.release(); callback(false); return; } var password1 = bcrypt.hashSync(password, result[0].salt); var directory = __dirname + "/login_helper.php"; directory = directory.split(' ').join('\\ '); exec("php " + directory + " " + password, (error, stdout, stderr) => { var password2 = stdout; var user_exists_query = mysql.format(user_exists_sql, [username, password1]); connection.query(user_exists_query).then(result => { if (result.length > 0) { connection.release(); var token = jwt.sign({ data: { username: username, password_hash: password1 } }, process.env.JWT_SECRET, { expiresIn: '10d' }); callback(token); } else { var user_exists_query = mysql.format(user_exists_sql, [username, password2]); connection.query(user_exists_query).then(result => { connection.release(); if (result.length > 0) { var token = jwt.sign({ data: { username: username, password_hash: password2 } }, process.env.JWT_SECRET, { expiresIn: '10d' }); callback(token); } else { callback(false); } }); } }); }); }); }
JavaScript
add_user(deviceID, username, unencrypt_password, latitude, longitude, dob, gender, weight, height, does_smoke, has_hypertension, has_diabetes, has_high_cholesterol) { latitude = latitude - latitude % process.env.ERR_RANGE + Number(process.env.ERR_RANGE); longitude = longitude - longitude % process.env.ERR_RANGE + Number(process.env.ERR_RANGE); var salt = bcrypt.genSaltSync(saltRounds); var password = bcrypt.hashSync(unencrypt_password, salt); var add_user_query = mysql.format(add_user_sql, [deviceID, latitude, longitude, username, password, salt, new Date(), dob, gender, weight, height, does_smoke, has_hypertension, has_diabetes, has_high_cholesterol]); return this.pool.getConnection().then(connection => { var res = connection.query(add_user_query); connection.release(); return res; }).then(result => { var token = jwt.sign({ data: { username: username, password_hash: password } }, process.env.JWT_SECRET, { expiresIn: '10d' }); return token }); }
add_user(deviceID, username, unencrypt_password, latitude, longitude, dob, gender, weight, height, does_smoke, has_hypertension, has_diabetes, has_high_cholesterol) { latitude = latitude - latitude % process.env.ERR_RANGE + Number(process.env.ERR_RANGE); longitude = longitude - longitude % process.env.ERR_RANGE + Number(process.env.ERR_RANGE); var salt = bcrypt.genSaltSync(saltRounds); var password = bcrypt.hashSync(unencrypt_password, salt); var add_user_query = mysql.format(add_user_sql, [deviceID, latitude, longitude, username, password, salt, new Date(), dob, gender, weight, height, does_smoke, has_hypertension, has_diabetes, has_high_cholesterol]); return this.pool.getConnection().then(connection => { var res = connection.query(add_user_query); connection.release(); return res; }).then(result => { var token = jwt.sign({ data: { username: username, password_hash: password } }, process.env.JWT_SECRET, { expiresIn: '10d' }); return token }); }
JavaScript
delete_user(username) { var delete_symptom_query = mysql.format(delete_user_sym_sql, [username]); var delete_disease_query = mysql.format(delete_user_diseases_sql, [username]) var delete_user_query = mysql.format(delete_user_sql, [username]) var connection; return this.pool.getConnection().then(con => { connection = con; return connection.query(delete_symptom_query); }).then(result => { return connection.query(delete_disease_query); }).then(result => { var res = connection.query(delete_user_query); connection.release(); return res; }); }
delete_user(username) { var delete_symptom_query = mysql.format(delete_user_sym_sql, [username]); var delete_disease_query = mysql.format(delete_user_diseases_sql, [username]) var delete_user_query = mysql.format(delete_user_sql, [username]) var connection; return this.pool.getConnection().then(con => { connection = con; return connection.query(delete_symptom_query); }).then(result => { return connection.query(delete_disease_query); }).then(result => { var res = connection.query(delete_user_query); connection.release(); return res; }); }
JavaScript
change_password(username, new_password) { var salt = bcrypt.genSaltSync(saltRounds); var password = bcrypt.hashSync(new_password, salt); var change_password_query = mysql.format(change_password_sql, [password, salt, username]); return this.pool.getConnection().then(connection => { var res = connection.query(change_password_query); connection.release(); return res; }).then(result => { var token = jwt.sign({ data: { username: username, password_hash: password } }, process.env.JWT_SECRET, { expiresIn: '10d' }); return token }); }
change_password(username, new_password) { var salt = bcrypt.genSaltSync(saltRounds); var password = bcrypt.hashSync(new_password, salt); var change_password_query = mysql.format(change_password_sql, [password, salt, username]); return this.pool.getConnection().then(connection => { var res = connection.query(change_password_query); connection.release(); return res; }).then(result => { var token = jwt.sign({ data: { username: username, password_hash: password } }, process.env.JWT_SECRET, { expiresIn: '10d' }); return token }); }
JavaScript
change_address(userID, latitude, longitude) { latitude = Math.ceil(latitude * 100) / 100; longitude = Math.ceil(longitude * 100) / 100; var change_address_query = mysql.format(change_address_sql, [latitude, longitude, userID]); return this.pool.getConnection().then(connection => { var res = connection.query(change_address_query); connection.release(); return res; }); }
change_address(userID, latitude, longitude) { latitude = Math.ceil(latitude * 100) / 100; longitude = Math.ceil(longitude * 100) / 100; var change_address_query = mysql.format(change_address_sql, [latitude, longitude, userID]); return this.pool.getConnection().then(connection => { var res = connection.query(change_address_query); connection.release(); return res; }); }
JavaScript
is_user_sick(userID) { var is_sick_query = mysql.format(get_user_current_sickness, [userID]); return this.pool.getConnection().then(connection => { var res = connection.query(is_sick_query); connection.release(); return res; }).then(result => { if (result.length === 0) { return false; } else { return true; } }) }
is_user_sick(userID) { var is_sick_query = mysql.format(get_user_current_sickness, [userID]); return this.pool.getConnection().then(connection => { var res = connection.query(is_sick_query); connection.release(); return res; }).then(result => { if (result.length === 0) { return false; } else { return true; } }) }
JavaScript
function castStringData(input, model) { input = input || ''; var result = ''; var subtype = model.subtype && model.subtype.type || ''; // if input has value, keep its value if (input) { result = input; } else { switch(subtype) { case 'random': result = Math.floor(Math.random() * 100000000); break; case 'uuid': result = require('node-uuid').v4().replace(/-/g, ''); break; default: result = input; } } return result; }
function castStringData(input, model) { input = input || ''; var result = ''; var subtype = model.subtype && model.subtype.type || ''; // if input has value, keep its value if (input) { result = input; } else { switch(subtype) { case 'random': result = Math.floor(Math.random() * 100000000); break; case 'uuid': result = require('node-uuid').v4().replace(/-/g, ''); break; default: result = input; } } return result; }
JavaScript
function initialize(passport, getUserByEmail, getUserById) { //done is returned as a user if authentication succeeds, returns false if authentication fails const authenticate = async (email, password, done) => { //check the email with our saved emails console.log("looking for email: ", email); const user = getUserByEmail(email); console.log("Found user: ", user); //if no user is found in our database/array //will end the function if this case is true if(user == null) { console.log("login failure incorrect email"); return done(null, false, { message: "There is no saved user with that email" }); } //use a try catch to make sure this function doesn't hang on us, it shouldn't but you never know try { //use a built-in bcrypt function to compare the password inserted, with the hashed password on the database/storage if(await brcypt.compare(password, user.password)) { console.log("login success"); return done(null, user); } else { console.log("login failure, incorrect password"); return done(null, false, { message: "password incorrect"}); } } catch(error) { //this catch handles a potential falure with our async function, returns information about failure return done(error); } }; //setting our passport strategy to use the email field on our database as the username field in the library passport.use(new LocalStratagey({ usernameField: "email" }, authenticate)); //this section will be used to keep a user logged in. passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser((id, done) => { return done(null, getUserById(id)); }); }
function initialize(passport, getUserByEmail, getUserById) { //done is returned as a user if authentication succeeds, returns false if authentication fails const authenticate = async (email, password, done) => { //check the email with our saved emails console.log("looking for email: ", email); const user = getUserByEmail(email); console.log("Found user: ", user); //if no user is found in our database/array //will end the function if this case is true if(user == null) { console.log("login failure incorrect email"); return done(null, false, { message: "There is no saved user with that email" }); } //use a try catch to make sure this function doesn't hang on us, it shouldn't but you never know try { //use a built-in bcrypt function to compare the password inserted, with the hashed password on the database/storage if(await brcypt.compare(password, user.password)) { console.log("login success"); return done(null, user); } else { console.log("login failure, incorrect password"); return done(null, false, { message: "password incorrect"}); } } catch(error) { //this catch handles a potential falure with our async function, returns information about failure return done(error); } }; //setting our passport strategy to use the email field on our database as the username field in the library passport.use(new LocalStratagey({ usernameField: "email" }, authenticate)); //this section will be used to keep a user logged in. passport.serializeUser((user, done) => done(null, user.id)); passport.deserializeUser((id, done) => { return done(null, getUserById(id)); }); }
JavaScript
function notAuthenticated(req, res, next) { if (req.isAuthenticated()) { //get the user off of the login page, since they don't need to log in //(and register page too) console.log("redirecting user to home, already logged in"); return res.redirect("/"); } next(); }
function notAuthenticated(req, res, next) { if (req.isAuthenticated()) { //get the user off of the login page, since they don't need to log in //(and register page too) console.log("redirecting user to home, already logged in"); return res.redirect("/"); } next(); }
JavaScript
function onAfterAddingFile(fileItem) { if ($window.FileReader) { var fileReader = new FileReader(); fileReader.readAsDataURL(fileItem._file); fileReader.onload = function (fileReaderEvent) { $timeout(function () { vm.selectPicture = fileReaderEvent.target.result; }, 0); vm.isUpoading = true; }; } }
function onAfterAddingFile(fileItem) { if ($window.FileReader) { var fileReader = new FileReader(); fileReader.readAsDataURL(fileItem._file); fileReader.onload = function (fileReaderEvent) { $timeout(function () { vm.selectPicture = fileReaderEvent.target.result; }, 0); vm.isUpoading = true; }; } }
JavaScript
function onSuccessItem(fileItem, response, status, headers) { // Show success message vm.success = true; // Populate user object vm.user.profileImageURL = response._id; Authentication.setUser(vm.user); vm.user = Authentication.getUser(); // Clear upload buttons cancelUpload(); }
function onSuccessItem(fileItem, response, status, headers) { // Show success message vm.success = true; // Populate user object vm.user.profileImageURL = response._id; Authentication.setUser(vm.user); vm.user = Authentication.getUser(); // Clear upload buttons cancelUpload(); }
JavaScript
function str2binl(str) { var bin = []; var mask = (1 << chrsz) - 1; for (var i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32); return bin; }
function str2binl(str) { var bin = []; var mask = (1 << chrsz) - 1; for (var i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32); return bin; }