language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class PresenceSetter extends OperationBaseClass { constructor(name) { super(name); this.regularX = /^presence/; } //overrides: isOperation(message) { return message.content.match(this.regularX); } execute(message) { var gameString = message.content.replace(this.regularX,""); //parse message content client.user.setPresence({game: { name: gameString, type: 0 }}); } help() { return "ohh Jeez, call presence and i will set as my game being played!!!" } }
JavaScript
class Betting extends BaseScene { /** * The indices of the poker chips (where to place them in the scene). * * @static * @memberof Betting */ static chipIndices = [169, 171, 173, 175, 199, 201, 203, 205]; /** * Returns the appropriate position index * for the given poker chip. * * @static * @param {Chip} chip the chip to get the index of. * @returns the index * @memberof Betting */ static getChipIndex(chip) { let index = Chip.VALUES.indexOf(chip.getValue()); return Betting.chipIndices[index]; } /** *Creates an instance of Betting. * @memberof Betting */ constructor() { super(CONSTANTS.Scenes.Keys.Betting); } /** * Stores variables from the calling scene. * * @param {*} blackjack * @memberof Betting */ init(blackjack) { this.blackjack = blackjack; } /** * Creates the components for this scene. * * @memberof Betting */ create() { super.create(() => { this.placeBetText = new Text(this, "Place your bet!"); this.dealButton = new Button(this, "Deal", () => this.dealButtonHandler()) .setClickSound('deal_click') .setAlpha(0); this.chips = new Chips(this); this.pot = new Pot(this); this.potText = new Text(this, `$${this.pot.amount}`).setVisible(false); this.placeUIComponents(); this.placeChips(); this.scene.launch(CONSTANTS.Scenes.Keys.Deal, this.blackjack); }); } /** * * * @memberof Betting */ placeUIComponents() { this.grid.placeAtIndex(124, this.dealButton); this.grid.placeAtIndex(67, this.placeBetText); this.grid.placeAtIndex(129, this.potText); } /** * Places the chips on the table depending on the * player's balance. * * @memberof Betting */ placeChips() { let currentValue = 0; for (const index of Object.values(Betting.chipIndices)) { let value = Chip.VALUES[currentValue]; if (this.blackjack.player.money < value) break; this.createChip(index, value); currentValue++; } } /** * Creates a poker chip and places on its respective * index. * * @param {*} index * @param {*} value * @memberof Betting */ createChip(index, value) { let chip = new Chip(this, value); this.grid.placeAtIndex(index, chip); this.chips.add(chip); chip.on('pointerup', () => this.moveChip(chip.disableInteractive(), index)); } /** * * * @param {*} chip * @param {*} index * @memberof Betting */ moveChip(chip, index) { if (this.pot.contains(chip)) this.removeTopChipFromPot(); else this.placeChipOnPot(chip, index); this.children.bringToTop(chip); if (this.pot.amount == 0) { this.fadeDealButtonAndPotText("out"); } else { this.fadeDealButtonAndPotText("in"); } this.updateChips(); } /** * Removes the top poker chip on the pot * and returns it to the player's collection of chips. * * @memberof Betting */ removeTopChipFromPot() { let chip = this.pot.removeFromTop(); this.updatePotText(); let position = this.grid.getIndexPos(Betting.getChipIndex(chip)); this.tweens.add({ targets: chip, x: position.x, y: position.y, duration: 250, onComplete: (_, targets) => { this.returnChipToPlayer(chip); this.pot.remove(chip, true, true) } }); } /** * * * @param {*} chip * @memberof Betting */ returnChipToPlayer(chip) { this.blackjack.player.give(chip); this.updatePlayersBalance(); this.updateChips(); } /** * Put's the given poker chip on the pot. * Increases to pot's balance by the given chip's value. * * @param {*} chip * @param {*} index * @param {*} value * @memberof Betting */ placeChipOnPot(chip, index) { this.blackjack.player.take(chip); this.updatePlayersBalance(); this.chips.remove(chip); let position = this.pot.add(chip); this.tweens.add({ targets: chip, duration: 250, ease: "Linear", x: position.x, y: position.y, onComplete: (_, targets) => { targets.forEach(c => c.setInteractive()); this.updatePotText(); } }); if (!this.chips.exists(chip)) { this.createChip(index, chip.model.value); } } /** * Updates the player's balance UI text. * * @memberof Betting */ updatePlayersBalance() { this.blackjack.balance.setText(`$${this.blackjack.player.money}`); } /** * Updates the text containing the pot amount using the model. * * @memberof Betting */ updatePotText() { this.potText.setText(`$${this.pot.amount}`); } /** * Fades the deal button and pot text depending on the type. * * @param {"in"|"out"} type * @memberof Betting */ fadeDealButtonAndPotText(type) { this.tweens.add({ onStart: type == "in" ? (_, targets) => targets.forEach(t => t.setVisible(true)) : () => this.dealButton.disableInteractive(), targets: [this.dealButton.setInteractive(), this.potText], alpha: type == "out" ? 0 : 1, duration: 500, onComplete: type == "out" ? (_, targets) => targets.forEach(t => t.setVisible(false)) : null, }); } /** * Updates the poker chips using the players balance. * * @memberof Betting */ updateChips() { this.chips.getChildren().forEach(chip => { if (this.blackjack.player.money < chip.getValue()) chip.setVisible(false); else chip.setVisible(true); }); } /** * Prepare for scene transition. * * @memberof Betting */ dealButtonHandler() { this.dealButton.disableInteractive(); this.scene.get("Deal").startDeal(); this.fadeChips("out"); this.hidePotTextAndDealButton(); this.movePot(118); this.movePotText(148); } /** * Moves the poker chips out of the scene. * * @memberof Betting */ fadeChips(type) { this.tweens.add({ targets: this.chips.getChildren(), alpha: type == "out" ? 0 : 1, duration: 500, onStart: type == "in" ? () => this.updateChips() : null, onComplete: type == "out" ? (_, targets) => targets.forEach(t => t.setVisible(false)) : null, }); } /** * Hides the deal button and the text * that displays how much money there is * on the pot. * * @memberof Betting */ hidePotTextAndDealButton() { this.tweens.add({ targets: [this.dealButton, this.placeBetText], alpha: 0, duration: 500, }); } /** * prepares the scene for betting. * * @memberof Betting */ prepareForBetting() { this.pot.reset(); this.fadeInPlaceBetText(); } /** * Fades in the 'Place your bet!' text * * @memberof Betting */ fadeInPlaceBetText() { this.tweens.add({ targets: this.placeBetText, alpha: 1, duration: 500 }) } /** * Moves the pot from the play area. * * @memberof Betting */ movePot(index, onComplete = null) { this.pot.disableInteractive(); let potPosition = this.grid.getIndexPos(index); this.tweens.add({ targets: this.pot.getChildren(), duration: 300, x: potPosition.x, y: potPosition.y, delay: this.tweens.stagger(30), onUpdate: (tweens, chip) => chip.getRandomSound().play(), onComplete: onComplete, completeDelay: 1000 }); } /** * * * @param {*} index * @memberof Betting */ startNewRoundAndMovePotTo(index) { let dealScene = this.scene.get(CONSTANTS.Scenes.Keys.Deal); this.pot.resetAmount(); this.movePot(index, () => dealScene.prepareForNewRound()); this.movePotText(this.pot.index); this.fadeOutPotText(); } /** * Moves the pot text to the given index. * * @param {*} index * @memberof Betting */ movePotText(index) { let textPosition = this.grid.getIndexPos(index); this.tweens.add({ targets: this.potText, duration: 500, x: textPosition.x, y: textPosition.y }); } /** * Fades out the pot text. * * @memberof Betting */ fadeOutPotText() { this.tweens.add({ targets: this.potText, duration: 500, alpha: 0, onStart: () => this.updatePotText(), onComplete: () => this.movePotText(129) }); } /** * Pays the player the pot amount by the multiplier. * * @param {*} multiplier * @memberof Betting */ payoutPlayer(multiplier) { this.blackjack.player.give(Math.floor(this.pot.amount * multiplier)); this.updatePlayersBalance(); } }
JavaScript
class EntityEditFormInstance extends FormInstance { /** * In all FormInstance derivatives, super.init() should be called LAST! * Otherwise, the [Static]{@link Defiant.Plugin.FormApi.Static} and * [Encrypt]{@link Defiant.Plugin.FormApi.Encrypt} elements will not work * properly. * * When this function is finished, then the form should be ready to * be rendered as a string. * @function * @async * @param {Object} [data={}] * The initialization data. */ async init(data={}) { const FormApi = this.context.engine.pluginRegistry.get('FormApi'); const Element = FormApi.getElement('Element'); const Button = FormApi.getElement('Button'); const Entity = this.renderable.Entity; for (let Attribute of Entity.attributeRegistry.getOrderedElements()) { let delta = 0; let maxWeight = 0; let elementGroup = Element.newInstance(this.context, {name: Attribute.attributeName}); this.addInstance(elementGroup); // Add an empty attribute array to the entity if needed. This will // be necessary if we are creating a new entity. if (this.buildState.entity[Attribute.attributeName] === undefined) { this.buildState.entity[Attribute.attributeName] = []; } if (Attribute.formType == 'individual') { // Add a form element for each of the existing values. for (let attribute of this.buildState.entity[Attribute.attributeName]) { let elementInstance = Element.newInstance(this.context, { name: `${elementGroup.name}[${delta}]`, attribute: merge(attribute, {delta}), }); elementGroup.addInstance(elementInstance); await Attribute.formInit(elementInstance); maxWeight = Math.max(maxWeight, parseFloat(attribute.weight || 0)); ++delta; } // Add a form element for each "missing" (empty) value. for (let i = delta; i < Attribute.data.count; ++i) { maxWeight += 1; let attribute = {delta: i, weight: maxWeight} this.buildState.entity[Attribute.attributeName].push(attribute); let elementInstance = Element.newInstance(this.context, { name: `${elementGroup.name}[${i}]`, attribute, }); elementGroup.addInstance(elementInstance); await Attribute.formInit(elementInstance); } } else if (Attribute.formType == 'group') { // The Attribute is responsible for handling the individual entries. let elementInstance = Element.newInstance(this.context, { name: `${elementGroup.name}`, attribute: this.buildState.entity[Attribute.attributeName], }); elementGroup.addInstance(elementInstance); await Attribute.formInit(elementInstance); } } // Add the buttons. this.addInstance(Button.newInstance(this.context, { name: 'update', data: { value: 'update', content: 'Update', }, })); this.addInstance(Button.newInstance(this.context, { name: 'update2', data: { value: 'update222', content: 'Update2', }, })); await super.init(data); } /** * Perform the form validations. * @function * @async */ async validate() { await super.validate(); const Entity = this.renderable.Entity; for (let Attribute of Entity.attributeRegistry.getOrderedElements()) { let elementGroup = this.instanceRegistry.get(Attribute.attributeName); // Validate the form elements for this attribute. for (let elementInstance of elementGroup.instanceRegistry.getOrderedElements()) { await Attribute.formValidate(elementInstance); } } } /** * Perform the form submission. * @function * @async */ async submit() { await super.submit(); const Entity = this.renderable.Entity; for (let Attribute of Entity.attributeRegistry.getOrderedElements()) { // Because we are using the same entity that was used to create the form // (which was stored in the buildState), we know that the order below // will also be the same for validation and submission purposes. let elementGroup = this.instanceRegistry.get(Attribute.attributeName); // Submit the form elements for this attribute. for (let elementInstance of elementGroup.instanceRegistry.getOrderedElements()) { await Attribute.formSubmit(elementInstance); // If the attribute is empty, it should be removed from the Entity. if (await Attribute.valueIsEmpty(elementInstance.attribute)) { let attr = this.buildState.entity[Attribute.attributeName]; let index = attr.indexOf(elementInstance.attribute, 1); if (index > -1) { attr.splice(); } } } } // Save the entity. await Entity.save(this.buildState.entity); // Delete the POST values. delete this.context.post[this.id]; } }
JavaScript
class Rect { constructor(r0, r1, c0, c1) { this.r0 = r0; this.r1 = r1; this.c0 = c0; this.c1 = c1; this.area = (c1 - c0 + 1) * (r1 - r0 + 1); } }
JavaScript
class AAIMInterpreter { constructor(behavior) { /** * The behavior instance executing state configurations * @private */ this._behavior = behavior; /** * The running state of the interpreter * @private */ this._running = false; /** * The currently loaded AAIM * @private */ this._currentAAIM = undefined; /** * The current state * @private */ this._currentState = undefined; /** * The states of the current AAIM mapped by their names * @private */ this._loadedStates = undefined; } /** * Returns if the interpreter is currently running. * * @return {Boolean} true, if the interpreter is running, false otherwise */ get running() { return this._running; } /** * Sets the interpreter to run or to pause. The interpreter can only be set * to running, if an AAIM is loaded. The interpreter upholds the current state * when getting paused and restarted. To restart the AAIM in its initial state * call {@link AAIMInterpreter#reset} after pausing the interpreter. * * @param {Boolean} run * true to run the interpreter, false to pause */ set running(run) { if (run && !this._running && this._currentAAIM !== undefined) { this._running = true; // Initial startup? if (this._currentState === undefined) { if (typeof this._currentAAIM.initial === "string" && this._loadedStates.has(this._currentAAIM.initial)) { this._performTransition(this._loadedStates.get(this._currentAAIM.initial)); } else { // Initial state is not defined or does not exist this._running = false; } } } else { this._running = false; } } /** * Returns the currently loaded AAIM. * * @return {Object} the currently loaded AAIM or undefined */ get aaim() { return this._currentAAIM; } /** * Returns the current state of the AAIM. * * @return {Object} the current state or undefined */ get state() { return this._currentState; } /** * Loads an AAIM. * * @param {AAIM} aaim * The javascript object representing the AAIM. */ load(aaim) { if (!this._running) { // AAIMs can only be replaced while not running if (typeof aaim === "object" && aaim !== null // AAIM objects but not null && Array.isArray(aaim.states) && aaim.states.length > 0) { // with an non-empty states array this._currentAAIM = aaim; // Create states map this._loadedStates = new Map(); for (let s of this._currentAAIM.states) { this._loadedStates.set(s.name, s); } return true; } } return false; } /** * Resets a paused interpreter. After the reset the interpreter will be in the * same state as directly after loading an AAIM (a.k.a. the initial state). * Calls to this method will have no effect if the interpreter is currently * running. */ reset() { if (!this._running) { this._currentState = undefined; } } /** * Executes an event on the current state of the interpreter by its name. An * event name not defined for the current state will have no effect. * Calls to this method will have no effect if the interpreter is currently * paused. * * @param {String} name * The name of the event so execute */ executeEvent(name) { if (this._running) { for (let e of this._currentState.events) { if (e.on == name && this._loadedStates.has(e.goto)) { this._performTransition(this._loadedStates.get(e.goto), e.do); break; } } } } /** * Actually performs the transition to the given target state by executing the * supplied behavior configuration. * * @private * * @param {Object} target * The target state to transition to * @param {Object} config * The do-configuration of the transition if specified or undefined */ _performTransition(target, config) { this._currentState = target; if (config && this._behavior) { this._behavior.executeTransition(config).then(function() { this._behavior.executeState(target.do); }.bind(this)); } else if (this._behavior) { this._behavior.executeState(target.do); } } }
JavaScript
class Node { constructor(name) { this.name = name; this.children = []; } addChild(name) { this.children.push(new Node(name)); return this; } // Method 1 depthFirstSearch1(array) { array.push(this.name); if (this.children) { for (let index in this.children) { this.dfsHelper(array, this.children[index]) } } // console.log(array); return array; } dfsHelper(array, kidchildren) { if (kidchildren.length === 0) return; const curName = kidchildren.name; array.push(curName); if (kidchildren.children.length) { kidchildren.children.forEach((e) => { this.dfsHelper(array, e) }) } return; } // Method 2 depthFirstSearch(array) { array.push(this.name); for (const kid of this.children) { // go inside of kid's scope and call kid's function kid.depthFirstSearch(array); } return array; } }
JavaScript
class Html extends Component { static propTypes = { assets: PropTypes.object, component: PropTypes.node, i18n: PropTypes.object, store: PropTypes.object, }; devStyles(styles) { const App = styles['./containers/App/App.scss']._style; const Header = styles['./components/Header/Header.scss']._style; const Footer = styles['./components/Footer/Footer.scss']._style; const Home = styles['./containers/Home/Home.scss']._style; return { __html: App + Header + Footer + Home }; } rawMarkup(markup) { return { __html: markup }; } serializedI18n(i18n) { return { __html: `window.__I18N__=${ serialize(i18n) };` }; } render() { const { assets, component, i18n, store } = this.props; let componentHTML = ''; let head = ''; let meta = ''; let script = ''; let title = ''; if (typeof component !== undefined) { componentHTML = renderToString(component); head = Helmet.rewind(); // see https://github.com/nfl/react-helmet title = head.title.toComponent(); meta = head.meta.toComponent(); script = head.script.toComponent(); } return ( <html> <head> { title } { meta } { script } <meta name="viewport" content="width=device-width, initial-scale=1" /> <link type="text/css" href="https://fonts.googleapis.com/css?family=Roboto:400,700,400italic,700italic,300italic,300,100italic,100,500,500italic' rel='stylesheet" /> {/* (Present only in production with webpack extract text plugin) */} { Object.keys(assets.styles).map((style, key) => <link key={ key } href={ assets.styles[style] } media="screen, projection" rel="stylesheet" type="text/css" charSet="utf-8" /> ) } {/* (Present only in development mode) */} {/* Outputs a <style/> tag with all base styles + App.scss. */} {/* can smoothen the initial style flash (flicker) on page load in development mode. */} {/* ideally one could also include here the style for the current page (Home.scss, About.scss, etc) */} { Object.keys(assets.styles).length === 0 ? <style dangerouslySetInnerHTML={ this.devStyles(assets.assets) } /> : null } </head> <body> <div id="app" dangerouslySetInnerHTML={ this.rawMarkup(componentHTML) } /> <script dangerouslySetInnerHTML={ this.serializedI18n(i18n) } charSet="utf-8" /> <script src="/js/bundle.js" charSet="utf-8" /> </body> </html> ); } }
JavaScript
class PrometheusPushTxObserver extends TxObserverInterface { /** * Initializes the observer instance. * @param {object} options The observer configuration object. * @param {MessengerInterface} messenger The worker messenger instance. */ constructor(options, messenger) { super(messenger); this.sendInterval = options && options.sendInterval || 1000; this.intervalObject = undefined; this.prometheusClient = new PrometheusClient(); this.prometheusClient.setGateway(options.push_url); this.internalStats = { previouslyCompletedTotal: 0, previouslySubmittedTotal: 0 }; } /** * Sends the current aggregated statistics to the master node when triggered by "setInterval". * @private */ async _sendUpdate() { const stats = super.getCurrentStatistics(); this.prometheusClient.configureTarget(stats.getRoundLabel(), stats.getRoundIndex(), stats.getWorkerIndex()); // Observer based requirements this.prometheusClient.push('caliper_txn_success', stats.getTotalSuccessfulTx()); this.prometheusClient.push('caliper_txn_failure', stats.getTotalFailedTx()); this.prometheusClient.push('caliper_txn_pending', stats.getTotalSubmittedTx() - stats.getTotalFinishedTx()); // TxStats based requirements, existing behaviour batches results bounded within txUpdateTime const completedTransactions = stats.getTotalSuccessfulTx() + stats.getTotalFailedTx(); const submittedTransactions = stats.getTotalSubmittedTx(); const batchCompletedTransactions = completedTransactions - this.internalStats.previouslyCompletedTotal; const batchTPS = (batchCompletedTransactions/this.sendInterval)*1000; // txUpdate is in ms const batchSubmittedTransactions = submittedTransactions - this.internalStats.previouslyCompletedTotal; const batchSubmitTPS = (batchSubmittedTransactions/this.sendInterval)*1000; // txUpdate is in ms const latency = (stats.getTotalLatencyForFailed() + stats.getTotalLatencyForSuccessful()) / completedTransactions; this.prometheusClient.push('caliper_tps', batchTPS); this.prometheusClient.push('caliper_latency', latency/1000); this.prometheusClient.push('caliper_txn_submit_rate', batchSubmitTPS); this.internalStats.previouslyCompletedTotal = batchCompletedTransactions; this.internalStats.previouslyCompletedTotal = batchSubmittedTransactions; } /** * Activates the TX observer instance and starts the regular update scheduling. * @param {number} workerIndex The 0-based index of the worker node. * @param {number} roundIndex The 0-based index of the current round. * @param {string} roundLabel The roundLabel name. */ async activate(workerIndex, roundIndex, roundLabel) { await super.activate(workerIndex, roundIndex, roundLabel); this.intervalObject = setInterval(async () => { await this._sendUpdate(); }, this.sendInterval); } /** * Deactivates the TX observer interface, and stops the regular update scheduling. */ async deactivate() { await super.deactivate(); this.internalStats = { previouslyCompletedTotal: 0, previouslySubmittedTotal: 0 }; if (this.intervalObject) { clearInterval(this.intervalObject); this.prometheusClient.push('caliper_txn_success', 0); this.prometheusClient.push('caliper_txn_failure', 0); this.prometheusClient.push('caliper_txn_pending', 0); await CaliperUtils.sleep(this.sendInterval); } } }
JavaScript
class Container { /** * Constructs an empty container. * * @param [HashMap] map - the map this container belongs too. * @param hash - the hash code for the keys in this container. */ constructor(map, parent, hash) { this.size = 0; this.contents = []; this.map = map; this.parent = parent; this.hash = hash; } /** * Does the provided hash conflict with this one, i.e. is it different. * This is used for ensuring only the correct keys are added. * * @param hash * @return {boolean} */ hashConflicts(hash) { return hash !== this.hash; } /** * Used to fetch the key and value. * * @param {*} key the key we use to retrieve the value. * @param options must contain the equals function for this key. * @return {*|undefined} the value for the key, or undefined if none available. */ get(key, options) { if (this.size !== 0) { const equals = options.equals; for (const entry of this.contents) { if (entry && equals(key, entry[0])) { return entry[1]; } } } return undefined; } optionalGet(key, options) { if (this.size !== 0) { const equals = options.equals; const entry = this.contents.find(entry => equals(key, entry[0])); if (entry) { return some(entry[1]); } } return none; } set(key, value, options) { const equals = options.equals; for (const entry of this.contents) { if (equals(key, entry[0])) { this.updateEntry(entry, value, options); return; } } this.createEntry(key, value, options); } emplace(key, handler, options) { const equals = options.equals; for (const entry of this.contents) { if (equals(key, entry[0])) { if('update' in handler) { const value = handler.update(entry[1], key, this.map); this.updateEntry(entry, value, options); return value; } return entry[1]; } } const value = handler.insert(key, this.map); this.createEntry(key, value, options); return value; } createEntry(key, value) { const entry = [key, value]; entry.parent = this; this.contents.push(entry); this.size += 1; return entry; } updateEntry(entry, newValue) { entry[1] = newValue; } deleteEntry(entry) { const idx = this.contents.indexOf(entry); if (idx !== -1) { this.deleteIndex(idx); let parent = this.parent; while (parent) { parent.size -= 1; parent = parent.parent; } } } deleteIndex(idx) { this.size -= 1; if (idx === 0) { return this.contents.shift(); } else if (idx === this.size) { return this.contents.pop(); } else { return this.contents.splice(idx, 1)[0]; } } has(key, options) { if (this.size !== 0) { const equals = options.equals; return this.contents.some(entry => equals(key, entry[0])); } return false; } delete(key, options) { const equals = options.equals; const idx = this.contents.findIndex(entry => equals(key, entry[0])); if (idx === -1) { return false; } this.deleteIndex(idx); return true; } * [Symbol.iterator]() { for (const entry of this.contents) { yield entry.slice(); } } * entriesRight() { for (let idx = this.contents.length - 1; idx >= 0; idx--) { yield this.contents[idx].slice(); } } * keys() { for (const entry of this.contents) { yield entry[0]; } } * values() { for (const entry of this.contents) { yield entry[1]; } } * keysRight() { for (let idx = this.contents.length - 1; idx >= 0; idx--) { yield this.contents[idx][0]; } } * valuesRight() { for (let idx = this.contents.length - 1; idx >= 0; idx--) { yield this.contents[idx][1]; } } }
JavaScript
class ThemeWrapper extends Component { render () { return <ThemeProvider>{this.props.children}</ThemeProvider> } }
JavaScript
class Clock extends HTMLElement { constructor() { super(); } connectedCallback() { const shadow = this.attachShadow({ mode: 'open' }); shadow.appendChild(clock.content.cloneNode(true)); setInterval(function() { let d = new Date(); var hourDeg = (d.getHours() * 30) + (0.5 * d.getMinutes()); // every hour, 30 deg. 30 / 60 var minuteDeg = (d.getMinutes() * 6) + (0.1 * d.getSeconds()); // every minute, 6 deg. 6 / 60 var secondDeg = d.getSeconds() * 6; // 360 / 60 shadow.getElementById('hourHand').style.transform = 'rotate(' + hourDeg + 'deg)'; shadow.getElementById('minuteHand').style.transform = 'rotate(' + minuteDeg + 'deg)'; shadow.getElementById('secondHand').style.transform = 'rotate(' + secondDeg + 'deg)'; }, 1000); } }
JavaScript
class ErrorPage extends Component { // componentDidMount() { // if (isBrowser()) { // document.querySelector('.header').style.display = 'none'; // document.querySelector('.footer').style.display = 'none'; // } // } // componentWillUnmount() { // if (isBrowser()) { // document.querySelector('.header').style.display = ''; // document.querySelector('.footer').style.display = ''; // } // } render() { return ( <Layout> <SEO title="404: Not found" /> <main className="main-container"> <div className="error-page-container"> <div className="error-block"> <div className="error-block_image" /> <div className="error-block_head-text">Error 404</div> <div className="error-block_descr">Sorry, Page not found</div> <div className="error-block_info">The link you followed probably broken or the page has been removed</div> <div className="error-block_button"> <Link className="btn btn-common" to="/"><span>Back to home</span> </Link> </div> </div> </div> </main> </Layout> ); } }
JavaScript
class Scenes { constructor(scenes) { this._scenes = new Map(); scenes.forEach(scene => this.scenes.set(scene.name, scene)); } /** @member {Map.<string, Scene>} */ get scenes() { return this._scenes; } set scenes(scenes) { Logger.fatal("Cannot set Scenes.scenes directly.\nIf you want to set a scene, please use Scenes#addScene(scene)."); } /** * Add new scene. * @param {Scene} scene new scene * @returns {boolean} If this already has the scene of the same name, returns `false`. */ addScene(scene) { if (this.hasScene(scene.name)) { return false; } else { this.scenes.set(scene.name, scene); return true; } } /** * Check if this has the scene. * @param {string} name the scene name * @returns {boolean} `true` if this has the scene */ hasScene(name) { return this.scenes.has(name); } /** * Returns the scene. * @param {string} name the scene name * @returns {?Scene} the scene */ getScene(name) { if (this.hasScene(name)) { return this.scenes.get(name); } else { Logger.error(`Scenes has no scene of name ${name}!`); return null; } } /** * Execute function for each scenes. * @param {Scenes~forEach} f callback function */ forEach(f) { this.scenes.forEach(f); } /** * @callback Scenes~forEach * @param {string} key * @param {Scene} value */ /** * Convert to string. * @returns {string} a string */ toString() { return `[Scenes]`; } }
JavaScript
class BSChannel { constructor(myProbab) { this.myProbab = myProbab; } transit(u8a) { const newU8a = new Uint8Array(u8a.length); let index = 0; for (const u8 of u8a) { let value = 0; for (let i = 0; i < 8; i++) { const bit = (u8 >>> i) % 2; const tran = this.transition(bit); value += tran << i; } newU8a[index] = value; index++; } return newU8a; } transition(bit) { let boolBit = bit !== 0; const val = Math.random(); if (val < this.myProbab) { boolBit = !boolBit; } return boolBit ? 1 : 0; } }
JavaScript
class TodoCreate extends React.Component { constructor(props) { super(props); this.state = { value: '', }; } onChange = (event) => { const value = event.target.value; this.setState({ value }); }; onCreateTdo = (event) => { this.props.onAddTodo(this.state.value); this.setState({ value: '' }); event.preventDefault(); }; render() { return ( <div> <form onSubmit={this.onCreateTdo}> <input type='text' value={this.state.value} onChange={this.onChange} /> <button type='submit'>Add</button> </form> </div> ); } }
JavaScript
class Response { constructor() { let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; Body.call(this, body, opts); const status = opts.status || 200; const headers = new Headers(opts.headers); if (body != null && !headers.has('Content-Type')) { const contentType = extractContentType(body); if (contentType) { headers.append('Content-Type', contentType); } } this[INTERNALS$1] = { url: opts.url, status, statusText: opts.statusText || STATUS_CODES[status], headers, counter: opts.counter }; } get url() { return this[INTERNALS$1].url || ''; } get status() { return this[INTERNALS$1].status; } /** * Convenience property representing if the request ended normally */ get ok() { return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; } get redirected() { return this[INTERNALS$1].counter > 0; } get statusText() { return this[INTERNALS$1].statusText; } get headers() { return this[INTERNALS$1].headers; } /** * Clone this response * * @return Response */ clone() { return new Response(clone(this), { url: this.url, status: this.status, statusText: this.statusText, headers: this.headers, ok: this.ok, redirected: this.redirected }); } }
JavaScript
class Request { constructor(input) { let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; let parsedURL; // normalize input if (!isRequest(input)) { if (input && input.href) { // in order to support Node.js' Url objects; though WHATWG's URL objects // will fall into this branch also (since their `toString()` will return // `href` property anyway) parsedURL = parse_url(input.href); } else { // coerce input to a string before attempting to parse parsedURL = parse_url(`${input}`); } input = {}; } else { parsedURL = parse_url(input.url); } let method = init.method || input.method || 'GET'; method = method.toUpperCase(); if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { throw new TypeError('Request with GET/HEAD method cannot have body'); } let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; Body.call(this, inputBody, { timeout: init.timeout || input.timeout || 0, size: init.size || input.size || 0 }); const headers = new Headers(init.headers || input.headers || {}); if (inputBody != null && !headers.has('Content-Type')) { const contentType = extractContentType(inputBody); if (contentType) { headers.append('Content-Type', contentType); } } let signal = isRequest(input) ? input.signal : null; if ('signal' in init) signal = init.signal; if (signal != null && !isAbortSignal(signal)) { throw new TypeError('Expected signal to be an instanceof AbortSignal'); } this[INTERNALS$2] = { method, redirect: init.redirect || input.redirect || 'follow', headers, parsedURL, signal }; // node-fetch-only options this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; this.counter = init.counter || input.counter || 0; this.agent = init.agent || input.agent; } get method() { return this[INTERNALS$2].method; } get url() { return format_url(this[INTERNALS$2].parsedURL); } get headers() { return this[INTERNALS$2].headers; } get redirect() { return this[INTERNALS$2].redirect; } get signal() { return this[INTERNALS$2].signal; } /** * Clone this request * * @return Request */ clone() { return new Request(this); } }
JavaScript
class RequestError extends Error { constructor(message, statusCode, options) { super(message); // Maintains proper stack trace (only available on V8) /* istanbul ignore next */ if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } this.name = "HttpError"; this.status = statusCode; Object.defineProperty(this, "code", { get() { logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); return statusCode; } }); this.headers = options.headers; // redact request credentials without mutating original request options const requestCopy = Object.assign({}, options.request); if (options.request.headers.authorization) { requestCopy.headers = Object.assign({}, options.request.headers, { authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]") }); } requestCopy.url = requestCopy.url // client_id & client_secret can be passed as URL query parameters to increase rate limit // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") // OAuth tokens can be passed as URL query parameters, although it is not recommended // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); this.request = requestCopy; } }
JavaScript
class DelayedJSONHandler extends AbstractHandler_1.AbstractHandler { constructor() { super(...arguments); this.pretty = false; this.data = []; } handle(data) { // really advanced this.data.push(data); } finished() { console.log(JSON.stringify(this.data)); } }
JavaScript
class Employee { constructor(firstName, lastName, employeeRole, manager) { this.firstName = firstName; this.lastName = lastName; this.employeeRole = employeeRole; this.manager = manager; } }
JavaScript
class EventTracker { constructor(dom_element) { this.dom_element = dom_element; this.mouseIsDown = false; this.lastP = null; this.lastDrag = null; this.lastTime = null; this.mouseDownListener = null; this.mouseDragListener = null; this.mouseUpListener = null; this.mouseWheelListener = null; this.keyPressListener = null; this.keyUpListener = null; this.keyDownListener = null; this.lastTouchP = null; this.specialKeys = { 'Tab': true, 'Escape': true, 'Delete': true, 'Backspace': true }; this.touchStart = (event) => { event.preventDefault(); this.lastTouchP = this.relTouchCoords(event); this.lastTouchTime = event.timeStamp; if (this.touchStartListener) { this.touchStartListener(this.lastTouchP); } }; this.touchMove = (event) => { event.preventDefault(); const p = this.relTouchCoords(event); const t = event.timeStamp; this.lastTouchMove = p.map((p,i) => { return { x : p.x - this.lastTouchP[i].x, y : p.y - this.lastTouchP[i].y }; }); if (this.touchMoveListener) { this.touchMoveListener(p, this.lastTouchMove); } this.lastTouchP = p; this.lastTouchTime = t; }; this.mouseDown = (event) => { this.mouseIsDown = true; this.lastP = this.relCoords(event); this.lastTime = event.timeStamp; if (this.mouseDownListener) { this.mouseDownListener(this.lastP); } }; this.mouseMove = (event) => { const p = this.relCoords(event); const t = event.timeStamp; if (this.mouseIsDown) { this.lastDrag = { x : p.x - this.lastP.x, y : p.y - this.lastP.y }; if (this.mouseDragListener) { this.mouseDragListener(p, this.lastDrag, event.button); } this.lastP = p; this.lastTime = t; } else { if (this.mouseMoveListener) { this.mouseMoveListener(p, event.button); } } }; this.mouseUp = (event) => { const p = this.relCoords(event); const t = event.timeStamp; this.mouseIsDown = false; if (this.mouseUpListener) { this.mouseUpListener(p, t - this.lastTime, this.lastDrag, event); } this.lastP = p; this.lastTime = t; }; this.mouseWheel = (event) => { if (this.mouseWheelListener) { event.preventDefault(); event.stopPropagation(); let delta = 0; if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9 delta = event.wheelDelta / 40; } else if ( event.detail ) { // Firefox delta = - event.detail / 3; } const p = this.relCoords(event); this.mouseWheelListener(delta, p); } }; this.keyPress = (event) => { if (this.keyPressListener) { this.keyPressListener(event); } }; this.keyUp = (event) => { if (this.keyUpListener) { this.keyUpListener(event); } }; this.keyDown = (event) => { if (this.keyDownListener) { this.keyDownListener(event); } }; } setTouchStartListener(listener) { this.touchStartListener = listener; return this; } setTouchMoveListener(listener) { this.touchMoveListener = listener; return this; } setMouseDownListener(listener) { this.mouseDownListener = listener; return this; } setMouseMoveListener(listener) { this.mouseMoveListener = listener; return this; } setMouseDragListener(listener) { this.mouseDragListener = listener; return this; } setMouseUpListener(listener) { this.mouseUpListener = listener; return this; } setMouseWheelListener(listener) { this.mouseWheelListener = listener; return this; } setKeyPressListener(listener) { this.keyPressListener = listener; return this; } setKeyUpListener(listener) { this.keyUpListener = listener; return this; } setKeyDownListener(listener) { this.keyDownListener = listener; return this; } relCoords(event) { return { x : event.pageX - this.dom_element.offsetLeft, y : event.pageY - this.dom_element.offsetTop, button: event.button }; } relTouchCoords(event) { const touchP = []; for (let i = 0; i < event.touches.length; ++i) { touchP.push(this.relCoords(event.touches[i])); } return touchP; } start() { this.dom_element.addEventListener( 'keypress', this.keyPress, false ); this.dom_element.addEventListener( 'keyup', this.keyUp, false ); this.dom_element.addEventListener( 'keydown', this.keyDown, false ); this.dom_element.addEventListener( 'mousedown', this.mouseDown, false ); this.dom_element.addEventListener( 'mousewheel', this.mouseWheel, false ); this.dom_element.addEventListener( 'mousemove', this.mouseMove, false); this.dom_element.addEventListener( 'mouseup', this.mouseUp, false); this.dom_element.addEventListener( 'touchstart', this.touchStart, false ); this.dom_element.addEventListener( 'touchmove', this.touchMove, false ); this.dom_element.addEventListener( 'contextmenu', (e) => { e.preventDefault(); return false; }); } }
JavaScript
class SubscriberSubtaskWorker extends task.SubtaskWorker { constructor() { super(); } childStart(startRequest) { let client = new PubSub({ projectId: startRequest.project }); let topic = client.topic(startRequest.topic); let options = { flowControl: { maxBytes: BYTES_PER_PROCESS, maxMessages: Number.MAX_SAFE_INTEGER, }, }; let subscription = topic.subscription(startRequest.pubsub_options.subscription, options); subscription.on('message', this.onMessage.bind(this)); subscription.on(`error`, error => { console.error(`ERROR: ${error}`); }); } onMessage(message) { let latency = (new Date).getTime() - parseInt(message.attributes['sendTime']); let pubId = parseInt(message.attributes['clientId']); let sequenceNumber = parseInt(message.attributes['sequenceNumber']); let messageAndDuration = new metrics_tracker.MessageAndDuration( pubId, sequenceNumber, latency); this.metricsTracker.put(messageAndDuration); message.ack(); } }
JavaScript
class Birthday { /** * The default constructor for the Birthday class. It accepts three * parameters, two of which are optional as they may not be known at the time * of instantiating the class. The user id is mandatory as it's used for * nearly every database call and we can't chance it being undefined/null. * * @param {string} userId The user id of the user we're working with * @param {string} date The date of the users birthday if known * @param {boolean} privateDate Whether or not their birthday should be private * * @constructor */ constructor (userId, date = undefined, privateDate = true) { this.user = userId this.date = date this.privateDate = privateDate } canModify (userId) { return new Promise((resolve, reject) => { if (userId === this.user) resolve(true) BirthdayModel.findById(this.user, (err, res) => { if (err) reject(err) else if (res.creatorId === userId) resolve(true) else resolve(false) }) }) } delete () { return new Promise((resolve, reject) => { BirthdayModel.deleteOne({ _id: this.user }, err => { if (err) reject(err) else resolve(true) }) }) } /** * Returns true or false depending on if the current birthday model has been * stored in the database yet. The database is queried for the user that was * provided when creating an instance of the Birthday class. * * @returns {Promise<boolean>} */ stored () { return new Promise((resolve, reject) => { BirthdayModel.findById(this.user, (err, res) => { if (err) reject(err) else if (res !== null) resolve(true) else resolve(false) }) }) } updateBirthday (info) { return new Promise((resolve, reject) => { BirthdayModel.findByIdAndUpdate(this.user, { date: info.date, privateDate: info.privateDate }, (err, res) => { if (err) reject(err) else resolve(true) }) }) } /** * If a birthday object is provided, it is stored in the birthdays collection * and returns true if it is successful. If no object is provided, it defaults * to the values provided when creating an instance of the Birthday class. * * @param {Bday} [bday] The birthday to be stored (defaults to values provided when creating the class) * * @return {Promise<boolean>} */ store (bday = { _id: this.user, date: this.date, privateDate: this.privateDate }) { return new Promise((resolve, reject) => { const newBday = new BirthdayModel(bday) newBday.save(err => { if (err) reject(err) else resolve(true) }) }) } /** * Gets the required info to be stored for a given birthday and returns it as * an object. * * @param {Message} msg * * @returns {Promise<Bday>} */ async getInfo (msg) { return Promise.resolve({ _id: this.user, date: await this.getDate(msg), privateDate: await this.getPrivacy(msg), creatorId: msg.author.id }) } /** * Gets a list of all public birthdays on the server where the provided * message was sent. * * @param {Message} msg */ async getServerBdays (msg) { return new Promise((resolve, reject) => { BirthdayModel.find({ privateDate: false }).sort('date').exec((err, res) => { if (err) { console.log(`There was an error getting the list of server bdays:`) console.error(err) } else { let bdays = [] res.forEach(val => { let member = msg.guild.members.get(val._id) if (member !== undefined) bdays.push({ username: member.user.username, date: this.formatDate(val.date) }) }) resolve(bdays) } }) }) } async getUserId (msg) { return new Promise((resolve, reject) => { const collector = baseCollector(msg) msg.reply('which user do you want to store a birthday for? Please reply with a mention of the user. (e.g. _@Alcha#0042_)') collector.on('collect', m => { if (m.mentions.users.size === 1) { collector.stop() resolve(m.mentions.users.first().id) } else m.reply('please mention at least one and only one, user.') }) }) } verifyNewUser (msg) { return new Promise((resolve, reject) => { const collector = baseCollector(msg) msg.reply('your birthday has already been stored. Would you like to add the birthday of another user? (**Y**/**N**)') collector.on('collect', m => { if (m.content.length === 1) { switch (m.content.toLowerCase()) { case 'y': collector.stop() resolve(true) break case 'n': collector.stop() resolve(false) break default: m.reply('please reply with the letter **Y** or **N**.') break } } else m.reply('please reply with the letter **Y** or **N**.') }) }) } /** * Gets the date of a users birthday using a message collector on the provided * message. If one is provided, it is returned via a Promise as a String. * * @param {Message} msg * * @returns {Promise<string>} */ getDate (msg) { return new Promise((resolve, reject) => { const collector = baseCollector(msg) msg.reply('which date is the birthday? (MMDD e.g. August 25 = **0825**)') collector.on('collect', m => { if (m.content.length === 4 && m.content.match(/[0-1]?[0-9][0-3][0-9]/)) { collector.stop() resolve(m.content) } else m.reply('date must be in MMDD format (e.g. August 25 = **0825**).') }) }) } /** * Gets the privacy preference from the user using a message collector on the * provided message object. If it is provided, true or false is returned based * on their reply `(yes = true, no = false)`. * * @param {Message} msg * * @returns {Promise<boolean>} */ getPrivacy (msg) { return new Promise((resolve, reject) => { const collector = baseCollector(msg) msg.reply('would you like the birthday to remain private?') collector.on('collect', m => { let content = m.content.toLowerCase() if (content === 'yes') { collector.stop() resolve(true) } else if (content === 'no') { collector.stop() resolve(false) } else m.reply('must provide yes or no.') }) }) } /** * "Formats" the given 4 digit date by adding a / between them. For example, * passing in the digits "0825" will return "08/25" for better reading. * * @param {string} date The date to be formatted */ formatDate (date) { /* let output = [] output.push(date[0]) output.push(date[1]) output.push('/') output.push(date[2]) output.push(date[3]) */ return [date.slice(0, 2), '/', date.slice(2)].join('') } }
JavaScript
class Layout extends __WEBPACK_IMPORTED_MODULE_0_react___default.a.Component { render() { return __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement( 'div', { className: __WEBPACK_IMPORTED_MODULE_4__Layout_css___default.a.root, __source: { fileName: _jsxFileName, lineNumber: 27 }, __self: this }, __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(__WEBPACK_IMPORTED_MODULE_5__Header__["a" /* default */], { __source: { fileName: _jsxFileName, lineNumber: 28 }, __self: this }), __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement( 'section', { className: __WEBPACK_IMPORTED_MODULE_4__Layout_css___default.a.mainContainer, __source: { fileName: _jsxFileName, lineNumber: 29 }, __self: this }, this.props.children ), __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(__WEBPACK_IMPORTED_MODULE_6__Footer__["a" /* default */], { __source: { fileName: _jsxFileName, lineNumber: 32 }, __self: this }) ); } }
JavaScript
class App extends __WEBPACK_IMPORTED_MODULE_0_react___default.a.PureComponent { getChildContext() { return this.props.context; } render() { // NOTE: If you need to add or modify header, footer etc. of the app, // please do that inside the Layout component. return __WEBPACK_IMPORTED_MODULE_0_react___default.a.Children.only(this.props.children); } }
JavaScript
class Router { /** * @constructor * @returns {Router} A new Router instance. */ constructor() { this._tree = new Tree(); this._apps = new WeakMap(); } /** * Mounts an app middleware function. Multiple apps can be mounted and requests will be routed according to the * indicated hostname and protocol. * * @param {Function} app The middleware function to add to the hostname routing tree. * @param {Object} [options={}] An options configuration object. * @property {String|Array<String>} [options.hostnames] An array of hostnames that should be associated with the * added app. Can also be a single string as shorthand. * @property {Object|String|Array<String>} [options.aliases] An array of hostname aliases that should be associated * with the added app. A hostname alias serves as a redirection to a primary hostname. Keys take the form of an * alias, values should be a hostname redirection (e.g. 'https://example.com' or 'example.com'). If no protocol * is included it will default to the type of listener (http or https). Can be a single string or array of * strings if `options.hostnames` contains a single hostname. Serves no purpose if `options.hostnames` isn't * specified. * @property {Boolean} [options.forceTLS] A boolean flag to indicate whether or not requests to the app should * enforce encrypted communication. * @returns {Router} The Router instance (chainable method). */ add(app, options = {}) { let hostnames = Array.isArray(options.hostnames) ? options.hostnames : [options.hostnames]; for (let i = 0; i < hostnames.length; i++) { let tokens = tokenizeHostname(hostnames[i]); let node = this._tree.add(tokens); if (this._apps.has(node)) { throw new Error('Ambiguous application mount. Handlers specified with a hostname cannot conflict.'); } node.forceTLS = options.forceTLS; node.alias = false; this._apps.set(node, app); } if (options.aliases) { let aliases; if (isPlainObject(options.aliases)) { aliases = options.aliases; } else { if (hostnames.length > 1) { throw new Error('Ambiguous hostname aliasing. Application mounted using more than one hostname.'); } if (hostnames[0].indexOf('*') > -1) { throw new Error('Ambiguous hostname aliasing. Application mounted using a wildcard hostname.'); } let aliasArray = Array.isArray(options.aliases) ? options.aliases : [options.aliases]; aliases = {}; for (let i = 0; i < aliasArray.length; i++) { aliases[aliasArray[i]] = hostnames[0]; } } for (let alias in aliases) { if (!aliases.hasOwnProperty(alias)) { break; } let tokens = tokenizeHostname(alias); let node = this._tree.add(tokens); if (this._apps.has(node)) { throw new Error('Ambiguous application mount. Handlers specified with a hostname cannot conflict.'); } let redirect = aliases[alias]; if (!RE_PROTOCOL.test(redirect)) { redirect = (options.forceTLS ? 'https' : 'http') + '://' + redirect; } let parsed = url.parse(redirect); node.forceTLS = null; node.alias = url.format({ protocol: parsed.protocol, hostname: parsed.hostname, port: parsed.port, pathname: '' }); this._apps.set(node, app); } } return this; } /** * Manifests the Router instance as a middleware function. The middleware function can be mounted onto an ExpressJS * application to route requests according to the indicated hostname and protocol properties. * * @returns {Function} A middleware function used to route inbound requests to appropriate middleware handlers. */ handler() { let self = this; return function(req, res, next) { let tokens = tokenizeHostname(req.hostname); let node = self._tree.find(tokens); let app = self._apps.get(node); if (!app) { let err = self._container.errors(404); next(err); } else if (node.alias) { res.redirect(self._container.redirectCode, node.alias + req.originalUrl); } else if (!node.forceTLS && req.secure) { let err = self._container.errors(404); next(err); } else if (node.forceTLS && !req.secure) { let trust = req.app.get('trust proxy fn'); let host = req.get('X-Forwarded-Host'); if (!host || !trust(req.connection.remoteAddress, 0)) { host = req.get('Host'); } res.redirect(self._container.redirectCode, 'https://' + host + req.originalUrl); } else { return app.call(this, req, res, next); } }; } }
JavaScript
class KernelListener { /** * Register all of the data collectors at compile time * @param {Object} event The event object * @param {Function} next The function to invoke on the next event listener in the series * @returns {void} */ onKernelCompile(event, next) { const { container } = event; // constantly monitor the server process const stat = container.get('profiler.stat'); stat.startMonitoring(stat.DELAY_IDLE); // find all the tagged data-collectors const tags = container.getTagsByName('profiler.data_collector'); // if we have no tagged data-collectors, move on if (!tags || tags.length === 0) { next(); return; } // sort the tags by priority container.get('conga.ioc.tag.sorter').sortByPriority(tags); // save the collector tags so we can fetch the services on demand // we do it this way so that the services can live in different scopes collectorTags = tags; next(); } /** * When the request is finished, stop the request from being profiled * @param event * @param next */ onResponse(event, next) { // processing is done in the background next(); const { container, request, error, redirect, status } = event; if (!container.get('profiler').isEnabled(request)) { return; } let response = Object.create(event.response); response.error = error; response.redirect = redirect; response.eventStatus = status; // get all the collectors in the current (request) scope (also includes global) let collectors = collectorTags.map(tag => container.get(tag.getServiceId())); container.get('profiler.request').stopRequest(request, response, collectors) .catch(err => console.error(err.stack || err)); } }
JavaScript
class canvasPad { constructor(x, y) { this.x = x this.y = y this.lastColor = rColor() this.nextColor = rColor() this.elapsed = 0 this.width = 50 this.lerpTime = 3000 } render(delta) { if (this.elapsed > this.lerpTime) { this.elapsed = 0 this.newColor() } fill(lerpColor(this.lastColor, this.nextColor, (this.elapsed / this.lerpTime))) rect(this.x, this.y, this.width, this.width) this.elapsed += delta } newColor() { this.lastColor = this.nextColor this.nextColor = rColor() this.lerpTime = rInt(6000,900) } }
JavaScript
class realPad extends canvasPad { constructor(a) { super(0, 0) this.address = a this.lerpTime = 100 } render(delta) { if (this.elapsed > this.lerpTime) { this.elapsed = 0 this.newColor() } let lc = lerpColor(this.lastColor, this.nextColor, (this.elapsed / this.lerpTime)) let payload = [11, this.address] payload.push(floor(red(lc)/8)) payload.push(floor(green(lc)/8)) payload.push(floor(blue(lc)/8)) device.sendCommand(payload) this.elapsed += delta } newColor() { this.lastColor = this.nextColor this.nextColor = rColor() this.lerpTime = rInt(4000,125) } }
JavaScript
class SomfyRtsRemoteAccessory { /** * Constructor of the class SomfyRtsRemoteAccessory * * @constructor * @param {Object} log - The Homebridge log * @param {Object} config - The Homebridge config data filtered for this item */ constructor(log, config) { this.log = log; if (!config || !config.name || !config.id) { throw new Error(`Invalid or missing configuration.`); } this.config = config; this.emitter = new RpiGpioRts(log, config); // Delay to reset the switch after being pressed this.delay = 500; this.buttons = ['Up', 'Down', 'My']; if (this.config.prog === true) this.buttons.push('Prog'); // Create an object such as {'Up': false, 'Down': false, ...} this.states = this.buttons.reduce((acc, cur) => { acc[cur] = false; return acc; }, {}); this.switchServices = {}; this.buttons.forEach(button => { this.switchServices[button] = new Service.Switch(`${this.config.name} ${button}`, button); this.switchServices[button] .getCharacteristic(Characteristic.On) .on('get', this.getOn.bind(this, button)) .on('set', this.setOn.bind(this, button)); }); this.log.debug(`Initialized accessory`); } /** * Getter for the 'On' characteristic of the 'Switch' service * * @method getOn * @param {Function} callback - A callback function from Homebridge * @param {String} button - 'Up', 'Down', 'My', 'Prog' */ getOn(button, callback) { this.log.debug(`Function getOn called for button ${button}`); const value = this.states[button]; callback(null, value); } /** * Setter for the 'On' characteristic of the 'Switch' service * * @method setOn * @param {Object} value - The value for the characteristic * @param {Function} callback - A callback function from Homebridge * @param {String} button - 'Up', 'Down', 'My', 'Prog' */ setOn(button, value, callback) { this.log.debug(`Function setOn called for button ${button} with value ${value}`); this.states[button] = value; if (value === true) { this.emitter.sendCommand(button); this.resetSwitchWithTimeout(button); } callback(null); } /** * Reset the switch to false to simulate a stateless behavior * * @method resetSwitchWithTimeout * @param {String} button - 'Up', 'Down', 'My', 'Prog' */ resetSwitchWithTimeout(button) { this.log.debug(`Function resetSwitchWithTimeout called for button ${button}`); setTimeout(function() { this.switchServices[button].setCharacteristic(Characteristic.On, false); }.bind(this), this.delay); } /** * Mandatory method for Homebridge * Return a list of services provided by this accessory * * @method getServices * @return {Array} - An array containing the services */ getServices() { this.log.debug(`Function getServices called`); return Object.values(this.switchServices); } }
JavaScript
class Automat { /** * @constructor * @param {Cell[]} elements - Initialized cells * @param {Room} room - Room object to use */ constructor(elements, room) { this.elements = new Set(); /** @private */ this.room = room /** @private */ this.fill(elements); } /** * @function * @name Automat.fill * @param {Cell[]} cells - The cells we deal with? * @todo Only 2D is currently supported */ fill(cells) { var rows = this.room.findTriangle(cells.length); let i = 0; // This is WTF. Apparently there's no useful array iterator (such as .next) without prototyping. Well. // TODO: OUTSOURCE THIS FUNCTIONALITY for (var x = rows[0]; x > 0; x--) { for (var y = rows[1]; y > 0; y--) { if (y > x ) continue; let coordinate = [x, y]; // needs a placeholder variable since weakly shared keys are garbaged otherwise this.room.push(coordinate, cells[i]); this.elements.add(coordinate); i++; } } }; /** * Loops over all elements in the room * This is used for living costs * @function * @name Automat.loop */ loop() { let self = this; this.elements.forEach(function(element) { self.room.apply(element, function(cell) { cell.live(); }); }); } }
JavaScript
class MenuBarItem { buildAttrs(attrs) { const elemAttrs = { class: "cursor-pointer", title: attrs.title }; if ("href" in attrs) { elemAttrs["href"] = attrs.href; } else if ("handler" in attrs) { elemAttrs["onclick"] = attrs.handler; } return elemAttrs; } view({ attrs }) { return m("li", m("a", this.buildAttrs(attrs), attrs.icon)); } }
JavaScript
class Docq { /** * @constructor * @param {string} html target html string * @param {string} query like document.querySelector * @param {string} type (outer|inner|text) */ constructor(html = '', query = '', type = 'outer') { this.dom = new JSDOM(html); this.query = query; this.type = type; } /** * run this.source * @return {string} output */ run() { const element = this.dom.window.document.querySelector(this.query); if ('inner' === this.type) { return element.innerHTML; } else if ('text' === this.type) { return element.textContent; } else if ('value' === this.type) { return element.getAttribute('value'); } return element.outerHTML; } }
JavaScript
class NodeS7Error extends Error { /** * Encapsulates an error, whether caused from a return code from the PLC or * internally in the library, identified by a code for it and an optional info * about the cause of the error * * @param {number|string} code the error code. numeric codes are from PLC responses, string codes are generated internally * @param {string} message the error message * @param {object} [info] Object containing additional info about the causes of the error. May not be always available */ constructor(code, message, info) { super(message); /** @type {number|string} */ this.code = code; /** @type {object} */ this.info = info; } }
JavaScript
class AreaAudience extends ChannelAudience { getBroadcastTargets() { if (!this.sender.room) { return []; } const { area } = this.sender.room; return area.getBroadcastTargets().filter((target) => target !== this.sender); } }
JavaScript
class Toolbox extends Component { renderModeRadio = (mode_key) => { var mode = MODE[mode_key]; var tt = MODE_TOOLTIPS[mode_key]; // TODO: Really when we get a change to state.verse, we should see if // the new verse is custom && mode is color_title, and if so, we should // automatically switch to a different mode. But bleh. var disabled = (mode === MODE.color_title && (!this.props.verse || !this.props.verse.title)); var divCname = disabled ? "radio-inline disabled" : "radio-inline"; return ( <label title={tt} key={mode} className={divCname}> <input type="radio" disabled={disabled} checked={this.props.mode === mode} value={mode} onChange={(e) => { this.props.onStateChange({mode: e.target.value}) }} name="mode" /> {mode} </label> ); } renderSingletonRadios = () => { var singstop = [this.props.ignoreSingletons, this.props.ignore_stopwords]; var modes = [ {label: 'show all', ss: [false, false]}, {label: 'ignore all', ss: [true, false]}, {label: 'ignore stopwords', ss: [false, true], tt: 'Show single-word matches, unless they\'re common words like "the" or "and"'}, ]; var radios = []; for (let mode of modes) { radios.push(( <label className="radio-inline" key={mode.label} title={mode.tt}> <input type="radio" checked={singstop[0] === mode.ss[0] && singstop[1] === mode.ss[1]} value={mode.ss} onChange={(e) => { this.props.onStateChange({ignore_singletons: mode.ss[0], ignore_stopwords: mode.ss[1]}); }} /> {mode.label} </label> )); } return ( <fieldset> <legend title="How to treat individual squares floating off the main diagonal"> Single-word matches </legend> {radios} </fieldset> ); } renderMobileCheckbox = () => { return ( <label className="checkbox-inline" title="(Janky) UI intended for small screens" > <input type="checkbox" checked={this.props.mobile} onChange={(e) => { this.props.onStateChange({mobile: e.target.checked}); }} /> Mobile mode </label> ); } renderSave = () => { if (!this.props.mobile && this.props.verse && config.exportSVGEnabled && this.props.exportSVG) { return ( <button className="btn" onClick={this.props.exportSVG} title="Save matrix as SVG file" > <span className="glyphicon glyphicon-save" /> </button> ); } } renderPermalink = () => { if (this.props.mobile || !(this.props.verse && this.props.verse.isCustom() && !this.props.verse.isBlank())) { return; } var perma = this.props.verse.get_permalink(this.props.router); if (perma) { return ( <label className="form-inline"> Permalink: <input type="text" readOnly={true} value={perma} /> <button id="perma" className="btn" data-clipboard-text={perma}> <span className="glyphicon glyphicon-copy" title="copy" /> </button> </label> ); } else { return ( <button className="btn" onClick={this.props.onShare} title="Generate a shareable permalink for this song" > Permalink </button> ); } } render() { var moderadios = Object.keys(MODE).map(this.renderModeRadio); var kls = this.props.mobile ? "" : "form-horizontal"; kls += ' toolbox'; kls = 'form-horizontal toolbox'; //kls = 'row toolbox'; var radioKls = 'col-xs-12 col-md-6 col-lg-4'; return ( <div className={kls}> <div className={radioKls}> <fieldset> <legend> Color Mode </legend> {moderadios} </fieldset> </div> <div className={radioKls}> {this.renderSingletonRadios()} </div> <div className='col-xs-5 col-md-4 col-lg-2'> {this.renderMobileCheckbox()} </div> <div className='col-xs-3 col-md-2 col-lg-1'> {this.renderSave()} </div> <div className='col-xs-8 col-md-6'> {this.renderPermalink()} </div> </div> ); } }
JavaScript
class FullscreenModel extends base_1.DOMWidgetModel { defaults() { return _.extend(base_1.DOMWidgetModel.prototype.defaults(), { _model_name: "FullscreenModel", _model_module: "fullscreen-js-widgets", _model_module_version: __webpack_require__(7).version, _view_name: "FullscreenView", _view_module: "fullscreen-js-widgets", _view_module_version: __webpack_require__(7).version }); } }
JavaScript
class Project { constructor(options) { options._type = 'project'; return new Item(options); } }
JavaScript
class Account extends React.Component { render() { const { data } = this.props if (!isAuthenticated()) { login() return <p>Redirecting to login...</p> } const user = getProfile() return ( <> <Router> <HomeAccount path="/account" user={user} /> </Router> <Layout location={this.props.location}> <p>This is going to be a protected route.</p> </Layout> </> ) } }
JavaScript
class chromeSerial { constructor(defaultUI=true, parentId='serialmenu', streamMonitorId="serialmonitor") { this.displayPorts = []; this.defaultUI = defaultUI; this.encodedBuffer = ""; this.connectionId = -1; this.recordData = false; this.recorded = []; this.monitoring = false; this.newSamples = 0; this.monitorSamples = 10000; //Max 10000 samples visible in stream monitor by default this.monitorData = []; this.monitorIdx = 0; if (typeof chrome.serial !== 'undefined' && chrome.serial !== null) { if(defaultUI == true) { this.setupSelect(parentId); } this.setupSerial(); } else { console.log("ERROR: Cannot locate chrome.serial."); } } setupSelect(parentId) { var displayOptions = document.createElement('select'); //Element ready to be appended displayOptions.setAttribute('id','serialports') var frag = document.createDocumentFragment(); frag.appendChild(displayOptions); document.getElementById(parentId).innerHTML = '<button id="refreshSerial">Get</button><button id="connectSerial">Set</button>'; document.getElementById(parentId).appendChild(frag); document.getElementById('refreshSerial').onclick = () => { this.setupSerial(); } document.getElementById('connectSerial').onclick = () => { if(this.connectionId != -1 ) {this.connectSelected(false)}; // Disconnect previous this.connectSelected(true, document.getElementById('serialports').value); } } setupMonitor(parentId) { if(this.monitorData.length > this.monitorSamples){ this.monitorData.splice(0, this.monitorData.length - this.monitorSamples); } var div = document.createElement('div'); div.setAttribute('id','streamMonitor'); this.monitorData.forEach((item,idx)=>{ div.innerHTML += '<div id='+this.monitorIdx+'>'+item+'</div>'; this.monitorIdx++; }); this.newSamples = 0; var frag = document.createDocumentFragment(); frag.appendChild(div); document.getElementById(parentId).appendChild(frag); var monitorAnim = () => { if(this.newSamples > 0){ if(this.monitorData.length > this.monitorSamples){ //Remove old samples if over the limit for(var i = this.monitorIdx - this.monitorSamples - (this.monitorData.length - this.monitorSamples); i > this.monitorIdx - this.monitorSamples; i++){ document.getElementById(i).remove(); } this.monitorData.splice(0, this.monitorData.length - this.monitorSamples); } //Load new samples for(var i = 0; i < newSamples; i++) { var newdiv = document.createElement('div'); newdiv.innerHTML = '<div id="'+this.monitorIdx+'">'+this.monitorData[this.monitorData.length - 1 - i]+'</div>'; var frag = document.createDocumentFragment(); frag.appendChild(newdiv); document.getElementById(parentId).appendChild(frag); this.monitorIdx++; var elem = document.getElementById('streamMonitor'); elem.scrollTop = elem.scrollHeight; } setTimeout(requestAnimationFrame(monitorAnim),15); } } requestAnimationFrame(monitorAnim); } onGetDevices = (ports) => { document.getElementById('serialports').innerHTML = ''; var paths = []; for (var i = 0; i < ports.length; i++) { console.log(ports[i].path); } ports.forEach((port) => { var displayName = port["displayName"] + "(" + port.path + ")"; console.log("displayName " + displayName); if (!displayName) displayName = port.path; paths.push({'option':displayName, 'value':port.path}); console.log(this.defaultUI); if(this.defaultUI == true) { var newOption = document.createElement("option"); newOption.text = displayName; newOption.value = port.path; console.log('option', newOption); document.getElementById('serialports').appendChild(newOption); } }); this.displayPorts = paths; } onReceive = (receiveInfo) => { //console.log("onReceive"); //if (receiveInfo.connectionId !== this.connectionId) { // console.log("ERR: Receive ID:", receiveInfo.connectionId); // return; //} var bufView = new Uint8Array(receiveInfo.data); var encodedString = String.fromCharCode.apply(null, bufView); this.encodedBuffer += decodeURIComponent(escape(encodedString)); //console.log(this.encodedBuffer.length); var index; while ((index = this.encodedBuffer.indexOf('\n')) >= 0) { var line = this.encodedBuffer.substr(0, index + 1); if(this.recordData == true) { this.recorded.push(line); } if(this.monitoring = true){ this.newSamples++; this.monitorData.push(line); } this.onReadLine(line); this.encodedBuffer = this.encodedBuffer.substr(index + 1); } } onReceiveError(errorInfo) { console.log("onReceiveError"); if (errorInfo.connectionId === this.connectionId) { console.log("Error from ID:", errorInfo.connectionId) this.onError.dispatch(errorInfo.error); console.log("Error: " + errorInfo.error); } } finalCallback() { //Customize this one for the front end integration after the device is successfully connected. console.log("USB device Ready!") } onConnectComplete = (connectionInfo) => { this.connectionId = connectionInfo.connectionId; console.log("Connected! ID:", this.connectionId); chrome.serial.onReceive.addListener(this.onReceive); chrome.serial.onReceiveError.addListener(this.onReceiveError); this.finalCallback() } sendMessage(msg) { msg+="\n"; if (typeof chrome.serial !== 'undefined' && chrome.serial !== null) { if (this.connectionId > -1) { var encodedString = unescape(encodeURIComponent(msg)); var bytes = new Uint8Array(encodedString.length); for (var i = 0; i < encodedString.length; ++i) { bytes[i] = encodedString.charCodeAt(i); } chrome.serial.send(this.connectionId, bytes.buffer, this.onSendCallback); console.log("Send message:", msg); } else { console.log("Device is disconnected!"); } } } onSendCallback(sendInfo) { console.log("sendInfo", sendInfo); } onReadLine(line) { console.log(line); } connectSelected(connect=true, devicePath='') { //Set connect to false to disconnect if ((connect == true) && (devicePath != '')) { console.log("Connecting", devicePath); chrome.serial.connect(devicePath, {bitrate: 115200}, this.onConnectComplete); } else { console.log("Disconnect" + devicePath); if (this.connectionId < 0) { console.log("connectionId", this.connectionId); return; } this.encodedBuffer = ""; chrome.serial.onReceive.removeListener(this.onReceive); chrome.serial.onReceiveError.removeListener(this.onReceiveError); chrome.serial.flush(this.connectionId, function () { console.log("chrome.serial.flush", this.connectionId); }); chrome.serial.disconnect(this.connectionId, function () { console.log("chrome.serial.disconnect", this.connectionId); }); } } setupSerial() { chrome.serial.getDevices(this.onGetDevices); } saveCsv(data=this.recorded, name=new Date().toISOString(),delimiter="|",header="Header\n"){ var csvDat = header; data.forEach((line) => { csvDat += line.split(delimiter).join(",")+"\n"; }); var hiddenElement = document.createElement('a'); hiddenElement.href = "data:text/csv;charset=utf-8," + encodeURI(csvDat); hiddenElement.target = "_blank"; if(name != ""){ hiddenElement.download = name+".csv"; } else{ hiddenElement.download = new Date().toISOString()+".csv"; } hiddenElement.click(); } openFile(delimiter=",") { var input = document.createElement('input'); input.type = 'file'; input.onchange = e => { this.csvDat = []; var file = e.target.files[0]; var reader = new FileReader(); reader.readAsText(file); reader.onload = event => { var tempcsvData = event.target.result; var tempcsvArr = tempcsvData.split("\n"); tempcsvArr.pop(); tempcsvArr.forEach((row,i) => { if(i==0){ var temp = row.split(delimiter); } else{ var temp = row.split(delimiter); this.csvDat.push(temp); } }); this.onOpen(); } input.value = ''; } input.click(); } onOpen() { // Customize this function in your init script, access data with ex. console.log(serialMonitor.csvDat), where var serialMonitor = new chromeSerial(defaultUI=false) alert("CSV Opened!"); } }
JavaScript
class QuestItemRegistry { /** Returns the existing item keys */ get items() { return Object.keys(this.itemDefinitions); } constructor() { this.itemDefinitions = {}; // key-collection of QuestItemDefinition this.itemCombinations = []; // array of { defA: QuestItemDefinition, defB: QuestItemDefinition, defResult: QuestItemDefinition } } /** Creates the definition of an object identified by key. * The properties are data shared between all instances of the given item (ie: labels, mesh, textures, ...) */ createDefinition(key, properties = {}) { if (this.itemDefinitions[key]) throw new Error(`The item definition '${key}' already exists`); this.itemDefinitions[key] = new QuestItemDefinition(key, properties); return this; } /** Makes possible the combination of two objects to build a third one */ createCombination(keyA, keyB, keyResult) { const defA = this.itemDefinitions[keyA]; const defB = this.itemDefinitions[keyB]; const defResult = this.itemDefinitions[keyResult]; // item validation if (!defA) throw new Error(`Unknown item '${keyA}'`); if (!defB) throw new Error(`Unknown item '${keyB}'`); if (!defResult) throw new Error(`Unknown item '${keyResult}'`); // check the pre-existents combinations if (this.getCombination(keyA, keyB)) throw new Error(`The combination between '${keyA}' and '${keyB}' already exist`); defResult.registerCombination(defA, defB); this.itemCombinations.push({ defA, defB, defResult}) return this; } /** Returns the combination between two objects, or undefined */ getCombination(keyA, keyB) { for (const combi of this.itemCombinations) { if ((keyA === combi.defA.key && keyB === combi.defB.key) || (keyA === combi.defB.key && keyB === combi.defA.key)) { return combi.defResult.key; } } return undefined; } /** Returns all objects whom the given object can be combined with */ getCombinations(key) { return this.itemCombinations.reduce((search, current) => { if (key === current.defA.key || key === current.defB.key) { search.push({ other: key === current.defA.key ? current.defB.key : current.defA.key, result: current.defResult.key }); } return search; }, []); } /** Return a value telling whether a combiation exist between two objects */ areCombinable(keyA, keyB) { return this.getCombination(keyA, keyB) !== undefined; } /** Tell whether an object is combinable with another */ isCombinable(key) { const item = this.itemDefinitions[key]; if (!item) throw new Error(`Unknown item '${key}'`); return item.isCombinable; } /** Tell whether this object is made by tow objects */ isCombination(key) { const item = this.itemDefinitions[key]; if (!item) throw new Error(`Unknown item '${key}'`); return item.isCombination; } /** Returns a value indicating whether an item exists */ itemExists(key) { return this.itemDefinitions.hasOwnProperty(key); } /** Returns the materials needed to build an item */ getMaterials(key) { const materials = this.itemDefinitions[key].madeFrom; return materials ? [ materials[0].key, materials[1].key ] : null; } /** Returns the properties registered for the given item type */ getProperties(key) { const item = this.itemDefinitions[key]; if (!item) throw new Error(`Unknown item '${key}'`); return item.properties; } }
JavaScript
class Boiler{ constructor(init_temp = INIT_SETTING_TEMP_SENSOR){ this.temp_reading = init_temp this.boiler_state = BOILER_ON_STATE } sleep(milliseconds) { const date = Date.now(); let currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); } _calc_settle_time(temp_delta){ return TEMP_STABILITY_TIME*temp_delta/Math.abs(ROOM_TEMPERATURE-INIT_SETTING_TEMP_SENSOR) } _regulate_temperature(temp_delta) { console.log(`current temp:${this.temp_reading} and temp delta is:${temp_delta}`) if (temp_delta > TEMP_STABILITY_DIFF) { this.boiler_state = BOILER_ON_STATE this.temp_reading += temp_delta } else { this.boiler_state = BOILER_OFF_STATE console.log(`temperature diff:${temp_delta} is less than min tolerance:${TEMP_STABILITY_DIFF}`) console.log(`switching off boiler`) } console.log(`setting temp to:${this.temp_reading}`) var sleep_time=this._calc_settle_time(temp_delta) this.sleep(sleep_time) console.log(`waited for ${sleep_time} and now returning set temperature:${this.temp_reading} `) return this.temp_reading } main(valve_open_level) { let t_delta = 0 if (valve_open_level == 100) { t_delta = UPPER_TEMP_DIFF_LIMIT } else { t_delta = (UPPER_TEMP_DIFF_LIMIT - LOWER_TEMP_DIFF_LIMIT)*valve_open_level/100 } if (t_delta < TEMP_STABILITY_DIFF) { console.log('reached stable temperature. Quitting') process.exit(1) } return this._regulate_temperature(t_delta) } }
JavaScript
class Disconnected /** implements firebase.database.OnDisconnect */ { cancel(onComplete) { return Promise.resolve(); } remove(onComplete) { return Promise.resolve(); } set(value, onComplete) { return Promise.resolve(); } setWithPriority(value, priority, onComplete) { return Promise.resolve(); } update(values, onComplete) { return Promise.resolve(); } }
JavaScript
class Knight extends Piece { /** * Destinations that a knight can move to from a square on a board. * @param {Square} square - The square the knight is on. * @param {GameState} gameState - The game state. * @return {SquareSet} */ destinations(square, gameState) { return gameState.squares.notOrthogonalOrDiagonal(square).atRange(square,2).unoccupiedOrOccupiedByOpponent(this.playerNumber); } }
JavaScript
class FenwickTree { constructor(length) { /** @private */ this._list = new Array(length + 1); /** @private */ this._list.fill(0); /** @private */ this._length = this._list.length; } /** * Get size of Fenwick Tree * @return {Number} Size of Fenwick Tree * @public */ get size() { return this._length - 1; } /** * Builds Fenwick Tree * @param {Array} array Array elements to be used to build the tree * @return {None} * @public */ buildTree(array) { if (!Array.isArray(array)) { throw new Error('Array needs to be passed in order to build the tree'); } for (let i = 0; i < this._length; i += 1) { this.updateTree(i, array[i]); } } /** * Check if tree is empty * @return {Boolean} Returns true if empty else false * @public */ isEmpty() { return (this._length - 1) === 0; } /** * Gets prefix sum of the array using the tree * @param {Number} index Index till which sum needs to be calculated * @return {Number} Prefix sum * @public */ getSum(index) { if (index + 1 >= (this._length)) { throw new RangeError('Index out of bound'); } let sum = 0; index += 1; while (index > 0) { sum += this._list[index]; index -= (index & (-index)); } return sum; } /** * Updates the tree with adding element to given index * @param {Number} index Index of element to be updated * @param {Number} element Element to be added * @return {None} * @public */ updateTree(index, element) { index += 1; while (index <= this._length) { this._list[index] += element; index += (index & (-index)); } } /** * Calculates range sum from given index to given index * @param {Number} left Left index * @param {Number} right Right index * @return {Number} Range sum * @public */ rangeSum(left, right) { if (left > right) { [left, right] = [right, left]; } return this.getSum(right) - this.getSum(left - 1); } }
JavaScript
class Path { /** * @return {string} */ static sep() { return '/'; } /** * @return {string} */ static root() { return '/'; } /** * @return {string} */ static delimiter() { return ':'; } /** * @param {*} path * @return {Array} */ static split(path) { if (!path.startsWith('/')) { console.error('Invalid absolute path.'); } return ['/'].concat(path.substr(1).split(this.sep())); } /** * @param {string} workingDirectory * @param {string} path * @return {string} */ static resolve(workingDirectory = '/', path) { if (path.startsWith('/')) { return path; } return workingDirectory + path.replace('./', '/'); } /** * Returns the closest matching path, if any. * @param {string} path * @param {array} paths * @return {string} */ static closest(path, paths) { if (paths.includes(path)) { return path; } let searchResult = path.lastIndexOf('/'); let searchPath = path.substring(0, searchResult); while (searchResult > 0) { if (paths.includes(searchPath)) { return searchPath; } else { searchResult = searchPath.lastIndexOf('/'); searchPath = searchPath.substring(0, searchResult); } } return ''; } /** * Returns directory name of the path. * @param {string} path * @return {string} */ static dirname(path) { if (path.lastIndexOf('/') <= 0) { return '/'; } return path.substring(0, path.lastIndexOf('/')); } /** * Returns last portion of the path. * @param {string} path * @return {string} */ static basename(path) { return path.substring(path.lastIndexOf('/') + 1); } /** * Returns parent directory name of the path. * @param {string} path * @return {string} */ static parentDirname(path) { return this.basename(this.dirname(path)); } /** * @param {string} path * @param {Object} obj * @return {Object} */ static findPathInObject(path, obj) { if (path.lastIndexOf('/') <= 0 && path in obj) { return obj[path] || null; } const objectPath = this.split(path); const pathLength = objectPath.length; let result = obj; for (let i = 0; i < pathLength; i++) { if (objectPath[i] in result) { result = result[objectPath[i]]; } else { return null; } } return result; } /** * @param {...any} segments * @return {string} */ static join(...segments) { if (!segments) { return ''; } const path = []; segments.forEach((fragment) => { if (fragment.includes(this.sep())) { Array.prototype.push.apply(path, fragment.split(this.sep())); } else { path.push(fragment); } }); return this.normalize(path.join(this.sep())); } /** * @param {string} path * @return {string} */ static normalize(path = '') { const pathSegments = path.split(this.sep()); const startsWithRoot = path.startsWith(this.root()); if (startsWithRoot) { pathSegments.splice(0, 1); } pathSegments.forEach((fragment, index) => { if (fragment == '..') { pathSegments[index] = ''; if (pathSegments[index - 1] !== undefined) { pathSegments[index - 1] = ''; } } }); const normalizedPathSegments = []; pathSegments.forEach((fragment) => { if (fragment) { normalizedPathSegments.push(fragment); } }); const result = normalizedPathSegments.join(this.sep()); if (startsWithRoot) { return this.root() + result; } return result; } /** * @param {string} path * @return {boolean} */ static isAbsolute(path = '') { if (path.startsWith(this.root())) { return true; } return false; } }
JavaScript
class AdminUsersView extends Component { constructor(props) { super(props); this.state = { dialogActive: false, editId: -1 }; } /** * Toggle the visiblity of the edit Dialog. */ toggleDialog = (id) => { var newDialogActive = !this.state.dialogActive; this.setState({ dialogActive: newDialogActive, editId: id }); } /** * Generates all TableCells of TableRow. * @return generated cells */ generateRowCells = () => { var cells = []; for(let i = 0; i < this.props.users.length; i++) { if(this.props.users[i] !== "") cells.push( <TableRow> <TableCell numeric> {this.props.users[i].id} </TableCell> <TableCell> {this.props.users[i].username} </TableCell> <TableCell> {this.props.users[i].name} </TableCell> <TableCell> {this.props.users[i].email} </TableCell> <TableCell> {this.props.users[i].phone} </TableCell> <TableCell> {this.props.users[i].faculty.name} </TableCell> <TableCell> {this.props.users[i].company.name} </TableCell> <TableCell> {this.props.users[i].roles} </TableCell> <TableCell> {this.props.users[i].lastLogin} </TableCell> <TableCell> {this.props.users[i].tags} </TableCell> <TableCell> <table> <tbody> <tr> <td> <EditButton toggleHandler={() => this.toggleDialog(i)} /> </td> <td> <DeleteButton deleteHandler={() => this.props.deleteHandler(i)} /> </td> </tr> </tbody> </table> </TableCell> </TableRow> ); } return cells; } getEditUser = () => { if(this.state.editId === -1) return -1; else return this.props.users[this.state.editId]; } handleUserEdit = (user) => { this.props.editHandler(this.state.editId, user); } render() { return( <div className="Users-admin"> <Table multiSelectable={false} selectable={false}> <TableHead> <TableCell numeric> ID </TableCell> <TableCell> Username </TableCell> <TableCell> Name </TableCell> <TableCell> Email </TableCell> <TableCell> Phone </TableCell> <TableCell> Faculty </TableCell> <TableCell> Company </TableCell> <TableCell> Role </TableCell> <TableCell> Last login </TableCell> <TableCell> Tags </TableCell> <TableCell> Actions </TableCell> </TableHead> {this.generateRowCells()} </Table> <UserEditDialog active={this.state.dialogActive} user={this.getEditUser()} editHandler={(user) => this.props.editHandler(this.state.editId, user)} toggleHandler={() => this.toggleDialog(-1)} /> </div> ); } }
JavaScript
class ProtocolHelper { /** * Given a channel address and a message Id returns the corresponding L1 tangle index that * allows to locate the L1 Ledger message * * @param channelAddress The channel address * @param messageId The message identifier * * @returns the tangle index encoded in hexadecimal chars */ static getIndexL1(channelAddress, messageId) { const addr = new node_1.Address(node_1.ChannelAddress.parse(channelAddress), node_1.MsgId.parse(messageId)); return addr.toMsgIndexHex(); } /** * Given an anchoring channel and an anchored message ID returns the * corresponding message ID at L1 on the Ledger * * @param channel The anchoring channel * @param messageId The Streams Message Id * * @returns the Layer 1 message ID */ static getMsgIdL1(channel, messageId) { return __awaiter(this, void 0, void 0, function* () { const addr = new node_1.Address(node_1.ChannelAddress.parse(channel.channelAddr), node_1.MsgId.parse(messageId)); const index = addr.toMsgIndex(); const client = new iota_js_1.SingleNodeClient(channel.node); const messagesResponse = yield client.messagesFind(index); if (messagesResponse.count === 0) { throw new anchoringChannelError_1.AnchoringChannelError(anchoringChannelErrorNames_1.AnchoringChannelErrorNames.L1_MSG_NOT_FOUND, "L1 message has not been found"); } return messagesResponse.messageIds[0]; }); } }
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:"#697777", textDecoration: "none", padding:"5px", margin: "20px" } if(this.state.menuOpen==true){ return( <nav style={navStyleMobile}> <Link style={linkStyle} to="/">Homepage</Link> <Link style={linkStyle} to="/portfolio">Portfolio</Link> <Link style={linkStyle} to="/blog">Blog</Link> <Link style={linkStyle} to="/contact">Contact</Link> </nav> ) } } render() { const headerStyle={ background:"#c0c3c6", }; const navStyle={ display:"flex", flexDirection:"row" } const linkStyle={ color:"#697777", textDecoration: "none", padding:"5px", margin: "20px" }; return ( <header style={headerStyle}> <Responsive minDeviceWidth={1024}> <nav style={navStyle}> <Link style={linkStyle} to="/">Homepage</Link> <Link style={linkStyle} to="/portfolio">Portfolio</Link> <Link style={linkStyle} to="/blog">Blog</Link> <Link style={linkStyle} to="/contact">Contact</Link> </nav> </Responsive> <Responsive maxDeviceWidth={1023}> <a href="#" onClick={() => this.handleMenu()}><img src="http://h4z.it/Image/fafe3b_burger.png"/></a> {this.renderMenu()} </Responsive> </header> ); } }
JavaScript
class Configuration { init(parameters = {}) { this.dpr = 1; this.app = {}; // for arbitrary use in end application } from_json(json) { } }
JavaScript
class AutoResponder extends React.PureComponent { /* Global and thread specific input values and selections. */ state = { gRegex: "", gRes: "", gSelect: [], regex: "", res: "", select: [], open: false, }; styles = { tabs: { position: "relative", top: -2, // cover the chatbot tab slider }, tabContent: { paddingTop: 16, paddingRight: 0, }, toggle: { padding: "32px 16px 16px 16px", }, container: { position: "relative", }, }; copyToClipboard(intlMap, index) { /* Create a fake textarea to copy the text from. */ let textArea = document.createElement("textarea"); /* hide the textarea as far as possible in case of an error before or while deleting it. */ textArea.classList.add("hidden"); /* Insert and select the text that shall be copied. */ textArea.value = Object.keys(intlMap)[index]; document.body.appendChild(textArea); textArea.select(); /* Make sure the process worked before showing a snackbar info. */ try { if (document.queryCommandSupported("copy")) { const success = document.execCommand("copy"); if (success) this.setState({open: true}); } } finally { /* Remove the fake textarea. */ document.body.removeChild(textArea); } } render() { const {formatMessage} = this.props.intl; const dictHeight = this.props.height - 120; const tableHeight = this.props.height - 48; const globalMsg = formatMessage(this.props.isGlobalEnabled ? messages.enabled : messages.disabled); const localMsg = formatMessage(this.props.isLocalEnabled ? messages.enabled : messages.disabled); const styles = { tabItem: { backgroundColor: this.props.muiTheme.drawer.color }, }; return ( <div style={this.styles.container}> <Snackbar open={this.state.open} message={formatMessage(messages.copied)} autoHideDuration={2000} onRequestClose={() => this.setState({open: false})} style={{left: "50%"}} /> <Tabs style={this.styles.tabs} tabItemContainerStyle={styles.tabItem}> <Tab label={formatMessage(messages.local)}> <Toggle toggled={this.props.isLocalEnabled} onToggle={this.props.setResponderState.bind(this, false)} label={localMsg + formatMessage(messages.local)} style={this.styles.toggle} /> {this.props.isLocalEnabled ? <Dictionary id="regexLocal" entries={this.props.localDict} keyLabel={formatMessage(messages.regex)} valueLabel={formatMessage(messages.res)} onSelect={(keys) => this.setState({select: keys})} onDelete={this.props.delRegex.bind(this, false, this.state.select)} onKeyChange={(evt, val) => this.setState({regex: val})} onValueChange={(evt, val) => this.setState({res: val})} onAdd={this.props.addRegex.bind(this, false, this.state.regex, this.state.res)} height={dictHeight} /> : null} </Tab> <Tab label={formatMessage(messages.global)}> <Toggle toggled={this.props.isGlobalEnabled} onToggle={this.props.setResponderState.bind(this, true)} label={globalMsg + formatMessage(messages.global)} style={this.styles.toggle} /> {this.props.isGlobalEnabled ? <Dictionary id="regexLocal" style={styles} entries={this.props.globalDict} keyLabel={formatMessage(messages.regex)} valueLabel={formatMessage(messages.res)} onSelect={(keys) => this.setState({gSelect: keys})} onDelete={this.props.delRegex.bind(this, true, this.state.gSelect)} onKeyChange={(evt, val) => this.setState({gRegex: val})} onValueChange={(evt, val) => this.setState({gRes: val})} onAdd={this.props.addRegex.bind(this, true, this.state.gRegex, this.state.gRes)} height={dictHeight} /> : null} </Tab> <Tab label={formatMessage(messages.examples)}> <IntlTable intlMap={examplesTable} keyHeader={formatMessage(messages.regex)} valueHeader={formatMessage(messages.explanation)} onSelectRow={this.copyToClipboard.bind(this)} footer={formatMessage(messages.copyHint)} height={tableHeight} /> </Tab> <Tab label={formatMessage(messages.help)}> <IntlTable intlMap={helpTable} keyHeader={formatMessage(messages.regex)} valueHeader={formatMessage(messages.explanation)} onSelectRow={this.copyToClipboard.bind(this)} footer={formatMessage(messages.caseHint)} height={tableHeight} keyColStyle={{width: "10rem"}} /> </Tab> </Tabs> </div> ); } }
JavaScript
class AntPath extends FeatureGroup { //this[Layers.main], this references are required for layer & polyline interfaces [Layers.main] = []; [Layers.pulse] = []; _map = null; /** * polyOptions to apply for each L.Path * @typedef {Object<string,any>} polyOptions * @property {polyline} use - L.pathType to use for construct the path * @property {number} weight - weight of the path stroke * @property {Renderer} renderer - render used to render polylayers * @property {number} opacity - opacity of the stroke * @property {string} color - hex color */ /** * default polyOption that will be merged on each L.Path * @type {polyOptions} * @memberof AntPath */ _defaultPolyOptions = { use: polyline, weight: 5, renderer: canvas({ pane: "overlayPane" }), opacity: 0.5, color: "#0000FF" }; /** * dashedOptions to apply on the dashed animated path * @typedef {Object<string,any>} dashedOptions * @property {Renderer} renderer - render used to render dashedlayers * @property {number} delay - speed of animation * @property {string} dashArray - dashed pattern * @property {string} color - hex color * @property {boolean} paused - state of animation * @property {boolean} reverse - direction of animation */ /** * default dashedOptions that will be merged with the input * @type {dashedOptions} * @memberof AntPath */ _defaultdashedOptions = { renderer: canvas({ pane: "overlayPane" }), delay: 400, dashArray: "10,20", color: "#FFFFFF", paused: false, reverse: false }; /** * polyDef to construct a Path * @typedef {Object<string,any>} polyDef * @property {latLngs|latlngs[]} path - single polyline latlngs or Multilatlngs * @property {polyOptions} [polyOptions=_defaultOptions] - Path options to apply */ /** * polyArray * @type {Array<polyDef>} * @memberof AntPath */ _polyArrayInput; /** * dashedOptions * @type {dashedOptions} * @memberof AntPath */ _dashedOptionsInput = {}; /** * Creates an instance of AntPath. * @constructor * @param {Array<polyDef>} polyArray - The Array of {@link polyDef} to be draw. * @param {dashedOptions} [commondashedOptions=_defaultdashedOptions] - The {@link dashedOptions} of dashed animated path (Common to all the Paths) * @memberof AntPath */ constructor(polyArray, commondashedOptions) { super(); //* this.options get feeded by Util.setOptions this._polyArrayInput = polyArray.map(p => { return { ...p, polyOptions: { ...this._defaultPolyOptions, ...p.polyOptions } }; }); this._dashedOptionsInput = { ...this._defaultdashedOptions, ...commondashedOptions }; // no need to call this twice this._mount(); } _mount() { //!One Layer per Color (~one per polyArray)(renderer by same canvas) + One layer per dashed polyType (all the dashed animated in same canvas together) const dic = {}; this._polyArrayInput.forEach(i => { const l = i.polyOptions.use(i.path, i.polyOptions); this.addLayer(l); this[Layers.main].push(l); //* gather the diferent paths by L.path type const ply = i.polyOptions.use.toString(); if (!dic[ply]) { //if not initialized dic[ply] = { path: [], use: i.polyOptions.use }; } dic[ply].path.push(i.path); // Test if it do nice on combination of single and multi line }); // Add the dashed layers for (const key in dic) { if (dic.hasOwnProperty(key)) { const dl = dic[key].use(dic[key].path, this._dashedOptionsInput); this.addLayer(dl); this[Layers.pulse].push(dl); } } } /** * Last Animation frame * @type {number} * @memberof AntPath */ _frameRef; //! since movecanvas is arrow could acces resume reverse? also maybe redraw only the this[Layers.pulse].foreach? _moveCanvas = () => { const dashDef = this._dashedOptionsInput.dashArray.split(","); let totalDashDef = 0; dashDef.forEach(n => totalDashDef + parseInt(n, 10)); // If at start of animation the dashedOffset = total DashDef, reset the animation (Or is mod = 0) if (this._dashedOptionsInput.renderer._ctx.lineDashOffset % totalDashDef === 0) { this._dashedOptionsInput.renderer._ctx.lineDashOffset = 0; } let speed = (1 / this._dashedOptionsInput.delay) * 1000; if (this._dashedOptionsInput.reverse) { speed = speed * -1; } this._dashedOptionsInput.renderer._ctx.lineDashOffset += speed; //not sure if non canvas renders have _ctx this[Layers.pulse].forEach(l => l.redraw()); this._frameRef = window.requestAnimationFrame(this._moveCanvas); }; // AntPath leaflet events onAdd(map) { this._map = map; //this._map.on("zoomend", this._calculateAnimationSpeed, this); this._mount(); //* requestAnimation have to be called ONCE for all the Canvas for performance... this._frameRef = window.requestAnimationFrame(this._moveCanvas); return this; } onRemove(layer) { if (this._map) { //this._map.off("zoomend", this._calculateAnimationSpeed, this); this._map = null; } if (layer) { this[Layers.pulse].forEach(l => layer.removeLayer(l)); this[Layers.main].forEach(l => layer.removeLayer(l)); } //* Maybe cancel requestAnimationFrame ? https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame window.cancelAnimationFrame(this._frameRef); return this; } // AntPath public Interface pause() { if (!this._dashedOptionsInput.paused) { this._dashedOptionsInput.paused = true; window.cancelAnimationFrame(this._frameRef); } } resume() { if (this._dashedOptionsInput.paused) { this._dashedOptionsInput.paused = false; this._frameRef = window.requestAnimationFrame(this._moveCanvas); } } //Feature Group methods overwriting bringToFront() { this[Layers.main].forEach(l => l.bringToFront()); this[Layers.pulse].forEach(l => l.bringToFront()); return this; } bringToBack() { this[Layers.pulse].forEach(l => l.bringToBack()); this[Layers.main].forEach(l => l.bringToBack()); return this; } //Layer interface removeFrom(layer) { if (layer && layer.hasLayer(this)) { layer.removeLayer(this); } return this; } //Polyline interface /** * reStyle the common dash options * @param {dashedOptions} options * @memberof AntPath */ setStyle(options) { // Todo compare new options to old and implement logic (at the end for redraw, inExample for color & dasharray => this[Layers.pulse].setStyle()) console.log(options); return this; } redraw() { this[Layers.main].forEach(l => l.redraw()); this[Layers.pulse].forEach(l => l.redraw()); return this; } getLatLngs() { return this[Layers.pulse].map(l => l.getLatLngs()); } getBounds() { return this[Layers.pulse][0].getBounds(); } toGeoJSON() { return this[Layers.pulse][0].toGeoJSON(); } }
JavaScript
class Body { constructor(name, constants) { this.name = name; this.constants = constants; this.primary = null; this.secondaries = []; this.orbit = new StationaryOrbit(this); this.maneuvers = []; } isPlanet() { return false; } isShip() { return false; } get position() { return this.orbit.stats.position; } get velocity() { return this.orbit.stats.velocity; } get mass() { return this.constants.mass; } hasSecondary(body) { return this.secondaries.some(s => s === body); } addSecondary(body) { if (this.hasSecondary(body)) { return false; } this.secondaries.push(body); return true; } removeSecondary(body) { const idx = this.secondaries.findIndex(s => s === body); if (idx < 0) { return false; } this.secondaries.splice(idx, 1); return true; } relativePosition(body = this.primary) { if (!body) { return this.position; } if (!this.position || !body.position) { return undefined; } return new Vector3().subVectors(this.position, body.position); } }
JavaScript
class BeforeReadyHandler{ constructor(_target,enabled,Flac){ this._target=_target; this.Flac=Flac; this._enabled=false; this._isWaitOnReady=false; this._enabled=enabled; } get isWaitOnReady(){ return this._isWaitOnReady; } get enabled(){ return this._enabled; } set enabled(val){ if(!val && this._enabled){ this._reset(); } this._enabled=this.enabled; } handleBeforeReady(funcName,args){ if(!this.Flac.isReady() && this.enabled){ if(!this._isWaitOnReady){ this._beforeReadyCache=this._beforeReadyCache || []; this._onReadyHandler=(_evt) => { if(this._beforeReadyCache){ this._beforeReadyCache.forEach(entry => this._target[entry.func].apply(this._target,entry.args)); } this._reset(); }; this.Flac.on('ready',this._onReadyHandler); this._isWaitOnReady=true; } if(this._beforeReadyCache){ this._beforeReadyCache.push({func:funcName,args:Array.from(args)}); return true; } } return false; } _reset(){ if(this._beforeReadyCache){ this._beforeReadyCache= void (0); } if(this._onReadyHandler){ this.Flac.off('ready',this._onReadyHandler); this._onReadyHandler= void (0); } this._isWaitOnReady=false; } }
JavaScript
class CompressorDecompressor { /** * * Constructs a `CompressorDecompressor` with the specified options * and listener, and a pellet class to be returned always by * `PelletFactory` getters. * * @param compressionOptions {Map} If not null, a `Map` specifying * which facilities of XQK should be enabled; * the `Map` must contain three * entries whose keys are * `bpaEnabled` (true to enable * bilateral pseudo-awareness), * `inliningEnabled` (true to * inline PUMP and UNPUMP directives), and * `spjEnabled` (true to enable * subjective packet-jettisoning (SPJ)). If * null, `#defaultCompressionOptions` * are used (which enables all three of these, * which is standard usage). * @param progressListener {ProgressListener} If not null, a `ProgressListener` * implementation instance. If null, a * `BasicProgressListener` is used. * @param pelletFactoryOverrideConstructor {function} Constructor of the concrete * `CompressionPellet` subclass, instances * of which will always be returned by * `PelletFactory`. This value may * be null; if so, the factory will return the * most appropriate type of pellet for given * conditions. */ constructor(compressionOptions = defaultCompressionOptions, progressListener = defaultProgressListener, pelletFactoryOverrideConstructor = null) { new ArgValidator(arguments).validate([ {name: 'compressionOptions', reqd: false, type: 'object', instOf: Map}, {name: 'progressListener', reqd: false, type: 'object', instOf: ProgressListener}, {name: 'pelletFactoryOverrideConstructor', reqd: false, type: 'function'} ]); /** * A `Map` containing exactly three keys: * `inliningEnabled` (true to inline all PUMP/UNPUMP directives), * `spjEnabled` (true to enable subjective packet-jettisoning (SPJ)), * and `bpaEnabled` (true to enable bilateral pseudo-awareness). If * null or not specified, `#defaultCompressionOptions` are used. * * @see #defaultCompressionOptions */ this.compressionOptions = compressionOptions; /** * Instance of a `ProgressListener` implementation. If null or * unspecified, `#defaultProgressListener` is used (an instance of * `BasicProgressListener`). * * @see ProgressListener * @see BasicProgressListener * @see #defaultProgressListener */ this.progressListener = progressListener; /** * If set, the `Class`, a concrete `CompressionPellet` subclass, * of all pellet instences to be returned by calls to `PelletFactory` * getter methods. If null or not specified, the factory will return instances * of optimal `CompressionPellet` subclasses based on current * conditions. While most users will want to rely on the factory to provide * appropriate pellets, XQK provides several `CompressionPellet` * subclasses which may suit user needs as well: `FatwarePellet` (often * used when strict Fullerton compatibility is required), * `OraclePelletAdapter`, `SandersonPseudoPellet` (the 'traditional' * R5/C pellet implementation), `TreePellet` (a lightweight alternative to * the Sanderson implementation often used for mobile implementations), and * `PseudoPellet` (an isotope-free tree-pellet with its own CCR). * * @see CompressionPellet * @see FatwarePellet * @see OraclePelletAdapter * @see SandersonPseudoPellet * @see PseudoPellet * @see TreePellet */ this.pelletFactoryOverrideConstructor = pelletFactoryOverrideConstructor; /** * Instance of a `TypeProvider` implementation to be used in prestructing * the invulnerability matrix which enfolds the actual payload of any XQK * archive. If not specified, this is a `LivermoreTypeProvider`, which * will meet most needs. (RS-443 compliance issues are generally the reason * other providers are used.) * * @see LivermoreTypeProvider */ this.provider = new LivermoreTypeProvider(); /** * Instance of an `Extrospector` implementation which will reside in the * archive's hard-shell contingency shield. (For version 5.x, this value is an * `ArchiveExtrospector` instance with a 5ms look/lookback, and cannot be * changed via this API.) */ this.extrospector = new ArchiveExtrospector(DEFAULT_EXTROSPECTOR_LOOK_MILLIS_INTERVAL); } /** * Compress or decompress a `File` to another `File`. * Because of a quirk of XQK's implementation, source and destination files * generally must be in the same directory. Both the XQK desktop application and * the command-line parser enforce this (by not allowing users to choose a * destination file (the exception is Fairchild client-terminals, which always * write all output of any kind to the `_OUT` subdirectory of the * user's home directory - the XQK GUI accounts for this). However, users of * this API may wish to write output to a file in a different directory from the * one where the source file is found, which is why this method allows for a * destination file to be specified. * * @param compress True to compress, false to decompress * @param inFilename The file to be compressed or decompressed (if the latter, the * filename should end with '.xqk'). * @param outFilename The destination file to which the source file should be * compressed or decompressed (if the former, the filename is * expected to end with '.xqk'). * @throws Error If either of the files don't exist, aren't readable, * aren't writeable, etc. */ execute(compress, inFilename, outFilename) { new ArgValidator(arguments).validate([ {name: 'compress', reqd: true, type: 'object', instOf: TrimodeBoolean}, {name: 'inFilename', reqd: true, type: 'string'}, {name: 'outFilename', reqd: true, type: 'string'} ]); this.progressListener.notifyStartOperation(compress.booleanValue()); const pumperDumper = PumperDumperFactory.getPumperDumper(opsCount++, this.progressListener); this.extrospector.setCompressionOptions(this.compressionOptions); this.extrospector.setProgressListener(this.progressListener); const matrix = new InvulnerabilityMatrix(provider, 1024, new TrimodeBoolean(true), pelletFactoryOverrideConstructor); this.progressListener.outPrintln('Hard-shell matrix created using provider "' + provider.getClass() + '"'); this.progressListener.outPrintln(''); this.progressListener.outPrintln('Initializing...'); this.progressListener.outPrintln((compress.booleanValue() ? 'Compressing ' : 'Decompressing ') + inFilename + '...'); const inStream = fs.createReadStream(inFilename); const outStream = fs.createWriteStream(outFilename); let hardShellStart = HardshellOverlayInterjector.generateEnfolder(DEFAULT_PELLET_CT, OBA_BYTES, matrix, this.progressListener, this.extrospector, this.pelletFactoryOverrideConstructor, compress); const hardShellLength = hardShellStart.length; let inFileSize = inFilename.length(); inFileSize += (compress.booleanValue() ? hardShellLength : (hardShellLength * -1)); inFileSize = (inFileSize <= 0 ? 1 : inFileSize); this.progressListener.notifyExpectedTotalBytes(inFileSize); // Don't cannibalize default values; if not needed, we'll still give them to Nigel at runtime: let inliningEnabled = true; let spjEnabled = true; let bpaEnabled = true; let flagsReadError = false; let flagsArr = '00000000'.split(''); try { let byteCounter = 0; let cumulativeByteCounter = 0; if (compress.booleanValue()) { inliningEnabled = this.compressionOptions.get('inliningEnabled'); spjEnabled = this.compressionOptions.get('spjEnabled'); bpaEnabled = compressionOptions.get('bpaEnabled'); this.extrospector.setDoInlinedPumpDirectives(new TrimodeBoolean(inliningEnabled)); this.extrospector.setEnableSPJ(new TrimodeBoolean(spjEnabled)); this.extrospector.setEnableBilateralPseudoAwareness(new TrimodeBoolean(bpaEnabled)); if (bpaEnabled) { extrospector.setBilateralPseudoAwarenessAgressionFactor( BilateralPseudoAwarenessAggressionFactor.REALLY_REALLY_PUMPED); } hardShellStart = pumperDumper.pump(hardShellStart); let hardShell = `${hardShellStart}`; hardShell = hardShell.substring(0, hardShell.indexOf('00000000')) + (inliningEnabled ? '1' : '0') + (spjEnabled ? '1' : '0') + (bpaEnabled ? '1' : '0') + '00000' + hardShell.substring(hardShell.indexOf('00000000') + 8); outStream.write(StringUtils.stringToByteArray(hardShell)); } else { let flags; try { const bytes = []; pumperDumper.unpump(bytes); inStream.mark(Integer.MAX_VALUE); const bytesRead = inStream.read(bytes); if (bytesRead !== 28) { throw new Error('less than 28 bytes in hard-shell.'); } flags = `${bytes}`; flags = flags.substring(flags.indexOf('/') + 1, flags.indexOf('/') + 9); if (flags.length() !== 8) { throw new Error('invalid flags.'); } } catch (e) { flags = '--------'; flagsReadError = true; } finally { inStream.reset(); } flagsArr = flags.split(''); const targetSkippedCount = hardShellStart.length; let skippedCount = inStream.skip(targetSkippedCount); let tries = 0; try { while (targetSkippedCount > skippedCount) { if (tries > targetSkippedCount) { throw new Error('Bad very input'); } let skipped = inStream.skip(targetSkippedCount - skippedCount); skippedCount += skipped; tries++; } } catch (e) { throw new Error('Missing or corrupted LOCKB substrate; unable to decompress compressed archive ' + 'contents.'); } } let b = inStream.read(); const start = System.currentTimeMillis(); while (b !== -1) { outStream.write(b); b = inStream.read(); byteCounter++; cumulativeByteCounter++; this.progressListener.notifyBytesWritten(cumulativeByteCounter); if (byteCounter > TICK_LENGTH_BYTES) { this.progressListener.progressTick(); byteCounter = 0; } } this.progressListener.outPrintln(''); let srcFileLength = cumulativeByteCounter; let destFileLength = cumulativeByteCounter; if (compress.booleanValue()) { destFileLength += hardShellLength; } else { srcFileLength += hardShellLength; } let compressionRatio = (compress.booleanValue() ? destFileLength : srcFileLength) / (!compress.booleanValue() ? destFileLength : srcFileLength); let durationSeconds = ((System.currentTimeMillis() - start) / 1000); if (durationSeconds === 0) { durationSeconds += 0.001; } const bytesPerSecond = (cumulativeByteCounter / durationSeconds); this.progressListener.outPrintln(''); this.progressListener.outPrintln((compress.booleanValue() ? 'Compressed ' : 'Decompressed ') + formatBytes(cumulativeByteCounter, NUMBER_FORMAT) + ' in ' + NUMBER_FORMAT.format(durationSeconds) + ' seconds (' + formatBytes(bytesPerSecond, NUMBER_FORMAT) + ' per second)'); this.progressListener.outPrintln(''); this.progressListener.outPrintln( LOG_PREFIX + 'Compressed file size is ' + PERCENT_FORMAT.format(compressionRatio) + ' of ' + 'uncompressed file size, not including effects of c27y-related operations which may increase or ' + 'decrease file size depending on archive contents, transport route, recipient\'s Hansen ' + 'fingerprint, etc.).'); if (compress.booleanValue()) { this.progressListener.outPrintln(''); this.progressListener.outPrintln('Note: a hard-shell PI contingency overlay enfolds this ' + 'archive, adding ' + hardShellLength + ' bytes to its size. The overlay consists of a ' + 'protective Livermore-style invulnerability matrix; the on-board algorithm; and ' + DEFAULT_PELLET_CT + ' bytes of R5/C compression pellets deployed into a Bourne-Harman ' + 'pseudoscaffold.'); if (!inliningEnabled) { this.progressListener.outPrintln(''); this.progressListener.outPrintln('WARN: PUMP/UNPUMP directives have not been inlined; ' + 'pumper-dumper reciprocity thus cannot be guaranteed, and will almost certainly not occur ' + 'during a Closson-Thorpe sub-event. Consider setting "Always inline PUMP/UNPUMP ' + 'directives" (or, from the command line, set the "inline-pdd" flag), especially if ' + 'CTSE\'s are expected.'); } else { this.progressListener.outPrintln(''); progressListener .outPrintln('All PUMP/UNPUMP directives have been inlined; recipient clients should assume ' + 'pumper-dumper ' + 'reciprocity in the transport layer (including Willis derivatives).'); } if (!spjEnabled) { // nothing; PPR-37 particulates... } else { this.progressListener.outPrintln(''); progressListener .outPrintln('SPJ is enabled; the OBA may subjectively discard packets en route based on Hansen ' + 'analysis.'); } if (!bpaEnabled) { progressListener .outPrintln('WARN: PUMP/UNPUMP directives have not been inlined! Pumper-dumper reciprocity ' + 'thus cannot be guaranteed, and will almost certainly not occur during a Closson-Thorpe ' + 'sub-event. Consider setting "Always inline PUMP/UNPUMP directives", especially if ' + 'CTS\'s are expected.'); } else { this.progressListener.outPrintln(''); progressListener .outPrintln('Bilateral Pseudoawareness capability has been embedded in this archive\'s ' + 'fatware substrate; packet-racing will occur during transport if metapath-twinned with ' + 'an identical file.'); } } else { // EXTRACTING: if (!flagsReadError) { inliningEnabled = flagsArr[IDX_INLINING].equals('1'); spjEnabled = flagsArr[IDX_SPJ].equals('1'); bpaEnabled = flagsArr[IDX_BS].equals('1'); if (!inliningEnabled) { this.progressListener.outPrintln(''); progressListener .outPrintln('WARN: PUMP/UNPUMP directives appear not to have been inlined; if a CTSE ' + 'occurred during ' + 'transport, the archive is likely corrupted.'); } if (spjEnabled) { this.progressListener.outPrintln(''); this.progressListener.outPrintln('SPJ was enabled for this archive; 0 bytes were ' + 'subjectively determined not to be of ' + 'interest and were thus jettisoned, based on the recipient\'s Hansen manifest.'); } if (bpaEnabled) { this.progressListener.outPrintln(''); progressListener .outPrintln('Bilateral Pseudoawareness was enabled in this archive\'s fatware, but no ' + 'metapath-twinned archive ' + 'was present, so no PR occurred.'); } else { this.progressListener.outPrintln(''); progressListener .outPrintln('Bilateral Pseudoawareness was not enabled in this archive\'s fatware, ' + 'so no PR occurred.'); } } else { this.progressListener.outPrintln(''); progressListener .outPrintln('WARN: Could not read CTD flags (SPJ, BS, directive-inlining, etc.); archive ' + 'may be corrupted.'); } } this.progressListener.outPrintln(''); progressListener .outPrintln(LOG_PREFIX + (compress.booleanValue() ? 'Compress' : 'Decompress') + ' success: output file is ' + outFilename.getAbsolutePath()); } this.progressListener.notifyOperationComplete(outFilename); } static get DEFAULT_EXTROSPECTOR_LOOK_MILLIS_INTERVAL() { return DEFAULT_EXTROSPECTOR_LOOK_MILLIS_INTERVAL; }; static get DEFAULT_PELLET_CT() { return DEFAULT_PELLET_CT; }; static get TICK_LENGTH_BYTES() { return TICK_LENGTH_BYTES; }; static get defaultCompressionOptions() { return defaultCompressionOptions; }; static get defaultProgressListener() { return defaultProgressListener; }; static _formatBytes(totalBytes, numberFormat) { new ArgValidator(arguments).validate([ {name: 'totalBytes', reqd: true, type: 'number'}, {name: 'numberFormat', reqd: true, type: 'object'} ]); if (totalBytes < KB_BYTES) { return numberFormat.format(totalBytes) + ' bytes'; } if (totalBytes < MB_BYTES) { return numberFormat.format(totalBytes / KB_BYTES) + ' KB'; } if (totalBytes < GB_BYTES) { return numberFormat.format(totalBytes / MB_BYTES) + ' MB'; } if (totalBytes < TB_BYTES) { return numberFormat.format(totalBytes / GB_BYTES) + ' GB'; } if (totalBytes < PB_BYTES) { return numberFormat.format(totalBytes / TB_BYTES) + ' TB'; } return numberFormat.format(totalBytes / PB_BYTES) + ' PB'; } }
JavaScript
class OverviewTabView extends React.Component { static getTabObject(props) { return { 'tab' : ( <React.Fragment> <i className="icon icon-eye-dropper fas icon-fw"/> <span>Overview</span> </React.Fragment> ), 'key' : 'overview', 'content' : <OverviewTabView {...props} /> }; } constructor(props) { super(props); this.state = { newestVariantSample: null, newVSLoading: true, }; this.loadNewestNotesFromVS = this.loadNewestNotesFromVS.bind(this); } componentDidMount() { this.loadNewestNotesFromVS(); } /** * Currently this only pulls updated notes; may be possible to expand to also pull newest fields for annotation * space, however due to the infrequency of anticipated updates to those fields, this hasn't been implemented. */ loadNewestNotesFromVS() { const { context: { uuid = null } = {} } = this.props; // Do AJAX request to get new variant sample w/only relevant notes // Using embed API instead of datastore=database in order to prevent gene-list related slowdown and to target request const vsFetchCallback = (resp) => { const [ { "@id": atID = null } = {} ] = resp; console.log("pulling new notes from VS", resp); if (!atID) { Alerts.queue({ title: "Error: Some information may be out of date.", style: "warning", message: "Could not retrieve the most recent version of this variant and its notes due to a server error. Please try refreshing the page in a few minutes." }); } this.setState({ "newVSLoading": false, "newestVariantSample": resp[0] }); }; ajax.load( '/embed', vsFetchCallback, "POST", vsFetchCallback, JSON.stringify({ "ids": [ uuid ], "fields": [ "@id", "institution.@id", "project.@id", // Variant and Gene Notes "gene_notes.@id", "gene_notes.status", "gene_notes.approved_by.display_title", "gene_notes.note_text", "gene_notes.approved_date", "gene_notes.last_modified.date_modified", "gene_notes.last_modified.modified_by.display_title", "gene_notes.principles_allowed", "variant_notes.@id", "variant_notes.status", "variant_notes.approved_by.display_title", "variant_notes.note_text", "variant_notes.approved_date", "variant_notes.last_modified.date_modified", "variant_notes.last_modified.modified_by.display_title", "variant_notes.principles_allowed", // Interpretation Notes "interpretation.@id", "interpretation.status", "interpretation.note_text", "interpretation.conclusion", "interpretation.classification", "interpretation.acmg_rules_invoked", "interpretation.approved_date", "interpretation.approved_by.display_title", "interpretation.last_modified.date_modified", "interpretation.last_modified.modified_by.display_title", "interpretation.principles_allowed", // Discovery Notes "discovery_interpretation.@id", "discovery_interpretation.status", "discovery_interpretation.note_text", "discovery_interpretation.variant_candidacy", "discovery_interpretation.gene_candidacy", "discovery_interpretation.approved_date", "discovery_interpretation.approved_by.display_title", "discovery_interpretation.last_modified.date_modified", "discovery_interpretation.last_modified.modified_by.display_title", "discovery_interpretation.principles_allowed", ] }) ); } render() { const { newestVariantSample = null, newVSLoading } = this.state; return ( <div> <h3 className="tab-section-title container-wide"> Annotation Space </h3> <hr className="tab-section-title-horiz-divider"/> <div className="container-wide bg-light py-3 mh-inner-tab-height-full"> <VariantSampleOverview {...this.props} newContext={newestVariantSample} {...{ newVSLoading }} /> </div> </div> ); } }
JavaScript
class InexorTreeWsAPI { /** * Constructs the Inexor Tree REST API. */ constructor(applicationContext) { // The express router and app this.app = applicationContext.get('app'); this.router = applicationContext.get('router'); // The express websockets handler this.websockets = applicationContext.get('websockets'); // The Inexor Tree this.root = applicationContext.get('tree'); // The tree node which contains all instance nodes this.instancesNode = this.root.getOrCreateNode('instances'); // Returns the value of the tree node. this.app.ws('/ws/tree', this.handleRequest.bind(this)); // The web socket server this.wss = this.websockets.getWss('/ws/tree'); // Listen on the root node if any node has changed this.root.on('postSet', this.syncNode.bind(this)); // Listen on the root node if any node has changed this.root.on('add', this.addNode.bind(this)); } /** * Sets the dependencies from the application context. */ setDependencies() { /// The class logger this.log = this.applicationContext.get('logManager').getLogger('flex.server.api.v1.ws.InexorTreeWsAPI'); } /** * Get or set node values. */ handleRequest(ws, req) { ws.on('message', (message) => { try { let request = JSON.parse(message); let node = this.root.findNode(request.path); if (node != null) { if (node.isContainer) { ws.send(this.getMessage(syncStates.get, node)); } else { if (req.hasOwnProperty('value')) { let value = this.convert(node._datatype, request.value); if (value != null) { node.set(value); } } ws.send(this.getMessage(syncStates.set, node)); } } else { ws.send(JSON.stringify({ state: syncStates.error, path: request.path, message: 'Not found' })); } } catch (err) { this.log.error(err, util.format('Failed to process message: %s\n%s', err.message, message)); } }); } /** * Send tree node sync events to the web socket clients. */ syncNode({node: node}) { try { this.wss.clients.forEach((client) => { client.send(this.getMessage(syncStates.sync, node)); }); } catch (err) { this.log.error(err, util.format('Failed to send tree node sync event for %s: %s', node.getPath(), err.message)); } } /** * Send tree node add events to the web socket clients. */ addNode(node) { try { this.wss.clients.forEach((client) => { client.send(this.getMessage(syncStates.add, node)); }); } catch (err) { this.log.error(err, util.format('Failed to send tree node add event for %s: %s', node.getPath(), err.message)); } } getMessage(state, node) { return JSON.stringify({ state: state, datatype: node._datatype, path: node.getPath(), value: node.isContainer ? node.getChildNames : node.get() }); } /** * Converts an incoming string value to the target datatype. * TODO: move to tree utils */ convert(datatype, value) { if (typeof value == 'string') { switch (datatype) { case 'int32': case 'int64': case 'enum': return parseInt(value); case 'float': return parseFloat(value); case 'bool': return (value == 'true'); case 'string': return value; default: // timestamp, object, node, return null; } } else if (typeof value == 'number') { switch (datatype) { case 'int32': case 'int64': case 'enum': case 'float': return value; case 'bool': return value == 1 ? true : false; case 'string': return value.toString(); default: // timestamp, object, node, return null; } } else if (typeof value == 'boolean') { switch (datatype) { case 'int32': case 'int64': case 'enum': case 'float': return value ? 1 : 0; case 'bool': return value; case 'string': return value.toString(); default: // timestamp, object, node, return null; } } else { return null; } } }
JavaScript
class ChannelsTable extends BotTable { /** * This table's name. * @type {string} */ static get CHANNELS_TABLE_NAME() { return CHANNELS_TABLE_NAME; } /** * Gets the class representing a row in this collection. * @return {Object} the row class */ getRowClass() { return OrgChannel; } /** * Gets an instance of a class representing a row in this collection, based on the provided values * @param {Object} dbObj the raw object from DB * @return {Object} the row class' instance */ getRowInstance(dbObject) { return new OrgChannel(dbObject); } /** * Gets this collection's name. * @return {string} the table name */ getTableName() { return CHANNELS_TABLE_NAME; } }
JavaScript
class DefaultLookAndFeelFactory { /** * Get a SVG drawer for the specified element. * @param {GraphicalElement} element The element must be a subclass of graphical element. * @return {*} A SVG drawer for the specified element. */ getDrawerFor(element) { if(element instanceof Marker) { return new DefaultMarkerDrawer(); } else if (element instanceof Circle) { return new DefaultCircleDrawer(); } else if (element instanceof Ellipse) { return new DefaultEllipseDrawer(); } else if (element instanceof Rectangle) { return new DefaultRectangleDrawer(); } else if (element instanceof Diamond) { return new DefaultDiamondDrawer(); } else if (element instanceof Text) { return new DefaultTextDrawer(); } else if (element instanceof VerticalGroup) { return new DefaultVerticalGroupDrawer(); } else if (element instanceof Line) { return new DefaultLineDrawer(); } else if (element instanceof PolyLine) { return new DefaultPolyLineDrawer(); } else if (element instanceof Image) { return new DefaultImageDrawer(); } else if (element instanceof BoxVerticesDecorator) { return new DefaultBoxVerticesDecoratorDrawer(); } else { throw "No SVG drawer was found for the element."; } } }
JavaScript
class SessionService { constructor() { this.stateCacheKey = "zenkey_state"; this.nonceCacheKey = "zenkey_nonce"; this.codeVerifierCacheKey = "zenkey_code_verifier"; this.mccmncCacheKey = "zenkey_mccmnc"; this.authorizationCacheKey = "zenkey_authorize"; } clear(session) { try { delete session[this.stateCacheKey]; } catch (e) {} // eslint-disable-line no-empty try { delete session[this.nonceCacheKey]; } catch (e) {} // eslint-disable-line no-empty try { delete session[this.mccmncCacheKey]; } catch (e) {} // eslint-disable-line no-empty try { delete session[this.codeVerifierCacheKey]; } catch (e) {} // eslint-disable-line no-empty } setState(session, state) { session[this.stateCacheKey] = state; } getState(session) { if (!(this.stateCacheKey in session)) { return null; } return session[this.stateCacheKey]; } setNonce(session, nonce) { session[this.nonceCacheKey] = nonce; } getNonce(session) { if (!(this.nonceCacheKey in session)) { return null; } return session[this.nonceCacheKey]; } setCodeVerifier(session, codeVerifier) { session[this.codeVerifierCacheKey] = codeVerifier; } getCodeVerifier(session) { if (!(this.codeVerifierCacheKey in session)) { return null; } return session[this.codeVerifierCacheKey]; } setMCCMNC(session, mccmnc) { session[this.mccmncCacheKey] = mccmnc; } getMCCMNC(session) { if (!(this.mccmncCacheKey in session)) { return null; } return session[this.mccmncCacheKey]; } deleteAuthorizationDetails(session) { try { delete session[this.authorizationCacheKey]; } catch (e) {} // eslint-disable-line no-empty } setAuthorizationDetails(session, type, context, options = {}) { const value = { type, context, options }; session[this.authorizationCacheKey] = value; } getAuthorizationDetails(session) { if (!(this.authorizationCacheKey in session)) { return null; } return session[this.authorizationCacheKey]; } }
JavaScript
class BackboneTagService extends TagService { constructor(props) { super(props); this.model = props.model; } async save(rawTag) { let tag = createTag(rawTag); if (!tag.valid) { throw new Error("Invalid tag"); } // update model let tags = new Set(this.model.attributes.tags); tags.add(tag.text); tags = Array.from(tags); await this.model.save({ tags }); return tag; } async delete(rawTag) { let tag = createTag(rawTag); let tags = new Set(this.model.attributes.tags); tags.delete(tag.text); tags = Array.from(tags); await this.model.save({ tags }); return tag; } }
JavaScript
class MinMax { /** * Crates the interval, MinMax. * * @param {number} min The start value of the interval * @param {number} max The end value of the interval */ constructor(min, max) { this.min = min; this.max = max; } /** * Returns the size of the interval (length). * * @returns {number} The size */ size() { return this.max - this.min; } /** * Expand the MinMax with another MinMax. * * @param {MinMax} other The other interval */ add(other) { this.min = Math.min(this.min, other.min); this.max = Math.max(this.max, other.max); } /** * Returns a copy of the interval. * * @returns {MinMax} The copy */ get copy() { return new MinMax(this.min, this.max); } /** * Creates a bounding box of a set of numbers. * * @param {...number} points The numbers to get the interval from * @returns {MinMax} The created interval */ static fromPoints(...points) { const ret = new MinMax(0, 0); ret.min = Math.min(...points); ret.max = Math.max(...points); return ret; } }
JavaScript
class JsonResponsePromise { /** * Wraps a fetch promise to be handled as request's response whose body contains JSON. * * @param {Promise} promise - the promise resulting from the fetch to Thingworx. * @param {ServiceExecutionRequest|PropertyGetRequest} request - the request that created the * promise. */ constructor(promise, request) { this.promise = promise; this.request = request; } /** * Parses the response's json body of the fetch request. * * @returns {Promise} a promise resolving to the object resulting from the json parsing. * @throws {Error} if the request was not successful. */ async json() { const response = new ThingworxResponse(await this.promise, this.request); if (!response.ok) { throw await this.buildError(response); } return response.json(); } /* This method is to make this class a Thenable. The presence of this method allows this class to be used in conjunction with the await keyword without having to use the .json(), .val(), or .infoTable() methods. */ then(successCallback, failureCallback) { // The .defaultValue() is implemented in the subclasses. // It defines the default value to which this promise should resolve without needing to call the // .json(), .val(), or .infoTable() methods. return this.defaultValue().then(successCallback, failureCallback); } /* Implement catch promise method */ catch(failureCallback) { return this.defaultValue().catch(failureCallback); } /* Implement finally promise method */ finally(finallyCallback) { return this.promise.finally(finallyCallback); } /** * Checks if a value is an infotable. * * @param {*} value - value to be checked. * @returns {boolean} true if value is infotable, false otherwise. */ static isInfoTable(value) { return Utils.isObject(value) && Array.isArray(value.rows) && Utils.isObject(value.dataShape) && Utils.isObject(value.dataShape.fieldDefinitions); } /** * Prettifies the infotable by stringifying it to JSON and putting indentation. * * @param {object} infoTable - an infotable-shaped object. * @returns {string} - the string prettified version of the infotable. */ static prettify(infoTable) { return JSON.stringify(infoTable, undefined, 2); } /** * Converts a single value received from a Thingworx response JSON to a JavaScript value. * * @param {number|string|boolean|null} value - the value to be parsed * @param {string} baseType - the Thingworx base type of the value. * * @returns {*} the final value already converted */ static parseValue(value, baseType) { switch (baseType) { case 'DATETIME': return new Date(value); case 'INFOTABLE': return JsonResponsePromise.parseInfoTable(value); default: return value; } } /** * Converts all JSON values in the infotable to JavaScript values. * InfoTables are send through the network as JSONs, which in the end, they are just simple * strings. JSON.parse() converted those strings back to JavaScript values, but some values need * more conversion. In particular, if you stringify a Date and then parse it as a json, the result * will be a string. You still need to convert the string back to a real instance Date. This * method does exactly that. * Precondition: the infotable object must be valid. JsonResponsePromise.isInfoTable(infoTable) * must return true. * * @param {object} infoTable - the infotable whose values are to be parsed. * @returns {object} - the same object given as parameter, for ease of use. The parameter might * have been imperatively modified by this method. */ static parseInfoTable(infoTable) { const { fieldDefinitions } = infoTable.dataShape; const dateTimeFields = []; const infoTableFields = []; Object.entries(fieldDefinitions).forEach(([fieldName, fieldObj]) => { const { baseType } = fieldObj; if (baseType === 'DATETIME') { dateTimeFields.push(fieldName); } else if (baseType === 'INFOTABLE') { infoTableFields.push(fieldName); } }); infoTable.rows.forEach((row) => { dateTimeFields.forEach((dateTimeField) => { if (Utils.hasProp(row, dateTimeField) && row[dateTimeField] !== null) { row[dateTimeField] = new Date(row[dateTimeField]); } }); infoTableFields.forEach((infoTableField) => { if (Utils.hasProp(row, infoTableField) && row[infoTableField] !== null) { row[infoTableField] = JsonResponsePromise.parseInfoTable(row[infoTableField]); } }); }); return infoTable; } /** * Retrieves the rows of the infotable, dropping its datashape. * If one of its fields is also an infotable, recursively does the same operation on that field. * * @param {object} infoTable - the infotable for which to obtain its rows. * @returns {Array} - the rows of the infotable. */ static getInfoTableRows(infoTable) { const { rows } = infoTable; const { fieldDefinitions } = infoTable.dataShape; Object.entries(fieldDefinitions) .filter(([, fieldDefinition]) => fieldDefinition.baseType === 'INFOTABLE') .forEach(([fieldName]) => { rows.forEach((row) => { if (Utils.hasProp(row, fieldName) && row[fieldName] !== null) { row[fieldName] = JsonResponsePromise.getInfoTableRows(row[fieldName]); } }); }); return rows; } }
JavaScript
class Client { constructor({ clientId = null, secret = null, token = {}, logger = NULL_LOGGER, callback = async () => {}, username, password, timeout = 5000, apiBase = MYOB_BASE }) { this.apiBase = apiBase; this.token = token || {}; this.logger = logger; this.callback = callback; this.adapter = axios; this.username = username; this.password = password; this.clientId = clientId; this.secret = secret; this.timeout = timeout; this.callback = callback; this.instance = this.getInstance(false); } getInstance(root) { const headers = this.getHeaders(root); this.logger.info('Request Headers', headers); const instance = this.adapter.create({ baseURL: this.apiBase, timeout: this.timeout, responseType: 'json', headers: headers, }); rateLimit(instance, 5); if (this.clientId) { expiredToken(instance, this, 2); timeoutInterceptor(instance); } return instance; } getHeaders(root = false) { const headers = { 'x-myobapi-version': 'v2', 'User-Agent': `Ordermentum MYOB Client ${pack.version}`, }; if (this.clientId) { headers['x-myobapi-key'] = this.clientId; headers.Authorization = `Bearer ${this.token.access_token}`; } if (!root) { headers['x-myobapi-cftoken'] = this.getUserToken(); } return headers; } get authentication() { if (!this.clientId) { return null; } return authentication(this.clientId, this.secret, this.logger); } getCompanyFiles() { return this.getInstance(true) .get(this.apiBase) .then(response => response.data); } getInfo() { return this.getInstance(true) .get('/info') .then(response => response.data); } getUserToken() { return new Buffer(`${this.username}:${this.password}`) .toString('base64'); } get(...args) { return this.instance.get(...args) .then(r => r.data); } post(...args) { return this.instance.post(...args) .then(r => r.data); } patch(...args) { return this.instance.patch(...args) .then(r => r.data); } put(...args) { return this.instance.put(...args) .then(r => r.data); } delete(...args) { return this.instance.delete(...args) .then(r => r.data); } }
JavaScript
class Pagination { /** * @constructor * @memberof Pagination * @param {number|string} page * @param {number|string} limit */ constructor(page = 1, limit = 10) { this.page = parseInt(page, 10); this.limit = parseInt(limit, 10); } /** * @memberof Pagination * @param {number} page * @return {object} - an object that returns query metadata for the page */ getQueryMetadata() { return { limit: this.limit, offset: this.limit * (this.page - 1) }; } /** * @memberof Pagination * @param {array} totalItems * @param {string} baseUrl * @param {string} extraQuery * @return {object} - an object that returns page metadata */ getPageMetadata(totalItems, baseUrl, extraQuery) { const { page, limit } = this; const pages = Math.ceil(totalItems / limit); const prev = page <= 1 ? undefined : `${baseUrl}?${extraQuery ? `${extraQuery}&` : ''}page=${page - 1}&limit=${limit}`; const next = page >= pages ? undefined : `${baseUrl}?${extraQuery ? `${extraQuery}&` : ''}page=${page + 1}&limit=${limit}`; return { prev, next, pages, totalItems, }; } }
JavaScript
class UserAPI extends BaseAPI { constructor(httpClient) { super(httpClient) } /** * Logs the user into proxer.me! * @param {string} username - The name of the user * @param {string} password - The password of the user * @param {object} optionalValues - The optional params * @param {object} [optionalValues.secretkey] - The 2FA key (needed if the user has 2FA activated). */ async login(username, password, optionalValues = {}) { optionalValues.username = username optionalValues.password = password const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.LOGIN, optionalValues) return new LoginUser(data) } /** * Logs the currently logged in user out. */ async logout() { await this.httpClient.post(API_CLASS, API_FUNCTIONS.LOGOUT) } /** * Gathers information about a user via name or ID. * * If nothing is specified, the information about the logged in user is gathered. * @param {object} optionalValues - The optional params * @param {number} [optionalValues.uid] - The unique ID of the user * @param {string} [optionalValues.username] - The name of the user (ignored when uid is set) */ async userInfo(optionalValues = {}) { const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.USERINFO, optionalValues) return new User(data) } /** * Gathers the favorites (TopTen) of the user specified by ID or username. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @param {object} optionalValues - The optional params * @param {string} [optionalValues.kat] - The category of the favorites (anime / manga). Default: anime. * @param {boolean} [optionalValues.isH] - Should the results contain hentai? Default: false. */ async topTen(identifier, optionalValues = {}) { if (typeof identifier === "number") optionalValues.uid = identifier else optionalValues.username = identifier const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.TOP_TEN, optionalValues) const results = data.map(it => new TopTenItem(it)) return results } /** * Gathers a list of all anime / manga, the user has an entry from. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @param {object} optionalValues - The optional params * @param {string} [optionalValues.kat] - The category of the UserEntry content (anime / manga). Default: anime. * @param {number} [optionalValues.p] - The page of the entries list. Default: 0. * @param {number} [optionalValues.limit] - The amount of entries to load. Default: 100. * @param {string} [optionalValues.search] - Searches for this string in the name of the entries. * @param {string} [optionalValues.search_start] - Searches for this string in the beginning of the name of the entries. * @param {boolean} [optionalValues.isH] - Is hentai content allowed? * @param {string} [optionalValues.sort] - The way to sort the results. DEfault: Sort by state, then by name (ascending). * @param {string} [optionalValues.filter] - A filter to specify the view-status of the content. Default: No filter. * @returns {Promise<UserEntry[]>} */ async list(identifier, optionalValues = {}) { if (typeof identifier === "number") optionalValues.uid = identifier else optionalValues.username = identifier const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.LIST, optionalValues) const results = data.map(it => new UserEntry(it)) return results } /** * Gathers a list of comments of a user specified by ID or username. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @param {object} optionalValues - The optional params * @param {string} [optionalValues.kat] - The category of the content (anime / manga) this comment was written at. Default: both. * @param {number} [optionalValues.p] - The page of the comment list. Default: 0. * @param {number} [optionalValues.limit] - The amount of comments to load. Default: 25. * @param {string} [optionalValues.length] - The minimum amount of characters the comments should contain. Default: 300. * @returns {Promise<Comments[]>} */ async latestComments(identifier, optionalValues = {}) { if (typeof identifier === "number") optionalValues.uid = identifier else optionalValues.username = identifier const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.LATEST_COMMENTS, optionalValues) const results = data.map(it => new Comment(it)) return results } /** * Gathers a list of comments of a user specified by ID or username. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @param {object} optionalValues - The optional params * @param {string} [optionalValues.kat] - The category of the content (anime / manga) this comment was written at. Default: both. * @param {number} [optionalValues.p] - The page of the history list. Default: 0. * @param {number} [optionalValues.limit] - The amount of history entries to load. Default: 100. * @returns {Promise<History[]>} */ async history(identifier, optionalValues = {}) { if (typeof identifier === "number") optionalValues.uid = identifier else optionalValues.username = identifier const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.HISTORY, optionalValues) const results = data.map(it => new History(it)) return results } /** * Gather information about the friends of a user. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @returns {Promise<Friend[]>} */ async friends(identifier) { const body = {} if (typeof identifier === "number") body.uid = identifier else body.username = identifier const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.FRIENDS, body) const results = data.map(it => new Friend(it)) return results } /** * Gather data from the user about page. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @returns {Promise<UserAbout>} */ async about(identifier) { const body = {} if (typeof identifier === "number") body.uid = identifier else body.username = identifier const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.ABOUT, body) return new UserAbout(data) } /** * Requests a user login. This could either be done via the returned link or the notification. * @param {(string|number)} identifier - This is either the unique ID (number) or the username (string). * @param {string} code - A 100 characters long code used for identification * @param {string} appName - The name of the application * @returns {Promise<string>} */ async requestAuth(identifier, code, appName) { const body = { code: code, name: appName } if (typeof identifier === "number") body.uid = identifier else body.username = identifier await this.httpClient.post(API_CLASS, API_FUNCTIONS.REQUEST_AUTHENTIFICATION, body) return `proxer.me/auth?code=${code}&name=${appName}` } /** * Checks if the specified login request was successful. * @param {string} code - The at requestAuth() specified 100 characters long code. * @param {string} appName - The at requestAuth() specified name of the application * @returns {Promise<LoginUser>} */ async checkAuth(code, appName) { const body = { code: code, name: appName } const data = await this.httpClient.post(API_CLASS, API_FUNCTIONS.CHECK_AUTHENTIFICATION, body) return new LoginUser(data) } }
JavaScript
class Schedule { constructor(tasks, checkedVal) { this.tasks = tasks; this.checkedVal = checkedVal; } }
JavaScript
class UI { // Displays stored tasks static displaySchedule() { const tasks = DataHandling.tasksCheck(); // Checks if the task is completed or not tasks.forEach((task) => { if (task.checkedVal === false) { UI.addTaskToList(task); } else { UI.addTaskToListWithCheck(task); } }); } // Deletes task from UI static deleteTask(el) { if (el.classList.contains('delete')) { el.parentElement.parentElement.remove(); } } // Add tasks to UI static addTaskToList(task) { const para = document.querySelector('#schedule-table'); const div = document.createElement('div'); div.innerHTML = `<div class="col s2"><div class="button delete">X</div></div><div class="col s8">${task.tasks}</div><label><input type="checkbox" /><span></span></label>`; para.appendChild(div); } // Displays the task marked! static addTaskToListWithCheck(task) { const para = document.querySelector('#schedule-table'); const div = document.createElement('div'); div.innerHTML = `<div class="col s2"><div class="button delete">X</div></div><div class="col s8 checked">${task.tasks}</div><label><input type="checkbox" checked /><span></span></label>`; para.appendChild(div); } // Show error message static errorMessage(message) { M.toast({html: message}); } // Clears the field(s) of input static clearFields() { document.querySelector('#task').value = ''; } // Returns the current day name static currentDay() { let dow; switch (d) { case 0: dow = "Sunday"; break; case 1: dow = "Monday"; break; case 2: dow = "Tuesday"; break; case 3: dow = "Wednesday"; break; case 4: dow = "Thursday"; break; case 5: dow = "Friday"; break; case 6: dow = "Saturday"; break; default: break; } const header = document.querySelector(".dayHeader"); header.innerHTML = `${dow}`; } }
JavaScript
class DataHandling { // Checks if the stored day is the current day // if the stored values correspond to current day static tasksCheck() { let tasksList, taskObj, day_of_week; if (localStorage.getItem('day_of_week') === null) { localStorage.setItem('day_of_week', d); } else if(localStorage.getItem('day_of_week') != d) { localStorage.clear(); //clears local storage localStorage.setItem('day_of_week', d); } if (localStorage.getItem('tasksList') === null) { tasksList = []; for (taskObj in tasksObj) { let arr = tasksObj[taskObj]; if (arr.days.includes(d)) { var taskItem = new Schedule(arr.task, false); tasksList.push(taskItem); localStorage.setItem('tasksList', JSON.stringify(tasksList)); } } } else { tasksList = JSON.parse(localStorage.getItem('tasksList')); } return tasksList; } // Add tasks to app static addTasks(task) { const tasksList = DataHandling.tasksCheck(); tasksList.push(task); localStorage.setItem('tasksList', JSON.stringify(tasksList)); } // Removes a task from localStorage static storageRemoveTask(text) { const tasks = DataHandling.tasksCheck(); tasks.forEach((taskItem, index) => { if (taskItem.tasks === text) { tasks.splice(index, 1); } }); localStorage.setItem('tasksList', JSON.stringify(tasks)); } // Toggles checked class accordingly static toggleCheckClass(text, el) { const tasks = DataHandling.tasksCheck(); tasks.forEach((taskItem, index) => { if (taskItem.tasks === text) { // Toggles true or false if (taskItem.checkedVal === false) { taskItem.checkedVal = true; $(el).addClass('checked'); } else { taskItem.checkedVal = false; $(el).removeClass('checked'); } } }); localStorage.setItem('tasksList', JSON.stringify(tasks)); } // Checks the status of task static statusCheckClass(text, el) {} }
JavaScript
class FederationStatsPlugin { /** * * @param {FederationStatsPluginOptions} options */ constructor(options) { if (!options || !options.filename) { throw new Error("filename option is required."); } this._options = options; } /** * * @param {import("webpack").Compiler} compiler */ apply(compiler) { const federationPlugins = compiler.options.plugins && compiler.options.plugins.filter( (plugin) => plugin.constructor.name === "ModuleFederationPlugin" && plugin._options.exposes ); if (!federationPlugins || federationPlugins.length === 0) { console.error("No ModuleFederationPlugin(s) found."); return; } compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { compilation.hooks.processAssets.tapPromise( { name: PLUGIN_NAME, stage: compilation.constructor.PROCESS_ASSETS_STAGE_REPORT, }, async () => { const stats = compilation.getStats().toJson({}); const federatedModules = federationPlugins.map((federationPlugin) => getFederationStats(stats, federationPlugin) ); const sharedModules = getMainSharedModules(stats); const statsResult = { sharedModules, federatedModules, }; const statsJson = JSON.stringify(statsResult); const statsBuffer = Buffer.from(statsJson, "utf-8"); const statsSource = { source: () => statsBuffer, size: () => statsBuffer.length, }; const filename = this._options.filename; const asset = compilation.getAsset(filename); if (asset) { compilation.updateAsset(filename, statsSource); } else { compilation.emitAsset(filename, statsSource); } } ); }); } }
JavaScript
class FocalPersonsList extends Component { static propTypes = { loading: PropTypes.bool.isRequired, focalPeople: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string })) .isRequired, page: PropTypes.number.isRequired, total: PropTypes.number.isRequired, onEdit: PropTypes.func.isRequired, onFilter: PropTypes.func.isRequired, onNotify: PropTypes.func.isRequired, onShare: PropTypes.func.isRequired, onBulkShare: PropTypes.func.isRequired, }; state = { selectedFocalPeople: [], selectedPages: [], }; /** * @function * @name handleOnSelectFocalPerson * @description Handle select a single focalPerson action * * @param {object} focalPerson selected focalPerson object * * @version 0.1.0 * @since 0.1.0 */ handleOnSelectFocalPerson = focalPerson => { const { selectedFocalPeople } = this.state; this.setState({ selectedFocalPeople: concat([], selectedFocalPeople, focalPerson), }); }; /** * @function * @name handleSelectAll * @description Handle select all focalPeople actions from current page * * @version 0.1.0 * @since 0.1.0 */ handleSelectAll = () => { const { selectedFocalPeople, selectedPages } = this.state; const { focalPeople, page } = this.props; const selectedList = uniqBy( [...selectedFocalPeople, ...focalPeople], '_id' ); const pages = uniq([...selectedPages, page]); this.setState({ selectedFocalPeople: selectedList, selectedPages: pages, }); }; /** * @function * @name handleDeselectAll * @description Handle deselect all focalPeople in a current page * * @returns {undefined} undefined * * @version 0.1.0 * @since 0.1.0 */ handleDeselectAll = () => { const { focalPeople, page } = this.props; const { selectedFocalPeople, selectedPages } = this.state; const selectedList = uniqBy([...selectedFocalPeople], '_id'); const pages = uniq([...selectedPages]); remove(pages, item => item === page); focalPeople.forEach(focalPerson => { remove( selectedList, item => item._id === focalPerson._id // eslint-disable-line ); }); this.setState({ selectedFocalPeople: selectedList, selectedPages: pages, }); }; /** * @function * @name handleFilterByStatus * @description Handle filter focalPeople by status action * * @version 0.1.0 * @since 0.1.0 */ handleFilterByStatus = () => { // if (status === 'All') { // filter({}); // } else if (status === 'Active') { // filter({}); // } else if (status === 'Archived') { // filter({}); // } }; /** * @function * @name handleOnDeselectFocalPerson * @description Handle deselect a single focalPerson action * * @param {object} focalPerson focalPerson to be removed from selected focalPeople * @returns {undefined} undefined * * @version 0.1.0 * @since 0.1.0 */ handleOnDeselectFocalPerson = focalPerson => { const { selectedFocalPeople } = this.state; const selectedList = [...selectedFocalPeople]; remove( selectedList, item => item._id === focalPerson._id // eslint-disable-line ); this.setState({ selectedFocalPeople: selectedList }); }; render() { const { focalPeople, loading, page, total, onEdit, onFilter, onNotify, onShare, onBulkShare, } = this.props; const { selectedFocalPeople, selectedPages } = this.state; const selectedFocalPeopleCount = intersectionBy( this.state.selectedFocalPeople, focalPeople, '_id' ).length; return ( <Fragment> {/* toolbar */} <Toolbar itemName="focal person" page={page} total={total} selectedItemsCount={selectedFocalPeopleCount} exportUrl={getFocalPeopleExportUrl({ filter: { _id: map(selectedFocalPeople, '_id') }, })} onFilter={onFilter} onNotify={() => onNotify(selectedFocalPeople)} onPaginate={nextPage => { paginateFocalPeople(nextPage); }} onRefresh={() => refreshFocalPeople( () => { notifySuccess('Focal People refreshed successfully'); }, () => { notifyError( 'An Error occurred while refreshing Focal People please contact system administrator' ); } ) } onShare={() => onBulkShare(selectedFocalPeople)} /> {/* end toolbar */} {/* focalPerson list header */} <ListHeader headerLayout={headerLayout} onSelectAll={this.handleSelectAll} onDeselectAll={this.handleDeselectAll} isBulkSelected={selectedPages.includes(page)} /> {/* end focalPerson list header */} {/* focalPeople list */} <List loading={loading} dataSource={focalPeople} renderItem={focalPerson => ( <FocalPersonsListItem key={focalPerson._id} // eslint-disable-line abbreviation={focalPerson.abbreviation} location={compact([ focalPerson.location.name, focalPerson.location.place.district, focalPerson.location.place.region, focalPerson.location.place.country, ]).join(', ')} name={focalPerson.name} agency={focalPerson.party ? focalPerson.party.name : 'N/A'} agencyAbbreviation={ focalPerson.party ? focalPerson.party.abbreviation : 'N/A' } role={focalPerson.role ? focalPerson.role.name : 'N/A'} email={focalPerson.email} mobile={focalPerson.mobile} isSelected={ // eslint-disable-next-line map(selectedFocalPeople, item => item._id).includes( focalPerson._id // eslint-disable-line ) } onSelectItem={() => { this.handleOnSelectFocalPerson(focalPerson); }} onDeselectItem={() => { this.handleOnDeselectFocalPerson(focalPerson); }} onEdit={() => onEdit(focalPerson)} onArchive={() => deleteFocalPerson( focalPerson._id, // eslint-disable-line () => { notifySuccess('Focal Person was archived successfully'); }, () => { notifyError( 'An Error occurred while archiving Focal Person please contact system administrator' ); } ) } onShare={() => { onShare(focalPerson); }} /> )} /> {/* end focalPeople list */} </Fragment> ); } }
JavaScript
class REVEL extends React.Component { render() { return ( <div> <div className='HeroAR'> <div className='TextAR'> <b> REVEL VR Startup</b> <br /> <strong> February 2016 - March 2018</strong> <br /> <p>Ever since VR entrepreneur Palmer Luckey presented his prototype of the Oculus Rift in 2012, and me backing it on Kickstarter, I felt like a VR-Evangelist. Even though it was only the first Developer Kit, I saw the initiate reaction of people, which was strengthening my believe in VR even more. </p> <div className='REVELVIDEO'> <video loop autoPlay> <source src={require('../../videos/REVEL.mp4')} type='video/mp4' /> </video> </div> </div> <div className='TextAR'> <p> Still I was waiting for the first consumer ready VR-Headset. That happened to be Samsung’s Gear VR. Unfortunately, being a student meant I had to save up for quite a while before I had the chance to buy this headset. I started using Oculus Social with my Gear VR, an application that allows users to socialize in a virtual environment, and immediately made a friend. We chatted for quite a while, before he invited me into a VR Group on WhatsApp. I knew a lot about the technology behind VR, so I was able to help others with tips & tricks and hands-on information on that group. After a week of doing this, Anouar contacted me on WhatsApp, asking if I wanted to be a part of Twisted Reality. </p> <img className='profilAR' src={require('../../static/images/Logo klein.png')} /> <p> From the start, I was really excited about us working hard to make Twisted Reality a successful movement. At that stage, our team still consisted of five members; we worked on exclusive game and app reviews and helped developers improve their creations. We even did some interviews with industry experts like Dr. Shafi Ahmed, the first doctor who ever broadcasted a live VR surgery. </p> <img className='profilAR' src={require('../../static/images/Prototype1.png')} /> <p>Meanwhile, our movement, Facebook group and support was getting so big that it was hard to manage just by ourselves, especially since a few of our original members dropped out. Andre Berthiaume was incredibly active in our group and both Anouar and me felt a good entrepreneurial vibe between us, therefore we asked him to be part of our team which he was more than happy to do. He added the manpower and VR expertise that we needed at that point, making Twisted Reality a known entity in the Virtual Reality ecosystem.</p> <img className='profilAR' src={require('../../static/images/Prototype2.png')} /> <p>A few months after establishing Twisted Reality, we started gathering ideas about creating our own, unique headset. Having built our own brand from the ground up, we had already gained the confidence to move forward quickly and to get a head start on a design that would be completely different from anything else available on the market. Made for technology aficionado’s but with fashionista’s in mind, we created REVEL: a stylish VR headset that fits any outfit, day or night. Bringing fashion tech to a new level! </p> <img className='profilAR' src={require('../../static/images/Mockup1.png')} /> </div> </div> </div> ) } }
JavaScript
class LoginPage extends Component { render() { return ( <div className="App"> <main> <PageContent changeCallback={(e) => this.props.changeCallback(e) } signUpCallback={() => this.props.signUpCallback() } signInCallback={() => this.props.signInCallback() } userInfo={this.props.userInfo} /> </main> </div> ); } }
JavaScript
class PageContent extends Component { handleChange(event) { this.props.changeCallback(event); } handleSignUp() { this.props.signUpCallback(); } handleSignIn() { this.props.signInCallback(); } menuToggle(e) { e.preventDefault(); let wrapper = document.querySelector('.wrapper'); if(wrapper.classList.contains('toggled')) { wrapper.classList.remove('toggled'); } else { wrapper.classList.add('toggled'); } } //This renders the layout between mobile and desktop login. render() { return( <div className="wrapper toggled"> <div className="sidebar-wrapper"> <UserInfo email={this.props.userInfo.email} username={this.props.userInfo.username} password={this.props.userInfo.password} change={(e) => this.handleChange(e)} signup={()=>this.handleSignUp()} signin={()=>this.handleSignIn()} /> {this.props.userInfo.errorMessage && <p className="alert alert-primary">{this.props.userInfo.errorMessage}</p>} </div> <div className="page-content-wrapper"> <div className="container-fluid"> <div className="login-menu"> <button type="button" className="btn btn-dark" onClick={this.menuToggle}> Menu </button> </div> </div> <WelcomeInfo/> <div className="mobile-user"> <UserInfo email={this.props.userInfo.email} username={this.props.userInfo.username} password={this.props.userInfo.password} change={(e) => this.handleChange(e)} signup={()=>this.handleSignUp()} signin={()=>this.handleSignIn()} /> {this.props.userInfo.errorMessage && <p className="alert alert-primary">{this.props.userInfo.errorMessage}</p>} </div> </div> </div> ); } }
JavaScript
class UserInfo extends Component { render() { return( <div className="user-info"> <main> <Form> <FormGroup> <Label>Email</Label> <Input type="email" name="email" placeholder="Enter email" value={this.props.email} onChange={(event) => { this.props.change(event) }} /> </FormGroup> <FormGroup> <Label>Password</Label> <Input type="password" name="password" placeholder="Enter password" value={this.props.password} onChange={(event) => { this.props.change(event) }} /> </FormGroup> <FormGroup> <Label>Username</Label> <Input name="username" placeholder="Enter username" value={this.props.username} onChange={(event) => { this.props.change(event) }} /> </FormGroup> <FormGroup className="button-group text-center"> <Button className="log-button" onClick={() => { this.props.signup() }}> Sign Up </Button> <Button className="log-button" onClick={() => { this.props.signin() }}> Sign In </Button> </FormGroup> </Form> </main> </div> ); } }
JavaScript
class WelcomeInfo extends Component { render() { return( <div className="welcome-info"> <header className="jumbotron jumbotron-fluid"> <h1>Mindful Journal</h1> <p>Express yourself</p> </header> </div> ); } }
JavaScript
class SocketIoService { constructor(crowi) { this.crowi = crowi; this.configManager = crowi.configManager; this.guestClients = new Set(); } get isInitialized() { return (this.io != null); } // Since the Order is important, attachServer() should be async async attachServer(server) { this.io = socketIo(server, { transports: ['websocket'], }); // create namespace for admin this.adminNamespace = this.io.of('/admin'); // setup middlewares // !!CAUTION!! -- ORDER IS IMPORTANT await this.setupSessionMiddleware(); await this.setupLoginRequiredMiddleware(); await this.setupAdminRequiredMiddleware(); await this.setupCheckConnectionLimitsMiddleware(); await this.setupStoreGuestIdEventHandler(); await this.setupLoginedUserRoomsJoinOnConnection(); await this.setupDefaultSocketJoinRoomsEventHandler(); } getDefaultSocket() { if (this.io == null) { throw new Error('Http server has not attached yet.'); } return this.io.sockets; } getAdminSocket() { if (this.io == null) { throw new Error('Http server has not attached yet.'); } return this.adminNamespace; } /** * use passport session * @see https://socket.io/docs/v4/middlewares/#Compatibility-with-Express-middleware */ setupSessionMiddleware() { const wrap = middleware => (socket, next) => middleware(socket.request, {}, next); this.io.use(wrap(expressSession(this.crowi.sessionConfig))); this.io.use(wrap(passport.initialize())); this.io.use(wrap(passport.session())); // express and passport session on main socket doesn't shared to child namespace socket // need to define the session for specific namespace this.getAdminSocket().use(wrap(expressSession(this.crowi.sessionConfig))); this.getAdminSocket().use(wrap(passport.initialize())); this.getAdminSocket().use(wrap(passport.session())); } /** * use loginRequired middleware */ setupLoginRequiredMiddleware() { const loginRequired = require('../middlewares/login-required')(this.crowi, true, (req, res, next) => { next(new Error('Login is required to connect.')); }); // convert Connect/Express middleware to Socket.io middleware this.io.use((socket, next) => { loginRequired(socket.request, {}, next); }); } /** * use adminRequired middleware */ setupAdminRequiredMiddleware() { const adminRequired = require('../middlewares/admin-required')(this.crowi, (req, res, next) => { next(new Error('Admin priviledge is required to connect.')); }); // convert Connect/Express middleware to Socket.io middleware this.getAdminSocket().use((socket, next) => { adminRequired(socket.request, {}, next); }); } /** * use checkConnectionLimits middleware */ setupCheckConnectionLimitsMiddleware() { this.getAdminSocket().use(this.checkConnectionLimitsForAdmin.bind(this)); this.getDefaultSocket().use(this.checkConnectionLimitsForGuest.bind(this)); this.getDefaultSocket().use(this.checkConnectionLimits.bind(this)); } setupStoreGuestIdEventHandler() { this.io.on('connection', (socket) => { if (socket.request.user == null) { this.guestClients.add(socket.id); socket.on('disconnect', () => { this.guestClients.delete(socket.id); }); } }); } setupLoginedUserRoomsJoinOnConnection() { this.io.on('connection', (socket) => { const user = socket.request.user; if (user == null) { logger.debug('Socket io: An anonymous user has connected'); return; } socket.join(getRoomNameWithId(RoomPrefix.USER, user._id)); }); } setupDefaultSocketJoinRoomsEventHandler() { this.io.on('connection', (socket) => { // set event handlers for joining rooms socket.on('join:page', ({ pageId }) => { socket.join(getRoomNameWithId(RoomPrefix.PAGE, pageId)); }); }); } async checkConnectionLimitsForAdmin(socket, next) { const namespaceName = socket.nsp.name; if (namespaceName === '/admin') { const clients = await this.getAdminSocket().allSockets(); const clientsCount = clients.length; logger.debug('Current count of clients for \'/admin\':', clientsCount); const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimitForAdmin'); if (limit <= clientsCount) { const msg = `The connection was refused because the current count of clients for '/admin' is ${clientsCount} and exceeds the limit`; logger.warn(msg); next(new Error(msg)); return; } } next(); } async checkConnectionLimitsForGuest(socket, next) { if (socket.request.user == null) { const clientsCount = this.guestClients.size; logger.debug('Current count of clients for guests:', clientsCount); const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimitForGuest'); if (limit <= clientsCount) { const msg = `The connection was refused because the current count of clients for guests is ${clientsCount} and exceeds the limit`; logger.warn(msg); next(new Error(msg)); return; } } next(); } /** * @see https://socket.io/docs/server-api/#socket-client */ async checkConnectionLimits(socket, next) { // exclude admin const namespaceName = socket.nsp.name; if (namespaceName === '/admin') { next(); } const clients = await this.getDefaultSocket().allSockets(); const clientsCount = clients.length; logger.debug('Current count of clients for \'/\':', clientsCount); const limit = this.configManager.getConfig('crowi', 's2cMessagingPubsub:connectionsLimit'); if (limit <= clientsCount) { const msg = `The connection was refused because the current count of clients for '/' is ${clientsCount} and exceeds the limit`; logger.warn(msg); next(new Error(msg)); return; } next(); } }
JavaScript
class SensorThingsHttp { /** * constructor of SensorThingsHttp * @param {Object} [optionsOpt] the options for the SensorThingsHttp * @param {Boolean} [optionsOpt.removeIotLinks=false] set to true if the overhead from IotLinks should be removed * @param {Boolean} [optionsOpt.httpClient=null] the httpClient to use as function(url, onsuccess, onerror) with onsuccess as function(response) and onerror as function(error) * @constructor * @returns {SensorThingsHttp} the instance of SensorThingsHttp */ constructor (optionsOpt) { const options = Object.assign({ removeIotLinks: false, httpClient: null }, optionsOpt); /** private **/ this.removeIotLinks = options.removeIotLinks; /** private **/ this.httpClient = options.httpClient; } /** * calls the given url, targets only data in expand, walks through all @iot.nextLink * @param {String} url the url to call * @param {Function} [onsuccess] as function(result) with result as Object[] (result is always an array) * @param {Function} [onstart] as function called on start * @param {Function} [oncomplete] as function called at the end anyways * @param {Function} [onerror] as function(error) * @param {Function} [callNextLinkOpt] see this.callNextLink - a fake callNextLink function for testing * @returns {void} */ get (url, onsuccess, onstart, oncomplete, onerror, callNextLinkOpt) { const nextLinkFiFo = [], result = []; if (typeof onstart === "function") { onstart(); } (typeof callNextLinkOpt === "function" ? callNextLinkOpt : this.callNextLink).bind(this)(url, nextLinkFiFo, () => { // onfinish if (typeof onsuccess === "function") { onsuccess(result); } if (typeof oncomplete === "function") { oncomplete(); } }, error => { // onerror if (typeof onerror === "function") { onerror(error); } if (typeof oncomplete === "function") { oncomplete(); } }, result); } /** * calls the given url to a SensorThings server, uses a call in extent, follows skip urls, response is given as callback onsuccess * @param {String} url the url to call * @param {Object} extentObj data for the extent * @param {Boolean} intersect - if it is intersect or not * @param {Number[]} extentObj.extent the extent based on OpenLayers (e.g. [556925.7670922858, 5925584.829527992, 573934.2329077142, 5942355.170472008]) * @param {String} extentObj.sourceProjection the projection of the extent * @param {String} extentObj.targetProjection the projection the broker expects * @param {Function} [onsuccess] a function (resp) with the response of the call * @param {Function} [onstart] a function to call on start * @param {Function} [oncomplete] a function to allways call when the request is finished (successfully or in failure) * @param {Function} [onerror] a function (error) to call on error * @param {Function} [getOpt] see this.get - a function for testing only * @returns {void} */ getInExtent (url, extentObj, intersect, onsuccess, onstart, oncomplete, onerror, getOpt) { const extent = extentObj && extentObj.extent ? extentObj.extent : false, sourceProjection = extentObj && extentObj.sourceProjection ? extentObj.sourceProjection : false, targetProjection = extentObj && extentObj.targetProjection ? extentObj.targetProjection : false, points = this.convertExtentIntoPoints(extent, sourceProjection, targetProjection, error => { if (typeof onstart === "function") { onstart(); } if (typeof onerror === "function") { onerror(error); } if (typeof oncomplete === "function") { oncomplete(); } }), requestUrl = this.addPointsToUrl(url, points, intersect, error => { if (typeof onstart === "function") { onstart(); } if (typeof onerror === "function") { onerror(error); } if (typeof oncomplete === "function") { oncomplete(); } }); if (points === false || requestUrl === false) { // if an error occured above return; } (typeof getOpt === "function" ? getOpt : this.get).bind(this)(requestUrl, onsuccess, onstart, oncomplete, onerror); } /** * creates a query to put into $filter of the SensorThingsAPI to select only Things within the given points * @param {Object[]} points the points as array with objects(x, y) to use as Polygon in SensorThingsAPI call * @param {Boolean} intersect - if it is intersect or not * @param {SensorThingsErrorCallback} onerror a function (error) to call on error * @returns {String|Boolean} the query to add to $filter= (excluding $filter=) or false on error */ getPolygonQueryWithPoints (points, intersect, onerror) { const loadRange = intersect ? "st_intersects" : "st_within"; let query = ""; if (!Array.isArray(points)) { if (typeof onerror === "function") { onerror("SensorThingsHttp - getPolygonQueryWithPoints: the given points should be an array"); } return false; } points.forEach(function (coord) { if (!coord || !coord?.x || !coord?.y) { return; } if (query !== "") { query += ","; } query += coord.x + " " + coord.y; }); return loadRange + "(Thing/Locations/location,geography'POLYGON ((" + query + "))')"; } /** * converts the given extent based on an OpenLayers extent into points used in the SensorThingsAPI * @param {Number[]} extent the extent based on OpenLayers (e.g. [556925.7670922858, 5925584.829527992, 573934.2329077142, 5942355.170472008]) * @param {String} sourceProjection the projection of the extent * @param {String} targetProjection the projection the result shall have * @param {SensorThingsErrorCallback} onerror a function (error) to call on error * @returns {Object[]} the points as array with objects(x, y) to use as Polygon in SensorThingsAPI call */ convertExtentIntoPoints (extent, sourceProjection, targetProjection, onerror) { let i; if (!Array.isArray(extent) || extent.length !== 4) { if (typeof onerror === "function") { onerror("SensorThingsHttp - convertExtentToPoints: the given extent must be an array with 4 entries"); } return false; } else if (typeof sourceProjection !== "string") { if (typeof onerror === "function") { onerror("SensorThingsHttp - convertExtentToPoints: the sourceProjection must be a string describing a projection (e.g. 'EPSG:4326')"); } return false; } else if (typeof targetProjection !== "string") { if (typeof onerror === "function") { onerror("SensorThingsHttp - convertExtentToPoints: the targetProjection must be a string describing a projection (e.g. 'EPSG:4326')"); } return false; } const points = [ {x: extent[0], y: extent[1]}, {x: extent[2], y: extent[1]}, {x: extent[2], y: extent[3]}, {x: extent[0], y: extent[3]}, {x: extent[0], y: extent[1]} ]; if (sourceProjection !== targetProjection) { for (i in points) { try { points[i] = transformProjectionToProjection(sourceProjection, targetProjection, points[i]); } catch (e) { if (typeof onerror === "function") { onerror(e); return false; } } } } return points; } /** * adds the given points into the query of the url * @param {String} url the url to extent - if POLYGON of SensorThingsAPI is already in use, nothing will change * @param {Object[]} points the points as array with objects(x, y) to use as Polygon in SensorThingsAPI call * @param {Boolean} intersect - if it is intersect or not * @param {SensorThingsErrorCallback} onerror a function (error) to call on error * @returns {String|Boolean} the url with an extent to call the SensorThingsAPI with or false on error */ addPointsToUrl (url, points, intersect, onerror) { const parsedUrl = new UrlParser(url), polygonQuery = this.getPolygonQueryWithPoints(points, intersect, onerror); if (!polygonQuery) { return false; } else if (!url || typeof url !== "string" || url.indexOf("http") !== 0) { if (typeof onerror === "function") { onerror("SensorThingsHttp - addPointsToUrl: an external url begining with http is expected"); } return false; } if (!parsedUrl.query) { parsedUrl.query = {}; } // use UrlParser.set to parse query into object parsedUrl.set("query", parsedUrl.query); if (polygonQuery && !Object.prototype.hasOwnProperty.call(parsedUrl.query, "$filter")) { parsedUrl.query.$filter = polygonQuery; } else if (polygonQuery && parsedUrl.query.$filter.indexOf("geography'POLYGON") === -1 && parsedUrl.query.$filter.indexOf("geography%27POLYGON") === -1) { parsedUrl.query.$filter += " and " + polygonQuery; } // use UrlParser.set(query) to overwrite href parsedUrl.set("query", parsedUrl.query); return parsedUrl.href; } /** * calls a nextLink for the recursion * @param {String} nextLink the url to call * @param {Object[]} nextLinkFiFo the fifo-List to walk through @iot.nextLink * @param {Function} onfinish as function to be called when finished * @param {Function} onerror as function(error) * @param {Object[]} resultRef the reference for the result anything should be added to at this depth * @param {Function} [collectNextLinksOpt] a collectNextLink function for testing only * @returns {void} */ callNextLink (nextLink, nextLinkFiFo, onfinish, onerror, resultRef, collectNextLinksOpt) { if (!Array.isArray(resultRef)) { if (typeof onerror === "function") { onerror("SensorThingsHttp - callNextLink: given resultRef is not an array - nextLink: " + nextLink + " - resultRef: " + resultRef); } return; } this.callHttpClient(nextLink, response => { if (response === null || typeof response !== "object" || Array.isArray(response)) { // the response is represented as a JSON object (no array) // https://docs.opengeospatial.org/is/15-078r6/15-078r6.html#36 if (typeof onerror === "function") { onerror("SensorThingsHttp - callNextLink: the response from the SensorThingsApi is not an object - check nextLink: " + nextLink); } return; } if (response?.value && Array.isArray(response.value)) { response.value.forEach(value => { resultRef.push(value); }); // all responses in a row of @iot.nextLink followups have following @iot.nextLink except the last one if (Object.prototype.hasOwnProperty.call(response, "@iot.nextLink")) { if (Array.isArray(nextLinkFiFo)) { nextLinkFiFo.push({ nextLink: response["@iot.nextLink"], resultRef: resultRef }); } } } else { resultRef.push(response); } (typeof collectNextLinksOpt === "function" ? collectNextLinksOpt : this.collectNextLinks).bind(this)(resultRef, nextLinkFiFo, () => { const obj = this.getNextFiFoObj(nextLinkFiFo); if (obj === false) { // depth barrier reached if (typeof onfinish === "function") { onfinish(); } return; } this.callNextLink(obj.nextLink, nextLinkFiFo, onfinish, onerror, obj.resultRef, collectNextLinksOpt); }); }, onerror); } /** * searches for @iot.nextLink in the given resultRef, removes the @iot.nextLink and expands the nextLinkFiFo-List * @param {*} resultRef something to walk through * @param {Object[]} nextLinkFiFo the fifo list to add found @iot.nextLink and their resultRef to * @param {Function} onfinish a function to call when finished * @returns {void} */ collectNextLinks (resultRef, nextLinkFiFo, onfinish) { if (resultRef === null || typeof resultRef !== "object") { if (typeof onfinish === "function") { onfinish(); } return; } let key; for (key in resultRef) { if (this.removeIotLinks && (key.indexOf("@iot.navigationLink") !== -1 || key.indexOf("@iot.selfLink") !== -1)) { // to reduce output navigationLink and selfLink should be removed delete resultRef[key]; continue; } const pos = key.indexOf("@iot.nextLink"); if (pos === -1) { // onfinish mustn't be used in recursion this.collectNextLinks(resultRef[key], nextLinkFiFo); } else if (pos === 0) { // this should never happen as the rood node is moved into nextLinkFiFo in callNextLink // we collect it anyways just in case some sub node uses @iot.nextLink, which shouldn't happen ... // @iot.nextLink - aka root node if (Array.isArray(nextLinkFiFo)) { nextLinkFiFo.push({ nextLink: resultRef[key], resultRef: resultRef.value }); } // always collect the nextLink to prevent additional recursions (avoiding double entities on resultRef) delete resultRef[key]; } else { if (Array.isArray(nextLinkFiFo)) { nextLinkFiFo.push({ nextLink: resultRef[key], resultRef: resultRef[key.substring(0, pos)] }); } // always collect the nextLink to prevent additional recursions (avoiding double entities on resultRef) delete resultRef[key]; } } if (typeof onfinish === "function") { onfinish(); } } /** * returns the next object from nextLinkFiFo, returns false if no valid object was found (depth barrier) * @param {Object[]} nextLinkFiFo the fifo list to add found @iot.nextLink and their resultRef to * @returns {(Object|Boolean)} the next fifo object to be followed or false if depth barrier has been triggert */ getNextFiFoObj (nextLinkFiFo) { if (!Array.isArray(nextLinkFiFo) || nextLinkFiFo.length === 0 || !nextLinkFiFo[0]?.nextLink) { return false; } const obj = nextLinkFiFo.shift(), topX = this.fetchTopX(obj.nextLink), skipX = this.fetchSkipX(obj.nextLink); if (topX > 0 && topX <= skipX) { // "In addition, if the $top value exceeds the service-driven pagination limitation (...), the $top query option SHALL be discarded and the server-side pagination limitation SHALL be imposed." // https://docs.opengeospatial.org/is/15-078r6/15-078r6.html#51 // that means: skipX can be less than top, but stop for all topX greater or equal skipX // all of this only if topX is given return this.getNextFiFoObj(nextLinkFiFo); } return obj; } /** * extracts the X from $top=X of the given String * @param {String} url the url to extract $top from * @returns {Number} the X in $top=X or 0 if no $top was found */ fetchTopX (url) { if (typeof url !== "string") { return 0; } const regex = /[$|%24]top=([0-9]+)/, result = regex.exec(url); if (!Array.isArray(result) || !Object.prototype.hasOwnProperty.call(result, 1)) { return 0; } return parseInt(result[1], 10); } /** * extracts the X from $skip=X of the given String * @param {String} url the url to extract $skip from * @returns {Number} the X in $skip=X or 0 if no $skip was found */ fetchSkipX (url) { if (typeof url !== "string") { return 0; } const regex = /[$|%24]skip=([0-9]+)/, result = regex.exec(url); if (!Array.isArray(result) || !Object.prototype.hasOwnProperty.call(result, 1)) { return 0; } return parseInt(result[1], 10); } /** * calls the httpClient as async function to call an url and to receive data from * @param {String} url the url to call * @param {Function} onsuccess a function (response) with the response of the call * @param {Function} onerror a function (error) with the error of the call if any * @returns {void} */ callHttpClient (url, onsuccess, onerror) { if (typeof this.httpClient === "function") { this.httpClient(url, onsuccess, onerror); return; } axios({ method: "get", url: url, responseType: "text" }).then(function (response) { if (response !== undefined && typeof onsuccess === "function") { onsuccess(response.data); } }).catch(function (error) { if (typeof onerror === "function") { onerror(error); } }); } /** * sets the httpClient after construction (used for testing only) * @param {Function} httpClient as function(url, onsuccess, onerror) * @post the internal httpClient is set to the given httpClient * @return {void} */ setHttpClient (httpClient) { this.httpClient = httpClient; } /** * sets the removeIotLinks flag after construction (used for testing only) * @param {Boolean} removeIotLinks see options * @post the removeIotLinks flag is set to the given removeIotLinks flag * @return {void} */ setRemoveIotLinks (removeIotLinks) { this.removeIotLinks = removeIotLinks; } }
JavaScript
class MeetingsSDKAdapter extends MeetingsAdapter { constructor(datasource) { super(datasource); this.getMeetingObservables = {}; this.meetings = {}; this.meetingControls[JOIN_CONTROL] = { ID: JOIN_CONTROL, action: this.joinMeeting.bind(this), display: this.joinControl.bind(this), }; this.meetingControls[AUDIO_CONTROL] = { ID: AUDIO_CONTROL, action: this.handleLocalAudio.bind(this), display: this.audioControl.bind(this), }; this.meetingControls[VIDEO_CONTROL] = { ID: VIDEO_CONTROL, action: this.handleLocalVideo.bind(this), display: this.videoControl.bind(this), }; this.meetingControls[SHARE_CONTROL] = { ID: SHARE_CONTROL, action: this.handleLocalShare.bind(this), display: this.shareControl.bind(this), }; this.meetingControls[EXIT_CONTROL] = { ID: EXIT_CONTROL, action: this.leaveMeeting.bind(this), display: this.exitControl.bind(this), }; this.meetingControls[ROSTER_CONTROL] = { ID: ROSTER_CONTROL, action: this.handleRoster.bind(this), display: this.rosterControl.bind(this), }; this.meetingControls[SETTINGS_CONTROL] = { ID: SETTINGS_CONTROL, action: this.toggleSettings.bind(this), display: this.settingsControl.bind(this), }; this.meetingControls[SWITCH_CAMERA_CONTROL] = { ID: SWITCH_CAMERA_CONTROL, action: this.switchCamera.bind(this), display: this.switchCameraControl.bind(this), }; this.meetingControls[SWITCH_MICROPHONE_CONTROL] = { ID: SWITCH_MICROPHONE_CONTROL, action: this.switchMicrophone.bind(this), display: this.switchMicrophoneControl.bind(this), }; this.meetingControls[SWITCH_SPEAKER_CONTROL] = { ID: SWITCH_SPEAKER_CONTROL, action: this.switchSpeaker.bind(this), display: this.switchSpeakerControl.bind(this), }; } /** * Register the SDK meeting plugin to the device * and sync the meeting collection from the server. */ async connect() { await this.datasource.meetings.register(); await this.datasource.meetings.syncMeetings(); } /** * Unregister the SDK meeting plugin from the device. */ async disconnect() { await this.datasource.meetings.unregister(); } /** * Returns an observable that emits local device media streams and their user permission status * * @private * @param {string} ID ID to retrieve the SDK meeting object to add the local media to * @returns {Observable} Observable that emits local media streams and their user permission status */ getLocalMedia(ID) { const audio$ = mediaSettings.sendAudio ? this.getStream(ID, {sendAudio: true}).pipe( map(({permission, stream}) => ({ localAudio: { stream, permission, }, localVideo: { stream: null, permission: null, }, })), ) : of({permission: null, stream: null}); const video$ = mediaSettings.sendVideo ? audio$.pipe( last(), concatMap((audio) => this.getStream(ID, {sendVideo: true}).pipe( map(({permission, stream}) => ({ ...audio, localVideo: { stream, permission, }, })), )), ) : of({permission: null, stream: null}); return concat(audio$, video$); } /** * Returns an observable that emits local device media streams and their user permission status based on the given constraints. * * @see {@link MediaStream|https://developer.mozilla.org/en-US/docs/Web/API/MediaStream}. * * @private * @param {string} ID ID of the meeting for which to fetch streams * @param {object} mediaDirection A configurable options object for joining a meetings * @param {object} audioVideo audio/video object to set audioinput and videoinput devices * @returns {Observable} Observable that emits local media streams and their user permission status */ getStream(ID, mediaDirection, audioVideo) { return new Observable(async (subscriber) => { try { const sdkMeeting = this.fetchMeeting(ID); subscriber.next({permission: 'ASKING', stream: null}); const [localStream] = await sdkMeeting.getMediaStreams(mediaDirection, audioVideo); for (const track of localStream.getTracks()) { if (track.kind === 'video' && !mediaDirection.sendVideo) { localStream.removeTrack(track); } if (track.kind === 'audio' && !mediaDirection.sendAudio) { localStream.removeTrack(track); } } subscriber.next({permission: 'ALLOWED', stream: localStream}); } catch (error) { let perm; // eslint-disable-next-line no-console console.error('Unable to retrieve local media stream for meeting', ID, 'with mediaDirection', mediaDirection, 'and audioVideo', audioVideo, 'reason:', error); if (error instanceof DOMException && error.name === 'NotAllowedError') { if (error.message === 'Permission dismissed') { perm = 'DISMISSED'; } else { perm = 'DENIED'; } } else { perm = 'ERROR'; } subscriber.next({permission: perm, stream: null}); } subscriber.complete(); }); } /** * Returns available media devices. * * @param {string} ID ID of the meeting * @param {'videoinput'|'audioinput'|'audiooutput'} type String specifying the device type. * See {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/kind|MDN} * @returns {MediaDeviceInfo[]} Array containing media devices. * @private */ // eslint-disable-next-line class-methods-use-this async getAvailableDevices(ID, type) { let devices; try { const sdkMeeting = this.fetchMeeting(ID); devices = await sdkMeeting.getDevices(); devices = devices.filter((device) => device.kind === type); } catch (error) { // eslint-disable-next-line no-console console.error(`Unable to retrieve devices for meeting "${ID}"`, error); devices = []; } return devices; } /** * Update the meeting object with media attached based on a given event type. * * @private * @param {string} ID ID of the meeting to update * @param {object} media Media stream to attach to the meeting object based on a given event type * @param {string} media.type Type of event associated with the media change * @param {MediaStream} media.stream Media stream to attach to meeting */ attachMedia(ID, {type, stream}) { const meeting = {...this.meetings[ID]}; switch (type) { case MEDIA_TYPE_LOCAL: this.meetings[ID] = { ...meeting, // Attach the media streams only if the streams are unmuted // `disableLocalAudio/Video` change inside handle media stream methods localAudio: { ...meeting.localAudio, stream: meeting.disabledLocalAudio ? null : new MediaStream(stream.getAudioTracks()), }, localVideo: { ...meeting.localVideo, stream: meeting.disabledLocalVideo ? null : new MediaStream(stream.getVideoTracks()), }, }; break; case MEDIA_TYPE_REMOTE_AUDIO: this.meetings[ID] = {...meeting, remoteAudio: stream}; break; case MEDIA_TYPE_REMOTE_VIDEO: this.meetings[ID] = {...meeting, remoteVideo: stream}; break; case MEDIA_TYPE_LOCAL_SHARE: this.meetings[ID] = {...meeting, localShare: {stream}}; break; case MEDIA_TYPE_REMOTE_SHARE: this.meetings[ID] = {...meeting, remoteShareStream: stream}; break; case EVENT_REMOTE_SHARE_START: // Only activate the remote stream when get get the start notification this.meetings[ID] = {...meeting, remoteShare: meeting.remoteShareStream}; break; case EVENT_REMOTE_SHARE_STOP: // Remove remote share on stop event this.meetings[ID] = {...meeting, remoteShare: null}; break; default: break; } } /** * Stops the tracks of the given media stream. * * @see {@link MediaStream|https://developer.mozilla.org/en-US/docs/Web/API/MediaStream}. * * @private * @static * @param {MediaStream} stream Media stream for which to stop tracks */ // eslint-disable-next-line class-methods-use-this stopStream(stream) { if (stream) { const tracks = stream.getTracks(); tracks.forEach((track) => track.stop()); } } /** * Update the meeting object by removing all media. * * @private * @param {string} ID ID of the meeting to update */ removeMedia(ID) { if (this.meetings && this.meetings[ID]) { this.stopStream(this.meetings[ID].localAudio.stream); this.stopStream(this.meetings[ID].localVideo.stream); this.stopStream(this.meetings[ID].localShare.stream); } this.meetings[ID] = { ...this.meetings[ID], localAudio: { stream: null, permission: null, }, localVideo: { stream: null, permission: null, }, localShare: { stream: null, }, remoteAudio: null, remoteVideo: null, remoteShare: null, cameraID: null, microphoneID: null, speakerID: null, }; } /** * Returns a promise of a meeting title for a given destination. * Supported destinations are person ID, room ID and SIP URI. * * @private * @param {string} destination Virtual meeting destination * @returns {Promise.<string>} Promise to the tile of the meeting at the destination */ async fetchMeetingTitle(destination) { const {id, type} = deconstructHydraId(destination); let meetingTitle = destination; if (type === HYDRA_ID_TYPE_PEOPLE) { const {displayName} = await this.datasource.people.get(id); meetingTitle = `${displayName}'s Personal Room`; } else if (type === HYDRA_ID_TYPE_ROOM) { // One must use a Hydra ID when calling `get` on rooms. // It has both the convo ID and cluster name in it. const {title} = await this.datasource.rooms.get(destination); meetingTitle = title; } else { try { const people = await this.datasource.people.list({email: destination}); if (people.items) { const {displayName} = people.items[0]; meetingTitle = `${displayName}'s Personal Room`; } // eslint-disable-next-line no-empty } catch (error) {} } return meetingTitle; } /** * Creates meeting and returns an observable to the new meeting data. * * @param {string} destination Destination where to start the meeting at * @returns {Observable.<Meeting>} Observable stream that emits data of the newly created meeting */ createMeeting(destination) { const newMeeting$ = from(this.datasource.meetings.create(destination)).pipe( flatMap(({id}) => from(this.fetchMeetingTitle(destination)).pipe( map((title) => ({ID: id, title})), )), map((meeting) => ({ ...meeting, localAudio: { stream: null, permission: null, }, localVideo: { stream: null, permission: null, }, localShare: { stream: null, }, remoteAudio: null, remoteVideo: null, remoteShare: null, showRoster: null, showSettings: false, state: MeetingState.NOT_JOINED, cameraID: null, microphoneID: null, speakerID: null, })), tap((meeting) => { this.meetings[meeting.ID] = meeting; }), ); const meeting$ = newMeeting$.pipe( concatMap((meeting) => this.getLocalMedia(meeting.ID).pipe( map((localMedia) => ({ ...meeting, ...localMedia, })), )), tap((meeting) => { this.meetings[meeting.ID] = meeting; }), ); return concat(newMeeting$, meeting$).pipe( catchError((err) => { // eslint-disable-next-line no-console console.error(`Unable to create a meeting with "${destination}"`, err); throw err; }), ); } /** * Returns a SDK meeting object retrieved from the collection. * * @private * @param {string} ID ID of the meeting to fetch. * @returns {object} The SDK meeting object from the meetings collection. */ fetchMeeting(ID) { return this.datasource.meetings.getMeetingByType('id', ID); } /** * Attempts to join the meeting of the given meeting ID. * If the meeting is successfully joined, a ready event is dispatched. * * @param {string} ID ID of the meeting to join */ async joinMeeting(ID) { try { const sdkMeeting = this.fetchMeeting(ID); const localStream = new MediaStream(); const localAudio = this.meetings[ID].localAudio.stream || this.meetings[ID].disabledLocalAudio; const localVideo = this.meetings[ID].localVideo.stream || this.meetings[ID].disabledLocalVideo; if (localAudio) { localAudio.getTracks().forEach((track) => localStream.addTrack(track)); } if (localVideo) { localVideo.getTracks().forEach((track) => localStream.addTrack(track)); } await sdkMeeting.join(); // SDK requires to join the meeting before adding the local stream media to the meeting await sdkMeeting.addMedia({localStream, mediaSettings}); // Mute either streams after join if user had muted them before joining if (this.meetings[ID].localAudio.stream === null) { await sdkMeeting.muteAudio(); } if (this.meetings[ID].localVideo.stream === null) { await sdkMeeting.muteVideo(); } } catch (error) { // eslint-disable-next-line no-console console.error(`Unable to join meeting "${ID}"`, error); } } /** * Attempts to leave the meeting of the given meeting ID. * If the user had left the meeting successfully, a stopped event is dispatched. * * @param {string} ID ID of the meeting to leave from */ async leaveMeeting(ID) { try { const sdkMeeting = this.fetchMeeting(ID); await sdkMeeting.leave(); // Due to SDK limitations, We need to emit a media stopped event for remote media types sdkMeeting.emit(EVENT_MEDIA_STOPPED, {type: MEDIA_TYPE_REMOTE_AUDIO}); sdkMeeting.emit(EVENT_MEDIA_STOPPED, {type: MEDIA_TYPE_REMOTE_VIDEO}); sdkMeeting.emit(EVENT_MEDIA_STOPPED, {type: MEDIA_TYPE_LOCAL_SHARE}); } catch (error) { // eslint-disable-next-line no-console console.error(`Unable to leave from the meeting "${ID}"`, error); } } /** * Returns an observable that emits the display data of a meeting control. * * @private * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the join control */ // eslint-disable-next-line class-methods-use-this joinControl() { return Observable.create((observer) => { observer.next({ ID: JOIN_CONTROL, text: 'Join meeting', tooltip: 'Join meeting', state: MeetingControlState.ACTIVE, }); observer.complete(); }); } /** * Returns an observable that emits the display data of a meeting control. * * @private * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the exit control */ // eslint-disable-next-line class-methods-use-this exitControl() { return Observable.create((observer) => { observer.next({ ID: EXIT_CONTROL, icon: 'cancel_28', tooltip: 'Leave', state: MeetingControlState.ACTIVE, }); observer.complete(); }); } /** * Attempts to mute the microphone of the given meeting ID. * If the microphone is successfully muted, an audio mute event is dispatched. * * @private * @param {string} ID ID of the meeting to mute audio */ async handleLocalAudio(ID) { const sdkMeeting = this.fetchMeeting(ID); try { const isInSession = !!this.meetings[ID].remoteAudio; const noAudio = !this.meetings[ID].disabledLocalAudio && !this.meetings[ID].localAudio.stream; const audioEnabled = !!this.meetings[ID].localAudio.stream; let state; if (noAudio) { state = MeetingControlState.DISABLED; } else if (audioEnabled) { // Mute the audio only if there is an active meeting if (isInSession) { await sdkMeeting.muteAudio(); } // Store the current local audio stream to avoid an extra request call this.meetings[ID].disabledLocalAudio = this.meetings[ID].localAudio.stream; this.meetings[ID].localAudio.stream = null; state = MeetingControlState.INACTIVE; } else { // Unmute the audio only if there is an active meeting if (isInSession) { await sdkMeeting.unmuteAudio(); } // Retrieve the stored local audio stream this.meetings[ID].localAudio.stream = this.meetings[ID].disabledLocalAudio; this.meetings[ID].disabledLocalAudio = null; state = MeetingControlState.ACTIVE; } // Due to SDK limitation around local media updates, // we need to emit a custom event for audio mute updates sdkMeeting.emit(EVENT_MEDIA_LOCAL_UPDATE, { control: AUDIO_CONTROL, state, }); } catch (error) { // eslint-disable-next-line no-console console.error(`Unable to update local audio settings for meeting "${ID}"`, error); } } /** * Returns an observable that emits the display data of a mute meeting audio control. * * @private * @param {string} ID ID of the meeting to mute audio * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the audio control */ audioControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const muted = { ID: AUDIO_CONTROL, icon: 'microphone-muted_28', tooltip: 'Unmute', state: MeetingControlState.ACTIVE, text: null, }; const unmuted = { ID: AUDIO_CONTROL, icon: 'microphone-muted_28', tooltip: 'Mute', state: MeetingControlState.INACTIVE, text: null, }; const disabled = { ID: AUDIO_CONTROL, icon: 'microphone-muted_28', tooltip: 'No microphone available', state: MeetingControlState.DISABLED, text: null, }; const states = { [MeetingControlState.ACTIVE]: unmuted, [MeetingControlState.INACTIVE]: muted, [MeetingControlState.DISABLED]: disabled, }; const initialState$ = Observable.create((observer) => { if (sdkMeeting) { const meeting = this.meetings[ID]; const noAudio = !meeting.disabledLocalAudio && !meeting.localAudio.stream; observer.next(noAudio ? disabled : unmuted); } else { observer.error(new Error(`Could not find meeting with ID "${ID}" to add audio control`)); } observer.complete(); }); const localMediaUpdateEvent$ = fromEvent(sdkMeeting, EVENT_MEDIA_LOCAL_UPDATE).pipe( filter((event) => event.control === AUDIO_CONTROL), map(({state}) => states[state]), ); return concat(initialState$, localMediaUpdateEvent$); } /** * Attempts to mute the camera of the given meeting ID. * If the camera is successfully muted, a video mute event is dispatched. * * @private * @param {string} ID ID of the meeting to mute video */ async handleLocalVideo(ID) { const sdkMeeting = this.fetchMeeting(ID); try { const isInSession = !!this.meetings[ID].remoteVideo; const noVideo = !this.meetings[ID].disabledLocalVideo && !this.meetings[ID].localVideo.stream; const videoEnabled = !!this.meetings[ID].localVideo.stream; let state; if (noVideo) { state = MeetingControlState.DISABLED; } else if (videoEnabled) { // Mute the video only if there is an active meeting if (isInSession) { await sdkMeeting.muteVideo(); } // Store the current local video stream to avoid an extra request call this.meetings[ID].disabledLocalVideo = this.meetings[ID].localVideo.stream; this.meetings[ID].localVideo.stream = null; state = MeetingControlState.INACTIVE; } else { // Unmute the video only if there is an active meeting if (isInSession) { await sdkMeeting.unmuteVideo(); } // Retrieve the stored local video stream this.meetings[ID].localVideo.stream = this.meetings[ID].disabledLocalVideo; this.meetings[ID].disabledLocalVideo = null; state = MeetingControlState.ACTIVE; } // Due to SDK limitation around local media updates, // we need to emit a custom event for video mute updates sdkMeeting.emit(EVENT_MEDIA_LOCAL_UPDATE, { control: VIDEO_CONTROL, state, }); } catch (error) { // eslint-disable-next-line no-console console.error(`Unable to update local video settings for meeting "${ID}"`, error); } } /** * Returns an observable that emits the display data of a mute meeting video control. * * @private * @param {string} ID ID of the meeting to mute video * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the video control */ videoControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const muted = { ID: VIDEO_CONTROL, icon: 'camera-muted_28', tooltip: 'Start video', state: MeetingControlState.ACTIVE, text: null, }; const unmuted = { ID: VIDEO_CONTROL, icon: 'camera-muted_28', tooltip: 'Stop video', state: MeetingControlState.INACTIVE, text: null, }; const disabled = { ID: VIDEO_CONTROL, icon: 'camera-muted_28', tooltip: 'No camera available', state: MeetingControlState.DISABLED, text: null, }; const states = { [MeetingControlState.ACTIVE]: unmuted, [MeetingControlState.INACTIVE]: muted, [MeetingControlState.DISABLED]: disabled, }; const initialState$ = Observable.create((observer) => { if (sdkMeeting) { const meeting = this.meetings[ID]; const noVideo = !meeting.disabledLocalVideo && !meeting.localVideo.stream; observer.next(noVideo ? disabled : unmuted); } else { observer.error(new Error(`Could not find meeting with ID "${ID}" to add video control`)); } observer.complete(); }); const localMediaUpdateEvent$ = fromEvent(sdkMeeting, EVENT_MEDIA_LOCAL_UPDATE).pipe( filter((event) => event.control === VIDEO_CONTROL), map(({state}) => states[state]), ); return concat(initialState$, localMediaUpdateEvent$); } /** * Attempts to start/stop screen sharing to the given meeting ID. * If successful, a sharing start/stop event is dispatched. * * @private * @param {string} ID ID of the meeting to start/stop sharing */ async handleLocalShare(ID) { const sdkMeeting = this.fetchMeeting(ID); if (!sdkMeeting.canUpdateMedia()) { // eslint-disable-next-line no-console console.error(`Unable to update screen share for meeting "${ID}" due to unstable connection.`); return; } const enableSharingStream = async () => { const [, localShare] = await sdkMeeting.getMediaStreams({sendShare: true}); this.meetings[ID].localShare.stream = localShare; sdkMeeting.emit(EVENT_MEDIA_LOCAL_UPDATE, { control: SHARE_CONTROL, state: MeetingControlState.ACTIVE, }); await sdkMeeting.updateShare({stream: localShare, sendShare: true, receiveShare: true}); }; const disableSharingStream = async () => { this.stopStream(this.meetings[ID].localShare); this.meetings[ID].localShare = null; sdkMeeting.emit(EVENT_MEDIA_LOCAL_UPDATE, { control: SHARE_CONTROL, state: MeetingControlState.INACTIVE, }); await sdkMeeting.updateShare({ sendShare: false, receiveShare: true, }); // The rest of the cleanup is done in the handling of the EVENT_LOCAL_SHARE_STOP event emitted by sdkMeeting.updateShare }; const resetSharingStream = (error) => { // eslint-disable-next-line no-console console.warn(`Unable to update local share stream for meeting "${ID}"`, error); if (this.meetings[ID] && this.meetings[ID].localShare) { this.stopStream(this.meetings[ID].localShare); this.meetings[ID].localShare = null; } sdkMeeting.emit(EVENT_MEDIA_LOCAL_UPDATE, { control: SHARE_CONTROL, state: MeetingControlState.INACTIVE, }); }; // // Workflow: // To enable or to disable the local sharing stream based on toggle state. // Will stop sharing stream and reset UI state when error happens // try { if (this.meetings[ID].localShare.stream) { await disableSharingStream(); } else { await enableSharingStream(); } } catch (error) { resetSharingStream(error); } } /** * Returns an observable that emits the display data of a share control. * * @private * @param {string} ID ID of the meeting to start/stop screen share * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the screen share control */ shareControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const inactiveShare = { ID: SHARE_CONTROL, icon: 'share-screen-presence-stroke_26', tooltip: 'Start Share', state: MeetingControlState.INACTIVE, text: null, }; const activeShare = { ID: SHARE_CONTROL, icon: 'share-screen-presence-stroke_26', tooltip: 'Stop Share', state: MeetingControlState.ACTIVE, text: null, }; const disabledShare = { ID: SHARE_CONTROL, icon: 'share-screen-presence-stroke_26', tooltip: 'Sharing is Unavailable', state: MeetingControlState.DISABLED, text: null, }; const getDisplayData$ = Observable.create((observer) => { if (sdkMeeting) { observer.next(inactiveShare); } else { observer.error(new Error(`Could not find meeting with ID "${ID}" to add share control`)); } observer.complete(); }); const localMediaUpdateEvent$ = fromEvent(sdkMeeting, EVENT_MEDIA_LOCAL_UPDATE).pipe( filter((event) => event.control === SHARE_CONTROL), map(({state}) => { let eventData; switch (state) { case MeetingControlState.DISABLED: eventData = disabledShare; break; case MeetingControlState.INACTIVE: eventData = inactiveShare; break; case MeetingControlState.ACTIVE: eventData = activeShare; break; default: eventData = disabledShare; break; } return eventData; }), ); const meetingWithMediaStoppedSharingLocalEvent$ = fromEvent( sdkMeeting, EVENT_LOCAL_SHARE_STOP, ).pipe( // eslint-disable-next-line no-console tap(() => console.info('EVENT_LOCAL_SHARE_STOP was triggered')), map(() => inactiveShare), ); const meetingWithMediaStartedSharingLocalEvent$ = fromEvent( sdkMeeting, EVENT_LOCAL_SHARE_START, ).pipe( // eslint-disable-next-line no-console tap(() => console.info('EVENT_LOCAL_SHARE_START was triggered')), map(() => activeShare), ); const sharingEvents$ = merge( localMediaUpdateEvent$, meetingWithMediaStoppedSharingLocalEvent$, meetingWithMediaStartedSharingLocalEvent$, ); return concat(getDisplayData$, sharingEvents$); } /** * Attempts to toggle roster to the given meeting ID. * A roster toggle event is dispatched. * * @private * @param {string} ID ID of the meeting to toggle roster */ handleRoster(ID) { const sdkMeeting = this.fetchMeeting(ID); const showRoster = !this.meetings[ID].showRoster; this.meetings[ID].showRoster = showRoster; sdkMeeting.emit(EVENT_ROSTER_TOGGLE, { state: showRoster ? MeetingControlState.ACTIVE : MeetingControlState.INACTIVE, }); } /** * Returns an observable that emits the display data of a roster control. * * @private * @param {string} ID ID of the meeting to toggle roster * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the roster control */ rosterControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const active = { ID: ROSTER_CONTROL, icon: 'participant-list_28', tooltip: 'Hide participants panel', state: MeetingControlState.ACTIVE, text: 'Participants', }; const inactive = { ID: ROSTER_CONTROL, icon: 'participant-list_28', tooltip: 'Show participants panel', state: MeetingControlState.INACTIVE, text: 'Participants', }; let state$; if (sdkMeeting) { const initialControl = (this.meetings[ID] && this.meetings[ID].showRoster) ? active : inactive; state$ = new BehaviorSubject(initialControl); const rosterEvent$ = fromEvent(sdkMeeting, EVENT_ROSTER_TOGGLE) .pipe(map(({state}) => (state === MeetingControlState.ACTIVE ? active : inactive))); rosterEvent$.subscribe((value) => state$.next(value)); } else { state$ = throwError(new Error(`Could not find meeting with ID "${ID}" to add roster control`)); } return state$; } /** * Toggles the showSettings flag of the given meeting ID. * A settings toggle event is dispatched. * * @private * @param {string} ID Meeting ID */ toggleSettings(ID) { const sdkMeeting = this.fetchMeeting(ID); const showSettings = !this.meetings[ID].showSettings; this.meetings[ID].showSettings = showSettings; sdkMeeting.emit(EVENT_SETTINGS_TOGGLE, { state: showSettings ? MeetingControlState.ACTIVE : MeetingControlState.INACTIVE, }); } /** * Returns an observable that emits the display data of a settings control. * * @private * @param {string} ID Meeting id * @returns {Observable.<MeetingControlDisplay>} Observable stream that emits display data of the settings control */ settingsControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const active = { ID: SETTINGS_CONTROL, icon: 'settings_32', tooltip: 'Hide settings panel', state: MeetingControlState.ACTIVE, text: 'Settings', }; const inactive = { ID: SETTINGS_CONTROL, icon: 'settings_32', tooltip: 'Show settings panel', state: MeetingControlState.INACTIVE, text: 'Settings', }; let state$; if (sdkMeeting) { const initialState = (this.meetings[ID] && this.meetings[ID].showSettings) ? active : inactive; state$ = new BehaviorSubject(initialState); const settingsEvent$ = fromEvent(sdkMeeting, EVENT_SETTINGS_TOGGLE) .pipe(map(({state}) => (state === MeetingControlState.ACTIVE ? active : inactive))); settingsEvent$.subscribe((value) => state$.next(value)); } else { state$ = throwError(new Error(`Could not find meeting with ID "${ID}" to add settings control`)); } return state$; } /** * Switches the camera control. * * @param {string} ID Meeting ID * @param {string} cameraID ID of the camera to switch to * @private */ async switchCamera(ID, cameraID) { const sdkMeeting = this.fetchMeeting(ID); const {stream, permission} = await this.getStream( ID, {sendVideo: true}, {video: {deviceId: cameraID}}, ).toPromise(); if (stream) { this.meetings[ID].localVideo.stream = stream; this.meetings[ID].cameraID = cameraID; if (this.meetings[ID].state === MeetingState.JOINED) { await sdkMeeting.updateVideo({ stream, receiveVideo: mediaSettings.receiveVideo, sendVideo: mediaSettings.sendVideo, }); } sdkMeeting.emit(EVENT_CAMERA_SWITCH, {cameraID}); } else { throw new Error('Could not change camera, permission not granted:', permission); } } /** * Switches the microphone control. * * @param {string} ID Meeting ID * @param {string} microphoneID ID of the microphone to switch to * @private */ async switchMicrophone(ID, microphoneID) { const sdkMeeting = this.fetchMeeting(ID); const {stream, permission} = await this.getStream( ID, {sendAudio: true}, {audio: {deviceId: microphoneID}}, ).toPromise(); if (stream) { this.meetings[ID].localAudio.stream = stream; this.meetings[ID].microphoneID = microphoneID; if (this.meetings[ID].state === MeetingState.JOINED) { await sdkMeeting.updateAudio({ stream, receiveAudio: mediaSettings.receiveAudio, sendAudio: mediaSettings.sendAudio, }); } sdkMeeting.emit(EVENT_MICROPHONE_SWITCH, {microphoneID}); } else { throw new Error('Could not change microphone, permission not granted:', permission); } } /** * Switches the speaker control. * * @param {string} ID Meeting ID * @param {string} speakerID ID of the speaker device to switch to * @private */ async switchSpeaker(ID, speakerID) { const sdkMeeting = this.fetchMeeting(ID); this.meetings[ID].speakerID = speakerID; sdkMeeting.emit(EVENT_SPEAKER_SWITCH, {speakerID}); } /** * Returns an observable that emits the display data of the switch camera control. * * @param {string} ID Meeting ID * @returns {Observable.<MeetingControlDisplay>} Observable that emits control display data of the switch camera control * @private */ switchCameraControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const availableCameras$ = defer(() => this.getAvailableDevices(ID, 'videoinput')); const initialControl$ = new Observable((observer) => { if (sdkMeeting) { observer.next({ ID: SWITCH_CAMERA_CONTROL, tooltip: 'Video Devices', options: null, selected: this.meetings[ID].cameraID, }); observer.complete(); } else { observer.error(new Error(`Could not find meeting with ID "${ID}" to add switch camera control`)); } }); const controlWithOptions$ = initialControl$.pipe( concatMap((control) => availableCameras$.pipe( map((availableCameras) => ({ ...control, selected: this.meetings[ID].cameraID, options: availableCameras && availableCameras.map((camera) => ({ value: camera.deviceId, label: camera.label, camera, })), })), )), ); const controlFromEvent$ = fromEvent(sdkMeeting, EVENT_CAMERA_SWITCH).pipe( concatMap(({cameraID}) => controlWithOptions$.pipe( map((control) => ({ ...control, selected: cameraID, })), )), ); return concat(initialControl$, controlWithOptions$, controlFromEvent$); } /** * Returns an observable that emits the display data of the switch microphone control. * * @param {string} ID Meeting ID * @returns {Observable.<MeetingControlDisplay>} Observable that emits control display data of the switch microphone control * @private */ switchMicrophoneControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const availableMicrophones$ = defer(() => this.getAvailableDevices(ID, 'audioinput')); const initialControl$ = new Observable((observer) => { if (sdkMeeting) { observer.next({ ID: SWITCH_MICROPHONE_CONTROL, tooltip: 'Microphone Devices', options: null, selected: this.meetings[ID].microphoneID, }); observer.complete(); } else { observer.error(new Error(`Could not find meeting with ID "${ID}" to add switch microphone control`)); } }); const controlWithOptions$ = initialControl$.pipe( concatMap((control) => availableMicrophones$.pipe( map((availableMicrophones) => ({ ...control, selected: this.meetings[ID].microphoneID, options: availableMicrophones && availableMicrophones.map((microphone) => ({ value: microphone.deviceId, label: microphone.label, microphone, })), })), )), ); const controlFromEvent$ = fromEvent(sdkMeeting, EVENT_MICROPHONE_SWITCH).pipe( concatMap(({microphoneID}) => controlWithOptions$.pipe( map((control) => ({ ...control, selected: microphoneID, })), )), ); return concat(initialControl$, controlWithOptions$, controlFromEvent$); } /** * Returns an observable that emits the display data of the speaker switcher control. * * @param {string} ID Meeting ID * @returns {Observable.<MeetingControlDisplay>} Observable that emits control display data of speaker switcher control * @private */ switchSpeakerControl(ID) { const sdkMeeting = this.fetchMeeting(ID); const availableSpeakers$ = defer(() => this.getAvailableDevices(ID, 'audiooutput')); const initialControl$ = new Observable((observer) => { if (sdkMeeting) { observer.next({ ID: SWITCH_SPEAKER_CONTROL, tooltip: 'Speaker Devices', options: null, selected: this.meetings[ID].speakerID, }); observer.complete(); } else { observer.error(new Error(`Could not find meeting with ID "${ID}" to add switch speaker control`)); } }); const controlWithOptions$ = initialControl$.pipe( concatMap((control) => availableSpeakers$.pipe( map((availableSpeakers) => ({ ...control, selected: this.meetings[ID].speakerID, options: availableSpeakers && availableSpeakers.map((speaker) => ({ value: speaker.deviceId, label: speaker.label, speaker, })), })), )), ); const controlFromEvent$ = fromEvent(sdkMeeting, EVENT_SPEAKER_SWITCH).pipe( concatMap(({speakerID}) => controlWithOptions$.pipe( map((control) => ({ ...control, selected: speakerID, })), )), ); return concat(initialControl$, controlWithOptions$, controlFromEvent$); } /** * Returns an observable that emits meeting data of the given ID. * * @param {string} ID ID of meeting to get * @returns {Observable.<Meeting>} Observable stream that emits meeting data of the given ID */ getMeeting(ID) { if (!(ID in this.getMeetingObservables)) { const sdkMeeting = this.fetchMeeting(ID); const getMeeting$ = Observable.create((observer) => { if (this.meetings[ID]) { observer.next(this.meetings[ID]); } else { observer.error(new Error(`Could not find meeting with ID "${ID}"`)); } observer.complete(); }); const meetingWithMediaReadyEvent$ = fromEvent(sdkMeeting, EVENT_MEDIA_READY).pipe( filter((event) => MEDIA_EVENT_TYPES.includes(event.type)), map((event) => this.attachMedia(ID, event)), ); const meetingWithMediaStoppedEvent$ = fromEvent(sdkMeeting, EVENT_MEDIA_STOPPED).pipe( tap(() => this.removeMedia(ID)), ); const meetingWithMediaShareEvent$ = fromEvent(sdkMeeting, EVENT_REMOTE_SHARE_START).pipe( tap(() => this.attachMedia(ID, {type: EVENT_REMOTE_SHARE_START})), ); const meetingWithMediaStoppedShareEvent$ = fromEvent(sdkMeeting, EVENT_REMOTE_SHARE_STOP) .pipe( tap(() => this.attachMedia(ID, {type: EVENT_REMOTE_SHARE_STOP})), ); const meetingWithLocalShareStoppedEvent$ = fromEvent(sdkMeeting, EVENT_LOCAL_SHARE_STOP); const meetingWithLocalUpdateEvent$ = fromEvent(sdkMeeting, EVENT_MEDIA_LOCAL_UPDATE); const meetingWithRosterToggleEvent$ = fromEvent(sdkMeeting, EVENT_ROSTER_TOGGLE); const meetingWithSwitchSpeakerEvent$ = fromEvent(sdkMeeting, EVENT_SPEAKER_SWITCH); const meetingWithSettingsToggleEvent$ = fromEvent(sdkMeeting, EVENT_SETTINGS_TOGGLE); const meetingWithSwitchCameraEvent$ = fromEvent(sdkMeeting, EVENT_CAMERA_SWITCH); const meetingWithSwitchMicrophoneEvent$ = fromEvent(sdkMeeting, EVENT_MICROPHONE_SWITCH); const meetingStateChange$ = fromEvent(sdkMeeting, EVENT_STATE_CHANGE).pipe( tap((event) => { const sdkState = event.payload.currentState; let state; if (sdkState === 'ACTIVE') { state = MeetingState.JOINED; } else if (sdkState === 'INACTIVE') { state = MeetingState.LEFT; } else { state = this.meetings[ID].state; } this.meetings[ID] = {...this.meetings[ID], state}; }), ); const meetingsWithEvents$ = merge( meetingWithMediaReadyEvent$, meetingWithMediaStoppedEvent$, meetingWithLocalUpdateEvent$, meetingWithLocalShareStoppedEvent$, meetingWithMediaShareEvent$, meetingWithMediaStoppedShareEvent$, meetingWithRosterToggleEvent$, meetingWithSettingsToggleEvent$, meetingStateChange$, meetingWithSwitchCameraEvent$, meetingWithSwitchMicrophoneEvent$, meetingWithSwitchSpeakerEvent$, ).pipe(map(() => this.meetings[ID])); // Return a meeting object from event const getMeetingWithEvents$ = concat(getMeeting$, meetingsWithEvents$); // Convert to a multicast observable this.getMeetingObservables[ID] = getMeetingWithEvents$.pipe( publishReplay(1), refCount(), takeWhile((meeting) => meeting.state && meeting.state !== MeetingState.LEFT, true), ); } return this.getMeetingObservables[ID]; } }
JavaScript
class OdorDataStore extends DataStore { constructor() { // run constructor in parent class super(); // make add promise this.add = (odor) => { return new Promise((resolve, reject) => { try { // make a new odor reference with an auto-generated id let transaction = firebase.database().ref("odors").push(); // dispatch set event to listener transaction.set({ UserId: odor.userid, UserName: odor.username, UserType: odor.usertype, UserOrigin: odor.userorigin, Intensity: odor.intensity, Nuisance: odor.nuisance, Type: odor.type, Origin: odor.origin, Address: odor.address, Latitude: odor.latitude, Longitude: odor.longitude, Date: odor.date, Begin: odor.begin, End: odor.end }).then(() => { // set identifier data odor.id = transaction.key; // resolve promise resolve(odor); }) // request is incorrectly returned .catch((error) => { // reject promise reject(error); }); } catch (error) { // reject promise reject(error); } }); }; // make update promise this.update = (odor) => { return new Promise((resolve, reject) => { try { // dispatch set event to listener firebase.database().ref("odors/" + odor.id).set({ UserId: odor.userid, UserName: odor.username, UserType: odor.usertype, UserOrigin: odor.userorigin, Intensity: odor.intensity, Nuisance: odor.nuisance, Type: odor.type, Origin: odor.origin, Address: odor.address, Latitude: odor.latitude, Longitude: odor.longitude, Date: odor.date, Begin: odor.begin, End: odor.end }).then(() => { // resolve promise resolve(odor); }) // request is incorrectly returned .catch((error) => { // reject promise reject(error); }); } catch (error) { // reject promise reject(error); } }); }; // make remove promise this.remove = (odor) => { return new Promise((resolve, reject) => { try { // dispatch set event to listener firebase.database().ref("odors/" + odor.id).remove().then(() => { // resolve promise resolve(odor); }) // request is incorrectly returned .catch((error) => { // reject promise reject(error); }); } catch (error) { // reject promise reject(error); } }); }; // make query promise this.query = (odor, filter) => { return new Promise((resolve, reject) => { try { // verify listener if (this.listener) { // turn off listener this.listener.off(); } // verify filter if (filter) { // set listener with filter this.listener = firebase.database().ref("odors").orderByChild("Date").startAt(filter.begin).endAt(filter.end); } else { // verify odor if (odor.id) { // set listener with odor this.listener = firebase.database().ref("odors/" + odor.id); } else { // set listener with user this.listener = firebase.database().ref("odors").orderByChild("UserId").equalTo(odor.userid); } } // make add listener this.listener.on("child_added", (data) => { // dispatch added event to odor data this.added(this.convert(data)); }); // make change listener this.listener.on("child_changed", (data) => { // dispatch changed event to odor data this.changed(this.convert(data)); }); // make remove listener this.listener.on("child_removed", (data) => { // dispatch removed event to odor data this.removed(data.key); }); // resolve promise resolve(); } catch (error) { // reject promise reject(error); } }); }; } /** * @param {Object} data */ convert(data) { // make odor with data let odor = new Odor(); odor.id = data.key; odor.userid = data.val().UserId; odor.username = data.val().UserName; odor.usertype = data.val().UserType; odor.userorigin = data.val().UserOrigin; odor.intensity = data.val().Intensity; odor.nuisance = data.val().Nuisance; odor.type = data.val().Type; odor.origin = data.val().Origin; odor.address = data.val().Address; odor.latitude = data.val().Latitude; odor.longitude = data.val().Longitude; odor.date = data.val().Date; odor.begin = data.val().Begin; odor.end = data.val().End; // return return odor; } /** * @returns {function} listener */ get listener() { return this._listener; } /** * @param {function} listener */ set listener(listener) { this._listener = listener; } /** * @returns {function} added */ get added() { return this._added; } /** * @param {function} added */ set added(added) { this._added = added; } /** * @returns {function} changed */ get changed() { return this._changed; } /** * @param {function} changed */ set changed(changed) { this._changed = changed; } /** * @returns {function} removed */ get removed() { return this._removed; } /** * @param {function} removed */ set removed(removed) { this._removed = removed; } }
JavaScript
class OdorSession { /** * @param {string} user */ set user(user) { window.sessionStorage.setItem("user", user); } /** * @returns {string} user */ get user() { return window.sessionStorage.getItem("user"); } /** * @param {string} odor */ set odor(odor) { window.sessionStorage.setItem("odor", odor); } /** * @returns {string} odor */ get odor() { return window.sessionStorage.getItem("odor"); } /** * @param {string} id */ set id(id) { window.sessionStorage.setItem("id", id); } /** * @returns {string} id */ get id() { return window.sessionStorage.getItem("id"); } /** * @param {string} userid */ set userid(userid) { window.sessionStorage.setItem("userid", userid); } /** * @returns {string} userid */ get userid() { return window.sessionStorage.getItem("userid"); } /** * @param {string} username */ set username(username) { window.sessionStorage.setItem("username", username); } /** * @returns {string} username */ get username() { return window.sessionStorage.getItem("username"); } /** * @param {string} usertype */ set usertype(usertype) { window.sessionStorage.setItem("usertype", usertype); } /** * @returns {string} usertype */ get usertype() { return window.sessionStorage.getItem("usertype"); } /** * @param {string} userorigin */ set userorigin(userorigin) { window.sessionStorage.setItem("userorigin", userorigin); } /** * @returns {string} userorigin */ get userorigin() { return window.sessionStorage.getItem("userorigin"); } /** * @param {string} intensity */ set intensity(intensity) { window.sessionStorage.setItem("intensity", intensity); } /** * @returns {string} intensity */ get intensity() { return window.sessionStorage.getItem("intensity"); } /** * @param {string} nuisance */ set nuisance(nuisance) { window.sessionStorage.setItem("nuisance", nuisance); } /** * @returns {string} nuisance */ get nuisance() { return window.sessionStorage.getItem("nuisance"); } /** * @param {string} type */ set type(type) { window.sessionStorage.setItem("type", type); } /** * @returns {string} type */ get type() { return window.sessionStorage.getItem("type"); } /** * @param {string} origin */ set origin(origin) { window.sessionStorage.setItem("origin", origin); } /** * @returns {string} origin */ get origin() { return window.sessionStorage.getItem("origin"); } /** * @param {string} address */ set address(address) { window.sessionStorage.setItem("address", address); } /** * @returns {string} address */ get address() { return window.sessionStorage.getItem("address"); } /** * @param {number} latitude */ set latitude(latitude) { window.sessionStorage.setItem("latitude", latitude.toString(10)); } /** * @returns {number} latitude */ get latitude() { return Number(window.sessionStorage.getItem("latitude") || "0"); } /** * @param {number} longitude */ set longitude(longitude) { window.sessionStorage.setItem("longitude", longitude.toString(10)); } /** * @returns {number} longitude */ get longitude() { return Number(window.sessionStorage.getItem("longitude") || "0"); } /** * @param {string} date */ set date(date) { window.sessionStorage.setItem("date", date); } /** * @returns {string} date */ get date() { return window.sessionStorage.getItem("date"); } /** * @param {string} begin */ set begin(begin) { window.sessionStorage.setItem("begin", begin); } /** * @returns {string} begin */ get begin() { return window.sessionStorage.getItem("begin"); } /** * @param {string} end */ set end(end) { window.sessionStorage.setItem("end", end); } /** * @returns {string} end */ get end() { return window.sessionStorage.getItem("end"); } /** * remove all saved data from session */ clear() { window.sessionStorage.clear(); } }
JavaScript
class EmailGenerator { /** * Configure Mailgen by setting the theme * @static *@memberof EmailGenerator @returns {Object} - It return the default email generator provided */ static configMailGen() { const mail = new Mailgen({ theme: 'default', product: { name: 'Crpto Wallet', link: 'http://localhost:3000/api/v1', }, }); return mail; } /** * Generate a email for user to confirm the email provided during signup; * @static * @param { String } firstName - user first name * @param { String } mailLink - link to verify email *@memberof EmailGenerator @returns {Object} - It returns the object of email format provided */ static mailGenEmailFormat(firstName, mailLink) { const body = { body: { name: firstName, intro: "Welcome to Cryto Wallet! We're very excited to have you on board.", action: { instructions: 'To join the league', button: { color: '#22BC66', text: 'verify your account', link: mailLink, }, }, outro: 'This is a no-reply email. Do not reply to this email as we cannot respond to queries sent to this email address. For assistance please email us directly', }, }; return body; } /** * Generate a email for user to intitiate the change password process; * @static * @param { String } mailLink - link to verify email *@memberof EmailGenerator @returns {Object} - It returns the object of email format provided */ static resetPasswordMailGenFormat(mailLink) { const body = { body: { name: 'There', intro: 'Reset your password', action: { instructions: 'We received a request to reset your password, click here to continue', button: { color: '#22BC66', text: 'Reset your password', link: mailLink, }, }, outro: 'This is a no-reply email. Do not reply to this email as we cannot respond to queries sent to this email address. For assistance please email us directly', }, }; return body; } }
JavaScript
class AWSS3DBI extends CloudDBI { /* ** ** Extends LoaderDBI enabling operations on Amazon Web Services S3 Buckets rather than a local file system. ** ** !!! Make sure your head is wrapped around the following statements before touching this code. ** ** An Export operaton involves reading data from the S3 object store ** An Import operation involves writing data to the S3 object store ** */ static #_YADAMU_DBI_PARAMETERS static get YADAMU_DBI_PARAMETERS() { this.#_YADAMU_DBI_PARAMETERS = this.#_YADAMU_DBI_PARAMETERS || Object.freeze(Object.assign({},DBIConstants.YADAMU_DBI_PARAMETERS,AWSS3Constants.DBI_PARAMETERS)) return this.#_YADAMU_DBI_PARAMETERS } get YADAMU_DBI_PARAMETERS() { return AWSS3DBI.YADAMU_DBI_PARAMETERS } get DATABASE_KEY() { return AWSS3Constants.DATABASE_KEY}; get DATABASE_VENDOR() { return AWSS3Constants.DATABASE_VENDOR}; get SOFTWARE_VENDOR() { return AWSS3Constants.SOFTWARE_VENDOR}; get PROTOCOL() { return AWSS3Constants.PROTOCOL } get BUCKET() { this._BUCKET = this._BUCKET || (() => { const bucket = this.parameters.BUCKET || AWSS3Constants.BUCKET this._BUCKET = YadamuLibrary.macroSubstitions(bucket, this.yadamu.MACROS) return this._BUCKET })(); return this._BUCKET } get STORAGE_ID() { return this.BUCKET } constructor(yadamu,settings,parameters) { super(yadamu,settings,parameters) } async finalize() { await Promise.all(Array.from(this.cloudService.writeOperations)) super.finalize() } updateVendorProperties(vendorProperties) { let url = vendorProperties.endpoint url = url && url.indexOf('://') < 0 ? `http://${url}` : url try { url = new URL(url ? url : 'http://0.0.0.0') } catch (e) { this.yadamuLogger.error([this.DATABASE_VENDOR,'CONNECTION'],`Invalid endpoint specified: "${vendorProperties.endpoint}"`) this.yadamuLogger.handleException([this.DATABASE_VENDOR,'CONNECTION'],e) url = new URL('http://0.0.0.0') } url.protocol = this.parameters.PROTOCOL || url.protocol url.hostname = this.parameters.HOSTNAME || url.hostname url.port = this.parameters.PORT || url.port url = url.toString() vendorProperties.accessKeyId = this.parameters.USERNAME || vendorProperties.accessKeyId vendorProperties.secretAccessKey = this.parameters.PASSWORD || vendorProperties.secretAccessKey vendorProperties.region = this.parameters.REGION || vendorProperties.region vendorProperties.endpoint = url vendorProperties.s3ForcePathStyle = true vendorProperties.signatureVersion = "v4" } getCredentials(vendorKey) { switch (vendorKey) { case 'snowflake': return `AWS_KEY_ID = '${this.vendorProperties.accessKeyId}' AWS_SECRET_KEY = '${this.vendorProperties.secretAccessKey}'`; } return '' } async createConnectionPool() { // this.yadamuLogger.trace([this.constructor.name],`new AWS.S3()`) this.cloudConnection = await new AWS.S3(this.vendorProperties) this.cloudService = new AWSS3StorageService(this.cloudConnection,this.BUCKET,{},this.yadamuLogger) } /* ** ** Remember: Export is Reading data from an S3 Object Store - load. ** */ parseContents(fileContents) { return JSON.parse(fileContents.Body.toString()) } classFactory(yadamu) { return new AWSS3DBI(yadamu) } getCredentials(vendorKey) { switch (vendorKey) { case 'snowflake': return `AWS_KEY_ID = '${this.vendorProperties.accessKeyId}' AWS_SECRET_KEY = '${this.vendorProperties.secretAccessKey}'`; } return '' } }
JavaScript
class LoggingSocket extends WebSocket { constructor(address, protocols, options) { super(address, protocols, options); this.on('error', e => { vscode_debugadapter_1.logger.log('Websocket error: ' + e.toString()); }); this.on('close', () => { vscode_debugadapter_1.logger.log('Websocket closed'); }); this.on('message', msgStr => { let msgObj; try { msgObj = JSON.parse(msgStr.toString()); } catch (e) { vscode_debugadapter_1.logger.error(`Invalid JSON from target: (${e.message}): ${msgStr}`); return; } if (msgObj && !(msgObj.method && msgObj.method.startsWith('Network.'))) { // Not really the right place to examine the content of the message, but don't log annoying Network activity notifications. if ((msgObj.result && msgObj.result.scriptSource)) { // If this message contains the source of a script, we log everything but the source msgObj.result.scriptSource = '<removed script source for logs>'; vscode_debugadapter_1.logger.verbose('← From target: ' + JSON.stringify(msgObj)); } else { vscode_debugadapter_1.logger.verbose('← From target: ' + msgStr); } } }); } send(data, opts, cb) { const msgStr = JSON.stringify(data); if (this.readyState !== WebSocket.OPEN) { vscode_debugadapter_1.logger.log(`→ Warning: Target not open! Message: ${msgStr}`); return; } super.send.apply(this, arguments); vscode_debugadapter_1.logger.verbose('→ To target: ' + msgStr); } }
JavaScript
class ChromeConnection { constructor(targetDiscovery, targetFilter) { this._targetFilter = targetFilter; this._targetDiscoveryStrategy = targetDiscovery || new chromeTargetDiscoveryStrategy_1.ChromeTargetDiscovery(vscode_debugadapter_1.logger, telemetry_1.telemetry); this.events = new executionTimingsReporter_1.StepProgressEventsEmitter([this._targetDiscoveryStrategy.events]); } get isAttached() { return !!this._client; } get api() { return this._client && this._client.api(); } get attachedTarget() { return this._attachedTarget; } setTargetFilter(targetFilter) { this._targetFilter = targetFilter; } /** * Attach the websocket to the first available tab in the chrome instance with the given remote debugging port number. */ attach(address = '127.0.0.1', port = 9222, targetUrl, timeout, extraCRDPChannelPort) { return this._attach(address, port, targetUrl, timeout, extraCRDPChannelPort) .then(() => { }); } attachToWebsocketUrl(wsUrl, extraCRDPChannelPort) { /* __GDPR__FRAGMENT__ "StepNames" : { "Attach.AttachToTargetDebuggerWebsocket" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" } } */ this.events.emitStepStarted('Attach.AttachToTargetDebuggerWebsocket'); this._socket = new LoggingSocket(wsUrl, undefined, { headers: { Host: 'localhost' } }); if (extraCRDPChannelPort) { this._crdpSocketMultiplexor = new crdpMultiplexor_1.CRDPMultiplexor(this._socket); new webSocketToLikeSocketProxy_1.WebSocketToLikeSocketProxy(extraCRDPChannelPort, this._crdpSocketMultiplexor.addChannel('extraCRDPEndpoint')).start(); this._client = new noice_json_rpc_1.Client(this._crdpSocketMultiplexor.addChannel('debugger')); } else { this._client = new noice_json_rpc_1.Client(this._socket); } this._client.on('error', e => vscode_debugadapter_1.logger.error('Error handling message from target: ' + e.message)); } getAllTargets(address = '127.0.0.1', port = 9222, targetFilter, targetUrl) { return this._targetDiscoveryStrategy.getAllTargets(address, port, targetFilter, targetUrl); } _attach(address, port, targetUrl, timeout = ChromeConnection.ATTACH_TIMEOUT, extraCRDPChannelPort) { let selectedTarget; return utils.retryAsync(() => this._targetDiscoveryStrategy.getTarget(address, port, this._targetFilter, targetUrl), timeout, /*intervalDelay=*/ 200) .catch(err => Promise.reject(errors.runtimeConnectionTimeout(timeout, err.message))) .then(target => { selectedTarget = target; return this.attachToWebsocketUrl(target.webSocketDebuggerUrl, extraCRDPChannelPort); }).then(() => { this._attachedTarget = selectedTarget; }); } run() { // This is a CDP version difference which will have to be handled more elegantly with others later... // For now, we need to send both messages and ignore a failing one. return Promise.all([ this.api.Runtime.runIfWaitingForDebugger(), this.api.Runtime.run() ]) .then(() => { }, () => { }); } close() { this._socket.close(); } onClose(handler) { this._socket.on('close', handler); } get version() { return this._attachedTarget.version .then(version => { return (version) ? version : new chromeTargetDiscoveryStrategy_1.TargetVersions(chromeTargetDiscoveryStrategy_1.Version.unknownVersion(), chromeTargetDiscoveryStrategy_1.Version.unknownVersion()); }); } }
JavaScript
class TaskDef { /** * Constructs an executable task definition, if the given parent is undefined and the given execute is a function; * or constructs an executable sub-task definition, if parent is defined and execute is a function; or constructs a * non-executable, externally managed sub-task definition, if parent is defined and execute is undefined; otherwise * throws an error. * * If parent is not specified, then this new task definition is assumed to be a top-level, executable task definition * and the given execute function must be defined and a valid function. * * If parent is specified, then this new task definition is assumed to be a sub-task definition of the given parent * task definition and the given execute function must be either undefined or a valid function. * * @param {string} name - the mandatory name of the task * @param {Function|undefined} [execute] - the optional function to be executed when a task created using this definition is started * @param {TaskDef|undefined} [parent] - an optional parent task definition * @param {TaskDefSettings|undefined} [settings] - optional settings to use to configure this task definition * @throws {Error} an error if the requested task definition is invalid */ constructor(name, execute, parent, settings) { // Validate the given name // ----------------------------------------------------------------------------------------------------------------- // Ensure name is a string and not blank if (!isString(name) || isBlank(name)) { throw new Error(`Cannot create a task definition with a ${!isString(name) ? "non-string" : "blank"} name (${JSON.stringify(name)})`); } const taskName = name.trim(); const skipAddToParent = settings && settings.skipAddToParent; // Validate the given parent and the given execute function // ----------------------------------------------------------------------------------------------------------------- if (parent) { // Creating a sub-task definition, so: // Ensure that the parent is a TaskDef itself if (!isInstanceOf(parent, TaskDef)) { throw new Error(`Cannot create a sub-task definition (${taskName}) with a parent that is not a task (or sub-task) definition`); } // Ensure that execute (if defined) is actually executable (i.e. a valid function) if (execute !== undefined && typeof execute !== 'function') { throw new Error(`Cannot create an executable sub-task definition (${taskName}) with an invalid execute function`); } // Ensure the parent's sub-task names will still be distinct if we include this new sub-task's name if (!skipAddToParent && !TaskDef.areSubTaskNamesDistinct(parent, taskName)) { throw new Error(`Cannot add a sub-task definition (${taskName}) with a duplicate name to parent (${parent.name}) with existing sub-task definitions ${JSON.stringify(parent.subTaskDefs.map(d => d.name))}`); } } else { // Creating an executable, top-level task definition, so: // Ensure that a top-level task definition does have an execute function, since a non-executable, top-level task would be useless if (!execute) { throw new Error(`Cannot create a top-level task definition (${taskName}) without an execute function)`); } // Ensure that execute (if defined) is actually executable (i.e. a valid function) if (typeof execute !== 'function') { throw new Error(`Cannot create a top-level task definition (${taskName}) with an invalid execute function`); } } // Finalise the new task definition's parent and execute const taskParent = parent ? parent : undefined; // or null? const managed = !execute || undefined; const taskExecute = execute || undefined; // Finally create each property as read-only (writable: false and configurable: false are defaults) // ----------------------------------------------------------------------------------------------------------------- Object.defineProperty(this, 'name', {value: taskName, enumerable: true}); Object.defineProperty(this, 'managed', {value: managed, enumerable: true}); Object.defineProperty(this, 'execute', {value: taskExecute, enumerable: false}); Object.defineProperty(this, 'subTaskDefs', {value: [], enumerable: true}); // Set the optional describeItem function (if any provided) const describeItem = settings && typeof settings.describeItem === 'function' ? settings.describeItem : undefined; Object.defineProperty(this, 'describeItem', {value: describeItem, writable: true, enumerable: false}); // Ensure that the proposed combined hierarchy to be formed from this new task definition and its parent // will still be valid and will ONLY contain distinct task definitions // ----------------------------------------------------------------------------------------------------------------- if (taskParent) { // NB: Must check this after adding sub-tasks, but before setting parent! TaskDef.ensureAllTaskDefsDistinct(taskParent, this); } // Link this new task definition to its parent (if any) // ----------------------------------------------------------------------------------------------------------------- Object.defineProperty(this, 'parent', {value: taskParent, enumerable: false}); if (taskParent && !skipAddToParent) { taskParent.subTaskDefs.push(this); } } /** * Returns true if this defines executable tasks; false otherwise * @returns {boolean} true if executable; false otherwise */ get executable() { return !this.managed; } /** * Marks this task definition as unusable (if true) or active (if false) * @param {boolean} unusable - whether this task definition is to be considered unusable or not (default undefined, i.e. not) */ set unusable(unusable) { if (unusable) Object.defineProperty(this, '_unusable', {value: unusable, enumerable: false, writable: true, configurable: true}); else delete this._unusable; } /** * Returns true if this task definition is marked as unusable or false if its not (i.e. if its active). * @return {boolean} true if unusable; false otherwise */ get unusable() { return !!this._unusable; } /** * Sets this task definition's `describeItem` function to the given function (if it's a function) or sets it to * undefined (if it's NOT a function), but ONLY if either the definition's `describeItem is NOT already set or if the * given`overrideExisting` flag is true. * @param {DescribeItem|undefined} [describeItem] - sets the `describeItem` function to the given function * @param {boolean|undefined} [overrideExisting] - whether to override an existing `describeItem` function or not (default not) */ setDescribeItem(describeItem, overrideExisting) { if (!this.describeItem || overrideExisting) { this.describeItem = typeof describeItem === 'function' ? describeItem : undefined; } } /** * Creates a new top-level, executable task definition to be used for creating executable tasks. Both the given name * and execute function MUST be correctly defined; otherwise an appropriate error will be thrown. * * As soon as you have defined your top-level task, you can start adding sub-task definitions to it (if necessary) using * {@linkcode TaskDef#defineSubTask} and/or {@linkcode TaskDef#defineSubTasks}, which return the newly created sub-task * definition(s). * * If any of your new sub-task definitions also need to have sub-task definitions of their own, then simply use exactly * the same procedure to add "sub-subTask" definitions to your sub-task definition. * * @param {string} taskName - the name of the task * @param {Function} execute - the function to be executed when a task created using this definition is started * @param {TaskDefSettings|undefined} [settings] - optional settings to use to configure this task definition * @throws {Error} if taskName or execute are invalid * @returns {TaskDef} a new executable task definition. */ static defineTask(taskName, execute, settings) { return new TaskDef(taskName, execute, undefined, settings); } /** * Creates and adds an executable sub-task definition (if execute is defined) or a non-executable, managed sub-task * definition (if execute is undefined) with the given name to this task definition. * @param {string} subTaskName - the name of the new sub-task definition * @param {Function|undefined} [execute] - the optional function to be executed when a sub-task created using this definition is executed * @param {TaskDefSettings|undefined} [settings] - optional settings to use to configure this task definition * @throws {Error} an error if the given name is blank or not a string or not distinct */ defineSubTask(subTaskName, execute, settings) { if (!isString(subTaskName) || isBlank(subTaskName)) { throw new Error(`Cannot create a sub-task definition with a ${!isString(subTaskName) ? "non-string" : "blank"} name (${JSON.stringify(subTaskName)})`); } const newName = subTaskName.trim(); // Ensure that execute (if defined) is actually executable (i.e. a valid function) if (execute !== undefined && typeof execute !== 'function') { throw new Error(`Cannot create an executable sub-task definition (${newName}) with an invalid execute function`); } const skipAddToParent = settings && settings.skipAddToParent; // Ensure this task definition's sub-task names will still be distinct if we include the new sub-task's name if (!skipAddToParent && !TaskDef.areSubTaskNamesDistinct(this, newName)) { throw new Error(`Cannot add sub-task definition (${newName}) with a duplicate name to task definition (${this.name}) with existing sub-task definitions ${JSON.stringify(this.subTaskDefs.map(d => d.name))}`); } // Create and add the new sub-task definition to this task definition's list of sub-task definitions return new TaskDef(newName, execute, this, settings); } /** * Creates and adds multiple new non-executable, managed sub-task definitions with the given names to this task * definition. * @param {string[]} subTaskNames - the names of the new non-executable, managed sub-task definitions * @param {TaskDefSettings|undefined} [settings] - optional settings to use to configure these task definitions * @returns {TaskDef[]} an array of new sub-task definitions (one for each of the given names) */ defineSubTasks(subTaskNames, settings) { if (!isArrayOfType(subTaskNames, "string")) { throw new Error(`Cannot create sub-task definitions with non-string names ${JSON.stringify(subTaskNames)}`); } if (subTaskNames.length > 0) { if (!subTaskNames.every(name => isNotBlank(name))) { throw new Error(`Cannot create sub-task definitions with blank names ${JSON.stringify(subTaskNames)}`); } const newNames = subTaskNames.map(n => n.trim()); // Ensure this task definition's sub-task names will still be distinct if we include the new sub-task names if (!TaskDef.areSubTaskNamesDistinct(this, newNames)) { throw new Error(`Cannot add sub-task definitions ${JSON.stringify(newNames)} with duplicate names to task definition (${this.name}) with existing sub-task definitions ${JSON.stringify(this.subTaskDefs.map(d => d.name))}`); } // Create and add the new sub-task definitions to this task definition's list of sub-task definitions return newNames.map(name => new TaskDef(name, undefined, this, settings)); } return []; } /** * Cautiously attempts to get the root task definition for the given task definition by traversing up its task * definition hierarchy using the parent links, until it finds the root (i.e. a parent task definition with no parent). * During this traversal, if any task definition is recursively found to be a parent of itself, an error will be thrown. * * @param {TaskDef} taskDef - any task definition in the task definition hierarchy from which to start * @throws {Error} if any task definition is recursively a parent of itself * @returns {TaskDef} the root task definition */ static getRootTaskDef(taskDef) { if (!taskDef || typeof taskDef !== 'object') { return undefined; } function loop(def, history) { const parent = def.parent; if (!parent) { return def; } if (history.indexOf(def) !== -1) { // We have an infinite loop, since a previously visited task is recursively a parent of itself! throw new Error(`Task hierarchy is not a valid Directed Acyclic Graph, since task definition (${def.name}) is recursively a parent of itself!`) } history.push(def); return loop(parent, history); } return loop(taskDef, []); } /** * Ensures that the task definition hierarchies of both the given proposed task definition and of the given parent task * definition (if any) are both valid and could be safely combined into a single valid hierarchy; and, if not, throws an * error. * * A valid hierarchy must only contain distinct task definitions (i.e. every task definition can only appear once in its * hierarchy). This requirement ensures that a hierarchy is a Directed Acyclic Graph and avoids infinite loops. * * NB: The proposed task definition MUST NOT be linked to the given parent BEFORE calling this function (otherwise * this function will always throw an error) and MUST only be subsequently linked to the given parent if this function * does NOT throw an error. * * @param {TaskDef|undefined} [parent] - an optional parent task (or sub-task) definition (if any), which identifies the * first hierarchy to check and to which the proposed task definition is intended to be linked * @param {TaskDef|undefined} proposedTaskDef - a optional proposed task definition, which identifies the second * hierarchy to check * @throws {Error} if any task definition appears more than once in either hierarchy or in the proposed combination of * both hierarchies */ static ensureAllTaskDefsDistinct(parent, proposedTaskDef) { // First find the root of the parent's task hierarchy const parentRoot = parent ? TaskDef.getRootTaskDef(parent) : undefined; // Next find the root of the proposed task definition's task hierarchy const proposedTaskDefRoot = proposedTaskDef ? TaskDef.getRootTaskDef(proposedTaskDef) : undefined; function loop(taskDef, history) { if (!taskDef) { return; } // Ensure that this definition does not appear more than once in the hierarchy if (history.indexOf(taskDef) !== -1) { // We have a problem with this task hierarchy, since a previously visited task definition appears more than once in the hierarchy! throw new Error(`Task hierarchy is not a valid Directed Acyclic Graph, since task definition (${taskDef.name}) appears more than once in the hierarchy!`) } // Remember that we have seen this one history.push(taskDef); // Now check all of its sub-task definitions recursively too const subTaskDefs = taskDef.subTaskDefs; for (let i = 0; i < subTaskDefs.length; ++i) { loop(subTaskDefs[i], history); } } const history = []; // Next loop from the parent's root down through all of its sub-task definitions recursively, ensuring that there is no // duplication of any task definition in the parent's hierarchy loop(parentRoot, history); // Finally loop from the proposed task definition's root down through all of its sub-task definitions recursively, // ensuring that there is no duplication of any task definition in either hierarchy loop(proposedTaskDefRoot, history); } /** * Returns true if the proposed sub-task names together with the given parent task definition's sub-task names are all * still distinct; otherwise returns false. * @param parent * @param {string|string[]} proposedNames - the name or names of the proposed sub-task definitions to be checked */ static areSubTaskNamesDistinct(parent, proposedNames) { const oldNames = parent ? parent.subTaskDefs.map(d => d.name) : []; const newNames = oldNames.concat(proposedNames); return isDistinct(newNames); } }
JavaScript
class Api { constructor(coin, network) { this.coin = coin; this.network = network; } url = path => { return "https://api.rawtx.com" + path; }; log = (...args) => { if (__DEV__) { console.log("Api", ...args); } }; blockCount = async () => { try { const r = await fetch( this.url("/" + this.coin + "/" + this.network + "/block_count") ); const j = await r.json(); return j.count; } catch (err) { return 0; } }; prices = async () => { try { return await (await fetch(this.url("/" + this.coin + "/prices"))).json(); } catch (err) { return {}; } }; }
JavaScript
class BookList extends Component { renderList() { return this.props.books.map((book) => { return ( <li key={book.title} onClick={() => this.props.selectBook(book)} className="list-group-item"> {book.title} </li> ) }); } render() { return ( <ul className="list-group col-sm-4"> {this.renderList()} </ul> ) } }
JavaScript
class UriComponent extends expressionEvaluator_1.ExpressionEvaluator { /** * Initializes a new instance of the [UriComponent](xref:adaptive-expressions.UriComponent) class. */ constructor() { super(expressionType_1.ExpressionType.UriComponent, UriComponent.evaluator(), returnType_1.ReturnType.String, functionUtils_1.FunctionUtils.validateUnary); } /** * @private */ static evaluator() { return functionUtils_1.FunctionUtils.apply((args) => encodeURIComponent(args[0]), functionUtils_1.FunctionUtils.verifyString); } }
JavaScript
class Product extends Base { constructor(client, data) { super(client); if (data) this._patch(data); } _patch(data) { /** * Product ID * @type {string} */ this.id = data.id; /** * Price * @type {string} */ this.price = data.price ? data.price : ''; /** * Product Thumbnail * @type {string} */ this.thumbnailUrl = data.thumbnailUrl; /** * Currency * @type {string} */ this.currency = data.currency; /** * Product Name * @type {string} */ this.name = data.name; /** * Product Quantity * @type {number} */ this.quantity = data.quantity; /** Product metadata */ this.data = null; return super._patch(data); } async getData() { if (this.data === null) { let result = await this.client.pupPage.evaluate((productId) => { return window.WWebJS.getProductMetadata(productId); }, this.id); if (!result) { this.data = undefined; } else { this.data = new ProductMetadata(this.client, result); } } return this.data; } }
JavaScript
class LCARSButton extends LCARSComponent { constructor(name, label, x, y, height, properties, auxLabel, auxLabelProperties) { super(name, label, x, y, properties); this.auxLabel = auxLabel; this.auxLabelProperties = auxLabelProperties; this.width = LCARS.LCARS_BTN_WIDTH; if((properties & LCARS.ES_RECT_RND) == 0) { this.height = height*LCARS.LCARS_BTN_HEIGHT + (height-1)*LCARS.LCARS_BTN_SPACING; } else { this.height = LCARS.LCARS_BTN_HEIGHT; } if((this.properties & LCARS.ES_FONT) == LCARS.EF_NORMAL) { this.fontSize = LCARS.FONT_BUTTON_SIZE; // the default font for button components } this.drawShape(); this.drawText(); if(this.auxLabel != "" && this.auxLabel != undefined) { this.drawAuxText(); } } setAuxText(textString) { this.auxTextElement.textContent = textString; } drawAuxText () { this.auxTextElement = document.createElementNS(LCARS.svgNS, "text"); this.auxTextElement.setAttribute("id", this.id + LCARS.AUX_TEXT_SUFFIX); this.auxTextElement.setAttribute("x", this.getAuxTextX()); this.auxTextElement.setAttribute("y", this.getAuxTextY()); this.auxTextElement.setAttribute("text-anchor", this.getAuxTextAnchor()); if(this.properties & LCARS.ES_DISABLED) { this.auxTextElement.setAttribute("fill", '#585858'); } else { this.auxTextElement.setAttribute("fill", LCARS.getColor(this.auxLabelProperties & LCARS.ES_COLOR)); } this.auxTextElement.setAttribute("font-family", LCARS.getFont()); this.auxTextElement.setAttribute("font-size", this.getAuxLabelFontSize()); this.auxTextElement.setAttribute("pointer-events", "none"); this.setAuxText(this.auxLabel); this.element.appendChild(this.auxTextElement); } getAuxTextX() { var x = 0; switch(this.auxLabelProperties & LCARS.ES_LABEL) { case LCARS.ES_LABEL_C: case LCARS.ES_LABEL_S: case LCARS.ES_LABEL_N: x = this.width/2; break; case LCARS.ES_LABEL_SW: case LCARS.ES_LABEL_W: case LCARS.ES_LABEL_NW: x = LCARS.TEXT_X_INSET; break; case LCARS.ES_LABEL_NE: case LCARS.ES_LABEL_E: case LCARS.ES_LABEL_SE: default: x = this.width - LCARS.TEXT_X_INSET; break; } return x; } getAuxTextY() { var y = 0; switch(this.auxLabelProperties & LCARS.ES_LABEL) { case LCARS.ES_LABEL_C: case LCARS.ES_LABEL_W: case LCARS.ES_LABEL_E: y = this.height/2 + LCARS.FONT_BUTTON_SIZE/2; break; case LCARS.ES_LABEL_NW: case LCARS.ES_LABEL_N: case LCARS.ES_LABEL_NE: y = LCARS.FONT_BUTTON_SIZE; break; case LCARS.ES_LABEL_S: case LCARS.ES_LABEL_SW: case LCARS.ES_LABEL_SE: default: y = this.height - LCARS.TEXT_Y_INSET; break; } return y; } getAuxTextAnchor() { var textAnchor = ""; switch(this.auxLabelProperties & LCARS.ES_LABEL) { case LCARS.ES_LABEL_C: case LCARS.ES_LABEL_S: case LCARS.ES_LABEL_N: textAnchor = "middle"; break; case LCARS.ES_LABEL_SW: case LCARS.ES_LABEL_W: case LCARS.ES_LABEL_NW: textAnchor = "start"; break; case LCARS.ES_LABEL_NE: case LCARS.ES_LABEL_E: case LCARS.ES_LABEL_SE: default: textAnchor = "end"; break; } return textAnchor; } getAuxLabelFontSize() { switch(this.auxLabelProperties & LCARS.ES_FONT) { case LCARS.EF_TITLE: return LCARS.FONT_TITLE_SIZE; case LCARS.EF_SUBTITLE: return LCARS.FONT_SUBTITLE_SIZE; case LCARS.EF_BUTTON: return LCARS.FONT_BUTTON_SIZE; case LCARS.EF_TINY: return LCARS.FONT_TINY_SIZE case LCARS.EF_BODY: default: return LCARS.FONT_BODY_SIZE; } } }
JavaScript
class ToCiceroMarkVisitor { /** * Construct the parser. * @param {object} [options] configuration options */ constructor(options = {}) { let { rules = [], } = options; this.options = options; this.rules = [...rules, ...defaultRules]; } /** * Filter out cruft newline nodes inserted by the DOM parser. * * @param {Object} element DOM element * @return {Boolean} true if node is not a new line */ cruftNewline(element) { return !(element.nodeName === '#text' && element.nodeValue === '\n'); } /** * Deserialize a DOM element. * * @param {Object} element DOM element * @return {Any} node */ deserializeElement(element) { let node; //console.log('tagName', element.tagName); if (!element.tagName) { element.tagName = ''; } const next = elements => { if (Object.prototype.toString.call(elements) === '[object NodeList]') { elements = Array.from(elements); } switch (typeOf(elements)) { case 'array': return this.deserializeElements(elements); case 'object': return this.deserializeElement(elements); case 'null': case 'undefined': return; default: throw new Error( `The \`next\` argument was called with invalid children: "${elements}".` ); } }; for (const rule of this.rules) { if (!rule.deserialize) {continue;} const ret = rule.deserialize(element, next); const type = typeOf(ret); if ( type !== 'array' && type !== 'object' && type !== 'null' && type !== 'undefined' ) { throw new Error( `A rule returned an invalid deserialized representation: "${node}".` ); } if (ret === undefined) { continue; } else if (ret === null) { return null; // } else if (ret.object === 'mark') { // node = this.deserializeMark(ret); // will we need this?? } else { node = ret; } if (node.object === 'block' || node.object === 'inline') { node.data = node.data || {}; node.nodes = node.nodes || []; } else if (node.object === 'text') { node.marks = node.marks || []; node.text = node.text || ''; } break; } return node || next(element.childNodes); } /** * Deserialize an array of DOM elements. * * @param {Array} elements DOM elements * @return {Array} array of nodes */ deserializeElements(elements = []) { let nodes = []; elements.filter(this.cruftNewline).forEach(element => { // console.log('element -- ', element); const node = this.deserializeElement(element); // console.log('node -- ', node); switch (typeOf(node)) { case 'array': nodes = nodes.concat(node); break; case 'object': nodes.push(node); break; } }); return nodes; } /** * Converts an html string to a CiceroMark DOM * @param {string} input - html string * @param {string} [format] result format, defaults to 'concerto'. Pass * 'json' to return the JSON data. * @returns {*} CiceroMark DOM */ toCiceroMark(input, format='concerto') { let fragment; // eslint-disable-next-line no-undef if (typeof DOMParser === 'undefined') { fragment = JSDOM.fragment(input); } else { // eslint-disable-next-line no-undef fragment = new DOMParser().parseFromString(input, 'text/html'); } const children = Array.from(fragment.childNodes); // console.log('children -- ', children); const nodes = this.deserializeElements(children); // console.log('nodes', nodes); return { '$class': `${NS_PREFIX_CommonMarkModel}${'Document'}`, nodes, xmlns: 'http://commonmark.org/xml/1.0', }; } }
JavaScript
class SchemaEditor extends HashBrown.Views.Editors.ResourceEditor { /** * Fetches the model */ async fetch() { try { this.model = await HashBrown.Helpers.SchemaHelper.getSchemaById(this.modelId); this.allSchemas = await HashBrown.Helpers.SchemaHelper.getAllSchemas(); for(let i in this.allSchemas) { let id = this.allSchemas[i].id; this.allSchemas[i] = await HashBrown.Helpers.SchemaHelper.getSchemaById(id, true); if(this.model.parentSchemaId === id) { this.parentSchema = this.allSchemas[i]; } } super.fetch(); } catch(e) { UI.errorModal(e); } } /** * Gets a schema synchronously * * @param {String} id * * @return {HashBrown.Models.Schema} Schema */ getSchema(id) { for(let schema of this.allSchemas) { if(schema.id === id) { return schema; } } return null; } /** * Event: Click advanced. Routes to the JSON editor */ onClickAdvanced() { location.hash = location.hash.replace('/schemas/', '/schemas/json/'); } /** * Event: Click save */ async onClickSave() { this.$saveBtn.toggleClass('working', true); await HashBrown.Helpers.SchemaHelper.setSchemaById(this.modelId, this.model); this.$saveBtn.toggleClass('working', false); // If id changed, change the hash if(Crisp.Router.params.id != this.model.id) { location.hash = '/schemas/' + this.model.id; } } /** * Event: Change icon */ onClickChangeIcon() { let modal = new HashBrown.Views.Modals.IconModal(); modal.on('change', (newIcon) => { this.model.icon = newIcon; this.update(); }); } /** * Gets the schema icon * * @returns {String} Icon */ getIcon() { if(this.model.icon) { return this.model.icon; } if(this.parentSchema && this.parentSchema.icon) { return this.parentSchema.icon; } return 'cogs'; } /** * Renders a config editor based on a schema id * * @param {String} schemaId * @param {Object} config * @param {Boolean} onlyCustom * * @return {HTMLElement} Config editor */ renderConfigEditor(schemaId, config, onlyCustom) { let schema = this.getSchema(schemaId); if(!schema || (onlyCustom && schema.parentSchemaId !== 'fieldBase')) { return null; } let editor = HashBrown.Views.Editors.FieldEditors[schema.editorId]; if(!editor) { return null; } return editor.renderConfigEditor.call(this, config, schema.id); } /** * Renders the body * * @return {HTMLElement} body */ renderBody() { return _.div({class: 'editor__body'}, this.field( { isLocked: true, label: 'Id' }, new HashBrown.Views.Widgets.Input({ value: this.model.id, onChange: (newValue) => { this.model.id = newValue; } }) ), this.field( 'Name', new HashBrown.Views.Widgets.Input({ value: this.model.name, onChange: (newValue) => { this.model.name = newValue; } }) ), this.field( 'Icon', _.button({class: 'widget small widget--button fa fa-' + this.getIcon()}) .click(() => { this.onClickChangeIcon(); }) ), this.field( 'Parent', new HashBrown.Views.Widgets.Dropdown({ value: this.model.parentSchemaId, options: HashBrown.Helpers.SchemaHelper.getAllSchemas(this.model.type), valueKey: 'id', labelKey: 'name', disabledOptions: [ { id: this.model.id, name: this.model.name } ], onChange: (newParent) => { this.model.parentSchemaId = newParent; this.fetch(); } }) ) ); } /** * Renders this editor */ template() { return _.div({class: 'editor editor--schema' + (this.model.isLocked ? ' locked' : '')}, _.div({class: 'editor__header'}, _.span({class: 'editor__header__icon fa fa-' + this.getIcon()}), _.h4({class: 'editor__header__title'}, this.model.name) ), this.renderBody(), _.div({class: 'editor__footer'}, _.div({class: 'editor__footer__buttons'}, _.button({class: 'widget widget--button embedded'}, 'Advanced' ).click(() => { this.onClickAdvanced(); }), _.if(!this.model.isLocked, this.$saveBtn = _.button({class: 'widget widget--button editor__footer__buttons__save'}, _.span({class: 'widget--button__text-default'}, 'Save '), _.span({class: 'widget--button__text-working'}, 'Saving ') ).click(() => { this.onClickSave(); }) ) ) ) ); } }
JavaScript
class TagCopyItem { /** * Creates a new instance of <code>TagCopyItem</code>. * @param {object} tag */ constructor(tag) { this.$tag = tag this.$pasteCount = 0 } /** * Gets the number of item that have been pasted. * @return {number} */ get pasteCount() { return this.$pasteCount } /** * Sets the number of item that have been pasted. * @param {number} value */ set pasteCount(value) { this.$pasteCount = value } /** * Gets the tag of the copied item. * @return {Object} */ get tag() { return this.$tag } /** * Sets the tag of the copied item. * @param {Object} value */ set tag(value) { this.$tag = value } /** * Increments the number of pasted elements. */ increasePasteCount() { this.pasteCount++ } }
JavaScript
class TaggedNodeClipboardHelper extends BaseClass(IClipboardHelper) { /** * Nodes can be copied unconditionally. * @param {IGraphClipboardContext} context The context in which this interface is used, can be null * @param {IModelItem} item The item to be copied * @see Specified by {@link IClipboardHelper#shouldCopy}. * @return {boolean} */ shouldCopy(context, item) { return true } /** * Nodes can be cut unconditionally. * @param {IGraphClipboardContext} context The context in which this interface is used, can be null * @param {IModelItem} item The item to be cut * @see Specified by {@link IClipboardHelper#shouldCut}. * @return {boolean} */ shouldCut(context, item) { return true } /** * Nodes can be pasted unconditionally. * @param {IGraphClipboardContext} context The context in which this interface is used, can be null * @param {IModelItem} item The item to be pasted * @param {object} userData The state memento that had been created during cut or copy * @see Specified by {@link IClipboardHelper#shouldPaste}. * @return {boolean} */ shouldPaste(context, item, userData) { return true } /** * If the copied node has at least one label, we store a variant of the label text * (see {@link CopyItem} implementation). * @param {IGraphClipboardContext} context The context in which this interface is used, can be null * @param {IModelItem} item The item to be copied * @see Specified by {@link IClipboardHelper#copy}. * @return {Object} */ copy(context, item) { const node = item return node.labels.size > 0 ? new CopyItem(node.labels.get(0).text) : null } /** * If the cut node has at least one label, we store a variant of the label text * (see {@link CopyItem} implementation). * @param {IGraphClipboardContext} context The context in which this interface is used, can be null * @param {IModelItem} item The item to be cut * @see Specified by {@link IClipboardHelper#cut}. * @return {Object} */ cut(context, item) { const node = item return node.labels.size > 0 ? new CopyItem(node.labels.get(0).text) : null } /** * If the pasted node has at least one label, we change the text using the one that is provided * by <code>userData</code>. * @param {IGraphClipboardContext} context The context in which this interface is used, can be null * @param {Object} item The copied item The item to be pasted * @param {object} userData The state memento that had been created during cut or copy * @see Specified by {@link IClipboardHelper#paste}. */ paste(context, item, userData) { const node = item if (node.labels.size > 0 && userData instanceof CopyItem && context !== null) { context.targetGraph.setLabelText(node.labels.get(0), userData.toString()) } } }
JavaScript
class CopyItem { /** * Creates a new instance of <code>CopyItem</code>. * @param {string} text */ constructor(text) { this.$text = text this.$pasteCount = 0 } /** * Gets the number of pasted elements. * @return {number} */ get pasteCount() { return this.$pasteCount } /** * Sets the number of pasted elements. * @param {number} value */ set pasteCount(value) { this.$pasteCount = value } /** * Gets the text of the copied elements. * @return {string} */ get text() { return this.$text } /** * Sets the text of the copied elements. * @param {string} value */ set text(value) { this.$text = value } /** * Returns the label text of the copied item and the number of pasted elements as string. * @return {string} */ toString() { // We count how often we have been pasted and change the string // accordingly. // If we start from a new copy, the counter is thus reset (try it!) this.pasteCount++ if (this.pasteCount < 2) { return `Copy of ${this.text}` } return `Copy (${this.pasteCount}) of ${this.text}` } }
JavaScript
class AddExpensePage extends React.Component { onSubmit = (expense) => { // Dispatches an event to the redux store this.props.startAddExpense(expense) // Redirects the user back to the home-page this.props.history.push('/') } render() { return ( <div> <div className={"page-header"}> <div className={"content-container"}> <h1 className={"page-header__title"}>Add Expense</h1> </div> </div> <div className={"content-container"}> <ExpenseForm onSubmit={this.onSubmit} /> </div> </div> ) } }
JavaScript
class IconWidget extends BackboneWidget { render() { let { name, type, ...props } = this.stateProps(); const Component = icons[name][type]; return <Component {...props}>{props.children}</Component> } }
JavaScript
class ChartPlaceholder extends Component { render() { const { height } = this.props; return ( <div aria-hidden="true" className="woocommerce-chart-placeholder" style={ { height } } > <Spinner /> </div> ); } }
JavaScript
class Node { constructor(val) { this.val = val; this.next = null; } }