language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Life { constructor(food, water, oxygen) { this.food = food; this.water = water; this.oxygen = oxygen; } }
JavaScript
class EasyDate { // Define our constructor, which is the function that defines our class constructor(day, month, year) { // If so, initialize with "this" this._day = day; this._month = month; this._year = year; } // add some basic methods addDays(nDays) { // Increment "this" date by n days } getDay() { return this._day; } }
JavaScript
class Foo { constructor(foo, norf) { this.foo = foo; this.norf = norf; } toUpperCase() { return `${this.foo.toUpperCase()}, ${this.norf.toUpperCase()}`; } }
JavaScript
class Bar extends Foo { constructor(foo, norf, bar ) { // must call super before you use this in subclass super(foo, norf); this.bar = bar; } toUpperCase() { return super.toUpperCase() + ' in ' + this.bar; } }
JavaScript
class Foo { constructor() { return Object.create(null); } }
JavaScript
class AsSimpleStyleableFeature { constructor(feature, conditionalStyles) { Object.assign(this, feature, {conditionalStyles}) } /** * Styles the given Leaflet layer with any supported simplestyle properties * present on this feature */ styleLeafletLayer(layer) { this.styleLeafletLayerWithStyles(layer, this.getFinalLayerStyles(layer)) } /** * Add additional, explicit simple styles to the given leaflet layer. This is * intended to be used for adding extra, temporary styling (such as * highlighting a feature) that can be subsequently removed with * popLeafletLayerSimpleStyles */ pushLeafletLayerSimpleStyles(layer, simplestyles, identifier) { if (!this.originalLeafletStyles) { this.originalLeafletStyles = [] } this.originalLeafletStyles.push({ identifier, style: _pick(layer.options, [ 'color', 'fillColor', 'fillOpacity', 'fillRule', 'stroke', 'lineCap', 'lineJoin', 'opacity', 'dashArray', 'dashOffset', 'weight', ]), icon: layer.options.icon, }) this.styleLeafletLayerWithStyles(layer, simplestyles) } /** * Restores the layer styling prior to the latest pushed styles from * pushLeafletLayerSimpleStyles, or does nothing if there are no prior styles * to restore */ popLeafletLayerSimpleStyles(layer, identifier) { if (!this.originalLeafletStyles ||this.originalLeafletStyles.length === 0) { return } if (identifier && this.originalLeafletStyles[this.originalLeafletStyles.length - 1].identifier !== identifier) { return } const priorStyle = this.originalLeafletStyles.pop() if (layer.setStyle) { layer.setStyle(priorStyle.style) } else if (_get(layer, 'options.icon.options.mrSvgMarker')) { // Restore icon, either SVG or original Leaflet layer._removeIcon() if (_get(priorStyle.icon, 'options.mrSvgMarker')) { layer.setIcon(L.vectorIcon(priorStyle.icon.options)) } else { layer.setIcon(new L.Icon.Default()) } } } /** * Styles the given Leaflet layer using the given simplestyles object of * simplestyle property names and desired values */ styleLeafletLayerWithStyles(layer, simplestyles) { if (getType(layer.feature) === 'Point') { this.styleLeafletMarkerLayer(layer, simplestyles) } else { this.styleLeafletPathLayer(layer, simplestyles) } } /** * Styles a leaflet path layer with the given line-compatible simplestyles */ styleLeafletPathLayer(layer, lineStyles) { if (!layer.setStyle) { return } _each(lineStyles, (styleValue, styleName) => { layer.setStyle({[simplestyleLineToLeafletMapping[styleName]]: styleValue}) }) } /** * Styles a leaflet marker layer with the given point-compatible simplestyles */ styleLeafletMarkerLayer(layer, pointStyles) { if (!layer.setIcon) { return } const customMarker = { mrSvgMarker: true, className: 'location-marker-icon', viewBox: '0 0 20 20', svgHeight: 40, svgWidth: 40, type: 'path', shape: { // zondicons "location" icon d: "M10 20S3 10.87 3 7a7 7 0 1 1 14 0c0 3.87-7 13-7 13zm0-11a2 2 0 1 0 0-4 2 2 0 0 0 0 4z" }, style: { fill: colors['blue-leaflet'], stroke: colors['grey-leaflet'], strokeWidth: 0.5, marginTop: '0px', marginLeft: '0px', }, iconSize: [40, 40], iconAnchor: [20, 40], // tip of marker } let useCustomMarker = false _each(pointStyles, (styleValue, styleName) => { switch (styleName) { case 'marker-color': useCustomMarker = true customMarker.style.fill = styleValue break case 'marker-size': useCustomMarker = true switch (styleValue) { case 'small': customMarker.svgHeight = 20 customMarker.svgWidth = 20 customMarker.iconAnchor = [10, 20] customMarker.iconSize = [20, 20] break case 'large': customMarker.svgHeight = 60 customMarker.svgWidth = 60 customMarker.iconAnchor = [30, 60] customMarker.iconSize = [60, 60] break default: // medium is already the default size break } break default: break } }) // If the layer already has one of our svg markers, make sure to clean it // up or else Leaflet has a tendencey to render dup markers if (_get(layer, 'options.icon.options.mrSvgMarker')) { layer._removeIcon() if (!useCustomMarker) { layer.setIcon(new L.Icon.Default()) } } if (useCustomMarker) { layer.setIcon(L.vectorIcon(customMarker)) } } /** * Returns active marker-specific simplestyles for the current layer, or * empty object if there are none for this layer */ markerSimplestyles(layer) { const styles = {} if (_get(layer, 'options.icon.options.mrSvgMarker')) { styles["marker-color"] = layer.options.icon.options.style.fill switch(layer.options.icon.options.svgHeight) { case 20: styles["marker-size"] = 'small' break case 60: styles["marker-size"] = 'large' break default: styles["marker-size"] = 'medium' break } } return styles } /** * Retrieves all simplestyle properties specified on this feature */ simplestyleFeatureProperties() { return _fromPairs(_compact(_map(supportedSimplestyles, simplestyleProperty => ( !_isUndefined(this.properties[simplestyleProperty]) ? [simplestyleProperty, this.properties[simplestyleProperty]] : null )))) } /** * Generates an object containing the final determined styles for the given * layer (taking the layer type into account), or for this feature more * broadly if no layer is specified */ getFinalLayerStyles(layer) { if (this.conditionalStyles) { return this.getConditionalStyles(layer, this.conditionalStyles) } else if (this.properties) { return this.getStyles(layer, this.simplestyleFeatureProperties(), false) } else { return {} } } /** * Apply the given styles conditionally based on whether this feature matches * the filters associated with each style. All matching styles (if any) are * combined and applied together on top of any normal styling from * simplestyle properties on this feature */ getConditionalStyles(layer, conditionalStyles) { const filterableFeature = AsFilterableFeature(this) const matchingStyles = _filter(conditionalStyles, style => filterableFeature.matchesPropertyFilter(style.propertySearch) ) if (matchingStyles.length > 0) { // flatten all matching styles into a single object const styleObject = _fromPairs(_flatten(_map(matchingStyles, match => _map(match.styles, style => [style.styleName, style.styleValue]) ))) return this.getStyles(layer, styleObject) } else { return this.getStyles(layer) } } getStyles(layer, simplestyles, mergeWithFeatureProperties=true) { const styles = mergeWithFeatureProperties ? _merge({}, this.simplestyleFeatureProperties(), simplestyles) : simplestyles // If we have a layer, only return styles applicable to that layer's type if (!layer) { return styles } const supportedStyles = getType(layer.feature) === 'Point' ? _intersection(_keys(styles), supportedSimplestylePointProperties) : _intersection(_keys(styles), supportedSimplestyleLineProperties) return _pick(styles, supportedStyles) } }
JavaScript
class XPath { constructor(parser, path) { this.parser = parser; this.path = path; this.elements = this.split(path); // System.out.println(Arrays.toString(elements)); } // TODO: check for invalid token/rule names, bad syntax split(path) { let input = new ANTLRInputStream_1.ANTLRInputStream(path); let lexer = new XPathLexer_1.XPathLexer(input); lexer.recover = (e) => { throw e; }; lexer.removeErrorListeners(); lexer.addErrorListener(new XPathLexerErrorListener_1.XPathLexerErrorListener()); let tokenStream = new CommonTokenStream_1.CommonTokenStream(lexer); try { tokenStream.fill(); } catch (e) { if (e instanceof LexerNoViableAltException_1.LexerNoViableAltException) { let pos = lexer.charPositionInLine; let msg = "Invalid tokens or characters at index " + pos + " in path '" + path + "' -- " + e.message; throw new RangeError(msg); } throw e; } let tokens = tokenStream.getTokens(); // System.out.println("path="+path+"=>"+tokens); let elements = []; let n = tokens.length; let i = 0; loop: while (i < n) { let el = tokens[i]; let next; switch (el.type) { case XPathLexer_1.XPathLexer.ROOT: case XPathLexer_1.XPathLexer.ANYWHERE: let anywhere = el.type === XPathLexer_1.XPathLexer.ANYWHERE; i++; next = tokens[i]; let invert = next.type === XPathLexer_1.XPathLexer.BANG; if (invert) { i++; next = tokens[i]; } let pathElement = this.getXPathElement(next, anywhere); pathElement.invert = invert; elements.push(pathElement); i++; break; case XPathLexer_1.XPathLexer.TOKEN_REF: case XPathLexer_1.XPathLexer.RULE_REF: case XPathLexer_1.XPathLexer.WILDCARD: elements.push(this.getXPathElement(el, false)); i++; break; case Token_1.Token.EOF: break loop; default: throw new Error("Unknowth path element " + el); } } return elements; } /** * Convert word like {@code *} or {@code ID} or {@code expr} to a path * element. {@code anywhere} is {@code true} if {@code //} precedes the * word. */ getXPathElement(wordToken, anywhere) { if (wordToken.type == Token_1.Token.EOF) { throw new Error("Missing path element at end of path"); } let word = wordToken.text; if (word == null) { throw new Error("Expected wordToken to have text content."); } let ttype = this.parser.getTokenType(word); let ruleIndex = this.parser.getRuleIndex(word); switch (wordToken.type) { case XPathLexer_1.XPathLexer.WILDCARD: return anywhere ? new XPathWildcardAnywhereElement_1.XPathWildcardAnywhereElement() : new XPathWildcardElement_1.XPathWildcardElement(); case XPathLexer_1.XPathLexer.TOKEN_REF: case XPathLexer_1.XPathLexer.STRING: if (ttype === Token_1.Token.INVALID_TYPE) { throw new Error(word + " at index " + wordToken.startIndex + " isn't a valid token name"); } return anywhere ? new XPathTokenAnywhereElement_1.XPathTokenAnywhereElement(word, ttype) : new XPathTokenElement_1.XPathTokenElement(word, ttype); default: if (ruleIndex == -1) { throw new Error(word + " at index " + wordToken.startIndex + " isn't a valid rule name"); } return anywhere ? new XPathRuleAnywhereElement_1.XPathRuleAnywhereElement(word, ruleIndex) : new XPathRuleElement_1.XPathRuleElement(word, ruleIndex); } } static findAll(tree, xpath, parser) { let p = new XPath(parser, xpath); return p.evaluate(tree); } /** * Return a list of all nodes starting at {@code t} as root that satisfy the * path. The root {@code /} is relative to the node passed to * {@link #evaluate}. */ evaluate(t) { let dummyRoot = new ParserRuleContext_1.ParserRuleContext(); dummyRoot.addChild(t); let work = [dummyRoot]; let i = 0; while (i < this.elements.length) { let next = []; // WAS LinkedHashSet<ParseTree> for (let node of work) { if (node.childCount > 0) { // only try to match next element if it has children // e.g., //func/*/stat might have a token node for which // we can't go looking for stat nodes. let matching = this.elements[i].evaluate(node); next = next.concat(matching); } } i++; work = next; } return work; } }
JavaScript
class TransferLocationInfo { /* * Create a new TransferLocationInfo. * * @param{{ volumeName: !string, breadcrumbsPath: !string, isTeamDrive: boolean, initialEntries: !Array<TestEntryInfo> }} opts Options for creating TransferLocationInfo. */ constructor(opts) { /** * The volume type (e.g. downloads, drive, drive_recent, * drive_shared_with_me, drive_offline) or team drive name. * @type {string} */ this.volumeName = opts.volumeName; /** @type {string} */ this.breadcrumbsPath = opts.breadcrumbsPath; /** * Whether this transfer location is a team drive. Defaults to false. * @type {boolean} */ this.isTeamDrive = opts.isTeamDrive || false; /** * Expected initial contents in the volume. * @type {Array<TestEntryInfo>} */ this.initialEntries = opts.initialEntries; } }
JavaScript
class TransferInfo { /* * Create a new TransferInfo. * * @param{{ fileToTransfer: !TestEntryInfo, source: !TransferLocationInfo, destination: !TransferLocationInfo, expectedDialogText: string, isMove: boolean, expectFailure: boolean, }} opts Options for creating TransferInfo. */ constructor(opts) { /** * The file to copy or move. Must be in the source location. * @type {!TestEntryInfo} */ this.fileToTransfer = opts.fileToTransfer; /** * The source location. * @type {!TransferLocationInfo} */ this.source = opts.source; /** * The destination location. * @type {!TransferLocationInfo} */ this.destination = opts.destination; /** * The expected content of the transfer dialog (including any buttons), or * undefined if no dialog is expected. * @type {string} */ this.expectedDialogText = opts.expectedDialogText || undefined; /** * True if this transfer is for a move operation, false for a copy * operation. * @type {!boolean} */ this.isMove = opts.isMove || false; /** * Whether the test is expected to fail, i.e. transferring to a folder * without correct permissions. * @type {!boolean} */ this.expectFailure = opts.expectFailure || false; } }
JavaScript
class DialogExampleSimple extends React.Component { state = { open: false, }; handleOpen = () => { this.setState({open: true}); console.log("5555555555555555555555555555555555555555555555555555"); }; handleClose = () => { this.setState({open: false}); }; render() { const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={this.handleClose} onClick={this.handleClose} />, <FlatButton label="Submit" primary={true} keyboardFocused={true} onTouchTap={this.handleClose} onClick={this.handleClose} />, ]; return ( <div> <MuiThemeProvider> <RaisedButton label="SUBMIT" onTouchTap={this.handleOpen} onClick={this.handleOpen}/> </MuiThemeProvider> <MuiThemeProvider> <Dialog title="Submit Your Form" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > you will get an answer in one hour </Dialog> </MuiThemeProvider> </div> ); } }
JavaScript
class TemplateResult { constructor(strings, values, type, processor) { this.strings = strings; this.values = values; this.type = type; this.processor = processor; } /** * Returns a string of HTML used to create a `<template>` element. */ getHTML() { const l = this.strings.length - 1; let html = ''; let isCommentBinding = false; for (let i = 0; i < l; i++) { const s = this.strings[i]; // For each binding we want to determine the kind of marker to insert // into the template source before it's parsed by the browser's HTML // parser. The marker type is based on whether the expression is in an // attribute, text, or comment position. // * For node-position bindings we insert a comment with the marker // sentinel as its text content, like <!--{{lit-guid}}-->. // * For attribute bindings we insert just the marker sentinel for the // first binding, so that we support unquoted attribute bindings. // Subsequent bindings can use a comment marker because multi-binding // attributes must be quoted. // * For comment bindings we insert just the marker sentinel so we don't // close the comment. // // The following code scans the template source, but is *not* an HTML // parser. We don't need to track the tree structure of the HTML, only // whether a binding is inside a comment, and if not, if it appears to be // the first binding in an attribute. const commentOpen = s.lastIndexOf('<!--'); // We're in comment position if we have a comment open with no following // comment close. Because <-- can appear in an attribute value there can // be false positives. isCommentBinding = (commentOpen > -1 || isCommentBinding) && s.indexOf('-->', commentOpen + 1) === -1; // Check to see if we have an attribute-like sequence preceding the // expression. This can match "name=value" like structures in text, // comments, and attribute values, so there can be false-positives. const attributeMatch = lastAttributeNameRegex.exec(s); if (attributeMatch === null) { // We're only in this branch if we don't have a attribute-like // preceding sequence. For comments, this guards against unusual // attribute values like <div foo="<!--${'bar'}">. Cases like // <!-- foo=${'bar'}--> are handled correctly in the attribute branch // below. html += s + (isCommentBinding ? commentMarker : nodeMarker); } else { // For attributes we use just a marker sentinel, and also append a // $lit$ suffix to the name to opt-out of attribute-specific parsing // that IE and Edge do for style and certain SVG attributes. html += s.substr(0, attributeMatch.index) + attributeMatch[1] + attributeMatch[2] + boundAttributeSuffix + attributeMatch[3] + marker; } } html += this.strings[l]; return html; } getTemplateElement() { const template = document.createElement('template'); let value = this.getHTML(); if (policy !== undefined) { // this is secure because `this.strings` is a TemplateStringsArray. // TODO: validate this when // https://github.com/tc39/proposal-array-is-template-object is // implemented. value = policy.createHTML(value); } template.innerHTML = value; return template; }}
JavaScript
class SVGTemplateResult extends TemplateResult { getHTML() { return `<svg>${super.getHTML()}</svg>`; } getTemplateElement() { const template = super.getTemplateElement(); const content = template.content; const svgElement = content.firstChild; content.removeChild(svgElement); reparentNodes(content, svgElement.firstChild); return template; }}
JavaScript
class VolumeReference { /** * Create a VolumeReference. * @member {string} name Name of the volume being referenced. * @member {boolean} [readOnly] The flag indicating whether the volume is * read only. Default is 'false'. * @member {string} destinationPath The path within the container at which * the volume should be mounted. Only valid path characters are allowed. */ constructor() { } /** * Defines the metadata of VolumeReference * * @returns {object} metadata of VolumeReference * */ mapper() { return { required: false, serializedName: 'VolumeReference', type: { name: 'Composite', className: 'VolumeReference', modelProperties: { name: { required: true, serializedName: 'name', type: { name: 'String' } }, readOnly: { required: false, serializedName: 'readOnly', type: { name: 'Boolean' } }, destinationPath: { required: true, serializedName: 'destinationPath', type: { name: 'String' } } } } }; } }
JavaScript
class MetadataResource extends construct_compat_1.Construct { constructor(scope, id) { super(scope, id); const metadataServiceExists = token_1.Token.isUnresolved(scope.region) || region_info_1.RegionInfo.get(scope.region).cdkMetadataResourceAvailable; if (metadataServiceExists) { const resource = new cfn_resource_1.CfnResource(this, 'Default', { type: 'AWS::CDK::Metadata', properties: { Analytics: lazy_1.Lazy.string({ produce: () => formatAnalytics(runtime_info_1.constructInfoFromStack(scope)) }), }, }); // In case we don't actually know the region, add a condition to determine it at deploy time if (token_1.Token.isUnresolved(scope.region)) { const condition = new cfn_condition_1.CfnCondition(this, 'Condition', { expression: makeCdkMetadataAvailableCondition(), }); // To not cause undue template changes condition.overrideLogicalId('CDKMetadataAvailable'); resource.cfnOptions.condition = condition; } } } }
JavaScript
class GeneratecomponentController { constructor($state) { 'ngInject' this.$state = $state; this.name = 'generatecomponent'; } }
JavaScript
class ListTemplate extends Template { /** * Constructor * @param {Object} params * @param {String} [params.direction="horizontal"] - Horizontal or vertical * @param {HTMLLIElement|Template} params.item_template - A cloneable HTMLElement * to populate the list with */ constructor({ direction = "horizontal", item_template = null, elements = { next: '.list-next', previous: '.list-previous', list: '.list-items' } } = {}) { super({elements}); // This template simply cannot work without a cloneable HTMLElement if(!(item_template instanceof HTMLElement)){ throw new Error("item_template must be an HTMLElement"); } /** * Which way the arrows display and the items move * "horizontal" - arrows are on the left/right, items move left/right * "vertical" - arrows on the top/bottom, items moves up/down * @type {String} */ this.direction = direction.toLowerCase(); /** * The list item template * @type {HTMLElement|Template} */ this.item_template = item_template; /** * Item element manager * @type {ElementManager} */ this.items = new ElementManager({template: this.item_template}); } /** * Attach button handlers. */ onConnected(){ this.items.appendTo(this.elements.list); this.attachButtonHandlers(); } /** * Attach button handlers */ attachButtonHandlers(){ this.elements.next.addEventListener('click', () => { this.next(); }); this.elements.previous.addEventListener('click', () => { this.previous(); }); } /** * Go to the next item */ next(){ } /** * Go to the previous item */ previous(){ } /** * Go to a specific item */ goTo(){ } }
JavaScript
class Select extends Component { constructor(props, context) { super(props, context); this._onAddDrop = this._onAddDrop.bind(this); this._onRemoveDrop = this._onRemoveDrop.bind(this); this._onForceClose = this._onForceClose.bind(this); this._onSearchChange = this._onSearchChange.bind(this); this._onNextOption = this._onNextOption.bind(this); this._onPreviousOption = this._onPreviousOption.bind(this); this._onEnter = this._onEnter.bind(this); this._stopPropagation = this._stopPropagation.bind(this); this._onInputKeyDown = this._onInputKeyDown.bind(this); this._announceOptions = this._announceOptions.bind(this); this.state = { announceChange: false, activeOptionIndex: -1, dropActive: false, searchText: '', value: this._normalizeValue(props, {}) }; } componentWillReceiveProps (nextProps) { if (nextProps.hasOwnProperty('value')) { this.setState({ value: this._normalizeValue(nextProps, this.state) }); } } componentDidUpdate (prevProps, prevState) { const { inline, options } = this.props; const { announceChange, dropActive } = this.state; const { intl } = this.context; // Set up keyboard listeners appropriate to the current state. let activeKeyboardHandlers = { up: this._onPreviousOption, down: this._onNextOption, enter: this._onEnter, left: this._stopPropagation, right: this._stopPropagation }; if (! inline) { activeKeyboardHandlers.esc = this._onForceClose; activeKeyboardHandlers.tab = this._onForceClose; } // the order here is important, need to turn off keys before turning on if (! dropActive && prevState.dropActive) { document.removeEventListener('click', this._onRemoveDrop); KeyboardAccelerators.stopListeningToKeyboard(this, activeKeyboardHandlers); if (this._drop) { this._drop.remove(); this._drop = undefined; } } if ((inline && ! prevProps.inline) || (dropActive && ! prevState.dropActive)) { if (! inline) { document.addEventListener('click', this._onRemoveDrop); } KeyboardAccelerators.startListeningToKeyboard(this, activeKeyboardHandlers); if (! inline) { // If this is inside a FormField, place the drop in reference to it. const control = findAncestor(this.componentRef, FORM_FIELD) || this.componentRef; this._drop = new Drop(control, this._renderOptions(`${CLASS_ROOT}__drop`), { align: { top: 'bottom', left: 'left' }, context: this.context, responsive: false // so suggestion changes don't re-align }); } if (this._searchRef) { this._searchRef.focus(); this._searchRef._inputRef.select(); } } else if (dropActive && prevState.dropActive) { this._drop.render(this._renderOptions(`${CLASS_ROOT}__drop`)); } if (announceChange && options) { const matchResultsMessage = Intl.getMessage( intl, 'Match Results', { count: options.length } ); let navigationHelpMessage = ''; if (options.length) { navigationHelpMessage = `(${Intl.getMessage(intl, 'Navigation Help')})`; } announce(`${matchResultsMessage} ${navigationHelpMessage}`); this.setState({ announceChange: false }); } } componentWillUnmount () { document.removeEventListener('click', this._onRemoveDrop); if (this._drop) { this._drop.remove(); } } _normalizeValue (props, state) { const { multiple, value } = props; let normalizedValue = value; if (multiple) { if (value) { if (! Array.isArray(value)) { normalizedValue = [value]; } } else { normalizedValue = []; } } return normalizedValue; } _announceOptions (index) { const { intl } = this.context; const labelMessage = this._renderValue(this.props.options[index]); const enterSelectMessage = Intl.getMessage(intl, 'Enter Select'); announce(`${labelMessage} ${enterSelectMessage}`); } _onInputKeyDown (event) { const up = 38; const down = 40; if (event.keyCode === up || event.keyCode === down) { // stop the input to move the cursor when options are present event.preventDefault(); } } _onSearchChange (event) { const { inline } = this.props; this.setState({ announceChange: true, activeOptionIndex: -1, dropActive: ! inline, searchText: event.target.value }); if (this.props.onSearch) { this.props.onSearch(event); } } _onAddDrop (event) { const { options, value } = this.props; event.preventDefault(); // Get values of options, so we can highlight selected option if (options) { const optionValues = options.map((option) => { if (option && typeof option === 'object') { return option.value; } else { return option; } }); const activeOptionIndex = optionValues.indexOf(value); this.setState({ dropActive: true, activeOptionIndex: activeOptionIndex }); } } _onRemoveDrop (event) { if (!this._searchRef || !findDOMNode(this._searchRef).contains(event.target)) { this.setState({dropActive: false}); } } _onForceClose () { this.setState({dropActive: false}); } _onNextOption (event) { event.preventDefault(); let index = this.state.activeOptionIndex; index = Math.min(index + 1, this.props.options.length - 1); this.setState({activeOptionIndex: index}, this._announceOptions.bind(this, index)); } _onPreviousOption (event) { event.preventDefault(); let index = this.state.activeOptionIndex; index = Math.max(index - 1, 0); this.setState({activeOptionIndex: index}, this._announceOptions.bind(this, index)); } _valueForSelectedOption (option) { const { multiple } = this.props; const { value } = this.state; let nextValue; if (multiple) { nextValue = value.slice(0); let index; for (index = 0; index < nextValue.length; index += 1) { if (this._valueEqualsOption(nextValue[index], option)) { break; } } if (index < nextValue.length) { // already existing, remove nextValue.splice(index, 1); } else { // not there, add nextValue.push(option); } } else { nextValue = option; } return nextValue; } _onEnter (event) { const { onChange, options } = this.props; const { activeOptionIndex } = this.state; const { intl } = this.context; if (activeOptionIndex >= 0) { event.preventDefault(); // prevent submitting forms const option = options[activeOptionIndex]; const value = this._valueForSelectedOption(option); this.setState({ dropActive: false, value }, () => { const optionMessage = this._renderLabel(option); const selectedMessage = Intl.getMessage(intl, 'Selected'); announce(`${optionMessage} ${selectedMessage}`); }); if (onChange) { onChange({ target: this.inputRef, option, value }); } } else { this.setState({ dropActive: false }); } } _stopPropagation () { if (findDOMNode(this._searchRef).contains(document.activeElement)) { return true; } } _onClickOption (option) { const { onChange } = this.props; const value = this._valueForSelectedOption(option); this.setState({ dropActive: false, value }); if (onChange) { onChange({ target: this.inputRef, option, value }); } } _renderLabel (option) { if (option && typeof option === 'object') { // revert for announce as label is often a complex object return option.label || option.value || ''; } else { return (undefined === option || null === option) ? '' : option; } } _renderValue (option) { const { intl } = this.context; if (Array.isArray(option)) { // Could be an Array when !inline+multiple if (1 === option.length) { return this._renderValue(option[0]); } else if (option.length > 1) { const selectedMultiple = Intl.getMessage( intl, 'Selected Multiple', { count: option.length } ); return selectedMultiple; } } else if (option && typeof option === 'object') { return option.label || option.value || ''; } else { return (undefined === option || null === option) ? '' : option; } } _valueEqualsOption (value, option) { let result = false; if (value && typeof value === 'object') { if (option && typeof option === 'object') { result = (value.value === option.value); } else { result = (value.value === option); } } else { if (option && typeof option === 'object') { result = (value === option.value); } else { result = (value === option); } } return result; } _optionSelected (option, value) { let result = false; if (value && Array.isArray(value)) { result = value.some(val => this._valueEqualsOption(val, option)); } else { result = this._valueEqualsOption(value, option); } return result; } _renderOptions (className, restProps={}) { const { intl } = this.context; const { id, inline, multiple, options, onSearch, value, searchPlaceHolder = Intl.getMessage(intl, 'Search') } = this.props; const { activeOptionIndex, searchText } = this.state; let search; if (onSearch) { search = ( <Search className={`${CLASS_ROOT}__search`} ref={(ref) => this._searchRef = ref} inline={true} fill={true} responsive={false} pad="medium" placeHolder={searchPlaceHolder} value={searchText} onDOMChange={this._onSearchChange} onKeyDown={this._onInputKeyDown} /> ); } let items; if (options) { items = options.map((option, index) => { const selected = this._optionSelected(option, value); let classes = classnames( { [`${CLASS_ROOT}__option`]: true, [`${CLASS_ROOT}__option--selected`]: selected, [`${CLASS_ROOT}__option--active`]: index === activeOptionIndex } ); let content = this._renderLabel(option); if (option && option.icon) { content = ( <span>{option.icon} {content}</span> ); } let itemOnClick; if (inline) { const itemId = `${option ? (option.value || option) : index}`; const Type = (multiple ? CheckBox : RadioButton ); content = ( <Type key={itemId} id={`${ id ? id + '-' + itemId : itemId}`} label={content} checked={selected} onChange={this._onClickOption.bind(this, option)} /> ); } else { itemOnClick = (e) => { e.stopPropagation(); this._onClickOption.bind(this, option)(); }; } return ( <li key={index} className={classes} onClick={itemOnClick}> {content} </li> ); }); } let onClick; if (! inline) { onClick = this._onRemoveDrop; } return ( <div {...restProps} className={className}> {search} <ol className={`${CLASS_ROOT}__options`} onClick={onClick}> {items} </ol> </div> ); } render () { const { className, inline, placeHolder, value } = this.props; const { active } = this.state; const { intl } = this.context; let classes = classnames( CLASS_ROOT, { [`${CLASS_ROOT}--active`]: active, [`${CLASS_ROOT}--inline`]: inline }, className ); const restProps = Props.omit(this.props, Object.keys(Select.propTypes)); if (inline) { return this._renderOptions(classes, restProps); } else { const renderedValue = this._renderValue(value); const shouldRenderElement = React.isValidElement(renderedValue); return ( <div ref={ref => this.componentRef = ref} className={classes} onClick={this._onAddDrop}> {shouldRenderElement && renderedValue} <input {...restProps} ref={ref => this.inputRef = ref} type={shouldRenderElement ? 'hidden' : 'text'} className={`${INPUT} ${CLASS_ROOT}__input`} placeholder={placeHolder} readOnly={true} value={renderedValue || ''} /> <Button className={`${CLASS_ROOT}__control`} a11yTitle={Intl.getMessage(intl, 'Select Icon')} icon={<CaretDownIcon />} onClick={this._onAddDrop} /> </div> ); } } }
JavaScript
class Tabs { constructor({ navSelector, contentSelector, initial } = {}) { /** * The value of the active tab * @type {string} */ this.active = initial; /** * The CSS selector used to target the tab navigation element * @type {string} */ this._navSelector = navSelector; /** * A reference to the HTML navigation element the tab controller is bound to * @type {HTMLElement|null} */ this._nav = null; /** * The CSS selector used to target the tab content element * @type {string} */ this._contentSelector = contentSelector; /** * A reference to the HTML container element of the tab content * @type {HTMLElement|null} */ this._content = null; } /* -------------------------------------------- */ /** * Bind the Tabs controller to an HTML application * @param {HTMLElement} html */ bind(html) { // Identify navigation element this._nav = html.querySelector(this._navSelector); if (!this._nav) return; // Identify content container if (!this._contentSelector) this._content = null;else if (html.matches(this._contentSelector)) this._content = html;else this._content = html.querySelector(this._contentSelector); // Initialize the active tab this.activate(this.active); // Register listeners this._nav.addEventListener("click", this._onClickNav.bind(this)); } /* -------------------------------------------- */ /** * Activate a new tab by name * @param {string} tabName * @param {boolean} triggerCallback */ activate(tabName, { triggerCallback = false } = {}) { // Validate the requested tab name const group = this._nav.dataset.group; const items = this._nav.querySelectorAll("[data-tab]"); if (!items.length) return; const valid = Array.from(items).some(i => i.dataset.tab === tabName); if (!valid) tabName = items[0].dataset.tab; // Change active tab for (let i of items) { i.classList.toggle("active", i.dataset.tab === tabName); } // Change active content if (this._content) { const tabs = this._content.querySelectorAll("[data-tab]"); for (let t of tabs) { if (t.dataset.group && t.dataset.group !== group) continue; t.classList.toggle("active", t.dataset.tab === tabName); } } // Store the active tab this.active = tabName; } /* -------------------------------------------- */ /** * Handle click events on the tab navigation entries * @param {MouseEvent} event A left click event * @private */ _onClickNav(event) { const tab = event.target.closest("[data-tab]"); if (!tab) return; event.preventDefault(); const tabName = tab.dataset.tab; if (tabName !== this.active) this.activate(tabName, { triggerCallback: true }); } }
JavaScript
class ItemWfrp4e extends Item { // Upon creation, assign a blank image if item is new (not duplicated) instead of mystery-man default static async create(data, options) { if (!data.img) data.img = "systems/dh2e/icons/blank.png"; super.create(data, options); } /******* ITEM EXPAND DATA *********** * Expansion data is called when an item's dropdown is created. Each function organizes a 'properties' array. * Each element of the array is shown at the bottom of the dropdown expansions. The description is shown above this. */ /** * Call the appropriate item type's expansion data. * * @param {Object} htmlOptions Currently unused - example: show secrets? */ getExpandData(htmlOptions) { const data = this[`_${this.data.type}ExpandData`](); data.description.value = data.description.value || ""; data.description.value = TextEditor.enrichHTML(data.description.value, htmlOptions); return data; } // Trapping Expansion Data _trappingExpandData() { const data = duplicate(this.data.data); data.properties = []; return data; } // Money Expansion Data _moneyExpandData() { const data = duplicate(this.data.data); data.properties = [`${game.i18n.localize("ITEM.PenniesValue")}: ${data.coinValue.value}`]; return data; } // Psychology Expansion Data _psychologyExpandData() { const data = duplicate(this.data.data); data.properties = []; return data; } // Mutation Expansion Data _mutationExpandData() { const data = duplicate(this.data.data); data.properties = []; data.properties.push(WFRP4E.mutationTypes[this.data.data.mutationType.value]); if (this.data.data.modifier.value) data.properties.push(this.data.data.modifier.value) return data; } // Disease Expansion Data _diseaseExpandData() { const data = duplicate(this.data.data); data.properties = []; data.properties.push(`<b>${game.i18n.localize("Contraction")}:</b> ${data.contraction.value}`); data.properties.push(`<b>${game.i18n.localize("Incubation")}:</b> ${data.incubation.value}`); data.properties.push(`<b>${game.i18n.localize("Duration")}:</b> ${data.duration.value}`); data.properties = data.properties.concat(data.symptoms.value.split(",").map(i => i = "<a class ='symptom-tag'><i class='fas fa-user-injured'></i> " + i.trim() + "</a>")); if (data.permanent.value) data.properties.push(`<b>${game.i18n.localize("Permanent")}:</b> ${data.permanent.value}`); return data; } // Talent Expansion Data _talentExpandData() { const data = duplicate(this.data.data); data.properties = []; return data; } // Trait Expansion Data _traitExpandData() { const data = duplicate(this.data.data); data.properties = []; return data; } // Career Expansion Data _careerExpandData() { const data = duplicate(this.data.data); data.properties = []; data.properties.push(`<b>${game.i18n.localize("Class")}</b>: ${this.data.data.class.value}`); data.properties.push(`<b>${game.i18n.localize("Group")}</b>: ${this.data.data.careergroup.value}`); data.properties.push(WFRP4E.statusTiers[this.data.data.status.tier] + " " + this.data.data.status.standing); data.properties.push(`<b>${game.i18n.localize("Characteristics")}</b>: ${this.data.data.characteristics.map(i => i = " " + WFRP4E.characteristicsAbbrev[i])}`); data.properties.push(`<b>${game.i18n.localize("Skills")}</b>: ${this.data.data.skills.map(i => i = " " + i)}`); data.properties.push(`<b>${game.i18n.localize("Talents")}</b>: ${this.data.data.talents.map(i => i = " " + i)}`); data.properties.push(`<b>${game.i18n.localize("Trappings")}</b>: ${this.data.data.trappings.map(i => i = " " + i)}`); data.properties.push(`<b>${game.i18n.localize("Income")}</b>: ${this.data.data.incomeSkill.map(i => ` <a class = 'career-income' data-career-id=${this.data._id}> ${this.data.data.skills[i]} <i class="fas fa-coins"></i></a>`)}`); // When expansion data is called, a listener is added for 'career-income' return data; } // Injury Expansion Data _injuryExpandData() { const data = duplicate(this.data.data); data.properties = []; return data; } // Critical Expansion Data _criticalExpandData() { const data = duplicate(this.data.data); data.properties = []; data.properties.push(`<b>${game.i18n.localize("Wounds")}</b>: ${this.data.data.wounds.value}`) if (data.modifier.value) data.properties.push(`<b>${game.i18n.localize("Modifier")}</b>: ${this.data.data.modifier.value}`) return data; } // Spell Expansion Data _spellExpandData() { const data = duplicate(this.data.data); let preparedSpell = this.actor.prepareSpellOrPrayer(duplicate(this.data)); data.description = preparedSpell.data.description data.properties = []; data.properties.push(`${game.i18n.localize("Range")}: ${preparedSpell.range}`); let target = preparedSpell.target; if (target.includes("AoE")) target = `<a class='aoe-template'><i class="fas fa-ruler-combined"></i>${target}</a>` data.properties.push(`${game.i18n.localize("Target")}: ${target}`); data.properties.push(`${game.i18n.localize("Duration")}: ${preparedSpell.duration}`); if (data.magicMissile.value) data.properties.push(`${game.i18n.localize("Magic Missile")}: +${preparedSpell.damage}`); else if (preparedSpell.data.damage.value) data.properties.push(`${game.i18n.localize("Damage")}: +" + ${preparedSpell.damage}`); return data; } // Prayer Expansion Data _prayerExpandData() { const data = duplicate(this.data.data); let preparedPrayer = this.actor.prepareSpellOrPrayer(this.data); data.properties = []; data.properties.push(`${game.i18n.localize("Range")}: ${preparedPrayer.range}`); data.properties.push(`${game.i18n.localize("Target")}: ${preparedPrayer.target}`); data.properties.push(`${game.i18n.localize("Duration")}: ${preparedPrayer.duration}`); if (preparedPrayer.data.damage.value) data.properties.push(`${game.i18n.localize("Damage")}: +" + ${preparedSpell.damage}`); return data; } // Weapon Expansion Data _weaponExpandData() { const data = duplicate(this.data.data); let properties = []; if (data.weaponGroup.value) properties.push(WFRP4E.weaponGroups[data.weaponGroup.value]); if (data.range.value) properties.push(`${game.i18n.localize("Range")}: ${data.range.value}`); if (data.damage.value) properties.push(`${game.i18n.localize("Damage")}: ${data.damage.value}`); for (let prop of WFRP_Utility._prepareQualitiesFlaws(this.data).map(i => i = "<a class ='item-property'>" + i + "</a>")) properties.push(prop); if (data.twohanded.value) properties.push(game.i18n.localize("ITEM.TwoHanded")); if (data.reach.value) properties.push(`${game.i18n.localize("Reach")}: ${WFRP4E.weaponReaches[data.reach.value] + " - " + WFRP4E.reachDescription[data.reach.value]}`); if (data.weaponDamage) properties.push(`<b>${game.i18n.localize("ITEM.WeaponDamaged")} ${data.weaponDamage} points</b>`) if (data.APdamage) properties.push(`${game.i18n.localize("ITEM.ShieldDamaged")} ${data.APdamage} points`) properties = properties.filter(p => p != game.i18n.localize("Special")); if (data.special.value) properties.push(`${game.i18n.localize("Special")}: ` + data.special.value); data.properties = properties.filter(p => !!p); return data; } // Armour Expansion Data _armourExpandData() { const data = duplicate(this.data.data); const properties = []; properties.push(WFRP4E.armorTypes[data.armorType.value]); for (let prop of WFRP_Utility._prepareQualitiesFlaws(this.data).map(i => i = "<a class ='item-property'>" + i + "</a>")) properties.push(prop); properties.push(data.penalty.value); data.properties = properties.filter(p => !!p); return data; } // Ammunition Expansion Data _ammunitionExpandData() { const data = duplicate(this.data.data); let properties = []; properties.push(WFRP4E.ammunitionGroups[data.ammunitionType.value]) if (data.range.value) properties.push(`${game.i18n.localize("Range")}: ${data.range.value}`); if (data.damage.value) properties.push(`${game.i18n.localize("Damage")}: ${data.damage.value}`); for (let prop of WFRP_Utility._prepareQualitiesFlaws(this.data).map(i => i = "<a class ='item-property'>" + i + "</a>")) properties.push(prop); properties = properties.filter(p => p != game.i18n.localize("Special")); if (data.special.value) properties.push(`${game.i18n.localize("Special")}: ` + data.special.value); data.properties = properties.filter(p => !!p); return data; } /** * Posts this item to chat. * * postItem() prepares this item's chat data to post it to chat, setting up * the image if it exists, as well as setting flags so drag+drop works. * */ postItem() { const properties = this[`_${this.data.type}ChatData`](); let chatData = duplicate(this.data); chatData["properties"] = properties //Check if the posted item should have availability/pay buttons chatData.hasPrice = "price" in chatData.data; if(chatData.hasPrice) { if(isNaN(chatData.data.price.gc)) chatData.data.price.gc = 0; if(isNaN(chatData.data.price.ss)) chatData.data.price.ss = 0; if(isNaN(chatData.data.price.bp)) chatData.data.price.bp = 0; } // Don't post any image for the item (which would leave a large gap) if the default image is used if (chatData.img.includes("/blank.png")) chatData.img = null; renderTemplate('systems/dh2e/templates/chat/post-item.html', chatData).then(html => { let chatOptions = WFRP_Utility.chatDataSetup(html) // Setup drag and drop data chatOptions["flags.transfer"] = JSON.stringify( { data: this.data, postedItem: true }) ChatMessage.create(chatOptions) }); } /******* ITEM CHAT DATA *********** * Chat data is called when an item is posted to chat. Each function organizes a 'properties' array. * Each element of the array is shown as a list below the description. */ // Trapping Chat Data _trappingChatData() { const data = duplicate(this.data.data); let properties = [ `<b>${game.i18n.localize("ITEM.TrappingType")}</b>: ${WFRP4E.trappingCategories[data.trappingType.value]}`, `<b>${game.i18n.localize("Price")}</b>: ${data.price.gc} ${game.i18n.localize("MARKET.Abbrev.GC")}, ${data.price.ss} ${game.i18n.localize("MARKET.Abbrev.SS")}, ${data.price.bp} ${game.i18n.localize("MARKET.Abbrev.BP")}`, `<b>${game.i18n.localize("Encumbrance")}</b>: ${data.encumbrance.value}`, `<b>${game.i18n.localize("Availability")}</b>: ${WFRP4E.availability[data.availability.value]}` ] return properties; } // Skill Chat Data _skillChatData() { const data = duplicate(this.data.data); let properties = [] properties.push(data.advanced == "adv" ? `<b>${game.i18n.localize("Advanced")}</b>` : `<b>${game.i18n.localize("Basic")}</b>`) return properties; } // Money Chat Data _moneyChatData() { const data = duplicate(this.data.data); let properties = [ `<b>${game.i18n.localize("ITEM.PenniesValue")}</b>: ${data.coinValue.value}`, `<b>${game.i18n.localize("Encumbrance")}</b>: ${data.encumbrance.value}`, ] return properties; } // Psychology Chat Data _psychologyChatData() { return []; } // Mutation Chat Data _mutationChatData() { let properties = [ `<b>${game.i18n.localize("ITEM.MutationType")}</b>: ${WFRP4E.mutationTypes[this.data.data.mutationType.value]}`, ]; if (this.data.data.modifier.value) properties.push(`<b>${game.i18n.localize("Modifier")}</b>: ${this.data.data.modifier.value}`) return properties; } // Disease Chat Data _diseaseChatData() { const data = duplicate(this.data.data); let properties = []; properties.push(`<b>${game.i18n.localize("Contraction")}:</b> data.contraction.value`); properties.push(`<b>${game.i18n.localize("Incubation")}:</b> <a class = 'chat-roll'><i class='fas fa-dice'></i> ${data.incubation.value}</a>`); properties.push(`<b>${game.i18n.localize("Duration")}:</b> <a class = 'chat-roll'><i class='fas fa-dice'></i> ${data.duration.value}</a>`); properties.push(`<b>${game.i18n.localize("Symptoms")}:</b> ${(data.symptoms.value.split(",").map(i => i = "<a class ='symptom-tag'><i class='fas fa-user-injured'></i> " + i.trim() + "</a>")).join(", ")}`); if (data.permanent.value) properties.push(`<b>${game.i18n.localize("Permanent")}:</b> ${data.permanent.value}`); return properties; } // Talent Chat Data _talentChatData() { const data = duplicate(this.data.data); let properties = []; properties.push(`<b>${game.i18n.localize("Max")}: </b> ${WFRP4E.talentMax[data.max.value]}`); if (data.tests.value) properties.push(`<b>${game.i18n.localize("Tests")}: </b> ${data.tests.value}`); return properties; } // Trait Chat Data _traitChatData() { const data = duplicate(this.data.data); let properties = []; if (data.specification.value) properties.push(`<b>${game.i18n.localize("Specification")}: </b> ${data.specification.value}`); return properties; } // Career Chat Data _careerChatData() { let properties = []; properties.push(`<b>${game.i18n.localize("Class")}</b>: ${this.data.data.class.value}`); properties.push(`<b>${game.i18n.localize("Group")}</b>: ${this.data.data.careergroup.value}`); properties.push(`<b>${game.i18n.localize("Status")}</b>: ${WFRP4E.statusTiers[this.data.data.status.tier] + " " + this.data.data.status.standing}`); properties.push(`<b>${game.i18n.localize("Characteristics")}</b>: ${this.data.data.characteristics.map(i => i = " " + WFRP4E.characteristicsAbbrev[i])}`); properties.push(`<b>${game.i18n.localize("Skills")}</b>: ${this.data.data.skills.map(i => i = " " + "<a class = 'skill-lookup'>" + i + "</a>")}`); properties.push(`<b>${game.i18n.localize("Talents")}</b>: ${this.data.data.talents.map(i => i = " " + "<a class = 'talent-lookup'>" + i + "</a>")}`); properties.push(`<b>${game.i18n.localize("Trappings")}</b>: ${this.data.data.trappings.map(i => i = " " + i)}`); properties.push(`<b>${game.i18n.localize("Income")}</b>: ${this.data.data.incomeSkill.map(i => " " + this.data.data.skills[i])}`); return properties; } // Injury Chat Data _injuryChatData() { const data = duplicate(this.data.data); let properties = []; properties.push(`<b>${game.i18n.localize("Location")}</b>: ${data.location.value}`); if (data.penalty.value) properties.push(`<b>${game.i18n.localize("Penalty")}</b>: ${data.penalty.value}`); return properties; } // Critical Chat Data _criticalChatData() { const data = duplicate(this.data.data); let properties = []; properties.push(`<b>${game.i18n.localize("Wounds")}</b>: ${data.wounds.value}`); properties.push(`<b>${game.i18n.localize("Location")}</b>: ${data.location.value}`); if (data.modifier.value) properties.push(`<b>${game.i18n.localize("Modifier")}</b>: ${data.modifier.value}`); return properties; } // Spell Chat Data _spellChatData() { const data = duplicate(this.data.data); let properties = []; if (WFRP4E.magicLores[data.lore.value]) properties.push(`<b>${game.i18n.localize("Lore")}</b>: ${WFRP4E.magicLores[data.lore.value]}`); else properties.push(`<b>${game.i18n.localize("Lore")}</b>: ${data.lore.value}`); properties.push(`<b>${game.i18n.localize("CN")}</b>: ${data.cn.value}`); properties.push(`<b>${game.i18n.localize("Range")}</b>: ${data.range.value}`); properties.push(`<b>${game.i18n.localize("Target")}</b>: ${data.target.value}`); properties.push(`<b>${game.i18n.localize("Duration")}</b>: ${data.duration.value}`); if (data.damage.value) properties.push(`<b>${game.i18n.localize("Damage")}</b>: ${data.damage.value}`); return properties; } // Prayer Chat Data _prayerChatData() { const data = duplicate(this.data.data); let properties = []; properties.push(`<b>${game.i18n.localize("Range")}</b>: ${data.range.value}`); properties.push(`<b>${game.i18n.localize("Target")}</b>: ${data.target.value}`); properties.push(`<b>${game.i18n.localize("Duration")}</b>: ${data.duration.value}`); if (data.damage.value) properties.push(`<b>${game.i18n.localize("Damage")}</b>: ${data.damage.value}`); return properties; } // Container Chat Data _containerChatData() { const data = duplicate(this.data.data); let properties = [ `<b>${game.i18n.localize("Price")}</b>: ${data.price.gc} GC, ${data.price.ss} SS, ${data.price.bp} BP`, `<b>${game.i18n.localize("Encumbrance")}</b>: ${data.encumbrance.value}`, `<b>${game.i18n.localize("Availability")}</b>: ${WFRP4E.availability[data.availability.value]}` ] properties.push(`<b>${game.i18n.localize("Wearable")}</b>: ${(data.wearable.value ? game.i18n.localize("Yes") : game.i18n.localize("No"))}`); properties.push(`<b>${game.i18n.localize("ITEM.CountOwnerEnc")}</b>: ${(data.countEnc.value ? game.i18n.localize("Yes") : game.i18n.localize("No"))}`); return properties; } // Weapon Chat Data _weaponChatData() { const data = duplicate(this.data.data); let properties = [ `<b>${game.i18n.localize("Price")}</b>: ${data.price.gc} ${game.i18n.localize("MARKET.Abbrev.GC")}, ${data.price.ss} ${game.i18n.localize("MARKET.Abbrev.SS")}, ${data.price.bp} ${game.i18n.localize("MARKET.Abbrev.BP")}`, `<b>${game.i18n.localize("Encumbrance")}</b>: ${data.encumbrance.value}`, `<b>${game.i18n.localize("Availability")}</b>: ${WFRP4E.availability[data.availability.value]}` ] if (data.weaponGroup.value) properties.push(`<b>Group</b>: ${WFRP4E.weaponGroups[data.weaponGroup.value]}`); if (data.range.value) properties.push(`<b>${game.i18n.localize("Range")}</b>: ${data.range.value}`); if (data.damage.value) properties.push(`<b>${game.i18n.localize("Damage")}</b>: ${data.damage.value}`); if (data.twohanded.value) properties.push(`<b>${game.i18n.localize("ITEM.TwoHanded")}</b>`); if (data.reach.value) properties.push(`<b>${game.i18n.localize("Reach")}</b>: ${WFRP4E.weaponReaches[data.reach.value] + " - " + WFRP4E.reachDescription[data.reach.value]}`); if (data.weaponDamage) properties.push(`<b>${game.i18n.localize("ITEM.WeaponDamaged")} ${data.weaponDamage} points</b>`) if (data.APdamage) properties.push(`${game.i18n.localize("ITEM.ShieldDamaged")} ${data.APdamage} points`) let weaponProperties = WFRP_Utility._separateQualitiesFlaws(WFRP_Utility._prepareQualitiesFlaws(this.data)); // Make qualities and flaws clickable weaponProperties.qualities = weaponProperties.qualities.map(i => i = "<a class ='item-property'>" + i + "</a>"); weaponProperties.flaws = weaponProperties.flaws.map(i => i = "<a class ='item-property'>" + i + "</a>"); if (weaponProperties.qualities.length) properties.push(`<b>${game.i18n.localize("Qualities")}</b>: ${weaponProperties.qualities.join(", ")}`) if (weaponProperties.flaws.length) properties.push(`<b>${game.i18n.localize("Flaws")}</b>: ${weaponProperties.flaws.join(", ")}`) properties = properties.filter(p => p != game.i18n.localize("Special")); if (data.special.value) properties.push(`<b>${game.i18n.localize("Special")}</b>: ` + data.special.value); properties = properties.filter(p => !!p); return properties; } // Armour Chat Data _armourChatData() { const data = duplicate(this.data.data); let properties = [ `<b>${game.i18n.localize("Price")}</b>: ${data.price.gc} ${game.i18n.localize("MARKET.Abbrev.GC")}, ${data.price.ss} ${game.i18n.localize("MARKET.Abbrev.SS")}, ${data.price.bp} ${game.i18n.localize("MARKET.Abbrev.BP")}`, `<b>${game.i18n.localize("Encumbrance")}</b>: ${data.encumbrance.value}`, `<b>${game.i18n.localize("Availability")}</b>: ${WFRP4E.availability[data.availability.value]}` ] if (data.armorType.value) properties.push(`<b>${game.i18n.localize("ITEM.ArmourType")}</b>: ${WFRP4E.armorTypes[data.armorType.value]}`); if (data.penalty.value) properties.push(`<b>${game.i18n.localize("Penalty")}</b>: ${data.penalty.value}`); for (let apVal in data.currentAP) { if (data.currentAP[apVal] == -1) data.currentAP[apVal] = data.maxAP[apVal]; } for (let loc in WFRP4E.locations) if (data.maxAP[loc]) properties.push(`<b>${WFRP4E.locations[loc]} AP</b>: ${data.currentAP[loc]}/${data.maxAP[loc]}`); let armourProperties = WFRP_Utility._separateQualitiesFlaws(WFRP_Utility._prepareQualitiesFlaws(this.data)); // Make qualities and flaws clickable armourProperties.qualities = armourProperties.qualities.map(i => i = "<a class ='item-property'>" + i + "</a>"); armourProperties.flaws = armourProperties.flaws.map(i => i = "<a class ='item-property'>" + i + "</a>"); if (armourProperties.qualities.length) properties.push(`<b>${game.i18n.localize("Qualities")}</b>: ${armourProperties.qualities.join(", ")}`) if (armourProperties.flaws.length) properties.push(`<b>${game.i18n.localize("Flaws")}</b>: ${armourProperties.flaws.join(", ")}`) properties = properties.filter(p => p != game.i18n.localize("Special")); if (data.special.value) properties.push(`<b>${game.i18n.localize("Special")}</b>: ` + data.special.value); properties = properties.filter(p => !!p); return properties; } // Ammunition Chat Data _ammunitionChatData() { const data = duplicate(this.data.data); let properties = []; properties.push(`<b>${game.i18n.localize("ITEM.AmmunitionType")}:</b> ${WFRP4E.ammunitionGroups[data.ammunitionType.value]}`) if (data.range.value) properties.push(`<b>${game.i18n.localize("Range")}</b>: ${data.range.value}`); if (data.damage.value) properties.push(`<b>${game.i18n.localize("Damage")}</b>: ${data.damage.value}`); let ammoProperties = WFRP_Utility._separateQualitiesFlaws(WFRP_Utility._prepareQualitiesFlaws(this.data)); ammoProperties.qualities = ammoProperties.qualities.map(i => i = "<a class ='item-property'>" + i + "</a>"); ammoProperties.flaws = ammoProperties.flaws.map(i => i = "<a class ='item-property'>" + i + "</a>"); if (ammoProperties.qualities.length) properties.push(`<b>${game.i18n.localize("Qualities")}</b>: ${ammoProperties.qualities.join(", ")}`) if (ammoProperties.flaws.length) properties.push(`<b>${game.i18n.localize("Flaws")}</b>: ${ammoProperties.flaws.join(", ")}`) properties = properties.filter(p => p != game.i18n.localize("Special")); if (data.special.value) properties.push(`<b>${game.i18n.localize("Special")}</b>: ` + data.special.value); properties = properties.filter(p => !!p); return properties; } }
JavaScript
class PostController { /** * Show a list of all posts. * GET posts * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index ({ request, response, view }) { const posts = await Post.all(); return posts; } /** * Create/save a new post. * POST posts * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store ({ request, response }) { const show = request.only([ 'title', 'content', 'draft' ]) await Post.create(show) return response.status('200').json({ status: 200, message: 'Created' }) } /** * Display a single post. * GET posts/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show ({ params, request, response, view }) { const { id } = params; const post = await Post.find(id); return response.status(200).json({ status: 200, message: { post } }) } /** * Update post details. * PUT or PATCH posts/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update ({ params, request, response }) { const { id } = params; const post = await Post.find(id); const update = request.only([ 'title', 'content', 'draft' ]); await post.merge(update) await post.save(); return response.status(200).json({ status: 200, message: `Success Update.` }) } /** * Delete a post with id. * DELETE posts/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy ({ params, request, response }) { const { id } = params; const post = await Post.find(id) await post.delete() return response.status(200).json({ status: '200', message: `Id: ${id} Deleted!` }) } }
JavaScript
class PermanentObjectController { /** * Retrieve a Permanent Object [GET /sites/{siteId}/permanent-objects/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Permanent Object ID * @return {Promise<PermanentObjectModel>} */ static getOne(siteId, id) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/sites/${siteId}/permanent-objects/${id}`) .then((result) => { let resolveValue = (function(){ return PermanentObjectModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Update a Permanent Object [PATCH /sites/{siteId}/permanent-objects/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Permanent Object ID * @param {PermanentObjectController.UpdateData} updateData The Permanent Object Update Data * @return {Promise<PermanentObjectModel>} */ static update(siteId, id, updateData) { return new Promise((resolve, reject) => { RequestHelper.patchRequest(`/sites/${siteId}/permanent-objects/${id}`, updateData) .then((result) => { let resolveValue = (function(){ return PermanentObjectModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Delete a Permanent Object [DELETE /sites/{siteId}/permanent-objects/{id}] * * @static * @public * @param {number} siteId The Site ID * @param {string} id The Permanent Object ID * @return {Promise<boolean>} */ static delete(siteId, id) { return new Promise((resolve, reject) => { RequestHelper.deleteRequest(`/sites/${siteId}/permanent-objects/${id}`) .then((result) => { resolve(result ?? true); }) .catch(error => reject(error)); }); } /** * List all Permanent Objects [GET /sites/{siteId}/permanent-objects] * * @static * @public * @param {number} siteId The Site ID * @param {PermanentObjectController.GetAllQueryParameters} [queryParameters] The Optional Query Parameters * @return {Promise<PermanentObjectModel[]>} */ static getAll(siteId, queryParameters = {}) { return new Promise((resolve, reject) => { RequestHelper.getRequest(`/sites/${siteId}/permanent-objects`, queryParameters) .then((result) => { let resolveValue = (function(){ if(Array.isArray(result) !== true) { return []; } return result.map((resultItem) => { return (function(){ return PermanentObjectModel.fromJSON(resultItem); }()); }); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } /** * Create a Permanent Object [POST /sites/{siteId}/permanent-objects] * * @static * @public * @param {number} siteId The Site ID * @param {PermanentObjectController.CreateData} createData The Permanent Object Create Data * @return {Promise<PermanentObjectModel>} */ static create(siteId, createData) { return new Promise((resolve, reject) => { RequestHelper.postRequest(`/sites/${siteId}/permanent-objects`, createData) .then((result) => { let resolveValue = (function(){ return PermanentObjectModel.fromJSON(result); }()); resolve(resolveValue); }) .catch(error => reject(error)); }); } }
JavaScript
class Time { //********************************************************************************** /** * Constructor for Time class * @param {Object} [parameters={}] * @param {Object} [parameters.schema] asn1js parsed value to initialize the class from * @property {number} [type] 0 - UTCTime; 1 - GeneralizedTime; 2 - empty value * @property {Date} [value] Value of the TIME class */ constructor(parameters = {}) { //region Internal properties of the object /** * @type {number} * @desc 0 - UTCTime; 1 - GeneralizedTime; 2 - empty value */ this.type = getParametersValue(parameters, "type", Time.defaultValues("type")); /** * @type {Date} * @desc Value of the TIME class */ this.value = getParametersValue(parameters, "value", Time.defaultValues("value")); //endregion //region If input argument array contains "schema" for this object if("schema" in parameters) this.fromSchema(parameters.schema); //endregion } //********************************************************************************** /** * Return default values for all class members * @param {string} memberName String name for a class member */ static defaultValues(memberName) { switch(memberName) { case "type": return 0; case "value": return new Date(0, 0, 0); default: throw new Error(`Invalid member name for Time class: ${memberName}`); } } //********************************************************************************** /** * Return value of pre-defined ASN.1 schema for current class * * ASN.1 schema: * ```asn1 * Time ::= CHOICE { * utcTime UTCTime, * generalTime GeneralizedTime } * ``` * * @param {Object} parameters Input parameters for the schema * @param {boolean} optional Flag that current schema should be optional * @returns {Object} asn1js schema object */ static schema(parameters = {}, optional = false) { /** * @type {Object} * @property {string} [blockName] * @property {string} [utcTimeName] Name for "utcTimeName" choice * @property {string} [generalTimeName] Name for "generalTimeName" choice */ const names = getParametersValue(parameters, "names", {}); return (new asn1js.Choice({ optional, value: [ new asn1js.UTCTime({ name: (names.utcTimeName || "") }), new asn1js.GeneralizedTime({ name: (names.generalTimeName || "") }) ] })); } //********************************************************************************** /** * Convert parsed asn1js object into current class * @param {!Object} schema */ fromSchema(schema) { //region Clear input data first clearProps(schema, [ "utcTimeName", "generalTimeName" ]); //endregion //region Check the schema is valid const asn1 = asn1js.compareSchema(schema, schema, Time.schema({ names: { utcTimeName: "utcTimeName", generalTimeName: "generalTimeName" } })); if(asn1.verified === false) throw new Error("Object's schema was not verified against input data for Time"); //endregion //region Get internal properties from parsed schema if("utcTimeName" in asn1.result) { this.type = 0; this.value = asn1.result.utcTimeName.toDate(); } if("generalTimeName" in asn1.result) { this.type = 1; this.value = asn1.result.generalTimeName.toDate(); } //endregion } //********************************************************************************** /** * Convert current object to asn1js object and set correct values * @returns {Object} asn1js object */ toSchema() { //region Construct and return new ASN.1 schema for this object let result = {}; if(this.type === 0) result = new asn1js.UTCTime({ valueDate: this.value }); if(this.type === 1) result = new asn1js.GeneralizedTime({ valueDate: this.value }); return result; //endregion } //********************************************************************************** /** * Convertion for the class to JSON object * @returns {Object} */ toJSON() { return { type: this.type, value: this.value }; } //********************************************************************************** }
JavaScript
class IotHubProperties { /** * Create a IotHubProperties. * @member {array} [authorizationPolicies] The shared access policies you can * use to secure a connection to the IoT hub. * @member {array} [ipFilterRules] The IP filter rules. * @member {string} [provisioningState] The provisioning state. * @member {string} [hostName] The name of the host. * @member {object} [eventHubEndpoints] The Event Hub-compatible endpoint * properties. The possible keys to this dictionary are events and * operationsMonitoringEvents. Both of these keys have to be present in the * dictionary while making create or update calls for the IoT hub. * @member {object} [routing] * @member {object} [routing.endpoints] * @member {array} [routing.endpoints.serviceBusQueues] The list of Service * Bus queue endpoints that IoT hub routes the messages to, based on the * routing rules. * @member {array} [routing.endpoints.serviceBusTopics] The list of Service * Bus topic endpoints that the IoT hub routes the messages to, based on the * routing rules. * @member {array} [routing.endpoints.eventHubs] The list of Event Hubs * endpoints that IoT hub routes messages to, based on the routing rules. * This list does not include the built-in Event Hubs endpoint. * @member {array} [routing.endpoints.storageContainers] The list of storage * container endpoints that IoT hub routes messages to, based on the routing * rules. * @member {array} [routing.routes] The list of user-provided routing rules * that the IoT hub uses to route messages to built-in and custom endpoints. * A maximum of 100 routing rules are allowed for paid hubs and a maximum of * 5 routing rules are allowed for free hubs. * @member {object} [routing.fallbackRoute] The properties of the route that * is used as a fall-back route when none of the conditions specified in the * 'routes' section are met. This is an optional parameter. When this * property is not set, the messages which do not meet any of the conditions * specified in the 'routes' section get routed to the built-in eventhub * endpoint. * @member {string} [routing.fallbackRoute.condition] The condition which is * evaluated in order to apply the fallback route. If the condition is not * provided it will evaluate to true by default. For grammar, See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language * @member {array} [routing.fallbackRoute.endpointNames] The list of * endpoints to which the messages that satisfy the condition are routed to. * Currently only 1 endpoint is allowed. * @member {boolean} [routing.fallbackRoute.isEnabled] Used to specify * whether the fallback route is enabled. * @member {object} [storageEndpoints] The list of Azure Storage endpoints * where you can upload files. Currently you can configure only one Azure * Storage account and that MUST have its key as $default. Specifying more * than one storage account causes an error to be thrown. Not specifying a * value for this property when the enableFileUploadNotifications property is * set to True, causes an error to be thrown. * @member {object} [messagingEndpoints] The messaging endpoint properties * for the file upload notification queue. * @member {boolean} [enableFileUploadNotifications] If True, file upload * notifications are enabled. * @member {object} [cloudToDevice] * @member {number} [cloudToDevice.maxDeliveryCount] The max delivery count * for cloud-to-device messages in the device queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. * @member {moment.duration} [cloudToDevice.defaultTtlAsIso8601] The default * time to live for cloud-to-device messages in the device queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. * @member {object} [cloudToDevice.feedback] * @member {moment.duration} [cloudToDevice.feedback.lockDurationAsIso8601] * The lock duration for the feedback queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. * @member {moment.duration} [cloudToDevice.feedback.ttlAsIso8601] The period * of time for which a message is available to consume before it is expired * by the IoT hub. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. * @member {number} [cloudToDevice.feedback.maxDeliveryCount] The number of * times the IoT hub attempts to deliver a message on the feedback queue. * See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. * @member {string} [comments] IoT hub comments. * @member {object} [operationsMonitoringProperties] * @member {object} [operationsMonitoringProperties.events] * @member {string} [features] The capabilities and features enabled for the * IoT hub. Possible values include: 'None', 'DeviceManagement' */ constructor() { } /** * Defines the metadata of IotHubProperties * * @returns {object} metadata of IotHubProperties * */ mapper() { return { required: false, serializedName: 'IotHubProperties', type: { name: 'Composite', className: 'IotHubProperties', modelProperties: { authorizationPolicies: { required: false, serializedName: 'authorizationPolicies', type: { name: 'Sequence', element: { required: false, serializedName: 'SharedAccessSignatureAuthorizationRuleElementType', type: { name: 'Composite', className: 'SharedAccessSignatureAuthorizationRule' } } } }, ipFilterRules: { required: false, serializedName: 'ipFilterRules', type: { name: 'Sequence', element: { required: false, serializedName: 'IpFilterRuleElementType', type: { name: 'Composite', className: 'IpFilterRule' } } } }, provisioningState: { required: false, readOnly: true, serializedName: 'provisioningState', type: { name: 'String' } }, hostName: { required: false, readOnly: true, serializedName: 'hostName', type: { name: 'String' } }, eventHubEndpoints: { required: false, serializedName: 'eventHubEndpoints', type: { name: 'Dictionary', value: { required: false, serializedName: 'EventHubPropertiesElementType', type: { name: 'Composite', className: 'EventHubProperties' } } } }, routing: { required: false, serializedName: 'routing', type: { name: 'Composite', className: 'RoutingProperties' } }, storageEndpoints: { required: false, serializedName: 'storageEndpoints', type: { name: 'Dictionary', value: { required: false, serializedName: 'StorageEndpointPropertiesElementType', type: { name: 'Composite', className: 'StorageEndpointProperties' } } } }, messagingEndpoints: { required: false, serializedName: 'messagingEndpoints', type: { name: 'Dictionary', value: { required: false, serializedName: 'MessagingEndpointPropertiesElementType', type: { name: 'Composite', className: 'MessagingEndpointProperties' } } } }, enableFileUploadNotifications: { required: false, serializedName: 'enableFileUploadNotifications', type: { name: 'Boolean' } }, cloudToDevice: { required: false, serializedName: 'cloudToDevice', type: { name: 'Composite', className: 'CloudToDeviceProperties' } }, comments: { required: false, serializedName: 'comments', type: { name: 'String' } }, operationsMonitoringProperties: { required: false, serializedName: 'operationsMonitoringProperties', type: { name: 'Composite', className: 'OperationsMonitoringProperties' } }, features: { required: false, serializedName: 'features', type: { name: 'String' } } } } }; } }
JavaScript
class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props){ super(props); this.state = {menuOpen:false}; }; handleMenu() { if(this.state.menuOpen == false){ this.setState({menuOpen:true}); }else{ this.setState({menuOpen:false}); } }; renderMenu(){ const navStyleMobile = { display: "flex", flexDirection: "column" }; const linkStyle = { color: "rgb(255,205,30)", textDecoration: "none", padding: "10px", margin: "15px", background: "rgb(0,0,0)" }; if (this.state.menuOpen){ return ( <nav style={navStyleMobile}> <Link style={linkStyle} to="/">Home</Link> <Link style={linkStyle} to="/Search">Search</Link> <Link style={linkStyle} to="/Browse">Browse</Link> <Link style={linkStyle} to="/ReportBug">Report a bug</Link> </nav> ); } }; componentWillMount(){ /* var aString = "this is a string"; var anInt = 2; var anArray = [0,1,2,3,4]; var aBool = false; var arrayOfStrings = ["this", "is", "array", "of", "strings"]; var anObject = {fabric:"denim", amount:4}; var arrayOfObjects = [{fabric:"denim", amount:4},{fabric:"satin", amount:6}]; if (anArray[0] == 0 || anInt == 2){ console.log(true); }else{ console.log(false); } for (var i = -1; i < anArray.length; ++i){ if (anArray[i] != 2){ aBool = true; console.log(anArray[i] + " : " + aBool); }else{ aBool = false; console.log(anArray[i] + " : " + aBool); } } //console.log(JSON.stringify(arrayOfObjects)); */ }; render() { const headerStyle = { background: "rgb(255,205,30)", padding: "15px" }; const navStyle = { display: "flex", flexDirection: "row" }; const linkStyle = { color: "rgb(255,205,30)", textDecoration: "none", padding: "10px", margin: "15px", background: "rgb(0,0,0)" }; return ( <header style={headerStyle}> <Responsive minDeviceWidth={768} > <nav style={navStyle}> <Link style={linkStyle} to="/">Home</Link> <Link style={linkStyle} to="/NewRecipe">New Recipe</Link> <Link style={linkStyle} to="/Search">Search</Link> <Link style={linkStyle} to="/Browse">Browse</Link> </nav> </Responsive> <Responsive maxDeviceWidth={767} > <nav> <a onClick={() => this.handleMenu()} href="#"><img src="http://h4z.it/Image/5a9808_burger.png" /></a> {this.renderMenu()} </nav> </Responsive> </header> ); } }
JavaScript
class CrossFrame { /** * @param {Element} element * @param {object} options * @param {Record<string, any>} options.config, * @param {boolean} [options.server] * @param {(event: string, ...args: any[]) => void} options.on * @param {(event: string, ...args: any[]) => void } options.emit */ constructor(element, options) { const { config, server, on, emit } = options; const discovery = new Discovery(window, { server }); const bridge = new Bridge(); const annotationSync = new AnnotationSync(bridge, { on, emit }); const frameObserver = new FrameObserver(element); const frameIdentifiers = new Map(); /** * Inject Hypothesis into a newly-discovered iframe. */ const injectIntoFrame = frame => { if (frameUtil.hasHypothesis(frame)) { return; } frameUtil.isLoaded(frame, () => { const subFrameIdentifier = discovery.generateToken(); frameIdentifiers.set(frame, subFrameIdentifier); const injectedConfig = { ...config, subFrameIdentifier, }; const { clientUrl } = config; frameUtil.injectHypothesis(frame, clientUrl, injectedConfig); }); }; const iframeUnloaded = frame => { bridge.call('destroyFrame', frameIdentifiers.get(frame)); frameIdentifiers.delete(frame); }; // Initiate connection to the sidebar. const onDiscoveryCallback = (source, origin, token) => bridge.createChannel(source, origin, token); discovery.startDiscovery(onDiscoveryCallback); frameObserver.observe(injectIntoFrame, iframeUnloaded); /** * Remove the connection between the sidebar and annotator. */ this.destroy = () => { bridge.destroy(); discovery.stopDiscovery(); frameObserver.disconnect(); }; /** * Notify the sidebar about new annotations created in the page. * * @param {AnnotationData[]} annotations */ this.sync = annotations => annotationSync.sync(annotations); /** * Subscribe to an event from the sidebar. * * @param {string} event * @param {Function} callback */ this.on = (event, callback) => bridge.on(event, callback); /** * Call an RPC method exposed by the sidebar to the annotator. * * @param {string} method * @param {any[]} args */ this.call = (method, ...args) => bridge.call(method, ...args); /** * Register a callback to be invoked once the connection to the sidebar * is set up. * * @param {Function} callback */ this.onConnect = callback => bridge.onConnect(callback); } }
JavaScript
class FieldMetadata extends implementationOf(MetadataInterface, MetadataPropertiesTrait) { /** * Constructor. * * @param {string} className * @param {string} name */ __construct(className, name) { /** * @type {string} */ this.className = className; /** * @type {string} * * @private */ this._name = name; /** * @type {ReflectionField} * * @private */ this._reflection = undefined; } __sleep() { const parent = super.__sleep(); parent.push('_name'); return parent; } /** * Gets the reflection field. * * @returns {ReflectionField} */ get reflection() { if (undefined === this._reflection) { const reflectionClass = new ReflectionClass(this.className); this._reflection = new ReflectionField(reflectionClass, this.name); } return this._reflection; } /** * @inheritdoc */ merge() { } /** * @inheritdoc */ get name() { return this._name; } }
JavaScript
class ToastManager extends React.Component { /** * Static id counter to create unique ids * for each toast */ /** * State to track all the toast across all positions */ constructor(props) { var _this; super(props); _this = this; _defineProperty(this, "state", { top: [], "top-left": [], "top-right": [], "bottom-left": [], bottom: [], "bottom-right": [] }); _defineProperty(this, "notify", (message, options) => { var toast = this.createToast(message, options); var { position, id } = toast; this.setState(prevToasts => { var isTop = position.includes("top"); /** * - If the toast is positioned at the top edges, the * recent toast stacks on top of the other toasts. * * - If the toast is positioned at the bottom edges, the recent * toast stacks below the other toasts. */ var toasts = isTop ? [toast, ...prevToasts[position]] : [...prevToasts[position], toast]; return _extends({}, prevToasts, { [position]: toasts }); }); return id; }); _defineProperty(this, "updateToast", (id, options) => { this.setState(prevState => { var nextState = _extends({}, prevState); var { position, index } = findToast(nextState, id); if (position && index !== -1) { nextState[position][index] = _extends({}, nextState[position][index], options); } return nextState; }); }); _defineProperty(this, "closeAll", function (_temp) { var { positions } = _temp === void 0 ? {} : _temp; // only one setState here for perf reasons // instead of spamming this.closeToast _this.setState(prev => { var allPositions = ["bottom", "bottom-right", "bottom-left", "top", "top-left", "top-right"]; var positionsToClose = positions != null ? positions : allPositions; return positionsToClose.reduce((acc, position) => { acc[position] = prev[position].map(toast => _extends({}, toast, { requestClose: true })); return acc; }, {}); }); }); _defineProperty(this, "createToast", (message, options) => { var _options$id, _options$position; ToastManager.counter += 1; var id = (_options$id = options.id) != null ? _options$id : ToastManager.counter; var position = (_options$position = options.position) != null ? _options$position : "top"; return { id, message, position, duration: options.duration, onCloseComplete: options.onCloseComplete, onRequestRemove: () => this.removeToast(String(id), position), status: options.status, requestClose: false }; }); _defineProperty(this, "closeToast", id => { this.setState(prevState => { var position = getToastPosition(prevState, id); if (!position) return prevState; return _extends({}, prevState, { [position]: prevState[position].map(toast => { // id may be string or number // eslint-disable-next-line eqeqeq if (toast.id == id) { return _extends({}, toast, { requestClose: true }); } return toast; }) }); }); }); _defineProperty(this, "removeToast", (id, position) => { this.setState(prevState => _extends({}, prevState, { // id may be string or number // eslint-disable-next-line eqeqeq [position]: prevState[position].filter(toast => toast.id != id) })); }); _defineProperty(this, "isVisible", id => { var { position } = findToast(this.state, id); return Boolean(position); }); _defineProperty(this, "getStyle", position => { var isTopOrBottom = position === "top" || position === "bottom"; var margin = isTopOrBottom ? "0 auto" : undefined; var top = position.includes("top") ? "env(safe-area-inset-top, 0px)" : undefined; var bottom = position.includes("bottom") ? "env(safe-area-inset-bottom, 0px)" : undefined; var right = !position.includes("left") ? "env(safe-area-inset-right, 0px)" : undefined; var left = !position.includes("right") ? "env(safe-area-inset-left, 0px)" : undefined; return { position: "fixed", zIndex: 5500, pointerEvents: "none", display: "flex", flexDirection: "column", margin, top, bottom, right, left }; }); var methods = { notify: this.notify, closeAll: this.closeAll, close: this.closeToast, update: this.updateToast, isActive: this.isVisible }; props.notify(methods); } /** * Function to actually create a toast and add it * to state at the specified position */ render() { return objectKeys(this.state).map(position => { var toasts = this.state[position]; return /*#__PURE__*/React.createElement("ul", { key: position, id: "chakra-toast-manager-" + position, style: this.getStyle(position) }, /*#__PURE__*/React.createElement(AnimatePresence, { initial: false }, toasts.map(toast => /*#__PURE__*/React.createElement(Toast, _extends({ key: toast.id }, toast))))); }); } }
JavaScript
class CheckoutPage extends Component { constructor(props) { super(props); this.state = { selectedBillingOption: billingOptions[0], // string property names to conveniently identify inputs related to commerce.js validation errors // e.g error { param: "shipping[name]"} 'customer[first_name]': 'John', 'customer[last_name]': 'Doe', 'customer[email]': '[email protected]', 'customer[phone]': '', 'customer[id]': null, 'shipping[name]': 'John Doe', 'shipping[street]': '318 Homer Street', 'shipping[street_2]': '', 'shipping[town_city]': 'Vancouver', 'shipping[region]': 'BC', 'shipping[postal_zip_code]': 'V6B 2V2', 'shipping[country]': 'CA', 'billing[name]': '', 'billing[street]': '', 'billing[street_2]': '', 'billing[town_city]': '', 'billing[region]': '', 'billing[postal_zip_code]': '', 'billing[country]': '', receiveNewsletter: true, orderNotes: '', countries: {}, 'fulfillment[shipping_method]': '', cardNumber: ccFormat('4242424242424242'), expMonth: '11', expYear: '22', cvc: '123', billingPostalZipcode: 'V6B 2V2', errors: { 'fulfillment[shipping_method]': null, gateway_error: null, 'customer[email]': null, 'shipping[name]': null, 'shipping[street]': null, 'shipping[town_city]': null, 'shipping[postal_zip_code]': null }, discountCode: 'CUSTOMCOMMERCE', selectedGateway: 'test_gateway', loading: false, // Optional if using Stripe, used to track steps of checkout using Stripe.js stripe: { paymentMethodId: null, paymentIntentId: null, }, } this.captureOrder = this.captureOrder.bind(this); this.generateToken = this.generateToken.bind(this); this.getAllCountries = this.getAllCountries.bind(this); this.toggleNewsletter = this.toggleNewsletter.bind(this); this.handleChangeForm = this.handleChangeForm.bind(this); this.handleDiscountChange = this.handleDiscountChange.bind(this); this.handleGatewayChange = this.handleGatewayChange.bind(this); this.handleCaptureSuccess = this.handleCaptureSuccess.bind(this); this.handleCaptureError = this.handleCaptureError.bind(this); this.redirectOutOfCheckout = this.redirectOutOfCheckout.bind(this); } componentDidMount() { // if cart is empty then redirect out of checkout; if (this.props.cart && this.props.cart.total_items === 0) { this.redirectOutOfCheckout() } this.updateCustomerFromRedux(); // on initial mount generate checkout token object from the cart, // and then subsequently below in componentDidUpdate if the props.cart.total_items has changed this.generateToken(); } componentDidUpdate(prevProps, prevState) { // if cart items have changed then regenerate checkout token object to reflect changes. if (prevProps.cart && prevProps.cart.total_items !== this.props.cart.total_items && !this.props.orderReceipt) { // reset selected shipping option this.setState({ 'fulfillment[shipping_method]': '', }) // regenerate checkout token object since cart has been updated this.generateToken(); } if (this.props.customer && !prevProps.customer) { this.updateCustomerFromRedux(); } const hasDeliveryCountryChanged = prevState['shipping[country]'] !== this.state['shipping[country]']; const hasDeliveryRegionChanged = prevState['shipping[region]'] !== this.state['shipping[region]']; // if delivery country or region have changed, and we still have a checkout token object, then refresh the token, // and reset the previously selected shipping method if ((hasDeliveryCountryChanged || hasDeliveryRegionChanged) && this.props.checkout) { // reset selected shipping option since previous checkout token live object shipping info // was set based off delivery country, deliveryRegion this.setState({ 'fulfillment[shipping_method]': '', }) this.generateToken(); } // if selected shippiing option changes, regenerate checkout token object to reflect changes if ( prevState['fulfillment[shipping_method]'] !== this.state['fulfillment[shipping_method]'] && this.state['fulfillment[shipping_method]'] && this.props.checkout ) { // update checkout token object with shipping information this.props.dispatchSetShippingOptionsInCheckout( this.props.checkout.id, this.state['fulfillment[shipping_method]'], this.state['shipping[country]'], this.state['shipping[region]'] ); } } /** * Uses the customer provided by redux and updates local state with customer detail (if present) */ updateCustomerFromRedux() { // Pull the customer object from prop (provided by redux) const { customer } = this.props; // Exit early if the customer doesn't exist if (!customer) { return; } // Build a some new state to use with "setState" below const newState = { 'customer[email]': customer.email, 'customer[id]': customer.id, }; if (customer.firstname) { newState['customer[first_name]'] = customer.firstname; newState['shipping[name]'] = customer.firstname; newState['billing[name]'] = customer.firstname; } if (customer.lastname) { newState['customer[last_name]'] = customer.lastname; // Fill in the rest of the full name for shipping/billing if the first name was also available if (customer.firstname) { newState['shipping[name]'] += ` ${customer.lastname}`; newState['billing[name]'] += ` ${customer.lastname}`; } } this.setState(newState); } /** * Generate a checkout token. This is called when the checkout first loads. */ generateToken() { const { cart, dispatchGenerateCheckout, dispatchGetShippingOptions } = this.props; const { 'shipping[country]': country, 'shipping[region]': region } = this.state; // Wait for a future update when a cart ID exists if (typeof cart.id === 'undefined') { return; } return dispatchGenerateCheckout(cart.id) .then((checkout) => { // continue and dispatch getShippingOptionsForCheckout to get shipping options based on checkout.id this.getAllCountries(checkout); return dispatchGetShippingOptions(checkout.id, country, region) }) .catch(error => { console.log('error caught in checkout/index.js in generateToken', error); }) } redirectOutOfCheckout() { this.props.router.push('/'); } handleGatewayChange(selectedGateway) { this.setState({ selectedGateway, }); } handleDiscountChange(e) { e.preventDefault(); if (!this.state.discountCode.trim() || !this.props.checkout) { return; } this.props.dispatchSetDiscountCodeInCheckout(this.props.checkout.id, this.state.discountCode) .then(resp => { if (resp.valid) { return this.setState({ discountCode: '', }); } return Promise.reject(resp); }) .catch(error => { alert('Sorry, the discount code could not be applied'); }); } handleChangeForm(e) { // when input cardNumber changes format using ccFormat helper if (e.target.name === 'cardNumber') { e.target.value = ccFormat(e.target.value) } // update form's input by name in state this.setState({ [e.target.name]: e.target.value, }); } /** * Handle a successful `checkout.capture()` request * * @param {object} result */ handleCaptureSuccess(result) { this.props.router.push('/checkout/confirm'); }; /** * Handle an error during a `checkout.capture()` request * * @param {object} result */ handleCaptureError(result) { // Clear the initial loading state this.setState({ loading: false }); let errorToAlert = ''; // If errors are passed as strings, output them immediately if (typeof result === 'string') { alert(result); return; } const { data: { error = {} } } = result; // Handle any validation errors if (error.type === 'validation') { console.error('Error while capturing order!', error.message); if (typeof error.message === 'string') { alert(error.message); return; } error.message.forEach(({param, error}, i) => { this.setState({ errors: { ...this.state.errors, [param]: error }, }); }) errorToAlert = error.message.reduce((string, error) => { return `${string} ${error.error}` }, ''); } // Handle internal errors from the Chec API if (['gateway_error', 'not_valid', 'bad_request'].includes(error.type)) { this.setState({ errors: { ...this.state.errors, [(error.type === 'not_valid' ? 'fulfillment[shipping_method]' : error.type)]: error.message }, }) errorToAlert = error.message } // Surface any errors to the customer if (errorToAlert) { alert(errorToAlert); } }; /** * Capture the order * * @param {Event} e */ captureOrder(e) { e.preventDefault(); // reset error states this.setState({ errors: { 'fulfillment[shipping_method]': null, gateway_error: null, 'shipping[name]': null, 'shipping[street]': null, }, }); // set up line_items object and inner variant group object for order object below const line_items = this.props.checkout.live.line_items.reduce((obj, lineItem) => { const variantGroups = lineItem.selected_options.reduce((obj, option) => { obj[option.group_id] = option.option_id; return obj; }, {}); obj[lineItem.id] = { ...lineItem, variantGroups }; return obj; }, {}); const shippingAddress = { name: this.state['shipping[name]'], country: this.state['shipping[country]'], street: this.state['shipping[street]'], street_2: this.state['shipping[street_2]'], town_city: this.state['shipping[town_city]'], county_state: this.state['shipping[region]'], postal_zip_code: this.state['shipping[postal_zip_code]'] } // construct order object const newOrder = { line_items, customer: { firstname: this.state['customer[first_name]'], lastname: this.state['customer[last_name]'], email: this.state['customer[email]'], phone: this.state['customer[phone]'] || undefined }, // collected 'order notes' data for extra field configured in the Chec Dashboard extrafields: { extr_j0YnEoqOPle7P6: this.state.orderNotes, }, // Add more to the billing object if you're collecting a billing address in the // checkout form. This is just sending the name as a minimum. billing: this.state.selectedBillingOption === 'Same as shipping Address' ? shippingAddress : { name: this.state['billing[name]'], country: this.state['billing[country]'], street: this.state['billing[street]'], street_2: this.state['billing[street_2]'], town_city: this.state['billing[town_city]'], county_state: this.state['billing[region]'], postal_zip_code: this.state['billing[postal_zip_code]'] }, shipping: shippingAddress, fulfillment: { shipping_method: this.state['fulfillment[shipping_method]'] }, payment: { gateway: this.state.selectedGateway, }, } // If test gateway selected add necessary card data for the order to be completed. if (this.state.selectedGateway === 'test_gateway') { this.setState({ loading: true, }); newOrder.payment.card = { number: this.state.cardNumber, expiry_month: this.state.expMonth, expiry_year: this.state.expYear, cvc: this.state.cvc, postal_zip_code: this.state.billingPostalZipcode, } } // If Stripe gateway is selected, register a payment method, call checkout.capture(), // and catch errors that indicate Strong Customer Authentication is required. In this // case we allow Stripe.js to handle this verification, then re-submit // `checkout.capture()` using the payment method ID or payment intent ID returned at // each step. if (this.state.selectedGateway === 'stripe') { // Create a new Payment Method in Stripe.js return this.props.stripe.createPaymentMethod({ type: 'card', card: this.props.elements.getElement(CardElement), }) .then((response) => { // Check for errors from using Stripe.js, surface to the customer if found if (response.error) { this.handleCaptureError(response.error.message); return; } // Enable loading state now that we're finished interacting with Elements this.setState({ loading: true, }); // Get the payment method ID and continue with the capture request this.props.dispatchCaptureOrder(this.props.checkout.id, { ...newOrder, payment: { ...newOrder.payment, stripe: { payment_method_id: response.paymentMethod.id, }, }, }) // If no further verification is required, go straight to the "success" handler .then(this.handleCaptureSuccess) .catch((error) => { // Look for "requires further verification" from the Commerce.js backend. This // will be surfaced as a 402 Payment Required error, with a unique type, and // the secret you need to continue verifying the transaction on the frontend. if (error.data.error.type !== 'requires_verification') { this.handleCaptureError(error); return; } this.props.stripe.handleCardAction(error.data.error.param) .then((result) => { // Check for errors from Stripe, e.g. failure to confirm verification of the // payment method, or the card was declined etc if (result.error) { this.handleCaptureError(result.error.message); return; } // Verification has successfully been completed. Get the payment intent ID // from the Stripe.js response and re-submit the Commerce.js // `checkout.capture()` request with it this.props.dispatchCaptureOrder(this.props.checkout.id, { ...newOrder, payment: { ...newOrder.payment, stripe: { payment_intent_id: result.paymentIntent.id, }, }, }) .then(this.handleCaptureSuccess) .catch(this.handleCaptureError); }); }); }) .catch(this.handleCaptureError); } // Capture the order this.props.dispatchCaptureOrder(this.props.checkout.id, newOrder) .then(this.handleCaptureSuccess) .catch(this.handleCaptureError); } /** * Fetch all available countries for shipping */ getAllCountries(checkout) { commerce.services.localeListShippingCountries(checkout.id).then(resp => { this.setState({ countries: resp.countries }) }).catch(error => console.log(error)) } toggleNewsletter() { this.setState({ receiveNewsletter: !this.state.receiveNewsletter, }); } /** * Renders payment methods and payment information * * @returns {JSX.Element} */ renderPaymentDetails() { const { checkout, stripe, elements } = this.props; const { selectedGateway, cardNumber, expMonth, expYear, cvc } = this.state; return ( <PaymentDetails gateways={checkout.gateways} onChangeGateway={this.handleGatewayChange} selectedGateway={selectedGateway} cardNumber={cardNumber} expMonth={expMonth} expYear={expYear} cvc={cvc} stripe={stripe} elements={elements} /> ); } render() { const { checkout, shippingOptions } = this.props; const selectedShippingOption = shippingOptions.find(({id}) => id === this.state['fulfillment[shipping_method]']); if (this.state.loading) { return <Loader />; } return ( <Root> <Head> <title>WeBuyEGR | EyeWear - Checkout</title> </Head> <div className="custom-container py-5 my-4 my-sm-5"> {/* Row */} <div className="row mt-4"> <div className="col-12 col-md-10 col-lg-6 offset-md-1 offset-lg-0"> {/* Breadcrumbs */} <div className="d-flex pb-4 breadcrumb-container"> <Link href="/collection"> <a className="font-color-dark font-size-caption text-decoration-underline cursor-pointer"> Cart </a> </Link> <img src="/icon/arrow-right.svg" className="w-16 mx-1" alt="Arrow icon"/> <div className="font-size-caption font-weight-bold cursor-pointer"> Checkout </div> </div> { checkout && ( <form onChange={this.handleChangeForm} onSubmit={this.captureOrder}> <p className="font-size-subheader font-weight-semibold mb-4"> Customer </p> <div className="row"> <div className="col-12 col-sm-6 mb-3"> <label className="w-100"> <p className="mb-1 font-size-caption font-color-light"> First name* </p> <input required name="customer[first_name]" autoComplete="given-name" value={this.state['customer[first_name]']} className="rounded-0 w-100" /> </label> </div> <div className="col-12 col-sm-6 mb-3"> <label className="w-100"> <p className="mb-1 font-size-caption font-color-light"> Last name* </p> <input required name="customer[last_name]" autoComplete="family-name" value={this.state['customer[last_name]']} className="rounded-0 w-100" /> </label> </div> </div> <div className="row"> <div className="col-12 col-sm-6 mb-3"> <label className="w-100"> <p className="mb-1 font-size-caption font-color-light"> Telephone </p> <input name="customer[phone]" autoComplete="tel" value={this.state['customer[phone]']} className="rounded-0 w-100" /> </label> </div> <div className="col-12 col-sm-6 mb-3"> <label className="w-100"> <p className="mb-1 font-size-caption font-color-light"> Email address* </p> <input required name="customer[email]" autoComplete="email" value={this.state['customer[email]']} className="rounded-0 w-100" /> </label> </div> </div> <p className="font-size-subheader font-weight-semibold mb-4"> Shipping Address </p> <div className="mb-5"> <AddressForm type="shipping" countries={this.state.countries} name={this.state['shipping[name]']} country={ this.state['shipping[country]']} region={this.state['shipping[region]']} street={this.state['shipping[street]']} street2={this.state['shipping[street_2]']} townCity={this.state['shipping[town_city]']} postalZipCode={this.state['shipping[postal_zip_code]']} /> <div className="row"> <div className="col-12 mb-3"> <label className="w-100"> <p className="mb-1 font-size-caption font-color-light"> Shipping method* </p> <Dropdown name="fulfillment[shipping_method]" value={ selectedShippingOption ? (`${selectedShippingOption.description} - ${selectedShippingOption.price.formatted_with_code}`) : '' } placeholder="Select a shipping method" > { shippingOptions && shippingOptions.map(option => ( <option key={option.id} value={option.id}> { `${option.description} - $${option.price.formatted_with_code}` } </option> )) } </Dropdown> </label> </div> </div> <div onClick={this.toggleNewsletter} className="d-flex mb-4 flex-nowrap cursor-pointer" > <Checkbox onClick={this.toggleNewsletter} checked={this.state.receiveNewsletter} className="mr-3" /> <p> Receive our news, restocking, good plans and news in your mailbox! Rest assured, you will not be flooded, we only send one newsletter per month approximately 🙂 </p> </div> <label className="w-100 mb-3"> <p className="mb-1 font-size-caption font-color-light"> Order notes (optional) </p> <textarea name="orderNotes" value={this.state.orderNotes} className="rounded-0 w-100" /> </label> </div> { this.renderPaymentDetails() } {/* Billing Address */} { checkout.collects && checkout.collects.billing_address && <> <p className="font-size-subheader font-weight-semibold mb-3"> Billing Address </p> <div className="border border-color-gray400 mb-5"> {billingOptions.map((value, index) => ( <label key={index} onClick={() => this.setState({ selectedBillingOption: value })} className={`p-3 d-flex align-items-center cursor-pointer ${index !== billingOptions.length - 1 && 'borderbottom border-color-gray500'}`} > <Radiobox checked={this.state.selectedBillingOption === value} onClick={() => this.setState({ selectedValue: value })} className="mr-3" /> <p className="font-weight-medium">{value}</p> </label> ))} </div> {this.state.selectedBillingOption === 'Use a different billing address' && ( <AddressForm type="billing" countries={this.state.countries} name={this.state['billing[name]']} country={ this.state['billing[country]']} region={this.state['billing[region]']} street={this.state['billing[street]']} street2={this.state['billing[street_2]']} townCity={this.state['billing[town_city]']} postalZipCode={this.state['billing[postal_zip_code]']} /> )} </>} <p className="checkout-error"> { !selectedShippingOption ? 'Select a shipping option!' : '' } </p> <button type="submit" className="bg-black font-color-white w-100 border-none h-56 font-weight-semibold d-lg-block" disabled={!selectedShippingOption} > Make payment </button> </form> ) } </div> <div className="col-12 col-lg-5 col-md-10 offset-md-1 mt-4 mt-lg-0"> <div className="bg-brand200 p-lg-5 p-3 checkout-summary"> <div className="borderbottom font-size-subheader border-color-gray400 pb-2 font-weight-medium"> Your order </div> <div className="pt-3 borderbottom border-color-gray400"> {(checkout.live ? checkout.live.line_items : []).map((item, index, items) => { return ( <div key={item.id} className="d-flex mb-2" > { (item && item.media) && (<img className="checkout__line-item-image mr-2" src={item.media.source} alt={item.product_name}/>) } <div className="d-flex flex-grow-1"> <div className="flex-grow-1"> <p className="font-weight-medium"> {item.product_name} </p> <p className="font-color-light">Quantity: {item.quantity}</p> <div className="d-flex justify-content-between mb-2"> {item.selected_options.map((option) => <p key={option.group_id} className="font-color-light font-weight-small"> {option.group_name}: {option.option_name} </p> )} </div> </div> <div className="text-right font-weight-semibold"> ${item.line_total.formatted_with_code} </div> </div> </div> ) })} </div> <div className="row py-3 borderbottom border-color-gray400"> <input name="discountCode" onChange={this.handleChangeForm} value={this.state.discountCode} placeholder="Gift card or discount code" className="mr-2 col" /> <button className="font-color-white border-none font-weight-medium px-4 col-auto" disabled={!this.props.checkout || undefined} onClick={this.handleDiscountChange} > Apply </button> </div> <div className="py-3 borderbottom border-color-black"> {[ { name: 'Subtotal', amount: checkout.live ? checkout.live.subtotal.formatted_with_symbol : '', }, { name: 'Tax', amount: checkout.live ? checkout.live.tax.amount.formatted_with_symbol : '', }, { name: 'Shipping', amount: selectedShippingOption ? `${selectedShippingOption.description} - ${selectedShippingOption.price.formatted_with_symbol}` : 'No shipping method selected', }, { name: 'Discount', amount: (checkout.live && checkout.live.discount && checkout.live.discount.code) ? `Saved ${checkout.live.discount.amount_saved.formatted_with_symbol}` : 'No discount code applied', } ].map((item, i) => ( <div key={i} className="d-flex justify-content-between align-items-center mb-2"> <p>{item.name}</p> <p className="text-right font-weight-medium"> {item.amount} </p> </div> ))} </div> <div className="d-flex justify-content-between align-items-center mb-2 pt-3"> <p className="font-size-title font-weight-semibold"> Total amount </p> <p className="text-right font-weight-semibold font-size-title"> $ { checkout.live ? checkout.live.total.formatted_with_code : '' } </p> </div> </div> </div> </div> </div> </Root> ); } }
JavaScript
class ColumnSelector extends React.Component { constructor(props) { super(props); // Set the initial React states. this.state = { columns: props.columns, // Make (effectively) a local mutatable copy of the columns sortOption: 'default', // Default sorting option }; // Bind `this` to non-React methods. this.submitHandler = this.submitHandler.bind(this); this.toggleColumn = this.toggleColumn.bind(this); this.handleSelectAll = this.handleSelectAll.bind(this); this.handleSelectOne = this.handleSelectOne.bind(this); this.handleSortChange = this.handleSortChange.bind(this); } toggleColumn(columnPath) { // Called every time a column's checkbox gets clicked on or off in the modal. `columnPath` // is the query-string term corresponding to each column. First, if the column is getting // turned off, make sure we have at least one other column selected, because at least one // column has to be selected. if (this.state.columns[columnPath].visible) { // The clicked column is currently visible, so before we make it invisible, make sure // at least one other column is also visible. const allColumnKeys = Object.keys(this.state.columns); const anotherVisible = allColumnKeys.some(key => key !== columnPath && this.state.columns[key].visible); if (!anotherVisible) { // A checkbox is being turned off, and no other checkbox is checked, so ignore the // click. return; } } // Either a checkbox is being turned on, or it's being turned off and another checkbox is // still checked. Change the component state to reflect the new checkbox states. Presumably // if the setState callback returned no properties setState becomes a null op, so the above // test could be done inside the setState callback. The React docs don't say what happens // if you return no properties (https://reactjs.org/docs/react-component.html#setstate) so // I avoided doing this. this.setState((prevState) => { // Toggle the `visible` state corresponding to the column whose checkbox was toggled. // Then set that as the new React state which causes a redraw of the modal with all the // checkboxes in the correct state. const columns = Object.assign({}, prevState.columns); columns[columnPath] = Object.assign({}, columns[columnPath]); columns[columnPath].visible = !columns[columnPath].visible; return { columns }; }); } submitHandler() { // Called when the user clicks the Select button in the column checkbox modal, which // sets a new state for all checked report columns. this.props.setColumnState(this.state.columns); } handleSelectAll() { // Called when the "Select all" button is clicked. this.setState((prevState) => { // For every column in this.state.columns, set its `visible` property to true. const columns = Object.assign({}, prevState.columns); Object.keys(columns).forEach((columnPath) => { columns[columnPath] = Object.assign({}, columns[columnPath]); columns[columnPath].visible = true; }); return { columns }; }); } handleSelectOne() { // Called when the "Select (first) only" button is clicked. this.setState((prevState) => { // Set all columns to invisible first. const columns = Object.assign({}, prevState.columns); const columnPaths = Object.keys(columns); columnPaths.forEach((columnPath) => { columns[columnPath] = Object.assign({}, columns[columnPath]); columns[columnPath].visible = false; }); // Now set the column for the first key to true so that only it's selected. columns[columnPaths[0]].visible = true; return { columns }; }); } // Called when the sorting option gets changed. handleSortChange(sortOption) { this.setState({ sortOption }); } render() { const { columns } = this.state; const firstColumnKey = Object.keys(columns)[0]; // Get the column paths, sorting them by the corresponding column title if the user asked // for that. const columnPaths = getColumnPaths(columns, this.state.sortOption); return ( <Modal addClasses="column-selector"> <ModalHeader title="Select columns to view" closeModal={this.props.closeSelector} /> <ColumnSelectorControls handleSelectAll={this.handleSelectAll} handleSelectOne={this.handleSelectOne} handleSortChange={this.handleSortChange} firstColumnTitle={columns[firstColumnKey].title} /> <ModalBody> <div className="column-selector__selectors"> {columnPaths.map((columnPath) => { const column = columns[columnPath]; return <ColumnItem key={columnPath} columnPath={columnPath} column={column} toggleColumn={this.toggleColumn} />; })} </div> </ModalBody> <ModalFooter closeModal={this.props.closeSelector} submitBtn={this.submitHandler} submitTitle="View selected columns" /> </Modal> ); } }
JavaScript
class ColumnItem extends React.Component { constructor() { super(); // Bind this to non-React methods. this.toggleColumn = this.toggleColumn.bind(this); } toggleColumn() { this.props.toggleColumn(this.props.columnPath); } render() { const { column } = this.props; /* eslint-disable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */ return ( <div className="column-selector__selector-item"> <input type="checkbox" onChange={this.toggleColumn} checked={column.visible} />&nbsp; <span onClick={this.toggleColumn} style={{ cursor: 'pointer' }}>{column.title}</span> </div> ); /* eslint-enable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */ } }
JavaScript
class BaseError extends Error { constructor (message) { super() // Set this.message Object.defineProperty(this, 'message', { configurable: true, enumerable: false, value: message !== undefined ? String(message) : '' }) // Set this.name Object.defineProperty(this, 'name', { configurable: true, enumerable: false, value: this.constructor.name }) // Set this.stack if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor) } } }
JavaScript
class Home extends Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick(name){ this.props.history.push(name); } render() { let role = this.props.auth.role return ( <Grid fluid> <h2>Home</h2> <div className="component-divider-sub"></div> <Row> ´ <Col md={3} > <Panel onClick={(e) => this.handleClick('/all-courses', e)}> <Panel.Body className="panelPointer">See All Courses</Panel.Body> </Panel> </Col> { role === 1 && <Col md={3} > <Panel onClick={(e) => this.handleClick('/create-course', e)}> <Panel.Body className="panelPointer">Create Course</Panel.Body> </Panel> </Col> } { role === 1 && <Col md={3}> <Panel onClick={(e) => this.handleClick('/all-users', e)}> <Panel.Body className="panelPointer">All Users</Panel.Body> </Panel> </Col> } </Row> </Grid> ) } }
JavaScript
class Scanner { /** * @param {ErrorReport} reporter * @param {SourceFile} file */ constructor(reporter, file, parser) { // These are not instance fields and this class should probably be refactor // to not give a false impression that multiple instances can be created. errorReporter = reporter; lineNumberTable = file.lineNumberTable; input = file.contents; length = file.contents.length; index = 0; lastToken = null; token = null; lookaheadToken = null; updateCurrentCharCode(); currentParser = parser; } get lastToken() { return lastToken; } /** @return {SourcePosition} */ getPosition() { return getPosition(getOffset()); } nextRegularExpressionLiteralToken() { lastToken = nextRegularExpressionLiteralToken(); token = scanToken(); return lastToken; } nextTemplateLiteralToken() { var t = nextTemplateLiteralToken(); token = scanToken(); return t; } /** @return {Token} */ nextToken() { return nextToken(); } /** * @return {Token} */ peekToken(opt_index) { // Too hot for default parameters. return opt_index ? peekTokenLookahead() : peekToken(); } peekTokenNoLineTerminator() { return peekTokenNoLineTerminator(); } isAtEnd() { return isAtEnd(); } }
JavaScript
class ItemTooLargeException extends Error { /** * ItemTooLargeException constructor. * * @param string $message * @param Item $item */ constructor(message, Item_item) { super(message); this.item = Item_item; } /** * @return Item */ getItem() { return this.item; } }
JavaScript
class WalletConnectSessions extends PureComponent { static navigationOptions = ({ navigation }) => getNavigationOptionsTitle(strings(`experimental_settings.wallet_connect_dapps`), navigation); state = { sessions: [] }; actionSheet = null; sessionToRemove = null; componentDidMount() { this.loadSessions(); } loadSessions = async () => { let sessions = []; const sessionData = await AsyncStorage.getItem('@MetaMask:walletconnectSessions'); if (sessionData) { sessions = JSON.parse(sessionData); } this.setState({ ready: true, sessions }); }; renderDesc = meta => { const { description } = meta; if (description) { return <Text style={styles.desc}>{meta.description}</Text>; } return null; }; onLongPress = session => { this.sessionToRemove = session; this.actionSheet.show(); }; createActionSheetRef = ref => { this.actionSheet = ref; }; onActionSheetPress = index => (index === 0 ? this.killSession() : null); killSession = async () => { try { await WalletConnect.killSession(this.sessionToRemove.peerId); Alert.alert( strings('walletconnect_sessions.session_ended_title'), strings('walletconnect_sessions.session_ended_desc') ); this.loadSessions(); } catch (e) { Logger.error(e, 'WC: Failed to kill session'); } }; renderSessions = () => { const { sessions } = this.state; return sessions.map(session => ( <TouchableOpacity // eslint-disable-next-line react/jsx-no-bind onLongPress={() => this.onLongPress(session)} key={`session_${session.peerId}`} style={styles.row} > <WebsiteIcon url={session.peerMeta.url} style={styles.websiteIcon} /> <View style={styles.info}> <Text style={styles.name}>{session.peerMeta.name}</Text> <Text style={styles.url}>{session.peerId}</Text> <Text style={styles.url}>{session.peerMeta.url}</Text> {this.renderDesc(session.peerMeta)} </View> </TouchableOpacity> )); }; renderEmpty = () => ( <View style={styles.emptyWrapper}> <Text style={styles.emptyText}>{strings('walletconnect_sessions.no_active_sessions')}</Text> </View> ); render = () => { const { ready, sessions } = this.state; if (!ready) return null; return ( <SafeAreaView style={styles.wrapper} testID={'wallet-connect-sessions-screen'}> <ScrollView style={styles.wrapper} contentContainerStyle={styles.scrollviewContent}> {sessions.length ? this.renderSessions() : this.renderEmpty()} </ScrollView> <ActionSheet ref={this.createActionSheetRef} title={strings('walletconnect_sessions.end_session_title')} options={[strings('walletconnect_sessions.end'), strings('walletconnect_sessions.cancel')]} cancelButtonIndex={1} destructiveButtonIndex={0} onPress={this.onActionSheetPress} /> </SafeAreaView> ); }; }
JavaScript
class ShutdownTimer { constructor () { // variables this.timerId = undefined this.inputTime = undefined this.remainingTime = undefined this.updateRateMs = undefined // performance.now this.lastExecutedTime = undefined /** * Indicates if the program is paused: * **true** if paused, **false** if not paused, **undefined** if timer not set or already went of */ this.paused = undefined // callback methods this.alarmCallback = (error, msObject) => {} this.countdownCallback = (error, msObject) => {} this.startCallback = (error, msObject) => {} this.pauseCallback = (error, msObject1, msObject2) => {} this.resumeCallback = (error, msObject1, msObject2) => {} this.stopCallback = (error, msObject) => {} this.resetCallback = (error) => {} // special callback method that runs every millisecond the timer runs this.timerCallback = () => { if (this.timerId === undefined) { this.countdownCallback(Error('Callback timer is not defined!')) } else if (this.remainingTime === undefined) { this.countdownCallback(Error('No remaining time defined!')) } else { this.remainingTime -= Math.floor( window.performance.now() - this.lastExecutedTime ) if (this.remainingTime <= 0) { this.alarm() } else { this.lastExecutedTime = window.performance.now() this.countdownCallback(null, this.msToObject(this.remainingTime)) } } } } /** * Get if the timer was paused or not * @returns {boolean} true if paused, false if currently running, undefined if neither of these actions took place */ get isPaused () { return this.paused } /** * Get if the timer was stopped * @returns {boolean} true if stopped, false if not */ get isStopped () { return this.paused === undefined } /** * Set callback methods to different events * @param {String} event - Event identifier * @param {Function} callback - Callback function * alarmCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, * countdownCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, * startCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, * pauseCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}, * {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, * resumeCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}, * {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, * stopCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, * resetCallback: (err, {msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}) => {}, */ on (event, callback) { switch (event) { case 'alarmCallback': this.alarmCallback = callback break case 'countdownCallback': this.countdownCallback = callback break case 'startCallback': this.startCallback = callback break case 'pauseCallback': this.pauseCallback = callback break case 'resumeCallback': this.resumeCallback = callback break case 'stopCallback': this.stopCallback = callback break case 'resetCallback': this.resetCallback = callback break default: console.error(new Error('Event does not exist!')) } return this } /** * Alarm callback */ alarm () { // error catching if (this.timerId === undefined) { this.alarmCallback(Error('The timer id was undefined!')) return } else if (this.inputTime === undefined) { this.alarmCallback(Error('The input time was undefined!')) return } // clear interval clearInterval(this.timerId) // set paused and remainingTime to undefined this.paused = undefined this.remainingTime = undefined // callback function with input time this.alarmCallback(null, this.inputTime) } start (milliseconds, updateRateMs = 100) { // error catching if (milliseconds === undefined) { if (this.inputTime === undefined) { this.startCallback(Error('No milliseconds/saved-input-time found!')) return } else if (this.inputTime.msInput === undefined) { this.startCallback(Error('Saved input time was not defined!')) return } else { milliseconds = this.inputTime.msInput console.debug( 'Hint:', `Milliseconds were undefined, but inputTime.msInput (${this.inputTime.msInput}) was not` ) } } else if (isNaN(milliseconds)) { this.startCallback(Error('Given milliseconds is not a number!')) return } else if (milliseconds < 0) { this.startCallback(Error('Given milliseconds cannot be less than 0!')) return } // set update rate this.updateRateMs = updateRateMs // set new input time if there was an valid input this.inputTime = this.msToObject(milliseconds) // set remaining time this.remainingTime = this.inputTime.msInput // save time when interval was stared this.lastExecutedTime = window.performance.now() // set paused to false this.paused = false // set interval this.timerId = setInterval(this.timerCallback, this.updateRateMs) // callback function with input time this.startCallback(null, this.inputTime) } /** * Pause timer which means the interval will be killed, the remaining time * will be saved and paused will be set to true */ pause () { // error catching if (this.timerId === undefined) { this.pauseCallback(Error('The timer id was undefined')) return } else if (this.paused === undefined) { this.resumeCallback(Error('The timer was not started before')) return } // clear interval clearInterval(this.timerId) // set last executedTime undefined this.lastExecutedTime = undefined // set paused to true this.paused = true // callback function with input time and current time this.pauseCallback( null, this.inputTime, this.msToObject(this.remainingTime) ) } /** * Resume timer */ resume () { // error catching if (this.inputTime === undefined) { this.resumeCallback(new Error('The input time is undefined')) return } else if (this.remainingTime === undefined) { this.resumeCallback(new Error('The remaining time is undefined')) return } else if (this.paused === undefined) { this.resumeCallback(new Error('The timer was not paused before')) return } // set last executedTime to right now this.lastExecutedTime = window.performance.now() // set new interval this.timerId = setInterval(this.timerCallback, this.updateRateMs) // set paused to false this.paused = false // callback function with input time and current time this.resumeCallback( null, this.inputTime, this.msToObject(this.remainingTime) ) } /** * Stop timer */ stop () { // error catching if (this.timerId === undefined) { // check if a timer was defined this.stopCallback(Error('There was no timer defined')) return } else if (this.inputTime === undefined) { // check if there is a saved input time this.stopCallback(Error('There was no input time defined')) return } // clear interval clearInterval(this.timerId) // set pause to undefined this.paused = undefined // callback function this.stopCallback(null, this.inputTime) } /** * Reset timer */ reset () { // stop timer if active clearInterval(this.timerId) // set all variables to undefined this.inputTime = undefined this.lastExecutedTime = undefined this.paused = undefined this.remainingTime = undefined this.timerId = undefined // callback function this.resetCallback(null) } /** * Convert given milliseconds to an object which contains days, hours, * minutes, seconds, milliseconds and the original milliseconds number * @param {Number} msInput Number of milliseconds * @returns {{msInput:Number,d:Number,h:Number,m:Number,s:Number,ms:Number}} * Time object */ msToObject (msInput) { var d; var h; var m; var s const newMs = Math.floor(msInput % 1000) s = Math.floor(msInput / 1000) m = Math.floor(s / 60) s = s % 60 h = Math.floor(m / 60) m = m % 60 d = Math.floor(h / 24) h = h % 24 return { d, h, m, ms: newMs, msInput, s } } }
JavaScript
class AssertError extends Error { constructor(msg) { super(msg); this.name = this.constructor.name; // We likely get a stack via 'super' constructor. Tune it. console.debug("!!! Assert stack:", this.stack); // tbd. Unfinished } }
JavaScript
class ResponseMock { /** * constructor * @param {function} callback */ constructor(callback) { this.callback = callback; this.responseJson = {}; } /** * Store JSON repsonse from WebhookClient * @param {Object} responseJson */ json(responseJson) { this.callback(responseJson); } /** * Get JSON response for testing comparison * @return {Object} response JSON from WebhookClient */ get() { return this.responseJson; } /** * Get status code for testing comparison * @param {number} code HTTP status code of response * @return {number} resposne status code from WebhookClient */ status(code) { this.responseJson += code; return this; } /** * Store JSON repsonse from WebhookClient * @param {Object} message response object */ send(message) { this.callback(message); } }
JavaScript
class ToggleModuleCommand extends Command { /** * Sets up the command by providing the prefix, command trigger, any * aliases the command might have and additional options that * might be usfull for the abstract command class. */ constructor() { super('togglemodule', ['tmod'], { allowDM: false, usage: '<module> [channel|all] [on|off]', middleware: [ 'require.user:general.administrator', 'throttle.user:2,5' ] }); /** * The list of command module/category names. * * @type {Array} */ this.categoryNames = _.map(categories, category => category.name.toLowerCase()); } /** * Executes the given command. * * @param {IUser} sender The Discordie user object that ran the command. * @param {IMessage} message The Discordie message object that triggered the command. * @param {Array} args The arguments that was parsed to the command. * @return {mixed} */ onCommand(sender, message, args) { if (args.length < 1) { return this.sendMissingArguments(message); } let moduleName = args.shift(); let module = this.getModule(moduleName); if (module === null) { return app.envoyer.sendWarn(message, 'commands.administration.togglemodule.invalid', { module: moduleName }); } if (module === 'administration') { return app.envoyer.sendWarn(message, 'commands.administration.togglemodule.disable-admin'); } let channel = 'all'; let secondArgument = args.shift(); if (secondArgument !== undefined) { channel = this.getChannelId(message, secondArgument); if (channel === null) { channel = 'all'; args.unshift(secondArgument); } } return app.database.getGuild(app.getGuildIdFrom(message)).then(guild => { let dbChannel = guild.get(`modules.${channel}`, {}); if (!dbChannel.hasOwnProperty(module)) { dbChannel[module] = true; } let status = !dbChannel[module]; if (guild.data.modules === null) { guild.data.modules = {}; } dbChannel[module] = this.getStatus(args, status); guild.data.modules[channel] = dbChannel; if (channel === 'all' && !status) { for (let index in guild.data.modules) { if (index === 'all') { continue; } if (guild.data.modules[index].hasOwnProperty(module)) { delete guild.data.modules[index][module]; } } } app.database.update(app.constants.GUILD_TABLE_NAME, { modules: JSON.stringify(guild.data.modules) }, query => query.where('id', app.getGuildIdFrom(message))); if (channel !== 'all') { return app.envoyer.sendSuccess(message, 'commands.administration.togglemodule.channel.' + (dbChannel[module] ? 'enabled' : 'disabled'), { channel: `<#${channel}>`, module }); } return app.envoyer.sendSuccess(message, 'commands.administration.togglemodule.global.' + (dbChannel[module] ? 'enabled' : 'disabled'), { module }); }); } /** * Gets the full module name that matches the given module. * * @param {String} module The module that should be fetched. * @return {String|null} */ getModule(module) { for (let i in this.categoryNames) { if (_.startsWith(this.categoryNames[i], module.toLowerCase())) { return this.categoryNames[i]; } } return null; } /** * Gets the channel ID from the given message. * * @param {IMessage} message The Discordie message object that triggered the command. * @param {String} channelString The channel argument given to the command. * @return {String|null} */ getChannelId(message, channelString) { if (!_.startsWith(channelString, '<#')) { return channelString.toLowerCase() === 'all' ? 'all' : null; } let id = channelString.substr(2, channelString.length - 3); let channels = message.guild.channels; for (let i in channels) { let channel = channels[i]; if (channel.type === 0 && channel.id === id) { return id; } } return null; } /** * Gets the status from the given arguments if one is * given, otherwise returne the fallback status. * * @param {Array} args The list of arguments given to the command. * @param {Boolean} status The fallback status. * @return {Boolean} */ getStatus(args, status) { if (args.length < 1) { return status; } let stringStatus = args[0].toLowerCase(); return stringStatus === 'on' ? true : stringStatus === 'off' ? false : status; } }
JavaScript
class OnsetDetection { /** * Get spectral flux * @param {Float32Array} audioData - non-interleaved IEEE 32-bit linear PCM with a nominal range of -1 -> +1 (Web Audio API - Audio Buffer) * @param {Object} fft - object with methods for performing FFT * @param {Object} [params={}] - parameters * @param {Number} [params.bufferSize=2048] - FFT windows size * @param {Number} [params.hopSize=441] - spacing of audio frames in samples * @return {Array} spectralFlux - the array of spectral flux values */ static calculateSF(audioData, fft, params = {}) { if (typeof fft == "undefined") { throw new ReferenceError("fft is undefined"); } if (typeof fft.getHammingWindow !== "function" || typeof fft.getSpectrum !== "function") { throw new ReferenceError("fft doesn't contain getHammingWindow or getSpectrum methods"); } // Array.fill polyfill if (!Array.prototype.fill) { Array.prototype.fill = function(value) { if (this == null) { throw new TypeError('this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; var start = arguments[1]; var relativeStart = start >> 0; var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); var end = arguments[2]; var relativeEnd = end === undefined ? len : end >> 0; var final = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); while (k < final) { O[k] = value; k++; } return O; }; } params.bufferSize = params.bufferSize || 2048; //params.samplingRate = params.samplingRate || 44100; params.hopSize = params.hopSize || 441; const {bufferSize, hopSize} = params; let k = Math.floor(Math.log(bufferSize) / Math.LN2); if (Math.pow(2, k) !== bufferSize) { throw "Invalid buffer size (" + bufferSize + "), must be power of 2"; } const hammWindow = fft.getHammingWindow(bufferSize); let spectralFlux = []; let spectrumLength = bufferSize / 2 + 1; let previousSpectrum = new Array(spectrumLength); previousSpectrum.fill(0); let im = new Array(bufferSize); let length = audioData.length; let zerosStart = new Array(bufferSize - hopSize); zerosStart.fill(0); audioData = zerosStart.concat(audioData); let zerosEnd = new Array(bufferSize - (audioData.length % hopSize)); zerosEnd.fill(0); audioData = audioData.concat(zerosEnd); for (let wndStart = 0; wndStart < length; wndStart += hopSize) { let wndEnd = wndStart + bufferSize; let re = []; let k = 0; for (let i = wndStart; i < wndEnd; i++) { re[k] = hammWindow[k] * audioData[i]; k++; } im.fill(0); fft.getSpectrum(re, im); let flux = 0; for(let j = 0; j < spectrumLength; j++) { let value = re[j] - previousSpectrum[j]; flux += value < 0 ? 0 : value; } spectralFlux.push(flux); previousSpectrum = re; } return spectralFlux; } /** * Normalize data to have a mean of 0 and standard deviation of 1 * @param {Array} data - data array */ static normalize(data) { if (!Array.isArray(data)) { throw "Array expected"; } if (data.length == 0) { throw "Array is empty"; } let sum = 0; let squareSum = 0; for (let i = 0; i < data.length; i++) { sum += data[i]; squareSum += data[i] * data[i]; } let mean = sum / data.length; let standardDeviation = Math.sqrt( (squareSum - sum * mean) / data.length ); if (standardDeviation == 0) standardDeviation = 1; for (let i = 0; i < data.length; i++) { data[i] = (data[i] - mean) / standardDeviation; } } /** * Finding local maxima in an array * @param {Array} spectralFlux - input data * @param {Object} [params={}] - parametrs * @param {Number} [params.decayRate=0.84] - how quickly previous peaks are forgotten * @param {Number} [params.peakFindingWindow=6] - minimum distance between peaks * @param {Number} [params.meanWndMultiplier=3] - multiplier for peak finding window * @param {Number} [params.peakThreshold=0.35] - minimum value of peaks * @return {Array} peaks - array of peak indexes */ static findPeaks(spectralFlux, params = {}) { const length = spectralFlux.length; const sf = spectralFlux; const decayRate = params.decayRate || 0.84; const peakFindingWindow = params.peakFindingWindow || 6; const meanWndMultiplier = params.meanWndMultiplier || 3; const peakThreshold = params.peakThreshold || 0.35; let max = 0; let av = sf[0]; let peaks = []; for (let i = 0; i < length; i++) { av = decayRate * av + (1 - decayRate) * sf[i]; if (sf[i] < av) continue; let wndStart = i - peakFindingWindow; let wndEnd = i + peakFindingWindow + 1; if (wndStart < 0) wndStart = 0; if (wndEnd > length) wndEnd = length; if (av < sf[i]) av = sf[i]; let isMax = true; for (let j = wndStart; j < wndEnd; j++) { if (sf[j] > sf[i]) isMax = false; } if (isMax) { let meanWndStart = i - peakFindingWindow * meanWndMultiplier; let meanWndEnd = i + peakFindingWindow; if (meanWndStart < 0) meanWndStart = 0; if (meanWndEnd > length) meanWndEnd = length; let sum = 0; let count = meanWndEnd - meanWndStart; for (let j = meanWndStart; j < meanWndEnd; j++) { sum += sf[j]; } if (sf[i] > sum / count + peakThreshold) { peaks.push(i); } } } if (peaks.length < 2) { throw "Fail to find peaks"; } return peaks; } }
JavaScript
class UriQueryOptionSemanticError extends UriSemanticError { /** * Creating an instance of UriQueryOptionSemanticError. * * @param {string} message The message of the error * @param {...string} parameters parameters for the message */ constructor(message, ...parameters) { super(util.format(message, ...parameters)); this.name = UriSemanticError.ErrorNames.URI_QUERY_OPTION_SEMANTIC; } }
JavaScript
class Sponsership extends React.Component { render() { return ( <> <div className="content"> {/* CODE GOES HERE INSIDE THE <DIV> */} <h2 id="h2">Coming Soon...</h2> </div> </> ); } }
JavaScript
class Mission { constructor(_selfId, _peerId, _params, _config) { this._selfId = _selfId; this._peerId = _peerId; this._params = _params; this._config = _config; } get params() { return this._params; } get id() { return this._selfId; } get peerId() { return this._peerId; } async getPeerId() { const kafkaMessageStream = await Kafka_1.default.messages(this._selfId, this._config); // Channel#4 or Channel#6 const messageParamsStream = kafkaMessageStream.filterType(KafkaMessageFactory_1.default.instance.getMessageTypes(MissionPeerIdMessageParams_1.default._protocol, KafkaMessageFactory_1.MessageCategories.Message)); const messageStream = messageParamsStream .do((messageParams) => { this._peerId = messageParams.senderId; }) .map((messageParams) => messageParams.senderId) .first() .toPromise(); return messageStream; } /** * @method signContract Used to transfer tokens to the basicMission contract in order to start the mission. * @param walletPrivateKey Ethereum wallet private key, to charge for the mission. * @returns Ethereum transaction receipt. */ async signContract(walletPrivateKey) { try { const transactionReceipt = await Contracts_1.default.startMission(this._params.id, this._params.neederDavId, walletPrivateKey, this._params.vehicleId, this._params.price, this._config); return transactionReceipt; } catch (err) { throw new Error(`Fail to sign contract ${err}`); } } /** * @method finalizeMission Used to approve the mission is completed, * and transfer the tokens from the basicMission contract to the service provider. * @param walletPrivateKey Ethereum wallet private key, to charge for the mission. * @returns Ethereum transaction receipt object. */ async finalizeMission(walletPrivateKey) { try { const transactionReceipt = await Contracts_1.default.finalizeMission(this._params.id, this._params.neederDavId, walletPrivateKey, this._config); return transactionReceipt; } catch (err) { throw new Error(`Fail to finalize mission ${err}`); } } /** * @method sendMessage Used to send message to the service consumer. * @param params message parameters. */ async sendMessage(params) { if (!this._peerId) { await this.getPeerId(); } params.senderId = this._selfId; return await Kafka_1.default.sendParams(this._peerId, params, this._config); // Channel#4 } /** * @method messages Used to subscribe for messages from the service provider. * @param filterType (optional) array of the expected message params object type. * @returns Observable object. */ async messages(filterType) { const kafkaMessageStream = await Kafka_1.default.messages(this._selfId, this._config); // Channel#4 or Channel#6 const messageParamsStream = kafkaMessageStream.filterType(filterType || KafkaMessageFactory_1.default.instance.getMessageTypes(this._params.protocol, KafkaMessageFactory_1.MessageCategories.Message)); const messageStream = messageParamsStream.map((params) => new Message_1.default(this._selfId, params, this._config)); return common_types_1.Observable.fromObservable(messageStream, messageParamsStream.topic); } }
JavaScript
class BaseComponent { constructor(hotInstance) { this.hot = hotInstance; /** * List of registered component UI elements. * * @type {Array} */ this.elements = []; /** * Flag which determines if element is hidden. * * @type {boolean} */ this.hidden = false; } /** * Reset elements to their initial state. */ reset() { arrayEach(this.elements, ui => ui.reset()); } /** * Hide component. */ hide() { this.hidden = true; } /** * Show component. */ show() { this.hidden = false; } /** * Check if component is hidden. * * @returns {boolean} */ isHidden() { return this.hidden; } /** * Destroy element. */ destroy() { this.clearLocalHooks(); arrayEach(this.elements, ui => ui.destroy()); this.elements = null; this.hot = null; } }
JavaScript
class LokiTransport extends Transport { /** * Creates an instance of LokiTransport. * @param {*} options * @memberof LokiTransport */ constructor (options) { super(options) // Pass all the given options to batcher this.batcher = new Batcher({ host: options.host, basicAuth: options.basicAuth, headers: options.headers || {}, interval: options.interval, json: options.json, batching: options.batching !== false, clearOnError: options.clearOnError, replaceOnError: options.replaceOnError, replaceTimestamp: options.replaceTimestamp, gracefulShutdown: options.gracefulShutdown !== false }) this.useCustomFormat = options.format !== undefined this.labels = options.labels } /** * An overwrite of winston-transport's log(), * which the Winston logging library uses * when pushing logs to a transport. * * @param {*} info * @param {*} callback * @memberof LokiTransport */ log (info, callback) { // Immediately tell Winston that this transport has received the log. setImmediate(() => { this.emit('logged', info) }) // Deconstruct the log const { label, labels, timestamp, level, message, ...rest } = info // build custom labels if provided let lokiLabels = { level: level } lokiLabels = Object.assign(lokiLabels, labels); if (this.labels) { lokiLabels = Object.assign(lokiLabels, this.labels) } else { lokiLabels['job'] = label } // follow the format provided const line = this.useCustomFormat ? info[MESSAGE] : `${message} ${ rest && Object.keys(rest).length > 0 ? JSON.stringify(rest) : '' }` // Construct the log to fit Grafana Loki's accepted format const logEntry = { labels: lokiLabels, entries: [ { ts: timestamp || Date.now().valueOf(), line } ] } // Pushes the log to the batcher this.batcher.pushLogEntry(logEntry) // Trigger the optional callback callback() } /** * Send batch to loki when clean up */ close () { this.batcher.sendBatchToLoki() .then(() => {}) // maybe should emit something here .catch(() => {}) // maybe should emit something here } }
JavaScript
class StringFormatter extends base_formatter_1.BaseFormatter { constructor() { super(); } /** * camelCase() * * converts an input into camel case. * * if the input is not a string type, camelCase() will attempt to convert it to a string. * @param input the input. * @returns The input in camel case format. */ camelCase(input) { return change_case_1.camelCase(this.castToString(input)); } /** * capitalCase() * * converts an input into capital case. * * if the input is not a string type, capitalCase() will attempt to convert it to a string. * @param input the input. * @returns The input in capital case format. */ capitalCase(input) { return change_case_1.capitalCase(this.castToString(input)); } /** * constantCase() * * converts an input into constant case. * * if the input is not a string type, constantCase() will attempt to convert it to a string. * @param input the input. * @returns The input in camel constant format. */ constantCase(input) { return change_case_1.constantCase(this.castToString(input)); } /** * dotCase() * * converts an input into dot case. * * if the input is not a string type, dotCase() will attempt to convert it to a string. * @param input the input. * @returns The input in dot case format. */ dotCase(input) { return change_case_1.dotCase(this.castToString(input)); } /** * headerCase() * * converts an input into header case. * * if the input is not a string type, headerCase() will attempt to convert it to a string. * @param input the input. * @returns The input in header case format. */ headerCase(input) { return change_case_1.headerCase(this.castToString(input)); } /** * noCase() * * converts an input into no case. * * if the input is not a string type, noCase() will attempt to convert it to a string. * @param input the input. * @returns The input in no case format. */ noCase(input) { return change_case_1.noCase(this.castToString(input)); } /** * paramCase() * * converts an input into param case. * * if the input is not a string type, paramCase() will attempt to convert it to a string. * @param input the input. * @returns The input in param case format. */ paramCase(input) { return change_case_1.paramCase(this.castToString(input)); } /** * pascalCase() * * converts an input into pascal case. * * if the input is not a string type, pascalCase() will attempt to convert it to a string. * @param input the input. * @returns The input in pascal case format. */ pascalCase(input) { return change_case_1.pascalCase(this.castToString(input)); } /** * pathCase() * * converts an input into path case. * * if the input is not a string type, pathCase() will attempt to convert it to a string. * @param input the input. * @returns The input in path case format. */ pathCase(input) { return change_case_1.pathCase(this.castToString(input)); } /** * snakeCase() * * converts an input into snake case. * * if the input is not a string type, snakeCase() will attempt to convert it to a string. * @param input the input. * @returns The input in snake case format. */ snakeCase(input) { return change_case_1.snakeCase(this.castToString(input)); } // ============================= // Helpers // ============================= /** * castToString() * * casts the input to a string * @param input the input to cast. */ castToString(input) { const type = typeof input; if ((input === null) || (input === undefined)) { return ""; } else if (type === "string") { return input; } else { return input.toString(); } } }
JavaScript
class Route { /** * HTTP method of the route. * @type {'get'|'post'|'put'|'delete'} */ method = null; /** * Route spec. * @type {string} */ spec = null; /** * Relative path from the app directory to the component. * @type {string} */ contentComponent = null; /** * Title of the page. * @type {string} */ title = null; /** * If true the route requires authorized user. * @type {boolean} */ requireAuth = false; /** * Alternative layout component. */ layout = null; /** * Callback to call when the route is called. * @type {function} */ callback = null; /** * * @param {'get'|'post'|'put'|'delete'} method HTTP method of the route. * @param {string} spec Route spec. * @param {string} contentComponent Relative path from the {config.appDir} to the component. * @param {string} title Title of the page. * @param {boolean} requireAuth If true the route requires authorized user. * @param {any} layout Alternative layout component. * @param {function=} callback Callback to call when the route is called. */ constructor(method, spec, contentComponent, title, requireAuth = false, layout = null, callback = null) { this.method = method; this.spec = spec; this.contentComponent = contentComponent; this.title = title; this.requireAuth = requireAuth; this.layout = layout; this.callback = callback; } }
JavaScript
class NOAAWind extends Wind { constructor(stationId, tzOffset=0, directionOffset=0) { super(directionOffset); this.stationId = stationId; this.tzOffset = tzOffset; var startTime = moment().subtract(24, 'hours').format('YYYY-MM-DDTHH:mm[Z]'); var endTime = moment().format('YYYY-MM-DDTHH:mm[Z]'); // Make request to get JSON weather data for stationId this.xmlhttp = new XMLHttpRequest(); this.xmlhttp.onreadystatechange = this.onDataLoad.bind(this); this.xmlhttp.open('GET', 'https://sdf.ndbc.noaa.gov/sos/server.php?request=GetObservation&service=SOS&version=1.0.0&offering=' + stationId + '&observedproperty=Winds&responseformat=text/csv&eventtime=' + startTime + '/' + endTime, true); this.xmlhttp.send(); // fields: // - 0 station_id // - 1 sensor_id // - 2 latitude (degree) // - 3 longitude (degree) // - 4 date_time // - 5 depth (m) // - 6 wind_from_direction (degree) // - 7 wind_speed (m/s) // - 8 wind_speed_of_gust (m/s) // - 9 upward_air_velocity (m/s) } onDataLoad() { if (this.xmlhttp.readyState == 4) { if (this.xmlhttp.status == 200) { var response = Papa.parse(this.xmlhttp.responseText, { header: true }); var windDir = []; var windSpeed = []; var windGust = []; var minMoment = moment().subtract(3, 'hours'); for (var i=0; i<response.data.length; i++) { var observation = response.data[i]; var observationMoment = moment.parseZone(observation.date_time).add(this.tzOffset, 'hours'); // Filter out data that is not within the last three hours if (!observationMoment.isAfter(minMoment)) continue; // Compensate for bad data! var winddirAvg = this.directionOffset + observation['wind_from_direction (degree)']; if (winddirAvg > 360) { winddirAvg = winddirAvg - 360; } windDir.push({x: observationMoment, y: winddirAvg}); windSpeed.push({x: observationMoment, y: Math.round(observation['wind_speed (m/s)'] * 2.23694)}); windGust.push({x: observationMoment, y: Math.round(observation['wind_speed_of_gust (m/s)'] * 2.23694)}); } this.createChart(windSpeed, windGust, windDir); } else { console.error("Didn't get the expected status: " + this.xmlhttp.status); // Display empty charts this.createChart([], [], []); } } } }
JavaScript
class FlightCreateRequest extends BaseModel { /** * @constructor * @param {Object} obj The object passed to constructor */ constructor(obj) { super(obj); if (obj === undefined || obj === null) return; this.awardMilesRules = this.constructor.getValue(obj.awardMilesRules || obj.award_miles_rules); this.passenger = this.constructor.getValue(obj.passenger); this.routingType = this.constructor.getValue(obj.routingType || obj.routing_type); this.flights = this.constructor.getValue(obj.flights); } /** * Function containing information about the fields of this model * @return {array} Array of objects containing information about the fields */ static mappingInfo() { return super.mappingInfo().concat([ { name: 'awardMilesRules', realName: 'award_miles_rules', type: 'AwardMilesRules' }, { name: 'passenger', realName: 'passenger', type: 'PassengerMax' }, { name: 'routingType', realName: 'routing_type' }, { name: 'flights', realName: 'flights', array: true, type: 'FlightMax' }, ]); } /** * Function containing information about discriminator values * mapped with their corresponding model class names * * @return {object} Object containing Key-Value pairs mapping discriminator * values with their corresponding model classes */ static discriminatorMap() { return {}; } }
JavaScript
class ImageViewerHelper { static getContainer() { return document.getElementById(Constant.imageViewerId); } static getBodyHeight() { return document.body.clientHeight; } }
JavaScript
class P extends Promise { constructor(resolver) { if (hijack) { hijack = false; super((resolve, reject) => { return resolver(values => { actualArguments.push(values.slice()); return resolve(values); }, reject); }); } else { super(resolver); } } static resolve(p) { return p; } }
JavaScript
class InboundCallSession extends CallSession { constructor(req, res) { super({ logger: req.locals.logger, srf: req.srf, application: req.locals.application, callInfo: req.locals.callInfo, accountInfo: req.locals.accountInfo, tasks: req.locals.application.tasks }); this.req = req; this.res = res; req.once('cancel', this._onCancel.bind(this)); this.on('callStatusChange', this._notifyCallStatusChange.bind(this)); this._notifyCallStatusChange({ callStatus: CallStatus.Trying, sipStatus: 100, sipReason: 'Trying' }); } _onCancel() { this._notifyCallStatusChange({ callStatus: CallStatus.NoAnswer, sipStatus: 487, sipReason: 'Request Terminated' }); this._callReleased(); } _onTasksDone() { if (!this.res.finalResponseSent) { if (this._mediaServerFailure) { this.logger.info('InboundCallSession:_onTasksDone generating 480 due to media server failure'); this.res.send(480, { headers: { 'X-Reason': 'crankback: media server failure' } }); } else { this.logger.info('InboundCallSession:_onTasksDone auto-generating non-success response to invite'); this.res.send(603); } } this.req.removeAllListeners('cancel'); } /** * This is invoked when the caller hangs up, in order to calculate the call duration. */ _callerHungup() { assert(this.dlg.connectTime); const duration = moment().diff(this.dlg.connectTime, 'seconds'); this.emit('callStatusChange', { callStatus: CallStatus.Completed, duration }); this.logger.debug('InboundCallSession: caller hung up'); this._callReleased(); this.req.removeAllListeners('cancel'); } }
JavaScript
class RemoteUser { constructor(editor, selection, hexColor, label) { this._cursorWidget = new CursorWidget( editor, selection.getPosition(), hexColor, label ); this._selectionDecoration = new SelectionDecoration( editor, selection, hexColor ); } /** * Updates indicators to match the given selection. */ update(selection) { this._cursorWidget.update(selection.getPosition()); this._selectionDecoration.update(selection); } /** * Performs necessary cleanup actions. */ dispose() { this._cursorWidget.dispose(); this._selectionDecoration.dispose(); } }
JavaScript
class ProtectedRoute extends Component { render() { const { component: Component, ...props } = this.props return ( <Route {...props} children={props => ( this.props.access_token ? <Component {...this.props} /> : <Welcome {...this.props} /> )} /> ) } }
JavaScript
class Input extends Base { [internal.componentDidMount]() { super[internal.componentDidMount](); // The following jsDoc comment doesn't directly apply to the statement which // follows, but is placed there because the comment has to go somewhere to // be visible to jsDoc, and the statement is at tangentially related. /** * Raised when the user changes the element's text content. * * This is the standard `input` event; the component does not do any work to * raise it. It is documented here to let people know it is available to * detect when the user edits the content. * * @event input */ this[internal.ids].inner.addEventListener("input", () => { this[internal.raiseChangeEvents] = true; // Invoke the value setter to fix up selectionStart/selectionEnd too. this.value = /** @type {any} */ (this.inner).value; this[internal.raiseChangeEvents] = false; }); this.setAttribute("role", "none"); } get [internal.template]() { const result = super[internal.template]; result.content.append( html` <style> [part~="inner"] { font: inherit; text-align: inherit; } </style> ` ); return result; } // Updating the value can also update the selectionStart and selectionEnd // properties, so we have to update our state to match. get value() { // @ts-ignore return super.value; } set value(value) { // @ts-ignore super.value = value; if (this[internal.shadowRoot]) { /** @type {any} */ const inner = this.inner; this.setInnerProperty("selectionStart", inner.selectionStart); this.setInnerProperty("selectionEnd", inner.selectionEnd); } } }
JavaScript
class MixedContent extends Gatherer { constructor() { super(); this.ids = new Set(); this.url = undefined; this._onRequestIntercepted = undefined; } /** * @param {string} url * @return {string} */ upgradeURL(url) { const parsedURL = new URL(url); parsedURL.protocol = 'https:'; return parsedURL.href; } /** * @param {string} url * @return {string} */ downgradeURL(url) { const parsedURL = new URL(url); parsedURL.protocol = 'http:'; return parsedURL.href; } /** * @param {string} pageUrl * @param {Driver} driver */ _getRequestInterceptor(pageUrl, driver) { /** @param {LH.Crdp.Network.RequestInterceptedEvent} event */ const onRequestIntercepted = (event) => { // Track requests the gatherer has already seen so we can try at-most-once // to upgrade each. This avoids repeatedly intercepting a request if it gets // downgraded back to HTTP. if (new URL(event.request.url).protocol === 'http:' && !URL.equalWithExcludedFragments(event.request.url, pageUrl) && !this.ids.has(event.interceptionId)) { this.ids.add(event.interceptionId); event.request.url = this.upgradeURL(event.request.url); driver.sendCommand('Network.continueInterceptedRequest', { interceptionId: event.interceptionId, rawResponse: Buffer.from( `HTTP/1.1 302 Found\r\nLocation: ${event.request.url}\r\n\r\n`, 'utf8').toString('base64'), }); } else { driver.sendCommand('Network.continueInterceptedRequest', { interceptionId: event.interceptionId, }); } }; return onRequestIntercepted; } /** * @param {LH.Gatherer.PassContext} passContext */ async beforePass(passContext) { const driver = passContext.driver; // Attempt to load the HTTP version of the page. // The base URL can be brittle under redirects of the page, but the worst // case is the gatherer accidentally upgrades the final base URL to // HTTPS and loses the ability to check upgrading active mixed content. passContext.url = this.downgradeURL(passContext.url); this.url = passContext.url; this._onRequestIntercepted = this._getRequestInterceptor(this.url, driver); await driver.sendCommand('Network.enable'); driver.on('Network.requestIntercepted', this._onRequestIntercepted); await driver.sendCommand('Network.setCacheDisabled', {cacheDisabled: true}); await driver.sendCommand('Network.setRequestInterception', {patterns: [{urlPattern: '*'}]}); } /** * @param {LH.Gatherer.PassContext} passContext * @return {Promise<{url: string}>} */ async afterPass(passContext) { const driver = passContext.driver; await driver.sendCommand('Network.setRequestInterception', {patterns: []}); if (this._onRequestIntercepted) { driver.off('Network.requestIntercepted', this._onRequestIntercepted); } await driver.sendCommand('Network.setCacheDisabled', {cacheDisabled: false}); return {url: passContext.url}; } }
JavaScript
class RegistryConfig extends EventEmitter { constructor() { super(); this.initialized = false; this.data = { teams: [], }; } /** * Triggers loading data from Windows registry, supports async/await * * @emits {update} emitted once all data has been loaded from the registry */ async init() { if (process.platform === 'win32') { // extract DefaultServerList from the registry try { const servers = await this.getServersListFromRegistry(); if (servers.length) { this.data.teams.push(...servers); } } catch (error) { console.log('[RegistryConfig] Nothing retrieved for \'DefaultServerList\'', error); } // extract EnableServerManagement from the registry try { const enableServerManagement = await this.getEnableServerManagementFromRegistry(); if (enableServerManagement !== null) { this.data.enableServerManagement = enableServerManagement; } } catch (error) { console.log('[RegistryConfig] Nothing retrieved for \'EnableServerManagement\'', error); } // extract EnableAutoUpdater from the registry try { const enableAutoUpdater = await this.getEnableAutoUpdatorFromRegistry(); if (enableAutoUpdater !== null) { this.data.enableAutoUpdater = enableAutoUpdater; } } catch (error) { console.log('[RegistryConfig] Nothing retrieved for \'EnableAutoUpdater\'', error); } } this.initialized = true; this.emit('update', this.data); } /** * Extracts a list of servers */ async getServersListFromRegistry() { const defaultTeams = await this.getRegistryEntry(`${BASE_REGISTRY_KEY_PATH}\\DefaultServerList`); return defaultTeams.flat(2).reduce((teams, team) => { if (team) { teams.push({ name: team.name, url: team.value, order: team.order, }); } return teams; }, []); } /** * Determines whether server management has been enabled, disabled or isn't configured */ async getEnableServerManagementFromRegistry() { const entries = (await this.getRegistryEntry(BASE_REGISTRY_KEY_PATH, 'EnableServerManagement')); const entry = entries.pop(); return entry ? entry === '0x1' : null; } /** * Determines whether the auto updated has been enabled, disabled or isn't configured */ async getEnableAutoUpdatorFromRegistry() { const entries = (await this.getRegistryEntry(BASE_REGISTRY_KEY_PATH, 'EnableAutoUpdater')); const entry = entries.pop(); return entry ? entry === '0x1' : null; } /** * Initiates retrieval of a specific key in the Windows registry * * @param {string} key Path to the registry key to return * @param {string} name Name of specific entry in the registry key to retrieve (optional) */ async getRegistryEntry(key, name) { const results = []; for (const hive of REGISTRY_HIVE_LIST) { results.push(this.getRegistryEntryValues(new WindowsRegistry({hive, key}), name)); } const entryValues = await Promise.all(results); return entryValues.filter((value) => value); } /** * Handles actual retrieval of entries from a configured WindowsRegistry instance * * @param {WindowsRegistry} regKey A configured instance of the WindowsRegistry class * @param {string} name Name of the specific entry to retrieve (optional) */ getRegistryEntryValues(regKey, name) { return new Promise((resolve) => { regKey.values((error, items) => { if (error || !items || !items.length) { resolve(); return; } if (name) { // looking for a single entry value const registryItem = items.find((item) => item.name === name); resolve(registryItem && registryItem.value ? registryItem.value : null); } else { // looking for an entry list resolve(items); } }); }); } }
JavaScript
class Project extends Requestable { /** * Create a Project. * @param {string} id - the id of the project * @param {Requestable.auth} [auth] - information required to authenticate to Github * @param {string} [apiBase=https://api.github.com] - the base Github API URL */ constructor(id, auth, apiBase) { super(auth, apiBase, 'inertia-preview'); this.__id = id; } /** * Get information about a project * @see https://developer.github.com/v3/projects/#get-a-project * @param {Requestable.callback} cb - will receive the project information * @return {Promise} - the promise for the http request */ getProject(cb) { return this._request('GET', `/projects/${this.__id}`, null, cb); } /** * Edit a project * @see https://developer.github.com/v3/projects/#update-a-project * @param {Object} options - the description of the project * @param {Requestable.callback} cb - will receive the modified project * @return {Promise} - the promise for the http request */ updateProject(options, cb) { return this._request('PATCH', `/projects/${this.__id}`, options, cb); } /** * Delete a project * @see https://developer.github.com/v3/projects/#delete-a-project * @param {Requestable.callback} cb - will receive true if the operation is successful * @return {Promise} - the promise for the http request */ deleteProject(cb) { return this._request('DELETE', `/projects/${this.__id}`, null, cb); } /** * Get information about all columns of a project * @see https://developer.github.com/v3/projects/columns/#list-project-columns * @param {Requestable.callback} [cb] - will receive the list of columns * @return {Promise} - the promise for the http request */ listProjectColumns(cb) { return this._requestAllPages(`/projects/${this.__id}/columns`, null, cb); } /** * Get information about a column * @see https://developer.github.com/v3/projects/columns/#get-a-project-column * @param {string} colId - the id of the column * @param {Requestable.callback} cb - will receive the column information * @return {Promise} - the promise for the http request */ getProjectColumn(colId, cb) { return this._request('GET', `/projects/columns/${colId}`, null, cb); } /** * Create a new column * @see https://developer.github.com/v3/projects/columns/#create-a-project-column * @param {Object} options - the description of the column * @param {Requestable.callback} cb - will receive the newly created column * @return {Promise} - the promise for the http request */ createProjectColumn(options, cb) { return this._request('POST', `/projects/${this.__id}/columns`, options, cb); } /** * Edit a column * @see https://developer.github.com/v3/projects/columns/#update-a-project-column * @param {string} colId - the column id * @param {Object} options - the description of the column * @param {Requestable.callback} cb - will receive the modified column * @return {Promise} - the promise for the http request */ updateProjectColumn(colId, options, cb) { return this._request('PATCH', `/projects/columns/${colId}`, options, cb); } /** * Delete a column * @see https://developer.github.com/v3/projects/columns/#delete-a-project-column * @param {string} colId - the column to be deleted * @param {Requestable.callback} cb - will receive true if the operation is successful * @return {Promise} - the promise for the http request */ deleteProjectColumn(colId, cb) { return this._request('DELETE', `/projects/columns/${colId}`, null, cb); } /** * Move a column * @see https://developer.github.com/v3/projects/columns/#move-a-project-column * @param {string} colId - the column to be moved * @param {string} position - can be one of first, last, or after:<column-id>, * where <column-id> is the id value of a column in the same project. * @param {Requestable.callback} cb - will receive true if the operation is successful * @return {Promise} - the promise for the http request */ moveProjectColumn(colId, position, cb) { return this._request( 'POST', `/projects/columns/${colId}/moves`, {position: position}, cb ); } /** * Get information about all cards of a project * @see https://developer.github.com/v3/projects/cards/#list-project-cards * @param {Requestable.callback} [cb] - will receive the list of cards * @return {Promise} - the promise for the http request */ listProjectCards(cb) { return this.listProjectColumns() .then(({data}) => { return Promise.all(data.map((column) => { return this._requestAllPages(`/projects/columns/${column.id}/cards`, null); })); }).then((cardsInColumns) => { const cards = cardsInColumns.reduce((prev, {data}) => { prev.push(...data); return prev; }, []); if (cb) { cb(null, cards); } return cards; }).catch((err) => { if (cb) { cb(err); return; } throw err; }); } /** * Get information about all cards of a column * @see https://developer.github.com/v3/projects/cards/#list-project-cards * @param {string} colId - the id of the column * @param {Requestable.callback} [cb] - will receive the list of cards * @return {Promise} - the promise for the http request */ listColumnCards(colId, cb) { return this._requestAllPages(`/projects/columns/${colId}/cards`, null, cb); } /** * Get information about a card * @see https://developer.github.com/v3/projects/cards/#get-a-project-card * @param {string} cardId - the id of the card * @param {Requestable.callback} cb - will receive the card information * @return {Promise} - the promise for the http request */ getProjectCard(cardId, cb) { return this._request('GET', `/projects/columns/cards/${cardId}`, null, cb); } /** * Create a new card * @see https://developer.github.com/v3/projects/cards/#create-a-project-card * @param {string} colId - the column id * @param {Object} options - the description of the card * @param {Requestable.callback} cb - will receive the newly created card * @return {Promise} - the promise for the http request */ createProjectCard(colId, options, cb) { return this._request('POST', `/projects/columns/${colId}/cards`, options, cb); } /** * Edit a card * @see https://developer.github.com/v3/projects/cards/#update-a-project-card * @param {string} cardId - the card id * @param {Object} options - the description of the card * @param {Requestable.callback} cb - will receive the modified card * @return {Promise} - the promise for the http request */ updateProjectCard(cardId, options, cb) { return this._request('PATCH', `/projects/columns/cards/${cardId}`, options, cb); } /** * Delete a card * @see https://developer.github.com/v3/projects/cards/#delete-a-project-card * @param {string} cardId - the card to be deleted * @param {Requestable.callback} cb - will receive true if the operation is successful * @return {Promise} - the promise for the http request */ deleteProjectCard(cardId, cb) { return this._request('DELETE', `/projects/columns/cards/${cardId}`, null, cb); } /** * Move a card * @see https://developer.github.com/v3/projects/cards/#move-a-project-card * @param {string} cardId - the card to be moved * @param {string} position - can be one of top, bottom, or after:<card-id>, * where <card-id> is the id value of a card in the same project. * @param {string} colId - the id value of a column in the same project. * @param {Requestable.callback} cb - will receive true if the operation is successful * @return {Promise} - the promise for the http request */ moveProjectCard(cardId, position, colId, cb) { return this._request( 'POST', `/projects/columns/cards/${cardId}/moves`, {position: position, column_id: colId}, // eslint-disable-line camelcase cb ); } }
JavaScript
class AbstractPredicateTransition extends Transition_1.Transition { constructor(target) { super(target); } }
JavaScript
class StateProofService { /** * Constructor * @param repositoryFactory */ constructor(repositoryFactory) { this.repositoryFactory = repositoryFactory; this.blockRepo = repositoryFactory.createBlockRepository(); } /** * @param address Account address. * @returns {Observable<StateMerkleProof>} */ accountById(address) { const accountRepo = this.repositoryFactory.createAccountRepository(); return accountRepo.getAccountInfo(address).pipe(operators_1.mergeMap((info) => this.account(info))); } account(info) { const accountRepo = this.repositoryFactory.createAccountRepository(); return accountRepo.getAccountInfoMerkle(info.address).pipe(operators_1.map((merkle) => this.toProof(info.serialize(), merkle))); } /** * Namespace proof can only be verified at root level * @param namespaceId Namepace Id. * @returns {Observable<StateMerkleProof>} */ namespaceById(namespaceId) { const namespaceRepo = this.repositoryFactory.createNamespaceRepository(); return namespaceRepo.getNamespace(namespaceId).pipe(operators_1.mergeMap((namespace) => { if (namespace.registrationType !== model_1.NamespaceRegistrationType.RootNamespace) { throw new Error('Namespace proof can only be verified at root level.'); } return this.namespaces(namespace); })); } namespaces(root) { if (root.registrationType !== model_1.NamespaceRegistrationType.RootNamespace) { throw new Error('Namespace proof can only be verified at root level.'); } const namespaceRepo = this.repositoryFactory.createNamespaceRepository(); return namespaceRepo .streamer() .search({ level0: root.id }) .pipe(operators_1.toArray()) .pipe(operators_1.mergeMap((fullPath) => { return namespaceRepo.getNamespaceMerkle(root.id).pipe(operators_1.map((merkle) => { return this.toProof(root.serialize(fullPath), merkle); })); })); } /** * @param mosaicId Mosaic Id. * @returns {Observable<StateMerkleProof>} */ mosaicById(mosaicId) { const mosaicRepo = this.repositoryFactory.createMosaicRepository(); return mosaicRepo.getMosaic(mosaicId).pipe(operators_1.mergeMap((info) => { return this.mosaic(info); })); } mosaic(info) { const mosaicRepo = this.repositoryFactory.createMosaicRepository(); return mosaicRepo.getMosaicMerkle(info.id).pipe(operators_1.map((merkle) => { return this.toProof(info.serialize(), merkle); })); } /** * @param address Multisig account address. * @returns {Observable<StateMerkleProof>} */ multisigById(address) { const multisigRepo = this.repositoryFactory.createMultisigRepository(); return multisigRepo.getMultisigAccountInfo(address).pipe(operators_1.mergeMap((info) => { return this.multisig(info); })); } multisig(info) { const multisigRepo = this.repositoryFactory.createMultisigRepository(); return multisigRepo.getMultisigAccountInfoMerkle(info.accountAddress).pipe(operators_1.map((merkle) => { return this.toProof(info.serialize(), merkle); })); } /** * @param compositeHash Composite hash. * @returns {Observable<StateMerkleProof>} */ secretLockById(compositeHash) { const secretLockRepo = this.repositoryFactory.createSecretLockRepository(); return secretLockRepo.getSecretLock(compositeHash).pipe(operators_1.mergeMap((info) => { return this.secretLock(info); })); } secretLock(info) { const secretLockRepo = this.repositoryFactory.createSecretLockRepository(); return secretLockRepo.getSecretLockMerkle(info.compositeHash).pipe(operators_1.map((merkle) => { return this.toProof(info.serialize(), merkle); })); } /** * @param hash hashs. * @returns {Observable<StateMerkleProof>} */ hashLockById(hash) { const hashLockRepo = this.repositoryFactory.createHashLockRepository(); return hashLockRepo.getHashLock(hash).pipe(operators_1.mergeMap((info) => this.hashLock(info))); } hashLock(info) { const hashLockRepo = this.repositoryFactory.createHashLockRepository(); return hashLockRepo.getHashLockMerkle(info.hash).pipe(operators_1.map((merkle) => { return this.toProof(info.serialize(), merkle); })); } /** * @param address Address. * @returns {Observable<StateMerkleProof>} */ accountRestrictionById(address) { const restrictionRepo = this.repositoryFactory.createRestrictionAccountRepository(); return restrictionRepo.getAccountRestrictions(address).pipe(operators_1.mergeMap((info) => { return restrictionRepo.getAccountRestrictionsMerkle(address).pipe(operators_1.map((merkle) => { return this.toProof(info.serialize(), merkle); })); })); } accountRestriction(info) { const restrictionRepo = this.repositoryFactory.createRestrictionAccountRepository(); return restrictionRepo.getAccountRestrictionsMerkle(info.address).pipe(operators_1.map((merkle) => { return this.toProof(info.serialize(), merkle); })); } /** * @param compositeHash Composite hash. * @returns {Observable<StateMerkleProof>} */ mosaicRestrictionById(compositeHash) { const restrictionRepo = this.repositoryFactory.createRestrictionMosaicRepository(); return restrictionRepo.getMosaicRestrictions(compositeHash).pipe(operators_1.mergeMap((info) => this.mosaicRestriction(info))); } mosaicRestriction(info) { const restrictionRepo = this.repositoryFactory.createRestrictionMosaicRepository(); return restrictionRepo .getMosaicRestrictionsMerkle(info.compositeHash) .pipe(operators_1.map((merkle) => this.toProof(info.serialize(), merkle))); } /** * @param compositeHash Composite hash. * @returns {Observable<StateMerkleProof>} */ metadataById(compositeHash) { const metaDataRepo = this.repositoryFactory.createMetadataRepository(); return metaDataRepo.getMetadata(compositeHash).pipe(operators_1.mergeMap((info) => this.metadata(info))); } metadata(info) { const metaDataRepo = this.repositoryFactory.createMetadataRepository(); return metaDataRepo .getMetadataMerkle(info.metadataEntry.compositeHash) .pipe(operators_1.map((merkle) => this.toProof(info.metadataEntry.serialize(), merkle))); } toProof(serialized, merkle) { var _a, _b; const hash = format_1.Convert.uint8ToHex(serialized); const stateHash = js_sha3_1.sha3_256.create().update(format_1.Convert.hexToUint8(hash)).hex().toUpperCase(); const valid = stateHash === ((_a = merkle.tree.leaf) === null || _a === void 0 ? void 0 : _a.value); return new state_1.StateMerkleProof(stateHash, merkle.tree, this.getRootHash(merkle.tree), (_b = merkle.tree.leaf) === null || _b === void 0 ? void 0 : _b.value, valid); } getRootHash(tree) { return tree.branches.length ? tree.branches[0].branchHash : tree === null || tree === void 0 ? void 0 : tree.leaf.leafHash; } }
JavaScript
class Client extends abstract_client_1.AbstractClient { constructor(clientConfig) { super("tcr.tencentcloudapi.com", "2019-09-24", clientConfig); } /** * 更新命名空间信息,当前仅支持修改命名空间访问级别 */ async ModifyNamespace(req, cb) { return this.request("ModifyNamespace", req, cb); } /** * 用于在个人版中查询与指定tag镜像内容相同的tag列表 */ async DescribeImageFilterPersonal(req, cb) { return this.request("DescribeImageFilterPersonal", req, cb); } /** * 用于查询应用更新触发器 */ async DescribeApplicationTriggerPersonal(req, cb) { return this.request("DescribeApplicationTriggerPersonal", req, cb); } /** * 用于在个人版中创建清理策略 */ async CreateImageLifecyclePersonal(req, cb) { return this.request("CreateImageLifecyclePersonal", req, cb); } /** * 用于在企业版中创建命名空间 */ async CreateNamespace(req, cb) { return this.request("CreateNamespace", req, cb); } /** * 用于获取个人版镜像仓库tag列表 */ async DescribeImagePersonal(req, cb) { return this.request("DescribeImagePersonal", req, cb); } /** * 用于获取个人版仓库中自动清理策略 */ async DescribeImageLifecyclePersonal(req, cb) { return this.request("DescribeImageLifecyclePersonal", req, cb); } /** * 用于获取个人版全局镜像版本自动清理策略 */ async DescribeImageLifecycleGlobalPersonal(req, cb) { return this.request("DescribeImageLifecycleGlobalPersonal", req, cb); } /** * 删除镜像仓库企业版实例 */ async DeleteInstance(req, cb) { return this.request("DeleteInstance", req, cb); } /** * 用于修改应用更新触发器 */ async ModifyApplicationTriggerPersonal(req, cb) { return this.request("ModifyApplicationTriggerPersonal", req, cb); } /** * 更新镜像仓库信息,可修改仓库描述信息 */ async ModifyRepository(req, cb) { return this.request("ModifyRepository", req, cb); } /** * 删除命名空间 */ async DeleteNamespace(req, cb) { return this.request("DeleteNamespace", req, cb); } /** * 删除镜像仓库 */ async DeleteRepository(req, cb) { return this.request("DeleteRepository", req, cb); } /** * 查询镜像仓库列表或指定镜像仓库信息 */ async DescribeRepositories(req, cb) { return this.request("DescribeRepositories", req, cb); } /** * 查询实例信息 */ async DescribeInstances(req, cb) { return this.request("DescribeInstances", req, cb); } /** * 用于在个人版镜像仓库中更新容器镜像描述 */ async ModifyRepositoryInfoPersonal(req, cb) { return this.request("ModifyRepositoryInfoPersonal", req, cb); } /** * 获取触发器日志 */ async DescribeWebhookTriggerLog(req, cb) { return this.request("DescribeWebhookTriggerLog", req, cb); } /** * 查询镜像版本列表或指定容器镜像信息 */ async DescribeImages(req, cb) { return this.request("DescribeImages", req, cb); } /** * 查询个人版命名空间信息 */ async DescribeNamespacePersonal(req, cb) { return this.request("DescribeNamespacePersonal", req, cb); } /** * 用于个人版镜像仓库中删除 */ async DeleteRepositoryPersonal(req, cb) { return this.request("DeleteRepositoryPersonal", req, cb); } /** * 查询个人版仓库信息 */ async DescribeRepositoryPersonal(req, cb) { return this.request("DescribeRepositoryPersonal", req, cb); } /** * 查询容器镜像Manifest信息 */ async DescribeImageManifests(req, cb) { return this.request("DescribeImageManifests", req, cb); } /** * 查询长期访问凭证信息 */ async DescribeInstanceToken(req, cb) { return this.request("DescribeInstanceToken", req, cb); } /** * 用于设置个人版全局镜像版本自动清理策略 */ async ManageImageLifecycleGlobalPersonal(req, cb) { return this.request("ManageImageLifecycleGlobalPersonal", req, cb); } /** * 用于查询应用更新触发器触发日志 */ async DescribeApplicationTriggerLogPersonal(req, cb) { return this.request("DescribeApplicationTriggerLogPersonal", req, cb); } /** * 预付费实例续费,同时支持按量计费转包年包月 */ async RenewInstance(req, cb) { return this.request("RenewInstance", req, cb); } /** * 删除长期访问凭证 */ async DeleteInstanceToken(req, cb) { return this.request("DeleteInstanceToken", req, cb); } /** * 修改个人用户登录密码 */ async ModifyUserPasswordPersonal(req, cb) { return this.request("ModifyUserPasswordPersonal", req, cb); } /** * 用于删除应用更新触发器 */ async DeleteApplicationTriggerPersonal(req, cb) { return this.request("DeleteApplicationTriggerPersonal", req, cb); } /** * 查询触发器 */ async DescribeWebhookTrigger(req, cb) { return this.request("DescribeWebhookTrigger", req, cb); } /** * 用于在个人版中删除tag */ async DeleteImagePersonal(req, cb) { return this.request("DeleteImagePersonal", req, cb); } /** * 管理实例内网访问VPC链接 */ async ManageInternalEndpoint(req, cb) { return this.request("ManageInternalEndpoint", req, cb); } /** * 更新触发器 */ async ModifyWebhookTrigger(req, cb) { return this.request("ModifyWebhookTrigger", req, cb); } /** * 更新实例内指定长期访问凭证的启用状态 */ async ModifyInstanceToken(req, cb) { return this.request("ModifyInstanceToken", req, cb); } /** * 创建实例 */ async CreateInstance(req, cb) { return this.request("CreateInstance", req, cb); } /** * 查询从实例列表 */ async DescribeReplicationInstances(req, cb) { return this.request("DescribeReplicationInstances", req, cb); } /** * 创建触发器 */ async CreateWebhookTrigger(req, cb) { return this.request("CreateWebhookTrigger", req, cb); } /** * 用于创建应用更新触发器 */ async CreateApplicationTriggerPersonal(req, cb) { return this.request("CreateApplicationTriggerPersonal", req, cb); } /** * 用于个人版镜像仓库中批量删除镜像仓库 */ async BatchDeleteRepositoryPersonal(req, cb) { return this.request("BatchDeleteRepositoryPersonal", req, cb); } /** * 查询个人用户配额 */ async DescribeUserQuotaPersonal(req, cb) { return this.request("DescribeUserQuotaPersonal", req, cb); } /** * 删除触发器 */ async DeleteWebhookTrigger(req, cb) { return this.request("DeleteWebhookTrigger", req, cb); } /** * 查询创建从实例任务状态 */ async DescribeReplicationInstanceCreateTasks(req, cb) { return this.request("DescribeReplicationInstanceCreateTasks", req, cb); } /** * 用于企业版创建镜像仓库 */ async CreateRepository(req, cb) { return this.request("CreateRepository", req, cb); } /** * 查询个人收藏仓库 */ async DescribeFavorRepositoryPersonal(req, cb) { return this.request("DescribeFavorRepositoryPersonal", req, cb); } /** * 用于在个人版中获取用户全部的镜像仓库列表 */ async DescribeRepositoryOwnerPersonal(req, cb) { return this.request("DescribeRepositoryOwnerPersonal", req, cb); } /** * 查询命名空间列表或指定命名空间信息 */ async DescribeNamespaces(req, cb) { return this.request("DescribeNamespaces", req, cb); } /** * 查询实例当前状态以及过程信息 */ async DescribeInstanceStatus(req, cb) { return this.request("DescribeInstanceStatus", req, cb); } /** * 用于在个人版仓库中创建镜像仓库 */ async CreateRepositoryPersonal(req, cb) { return this.request("CreateRepositoryPersonal", req, cb); } /** * 用于在个人版镜像仓库中批量删除Tag */ async BatchDeleteImagePersonal(req, cb) { return this.request("BatchDeleteImagePersonal", req, cb); } /** * 用于在个人版镜像仓库中复制镜像版本 */ async DuplicateImagePersonal(req, cb) { return this.request("DuplicateImagePersonal", req, cb); } /** * 用于在个人版镜像仓库中,获取满足输入搜索条件的用户镜像仓库 */ async DescribeRepositoryFilterPersonal(req, cb) { return this.request("DescribeRepositoryFilterPersonal", req, cb); } /** * 查询个人版用户命名空间是否存在 */ async ValidateNamespaceExistPersonal(req, cb) { return this.request("ValidateNamespaceExistPersonal", req, cb); } /** * 创建个人版镜像仓库命名空间,此命名空间全局唯一 */ async CreateNamespacePersonal(req, cb) { return this.request("CreateNamespacePersonal", req, cb); } /** * 创建个人用户 */ async CreateUserPersonal(req, cb) { return this.request("CreateUserPersonal", req, cb); } /** * 用于删除个人版全局镜像版本自动清理策略 */ async DeleteImageLifecycleGlobalPersonal(req, cb) { return this.request("DeleteImageLifecycleGlobalPersonal", req, cb); } /** * 删除共享版命名空间 */ async DeleteNamespacePersonal(req, cb) { return this.request("DeleteNamespacePersonal", req, cb); } /** * 用于更新个人版镜像仓库的访问属性 */ async ModifyRepositoryAccessPersonal(req, cb) { return this.request("ModifyRepositoryAccessPersonal", req, cb); } /** * 查询实例内网访问VPC链接 */ async DescribeInternalEndpoints(req, cb) { return this.request("DescribeInternalEndpoints", req, cb); } /** * 用于在个人版镜像仓库中删除仓库Tag自动清理策略 */ async DeleteImageLifecyclePersonal(req, cb) { return this.request("DeleteImageLifecyclePersonal", req, cb); } /** * 用于判断个人版仓库是否存在 */ async ValidateRepositoryExistPersonal(req, cb) { return this.request("ValidateRepositoryExistPersonal", req, cb); } /** * 删除指定镜像 */ async DeleteImage(req, cb) { return this.request("DeleteImage", req, cb); } /** * 创建实例的临时或长期访问凭证 */ async CreateInstanceToken(req, cb) { return this.request("CreateInstanceToken", req, cb); } }
JavaScript
class PowerSchoolSchool { constructor(api, id, name, schoolNumber, formattedAddress, addressParts, phone, fax, lowGrade, highGrade, disabled, disabledMessage, disabledFeatures, abbreviation) { this.api = api; /** * The ID of this school. * @member {number} */ this.id = id; /** * The name of this school. * @member {string} */ this.name = name; /** * The number of this school. * @member {number} */ this.schoolNumber = schoolNumber; /** * The school's address, formatted for display. * @member {string} */ this.formattedAddress = formattedAddress; /** * The part's making up the school's address (such as street address, city, state/province, country, ZIP/postal code). * @member {object} */ this.addressParts = addressParts; /** * The school's phone number, formatted for display. * @member {string} */ this.phone = phone; /** * The school's fax number, formatted for display. * @member {string} */ this.fax = fax; /** * The lowest grade this school has. * @member {number} */ this.lowGrade = lowGrade; /** * The highest grade this school has. * @member {number} */ this.highGrade = highGrade; /** * Whether or not the school is currently disabled. * @member {boolean} */ this.disabled = disabled; /** * Optional messages to display for the school if it is disabled (title and message keys in the object). * @member {object} */ this.disabledMessage = disabledMessage; /** * Features that are disabled on the school (object with true or false, on disabled status of each key). * @member {object} */ this.disabledFeatures = disabledFeatures; /** * The abbreviation for the school. * @member {object} */ this.abbreviation = abbreviation; } static fromData(data, api) { return new PowerSchoolSchool(api, data.schoolId, data.name, data.schoolNumber, data.address, { streetAddress: data.schooladdress, city: data.schoolcity, state: data.schoolstate, country: data.schoolcountry, zip: data.schoolzip }, data.schoolphone, data.schoolfax, data.lowGrade, data.highGrade, data.schoolDisabled, data.schoolDisabledTitle || data.schoolDisabledMessage ? { title: data.schoolDisabledTitle, message: data.schoolDisabledMessage } : null, data.disabledFeatures, data.abbreviation); } /** * Get the attendance codes that belong to this school. * @return {PowerSchoolAttendanceCode} */ getAttendanceCodes() { return Object.values(this.api._cachedInfo.attendanceCodes).filter((c) => c.schoolNumber == this.schoolNumber); } }
JavaScript
class TiledRoadMapLayer { constructor(options) { this.options = options ? options : {}; this.urls = [ "https://g1.cloudgis.vn/gservices/rest/maps/roadmap/tile/{z}/{x}/{y}.png", "https://g2.cloudgis.vn/gservices/rest/maps/roadmap/tile/{z}/{x}/{y}.png", "https://g3.cloudgis.vn/gservices/rest/maps/roadmap/tile/{z}/{x}/{y}.png", "https://g4.cloudgis.vn/gservices/rest/maps/roadmap/tile/{z}/{x}/{y}.png" ]; this.TileLayer = new ol.ekmap.TileLayer({ urls: this.urls, id: this.options.id, name: this.options.name != undefined ? this.options.name : 'Road Map', visible: this.options.visible != undefined ? this.options.visible : true, token: this.options.token, image: 'https://g3.cloudgis.vn/gservices/rest/maps/roadmap/tile/5/25/14.png?apikey=1-B27W7NTVd63eQdYAqOuEx8o3qTxDETo9' }) } /** * @function ol.ekmap.TiledRoadMapLayer.prototype.addTo * @description Adds the layer to the given map or layer group. * @param {ol.Map} map - Adds the layer to the given map or layer group. * @returns this */ addTo(map) { return this.TileLayer.addTo(map); } }
JavaScript
class BusinessRegistrationNumber { /** * Constructs a new <code>BusinessRegistrationNumber</code>. * @alias module:model/BusinessRegistrationNumber */ constructor() { BusinessRegistrationNumber.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>BusinessRegistrationNumber</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/BusinessRegistrationNumber} obj Optional instance to populate. * @return {module:model/BusinessRegistrationNumber} The populated <code>BusinessRegistrationNumber</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new BusinessRegistrationNumber(); if (data.hasOwnProperty('Name')) { obj['Name'] = ApiClient.convertToType(data['Name'], 'String'); } if (data.hasOwnProperty('Description')) { obj['Description'] = ApiClient.convertToType(data['Description'], 'String'); } if (data.hasOwnProperty('Country')) { obj['Country'] = ApiClient.convertToType(data['Country'], 'String'); } if (data.hasOwnProperty('Jurisdiction')) { obj['Jurisdiction'] = ApiClient.convertToType(data['Jurisdiction'], 'String'); } if (data.hasOwnProperty('Supported')) { obj['Supported'] = ApiClient.convertToType(data['Supported'], 'Boolean'); } if (data.hasOwnProperty('Type')) { obj['Type'] = ApiClient.convertToType(data['Type'], 'String'); } if (data.hasOwnProperty('Masks')) { obj['Masks'] = ApiClient.convertToType(data['Masks'], [BusinessRegistrationNumberMask]); } } return obj; } }
JavaScript
class GodRaysMaterial extends ShaderMaterial { /** * Constructs a new god rays material. * * @param {Vector2} lightPosition - The light position in screen space. */ constructor(lightPosition) { super({ type: "GodRaysMaterial", defines: { SAMPLES_INT: "60", SAMPLES_FLOAT: "60.0" }, uniforms: { inputBuffer: new Uniform(null), lightPosition: new Uniform(lightPosition), density: new Uniform(1.0), decay: new Uniform(1.0), weight: new Uniform(1.0), exposure: new Uniform(1.0), clampMax: new Uniform(1.0) }, fragmentShader, vertexShader, blending: NoBlending, depthWrite: false, depthTest: false }); /** @ignore */ this.toneMapped = false; } /** * The amount of samples per pixel. * * @type {Number} */ get samples() { return Number(this.defines.SAMPLES_INT); } /** * Sets the amount of samples per pixel. * * @type {Number} */ set samples(value) { const s = Math.floor(value); this.defines.SAMPLES_INT = s.toFixed(0); this.defines.SAMPLES_FLOAT = s.toFixed(1); this.needsUpdate = true; } }
JavaScript
class SeedInput extends React.PureComponent { static propTypes = { /** Current seed value */ seed: PropTypes.array.isRequired, /** Seed input label */ label: PropTypes.string.isRequired, /** Should input focus when changed to true */ focus: PropTypes.bool, /** Camera modal close label */ closeLabel: PropTypes.string.isRequired, /** Seed change event function * @param {array} value - Current seed value */ onChange: PropTypes.func.isRequired, /** @ignore */ setAdditionalAccountInfo: PropTypes.func.isRequired, /** Should the onboarding name be updated to imported SeedVault account name */ updateImportName: PropTypes.bool, /** Create a notification message * @param {string} type - notification type - success, error * @param {string} title - notification title * @param {string} text - notification explanation * @ignore */ generateAlert: PropTypes.func.isRequired, /** Translation helper * @param {string} translationString - locale string identifier to be translated * @ignore */ t: PropTypes.func.isRequired, }; state = { showScanner: false, importBuffer: null, hidden: true, cursor: 0, accounts: [], accountIndex: -1, }; componentDidMount() { if (this.props.focus) { this.input.focus(); } } componentWillReceiveProps(nextProps) { if (!this.props.focus && nextProps.focus) { this.input.focus(); } } componentDidUpdate() { if (this.input && this.props.seed && this.props.seed.length >= this.state.cursor) { try { const range = document.createRange(); const sel = window.getSelection(); range.setStart(this.input, this.state.cursor); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); this.input.scrollLeft = range.startOffset * 10; } catch (error) {} } } onScanEvent = (input) => { if (input && input.match(VALID_SEED_REGEX) && input.length === MAX_SEED_LENGTH) { this.setState(() => ({ showScanner: false, })); const seed = input.split('').map((char) => charToByte(char)); Electron.garbageCollect(); this.props.onChange(seed); } }; onPaste = (e) => { e.preventDefault(); }; onDrop = async (buffer) => { if (!buffer) { return this.props.generateAlert( 'error', 'Error opening keystore file', 'There was an error opening keystore file', ); } this.setState({ importBuffer: buffer, }); }; /** * Set valid length drag&drop seed to state * @param {array} seed - Target seed byte array */ onTextDrop = (seed) => { if (seed.length === MAX_SEED_LENGTH) { this.props.onChange(seed); } Electron.garbageCollect(); }; getCursor = (element) => { const range = document.getSelection().getRangeAt(0); const preCaretRange = range.cloneRange(); preCaretRange.selectNodeContents(element); preCaretRange.setEnd(range.endContainer, range.endOffset); const start = preCaretRange.toString().length; const postCaretRange = range.cloneRange(); postCaretRange.selectNodeContents(element); postCaretRange.setEnd(range.startContainer, range.startOffset); const end = postCaretRange.toString().length; return [start, end]; }; setVisibility = () => { this.setState({ hidden: !this.state.hidden, }); }; closeScanner = () => { this.setState(() => ({ showScanner: false, })); }; openScanner = () => { this.setState(() => ({ showScanner: true, })); }; decryptFile = async (password) => { const { generateAlert, setAdditionalAccountInfo, updateImportName, t } = this.props; try { let accounts = await Electron.importSeed(this.state.importBuffer, password); this.setState({ importBuffer: null, }); if (!accounts || !accounts.length) { throw Error('SeedNotFound'); } accounts = accounts.filter((account) => { return account.seed.length === MAX_SEED_LENGTH; }); if (!accounts.length) { throw Error('SeedNotFound'); } else if (accounts.length === 1) { this.props.onChange(accounts[0].seed); if (updateImportName && accounts[0].title.length < MAX_ACC_LENGTH) { setAdditionalAccountInfo({ addingAdditionalAccount: true, additionalAccountName: accounts[0].title, additionalAccountType: 'keychain', }); } } else { this.setState({ accounts: accounts, accountIndex: -1, }); } Electron.garbageCollect(); } catch (error) { if (error.code === 'InvalidKey') { generateAlert('error', t('unrecognisedPassword'), t('unrecognisedPasswordExplanation')); } else if (error.message === 'SeedNotFound') { generateAlert('error', t('seedVault:noSeedFound'), t('seedVault:noSeedFoundExplanation')); } else { generateAlert('error', t('seedVault:seedFileError'), t('seedVault:seedFileErrorExplanation')); } } }; chooseSeed = (e) => { e.preventDefault(); const account = this.state.accounts[this.state.accountIndex]; this.props.onChange(account.seed); if (this.props.updateImportName && account.title.length < MAX_ACC_LENGTH) { this.props.setAdditionalAccountInfo({ addingAdditionalAccount: true, additionalAccountName: account.title, additionalAccountType: 'keychain', }); } this.setState({ accounts: [], accountIndex: -1, }); }; keyDown = (e) => { const key = e.key; if (['ArrowRight', 'ArrowLeft', 'ArrowUp', 'ArrowDown'].indexOf(key) > -1) { return true; } const byte = charToByte(key.toUpperCase()); if (!e.metaKey && !e.ctrlKey) { e.preventDefault(); if (byte > -1 || key === 'Backspace') { const cursor = this.getCursor(this.input); const seed = this.props.seed.slice(0); let cursorPos = cursor[0] <= cursor[1] ? cursor[0] + 1 : cursor[1] + 1; if (key === 'Backspace') { if (this.props.seed.length > 0) { if (cursor[0] === cursor[1] && cursor[0] > 0) { seed.splice(cursor[0] - 1, 1); cursorPos = Math.max(cursor[0] - 1, 0); } else { seed.splice(Math.min(...cursor), Math.abs(cursor[0] - cursor[1])); cursorPos = Math.min(...cursor); } } } else { seed.splice(Math.min(...cursor), Math.abs(cursor[0] - cursor[1]), byte); } if (seed.length > MAX_SEED_LENGTH) { return; } this.setState({ cursor: seed.length ? cursorPos : 0, }); this.props.onChange(seed); } } }; render() { const { seed, label, closeLabel, t } = this.props; const { importBuffer, accounts, accountIndex, showScanner, hidden } = this.state; const checkSum = seed.length < MAX_SEED_LENGTH ? '< 81' : Electron.getChecksum(seed); return ( <div className={classNames(css.input, css.seed)}> <fieldset> <a className={hidden ? css.strike : null} onClick={this.setVisibility}> <Icon icon="eye" size={16} /> </a> <a className={css.right} onClick={this.openScanner}> <Icon icon="camera" size={16} /> </a> <div className={css.editable}> <div ref={(input) => { this.input = input; }} onKeyDown={this.keyDown} onPaste={this.onPaste} contentEditable suppressContentEditableWarning > {seed.map((byte, index) => { const letter = byteToChar(byte); return ( <span className={css.letter} data-letter={hidden ? '•' : letter} key={`${index}-${byte}`} > &nbsp; </span> ); })} </div> </div> <small>{label}</small> </fieldset> <Dropzone onDrop={this.onDrop} onTextDrop={this.onTextDrop} /> {seed.length ? <span className={css.info}>{checkSum}</span> : null} {showScanner && ( <Modal isOpen onClose={this.closeScanner}> <div className={css.qrScanner}> <QrReader delay={350} onScan={this.onScanEvent} onError={() => {}} /> <Button type="button" onClick={this.closeScanner} variant="secondary"> {closeLabel} </Button> </div> </Modal> )} {importBuffer && ( <Password content={{ title: t('enterPassword'), message: t('seedVault:enterPasswordExplanation'), confirm: t('seedVault:importSeedVault'), }} isOpen onClose={() => this.setState({ importBuffer: null })} onSubmit={(password) => this.decryptFile(password)} /> )} {accounts.length > 0 && ( <Modal isOpen onClose={() => this.setState({ accounts: [] })} onSubmit={(password) => this.decryptFile(password)} > <h1>Choose seed</h1> <p>Your SeedFile contains multiple valid seeds, please choose which seed to import</p> <Select value={accountIndex > -1 ? accounts[accountIndex].title : ''} label={t('addAdditionalSeed:accountName')} onChange={(value) => this.setState({ accountIndex: value })} options={accounts.map((account, index) => { return { value: index, label: account.title }; })} /> <footer> <Button onClick={() => this.setState({ accounts: [] })} variant="dark"> {t('cancel')} </Button> <Button disabled={accountIndex < 0} onClick={this.chooseSeed} variant="primary"> {t('seedVault:importSeedVault')} </Button> </footer> </Modal> )} </div> ); } }
JavaScript
class StoreLoader extends LoaderBase { /** * Creates a new instance of the store loader. * @param {ServiceLocator} locator The service locator for resolving dependencies. */ constructor(locator) { var storeTransforms; try { storeTransforms = locator.resolveAll('storeTransform'); } catch (e) { storeTransforms = []; } super(locator, storeTransforms); /** * Current event bus. * @type {EventEmitter} * @private */ this._eventBus = locator.resolve('eventBus'); /** * Current store finder. * @type {StoreFinder} * @private */ this._storeFinder = locator.resolve('storeFinder'); /** * Current release flag. * @type {boolean} * @private */ this._isRelease = Boolean(locator.resolve('config').isRelease); /** * Current map of loaded stores by their names. * @type {Object} * @private */ this._loadedStores = null; } /** * Loads all stores into the memory. * @returns {Promise<Object>} The promise for a map of the loaded stores. */ load() { if (this._loadedStores) { return Promise.resolve(this._loadedStores); } const result = Object.create(null); return this._storeFinder.find() .then(details => { const storePromises = Object.keys(details) .map(storeName => this._getStore(details[storeName])); return Promise.all(storePromises); }) .then(stores => { stores.forEach(store => { if (!store || typeof (store) !== 'object') { return; } result[store.name] = store; }); this._loadedStores = result; if (!this._isRelease) { this._eventBus.emit('info', 'Watching stores for changes...'); this._storeFinder.watch(); this._handleChanges(); } this._eventBus.emit('allStoresLoaded', result); return this._loadedStores; }); } /** * Gets current map of stores by their names. * @returns {Object} The map of stores by their names. */ getStoresByNames() { return this._loadedStores || Object.create(null); } /** * Gets a store object by the found store details. * @param {Object} storeDetails The found details. * @returns {Object} The store object. * @private */ _getStore(storeDetails) { var constructor; try { constructor = require(requireHelper.getAbsoluteRequirePath(storeDetails.path)); } catch (e) { this._eventBus.emit('error', e); return Promise.resolve(null); } if (typeof (constructor) !== 'function') { const errorMessage = `Store's file ${storeDetails.path} should export a constructor function or a class`; this._eventBus.emit('error', new Error(errorMessage)); return Promise.resolve(null); } const result = Object.create(storeDetails); result.constructor = constructor; return this._applyTransforms(result) .then(transformed => { if (!transformed) { throw new Error(`Transformation for the "${storeDetails.name}" store returned a bad result`); } this._eventBus.emit('storeLoaded', transformed); return transformed; }) .catch(error => { this._eventBus.emit('error', error); return null; }); } /** * Handles changes while watching. * @private */ _handleChanges() { const loadStore = storeDetails => { this._getStore(storeDetails) .then(store => { this._loadedStores[storeDetails.name] = store; }); }; this._storeFinder .on('add', storeDetails => { this._eventBus.emit('info', `Store "${storeDetails.path}" has been added, initializing...`); requireHelper.clearCacheKey(requireHelper.getAbsoluteRequirePath(storeDetails.path)); loadStore(storeDetails); }) .on('change', storeDetails => { this._eventBus.emit('info', `Store "${storeDetails.path}" has been changed, reinitializing...`); requireHelper.clearCacheKey(requireHelper.getAbsoluteRequirePath(storeDetails.path)); loadStore(storeDetails); }) .on('unlink', storeDetails => { this._eventBus.emit('info', `Store "${storeDetails.path}" has been unlinked, removing...`); requireHelper.clearCacheKey(requireHelper.getAbsoluteRequirePath(storeDetails.path)); delete this._loadedStores[storeDetails.name]; }); } }
JavaScript
class Result { constructor(props) { this.status = props.status || null; this.code = props.code || null; this.error = props.error || null; this.data = props.data; this.message = props.message !== undefined ? props.message : null; } /** * Is result success * * @returns * * @memberOf Result */ isSuccess() { return this.status === Result.STATUS.SUCCESS; } /** * Get properties of result * * @returns {object} * * @memberOf Result */ getContext() { let result = { error: this.error, data: this.data, code: this.code, result: this, message: this.message, }; return result; } /** * Get properties if success result, or throw Error * * @returns {object} * * @memberOf Result */ getContextOrThrow() { if (this.isSuccess() || !this.error) { return this.getContext(); } else { throw this.error; } } /** * Get properties of result as array * * @param {string[]} properties array. * * @returns {string[]} * * @memberOf Result */ get(propertiesArr) { let result = { error: this.error, data: this.data, code: this.code, result: this, message: this.message, }; if (Array.isArray(propertiesArr)) { let resultArr = []; for (let property of propertiesArr) { resultArr.push(result[property]); } return resultArr; } else { return [this.error, this.data, this.code, this, this.message]; } } /** * Get properties as array if success result, or throw Error * * @param {string[]} properties array. * * @returns {string[]} * * @memberOf Result */ getOrThrow(propertiesArr) { if (this.isSuccess() || !this.error) { return this.get(propertiesArr); } else { throw this.error; } } /** * For express * * @param {object} res response object * @param {string} type The attribute being used for represent as response body * * @memberOf Result */ sendResponse(res, type) { if (this.isSuccess()) { let code = this.code || 200; let responseBody = '' if (type) { responseBody = this[type]; } else { responseBody = this.data !== undefined ? this.data : (this.message || http.STATUS_CODES[code]); } res.status(code).send(responseBody); } else { let code = this.code || 500; let responseBody = '' if (type) { responseBody = this[type]; } else { responseBody = this.message || http.STATUS_CODES[code]; } res.status(code).send(responseBody); } } /** * Helper static function for creating new success result object * * @static * @param {object} props * @returns * * @memberOf Result */ static newSuccess(props) { return new Result(Object.assign({}, props, { status: Result.SUCCESS, message: props.message || http.STATUS_CODES[props.code] })); } /** * Helper static function for creating new fail result object * * @static * @param {object} props * @returns * * @memberOf Result */ static newFail(props) { return new Result(Object.assign({}, props, { status: Result.FAIL, error: props.error || new Exception(props.code, props.message || http.STATUS_CODES[props.code]), message: props.message || http.STATUS_CODES[props.code] })); } }
JavaScript
class Thermostat { constructor(Dt = 2, DtCool = 1.5 , DtHeat = 1) { this._Dt = Dt; this._DtCool = DtCool; this._DtHeat = DtHeat; this.idle_process = this.idle_process.bind(this); this.cooling_process = this.cooling_process.bind(this); this.heating_process = this.heating_process.bind(this); } // Determines if thermostat in the comfortable/idle state determines if it either // too hot, too cold, or within the comfort range. idle_process(currTemp, setTemp) { var highThreshold = setTemp + this._Dt + this._DtCool; var lowThreshold = setTemp - this._Dt - this._DtHeat; if (currTemp > highThreshold) { console.log("Thermostat: Surroundings too hot.") return "too_hot"; } else if (currTemp < lowThreshold) { console.log("Thermostat: Surroundings too cold.") return "too_cold"; } else { return "continue"; } } // Determines if thermostat in cooling state determines if it is cold enough to be // back within the comfort range. cooling_process(currTemp, setTemp) { var coolEnough_thresholdToStop = setTemp + (this._Dt - this._DtCool); if (currTemp < coolEnough_thresholdToStop) { console.log("Thermostat: Surroundings cold enough now.") return "cold_enough" } else { return "continue" } } // Determines if thermostat in heating state determines if it is hot enough to be // back within the comfort range. heating_process(currTemp, setTemp) { var hotEnough_thresholdToStop = setTemp - (this._Dt - this._DtHeat); if (currTemp > hotEnough_thresholdToStop) { console.log("Thermostat: Surroundings hot enough now.") return "hot_enough" } else { return "continue" } } }
JavaScript
class MediaTask { /** * @param {string} name * @param {!Object=} options */ constructor(name, options = {}) { /** @private @const {string} */ this.name_ = name; const deferred = new Deferred(); /** @private @const {!Promise} */ this.completionPromise_ = deferred.promise; /** @protected @const {!Object} */ this.options = options; /** @private {?function()} */ this.resolve_ = deferred.resolve; /** @private {?function(*)} */ this.reject_ = deferred.reject; } /** * @return {string} The name of this task. */ getName() { return this.name_; } /** * @return {!Promise<*>} A promise that is resolved when the task has * completed execution. */ whenComplete() { return this.completionPromise_; } /** * @param {!HTMLMediaElement} mediaEl The element on which this task should be * executed. * @return {!Promise} A promise that is resolved when the task has completed * execution. */ execute(mediaEl) { return this.executeInternal(mediaEl) .then(this.resolve_, this.reject_); } /** * @param {!HTMLMediaElement} unusedMediaEl The element on which this task * should be executed. * @protected */ executeInternal(unusedMediaEl) { return Promise.resolve(); } /** * @return {boolean} true, if this task must be executed synchronously, e.g. * if it requires a user gesture. */ requiresSynchronousExecution() { return false; } /** * @param {*} reason The reason for failing the task. * @protected */ failTask(reason) { this.reject_(reason); } }
JavaScript
class PlayTask extends MediaTask { /** * @public */ constructor() { super('play'); } /** @override */ executeInternal(mediaEl) { if (!mediaEl.paused) { // We do not want to invoke play() if the media element is already // playing, as this can interrupt playback in some browsers. return Promise.resolve(); } // The play() invocation is wrapped in a Promise.resolve(...) due to the // fact that some browsers return a promise from media elements' play() // function, while others return a boolean. return tryResolve(() => mediaEl.play()); } }
JavaScript
class PauseTask extends MediaTask { /** * @public */ constructor() { super('pause'); } /** @override */ executeInternal(mediaEl) { mediaEl.pause(); return Promise.resolve(); } }
JavaScript
class UnmuteTask extends MediaTask { /** * @public */ constructor() { super('unmute'); } /** @override */ executeInternal(mediaEl) { mediaEl.muted = false; mediaEl.removeAttribute('muted'); return Promise.resolve(); } }
JavaScript
class MuteTask extends MediaTask { /** * @public */ constructor() { super('mute'); } /** @override */ executeInternal(mediaEl) { mediaEl.muted = true; mediaEl.setAttribute('muted', ''); return Promise.resolve(); } }
JavaScript
class SetCurrentTimeTask extends MediaTask { /** * @param {!Object=} options */ constructor(options = {currentTime: 0}) { super('setCurrentTime', options); } /** @override */ executeInternal(mediaEl) { mediaEl.currentTime = this.options.currentTime; return Promise.resolve(); } }
JavaScript
class LoadTask extends MediaTask { /** * @public */ constructor() { super('load'); } /** @override */ executeInternal(mediaEl) { mediaEl.load(); return Promise.resolve(); } }
JavaScript
class BlessTask extends MediaTask { /** * @public */ constructor() { super('bless'); } /** @override */ requiresSynchronousExecution() { return true; } /** @override */ executeInternal(mediaEl) { const isMuted = mediaEl.muted; mediaEl.muted = false; if (isMuted) { mediaEl.muted = true; } return Promise.resolve(); } }
JavaScript
class UpdateSourcesTask extends MediaTask { /** * @param {!Sources} newSources The sources to which the media element should * be updated. */ constructor(newSources) { super('update-src'); /** @private @const {!Sources} */ this.newSources_ = newSources; } /** @override */ executeInternal(mediaEl) { Sources.removeFrom(mediaEl); this.newSources_.applyToElement(mediaEl); return Promise.resolve(); } }
JavaScript
class SwapIntoDomTask extends MediaTask { /** * @param {!Element} placeholderEl The element to be replaced by the media * element on which this task is executed. */ constructor(placeholderEl) { super('swap-into-dom'); /** @private @const {!Element} */ this.placeholderEl_ = placeholderEl; } /** @override */ executeInternal(mediaEl) { if (!isConnectedNode(this.placeholderEl_)) { this.failTask('Cannot swap media for element that is not in DOM.'); return Promise.resolve(); } copyCssClasses(this.placeholderEl_, mediaEl); copyAttributes(this.placeholderEl_, mediaEl); this.placeholderEl_.parentElement .replaceChild(mediaEl, this.placeholderEl_); return Promise.resolve(); } }
JavaScript
class SwapOutOfDomTask extends MediaTask { /** * @param {!Element} placeholderEl The element to replace the media element on * which this task is executed. */ constructor(placeholderEl) { super('swap-out-of-dom'); /** @private @const {!Element} */ this.placeholderEl_ = placeholderEl; } /** @override */ executeInternal(mediaEl) { copyCssClasses(mediaEl, this.placeholderEl_); copyAttributes(mediaEl, this.placeholderEl_); mediaEl.parentElement.replaceChild(this.placeholderEl_, mediaEl); return Promise.resolve(); } }
JavaScript
class EventQueue { /** * @description constructor. * * @param none. * * @return none. */ constructor() { this.queue = []; } /** * @description adds an event to this event queue add the appropriate position. * * @param none. * * @return none. */ push(newEvent) { /** * Down the line it may be best to create event priorities (i.e. event.priority). * As such event comparision would start from priority and cascade down to date. */ if (newEvent.type === "END_PLAY_EVENT") { this.queue.splice(0, 0, newEvent); } else { if (this.queue.length == 0 || this.queue[this.queue.length - 1].date.isLessOrEqualTo(newEvent.date)) { this.queue.push(newEvent); } else { for (var i = 0; i < this.queue.length; i++) { /** * If the new event is set to be fired sooner than the event at this index, * then push the current event at this index further into the queue and insert * the new event at this position. */ if (newEvent.date.isLessOrEqualTo(this.queue[i].date)) { this.queue.splice(i, 0, newEvent); break; } } } } } /** * @description check whether this queue has events. * * @param none. * * @return true or false. */ hasEvents() { /** * Check that the queue is not empty. */ return (this.queue.length > 0); } /** * @description returns the first element in the queue. * Should the queue be queue be empty it returns null. * * @param none. * * @return event. */ peek() { return (this.hasEvents()) ? this.queue[0] : null; } /** * @description remove the event at the specified index. * * @param none. * * @return none. */ remove(index) { this.queue.splice(index, 1); } /** * @description resets the internal queue to an empty string. * * @param none. * * @return none. */ reset() { this.queue = []; } }
JavaScript
class SeasonDb { // # ## # ## // # # # # # # // ### ## ### # # # ### ### ## ### ### # ## ### ### ## ### // # # # ## # # # # # # # # # ## # # # # # ## # # ## # # # # // ## ## # # # # # # # ## # # # # # ## # ## ## # # # # // # ## ## ## ### # # ## # # ## ## ## # # ### ## # # // ### /** * Gets the current season number. * @return {Promise<number>} A promise that returns the current season number. */ static async getCurrentSeason() { /** @type {SeasonDbTypes.GetCurrentSeasonRecordset} */ const data = await db.query(/* sql */` SELECT MAX(Season) Season FROM tblSeason `); return data && data.recordsets && data.recordsets[0] && data.recordsets[0][0] && data.recordsets[0][0].Season || void 0; } // # ## # # # // # # # ## # # // ### ## ### # ## ### ### ## ### ## # # # # # ### ## ### ### // # # # ## # # # ## # # ## # # # # # ## # # #### # # # ## # # ## // ## ## # # # ## # ## ## # # # # # ## # # # # # # ## # ## // # ## ## ## ## # # ### ## # # # # ### # # ### ## # ### // ### /** * Gets the list of season numbers. * @returns {Promise<number[]>} A promise that resolves with the list of available seasons. */ static async getSeasonNumbers() { const key = `${settings.redisPrefix}:db:season:getSeasonNumbers`; /** @type {number[]} */ let cache; if (!settings.disableRedis) { cache = await Cache.get(key); } if (cache) { return cache; } /** @type {SeasonDbTypes.GetSeasonNumbersRecordset} */ const data = await db.query(/* sql */` SELECT Season FROM tblSeason WHERE DateStart < GETUTCDATE() ORDER BY Season SELECT TOP 1 DateEnd FROM tblSeason WHERE DateEnd > GETUTCDATE() `); cache = data && data.recordsets && data.recordsets[0] && data.recordsets[0].map((row) => row.Season) || []; if (!settings.disableRedis) { await Cache.add(key, cache, data && data.recordsets && data.recordsets[1] && data.recordsets[1][0] && data.recordsets[1][0].DateEnd || void 0, [`${settings.redisPrefix}:invalidate:season:added`]); } return cache; } }
JavaScript
class Store { constructor(name, inventory = []) { this.name = name; this.inventory = inventory; logger.log(`New Store: ${name} has ${inventory.length} items in stock.`); } }
JavaScript
class View extends React.Component { static propTypes = { children: PropTypes.node, dispatch: PropTypes.func, isAnyModalOpen: PropTypes.bool, name: PropTypes.string }; /** * Logs the display of the view. * * @inheritdoc */ componentDidMount() { logger.log('View mounted', { name: this.props.name }); this.props.dispatch(viewDisplayed(this.props.name)); } /** * Implements React's {@link Component#render()}. * * @inheritdoc */ render() { const className = `view ${this.props.isAnyModalOpen ? 'modal-open' : ''}`; return ( <div className = { className } data-qa-id = { `${this.props.name}-view` }> { /** * The div with view-content-container will allow for * overflow while the div with view-content-center allows * for centering whatever the children might be. This is * done for cross browser support with safari and android * browsers. */ } <div className = 'view-content-container'> <div className = 'view-content-center'> { this.props.children } </div> </div> </div> ); } }
JavaScript
class Eye extends Document { constructor() { super('eyes'); this.color = String; } }
JavaScript
class Eye extends Document { constructor() { super('eyes'); this.color = String; } }
JavaScript
class User extends Document { constructor() { super('user'); this.firstName = String; this.lastName = String; } set fullName(name) { var split = name.split(' '); this.firstName = split[0]; this.lastName = split[1]; } get fullName() { return this.firstName + ' ' + this.lastName; } }
JavaScript
class ZoomBox { constructor(template, parentCodePoints, ordinal, childIndex) { this._template = template; this._messageCodePoints = parentCodePoints.slice(); this._ordinal = ordinal; this._childIndex = childIndex; if (template.codePoint !== null) { this._messageCodePoints.push(template.codePoint); } this._cssClass = ( template.cssClass === null ? template.palette.sequence_CSS(ordinal, childIndex) : template.cssClass); this._message = ( this.messageCodePoints === undefined ? undefined : String.fromCodePoint(...this.messageCodePoints)); this._childBoxes = undefined; this._controllerData = undefined; this._left = undefined; this._width = undefined; this._middle = undefined; this._height = undefined; this._trimmedIndex = undefined; this._trimmedParent = null; this._viewer = null; } instantiate_child_boxes(configure) { if (this._childBoxes === undefined) { this._childBoxes = this._template.childTemplates.map( (template, index) => new ZoomBox( template, this._messageCodePoints, template.codePoint === null ? this._ordinal : this._ordinal + 1, index ) ); this._childBoxes.forEach(childBox => { configure(childBox); if (childBox.template.cssClass !== null) { childBox.instantiate_child_boxes(configure); } }); return true; } return false; } get cssClass() {return this._cssClass;} get text() {return this._template.displayText; } //this._text;} get template() {return this._template;} get trimmedIndex() {return this._trimmedIndex;} set trimmedIndex(trimmedIndex) {this._trimmedIndex = trimmedIndex;} get trimmedParent() {return this._trimmedParent;} set trimmedParent(trimmedParent) {this._trimmedParent = trimmedParent;} get messageCodePoints() {return this._messageCodePoints;} get message() {return this._message;} get childBoxes() {return this._childBoxes;} clear_child_boxes() {this._childBoxes = undefined;} get controllerData() {return this._controllerData;} set controllerData(controllerData) {this._controllerData = controllerData;} get viewer() {return this._viewer;} set viewer(viewer) {this._viewer = viewer;} // Erase this box from the view, if it has ever been drawn. Note that child // boxes are left in place. erase() { // console.log(`erase() "${this.cssClass} "${this.message}"`); if (this.viewer !== null) { // Next line cascades to erase all child boxes. this.viewer.erase(); } this._left = undefined; } // Principal properties that define the location and size of the box. The // update() method is always a no-op in the current version but could be // changed later. get left() { return this._left; } set left(left) { this._left = left; this.update(); } get width() { return this._width; } set width(width) { this._width = width; this.update(); } get middle() { return this._middle; } set middle(middle) { this._middle = middle; this.update(); } get height() { return this._height; } set height(height) { this._height = height; this.update(); } // Computed properties for convenience. get top() { if (this.middle === undefined || this.height === undefined) { return undefined; } return this.middle - (this.height / 2); } get bottom() { if (this.middle === undefined || this.height === undefined) { return undefined; } return this.middle + (this.height / 2); } get right() { if (this.left === undefined || this.width === undefined) { return undefined; } return this.left + this.width; } // Special setters that avoid individual updates. set_dimensions(left, width, middle, height) { if (left !== undefined) { this._left = left; } if (width !== undefined) { this._width = width; } if (middle !== undefined) { this._middle = middle; } if (height !== undefined) { this._height = height; } this.update(); } update() { } dimension_undefined() { return ( this.left === undefined || this.width === undefined || this.middle === undefined || this.height === undefined ); } /* Returns the leafiest child of this box that holds the specified point, or * null if this box doesn't hold the point. If a `path` is passed, it will * be populated with a list of the child index values used to reach the * holder, and a -1 terminator. */ holder(rawX, rawY, path) { // if (!this.spawned) { return null; } if (!this.holds(rawX, rawY)) { // This box doesn't hold the point, so neither will any of its child // boxes. The holds() method can return undefined, which this method // treats as `false`. return null; } if (path === undefined) { // If the caller didn't specify a path, create a path here. It gets // discarded on return but makes the code easier to read. path = []; } // This box holds the point; check its child boxes. // The child array isn't sparse now, although it was in earlier // versions. for(let index = this.childBoxes.length - 1; index >= 0; index--) { const child = this.childBoxes[index]; // Recursive call. const holder = child.holder(rawX, rawY, path); // If any child dimension is undefined, holder() will return null. if (holder === null) { continue; } // If the code reaches here then a child holds the point. Finish // here. // The recursive call to holder() will have push'd the -1 // terminator. path.unshift(index); return holder; } // If the code reaches here, this box holds the point, and none of its // child boxes do. Push the terminator and return. path.push(-1); return this; } holds(rawX, rawY) { if (this.dimension_undefined()) { return undefined; } // Box top and bottom are measured from the top of the window. This // means that negative numbers represent points above the origin. const negativeY = 0 - rawY; return ( rawX >= this.left && rawX <= this.right && negativeY >= this.top && negativeY <= this.bottom ); } // If a child of this box should now be the new root box, then set it up and // return the new root box. Otherwise return null. child_root(limits) { const rootIndex = this._trimmed_root_index(limits); if (rootIndex === -1) { return null; } // If the code reaches this point then there is a new root box. This box // is about to be erased. The new root is a child of this box and would // also get erased, so save it here and replace it in the child box // array with a dummy. const trimmedRoot = this.childBoxes[rootIndex]; this.childBoxes[rootIndex] = {erase:() => { return; }}; // Later, the user might backspace and this box would need to be // inserted back, as a parent of the new root. Set a reference and some // values into the new root to make that possible. trimmedRoot.trimmedParent = this; trimmedRoot.trimmedIndex = rootIndex; return trimmedRoot; } _trimmed_root_index(limits) { if (this.left > limits.left) { // This box is still inside the window; don't trim. return -1; } // If there is exactly one child box with defined dimensions, it could // be the trimmed root. A child box will have undefined dimensions if it // wasn't ever rendered, or if it went off limits and was erased. let candidate; for(let index = this.childBoxes.length - 1; index >= 0; index--) { if (this.childBoxes[index].dimension_undefined()) { continue; } if (candidate === undefined) { candidate = index; } else { // If the code reaches this point then two candidates have been // found. The condition for trimming is that there is exactly // one candidate, so getting here means we can't trim. return -1; } } if (candidate === undefined) { // Zero child boxes with defined dimensions; can't trim. return -1; } if (this.childBoxes[candidate].left > limits.left) { // The candidate box isn't at the edge of the window; don't trim. return -1; } return candidate; } // If the trimmed parent of this box should now be the new root box then set // it up and return the new root box. Otherwise return null. parent_root(limits) { const parent = this.trimmedParent; // If there isn't a trimmed parent, root box shouldn't change. if (parent === null) { return null; } // If there isn't any space around this box, root box shouldn't change. // It only matters if there is no space above if this isn't the first // child box. Vice versa, it only matters if there is no space below if // this isn't the last child box. if (!( this.left > limits.left || ( this.bottom < limits.bottom && this.trimmedIndex < parent.childBoxes.length - 1 ) || ( this.top > limits.top && this.trimmedIndex > 0 ) )) { return null; } // console.log( // parent.childBoxes[this.trimmedIndex], this.left > limits.left, // this.bottom < limits.bottom, this.top > limits.top); parent.childBoxes[this.trimmedIndex] = this; return parent; } }
JavaScript
class Consts { static get gitIgnoreFileName() { return '.gitignore'; } static get settingsDirName() { return 'settings'; } static get authFileName() { return 'auth.info'; } static get gitIgnoreFileContent() { return Consts.authFileName; } static get authFileLocalPath() { return path.join(Consts.settingsDirName, Consts.authFileName); } static get configFileName() { return 'imp.config'; } static get configFileLocalPath() { return path.join(Consts.settingsDirName, Consts.configFileName); } static get srcDirName() { return 'src'; } static get agentSourceFileName() { return 'agent.nut'; } static get deviceSourceFileName() { return 'device.nut'; } static get agentSourceHeader() { return '// This is agent code'; } static get deviceSourceHeader() { return '// This is device code'; } }
JavaScript
class Path { static getPWD() { const folders = vscode.workspace.workspaceFolders; let folder; if (!folders) { return undefined; } if (folders.length === 1) { [folder] = folders; } else { vscode.window.showErrorMessage(User.ERRORS.WORKSPACE_MULTIROOT); return undefined; } return folder.uri.fsPath; } static getConfig() { return path.join(Path.getPWD(), Consts.configFileLocalPath); } static getAuth() { return path.join(Path.getPWD(), Consts.authFileLocalPath); } static getDefaultSrcDir() { return path.join(Path.getPWD(), Consts.srcDirName); } }
JavaScript
class Data { /* * The input function argument should have the next structure: * { accessToken: object returned from ImpCentralApi.login(), * cloudURL: string with actual cloud url } */ static storeAuthInfo(auth) { return new Promise((resolve, reject) => { const authInfo = auth; authInfo.builderSettings = { github_user: null, github_token: null }; if (!isWorkspaceFolderOpened()) { reject(User.ERRORS.WORKSPACE_FOLDER_SELECT); return; } const settingsDirPath = path.join(Path.getPWD(), Consts.settingsDirName); if (!fs.existsSync(settingsDirPath)) { fs.mkdirSync(settingsDirPath); } const authFile = path.join(Path.getPWD(), Consts.authFileLocalPath); try { if (fs.existsSync(authFile)) { /* * Do not overwrite github creds, in case of relogin. */ const oldAuthInfo = JSON.parse(fs.readFileSync(authFile).toString()); authInfo.builderSettings = oldAuthInfo.builderSettings; } } catch (err) { vscode.window.showWarningMessage(`Cannot read old auth info ${err}`); } const gitIgnoreFile = path.join(Path.getPWD(), Consts.gitIgnoreFileName); try { fs.writeFileSync(authFile, JSON.stringify(authInfo, null, 2)); if (!fs.existsSync(gitIgnoreFile)) { fs.writeFileSync(gitIgnoreFile, Consts.gitIgnoreFileContent); } else { /* * Check if auth.info is added to it. */ const gitIgnoreContent = fs.readFileSync(gitIgnoreFile); const gitIgnoreItem = Consts.gitIgnoreFileContent; if (gitIgnoreContent.includes(`${gitIgnoreItem}\n`) === false) { fs.writeFileSync(gitIgnoreFile, `${gitIgnoreItem}\n${gitIgnoreContent}`); } } resolve(); } catch (err) { reject(err); } }); } static isAuthInfoValid(auth) { if (auth.accessToken === undefined) { return false; } if (auth.accessToken.access_token === undefined) { return false; } if (auth.builderSettings === undefined) { return false; } if (auth.builderSettings.github_user === undefined) { return false; } if (auth.builderSettings.github_token === undefined) { return false; } return true; } static getAuthInfoSync() { const authFile = Path.getAuth(); return JSON.parse(fs.readFileSync(authFile).toString()); } static getAuthInfo() { return new Promise((resolve, reject) => { if (!isWorkspaceFolderOpened()) { reject(new Error(User.ERRORS.WORKSPACE_FOLDER_SELECT)); return; } let auth; try { auth = Data.getAuthInfoSync(); } catch (err) { reject(new User.GetAuthFileError(err)); return; } if (!Data.isAuthInfoValid(auth)) { reject(new Error(User.ERRORS.AUTH_FILE_ERROR)); return; } resolve(auth); }); } static getWorkspaceInfoFilePath() { return path.join(Path.getPWD(), Consts.configFileLocalPath); } static storeWorkspaceInfo(info) { return new Promise((resolve, reject) => { if (!isWorkspaceFolderOpened()) { reject(User.ERRORS.WORKSPACE_FOLDER_SELECT); return; } const settingsDirPath = path.join(Path.getPWD(), Consts.settingsDirName); if (!fs.existsSync(settingsDirPath)) { fs.mkdirSync(settingsDirPath); } try { fs.writeFileSync(Data.getWorkspaceInfoFilePath(), JSON.stringify(info, null, 2)); resolve(); } catch (err) { reject(err); } }); } static getWorkspaceInfoSync() { const cfgFile = Data.getWorkspaceInfoFilePath(); return JSON.parse(fs.readFileSync(cfgFile).toString()); } static getWorkspaceInfo() { return new Promise((resolve, reject) => { if (!isWorkspaceFolderOpened()) { reject(new Error(User.ERRORS.WORKSPACE_FOLDER_SELECT)); return; } const cfgFile = Data.getWorkspaceInfoFilePath(); if (!fs.existsSync(cfgFile)) { reject(new Error(User.ERRORS.WORSPACE_CFG_NONE)); return; } try { const config = Data.getWorkspaceInfoSync(); if (config.deviceGroupId === undefined) { vscode.window.showTextDocument(vscode.workspace.openTextDocument(cfgFile)); reject(new Error(User.ERRORS.WORKSPACE_CFG_CORRUPTED)); return; } const agentSrc = path.join(Path.getPWD(), config.agent_code); if (!fs.existsSync(agentSrc)) { vscode.window.showTextDocument(vscode.workspace.openTextDocument(cfgFile)); reject(new Error(User.ERRORS.WORKSPACE_SRC_AGENT_NONE)); return; } const deviceSrc = path.join(Path.getPWD(), config.device_code); if (!fs.existsSync(deviceSrc)) { vscode.window.showTextDocument(vscode.workspace.openTextDocument(cfgFile)); reject(new Error(User.ERRORS.WORKSPACE_SRC_DEVICE_NONE)); return; } resolve(config); } catch (err) { reject(new Error(`${User.ERRORS.WORKSPACE_CFG_CORRUPTED}: ${err}`)); } }); } static workspaceInfoFileExist() { const cfgFile = Data.getWorkspaceInfoFilePath(); if (fs.existsSync(cfgFile)) { return true; } return false; } static getSourcesPathsSync() { const config = Data.getWorkspaceInfoSync(); return { agent_path: path.join(Path.getPWD(), config.agent_code), device_path: path.join(Path.getPWD(), config.device_code), }; } static getSources() { return new Promise((resolve, reject) => { if (!isWorkspaceFolderOpened()) { reject(User.ERRORS.WORKSPACE_FOLDER_SELECT); return; } Data.getWorkspaceInfo().then((config) => { try { const agentSourcePath = path.join(Path.getPWD(), config.agent_code); const agentSource = fs.readFileSync(agentSourcePath).toString(); const deviceSourcePath = path.join(Path.getPWD(), config.device_code); const deviceSource = fs.readFileSync(deviceSourcePath).toString(); const sources = { agent_source: agentSource, agent_path: agentSourcePath, device_source: deviceSource, device_path: deviceSourcePath, }; resolve(sources); } catch (err) { reject(err); } }, (err) => { reject(err); }); }); } }
JavaScript
class IdenticonImageBuilder { constructor(patchSize = DEFAULT_PATCH_SIZE, backgroundColor = { red: 255, green: 255, blue: 255 }) { this.patchSize = patchSize; this.backgroundColor = backgroundColor; } buildImage(avatar, random, width, height) { return __awaiter(this, void 0, void 0, function* () { const size = Math.min(width, height); const canvas = canvas_1.createCanvas(width, height); const ctx = canvas.getContext('2d'); ctx.translate((width - size) / 2, (height - size) / 2); const code = random.nextInt(4294967296); this.renderQuilt(ctx, code, size); return canvas; }); } renderQuilt(ctx, code, size) { const middleType = CENTER_PATCH_TYPES[code & 0x3]; const middleInvert = ((code >> 2) & 0x1) != 0; const cornerType = (code >> 3) & 0x0f; const cornerInvert = ((code >> 7) & 0x1) != 0; let cornerTurn = (code >> 8) & 0x3; const sideType = (code >> 10) & 0x0f; const sideInvert = ((code >> 14) & 0x1) != 0; let sideTurn = (code >> 15) & 0x3; const blue = ((code >> 16) & 0x01f) << 3; const green = ((code >> 21) & 0x01f) << 3; const red = ((code >> 27) & 0x01f) << 3; const fillColor = `rgb(${red}, ${green}, ${blue})`; let strokeColor; if (IdenticonImageBuilder.getColorDistance({ red: red, green: green, blue: blue }, { red: this.backgroundColor.red, green: this.backgroundColor.green, blue: this.backgroundColor.blue }) < 32.0) { const color = IdenticonImageBuilder.getComplementaryColor({ red: red, green: green, blue: blue }); strokeColor = `rgb(${color.red}, ${color.green}, ${color.blue})`; } ctx.fillStyle = `rgb(${this.backgroundColor.red},${this.backgroundColor.green},${this.backgroundColor.blue}`; ctx.fillRect(0, 0, size, size); const blockSize = Math.ceil(size / 3); const blockSize2 = Math.ceil(blockSize * 2); // middle patch this.drawPatch(ctx, blockSize, blockSize, blockSize, middleType, 0, middleInvert, fillColor, strokeColor); // side patchs, starting from top and moving clock-wise this.drawPatch(ctx, blockSize, 0, blockSize, sideType, sideTurn++, sideInvert, fillColor, strokeColor); this.drawPatch(ctx, blockSize2, blockSize, blockSize, sideType, sideTurn++, sideInvert, fillColor, strokeColor); this.drawPatch(ctx, blockSize, blockSize2, blockSize, sideType, sideTurn++, sideInvert, fillColor, strokeColor); this.drawPatch(ctx, 0, blockSize, blockSize, sideType, sideTurn++, sideInvert, fillColor, strokeColor); // corner patchs, starting from top left and moving clock-wise this.drawPatch(ctx, 0, 0, blockSize, cornerType, cornerTurn++, cornerInvert, fillColor, strokeColor); this.drawPatch(ctx, blockSize2, 0, blockSize, cornerType, cornerTurn++, cornerInvert, fillColor, strokeColor); this.drawPatch(ctx, blockSize2, blockSize2, blockSize, cornerType, cornerTurn++, cornerInvert, fillColor, strokeColor); this.drawPatch(ctx, 0, blockSize2, blockSize, cornerType, cornerTurn++, cornerInvert, fillColor, strokeColor); } drawPatch(ctx, x, y, size, patch, turn, invert, fillColor, strokeColor) { patch %= PATCH_TYPES.length; turn %= 4; if ((PATCH_FLAGS[patch] & PATCH_INVERTED) != 0) { invert = !invert; } const scale = size / this.patchSize; const offset = size / 2.0; // paint background ctx.fillStyle = invert ? fillColor : `rgb(${this.backgroundColor.red},${this.backgroundColor.green},${this.backgroundColor.blue}`; ctx.fillRect(x, y, size, size); ctx.save(); ctx.translate(x + offset, y + offset); ctx.scale(scale, scale); ctx.rotate(turn * 90 * (Math.PI / 180)); if (strokeColor != null) { ctx.strokeStyle = strokeColor; ctx.beginPath(); this.drawPath(ctx, patch); ctx.stroke(); } ctx.fillStyle = invert ? `rgb(${this.backgroundColor.red},${this.backgroundColor.green},${this.backgroundColor.blue}` : fillColor; ctx.beginPath(); this.drawPath(ctx, patch); ctx.fill(); ctx.restore(); } drawPath(ctx, path) { const patchOffset = this.patchSize / 2; const patchScale = this.patchSize / 4; let moveTo = true; const patchVertices = PATCH_TYPES[path]; for (let j = 0; j < patchVertices.length; j++) { const v = patchVertices[j]; if (v == PATCH_MOVETO) { moveTo = true; } const vx = ((v % PATCH_GRIDS) * patchScale) - patchOffset; const vy = Math.floor(v / PATCH_GRIDS) * patchScale - patchOffset; if (!moveTo) { ctx.lineTo(vx, vy); } else { moveTo = false; ctx.moveTo(vx, vy); } } } static getColorDistance(color1, color2) { const dx = color1.red - color2.red; const dy = color1.green - color2.green; const dz = color1.blue - color2.blue; return Math.sqrt(dx * dx + dy * dy + dz * dz); } static getComplementaryColor(color) { return { red: color.red ^ 0xFF, green: color.green ^ 0xFF, blue: color.blue ^ 0xFF }; } }
JavaScript
class UserPanelButton extends Component { constructor(props) { super(props); this.button = React.createRef(); } state = { anchorEl: null, isOpen: false, }; handleMenu = () => { this.setState(state => ({ anchorEl: this.button.current, isOpen: !state.isOpen, })); }; handleClose = () => { this.setState(state => ({ anchorEl: null, isOpen: !state.isOpen, })); }; render() { const { classes } = this.props; const { isOpen, anchorEl } = this.state; return ( <div className={classes.rightBlockItem} ref={this.button}> <Tooltip title="User panel"> <IconButton id="icon-profile" className={classes.rightBlockButton} aria-owns={isOpen ? 'menu-appbar' : undefined} aria-haspopup="true" onClick={this.handleMenu.bind(this)} color="inherit" aria-label="User Panel" > <PersonIcon /> </IconButton> </Tooltip> <Popover id="menu-appbar" anchorEl={anchorEl} anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }} transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={isOpen} onClose={this.handleClose} > <Card id="userPanel" className={classes.userPanel}> <Typography variant="h1" className={classes.userName}> {localStorage.getItem('username')} </Typography> <Typography className={classes.userRole}> <span>User role:</span> {localStorage.getItem('role')} </Typography> <CustomLogoutButton classes={classes} /> </Card> </Popover> </div> ); } }
JavaScript
class BackgroundElements { constructor(app) { this._app = app; this._collidable = []; // elements that trigger collision with player this._backgroundElements = {}; // hashmap with the background elements // background elements are defined in Config for(const [name, config] of Object.entries(Config.backgroundElements)) { // instantiate using the class defined in config const backgroundElement = new config.type(this._app, config); this._backgroundElements[name] = backgroundElement; // prefill background elements such as trees if(config.type == SpriteEmitter) backgroundElement.preFill(); if(config.collidable) this._collidable.push(backgroundElement); app.stage.addChild(backgroundElement); backgroundElement.x = Config.getNested(config, 'position.x') || 0; backgroundElement.y = Config.getNested(config, 'position.y') || 0; if(config.type == BackgroundScroller) { backgroundElement.tilePosition.x = Config.getNested(config, 'tilePosition.x') || 0; backgroundElement.tilePosition.y = Config.getNested(config, 'tilePosition.y') || 0; } } this.moving = false; } /** * Make all background elements start moving */ set moving(moving) { for(const element of Object.values(this._backgroundElements)) { element.moving = moving; } } /** * Returns list of collidable elements */ get collidable() { return this._collidable; } /** * Calculation of floor position (player position on game over) */ get floorPosition() { return this._backgroundElements['floor_back'].y + Config.player.collision.margin; } /** * Remove all obstacles to reset the game */ removeObstacles() { this._backgroundElements['columns'].removeObstacles(); } /** * Update all background elements */ update(elapsed) { for(const element of Object.values(this._backgroundElements)) element.update(elapsed); } }
JavaScript
class FallbackQueue { /** * @param {*} name - name of queue * @param {object} opts - unused, here for compatibility only */ constructor(name, opts) { this.name = name this.processor = undefined this.opts = opts this.eventHandlers = {} } /** * Adds a job to the queue. Job will be run immediately, and you * can `await` the job's completion if your processing function supports it. * @param {*} data */ async add(data) { log.info(this.name + ' queue using inline queue processor fallback.') if (this.processor == undefined) { throw new Error('No processor defined for this fake job queue') } const job = { id: Date.now(), data: data, progress: () => undefined, log: log.info, queue: this } await this.processor(job) return job } /** * Registers your job processing function. * @param {function} fn - code the runs for each submitted job */ process(fn) { this.processor = fn } /** * Do nothing stub */ resume() {} /** * Do nothing stub */ pause() {} /** * Fake job counts for health check */ getJobCounts() { return { waiting: -1, active: -1, completed: -1, failed: -1, delayed: -1, paused: -1 } } /** * Event handlers */ on(name, cb) { // TODO: implement event triggers? ref: https://github.com/OptimalBits/bull/blob/712df1db6f132fa8198745be298d2d8befa203b1/lib/queue.js#L328-L331 this.eventHandlers[name] = cb } }
JavaScript
class Differ { constructor (id) { this.id = id this.map = [] this.hooks = [] } isEmpty () { return this.map.length === 0 } append (type, depth, ref, handler) { if (!this.hasTimer) { this.hasTimer = true setTimeout(() => { this.hasTimer = false this.flush(true) }, 0) } const map = this.map if (!map[depth]) { map[depth] = {} } const group = map[depth] if (!group[type]) { group[type] = {} } if (type === 'element') { if (!group[type][ref]) { group[type][ref] = [] } group[type][ref].push(handler) } else { group[type][ref] = handler } } flush (isTimeout) { const map = this.map.slice() this.map.length = 0 map.forEach((group) => { callTypeMap(group, 'repeat') callTypeMap(group, 'shown') callTypeList(group, 'element') }) const hooks = this.hooks.slice() this.hooks.length = 0 hooks.forEach((fn) => { fn() }) if (!this.isEmpty()) { this.flush() } } then (fn) { this.hooks.push(fn) } }
JavaScript
class XcodeCheck extends DoctorCheck { async diagnose () { let xcodePath; try { // https://github.com/appium/appium/issues/12093#issuecomment-459358120 can happen await exec('xcrun', ['simctl', 'help']); } catch (err) { return nok('Error running xcrun simctl'); } try { const {stdout} = await exec('xcode-select', ['-p']); xcodePath = (stdout || '').replace('\n', ''); } catch (err) { return nok('Xcode is NOT installed!'); } return xcodePath && await fs.exists(xcodePath) ? ok(`Xcode is installed at: ${xcodePath}`) : nok(`Xcode cannot be found at '${xcodePath}'!`); } async fix () { // eslint-disable-line require-await return `Manually install ${'Xcode'.bold}, and make sure 'xcode-select -p' command shows proper path like '/Applications/Xcode.app/Contents/Developer'`; } }
JavaScript
class XcodeCmdLineToolsCheck extends DoctorCheck { constructor () { super({autofix: true}); } async diagnose () { const errMess = 'Xcode Command Line Tools are NOT installed!'; try { // https://stackoverflow.com/questions/15371925/how-to-check-if-command-line-tools-is-installed const stdout = (await exec('xcode-select', ['-p'])).stdout; return ok(`Xcode Command Line Tools are installed in: ${stdout.trim()}`); } catch (err) { log.debug(err); return nok(errMess); } } async fix () { log.info(`The following command need be executed: xcode-select --install`); let yesno = await fixIt(); if (yesno === 'yes') { await exec('xcode-select', ['--install']); } else { log.info(`Skipping you will need to install ${'Xcode'.bold} manually.`); throw new FixSkippedError(); } } }
JavaScript
class DevToolsSecurityCheck extends DoctorCheck { constructor () { super({autofix: true}); } async diagnose () { const errMess = 'DevToolsSecurity is NOT enabled!'; let stdout; try { stdout = (await exec('DevToolsSecurity', [])).stdout; } catch (err) { log.debug(err); return nok(errMess); } return stdout && stdout.match(/enabled/) ? ok('DevToolsSecurity is enabled.') : nok(errMess); } async fix () { return await fixes.authorizeIosFix(); } }
JavaScript
class CarthageCheck extends DoctorCheck { async diagnose () { let carthagePath = await CarthageDetector.detect(); let version; if (carthagePath) { try { const {stdout} = await exec(carthagePath, ['version']); // 'Please update to the latest Carthage version: 0.33.0. You currently are on 0.32.0\n0.32.0\n' or '0.32.0\n' // 0.32.0 is the current version. 0.33.0 is an available newer version. version = _.last(stdout.match(/(\d+\.\d+\.\d+)/g)); if (!util.coerceVersion(version, false)) { log.warn(`Cannot parse Carthage version from ${stdout}`); } } catch (err) { log.warn(err); } } return carthagePath ? ok(`Carthage was found at: ${carthagePath}${ version ? `. Installed version is: ${version}` : ''}`) : nok(`Carthage was NOT found!`); } async fix () { // eslint-disable-line require-await return `Please install ${'Carthage'.bold}. Visit https://github.com/Carthage` + '/Carthage#installing-carthage for more information.'; } }