language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class ModelScene extends Scene { constructor({ canvas, element, width, height }) { super(); this[_a] = false; this.aspect = 1; this.shadow = null; this.shadowIntensity = 0; this.shadowSoftness = 1; this.width = 1; this.height = 1; this.isVisible = false; this.isDirty = false; this.exposure = 1; this.framedFieldOfView = DEFAULT_FOV_DEG; // These default camera values are never used, as they are reset once the // model is loaded and framing is computed. this.camera = new PerspectiveCamera(45, 1, 0.1, 100); this.name = 'ModelScene'; this.element = element; this.canvas = canvas; this.context = canvas.getContext('2d'); this.model = new Model(); // These default camera values are never used, as they are reset once the // model is loaded and framing is computed. this.camera = new PerspectiveCamera(45, 1, 0.1, 100); this.camera.name = 'MainCamera'; this.activeCamera = this.camera; this.pivot = new Object3D(); this.pivot.name = 'Pivot'; this.pivotCenter = new Vector3; this.skyboxMesh = this.createSkyboxMesh(); this.add(this.pivot); this.pivot.add(this.model); this.setSize(width, height); this.background = new Color(0xffffff); this.model.addEventListener('model-load', (event) => this.onModelLoad(event)); } get paused() { return this[$paused]; } pause() { this[$paused] = true; } resume() { this[$paused] = false; } /** * Sets the model via URL. */ async setModelSource(source, progressCallback) { try { await this.model.setSource(source, progressCallback); } catch (e) { throw new Error(`Could not set model source to '${source}': ${e.message}`); } } /** * Receives the size of the 2D canvas element to make according * adjustments in the scene. */ setSize(width, height) { if (width !== this.width || height !== this.height) { this.width = Math.max(width, 1); this.height = Math.max(height, 1); // In practice, invocations of setSize are throttled at the element level, // so no need to throttle here: const dpr = resolveDpr(); this.canvas.width = this.width * dpr; this.canvas.height = this.height * dpr; this.canvas.style.width = `${this.width}px`; this.canvas.style.height = `${this.height}px`; this.aspect = this.width / this.height; this.frameModel(); // Immediately queue a render to happen at microtask timing. This is // necessary because setting the width and height of the canvas has the // side-effect of clearing it, and also if we wait for the next rAF to // render again we might get hit with yet-another-resize, or worse we // may not actually be marked as dirty and so render will just not // happen. Queuing a render to happen here means we will render twice on // a resize frame, but it avoids most of the visual artifacts associated // with other potential mitigations for this problem. See discussion in // https://github.com/GoogleWebComponents/model-viewer/pull/619 for // additional considerations. Promise.resolve().then(() => { this.element[$renderer].render(performance.now()); }); } } /** * Set's the framedFieldOfView based on the aspect ratio of the window in * order to keep the model fully visible at any camera orientation. */ frameModel() { const vertical = DEFAULT_TAN_FOV * Math.max(1, this.model.fieldOfViewAspect / this.aspect); this.framedFieldOfView = 2 * Math.atan(vertical) * 180 / Math.PI; } /** * Returns the size of the corresponding canvas element. */ getSize() { return { width: this.width, height: this.height }; } /** * Returns the current camera. */ getCamera() { return this.activeCamera; } /** * Sets the passed in camera to be used for rendering. */ setCamera(camera) { this.activeCamera = camera; } /** * Sets the rotation of the model's pivot, around its pivotCenter point. */ setPivotRotation(radiansY) { this.pivot.rotation.y = radiansY; this.pivot.position.x = -this.pivotCenter.x; this.pivot.position.z = -this.pivotCenter.z; this.pivot.position.applyAxisAngle(this.pivot.up, radiansY); this.pivot.position.x += this.pivotCenter.x; this.pivot.position.z += this.pivotCenter.z; if (this.shadow != null) { this.shadow.setRotation(radiansY); } } /** * Gets the current rotation value of the pivot */ getPivotRotation() { return this.pivot.rotation.y; } /** * Called when the model's contents have loaded, or changed. */ onModelLoad(event) { this.frameModel(); this.setShadowIntensity(this.shadowIntensity); if (this.shadow != null) { this.shadow.setModel(this.model, this.shadowSoftness); } // Uncomment if using showShadowHelper below // if (this.children.length > 1) { // (this.children[1] as CameraHelper).update(); // } this.element[$needsRender](); this.dispatchEvent({ type: 'model-load', url: event.url }); } /** * Sets the shadow's intensity, lazily creating the shadow as necessary. */ setShadowIntensity(shadowIntensity) { this.shadowIntensity = shadowIntensity; if (shadowIntensity > 0 && this.model.hasModel()) { if (this.shadow == null) { this.shadow = new Shadow(this.model, this.pivot, this.shadowSoftness); this.pivot.add(this.shadow); // showShadowHelper(this); } this.shadow.setIntensity(shadowIntensity); } } /** * Sets the shadow's softness by mapping a [0, 1] softness parameter to the * shadow's resolution. This involves reallocation, so it should not be * changed frequently. Softer shadows are cheaper to render. */ setShadowSoftness(softness) { this.shadowSoftness = softness; if (this.shadow != null) { this.shadow.setSoftness(softness); } } createSkyboxMesh() { const geometry = new BoxBufferGeometry(1, 1, 1); geometry.deleteAttribute('normal'); geometry.deleteAttribute('uv'); const material = new ShaderMaterial({ uniforms: { envMap: { value: null }, opacity: { value: 1.0 } }, vertexShader: ShaderLib.cube.vertexShader, fragmentShader: ShaderLib.cube.fragmentShader, side: BackSide, // Turn off the depth buffer so that even a small box still ends up // enclosing a scene of any size. depthTest: false, depthWrite: false, fog: false, }); material.extensions = { derivatives: true, fragDepth: false, drawBuffers: false, shaderTextureLOD: false }; const samplerUV = ` #define ENVMAP_TYPE_CUBE_UV #define PI 3.14159265359 ${cubeUVChunk} uniform sampler2D envMap; `; material.onBeforeCompile = (shader) => { shader.fragmentShader = shader.fragmentShader.replace('uniform samplerCube tCube;', samplerUV) .replace('vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );', 'gl_FragColor = textureCubeUV( envMap, vWorldDirection, 0.0 );') .replace('gl_FragColor = mapTexelToLinear( texColor );', ''); }; const skyboxMesh = new Mesh(geometry, material); skyboxMesh.frustumCulled = false; // This centers the box on the camera, ensuring the view is not affected by // the camera's motion, which makes it appear inifitely large, as it should. skyboxMesh.onBeforeRender = function (_renderer, _scene, camera) { this.matrixWorld.copyPosition(camera.matrixWorld); }; return skyboxMesh; } skyboxMaterial() { return this.skyboxMesh.material; } }
JavaScript
class Search extends Component { search_items (search_term, items) { // In perfect match, all words in search term must be somewhere in item name or desc. // in inclusive match, at least one word in search term must be in name or desc. // and item is not in perfect match let perfect_match = []; let inclusive_match = []; let search_list = (search_term === '') ? [] : search_term.toLowerCase().replace(/[^a-z\s]+/g, '').split(' '); let temp_str_list = ''; let temp_item; let temp_is_perfect; let temp_is_inclusive; let temp_search_item; let j; for (let i = 0; i < items.length; i++) { temp_item = items[i]; temp_str_list = temp_item.name.toLowerCase() .replace(/[^a-z\s]+/g, '').split(' ') .concat(temp_item.description.toLowerCase() .replace(/[^a-z\s]+/g, '').split(' ')); temp_is_perfect = true; temp_is_inclusive = false; if (search_list.length === 0) temp_is_perfect = false; for (j = 0; j < search_list.length; j++) { temp_search_item = search_list[j]; // if we know that this not perfect and is inclusive, no reason to keep looking if ((!temp_is_perfect && temp_is_inclusive) || temp_search_item.length === 0) break; if (j !== search_list.length - 1) { if (temp_str_list.includes(temp_search_item)) { // if previously false, maintain false, otherwise true // temp_is_perfect = temp_is_perfect && true; // no matter what, this is now true temp_is_inclusive = true; } else { // no matter what, now imperfect temp_is_perfect = false; // if previously true, maintain true, otherwise false. // temp_is_inclusive = temp_is_inclusive || false; } } else { // if we're looking at the last search term word, check if it's a subset // of any words in item name or desc. let temp_item_str = temp_str_list.join(' '); if (temp_item_str.includes(temp_search_item)) { temp_is_inclusive = true; } else { temp_is_perfect = false; } } } if (temp_is_perfect) perfect_match.push(items[i]); else if (temp_is_inclusive) inclusive_match.push(items[i]); } return {'perfect_match': perfect_match, 'inclusive_match': inclusive_match}; } render() { let searched_items = this.search_items(this.props.search_term, this.props.items); let message = null; if(searched_items.perfect_match.length === 0 && searched_items.inclusive_match.length === 0) message = <h3>No items matched your search</h3>; let separate = null; if(searched_items.perfect_match.length > 0 && searched_items.inclusive_match.length > 0) separate = <hr className="search" />; return ( <div> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to our Store</h1> </header> <p className="App-intro"> Searching for {this.props.search_term} </p> {message} <ShowItems items={searched_items.perfect_match} user={this.props.user} db={this.props.db} user_cart={this.props.user_cart} no_message = {true} page="search"/> {separate} <ShowItems items={searched_items.inclusive_match} user={this.props.user} db={this.props.db} user_cart={this.props.user_cart} no_message = {true} page="search"/> </div> ); } }
JavaScript
class LowestCommonAncestorBST { //using postOrder traversal lowestCommonAncestor( root, n1, n2 ) { if (root == null) { return null; } // If root>n1 and root>n2 then lowest common ancestor will be in left subtree. if (root.data > n1.data && root.data > n2.data) { return this.lowestCommonAncestor(root.left, n1, n2); } else if (root.data < n1.data && root.data < n2.data) { // If root<n1 and root<n2 then lowest common ancestor will be in right subtree. return this.lowestCommonAncestor(root.right, n1, n2); } // if I am here that means i am at the root which is lowest common ancestor return root; } lowestCommonAncestor2( root, n1, n2 ) { while (root != null) { // If root>n1 and root>n2 then lowest common ancestor will be in left subtree. if (root.data > n1.data && root.data > n2.data) { root = root.left; } else if (root.data < n1.data && root.data < n2.data) { // If root<n1 and root<n2 then lowest common ancestor will be in right subtree. root = root.right; } else { // if I am here that means i am at the root which is lowest common ancestor return root; } } return root; } /* 15 / \ 10 20 / \ 5 13 / \ 12 14 Lowest Common Ancestor of Nodes 5 and 14 is : 10 */ test() { let root = new TreeNode(15); root.left = new TreeNode(10); root.right = new TreeNode(20); let n1 = new TreeNode(5); root.left.left = n1; root.left.right = new TreeNode(13); let n2 = new TreeNode(14); root.left.right.right = n2; root.left.right.left = new TreeNode(12); // int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // TreeNode root = TreeNode.createMinimalBST(array); // TreeNode n1 = root.find(6); // TreeNode n2 = root.find(9); console.log("Recursive-Lowest Common Ancestor of Nodes " + n1.data + " and " + n2.data + " is : " + this.lowestCommonAncestor(root, n1, n2).data); let x = this.lowestCommonAncestor2(root, n1, n2); console.log("Iterative-Lowest Common Ancestor of Nodes " + n1.data + " and " + n2.data + " is : " + x.data); } }
JavaScript
class DiceChain { /* * Return the name of the primary dice in an expression * @param {String} Roll expression * @returns {Number} Primary dice (e.g. d3, d8, d14) */ static getPrimaryDie (expression) { const faces = this.getPrimaryDieFaces(expression) if (faces) { return 'd' + faces } return null } /* * Return the number of faces on the primary dice in an expression * @param {String} Roll expression * @returns {Number} Number of faces of the largest die */ static getPrimaryDieFaces (expression) { const roll = new Roll(expression) roll.evaluate({ async: false }) let maxFaces = 0 for (const die of roll.dice) { if (die.faces > maxFaces) { maxFaces = die.faces } } return maxFaces } /* * Return the rank in the dice chain of the largest die in an expression * Dice of sizes not in the dice chain are ignored * * @param {String} Roll expression * @returns {Number} Rank of the largest die */ static rankDiceExpression (expression) { const roll = new Roll(expression) roll.evaluate({ async: false }) let rank = 0 for (const die of roll.dice) { const dieRank = CONFIG.DCC.DICE_CHAIN.indexOf(die.faces) if (dieRank > rank) { rank = dieRank } } return rank } }
JavaScript
class Human2RegexLexerOptions { /** * Constructor for the Human2RegexLexerOptions * * @param skip_validations If true, the lexer will skip validations (~25% faster) * @param type The type of indents the lexer will allow * @param spaces_per_tab Number of spaces per tab */ constructor(skip_validations = false, type = IndentType.Both, spaces_per_tab = 4) { this.skip_validations = skip_validations; this.type = type; this.spaces_per_tab = spaces_per_tab; /* empty */ } }
JavaScript
class Human2RegexLexer { /** * Human2Regex Lexer * * @remarks Only 1 lexer instance allowed due to a technical limitation and performance reasons * @param options options for the lexer * @see Human2RegexLexerOptions */ constructor(options = new Human2RegexLexerOptions()) { if (Human2RegexLexer.already_init) { throw new Error("Only 1 instance of Human2RegexLexer allowed"); } Human2RegexLexer.already_init = true; this.setOptions(options); } /** * Sets the options for this lexer * * @param options options for the lexer * @see Human2RegexLexerOptions */ setOptions(options) { this.options = options; let indent_regex = null; // Generate an index lexer (accepts tabs or spaces or both based on options) if (this.options.type === IndentType.Tabs) { indent_regex = /\t/y; } else { let reg = ` {${this.options.spaces_per_tab}}`; if (this.options.type === IndentType.Both) { reg += "|\\t"; } indent_regex = new RegExp(reg, "y"); } tokens_1.Indent.PATTERN = indent_regex; this.lexer = new chevrotain_1.Lexer(tokens_1.AllTokens, { ensureOptimizations: true, skipValidations: options.skip_validations }); } lexError(token) { var _a, _b, _c; return { offset: token.startOffset, line: (_a = token.startLine) !== null && _a !== void 0 ? _a : NaN, column: (_b = token.startColumn) !== null && _b !== void 0 ? _b : NaN, length: (_c = token.endOffset) !== null && _c !== void 0 ? _c : NaN - token.startOffset, message: "Unexpected indentation found" }; } /** * Tokenizes the given text * * @param text the text to analyze * @returns a tokenize result which contains the token stream and error list * @public */ tokenize(text) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; const lex_result = this.lexer.tokenize(text); if (lex_result.tokens.length === 0) { return new TokenizeResult(lex_result.tokens, lex_result.errors.map(utilities_1.CommonError.fromLexError)); } const tokens = []; const indent_stack = [0]; let curr_indent_level = 0; let start_of_line = true; let had_indents = false; // create Outdents for (let i = 0; i < lex_result.tokens.length; i++) { // EoL? check for indents next (by setting startOfLine = true) if (lex_result.tokens[i].tokenType === tokens_1.EndOfLine) { if (tokens.length === 0 || tokens[tokens.length - 1].tokenType === tokens_1.EndOfLine) { // Ignore multiple EOLs and ignore first EOL } else { start_of_line = true; tokens.push(lex_result.tokens[i]); } } // start with 1 indent. Append all other indents else if (lex_result.tokens[i].tokenType === tokens_1.Indent) { had_indents = true; curr_indent_level = 1; const start_token = lex_result.tokens[i]; let length = lex_result.tokens[i].image.length; // grab all the indents (and their length) while (lex_result.tokens.length > i + 1 && lex_result.tokens[i + 1].tokenType === tokens_1.Indent) { curr_indent_level++; i++; length += lex_result.tokens[i].image.length; } start_token.endOffset = start_token.startOffset + length; start_token.endColumn = lex_result.tokens[i].endColumn; // must be the same line //start_token.endLine = lex_result.tokens[i].endLine; // are we an empty line? if (lex_result.tokens.length > i + 1 && lex_result.tokens[i + 1].tokenType === tokens_1.EndOfLine) { // Ignore all indents AND newline // continue; } // new indent is too far ahead else if (!start_of_line || (curr_indent_level > utilities_1.last(indent_stack) + 1)) { lex_result.errors.push(this.lexError(start_token)); } // new indent is just 1 above else if (curr_indent_level > utilities_1.last(indent_stack)) { indent_stack.push(curr_indent_level); tokens.push(start_token); } // new indent is below the past indent else if (curr_indent_level < utilities_1.last(indent_stack)) { const index = utilities_1.findLastIndex(indent_stack, curr_indent_level); // this will never happen since earlier up we exclude when you're too far ahead // you have to go in order, 1 by 1, thus you can never not be in the indent stack //if (index < 0) { // lex_result.errors.push(this.lexError(start_token)); // continue; //} const number_of_dedents = indent_stack.length - index - 1; for (let j = 0; j < number_of_dedents; j++) { indent_stack.pop(); tokens.push(chevrotain_1.createTokenInstance(tokens_1.Outdent, "", start_token.startOffset, start_token.startOffset + length, (_a = start_token.startLine) !== null && _a !== void 0 ? _a : NaN, (_b = start_token.endLine) !== null && _b !== void 0 ? _b : NaN, (_c = start_token.startColumn) !== null && _c !== void 0 ? _c : NaN, ((_d = start_token.startColumn) !== null && _d !== void 0 ? _d : NaN) + length)); } } else { // same indent level: don't care // continue; } } else { if (start_of_line && !had_indents) { const tok = lex_result.tokens[i]; //add remaining Outdents while (indent_stack.length > 1) { indent_stack.pop(); tokens.push(chevrotain_1.createTokenInstance(tokens_1.Outdent, "", tok.startOffset, tok.startOffset, (_e = tok.startLine) !== null && _e !== void 0 ? _e : NaN, NaN, (_f = tok.startColumn) !== null && _f !== void 0 ? _f : NaN, NaN)); } } start_of_line = false; had_indents = false; tokens.push(lex_result.tokens[i]); } } const tok = utilities_1.last(tokens); // Do we have an EOL marker at the end? if (tokens.length > 0 && tok.tokenType !== tokens_1.EndOfLine) { tokens.push(chevrotain_1.createTokenInstance(tokens_1.EndOfLine, "\n", (_g = tok.endOffset) !== null && _g !== void 0 ? _g : NaN, (_h = tok.endOffset) !== null && _h !== void 0 ? _h : NaN, (_j = tok.startLine) !== null && _j !== void 0 ? _j : NaN, NaN, (_k = tok.startColumn) !== null && _k !== void 0 ? _k : NaN, NaN)); } //add remaining Outdents while (indent_stack.length > 1) { indent_stack.pop(); tokens.push(chevrotain_1.createTokenInstance(tokens_1.Outdent, "", (_l = tok.endOffset) !== null && _l !== void 0 ? _l : NaN, (_m = tok.endOffset) !== null && _m !== void 0 ? _m : NaN, (_o = tok.startLine) !== null && _o !== void 0 ? _o : NaN, NaN, (_p = tok.startColumn) !== null && _p !== void 0 ? _p : NaN, NaN)); } return new TokenizeResult(tokens, lex_result.errors.map(utilities_1.CommonError.fromLexError)); } }
JavaScript
class Derbies extends Feature { commands_ = null; games_ = null; registry_ = null; constructor() { super(); // It's possible for players to become invisible while playing a derby. this.defineDependency('player_colors'); // The Derby feature depends on the Games API for providing its functionality. this.games_ = this.defineDependency('games'); this.games_.addReloadObserver(this, () => this.registerGame()); // The registry is responsible for keeping tabs on the available derbies. this.registry_ = new VehicleGameRegistry('derby', kDerbyDirectory, DerbyDescription); // Provides the commands through which players can interact with the race system. this.commands_ = new DerbyCommands(this.games_, this.registry_); // Immediately register the DerbyGame so that the Games API knows of its existence. this.registerGame(); } // --------------------------------------------------------------------------------------------- // Registers the DerbyGame with the Games API as a game that can be started by players. The // entry point for derbies will still be the "/derby" command manually provided. registerGame() { this.games_().registerGame(DerbyGame, { name: Derbies.prototype.generateDerbyName.bind(this), commandFn: Derbies.prototype.generateDerbyCommand.bind(this), goal: 'Be the last person standing in a vehicle war.', minimumPlayers: 2, maximumPlayers: 4, price: 0, settings: [ // Option: Game Description ID (number) new Setting('game', 'description_id', Setting.TYPE_NUMBER, -1, 'Description ID'), ], }, { registry: this.registry_ }); } // Generates the command through which a particular derby can be started, information which will // be conveyed through the |settings| argument. NULL when absent. generateDerbyCommand(settings) { const description = this.registry_.getDescription(settings.get('game/description_id')); return description ? `derby ${description.id}` : null; } // Generates the name for the derby described by the given |settings|. It depends on the game's // ID that's contained within the |settings|, which should be known to the registry. generateDerbyName(settings) { const description = this.registry_.getDescription(settings.get('game/description_id')); return description ? description.name : 'Derby'; } // --------------------------------------------------------------------------------------------- // The derbies feature does not define a public API. // --------------------------------------------------------------------------------------------- dispose() { this.games_().removeGame(DerbyGame); this.games_.removeReloadObserver(this); this.games_ = null; this.commands_.dispose(); this.commands_ = null; this.registry_.dispose(); this.registry_ = null; } }
JavaScript
class Event { /** * @param {string} subtype event subtype name. * @param {number} deltaTime delta time. * @param {number} time time. */ constructor(subtype, deltaTime, time) { /** @type {string} */ this.subtype = subtype; /** @type {number} */ this.deltaTime = deltaTime; /** @type {number} */ this.time = time; } }
JavaScript
class ChannelEvent extends Event { /** * @param {string} subtype * @param {number} deltaTime delta time. * @param {number} time time. * @param {number} channel * @param {number=} optParameter1 * @param {number=} optParameter2 */ constructor(subtype, deltaTime, time, channel, optParameter1, optParameter2) { super(subtype, deltaTime, time); /** @type {number} */ this.channel = channel; /** @type {(number|undefined)} */ this.parameter1 = optParameter1; /** @type {(number|undefined)} */ this.parameter2 = optParameter2; } }
JavaScript
class SystemExclusiveEvent extends Event { /** * @param {string} subtype * @param {number} deltaTime delta time. * @param {number} time time. * @param {ByteArray} data */ constructor(subtype, deltaTime, time, data) { super(subtype, deltaTime, time); /** @type {ByteArray} */ this.data = data; } }
JavaScript
class MetaEvent extends Event { /** * @param {string} subtype * @param {number} deltaTime delta time. * @param {number} time time. * @param {Array.<*>} data meta data. */ constructor(subtype, deltaTime, time, data) { super(subtype, deltaTime, time); /** @type {Array.<*>} */ this.data = data; }; }
JavaScript
class Section { constructor(epubType, id, content, includeInToc, includeInLandmarks, ...argv) { this.subSections = []; this.sectionConfig = {}; this.epubType = epubType; this.id = id; this.includeInToc = includeInToc; this.includeInLandmarks = includeInLandmarks; this.subSections = []; /* this.content = content; if (content) { content.renderTitle = content.renderTitle !== false; // 'undefined' should default to true } */ this.setContent(content, true); } /** * * @param {ISectionContent|string} content * @param {boolean} allow_null * @returns {this} */ setContent(content, allow_null) { let o = {}; if (typeof content == 'string') { o.content = content; } else if (content.title || content.content || content.renderTitle || content.cover) { o = content; } if (Object.keys(o).length) { if (this.content) { this.content = Object.assign(this.content, o); } else { this.content = o; } this.content.renderTitle = this.content.renderTitle !== false; } else if (content) { this.content = content; } else if (!allow_null) { throw new ReferenceError(); } return this; } get epubTypeGroup() { return EpubMaker.epubtypes.getGroup(this.epubType); } get lang() { return this.sectionConfig.lang || (this._EpubMaker_ ? this._EpubMaker_.lang : null) || null; } get langMain() { return (this._EpubMaker_ ? this._EpubMaker_.lang : null) || null; } static create(epubType, id, content, includeInToc, includeInLandmarks, ...argv) { return new this(epubType, id, content, includeInToc, includeInLandmarks, ...argv); } withSubSection(subsection) { subsection.parentSection = this; this.subSections.push(subsection); return this; } ; collectToc() { return this.collectSections(this, 'includeInToc'); } ; collectLandmarks() { return this.collectSections(this, 'includeInLandmarks'); } ; collectSections(section, prop) { let sections = section[prop] ? [section] : []; for (let i = 0; i < section.subSections.length; i++) { Array.prototype.push.apply(sections, this.collectSections(section.subSections[i], prop)); } return sections; } }
JavaScript
class R1Recipient { /** * @param {Object} blocks * @param {RecipientIndicativeArea} [blocks.recipientIndicativeArea] * @param {Number} [blocks.recipientType] * @param {Object} [blocks.recipient] * @param {Number} [blocks.recipient.siret] R 112 SIRET bénéficiaire * @param {String} [blocks.recipient.socialReason] R 113 Raison social (mandatory for corporate) * @param {String} [blocks.recipient.familyname] R 114 Nom de famille (mandatory for physical person) * @param {String} [blocks.recipient.firstnames] R 115 Prénoms (ordre état civil) (mandatory for physical person) * @param {String} [blocks.recipient.name] R 116 Nom d'usage * @param {Number} [blocks.recipient.sex] R 118 Code sexe (mandatory for physical person) * @param {Object} [blocks.birth] * @param {Number} [blocks.birth.year] R 119 Année (format YYYYMMDD) * @param {Number} [blocks.birth.month] R 120 Mois (format MM) * @param {Number} [blocks.birth.day] R 121 Jour (format DD) * @param {String} [blocks.birth.departementCode] R 122 Code département * @param {String} [blocks.birth.cityCode] R 123 Code commune * @param {String} [blocks.birth.city] R 124 Libellé commune * @param {String} [blocks.birth.job] R 126 Profession * @param {RecipientAddress} [blocks.recipientAddress] */ constructor(blocks) { [ 'recipientIndicativeArea', 'recipientType', 'recipient', 'birth', 'recipientAddress' ].forEach((blockName) => { this[blockName] = blocks[blockName] }); } export() { this.validation(); return [ ...this.recipientIndicativeArea.export(), numberPad(this.recipient.siret, 14), wordPad(this.recipient.socialReason, 50), wordPad(this.recipient.familyname, 30), wordPad(this.recipient.firstnames, 20), wordPad(this.recipient.name, 30), fillWith(' ', 20), wordPad(this.recipient.sex, 1), this.birth.year, numberPad(this.birth.month, 2), numberPad(this.birth.day, 2), this.birth.departementCode, numberPad(this.birth.cityCode, 3), wordPad(this.birth.city, 26), ' ', wordPad(this.birth.job, 30), ...this.recipientAddress.export() ]; } validation() { this.recipientIndicativeArea.validation(); this.recipientAddress.validation(); const recipientSchema = { siret: { length: { is: 14 } }, socialReason: { presence: (this.recipientType === 1), length: { maximum: 50 } }, familyname: { presence: (this.recipientType === 2), length: { maximum: 30 } }, firstnames: { presence: (this.recipientType === 2), length: { maximum: 20 } }, name: { length: { maximum: 30 } }, sex: { presence: (this.recipientType === 2), numericality: { onlyInteger: true, greaterThanOrEqualTo: 1, lessThanOrEqualTo: 2 } } }; const birthSchema = { year: { presence: true, numericality: { onlyInteger: true, greaterThanOrEqualTo: 1900, lessThanOrEqualTo: 2999 } }, month: { presence: true, numericality: { onlyInteger: true, greaterThanOrEqualTo: 1, lessThanOrEqualTo: 12 } }, day: { presence: true, numericality: { onlyInteger: true, greaterThanOrEqualTo: 1, lessThanOrEqualTo: 31 } }, departementCode: { presence: true, length: { is: 2 } }, cityCode: { length: { is: 3 } }, city: { presence: true, length: { maximum: 26 } }, job: { length: { maximum: 30 } } }; const invalid = validate(this.recipient, recipientSchema); const invalid2 = validate(this.birth, birthSchema); if (invalid) { throw new ValidationError(invalid); } if (invalid2) { throw new ValidationError(invalid2); } return true; } }
JavaScript
class Memory { /** * Set calculable instance * @example Memory.setComputedInstance(new yourComputedInstance()) * @param {AbstractComputedMap} computedInstance - instance of computed map */ static setComputedInstance(computedInstance) { this.computedInstance = computedInstance; } /** * Set constant instance * @example Memory.setConstantsInstance(new yourConstantsInstance()) * @param {AbstractConstantMap} constantsInstance - instance of constants map */ static setConstantsInstance(constantsInstance) { this.constantsInstance = constantsInstance; } /** * Bind value to memory class * @param {string} key - key * @param {*} value - value * @example Memory.setValue("key", 1) */ static setValue(key, value) { if (!this.memory) { this.memory = {} } this.memory[key] = value; } /** * Returns value if exists in memory * @private * @param {string} key - key * @return {string|number|Object} - parsed value * @throws {Error} * @example Memory.parseValue("$key") */ static parseValue(key) { const MEMORY_REGEXP = /^(\$|#|!{1,2})?([^$#!]?.+)$/; if (MEMORY_REGEXP.test(key)) { const [_, prefix, parsedKey] = key.match(MEMORY_REGEXP); switch (prefix) { case "$": return this._getMemoryValue(parsedKey); case "#": return this._getComputedValue(parsedKey); case "!": return this._getConstantValue(parsedKey); case "!!": return this._getFileConstantValue(parsedKey); case undefined: return parsedKey; default: throw new Error(`${parsedKey} is not defined`) } } else { return key } } /** * Replace param templates withing string with their values * @param {string} str - string to parse * @return {string|Promise<string>} - parsed */ static getValue(str) { const MEMORY_REGEXP = /^(\$|#|!{1,2})([^$#!]?.+)$/; const PARSE_STRING_REGEXP = /{((?:\$|#|!{1,2})?(?:[^$#!]?.+?))}/g; if (MEMORY_REGEXP.test(str)) { return this.parseValue(str) } else if (PARSE_STRING_REGEXP.test(str)) { const matches = str.match(PARSE_STRING_REGEXP).map(match => match.replace(/{|}/g, ``)); if (matches.some(alias => this.parseValue(alias) instanceof Promise)) { const promises = matches.map(alias => this.parseValue(alias)); return Promise .all(promises) .then(pmatches => pmatches .map((match, i) => ({ alias: matches[i], value: match })) .reduce((string, variable) => string.replace(`{${variable.alias}}`, variable.value), str)) .catch(e => { throw e }) } else return matches.reduce((string, variable) => string.replace(`{${variable}}`, this.parseValue(variable)), str); } else return str } /** * Return value from memory * @param {string} alias - key * @return {string|number|Object} - value by key * @private */ static _getMemoryValue(alias) { if (this.memory[alias] !== undefined) { return this.memory[alias]; } else { throw new Error(`Value ${alias} doesn't exist in memory`) } } /** * Return calculated value * @param {string} alias - key * @return {string|number|Object} - value by key * @private */ static _getComputedValue(alias) { if (this.computedInstance) { return this.computedInstance.getComputed(alias) } else throw new Error(`Instance of computed is not defined`) } /** * Return constant value * @param {string} key - key * @return {string|number|Object} - value by key * @private */ static _getConstantValue(key) { if (this.constantsInstance) { return this.constantsInstance.getConstant(key) } else throw new Error(`Instance of constants is not defined`) } /** * Return file constant value * @param {string} key - key * @return {string|Buffer} - value by key * @private */ static _getFileConstantValue(key) { if (this.constantsInstance) { return this.constantsInstance.getFileConstant(key) } else throw new Error(`Instance of constants is not defined`) } }
JavaScript
class Texture { /** * * @param {WebGLRenderingContext} gl * @param {GLenum} format * @param {GLenum} internalFormat * @param {GLenum} type */ constructor(gl, format = RGB, internalFormat = RGB, type = UNSIGNED_BYTE) { this._gl = gl; if (!this._gl) { console.error('[Texture]gl is missed'); return; } /** * @member WebGLTexture */ this._texture = this._gl.createTexture(); this.setFormat(format, internalFormat, type); return this; } /** * @description active texture * @returns {Texture} */ activeTexture(unit = 0) { this._gl.activeTexture(this._gl.TEXTURE0 + (0 | unit)); return this; } /** * @description bind texture * * @returns {Texture} */ bind() { this._gl.bindTexture(this._gl.TEXTURE_2D, this._texture); return this; } /** * @description unbind texture * @returns Texture */ unbind() { this._gl.bindTexture(this._gl.TEXTURE_2D, null); return this; } /** * @description update data fro texture with image * * @param {Image} image * @param {number} width * @param {number} height * * @returns Texture */ fromImage(image, width, height) { this._width = width ? width : image.width; this._height = height ? height : image.height; this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._internalFormt, this._format, this._type, image); return this; } /** * @description update texture with width and height and emptyData * * @param {number} width * @param {number} height * * @returns {Texture} */ fromSize(width, height) { if (width) this._width = width; if (height) this._height = height; this._gl.texImage2D( this._gl.TEXTURE_2D, 0, this._internalFormt, this._width, this._height, 0, this._format, this._type, null ); return this; } /** * @description update texture from dataArray * * @param {number} width * @param {number} height * @param {Float32Array|Float64Array} dataArray * * @returns {Texture} */ fromData(width, height, dataArray) { if (width) this._width = width; if (height) this._height = height; this._gl.texImage2D( this._gl.TEXTURE_2D, 0, this._internalFormt, this._width, this._height, 0, this._format, this._type, dataArray ); return this; } /** * @description flip the texture */ setFlip() { this.setPixelStore(this._gl.UNPACK_FLIP_Y_WEBGL, true); return this; } /** * @description specify the pixel storage mode * * @param {GLenum} pname * @param {object} params */ setPixelStore(pname, params) { this._gl.pixelStorei(pname, params); return this; } /** * * @description update format for texture * * @param {GLenum} format * @param {GLenum} internalFormat * @param {Glenum} type */ setFormat(format, internalFormat, type) { if (format) this._format = format; if (internalFormat) this._internalFormt = internalFormat; if (type) this._type = type; return this; } /** * @description confirm texture is active * * @param {GLenum} unit * @returns {boolean} */ isActiveTexture(unit) { return unit === this.unit; } /** * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texParameter * https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getTexParameter * https://webglfundamentals.org/webgl/lessons/webgl-3d-textures.html * * @param {GLenum} filter * * @returns {Texture} */ setFilter(filter = LINEAR) { this.setMinFilter(filter); this.setMagFilter(filter); return this; } /** * set mag filter to texture * * @param {GLenum} filter * * @returns {Texture} */ setMagFilter(filter = LINEAR) { this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filter); return this; } /** * set min filter to texture * * @param {GLenum} filter * * @returns {Texture} */ setMinFilter(filter = NEAREST) { this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filter); return this; } /** * @description set the wrap mode in texture */ wrap(wrap = CLAMP_TO_EDGE) { this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, wrap); this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, wrap); return this; } /** * generate mipmap for texture * * @returns {WebGLTexture} */ generateMipmap() { this._gl.generateMipmap(this._gl.TEXTURE_2D); return this; } /** * @description get webgl texture * @returns {Texture} */ getTexture() { return this._texture; } /** @description delete the texture */ delete() { this._gl.deleteTexture(this._texture); this._texture = null; } /** * @description get webgl texture as id * @return {WebGLTexture} */ get id(){ return this._texture; } }
JavaScript
class ForthStep extends Page { /** * @return{string} */ render() { return template(this.props); } }
JavaScript
class CarLoanCalculator { constructor() { let bus = maglev.maglev.MagLev.getInstance('default'); let lib = new carloancalculator.carloancalculator.CarLoanCalculator(bus); } /** * Calculate what the payments would be from the price of the new car and the parameters of the monthly loan payments * @param {number} newCarPrice price of the car new * @param {number} tradeInAllowance trade-in value * @param {number} tradeInLoanBalance loan balance after trade-in * @param {number} downPaymentAndRebates total amount of rebates plus downpayment * @param {number} loanDuration loan duration in months * @param {number} salesTaxRate sales tax as percentage * @param {number} interestRate interest rate as percentage * @return {Promise} payments and total interest Promise will resolve to type array. */ CalcPayments(newCarPrice, tradeInAllowance, tradeInLoanBalance, downPaymentAndRebates, loanDuration, salesTaxRate, interestRate) { let jsbus = maglev.maglev.MagLevJs.getInstance('default'); let args = [newCarPrice, tradeInAllowance, tradeInLoanBalance, downPaymentAndRebates, loanDuration, salesTaxRate, interestRate]; let ret = jsbus.call('CarLoanCalculator.CalcPayments', args); return ret; } /** * Calculate the price of the car from the monthly loan payment information * @param {number} monthlyPayment monthly payment amount * @param {number} tradeInAllowance trade-in value * @param {number} tradeInLoanBalance loan balance after trade-in * @param {number} downPaymentAndRebates total amount of rebates plus downpayment * @param {number} loanDuration loan duration in months * @param {number} salesTaxRate sales tax rate as percentage * @param {number} interestRate interest rate as percentage * @return {Promise} target price with tax and fees Promise will resolve to type number. */ CalcAffordability(monthlyPayment, tradeInAllowance, tradeInLoanBalance, downPaymentAndRebates, loanDuration, salesTaxRate, interestRate) { let jsbus = maglev.maglev.MagLevJs.getInstance('default'); let args = [monthlyPayment, tradeInAllowance, tradeInLoanBalance, downPaymentAndRebates, loanDuration, salesTaxRate, interestRate]; let ret = jsbus.call('CarLoanCalculator.CalcAffordability', args); return ret; } }
JavaScript
class PlayerRando extends Player { static get name() { return 'Rando'; } static get description() { return 'Just randomly places pieces'; } async getPlay(state) { this.assertValidState(state); const positions = state.validPlays(); this.emit('thinking', 'Considering options...'); this.emit('highlight', positions); await this.delay(500); const position = chooseRandom(positions); this.emit('thinking', 'Choosing one at random...'); this.emit('highlight', [position]); await this.delay(500); this.emit('thinking', 'Chose position '+position+'.'); return position; } }
JavaScript
class LatencyCompensator { constructor(player) { this.player = player; this.enabled = false; this.running = false; this.inTimeout = false; this.timeoutTimer = 0; this.checkTimer = 0; this.bufferingCounter = 0; this.bufferingTimer = 0; this.playbackRate = 1.0; this.player.on('playing', this.handlePlaying.bind(this)); this.player.on('error', this.handleError.bind(this)); this.player.on('waiting', this.handleBuffering.bind(this)); this.player.on('ended', this.handleEnded.bind(this)); this.player.on('canplaythrough', this.handlePlaying.bind(this)); this.player.on('canplay', this.handlePlaying.bind(this)); } // This is run on a timer to check if we should be compensating for latency. check() { console.log( 'playback rate', this.playbackRate, 'enabled:', this.enabled, 'running: ', this.running, 'timeout: ', this.inTimeout, 'buffer count:', this.bufferingCounter ); if (this.inTimeout) { return; } const tech = this.player.tech({ IWillNotUseThisInPlugins: true }); if (!tech || !tech.vhs) { return; } try { // Check the player buffers to make sure there's enough playable content // that we can safely play. if (tech.vhs.stats.buffered.length === 0) { this.timeout(); } let totalBuffered = 0; tech.vhs.stats.buffered.forEach((buffer) => { totalBuffered += buffer.end - buffer.start; }); console.log('buffered', totalBuffered); if (totalBuffered < 18) { this.timeout(); } } catch (e) {} // Determine how much of the current playlist's bandwidth requirements // we're utilizing. If it's too high then we can't afford to push // further into the future because we're downloading too slowly. const currentPlaylist = tech.vhs.playlists.media(); const currentPlaylistBandwidth = currentPlaylist.attributes.BANDWIDTH; const playerBandwidth = tech.vhs.systemBandwidth; const bandwidthRatio = playerBandwidth / currentPlaylistBandwidth; if (bandwidthRatio < REQUIRED_BANDWIDTH_RATIO) { this.timeout(); return; } let proposedPlaybackRate = bandwidthRatio * 0.34; console.log('proposed rate', proposedPlaybackRate); proposedPlaybackRate = Math.max( Math.min(proposedPlaybackRate, MAX_SPEEDUP_RATE), 1.0 ); try { const segment = getCurrentlyPlayingSegment(tech); if (!segment) { return; } // How far away from live edge do we start the compensator. const maxLatencyThreshold = Math.min( MAX_LATENCY, segment.duration * 1000 * HIGHEST_LATENCY_SEGMENT_LENGTH_MULTIPLIER ); // How far away from live edge do we stop the compensator. const minLatencyThreshold = Math.max( MIN_LATENCY, segment.duration * 1000 * LOWEST_LATENCY_SEGMENT_LENGTH_MULTIPLIER ); const segmentTime = segment.dateTimeObject.getTime(); const now = new Date().getTime(); const latency = now - segmentTime; console.log( 'latency', latency / 1000, 'min', minLatencyThreshold / 1000, 'max', maxLatencyThreshold / 1000 ); if (latency > maxLatencyThreshold) { this.start(proposedPlaybackRate); } else if (latency < minLatencyThreshold) { this.stop(); } } catch (err) { // console.warn(err); } } setPlaybackRate(rate) { this.playbackRate = rate; this.player.playbackRate(rate); } start(rate = 1.0) { if (this.inTimeout || !this.enabled || rate === this.playbackRate) { return; } this.running = true; this.setPlaybackRate(rate); } stop() { this.running = false; this.setPlaybackRate(1.0); } enable() { this.enabled = true; clearInterval(this.checkTimer); clearTimeout(this.bufferingTimer); this.checkTimer = setInterval(() => { this.check(); }, CHECK_TIMER_INTERVAL); } // Disable means we're done for good and should no longer compensate for latency. disable() { clearInterval(this.checkTimer); clearTimeout(this.timeoutTimer); this.stop(); this.enabled = false; } timeout() { this.inTimeout = true; this.stop(); clearTimeout(this.timeoutTimer); this.timeoutTimer = setTimeout(() => { this.endTimeout(); }, TIMEOUT_DURATION); } endTimeout() { clearTimeout(this.timeoutTimer); this.inTimeout = false; } handlePlaying() { clearTimeout(this.bufferingTimer); if (!this.enabled) { return; } } handleEnded() { if (!this.enabled) { return; } this.disable(); } handleError(e) { if (!this.enabled) { return; } console.log('handle error', e); this.timeout(); } countBufferingEvent() { this.bufferingCounter++; if (this.bufferingCounter > REBUFFER_EVENT_LIMIT) { this.disable(); return; } this.timeout(); // Allow us to forget about old buffering events if enough time goes by. setTimeout(() => { if (this.bufferingCounter > 0) { this.bufferingCounter--; } }, BUFFERING_AMNESTY_DURATION); } handleBuffering() { if (!this.enabled) { return; } this.timeout(); this.bufferingTimer = setTimeout(() => { this.countBufferingEvent(); }, MIN_BUFFER_DURATION); } }
JavaScript
class LegendFromDefinitionJson extends React.Component { static defaultProps = { legendDefinitionJsonUrl: null, }; constructor(props) { super(props); this.state = { loading: false, legend: null, error: null, }; this.cancelTokenSource = CancelToken.source(); } loadLegendDefinition(url) { const newPromise = new Promise((resolve, reject) => { axios(url, { cancelToken: this.cancelTokenSource.token, }) .then(res => resolve({ legend: res.data })) .catch(e => reject(e)); }); return newPromise; } componentDidMount() { let { legendDefinitionJsonUrl } = this.props; this.setState({ loading: true, }); this.loadLegendDefinition(legendDefinitionJsonUrl) .then(legend => this.setState({ legend, loading: false })) .catch(error => { if (!isCancel(error)) { this.setState({ error, loading: false }); } }); } componentWillUnmount() { if (this.state.loading) { this.cancelTokenSource.cancel('Operation cancelled by user.'); } } render() { const { loading, legend, error } = this.state; if (loading) { return ( <div className="legend"> <i className="fa fa-spinner fa-spin fa-fw" /> </div> ); } if (error) { return <p>Error while loading legend data.</p>; } if (legend) { return <LegendFromSpec legendSpec={legend} />; } return null; } }
JavaScript
class LegendFromGraphicsUrl extends React.Component { static defaultProps = { legendUrl: null, handleError: null, }; constructor(props) { super(props); this.state = { error: false, loading: true, }; } handleError = () => { this.setState({ error: true, loading: false }); this.props.hideLegend(); }; render() { if (this.state.error) return null; return ( <div className="legend"> {this.state.loading && <i className="fa fa-spinner fa-spin fa-fw" />} <img src={this.props.legendUrl} alt="legend" onError={this.handleError} onLoad={() => { this.setState({ loading: false }); }} /> </div> ); } }
JavaScript
class LegendFromSpec extends React.Component { static defaultProps = { spec: null, }; renderDiscreteLegendItem(legendItem, index) { return ( <div key={index} className="legend-item discrete"> <div className="color" style={{ backgroundColor: legendItem.color, }} /> <label>{legendItem.label}</label> </div> ); } renderContinuousLegend(legend) { const { minPosition, maxPosition, gradients } = createGradients(legend); return ( <div className="legend-item continuous"> <div className="gradients"> {gradients.map((g, index) => ( <div key={index} className="gradient" style={{ bottom: `${g.pos * 100}%`, height: `${g.size * 100}%`, background: `linear-gradient(to top, ${g.startColor}, ${g.endColor})`, }} /> ))} </div> <div className="ticks"> {legend.gradients.filter(g => g.label !== undefined && g.label !== null).map((g, index) => ( <label key={index} className="tick" style={{ bottom: `${((g.position - minPosition) / (maxPosition - minPosition) * 100).toFixed(1)}%`, }} > {g.label} </label> ))} </div> </div> ); } render() { if (!this.props.legendSpec) { return null; } try { let legend; if (this.props.legendSpec) { const { items, gradients } = this.props.legendSpec.legend; if (gradients) { legend = <div className="legend">{this.renderContinuousLegend(this.props.legendSpec.legend)}</div>; } if (items) { legend = ( <div className="legend"> {items.map((legendItem, index) => this.renderDiscreteLegendItem(legendItem, index))} </div> ); } } return legend; } catch (err) { console.error(err); return <div>Error parsing legend data.</div>; } } }
JavaScript
class ProfileController { async index({ request, Response }) { const id = request.body.id if (request.body.id) { const profile = await Profile .query() .where('id', id) .with('users') .fetch() if (profile.rows.length === 0) { return ( response.status(404), Message.messageNotFound(`Id do Perfil não encontrado`) ) } else { return profile } } if (!request.body.id) { const profile = await Profile .query() .with('users') .fetch() return profile } } /* const profile = await Profile .query() .with('users') .fetch() return (profile) */ async store({ request, response }) { /** * Create/save a new profile. */ var dados = {} dados.rules = { user: { create: false, update: false, read: false, delete: false }, person: { create: false, update: false, read: false, delete: false }, arma: { create: false, update: false, read: false, delete: false }, vehicle: { create: false, update: false, read: false, delete: false }, profile: { create: false, update: false, read: false, delete: false } } const userId = request.body.userId const dadosReq = request.only(['profile', 'unidade', 'carteira', 'rules', 'restritivo', 'posicional']) _.merge(dados, dadosReq) const user = await User.find(userId) const profile = await Profile.findOrCreate(dados) await user.profile().attach(profile.id) profile.user = await profile.users().fetch() return ( response.status(200), Message.messageOk('Profile cadastrado com sucesso') ) } /** * Update profile details. * PUT or PATCH profiles/:id */ async update({ request }) { /* const data = request.only([ 'profile', 'unidade', 'carteira', 'rules', 'restritivo', 'posicional' ]) console.log(data) const profile = await Profile.find(params.id) profile.merge(data) await profile.save() return profile */ const data = request.body const profile = await Profile.find(data.id) if (!profile) { return ( response.status(404), Message.messageNotFound('Perfil não encontrado') ) } profile.merge(data) await profile.save() return ( response.status(200), Message.messageOk('Perfil atualizado com sucesso') ) } /** * Delete a profile with id. * DELETE profiles/:id */ async destroy({ request }) { const data = request.body const profile = await Profile.find(data.id) if (profile) { await profile.delete() return ( response.status(200), Message.messageOk('Perfil deletado') ) } else { return ( response.status(404), Message.messageNotFound('Perfil não encontrado') ) } /* const profile = await Profile.find(params.id) if (profile) { await profile.delete() return Message.messageOk('deleted') } else { return Message.messageNotFound(`Not Found profile ${params.id}`) } */ } }
JavaScript
class Validation { /** * Validate the columns against the data if they match the types before inserting. * * @param {*} column * @param {*} value * @param {*} default_value */ static validate(column, value, default_value = true){ if(column) { if(typeof value !== 'undefined'){ if(Validation.validate_nullable(column, value)){ return { valid : true, value } } else if(Validation.validate_type(column, value)){ return { valid : true, value } } } else if (default_value){ if(typeof column.default !== 'undefined'){ return { valid : true, value : column.default } } else if (typeof column.null === 'undefined' || column.null){ return { valid : true, value : null } } else if(column.type) { switch(column.type){ case TYPE_BOOL: return { valid : true, value : false } // TYPE_BOOL case TYPE_BYTE: return { valid : true, value : '' } // TYPE_BYTE case TYPE_INT2: // TYPE_INT2 case TYPE_INT4: // TYPE_INT4 case TYPE_INT8: return { valid : true, value : 0 } // TYPE_INT8 case TYPE_FLOAT4: // TYPE_FLOAT4 case TYPE_FLOAT8: return { valid : true, value : 0.0 } // TYPE_FLOAT8 case TYPE_TIMESTAMP: return { valid : true, value : (new Date()).toUTCString() } // TYPE_TIMESTAMP case TYPE_VARCHAR: // TYPE_VARCHAR case TYPE_TEXT: // TYPE_TEXT case TYPE_CHAR: return { valid : true, value : '' } // TYPE_CHAR case TYPE_JSON: return { valid : true, value : '{}' } // TYPE_JSON } } } } console.error('Validation->validate FAILED: ', column, value) return { valid : false, value } } /** * Validate against column type. * * @param {*} column * @param {*} value */ static validate_type(column, value){ let type = typeof value if((type === 'number' || type === 'bigint') && column.type > TYPE_BOOL && column.type < TYPE_VARCHAR){ return true } else if(type === 'boolean' && column.type === TYPE_BOOL){ return true } else if(type === 'string'){ if((column.type === TYPE_TIMESTAMP || column.type === TYPE_VARCHAR || column.type === TYPE_TEXT || column.type === TYPE_CHAR)){ if(column.length && column.length < value.length){ console.error('Validation->validate_type: string length wrong: ', column.length, '<', value.length) return false } return true } else if(column.type === TYPE_BYTE){ console.error('Validation->validate_type: Buffer as string: ', column, value) return false } } else if(type === 'object'){ if(column.type === TYPE_BYTE && Buffer.isBuffer(value)){ return true } else if(column.type === TYPE_JSON) { return true } else if(column.type === TYPE_TIMESTAMP) { return true } } console.error('Validation->validate_type: type FALSE: ', type, column, value) return false } /** * Validate against column nullable. * * @param {*} column * @param {*} value */ static validate_nullable(column, value){ let value_null = (typeof value === 'undefined' || value === null) ? true : false // is null column if(typeof column.null === 'undefined' || column.null === true){ if(!value_null){ return false // check type THEN no error } // else true } else if(value_null){ console.error('Validation->validate_nullable: ', column, value) return false } return true } }
JavaScript
class BitmapFont { /** Use this constant for the <code>fontSize</code> property of the TextField class to * render the bitmap font in exactly the size it was created. */ static NATIVE_SIZE = -1 /** The font name of the embedded minimal bitmap font. Use this e.g. for debug output. */ static MINI = 'mini' static CHAR_MISSING = 0 static CHAR_TAB = 9 static CHAR_NEWLINE = 10 static CHAR_CARRIAGE_RETURN = 13 static CHAR_SPACE = 32 _texture _chars _name _size _lineHeight _baseline _offsetX _offsetY _padding _helperImage _type _distanceFieldSpread // helper objects static sLines = [] static sDefaultOptions /** Creates a bitmap font from the given texture and font data. * If you don't pass any data, the "mini" font will be created. * * @param texture The texture containing all the glyphs. * @param fontData Typically an XML file in the standard AngelCode format. Override the * the 'parseFontData' method to add support for additional formats. */ constructor(texture = null, fontData = null) { if (!BitmapFont.sDefaultOptions) BitmapFont.sDefaultOptions = new TextOptions() // if no texture is passed in, we create the minimal, embedded font if (!texture && !fontData) { const miniBitmapFont = getMiniBitmapFont() texture = miniBitmapFont.texture fontData = miniBitmapFont.fontData } else if (!texture || !fontData) { throw new Error( `[ArgumentError] Set both of the 'texture' and 'fontData' arguments to valid objects or leave both of them null.` ) } const { CHAR_MISSING } = BitmapFont this._name = 'unknown' this._lineHeight = this._size = this._baseline = 14 this._offsetX = this._offsetY = this._padding = 0.0 this._texture = texture this._chars = new Map() this._helperImage = new Image(texture) this._type = BitmapFontType.STANDARD this._distanceFieldSpread = 0.0 this.addChar(CHAR_MISSING, new BitmapChar(CHAR_MISSING, null, 0, 0, 0)) this.parseFontData(fontData) } /** Disposes the texture of the bitmap font. */ dispose() { if (this._texture) this._texture.dispose() } /** Parses the data that's passed as second argument to the constructor. * Override this method to support different file formats. */ parseFontData(data) { if (data) this.parseFontXml(data) else throw new Error('[ArgumentError] BitmapFont only supports XML data') } parseFontXml(fontXml) { const scale = this._texture.scale const frame = this._texture.frame const frameX = frame ? frame.x : 0 const frameY = frame ? frame.y : 0 this._name = fontXml.font.info._attributes.face this._size = parseFloat(fontXml.font.info._attributes.size) / scale this._lineHeight = parseFloat(fontXml.font.common._attributes.lineHeight) / scale this._baseline = parseFloat(fontXml.font.common._attributes.base) / scale if (fontXml.font.info._attributes.smooth === '0') this.smoothing = TextureSmoothing.NONE if (this._size <= 0) { console.log( `[Starling] Warning: invalid font size in '${this._name}' font.` ) this._size = this._size === 0.0 ? 16.0 : this._size * -1.0 } if (fontXml.font.distanceField) { // todo: test df fonts this._distanceFieldSpread = parseFloat( fontXml.font.distanceField._attributes.distanceRange ) this._type = fontXml.distanceField._attributes.fieldType === 'msdf' ? BitmapFontType.MULTI_CHANNEL_DISTANCE_FIELD : BitmapFontType.DISTANCE_FIELD } else { this._distanceFieldSpread = 0.0 this._type = BitmapFontType.STANDARD } for (const charElement of fontXml.font.chars.char) { const id = parseInt(charElement._attributes.id, 10) const xOffset = parseFloat(charElement._attributes.xoffset) / scale const yOffset = parseFloat(charElement._attributes.yoffset) / scale const xAdvance = parseFloat(charElement._attributes.xadvance) / scale const region = new Rectangle() region.x = parseFloat(charElement._attributes.x) / scale + frameX region.y = parseFloat(charElement._attributes.y) / scale + frameY region.width = parseFloat(charElement._attributes.width) / scale region.height = parseFloat(charElement._attributes.height) / scale const texture = createSubtexture({ texture: this._texture, region }) const bitmapChar = new BitmapChar(id, texture, xOffset, yOffset, xAdvance) this.addChar(id, bitmapChar) } if (fontXml.font.kernings) { for (const kerningElement of fontXml.font.kernings.kerning) { const first = parseInt(kerningElement._attributes.first, 10) const second = parseInt(kerningElement._attributes.second, 10) const amount = parseFloat(kerningElement._attributes.amount, 10) / scale if (this._chars.has(second)) this.getChar(second).addKerning(first, amount) } } } /** Returns a single bitmap char with a certain character ID. */ getChar(charID) { return this._chars.get(charID) } /** Adds a bitmap char with a certain character ID. */ addChar(charID, bitmapChar) { this._chars.set(charID, bitmapChar) } /** Returns a vector containing all the character IDs that are contained in this font. */ getCharIDs(out = null) { if (!out) out = [] this._chars.forEach((value, key) => (out[out.length] = parseInt(key, 10))) // todo: ok? return out } /** Checks whether a provided string can be displayed with the font. */ hasChars(text) { if (!text) return true const { CHAR_CARRIAGE_RETURN, CHAR_TAB, CHAR_NEWLINE, CHAR_SPACE } = BitmapFont let charID const numChars = text.length for (let i = 0; i < numChars; ++i) { charID = text.charCodeAt(i) if ( charID !== CHAR_SPACE && charID !== CHAR_TAB && charID !== CHAR_NEWLINE && charID !== CHAR_CARRIAGE_RETURN && !this.getChar(charID) ) { return false } } return true } /** Creates a sprite that contains a certain text, made up by one image per char. */ createSprite(width, height, text, format, options = null) { const charLocations = this.arrangeChars( width, height, text, format, options ) const numChars = charLocations.length const smoothing = this.smoothing const sprite = new Sprite() for (let i = 0; i < numChars; ++i) { const charLocation = charLocations[i] const char = charLocation.char.createImage() char.x = charLocation.x char.y = charLocation.y char.scale = charLocation.scale char.color = format.color char.textureSmoothing = smoothing sprite.addChild(char) } BitmapCharLocation.rechargePool() return sprite } /** Draws text into a QuadBatch. */ fillMeshBatch(meshBatch, width, height, text, format, options = null) { const charLocations = this.arrangeChars( width, height, text, format, options ) const numChars = charLocations.length this._helperImage.color = format.color for (let i = 0; i < numChars; ++i) { const charLocation = charLocations[i] this._helperImage.texture = charLocation.char.texture this._helperImage.readjustSize() this._helperImage.x = charLocation.x this._helperImage.y = charLocation.y this._helperImage.scale = charLocation.scale meshBatch.addMesh(this._helperImage) } BitmapCharLocation.rechargePool() } /** @inheritDoc */ clearMeshBatch(meshBatch) { meshBatch.clear() } /** @inheritDoc */ getDefaultMeshStyle(previousStyle, format) { if (this._type === BitmapFontType.STANDARD) return null else { // -> distance field font const fontSize = format.size < 0 ? format.size * -this._size : format.size const dfStyle = previousStyle instanceof DistanceFieldStyle ? previousStyle : new DistanceFieldStyle() // todo: questionable dfStyle.multiChannel = this._type === BitmapFontType.MULTI_CHANNEL_DISTANCE_FIELD dfStyle.softness = this._size / (fontSize * this._distanceFieldSpread) return dfStyle } } /** Arranges the characters of text inside a rectangle, adhering to the given settings. * Returns a Vector of BitmapCharLocations. * * <p>BEWARE: This method uses an object pool for the returned vector and all * (returned and temporary) BitmapCharLocation instances. Do not save any references and * always call <code>BitmapCharLocation.rechargePool()</code> when you are done processing. * </p> */ arrangeChars(width, height, text, format, options) { if (!text || text.length === 0) return BitmapCharLocation.vectorFromPool() if (!options) options = BitmapFont.sDefaultOptions const { CHAR_MISSING, CHAR_SPACE, CHAR_TAB, CHAR_CARRIAGE_RETURN, CHAR_NEWLINE, sLines } = BitmapFont const { kerning, leading, letterSpacing: spacing, horizontalAlign: hAlign, verticalAlign: vAlign } = format const { autoScale, wordWrap } = options let fontSize = format.size let finished = false let charLocation let numChars let containerWidth let containerHeight let scale let i, j let currentX = 0 let currentY = 0 if (fontSize < 0) fontSize *= -this._size while (!finished) { sLines.length = 0 scale = fontSize / this._size containerWidth = (width - 2 * this._padding) / scale containerHeight = (height - 2 * this._padding) / scale if (this._size <= containerHeight) { let lastWhiteSpace = -1 let lastCharID = -1 let currentLine = BitmapCharLocation.vectorFromPool() currentX = 0 currentY = 0 numChars = text.length for (i = 0; i < numChars; ++i) { let lineFull = false let charID = text.charCodeAt(i) let char = this.getChar(charID) if (charID === CHAR_NEWLINE || charID === CHAR_CARRIAGE_RETURN) { lineFull = true } else { if (!char) { console.log( `[Starling] Character '${text.charAt( i )}' (id: ${charID}) not found in '${name}'` ) charID = CHAR_MISSING char = this.getChar(CHAR_MISSING) } if (charID === CHAR_SPACE || charID === CHAR_TAB) lastWhiteSpace = i if (kerning) currentX += char.getKerning(lastCharID) charLocation = BitmapCharLocation.instanceFromPool(char) charLocation.index = i charLocation.x = currentX + char.xOffset charLocation.y = currentY + char.yOffset currentLine[currentLine.length] = charLocation // push currentX += char.xAdvance + spacing lastCharID = charID if (charLocation.x + char.width > containerWidth) { if (wordWrap) { // when autoscaling, we must not split a word in half -> restart if (autoScale && lastWhiteSpace === -1) break // remove characters and add them again to next line const numCharsToRemove = lastWhiteSpace === -1 ? 1 : i - lastWhiteSpace for ( j = 0; j < numCharsToRemove; ++j // faster than 'splice' ) currentLine.pop() if (currentLine.length === 0) break i -= numCharsToRemove } else { if (autoScale) break currentLine.pop() // continue with next line, if there is one while (i < numChars - 1 && text.charCodeAt(i) !== CHAR_NEWLINE) ++i } lineFull = true } } if (i === numChars - 1) { sLines[sLines.length] = currentLine // push finished = true } else if (lineFull) { sLines[sLines.length] = currentLine // push if (lastWhiteSpace === i) currentLine.pop() if ( currentY + this._lineHeight + leading + this._size <= containerHeight ) { currentLine = BitmapCharLocation.vectorFromPool() currentX = 0 currentY += this._lineHeight + leading lastWhiteSpace = -1 lastCharID = -1 } else { break } } } // for each char } // if (this._lineHeight <= containerHeight) if (autoScale && !finished && fontSize > 3) fontSize -= 1 else finished = true } // while (!finished) const finalLocations = BitmapCharLocation.vectorFromPool() const numLines = sLines.length const bottom = currentY + this._lineHeight let yOffset = 0 if (vAlign === Align.BOTTOM) yOffset = containerHeight - bottom else if (vAlign === Align.CENTER) yOffset = (containerHeight - bottom) / 2 for (let lineID = 0; lineID < numLines; ++lineID) { const line = sLines[lineID] numChars = line.length if (numChars === 0) continue let xOffset = 0 const lastLocation = line[line.length - 1] const right = lastLocation.x - lastLocation.char.xOffset + lastLocation.char.xAdvance if (hAlign === Align.RIGHT) xOffset = containerWidth - right else if (hAlign === Align.CENTER) xOffset = (containerWidth - right) / 2 for (let c = 0; c < numChars; ++c) { charLocation = line[c] charLocation.x = scale * (charLocation.x + xOffset + this._offsetX) + this._padding charLocation.y = scale * (charLocation.y + yOffset + this._offsetY) + this._padding charLocation.scale = scale if (charLocation.char.width > 0 && charLocation.char.height > 0) finalLocations[finalLocations.length] = charLocation } } return finalLocations } /** The name of the font as it was parsed from the font file. */ get name() { return this._name } set name(value) { this._name = value } /** The native size of the font. */ get size() { return this._size } set size(value) { this._size = value } /** The type of the bitmap font. @see starling.text.BitmapFontType @default standard */ get type() { return this._type } set type(value) { this._type = value } /** If the font uses a distance field texture, this property returns its spread (i.e. * the width of the blurred edge in points). */ get distanceFieldSpread() { return this._distanceFieldSpread } set distanceFieldSpread(value) { this._distanceFieldSpread = value } /** The height of one line in points. */ get lineHeight() { return this._lineHeight } set lineHeight(value) { this._lineHeight = value } /** The smoothing filter that is used for the texture. */ get smoothing() { return this._helperImage.textureSmoothing } set smoothing(value) { this._helperImage.textureSmoothing = value } /** The baseline of the font. This property does not affect text rendering; * it's just an information that may be useful for exact text placement. */ get baseline() { return this._baseline } set baseline(value) { this._baseline = value } /** An offset that moves any generated text along the x-axis (in points). * Useful to make up for incorrect font data. @default 0. */ get offsetX() { return this._offsetX } set offsetX(value) { this._offsetX = value } /** An offset that moves any generated text along the y-axis (in points). * Useful to make up for incorrect font data. @default 0. */ get offsetY() { return this._offsetY } set offsetY(value) { this._offsetY = value } /** The width of a "gutter" around the composed text area, in points. * This can be used to bring the output more in line with standard TrueType rendering: * Flash always draws them with 2 pixels of padding. @default 0.0 */ get padding() { return this._padding } set padding(value) { this._padding = value } /** The underlying texture that contains all the chars. */ get texture() { return this._texture } }
JavaScript
class ExposeIgniteFormFieldControl { /** @type {IgniteFormField} */ formField; /** @type {ng.INgModelController} */ ngModel; /** * Name used to access control from $scope. * @type {string} */ name; $onInit() { if (this.formField && this.ngModel) this.formField.exposeControl(this.ngModel, this.name); } }
JavaScript
class Cart extends React.Component { addAnotherToCart(productId) { console.log('productId', productId) this.props.getCartWithItemAdded(productId) } removeOneFromCart(cartId, productId) { this.props.getCartWithItemRemoved(cartId, productId) } render() { console.log('PROPS IN THE CART', this.props) const products = this.props.cart.products const cart = this.props.cart return ( <div> <h1>Cart Contents: </h1> {products ? products.length > 0 ? products.map(product => ( <li key={product.id} className="cart-list-item"> <img className="cart-product-image" src={product.imageUrl} alt={(product.cut, product.color)} /> <div className="product-in-cart-description"> <div>Cut: {product.cut}</div> <div>Color: {product.color}</div> <div>Size: {product.size}</div> <b>Item Price: </b> ${product.price / 100} </div> <div className="cart-button"> <button type="button" onClick={() => this.addAnotherToCart(product.id)} > + </button> <p> I want more! </p> </div> <div className="cart-product-quantity"> <b>I'm getting: </b> <p>{product.cartProducts.quantity}</p> </div> <div className="cart-button"> <button type="button" onClick={() => this.removeOneFromCart(cart.id, product.id) } > - </button> <p> Next time... </p> </div> <div className="cart-product-total-price"> <b>Total Price: </b> <p> ${product.price * product.cartProducts.quantity / 100} .00 </p> </div> </li> )) : 'Oh no! Your cart is empty. Time to go shopping!!' : 'Oh no! Your cart is empty. Time to go shopping!'} <h3>Subtotal: ${this.props.cart.subTotal}</h3> {this.props.cart.subTotal > 0 ? ( <div> <h3>Make Them Mine!</h3> <button type="button" className="cart-checkout-button" onClick={this.props.checkOut} > <Link to="/checkout">Check Me Out!</Link> </button> </div> ) : ( '' )} </div> ) } }
JavaScript
class Config{ constructor(dataBase, port, dist, defaultPath){ this.dataBase = dataBase this.port = port this.dist = dist this.defaultPath = defaultPath } }
JavaScript
class SceneController { constructor() { this.mVisual = new Container("root"); this.mScene = new Three.Scene(); this.mScene.background = new Three.Color(0xF0F0F0); this.mScene.userData.controller = this; // Size of a handle in world coordinates = 50cm this.mHandleSize = Units.UPM[Units.IN] / 2; let self = this; // Set up the selection manager this.mSelection = new Selection((sln) => { let $report = $("<ul></ul>"); for (let sel of sln.items) { if (sln.resizeHandles) sln.resizeHandles(); let $s = makeControls(sel.scheme("")); if ($s) $report.append($s); } $(".information") .empty() .append($report); }); this._bindDialogHandlers(); } // Command handler, returns true if the command is handled onCmd(fn) { if (this[fn]) { this[fn].call(this); return true; } return false; } /** * Finish up after leading a new visual */ _onLoadedVisual(fn, visual) { this.mVisual.addChild(visual); visual.addToScene(this.mScene); this.refrshMesh(); let bb = this.mVisual.boundingBox; let min = Units.stringify(Units.IN, bb.min, Units.LATLON); let max = Units.stringify(Units.IN, bb.max, Units.LATLON); console.log(`Loaded ${fn}, ${min} -> ${max}`); $(document).trigger("fitViews"); } /** * Add in handlers for load and save dialogs */ _bindDialogHandlers() { let self = this; // URL load $("#loadURL_dialog .load").on("click", function(evt) { let url = $("#loadURL_dialog .url").val(); let type = url.replace(/^.*\./u, "").toLowerCase(); $("#loadURL_dialog").dialog("close"); requirejs( [`js/FileFormats/${type}`], (Loader) => { $.get(url, function(data) { new Loader().load(url, data) .then((visual) => { self._onLoadedVisual(url, visual); }) .catch((err) => { console.debug(err); }); }, "text"); }); }); // Local file upload $("#loadFile_dialog .load").on("change", function(evt) { let f = evt.target.files[0]; let fn = f.name; let type = fn.replace(/^.*\./u, "").toLowerCase(); $("#loadFile_dialog").dialog("close"); requirejs( [`js/FileFormats/${type}`], (Loader) => { let reader = new FileReader(); reader.onload = (e) => { let data = e.target.result; new Loader().load(fn, data) .then((visual) => { self._onLoadedVisual(fn, visual); }) .catch((err) => { console.debug(err); }); }; // Read in the image file as a data URL. reader.readAsText(f); }, (err) => { $("#alert_message") .html(`Error loading js/FileFormats/${type} - is the file format supported?`); $("#alert_dialog").dialog("open"); }); }); // Download to local file let saver; $("#download_dialog .download_button").on("click", function() { let str = saver.save(self.mVisual); // If saver.save() returns null, then it has used a dialog and we // don't require native event handling if (!str) return false; // suppress native event handling // The format wants to use the Save button to trigger the save this.href = URL.createObjectURL(new Blob([str])); let fmt = $("#download_dialog .format").val(); this.download = `survey.${fmt}`; // Pass on for native event handling return true; }); // Cannot set the saver from inside the save handler // because loading a FileFormat requires a promise, but // the native click event on the download link is required // to trigger the download, which requires a true return // from the handler. So have to do it in two // steps. Setting the save format loads the saver and // enables the save button if successful. Clicking the // save button saves using that saver. $("#download_dialog .format").on("change", function() { let type = $(this).val(); requirejs( [`js/FileFormats/${type}`], (Format) => { saver = new Format(); $("#download_dialog .download_button") .removeProp("disabled"); }); }); } /** * Canvas controllers use this to publicise the current method * for getting the zoom factor. This is required to set handle * and cursor sizes. */ setZoomGetter(fn) { this.mZoomGetter = fn; } /** * Get the handle size scaled as appropriate for the current view */ get handleSize() { return this.mHandleSize / this.mZoomGetter.call(); } /** * Resize all handles in the visual so they appear as a * fraction of the view */ resizeHandles(viewSize) { // Scale handles appropriately if (viewSize) { this.mHandleSize = viewSize / 50; } this.mVisual.resizeHandles(); } /** * Get the current selection in the scene */ get selection() { return this.mSelection; } /** * Get the bounding box for the visual, or a suitable box if * no visual is currently displayed */ get boundingBox() { let bounds = this.mVisual.boundingBox; if (bounds.isEmpty()) { // Deal with an empty visual // A roughly 1nm square block of sea in the English Channel let ll = Units.convert( Units.LATLON, { lon: -0.5, lat: 50 }, Units.IN); ll = new Three.Vector3(ll.x, ll.y, -10); let ur = Units.convert( Units.LATLON, { lon: -0.483, lat: 50.017 }, Units.IN); ur = new Three.Vector3(ur.x, ur.y, 10); bounds = new Three.Box3(ll, ur); } return bounds; } /** * Get the Visual being handled by this controller * @return {Visual} the root visual */ get visual() { return this.mVisual; } /** * Get the Three.Scene generated from the visual in this canvas * @return {Three.Scene} the scene */ get scene() { return this.mScene; } /** * Project the given ray into the scene. @see Visual */ projectRay(ray) { return this.mVisual.projectRay( ray, Units.UPM[Units.IN] * Units.UPM[Units.IN]); } // Command handlers /** * Import scene data by uploading a file from local disk */ loadFile() { $("#loadFile_dialog").dialog("open"); } /** * Import scene data from a URL */ loadURL() { $("#loadURL_dialog").dialog("open"); } /** * Download the current scene */ download() { $("#download_dialog").dialog("open"); } /** * Add a new POI under the ruler start */ addPOI() { let pt = new POI(this.rulerStart, "New POI"); this.mVisual.addChild(pt); pt.addToScene(this.scene); pt.resizeHandles(); this.mSelection.add(pt); } /** * Add a new Sounding under the ruler start */ addSounding() { let pt = new Sounding(this.rulerStart, "New sounding"); this.mVisual.addChild(pt); pt.addToScene(this.scene); pt.resizeHandles(); this.mSelection.add(pt); this.refreshMesh(); } /** * Change the selection to select the sibling before it in the * scene. Applies across all items in the visual. */ selPrev() { let sel = this.mSelection.items.slice(); for (let s of sel) { if (s.prev) { this.mSelection.remove(s); this.mSelection.add(s.prev); } } return false; } /** * Change the selection to select the sibling after it in the * scene. Applies across all items in the visual. */ selNext() { let sel = this.mSelection.items.slice(); for (let s of sel) { if (s.next) { this.mSelection.remove(s); this.mSelection.add(s.next); } } return false; } /** * Change the selection to select the parent of it in the * scene. Applies across all items in the visual. */ selParent() { let sel = this.mSelection.items.slice(); for (let s of sel) { if (s.parent !== this.mVisual) { this.mSelection.remove(s); this.mSelection.add(s.parent); } } return false; } /** * Change the selection to select the first child (if it has * children). Applies across all items in the visual. */ selFirstChild() { let sel = this.mSelection.items.slice(); for (let s of sel) { if (s.children && s.children.length > 0) { this.mSelection.remove(s); this.mSelection.add(s.children[0]); } } return false; } /** * Delete all currently selected items */ selDelete() { for (let sel of this.mSelection.items) // Remove the item completely sel.remove(); this.mSelection.clear(); return false; } /** * Add a new path, two points, one at the rulerStart, the other * nearby */ addPath() { let visual = new Path("New path"); visual.addVertex(this.rulerStart); visual.addVertex({ x: this.rulerStart.x + 2 * Units.UPM[Units.IN], y: this.rulerStart.y + 2 * Units.UPM[Units.IN], z: this.rulerStart.z }); this.mVisual.addChild(visual); visual.addToScene(this.mScene); visual.resizeHandles(); this.mSelection.add(visual); } /** * Add a new contour, three points centred on the start of the * ruler, 1m radius */ addContour() { let visual = new Contour("New point"); visual.addVertex( { x: this.rulerStart.x, y: this.rulerStart.y + Units.UPM[Units.IN] }); visual.addVertex( { x: this.rulerStart.x + 0.866 * Units.UPM[Units.IN], y: this.rulerStart.y - 0.5 * Units.UPM[Units.IN] }); visual.addVertex( { x: this.rulerStart.x - 0.866 * Units.UPM[Units.IN], y: this.rulerStart.y - 0.5 * Units.UPM[Units.IN] }); visual.close(); visual.setZ(0); this.mVisual.addChild(visual); visual.addToScene(this.mScene); visual.resizeHandles(); this.mSelection.add(visual); this.refreshMesh(); } /** * Split all edges that are selected by virtue of their * endpoints being selected. Edges are split at their midpoint. */ splitEdges() { if (this.mSelection.isEmpty) return; let sel = this.mSelection.items; // Split edges where both end points are in the selection let split = []; for (let i = 0; i < sel.length; i++) { let s = sel[i]; if (s instanceof Spot) { for (let j = i + 1; j < sel.length; j++) { let ss = sel[j]; if (ss !== s && ss.parent === s.parent && s.parent.hasEdge && s.parent.hasEdge(s, ss)) split.push({ p: ss.parent, a: s, b: ss }); } } } for (let e of split) { let v = e.p.splitEdge(e.a, e.b); if (v) { this.mSelection.add(v); v.resizeHandles(); } } this.refreshMesh(); } /** * Remove the currently computed mesh from the scene. */ // Does not delete the mesh. removeMeshFromScene() { if (this.mMesh) this.mScene.remove(this.mMesh); } /** * If there is a currently computed mesh, delete it * and recompute a fresh mesh. */ refreshMesh() { if (this.mMesh) { this.mScene.remove(this.mMesh); this.mMesh = null; this.addMeshToScene(); } } /** * Add a mesh to the scene. The mesh is built by condensing * Contour and Sounding points into a point cloud and then * computing a Delaunay triangulation. */ addMeshToScene() { if (this.mMesh) { this.mScene.add(this.mMesh); return; } // Condense Contours and Soundings into a cloud of points // and edges - @see Visual let v = []; let e = []; this.mVisual.condense(v, e); let geom = new Three.Geometry(); let coords = []; for (let o of v) { coords.push([o.x, o.y]); geom.vertices.push(o); } let del = Delaunator.from(coords); for (let t = 0; t < del.triangles.length / 3; t++) { geom.faces.push(new Three.Face3( del.triangles[3 * t + 2], del.triangles[3 * t + 1], del.triangles[3 * t])); } geom.computeFaceNormals(); geom.computeVertexNormals(); this.mMesh = new Three.Mesh(geom, Materials.MESH); this.mScene.add(this.mMesh); } }
JavaScript
class JSONConverter extends Converter { uniqueValuesMap = {}; constructor(commonAPIHandler) { super(commonAPIHandler); } async appendToRequest(requestBase, requestObject) { return JSON.stringify(requestBase.getRequestBody()) || null; } async formRequest(requestInstance, pack, instanceNumber, memberDetail) { var classDetail = Initializer.jsonDetails[pack]; if (classDetail.hasOwnProperty(Constants.INTERFACE) && classDetail[Constants.INTERFACE]) { var classes = classDetail[Constants.CLASSES]; var baseName = pack.split('/').slice(0, -1); let className = await this.getFileName(requestInstance.constructor.name); baseName.push(className); let requestObjectClassName = baseName.join('/'); for (let className1 in classes) { if (classes[className1].toLowerCase() == requestObjectClassName) { classDetail = Initializer.jsonDetails[requestObjectClassName]; break; } } } if (requestInstance instanceof Record) { let moduleAPIName = this.commonAPIHandler.getModuleAPIName(); let returnJSON = await this.isRecordRequest(requestInstance, classDetail, instanceNumber, memberDetail); this.commonAPIHandler.setModuleAPIName(moduleAPIName); return returnJSON; } else { return await this.isNotRecordRequest(requestInstance, classDetail, instanceNumber, memberDetail); } } async isNotRecordRequest(requestInstance, classDetail, instanceNumber, classMemberDetail) { var requestJSON = {}; var requiredKeys = new Map(); var primaryKeys = new Map(); var requiredInUpdateKeys = new Map(); var lookUp = false; var skipMandatory = false; var classMemberName = null; if (classMemberDetail != null) { lookUp = (classMemberDetail.hasOwnProperty(Constants.LOOKUP) ? classMemberDetail[Constants.LOOKUP] : false); skipMandatory = (classMemberDetail.hasOwnProperty(Constants.SKIP_MANDATORY) ? classMemberDetail[Constants.SKIP_MANDATORY] : false); classMemberName = this.buildName(classMemberDetail[Constants.NAME]); } for (let memberName in classDetail) { var modification = null; var memberDetail = classDetail[memberName]; if ((memberDetail.hasOwnProperty(Constants.READ_ONLY) && memberDetail[Constants.READ_ONLY] == 'true') || !memberDetail.hasOwnProperty(Constants.NAME)) {// read only or no keyName continue; } var keyName = memberDetail[Constants.NAME]; try { modification = requestInstance.isKeyModified(keyName); } catch (ex) { throw new SDKException(Constants.EXCEPTION_IS_KEY_MODIFIED, null, null, ex); } if (memberDetail.hasOwnProperty(Constants.REQUIRED) && memberDetail[Constants.REQUIRED] == true) { requiredKeys.set(keyName, true); } if (memberDetail.hasOwnProperty(Constants.PRIMARY) && memberDetail[Constants.PRIMARY] == true && (!memberDetail.hasOwnProperty(Constants.REQUIRED_IN_UPDATE) || memberDetail[Constants.REQUIRED_IN_UPDATE] == true)) { primaryKeys.set(keyName, true); } if (memberDetail.hasOwnProperty(Constants.REQUIRED_IN_UPDATE) && memberDetail[Constants.REQUIRED_IN_UPDATE] == true) { requiredInUpdateKeys.set(keyName, true); } var fieldValue = null; if (modification != null && modification != 0) { fieldValue = Reflect.get(requestInstance, memberName); if (await this.valueChecker(requestInstance.constructor.name, memberName, memberDetail, fieldValue, this.uniqueValuesMap, instanceNumber)) { if (fieldValue != null) { requiredKeys.delete(keyName); primaryKeys.delete(keyName); requiredInUpdateKeys.delete(keyName); } if (requestInstance instanceof FileDetails) { if (fieldValue == null || fieldValue == "null") { requestJSON[keyName.toLowerCase()] = null; } else { requestJSON[keyName.toLowerCase()] = fieldValue; } } else { requestJSON[keyName] = await this.setData(memberDetail, fieldValue) } } } } if (skipMandatory || this.checkException(classMemberName, requestInstance, instanceNumber, lookUp, requiredKeys, primaryKeys, requiredInUpdateKeys) === true) { return requestJSON; } } checkException(memberName, requestInstance, instanceNumber, lookUp, requiredKeys, primaryKeys, requiredInUpdateKeys) { if (requiredInUpdateKeys.size > 0 && this.commonAPIHandler.getCategoryMethod() != null && this.commonAPIHandler.getCategoryMethod().toUpperCase() == Constants.REQUEST_CATEGORY_UPDATE) { let error = {}; error.field = memberName; error.type = requestInstance.constructor.name; error.keys = Array.from(requiredInUpdateKeys.keys()).toString(); if (instanceNumber != null) { error.instance_number = instanceNumber; } throw new SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error, null); } if (this.commonAPIHandler.isMandatoryChecker() != null && this.commonAPIHandler.isMandatoryChecker()) { if (this.commonAPIHandler.getCategoryMethod().toUpperCase() == Constants.REQUEST_CATEGORY_CREATE) { if (lookUp) { if (primaryKeys.size > 0) { let error = {}; error.field = memberName; error.type = requestInstance.constructor.name; error.keys = Array.from(primaryKeys.keys()).toString(); if (instanceNumber != null) { error.instance_number = instanceNumber; } throw new SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error, null); } } else if (requiredKeys.size > 0) { let error = {}; error.field = memberName; error.type = requestInstance.constructor.name; error.keys = Array.from(requiredKeys.keys()).toString(); if (instanceNumber != null) { error.instance_number = instanceNumber; } throw new SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.MANDATORY_KEY_ERROR, error, null); } } if (this.commonAPIHandler.getCategoryMethod().toUpperCase() == Constants.REQUEST_CATEGORY_UPDATE && primaryKeys.size > 0) { let error = {}; error.field = memberName; error.type = requestInstance.constructor.name; error.keys = Array.from(primaryKeys.keys()).toString(); if (instanceNumber != null) { error.instance_number = instanceNumber; } throw new SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error, null); } } else if (lookUp && this.commonAPIHandler.getCategoryMethod().toUpperCase() == Constants.REQUEST_CATEGORY_UPDATE) { if (primaryKeys.size > 0) { let error = {}; error.field = memberName; error.type = requestInstance.constructor.name; error.keys = Array.from(primaryKeys.keys()).toString(); if (instanceNumber != null) { error.instance_number = instanceNumber; } throw new SDKException(Constants.MANDATORY_VALUE_ERROR, Constants.PRIMARY_KEY_ERROR, error, null); } } return true; } async isRecordRequest(recordInstance, classDetail, instanceNumber, classMemberDetail) { var requestJSON = {}; var moduleDetail = {}; var lookUp = false; var skipMandatory = false; var classMemberName = null; if (classMemberDetail != null) { lookUp = (classMemberDetail.hasOwnProperty(Constants.LOOKUP) ? classMemberDetail[Constants.LOOKUP] : false); skipMandatory = (classMemberDetail.hasOwnProperty(Constants.SKIP_MANDATORY) ? classMemberDetail[Constants.SKIP_MANDATORY] : false); classMemberName = this.buildName(classMemberDetail[Constants.NAME]); } var moduleAPIName = this.commonAPIHandler.getModuleAPIName(); if (moduleAPIName != null) {// entry this.commonAPIHandler.setModuleAPIName(null); var fullDetail = await Utility.searchJSONDetails(moduleAPIName);// to get correct moduleapiname in proper format if (fullDetail != null) {// from Jsondetails moduleDetail = fullDetail[Constants.MODULEDETAILS]; } else {// from user spec moduleDetail = await this.getModuleDetailFromUserSpecJSON(moduleAPIName); } } else {// inner case moduleDetail = classDetail; classDetail = Initializer.jsonDetails[Constants.RECORD_NAMESPACE]; }// class detail must contain record structure at this point let uniqueValues = new Map(); var keyValues = Reflect.get(recordInstance, Constants.KEY_VALUES); var keyModified = Reflect.get(recordInstance, Constants.KEY_MODIFIED); var requiredKeys = new Map(); var primaryKeys = new Map(); if (!skipMandatory) { for (let keyName of Object.keys(moduleDetail)) { const keyDetail = moduleDetail[keyName]; let name = keyDetail[Constants.NAME]; if (keyDetail != null && keyDetail.hasOwnProperty(Constants.REQUIRED) && keyDetail[Constants.REQUIRED] == true) { requiredKeys.set(name, true); } if (keyDetail != null && keyDetail.hasOwnProperty(Constants.PRIMARY) && keyDetail[Constants.PRIMARY] == true) { primaryKeys.set(name, true); } } for (let keyName of Object.keys(classDetail)) { const keyDetail = classDetail[keyName]; let name = keyDetail[Constants.NAME]; if (keyDetail.hasOwnProperty(Constants.REQUIRED) && keyDetail[Constants.REQUIRED] == true) { requiredKeys.set(name, true); } if (keyDetail.hasOwnProperty(Constants.PRIMARY) && keyDetail[Constants.PRIMARY] == true) { primaryKeys.set(name, true); } } } for (let keyName of Array.from(keyModified.keys())) { if (keyModified.get(keyName) != 1) { continue; } let keyDetail = {}; let keyValue = keyValues.has(keyName) ? keyValues.get(keyName) : null; let jsonValue = null; if (keyValue != null) { requiredKeys.delete(keyName); primaryKeys.delete(keyName); } let memberName = this.buildName(keyName); if (moduleDetail != null && Object.keys(moduleDetail).length > 0 && (moduleDetail.hasOwnProperty(keyName) || moduleDetail.hasOwnProperty(memberName))) { if (moduleDetail.hasOwnProperty(keyName)) { keyDetail = moduleDetail[keyName];// incase of user spec json } else { keyDetail = moduleDetail[memberName];// json details } } else if (classDetail.hasOwnProperty(memberName)) { keyDetail = classDetail[memberName]; } if (Object.keys(keyDetail).length > 0) { if ((keyDetail.hasOwnProperty(Constants.READ_ONLY) && (keyDetail[Constants.READ_ONLY] == true || keyDetail[Constants.READ_ONLY] == 'true')) || !keyDetail.hasOwnProperty(Constants.NAME)) { // read only or no keyName continue; } if (await this.valueChecker(recordInstance.constructor.name, keyName, keyDetail, keyValue, uniqueValues, instanceNumber)) { jsonValue = await this.setData(keyDetail, keyValue); } } else { jsonValue = await this.redirectorForObjectToJSON(keyValue); } requestJSON[keyName] = jsonValue; } if (skipMandatory || this.checkException(classMemberName, recordInstance, instanceNumber, lookUp, requiredKeys, primaryKeys, new Map())) { return requestJSON; } return requestJSON; } async setData(memberDetail, fieldValue) { if (fieldValue != null) { let type = memberDetail[Constants.TYPE].toString(); if (type.toLowerCase() == Constants.LIST_NAMESPACE.toLowerCase()) { return await this.setJSONArray(fieldValue, memberDetail); } else if (type.toLowerCase() == Constants.MAP_NAMESPACE.toLowerCase()) { return await this.setJSONObject(fieldValue, memberDetail); } else if (type == Constants.CHOICE_NAMESPACE || (memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME) && memberDetail[Constants.STRUCTURE_NAME] == Constants.CHOICE_NAMESPACE)) { return fieldValue.getValue(); } else if (memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME) && memberDetail.hasOwnProperty(Constants.MODULE)) { return await this.isRecordRequest(fieldValue, await this.getModuleDetailFromUserSpecJSON(memberDetail[Constants.MODULE]), null, memberDetail); } else if (memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME)) { return await this.formRequest(fieldValue, memberDetail[Constants.STRUCTURE_NAME], null, memberDetail); } else { return DatatypeConverter.postConvert(fieldValue, type); } } return null; } async setJSONObject(requestObject, memberDetail) { var jsonObject = {}; if (Array.from(requestObject.keys()).length > 0) { if (memberDetail == null || (memberDetail != null && !memberDetail.hasOwnProperty(Constants.KEYS))) { for (let key of Array.from(requestObject.keys())) { jsonObject[key] = await this.redirectorForObjectToJSON(requestObject.get(key)); } } else { if (memberDetail !== null && memberDetail.hasOwnProperty(Constants.KEYS)) { var keysDetail = memberDetail[Constants.KEYS]; for (let keyIndex = 0; keyIndex < keysDetail.length; keyIndex++) { let keyDetail = keysDetail[keyIndex]; let keyName = keyDetail[Constants.NAME]; let keyValue = null; if (requestObject.has(keyName) && requestObject.get(keyName) != null) { keyValue = await this.setData(keyDetail, requestObject.get(keyName)); jsonObject[keyName] = keyValue; } } } } } return jsonObject; } async setJSONArray(requestObjects, memberDetail) { var jsonArray = []; if (requestObjects.length > 0) { if (memberDetail == null || (memberDetail != null && !memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME))) { for (let request of requestObjects) { jsonArray.push(await this.redirectorForObjectToJSON(request)); } } else { let pack = memberDetail[Constants.STRUCTURE_NAME].toString(); if (pack == Constants.CHOICE_NAMESPACE) { for (let request of requestObjects) { jsonArray.push(request.getValue()); } } else if (memberDetail.hasOwnProperty(Constants.MODULE) && memberDetail[Constants.MODULE] != null) { let instanceCount = 0; for (let request of requestObjects) { jsonArray.push(await this.isRecordRequest(request, await this.getModuleDetailFromUserSpecJSON(memberDetail[Constants.MODULE]), instanceCount++, memberDetail)); } } else { let instanceCount = 0; for (let request of requestObjects) { jsonArray.push(await this.formRequest(request, pack, instanceCount++, memberDetail)); } } } } return jsonArray; } async redirectorForObjectToJSON(request) { if (Array.isArray(request)) { return await this.setJSONArray(request, null); } else if (request instanceof Map) { return await this.setJSONObject(request, null); } else { return request; } } async getWrappedResponse(response, pack) { if (response.body.length != 0) { var responseJson = JSON.parse(response.body); return await this.getResponse(responseJson, pack); } return null; } async getResponse(responseJson, packageName) { var instance = null; if (responseJson == null || responseJson == "" || responseJson.length == 0) { return instance; } var classDetail = Initializer.jsonDetails[packageName]; if (classDetail.hasOwnProperty(Constants.INTERFACE) && classDetail[Constants.INTERFACE]) { let classes = classDetail[Constants.CLASSES]; instance = await this.findMatch(classes, responseJson);// findmatch returns instance(calls getresponse() recursively) } else { let ClassName = require("../../" + packageName).MasterModel; instance = new ClassName(); if (instance instanceof Record) {// if record -> based on response json data will be assigned to field Values let moduleAPIName = this.commonAPIHandler.getModuleAPIName(); instance = await this.isRecordResponse(responseJson, classDetail, packageName); this.commonAPIHandler.setModuleAPIName(moduleAPIName); } else { instance = await this.notRecordResponse(instance, responseJson, classDetail);// based on json details data will be assigned } } return instance; } async notRecordResponse(instance, responseJSON, classDetail) { for (let memberName in classDetail) { let keyDetail = classDetail[memberName]; let keyName = keyDetail.hasOwnProperty(Constants.NAME) ? keyDetail[Constants.NAME] : null;// api-name of the member if (keyName != null && responseJSON.hasOwnProperty(keyName) && responseJSON[keyName] !== null) { let keyData = responseJSON[keyName]; let memberValue = await this.getData(keyData, keyDetail); Reflect.set(instance, memberName, memberValue); } } return instance; } async isRecordResponse(responseJson, classDetail, pack) { let className = require("../../" + pack).MasterModel; let recordInstance = new className(); let moduleAPIName = this.commonAPIHandler.getModuleAPIName(); let moduleDetail = {}; if (moduleAPIName != null) { // entry this.commonAPIHandler.setModuleAPIName(null); let fullDetail = await Utility.searchJSONDetails(moduleAPIName);// to get correct moduleapiname in proper format if (fullDetail != null) {// from Jsondetails moduleDetail = fullDetail[Constants.MODULEDETAILS]; let moduleClassName = require("../../" + fullDetail[Constants.MODULEPACKAGENAME]).MasterModel; recordInstance = new moduleClassName(); } else { // from user spec moduleDetail = await this.getModuleDetailFromUserSpecJSON(moduleAPIName); } } for (let key in classDetail) { moduleDetail[key] = classDetail[key]; } var recordDetail = Initializer.jsonDetails[Constants.RECORD_NAMESPACE]; var keyValues = new Map(); for (let keyName in responseJson) { let memberName = this.buildName(keyName); let keyDetail = {}; if (moduleDetail != null && Object.keys(moduleDetail).length > 0 && (moduleDetail.hasOwnProperty(keyName) || moduleDetail.hasOwnProperty(memberName))) { if (moduleDetail.hasOwnProperty(keyName)) { keyDetail = moduleDetail[keyName]; } else { keyDetail = moduleDetail[memberName]; } } else if (recordDetail.hasOwnProperty(memberName)) { keyDetail = recordDetail[memberName]; } let keyValue = null; let keyData = responseJson[keyName]; if (keyDetail != null && Object.keys(keyDetail).length > 0) { keyName = keyDetail[Constants.NAME]; keyValue = await this.getData(keyData, keyDetail); } else {// if not key detail keyValue = await this.redirectorForJSONToObject(keyData); } keyValues.set(keyName, keyValue); } Reflect.set(recordInstance, Constants.KEY_VALUES, keyValues); return recordInstance; } async getData(keyData, memberDetail) { let memberValue = null; if (keyData != null) { let type = memberDetail[Constants.TYPE].toString(); if (type.toLowerCase() == Constants.LIST_NAMESPACE.toLowerCase()) { memberValue = await this.getCollectionsData(keyData, memberDetail); } else if (type.toLowerCase() == Constants.MAP_NAMESPACE.toLowerCase()) { memberValue = await this.getMapData(keyData, memberDetail); } else if (type == Constants.CHOICE_NAMESPACE || (memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME) && memberDetail[Constants.STRUCTURE_NAME] == Constants.CHOICE_NAMESPACE)) { let Choice = require(Constants.CHOICE_PATH).MasterModel; memberValue = new Choice(keyData); } else if (memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME) && memberDetail.hasOwnProperty(Constants.MODULE)) { memberValue = await this.isRecordResponse(keyData, await this.getModuleDetailFromUserSpecJSON(memberDetail[Constants.MODULE]), memberDetail[Constants.STRUCTURE_NAME]); } else if (memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME)) { memberValue = await this.getResponse(keyData, memberDetail[Constants.STRUCTURE_NAME]); } else { memberValue = await DatatypeConverter.preConvert(keyData, type); } } return memberValue; } async getMapData(response, memberDetail) { var mapInstance = new Map(); if (Object.keys(response).length > 0) { if (memberDetail == null || (memberDetail != null && !memberDetail.hasOwnProperty(Constants.KEYS))) { for (let key in response) { mapInstance.set(key, await this.redirectorForJSONToObject(response[key])); } } else {// member must have keys if (memberDetail.hasOwnProperty(Constants.KEYS)) { var keysDetail = memberDetail[Constants.KEYS]; for (let keyIndex = 0; keyIndex < keysDetail.length; keyIndex++) { var keyDetail = keysDetail[keyIndex]; var keyName = keyDetail[Constants.NAME]; var keyValue = null; if (response.hasOwnProperty(keyName) && response[keyName] != null) { keyValue = await this.getData(response[keyName], keyDetail); mapInstance.set(keyName, keyValue); } } } } } return mapInstance; } async getCollectionsData(responses, memberDetail) { var values = new Array(); if (responses.length > 0) { if (memberDetail == null || (memberDetail != null && !memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME))) { for (let response of responses) { values.push(await this.redirectorForJSONToObject(response)); } } else {// need to have structure Name in memberDetail var pack = memberDetail[Constants.STRUCTURE_NAME]; if (pack == Constants.CHOICE_NAMESPACE) { for (let response of responses) { let choiceClass = require(Constants.CHOICE_PATH).MasterModel; let choiceInstance = new choiceClass(response); values.push(choiceInstance); } } else if (memberDetail.hasOwnProperty(Constants.MODULE) && memberDetail[Constants.MODULE] != null) { for (let response of responses) { values.push(await this.isRecordResponse(response, await this.getModuleDetailFromUserSpecJSON(memberDetail[Constants.MODULE]), pack)); } } else { for (let response of responses) { values.push(await this.getResponse(response, pack)); } } } } return values; } async getModuleDetailFromUserSpecJSON(module) { let initializer = await Initializer.getInitializer(); var recordFieldDetailsPath = path.join(initializer.getResourcePath(), Constants.FIELD_DETAILS_DIRECTORY, await this.getEncodedFileName()); var moduleDetail = await Utility.getJSONObject(Initializer.getJSON(recordFieldDetailsPath), module); return moduleDetail; } async redirectorForJSONToObject(keyData) { let type = Object.prototype.toString.call(keyData); if (type == Constants.OBJECT_TYPE) { return await this.getMapData(keyData, null); } else if (type == Constants.ARRAY_TYPE) { return await this.getCollectionsData(keyData, null); } else { return keyData; } } async findMatch(classes, responseJson) { let pack = ""; let ratio = 0; for (let className of classes) { var matchRatio = await this.findRatio(className, responseJson); if (matchRatio == 1.0) { pack = className; ratio = 1; break; } else if (matchRatio > ratio) { ratio = matchRatio; pack = className; } } return this.getResponse(responseJson, pack); } findRatio(className, responseJson) { var classDetail = Initializer.jsonDetails[className]; var totalPoints = Array.from(Object.keys(classDetail)).length; var matches = 0; if (totalPoints == 0) { return 0; } else { for (let memberName in classDetail) { var memberDetail = classDetail[memberName]; var keyName = memberDetail.hasOwnProperty(Constants.NAME) ? memberDetail[Constants.NAME] : null; if (keyName != null && responseJson.hasOwnProperty(keyName) && responseJson[keyName] != null) {// key not empty var keyData = responseJson[keyName]; let type = Object.prototype.toString.call(keyData); let structureName = memberDetail.hasOwnProperty(Constants.STRUCTURE_NAME) ? memberDetail[Constants.STRUCTURE_NAME] : null; if (type == Constants.OBJECT_TYPE) { type = Constants.MAP_TYPE; } if (Constants.TYPE_VS_DATATYPE.has(memberDetail[Constants.TYPE].toLowerCase()) && Constants.TYPE_VS_DATATYPE.get(memberDetail[Constants.TYPE].toLowerCase()) == type) { matches++; } else if (memberDetail[Constants.TYPE] == Constants.CHOICE_NAMESPACE) { let values = memberDetail[Constants.VALUES]; for (let value in values) { if (keyData == values[value]) { matches++; break; } } } if (structureName != null && structureName == memberDetail[Constants.TYPE]) { if (memberDetail.hasOwnProperty(Constants.VALUES)) { let values = memberDetail[Constants.VALUES]; for (let value in values) { if (keyData == values[value]) { matches++; break; } } } else { matches++; } } } } } return matches / totalPoints; } buildName(memberName) { let name = memberName.toLowerCase().split("_"); var index = 0; if (name.length == 0) { index = 1; } var sdkName = name[0] sdkName = sdkName[0].toLowerCase() + sdkName.slice(1); index = 1; for (var nameIndex = index; nameIndex < name.length; nameIndex++) { var fieldName = name[nameIndex]; var firstLetterUppercase = ""; if (fieldName.length > 0) { firstLetterUppercase = fieldName[0].toUpperCase() + fieldName.slice(1); } sdkName = sdkName.concat(firstLetterUppercase); } return sdkName; } getFileName(name) { let fileName = []; let nameParts = name.split(/([A-Z][a-z]+)/).filter(function (e) { return e }); fileName.push(nameParts[0].toLowerCase()); for (let i = 1; i < nameParts.length; i++) { fileName.push(nameParts[i].toLowerCase()); } return fileName.join("_"); } }
JavaScript
class TxHashTooltip extends Component { constructor(props) { super(props); this.toggleTooltip = this.toggleTooltip.bind(this); this.state = { isOpenTooltip: false, tooltipText: 'Click to copy' }; } /** * @method toggleTooltip : To toggle tooltip view. */ toggleTooltip() { this.setState({ isOpenTooltip: !this.state.isOpenTooltip }); } render() { const { hash, index, copyToClipboard } = this.props; const { tooltipText, isOpenTooltip } = this.state; return ( <p style={{ cursor: 'pointer' }} id={`copyToClipboard_tooltip${index}`} onClick={() => copyToClipboard(hash)} > <span>TX#</span> {hash} <Tooltip placement="top" isOpen={isOpenTooltip} target={`copyToClipboard_tooltip${index}`} toggle={this.toggleTooltip} > {tooltipText} </Tooltip> </p> ); } }
JavaScript
class NavContainer extends React.Component { static propTypes = { children: PropTypes.any }; /** * Implements React's {@link SettingsMenu#render()}. * * @inheritdoc * @returns {ReactElement} */ render() { return ( <div className = 'nav-section'> <div className = 'nav'> { this.props.children } </div> </div> ); } }
JavaScript
class HandlerExecutorFactory { constructor(arweave) { this.arweave = arweave; this.logger = LoggerFactory.INST.create('HandlerExecutorFactory'); this.assignReadContractState = this.assignReadContractState.bind(this); this.assignViewContractState = this.assignViewContractState.bind(this); } async create(contractDefinition) { const normalizedSource = HandlerExecutorFactory.normalizeContractSource(contractDefinition.src); const swGlobal = new SmartWeaveGlobal(this.arweave, { id: contractDefinition.txId, owner: contractDefinition.owner }); const contractFunction = new Function(normalizedSource); // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; const contractLogger = LoggerFactory.INST.create('Contract'); return { async handle(executionContext, state, interaction, interactionTx, currentTx) { try { const handler = contractFunction(swGlobal, BigNumber, clarity, contractLogger); const stateCopy = JSON.parse(JSON.stringify(state)); swGlobal._activeTx = interactionTx; self.logger.trace(`SmartWeave.contract.id:`, swGlobal.contract.id); self.assignReadContractState(swGlobal, contractDefinition, executionContext, currentTx); self.assignViewContractState(swGlobal, contractDefinition, executionContext); const handlerResult = await handler(stateCopy, interaction); if (handlerResult && (handlerResult.state || handlerResult.result)) { return { type: 'ok', result: handlerResult.result, state: handlerResult.state || state }; } // Will be caught below as unexpected exception. throw new Error(`Unexpected result from contract: ${JSON.stringify(handlerResult)}`); } catch (err) { switch (err.name) { case 'ContractError': return { type: 'error', errorMessage: err.message, state, // note: previous version was writing error message to a "result" field, // which fucks-up the HandlerResult type definition - // HandlerResult.result had to be declared as 'Result | string' - and that led to a poor dev exp. // TODO: this might be breaking change! result: null }; default: return { type: 'exception', errorMessage: `${(err && err.stack) || (err && err.message)}`, state, result: null }; } } } }; } assignViewContractState(swGlobal, contractDefinition, executionContext) { swGlobal.contracts.viewContractState = async (contractTxId, input) => { this.logger.debug('swGlobal.viewContractState call:', { from: contractDefinition.txId, to: contractTxId, input }); const childContract = executionContext.smartweave .contract(contractTxId, executionContext.contract) .setEvaluationOptions(executionContext.evaluationOptions); return await childContract.viewStateForTx(input, swGlobal._activeTx); }; } assignReadContractState(swGlobal, contractDefinition, executionContext, currentTx) { swGlobal.contracts.readContractState = async (contractTxId, height, returnValidity) => { const requestedHeight = height || swGlobal.block.height; this.logger.debug('swGlobal.readContractState call:', { from: contractDefinition.txId, to: contractTxId, height: requestedHeight, transaction: swGlobal.transaction.id }); const childContract = executionContext.smartweave .contract(contractTxId, executionContext.contract) .setEvaluationOptions(executionContext.evaluationOptions); const stateWithValidity = await childContract.readState(requestedHeight, [ ...(currentTx || []), { contractTxId: contractDefinition.txId, interactionTxId: swGlobal.transaction.id } ]); // TODO: it should be up to the client's code to decide which part of the result to use // (by simply using destructuring operator)... // but this (i.e. returning always stateWithValidity from here) would break backwards compatibility // in current contract's source code..:/ return returnValidity ? deepCopy(stateWithValidity) : deepCopy(stateWithValidity.state); }; } static normalizeContractSource(contractSrc) { // Convert from ES Module format to something we can run inside a Function. // Removes the `export` keyword and adds ;return handle to the end of the function. // Additionally it removes 'IIFE' declarations // (which may be generated when bundling multiple sources into one output file // - eg. using esbuild's "IIFE" bundle format). // We also assign the passed in SmartWeaveGlobal to SmartWeave, and declare // the ContractError exception. // We then use `new Function()` which we can call and get back the returned handle function // which has access to the per-instance globals. contractSrc = contractSrc .replace(/export\s+async\s+function\s+handle/gmu, 'async function handle') .replace(/export\s+function\s+handle/gmu, 'function handle') .replace(/\(\s*\(\)\s*=>\s*{/g, '') .replace(/\s*\(\s*function\s*\(\)\s*{/g, '') .replace(/}\s*\)\s*\(\)\s*;/g, ''); return ` const [SmartWeave, BigNumber, clarity, logger] = arguments; clarity.SmartWeave = SmartWeave; class ContractError extends Error { constructor(message) { super(message); this.name = 'ContractError' } }; function ContractAssert(cond, message) { if (!cond) throw new ContractError(message) }; ${contractSrc}; return handle; `; } }
JavaScript
class App extends Component { render() { return ( <Router> <div className="App"> <Route exact path="/" component={Home} /> <Route path="/home" component={Home} /> </div> </Router> ); } }
JavaScript
class Spherical { /** * Constructs a new spherical system. * * @param {Number} [radius=1] - The radius of the sphere. * @param {Number} [phi=0] - The polar angle phi. * @param {Number} [theta=0] - The equator angle theta. */ constructor(radius = 1, phi = 0, theta = 0) { /** * The radius of the sphere. * * @type {Number} */ this.radius = radius; /** * The polar angle, up and down towards the top and bottom pole. * * @type {Number} */ this.phi = phi; /** * The angle around the equator of the sphere. * * @type {Number} */ this.theta = theta; } /** * Sets the values of this spherical system. * * @param {Number} radius - The radius. * @param {Number} phi - Phi. * @param {Number} theta - Theta. * @return {Spherical} This spherical system. */ set(radius, phi, theta) { this.radius = radius; this.phi = phi; this.theta = theta; return this; } /** * Copies the values of the given spherical system. * * @param {Spherical} s - A spherical system. * @return {Spherical} This spherical system. */ copy(s) { this.radius = s.radius; this.phi = s.phi; this.theta = s.theta; return this; } /** * Clones this spherical system. * * @return {Spherical} The cloned spherical system. */ clone() { return new this.constructor().copy(this); } /** * Restricts phi to `[1e-6, PI - 1e-6]`. * * @return {Spherical} This spherical system. */ makeSafe() { this.phi = Math.max(1e-6, Math.min(Math.PI - 1e-6, this.phi)); return this; } /** * Sets the values of this spherical system based on a vector. * * The radius is set to the vector's length while phi and theta are set from * its direction. * * @param {Vector3} v - The vector. * @return {Spherical} This spherical system. */ setFromVector3(v) { return this.setFromCartesianCoords(v.x, v.y, v.z); } /** * Sets the values of this spherical system based on cartesian coordinates. * * @param {Number} x - The X coordinate. * @param {Number} y - The Y coordinate. * @param {Number} z - The Z coordinate. * @return {Spherical} This spherical system. */ setFromCartesianCoords(x, y, z) { this.radius = Math.sqrt(x * x + y * y + z * z); if(this.radius === 0) { this.theta = 0; this.phi = 0; } else { // Calculate the equator angle around the positive Y-axis. this.theta = Math.atan2(x, z); // Calculate the polar angle. this.phi = Math.acos(Math.min(Math.max(y / this.radius, -1), 1)); } return this; } }
JavaScript
class Project { // CONSTRUCTOR constructor(start, tasks, schedules, performances) { this._start = start; this._tasks = tasks; this._schedules = schedules; this._performances = performances; } // FACTORY FUNCTIONS /** * Create a Project from an object with tasks, schedules and such specified * with reasonable defaults. * * This function is intended to be forgiving. It will validate your input and * return a {@link ValidationError} on any issues. */ static fromObject(projectObject) { // start date let start = luxon_1.DateTime.local(); // set to a default if (projectObject.start) { // if start is specified start = luxon_1.DateTime.fromISO(projectObject.start); } if (!start.isValid) { throw new Error_1.ValidationError(start.invalidExplanation, "invalid start date specified", "start"); } // tasks let rawTasks = projectObject.tasks || []; // default is no tasks let rawGroups = projectObject.groups || []; // default is no groups // validate tasks try { rawTasks.forEach((task, index) => { if (!task.identifier) throw new Error_1.ValidationError("no identifier for task", "project task", index); if (!task.resource) throw new Error_1.ValidationError("no resource for task", "project task", index); if (!task.prediction) throw new Error_1.ValidationError("no prediction for task duration", "project task", index); }); } catch (error) { if (error instanceof Error_1.ValidationError) { Error_1.rethrowValidationError(error, "project task list", "tasks"); } else { throw error; } } // turn projectObject tasks into actual task objects const originalTasks = rawTasks.map(task => { return new Task_1.Task(task.identifier, task.resource, task.prediction, task.dependencies, task.actual, task.done); }); // validate groups try { rawGroups.forEach((group, index) => { if (!group.identifier) throw new Error_1.ValidationError("no identifier for group", "project group", index); }); } catch (error) { if (error instanceof Error_1.ValidationError) { Error_1.rethrowValidationError(error, "project group list", "groups"); } else { throw error; } } // turn projectObject groups into actual group objects const originalGroups = rawGroups.map(group => { return new Task_1.Group(group.identifier, group.tasks || []); }); // internalize tasks let tasks = []; try { tasks = Task_1.internalizeTasks(originalTasks, originalGroups); } catch (error) { if (error instanceof Error_1.ValidationError) { Error_1.rethrowValidationError(error, "resolving groups", "groups"); } else { throw error; } } // get resources from tasks const resources = new Set(tasks.map(task => task.resource)); // schedules // validate that there are schedules for each resource in the tasks resources.forEach(resource => { if (!new Set(Object.keys(projectObject.schedules)).has(resource)) throw new Error_1.ValidationError("resource missing schedule", "checking that all resources have a schedule", resource); }); let schedules = {}; try { schedules = Object.keys(projectObject.schedules) .reduce((all, resource) => { try { all[resource] = new Schedule_1.Schedule(projectObject.schedules[resource]); } catch (error) { if (error instanceof Error_1.ValidationError) { Error_1.rethrowValidationError(error, "making schedule for a resource", resource); } else { throw error; } } return all; }, {}); } catch (error) { if (error instanceof Error_1.ValidationError) { Error_1.rethrowValidationError(error, "making schedules", "schedules"); } else { throw error; } } // performances const performances = [...resources] .reduce((all, resource) => { // Record<ResourceIdentifier, Array<Accuracy>> | undefined let accuracies = tasks // include accuracies from finished tasks in this project .filter(task => task.done && task.resource == resource) // tasks which are done and for this resource .map(task => task.actual / task.prediction); // calculate the accuracies if (projectObject.accuracies && projectObject.accuracies[resource]) { // if performances was specified for this resource accuracies = accuracies.concat(projectObject.accuracies[resource]); // include the historical accuracies specified } all[resource] = new Performance_1.Performance(accuracies); return all; }, {}); // output return new Project(start, tasks, schedules, performances); } // GETTERS get start() { return this._start.toISODate(); } /** * This returns the tasks with begin and end dates assigned. It schedules them * according to the schedules specified */ get schedule() { if (!this._taskSchedule) { // if the task schedule has not been calculated yet this._taskSchedule = Simulation_1.scheduleTasks(this._tasks, this._start, this._schedules) // calculate it .map(scheduledTask => ({ task: scheduledTask.task, begin: scheduledTask.begin.toISO(), end: scheduledTask.end.toISO() })); // convert it into an exportable format } return this._taskSchedule; } // SETTERS /** * returns a this project, but with a different start date. */ startOn(date) { const parsed = luxon_1.DateTime.fromISO(date); if (!parsed.isValid) throw new Error_1.ValidationError(parsed.invalidExplanation, "Invalid date", date); return new Project(luxon_1.DateTime.fromISO(date), this._tasks, this._schedules, this._performances); } // METHODS /** * Gets the probability that the entire project will end on a specific date. * You can optionally specify how many simulations to do. */ async probabilityOfEndingOnDate(dateString, simulations = 1000) { const date = luxon_1.DateTime.fromISO(dateString); if (!date.isValid) throw new Error_1.ValidationError(date.invalidExplanation, "Invalid date", dateString); if (!this._simulations) { // if simulations have been done this._simulations = await Simulation_1.monteCarloSimulations(this._tasks, this._performances, this._schedules, simulations); // run simulations } return Probability_1.cumulativeProbability(this._simulations, date); } /** * Gets the scheduled times that a specifiedresource is working on the project * over a specified date range. */ resourceScheduleInRange(resource, fromString, toString) { const from = luxon_1.DateTime.fromISO(fromString); const to = luxon_1.DateTime.fromISO(toString); if (!from.isValid) throw new Error_1.ValidationError(from.invalidExplanation, "Invalid date", fromString); if (!to.isValid) throw new Error_1.ValidationError(to.invalidExplanation, "Invalid date", toString); return this._schedules[resource].periodsInRange(from, to); } }
JavaScript
class EmptyDatasource extends MemoryDatasource { constructor(options) { super(options); } // Retrieves all quads in the datasource _getAllQuads(addQuad, done) { done(); } }
JavaScript
class Stream { /** * Constructs a new stream with set pointer. Throws an Error if the stream * failed. * * @param {Number} stream the pointer */ constructor(stream) { this._stream = stream; this.streamCheck(this._stream); } /** * Throws an Error if the stream failed. */ streamCheck() { if (!ne.stream_check(this._stream)) { throw new Error("Stream failed!"); } } }
JavaScript
class FileStream extends Stream { /** * Constructs a stream from the given file. * * @param {String} fullpath the path to the file */ constructor(fullpath) { const ptr = ne.stream_file_new(fullpath); super(ptr); } /** * Frees the file stream. */ destructor() { ne.free_file_stream(self.stream); } }
JavaScript
class BufferStream extends Stream { /** * Constructs the stream from the given buffer. * * @param {String} buffer buffer of memory */ constructor(buffer) { const ptr = ne.stream_buffer_new(buffer); super(ptr); } /** * Frees the buffer stream. */ destructor() { ne.free_buffer_stream(self.stream); } }
JavaScript
class Extractor { /** * Constructs an extactor with given miners, batch size and thread count. * * @param {Array} miners the miners, see addMiner for format * @param {Number} batch the batch size for each mining * @param {Number} threads how many threads to use (0 will use all threads * on current machine) */ constructor(miners, batch, threads, flags) { const defaults = { miners: [], batch: 1000, threads: 1, flags: 0, }; this.miners = defaults.miners; this.batch = batch || defaults.batch; this._extractor = ne.create_extractor(threads || defaults.threads); this.flags = 0; miners = miners || defaults.miners; for (let miner of miners) { if (!this.addMiner(...miner)) { console.warn( `Couldn't add ${miner[0]}::${miner[1]}: ` + `${this.getLastError()}.` ); } } this.setFlags(flags || defaults.flags); } /** * Frees the extractor. */ destructor() { ne.free_extractor(this._extractor); } /** * Checks the stream and throws an Error if it's not set. */ _checkStream() { if (this.stream === undefined) { throw new Error("No stream set"); } } /** * Adds a miner to the extractor. * * @param {String} so_dir path to file with miners * @param {String} symb name of miner * @param {String} params arguments for the miner, if any * * @return true on success */ addMiner(so_dir, symb, params) { params = (params === undefined) ? "" : params; if (ne.add_miner_so( this._extractor, so_dir, symb, params) ) { this.miners = [...this.miners, [so_dir, symb, params]]; return true; }; return false; } /** Opens new FileStream and sets it to the Extractor. * * @param {String} path Path to a file */ open(path) { const stream = new FileStream(path); this.setStream(stream); } /** Closes previously opened stream via .open() implicitly. */ close() { this.unsetStream(); } /** * Sets the stream to mine from. * * @param {Stream} stream the stream * * @return this extractor */ setStream(stream) { this.stream = stream; if (!ne.set_stream(this._extractor, stream._stream)) { throw new Error("Cannot set stream!"); } return this; } /** * Unsets any set stream. * * @return this extractor */ unsetStream() { ne.unset_stream(this._extractor); this.stream = undefined; return this; } /** * Sets flags for extractor. * * @param {Number} flags bit flag * * @return {Number} new flag setting */ setFlags(flags) { return this.flags = ne.set_flags(this._extractor, flags); } /** * Unsets flags for extractor. * * @param {Number} flags bit flag * * @return {Number} new flag setting */ unsetFlags(flags) { return this.flags = ne.unset_flags(this._extractor, flags); } /** * Check for EOF in the current stream. * * @return true if stream at EOF */ eof() { this._checkStream(); return ne.eof(this._extractor); } /** * Asynchronously processes the next batch in the stream. * * @param {function (error, result)} callback what to call when done * @param {Number} batch batch size, optional */ next(callback, batch) { if (batch === undefined) { batch = this.batch; } if (callback === undefined) { callback = function () { }; } this._checkStream(); return ne.next(this._extractor, batch, callback); } /** * Returns the last error message. * * @return the last error message */ getLastError() { return ne.get_last_error(this._extractor); } /** * Returns metainfo. Maps labels to {path, miner, label} dicts. * * @return {Object<String, Object>} the metainfo */ getMeta() { const ret = {}; const dlsyms = ne.dlsymbols(this._extractor); for (const i in dlsyms) { const entry = dlsyms[i]; ret[entry.label] = entry; } return ret; } /** * @param {{ (accumulator, occurrences: Object[], callback?: (err, res) => void) => void }} fn * A function executed for each list of mined occurrences. If you want it to be * asynchronous, it needs to take three argument, where the last one is a callback. * @param {*} initialValue * @param {{ (err, res) => void }} callback */ reduce(fn, initialValue, callback) { let isFirst = true; let acc; let handleNext; if (fn.length > 2) { // Asynchronous version handleNext = (err, res) => { if (err) { callback(err); return; } if (isFirst) { acc = (initialValue !== undefined) ? initialValue : res; isFirst = false; } fn(acc, res, (err, retval) => { if (err) { callback(err); return; } acc = retval; if (this.eof()) { callback(null, acc); return; } this.next(handleNext); }); }; } else { // Synchronous version handleNext = (err, res) => { if (err) { callback(err); return; } if (isFirst) { acc = (initialValue !== undefined) ? initialValue : res; isFirst = false; } try { acc = fn(acc, res); } catch (e) { callback(e); return; } if (this.eof()) { callback(null, acc); return; } this.next(handleNext); }; } this.next(handleNext); } }
JavaScript
class AvatarColorScheme extends DataType { static isValid(value) { return !!AvatarColorSchemes[value]; } }
JavaScript
class Login extends React.Component { constructor() { super(); this.state = { display: false, activeLoginSection: 'activateCoin', loginPassphrase: '', seedInputVisibility: false, loginPassPhraseSeedType: null, bitsOption: 256, randomSeed: PassPhraseGenerator.generatePassPhrase(256), randomSeedConfirm: '', isSeedConfirmError: false, isSeedBlank: false, displaySeedBackupModal: false, customWalletSeed: false, isCustomSeedWeak: false, nativeOnly: Config.iguanaLessMode, trimPassphraseTimer: null, displayLoginSettingsDropdown: false, displayLoginSettingsDropdownSection: null, shouldEncryptSeed: false, encryptKey: '', pubKey: '', decryptKey: '', selectedPin: '', isExperimentalOn: false, enableEncryptSeed: false, }; this.toggleActivateCoinForm = this.toggleActivateCoinForm.bind(this); this.updateRegisterConfirmPassPhraseInput = this.updateRegisterConfirmPassPhraseInput.bind(this); this.updateLoginPassPhraseInput = this.updateLoginPassPhraseInput.bind(this); this.loginSeed = this.loginSeed.bind(this); this.toggleSeedInputVisibility = this.toggleSeedInputVisibility.bind(this); this.handleRegisterWallet = this.handleRegisterWallet.bind(this); this.toggleSeedBackupModal = this.toggleSeedBackupModal.bind(this); this.copyPassPhraseToClipboard = this.copyPassPhraseToClipboard.bind(this); this.execWalletCreate = this.execWalletCreate.bind(this); this.resizeLoginTextarea = this.resizeLoginTextarea.bind(this); this.toggleLoginSettingsDropdown = this.toggleLoginSettingsDropdown.bind(this); this.updateEncryptKey = this.updateEncryptKey.bind(this); this.updatePubKey = this.updatePubKey.bind(this); this.updateDecryptKey = this.updateDecryptKey.bind(this); this.loadPinList = this.loadPinList.bind(this); } // the setInterval handler for 'activeCoins' _iguanaActiveCoins = null; toggleLoginSettingsDropdownSection(sectionName) { Store.dispatch(toggleLoginSettingsModal(true)); this.setState({ displayLoginSettingsDropdown: false, displayLoginSettingsDropdownSection: sectionName, }); } isCustomWalletSeed() { return this.state.customWalletSeed; } toggleCustomWalletSeed() { this.setState({ customWalletSeed: !this.state.customWalletSeed, }, () => { // if customWalletSeed is set to false, regenerate the seed if (!this.state.customWalletSeed) { this.setState({ randomSeed: PassPhraseGenerator.generatePassPhrase(this.state.bitsOption), isSeedConfirmError: false, isSeedBlank: false, isCustomSeedWeak: false, }); } else { // if customWalletSeed is set to true, reset to seed to an empty string this.setState({ randomSeed: '', randomSeedConfirm: '', }); } }); } shouldEncryptSeed() { return this.state.shouldEncryptSeed; } toggleShouldEncryptSeed() { this.setState({ shouldEncryptSeed: !this.state.shouldEncryptSeed }); } updateEncryptKey(e) { this.setState({ encryptKey: e.target.value, }); } updatePubKey(e) { this.setState({ pubKey: e.target.value, }); } updateDecryptKey(e) { this.setState({ decryptKey: e.target.value, }); } componentDidMount() { this.setState({ isExperimentalOn: mainWindow.experimentalFeatures, }); } toggleSeedInputVisibility() { this.setState({ seedInputVisibility: !this.state.seedInputVisibility, }); this.resizeLoginTextarea(); } generateNewSeed(bits) { this.setState(Object.assign({}, this.state, { randomSeed: PassPhraseGenerator.generatePassPhrase(bits), bitsOption: bits, isSeedBlank: false, })); } toggleLoginSettingsDropdown() { this.setState(Object.assign({}, this.state, { displayLoginSettingsDropdown: !this.state.displayLoginSettingsDropdown, })); } componentWillReceiveProps(props) { if (props.Login.pinList === 'no pins') { props.Login.pinList = []; } if (props && props.Main && props.Main.isLoggedIn) { if (props.Main.total === 0) { this.setState({ activeLoginSection: 'activateCoin', loginPassphrase: '', display: true, }); } else { this.setState({ loginPassphrase: '', display: false, }); } } if (props && props.Main && !props.Main.isLoggedIn) { document.body.className = 'page-login layout-full page-dark'; if (props.Interval && props.Interval.interval && props.Interval.interval.sync) { Store.dispatch(dashboardChangeActiveCoin()); Store.dispatch( stopInterval( 'sync', props.Interval.interval ) ); } this.setState({ display: true, activeLoginSection: this.state.activeLoginSection !== 'signup' ? 'login' : 'signup', }); } if (props.Main && props.Main.total === 0) { document.body.className = 'page-login layout-full page-dark'; if (props.Interval && props.Interval.interval && props.Interval.interval.sync) { Store.dispatch(dashboardChangeActiveCoin()); Store.dispatch( stopInterval( 'sync', props.Interval.interval ) ); } } if (this.state.activeLoginSection !== 'signup' && props && props.Main && props.Main.isLoggedIn) { this.setState({ loginPassphrase: '', activeLoginSection: 'activateCoin', }); } } toggleActivateCoinForm() { Store.dispatch(toggleAddcoinModal(true, false)); } resizeLoginTextarea() { // auto-size textarea setTimeout(() => { if (this.state.seedInputVisibility) { document.querySelector('#loginPassphrase').style.height = '1px'; document.querySelector('#loginPassphrase').style.height = `${(15 + document.querySelector('#loginPassphrase').scrollHeight)}px`; } }, 100); } updateLoginPassPhraseInput(e) { // remove any empty chars from the start/end of the string const newValue = e.target.value; clearTimeout(this.state.trimPassphraseTimer); const _trimPassphraseTimer = setTimeout(() => { this.setState({ loginPassphrase: newValue ? newValue.trim() : '', // hardcoded field name loginPassPhraseSeedType: this.getLoginPassPhraseSeedType(newValue), }); }, 2000); this.resizeLoginTextarea(); this.setState({ trimPassphraseTimer: _trimPassphraseTimer, [e.target.name === 'loginPassphraseTextarea' ? 'loginPassphrase' : e.target.name]: newValue, loginPassPhraseSeedType: this.getLoginPassPhraseSeedType(newValue), }); } updateRegisterConfirmPassPhraseInput(e) { this.setState({ [e.target.name]: e.target.value, isSeedConfirmError: false, isSeedBlank: this.isBlank(e.target.value), }); } updateWalletSeed(e) { this.setState({ randomSeed: e.target.value, isSeedConfirmError: false, isSeedBlank: this.isBlank(e.target.value), }); } loginSeed() { // reset the login pass phrase values so that when the user logs out, the values are clear this.setState({ loginPassphrase: '', loginPassPhraseSeedType: null, }); // reset login input vals this.refs.loginPassphrase.value = ''; this.refs.loginPassphraseTextarea.value = ''; if (this.state.shouldEncryptSeed) { Store.dispatch(encryptPassphrase(this.state.loginPassphrase, this.state.encryptKey, this.state.pubKey)); } if (this.state.selectedPin) { Store.dispatch(loginWithPin(this.state.decryptKey, this.state.selectedPin)); } else { Store.dispatch( shepherdElectrumAuth(this.state.loginPassphrase) ); Store.dispatch( shepherdElectrumCoins() ); } } loadPinList() { Store.dispatch(loadPinList()); } updateSelectedPin(e) { this.setState({ selectedPin: e.target.value, }); } getLoginPassPhraseSeedType(passPhrase) { if (!passPhrase) { return null; } const passPhraseWords = passPhrase.split(' '); if (!PassPhraseGenerator.arePassPhraseWordsValid(passPhraseWords)) { return null; } if (PassPhraseGenerator.isPassPhraseValid(passPhraseWords, 256)) { return translate('LOGIN.IGUANA_SEED'); } if (PassPhraseGenerator.isPassPhraseValid(passPhraseWords, 160)) { return translate('LOGIN.WAVES_SEED'); } if (PassPhraseGenerator.isPassPhraseValid(passPhraseWords, 128)) { return translate('LOGIN.NXT_SEED'); } return null; } updateActiveLoginSection(name) { // reset login/create form this.setState({ activeLoginSection: name, loginPassphrase: null, loginPassPhraseSeedType: null, seedInputVisibility: false, bitsOption: 256, randomSeed: PassPhraseGenerator.generatePassPhrase(256), randomSeedConfirm: '', isSeedConfirmError: false, isSeedBlank: false, displaySeedBackupModal: false, customWalletSeed: false, isCustomSeedWeak: false, }); } execWalletCreate() { Store.dispatch( shepherdElectrumAuth(this.state.randomSeedConfirm) ); Store.dispatch( shepherdElectrumCoins() ); this.setState({ activeLoginSection: 'activateCoin', displaySeedBackupModal: false, isSeedConfirmError: false, }); } // TODO: disable register btn if seed or seed conf is incorrect handleRegisterWallet() { const enteredSeedsMatch = this.state.randomSeed === this.state.randomSeedConfirm; const isSeedBlank = this.isBlank(this.state.randomSeed); // if custom seed check for string strength // at least 1 letter in upper case // at least 1 digit // at least one special char // min length 10 chars const _customSeed = this.state.customWalletSeed ? this.state.randomSeed.match('^(?=.*[A-Z])(?=.*[^<>{}\"/|;:.,~!?@#$%^=&*\\]\\\\()\\[_+]*$)(?=.*[0-9])(?=.*[a-z]).{10,99}$') : false; this.setState({ isCustomSeedWeak: _customSeed === null ? true : false, isSeedConfirmError: !enteredSeedsMatch ? true : false, isSeedBlank: isSeedBlank ? true : false, }); if (enteredSeedsMatch && !isSeedBlank && _customSeed !== null) { this.toggleSeedBackupModal(); } } isBlank(str) { return (!str || /^\s*$/.test(str)); } handleKeydown(e) { this.updateLoginPassPhraseInput(e); if (e.key === 'Enter') { this.loginSeed(); } } toggleSeedBackupModal() { this.setState(Object.assign({}, this.state, { displaySeedBackupModal: !this.state.displaySeedBackupModal, })); } copyPassPhraseToClipboard() { const passPhrase = this.state.randomSeed; const textField = document.createElement('textarea'); textField.innerText = passPhrase; document.body.appendChild(textField); textField.select(); document.execCommand('copy'); textField.remove(); Store.dispatch( triggerToaster( translate('LOGIN.SEED_SUCCESSFULLY_COPIED'), translate('LOGIN.SEED_COPIED'), 'success' ) ); } renderSwallModal() { if (this.state.displaySeedBackupModal) { return SwallModalRender.call(this); } return null; } render() { if ((this.state && this.state.display) || !this.props.Main) { return LoginRender.call(this); } return null; } }
JavaScript
class context_menu_image_info_widget extends illust_widget { set_illust_and_page(illust_id, page) { if(this._illust_id == illust_id && this._page == page) return; this._illust_id = illust_id; this._page = page; this.refresh(); } refresh_internal(illust_data) { this.container.hidden = (illust_data == null || this._page == null); if(this.container.hidden) return; var set_info = (query, text) => { var node = this.container.querySelector(query); node.innerText = text; node.hidden = text == ""; }; // Add the page count for manga. var page_text = ""; if(illust_data.pageCount > 1) { if(this._page == -1) page_text = illust_data.pageCount + " pages"; else page_text = "Page " + (this._page+1) + "/" + illust_data.pageCount; } set_info(".page-count", page_text); // Show info for the current page. If _page is -1 then we're on the search view and don't have // a specific page, so show info for the first page. let page = this._page; if(page == -1) page = 0; var info = ""; var page_info = illust_data.mangaPages[page]; info += page_info.width + "x" + page_info.height; set_info(".image-info", info); } }
JavaScript
class Logger { /** * Generic information logger. * * @static * @param {String} msg Message to log. */ static info(msg) { console.log(`\x1b[37;42minfo\x1b[32;49m ${msg}\x1b[0m`); } /** * Internal command logger. * * @static * @param {String} msg Message to log. */ static cmd(msg) { console.log(`\x1b[37;45mcmd\x1b[35;49m ${msg}\x1b[0m`); } /** * Warning logger. * Intended for not-100%-breaking errors, but you should still know about it. * * @static * @param {String} msg Message to log. */ static warn(msg) { console.log(`\x1b[37;43mwarn\x1b[33;49m ${msg}\x1b[0m`); } /** * Error logger. * * @static * @param {String} msg Message to log. */ static error(msg) { console.error(`\x1b[37;41merror\x1b[31;49m ${msg}\x1b[0m`); } /** * Generic information logger with custom tag, and blue colour. * * @static * @param {String} tag Tag for the logged message. * @param {String} msg Message to log. */ static custom(tag, msg) { console.log(`\x1b[37;44m${tag}\x1b[34;49m ${msg}\x1b[0m`); } /** * Error logger with custom tag. * * @static * @param {String} tag Tag for the logged message. * @param {String} msg Message to log. */ static customError(tag, msg) { console.log(`\x1b[37;41m${tag}\x1b[31;49m ${msg}\x1b[0m`); } }
JavaScript
class JobScheduler { /** * Class constructor. */ constructor() {} /** * Execute the given function every January 1 at 12:00AM. * * @param {Function} fn */ scheduleEveryYear(fn) { schedule.scheduleJob('0 0 1 1 *', fn); } /** * Execute the given function at 12:00AM on the first of every month. * * @param {Function} fn */ scheduleEveryMonth(fn) { schedule.scheduleJob('0 0 1 * *', fn); } /** * Execute the given function every Sunday at 12:30. * * @param {Function} fn */ scheduleEveryWeek(fn) { schedule.scheduleJob({ hour: 12, minute: 30, dayOfWeek: 0 }, fn); } /** * Execute the given function every day at the given hour and minute. * * @param {Number} hour * @param {Number} minute * @param {Function} fn */ scheduleEveryDayAt(hour, minute, fn) { const rule = new schedule.RecurrenceRule(); rule.hour = hour; rule.minute = minute; schedule.scheduleJob(rule, fn); } /** * Execute the given function every hour. * * @param {Function} fn */ scheduleEveryHour(fn) { schedule.scheduleJob('* * 1 * *', fn); } /** * Execute the given function every hour at the given minute. * * @param {Number} minute * @param {Function} fn */ scheduleEveryHourAt(minute, fn) { const rule = new schedule.RecurrenceRule(); rule.minute = minute; schedule.scheduleJob(rule, fn); } /** * Execute the given function at every specified time. * * @param {String} time * @param {Function} fn */ scheduleEvery(time, fn) { let now = new Date; let d = date(time); const offset = d - now; let until = offset; if (until <= 0) { throw new Error(`Did not recognize "${time}"`); } setTimeout(schedule, until); function schedule() { d = date(time); if (!fn.length) { fn(); reset(); } else { fn(reset); } } function reset() { if (!offset) return; now = new Date; until = d - now; if (until < 0) { schedule(); } else { setTimeout(schedule, until); } } } /** * Execute the given function at a certain time. * * @param {String} time * @param {Function} fn */ scheduleAt(time, fn) { const now = new Date; const d = date(time); const offset = d - now; if (! offset) { throw new Error(`Did not recognize "${time}"`); } return setTimeout(fn, offset) } }
JavaScript
class MongodbClient extends AbstractClient { constructor(credential, region, profile) { super("mongodb.tencentcloudapi.com", "2018-04-08", credential, region, profile); } /** * 本接口(AssignProject)用于指定云数据库实例的所属项目。 * @param {AssignProjectRequest} req * @param {function(string, AssignProjectResponse):void} cb * @public */ AssignProject(req, cb) { let resp = new AssignProjectResponse(); this.request("AssignProject", req, resp, cb); } /** * 本接口(TerminateDBInstance)用于销毁按量计费的MongoDB云数据库实例 * @param {TerminateDBInstanceRequest} req * @param {function(string, TerminateDBInstanceResponse):void} cb * @public */ TerminateDBInstance(req, cb) { let resp = new TerminateDBInstanceResponse(); this.request("TerminateDBInstance", req, resp, cb); } /** * 本接口(CreateDBInstance)用于创建包年包月的MongoDB云数据库实例。 * @param {CreateDBInstanceRequest} req * @param {function(string, CreateDBInstanceResponse):void} cb * @public */ CreateDBInstance(req, cb) { let resp = new CreateDBInstanceResponse(); this.request("CreateDBInstance", req, resp, cb); } /** * 本接口(CreateDBInstanceHour)用于创建按量计费的MongoDB云数据库实例(包括主实例、灾备实例和只读实例),可通过传入实例规格、实例类型、MongoDB版本、购买时长和数量等信息创建云数据库实例。 * @param {CreateDBInstanceHourRequest} req * @param {function(string, CreateDBInstanceHourResponse):void} cb * @public */ CreateDBInstanceHour(req, cb) { let resp = new CreateDBInstanceHourResponse(); this.request("CreateDBInstanceHour", req, resp, cb); } /** * 本接口(DescribeSlowLogs)用于获取云数据库实例的慢查询日志。 * @param {DescribeSlowLogRequest} req * @param {function(string, DescribeSlowLogResponse):void} cb * @public */ DescribeSlowLog(req, cb) { let resp = new DescribeSlowLogResponse(); this.request("DescribeSlowLog", req, resp, cb); } /** * 本接口(RenameInstance)用于修改云数据库实例的名称。 * @param {RenameInstanceRequest} req * @param {function(string, RenameInstanceResponse):void} cb * @public */ RenameInstance(req, cb) { let resp = new RenameInstanceResponse(); this.request("RenameInstance", req, resp, cb); } /** * 本接口(UpgradeDBInstance)用于升级包年包月的MongoDB云数据库实例,可以扩容内存、存储以及Oplog * @param {UpgradeDBInstanceRequest} req * @param {function(string, UpgradeDBInstanceResponse):void} cb * @public */ UpgradeDBInstance(req, cb) { let resp = new UpgradeDBInstanceResponse(); this.request("UpgradeDBInstance", req, resp, cb); } /** * 本接口(SetAutoRenew)用于设置包年包月云数据库实例的续费选项。 * @param {SetAutoRenewRequest} req * @param {function(string, SetAutoRenewResponse):void} cb * @public */ SetAutoRenew(req, cb) { let resp = new SetAutoRenewResponse(); this.request("SetAutoRenew", req, resp, cb); } /** * 本接口(DescribeSpecInfo)用于查询实例的售卖规格。 * @param {DescribeSpecInfoRequest} req * @param {function(string, DescribeSpecInfoResponse):void} cb * @public */ DescribeSpecInfo(req, cb) { let resp = new DescribeSpecInfoResponse(); this.request("DescribeSpecInfo", req, resp, cb); } /** * 本接口(SetPassword)用于设置云数据库账户的密码。 * @param {SetPasswordRequest} req * @param {function(string, SetPasswordResponse):void} cb * @public */ SetPassword(req, cb) { let resp = new SetPasswordResponse(); this.request("SetPassword", req, resp, cb); } /** * 本接口(UpgradeDBInstanceHour)用于升级按量计费的MongoDB云数据库实例,可以扩容内存、存储以及oplog * @param {UpgradeDBInstanceHourRequest} req * @param {function(string, UpgradeDBInstanceHourResponse):void} cb * @public */ UpgradeDBInstanceHour(req, cb) { let resp = new UpgradeDBInstanceHourResponse(); this.request("UpgradeDBInstanceHour", req, resp, cb); } /** * 本接口(DescribeDBInstances)用于查询云数据库实例列表,支持通过项目ID、实例ID、实例状态等过滤条件来筛选实例。支持查询主实例、灾备实例和只读实例信息列表。 * @param {DescribeDBInstancesRequest} req * @param {function(string, DescribeDBInstancesResponse):void} cb * @public */ DescribeDBInstances(req, cb) { let resp = new DescribeDBInstancesResponse(); this.request("DescribeDBInstances", req, resp, cb); } }
JavaScript
class Deque { #count = 0; #lowestCount = 0; #items = {}; constructor(){ this.#count = 0; this.#lowestCount = 0; this.#items = {}; } /** * @param {any} element */ addFront(element){ if(this.isEmpty()){ this.addBack(element); } else if (this.#lowestCount > 0){ this.#lowestCount--; this.#items[this.#lowestCount] = element; } else { for (let i = this.#count; i > 0; i--){ this.#items[i] = this.#items[i - 1]; } this.#count++; this.#lowestCount = 0; this.#items[0] = element; } } addBack(element){ this.#items[this.#count] = element; this.#count++; } removeFront(){ if (this.isEmpty()) { return undefined; } const result = this.#items[this.#lowestCount]; delete this.#items[this.#lowestCount]; this.#lowestCount++; return result; } removeBack(){ if(this.isEmpty()){ return undefined; } this.#count--; const result = this.#items[this.#count]; delete this.#items[this.#count]; return result; } peekFront(){ if(this.isEmpty()){ return undefined; } this.#count--; const result = this.#items[this.#count]; delete this.#items[this.#count]; return result; } peekBack(){ if (this.isEmpty()) { return undefined; } return this.#items[this.#lowestCount]; } /** * Responder se fila é vázia */ isEmpty(){ return this.size() === 0; } /** * Mostrar tamanho da fila */ size(){ return this.#count - this.#lowestCount; } clear(){ this.#items = {} this.#count = 0; this.#lowestCount = 0; } toString(){ if (this.isEmpty()) { return ''; } let objString = `${this.#items[this.#lowestCount]}` for(let i = this.#lowestCount + 1; i < this.#count; i++){ objString = `${objString},${this.#items[i]}`; } return objString; } }
JavaScript
class AgentRegistrationRegenerateKeyParameter { /** * Create a AgentRegistrationRegenerateKeyParameter. * @member {string} keyName Gets or sets the agent registration key name - * Primary or Secondary. Possible values include: 'Primary', 'Secondary' * @member {string} [name] Gets or sets the name of the resource. * @member {string} [location] Gets or sets the location of the resource. * @member {object} [tags] Gets or sets the tags attached to the resource. */ constructor() { } /** * Defines the metadata of AgentRegistrationRegenerateKeyParameter * * @returns {object} metadata of AgentRegistrationRegenerateKeyParameter * */ mapper() { return { required: false, serializedName: 'AgentRegistrationRegenerateKeyParameter', type: { name: 'Composite', className: 'AgentRegistrationRegenerateKeyParameter', modelProperties: { keyName: { required: true, serializedName: 'keyName', type: { name: 'String' } }, name: { required: false, serializedName: 'name', type: { name: 'String' } }, location: { required: false, serializedName: 'location', type: { name: 'String' } }, tags: { required: false, serializedName: 'tags', type: { name: 'Dictionary', value: { required: false, serializedName: 'StringElementType', type: { name: 'String' } } } } } } }; } }
JavaScript
class PositionedAtSelection extends Component { constructor() { super( ...arguments ); this.state = { style: getCurrentCaretPositionStyle(), }; } render() { const { children } = this.props; const { style } = this.state; return ( <div className="editor-format-toolbar__selection-position" style={ style }> { children } </div> ); } }
JavaScript
class Tx { /** @hidden */ constructor(client) { this.client = client; } /** * Build, sign and broadcast the msgs * @param msgs Msgs to be sent * @param baseTx * @returns * @since v0.17 */ buildAndSend(msgs, baseTx) { return __awaiter(this, void 0, void 0, function* () { // Build Unsigned Tx const unsignedTx = this.client.auth.newStdTx(msgs, baseTx); const fee = yield this.client.utils.toMinCoins(unsignedTx.value.fee.amount); unsignedTx.value.fee.amount = fee; // Sign Tx const signedTx = yield this.sign(unsignedTx, baseTx.from, baseTx.password); // Broadcast Tx return this.broadcast(signedTx, baseTx.mode); }); } /** * Broadcast a tx * @param signedTx The tx object with signatures * @param mode Broadcast mode * @returns * @since v0.17 */ broadcast(signedTx, mode) { signedTx = this.marshal(signedTx); const txBytes = amino_js_1.marshalTx(signedTx); switch (mode) { case types.BroadcastMode.Commit: return this.broadcastTxCommit(txBytes); case types.BroadcastMode.Sync: return this.broadcastTxSync(txBytes).then(response => { return this.newTxResult(response.hash); }); default: return this.broadcastTxAsync(txBytes).then(response => { return this.newTxResult(response.hash); }); } } /** * Single sign a transaction * * @param stdTx StdTx with no signatures * @param name Name of the key to sign the tx * @param password Password of the key * @param offline Offline signing, default `false` * @returns The signed tx * @since v0.17 */ sign(stdTx, name, password, offline = false) { return __awaiter(this, void 0, void 0, function* () { if (is.empty(name)) { throw new errors_1.SdkError(`Name of the key can not be empty`); } if (is.empty(password)) { throw new errors_1.SdkError(`Password of the key can not be empty`); } if (!this.client.config.keyDAO.decrypt) { throw new errors_1.SdkError(`Decrypt method of KeyDAO not implemented`); } if (is.undefined(stdTx) || is.undefined(stdTx.value) || is.undefined(stdTx.value.msg)) { throw new errors_1.SdkError(`Msgs can not be empty`); } const keyObj = this.client.config.keyDAO.read(name); if (!keyObj) { throw new errors_1.SdkError(`Key with name '${name}' not found`); } const msgs = []; stdTx.value.msg.forEach(msg => { if (msg.getSignBytes) { msgs.push(msg.getSignBytes()); } }); if (!offline) { // Query account info from block chain const addr = keyObj.address; const account = yield this.client.bank.queryAccount(addr); const sigs = [ { pub_key: account.public_key, account_number: account.account_number, sequence: account.sequence, signature: '', }, ]; stdTx.value.signatures = sigs; } // Build msg to sign const sig = stdTx.value.signatures[0]; const signMsg = { account_number: sig.account_number, chain_id: this.client.config.chainId, fee: stdTx.value.fee, memo: stdTx.value.memo, msgs, sequence: sig.sequence, }; // Signing const privKey = this.client.config.keyDAO.decrypt(keyObj.privKey, password); const signature = utils_1.Crypto.generateSignature(utils_1.Utils.str2hexstring(JSON.stringify(utils_1.Utils.sortObject(signMsg))), privKey); sig.signature = signature.toString('base64'); sig.pub_key = utils_1.Crypto.getPublicKeySecp256k1FromPrivateKey(privKey); stdTx.value.signatures[0] = sig; return stdTx; }); } /** * Broadcast tx async * @param txBytes The tx bytes with signatures * @returns */ broadcastTxAsync(txBytes) { return this.broadcastTx(txBytes, types.RpcMethods.BroadcastTxAsync); } /** * Broadcast tx sync * @param txBytes The tx bytes with signatures * @returns The result object of broadcasting */ broadcastTxSync(txBytes) { return this.broadcastTx(txBytes, types.RpcMethods.BroadcastTxSync); } /** * Broadcast tx and wait for it to be included in a block. * @param txBytes The tx bytes with signatures * @returns The result object of broadcasting */ broadcastTxCommit(txBytes) { return this.client.rpcClient .request(types.RpcMethods.BroadcastTxCommit, { tx: belt_1.bytesToBase64(txBytes), }) .then(response => { var _a, _b, _c, _d; // Check tx error if (response.check_tx && response.check_tx.code > 0) { throw new errors_1.SdkError(response.check_tx.log, response.check_tx.code); } // Deliver tx error if (response.deliver_tx && response.deliver_tx.code > 0) { throw new errors_1.SdkError(response.deliver_tx.log, response.deliver_tx.code); } if (response.deliver_tx && response.deliver_tx.tags) { response.deliver_tx.tags = utils_1.Utils.decodeTags(response.deliver_tx.tags); } return { hash: response.hash, height: response.height, gas_wanted: (_a = response.deliver_tx) === null || _a === void 0 ? void 0 : _a.gas_wanted, gas_used: (_b = response.deliver_tx) === null || _b === void 0 ? void 0 : _b.gas_used, info: (_c = response.deliver_tx) === null || _c === void 0 ? void 0 : _c.info, tags: (_d = response.deliver_tx) === null || _d === void 0 ? void 0 : _d.tags, }; }); } /** * Broadcast tx sync or async * @private * @param signedTx The tx object with signatures * @returns The result object of broadcasting */ broadcastTx(txBytes, method) { // Only accepts 'broadcast_tx_sync' and 'broadcast_tx_async' if (is.not.inArray(method, [ types.RpcMethods.BroadcastTxSync, types.RpcMethods.BroadcastTxAsync, ])) { throw new errors_1.SdkError(`Unsupported broadcast method: ${method}`); } return this.client.rpcClient .request(method, { tx: belt_1.bytesToBase64(txBytes), }) .then(response => { if (response.code && response.code > 0) { throw new errors_1.SdkError(response.data, response.code); } return response; }); } marshal(stdTx) { const copyStdTx = stdTx; Object.assign(copyStdTx, stdTx); stdTx.value.msg.forEach((msg, idx) => { if (msg.marshal) { copyStdTx.value.msg[idx] = msg.marshal(); } }); return copyStdTx; } newTxResult(hash, height, deliverTx) { return { hash, height, gas_wanted: deliverTx === null || deliverTx === void 0 ? void 0 : deliverTx.gas_wanted, gas_used: deliverTx === null || deliverTx === void 0 ? void 0 : deliverTx.gas_used, info: deliverTx === null || deliverTx === void 0 ? void 0 : deliverTx.info, tags: deliverTx === null || deliverTx === void 0 ? void 0 : deliverTx.tags, }; } }
JavaScript
class BaseProvider { /** * Provider constructor. * * @param {Object} registry the registry for this provider */ constructor(registry = {}) { this._jskos = registry this.axios = axios.create({ // TODO: Decide on timeout value timeout: 20000, }) // Path is used for https check and local mappings this._path = typeof window !== "undefined" && window.location.pathname /** * A dictionary with functionality of the registry (e.g. `registry.has.schemes`). * @type {Object} * @readonly */ this.has = {} // Set default language priority list this._defaultLanguages = "en,de,fr,es,nl,it,fi,pl,ru,cs,jp".split(",") /** * A list of RFC 3066 language tags in lowercase in order of priority. * @type {string[]} */ this.languages = [] // Set auth details to null this._auth = { key: null, bearerToken: null, } // Set repeating requests array this._repeating = [] // Set API URLs from registry object this._api = { status: registry.status, schemes: registry.schemes, top: registry.top, data: registry.data, concepts: registry.concepts, narrower: registry.narrower, ancestors: registry.ancestors, types: registry.types, suggest: registry.suggest, search: registry.search, "voc-suggest": registry["voc-suggest"], "voc-search": registry["voc-search"], mappings: registry.mappings, concordances: registry.concordances, annotations: registry.annotations, occurrences: registry.occurrences, reconcile: registry.reconcile, api: registry.api, } this._config = {} // Set default retry config this.setRetryConfig() // Add a request interceptor this.axios.interceptors.request.use((config) => { // Add language parameter to request const language = _.uniq([].concat(_.get(config, "params.language", "").split(","), this.languages, this._defaultLanguages).filter(lang => lang != "")).join(",") _.set(config, "params.language", language) // Set auth if (this.has.auth && this._auth.bearerToken && !_.get(config, "headers.Authorization")) { _.set(config, "headers.Authorization", `Bearer ${this._auth.bearerToken}`) } // Don't perform http requests if site is used via https if (config.url.startsWith("http:") && typeof window !== "undefined" && window.location.protocol == "https:") { // TODO: Return proper error object. throw new axios.Cancel("Can't call http API from https.") } return config }) // Add a response interceptor this.axios.interceptors.response.use(({ data, headers = {}, config = {} }) => { // Apply unicode normalization data = jskos.normalize(data) // Add URL to array as prop let url = config.url if (!url.endsWith("?")) { url += "?" } _.forOwn(config.params || {}, (value, key) => { url += `${key}=${encodeURIComponent(value)}&` }) if (_.isArray(data) || _.isObject(data)) { // Add total count to array as prop let totalCount = parseInt(headers["x-total-count"]) if (!isNaN(totalCount)) { data._totalCount = totalCount } data._url = url } // TODO: Return data or whole response here? return data }, error => { const count = _.get(error, "config._retryCount", 0) const method = _.get(error, "config.method") const statusCode = _.get(error, "response.status") if ( this._retryConfig.methods.includes(method) && this._retryConfig.statusCodes.includes(statusCode) && count < this._retryConfig.count ) { error.config._retryCount = count + 1 // from: https://github.com/axios/axios/issues/934#issuecomment-531463172 if (error.config.data) error.config.data = JSON.parse(error.config.data) return new Promise((resolve, reject) => { setTimeout(() => { this.axios(error.config).then(resolve).catch(reject) }, (() => { const delay = this._retryConfig.delay if (typeof delay === "function") { return delay(count) } return delay })()) }) } else { return Promise.reject(error) } }) const currentRequests = [] for (let { method, type } of utils.requestMethods) { // Make sure all methods exist, but thrown an error if they are not implemented const existingMethod = this[method] && this[method].bind(this) if (!existingMethod) { this[method] = () => { throw new errors.MethodNotImplementedError({ method }) } continue } this[method] = (options = {}) => { // Allow calling the "raw" method without adjustments if (options._raw) { delete options._raw return existingMethod(options) } // Return from existing requests if one exists const existingRequest = currentRequests.find(r => r.method == method && _.isEqual(r.options, options)) if (existingRequest) { return existingRequest.promise } // Add an axios cancel token to each request let source if (!options.cancelToken) { source = this.getCancelTokenSource() options.cancelToken = source.token } // Make sure a registry is initialized (see `init` method) before any request // TODO: Is this a good solution? const promise = this.init() .then(() => existingMethod(options)) // Add totalCount to arrays .then(result => { if (_.isArray(result) && result._totalCount === undefined) { result._totalCount = result.length } else if (_.isObject(result) && result._totalCount === undefined) { result._totalCount = 1 } if (result && type && this[`adjust${type}`]) { result = this[`adjust${type}`](result) } return result }).catch(error => { if (error instanceof errors.CDKError) { throw error } else { if (error.response) { // 4xx = invalid request if (error.response.status.toString().startsWith(4)) { throw new errors.InvalidRequestError({ relatedError: error, code: error.response.status }) } else { throw new errors.BackendError({ relatedError: error, code: error.response.status }) } } else if (error.request) { if (typeof navigator !== "undefined") { // If connected, it should be a backend problem if (navigator.connection || navigator.mozConnection || navigator.webkitConnection) { throw new errors.BackendUnavailableError({ relatedError: error }) } } // Otherwise, assume a network error throw new errors.NetworkError({ relatedError: error }) } else { // Otherwise, throw generic CDKError throw new errors.CDKError({ relatedError: error }) } } }) // Attach cancel method to Promise if (source) { promise.cancel = (...args) => { return source.cancel(...args) } } // Save to list of existing requests const request = { method, options: _.omit(options, ["cancelToken"]), promise, } currentRequests.push(request) // Remove from list of current requests after promise is done promise.catch(() => { }).then(() => currentRequests.splice(currentRequests.indexOf(request), 1)) // Add adjustment methods return promise } } } // Expose some properties from original registry object as getters get uri() { return this._jskos.uri } get notation() { return this._jskos.notation } get prefLabel() { return this._jskos.prefLabel } get definition() { return this._jskos.definition } get schemes() { return this._jskos.schemes } get excludedSchemes() { return this._jskos.excludedSchemes } get stored() { return this._jskos.stored !== undefined ? this._jskos.stored : this.constructor.stored } /** * Load data about registry via the status endpoint. * * @returns {Promise} Promise that resolves when initialization is complete. */ async init() { // Save the actual Promise in _init and return it immediately on a second call if (this._init) { return this._init } this._init = (async () => { // Call preparation method this._prepare() let status if (_.isString(this._api.status)) { // Request status endpoint try { status = await this.axios({ method: "get", url: this._api.status, }) } catch (error) { if (_.get(error, "response.status") === 404) { // If /status is not available, remove from _api this._api.status = null } } } else { // Assume object status = this._api.status } if (_.isObject(status) && !_.isEmpty(status)) { // Set config this._config = status.config || {} // Merge status result and existing API URLs for (let key of Object.keys(this._api)) { // Only override if undefined if (this._api[key] === undefined) { // Fall back to null, i.e. if /status was successful, no endpoints are implied by the provider // See also: https://github.com/gbv/cocoda-sdk/issues/21 this._api[key] = status[key] || null } } } this._setup() })() return this._init } /** * Preparation to be executed before init. Should be overwritten by subclasses. * * @private */ _prepare() { } /** * Setup to be executed after init. Should be overwritten by subclasses. * * @private */ _setup() { } /** * Returns a source for a axios cancel token. * * @returns {Object} axios cancel token source */ getCancelTokenSource() { return axios.CancelToken.source() } /** * Sets authentication credentials. * * @param {Object} options * @param {string} options.key public key of login-server instance the user is authorized for * @param {string} options.bearerToken token that is sent with each request */ setAuth({ key = this._auth.key, bearerToken = this._auth.bearerToken }) { this._auth.key = key this._auth.bearerToken = bearerToken } /** * Sets retry configuration. * * @param {Object} config * @param {string[]} [config.methods=["get", "head", "options"]] HTTP methods to retry (lowercase) * @param {number[]} [config.statusCodes=[401, 403]] status codes to retry * @param {number} [config.count=3] maximum number of retries * @param {number|Function} [config.delay=300*count] a delay in ms or a function that takes the number of current retries and returns a delay in ms */ setRetryConfig(config = {}) { this._retryConfig = Object.assign({ methods: ["get", "head", "options"], statusCodes: [401, 403], count: 3, delay: (count) => { return 300 * count }, }, config) } /** * Returns whether a user is authorized for a certain request. * * @param {Object} options * @param {string} options.type type of item (e.g. mappings) * @param {string} options.action action to be performed (read/create/update/delete) * @param {Object} options.user user object * @param {boolean} [options.crossUser] whether the request is a crossUser request (i.e. updading/deleting another user's item) * @returns {boolean} */ isAuthorizedFor({ type, action, user, crossUser }) { if (action == "read" && this.has[type] === true) { return true } if (!this.has[type]) { return false } const options = _.get(this._config, `${type}.${action}`) if (!options) { return !!this.has[type][action] } if (options.auth && (!user || !this._auth.key)) { return false } // Public key mismatch if (options.auth && this._auth.key != _.get(this._config, "auth.key")) { return false } if (options.auth && options.identities) { // Check if one of the user's identities matches const uris = [user.uri].concat(Object.values(user.identities || {}).map(id => id.uri)).filter(uri => uri != null) if (_.intersection(uris, options.identities).length == 0) { return false } } if (options.auth && options.identityProviders) { // Check if user has the required provider const providers = Object.keys((user && user.identities) || {}) if (_.intersection(providers, options.identityProviders).length == 0) { return false } } if (crossUser) { return !!options.crossUser } return !!this.has[type][action] } /** * Returns a boolean whether a certain target scheme is supported or not. * * @param {Object} scheme * @returns {boolean} */ supportsScheme(scheme) { if (!scheme) { return false } let schemes = _.isArray(this.schemes) ? this.schemes : null if (schemes == null && !jskos.isContainedIn(scheme, this.excludedSchemes || [])) { return true } return jskos.isContainedIn(scheme, schemes) } adjustConcept(concept) { // Add _getNarrower function to concepts concept._getNarrower = (config) => { return this.getNarrower({ ...config, concept }) } // Add _getAncestors function to concepts concept._getAncestors = (config) => { return this.getAncestors({ ...config, concept }) } // Add _getDetails function to concepts concept._getDetails = async (config) => { return (await this.getConcepts({ ...config, concepts: [concept] }))[0] } // Adjust broader/narrower/ancestors if necessary for (let type of ["broader", "narrower", "ancestors"]) { if (Array.isArray(concept[type]) && !concept[type].includes(null)) { concept[type] = this.adjustConcepts(concept[type]) } } // Add _registry to concepts concept._registry = this return concept } adjustConcepts(concepts) { return utils.withCustomProps(concepts.map(concept => this.adjustConcept(concept)), concepts) } adjustRegistries(registries) { return registries } adjustScheme(scheme) { // Add _registry to schemes scheme._registry = (this.cdk && this.cdk.registryForScheme(scheme)) || this if (scheme._registry) { // Add _getTop function to schemes scheme._getTop = (config) => { return scheme._registry.getTop({ ...config, scheme }) } // Add _getTypes function to schemes scheme._getTypes = (config) => { return scheme._registry.getTypes({ ...config, scheme }) } // Add _suggest function to schemes scheme._suggest = ({ search, ...config }) => { return scheme._registry.suggest({ ...config, search, scheme }) } } return scheme } adjustSchemes(schemes) { return utils.withCustomProps(schemes.map(scheme => this.adjustScheme(scheme)), schemes) } adjustConcordances(concordances) { for (let concordance of concordances) { // Add _registry to concordance concordance._registry = this } return concordances } adjustMapping(mapping) { // TODO: Add default type // Add fromScheme and toScheme if missing for (let side of ["from", "to"]) { let sideScheme = `${side}Scheme` if (!mapping[sideScheme]) { mapping[sideScheme] = _.get(jskos.conceptsOfMapping(mapping, side), "[0].inScheme[0]", null) } } mapping._registry = this if (!mapping.identifier) { // Add mapping identifiers for this mapping let identifier = _.get(jskos.addMappingIdentifiers(mapping), "identifier") if (identifier) { mapping.identifier = identifier } } return mapping } adjustMappings(mappings) { return utils.withCustomProps(mappings.map(mapping => this.adjustMapping(mapping)), mappings) } /** * POSTs multiple mappings. Do not override in subclass! * * @param {Object} config * @param {Array} config.mappings array of mapping objects * @returns {Object[]} array of created mapping objects; in case of failure, consult the `_errors` property on the array at the index of the failed request */ async postMappings({ mappings, ...config } = {}) { if (!mappings || !mappings.length) { throw new errors.InvalidOrMissingParameterError({ parameter: "mappings" }) } return this._callHelperForArrayWrappers({ method: "postMapping", items: mappings, itemProperty: "mapping", config, }) } /** * DELETEs multiple mappings. Do not override in subclass! * * @param {Object} config * @param {Array} config.mappings array of mapping objects * @returns {Object[]} array of results (`true` if successful); in case of failure, consult the `_errors` property on the array at the index of the failed request */ async deleteMappings({ mappings, ...config } = {}) { if (!mappings || !mappings.length) { throw new errors.InvalidOrMissingParameterError({ parameter: "mappings" }) } return this._callHelperForArrayWrappers({ method: "deleteMapping", items: mappings, itemProperty: "mapping", config, }) } /** * Calls a method that is for only one item for an array of items. Returns an array of results. * * If there is an error, that index in the result array will be `null`. There is a property `_errors` on the result array that will contain the respective error at the correct index. * * @param {Object} options * @param {string} options.method instance method to call (e.g. `postMapping`) * @param {Object[]} options.items items to call the method for * @param {string} options.itemProperty the property name for the item when calling the method (e.g. `mapping`) * @param {Object} options.config other properties to pass to the method call * @returns {any[]} result array with values returned from individual method calls * * @private */ async _callHelperForArrayWrappers({ method, items, itemProperty, config }) { const errors = [] const resultItems = await Promise.all(items.map(async item => { try { const resultItem = await this[method]({ [itemProperty]: item, ...config, _raw: true }) return resultItem } catch (error) { errors[items.indexOf(item)] = error return null } })) resultItems._errors = errors return resultItems } }
JavaScript
class InputWidget { constructor(elementname, isastring) { //Add properties this.widget = document.getElementById(elementname); this.elementname = elementname; this.isastring = isastring; this.focused = false; //Check for widget not found if(this.widget == null) return; //Add event listeners to widget if not read only if(!this.widget.readOnly) { this.widget.addEventListener("focus", this.OnFocus.bind(this)); this.widget.addEventListener("blur", this.OnBlur.bind(this)); this.widget.addEventListener("keypress", this.OnKeyPress.bind(this)); } } OnFocus() { //Check for widget not found if(this.widget == null) return; //Make visual change and don't allow update of widget value this.widget.style.backgroundColor = "lightblue"; this.focused = true; } OnBlur() { //Check for widget not found if(this.widget == null) return; //Make visual change and allow update of widget value this.widget.style.backgroundColor = ""; this.focused = false; } OnKeyPress(event) { //Check for widget not found if(this.widget == null) return; //Check for enter key if(event.key === 'Enter') { var jsoncmd; //Encode element command as JSON if(this.isastring) var jsoncmd = JSON.stringify(["se",this.elementname,this.widget.value]); else var jsoncmd = JSON.stringify(["se",this.elementname,parseInt(this.widget.value)]); //Send HTTP request to server var req = new XMLHttpRequest(); req.open("GET", "hcquery.php?cmd=[" + Xactnum + "," + jsoncmd + "]&" + (new Date()).getTime(), true); req.send(null); //Increment transaction number Xactnum++; //Limit 0-99 if(Xactnum > 99) Xactnum = 0; //Force call of blur event handler this.widget.blur(); } } UpdateValue(elementname, elementval, err) { //Check for widget not found if(this.widget == null) return; //Check for not our element if(this.elementname !== elementname) return; //Check for focused if(this.focused) return; //Update widget value this.widget.value = elementval; //Check for error if(err == "None") this.widget.style.backgroundColor = ""; else this.widget.style.backgroundColor = "yellow"; } }
JavaScript
class Model { constructor(data = {}, [parent, key] = []) { const $this = this /** * create schema */ class Schema extends _Schema { constructor(metas) { const defs = map(metas, (def) => { if (!def) { return } /** * class SomeModel extends Model { * static some = OtherModel * } */ if (isInheritedOf(def, Model)) { return Factory.getMeta(def) } /** * class SomeModel extends Model { * static some = [OtherModel, AnyModel] * } */ if (isArray(def) && !def.some(def => !isInheritedOf(def, Model))) { return Factory.getMeta(def) } return def }) super(defs) } onError(e) { // dont throw error when generate data when initialize if ($this.$init && e.attr === 'create') { return } $this.onError(e) $this.emit('error', e) } } // create schema let schema = this.schema(Schema) // support schema instance or object if (!isInstanceOf(schema, _Schema)) { schema = map(schema, (value) => { if (!value) { return } if (isInstanceOf(value, Meta) || isInheritedOf(value, Meta)) { return value } // support use a object which contains a 'default' property to be a Meta if (isObject(value) && inObject('default', value)) { return new Meta(value) } // default, support Model return value }) schema = new Schema(schema) } define(this, '$schema', schema) define(this, '$hooks', []) define(this, '$$attrs', { ...DEFAULT_ATTRIBUTES, ...this.attrs() }) define(this, '$$state', this.state()) define(this, '$$deps', {}) // use passed parent if (parent && isInstanceOf(parent, Model) && key) { this.setParent([parent, key]) } define(this, '$root', () => { let parent = this.$parent if (!parent) { return } while (parent.$parent) { parent = parent.$parent } return parent }) define(this, '$absKeyPath', () => { let parent = this.$parent if (!parent) { return [] } const path = [...this.$keyPath] while (parent && parent.$keyPath) { path.unshift(...parent.$keyPath) parent = parent.$parent } return path }) /** * create store */ class Store extends _Store { _traps(traps) { const isNotAllowed = (keyPath) => { if (keyPath.length !== 1) { return false } const [key] = keyPath const meta = $this.$schema[key] if (!meta) { return false } if (!isInstanceOf(meta, FactoryMeta)) { return false } } const inserter = (keyPath, args) => { if (isNotAllowed(keyPath)) { return false } const [key] = keyPath const meta = $this.$schema[key] const { $entries } = meta const nexts = args.filter((item) => { if ($entries.some(One => isInstanceOf(item, One))) { return true } if (isObject(item)) { return true } return false }) const [Entry] = $entries const values = nexts.map((next) => { const model = $entries.some(One => isInstanceOf(next, One)) ? next.setParent([$this, key]) : isObject(next) ? new Entry(next, [$this, key]) : new Entry({}, [$this, key]) return model }) return values } traps.push = inserter traps.unshift = inserter traps.splice = (keyPath, args) => { if (isNotAllowed(keyPath)) { return false } const [start, count, ...items] = args const values = items.length ? inserter(keyPath, items) : [] return [start, count, ...values] } traps.fill = (keyPath, args) => { if (isNotAllowed(keyPath)) { return false } const [value, start, end] = args const [key] = keyPath const current = $this[key] const len = current.length // without effects if (start && start >= len) { return false } const from = start || 0 if (end && end <= from) { return false } const to = !end || end > len ? len : end const count = to - from const items = createArray(value, count) const values = inserter(keyPath, items) return { to: 'splice', args: [start, count, ...values], } } const trapGet = traps.get traps.get = (keyPath, active) => { trapGet(keyPath, active) if (!$this.$collection) { const deep = [] let child = $this let parent = child.$parent let flag = null while (parent) { const keyPath = child.$keyPath deep.unshift(...keyPath) if (parent.$collection) { flag = parent break } child = parent parent = child.$parent } if (flag) { flag.$collection.items.push([deep, $this]) $this.collect() } } if ($this.$collection && $this.$collection.enable && $this.$collection.fields) { $this.$collection.items.push([keyPath, active]) if (isInstanceOf(active, Model)) { active.collect() } } return active } return traps } dispatch(keyPath, e, force) { const notified = super.dispatch(keyPath, e, force) // propagation if (notified && $this.$parent && $this.$keyPath) { $this.$parent.$store.dispatch([...$this.$keyPath, ...keyPath], e, true) } return notified } } const store = new Store() define(this, '$store', store) this.init(data) /** * support async onInit * i.e. * * async onInit() { * const options = await this.$schema.some.getOptionsAsync() * this.options = options * } * * async getOptions() { * await this.$ready * return this.options * } */ define(this, '$ready', Promise.resolve(this.onInit())) } schema() { // create schema by model's static properties return ofChain(this, Model) } state() { return {} } attrs() { return {} } init(data = {}) { if (this.$ready) { return } const keys = Object.keys(this.$schema) // patch keys to this keys.forEach((key) => { define(this, key, { get: () => this.get(key), set: (value) => this.set(key, value), enumerable: true, }) }) // views const views = {} keys.forEach((key) => { // patch attributes from meta const meta = this.$schema[key] // default attributes which will be used by Model/Schema, can not be reset by userself const attrs = this.$$attrs // define a view const view = { changed: false, // whether the field has changed } // use defineProperties to define view properties const viewDef = {} each(attrs, (fallback, attr) => { if (isNull(fallback)) { return } viewDef[attr] = { get: () => this.$schema.$decide(key, attr, this)(fallback), enumerable: true, } }) each(meta, (descriptor, attr) => { if (inArray(attr[0], ['$', '_'])) { return } if (inObject(attr, attrs)) { return } const { value, get, set } = descriptor if (get || set) { viewDef[attr] = { get: get && get.bind(this), set: set && set.bind(this), enumerable: true, configurable: true, } } else if (isAsyncRef(value)) { const { current, attach } = value let attrValue = current // async set attr value attach(key, attr).then((next) => { if (next === attrValue) { return } const prev = attrValue attrValue = next this.$store.forceDispatch(`!${key}.${attr}`, next, prev) }) viewDef[attr] = { get: () => { if (this.$collection && this.$collection.enable && this.$collection.views) { this.$collection.items.push([`!${key}.${attr}`]) } return attrValue }, set: (value) => { const prev = attrValue attrValue = value this.$store.forceDispatch(`!${key}.${attr}`, value, prev) }, enumerable: true, configurable: true, } } // use as a getter else if (isFunction(value)) { viewDef[attr] = { get: value.bind(this), enumerable: true, configurable: true, } } // patch to view directly else { let attrValue = value viewDef[attr] = { get: () => { if (this.$collection && this.$collection.enable && this.$collection.views) { this.$collection.items.push([`!${key}.${attr}`]) } return attrValue }, set: (value) => { const prev = attrValue attrValue = value this.$store.forceDispatch(`!${key}.${attr}`, value, prev) }, enumerable: true, configurable: true, } } }, true) // unwritable mandatory view properties const getData = () => this._getData(key) Object.assign(viewDef, { key: { get: () => key, enumerable: true, }, value: { get: () => this.get(key), set: (value) => this.set(key, value), enumerable: true, }, errors: { get: () => makeMsg(this.$schema.$validate(key, getData(), this)([])), enumerable: true, }, empty: { get: () => this.$schema.empty(key, getData(), this), enumerable: true, }, data: { get: () => getData(), enumerable: true, }, text: { get: () => this.$schema.format(key, getData(), this), enumerable: true, }, state: { get: () => { const state = meta.state ? meta.state.call(null) : {} const keys = Object.keys(state) const proxy = new Proxy(state, { get: (_, key) => inArray(key, keys) ? this.get(key) : undefined, set: (_, key, value) => inArray(key, keys) && this.set(key, value), }) return proxy }, enumerable: true, }, absKeyPath: { get: () => { const absKeyPath = this.$absKeyPath return [...absKeyPath, key] }, enumerable: true, }, }) Object.defineProperties(view, viewDef) define(views, key, { get: () => { if (this.$collection && this.$collection.enable && this.$collection.views) { this.$collection.items.push([`!${key}`]) } return view }, enumerable: true, }) }) define(this, '$views', views) // create errors, so that is's easy and quick to know the model's current status define(this.$views, '$errors', () => { const errors = [] each(views, (view) => { errors.push(...view.errors) }) return makeMsg(errors) }) // create changed, so that it's easy to find out whether the data has changed define(this.$views, '$changed', { get: () => this.collect(() => keys.some((key) => this.$views[key].changed), true), set: (status) => this.collect(() => keys.forEach(key => this.$views[key].changed = !!status), true), }) // create $state, so that it's easy to read state from $views define(this.$views, '$state', () => { const state = this._combineState() const keys = Object.keys(state) const output = {} keys.forEach((key) => { define(output, key, { enumerable: true, get: () => this[key], set: (value) => this[key] = value, }) }) return output }) // invoke `init` attribute keys.forEach((key) => { const meta = this.$schema[key] if (meta.init) { meta.init.call(this, key) } }) // init data this._initData(data) // register a listener this.watch('*', (e) => { const { key, compute } = e const root = key[0] const def = this.$schema[root] if (!def) { return } // disable for private properties if (inArray(key[key.length - 1][0], ['$', '_'])) { return } // response for def.watch attribute if (def.watch) { def.watch.call(this, e, key) } // check $parent this._ensure(root) // modify view.changed if (!compute) { this.collect(() => { this.$views[root].changed = true }, true) } if (this.$$deps[root]) { const { deps, fn } = this.$$deps[root] deps.forEach((dep) => { this.unwatch(dep, fn) }) } this.onChange(root) }, true) } _initData(data) { this.$initing = true this.fromJSON(data) delete this.$initing } _combineState() { const output = {} const state = this.$$state const combine = (state) => { each(state, (descriptor, key) => { const { value } = descriptor if (isAsyncRef(value)) { const { current, attach } = value output[key] = current if (this.$ready) { return } // async set attr value attach(key).then((next) => { if (this[key] === next) { return } if (this[key] && typeof this[key] === 'object' && this[key][Symbol('ORIGIN')] === next) { return } this[key] = next // will trigger watcher }) return } define(output, key, { ...descriptor, enumerable: true, configurable: true, }) }, true) } combine(state) each(this.$schema, (meta) => { if (!meta.state) { return } const metaState = meta.state.call(null) combine(metaState) }) return output } /** * reset and cover all data, original model will be clear first, and will use new data to cover the whole model. * notice that, properties which are in original model be not in schema may be removed. * @param {*} data * @param {string[]} keysPatchToThis keys those not in schema but path to this */ restore(data, keysPatchToThis = []) { if (!this.$store.editable) { return this } const schema = this.$schema const state = this._combineState() const params = {} const input = {} const ensure = (value, key) => { if (isArray(value)) { value.forEach((item, i) => ensure(item, key)) } else if (isInstanceOf(value, Model)) { value.setParent([this, key]) } } const record = (key) => { if (inObject(key, data)) { const value = data[key] input[key] = value ensure(value, key) } } // patch state each(state, (descriptor, key) => { if (descriptor.get || descriptor.set) { define(params, key, descriptor) // use data property if exist, use data property directly record(key) } else if (inObject(key, data)) { params[key] = data[key] } else { params[key] = descriptor.value } // define state here so that we can invoke this.state() only once when initialize define(this, key, { get: () => this.get(key), set: (value) => this.set(key, value), enumerable: true, configurable: true, }) }, true) // those on schema each(schema, (_, key) => { if (inObject(key, data)) { const value = data[key] params[key] = value ensure(value, key) return } // notice here, we call this in default(), we can get passed state properties const value = schema.getDefault(key, this) // default can be an AsyncGetter, so that we can set default value asyncly if (isAsyncRef(value)) { const { current, attach } = value params[key] = current ensure(current, key) attach(key, 'default').then((next) => { if (this[key] === next) { return } if (this[key] && typeof this[key] === 'object' && this[key][Symbol('ORIGIN')] === next) { return } this[key] = next // will trigger watcher }) } else { params[key] = value ensure(value, key) } }) // delete the outdate properties each(this.$store.state, (_, key) => { if (inObject(key, params)) { return } // disable for private properties if (inArray(key[0], ['$', '_'])) { return } this.$store.del(key) delete this[key] }, true) // reset into store const initParams = this.onSwitch(params) this.emit('switch', initParams) this.$store.init(initParams) // patch those which are not in store but on `this` each(data, (value, key) => { if (!inObject(key, params) && inObject(key, this)) { this[key] = value } }) // patch keys to this, i.e. this.fromJSON(data, ['polices']) => this.polices keysPatchToThis.forEach((key) => { if (!inObject(key, this)) { this[key] = json[key] } }) // reset changed this.$views.$changed = false this.onRestore() this.emit('restore') // dependencies collection // after onRestore, so that developers can do some thing before collection each(this.$schema, (meta, key) => { if (meta.compute) { this._getData(key) } }) return this } /** * get field value, with formatting by `getter` * @param {array|string} keyPath */ get(keyPath) { const chain = isArray(keyPath) ? [...keyPath] : makeKeyChain(keyPath) const key = chain.shift() const value = this._getData(key) const transformed = this.$schema.get(key, value, this) const output = parse(transformed, chain) return output } /** * @param {*} type 0: start, 1: end */ collect(collector, inverse) { if (isFunction(collector)) { if (inverse) { // if true, do not collect deps, and return normal value of collector fn if (this.$collection) { this.$collection.enable = false } const res = collector() if (this.$collection) { this.$collection.enable = true } return res } // if false, do fn, return deps this.collect() collector() return this.collect(true) } const summarize = () => { const { items } = this.$collection const records = [] items.forEach(([keyPath, value]) => { const key = isArray(keyPath) ? makeKeyPath(keyPath, true) : keyPath records.push({ key, value }) if (isInstanceOf(value, Model)) { const deps = value.collect(true) const keys = deps.map((dep) => { const chain = makeKeyChain(dep) const key = makeKeyPath([...keyPath, ...chain], true) return key }) keys.forEach((key) => { records.push({ key, subof: value }) }) } }) const res = [] const push = (key, value) => { if (!isFunction(value) && !res.includes(key) && key.split('.').pop() !== 'length') { res.push(key) } } let prev = null records.forEach((record, i) => { if (i === 0 && i !== records.length - 1) { prev = record return } const { key, value, subof } = record if (prev) { const { key: prevKey, value: prevValue } = prev if (subof && subof !== prevValue) { push(prevKey, prevValue) } else if (prevKey === key) { push(prevKey, prevValue) } else if (key.indexOf(prevKey) !== 0) { push(prevKey, prevValue) } } if (i === records.length - 1) { push(key, value) } prev = record }) return res } // end, clear, and return deps if (collector === true) { const collection = this.$collection if (!collection) { return [] } const keys = summarize() const { timer } = collection clearTimeout(timer) delete this.$collection return keys } // dont start collect again if (this.$collection) { return summarize } // start collecting const items = [] const timer = setTimeout(() => this.collect(true), 32) define(this, '$collection', { value: { items, // clear automaticly to free memory timer, enable: true, views: collector && typeof collector === 'object' ? collector.views : false, fields: collector && typeof collector === 'object' && 'fields' in collector ? collector.fields : true }, configurable: true, }) // end before timeout return summarize } /** * get a view of field by its keyPath * @param {*} keyPath */ use(keyPath) { const chain = isArray(keyPath) ? [...keyPath] : makeKeyChain(keyPath) const key = chain.pop() if (!chain.length) { return this.$views[key] } const target = parse(this, chain) if (isInstanceOf(target, Model)) { return target.$views[key] } } /** * set field value, with `readonly`, `disabled`, `editable`, `type` checking, and formatting by `setter` * @param {array|string} keyPath * @param {*} next * @param {boolean} force force set, ignore `readonly` & `disabled` */ set(keyPath, next, force) { if (!this.$store.editable) { return parse(this, keyPath) } const chain = isArray(keyPath) ? [...keyPath] : makeKeyChain(keyPath) const key = chain.shift() // deep set if (chain.length) { const current = this.$store.get(key) const cloned = clone(current) assign(cloned, chain, next) next = cloned } const def = this.$schema[key] if (!def) { return this.define(key, next) } this._check(key) const prev = this.$store.get(key) const value = force ? this.$schema.$set(key, next, this) : this.$schema.set(key, next, prev, this) const coming = this.$store.set(key, value) this.emit('set', keyPath, coming, prev) return coming } update(data) { if (!this.$store.editable) { return this } each(data, (value, key) => { // only update existing props, ignore those which are not on model // this shakes affects by over-given props if (inObject(key, this)) { this[key] = value } }) return this } reset(key) { const value = this.$schema.getDefault(key, this) this.set(key, value, true) return this } define(key, value) { if (!this.$store.editable) { return parse(this, keyPath) } if (this.$schema[key]) { return this[key] } // delete this key if (isUndefined(value)) { delete this[key] this.$store.del(key) return } const def = { get: () => this.$store.get(key), configurable: true, enumerable: true, } if (!isFunction(value)) { def.set = value => this.$store.set(key, value) } Object.defineProperty(this, key, def) const coming = isFunction(value) ? this.$store.define(key, value) : this.$store.set(key, value) return coming } watch(key, fn) { this.$store.watch(key, fn, true, this) return this } unwatch(key, fn) { this.$store.unwatch(key, fn) return this } validate(key) { // validate all properties once together if (!key) { const errors = [] const errs = this.onCheck() || [] this.emit('check', errs) errors.push(...errs) const keys = Object.keys(this.$schema) keys.forEach((key) => { const errs = this.validate(key) errors.push(...errs) }) return makeMsg(errors) } if (isArray(key)) { const errors = [] key.forEach((key) => { const errs = this.validate(key) errors.push(...errs) }) return makeMsg(errors) } this._check(key, true) const value = this._getData(key) const errors = this.$schema.validate(key, value, this) return makeMsg(errors) } validateAsync(key) { // validate all properties once together if (!key) { const errors = [] const errs = this.onCheck() || [] this.emit('check', errs) errors.push(...errs) const keys = Object.keys(this.$schema) return this.validateAsync(keys).then((errs) => { errors.push(...errs) return makeMsg(errors) }) } if (isArray(key)) { return Promise.all(key.map(key => this.validateAsync(key))).then((groups) => { const errors = flatArray(groups.filter(group => !!group)) return makeMsg(errors) }) } this._check(key, true) const value = this._getData(key) const errors = this.$schema.validateAsync(key, value, this) return makeMsg(errors) } _getData(key) { const value = this.$store.get(key) const meta = this.$schema[key] const view = this.collect(() => this.$views[key], true) // if value is changed manully, we will use changed value if (view && view.changed) { return value } // if value is not changed, we will use computed value else if (meta && meta.compute) { this.collect() const res = tryGet(() => meta.compute.call(this), value) const deps = this.collect(true) // clear previous watchers const depent = this.$$deps[key] if (depent && depent.deps && depent.deps.length) { const away = depent.deps.filter(item => !deps.includes(item)) const { fn } = depent away.forEach((key) => { this.unwatch(key, fn) }) } // // subscribe new watchers if (deps.length) { const fn = () => { const prev = res const value = this.$store.get(key) const next = tryGet(() => meta.compute.call(this), value) this.$store.dispatch(key, { value: next, next, prev, active: next, invalid: prev, compute: true }) } deps.forEach((key) => { this.watch(key, fn, true) }) this.$$deps[key] = { deps, fn } } return res } else { return value } } _bundleData() { const state = this.$store.state const schema = this.$schema const views = this.$views const computed = {} each(schema, (meta, key) => { if (this.collect(() => views[key] && views[key].changed, true)) { return } if (meta.compute) { const value = tryGet(() => meta.compute.call(this), state[key]) computed[key] = value } }) return { ...state, ...computed } } /** * use schema `create` option to generate and restore data * @param {*} json */ fromJSON(json, keysPatchToThis) { if (!this.$store.editable) { return this } // prepare for sub models this.$children = [] // patch state into this, so that we can get passed state in default() // dont be worried about reactive, the properties will be override by restore() const state = this._combineState() const patches = map(state, (value, key) => { if (inObject(key, json)) { return json[key] } else { return value } }) Object.assign(this, patches) // when new Model, onParse may throw error const entry = tryGet(() => this.onParse(json) || json, json) this.emit('parse', entry) const data = this.$schema.parse(entry, this) const next = { ...entry, ...data } this.restore(next, keysPatchToThis) // ask children to recompute computed properties this.$children.forEach(child => child.onRegress()) // we do not need $children delete this.$children // reset changed, make sure changed=false after recompute this.$views.$changed = false return this } toJSON() { this._check() const data = clone(this._bundleData()) // original data const output = this.$schema.record(data, this) const result = this.onRecord(output) || output this.emit('record', result) return result } /** * update model by passing data, which will use schema `create` attribute to generate value * @param {*} data * @param {string[]} onlyKeys the keys outside of this array will not be set, if not set, all keys will be used */ fromJSONPatch(data, onlyKeys) { const output = {} each(data, (value, key) => { if (onlyKeys && !inArray(key, onlyKeys)) { return } const coming = this.$schema.$parse(key, value, data, this) output[key] = coming }) this.update(output) // reset changed, make sure changed=false after recompute this.collect(() => { const keys = Object.keys(output) keys.forEach((key) => { if (this.$views[key]) { this.$views[key].changed = false } }) }, true) return this } toData() { this._check() const data = clone(this._bundleData()) // original data const output = this.$schema.export(data, this) const result = this.onExport(output) || output this.emit('export', result) return result } toParams(determine) { const data = this.toData() const output = flat(data, determine) return output } toFormData(determine) { const data = this.toParams(determine) const formdata = new FormData() each(data, (value, key) => { formdata.append(key, value) }) return formdata } on(hook, fn) { this.$hooks.push({ hook, fn }) return this } off(hook, fn) { this.$hooks.forEach((item, i) => { if (hook === item.hook && (isUndefined(fn) || fn === item.fn)) { this.$hooks.splice(i, 1) } }) return this } emit(hook, ...args) { this.$hooks.forEach((item) => { if (hook !== item.hook) { return } item.fn.call(this, ...args) }) } // when initialized onInit() {} // before restore model datas onSwitch(params) { return params } // parse data before parse, should be override onParse(data) { return data } // by toJSON onRecord(data) { return data } // serialize data after export, should be override onExport(data) { return data } onCheck() {} onError() {} onEnsure() {} onRestore() {} onRegress() {} onChange(key) {} lock() { this.$store.editable = true } unlock() { this.$store.editable = false } setParent([parent, key]) { if (this.$parent && this.$parent === parent && this.$keyPath && this.$keyPath[0] === key) { return this } define(this, '$parent', { value: parent, writable: false, configurable: true, }) define(this, '$keyPath', { get: () => { const field = parent[key] const res = parent.collect(() => isArray(field) ? [key, field.indexOf(this)] : [key], true) return res }, configurable: true, }) // record sub models if (parent.$children) { parent.$children.push(this) } // recompute depend on $parent else { this.onRegress() } return this } setAttr(key) { return (attr, value) => { if (this.$views[key]) { this.$views[key][attr] = value } } } _ensure(key) { const add = (value, key) => { if (isInstanceOf(value, Model) && !value.$parent) { value.setParent([this, key]) value.onEnsure(this) value.emit('ensure', this) } } const use = (value, key) => { if (isArray(value)) { value.forEach((item) => add(item, key)) } else { add(value, key) } } const root = isArray(key) ? key[0] : key const value = this._getData(root) use(value, key) } _check(key, isValidate = false) { const schema = this.$schema const keys = key ? [key] : Object.keys(schema) keys.forEach((key) => { // dont check if disabled if (this.$schema.disabled(key, this)) { return } const def = schema[key] each(def, (value, attr) => { let str = '' if (attr === 'validators' && isValidate) { value.forEach((item) => { each(item, (value) => { str += isFunction(value) ? value + '' : '' }) }) } else { str += isFunction(value) ? value + '' : '' } if (str.indexOf('this.$parent') > -1 && !this.$parent) { const e = { key, attr, action: '_check $parent', message: `this.$parent is called in ${attr}, but current model has no $parent`, } this.onError(e) this.emit('error', e) } }) }) } static extend(next) { const Constructor = inherit(this) if (isObject(next)) { const metas = map(next, (value) => { // make it easy to extend, 'default' is required if (isObject(value) && inObject('default', value)) { return new Meta(value) } else { return value } }) Object.assign(Constructor, metas) } // isConstructor should must come before isFunction else if (isConstructor(next, 2)) { mixin(Constructor, next) } else if (isFunction(next)) { return next(Constructor) } return Constructor } static get toEdit() { const Editor = edit(this) return Editor } toEdit(next) { const $this = this const Constructor = getConstructorOf(this) const _Editor = Constructor.toEdit.extend(next) class Editor extends _Editor { init(data) { // set parent before restore const { $parent, $keyPath } = $this if ($parent) { this.setParent([$parent, $keyPath[0]]) } super.init(data) // override current metas to editable metas each($this.$views, (view, key) => { each(view, (descriptor, attr) => { if ('value' in descriptor) { const { value } = descriptor this.setAttr(key, attr, value) } }, true) }) } submit() { return super.submit($this) } } const editor = new Editor(this) this.onEdit(editor) this.emit('edit', editor) return editor } onEdit() {} /** * use a meta definition to find out view * @param {Meta} Meta * @param {function} [fn] key => any * @returns {view} * @example * class Some extends Meta { * ... * } * class Dog extends Meta { * drop() { * const some = this.reflect(Some) || {} // undefined if Some not used * return some.value * } * } */ reflect(Meta, fn) { const keys = Object.keys(this.$schema) for (let i = 0, len = keys.length; i < len; i ++) { const key = keys[i] const meta = this.$schema[key] if (meta === Meta || (isConstructor(Meta) && isInstanceOf(meta, Meta))) { return isFunction(fn) ? fn.call(this, key) : this.$views[key] } } } }
JavaScript
class Engine { constructor(scheduler) { this._scheduler = scheduler; this._lock = 1; } /** * Start the main loop. When this call returns, the loop is locked. */ start() { return this.unlock(); } /** * Interrupt the engine by an asynchronous action */ lock() { this._lock++; return this; } /** * Resume execution (paused by a previous lock) */ unlock() { if (!this._lock) { throw new Error("Cannot unlock unlocked engine"); } this._lock--; while (!this._lock) { let actor = this._scheduler.next(); if (!actor) { return this.lock(); } /* no actors */ let result = actor.act(); if (result && result.then) { /* actor returned a "thenable", looks like a Promise */ this.lock(); result.then(this.unlock.bind(this)); } } return this; } }
JavaScript
class FormSerializeUtil { /** * serializes a form * * @param {HTMLFormElement} form * @param {boolean} strict * * @returns {*} */ static serialize(form, strict = true) { if (form.nodeName !== 'FORM') { if (strict) { throw new Error('The passed element is not a form!'); } return {}; } return new FormData(form); } /** * * serializes the form and returns * its data as json * * @param {HTMLFormElement} form * @param {boolean} strict * @returns {*} */ static serializeJson(form, strict = true) { const formData = FormSerializeUtil.serialize(form, strict); if (formData === {}) return formData; const json = {}; Iterator.iterate(formData, (value, key) => json[key] = value); return json; } }
JavaScript
class ProxyResource extends Resource { constructor(scope, id, props) { super(scope, id, { parent: props.parent, pathPart: '{proxy+}', defaultIntegration: props.defaultIntegration, defaultMethodOptions: props.defaultMethodOptions, }); const anyMethod = props.anyMethod !== undefined ? props.anyMethod : true; if (anyMethod) { this.anyMethod = this.addMethod('ANY'); } } addMethod(httpMethod, integration, options) { // In case this proxy is mounted under the root, also add this method to // the root so that empty paths are proxied as well. if (this.parentResource && this.parentResource.resourcePath === '/') { this.parentResource.addMethod(httpMethod); } return super.addMethod(httpMethod, integration, options); } }
JavaScript
class Line { constructor({ line, lineNumber, fileName }) { this.line = line this.lineNumber = lineNumber this.fileName = fileName } match(re) { return this.line.match(re) || [] } static of(line) { return new Line(line) } }
JavaScript
class LineReader extends Transform { #fileName #state constructor(fileName) { super({ objectMode: true }) this.#state = new State({ lineCount: 0, buffer: [] }, readLineReducer) this.#fileName = fileName } pushLine() { const { buffer, lineCount } = this.#state.get() if (notEmpty(buffer)) { this.push( Line.of({ line: join('', buffer), lineNumber: lineCount, fileName: this.#fileName, }) ) this.#state.dispatch(clearBuffer()) } } _transform(chunk, _, callback) { for (const char of chunk.toString()) { if (!isTerminator(char)) { this.#state.dispatch(addChar(char)) } else { this.#state.dispatch(incrementLineCount()) this.pushLine(this) } } callback() } _flush(callback) { this.#state.dispatch(incrementLineCount()) this.pushLine(this) callback() } static for(fileName) { return new LineReader(fileName) } }
JavaScript
class Auth0CordovaWrapper { /** * @param {Auth0Cordova} client - Instance of client conforming to the interface */ constructor(client, store) { this.client = client; this.store = store; this.cache = {}; } /** * * @param {*} audience * @param {*} scope */ async authenticate(audience, scope) { const credentials = await new Promise((resolve, reject) => { this.client.authorize({ audience, scope }, (err, result) => { if (err) { reject(err); return; } resolve(result); }) }); const key = `${audience}:${scope}`; credentials.expiresAt = Date.now() + credentials.expiresIn * 1000; this.cache[key] = credentials; // Store RT so that we can make calls later await this.store.set(audience, credentials.refreshToken); } /** * Get Token wrapper * * @param {String} audience * @param {String} scope */ async getToken(audience, scope) { const key = `${audience}:${scope}`; let cached = this.cache[key]; if (cached && cached.expiresAt < Date.now()) { return cached.accessToken; } const refreshToken = this.store.get(key, audience); // Update tokens const credentials = await new Promise((resolve, reject) => { this.client.client.oauthToken({ grantType: 'refresh_token', refreshToken }) }); this.cache[key] = credentials; credentials.expiresAt = credentials.expiresIn * 1000 + Date.now(); return credentials.accessToken; } /** * Get audience wrapper * @param {*} audience * @param {*} scope */ async getUserProfile(audience, scope) { const key = `${audience}:${scope}`; let cached = this.cache[key]; if (cached && cached.expireAt < Date.now()) { return cached.idTokenPayload; } const refreshToken = this.store.get(key, audience); // Update tokens const credentials = await new Promise((resolve, reject) => { this.client.client.oauthToken({ grantType: 'refresh_token', refreshToken }) }); this.cache[key] = credentials; credentials.expiresAt = credentials.expiresIn * 1000 + Date.now(); return credentials.idTokenPayload; } async isAuthenticated() { try { return !!await this.getUserProfile(audience, scope); } catch (e) { } return false; } /** * */ logout() { return this.store.removeAll(); } // Noop on Cordova handleCallback() { } }
JavaScript
class DragList extends React.Component { /** * Main globals settings. * * @memberof DragList */ globals = { mainClassName: 'drag-list-element' } /** * Main state of component. * * @memberof DragList */ state = { target: null, current: null, handler: true, propagation: false, placeholder: true } /** * Prototypes for compojent. * * @static * @memberof DragList */ static propTypes = { handler: PropTypes.bool, placeholder: PropTypes.bool, list: PropTypes.array.isRequired, update: PropTypes.func.isRequired, render: PropTypes.func.isRequired } /** * Creates an instance of DragList. * * @param {any} [props={}] * @memberof DragList */ constructor(props = {}){ super(props); this.state.placeholder = this.props.placeholder === true || this.props.placeholder === false? this.props.placeholder : this.state.placeholder; this.state.handler = this.props.handler === true || this.props.handler === false? this.props.handler : this.state.handler; } /** * Handle component will mount event. * * @memberof DragList */ componentWillMount = () => window.addEventListener("mousemove", (event) => { if(!this.state.current) { return false; } this.setState({ current: { ...this.state.current, posX: event.clientX, posY: event.clientY } }) }); /** * Prepare list for handle drag event. * * @memberof DragList */ preapre = () => this.props.list.map((item, index) => ( <div key={`drag-list-${index}`} className={this.globals.mainClassName} onMouseDown={!this.state.handler? this.handleMouseDown : () => {}} onMouseUp={this.handleMouseUp} onMouseMove={this.handleMouseMove} data-index={index} > {this.state.handler? <div onMouseDown={this.handleMouseDown} className="drag-list-handler" > <span /> <span /> <span /> </div> : null } {this.props.render(item, index)} </div>)) /** * Handle mouse over event. * * @param {any} [event={}] * @memberof DragList */ handleMouseMove = (event = {}) => { if(this.state.propagation) { const parent = event.target.parentElement; if(parent.className !== this.globals.mainClassName) { return false; } this.startHandleDrag(parent, event); } if(!this.state.current) { return false; } this.setState({ target: event.currentTarget.dataset.index }) } /** * Start propagation element drag. * * @param {any} [parent={}] * @param {any} [event={}] * @memberof DragList */ startHandleDrag = (parent = {}, event = {}) => { const node = this.state.handler? nodeToString(parent).replace('<div class="drag-list-handler"><span></span><span></span><span></span></div>', '') : nodeToString(event.target); this.setState({ current: { index: this.state.handler? parent.dataset.index: event.currentTarget.dataset.index, element: <div dangerouslySetInnerHTML={{ __html: node }} /> }, propagation: false }); } /** * Handle mouse down event. * * @param {any} [event={}] * @memberof DragList */ handleMouseDown = (event = {}) => this.setState({ propagation: true }); /** * Handle mouse up event. * * @param {any} [event={}] * @memberof DragList */ handleMouseUp = (event = {}) => { if(!this.state.current) { this.clear(); return false; } const index = event.currentTarget.dataset.index? event.currentTarget.dataset.index : this.state.target; if(this.state.current.index === index || !index || !this.state.current.index){ this.clear(); return false; } this.props.update(this.props.list[this.state.current.index], this.state.current.index, index); this.setState({ current: null, target: null, propagation: false }); } /** * Clear all state. * * @memberof DragList */ clear = () => this.setState({ current: null, target: null, propagation: false }); /** * Main rendering function. * * @memberof DragList */ render = () => template(this); }
JavaScript
class NullConsole { log() { return null; } debug() { return null; } info() { return null; } warn() { return null; } error() { return null; } group() { return null; } groupEnd() { return null; } assert() { return null; } clear() { return null; } count() { return null; } dir() { return null; } dirxml() { return null; } exception() { return null; } groupCollapsed() { return null; } time() { return null; } timeEnd() { return null; } trace() { return null; } msIsIndependentlyComposed() { return null; } profile() { return null; } profileEnd() { return null; } select() { return null; } table() { return null; } }
JavaScript
class Payments extends Component { constructor() { super(); this.state = { showView: false, show: false, // Currently are dummy data FixedPayments: [{ PaymentType: "Rent", Amount: 240, StartDate: "15/03", EndDate: "15/12", Frequency: "Monthly", Contributors: ["Misty", "Brock"] }, { PaymentType: "WiFi", Amount: 100, StartDate: "15/03", EndDate: "15/12", Frequency: "Monthly", Contributors: ["Misty", "Brock", "Samuel"] }], VariablePayments: [{ PaymentType: "Water", Amount: 140, StartDate: "15/03", EndDate: "15/12", Frequency: "Monthly", Contributors: ["Misty", "Brock"] }, { PaymentType: "Electricity", Amount: 100, StartDate: "15/03", EndDate: "15/12", Frequency: "Monthly", Contributors: ["Misty", "Brock", "Samuel"] }], currentPayment: { PaymentType: "", Amount: 0, StartDate: "", EndDate: "", Frequency: "", Contributors: ["", ""] } } } //Methods for opening new payment component _handleOpen = () => { this.setState({ show: true }) } _handleClose = () => { this.setState({ show: false }) } //Methods for opening view payment component _handleOpenView = () => { this.setState({ showView: true }) } _handleCloseView = () => { this.setState({ showView: false }) } _handleEdit = () => { this.setState({ show: true, showView: false }) } _handleTableClick = (payment) => { this.setState({ currentPayment: payment }, () => this._handleOpenView()) } render() { const FixedPaymentsHtml = []; const VariablePaymentsHtml = [] this.state.FixedPayments.forEach( PaymentData => { FixedPaymentsHtml.push( <PaymentModule Payment={PaymentData} onTableClick={this._handleTableClick}/> ) } ) this.state.VariablePayments.forEach( PaymentData => { VariablePaymentsHtml.push( <PaymentModule Payment={PaymentData} onTableClick={this._handleTableClick}/> ) } ) return ( <div className="PaymentPage"> <table className="PaymentTable"> <tr> <td colSpan="2" className="PaymentPageTitle"> <span className="PaymentPageTitle"> <h2 className="PaymentsTitle">Payments</h2> </span> <span className="NewPaymentButton" onClick={this._handleOpen}> <button className="NewPaymentButton"> Add new </button> </span> <NewPayment onClose={this._handleClose} show={this.state.show} /> </td> </tr> <tr> <td> <h4 className="Subtitle"> Fixed </h4> </td> <td> <h4 className="Subtitle"> Variable </h4> </td> </tr> <tr> <td> {FixedPaymentsHtml} </td> <td> {VariablePaymentsHtml} </td> <ViewPayment onCloseView={this._handleCloseView} showView={this.state.showView} onEdit={this._handleEdit} payment={this.state.currentPayment}/> </tr> </table> </div> ) } }
JavaScript
class GameImage{ /** * Loads an image from a file and makes it an html img. * @param {string} name - The name of the image file to be loaded, without file extension. * @return {boolean} True if the image file was found, otherwise false. */ static LoadImage(name){ let returnValue = false; if(name in JpgImages){ let img = document.createElement("img"); img.classList.add(name); img.src = JpgImages[name]; document.querySelector("canvas").appendChild(img); returnValue = true; } else if (name in PngImages){ let img = document.createElement("img"); img.classList.add(name); img.src = PngImages[name]; document.querySelector("canvas").appendChild(img); returnValue = true; } return returnValue; } }
JavaScript
class Radio extends ThreeButtonControl { /** * @inheritDoc */ constructor(...options) { super('radio', ...options); } /** * Sets whether control allows mixed values. * * @param {Boolean} [enabled=true] * Flag determining whether this option is enabled. * * @return {Control.<Radio>} */ allowMixed(enabled = true) { return this.setOption('allowMixed', enabled); } /** * @inheritDoc */ availableOptions() { let options = super.availableOptions(); options.allowMixed = false; options.columns = -1; options.disabled = ''; options.items = ''; options.mixed = ''; options.rows = -1; options.selected = -1; return options; } /** * Creates a new result object for the control. * * @return {RadioResult} */ getResult() { return new RadioResult(this); } /** * Sets the number of columns the items should fit into. * * @param {Number} [columns=0] * The amount of columns to set. * * @return {Control.<Radio>} */ setColumns(columns = 0) { return this.setOption('columns', columns ? columns : null); } /** * Sets which items are disabled when the control opens. * * @param {Array} disabled * An array of item indices to set as disabled. * * @return {Control.<Radio>} */ setDisabled(disabled = []) { return this.setOption('disabled', disabled); } /** * Sets the items for the control. * * @param {Array} items * An array of item labels. * * @return {Control.<Radio>} */ setItems(items = []) { return this.setOption('items', items); } /** * Sets which items are in a mixed state when the control opens. * * @param {Array} mixed * An array of item indices to set as mixed. * * @return {Control.<Radio>} */ setMixed(mixed = []) { return this.setOption('mixed', mixed); } /** * Sets the number of rows the items should fit into. * * @param {Number} [rows=0] * The amount of rows to set. * * @return {Control.<Radio>} */ setRows(rows = 0) { return this.setOption('rows', rows ? rows : null); } /** * Sets which item is selected. * * @param {Number} selected * The item index to select. * * @return {Control.<Radio>} */ setSelected(selected = 0) { return this.setOption('selected', selected); } }
JavaScript
class Project extends Model { /** * @method getById * @author Ernesto Rojas <[email protected]> * @description This method get model name. * @returns {string} Model name. */ getName() { return 'Project'; } /** * @method build * @author Ernesto Rojas <[email protected]> * @description This method build the model. * @returns {mongoose.Model} Mongoose model. */ getSchema() { const opts = { timestamps: true, }; return new Schema( { name: { type: String, required: true, }, priority: { type: Number, required: true, }, description: { type: String, required: true, }, deliveryDate: { type: Date, required: true, }, }, opts, ); } }
JavaScript
class BattleManager { constructor (p1, p2) { if (!(p1 instanceof Player) || !(p2 instanceof Player)) { throw 'BattleManager constructor bad parameters' } this.p1 = p1 this.p2 = p2 // should always be a bot this.gameScore = new GameScore() this.nbRound = 0 this.done = false } /** * Launch the battle, and get the result * and store the score */ battle (uiHit1 = null, uiHit2 = null) { const hit1 = this.p1.play(uiHit1) const hit2 = this.p2.play(uiHit2, this.gameScore.playerScores[1].score) const res = BattleRPS.battle(hit1, hit2) let status1 = PlayerScore.STATUS_EQUALITY let status2 = PlayerScore.STATUS_EQUALITY if (res === 1) { status1 = PlayerScore.STATUS_WON status2 = PlayerScore.STATUS_LOST } else if (res === 2) { status1 = PlayerScore.STATUS_LOST status2 = PlayerScore.STATUS_WON } const scores = [ { hit: hit1, status: status1 }, { hit: hit2, status: status2 } ] // register scores for player1 and player2 this.gameScore.registerNewScores(scores[0], scores[1]) this.nbRound++ this.checkGameState() return scores } /** * check if their is a winner after a round * and stop the game if their is one winner */ checkGameState () { const maxWonRounds = this.gameScore.getMaxWonRounds() if (maxWonRounds > BattleManager.ROUNDS_NUMBER) { throw 'BattleManager should already stop the game and setup a winner' } else if (maxWonRounds === BattleManager.ROUNDS_NUMBER) { if (this.gameScore.playerScores[0].countWonRounds() === BattleManager.ROUNDS_NUMBER) { this.p1.winner = true } else { this.p2.winner = true } this.done = true } } /** * winner getter * @return Player the winner */ get winner () { if (this.p1.winner) { return this.p1 } else if (this.p2.winner) { return this.p2 } else { return null } } }
JavaScript
class ConfigParser extends AwesomeUtils.Parser.AbstractParser { constructor() { super(); this[$ORIGIN] = null; this[$DEFAULT_CONDITIONS] = ""; } get origin() { return this[$ORIGIN]; } get defaultConditions() { return this[$DEFAULT_CONDITIONS]; } isPathCharacter(c) { return this.isLetter(c) || this.isDigit(c) || c==="." || c==="_" || c==="$" || c==="-"; } isQuoteCharacter(c) { return c==="\"" || c==="'"; } isAssignmentCharacter(c) { return c===":" || c==="="; } popJSONText() { let braces = 0; let quoting = null; let keystart = false; let keyend = false; let text = ""; while (this.pos<this.content.length) { let next2 = this.peek(2); let next = this.pop(); if (next===undefined) break; if (!quoting && next==="{") { braces += 1; keystart = true; } else if (!quoting && next==="}") { braces -= 1; } else if (!quoting && next===",") { keystart = true; } else if (keystart && !this.isSpace(next) && !this.isNewLine(next)) { if (!this.isQuoteCharacter(next)) text += "\""; keystart = false; keyend = true; } else if (keyend && (this.isSpace(next) || next===":" || next==="\"" || next==="'")) { if (!this.isQuoteCharacter(next)) text += "\""; keyend = false; } else if (!quoting && this.isQuoteCharacter(next) && this.previous()!=="\\") { quoting = next; } else if (quoting && next===quoting) { quoting = null; } else if (!quoting && next==="[") { this.back(); next = this.popArrayText(); } else if (!quoting && (next==="#" || next2==="//" || next2==="/*")) { this.back(); this.parseComment(); next = null; } if (next) text += next; if (braces===0) break; } return text; } popArrayText() { let brackets = 0; let quoting = null; let text = ""; while (this.pos<this.content.length) { let next2 = this.peek(2); let next = this.pop(); if (next===undefined) break; if (!quoting && next==="[") { brackets += 1; } else if (!quoting && next==="]") { brackets -= 1; } else if (!quoting && this.isQuoteCharacter(next) && this.previous()!=="\\") { quoting = next; } else if (quoting && next===quoting) { quoting = null; } else if (!quoting && next==="{") { this.back(); next = this.popJSONText(); } else if (!quoting && (next==="#" || next2==="//" || next2==="/*")) { this.back(); this.parseComment(); next = null; } if (next) text += next; if (brackets===0) break; } return text; } parseComment() { let next2 = this.peek(2); let next = this.peek(); let starting = next==="#" && "#" || next2==="//" && "//" || next2==="/*" && "/*" || null; if (!starting) this.error("Expected comment"); this.pop(starting.length); let text = ""; while (this.pos<this.content.length) { next2 = this.peek(2); next = this.peek(); if (next===undefined) break; if (starting==="#" && this.isNewLine(next)) { this.pop(); break; } else if (starting==="//" && this.isNewLine(next)) { this.pop(); break; } else if (starting==="/*" && next2==="*/") { this.pop(2); break; } else { text == this.pop(); } } } parseKeyValue(root) { let key = this.parseKey(); if (!key) this.error("Empty key in key/value."); this.popSpace(); let next = this.peek(); if (next==="{") { let pos = this.pos; let json = this.popJSONText(); try { let obj = JSON.parse(json); if (obj===undefined || obj===null) obj = null; AwesomeUtils.Object.set(root,key,obj); if (this.peek()===",") this.pop(); } catch (ex) { this.error("JSON parsing error",pos); } } else if (next==="[") { let pos = this.pos; let json = this.popArrayText(); try { let obj = JSON.parse(json); if (obj===undefined || obj===null) obj = null; AwesomeUtils.Object.set(root,key,obj); if (this.peek()===",") this.pop(); } catch (ex) { this.error("JSON parsing error",pos); } } else { let value = this.parseValue(); if (value===undefined) this.error("Empty value in key/value."); AwesomeUtils.Object.set(root,key,value); } } parseKey() { let key = ""; let mustBeAssignment = false; while (this.pos<this.content.length) { let next = this.pop(); if (next===undefined) break; if (!mustBeAssignment && this.isPathCharacter(next)) { key += next; } else if (!mustBeAssignment && this.isSpace()) { this.popSpace(); mustBeAssignment = true; } else if (this.isAssignmentCharacter(next)) { break; } else { this.error("Invalid character '"+next+"' in key/value key."+key); } } return key; } parseValue() { let value = ""; let quoting = null; let quoted = false; while (this.pos<this.content.length) { let next2 = this.peek(2); let next = this.pop(); if (next===undefined) break; if (this.isNewLine(next)) { break; } else if (quoted && !quoting && next!==",") { this.error("Invalid characters after quote."); } else if (!quoting && this.isQuoteCharacter(next) && this.previous()!=="\\") { quoting = next; quoted = true; } else if (quoting && next===quoting) { quoting = null; } else if (!quoting && (next==="#" || next2==="//" || next2==="/*")) { this.back(); this.parseComment(); if (next==="#" || next2==="//") break; // comments run to eol, which is end of value for us. next = null; } if (next) value += next; } if (value.endsWith(",")) value = value.slice(0,-1); value = this.transformValue(value); return value; } parseRootJSON(root) { let pos = this.pos; let json = this.popJSONText(); try { let obj = JSON.parse(json); if (obj===undefined || obj===null) return; AwesomeUtils.Object.extend(root,obj); } catch (ex) { this.error("JSON parsing error",pos); } } parseRootConditions() { let quoting = null; this.pop(); let text = ""; while (this.pos<this.content.length) { let next2 = this.peek(2); let next = this.pop(); if (next===undefined) break; if (!quoting && next==="]") { break; } else if (!quoting && this.isQuoteCharacter(next) && this.previous()!=="\\") { quoting = next; } else if (quoting && next===quoting) { quoting = null; } else if (!quoting && (next==="#" || next2==="//" || next2==="/*")) { this.back(); this.parseComment(); next = null; } if (next) text += next; } return text || null; } parseRoot() { let root = {}; let conditions = this.defaultConditions; let sources = []; while (this.pos<this.content.length) { let next2 = this.peek(2); let next = this.peek(); if (next===undefined) break; if (this.isWhiteSpace(next)) { this.popWhiteSpace(); } else if (next==="#" || next2==="//" || next2==="/*") { this.parseComment(); } else if (next==="{") { this.parseRootJSON(root); } else if (next==="[") { if (Object.keys(root).length>0) { sources.push(new ConfigSource(this.origin,root,conditions||"")); } conditions = this.parseRootConditions() || this.defaultConditions; root = {}; } else if (this.isPathCharacter(next)) { this.parseKeyValue(root); } } if (Object.keys(root).length>0) { sources.push(new ConfigSource(this.origin,root,conditions||"")); } return sources; } parse(origin,content,defaultConditions=null) { super.parse(content); this[$ORIGIN] = origin; this[$DEFAULT_CONDITIONS] = defaultConditions; return this.parseRoot(); } transformValue(value) { value = value.trim(); if (value===null) return null; if (value==="null") return null; if (value===true) return true; if (value===false) return false; if (value==="true") return true; if (value==="false") return false; if (value==="0") return 0; if (value.match(/^[+-]?[\d]+$/)) return parseInt(value); if (value.match(/^[+-]?[\d]+(\.\d+)$/)) return parseFloat(value); if (value.startsWith("\"") && value.endsWith("\"")) return value.slice(1,-1); if (value.startsWith("'") && value.endsWith("'")) return value.slice(1,-1); return value; } error(msg,pos=null) { try { super.error(msg,pos); } catch (ex) { ex.message = ex.message.replace(/Error\sat/,"Error in "+this.origin+" at"); throw ex; } } }
JavaScript
class ParkrunDataNotAvailableError extends Error { constructor(reqName) { const message = `no data available for ${reqName}`; super(message); this.name = this.constructor.name; } }
JavaScript
class Router extends React.Component { render () { return ( <HashRouter> <div> <Route path = "/" component = {Home} exact = {true} /> <Route path = "/acerca" component = {Acerca} /> </div> </HashRouter> ) } }
JavaScript
class HeaderSecondary extends Component { view() { return <ul className="Header-controls">{listItems(this.items().toArray())}</ul>; } /** * Build an item list for the controls. * * @return {ItemList} */ items() { const items = new ItemList(); items.add( 'help', <LinkButton href="https://docs.flarum.org/troubleshoot.html" icon="fas fa-question-circle" external={true} target="_blank"> {app.translator.trans('core.admin.header.get_help')} </LinkButton> ); items.add('session', SessionDropdown.component()); return items; } }
JavaScript
class Teleportation extends Feature { constructor() { super(); } dispose() { } }
JavaScript
class PlayerGoToJail extends BaseAction { constructor() { super(); } /** * Sends the player to the Jail tile and sets their * state as jailed. * * @override * @param {GameManager} game The game manager instance. * @param {Player} player The player instance. */ do(game, player) { // player is sent to jail and is given usual restrictions for jailed players console.log(player); } }
JavaScript
class BesluitPlugin { /** * Handles the incoming events from the editor dispatcher. Responsible for generating hint cards. * * @method execute * * @param {string} hrId Unique identifier of the state in the HintsRegistry. Allows the * HintsRegistry to update absolute selected regions based on what a user has entered in between. * @param {Array} rdfaBlocks Set of logical blobs of content which may have changed. Each blob is * either has a different semantic meaning, or is logically separated (eg: a separate list item). * @param {Object} hintsRegistry Keeps track of where hints are positioned in the editor. * @param {Object} editor Your public interface through which you can alter the document. * * @public */ controller; get name() { return 'besluit'; } initialize(controller) { this.controller = controller; controller.registerCommand( new InsertArticleCommand(controller._rawEditor._model) ); controller.registerCommand( new InsertTitleCommand(controller._rawEditor._model) ); controller.registerCommand( new MoveArticleCommand(controller._rawEditor._model) ); controller.registerCommand( new RecalculateArticleNumbersCommand(controller._rawEditor._model) ); controller.registerWidget({ componentName: 'besluit-plugin-card', identifier: 'besluit-plugin/card', desiredLocation: 'insertSidebar', }); controller.registerWidget({ componentName: 'besluit-context-card', identifier: 'besluit-context-plugin/card', desiredLocation: 'sidebar', }); } }
JavaScript
class SpeechBox extends Component { constructor(props) { super(props); this.aHalfWidth = typeof this.props.anchorBaseWidth === 'undefined' ? 8 : this.props.anchorBaseWidth; this.state = { aTop: false, aBottom: false, aLeft: false, aRight: false }; } set cpoint(point) { this._cpoint = point; this.calcAnchorDirection(); } get cpoint() { return this._cpoint; } beforeMount() { typeof this.props.onRef === 'function' && this.props.onRef(undefined); } afterMount() { typeof this.props.onRef === 'function' && this.props.onRef(this); } beforeUpdate(nextProps) { this.aHalfWidth = typeof nextProps.anchorBaseWidth === 'undefined' ? 8 : nextProps.anchorBaseWidth; } render() { this.cpoint = this.props.cpoint; return ( <g id={this.props.id || ''} class='sc-speech-box' transform={`translate(${this.props.x},${this.props.y})`}> {this.props.shadow && UiCore.dropShadow('sc-speech-box-drop-shadow')} <path class='sc-speech-box-path' d={this.getBoxPath()} fill={this.props.bgColor} fill-opacity={typeof this.props.fillOpacity === 'undefined' ? 1 : this.props.fillOpacity} filter={this.props.shadow ? 'url(#sc-speech-box-drop-shadow)' : ''} stroke={this.props.strokeColor} stroke-width={typeof this.props.strokeWidth === 'undefined' ? 1 : this.props.strokeWidth } stroke-opacity={typeof this.props.strokeOpacity === 'undefined' ? 1 : this.props.strokeOpacity} shape-rendering='geometricPrecision' vector-effect='non-scaling-stroke' /> </g> ); } getBoxPath() { const cr = this.props.cornerRadius || 0; let d = ['M', cr, 0]; let topPath, bottomPath, leftPath, rightPath, cpoint = new Point(this.cpoint.x - this.props.x, this.cpoint.y - this.props.y); if (this.state.aTop) { topPath = ['L', cpoint.x - this.aHalfWidth, 0, cpoint.x, cpoint.y, cpoint.x + this.aHalfWidth, 0, this.props.width, 0]; if (cr) { topPath = ['L', cpoint.x - this.aHalfWidth, 0, cpoint.x, cpoint.y, cpoint.x + this.aHalfWidth, 0, this.props.width - cr, 0, 'A', cr, cr, 0, 0, 1, this.props.width, cr]; } } else { topPath = ['L', this.props.width, 0]; if (cr) { topPath = ['L', this.props.width - cr, 0, 'A', cr, cr, 0, 0, 1, this.props.width, cr]; } } if (this.state.aRight) { rightPath = ['L', this.props.width, cpoint.y - this.aHalfWidth, cpoint.x, cpoint.y, this.props.width, cpoint.y + this.aHalfWidth, this.props.width, this.props.height]; if (cr) { rightPath = ['L', this.props.width, cpoint.y - this.aHalfWidth, cpoint.x, cpoint.y, this.props.width, cpoint.y + this.aHalfWidth, this.props.width, this.props.height - cr, 'A', cr, cr, 0, 0, 1, this.props.width - cr, this.props.height]; } } else { rightPath = ['L', this.props.width, this.props.height]; if (cr) { rightPath = ['L', this.props.width, this.props.height - cr, 'A', cr, cr, 0, 0, 1, this.props.width - cr, this.props.height]; } } if (this.state.aBottom) { bottomPath = ['L', cpoint.x + this.aHalfWidth, this.props.height, cpoint.x, cpoint.y, cpoint.x - this.aHalfWidth, this.props.height, 0, this.props.height]; if (cr) { bottomPath = ['L', cpoint.x + this.aHalfWidth, this.props.height, cpoint.x, cpoint.y, cpoint.x - this.aHalfWidth, this.props.height, cr, this.props.height, 'A', cr, cr, 0, 0, 1, 0, this.props.height - cr]; } } else { bottomPath = ['L', 0, this.props.height]; if (cr) { bottomPath = ['L', cr, this.props.height, 'A', cr, cr, 0, 0, 1, 0, this.props.height - cr]; } } if (this.state.aLeft) { leftPath = ['L', 0, cpoint.y + this.aHalfWidth, cpoint.x, cpoint.y, 0, cpoint.y - this.aHalfWidth, 0, 0]; if (cr) { leftPath = ['L', 0, cpoint.y + this.aHalfWidth, cpoint.x, cpoint.y, 0, cpoint.y - this.aHalfWidth, 0, cr, 'A', cr, cr, 0, 0, 1, cr, 0]; } } else { leftPath = ['L', 0, 0]; if (cr) { leftPath = ['L', 0, cr, 'A', cr, cr, 0, 0, 1, cr, 0]; } } if (this.state.aTop && this.state.aRight) { topPath = ['L', this.props.width - (2 * this.aHalfWidth), 0, cpoint.x, cpoint.y]; rightPath = ['L', this.props.width, (2 * this.aHalfWidth), this.props.width, this.props.height]; if (cr) { rightPath = ['L', this.props.width, (2 * this.aHalfWidth), this.props.width, this.props.height - cr, 'A', cr, cr, 0, 0, 1, this.props.width - cr, this.props.height]; } } if (this.state.aTop && this.state.aLeft) { topPath = ['L', cpoint.x, cpoint.y, (2 * this.aHalfWidth), 0, this.props.width, 0]; leftPath = ['L', 0, (2 * this.aHalfWidth), cpoint.x, cpoint.y]; if (cr) { topPath = ['L', this.props.width - cr, 0, 'A', cr, cr, 0, 0, 1, this.props.width, cr]; leftPath = ['L', 0, (2 * this.aHalfWidth), cpoint.x, cpoint.y, cr + this.aHalfWidth, 0]; } } if (this.state.aBottom && this.state.aRight) { bottomPath = ['L', cpoint.x, cpoint.y, this.props.width - (2 * this.aHalfWidth), this.props.height, 0, this.props.height]; rightPath = ['L', this.props.width, this.props.height - (2 * this.aHalfWidth), cpoint.x, cpoint.y]; if (cr) { bottomPath = ['L', cpoint.x, cpoint.y, this.props.width - (2 * this.aHalfWidth), this.props.height, cr, this.props.height, 'A', cr, cr, 0, 0, 1, 0, this.props.height - cr]; } } if (this.state.aBottom && this.state.aLeft) { bottomPath = ['L', (2 * this.aHalfWidth), this.props.height, cpoint.x, cpoint.y]; leftPath = ['L', cpoint.x, cpoint.y, 0, this.props.height - (2 * this.aHalfWidth), 0, 0]; if (cr) { leftPath = ['L', cpoint.x, cpoint.y, 0, this.props.height - (2 * this.aHalfWidth), 0, cr, 'A', cr, cr, 0, 0, 1, cr, 0]; } } d.push(...topPath, ...rightPath, ...bottomPath, ...leftPath, 'Z'); return d.join(' '); } calcAnchorDirection() { const cr = this.props.cornerRadius || 0; this.state.aTop = this.props.y > (this.cpoint.y - this.aHalfWidth - cr) ? true : false; this.state.aBottom = this.cpoint.y > (this.props.y + this.props.height - this.aHalfWidth - cr) ? true : false; this.state.aRight = this.cpoint.x > (this.props.x + this.props.width - this.aHalfWidth - cr) ? true : false; this.state.aLeft = this.props.x > (this.cpoint.x - this.aHalfWidth - cr) ? true : false; } }
JavaScript
class InvalidInputError extends Error { /** * Constructor for InvalidInputError * @param message - error message */ constructor(message) { super(message); this.name = "InvalidInputError"; } }
JavaScript
class InvalidDataURLError extends Error { /** * Constructor for InvalidDataURLError */ constructor() { super("The dataURL is not set"); this.name = "InvalidDataURLError"; } }
JavaScript
class portfolioRemove { constructor() { microsoftTeams.initialize(); microsoftTeams.getContext((context) => { theme_1.TeamsTheme.fix(context); microsoftTeams.settings.setValidityState(true); }); microsoftTeams.settings.registerOnRemoveHandler((removeEvent) => { removeEvent.notifySuccess(); }); } }
JavaScript
class LocalStorage { constructor(prefix) { this.prefix = prefix; } static isSupported() { return __awaiter(this, void 0, void 0, function* () { return Promise.resolve(Boolean(typeof window !== 'undefined') && Boolean(window.localStorage)); }); } get(key) { return __awaiter(this, void 0, void 0, function* () { const value = localStorage.getItem(this.getPrefixedKey(key)); if (!value) { if (typeof defaultValues[key] === 'object') { return JSON.parse(JSON.stringify(defaultValues[key])); } else { return defaultValues[key]; } } else { try { return JSON.parse(value); } catch (jsonParseError) { return value; // TODO: Validate storage } } }); } set(key, value) { return __awaiter(this, void 0, void 0, function* () { if (typeof value === 'string') { return localStorage.setItem(this.getPrefixedKey(key), value); } else { return localStorage.setItem(this.getPrefixedKey(key), JSON.stringify(value)); } }); } delete(key) { return __awaiter(this, void 0, void 0, function* () { return Promise.resolve(localStorage.removeItem(this.getPrefixedKey(key))); }); } getPrefixedKey(key) { return this.prefix ? `${this.prefix}-${key}` : key; } }
JavaScript
class HighChartsBar extends Component { constructor(props) { super(props); this.chart = React.createRef(); this.state = { options: null, }; this.nbBars = 20; } componentDidMount() { this.loadAll(); } componentDidUpdate(prevProps) { if (this.props.data !== prevProps.data) { this.loadAll(); } } loadAll() { let localData = []; if (this.props.data.entries) { localData = this.props.data.entries.filter(item => item.value).map(item => ({ label: item.value, count: item.count, label_normalized: item.value.normalize('NFD').toLowerCase().replace(/[\u0300-\u036f]/g, '').replace('"', '') })); } const r = {}; localData.forEach((o) => { r[o.label_normalized] = { count: (r[o.label_normalized] ? r[o.label_normalized].count + o.count : o.count), label: (r[o.label_normalized] ? r[o.label_normalized].label : o.label), }; }); let result = Object.keys(r).map(k => ( { label: r[k].label, count: r[k].count } )); result = result.sort((a, b) => b.count - a.count); const labels = []; const values = []; result.forEach((e) => { if (labels.length < this.nbBars) { labels.push(e.label); values.push(e.count); } }); const data = { labels, values, }; const style = { 'font-family': 'Inter UI' }; if (this.props.height) { style.height = this.props.height; } const unit = 'unité'; const options = { chart: { type: 'bar', style, }, credits: { enabled: false, }, title: { text: '', }, subtitle: { text: (this.props.subtitle) ? (this.props.subtitle) : '', }, xAxis: { minorGridLineWidth: 0, gridLineWidth: 0, lineWidth: 0, tickWidth: 0, categories: data.labels, labels: { style: { color: '#000000' }, align: 'right', 'font-size': '1.2rem', x: -10, }, }, yAxis: { gridLineWidth: 0, lineWidth: 0, tickWidth: 0, minorGridLineWidth: 0, title: { text: '' }, labels: { enabled: false }, }, legend: { hide: true, enabled: false, // reversed: true }, plotOptions: { series: { stacking: 'normal', pointPadding: 0, // groupPadding: 0.1, dataLabels: { enabled: true, align: 'right', // textAlign: 'right', x: 0, style: { color: '#000000' }, }, }, }, series: [{ color: '#FDD85E', name: unit, data: data.values, borderRadiusTopLeft: '80%', borderRadiusTopRight: '80%', borderRadiusBottomLeft: '80%', borderRadiusBottomRight: '80%', }], exporting: { filename: this.props.filename, buttons: { contextButton: { enabled: false, }, }, chartOptions: { title: { text: this.props.filename, }, credits: { enabled: true, text: "Source : scanR, Moteur de la Recherche et de l'Innovation", }, }, }, }; this.setState({ options }); } render() { return ( <div> { this.state.options !== null ? ( <div> <hr className={classes.HorizontalBar} /> <div className="pl-4"> <HighchartsReact highcharts={Highcharts} options={this.state.options} ref={this.chart} /> </div> <hr className={classes.HorizontalBar} /> <ShareComponent language={this.props.language} filename={this.props.filename} chart={this.chart} /> </div> ) : <div>Loading...</div> } </div> ); } }
JavaScript
class GameOfLife { constructor(width, height) { this.rows = height / 10; this.cols = width / 10; this.generation = this.initGeneration(); } /** * Creates an initial generation. */ initGeneration(sparseness=0.4) { const cells = createMatrix(this.rows, this.cols); let population = 0; for (const row of cells) { for (let i=0; i < row.length; i++) { row[i] = random() < sparseness; if (row[i]) population++; } } return { cells, population, year: 1 }; } /** * Play the game of life, evolve to next generation and return it */ evolve() { const { cells, year } = this.generation; const nextCells = createMatrix(this.rows, this.cols); let population = 0; for (let r=0; r < this.rows; r++) { for (let c=0; c < this.cols; c++) { const liveNeighbors = getLiveNeighbors(r, c, cells); nextCells[r][c] = (cells[r][c] ? (liveNeighbors == 2 || liveNeighbors == 3) : (liveNeighbors == 3)); if (nextCells[r][c]) population++; } } this.generation = { cells: nextCells, population, year: year + 1 }; return this.generation; } }
JavaScript
class Planets extends React.Component { constructor(props){ super(props); this.state = { planets: [ { name: "Mercurio", description: "Mercúrio é um metal líquido à temperatura ambiente, conhecido desde os tempos da Grécia Antiga.Também é conhecido como hidrargírio,[1] hidrargiro,[1] azougue[2] e prata-viva, entre outras denominações.", img_url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Mercury_in_color_-_Prockter07-edit1.jpg/1200px-Mercury_in_color_-_Prockter07-edit1.jpg", text: "Um texto do Planeta Mercurio", link: "https://pt.wikipedia.org/wiki/Merc%C3%BArio" }, { name: "Venus", description:"Vénus é considerado um planeta do tipo terrestre ou telúrico, chamado com frequência de planeta irmão da Terra", img_url:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQROJvvc_gBXgwyxLW0z_Fl6X0FEgqvcK4IzSq3bShHDDVqGdgJyfbgFzw9W8ElFZy5RtY&usqp=CAU", text:"Um texto do planeta Venus" }, { name: "Plutao", description:"Plutão é considerado um planeta do tipo terrestre ou telúrico, chamado com frequência de planeta irmão da Terra", img_url:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQROJvvc_gBXgwyxLW0z_Fl6X0FEgqvcK4IzSq3bShHDDVqGdgJyfbgFzw9W8ElFZy5RtY&usqp=CAU", } ] } } /* funçao para remover planeta*/ removeLast = () => { let new_planets = [...this.state.planets] new_planets.pop() this.setState(state => ({ planets: new_planets })) } /* funçao para duplicar(adicionar) um planeta*/ duplicateLastPlanet = () => { let last_planet = this.state.planets[this.state.planets.length -1] this.setState(state => ({ planets: [...this.state.planets, last_planet] })) } render() { return ( <> <h3>Planets List</h3> <button onClick={this.removeLast}>Remove Last</button> <button onClick={this.duplicateLastPlanet}>Duplicate Last Planet</button> <hr /> {this.state.planets.map(() => <Planet id={Planet.id} name={Planet.name} description={Planet.description} img_url= {Planet.img_url} link= {Planet.link} //key={index} /> )} </> ) } }
JavaScript
class VtexAccount { constructor() { /** * Version * @type {String} */ this.version = '0.0.2'; /** * Package name * @type {String} */ this.name = '@VtexAccount'; /** * Extend public methods * @type {Method} */ this.globalHelpers.extend(VtexAccount.prototype, vtexAccountMethods); } }
JavaScript
class Cloudant { /** * Creates a cloudant db connection. * @constructor */ constructor() { this.cloudant = new cloudant({ account: process.env.CLOUDANT_ACCOUNT, key: process.env.CLOUDANT_API_KEY, password: process.env.CLOUDANT_PASSWORD }); this.mass_db = this.cloudant.db.use("weight"); this.user_db = this.cloudant.db.use("users"); this.steps_db = this.cloudant.db.use("steps"); } /** * Returns all users registered. * @returns {Array} All users registered in the db. */ getAllUsers() { return new Promise((resolve,reject) => { this.user_db.list({ include_docs:true }, (err, data) => { if(err) reject(err); resolve(data.rows); }); }); } /** * Register user into database. * @param {Object} doc A formatted doc for cloudant to insert a user * @returns {Object} Response from cloudant. */ addUser(doc) { //TODO: Add check to see if user, already exists. return new Promise((resolve,reject) => { this.user_db.insert(doc, (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Retrieves a user from the database. * @param {Object} query A formatted query for cloudant to retrieve a user. * @returns {Object} Response from cloudant. */ getUser(query) { return new Promise((resolve,reject) => { this.user_db.find(query, (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Retrieves a user from the database. * @param {Object} user A user that you want to delete from user's db * @returns {Object} Response from cloudant. */ deleteUser(user) { return new Promise((resolve,reject) => { this.user_db.destroy(user["_id"], user["_rev"], (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Insert steps into db. * @param {Object} doc A formatted doc for cloudant to insert steps for a given user * @returns {Object} Response from cloudant. */ insertSteps(doc) { return new Promise((resolve,reject) => { this.steps_db.insert(doc, (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Delete steps from steps db. * @param {Object} doc A formatted doc for cloudant to insert steps for a given user * @returns {Object} Response from cloudant. */ deleteSteps(doc) { return new Promise((resolve,reject) => { this.steps_db.destroy(doc["_id"], doc["_rev"], (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Insert steps in bulk into db. * @param {Array} docs An array of formatted doc for cloudant to insert steps for a given user * @returns {Object} Response from cloudant. */ insertBulkSteps(docs) { return new Promise((resolve,reject) => { this.steps_db.bulk({ docs }, (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Insert weight in bulk into db. * @param {Array} docs An array of formatted doc for cloudant to insert weight for a given user * @returns {Object} Response from cloudant. */ insertBulkWeight(docs) { return new Promise((resolve,reject) => { this.mass_db.bulk({ docs }, (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Returns steps for a given user. * @param {Object} query A formatted query for cloudant to get steps for a given user * @returns {Array} Returns all steps for a given user. */ getSteps(query) { return new Promise((resolve,reject) => { this.steps_db.find(query, (err, data) => { if(err) reject(err); data = (data ? data.docs : []); resolve(data); }); }); } /** * Insert weight into db. * @param {Object} doc A formatted doc for cloudant to insert weight for a given user * @returns {Object} Response from cloudant. */ insertMass(doc) { return new Promise((resolve,reject) => { this.mass_db.insert(doc, (err, data) => { if(err) reject(err); resolve(data); }); }); } /** * Returns weight for a given user. * @param {Object} query A formatted query for cloudant to get weight for a given user * @returns {Array} Returns all weight for a given user. */ getMass(query) { return new Promise((resolve,reject) => { this.mass_db.find(query, (err, data) => { if(err) reject(err); data = (data ? data.docs : []); resolve(data); }); }); } /** * Delete weight doc from database * @param {Object} doc A formatted doc for cloudant to insert steps for a given user * @returns {Object} Response from cloudant. */ deleteMass(doc) { return new Promise((resolve,reject) => { this.mass_db.destroy(doc["_id"], doc["_rev"], (err, data) => { if(err) reject(err); resolve(data); }); }); } }
JavaScript
class Upselling { constructor(client) { this.client = client; } /** * Get available seats in different fare classes * * @param {Object} params * @return {Promise.<Response,ResponseError>} a Promise * * ```js * amadeus.shopping.flightOffers.upselling.post(body); * ``` */ post(params = {}) { return this.client.post('/v1/shopping/flight-offers/upselling', params); } }
JavaScript
class AutoComplete extends React.PureComponent { /** * Handle state changes inside of Downshift component. * We need it to not close menu after element is clicked in multi-select. * * @param {object} state * @param {object} changes * @returns {object} */ stateReducer = (state, changes) => { switch (changes.type) { case Downshift.stateChangeTypes.touchStart: case Downshift.stateChangeTypes.blurInput: case Downshift.stateChangeTypes.mouseUp: return { ...changes, inputValue: this.props.inputValue } default: return changes } } /** * Check if component is disabled. * * @param {object} [props] * @param {boolean} [props.disabled] * @param {boolean} [props.readOnly] * @returns {boolean} */ isDisabled (props) { const { disabled, readOnly } = props || this.props return disabled || readOnly } /** * Get props which should be passed through our components below Downshift. * * @param {object} data * @returns {object} */ getStateProps (data) { const { footer, icon, options, buildItemId, renderItem, onBlur, id } = this.props // Compose function to get input props const getInputProps = composeInputProps(data, { onFocus: this.focus, onBlur }) return { ...data, ...{ footer, icon, options, buildItemId, renderItem, getInputProps, id } } } focus = (...args) => { const { onFocus, openOnFocus } = this.props if (this.downshift && openOnFocus && !this.isDisabled()) { this.downshift.openMenu() } if (onFocus) { onFocus(...args) } } /** * Handle item (un)selection. * * @param {object} item */ select = (item) => { const { onChoose } = this.props // Don't handle it when it's disabled if (this.isDisabled()) { return } // Handle simple selection for single select-box if (onChoose) { onChoose(item) } } /** * Build external input with correct props. * * @param {object} data */ buildInput (data) { const { children, disabled, readOnly, name } = this.props const input = React.Children.only(children) const inputProps = data.getInputProps(input.props, data) if (disabled) { inputProps.disabled = disabled } if (readOnly) { inputProps.readOnly = readOnly } if (name != null) { inputProps.name = name } return React.cloneElement(input, inputProps) } /** * Render component in Downshift flow. * * @param {object} _data * @returns {React.Element} */ renderComponent = (_data) => { // Compose Downshift & our properties const data = this.getStateProps(_data) // Get required data to render component const { className } = this.props const { isOpen, options, icon } = data // Check if menu should be visible const open = isOpen && options.length > 0 // Build class name for wrapper const clsName = buildClassName(moduleName, className, { open, 'with-info': icon }) // Build menu component const menu = open ? <Menu {...data} /> : null // Render component return ( <div className={clsName}> {this.buildInput(data)} {menu} </div> ) } setDownshiftRef = ref => { this.downshift = ref } /** * Render Downshift component with our wrappers. * * @returns {React.Element} */ render () { const { id, icon, options, onChoose, buildItemId, renderItem, disabled, readOnly, children, onFocus, onBlur, onChange, ...passedProps } = this.props const idProps = {} if (id) { idProps.inputId = id idProps.id = 'container_' + id } return ( <Downshift {...idProps} ref={this.setDownshiftRef} stateReducer={this.stateReducer} onChange={this.select} selectedItem={null} disabled={this.isDisabled()} {...passedProps} > {this.renderComponent} </Downshift> ) } }
JavaScript
class AssemblerFactory { static getAssembler(DTOClass, EntityClass) { const AssemblerClasses = assembler_1.getAssemblers(DTOClass); if (AssemblerClasses) { const AssemblerClass = AssemblerClasses.get(EntityClass); if (AssemblerClass) { return new AssemblerClass(); } const keys = [...AssemblerClasses.keys()]; const keysWithParent = keys.filter((k) => k.prototype instanceof EntityClass); if (keysWithParent.length === 1) { return this.getAssembler(DTOClass, keysWithParent[0]); } } const defaultAssembler = new default_assembler_1.DefaultAssembler(DTOClass, EntityClass); // if its a default just assume the types can be converted for all types return defaultAssembler; } }
JavaScript
class SliderField extends PureComponent { input = ({input}) => { if (this.props.readonly && isRequired(input.value)) return null const {onChange, defaultValue, denormalize, normalize, format, parse = normalize, ...props} = this.props this.val = input.value this.value = isList(input.value) ? input.value : (isNumber(input.value) ? input.value : defaultValue) this.onChange = input.onChange return ( <Slider value={denormalize ? denormalize(this.value) : this.value} onChange={value => { input.onChange(value) isFunction(onChange) && onChange(parse ? parse(value) : value) }} {...props} /> ) } componentDidMount () { // Auto dispatch action to set min value if default value is out of min-max range, // because we cannot use initialValues when new slider is added in <Active.FieldsWithLevel />, // and need a way to detect changes to enable saving. // Only dispatchChangeOnMount if field is added for the first time. const {min, onChange, dispatchChangeOnMount} = this.props const valueToChange = this.value < min ? min : ((dispatchChangeOnMount && this.val === '') ? this.value : null) if (valueToChange == null) return this.onChange(valueToChange) onChange && onChange(valueToChange) } render = () => { const {name, disabled, normalize, format = normalize, parse = normalize, validate} = this.props return <Active.Field {...{name, disabled, normalize, format, parse, validate}} component={this.input}/> } }
JavaScript
class ServicesManager extends FeaturesManager { /** * Create a ServicesManager instance * @extends FeaturesManager * @param {string|undefined} arg_log_context - optional. * @param {LoggerManager} arg_logger_manager - logger manager object (optional). * @returns {nothing} */ constructor(arg_runtime, arg_log_context, arg_logger_manager) { super(arg_runtime, arg_log_context ? arg_log_context : context, arg_logger_manager) this.is_service_manager = true } /** * Get class name. * * @return {string} */ get_class() { return 'ServicesManager' } /** * Test if plugin is valid. * @param {Plugin} arg_plugin - plugin instance. * @returns {boolean} - given plugin is valid for this manager. */ plugin_is_valid(arg_plugin) { return arg_plugin.is_services_plugin } }
JavaScript
class InlineResponse2001DataDataPageList { /** * Constructs a new <code>InlineResponse2001DataDataPageList</code>. * @alias module:model/InlineResponse2001DataDataPageList * @class */ constructor() { } /** * Constructs a <code>InlineResponse2001DataDataPageList</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/InlineResponse2001DataDataPageList} obj Optional instance to populate. * @return {module:model/InlineResponse2001DataDataPageList} The populated <code>InlineResponse2001DataDataPageList</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new InlineResponse2001DataDataPageList(); if (data.hasOwnProperty('name')) obj.name = ApiClient.convertToType(data['name'], 'String'); if (data.hasOwnProperty('id')) obj.id = ApiClient.convertToType(data['id'], 'Number'); } return obj; } }
JavaScript
class Navbar extends React.Component { render() { return ( <header> <nav> <div className ="dropdown"> <button className="menu" aria-label="menu button">&#9776;</button> <div className="dropdown-content"> <Link to="/">Home</Link> <Link to="/projects">Projects</Link> <Link to="/contact">Contact</Link> <Link to="/about">About</Link> </div> </div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/projects">Projects</Link></li> <li><Link to="/contact">Contact</Link></li> <li><Link to="/about">About</Link></li> </ul> </nav> </header> ); } }
JavaScript
class Reviews { /** * *post reviews for a business *@param {any} req - request value - handles data coming from the user *@param {any} res - response value - this is the response gotten after interaction with the Api routes *@return {status} response object gotten *@memberof Businesses */ static postReview(req, res) { const { reviewer, message } = req.body; const businessId = parseInt(req.params.businessId, 10); businesses.forEach((business) => { if (business.id === businessId) { business.reviews.push({ reviewer, message }); res.status(201).json({ message: 'Review posted successfully', error: false }); } }); return res.status(404).send({ message: 'Business not found, no review posted', error: true }); } /** * *gets all reviews under a business *@param {any} req - request value - handles data coming from the user *@param {any} res - response value - this is the response gotten after interaction with the Api routes *@return {status} response object gotten *@memberof Businesses */ static getReview(req, res) { const businessId = parseInt(req.params.businessId, 10); businesses.forEach((business) => { if (business.id === businessId) { res.status(200).json(business.reviews); } }); return res.status(404).send({ message: 'Business not found, no review gotten', error: true }); } }
JavaScript
class Engineer extends Employee { constructor(firstName, lastName) { //super is a keyword that inherits from Employee super(firstName, lastName) this.github = `github.com/${firstName}`; } //methods getName() { return this.first + this.last } getRole() { return this.role = 'Engineer' } getEmail() { return this.first + this.last + '@mycompany.com' } getId() { return this.id } getGithub() { return this.github } }
JavaScript
class URDFLoader { // Cached mesh loaders static get STLLoader() { this._stlloader = this._stlloader || new THREE.STLLoader() return this._stlloader } static get DAELoader() { this._daeloader = this._daeloader || new THREE.ColladaLoader() return this._daeloader } static get TextureLoader() { this._textureloader = this._textureloader || new THREE.TextureLoader() return this._textureloader } /* Utilities */ // forEach and filter function wrappers because // HTMLCollection does not the by default static forEach(coll, func) { return [].forEach.call(coll, func) } static filter(coll, func) { return [].filter.call(coll, func) } // take a vector "x y z" and process it into // an array [x, y, z] static _processTuple(val) { if (!val) return [0, 0, 0] return val.trim().split(/\s+/g).map(num => parseFloat(num)) } // applies a rotation a threejs object in URDF order static _applyRotation(obj, rpy) { obj.rotateOnAxis(new THREE.Vector3(0,0,1), rpy[2]) obj.rotateOnAxis(new THREE.Vector3(0,1,0), rpy[1]) obj.rotateOnAxis(new THREE.Vector3(1,0,0), rpy[0]) } /* Public API */ // pkg: The equivelant of a ROS package:// directory // urdf: The URDF path in the directory // cb: Callback that is passed the model once loaded static load(pkg, urdf, cb, loadMeshCb, fetchOptions) { const path = `${pkg}/${urdf}` fetch(path, fetchOptions) .then(res => res.text()) .then(data => this.parse(pkg, data, cb, loadMeshCb)) } static parse(pkg, content, cb, loadMeshCb) { cb(this._processUrdf(pkg, content, loadMeshCb || this.defaultMeshLoader)) } // Default mesh loading function static defaultMeshLoader(path, ext, done) { if (/\.stl$/i.test(path)) URDFLoader.STLLoader.load(path, geom => { const mesh = new THREE.Mesh() mesh.geometry = geom done(mesh) }) else if (/\.dae$/i.test(path)) URDFLoader.DAELoader.load(path, dae => done(dae.scene)) else console.warn(`Could note load model at ${path}:\nNo loader available`) } /* Private Functions */ // Process the URDF text format static _processUrdf(pkg, data, loadMeshCb) { const parser = new DOMParser() const urdf = parser.parseFromString(data, 'text/xml') const res = [] URDFLoader.forEach(urdf.children, n => res.push(this._processRobot(pkg, n, loadMeshCb))) return res } // Process the <robot> node static _processRobot(pkg, robot, loadMeshCb) { const links = [] const joints = [] const obj = new THREE.Object3D() obj.name = robot.getAttribute('name') obj.urdf = { node: robot } // Process the <joint> and <link> nodes URDFLoader.forEach(robot.children, n => { const type = n.nodeName.toLowerCase() if (type === 'link') links.push(n) else if (type === 'joint') joints.push(n) }) // Create the <link> map const linkMap = {} URDFLoader.forEach(links, l => { const name = l.getAttribute('name') linkMap[name] = this._processLink(pkg, l, loadMeshCb) }) // Create the <joint> map const jointMap = {} URDFLoader.forEach(joints, j => { const name = j.getAttribute('name') jointMap[name] = this._processJoint(j, linkMap) }) for (let key in linkMap) linkMap[key].parent ? null : obj.add(linkMap[key]) obj.urdf.joints = jointMap obj.urdf.links = linkMap return obj } // Process joint nodes and parent them static _processJoint(joint, linkMap) { const jointType = joint.getAttribute('type') const obj = new THREE.Object3D() obj.name = joint.getAttribute('name') obj.urdf = { node: joint, type: jointType, angle: 0, axis: null, limits: { lower: 0, upper: 0 }, setAngle: () => {} } let parent = null let child = null let xyz = [0, 0, 0] let rpy = [0, 0, 0] // Extract the attributes URDFLoader.forEach(joint.children, n => { const type = n.nodeName.toLowerCase() if (type === 'origin') { xyz = this._processTuple(n.getAttribute('xyz')) rpy = this._processTuple(n.getAttribute('rpy')) } else if(type === 'child') { child = linkMap[n.getAttribute('link')] } else if(type === 'parent') { parent = linkMap[n.getAttribute('link')] } else if(type === 'limit') { obj.urdf.limits.lower = parseFloat(n.getAttribute('lower') || obj.urdf.limits.lower) obj.urdf.limits.upper = parseFloat(n.getAttribute('upper') || obj.urdf.limits.upper) } }) // Join the links parent.add(obj) obj.add(child) this._applyRotation(obj, rpy) obj.position.set(xyz[0], xyz[1], xyz[2]) // Set up the rotate function const origRot = new THREE.Quaternion().copy(obj.quaternion) const axisnode = URDFLoader.filter(joint.children, n => n.nodeName.toLowerCase() === 'axis')[0] if (axisnode) { const axisxyz = axisnode.getAttribute('xyz').split(/\s+/g).map(num => parseFloat(num)) obj.urdf.axis = new THREE.Vector3(axisxyz[0], axisxyz[1], axisxyz[2]) } switch (jointType) { case 'fixed': break; case 'continuous': obj.urdf.limits.lower = -Infinity obj.urdf.limits.upper = Infinity case 'revolute': obj.urdf.setAngle = function(angle = 0) { if (!this.axis) return angle = Math.min(this.limits.upper, angle) angle = Math.max(this.limits.lower, angle) // FromAxisAngle seems to rotate the opposite of the // expected angle for URDF, so negate it here const delta = new THREE.Quaternion().setFromAxisAngle(this.axis, angle * -1) obj.quaternion.multiplyQuaternions(origRot, delta) this.angle = angle } break; case 'floating': case 'prismatic': case 'planar': // TODO: Support these joint types console.warn(`'${ jointType }' joint not yet supported`) } return obj } // Process the <link> nodes static _processLink(pkg, link, loadMeshCb) { const visualNodes = URDFLoader.filter(link.children, n => n.nodeName.toLowerCase() === 'visual') const obj = new THREE.Object3D() obj.name = link.getAttribute('name') obj.urdf = { node: link } URDFLoader.forEach(visualNodes, vn => this._processVisualNode(pkg, vn, obj, loadMeshCb)) return obj } // Process the visual nodes into meshes static _processVisualNode(pkg, vn, linkObj, loadMeshCb) { let xyz = [0, 0, 0] let rpy = [0, 0, 0] let mesh = null const material = new THREE.MeshLambertMaterial() URDFLoader.forEach(vn.children, n => { const type = n.nodeName.toLowerCase() if (type === 'geometry') { const geoType = n.children[0].nodeName.toLowerCase() if (geoType === 'mesh') { const filename = n.children[0].getAttribute('filename').replace(/^((package:\/\/)|(model:\/\/))/, '') const path = pkg + '/' + filename const ext = path.match(/.*\.([A-Z0-9]+)$/i).pop() || '' loadMeshCb(path, ext, obj => { if (obj) { if (obj instanceof THREE.Mesh) { obj.material = material } linkObj.add(obj) obj.position.set(xyz[0], xyz[1], xyz[2]) obj.rotation.set(0,0,0) this._applyRotation(obj, rpy) } }) } else if (geoType === 'box') { requestAnimationFrame(() => { const mesh = new THREE.Mesh() mesh.geometry = new THREE.BoxGeometry(1, 1, 1) mesh.material = material const size = this._processTuple(n.children[0].getAttribute('size')) linkObj.add(mesh) this._applyRotation(mesh, rpy) mesh.position.set(xyz[0], xyz[1], xyz[2]) mesh.scale.set(size[0], size[1], size[2]) }) } else if (geoType === 'sphere') { requestAnimationFrame(() => { const mesh = new THREE.Mesh() mesh.geometry = new THREE.SphereGeometry(1, 20, 20) mesh.material = material const radius = parseFloat(n.children[0].getAttribute('radius')) || 0 mesh.position.set(xyz[0], xyz[1], xyz[2]) mesh.scale.set(radius, radius, radius) }) } else if (geoType === 'cylinder') { requestAnimationFrame(() => { const radius = parseFloat(n.children[0].getAttribute('radius')) || 0 const length = parseFloat(n.children[0].getAttribute('length')) || 0 const mesh = new THREE.mesh() mesh.geometry = new THREE.CylinderBufferGeometry(1, 1, 1, 25) mesh.material = material mesh.scale.set(radius, length, radius) const obj = new THREE.Object3D() obj.add(mesh) mesh.rotation.set(Math.PI, 0, 0) linkObj.add(obj) this._applyRotation(obj, rpy) obj.position.set(xyz[0], xyz[1], xyz[2]) obj.scale.set(size[0], size[1], size[2]) }) } } else if(type === 'origin') { xyz = this._processTuple(n.getAttribute('xyz')) rpy = this._processTuple(n.getAttribute('rpy')) } else if(type === 'material') { URDFLoader.forEach(n.children, c => { if (c.nodeName.toLowerCase() === 'color') { let rgba = c.getAttribute('rgba') .split(/\s/g) .map(v => parseFloat(v)) material.color.r = rgba[0] material.color.g = rgba[1] material.color.b = rgba[2] material.opacity = rgba[3] if (material.opacity < 1) material.transparent = true } else if (c.nodeName.toLowerCase() === 'texture') { const filename = c.getAttribute('filename').replace(/^(package:\/\/)/, '') const path = pkg + '/' + filename material.map = this._textureloader.load(path) } }) } }) } }
JavaScript
class MathUtil { /** * * @param {number} x * @param {number} y * @returns {number} */ static intDiv(x, y) { let r = x/y; r = MathUtil.roundDown(r); return MathUtil.safeZero(r); } /** * * @param {number} x * @param {number} y * @returns {number} */ static intMod(x, y) { let r = x - MathUtil.intDiv(x, y) * y; r = MathUtil.roundDown(r); return MathUtil.safeZero(r); } /** * * @param {number} r * @returns {number} */ static roundDown(r){ if (r < 0) { return Math.ceil(r); } else { return Math.floor(r); } } /** * * @param {number} x * @param {number} y * @returns {number} */ static floorDiv(x, y){ const r = Math.floor(x / y); return MathUtil.safeZero(r); } /** * * @param {number} x * @param {number} y * @returns {number} */ static floorMod(x, y){ const r = x - MathUtil.floorDiv(x, y) * y; return MathUtil.safeZero(r); } /** * * @param {number} x * @param {number} y * @returns {number} */ static safeAdd(x, y) { MathUtil.verifyInt(x); MathUtil.verifyInt(y); if (x === 0) { return MathUtil.safeZero(y); } if (y === 0) { return MathUtil.safeZero(x); } const r = MathUtil.safeToInt(x + y); if (r === x || r === y) { throw new ArithmeticException('Invalid addition beyond MAX_SAFE_INTEGER!'); } return r; } /** * * @param {number} x * @param {number} y * @returns {number} */ static safeSubtract(x, y) { MathUtil.verifyInt(x); MathUtil.verifyInt(y); if (x === 0 && y === 0) { return 0; } else if (x === 0) { return MathUtil.safeZero(-1 * y); } else if (y === 0) { return MathUtil.safeZero(x); } return MathUtil.safeToInt(x - y); } /** * * @param {number} x * @param {number} y * @returns {number} */ static safeMultiply(x, y) { MathUtil.verifyInt(x); MathUtil.verifyInt(y); if (x === 1) { return MathUtil.safeZero(y); } if (y === 1) { return MathUtil.safeZero(x); } if (x === 0 || y === 0) { return 0; } const r = MathUtil.safeToInt(x * y); if (r / y !== x || (x === MIN_SAFE_INTEGER && y === -1) || (y === MIN_SAFE_INTEGER && x === -1)) { throw new ArithmeticException(`Multiplication overflows: ${x} * ${y}`); } return r; } /** * * @param {number} value * @returns {number} */ static parseInt(value) { const r = parseInt(value); return MathUtil.safeToInt(r); } /** * * @param {number} value * @returns {number} */ static safeToInt(value) { MathUtil.verifyInt(value); return MathUtil.safeZero(value); } /** * * @param {number} value */ static verifyInt(value){ if (value == null) { throw new ArithmeticException(`Invalid value: '${value}', using null or undefined as argument`); } if (isNaN(value)) { throw new ArithmeticException('Invalid int value, using NaN as argument'); } if ((value % 1) !== 0) { throw new ArithmeticException(`Invalid value: '${value}' is a float`); } if (value > MAX_SAFE_INTEGER || value < MIN_SAFE_INTEGER) { throw new ArithmeticException(`Calculation overflows an int: ${value}`); } } /** * convert -0 to 0 and int as string to a number ( '1' -> 1 ) * * @param {number} value * @returns {number} */ static safeZero(value){ return value === 0 ? 0 : +value; } /** * Compares two Numbers. * * @param {number} a the first value * @param {number} b the second value * @return {number} the result */ static compareNumbers(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } // convert to small integer for v8 optimisation static smi(int) { return ((int >>> 1) & 0x40000000) | (int & 0xBFFFFFFF); } // calculate 32 bit hash of a number and convert to SMI static hash(number) { if (number !== number || number === Infinity) { return 0; } let result = number; while (number > 0xFFFFFFFF) { number /= 0xFFFFFFFF; result ^= number; } return MathUtil.smi(result); } // default hashCode calculation for a number sequence as mentioned by Joshua Bloch static hashCode(...numbers) { let result = 17; for (const n of numbers) { result = (result << 5) - result + MathUtil.hash(n); } return MathUtil.hash(result); } }
JavaScript
class MyComponent extends React.Component { constructor(props) { super(props); } render() { // change code below this line return ( <div> <h1>Hello React!</h1> </div> ); // change code above this line } }
JavaScript
class ThemeVisitor { constructor(theme) { this.theme = theme; } /** * Applies a function to every style in the theme. * * @param visitFunc - Function to be called with `style` as an argument. Function should return * `true` to cancel visitation. * @returns `true` if function has finished prematurely. */ visitStyles(visitFunc) { const visit = (style) => { if (Expr_1.isJsonExpr(style)) { return false; } if (visitFunc(style)) { return true; } return false; }; if (this.theme.styles !== undefined) { for (const styleSetName in this.theme.styles) { if (this.theme.styles[styleSetName] !== undefined) { for (const style of this.theme.styles[styleSetName]) { if (visit(style)) { return true; } } } } } return false; } }
JavaScript
class NodeTimings { constructor(parent, xmlNode) { this.parent = parent; this.begin = xmlNode.begin; this.end = xmlNode.end; this._isActive = !this.begin && !this.end; } get active() { return this._isActive; } set active(val) { this._isActive = val; this.parent.onActive(); } makeCueObject() { return null; } }
JavaScript
class Admin extends Component { constructor() { super( ...arguments ); const { namespace = '' } = this.context; const { data: masterData = {} } = this.props; const cookiePrefix = namespace.replace( '-', '_' ); // uncomment to clear cookies /* setCookie( `${ cookiePrefix }_max_grids`, 25 ); setCookie( `${ cookiePrefix }_sort_favs`, false ); setCookie( `${ cookiePrefix }_sort_ids`, false ); setCookie( `${ cookiePrefix }_sort_names`, false ); setCookie( `${ cookiePrefix }_sort_modified`, false ); */ const sortFavs = trueFalse( getCookie( `${ cookiePrefix }_sort_favs`, false ) ); const sortIds = trueFalse( getCookie( `${ cookiePrefix }_sort_ids`, false ) ); const sortNames = sortIds ? false : trueFalse( getCookie( `${ cookiePrefix }_sort_names`, false ) ); const sortModified = sortNames || sortIds ? false : trueFalse( getCookie( `${ cookiePrefix }_sort_modified`, false ) ); const max = parseInt( getCookie( `${ cookiePrefix }_max_grids`, 25 ), 10 ); const { gridId = '', section = 'settings' } = gridMagicData; const page = gridId ? 'editor' : 'overview'; const { gridList: allGrids } = masterData; let gridList; if( isObject( allGrids ) ) { gridList = allGrids; } else { gridList = {}; masterData.gridList = gridList; } let grids = Object.keys( gridList ); grids.forEach( key => { const { draft } = gridList[ key ]; if( trueFalse( draft ) ) { delete gridList[ key ]; } } ); grids = Object.keys( gridList ); if( sortFavs ) { gridList = sortObject( 'favorite', 'boolean', grids, gridList ); grids = Object.keys( gridList ); } if( sortIds ) { gridList = sortObject( 'id', 'number', grids, gridList, false, 'gmagic-' ); } else if( sortNames ) { gridList = sortObject( 'name', 'string', grids, gridList ); } else if( sortModified ) { gridList = sortObject( 'lastModified', 'number', grids, gridList ); } masterData.gridList = gridList; const gridLength = Object.keys( gridList ).length; const pagination = gridLength > max && max !== -1; /* * @desc the AdminContext Provider = the state * PUBLIC class methods are the ones we push into the state here so child components that adopt the context can call them * @since 0.1.0 */ this.state = { max, page, gridId, gridLength, pagination, namespace, sortIds, sortFavs, sortNames, sortModified, draftId: '', newGrids: [], saving: false, restError: false, restInRoute: false, curPagination: 0, settingsPage: section, softUpdateMessage: '', softUpdateSuccess: false, showSoftUpdateNotice: false, getContent: this.getContent, softUpdate: this.softUpdate, changePage: this.changePage, updateData: this.updateData, gridAction: this.gridAction, updateAdmin: this.updateAdmin, checkPagination: this.checkPagination, getCategories: this.getCategories, getPages: this.getPages, masterData: {...masterData }, }; } /* * @class-property - PRIVATE * @desc make sure drafts aren't posted * @param object data - incoming data to remove the draft from * @param string draftId - the draft to remove * @since 0.1.0 */ pluckDrafts( data = {}, draftId = '' ) { const newData = cloneObj( data ); const { gridList = {} } = newData; delete gridList[ draftId ]; return newData; } /* * @class-property - PRIVATE * @desc user prompt if REST calls are still in route * @param object e - window beforeunload event object * @since 0.1.0 */ onUnload = e => { e.preventDefault(); const message = 'Are you sure you want to exit?'; e.returnValue = message; return message; }; /* * @class-property - PRIVATE * @desc NON-blocking async/await REST call * @param object data - incoming data to update * @param string route - optional custom route * @since 0.1.0 */ async softPostData( incomingData = {}, route = 'opt', callback, draftId = '' ) { const data = route === 'opt' && draftId ? this.pluckDrafts( incomingData, draftId ) : incomingData; const { endpoint = '' } = gridMagicData; let res; window.addEventListener( 'beforeunload', this.onUnload ); try { res = await axios.post( `${ endpoint }${ route }/`, qs.stringify( { data } ) ); } catch(e) { res = null; } let restError; let softUpdateSuccess; let softUpdateMessage; let showSoftUpdateNotice; if( res ) { const { data: response } = res; if( Array.isArray( response ) && response.length === 2 ) { softUpdateSuccess = trueFalse( response[0] ); softUpdateMessage = String( response[1] ); showSoftUpdateNotice = true; } else { restError = response === 'success' ? false : response; } } else { restError = true; } window.removeEventListener( 'beforeunload', this.onUnload ); this.setState( { restError, softUpdateSuccess, softUpdateMessage, showSoftUpdateNotice, restInRoute: false, }, callback ); } /* * @class-property - PRIVATE * @desc BLOCKING REST call for things where we want the user to wait, such as a purchase code registration action * @param object data - new master data object to send to the server * @since 0.1.0 */ async hardPostData( incomingData = {}, route = 'opt', draftId = '' ) { const data = route === 'opt' && draftId ? this.pluckDrafts( incomingData, draftId ) : incomingData; const { endpoint = '' } = gridMagicData; const newData = { ...data }; let res; window.addEventListener( 'beforeunload', this.onUnload ); try { res = await axios.post( `${ endpoint }${ route }/`, qs.stringify( { data } ) ); } catch( e ) { res = {}; console.log( e ); } window.removeEventListener( 'beforeunload', this.onUnload ); const { data: response } = res; const restError = response === 'success' ? false : response; this.setState( { restError, saving: false, masterData: newData, restInRoute: false, } ); } /* * @class-property - PRIVATE * @desc get bulk content on-demand from a php file or from the TP servers such as the changelog, etc. * @param string route - required route name * @param function callback - callback to fire once content is retrieved * @since 0.1.0 */ async loadContent( route, callback ) { const { endpoint = '' } = gridMagicData; let res; window.addEventListener( 'beforeunload', this.onUnload ); try { res = await axios.get( `${ endpoint }${ route }/` ); } catch( e ) { res = {}; console.log( e ); } window.removeEventListener( 'beforeunload', this.onUnload ); const { data: response = '' } = res; try { callback( response ); } catch( e ) { console.log( e ); } } /* * @class-property - PUBLIC * @desc - fecthes categories and tags together asynchrounously and silently * @param function callback - callback to fire once content is retrieved * @since 0.1.0 * @todo - lift this data up */ getCategories = callback => { if( ! callback ) { return; } this.setState( { restInRoute: true }, () => { const { catTags = '' } = Queries; window.addEventListener( 'beforeunload', this.onUnload ); fetch( '/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: catTags }), }) .then( res => res.json() ) .then( res => { const { data = {} } = res; const { categories = {}, tags = {} } = data; const { nodes:catNodes = [] } = categories; const { nodes:tagNodes = [] } = tags; this.setState( { restInRoute: false }, () => { try { callback( catNodes, tagNodes ); } catch( e ) { console.log( e ); } finally { window.removeEventListener( 'beforeunload', this.onUnload ); } } ); }); }); }; /* * @class-property - PUBLIC * @desc - fecthes psges asynchrounously and silently * @param function callback - callback to fire once content is retrieved * @since 0.1.0 * @todo - lift this data up? */ getPages = callback => { if( ! callback ) { return; } this.setState( { restInRoute: true }, () => { const { pages = '' } = Queries; window.addEventListener( 'beforeunload', this.onUnload ); fetch( '/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: pages }), }) .then( res => res.json() ) .then( res => { const { data = {} } = res; const { pages = {} } = data; const { nodes = [] } = pages; this.setState( { restInRoute: false }, () => { try { callback( nodes ); } catch( e ) { console.log( e ); } finally { window.removeEventListener( 'beforeunload', this.onUnload ); } } ); }); }); }; /* * @class-property - PUBLIC * @desc set the state here from a child component * @param object newData - incoming data to update * @since 0.1.0 */ updateAdmin = ( newData = {}, callback ) => { this.setState( { ...newData }, callback ); }; /* * @class-property - PUBLIC * @desc check if we should go into overview list pagination mode * @param object params - just max for now * @param func callback - used to set a cookie afterward (for now) * @since 0.1.0 */ checkPagination = ( { max = 25 }, callback ) => { this.setState( prevState => { const { masterData = {} } = prevState; const { gridList = {}, curPagination: prevPagination = 0 } = masterData; const gridLength = Object.keys( gridList ).length; const pagination = gridLength > max && max !== -1; const curPagination = pagination ? 0 : prevPagination; return { max, gridLength, pagination, curPagination, }; }, callback ); }; /* * @class-property - PUBLIC * @desc spread data and to the server with a NON-blocking REST call * @param object newData - incoming data to update * @param string route - optional custom route * @since 0.1.0 */ softUpdate = ( newData = {}, route = 'opt', callback, draftId = '', internal ) => { if( ! internal ) { this.setState( { restInRoute: true }, () => { this.softPostData( { ...newData }, route, callback, draftId ); } ); } else { this.softPostData( { ...newData }, route, callback, draftId ); } }; /* * @class-property - PUBLIC * @desc get bulk content on-demand from a php file or from the TP servers such as the changelog, etc. * @param string route - route name that descripts the REST action * @param function callback - callback to fire once content is retrieved * @since 0.1.0 */ getContent = ( route = 'opt', callback ) => { if( ! callback ) { return; } this.setState( { restInRoute: true }, () => { this.loadContent( route, callback ); } ); }; /* * @class-property - PUBLIC * @desc REST call for things where we want the user to wait, such as a purchase code registration action * @param object incomingData - new master data object to send to the server * @param string message - message to show the user while they wait * @since 0.1.0 */ updateData = ( incomingData = {}, message = '', hardUpdate = false ) => { let saving = message; if( ! saving ) { saving = __( `${ messagePath }saving_data` ); } const newData = { ...incomingData }; let data; let draft; this.setState( prevState => { const { masterData = {}, draftId = '' } = prevState; const clonedData = cloneObj( masterData ); data = extend( clonedData, newData ); draft = draftId; if( ! hardUpdate ) { return { masterData: data, restInRoute: true }; } return { saving, restInRoute: true }; }, () => { if( ! hardUpdate ) { this.softPostData( { ...data }, 'opt', null, draft ); } else { this.hardPostData( { ...data }, 'opt', draft ); } } ); }; /* * @class-property - PRIVATE * @desc create a new Grid * @param function callback - possible callback, must be null otherwise * @since 0.1.0 */ newGrid( callback ) { let data; let draftId; this.setState( prevState => { const { draftId: curDraftId = '' } = prevState; const newGrid = this.createNewGrid( prevState, false, curDraftId ); const { newId = '', clonedData: masterData, gridLength = 0, } = newGrid; draftId = curDraftId; data = { ...masterData }; return { masterData, gridLength, draftId: '', newGrids: [ newId ], restInRoute: true, }; }, () => { if( callback && isFunction( callback ) ) { callback(); } this.softPostData( { ...data }, 'opt', null, draftId ); } ); } /* * @class-property - PUBLIC * @desc actions for the grids listed in the overview page * @param action string - the action to handle * @param gridId string - the Grid's ID * @param data * - the Grid's ID * @since 0.1.0 */ gridAction = ( { action, gridId = '', data, callback } ) => { // no default for the switch. // the action name must match something // possible incoming data to handle depending on the action switch( action ) { case 'edit_grid': this.changePage( 'editor', { gridId } ); break; case 'create_grid': this.newGrid( callback ); break; case 'delete_grid': this.deleteGrid( gridId ); break; case 'duplicate_grid': this.duplicateGrid( gridId ); break; case 'toggle_favorite': this.updateFavorite( gridId, data ); break; case 'sort_favorites': this.sortGrids( 'favorite', 'sortFavs', 'sort_favs', 'boolean' ); break; case 'sort_ids': this.sortGrids( 'id', 'sortIds', 'sort_ids', 'number' ); break; case 'sort_names': this.sortGrids( 'name', 'sortNames', 'sort_names', 'string' ); break; case 'sort_modified': this.sortGrids( 'lastModified', 'sortModified', 'sort_modified', 'number' ); break; case 'bulk_delete': this.deleteBulkGrids( [ ...data ], callback ); break; case 'change_pagination': this.setState( { curPagination: data }, callback ); } }; /* * @class-property - PRIVATE * @desc bulk delete the grids * @param grids array - the grids to bulk delete * @since 0.1.0 */ deleteBulkGrids( grids = [], callback ) { if( window.confirm( __( `${ messagePath }sure_you_want_to_delete_these_grids` ) ) ) { this.setState( prevState => { const { masterData = {}, draftId = '' } = prevState; const clonedData = cloneObj( masterData ); const { gridList = {} } = clonedData; Object.keys( gridList ).forEach( key => { if( grids.indexOf( key ) !== -1 ) { delete gridList[ key ]; } } ); this.softUpdate( clonedData, 'opt', null, draftId, true ); return { draftId: '', masterData: clonedData, gridLength: Object.keys( gridList ).length, }; }, callback ); } } /* * @class-property - PRIVATE * @desc switches between the main 3 pages, currently: 'overview', 'editor' and 'globals' * @param prevState object - grabbed from the setState function and then used here to create a new Grid * @param draft boolean - whether the new grid is a draft or not * @since 0.1.0 */ createNewGrid( prevState = {}, draft, draftId = '' ) { const { masterData = {} } = prevState; const clonedData = cloneObj( masterData ); const { gridList = {} } = clonedData; const gridKeys = Object.keys( gridList ); const hasDraft = gridKeys.indexOf( draftId ) !== -1; let newId = gridKeys.length; while( gridKeys.indexOf( `gmagic-${ newId.toString() }` ) !== -1 ) { newId++; } if( hasDraft && newId === 2 ) { newId = 1; } const gridIndex = newId ? newId : 1; newId = Math.max( gridIndex, 1 ).toString(); let realId = newId; let name = `Grid: ${ newId }`; if( ! draft ) { let slugId = `gmagic-${ newId }`; let i = 1; while( gridKeys.indexOf( slugId ) !== -1 ) { name = `${ name }-${ i }`; newId = `${ newId }${ i }`; slugId = `gmagic-${ newId }`; i++; } } else { name = `${ name } (draft)`; newId = 'draft'; realId = 'draft'; } const alias = toSlug( name.replace( ':', '' ) ); const newGrid = { name, alias, favorite: false, settings: 'Even, 4:3, Custom, Boxed', lastModified: getTimeStamp(), }; if( draft ) { newGrid.draft = true; } newId = `gmagic-${ realId }`; const newList = { [ newId ]: { ...newGrid } }; Object.keys( gridList ).forEach( key => { newList[ key ] = { ...gridList[ key ] }; } ); clonedData.gridList = newList; return { newId, clonedData, gridLength: Object.keys( newList ).length, }; } /* * @class-property - PUBLIC * @desc switches between the main 3 pages, currently: 'overview', 'editor' and 'globals' * @param string page - the new page to change to * @since 0.1.0 */ changePage = ( newPage = '', params = {} ) => { const page = String( newPage ); let args = isObject( params ) ? { ...params } : {}; if( topLevelPages.indexOf( page ) !== -1 ) { this.setState( prevState => { if( page === 'editor' ) { const { masterData = {} } = prevState; const { gridList = {} } = masterData; const gridKeys = Object.keys( gridList ); if( gridKeys.length ) { const { gridId } = args; if( gridId ) { args = { ...args, newGrids: [ gridId ] }; } } else { // if no grids exist we'll create a draft const newGrid = this.createNewGrid( prevState, true ); const { clonedData, newId = '' } = newGrid; const newData = { masterData: { ...clonedData } }; const { newGrids = [] } = prevState; newGrids.push( newId ); args = { ...args, ...newData, draftId: newId, newGrids: newGrids.slice() }; } } return { ...args, page }; }, () => { if( page !== 'editor' ) { const params = new URLSearchParams( location.search ); params.delete( 'edit_grid' ); params.delete( 'grid_id' ); window.history.replaceState( {}, '', `${ location.pathname }?${ params }` ); } } ); } else { console.log( __( `${ messagePath }admin_page_does_not_exist` ) ); } }; /* * @class-property - PRIVATE * @desc duplicates a grid from the overview page on user-action * @param string gridId - the ID of the Grid to duplicate * @since 0.1.0 */ duplicateGrid( gridId = '' ) { this.setState( prevState => { const { masterData = {}, draftId = '', pagination = false, curPagination = 0, max = 25, } = prevState; const clonedData = cloneObj( masterData ); const { gridList = {} } = clonedData; const gridKeys = Object.keys( gridList ); const gridLength = gridKeys.length; const curIndex = gridKeys.indexOf( gridId ) + 1; const grid = gridList[ gridId ]; if( ! grid ) { console.log( __( `${ messagePath }unable_to_duplicate_grid` ) ); } const clonedGrid = cloneObj( grid ); let newId = gridLength; while( gridKeys.indexOf( `gmagic-${ newId.toString() }` ) !== -1 ) { newId++; } const { name, alias } = clonedGrid; const ids = parseInt( gridId.replace( 'gmagic-', '' ), 10 ); let newName = `${ name }-${ ids }`; let newAlias = `${ alias }-${ ids }`; gridKeys.forEach( key => { const itm = gridList[ key ]; const { name, alias } = itm; let i = 1; let j = 1; while( newName === name ) { newName = `${ newName }-${ i }`; i++; } while( newAlias === alias ) { newAlias = `${ newAlias }-${ j }`; j++; } } ); clonedGrid.name = newName; clonedGrid.alias = newAlias; newId = `gmagic-${ newId }`; const realMax = max !== -1 ? max : gridLength; const pageIndex = curPagination * realMax; const pageMax = pageIndex + realMax - 1; const placeBefore = pagination && curIndex > pageIndex + realMax - 2; const newList = {}; let placed; Object.keys( gridList ).forEach( ( key, index ) => { if( ! placeBefore ) { if( curIndex === index ) { placed = true; newList[ newId ] = clonedGrid; } } else { if( index === pageMax ) { placed = true; newList[ newId ] = clonedGrid; } } newList[ key ] = { ...gridList[ key ] }; } ); // fallback just in case if( ! placed ) { newList[ newId ] = clonedGrid; } clonedData.gridList = { ...newList }; this.softUpdate( clonedData, 'opt', null, draftId, true ); return { draftId: '', masterData: clonedData, newGrids: [ newId ], gridLength: Object.keys( newList ).length, }; } ); } /* * @class-property - PRIVATE * @desc deletes a grid from the overview page on user-action * @param string gridId - the ID of the Grid to delete * @since 0.1.0 */ deleteGrid( gridId = '' ) { if( window.confirm( __( `${ messagePath }sure_you_want_to_delete_grid` ) ) ) { this.setState( prevState => { const { masterData = {}, draftId = '' } = prevState; const clonedData = cloneObj( masterData ); const { gridList = {} } = clonedData; const grid = gridList[ gridId ]; if( ! grid ) { console.log( __( `${ messagePath }unable_to_delete_grid` ) ); } delete gridList[ gridId ]; this.softUpdate( clonedData, 'opt', null, draftId, true ); return { draftId: '', masterData: clonedData, gridLength: Object.keys( gridList ).length, }; } ); } } /* * @class-property - PRIVATE * @desc sorts grids depending on user action * @since 0.1.0 */ sortGrids( prop = '', propSelected = '', cookieSlug = '', type = 'boolean' ) { let isSorted; let namespace; this.setState( prevState => { const { masterData = {}, [ propSelected ]: selected, namespace:ns = '', } = prevState; namespace = ns; const clonedData = cloneObj( masterData ); const { gridList = {} } = clonedData; const grids = Object.keys( gridList ); let obj = {}; if( prop === 'id' ) { obj = { sortNames: false, sortModified: false, }; } else if( prop === 'name' ) { obj = { sortIds: false, sortModified: false, }; } else if( prop === 'lastModified' ) { obj = { sortIds: false, sortNames: false, }; } isSorted = ! selected; clonedData.gridList = sortObject( prop, type, grids, gridList, selected, prop === 'id' ? 'gmagic-' : '', // replace string when sorting by ID ); return { masterData: clonedData, [ propSelected ]: isSorted, ...obj, }; }, () => { setCookie( `${ namespace.replace( '-', '_' ) }_${ cookieSlug }`, isSorted ); } ); } /* * @class-property - PRIVATE * @desc toggles Grid favorites from the grid-list on the overview page * @param string gridId - the ID of the Grid to delete * @param boolean selected - whether the favorite is selected or not * @since 0.1.0 */ updateFavorite( gridId = '', selected ) { this.setState( prevState => { const { masterData = {}, draftId = '' } = prevState; const clonedData = cloneObj( masterData ); const { gridList = {} } = clonedData; const grid = gridList[ gridId ]; if( ! grid ) { console.log( __( `${ messagePath }unable_to_save_favorite` ) ); return; } const clonedGrid = cloneObj( grid ); clonedGrid.favorite = selected; gridList[ gridId ] = clonedGrid; this.softUpdate( clonedData, 'opt', null, draftId, true ); return { masterData: clonedData }; } ); } /* * @class-property - PRIVATE * @desc the rendered view. Here we pass the current class state down to any component that adopts the AdminContext * then the ErrorBoundary catches errors that bubble up so we can show custom messages * then the Display component is basically the admin's main wrapper, i.e. header, menu, body content * @since 0.1.0 */ render() { return ( <AdminContext.Provider value={ this.state }> <ErrorBoundary> <Display /> </ErrorBoundary> </AdminContext.Provider> ); } }
JavaScript
class Friends extends Component { state = { themeColor: Boolean(localStorage.getItem("theme")) ? parseInt(localStorage.getItem("theme")) : ThemeColor.Light, mainVisible: false, }; // Load selected theme componentDidMount() { let classList = document.body.classList; if (classList.length === 0 && this.state.themeColor === ThemeColor.Dark) { document.body.classList.add("dark-skin"); } else if (classList.length && this.state.themeColor === ThemeColor.Light) { document.body.classList.remove("dark-skin"); } } handleMainVisible = () => { this.setState({ mainVisible: true }); }; handleHideMain = () => { this.setState({ mainVisible: false }); }; render() { return ( <div className="chats-tab-open h-100"> <div className={"main-layout h-100"}> <NavBar activeMenu="friends" /> <FriendList setMainVisible={this.handleMainVisible} /> <FriendProfile showMain={this.state.mainVisible} hideMain={this.handleHideMain} /> <div className="backdrop"></div> </div> </div> ); } }