language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class CakeProductStore extends Store { //> The `recordClass` getter tells the Store // what this store contains. get recordClass() { return CakeProduct; } //> The `comparator` getter returns a function that maps a record // to the property it should be sorted _by_. So if we wanted to sort // cakes by their names, we'd write: get comparator() { return cake => cake.get('name'); } //> If you're looking for more advanced sorting behavior, you're welcome // to override `Store#summarize()` in your subclass based on Torus's implementation. }
JavaScript
class CakeProductStore extends StoreOf(CakeProduct) { get comparator() { return cake => cake.get('name'); } }
JavaScript
class WinnerListing extends Component { init(winner, removeCallback) { //> We can store the winner's properties here this.winner = winner; //> When we want to remove this item from the list // (from a user event, for example), we can run this callback // passed from `List`. this.removeCallback = removeCallback; } compose() { return jdom`<li> ${this.winner.name}, from ${this.winner.city} </li>`; } }
JavaScript
class WinnerList extends List { get itemClass() { return WinnerListing; } }
JavaScript
class WinnerList extends ListOf(WinnerListing) { compose() { // We want the list to have a header, and a wrapper element. return jdom`<div class="winner-list"> <h1>Winners!</h1> <ul>${this.nodes}</ul> </div>`; } }
JavaScript
class App extends Component { init(router) { //> We bind to a router just like we'd bind to a record or store. // the event summary will contain two values in an array: the name of the // route, as defined in the router, and the route parameters, like `:tabID`. this.bind(router, ([name, params]) => { //> You can write your routing logic however you like, but // I personally found switch cases based on the name of the route // to be a good pattern. switch (name) { case 'tabPage': this.activeTab = params.tabID; this.activePage = params.pageNumber; // render the tab and page break; case 'tab': this.activeTab = params.tabID; // render the tab break; // ... default: // render the default page } }); } }
JavaScript
class ProjectContexts { /** * Constructor. * * @param {Tenant} tenant The tenant instance. * @param {Project} project The project instance. */ constructor(tenant, project) { /** * The tenant. * @type {Tenant} */ this.tenant = tenant; /** * The project * @type {Project} */ this.project = project; } /** * Retrieves the list of project contexts for the current project. * * @param {Object} options The options object. * @return {Promise<Array<Object>, Error>} */ list(options = {}) { return this.tenant.execute({path: endpoint("projectContexts", (this.project.projectId))}, options) .then((response) => { if (response["_embedded"]) { return response["_embedded"]["be:project_context"]; } else { return []; } }); } /** * Retrieve a project context object to perform operations on it. * * @param {String} id The id of the project context. * @return {ProjectContext} */ context(id) { return new ProjectContext(this.tenant, this.project, id); } /** * Create a new context for the current project * * @param {String} name Context name * @param {Object} options The options object * @returns {Promise.<Object, Error>} */ create(name, options = {}) { return this.tenant.execute( requests.createProjectContext(this.project.projectId, name), options ); } }
JavaScript
class SFRPGCustomChatMessage { static getToken(actor) { if (actor.token) { return `${actor.token.parent.id}.${actor.token.id}`; } else if (canvas.tokens?.controlled[0]?.id) { return `${game.scenes.active.id}.${canvas.tokens.controlled[0].id}`; } else { return ""; } } /** * Render a custom standard roll to chat. * * @param {Roll} roll The roll data * @param {object} data The data for the roll * @param {RollContext} data.rollContent The context for the roll * @param {string} [data.title] The chat card title * @param {SpeakerData} [data.speaker] The speaker for the ChatMesage * @param {string} [data.rollMode] The roll mode * @param {string} [data.breakdown] An explanation for the roll and it's modifiers * @param {Tag[]} [data.tags] Any item metadata that will be output at the bottom of the chat card. */ static renderStandardRoll(roll, data) { /** Get entities */ const mainContext = data.rollContext.mainContext ? data.rollContext.allContexts[data.rollContext.mainContext] : null; let actor = data.rollContext.allContexts['actor'] ? data.rollContext.allContexts['actor'].entity : mainContext?.entity; if (!actor) { actor = data.rollContext.allContexts['ship'] ? data.rollContext.allContexts['ship'].entity : mainContext?.entity; if (!actor) { return false; } } let item = data.rollContext.allContexts['item'] ? data.rollContext.allContexts['item'].entity : mainContext?.entity; if (!item) { item = data.rollContext.allContexts['weapon'] ? data.rollContext.allContexts['weapon'].entity : mainContext?.entity; if (!item) { return false; } } /** Set up variables */ const hasCapacity = item.hasCapacity(); const currentCapacity = item.getCurrentCapacity(); const options = { item: item, hasDamage: data.rollType !== "damage" && (item.hasDamage || false), hasSave: item.hasSave || false, hasCapacity: hasCapacity, ammoLeft: currentCapacity, title: data.title ? data.title : 'Roll', rawTitle: data.speaker.alias, dataRoll: roll, rollType: data.rollType, rollNotes: data.htmlData?.find(x => x.name === "rollNotes")?.value, type: CONST.CHAT_MESSAGE_TYPES.ROLL, config: CONFIG.SFRPG, tokenImg: actor.data.token?.img || actor.img, actorId: actor.id, tokenId: this.getToken(actor), breakdown: data.breakdown, tags: data.tags, damageTypeString: data.damageTypeString, specialMaterials: data.specialMaterials, rollOptions: data.rollOptions, }; const speaker = data.speaker; if (speaker) { let setImage = false; if (speaker.token) { const token = game.scenes.get(speaker.scene)?.tokens?.get(speaker.token); if (token) { options.tokenImg = token.data.img; setImage = true; } } if (speaker.actor && !setImage) { const actor = Actors.instance.get(speaker.actor); if (actor) { options.tokenImg = actor.data.img; } } } SFRPGCustomChatMessage._render(roll, data, options); return true; } static async _render(roll, data, options) { const templateName = "systems/sfrpg/templates/chat/chat-message-attack-roll.html"; let rollContent = await roll.render({htmlData: data.htmlData}); // Insert the damage type string if possible. const damageTypeString = options?.damageTypeString; if (damageTypeString?.length > 0) { rollContent = DiceSFRPG.appendTextToRoll(rollContent, damageTypeString); } if (options.rollOptions?.actionTarget) { rollContent = DiceSFRPG.appendTextToRoll(rollContent, game.i18n.format("SFRPG.Items.Action.ActionTarget.ChatMessage", {actionTarget: options.rollOptions.actionTargetSource[options.rollOptions.actionTarget]})); } options = foundry.utils.mergeObject(options, { rollContent }); const cardContent = await renderTemplate(templateName, options); const rollMode = data.rollMode ? data.rollMode : game.settings.get('core', 'rollMode'); // let explainedRollContent = rollContent; // if (options.breakdown) { // const insertIndex = rollContent.indexOf(`<section class="tooltip-part">`); // explainedRollContent = rollContent.substring(0, insertIndex) + options.explanation + rollContent.substring(insertIndex); // } const messageData = { flavor: data.title, speaker: data.speaker, content: cardContent, //+ explainedRollContent + (options.additionalContent || ""), rollMode: rollMode, roll: roll, type: CONST.CHAT_MESSAGE_TYPES.ROLL, sound: CONFIG.sounds.dice, rollType: data.rollType, flags: {} }; if (damageTypeString?.length > 0) { messageData.flags.damage = { amount: roll.total, types: damageTypeString?.replace(' & ', ',')?.toLowerCase() ?? "" }; } if (options?.specialMaterials) { messageData.flags.specialMaterials = options.specialMaterials; } if (options.rollOptions) { messageData.flags.rollOptions = options.rollOptions; } ChatMessage.create(messageData); } }
JavaScript
class Fabric extends Scribe { /** * The {@link Fabric} type implements a peer-to-peer protocol for * establishing and settling of mutually-agreed upon proofs of * work. Contract execution takes place in the local node first, * then is optionally shared with the network. * * Utilizing * @exports Fabric * @constructor * @param {Vector} config - Initial configuration for the Fabric engine. This can be considered the "genesis" state for any contract using the system. If a chain of events is maintained over long periods of time, `state` can be considered "in contention", and it is demonstrated that the outstanding value of the contract remains to be settled. * @emits Fabric#thread * @emits Fabric#step Emitted on a `compute` step. */ constructor (vector = {}) { super(vector); // set local config this.config = Object.assign({ path: './stores/fabric', persistent: false }, vector); // start with reference to object this.ident = new State(this.config); this.state = new State(vector); // State // TODO: remove this this['@entity'] = {}; // build maps this.agent = {}; // Identity this.modules = {}; // List<Class> this.opcodes = {}; // Map<id> this.peers = {}; // Map<id> this.plugins = {}; // Map<id> this.services = {}; // Map<id> // initialize components this.chain = new Chain(this.config); this.machine = new Machine(this.config); this.store = new Store(this.config); // this.script = new Script(this.config); // provide instance return this; } static get registry () { return { local: require('../services/local') }; } static get App () { return App; } static get Block () { return Block; } static get Chain () { return Chain; } static get Circuit () { return Circuit; } static get Collection () { return Collection; } // static get Contract () { return Contract; } // static get Disk () { return Disk; } static get Entity () { return Entity; } static get Key () { return Key; } static get Ledger () { return Ledger; } static get Machine () { return Machine; } static get Message () { return Message; } static get Observer () { return Observer; } static get Oracle () { return Oracle; } // static get Peer () { return Peer; } static get Program () { return Program; } static get Remote () { return Remote; } static get Resource () { return Resource; } static get Service () { return Service; } static get Scribe () { return Scribe; } static get Script () { return Script; } static get Stack () { return Stack; } static get State () { return State; } static get Store () { return Store; } static get Swarm () { return Swarm; } // static get Transaction () { return Transaction; } static get Vector () { return Vector; } static get Wallet () { return Wallet; } static get Worker () { return Worker; } static sha256 (data) { return crypto.createHash('sha256').update(data).digest('hex'); } static random () { // TODO: select random function // do not trust keys until this is determined! return Math.random(); } async _GET (key) { return this.store._GET(key); } async _SET (key, value) { return this.store._SET(key, value); } async _PUT (key, value) { return this.store._SET(key, value); } async _POST (collection, value) { return this.store._POST(collection, value); } async _PATCH (key, overlay) { return this.store._PATCH(key, overlay); } async _DELETE (key) { return this.store._DELETE(key); } async start () { await super.start(); for (let i in this.config.services) { let name = this.config.services[i]; let service = Service.fromName(name); await this.register(service); await this.enable(name); } // identify ourselves to the network await this.identify(); return this; } async stop () { this.log('Stopping...'); for (let name in this.services) { await this.services[name].stop(); } if (this.chain) { await this.chain.stop(); } await super.stop(); this.emit('done'); return this; } /** * Register an available {@link Service} using an ES6 {@link Class}. * @param {Class} service The ES6 {@link Class}. */ async register (service) { if (!service) return new Error('Service must be provided.'); try { let name = service.name || service.constructor.name; this.modules[name.toLowerCase()] = service; this.emit('message', { '@type': 'ServiceRegistration', '@data': { name: name } }); } catch (E) { this.error('Could not register service:', E); } return this; } async enable (name) { let self = this; let Module = null; let config = Object.assign({ name: name, path: `./stores/${name}` }, this.config[name]); if (this.modules[name]) { Module = this.modules[name]; } else { return this.error(`Could not enable module ${name}. Check local registry.`); } // configure the service this.services[name] = new Module(config); this.services[name].on('ready', function () { self.emit('service:ready', { name }); }); // bind all events self.trust(this.services[name]); try { await this.services[name].start(); this.emit('message', { '@type': 'ServiceStartup', '@data': { name: name } }); } catch (E) { console.error(`exceptioning:`, E); } return this; } append (value) { return this.chain.append(value); } set (key, value) { return State.pointer.set(this['@entity'], key, value); } get (key) { return State.pointer.get(this['@entity'], key); } /** * Push an instruction onto the stack. * @param {Instruction} value * @return {Stack} */ push (value) { let name = value.constructor.name; if (name !== 'Vector') value = new Vector(value)._sign(); this.machine.script.push(value); return this.machine.script; } use (name, description) { this.log('[FABRIC]', `defining <code>${name}</code> as:`, description); this.opcodes[name] = new Opcode(description); return this.define(name, description); } define (name, description) { this.log(`Defining resource "${name}":`, description); let vector = new Fabric.State(description); let resource = new Fabric.Resource(name, description); this.log(`Resource:`, resource); this.log(`Resource as vector:`, vector); return resource; } identify (vector) { if (!vector) vector = {}; let self = this; let key = new Key(); self.identity = { key }; // a "vector" is a known truth, something that we've generated ourselves // or otherwise derived truth from an origin (a genesis vector // TODO: remove lodash self['@data'] = Object.assign({}, self['@data'], vector, key); // should be equivalent to `f(x + y)` this.emit('auth', { key: { public: key.public } }); return this; } send (target, message) { // console.log('sending:', target, message); return this.emit('message', { 'target': target, 'object': message }); } broadcast (msg, data) { var self = this; self.emit(msg, data); Object.keys(self.peers).forEach(function tell (id) { var peer = self.peers[id]; peer.send(msg); }); return true; } /** * Blindly consume messages from a {@link Source}, relying on `this.chain` to * verify results. * @param {EventEmitter} source Any object which implements the `EventEmitter` pattern. * @return {Fabric} Returns itself. */ trust (source) { let self = this; this.warn('[TRUST]', 'trusting:', typeof source); source.on('changes', async function (changes) { self.log('source', typeof source, 'emitted:', changes); }); source.on('transaction', async function (transaction) { // console.log('[FABRIC:CORE]', '[EVENT:TRANSACTION]', `source (${source.constructor.name}):`, transaction); // console.log('[PROPOSAL]', 'apply this transaction to local state:', transaction); }); source.on('block', async function (block) { await self.chain.append(block).catch(self.log.bind(self)); }); source.on('patch', function (patch) { console.log('source', typeof source, 'emitted patch:', patch); self.emit('patch', Object.assign({}, patch, { path: source.name + patch.path // TODO: check in Vector Machine that this is safe })); }); // normalized bindings source.on('actor', function (actor) { self.log(typeof source, 'source emitted actor:', actor); self.emit('actor', { id: [source.name, 'actors', actor.id].join('/'), name: actor.name, online: actor.online || false, subscriptions: [] }); }); source.on('channel', function (channel) { self.emit('channel', { id: [source.name, 'channels', channel.id].join('/'), name: channel.name, members: [] }); }); source.on('join', async function (join) { self.emit('join', { user: [source.name, 'actors', join.user].join('/'), channel: [source.name, 'channels', join.channel].join('/') }); }); source.on('message', async function (msg) { let now = Date.now(); let id = [now, msg.actor, msg.target, msg.object].join('/'); let hash = crypto.createHash('sha256').update(id).digest('hex'); let message = { id: [source.name, 'messages', (msg.id || hash)].join('/'), actor: [source.name, 'actors', msg.actor].join('/'), target: [source.name, 'channels', msg.target].join('/'), object: msg.object, origin: { type: 'Link', name: source.name }, created: now }; this.log('message:', message); self.emit('message', message); let response = await self.parse(message); if (response) { await source.send(msg.target, response, { parent: message }); self.emit('response', { parent: message, response: response }); } }); return self; } /** * Process the current stack. * @return {Fabric} Resulting instance of the stack. */ compute () { ++this.clock; // console.log('[FABRIC:COMPUTE]', '[COMMIT:RESULT]', this.commit()); return this; } render () { return `<Fabric integrity="sha256:${this.id}" />`; } }
JavaScript
class TitleHandler { element(element) { element.prepend("Goutham Gopal, "); } }
JavaScript
class BodyHandler { element(element) { element.replace("Providing link to my github account"); } }
JavaScript
class ActionHandler { element(element) { element .setInnerContent("github/gouthamgopal") .setAttribute("href", "https://github.com/gouthamgopal"); } }
JavaScript
class Ansis { constructor() { const self = (str) => str; Object.setPrototypeOf(self, styleProxy); return self; } }
JavaScript
class Card { constructor(cardStr) { var rank = cardStr.charAt(0); if (rank == '2' || rank == '3' || rank == '4' || rank == '5' || rank == '6' || rank == '7' || rank == '8' || rank == '9') { this.rank = parseInt(rank); } else if (rank == 'T') { this.rank = 10; } else if (rank == 'J') { this.rank = 11; } else if (rank == 'Q') { this.rank = 12; } else if (rank == 'K') { this.rank = 13; } else if (rank == 'A') { this.rank = 14; } this.suit = cardStr.charAt(1); } // If card1 is greater than card2, returns 1. If less than, returns -1, and // if they are equal, returns 0. compareTo(card2) { if (this.rank > card2.rank) { return 1; } else if (this.rank < card2.rank) { return -1; } else { return 0; } } // Determine if the cards are the same equals(card2) { return (this.rank == card2.rank && this.suit == card2.suit); } }
JavaScript
class Engineer extends Employee { constructor (name, employeeId, email, github) { // Calling employee constructor super (name, employeeId, email); this.github = github; } // Returning github from input getGithub() { return this.github; } // Override employee role to engineer getRole() { return 'Engineer'; } }
JavaScript
class AbstractDynamicList extends NbList { #mercureUpdateCallback = null; constructor() { super(); this._isWaitingForServerResponse = false; } connectedCallback() { super.connectedCallback(); this.addEventListener("items-initialized", () => { this.#initMercureUpdateListener(); }, { once: true }); } render() { return [ fontawesomeImport, super.render() ]; } firstUpdated() { if (this.items) { this.dispatchEvent(new CustomEvent("items-initialized")); return; } this.fetchListData(); } updated() { // In some cases, attributes may be set after the initial render, // which causes a list that is "stuck" in the loading state. // By checking on subsequent updates, we can avoid this. if (this.isLoading && !this._isWaitingForServerResponse) { this.fetchListData(); } } disconnectedCallback() { if (this.#mercureUpdateCallback) { MercureClient.unsubscribe(this.supportedEntityType(), this.#mercureUpdateCallback); } super.disconnectedCallback(); } /** * Returns the list of dynamic actions that are supported by this list. * Available actions: * - `"update"` * - `"add"` * - `"delete"` * * @returns {string[]} Array of supported actions */ supportedDynamicActions() { return ["update", "add", "delete"]; } /** * Returns the type of entity this list supports. * * @returns {string|null} */ supportedEntityType() { return null; } /** * Receives an update as an argument and returns * a boolean indicating whether the update should * be treated by this component or not. * * * @returns {function} */ supportedUpdateFilter(update) // eslint-disable-line no-unused-vars { return true; } /** * Whether the given action is supported or not by the list. * Available actions: * - `"update"` * - `"add"` * - `"delete"` * * @final * @param {string} action * @returns {boolean} Whether the action is supported by this list. */ supportsDynamicAction(action) { return this.supportedDynamicActions().includes(action.trim().toLowerCase()); } /** * @param {string} endpoint * @param {FormData|object} body */ fetchListData(endpoint, body = {}) { this._isWaitingForServerResponse = true; ApiClient.get(endpoint, body).then(response => { this._isWaitingForServerResponse = false; this.items = Array.isArray(response.data) ? response.data : Object.values(response.data); this.dispatchEvent(new CustomEvent("items-initialized")); }); } #initMercureUpdateListener() { if (this.supportedEntityType()) { this.#mercureUpdateCallback = (update) => this.#processMercureUpdate(update); MercureClient.subscribe(this.supportedEntityType(), this.#mercureUpdateCallback); } } #processMercureUpdate(update) { if (!this.supportedUpdateFilter(update)) { // The component doesn't support that update. return; } let itemsHaveChanged = false; switch (update.event) { case "delete": if (this.supportsDynamicAction("delete")) { const originalLength = this.items.length; this.items = this.items.filter(item => item.id != update.id); if (this.items.length != originalLength) { itemsHaveChanged = true; } } break; case "update": if (this.supportsDynamicAction("update")) { for (const index in this.items) { if (this.items[index].id == update.id) { const updatedList = [...this.items]; updatedList[index] = update.data; this.items = updatedList; itemsHaveChanged = true; break; } } } // If we couldn't find the item to update, create it. if (!itemsHaveChanged && this.supportsDynamicAction("add")) { this.items = this.items.concat([update.data]); itemsHaveChanged = true; } break; case "create": if (this.supportsDynamicAction("add")) { this.items = this.items.concat([update.data]); itemsHaveChanged = true; } break; } if (itemsHaveChanged) { this.dispatchEvent(new CustomEvent("items-updated")); } } }
JavaScript
class jfNode { /** * Constructor de la clase. * * @param {object|null} config Configuración a aplicar a la instancia. */ constructor(config = null) { /** * Metadatos almacenados en el nodo. * * @property data * @type {*} */ this.data = null; /** * Identificador del nodo. * * @property id * @type {Number} */ this.id = counter++; /** * Nodo anterior. * * @property previous * @type {jf.Node|null} */ this.previous = null; /** * Nodo siguiente. * * @property next * @type {jf.Node|null} */ this.next = null; /** * Valor del nodo. * * @property value * @type {*} */ this.value = null; //------------------------------------------------------------------------------ if (config) { this.setProperties(config); } } /** * Inserta el nodo actual después del nodo especificado. * * @param {jf.Node} node Nodo siguiente. * @param {boolean} remove Si es `true` el nodo primero se elimina de la lista actual y luego se agrega. * * @return {jf.Node} Nodo actual. */ after(node, remove = true) { if (node instanceof jfNode) { if (remove) { this.remove(); } const _next = node.next; if (_next) { _next.previous = this; this.next = _next; } node.next = this; this.previous = node; } return this; } /** * Inserta el nodo actual antes del nodo especificado. * * @param {jf.Node} node Nodo siguiente. * @param {boolean} remove Si es `true` el nodo primero se elimina de la lista actual y luego se agrega. * * @return {jf.Node} Nodo actual. */ before(node, remove = true) { if (node instanceof jfNode) { if (remove) { this.remove(); } const _previous = node.previous; if (_previous) { _previous.next = this; } node.previous = this; this.previous = _previous; this.next = node; } return this; } /** * Clona el nodo actual y devuelve una copia. * * @return {jf.Node} Clon del nodo. */ clone() { const _clone = new this.constructor(); _clone.setProperties(this); return _clone; } /** * Realiza un volcado por pantalla del nodo para inspeccionaarlo. * * @param {number} length Longitud del nombre de la clase del nodo. */ dump(length = 10) { console.log( '%s | %s | %s', this.id.toFixed(0).padStart(4, '0'), this.getName().padEnd(length, ' '), this.value ); } /** * Encuentra el nodo con el valor especificado permitiendo ir hacia adelante * o hacia atrás. * * @param {string} value Valor a buscar. * @param {string} iterate Propiedad del nodo sobre la que se iterará. * @param {string} property Propiedad que tiene el valor a buscar. * * @return {jf.Node|null} Nodo con el valor o `null` si no se encontró. */ find(value, iterate = 'next', property = 'data') { let _node = this; while (_node instanceof jfNode && _node[property] !== value) { _node = _node[iterate]; } return _node; } /** * Devuelve todos los nodos para los cuales la función devuelve `true`. * La función recibe como primer parámetro el nodo y como segundo el índice. * * @param {function} fn Función a llamar para cada nodo encontrado. * @param {string} iterate Propiedad del nodo sobre la que se iterará. * * @return {Node[]} Listado de nodos encontrados. */ filter(fn, iterate = 'next') { const _nodes = []; if (typeof fn === 'function') { let _node = this; let _index = 0; while (_node instanceof jfNode) { if (fn(_node, _index++)) { _nodes[iterate === 'next' ? 'push' : 'unshift'](_node); _node = _node[iterate]; } else { break; } } } return _nodes; } /** * Devuelve el nombre del nodo. * * @return {string} Nombre del nodo. */ getName() { return this.constructor.name; } /** * Encuentra el primer node de la secuencia que no contiene la propiedad buscada o el * valor de la propiedad no es un nodo. * * @param {string} property Propiedad que tiene el valor a buscar. * * @return {jf.Node} Primer nodo de la secuencia. */ lookup(property = 'previous') { let _node = this; while (_node instanceof jfNode) { if (property in _node && _node[property] instanceof jfNode) { _node = _node[property]; } else { break; } } return _node; } /** * Devuelve un listado con el valor de la propiedad en la secuencia actual y a partir del nodo actual. * * @param {string} property Nombre de la propiedad a extraer. * * @return {array} Valores extraídos. */ pluck(property = 'data') { const _output = []; let _node = this; while (_node) { _output.push(_node[property]); _node = _node.next; } return _output; } /** * Elimina el nodo actual. * * @return {jf.Node} Nodo actual. */ remove() { const _previous = this.previous; const _next = this.next; if (_previous instanceof jfNode) { _previous.next = _next; this.previous = null; } if (_next instanceof jfNode) { _next.previous = _previous; this.next = null; } return this; } /** * Reemplaza el nodo especificado por el nodo actual. * Si el nodo a reemplazar no pertenece a una cadena, no pasa nada. * * @param {jf.Node} node Nodo a reemplazar. * * @return {jf.Node} Nodo actual. */ replace(node) { const _previous = node.previous; const _next = node.next; if (_previous instanceof jfNode) { node.remove(); this.after(_previous); } else if (_next instanceof jfNode) { node.remove(); this.before(_next); } return this; } /** * Asigna los valores a las propiedades de la instancia. * * @param {object} values Valores a asignar. */ setProperties(values) { if (values) { Object.keys(values).forEach( property => { if (property in this) { const _value = values[property]; if (_value !== undefined) { this[property] = _value; } } } ); } } /** * Convierte la secuencia de nodos en un array. * * @return {jf.Node[]} Listado de nodos. */ toArray() { const _nodes = []; let _node = this.previous; while (_node) { _nodes.unshift(_node); _node = _node.previous; } _node = this; while (_node) { _nodes.push(_node); _node = _node.next; } return _nodes; } /** * @override */ toJSON() { const _data = {}; Object.keys(this) .sort() // Devolvemos todas las propiedades menos los 2 nodos y cualquiera que se haya agregado como privada. .filter(property => property[0] !== '_' && property !== 'previous' && property !== 'next') .forEach( property => { let _value = this[property]; if (_value instanceof jfNode) { _value = _value.toJSON(); } if (Array.isArray(_value)) { _value.forEach( (value, index) => { if (value instanceof jfNode) { _value[index] = value.toJSON(); } } ); } _data[property] = _value; } ); return _data; } /** * @override */ toString() { return JSON.stringify(this, null, 4); } /** * Devuelve todos los nodos existentes hasta el nodo que tiene el valor buscado sin incluir el nodo actual. * * @param {string} value Valor a buscar. * @param {string} iterate Propiedad del nodo sobre la que se iterará. * @param {string} property Propiedad que tiene el valor a buscar. * * @return {Node[]} Listado de nodos encontrados. */ until(value, iterate = 'next', property = 'value') { const _node = this[iterate]; return _node instanceof jfNode ? _node.filter(node => node[property] !== value, iterate) : []; } /** * Devuelve todos los nodos inmediatos con el valor especificado sin incluir el nodo actual. * * @param {string} value Valor a buscar. * @param {string} iterate Propiedad del nodo sobre la que se iterará. * @param {string} property Propiedad que tiene el valor a buscar. * * @return {Node[]} Listado de nodos encontrados. */ while(value, iterate = 'next', property = 'value') { const _node = this[iterate]; return _node instanceof jfNode ? _node.filter(node => node[property] === value, iterate) : []; } }
JavaScript
class LitmlWork extends HTMLElement { constructor() { super(); } generateHeader(workInfo) { var headerHtml; var headerObj; if (this.publisherTemplates && this.publisherTemplates.workHeader) { headerHtml = this.publisherTemplates.workHeader(workInfo); } else { headerHtml = this.generateDefaultHeaderHtml(workInfo); } if (headerHtml) { headerObj = document.createElement("header"); headerObj.setAttribute("slot","header"); headerObj.innerHTML = headerHtml; this.appendChild(headerObj); } } generateFooter(workInfo) { var footerHtml; var footerObj; if (this.publisherTemplates && this.publisherTemplates.workFooter) { footerHtml = this.publisherTemplates.workFooter(workInfo); } else { footerHtml = this.generateDefaultFooterHtml(workInfo); } if (footerHtml) { footerObj = document.createElement("footer"); footerObj.setAttribute("slot","footer"); footerObj.innerHTML = footerHtml; this.appendChild(footerObj); } } generateJsonLd(workInfo) { var jsonLDTxt; var scriptNode; if (this.publisherTemplates && this.publisherTemplates.genJsonLd) { jsonLDTxt = this.publisherTemplates.genJsonLd(workInfo); } else { jsonLDTxt = this.generateDefaultJsonLd(workInfo); } if (jsonLDTxt) { scriptNode = document.createElement("script"); scriptNode.setAttribute("type","application/ld+json"); scriptNode.setAttribute("slot","metadata"); scriptNode.innerText = jsonLDTxt; this.appendChild(scriptNode); } } buildWorkInfo() { var authorName = null; var title = null; var subtitle; var workType; var copyright; authorName = this.getAttribute("litml-author"); title = this.getAttribute("litml-title"); workType = this.getAttribute("litml-work-type"); subtitle = this.getAttribute('litml-subtitle'); copyright = this.getAttribute('litml-copyright'); this.workInfo = { "authorName": authorName, "title": title, "subtitle": subtitle, "workType": workType, "copyright": copyright }; return this.workInfo; } addContent() { this.attachShadow({ mode: 'open' }); this.initTemplate(); this.shadowRoot.appendChild(this.template.content.cloneNode(true)); this._slot = this.shadowRoot.querySelector('slot'); this.buildWorkInfo(); this.generateHeader(this.workInfo); this.generateJsonLd(this.workInfo); this.generateFooter(this.workInfo); } connectedCallback() { if (this.isConnected) { this.addContent(); } } }
JavaScript
class ReduceNoInitialValueSelector { constructor (reducer) { // this.reducer is public API this.reducer = reducer this._cache = new _WeakLruCache(2) } select (srcList) { if (srcList.size === 0) { return undefined } else if (srcList.size === 1) { return srcList.get(0) } let cacheEntry = this._cache.swap(srcList.root, null) if (cacheEntry != null) { console.log('cache hit') let oldSrcList = cacheEntry.srcList let reductionCache = cacheEntry.reductionCache cacheEntry = null oldSrcList.observeChangesFor(srcList, { insert: (index, value) => { console.log('+', index, value) }, delete: (index, value) => { console.log('-', index, value) } }) // update our cache cacheEntry = { srcList, reductionCache } this._cache.swap(srcList.root, cacheEntry) return null } console.log('cache miss') let reduction = srcList.get(0) let nextCacheIndex = Math.floor(srcList.size / 2) let reductionCache = [] for (let i = 1; i < srcList.size; ++i) { reduction = this.reducer(reduction, srcList.get(i)) if (i >= nextCacheIndex) { reductionCache.push({ index: i, reduction }) nextCacheIndex = Math.floor((i + (srcList.size - i) / 2)) } } cacheEntry = { srcList, reductionCache } this._cache.swap(srcList.root, cacheEntry) return reduction } }
JavaScript
class Bunny extends Sprite { constructor() { const texture = Texture.fromImage(BUNNY); super(texture); this.tween = new Tween(this); this.anchor.x = .5; this.anchor.y = 1; this.pivot.x = .5; this.pivot.y = .5; this.interactive = true; this.on('mouseover', this.startSpin.bind(this)); console.log(this) } startSpin() { this.tween.to({rotation: Math.PI*2}, 1000); this.tween.start(); this.tween.onComplete(() => this.rotation = 0); } }
JavaScript
class App extends Component { constructor(props) { super(props); this.pubnub = new PubNubReact({ publishKey: 'pub-c-2df6bd48-0dad-40af-a0a0-b0e193bae137', subscribeKey: 'sub-c-bc6b661e-f7a3-11e8-b085-b2b44c5b7fba' }); this.pubnub.init(this); PushNotification.configure({ // Called when Token is generated. onRegister: function(token) { console.log( 'TOKEN:', token ); this.storeData('deviceToken',token.token); if (token.os == "ios") { this.pubnub.push.addChannels( { channels: ['notifications'], device: token.token, pushGateway: 'apns' }); // Send iOS Notification from debug console: {"pn_apns":{"aps":{"alert":"Hello World."}}} } else if (token.os == "android"){ this.pubnub.push.addChannels( { channels: ['notifications'], device: token.token, pushGateway: 'gcm' // apns, gcm, mpns }); // Send Android Notification from debug console: {"pn_gcm":{"data":{"message":"Hello World."}}} } }.bind(this), // Something not working? // See: https://support.pubnub.com/support/solutions/articles/14000043605-how-can-i-troubleshoot-my-push-notification-issues- // Called when a remote or local notification is opened or received. onNotification: function(notification) { console.log( 'NOTIFICATION:', notification ); // Do something with the notification. // Required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html) // notification.finish(PushNotificationIOS.FetchResult.NoData); }, // ANDROID: GCM or FCM Sender ID senderID: "814833699979", }); } storeData = async (storeValueName, storeValue) => { console.log('storeDataisCalled',storeValue) try { await AsyncStorage.setItem(storeValueName, storeValue); console.log('deviceTokenSavedStoreData',storeValue) } catch (error) { // Error saving data } } render () { return ( <Provider store={store}> <RootContainer /> </Provider> ) } }
JavaScript
class BlockcypherDao extends AbstractDao{ static URL_BASE = 'https://api.blockcypher.com/v1/btc' /** * Creates an instance of the BlockcypherDao * * @param {Bech32hrp} chain - The chain should be set using one of the chain variables */ constructor( chain = Bech32hrp.BTC_TESTNET ){ // Call the AbstractDao constructor super(chain) // Test for valid chain if ( chain === Bech32hrp.BTC_MAINNET || chain === Bech32hrp.BTC_TESTNET ){ this.chain = chain }else{ throw new Error(`Invalid chain: ${chain}`) } } }
JavaScript
class PredictionAssistant { /** * The constructor of {PredictionaAssistant} class. * @param {FastaSeq} a fastaSequenceObject. */ constructor(fastaSequenceObject) { this.fastaSequenceObject = fastaSequenceObject; this.patternsWithIds = null; } /** * Sets the pattern used for prediction. Pattern (motif) is string which is used to check if sequence (string) is matched. * User can have the following input: * 1. A pattern string without pattern Id. Example 1: "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]" * 2. An array of strings, and each element in this array is a pattern used to prediction. Element in this array cannot be repeat. Example 2: * ["[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]", "[DNS]-x-[DNS]-{FLIVWY}"] * 3. A JSON object containing a pattern and a pattern Id. Example 3: * {"patternId_1": "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]"} * OR * { * "patternId_1": { * "pattern": "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]", * "description": "This is a desciption of this pattern, what is used for, where it is come from", * "url":"www.reference_url.io" * }, * "patternId_2": "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]" * } * @param {String}, {Arrary}, {Object} in above description * @returns {PredictionAssistant} object with patternMap being set. * @throws a exception if input is null, undefined, a blank string, or an empty string. */ setPatterns(patterns){ // check invalid input if (patterns === null || patterns === undefined) { throw new Error("The input patterns cannot be null or undefined."); } // convert input into a {PatternMap} object switch(typeof patterns){ case "string": // like example 1 if(patterns.trim() === "") { throw new Error("The input patterns cannot be blank string or an empty string."); } this.patternsWithIds = this.translatePatternString(patterns); break; case "object": if(Array.isArray(patterns)) { // if input is an array with string element, like example 2 this.patternsWithIds = this.translatePatternArray(patterns); } else { // treat as example 3. this.patternsWithIds = this.translatePatternObject(patterns); } break; default: throw new Error("The format of input patterns is not supported."); } return this; } /** * Translates a string to a {PatternMap}. * input example: "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]" * @param {Sting} stringPattern * @returns a {PatternMap}. */ translatePatternString(stringPattern) { const patternId = stringPattern; // patternId is same as input string const patternInfo= { "pattern": convertPatternToRegExp(stringPattern), "originalPattern": stringPattern, "description": null, "url": null }; const outputPatternMap = new Map(); outputPatternMap.set(patternId, patternInfo); return outputPatternMap; } /** * Translates a JSON object containing keys and values into a {PatternMap}. * Input patern object example -> A JSON object containing a pattern and a pattern Id: * {"patternId_1": "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]"} * OR * { * "patternId_1": { * "pattern": "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]", * "description": "This is a desciption of this pattern, what is used for, where it is come from", * "url":"www.reference_url.io" * }, * "patternId_2": "[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]" * } * @param {Object} patternObject */ translatePatternObject(patternObject) { const keys = Object.keys(patternObject); const outputPatternMap = new Map(); for (const key of keys) { const patternId = key; if (typeof patternObject[key] === "string") { const patternInfo = { "pattern": convertPatternToRegExp(patternObject[key]), "originalPattern": patternObject[key], "description": null, "url": null }; outputPatternMap.set(patternId, patternInfo); } else if (typeof patternObject[key] === "object" && typeof patternObject[key].pattern === "string") { const value = patternObject[key]; const patternInfo = { "pattern": convertPatternToRegExp(value.pattern), "originalPattern": value.pattern, "description": value.description, "url": value.url }; outputPatternMap.set(patternId, patternInfo); } else { throw new Error("The input pattern is not valid."); } } return outputPatternMap; } /** * Translates an arry of pattern strings (no key) into a {PatternMap}. * input example: ["[DNS]-x-[DNS]-{FLIVWY}-[DNESTG]-[DNQGHRK]-{GP}-[LIVMC]-[DENQSTAGC]-x(2)-[ED]", "[DNS]-x-[DNS]-{FLIVWY}"] * @param {Array} patternArray * @throws a error if input is not valid. */ translatePatternArray(patternArray) { const outputPatternMap = new Map(); const patternSet = new Set(patternArray); for (const patternString of patternSet) { if (typeof patternString !== "string") { throw new Error ("The input pattern is not valid."); } const patternId = patternString; const patternInfo = { "pattern": convertPatternToRegExp(patternString), "originalPattern": patternString, "description": null, "url": null }; outputPatternMap.set(patternId, patternInfo); } return outputPatternMap; } /** * Predict/find the motifs based on pattern search for the input FASTA sequences. * Read instructions on https://github.com/accliu/Nerds_pockets/projects/1 on * how to use this method correctly. * @returns the prediction results along with the fasta sequence Ids, fasta sequences, * pattern(motif) name, pattern signiture, and prediction result. Example: * [ * { * sequenceId: "fake sequence Id 1", * sequence: "DKSKKDKDKDDSKSDKSDKSDK......", * contained_motifs: ["ef-hand"] * motifs: * { * "ef-hand": * { * pattern_signiture: "[D]-x-[D,E]-x-[D,E]", * matched_sequences: [{starting_index: 23, sequence: "DKDGE"}, {starting_index: 55, sequence: "DSEKD"}] * }, * "zink-finger": * { * pattern_signiture: "[C]-x-[C]-x-[C]", * matched_sequences: [], * discription: "description of zink finger", * url: "www.fakeurl.com" * } * } * }, * { * sequenceId: "fake sequence Id 2", * sequence: "PPPPPPPIIIIKKKDRGD", * contained_motifs: [] * motifs: * { * "ef-hand": * { * pattern_signiture: "[D]-x-[D,E]-x-[D,E]", * matched_sequences: [] * }, * "zink-fingure": * { * pattern_signiture: "[C]-x-[C]-x-[C]", * matched_sequences: [] * } * } * }, * ] * @throws error if FASTA sequence is fastaSequenceObject or patternsWithIds in {PredictionAssistant} object is null or not defined. */ predict(){ if (!this.fastaSequenceObject) {throw new Error("FASTA sequence is not setup properly.");} if (!this.patternsWithIds) {throw new Error("Motif (pattern) is not setup properly");} const predictionResultArray = []; // retrive FASTA sequences Ids from fastaSequenceObject and stored in an array. const fastaSeqIdArray = this.fastaSequenceObject.getAllSequenceIds(); // retrive Pattern Ids from {PatternMap} stored in patternsWithIds. const patternIdArray = [...this.patternsWithIds.keys()]; if (fastaSeqIdArray.length && patternIdArray.length) { // loop through each sequence Ids for (let sequenceId of fastaSeqIdArray){ // extract sequence by sequenceId const sequence = this.fastaSequenceObject.getSequenceById(sequenceId); const predictionResult = {}; // store sequenceId and sequence into predictionResult object predictionResult.sequenceId = sequenceId; predictionResult.sequence = sequence; predictionResult.contained_motifs = []; predictionResult.motifs = {}; // loop through patternIds and predict the presence of each motif against sequence. for (let patternId of patternIdArray) { //retrieve motif pattern (signiture), desription, and reference url const pattern = this.patternsWithIds.get(patternId).pattern; const originalPattern = this.patternsWithIds.get(patternId).originalPattern; const description = this.patternsWithIds.get(patternId).description; const url = this.patternsWithIds.get(patternId).url; // save patternId key and pattern signiture into predictionResult.motifs predictionResult.motifs[patternId] = {}; predictionResult.motifs[patternId].pattern_signiture = originalPattern; predictionResult.motifs[patternId].matched_sequences = []; // if desciption and url are not null or defined, save these information as part of // motif information as well. if (description != null || description != undefined) { predictionResult.motifs[patternId].description = description; } if (url !== null || description != undefined) { predictionResult.motifs[patternId].url = url; } // scan this pattern (motif signiture) against sequence, // if there is pattern match, then push the pattern id to predictionResult.contained_motifs array. const finder = new PatternFinder(); if(finder.containPattern(pattern, sequence)) { predictionResult.contained_motifs.push(patternId); // also add prediction results to predictionResult.motifs[patternId].matched_sequences. predictionResult.motifs[patternId].matched_sequences = finder.getMatchedSequences(pattern, sequence); } } predictionResultArray.push(predictionResult); } } return predictionResultArray; } }
JavaScript
class TextureLoaderWrapper { constructor (type, basePath) { this.loader = null switch (type) { case 'texture': this.loader = new THREE.TextureLoader().setPath(basePath) break case 'cubeTexture': this.loader = new THREE.CubeTextureLoader().setPath(basePath) break } } load (path, key) { return new Promise(function (resolve, reject) { this.loader.load( path, function (texture) { let returnData = { texture: texture, key: key } resolve(returnData) }, undefined, function (error) { reject(error) } ) }.bind(this)) } }
JavaScript
class CustomCSSBuilder extends tron.builders.GCSSBuilder { src() { // print input files by overloading src() function return super.src().debug({ title: 'MyCSSBuilder:' }) } }
JavaScript
class OverlayEngine extends React.Component { componentDidMount() { this.props.subscribeToOverlays(); } render() { if (this.props.loading) { return <div>loading</div>; } if (this.props.overlay.id === 'scoreboard') { return <Scoreboard isShowing={this.props.overlay.isShowing} matchId="123" />; } if (this.props.overlay.id === 'playerlist') { return <PlayerList showHomeTeam isShowing={this.props.overlay.isShowing} matchId="123" />; } return `Overlay:${this.props.data.Overlay.id}`; } }
JavaScript
class HistogramLanguageModel { /** * Constructor. * @param {?Vocabulary} vocab Symbol vocabulary object. */ constructor(vocab) { this.vocab_ = vocab; assert(this.vocab_.size() > 1, "Expecting at least two symbols in the vocabulary"); // Total number of symbols observed during the training. this.totalObservations_ = 0; // Histogram of symbol counts. The first element is ignored. const numSymbols = this.vocab_.size(); this.histogram_ = new Array(numSymbols); for (let i = 0; i < numSymbols; ++i) { this.histogram_[i] = 0; } } /** * Creates new context which is initially empty. * @return {?Context} Context object. * @final */ createContext() { // Nothing to do here. return new Context(); } /** * Clones existing context. * @param {?Context} context Existing context object. * @return {?Context} Cloned context object. * @final */ cloneContext(context) { // Nothing to do here. return new Context(); } /** * Adds symbol to the supplied context. Does not update the model. * @param {?Context} context Context object. * @param {number} symbol Integer symbol. * @final */ addSymbolToContext(context, symbol) { // Nothing to do here. } /** * Adds symbol to the supplied context and updates the model. * @param {?Context} context Context object. * @param {number} symbol Integer symbol. * @final */ addSymbolAndUpdate(context, symbol) { if (symbol <= vocab.rootSymbol) { // Only add valid symbols. return; } assert(symbol < this.vocab_.size(), "Invalid symbol: " + symbol); this.histogram_[symbol]++; this.totalObservations_++; } /** * Returns probabilities for all the symbols in the vocabulary given the * context. * * This particular formulation can be seen as modified Kneser-Ney smoothing, * a two-parameter Chinese Restaurant process or a discrete Pitman-Yor * process. See * * Steinruecken, Christian (2015): "Lossless Data Compression", PhD * dissertation, University of Cambridge. Section 4.2.3 (pp. 65--67). * * The distribution is computed as follows: * P(w_{N+1} = s | w_1, ..., w_N) = * \frac{n_s - \beta}{N + \alpha} * 1[n_s > 0] + * \frac{\alpha + \beta * U}{N + \alpha} * P_b(s) , * where * - "s" is the symbol to predict and "n_s" is its count in the data, * - 1[n_s > 0]: an indicator boolean function, * - U is the number of unique seen symbols and * - P_b(s) is the base distribution, which in our implementation is * a uniform distribution. * * @param {?Context} context Context symbols. * @return {?array} Array of floating point probabilities corresponding to all * the symbols in the vocabulary plus the 0th element * representing the root of the tree that should be ignored. * @final */ getProbs(context) { const numSymbols = this.vocab_.size(); const numValidSymbols = numSymbols - 1; // Minus the first symbol. let probs = new Array(numSymbols); probs[0] = 0.0; // Ignore first symbol. // Figure out the number of unique (seen) symbols. let numUniqueSeenSymbols = 0; for (let i = 1; i < numSymbols; ++i) { if (this.histogram_[i] > 0) { numUniqueSeenSymbols++; } } // Compute the distribution. const denominator = this.totalObservations_ + pyAlpha; const baseFactor = (pyAlpha + pyBeta * numUniqueSeenSymbols) / denominator; const uniformPrior = 1.0 / numValidSymbols; let totalMass = 1.0; for (let i = 1; i < numSymbols; ++i) { let empirical = 0.0; if (this.histogram_[i] > 0) { empirical = (this.histogram_[i] - pyBeta) / denominator; } probs[i] = empirical + baseFactor * uniformPrior; totalMass -= probs[i]; } assert(Math.abs(totalMass) < epsilon, "Invalid remaining probability mass: " + totalMass); // Adjust the remaining probability mass, if any. let newProbMass = 0.0; let leftSymbols = numValidSymbols; for (let i = 1; i < numSymbols; ++i) { const p = totalMass / leftSymbols; probs[i] += p; totalMass -= p; newProbMass += probs[i]; --leftSymbols; } assert(totalMass == 0.0, "Expected remaining probability mass to be zero!"); assert(Math.abs(1.0 - newProbMass) < epsilon); return probs; } /** * Prints the histogram to console. * @final */ printToConsole() { console.log("Histogram of counts (total: " + this.totalObservations_ + "): "); for (let i = 1; i < this.histogram_.length; ++i) { console.log("\t" + this.vocab_.symbols_[i] + ": " + this.histogram_[i]); } } }
JavaScript
class PolandCombinedRecognizerResult extends RecognizerResult { constructor(nativeResult) { super(nativeResult.resultState); /** * The date of birth of the Poland ID owner. */ this.dateOfBirth = nativeResult.dateOfBirth != null ? new Date(nativeResult.dateOfBirth) : null; /** * The date of expiry of the Poland ID card. */ this.dateOfExpiry = nativeResult.dateOfExpiry != null ? new Date(nativeResult.dateOfExpiry) : null; /** * Digital signature of the recognition result. Available only if enabled with signResult property. */ this.digitalSignature = nativeResult.digitalSignature; /** * Version of the digital signature. Available only if enabled with signResult property. */ this.digitalSignatureVersion = nativeResult.digitalSignatureVersion; /** * Returns true if data from scanned parts/sides of the document match, * false otherwise. For example if date of expiry is scanned from the front and back side * of the document and values do not match, this method will return false. Result will * be true only if scanned values for all fields that are compared are the same. */ this.documentDataMatch = nativeResult.documentDataMatch; /** * The document number of the Poland ID card. */ this.documentNumber = nativeResult.documentNumber; /** * face image from the document if enabled with returnFaceImage property. */ this.faceImage = nativeResult.faceImage; /** * The family name of the Poland ID owner. */ this.familyName = nativeResult.familyName; /** * back side image of the document if enabled with returnFullDocumentImage property. */ this.fullDocumentBackImage = nativeResult.fullDocumentBackImage; /** * front side image of the document if enabled with returnFullDocumentImage property. */ this.fullDocumentFrontImage = nativeResult.fullDocumentFrontImage; /** * The given names of the Poland ID owner. */ this.givenNames = nativeResult.givenNames; /** * The issuing authority of the Poland ID card. */ this.issuedBy = nativeResult.issuedBy; /** * Determines if all check digits inside MRZ are correct */ this.mrzVerified = nativeResult.mrzVerified; /** * The nationality of the Poland ID owner. */ this.nationality = nativeResult.nationality; /** * The parents given names of the Poland ID owner. */ this.parentsGivenNames = nativeResult.parentsGivenNames; /** * The personal number of the Poland ID owner. */ this.personalNumber = nativeResult.personalNumber; /** * Returns true if recognizer has finished scanning first side and is now scanning back side, * false if it's still scanning first side. */ this.scanningFirstSideDone = nativeResult.scanningFirstSideDone; /** * The sex of the Poland ID owner. */ this.sex = nativeResult.sex; /** * The surname of the Poland ID owner. */ this.surname = nativeResult.surname; } }
JavaScript
class PolandCombinedRecognizer extends Recognizer { constructor() { super('PolandCombinedRecognizer'); /** * Defines if glare detection should be turned on/off. * * */ this.detectGlare = true; /** * Defines if date of birth of Poland ID owner should be extracted. * * */ this.extractDateOfBirth = true; /** * Defines if family name of Poland ID owner should be extracted. * * */ this.extractFamilyName = false; /** * Defines if given names of Poland ID owner should be extracted. * * */ this.extractGivenNames = true; /** * Defines if parents given names of Poland ID owner should be extracted. * * */ this.extractParentsGivenNames = false; /** * Defines if sex of Poland ID owner should be extracted. * * */ this.extractSex = true; /** * Defines if surname of Poland ID owner should be extracted. * * */ this.extractSurname = true; /** * Property for setting DPI for face images * Valid ranges are [100,400]. Setting DPI out of valid ranges throws an exception * * */ this.faceImageDpi = 250; /** * Property for setting DPI for full document images * Valid ranges are [100,400]. Setting DPI out of valid ranges throws an exception * * */ this.fullDocumentImageDpi = 250; /** * Image extension factors for full document image. * * @see ImageExtensionFactors * */ this.fullDocumentImageExtensionFactors = new ImageExtensionFactors(); /** * Sets whether face image from ID card should be extracted * * */ this.returnFaceImage = false; /** * Sets whether full document image of ID card should be extracted. * * */ this.returnFullDocumentImage = false; /** * Whether or not recognition result should be signed. * * */ this.signResult = false; this.createResultFromNative = function (nativeResult) { return new PolandCombinedRecognizerResult(nativeResult); } } }
JavaScript
class TwitterApiv2ReadWrite extends client_v2_read_1.default { constructor() { super(...arguments); this._prefix = globals_1.API_V2_PREFIX; } /* Sub-clients */ /** * Get a client with only read rights. */ get readOnly() { return this; } /** * Get a client for v2 labs endpoints. */ get labs() { if (this._labs) return this._labs; return this._labs = new client_v2_labs_write_1.default(this); } /* Tweets */ /** * Hides or unhides a reply to a Tweet. * https://developer.twitter.com/en/docs/twitter-api/tweets/hide-replies/api-reference/put-tweets-id-hidden */ hideReply(tweetId, makeHidden) { return this.put('tweets/:id/hidden', { hidden: makeHidden }, { params: { id: tweetId } }); } /** * Causes the user ID identified in the path parameter to Like the target Tweet. * https://developer.twitter.com/en/docs/twitter-api/tweets/likes/api-reference/post-users-user_id-likes * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ like(loggedUserId, targetTweetId) { return this.post('users/:id/likes', { tweet_id: targetTweetId }, { params: { id: loggedUserId } }); } /** * Allows a user or authenticated user ID to unlike a Tweet. * The request succeeds with no action when the user sends a request to a user they're not liking the Tweet or have already unliked the Tweet. * https://developer.twitter.com/en/docs/twitter-api/tweets/likes/api-reference/delete-users-id-likes-tweet_id * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ unlike(loggedUserId, targetTweetId) { return this.delete('users/:id/likes/:tweet_id', undefined, { params: { id: loggedUserId, tweet_id: targetTweetId }, }); } /** * Causes the user ID identified in the path parameter to Retweet the target Tweet. * https://developer.twitter.com/en/docs/twitter-api/tweets/retweets/api-reference/post-users-id-retweets * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ retweet(loggedUserId, targetTweetId) { return this.post('users/:id/retweets', { tweet_id: targetTweetId }, { params: { id: loggedUserId } }); } /** * Allows a user or authenticated user ID to remove the Retweet of a Tweet. * The request succeeds with no action when the user sends a request to a user they're not Retweeting the Tweet or have already removed the Retweet of. * https://developer.twitter.com/en/docs/twitter-api/tweets/retweets/api-reference/delete-users-id-retweets-tweet_id * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ unretweet(loggedUserId, targetTweetId) { return this.delete('users/:id/retweets/:tweet_id', undefined, { params: { id: loggedUserId, tweet_id: targetTweetId }, }); } tweet(status, payload = {}) { if (typeof status === 'object') { payload = status; } else { payload = { text: status, ...payload }; } return this.post('tweets', payload); } /** * Reply to a Tweet on behalf of an authenticated user. * https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets */ reply(status, toTweetId, payload = {}) { var _a; const reply = { in_reply_to_tweet_id: toTweetId, ...(_a = payload.reply) !== null && _a !== void 0 ? _a : {} }; return this.post('tweets', { text: status, ...payload, reply }); } /** * Post a series of tweets. * https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets */ async tweetThread(tweets) { var _a, _b; const postedTweets = []; for (const tweet of tweets) { // Retrieve the last sent tweet const lastTweet = postedTweets.length ? postedTweets[postedTweets.length - 1] : null; // Build the tweet query params const queryParams = { ...(typeof tweet === 'string' ? ({ text: tweet }) : tweet) }; // Reply to an existing tweet if needed const inReplyToId = lastTweet ? lastTweet.data.id : (_a = queryParams.reply) === null || _a === void 0 ? void 0 : _a.in_reply_to_tweet_id; const status = (_b = queryParams.text) !== null && _b !== void 0 ? _b : ''; if (inReplyToId) { postedTweets.push(await this.reply(status, inReplyToId, queryParams)); } else { postedTweets.push(await this.tweet(status, queryParams)); } } return postedTweets; } /** * Allows a user or authenticated user ID to delete a Tweet * https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/delete-tweets-id */ deleteTweet(tweetId) { return this.delete('tweets/:id', undefined, { params: { id: tweetId, }, }); } /* Users */ /** * Allows a user ID to follow another user. * If the target user does not have public Tweets, this endpoint will send a follow request. * https://developer.twitter.com/en/docs/twitter-api/users/follows/api-reference/post-users-source_user_id-following * * OAuth2 scope: `account.follows.write` * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ follow(loggedUserId, targetUserId) { return this.post('users/:id/following', { target_user_id: targetUserId }, { params: { id: loggedUserId } }); } /** * Allows a user ID to unfollow another user. * https://developer.twitter.com/en/docs/twitter-api/users/follows/api-reference/delete-users-source_id-following * * OAuth2 scope: `account.follows.write` * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ unfollow(loggedUserId, targetUserId) { return this.delete('users/:source_user_id/following/:target_user_id', undefined, { params: { source_user_id: loggedUserId, target_user_id: targetUserId }, }); } /** * Causes the user (in the path) to block the target user. * The user (in the path) must match the user context authorizing the request. * https://developer.twitter.com/en/docs/twitter-api/users/blocks/api-reference/post-users-user_id-blocking * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ block(loggedUserId, targetUserId) { return this.post('users/:id/blocking', { target_user_id: targetUserId }, { params: { id: loggedUserId } }); } /** * Allows a user or authenticated user ID to unblock another user. * https://developer.twitter.com/en/docs/twitter-api/users/blocks/api-reference/delete-users-user_id-blocking * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ unblock(loggedUserId, targetUserId) { return this.delete('users/:source_user_id/blocking/:target_user_id', undefined, { params: { source_user_id: loggedUserId, target_user_id: targetUserId }, }); } /** * Allows an authenticated user ID to mute the target user. * https://developer.twitter.com/en/docs/twitter-api/users/mutes/api-reference/post-users-user_id-muting * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ mute(loggedUserId, targetUserId) { return this.post('users/:id/muting', { target_user_id: targetUserId }, { params: { id: loggedUserId } }); } /** * Allows an authenticated user ID to unmute the target user. * The request succeeds with no action when the user sends a request to a user they're not muting or have already unmuted. * https://developer.twitter.com/en/docs/twitter-api/users/mutes/api-reference/delete-users-user_id-muting * * **Note**: You must specify the currently logged user ID ; you can obtain it through v1.1 API. */ unmute(loggedUserId, targetUserId) { return this.delete('users/:source_user_id/muting/:target_user_id', undefined, { params: { source_user_id: loggedUserId, target_user_id: targetUserId }, }); } /* Lists */ /** * Creates a new list for the authenticated user. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists */ createList(options) { return this.post('lists', options); } /** * Updates the specified list. The authenticated user must own the list to be able to update it. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/put-lists-id */ updateList(listId, options = {}) { return this.put('lists/:id', options, { params: { id: listId } }); } /** * Deletes the specified list. The authenticated user must own the list to be able to destroy it. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id */ removeList(listId) { return this.delete('lists/:id', undefined, { params: { id: listId } }); } /** * Adds a member to a list. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-lists-id-members */ addListMember(listId, userId) { return this.post('lists/:id/members', { user_id: userId }, { params: { id: listId } }); } /** * Remember a member to a list. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-lists-id-members-user_id */ removeListMember(listId, userId) { return this.delete('lists/:id/members/:user_id', undefined, { params: { id: listId, user_id: userId } }); } /** * Subscribes the authenticated user to the specified list. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-users-id-followed-lists */ subscribeToList(loggedUserId, listId) { return this.post('users/:id/followed_lists', { list_id: listId }, { params: { id: loggedUserId } }); } /** * Unsubscribes the authenticated user to the specified list. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-users-id-followed-lists-list_id */ unsubscribeOfList(loggedUserId, listId) { return this.delete('users/:id/followed_lists/:list_id', undefined, { params: { id: loggedUserId, list_id: listId } }); } /** * Enables the authenticated user to pin a List. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/post-users-id-pinned-lists */ pinList(loggedUserId, listId) { return this.post('users/:id/pinned_lists', { list_id: listId }, { params: { id: loggedUserId } }); } /** * Enables the authenticated user to unpin a List. * https://developer.twitter.com/en/docs/twitter-api/lists/manage-lists/api-reference/delete-users-id-pinned-lists-list_id */ unpinList(loggedUserId, listId) { return this.delete('users/:id/pinned_lists/:list_id', undefined, { params: { id: loggedUserId, list_id: listId } }); } }
JavaScript
class HeroPlatformerScene extends Phaser.Scene{ /** * Construct this scene * inheriting Phaser.Scene with a parameter of this name. */ constructor() { super('HeroPlatformerScene'); } /** * What we do before the game is loaded. */ preload() { this.load.image('hero', image_steve_stop); // Load the hero image this.load.image('grass_block', image_grass_block); // Load the grass block image this.load.image('melody', image_melody_stand); // Load the melody image this.load.image('shuriken', image_shuriken); // Load Shuriken image } /** * What we do when the game has just started. * We create all essential elements of the game. */ create() { this.create_hero(); this.create_grass_blocks(); this.melody_troop = this.physics.add.group(); this.shuriken_group = this.physics.add.group(); this.create_score_text(); } /** * We create the hero in this method. */ create_hero() { // Set the hero's start position (x,y) as the center of the screen let hero_start_x = this.game.config.width / 2; let hero_start_y = this.game.config.height / 2; let hero_name = 'hero'; // Each sprite should have a name this.hero = this.physics.add.sprite(hero_start_x, hero_start_y, hero_name); // Set the sprite gravity effect (able to fall down) let steve_gravity = 400; this.hero.body.gravity.y = steve_gravity; // Define a method "hero_jump" when "pointerdown" event is received. this.input.on('pointerdown', this.hero_jump, this); } /** * This method is to handle how the hero can jump. */ hero_jump(pointer) { if (this.hero.getBounds().contains(pointer.x, pointer.y)) { this.shoot_weapon(); } else { let is_standing = this.hero.body.blocked.down || this.hero.body.touching.down; if (is_standing) { // Hero can jump only on a platform, not in the air. // jumping up at speed rate 200 initially this.hero.body.velocity.y = -1 * 400; } } } /** * This method is to handle how you shoot a weapon. */ shoot_weapon() { let weapon_name = 'shuriken'; // Each sprite should have a name var weapon = this.shuriken_group.create( this.hero.body.x + 30 , this.hero.body.y + 30 , weapon_name ); weapon.setVelocityX(10 * screen_velocity); } /** * We create grass blocks in this method. */ create_grass_blocks() { // Generate a group of grass blocks // from (0,bottom) and repeat 12 times per 30 units to the right this.grass_group = this.physics.add.group( { key: 'grass_block' , repeat: 12 , setXY: { x: 0 , y: this.game.config.height - 30 , stepX: 30 } } ); // Create more grass platforms in the beginning this.grass_group.createMultiple( { key: 'grass_block' , repeat: 6 , setXY: { x: 300 , y: this.game.config.height - 150 , stepX: 30 } } ); // For each child block, scale down the size and fix it not moveable this.grass_group.children.each( (child) => { child.setImmovable(true); } ); // grass grounds are scrolling to the left this.grass_group.setVelocityX(-1 * screen_velocity); // Make grass blocks and hero be bound to each other this.physics.add.collider(this.grass_group, this.hero); } /** * Method: create an enemy #1: Melody */ create_melody(pos_x, pos_y) { // Set the character's start position (pos_x,pos_y) as the center of the screen let melody_name = 'melody'; // Each sprite should have a name this.melody_troop.create( pos_x , pos_y , melody_name ); // Set the sprite gravity effect (able to fall down) let melody_gravity = 400; this.melody_troop.children.each( (child) => { child.body.gravity.y = melody_gravity; } ); // Make grass blocks and melody be bound to each other this.physics.add.collider(this.grass_group, this.melody_troop); this.melody_troop.setVelocityX(-1 * screen_velocity); } /** * Create a text of current score */ create_score_text() { this.score = 0; this.topScore = localStorage.getItem(highest_score_storage) == null ? 0 : localStorage.getItem(highest_score_storage); this.scoreText = this.add.text(10, 10, ''); this.updateScore(this.score); } /** * What we do when the game is being played. */ update(){ if (this.hero.body.x > this.game.config.width / 2) { // Move the hero to the left if it is on right side this.hero.setVelocityX(-1 * screen_velocity); } else if (this.hero.body.x < this.game.config.width / 2) { // Move the hero to the right if it is on left side this.hero.setVelocityX(screen_velocity); } // Remove child melody if it is out of screen (left side) this.melody_troop.children.each( (child) => { if (child.body.x < 0) { this.melody_troop.remove(child); child.destroy(); } // // Remove child melody if it touches Shuriken var touchShuriken = false this.shuriken_group.children.each( (shuriken) => { if (Phaser.Geom.Rectangle.Overlaps(shuriken.getBounds(), child.getBounds())) { touchShuriken = true; } } ); if (touchShuriken) { this.melody_troop.remove(child); child.destroy(); } } ); // Remove child grass if it is out of screen (left side) this.grass_group.children.each( (child) => { if (child.body.x < 0) { this.grass_group.remove(child); child.destroy(); // Add scores when new grass grounds are removed. this.updateScore(1); } } ); // Remove child shuriken if it is out of screen (right side) this.shuriken_group.children.each( (child) => { if (child.body.x > this.game.config.width) { this.shuriken_group.remove(child); child.destroy(); } } ); // If the right ground is moving to provide more space, fill it up if (this.getRightMostGrass().x < this.game.config.width - 90) { /** * Randomly create grass blocks in the front * 0 - ground * 1 - lower than the player * 2 - as high as the player * 3 - higher than the player */ var random_make_grass = Math.floor(Math.random() * 4); var target_y = 0; switch(random_make_grass) { case 1: target_y = this.getGridY(this.hero.body.y + 30); break; case 2: target_y = this.getGridY(this.hero.body.y); break; case 3: target_y = this.getGridY(this.hero.body.y - 30); break; default: target_y = this.game.config.height - 30; break; } var num_of_blocks = Math.floor(Math.random() * 5) + 1; // Create more grass platforms this.grass_group.createMultiple( { key: 'grass_block' , repeat: num_of_blocks , setXY: { x: this.game.config.width , y: target_y , stepX: 30 } } ); // For each child block, scale down the size and fix it not moveable this.grass_group.children.each( (child) => { child.setImmovable(true); child.body.velocity.x = -1 * screen_velocity; } ); // Create a melody on top of the right most grass this.create_melody(this.game.config.width, target_y - 60); } } /** * When Update a Score * @param {*} inc increased score */ updateScore(inc){ this.score += inc; this.scoreText.text = 'Score: ' + this.score + '\nBest: ' + this.topScore; } /** * Utility method to get the right most grass object * @returns the right most grass object */ getRightMostGrass() { let rightMostChild = null this.grass_group.children.iterate( (child) => { if (rightMostChild == null) { rightMostChild = child; } else if (rightMostChild.body.x < child.body.x) { rightMostChild = child; } } ); return rightMostChild; } /** * Calculate Y of a grid based on the given general coordinate y * so that the block is within a grid, not between grids. * @param {*} coord_y The general y coordinate * @return y of the grid belong to the given y */ getGridY(coord_y) { var ground_y = this.game.config.height - 30; var diff_from_ground = ground_y - coord_y; var count_of_grid = Math.floor(diff_from_ground / 30); return ground_y - count_of_grid * 30; } /** * Check whether the given rectangle is overlapped with any sprite * @param {*} rect Given rectangle * @returns true if overlapped; else false */ hasAnySprite(rect) { console.log(this.grass_group.children.size) // Check if overlapped with hero if (Phaser.Geom.Rectangle.Overlaps(this.hero.getBounds(), rect)) { return true; } console.log("hero: " + this.hero.body.x + ", " + this.hero.body.y); console.log("rect: " + rect.left + ", " + rect.right + "|"+ rect.top + ", " + rect.bottom); // Check if overlapped with grass this.grass_group.children.iterate( (child) => { if (Phaser.Geom.Rectangle.Overlaps(child.getBounds(), rect)) { return true; } else { // console.log(child.getBounds().left + " vs " + rect.left + ", " + child.getBounds().right + " vs " + rect.right + "|"+ child.getBounds().top + " vs " + rect.top + ", " + child.getBounds().bottom + " vs " + rect.bottom); // console.log(rect.left + ", " + rect.right + "|"+ rect.top + ", " + rect.bottom); console.log(child.getBounds().left + ", " + child.getBounds().right + "|"+ child.getBounds().top + ", " + child.getBounds().bottom); } } ); // Nothing is overlapped return false; } }
JavaScript
class StepScalingPolicy extends cdk.Construct { constructor(scope, id, props) { super(scope, id); if (props.scalingSteps.length < 2) { throw new Error('You must supply at least 2 intervals for autoscaling'); } const adjustmentType = props.adjustmentType || step_scaling_action_1.AdjustmentType.ChangeInCapacity; const changesAreAbsolute = adjustmentType === step_scaling_action_1.AdjustmentType.ExactCapacity; const intervals = aws_autoscaling_common_1.normalizeIntervals(props.scalingSteps, changesAreAbsolute); const alarms = aws_autoscaling_common_1.findAlarmThresholds(intervals); if (alarms.lowerAlarmIntervalIndex !== undefined) { const threshold = intervals[alarms.lowerAlarmIntervalIndex].upper; this.lowerAction = new step_scaling_action_1.StepScalingAction(this, 'LowerPolicy', { adjustmentType: props.adjustmentType, cooldownSec: props.cooldownSec, metricAggregationType: aggregationTypeFromMetric(props.metric), minAdjustmentMagnitude: props.minAdjustmentMagnitude, scalingTarget: props.scalingTarget, }); for (let i = alarms.lowerAlarmIntervalIndex; i >= 0; i--) { this.lowerAction.addAdjustment({ adjustment: intervals[i].change, lowerBound: i !== 0 ? intervals[i].lower - threshold : undefined, upperBound: intervals[i].upper - threshold, }); } this.lowerAlarm = new cloudwatch.Alarm(this, 'LowerAlarm', { // Recommended by AutoScaling metric: props.metric.with({ periodSec: 60 }), alarmDescription: 'Lower threshold scaling alarm', comparisonOperator: cloudwatch.ComparisonOperator.LessThanOrEqualToThreshold, evaluationPeriods: 1, threshold, }); this.lowerAlarm.onAlarm(this.lowerAction); } if (alarms.upperAlarmIntervalIndex !== undefined) { const threshold = intervals[alarms.upperAlarmIntervalIndex].lower; this.upperAction = new step_scaling_action_1.StepScalingAction(this, 'UpperPolicy', { adjustmentType: props.adjustmentType, cooldownSec: props.cooldownSec, metricAggregationType: aggregationTypeFromMetric(props.metric), minAdjustmentMagnitude: props.minAdjustmentMagnitude, scalingTarget: props.scalingTarget, }); for (let i = alarms.upperAlarmIntervalIndex; i < intervals.length; i++) { this.upperAction.addAdjustment({ adjustment: intervals[i].change, lowerBound: intervals[i].lower - threshold, upperBound: i !== intervals.length - 1 ? intervals[i].upper - threshold : undefined, }); } this.upperAlarm = new cloudwatch.Alarm(this, 'UpperAlarm', { // Recommended by AutoScaling metric: props.metric.with({ periodSec: 60 }), alarmDescription: 'Upper threshold scaling alarm', comparisonOperator: cloudwatch.ComparisonOperator.GreaterThanOrEqualToThreshold, evaluationPeriods: 1, threshold, }); this.upperAlarm.onAlarm(this.upperAction); } } }
JavaScript
class Chart { /** * Constructor of all chart types created by * sgvizler.charts inherit from. * @memberof sgvizler.Chart * @constructor sgvizler.Chart */ constructor() { /** * Give the options of chart * @property options * @memberof sgvizler.Chart * @public * @type {{}} */ this.options = {}; this._tabDependences = []; this._patternOptions = CHART_PATTERN_OPTIONS.EMPTY; this._width = ''; this._height = ''; this._optionsRaw = ''; this._class = ''; this._style = ''; this._width = '100%'; this._isDone = false; let currentThis = this; Loader.on('loaded', () => { if (currentThis.container != null && !currentThis._isDone && currentThis.isLoadedAllDependencies() && currentThis._resultSparql !== null && currentThis._resultSparql !== undefined) { currentThis.doDraw(); } }); } loadDependenciesAndDraw(result) { return __awaiter(this, void 0, void 0, function* () { Logger.log(this.container, 'Chart loaded dependencies : ' + this.container.id); // let promisesArray: Array<any> = [] this._resultSparql = result; if (this.isLoadedAllDependencies()) { yield this.doDraw(); } else { yield this.loadDependencies(); } }); } loadDependencies() { return __awaiter(this, void 0, void 0, function* () { let promisesArray = []; for (let dep of this._tabDependences) { promisesArray.push(dep.load()); } return Promise.all(promisesArray); }); } /** * Todo * @memberof sgvizler.Chart * @returns {CHART_PATTERN_OPTIONS} */ get patternOptions() { return this._patternOptions; } /** * Todo * @memberof sgvizler.Chart * @returns {string} */ get classHtml() { return this._class; } /** * Todo * @memberof sgvizler.Chart * @param {string} value */ set classHtml(value) { this._class = value; } /** * Todo * @memberof sgvizler.Chart * @returns {string} */ get style() { return this._style; } /** * Todo * @memberof sgvizler.Chart * @param {string} value */ set style(value) { this._style = value; } /** * * @memberof sgvizler.Chart * @returns {Container} */ get container() { return this._container; } /** * Todo * @memberof sgvizler.Chart * @param {Container} value */ set container(value) { this._container = value; } /** * Todo * @memberof sgvizler.Chart * @returns {string} */ get optionsRaw() { return this._optionsRaw; } /** * Todo * @memberof sgvizler.Chart * @param {string} value */ set optionsRaw(value) { this._optionsRaw = value; this.doParseOptionsRaw(); } /** * To read new options for interactive chart */ get newOptionsRaw() { return this.optionsRaw; } /** * Todo * @memberof sgvizler.Chart * @returns {string} */ get height() { return this._height; } /** * Todo * @memberof sgvizler.Chart * @param {string} value */ set height(value) { this._height = value; } /** * Todo * @memberof sgvizler.Chart * @returns {string} */ get width() { return this._width; } /** * Todo * @memberof sgvizler.Chart * @param {string} value */ set width(value) { this._width = value; } /** * Todo * @memberof sgvizler.Chart * @returns {string} */ getHTMLStyleOrClass() { let html = ''; let opts = this.options; if (this._patternOptions === CHART_PATTERN_OPTIONS.CLASS) { html = Object.keys(opts).map((property) => '${opts[property]}').join(' '); html = 'class="' + html + '"'; } if (this._patternOptions === CHART_PATTERN_OPTIONS.STYLE) { html = Object.keys(opts).map((property) => '${property}:${opts[property]}').join(';'); html = 'style="' + html + '"'; } return html; } addScript(url, loadBefore) { let dep = new ScriptDependency(url, loadBefore); this._tabDependences.push(dep); return dep; } addCss(url, loadBefore) { let dep = new CssDependency(url, loadBefore); this._tabDependences.push(dep); return dep; } isLoadedAllDependencies() { for (let dep of this._tabDependences) { if (!Loader.isLoaded(dep)) { return false; } } return true; } doDraw() { Logger.log(this.container, 'Chart started : ' + this._container.id); let currentThis = this; let isEmpty = false; if (currentThis._resultSparql === null || currentThis._resultSparql === undefined) { isEmpty = true; } else { let cols = currentThis._resultSparql.head.vars; let rows = currentThis._resultSparql.results.bindings; let noCols = cols.length; let noRows = rows.length; if (noCols === 0) { isEmpty = true; } } if (isEmpty) { Logger.displayFeedback(currentThis._container, MESSAGES.ERROR_DATA_EMPTY); Logger.log(currentThis.container, 'Chart finished with error : ' + currentThis._container.id); } else { currentThis.draw(currentThis._resultSparql).then(function (valeur) { currentThis._isDone = true; Logger.log(currentThis.container, 'Chart finished : ' + currentThis._container.id); Logger.fireDoneEvent(currentThis._container); }, function (error) { console.log(error); Logger.displayFeedback(currentThis._container, MESSAGES.ERROR_CHART, [error]); Logger.log(currentThis.container, 'Chart finished with error : ' + currentThis._container.id); }); } } // noinspection JSValidateJSDoc // noinspection tslint /** * todo * @memberof sgvizler.Chart * @param {RegExp} patternOption * @param {CHART_PATTERN_OPTIONS} typePattern */ execPattern(patternOption, typePattern) { let matchArray; let raw = this._optionsRaw; while ((matchArray = patternOption.exec(raw)) !== null) { // tslint:disable-line // this.options[matchArray[1].toLowerCase()] = matchArray[2].trim() // this.options[matchArray[1]] = matchArray[2].trim() Tools.assignProperty(this.options, matchArray[1], matchArray[2].trim()); this._patternOptions = typePattern; } } /** * todo * @memberof sgvizler.Chart */ doParseOptionsRaw() { // 3 possibilities // pattern option : separate by optionA=a|optionB=b // pattern style : any options, only style separate by ; // pattern class : words separate by space // noinspection TsLint let patternOption = /\|? *([^=]*) *= *([^=|]*)/iy; // tslint:disable-line let patternStyle = /([^:]+):([^:;]+) *;?/iy; // tslint:disable-line let patternClass = /([^ |;]+) ?/iy; // tslint:disable-line let patternWiki = /\!? *([^=]*) *= *([^=!]*)/iy; // tslint:disable-line let raw = this._optionsRaw; if (raw === '') { this._patternOptions = CHART_PATTERN_OPTIONS.EMPTY; } else { this._patternOptions = CHART_PATTERN_OPTIONS.UNKNOWN; } if (this._optionsRaw.indexOf('{') === 0 && this.patternOptions === CHART_PATTERN_OPTIONS.UNKNOWN) { //this.execPattern(patternObject,CHART_PATTERN_OPTIONS.OBJECT) // todo ? this._patternOptions = CHART_PATTERN_OPTIONS.OBJECT; } if (this._optionsRaw.indexOf('|') === -1 && this.patternOptions === CHART_PATTERN_OPTIONS.UNKNOWN) { this.execPattern(patternWiki, CHART_PATTERN_OPTIONS.WIKI); } if (this.patternOptions === CHART_PATTERN_OPTIONS.UNKNOWN) { this.execPattern(patternOption, CHART_PATTERN_OPTIONS.VARIABLE); } if (this.patternOptions === CHART_PATTERN_OPTIONS.UNKNOWN) { this.execPattern(patternStyle, CHART_PATTERN_OPTIONS.STYLE); } if (this.patternOptions === CHART_PATTERN_OPTIONS.UNKNOWN) { let matchArray; let raw = this._optionsRaw; let i = 0; while ((matchArray = patternClass.exec(raw)) !== null) { // tslint:disable-line this.options['class' + i] = matchArray[2]; this._patternOptions = CHART_PATTERN_OPTIONS.UNKNOWN; i++; } } if (this.patternOptions === CHART_PATTERN_OPTIONS.UNKNOWN) { Logger.displayFeedback(this.container, MESSAGES.ERROR_CHART_PATTERN_OPTION_UNKNOWN, [this._optionsRaw]); } else if (this.patternOptions === CHART_PATTERN_OPTIONS.WIKI || this.patternOptions === CHART_PATTERN_OPTIONS.VARIABLE || this.patternOptions === CHART_PATTERN_OPTIONS.STYLE) { if (this.options['width'] !== undefined) { this.width = this.options['width']; } if (this.options['height'] !== undefined) { this.height = this.options['height']; } } } }
JavaScript
class Logger { static done(callback) { this._doneCallEvent = callback; return this; } static fireDoneEvent(container) { container.loadingIcon.hide(); if (this._doneCallEvent) { this._doneCallEvent(container.id); } } static fail(callback) { this._failCallEvent = callback; return this; } static fireFailEvent(container) { container.loadingIcon.hide(); if (this._failCallEvent) { this._failCallEvent(container.id); } } /** * Logs a message. * @method log * @protected * @param {string} message The message to log. */ static log(container, message) { if (container.loglevel === 2) { console.log(this.elapsedTime() + 's: ' + message); } } static logSimple(message) { console.log(this.elapsedTime() + 's: ' + message); } /** * Todo * @param {Container} container * @param {MESSAGES} messageName * @param {Array<string>} args */ static displayFeedback(container, messageName, args) { let message = Messages.get(messageName, args); if (container.loglevel === 2) { if (message) { let obj = document.getElementById(container.id); if (obj) { obj.innerHTML = "<p style='color:red'>" + message + '</p>'; } } } Logger.fireFailEvent(container); } /** * @method timeElapsed * @private * @return {number} The number of seconds elapsed since * this sgvizler got loaded. */ static elapsedTime() { return (Date.now() - this._startTime) / 1000; } }
JavaScript
class Request { constructor() { this._query = ''; this._endpoint = ''; this._endpointOutputFormat = SPARQL_RESULT.json; this._method = 'GET'; this._queryParameter = 'query'; this.listeners = {}; } // private _endpointResultsUrlPart: string // // private _chartPathFunction: string // private _endpointURL: string /** * * @returns {string} */ get method() { return this._method; } /** * * @param {string} value */ set method(value) { this._method = value; } /** * * @returns {Container} */ get container() { return this._container; } /** * * @param {Container} value */ set container(value) { this._container = value; } /** * Get query string. * @method query * @public * @return {string} */ get query() { return this._query; } /** * Set query string. * @method query * @public * @chainable * @param value */ set query(value) { this._query = value; } /** * Get endpoint URL. * @method endpointURL * @public * @return {string} */ get endpoint() { return this._endpoint; } /** * Set endpoint URL. * @method endpointURL * @public * @chainable * @example * sgvizler.endpointURL('http://sparql.dbpedia.org'); * sets this Query object's endpoint to DBpedia. * @param value */ set endpoint(value) { this._endpoint = value; } /** * Get endpoint output format. * @method endpointOutputFormat * @public * @return {string} */ get endpointOutputFormat() { return this._endpointOutputFormat; } /** * Set endpoint output format. Legal values are `'xml'`, * `'json'`, `'jsonp'`. * @method endpointOutputFormat * @public * @chainable * @param value */ set endpointOutputFormat(value) { this._endpointOutputFormat = value; } /** * todo * @returns {string} */ get queryParameter() { return this._queryParameter; } /** * todo * @param {string} value */ set queryParameter(value) { this._queryParameter = value; } sendRequest() { let myRequest = this; // Create new promise with the Promise() constructor; // This has as its argument a function // with two parameters, resolve and reject return new Promise(function (resolve, reject) { // Standard XHR to load an image let xhr = new XMLHttpRequest(); let data; let url = myRequest.endpoint; if (myRequest.method.toLowerCase() === 'get') { url += '?' + myRequest.queryParameter + '=' + encodeURIComponent(myRequest.query) + '&output=' + SparqlTools.getOutputLabel(myRequest.endpointOutputFormat); } else { data = myRequest.queryParameter + '=' + encodeURIComponent(myRequest.query); } xhr.open(myRequest.method, url, true); xhr.setRequestHeader('Accept', SparqlTools.getHeaderAccept(myRequest.endpointOutputFormat)); // hide errors xhr.responseType = SparqlTools.getXMLHttpRequestResponseType(myRequest.endpointOutputFormat) // TODO check progress xhr.onprogress = function (oEvent) { if (oEvent.lengthComputable) { let percentComplete = (oEvent.loaded / oEvent.total) * 100; console.log('onprogress' + percentComplete); } }; // When the request loads, check whether it was successful xhr.onload = function (options) { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { // If successful, resolve the promise by passing back the request response resolve(JSON.parse(xhr.response)); } else { // If it fails, reject the promise with a error message reject(SparqlError.getErrorMessageWithStatus200(xhr)); } } }; xhr.onerror = () => reject(SparqlError.getErrorWithOtherStatus(xhr, url)); // Send the request if (data) { xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send(data); } else { xhr.send(); } // console.log(myRequest.query) }); } }
JavaScript
class Container { /** * Collects values designated for sgvizler in the given. * See also property PREFIX. * @param {string} elementID The ID for which the attributes should be collected. */ constructor(elementID) { this._lang = 'en'; this._chartOptions = ''; this._chartName = ''; this._loglevel = 0; this._id = ''; // step 1 : read parameters and create the object Query // pre-condition let element = document.getElementById(elementID); if (element === null) { throw new Error('elementID unknown : ' + elementID); } let self = Container; this._state = CONTAINER_STATE.LOADING; let elmAttrs = element.attributes; // read basic parameters if (elmAttrs[self.LANG]) { this._lang = elmAttrs[self.LANG].value; } if (elmAttrs[self.LOG_LEVEL_ATTRIBUTE_NAME]) { this._loglevel = parseInt(elmAttrs[self.LOG_LEVEL_ATTRIBUTE_NAME].value, 10); } if (elmAttrs[self.CHART_ATTRIBUTE_NAME]) { this._chartName = elmAttrs[self.CHART_ATTRIBUTE_NAME].value; // This code will disappear but it's necessary for the migration with the old Sgvizler switch (this._chartName) { case 'google.visualization.AnnotatedTimeLine': case 'google.visualization.Gauge': case 'google.visualization.ImageSparkLine': case 'google.visualization.MotionChart': case 'sgvizler.visualization.D3ForceGraph': case 'sgvizler.visualization.DefList"': case 'sgvizler.visualization.DraculaGraph': case 'sgvizler.visualization.List': case 'sgvizler.visualization.Text': case 'sgvizler.visualization.MapWKT': { console.warn('Sgvizler2 : ' + this._chartName + ' is deprecated. Please choose another chart.'); this._chartName = 'bordercloud.visualization.DataTable'; break; } case 'sgvizler.visualization.Map': { console.warn('Sgvizler2 : ' + this._chartName + ' is obsolete. Please choose leaflet.visualization.Map or another chart.'); this._chartName = 'leaflet.visualization.Map'; break; } case 'google.visualization.GeoMap': { console.warn('Sgvizler2 : ' + this._chartName + ' is obsolete. Please choose google.visualization.Map or another chart.'); this._chartName = 'google.visualization.Map'; break; } case 'google.visualization.PieChart': { console.warn('Sgvizler2 : ' + this._chartName + ' is obsolete. Please choose google.visualization.Pie or another chart.'); this._chartName = 'google.visualization.Pie'; break; } } } if (elmAttrs[self.CHART_OPTION_ATTRIBUTE_NAME]) { this._chartOptions = Tools.decodeHtml(elmAttrs[self.CHART_OPTION_ATTRIBUTE_NAME].value); } // build request object let request = new Request(); request.container = this; this._id = elementID; if (elmAttrs[self.QUERY_ATTRIBUTE_NAME]) { request.query = Tools.decodeHtml(elmAttrs[self.QUERY_ATTRIBUTE_NAME].value); } if (elmAttrs[self.ENDPOINT_ATTRIBUTE_NAME]) { request.endpoint = Tools.decodeHtml(elmAttrs[self.ENDPOINT_ATTRIBUTE_NAME].value); } else { this._state = CONTAINER_STATE.FAILED; Logger.displayFeedback(this, MESSAGES.ERROR_ENDPOINT_FORGOT); return; } if (elmAttrs[self.OUTPUT_FORMAT_ATTRIBUTE_NAME]) { request.endpointOutputFormat = SparqlTools.convertString(elmAttrs[self.OUTPUT_FORMAT_ATTRIBUTE_NAME].value); } if (elmAttrs[self.OUTPUT_METHOD_ATTRIBUTE_NAME]) { request.method = elmAttrs[self.OUTPUT_METHOD_ATTRIBUTE_NAME].value; } if (elmAttrs[self.QUERY_PARAMETER_ATTRIBUTE_NAME]) { request.queryParameter = elmAttrs[self.QUERY_PARAMETER_ATTRIBUTE_NAME].value; } this._request = request; // build the chart object let chart = Tools.getObjectByPath(this.chartName); if (chart === undefined) { this._state = CONTAINER_STATE.FAILED; Logger.displayFeedback(this, MESSAGES.ERROR_CHART_UNKNOWN, [this.chartName]); } else { chart.container = this; // read with and height of container before chart options try { let element = $('#' + elementID); let widthCss = element.css('width'); let heightCss = element.css('height'); if (widthCss !== null) { chart.width = widthCss; } if (heightCss !== null && heightCss !== '0px') { chart.height = heightCss; } } catch (e) { // do nothing, unit test not support jquery } // read options (and replace may be with and height) chart.optionsRaw = this._chartOptions; this._chart = chart; } this.saveRefOfContainer(); } /** * Save the reference of container */ saveRefOfContainer() { let index = -1; let len = Container.list.length; for (let i = 0; i < len; i++) { let dep = Container.list[i]; if (this.id === Container.list[i].id) { //this._dependenciesToLoad.splice(i) index = i; } } if (index != -1) { Container.list[index] = this; } else { Container.list.push(this); } } /** * Draws the sgvizler-containers with the given element id. * @method containerDraw * @param {string} elementID * @param options * @returns {Promise<void>} */ static drawWithElementId(elementID, options) { return __awaiter(this, void 0, void 0, function* () { let container = new Container(elementID); // console.log(container) container._loadingIcon = new LoadingIcon(container); container.loadingIcon.show(); Logger.log(container, 'drawing id: ' + elementID); yield container.draw(); }); } // noinspection JSValidateJSDoc /** * Draws all sgvizler-containers on page. * @returns {Promise<any>} */ static drawAll() { let promisesArray = []; let ids = []; let iterator = document.evaluate('//div[@' + Container.PREFIX + 'query]/@id', document, null, XPathResult.ANY_TYPE, null); let thisNode = iterator.iterateNext(); while (thisNode) { ids.push(thisNode.value); thisNode = iterator.iterateNext(); } for (let id of ids) { promisesArray.push(Container.drawWithElementId(id)); } return Promise.all(promisesArray); } static loadDependenciesId(elementID, options) { return __awaiter(this, void 0, void 0, function* () { let container = new Container(elementID); // console.log(container) Logger.log(container, 'Load dependencies id: ' + elementID); yield container.loadDependencies(); }); } static loadAllDependencies() { let promisesArray = []; let ids = []; let iterator = document.evaluate('//div[@' + Container.PREFIX + 'query]/@id', document, null, XPathResult.ANY_TYPE, null); let thisNode = iterator.iterateNext(); while (thisNode) { ids.push(thisNode.value); thisNode = iterator.iterateNext(); } for (let id of ids) { promisesArray.push(Container.loadDependenciesId(id)); } return Promise.all(promisesArray); } /** * * @param {string} elementID * @param {string} endpoint * @param {string} query * @param {string} chartName * @param {string} options * @param {string} loglevel * @returns {string} */ static create(elementID, endpoint, query, chartName, options, loglevel, output, method, parameter, lang) { let element = document.getElementById(elementID); if (element === null) { throw new Error('elementID unknown : ' + elementID); } let self = Container; let attrQuery = document.createAttribute(self.QUERY_ATTRIBUTE_NAME); let attrEndpoint = document.createAttribute(self.ENDPOINT_ATTRIBUTE_NAME); let attrChart = document.createAttribute(self.CHART_ATTRIBUTE_NAME); // attrQuery.value = Tools.escapeHtml(query) attrQuery.value = query; attrEndpoint.value = endpoint; attrChart.value = chartName; element.setAttributeNode(attrQuery); element.setAttributeNode(attrEndpoint); element.setAttributeNode(attrChart); if (options) { let attrOptions = document.createAttribute(self.CHART_OPTION_ATTRIBUTE_NAME); attrOptions.value = options; element.setAttributeNode(attrOptions); } if (loglevel) { let attrLevel = document.createAttribute(self.LOG_LEVEL_ATTRIBUTE_NAME); attrLevel.value = loglevel; element.setAttributeNode(attrLevel); } if (output) { let attrOutput = document.createAttribute(self.OUTPUT_FORMAT_ATTRIBUTE_NAME); attrOutput.value = output; element.setAttributeNode(attrOutput); } if (method) { let attrMethod = document.createAttribute(self.OUTPUT_METHOD_ATTRIBUTE_NAME); attrMethod.value = method; element.setAttributeNode(attrMethod); } if (parameter) { let attrQueryAttribut = document.createAttribute(self.QUERY_PARAMETER_ATTRIBUTE_NAME); attrQueryAttribut.value = parameter; element.setAttributeNode(attrQueryAttribut); } if (lang) { let attrQueryAttribut = document.createAttribute(self.LANG); attrQueryAttribut.value = lang; element.setAttributeNode(attrQueryAttribut); } return element.innerHTML; } /** * * @returns {string} */ get id() { return this._id; } /** * * @returns {string} */ get lang() { return this._lang; } /** * Get the name of chart object. * @returns {string} */ get chartName() { return this._chartName; } /** * Get the loading icon of container. * @returns {string} */ get loadingIcon() { return this._loadingIcon; } ///////////////////////////////////// OPTIONS /** * * @returns {string} */ get chartOptions() { return this._chartOptions; } /** * * @returns {Chart} */ get chart() { return this._chart; } /** * * @returns {Request} */ get request() { return this._request; } /** * * @returns {number} */ get loglevel() { return this._loglevel; } /** * * @returns {Promise<void>} */ draw() { return __awaiter(this, void 0, void 0, function* () { let sparqlResult; if (this._state === CONTAINER_STATE.FAILED) { return; } try { sparqlResult = yield this.request.sendRequest(); // console.log(queryResult) } catch (error) { console.log(error); Logger.displayFeedback(this, MESSAGES.ERROR_REQUEST, [error]); this._state = CONTAINER_STATE.FAILED; } if (this._state === CONTAINER_STATE.FAILED) { return; } let sparqlResultI = sparqlResult; if (sparqlResultI.head === undefined) { console.log(sparqlResultI); Logger.displayFeedback(this, MESSAGES.ERROR_CHART, ['ERROR_head_undefined']); this._state = CONTAINER_STATE.FAILED; } try { this._chart.loadDependenciesAndDraw(sparqlResultI); } catch (error) { console.log(error); Logger.displayFeedback(this, MESSAGES.ERROR_CHART, [error]); this._state = CONTAINER_STATE.FAILED; } }); } loadDependencies() { return __awaiter(this, void 0, void 0, function* () { try { yield this._chart.loadDependencies(); } catch (error) { console.log(error); Logger.displayFeedback(this, MESSAGES.ERROR_DEPENDENCIES, [error]); this._state = CONTAINER_STATE.FAILED; } }); } }
JavaScript
class Tools$1 { static decodeFormatSize(value) { let result = value; if (Number.isNaN(Number(value))) { let patternPercent = /%/gi; let patternPixel = /px/gi; if (result.search(patternPixel) >= 0) { result = result.replace('px', ''); if (!Number.isNaN(Number(result))) { result = Number(result); } } else if (result.search(patternPercent) >= 0) ; } return result; } }
JavaScript
class TreeIndex { /** * Get value at path. * * @return {object} The value stored for a given path * * @example * * obj.get(['b', 'b1']); * => b1Val */ get (path) { if (arguments.length > 1) { path = Array.prototype.slice(arguments, 0) } path = _pathify(path) return get(this, path) } getAll (path) { if (arguments.length > 1) { path = Array.prototype.slice(arguments, 0) } path = _pathify(path) if (!isArray(path)) { throw new Error('Illegal argument for TreeIndex.get()') } const node = get(this, path) return this._collectValues(node) } set (path, value) { path = _pathify(path) setWith(this, path, value, function (val) { if (!val) return new TreeNode() }) } delete (path) { path = _pathify(path) if (path.length === 1) { delete this[path[0]] } else { const key = path[path.length - 1] path = path.slice(0, -1) const parent = get(this, path) if (parent) { delete parent[key] } } } clear () { const root = this for (const key in root) { if (hasOwnProperty(root, key)) { delete root[key] } } } traverse (fn) { this._traverse(this, [], fn) } forEach (...args) { this.traverse(...args) } _traverse (root, path, fn) { let id for (id in root) { if (!hasOwnProperty(root, id)) continue const child = root[id] const childPath = path.concat([id]) if (child instanceof TreeNode) { this._traverse(child, childPath, fn) } else { fn(child, childPath) } } } _collectValues (root) { // TODO: don't know if this is the best solution // We use this only for indexes, e.g., to get all annotation on one node const vals = {} this._traverse(root, [], function (val, path) { const key = path[path.length - 1] vals[key] = val }) return vals } }
JavaScript
class UnknownError extends Error { constructor(msg) { super() this.type = 'cli' this.message = msg } }
JavaScript
class AtomTree { constructor() { this.root = [] } get length() { return this.root.length } /** * insert - Insert an atom into the atom tree at it's appropriate location * * @param {Atom} atom An Atom object */ insert(atom) { let root = this.root let children = root.flatMap(function(e) { return explode(e) }) .filter(function(e) { if (isChild(atom, e)) { return e } }) if (children.length == 0) { root.push(atom) } else { let lastChild = children[children.length-1] lastChild.insert(atom) } } /** * findAtoms - Find atoms by name * * @param {String} atomName The name of all the atoms you want to find * @return {Array<Atom>} An array of atoms with the name searched for */ findAtoms(atomName) { return this.root.flatMap(function(e) { return explode(e) }) .filter(function(e) { if (e.name == atomName) { return e } }) } }
JavaScript
class Nodo { constructor(data, next, prev) { this.data = data; //Guardando el dato del nodo this.next = next; //Guardando el dato del siguiente nodo this.prev = prev; //Guardando eld ato del anterior nodo } }
JavaScript
class ListaDEnlazada { constructor() { this.head = null; //Cabeza de la lista this.tail = null; //Cola de la lista this.size = 0; //Tamaño de la lista } //Metodo para agergar un nuevo nodo en la cabeza de la lista addToHead(data){ const newNodo = new Nodo(data, this.head, null); if(this.head){ newNodo.next = this.head; this.head. prev = newNodo; this.head = newNodo; } else { this.head = newNodo; this.tail = newNodo; } this.size++; } //Metodo para agergar un nuevo nodo en el final de la lista addToTail(data){ const newNodo = new Nodo(data, null, this.tail); if(this.tail){ newNodo.prev = this.tail this.tail.next = newNodo; this.tail = newNodo; } else { this.tail = newNodo; this.head = newNodo; } this.size++; } //Metodo para agregar un nodo en cierta posicion de la lista insertAt(data, index) { if (index < 0 || index > this.size) { return null } const newNodo = new Nodo(data, null, null); let current = this.head; let previous; if (index === 0) { newNodo.next = current; current.prev = newNodo; this.head = newNodo; } else { for (let i = 0; i < index; i++) { previous = current; current = current.next; } newNodo.next =current; newNodo.prev = previous; current.prev = newNodo; previous.next = newNodo; } } //Eliminar un nodo al principio de la lista removeFromHead() { if (this.isEmpty()) { return null } const valueToReturn = this.head.data; if (this.head === this.tail) { this.head = null; this.tail = null; } else { this.head = this.head.next; this.head.prev = null; } this.size--; return valueToReturn; } //Eliminar un nodo al final de la lista removeFromTail() { if (this.isEmpty()) { return null } const valueToReturn = this.tail.data; if (this.head === this.tail) { this.head = null; this.tail = null; } else { this.tail = this.tail.prev; this.tail.next = null; } this.size--; return valueToReturn; } //Eliminar un nodo con cierto dato de la lista removeData(data){ let current = this.head; let previous = null; while(current !== null) { if (current.data === data) { if (!previous) { this.removeFromHead(); } else if (!current.next) { this.removeFromTail(); } else { previous.next = current.next; current.next.prev = previous; } this.size--; return current.data; } previous = current; current = current.next; } return null; } //Metodo para actualizar un nodo en cierta posicion de la lista updateAt(data, index){ if (index < 0 || index > this.size) { return null } const newNodo = new Nodo(data, null, null); let current = this.head; let previous; if (index === 0) { newNodo.next = this.head.next; newNodo.prev = this.head.prev; this.head = newNodo; } else { for (let i = 0; i < index; i++) { previous = current; current = current.next; } newNodo.next = current.next; newNodo.prev = previous; previous.next = newNodo; current.next.prev = newNodo; } } //Encontrar un nodo con cierto dato en la lista findData(data){ let current = this.head; let previous = null; while(current !== null) { if (current.data === data) { return "El elemento se encuentra dentro de la lista"; } previous = current; current = current.next; } return "El elemento no ha sido encontrado en la lista"; } //Imprimir la lista print() { let current = this.head; let result = ''; while(current) { result += current.data + ' ⇦⇨ '; current = current.next; }; return result += 'X '; }; // Revisar el tamaño de la lista getSize(){ return this.size; } //Revisar si la lista esta vacia isEmpty(){ if(this.getSize() === 0){ return true; } else { return false; } } //Guardar la lista en un archivo JSON saveFile(){ var fs = require('fs'); const jsonContent = JSON.stringify(this); fs.writeFile("./LinkedList", jsonContent, 'utf8', function (err){ if (err){ return console.log(err); } console.log("The file was saved!"); }) } }
JavaScript
class MesaSubscriptionKeyManagementService extends ExternalAPIKeyManagementServiceCore { constructor(...args) { super( KEY_SECURE_LOCAL_STORAGE_MESA_SUBSCRIPTION_KEY, "Azure Subscription", ...args ); } }
JavaScript
class Create extends Component { constructor(props) { super(props); this.state = { current: 0, }; } next() { const current = this.state.current + 1; this.setState({ current }); } prev() { const current = this.state.current - 1; this.setState({ current }); } goStep(current) { this.setState({ current }); } render() { const { current } = this.state; const steps = [ { title: '유형 선택', content: ( <div className={styles.inner}> <Radio.Group defaultValue="a" buttonStyle="solid"> <Radio.Button value="a">All</Radio.Button> <Radio.Button value="w">Windows</Radio.Button> <Radio.Button value="l">Linux</Radio.Button> </Radio.Group> <Radio.Group defaultValue="6" buttonStyle="solid" style={{marginLeft: 20}}> <Radio.Button value="3">32bit</Radio.Button> <Radio.Button value="6">64bit</Radio.Button> </Radio.Group> <Radio.Group defaultValue="a" buttonStyle="solid" style={{marginLeft: 20}}> <Radio.Button value="a">All</Radio.Button> <Radio.Button value="s">SSD</Radio.Button> <Radio.Button value="h">HDD</Radio.Button> </Radio.Group> <Divider /> <Row gutter={[16, 16]}> <Col span={12}> <Card hoverable onClick={this.next.bind(this)} // cover={<div className={styles.cover}><img src={vm_ubuntu} /></div>} > <Meta avatar={<Avatar src={vm_windows} />} title="WINDOWS 10" description="64bit, SSD" /> </Card> </Col> <Col span={12}> <Card hoverable // onClick={this.showDrawer} // cover={<div className={styles.cover}><img src={vm_ubuntu} /></div>} > <Meta avatar={<Avatar src={vm_suse} />} title="SUSE Linux" description="64bit, SSD" /> </Card> </Col> <Col span={12}> <Card hoverable // onClick={this.showDrawer} // cover={<div className={styles.cover}><img src={vm_ubuntu} /></div>} > <Meta avatar={<Avatar src={vm_centos} />} title="CentOs" description="64bit, SSD" /> </Card> </Col> <Col span={12}> <Card hoverable // onClick={this.showDrawer} // cover={<div className={styles.cover}><img src={vm_ubuntu} /></div>} > <Meta avatar={<Avatar src={vm_redhat} />} title="Redhat" description="64bit, SSD" /> </Card> </Col> <Col span={12}> <Card hoverable // onClick={this.showDrawer} // cover={<div className={styles.cover}><img src={vm_ubuntu} /></div>} > <Meta avatar={<Avatar src={vm_linux} />} title="Linux" description="64bit, SSD" /> </Card> </Col> </Row> {/*<Button block onClick={this.next.bind(this)}>접속 문제</Button>*/} {/*<Button block>설치 문의</Button>*/} {/*<Button block>사용 문의</Button>*/} {/*<Button block>기타 문의</Button>*/} </div> ), }, { title: '자원 선택', content: ( <div className={styles.inner}> <Button block>VM이 보이지 않습니다.</Button> <Button block>접속시 로딩시간이 많이 소요됩니다.</Button> <Button block onClick={this.next.bind(this)}>접속이 되지 않습니다.</Button> </div> ), }, { title: '검토', content: ( <Result // status="success" title="관리자 문의 필요" subTitle="재기동후에도 VM 접속이 안될 경우, 고장신고를 해주시기 바랍니다." extra={[ <Button type="primary" key="console"> 재기동 </Button>, <Button key="buy">고장신고</Button>, ]} > {/*<div className="desc">*/} {/* <Paragraph>*/} {/* <Text*/} {/* strong*/} {/* style={{*/} {/* fontSize: 16,*/} {/* }}*/} {/* >*/} {/* The content you submitted has the following error:*/} {/* </Text>*/} {/* </Paragraph>*/} {/* <Paragraph>*/} {/* <Icon style={{ color: 'red' }} type="close-circle" /> Your account has been frozen*/} {/* <a>Thaw immediately &gt;</a>*/} {/* </Paragraph>*/} {/* <Paragraph>*/} {/* <Icon style={{ color: 'red' }} type="close-circle" /> Your account is not yet eligible to*/} {/* apply <a>Apply Unlock &gt;</a>*/} {/* </Paragraph>*/} {/*</div>*/} </Result> ), }, ]; return ( <div className={styles.container}> <Steps current={current} onChange={this.goStep.bind(this)}> {steps.map(item => ( <Step key={item.title} title={item.title}/> ))} </Steps> <div>{steps[current].content}</div> {/*<div className="steps-action">*/} {/* {current < steps.length - 1 && (*/} {/* <Button type="primary" onClick={() => this.next()}>*/} {/* Next*/} {/* </Button>*/} {/* )}*/} {/* {current === steps.length - 1 && (*/} {/* <Button type="primary" onClick={() => message.success('Processing complete!')}>*/} {/* Done*/} {/* </Button>*/} {/* )}*/} {/* {current > 0 && (*/} {/* <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>*/} {/* Previous*/} {/* </Button>*/} {/* )}*/} {/*</div>*/} </div> ); } }
JavaScript
class HospitalSelector extends Component { /** * render - renders the component to the screen (all dropdown menus and the * '+' button) * * @return {JSX} JSX of the component */ render() { return ( <div className="hospitalSelector"> {this.props.hospitalDropdowns} <button className="addHospitalButton addButton" onClick={() => this.props.addHospital()}>+</button> </div> ); } }
JavaScript
class Base { /** * Base constructor * @param {Object} [options] - Options as `key: value` pairs */ constructor(options = {}) { this.options = extend(true, {}, options); this.plugins = []; this.events = {}; // * Prefill with initial events for (const type of ["on", "once"]) { for (const args of Object.entries(this.options[type] || {})) { this[type](...args); } } } /** * Retrieve option value by key, supports subkeys * @param {String} key Option name * @param {*} [fallback] Fallback value for non-existing key * @returns {*} */ option(key, fallback, ...rest) { // Make sure it is string key = String(key); let value = resolve(key, this.options); // Allow to have functions as options if (typeof value === "function") { value = value.call(this, this, ...rest); } return value === undefined ? fallback : value; } /** * Simple l10n support - replaces object keys * found in template with corresponding values * @param {String} str String containing values to localize * @param {Array} params Substitute parameters * @returns {String} */ localize(str, params = []) { return String(str).replace(/\{\{(\w+).?(\w+)?\}\}/g, (match, key, subkey) => { let rez = false; // Plugins have `Plugin.l10n.KEY` if (subkey) { rez = this.option(`${key[0] + key.toLowerCase().substring(1)}.l10n.${subkey}`); } else { rez = this.option(`l10n.${key}`); } if (!rez) { return key; } for (let index = 0; index < params.length; index++) { rez = rez.split(params[index][0]).join(params[index][1]); } return rez; }); } /** * Subscribe to an event * @param {String} name * @param {Function} callback * @returns {Object} */ on(name, callback) { if (isPlainObject(name)) { for (const args of Object.entries(name)) { this.on(...args); } return this; } String(name) .split(" ") .forEach((item) => { const listeners = (this.events[item] = this.events[item] || []); if (listeners.indexOf(callback) == -1) { listeners.push(callback); } }); return this; } /** * Subscribe to an event only once * @param {String} name * @param {Function} callback * @returns {Object} */ once(name, callback) { if (isPlainObject(name)) { for (const args of Object.entries(name)) { this.once(...args); } return this; } String(name) .split(" ") .forEach((item) => { const listener = (...details) => { this.off(item, listener); callback.call(this, this, ...details); }; listener._ = callback; this.on(item, listener); }); return this; } /** * Unsubscribe event with name and callback * @param {String} name * @param {Function} callback * @returns {Object} */ off(name, callback) { if (isPlainObject(name)) { for (const args of Object.entries(name)) { this.off(...args); } return; } name.split(" ").forEach((item) => { const listeners = this.events[item]; if (!listeners || !listeners.length) { return this; } let index = -1; for (let i = 0, len = listeners.length; i < len; i++) { const listener = listeners[i]; if (listener && (listener === callback || listener._ === callback)) { index = i; break; } } if (index != -1) { listeners.splice(index, 1); } }); return this; } /** * Emit an event. * If present, `"*"` handlers are invoked after name-matched handlers. * @param {String} name * @param {...any} details * @returns {Boolean} */ trigger(name, ...details) { for (const listener of [...(this.events[name] || [])].slice()) { if (listener && listener.call(this, this, ...details) === false) { return false; } } // A wildcard "*" event type for (const listener of [...(this.events["*"] || [])].slice()) { if (listener && listener.call(this, name, this, ...details) === false) { return false; } } return true; } /** * Add given plugins to this instance, * this will end up calling `attach` method of each plugin * @param {Object} Plugins * @returns {Object} */ attachPlugins(plugins) { const newPlugins = {}; for (const [key, Plugin] of Object.entries(plugins || {})) { // Check if this plugin is not disabled by option if (this.options[key] !== false && !this.plugins[key]) { // Populate options with defaults from the plugin this.options[key] = extend({}, Plugin.defaults || {}, this.options[key]); // Initialise plugin newPlugins[key] = new Plugin(this); } } for (const [key, plugin] of Object.entries(newPlugins)) { plugin.attach(this); } this.plugins = Object.assign({}, this.plugins, newPlugins); return this; } /** * Remove all plugin instances from this instance, * this will end up calling `detach` method of each plugin * @returns {Object} */ detachPlugins() { for (const key in this.plugins) { let plugin; if ((plugin = this.plugins[key]) && typeof plugin.detach === "function") { plugin.detach(this); } } this.plugins = {}; return this; } }
JavaScript
class AddProduct { /** * Constructor * @param {object} amqp * @param {object} config * @param {object} log * @param {object} db */ constructor({ config, log, db, }) { this.config = config; this.log = log; this.db = db; this.models = models(db); } /** * Run the script using application environment * @return {Promise<void>} */ async bootstrap() { const { Product } = this.models; const productName = this.config.args[0]; this.log.info(`Adding product "${productName}" to License Manager`); let shouldFail = 0; try { await Product.query().upsertGraph({ name: productName, }, { insertMissing: true }); } catch (error) { console.log(error.message); if (error.constraint !== 'products_name_unique') { shouldFail = 1; } } finally { process.exit(shouldFail); } } }
JavaScript
class Dish { async getDishes() { try { let contentful = await client.getEntries({ content_type: "naijaDishes" }) let result = await fetch('dishes.json'); let data = await result.json(); // let dishes = data.items; let dishes = contentful.items; dishes = dishes.map(item => { const { title, price } = item.fields; const { id } = item.sys; const image = item.fields.image.fields.file.url; return { title, price, id, image } }) console.log(dishes); return dishes; } catch (error) { alert('Error in fetching data from the storage'); console.log(error); } } }
JavaScript
class TemplateController extends Controller { /** * Template controller web component constructor. * @constructor */ constructor() { // Call the super with the page to load super({ htmlPath: 'template.html', cssPath: 'template.css', importMetaUrl: import.meta.url }); // Set test variable this.a = 1; this.b = 2; this.c = 3; this.abc = 'hello world'; this.color1 = 'red'; this.color2 = 'green'; } /** * Override loadedCallback function to handle when HTML/CSS has been loaded. * @override */ loadedCallback() { // Create template object this._template = new Template('templateTest', this); // Create special template object this._specialTemplate = new SpecialTemplate('specialTemplateTest', this); // Update the tempates for the first time this._template.update(); this._specialTemplate.update(); } /** * Test double function. * @param {number} value The value to double. * @return {number} The result of the value doubled. */ double(value) { // Return the value amount doubled return value * value; } }
JavaScript
class CustomDeck extends Deck { _handleKeyPress(e) { // Call base method. super._handleKeyPress(e); // Add some extra key bindings for Satechi remote. /*globals window:false*/ const event = window.event || e; const SATECHI_PREV_KEY = 38; if (event.keyCode === SATECHI_PREV_KEY) { this._prevSlide(); } const SATECHI_NEXT_KEY = 40; if (event.keyCode === SATECHI_NEXT_KEY) { this._nextSlide(); } } }
JavaScript
class Body { /** * * @param {TILES2D.Sprite} sprite - The sprite to apply body transformations * */ constructor(sprite = null, shape = new Rectangle()) { /** * The id of the body object, can be used for identify the instance or for indexing * * @private * @member {number} */ this._id = -1; /** * The name of the body object, can be used for identify the instance * * @member {string} */ this.name = ""; /** * The type of the body object, can be used for identify the instance * * @member {string} */ this.type = ""; this.static = false; this.automaticPropertiesUpdate = false; /** * The variable to know if the tile is grabable or not * * @private * @member {boolean} */ this.grabbable = false; /** * Sets the state of the body, used for skip some calculations if it'is "sleeping" * * @member {boolean} * @default false */ this.sleeping = false; this.dragCoefficient = 1.0; //Calculated physics properties this._sprite = null; this._density = 1; this._volume = 1; this._area = {x:0, y:0}; this._mass = 70; this._size = { min: {left: 0, right: 0, top: 0, bottom: 0}, max: {left: 1, right: 1, top: 1, bottom: 1}, pixels: {width: 1,height: 1,depth: 1}, meters: {width: 1, height: 1, depth: 1}, initial: {width: 1, height: 1, depth: 1} } this._frictionArea = {left:{top:0, bottom:0}, right:{top:0, bottom:0}, top:{left:0, right:0}, bottom:{left:0, right:0}}; this._friction = {x: {'1':0, '-1':0}, y: {'1':0, '-1':0}}; this._contactfriction = {x: {'1':0, '-1':0}, y: {'1':0, '-1':0}}; /** * The bounciness of the body * * @private * @member {object} */ this._bounciness = {x: {'1':0, '-1':0}, y: {'1':0, '-1':0}}; //physics properties this.velocity = new Vector2(0, 0); this.acceleration = {x:0, y:0}; //variables for calculation this._environment = false; this._displacedVolume = 0; this._environmentForce = {x:0, y:0}; this._netForce = {x:0, y:0}; this._frictionalForce = {x:0, y:0}; this._dragForce = {x:0, y:0}; this._buoyantForce = {x:0, y:0}; this._movingForce = {x:0, y:0}; this._movingImpulse = {x:0, y:0}; this._direction = {x:0, y:0}; this._impulseDirection = {x: 0, y: 0}; this._restitution = {x: 0, y: 0}; /** * The array list of impulses to apply to this body * * @private * @member {array} */ this._impulseList = []; /** * The array list of bodies in contact with this one * * @private * @member {array} */ this._contactList = []; this.shape = shape; this.sprite = sprite; } set x(value) { this._sprite.x = value; } get x() { return this._sprite.x; } set y(value) { this._sprite.y = value; } get y() { return this._sprite.y; } set width(value) { this._size.pixels.width = value; this._size.initial.width = value; this._size.meters.width = value / SETTINGS.PIXEL_METER_UNIT; this._area.y = this._size.meters.width * this._size.meters.depth; this._volume = this._size.meters.width * this._size.meters.height * this._size.meters.depth; this._sprite.width = value; } get width() { return this._size.pixels.width; } set height(value) { this._size.pixels.height = value; this._size.initial.height = value; this._size.meters.height = value / SETTINGS.PIXEL_METER_UNIT; this._area.x = this._size.meters.height * this._size.meters.depth; this._volume = this._size.meters.width * this._size.meters.height * this._size.meters.depth; this._sprite.height = value; } get height() { return this._size.pixels.height; } set depth(value) { this._size.pixels.depth = value; this._size.initial.depth = value; this._size.meters.depth = value / SETTINGS.PIXEL_METER_UNIT; this._area.x = this._size.meters.height * this._size.meters.depth; this._area.y = this._size.meters.width * this._size.meters.depth; this._volume = this._size.meters.width * this._size.meters.height * this._size.meters.depth; } get depth() { return this._size.pixels.depth; } set frictionArea(value) { if(typeof(value)=='number') this._frictionArea = {left:{top:0, bottom:value}, right:{top:0, bottom:value}, top:{left:0, right:value}, bottom:{left:0, right:value}}; else if(typeof(value)=='object') { if(value.hasOwnProperty('left')) { if(typeof(value.left)=='number') { this._frictionArea.left.top = value.left; this._frictionArea.left.bottom = value.left; } else if(typeof(value)=='object') this._frictionArea.left = value.left; } this._frictionArea = {x: {'1': value.left, '-1': value.right}, y: {'1': value.top, '-1': value.bottom}}; } else this._frictionArea = this._frictionArea; } get frictionArea() { return { left: { top: this.y + (this.height * this._frictionArea.left.top), bottom: this.y + (this.height * this._frictionArea.left.bottom) }, right: { top: this.y + (this.height * this._frictionArea.right.top), bottom: this.y + (this.height * this._frictionArea.right.bottom) }, top: { left: this.x + (this.width * this._frictionArea.top.left), right: this.x + (this.width * this._frictionArea.top.right) }, bottom: { left: this.x + (this.width * this._frictionArea.bottom.left), right: this.x + (this.width * this._frictionArea.bottom.right) } } } set sprite(value) { this._sprite = value; this.width = this._sprite.width; this.height = this._sprite.height; this.depth = this._sprite.width; this.shape.x = this._sprite.x; this.shape.y = this._sprite.y; this.shape.width = this._sprite.width; this.shape.height = this._sprite.height; } get sprite() { return this._sprite; } set friction(value) { if(typeof(value)=='number') { value = Math.min(Math.max(value, 0), 1); this._friction.x['1'] = value; this._friction.x['-1'] = value; this._friction.y['1'] = value; this._friction.y['-1'] = value; } else if(typeof(value)=='object') { if(value.hasOwnProperty('left')) { value.left = Math.min(Math.max(value.left, 0), 1); this._friction.x['1'] = value.left; } if(value.hasOwnProperty('right')) { value.right = Math.min(Math.max(value.right, 0), 1); this._friction.x['-1'] = value.right; } if(value.hasOwnProperty('top')) { value.top = Math.min(Math.max(value.top, 0), 1); this._friction.y['1'] = value.top; } if(value.hasOwnProperty('bottom')) { value.bottom = Math.min(Math.max(value.bottom, 0), 1); this._friction.y['-1'] = value.bottom; } } } get friction() { return { left: this._friction.x['1'], right: this._friction.x['-1'], top: this._friction.y['1'], bottom: this._friction.y['-1'], }; } set bounciness(value) { if(typeof(value)=='number') { value = Math.min(Math.max(value, 0), 1); this._bounciness.x['1'] = value; this._bounciness.x['-1'] = value; this._bounciness.y['1'] = value; this._bounciness.y['-1'] = value; } else if(typeof(value)=='object') { if(value.hasOwnProperty('left')) { value.left = Math.min(Math.max(value.left, 0), 1); this._bounciness.x['1'] = value.left; } if(value.hasOwnProperty('right')) { value.right = Math.min(Math.max(value.right, 0), 1); this._bounciness.x['-1'] = value.right; } if(value.hasOwnProperty('top')) { value.top = Math.min(Math.max(value.top, 0), 1); this._bounciness.y['1'] = value.top; } if(value.hasOwnProperty('bottom')) { value.bottom = Math.min(Math.max(value.bottom, 0), 1); this._bounciness.y['-1'] = value.bottom; } } } get bounciness() { return { left: this._bounciness.x['1'], right: this._bounciness.x['-1'], top: this._bounciness.y['1'], bottom: this._bounciness.y['-1'], }; } set mass(value) { this._mass = value; if(this.automaticPropertiesUpdate) this._density = this._mass / this._volume; } get mass() { return this._mass; } set volume(value) { this._size.meters.depth = value / (this._size.meters.width * this._size.meters.height); if(this.automaticPropertiesUpdate) this._density = this._mass / this._volume; } get volume() { return this._volume; } set density(value) { this._density = value; if(this.automaticPropertiesUpdate) this._mass = this._volume * this._density; } get density() { return this._density; } set area(value) { if(typeof(value)=='number') this._area = {x:value, y:value}; else this._area = value; } get area() { return this._area; } applyForce(axis = "", force = 0) { if (force != 0 && (axis===AXIS.X || axis===AXIS.Y)) this._movingForce[axis] += force; return this; } clearForces() { this._movingForce = {x:0, y:0}; return this; } addImpulse(axis = "", force = 0, time = 0.1, delay = 0) { if(axis===AXIS.X || axis===AXIS.Y) this._impulseList.push({axis:axis, force:force, time:delay+time, delay:delay, _dt:0}); return this; } removeImpulses(axis = "") { if(axis===AXIS.X || axis===AXIS.Y) { this._movingImpulse[axis] = 0; let i; for (i = 0; i < this._impulseList.length; i++) { if(this._impulseList[i].axis==axis) this._impulseList.splice(i, 1); } } return this; } applyImpulses(deltatime = 0) { let i, ilen; for (i = 0, ilen = this._impulseList.length; i < ilen; i++) { this._impulseList[i]._dt += deltatime; if (this._impulseList[i].force != 0 && this._impulseList[i]._dt >= this._impulseList[i].delay) this._movingImpulse[this._impulseList[i].axis] += this._impulseList[i].force; } return this; } clearImpulses() { this._movingImpulse = {x:0, y:0}; let i; for (i = 0; i < this._impulseList.length; i++) { if (this._impulseList[i]._dt >= this._impulseList[i].time) this._impulseList.splice(i, 1); } return this; } clearContacts() { this._impulseDirection.x = 0; this._impulseDirection.y = 0; this._restitution.x = 0; this._restitution.y = 0; this._contactfriction.x['-1'] = this._contactfriction.x['1'] = 0; this._contactfriction.y['-1'] = this._contactfriction.y['1'] = 0; } beginUpdate(deltatime = 0) { //Apply all the impulses this.applyImpulses(deltatime); } update(deltatime = 0) { if(this._sprite) this._sprite.draw(deltatime); } endUpdate(deltatime = 0) { //Clear forces this.clearForces(); //Clear all finished impulses this.clearImpulses(); } }
JavaScript
class Listing extends Component { /** * Renders an element at the specified index. * * @param element element to render * @param i element index */ _renderItem(element, i) { let item; if (i === 0) { item = <ListItem key={i} separator='horizontal'>{element}</ListItem>; } else { item = <ListItem key={i}>{element}</ListItem>; } return item; } render() { return <List> {this.props.source.map((element, i) => this._renderItem(element, i))} </List>; } }
JavaScript
class LinkXLM extends Component { constructor(props) { super(props); this.offers = []; this.reload = this.reload.bind(this); this.loadOffers = this.loadOffers.bind(this); this.handleChange = this.handleChange.bind(this); this.createOffer = this.createOffer.bind(this); this.modifyOffer = this.modifyOffer.bind(this); this.state = { loading: true, checked: false, price: 'loading...', amount: '', offerLoaded: false } } handleChange(e) { if (e.target.id == "check") { this.setState({ checked: !this.state.checked }); } else { this.setState({ [e.target.id]: e.target.value }); } } componentDidMount() { this.mounted = true; this.props.account.offers({ order: "desc", limit: 100 }).then(offers => { this.loadOffers(offers); }).catch(e => { console.log(e); }); fetch('https://min-api.cryptocompare.com/data/price?fsym=XLM&tsyms=USD') .then(data => data.json()) .then(price => { this.setState({ price: price.USD }) }); } reload() { this.offers = []; this.setState({ loading: true }); fetch('https://min-api.cryptocompare.com/data/price?fsym=XLM&tsyms=USD') .then(data => data.json()) .then(price => { this.setState({ price: price.USD }) }); this.props.account.offers({ order: "desc", limit: 100 }).then(offers => { this.loadOffers(offers); }).catch(e => { console.log(e); setTimeout(this.reload, 1500); }); } loadOffers(offers) { if (offers.records.length > 0) { offers.records.forEach(offer => { if (offer.buying.asset_issuer == this.props.account.account_id && offer.selling.asset_type == 'native') { this.offer = offer; this.setState({ amount: offer.amount, price: offer.price }); } }) offers.next().then(offers => { this.loadOffers(offers); }); } else { if (this.mounted) { this.setState({ loading: false }); } } } componentWillUnmount() { this.mounted = false; } modifyOffer() { this.setState({ loading: true }); stellar.linkXLM(this.props.privkey, this.state.price, this.state.amount, this.offer.id).then(res => { if (this.mounted) { this.setState({ loading: false, checked: false, price: 'loading...', amount: '' }); this.offer = null; this.reload(); } M.toast({ html: 'Success: Your offer has been modified', classes: 'success-toast' }); }).catch(e => { if (this.mounted) { this.setState({ loading: false }); } M.toast({ html: 'Error: Offer modification failed', classes: 'error-toast' }); }); } createOffer() { this.setState({ loading: true }); stellar.linkXLM(this.props.privkey, this.state.price, this.state.amount).then(res => { if (res) { if (this.mounted) { this.setState({ loading: false, checked: false }); this.reload(); } M.toast({ html: 'Success: Your offer has been created', classes: 'success-toast' }); } else { if (this.mounted) { this.setState({ loading: false, checked: false }); } M.toast({ html: 'You already have an existing offer', classes: 'success-toast' }); } }).catch(e => { if (this.mounted) { this.setState({ loading: false }); } M.toast({ html: 'Error: Offer submission failed', classes: 'error-toast' }); }); } render() { if (this.state.loading) { return ( <div> <div className="modal-content"> <div className="loader-container" style={{ padding: '15% 0px 50px 0px', height: '100%', marginTop: '0px' }}> <Loader /> </div> </div> </div> ); } else if (this.offer) { return ( <div> <div className="modal-content"> <form className="col s10 offset-s1"> <div className="row"> <h6><b>Modify XLM Link</b></h6> <p>To delete your XLM Link, simply set the amount to 0.</p> </div> <div className="row"> <div className="input-field col s12"> <i style={{color: 'transparent'}} className="material-icons prefix"></i> <input disabled value={ this.offer.id } id="offerId" type="number" className="validate" /> <label className="active" htmlFor="offerId">Offer ID</label> </div> </div> <div className="row"> <div className="input-field col s6" style={{ paddingRight: '15px' }}> <i className="material-icons prefix">attach_money</i> <input value={ this.state.price } id="price" type="number" className="validate" onChange={ this.handleChange } /> <label className="active" htmlFor="price">Price</label> <span className="helper-text">Valuation of XLM in USD (rate of your asset to XLM)</span> </div> <div className="input-field col s6" style={{ paddingLeft: '15px' }}> <input value={ this.state.amount } id="amount" type="number" className="validate" onChange={ this.handleChange } /> <label style={{ paddingLeft: '15px' }} className="active" htmlFor="amount">Amount</label> <span className="helper-text">The amount of XLM to buyback with</span> </div> </div> <div className="row"> <p> <label> <input id="check" type="checkbox" className="filled-in" checked={ this.state.checked } onChange={ this.handleChange } /> <span> I would like to modify my offer with the provided fields. </span> </label> </p> </div> </form> </div> <div className="modal-footer"> <button className={ (this.state.checked && this.state.amount && this.state.price) ? "btn waves-effect waves-light btn-primary" : "btn disabled" } onClick={ this.modifyOffer }>Submit</button> <a className="modal-close waves-effect waves-green btn-flat">Cancel</a> </div> </div> ); } else { return ( <div> <div className="modal-content"> <form className="col s10 offset-s1"> <div className="row"> <h6><b>Link XLM</b></h6> <p>This action will create an offer enabling holders of your debt asset to exchange your debt, instantly, for native Lumens. Note that any holder of your asset may exchange your asset for Lumens, making this a dangerous action if used improperly.</p> </div> <div className="row"> <div className="input-field col s6" style={{ paddingRight: '15px' }}> <i className="material-icons prefix">attach_money</i> <input value={ this.state.price } id="price" type="number" className="validate" onChange={ this.handleChange } /> <label className="active" htmlFor="price">Price</label> <span className="helper-text">Valuation of XLM in USD (rate of your asset to XLM)</span> </div> <div className="input-field col s6" style={{ paddingLeft: '15px' }}> <input value={ this.state.amount } id="amount" type="number" className="validate" onChange={ this.handleChange } /> <label style={{ paddingLeft: '15px' }} className="active" htmlFor="amount">Amount</label> <span className="helper-text">The amount of XLM to buyback with</span> </div> </div> <div className="row"> <p> <label> <input id="check" type="checkbox" className="filled-in" checked={ this.state.checked } onChange={ this.handleChange } /> <span> I have reviewed the offer details and would like to create an offer buying my debt asset for native Lumens. </span> </label> </p> </div> </form> </div> <div className="modal-footer"> <button className={ (this.state.checked && this.state.amount && this.state.price) ? "btn waves-effect waves-light btn-primary" : "btn disabled" } onClick={ this.createOffer }>Submit</button> <a className="modal-close waves-effect waves-green btn-flat">Cancel</a> </div> </div> ); } } }
JavaScript
class InputFileNames extends Svelto.Widget { /* SPECIAL */ _variables () { this.$names = this.$element; this.$input = this.$names.closest ( 'label' ).find ( 'input[type="file"]' ); this.input = this.$input[0]; } _init () { this.options.placeholder = this.$names.text () || this.options.placeholder; this._update (); } _events () { this.___change (); } /* PRIVATE */ _getNames () { let names = []; for ( let i = 0, l = this.input.files.length; i < l; i++ ) { names.push ( this.input.files[i].name ); } return names; } _getText () { let names = this._getNames (); return names.length ? names.join ( ', ' ) : this.options.placeholder; } /* CHANGE */ ___change () { this._on ( true, this.$input, 'change', this._update ); } /* UPDATE */ _update () { let previous = this.$names.text (), current = this._getText (); if ( previous === current ) return; this.$names.text ( current ); this._trigger ( 'change' ); } }
JavaScript
class FrappeDoctypeModel extends RestModel { /** * * @param {object} options */ constructor(options) { super(Object.assign({ }, options)); } /** * Overwrites rest getEndPoint * @param {string} action * @param {object} options * @param {*} id * @param {object} args * @param {*} data */ getEndPoint(action, options, id, args, data) { let argStr = ''; if (action == 'fetch') { let tmpArgs = []; for (var k in args) { if ( args[k] !== undefined ) { tmpArgs.push(`${k}=${encodeURIComponent(args[k])}`); } } argStr = tmpArgs.join('&'); } let ACTIONS = { connect: { url: `${options.baseUrl}/api/method/login?usr=${encodeURIComponent(options.auth.usr)}&pwd=${encodeURIComponent(options.auth.pwd)}`, method: 'get' }, disconnect: { url: `${options.baseUrl}/api/method/logout`, method: 'get' }, fetch: { url: `${options.baseUrl}/api/resource/${encodeURIComponent(options.resource)}${id ? '/' + id : ''}${argStr ? '?' + argStr : ''}`, method: 'get' }, create: { url: `${options.baseUrl}/api/resource/${encodeURIComponent(options.resource)}`, method: 'post', data }, update: { url: `${options.baseUrl}/api/resource/${encodeURIComponent(options.resource)}/${id}`, method: 'put', data }, delete: { url: `${options.baseUrl}/api/resource/${encodeURIComponent(options.resource)}/${id}`, method: 'delete', }, method: { url: `${options.baseUrl}/api/method/${id}`, method: 'get' }, default: { url: `${options.baseUrl}`, method: 'get' } } return action in ACTIONS ? ACTIONS[action] : ACTIONS.default; } /** * Parses frappe server responses for error messages. * @param {object} response * @param {string} label */ handleFrappeErrors(response, label) { let rx = /(?:\<pre\>)([^<]+)(?:\<\/pre\>)/ig; let matches = rx.exec(response.data); let remoteTrace = matches[1].trim().split("\n"); let msg = remoteTrace[remoteTrace.length - 1]; throw new RemoteError((this.options.name || 'Frappe') + (label?`[${label}]`:''), msg, remoteTrace); } /** * * @param {*} data * @override */ async isConnected(data) { let endPoint = this.getEndPoint('method', this.options, 'frappe.auth.get_logged_user'); return this.HTTP(endPoint).then(response => { if (response.status == 200) { return data; } else { throw new Error(response.status); } }); } /** * * @param {(function|object)} query * @override */ async fetch({where, orderby, start, limit}) { let filters, order_by, fields=JSON.stringify(this.fields), builder = new ExpressionBuilder({ transform: new FrappeRestQueryAstTransform({ r: this.meta.fields }) }), orderBuilder = new ExpressionBuilder({ transform: new FrappeRestQueryAstTransform({ r: this.meta.fields }, { allowArrayExpression: true, allowLogicalOperators: false, allowBinaryOperators: false, finalize(output) { return JSON.stringify(output); } }) }); if ( where ) { filters = builder.parse(where).transform(); } if ( orderby ) { order_by = orderBuilder.parse(orderby).transform(); } let fetchArgs = { fields, filters, order_by, limit_start: start, limit_page_length: limit }; let fetchEndPoint = this.getEndPoint('fetch', this.options, null, fetchArgs); let totalArgs = { fields: JSON.stringify(["count(*) as total"]), filters, order_by }; let totalEndPoint = this.getEndPoint('fetch', this.options, null, totalArgs); return Promise.all([ this.HTTP(fetchEndPoint), this.HTTP(totalEndPoint)]) .then(responses => { let fetchResponse = responses[0], totalResponse = responses[1], result = { rows: null, total: 0 }; // fetch results if (fetchResponse.status == 200) { if (typeof fetchResponse.data != 'object') { // something went wrong, needle could not parse returned json throw new UnexpectedResponseError(this.name || "Frappe", fetchResponse.body, "Could not parse response from service"); } result.rows = fetchResponse.data.data; } else { this.handleFrappeErrors(fetchResponse, "Error while parsing fetch row results."); } // fetch query count if (totalResponse.status == 200) { if (typeof totalResponse.data != 'object') { // something went wrong, needle could not parse returned json throw new UnexpectedResponseError(this.name || "Frappe", totalResponse.body, "Could not parse response from service"); } result.total = totalResponse.data.data[0].total } else { this.handleFrappeErrors(totalResponse, "Error while parsing fetch total results."); } return result; }); } }
JavaScript
class Cropper { /** * Retrieve a 2d context */ get Context() { return this.canvas.getContext('2d') } /** * Create a cropper canvas * @param {HTMLCanvasElement} canvas The canvas element this is to be bound * @param {string} src The image source */ constructor(canvas, src) { /** The canvas element */ this.canvas = null /** The image object */ this.image = null /** The dimensions and */ this.viewPosition = null /** A number indicating the level of zoom */ this.zoom = 1 /** * The object containing the mouse tracking data. */ this.mouseDetails = { isMouseDown: false, lastX: null, lastY: null, } this.canvas = canvas /** The view acts like a camera */ this.viewPosition = { x: 0, y: 0, } canvas.onmousemove = this.mouseMove.bind(this) canvas.onmousedown = this.mouseDown.bind(this) canvas.onmouseup = this.mouseUp.bind(this) this.loadImage(src) .then(() => { this.resetOrientation() this.redraw() }) } /** * Only draws the image */ drawImage() { this.Context.drawImage( this.image, this.viewPosition.x, this.viewPosition.y, this.canvas.width * this.zoom, this.canvas.height * this.zoom, // Start at (0, 0) for drawing, and fill the canvas 0, 0, this.canvas.width, this.canvas.height, ) } /** * Load an image into this object asynchronously * @param {string} src The image link */ loadImage(src) { return new Promise((resolve, reject) => { this.image = new Image() this.image.src = src this.image.onload = resolve }) } /** * Draw a white background before drawing the image */ redraw() { let context = this.Context context.clearRect(0, 0, this.canvas.width, this.canvas.height) context.fillStyle = "white"; context.fillRect(0, 0, this.canvas.width, this.canvas.height) this.drawImage() } // EVENT HANDLERS /** The handling for the mouse release */ mouseUp() { this.mouseDetails.isDown = false this.mouseDetails.lastX = null this.mouseDetails.lastY = null } /** The handling for the mouse depress */ mouseDown(evt) { this.mouseDetails.isDown = true this.mouseDetails.lastX = evt.clientX this.mouseDetails.lastY = evt.clientY } /** The mouse movement, and moving the image about the canvas */ mouseMove(evt) { if (!this.mouseDetails.isDown) return // Take the pixel-change (since the canvas is 1:1 with the page) let xDif = (evt.clientX - this.mouseDetails.lastX) let yDif = (evt.clientY - this.mouseDetails.lastY) // Apply the zoom modifier let newX = xDif * this.zoom let newY = yDif * this.zoom // Modify the location this.viewPosition.x -= newX this.viewPosition.y -= newY // Update the mouse tracking data this.mouseDetails.lastX = evt.clientX this.mouseDetails.lastY = evt.clientY // Perform a redraw now that everything is ready this.redraw() } // Image Manipulators /** * Increment the zoom by a strength (negatives work) * @param {number} amt The zoom quantity * @param {number} strength How powerful the zoom modifier is */ modifyZoomBy(amt, strength = 100) { console.log('Zoom ' + amt / strength) let oldZoom = this.zoom this.zoom -= amt / strength let zoomDif = oldZoom - this.zoom this.viewPosition.x += (zoomDif * this.canvas.width) / 2 this.viewPosition.y += (zoomDif * this.canvas.height) / 2 this.redraw() } /** * Horizontally center the image about the canvas */ centerImageX() { this.viewPosition.x = -((this.canvas.width * this.zoom) / 2) + (this.image.width / 2) } /** * Vertically center the image about the canvas */ centerImageY() { this.viewPosition.y = -((this.canvas.height * this.zoom) / 2) + (this.image.height / 2) } /** * Horizontally and vertically center the image about the canvas */ centerImageBoth() { this.centerImageX() this.centerImageY() } /** * Fit the image to the canvas * @description Set the zoom to 1:1 if the canvas is square. If it is not, fit the * appropriate dimension to the canvas (landscape canvas = fit width, portrait = fit height) */ fitImage() { // Ensure 1:1 canvases are taken care of immediately this.zoom = this.image.height / this.canvas.height // What is the ratio of the canvas? let canvasRatio = this.canvas.width / this.canvas.height // Apply landscape, if not, apply portrait if (canvasRatio > 1) { this.zoom = this.image.width / this.canvas.width } else if (canvasRatio < 1) { this.zoom = this.image.height / this.canvas.height } } /** * Fit the image to the screen, and center it */ resetOrientation() { this.fitImage() this.centerImageBoth() this.redraw() } /** * Export the canvas as an octet stream */ export() { return this.canvas.toDataURL("image/png").replace("image/png", "image/octet-stream") } }
JavaScript
class MousetrapClickCustomAttribute extends AbstractMousetrapAttribute { static act(element) { element.click(); } }
JavaScript
class GridNode extends Component{ constructor(props){ super(props); this.state = {color:'white',innerColor:'white',type:'none'}; this.selfRef = React.createRef(); } componentDidMount(){ //events that will be listened for while model is running: this.selfRef.current.addEventListener("beingVisited",this.handleVisted); this.selfRef.current.addEventListener("beingExtracted",this.handleExtracted); this.selfRef.current.addEventListener("isInPath",this.handleIsInPath); this.selfRef.current.addEventListener("isEnd",this.handleIsEnd); this.selfRef.current.addEventListener("reset",this.resetEvent); } //event handlers: setTypeofNode = ()=>{ let bgColor = this.state.color; let updatedState = this.state.type; if(this.props.nodeType === 'start' && this.props.limited[0]===0){ bgColor = 'green'; updatedState = 'start'; startPointSelected(this.props.iCoordinate,this.props.jCoordinate,this.props.parentRef); } else if(this.props.nodeType === 'end' && this.props.limited[1]===0){ bgColor = 'blue'; updatedState = 'end'; endPointSelected(this.props.iCoordinate,this.props.jCoordinate,this.props.parentRef); } else if(this.props.nodeType === 'block' && this.state.type === 'none'){ bgColor = 'brown'; updatedState = 'block'; blockSelected(this.props.iCoordinate,this.props.jCoordinate,this.props.parentRef); } else if(this.props.nodeType === 'unBlock' && this.state.type === 'block'){ bgColor = 'white'; updatedState = 'none'; unBlockSelected(this.props.iCoordinate,this.props.jCoordinate,this.props.parentRef); } this.setState(()=>({color:bgColor,type:updatedState})); } handleVisted = ()=>{ let visitedColor = 'rgb(158, 215, 255)'; this.setState(()=>({color:visitedColor})); } handleExtracted = ()=>{ let extractedColor = 'rgb(120, 122, 235)'; this.setState(()=>({color:extractedColor})); } handleIsInPath = ()=>{ let inPathColor = 'rgb(245, 197, 24)'; this.setState(()=>({color:inPathColor})); } handleIsEnd = ()=>{ let isEndColor = 'red'; this.setState(()=>({color:isEndColor})); } resetEvent = ()=>{ this.setState(()=>({color:'white',type:'none'})); } // end of event handler section render(){ let nodeWidth = this.props.w - 1; let nodeHeight = this.props.h - 1; let styleObj = { width: nodeWidth, height: nodeHeight, backgroundColor: this.state.color, border: "solid", borderWidth: '1px', borderColor: 'black', display: 'flex', justifyContent: 'center', alignItems: 'center' }; let innerDotDim = (nodeWidth + nodeHeight) * INNERDOT_SCALING_FACTOR; let innerStyleObj = { width: innerDotDim, height: innerDotDim, backgroundColor: this.state.innerColor, borderRadius: '50%' } let nodeId = this.props.iCoordinate + "-" + this.props.jCoordinate; return( <div id={nodeId} style={styleObj} onClick={this.setTypeofNode} ref={this.selfRef}> <div style={innerStyleObj}></div> </div> ); } }
JavaScript
class Roles { constructor(role, active = true, user_id) { this.role = role; this.active = active; this.user_id = user_id; } }
JavaScript
class GameOver extends objects.Scene { // CONSTRUCTOR /** * Creates an instance of Game Over scene * @memberof GameOver */ constructor() { super(); // initialize label this._gameOverLabel = new objects.Label(); this._btnRestart = new objects.Button(); this._btnMain = new objects.Button(); // initialize background this._background = new createjs.Bitmap(config.Game.ASSETS.getResult("bgGameOver")); // initialize manager this._scoreBoard = new managers.ScoreBoard(); this.Start(); } // PUBLIC METHODS /** * Start method of Game Over scene * * @memberof GameOver */ Start() { // set current scene to this config.Game.CURRENT_SCENE = this; // set label this._gameOverLabel = new objects.Label("Game Over", "40px", "Consolas", "red", 300, 80, true); this._btnRestart = new objects.Button(config.Game.ASSETS.getResult("btnRestart"), 300, 460, true); this._btnMain = new objects.Button(config.Game.ASSETS.getResult("btnMain"), 300, 520, true); // set high score and score this._scoreBoard.HighScore = config.Game.HIGH_SCORE; this._scoreBoard.Score = config.Game.SCORE; this.Main(); } /** * Update method of Game Over scene * * @memberof GameOver */ Update() { } /** * Main method of Game Over scene * * @memberof GameOver */ Main() { // add elements to display this.addChild(this._background); this.addChild(this._gameOverLabel); this.addChild(this._btnRestart); this.addChild(this._btnMain); this.addChild(this._scoreBoard.HighScoreLabel); this.addChild(this._scoreBoard.CurrentScoreLabel); // when restart button is clicked, reset values, play button sound and switch scene this._btnRestart.on("click", () => { this.ResetValues(); let buttonSound = createjs.Sound.play("buttonSound"); buttonSound.volume = 0.2; // 20% volume config.Game.SCENE_STATE = scenes.State.PLAY; }); // when main button is clicked, reset values, play button sound and switch scene this._btnMain.on("click", () => { this.ResetValues(); let buttonSound = createjs.Sound.play("buttonSound"); buttonSound.volume = 0.2; // 20% volume config.Game.SCENE_STATE = scenes.State.MAIN; }); } /** * Cleam method of Game Over scene * * @memberof GameOver */ Clean() { // remove all elements this.removeAllChildren(); } /** * Method for resetting values * * @memberof GameOver */ ResetValues() { config.Game.LIVES = 3; config.Game.SCORE = 0; config.Game.BULLET_NUMBER = 20; } }
JavaScript
class MeasureDistanceTool extends BaseTool { /** * Creates an instance of MeasureDistanceTool. * * @param {object} appData - The appData value */ constructor(appData) { super() this.colorParam = this.addParameter(new ColorParameter('Color', new Color('#F9CE03'))) if (!appData) console.error('App data not provided to tool') this.appData = appData this.measurementChange = null this.highlightedItemA = null this.highlightedItemB = null this.stage = 0 } /** * The activateTool method. */ activateTool() { super.activateTool() if (this.appData && this.appData.renderer) { this.prevCursor = this.appData.renderer.getGLCanvas().style.cursor this.appData.renderer.getGLCanvas().style.cursor = 'crosshair' } } /** * The deactivateTool method. */ deactivateTool() { super.deactivateTool() if (this.appData && this.appData.renderer) { this.appData.renderer.getGLCanvas().style.cursor = this.prevCursor } if (this.stage != 0) { const parentItem = this.measurement.getOwner() parentItem.removeChild(parentItem.getChildIndex(this.measurement)) this.measurement = null if (this.highlightedItemB) { this.highlightedItemB.removeHighlight('measure', true) this.highlightedItemB = null } if (this.highlightedItemA) { this.highlightedItemA.removeHighlight('measure', true) this.highlightedItemA = null } this.stage = 0 } } /** * @param {GeomItem} geomItem * @param {Vec3} pos * @return {Vec3} * @private */ snapToParametricEdge(geomItem, pos) { const xfo = geomItem.getParameter('GlobalXfo').getValue() if (geomItem.hasParameter('CurveType')) { const curveType = geomItem.getParameter('CurveType').getValue() switch (curveType) { case 'Line': { const crvToPnt = pos.subtract(xfo.tr) const xaxis = xfo.ori.getXaxis() return xfo.tr.add(xaxis.scale(crvToPnt.dot(xaxis))) } case 'Circle': { const crvToPnt = pos.subtract(xfo.tr) const radius = geomItem.getParameter('Radius').getValue() * xfo.sc.x const zaxis = xfo.ori.getZaxis() crvToPnt.subtractInPlace(zaxis.scale(crvToPnt.dot(zaxis))) const length = crvToPnt.length() return xfo.tr.add(crvToPnt.scale(radius / length)) } default: { console.log('Unhandled Edge Type: ', curveType) } } } else if (geomItem.hasParameter('SurfaceType')) { const surfaceType = geomItem.getParameter('SurfaceType').getValue() switch (surfaceType) { case 'Plane': { const srfToPnt = pos.subtract(xfo.tr) const zaxis = xfo.ori.getZaxis() return pos.subtract(zaxis.scale(srfToPnt.dot(zaxis))) } case 'Cylinder': { const srfToPnt = pos.subtract(xfo.tr) const zaxis = xfo.ori.getZaxis() const pointOnAxis = xfo.tr.add(zaxis.scale(srfToPnt.dot(zaxis))) const radius = geomItem.getParameter('Radius').getValue() * xfo.sc.x const axisToPnt = pos.subtract(pointOnAxis) const length = axisToPnt.length() return pointOnAxis.add(axisToPnt.scale(radius / length)) } default: { console.log('Unhandled Surface Type: ', surfaceType) } } } } /** * * * @param {MouseEvent|TouchEvent} event - The event value */ onPointerDown(event) { // skip if the alt key is held. Allows the camera tool to work if (event.altKey || (event.pointerType === 'mouse' && event.button !== 0) || !event.intersectionData) return if (this.stage == 0) { if (this.highlightedItemA) { const ray = event.pointerRay let hitPos if (event.intersectionData) { hitPos = ray.start.add(ray.dir.scale(event.intersectionData.dist)) } else { const plane = new Ray(new Vec3(), new Vec3(0, 0, 1)) const distance = ray.intersectRayPlane(plane) hitPos = ray.start.add(ray.dir.scale(distance)) } const startPos = this.snapToParametricEdge(this.highlightedItemA, hitPos) const color = this.colorParam.getValue() this.measurement = new MeasureDistance('Measure Distance', color) this.measurement.setStartMarkerPos(startPos) this.measurement.setEndMarkerPos(startPos) this.appData.scene.getRoot().addChild(this.measurement) this.measurementChange = new MeasurementChange(this.measurement) UndoRedoManager.getInstance().addChange(this.measurementChange) this.stage++ event.stopPropagation() } } else if (this.stage == 1) { if (this.highlightedItemB) { const ray = event.pointerRay const hitPos = ray.start.add(ray.dir.scale(event.intersectionData.dist)) const startPos = this.snapToParametricEdge(this.highlightedItemA, hitPos) const endPos = this.snapToParametricEdge(this.highlightedItemB, hitPos) this.measurement.setStartMarkerPos(startPos) this.measurement.setEndMarkerPos(endPos) if (this.highlightedItemA) { this.highlightedItemA.removeHighlight('measure', true) this.highlightedItemA = null } if (this.highlightedItemB) { this.highlightedItemB.removeHighlight('measure', true) this.highlightedItemB = null } this.stage = 0 this.measurement = null event.stopPropagation() } } } /** * * * @param {MouseEvent|TouchEvent} event - The event value */ onPointerMove(event) { // skip if the alt key is held. Allows the camera tool to work if (event.altKey || (event.pointerType === 'mouse' && event.button !== 0)) return if (this.stage == 0) { if (event.intersectionData) { const { geomItem } = event.intersectionData if (geomItem.hasParameter('CurveType') || geomItem.hasParameter('SurfaceType')) { if (!geomItem != this.highlightedItemA) { if (this.highlightedItemA) { this.highlightedItemA.removeHighlight('measure', true) } this.highlightedItemA = geomItem this.highlightedItemA.addHighlight('measure', new Color(1, 1, 1, 0.2), true) } } } else { if (this.highlightedItemA) { this.highlightedItemA.removeHighlight('measure', true) this.highlightedItemA = null } } event.stopPropagation() } else if (this.stage == 1) { if (event.intersectionData) { const { geomItem } = event.intersectionData if (geomItem != this.highlightedItemA && geomItem != this.highlightedItemB) { if (geomItem.hasParameter('CurveType') || geomItem.hasParameter('SurfaceType')) { if (this.highlightedItemB) { this.highlightedItemB.removeHighlight('measure', true) this.highlightedItemB = null } this.highlightedItemB = geomItem this.highlightedItemB.addHighlight('measure', new Color(1, 1, 1, 0.2), true) } } } else { if (this.highlightedItemB) { this.highlightedItemB.removeHighlight('measure', true) this.highlightedItemB = null } } event.stopPropagation() } } /** * * * @param {MouseEvent|TouchEvent} event - The event value */ onPointerUp(event) {} }
JavaScript
class y { constructor(t, s, i) { (this.t = []), (this.template = t), (this.processor = s), (this.options = i); } update(t) { let s = 0; for (const i of this.t) void 0 !== i && i.setValue(t[s]), s++; for (const t of this.t) void 0 !== t && t.commit(); } _clone() { const s = t ? this.template.element.content.cloneNode(!0) : document.importNode(this.template.element.content, !0), i = [], e = this.template.parts, n = document.createTreeWalker(s, 133, null, !1); let o, r = 0, c = 0, l = n.nextNode(); for (; r < e.length; ) if (((o = e[r]), h(o))) { for (; c < o.index; ) c++, 'TEMPLATE' === l.nodeName && (i.push(l), (n.currentNode = l.content)), null === (l = n.nextNode()) && ((n.currentNode = i.pop()), (l = n.nextNode())); if ('node' === o.type) { const t = this.processor.handleTextExpression(this.options); t.insertAfterNode(l.previousSibling), this.t.push(t); } else this.t.push( ...this.processor.handleAttributeExpressions( l, o.name, o.strings, this.options ) ); r++; } else this.t.push(void 0), r++; return t && (document.adoptNode(s), customElements.upgrade(s)), s; } }
JavaScript
class Y extends X { static get styles() { return K` :host { display: block; border: solid 1px gray; padding: 16px; max-width: 800px; } `; } static get properties() { return {name: {type: String}, count: {type: Number}}; } constructor() { super(), (this.name = 'World'), (this.count = 0); } render() { return N` <h1>Hello, ${this.name}!</h1> <button @click=${this._onClick} part="button"> Click Count: ${this.count} </button> <slot></slot> `; } _onClick() { this.count++; } }
JavaScript
class Badge extends WixComponent { constructor(props) { super(props); this.setStyles(badgeStyles, typography); } render() { const {children, type, appearance, alignment, shape, dataHook} = this.props; const {styles, typography} = this; const className = classnames( styles.badge, styles[type], styles[alignment], styles[shape], typography[convertFromUxLangToCss(appearance) ]); return ( <span className={className} data-hook={dataHook}> {children} </span> ); } }
JavaScript
class ContentType extends Base { /** * @inheritDoc */ static get className() { return 'model/ContentType'; } /** * Any */ static get ANY() { return '*'; } /** * Sass */ static get SASS() { return 'sass'; } /** * Js */ static get JS() { return 'js'; } /** * Json */ static get JSON() { return 'json'; } /** * Jinja */ static get JINJA() { return 'jinja'; } /** * Markdown */ static get MARKDOWN() { return 'markdown'; } }
JavaScript
class BlobBeginCopyFromUrlPoller extends Poller { constructor(options) { const { blobClient, copySource, intervalInMs = 15000, onProgress, resumeFrom, startCopyFromURLOptions } = options; let state; if (resumeFrom) { state = JSON.parse(resumeFrom).state; } const operation = makeBlobBeginCopyFromURLPollOperation(Object.assign(Object.assign({}, state), { blobClient, copySource, startCopyFromURLOptions })); super(operation); if (typeof onProgress === "function") { this.onProgress(onProgress); } this.intervalInMs = intervalInMs; } delay() { return delay(this.intervalInMs); } }
JavaScript
class CustomColumnEvent { static AddEvent() { } static AddEventOnce() { $(document).off('click.exment_custom_column', '[data-contentname="options_calc_formula"] .button-addcalcitem').on('click.exment_custom_column', '[data-contentname="options_calc_formula"] .button-addcalcitem', {}, CustomColumnEvent.calcButtonAddItemEvent); $(document).off('click.exment_custom_column', '#validateFormula').on('click.exment_custom_column', '#validateFormula', {}, CustomColumnEvent.validateFormula); $(document).off('keydown.exment_custom_column', '#calc_formula_input').on('keydown.exment_custom_column', '#calc_formula_input', {}, CustomColumnEvent.inputFormulaEvent); $(document).off('focus.exment_custom_column', '#calc_formula_input').on('focus.exment_custom_column', '#calc_formula_input', {}, CustomColumnEvent.focusFormulaEvent); $(document).on('pjax:complete', function (event) { CustomColumnEvent.AddEvent(); }); } /** * Set formula input area * @param text */ static setCalcInput(text) { let area = $('#calc_formula_input').get(0); let point = null; if (hasValue(CustomColumnEvent.formulaInputselection)) { point = CustomColumnEvent.formulaInputselection; } else { point = area.selectionStart; } let afterPoint = area.value.substr(0, point).length + text.trim().length; area.value = area.value.substr(0, point) + text.trim() + area.value.substr(point); // set area.selectionStart point CustomColumnEvent.formulaInputselection = afterPoint; } static GetSettingValText() { let formula = $('#calc_formula_input').val(); // replace ${XXX} string as column name formula = formula.replace(/\$\{.+?\}/g, function (match) { let $target = $('.col-target-block-column button[data-val="' + match + '"]'); if (!hasValue($target)) { return match; } return $target.data('displayText'); }); return { value: $('#calc_formula_input').val(), text: formula }; } static inputFormulaEvent(e) { if (e && e.key == 'Enter') { return false; } $('.modal .modal-submit').prop('disabled', true); $('.modal #validateResult > span').hide(); } static focusFormulaEvent(e) { CustomColumnEvent.formulaInputselection = null; } static validateFormula() { let result = true; let formula = $('#calc_formula_input').val(); if (!hasValue(formula)) { result = false; } else { // replace ${XXX} string as 1 let replaceFormula = formula.replace(/\$\{.+?\}/g, function (match) { // find key value let $target = $('.col-target-block-column button[data-val="' + match + '"]'); if (!hasValue($target)) { result = false; } return '1'; }); if (result) { result = Exment.CalcEvent.validateMathFormula(replaceFormula); } // if match \$\{.+?\} \$\{.+?\}, return false if (formula.match(/\$\{.+?\} *\$\{.+?\}/g)) { result = false; } } $('.modal .modal-submit').prop('disabled', !result); $('.modal #validateResult > span').hide(); if (result) { $('.modal #validateResultSuccess').show(); } else { $('.modal #validateResultError').show(); } } }
JavaScript
class Sidenav extends React.Component { render() { let subNameEn = ""; let subNameFr = ""; let subGroup = []; let subPieces = []; const data = this.props.data; data[this.props.path.split("/")[1]].edges.forEach((edges) => { if (edges.node.frontmatter.subnav.split("/")[1] !== subNameEn) { if (subNameEn !== "") { subPieces.push( <Subnav files={ subGroup } nameEn={ subNameEn } nameFr={ subNameFr } path={ this.props.path } i18n={ this.props.i18n } key={ subNameEn } /> ); } subGroup = []; subNameEn = edges.node.frontmatter.subnav.split("/")[1]; subNameFr = edges.node.frontmatter.subnav.split("/")[2]; } subGroup.push(edges); }); if (subGroup.push.length !== 0) { subPieces.push( <Subnav files={ subGroup } nameEn={ subNameEn } nameFr={ subNameFr } path={ this.props.path } i18n={ this.props.i18n } key={ subNameEn } /> ); } return( <I18n ns={["translation"]}> { (t, { i18n }) => ( <nav class="sidenav" role="navigation" aria-label={t("SubNavigation")}> <Nav style={{'marginTop':'110px', 'marginBottom':'40px'}}> {subPieces} </Nav> </nav> ) } </I18n> ); } }
JavaScript
class TextFragmentsDataDrivenTest extends DataDrivenTest { /** * Constructor of {@link DataDrivenTest}. Configure your tests here by * providing the source of input and output files. To be able differentiate * input and output files, either |inputDirectory| must be different of * |outputDirectory|, or |inputExtension| must be different to * |outputExtension| * @param {String} testSuiteName - Name of the Jasmine test suite that * contains the tests run by this instance. e.g: 'My Beautiful Feature * Data Driven Tests' * @param {String} inputDirectory - Path to directory containing input files. * Relative to your Karma base path. e.g: * 'test/data-driven/input/test-params/' * * Each input file must be a {@see TextFragmentDataDrivenTestInput} json * serialized. * @param {String} inputExtension - File extension of input files. e.g: 'json' * @param {String} outputDirectory - Path to directory containing output * files. Relative to your Karma base path. e.g: * 'test/data-driven/output/' * @param {String} outputExtension - File extension of output files. e.g: * 'out' * @param {String} htmlDirectory - Path to directory containing the test * case's html pages. Relative to your Karma base path. e.g: * 'test/data-driven/input/html/' */ constructor( testSuiteName, inputDirectory, inputExtension, outputDirectory, outputExtension, htmlDirectory) { super( testSuiteName, inputDirectory, inputExtension, outputDirectory, outputExtension); this.htmlDirectory = htmlDirectory } /** * Runs a Text Fragment data-driven test case. * * This method takes a test case definition in |inputText|, tries to generate * and highlight a text fragment, checking if the highlighted text matches the * test case's expected highlighted text. * @param {String} inputText - Test case input. Expected to be a * {@see TextFragmentDataDrivenTestInput} json serialized. * @return {String} - The test results, having the following format: * * GENERATION: [Success | Failure] * HIGHLIGHTING: [Success | Failure] * * The GENERATION line indicates if a fragment was successfully generated for * the test case input. The HIGHLIGHTING line indicates if the highlighted * text matched the test case's expected highlighted text. */ generateResults(inputText) { const input = this.parseInput(inputText); document.body.innerHTML = __html__[this.getPathForHtml(input.htmlFileName)]; const generatedFragment = this.generateFragment(input); const generationResult = generatedFragment ? true : false; const highlightingResult = generationResult && this.testHighlighting(generatedFragment, input); const outputText = this.generateOutput(generationResult, highlightingResult); return outputText; } /** * Generates a text fragment for a test case input. * @param {TextFragmentDataDrivenTestInput} input - Test case input. * @return {TextFragment|null} Generated text fragment or null if generation * failed. */ generateFragment(input) { const startParent = input.startParentId ? document.getElementById(input.startParentId) : document.body; const start = startParent.childNodes[input.startOffsetInParent]; const startOffset = input.startTextOffset ?? 0; const endParent = input.endParentId ? document.getElementById(input.endParentId) : document.body; const end = endParent.childNodes[input.endOffsetInParent]; const endOffset = input.endTextOffset ?? 0; const range = document.createRange(); range.setStart(start, startOffset); range.setEnd(end, endOffset); const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); const result = generationUtils.generateFragment(selection); return result.fragment; } /** * Verifies that the text highlighted for a given text fragment is correct. * @param {TextFragment} fragment - Fragment to highlight. * @param {TextFragmentDataDrivenTestInput} testInput - Test input object * including the expected highlight text. * @return {Boolean} True iff the text highlighted for |fragment| is the same * as |testInput.highlightText|. */ testHighlighting(fragment, testInput) { const directive = {text: [fragment]}; const processedDirectives = fragmentUtils.processFragmentDirectives( directive, )['text']; if (processedDirectives.count == 0) { return false; } const marks = processedDirectives[0]; const highlightingTextMatch = marksArrayToString(marks) == testInput.highlightText; return highlightingTextMatch; } /** * Generates the output of a test case. * @param {Boolean} generationSuccess - True if fragment generation test was * successful. * @param {Boolean} highlightingSuccess - True if highlighting test was * successful. * @return {String} The test's output text that will be compared with the * expected output in the test's output file. */ generateOutput(generationSuccess, highlightingSuccess) { return `GENERATION: ${this.getTextForTestResult(generationSuccess)}\n` + `HIGHLIGHTING: ${this.getTextForTestResult(highlightingSuccess)}\n` } /** * Helper method to get the textual representation of a test result that is * included in the data driven test output. * @param {Boolean} testSuccess - True if test was successful. * @return {String} {@link OUTPUT_SUCCESS} when |testSuccess| is true * or {@link OUTPUT_FAILURE} when false. */ getTextForTestResult(testSuccess) { return testSuccess ? OUTPUT_SUCCESS : OUTPUT_FAILURE; } /** * Text Fragments Data Driven Test input object. * @typedef {Object} TextFragmentDataDrivenTestInput * @property {String} htmlFileName - Html file name for the test case. This * file should be in |htmlDirectory|. * @property {String} [startParentId] - Id of the parent of the node where the * test case’s selection starts. Optional: when null then the parent node is * the document's body. * @property {Number} startOffsetInParent - Offset of the selection’s starting * node in its parent node. * @property {Number} [startTextOffset] - When the selection starts in a text * node, this value indicates the offset inside the node’s text where the * selection starts. * @property {String} [endParentId] - Id of the parent of the node where the * test case’s selection ends. Optional: when null then the parent node is the * document's body. * @property {Number} endOffsetInParent - Offset of the selection’s ending * node in its parent node. * @property {Number} [endTextOffset] - When the selection ends in a text * node, this value indicates the offset inside the node’s text where the * selection ends. * @property {String} selectedText - Expected text content inside the * selection. * @property {String} highlightText - Expected text content inside the range * highlighted. */ /** * Parses the content of a test case input file. * @param {String} input - Content of a test case input file. * @return {TextFragmentDataDrivenTestInput} Test Case input object. */ parseInput(input) { try { return JSON.parse(input); } catch (error) { throw new Error( 'Invalid input file. Content must be a valid json object.\n' + `${error}.`); } } /** * Builds the path to an html file using |htmlDirectory|. * The resulting path can be used to get the html contents * via karma's __html__[path]. * @param {String} fileName - Html file name including extension. * @return {String} Path to html file. */ getPathForHtml(fileName) { return `${this.htmlDirectory}${fileName}`; } }
JavaScript
class Embeddings extends API { /** * Finds documents in the embeddings model most similar to the input query. Returns * a list of {id: value, score: value} sorted by highest score, where id is the * document id in the embeddings model. * * @param query query text * @param limit maximum results (defaults to 10) * @return list of {id: value, score: value} */ async search(query, limit = 10) { return await this.get("search", {query: query, limit: limit}).catch(e => { throw(e); }); } /** * Finds documents in the embeddings model most similar to the input queries. Returns * a list of {id: value, score: value} sorted by highest score per query, where id is * the document id in the embeddings model. * * @param queries queries text * @param limit maximum results (defaults to 10) * @return list of {id: value, score: value} per query */ async batchsearch(queries, limit = 10) { return await this.post("batchsearch", {queries: queries, limit: limit}).catch (e => { throw(e); }); } /** * Adds a batch of documents for indexing. * * @param documents list of {id: value, text: value} */ async add(documents) { await this.post("add", documents).catch(e => { throw(e); }); } /** * Builds an embeddings index for previously batched documents. */ async index() { await this.get("index", null).catch(e => { throw(e); }); } /** * Runs an embeddings upsert operation for previously batched documents. */ async upsert() { await this.get("upsert", null).catch(e => { throw(e); }); } /** * Deletes from an embeddings index. Returns list of ids deleted. * * @param ids list of ids to delete * @return ids deleted */ async delete(ids) { return await this.post("delete", ids).catch(e => { throw(e); }); } /** * Total number of elements in this embeddings index. * * @return number of elements in embeddings index */ async count() { return await this.get("count", null).catch(e => { throw(e); }); } /** * Computes the similarity between query and list of text. Returns a list of * {id: value, score: value} sorted by highest score, where id is the index * in texts. * * @param query query text * @param texts list of text * @return list of {id: value, score: value} */ async similarity(query, texts) { return await this.post("similarity", {query: query, texts: texts}).catch (e => { throw(e); }); } /** * Computes the similarity between list of queries and list of text. Returns a list * of {id: value, score: value} sorted by highest score per query, where id is the * index in texts. * * @param queries queries text * @param texts list of text * @return list of {id: value, score: value} per query */ async batchsimilarity(queries, texts) { return await this.post("batchsimilarity", {queries: queries, texts: texts}).catch (e => { throw(e); }); } /** * Transforms text into an embeddings array. * * @param text input text * @return embeddings array */ async transform(text) { return await this.get("transform", {text: text}).catch(e => { throw(e); }); } /** * Transforms list of text into embeddings arrays. * * @param texts list of text * @return embeddings array */ async batchtransform(texts) { return await this.post("batchtransform", texts).catch(e => { throw(e); }); } }
JavaScript
class ObapSelectorContainer extends ObapElement { static get styles() { return [css` :host { display: block; } :host([hidden]) { display: none !important; } :host([disabled]) { pointer-events: none; } `]; } static get properties() { return { /** Gets or sets the selected element index. @type {Number} @default -1 */ selectedIndex: { type: Number, attribute: 'selected-index' } } } constructor() { super(); this.selectedIndex = -1; this._items = []; this._selectable = true; this._boundHandleSlotChangeEvent = this._handleSlotChangeEvent.bind(this); this._boundHandleItemSelectedEvent = this._handleItemSelectedEvent.bind(this); this.renderRoot.addEventListener('slotchange', this._boundHandleSlotChangeEvent); this.addEventListener('obap-item-selected', this._boundHandleItemSelectedEvent); } updated(changedProperties) { super.updated(changedProperties); changedProperties.forEach((oldValue, propName) => { if (propName === 'selectedIndex') { this._updateSelectors(); } }); } render() { return html`<slot></slot>`; } _handleItemSelectedEvent(e) { if (this._items.indexOf(e.target) > -1) { this.selectedIndex = e.detail.index; e.stopPropagation(); e.preventDefault(); } } _handleSlotChangeEvent(e) { this._items = [...this.querySelectorAll('*')].filter((el) => { return (el.nodeType === 1) && (el._selectable); }); this._updateSelectors(); } _updateSelectors() { this._items.forEach(item => item.selectedIndex = this.selectedIndex); } }
JavaScript
class PingService { /** * Register futoin.ping interface with Executor * @param {AsyncSteps} as - steps interface * @param {Executor} executor - executor instance * @return {PingService} instance by convention */ static register( as, executor ) { var iface = PingFace.spec( "1.0" ); var ifacever = iface.iface + ':' + iface.version; var impl = new this(); executor.register( as, ifacever, impl, [ iface ] ); return impl; } ping( as, reqinfo ) { reqinfo.result().echo = reqinfo.params().echo; } }
JavaScript
class Controller extends FeatureEditCtrl { /** * Constructor. * @param {!angular.Scope} $scope * @param {!angular.JQLite} $element * @param {!angular.$timeout} $timeout * @ngInject */ constructor($scope, $element, $timeout) { super($scope, $element, $timeout); // if the name wasn't set in the base class, set it to New Place this['name'] = this['name'] || 'New Place'; this['customFoldersEnabled'] = false; // by default, show column choices for the default KML source. remove internal columns because they're not generally // useful to a user. var defaultColumns = kml.SOURCE_FIELDS.filter(function(field) { return !osFeature.isInternalField(field); }).map(function(col) { return new ColumnDefinition(col); }); /** * The preview annotation. * @type {FeatureAnnotation|undefined} * @protected */ this.previewAnnotation; /** * @type {!Array<string>} */ this['labelColumns'] = defaultColumns; /** * tempHeaderColor * @type {string|undefined} */ this['tempHeaderBG'] = this['annotationOptions'].headerBG || undefined; /** * tempBodyColor * @type {string|undefined} */ this['tempBodyBG'] = this['annotationOptions'].bodyBG || undefined; var time = this.options['time']; if (time) { this['startTime'] = time.getStart(); this['startTimeISO'] = this['startTime'] ? new Date(this['startTime']).toISOString() : undefined; this['endTime'] = time.getEnd() === this['startTime'] ? undefined : time.getEnd(); this['endTimeISO'] = this['endTime'] ? new Date(this['endTime']).toISOString() : undefined; if (this['endTime'] > this['startTime']) { this['dateType'] = AnyDateType.RANGE; } else { this['dateType'] = AnyDateType.INSTANT; } } if (!this.isFeatureDynamic()) { var optionsListId = 'optionsList' + this['uid']; list.add(optionsListId, '<annotationoptions options="ctrl.annotationOptions"></annotationoptions>'); if (this.options['annotation']) { // if creating a new annotation, expand the Annotation Options section by default this.defaultExpandedOptionsId = 'featureAnnotation' + this['uid']; } this['customFoldersEnabled'] = true; var folders = []; var rootFolder = PlacesManager.getInstance().getPlacesRoot(); structs.flattenTree(rootFolder, folders, (node) => /** @type {KMLNode} */ (node).isFolder()); this['folderOptions'] = folders; var parentFolder = this.options['parent']; if (!parentFolder && this.options['node']) { parentFolder = this.options['node'].getParent(); } this['folder'] = parentFolder || rootFolder; } $scope.$on('headerColor.reset', this.resetHeaderBackgroundColor_.bind(this)); $scope.$on('bodyColor.reset', this.resetBodyBackgroundColor_.bind(this)); $scope.$on('headerColor.change', this.saveHeaderBackgroundColor_.bind(this)); $scope.$on('bodyColor.change', this.saveBodyBackgroundColor_.bind(this)); } /** * @inheritDoc */ disposeInternal() { super.disposeInternal(); if (this.previewAnnotation) { dispose(this.previewAnnotation); this.previewAnnotation = null; } if (this.options['feature']) { this.options['feature'].changed(); } } /** * @inheritDoc * @export */ accept() { // create a new feature if necessary var feature = this.options['feature'] = this.options['feature'] || new Feature(); // filter out empty labels when the placemark is saved if (this['labels']) { this['labels'] = this['labels'].filter(function(label) { return label['column'] != null; }); } // enable editing the annotation when the feature is saved this['annotationOptions'].editable = true; this.saveToFeature(feature); if (!feature.getId()) { feature.setId(getUid(feature)); } kmlUI.updatePlacemark(this.options); if (this.callback) { this.callback(this.options); } this.close(); } /** * @inheritDoc */ createPreviewFeature() { super.createPreviewFeature(); // set the default options for the annotation this['annotationOptions'] = osObject.unsafeClone(annotation.DEFAULT_OPTIONS); // disable annotation edit when creating an annotation this['annotationOptions'].editable = false; if (this.options['annotation']) { this.previewFeature.set(annotation.OPTIONS_FIELD, this['annotationOptions']); if (!this.originalGeometry) { // default to hiding the geometry for points as it tends to visually obscure what you're annotating this['shape'] = osStyle.ShapeType.NONE; } // don't display a label, but leave the config present to populate the UI this['labels'][0]['column'] = ''; } else { this['annotationOptions'].show = false; } } /** * @inheritDoc */ loadFromFeature(feature) { super.loadFromFeature(feature); var currentOptions = feature.get(annotation.OPTIONS_FIELD); this['annotationOptions'] = osObject.unsafeClone(currentOptions || annotation.DEFAULT_OPTIONS); if (!currentOptions) { this['annotationOptions'].show = false; } // disable annotation edit when editing an annotation this['annotationOptions'].editable = false; } /** * @inheritDoc */ saveToFeature(feature) { super.saveToFeature(feature); feature.set(annotation.OPTIONS_FIELD, this['annotationOptions']); } /** * @inheritDoc * @export */ updatePreview() { super.updatePreview(); this.updateAnnotation(); } /** * Updates the option for the placemark's parent folder * * @export */ updateFolder() { if (this['folder']) { this.options['parent'] = this['folder']; } } /** * Updates the temporary annotation. * * @export */ updateAnnotation() { if (this.previewFeature) { if (this['annotationOptions'].show) { // only create the preview annotation if not already present, and the feature isn't already displaying an // annotation overlay if (!this.previewAnnotation && !annotation.hasOverlay(this.previewFeature)) { this.previewAnnotation = new FeatureAnnotation(this.previewFeature); } } else { // dispose the preview dispose(this.previewAnnotation); this.previewAnnotation = null; } // fire a change event on the feature to trigger an overlay update (if present) this.previewFeature.changed(); } } /** * Resets the header background to the current default theme color * * @private */ resetHeaderBackgroundColor_() { this['annotationOptions'].headerBG = undefined; this['tempHeaderBG'] = undefined; } /** * Resets the body background to the current default theme color * * @private */ resetBodyBackgroundColor_() { this['annotationOptions'].bodyBG = undefined; this['tempBodyBG'] = undefined; } /** * Save color to feature * * @param {angular.Scope.Event} event * @param {string} color The new color */ saveHeaderBackgroundColor_(event, color) { this['annotationOptions'].headerBG = color; } /** * Save color to feature * * @param {angular.Scope.Event} event * @param {string} color The new color */ saveBodyBackgroundColor_(event, color) { this['annotationOptions'].bodyBG = color; } }
JavaScript
class Expression { /** * @param {Object} constructorParams * @param {String} constructorParams.value */ constructor({ value } = {}) { this.value = value; /** * @type {String} */ this.error = null; /** * @type {String} */ this.description = null; } /** * @param {String} varPath * @param {Context} context */ validateVariablePath(varPath, context) { const variable = context.searchVar(varPath) || context.upsearchVar(varPath); if (!variable) this.error = `Can't find the variable or property '${varPath}'.`; return variable; } /** * Check if this expression's syntax is valid * @returns {Boolean} */ validateSyntax() { let match = null; // This expression can be validated without semantic // "...string value..." if ((match = this.value.match(new RegExp(`^\\s*${GlobalRegex.Static.String}\\s*$`)))) { this.match = match; this.type = Type.StaticValue; // Replace escaped quotes with quotes this.staticValue = match[1].replace('\\"', '"'); this.description = `Static << ${this.staticValue} >>`; } // This expression can be validated without semantic // e.g. 120, 0.9, 0.0024 else if ((match = this.value.match(new RegExp(`^\\s*${GlobalRegex.Static.Number}\\s*$`)))) { this.match = match; this.type = Type.StaticValue; // Replace escaped quotes with quotes this.staticValue = Number(this.match[1]); this.description = `Static << ${this.staticValue} >>`; } // The simplest value expression, a variable's path // variable_x.property....finalProp else if ((match = this.value.match(new RegExp(`^\\s*${GlobalRegex.Identifier.Path}\\s*$`)))) { this.match = match; this.type = Type.VariableValue; this.description = `Variable << ${this.match[1]} >>`; } // Function call // functionName(param1, param2, args...) else if ((match = this.value.match(new RegExp(`^\\s*${GlobalRegex.Function.Call}\\s*$`)))) { this.match = match; this.type = Type.FunctionCallValue; } // Declaration // variableName = anotherVariable // variableName = anotherVariable.property // variableName = functionName(param1, param2, args...) else if ((match = this.value.match(new RegExp(`^\\s*${GlobalRegex.Declaration}\\s*$`)))) { this.match = match; this.type = Type.Declaration; } else return false; return true; } /** Check if this expression's semantic is valid in the given context * @returns {Boolean} */ validateSemantic({ context }) { switch (this.type) { case Type.VariableValue: const variable = this.validateVariablePath(this.match[1], context); if (!variable) return false; this.variable = variable; break; case Type.FunctionCallValue: const functionName = this.match[1]; if (Functions[functionName]) { // Function's name is valid const functionParameters = []; // Extract parameters let parenthesis = 0; let currentParam = ''; for (let i = 0; i < this.match[2].length; i++) { const char = this.match[2][i]; if (char === '(') parenthesis++; else if (char === ')') parenthesis--; if (parenthesis === 0) { if (char === ',') { functionParameters.push(currentParam); currentParam = ''; continue; } } currentParam += this.match[2][i]; } functionParameters.push(currentParam); const parameters = []; // Check if parameters are valid for (let p = 0; p < functionParameters.length; p++) { const paramExpression = new Expression({ value: functionParameters[p] }); const valid = paramExpression.validate({ context }); if (!valid) { this.error = `Can't validate the parameter << ${functionParameters[p]} >> ${ paramExpression.error ? `<< ${paramExpression.error} >>` : '' }`; return false; } parameters.push(paramExpression); } this.functionName = functionName; this.parameters = parameters; const dataType = this.deduceDataType(); this.description = `Function ${functionName}'s call with parameters ( ${functionParameters.join(',\n ')} ) that returns << ${dataType.description} >>`; } else { this.error = `Can't find the function '${functionName}'`; return false; } break; case Type.Declaration: const valueExpression = new Expression({ value: this.match[2] }); if (!valueExpression.validate({ context })) { this.error = `Can't validate the value << ${this.match[2]} >> ${ valueExpression.error ? `<< ${valueExpression.error} >>` : '' }`; return false; } // Deduce type of this declaration const dataType = valueExpression.deduceDataType(); const declaredVariable = new Variable({ name: this.match[1], type: dataType.type, props: dataType.props, description: dataType.description, }); declaredVariable.value = valueExpression.evaluate(); context.variables.push(declaredVariable); this.description = `Declaration of variable << ${declaredVariable.name} >>, value assigned to: << ${dataType.description} >>`; break; } return true; } /** * Validate in the context * @param {Context} context * @returns {Boolean} */ validate({ context }) { return this.validateSyntax() && this.validateSemantic({ context }); } deduceDataType() { if (this.type === Type.FunctionCallValue) { let dataType = Functions[this.functionName].returns; if (typeof dataType === 'function') // If returns type is a function, then deduce the return type by the parameters types return Functions[this.functionName].returns( ...this.parameters.map((p) => [p.deduceDataType(), p.evaluate()]) ); return deduceDataType(dataType); } else if (this.type === Type.VariableValue) return this.variable; else return { type: DataType.Primitive }; } /** * Get the value to which the expression is evaluated */ evaluate() { switch (this.type) { case Type.StaticValue: return this.staticValue; case Type.VariableValue: return this.variable.value; case Type.FunctionCallValue: return (Functions[this.functionName].function || Functions[this.functionName])( ...this.parameters.map((param) => param.evaluate()) ); } return undefined; } /** * Render the value of the expression after validation */ render() { return this.evaluate(); } }
JavaScript
class Query { constructor(sqlString) { this.sqlString = sqlString; }; runQuery(connection, values) { // Binding this to that so it can be referenced within the promise const that = this; // Wrapped connection.query in a Promise so calling function can wait for a Promise return new Promise(function (resolve, reject) { connection.query(that.sqlString, values, (err, data) => { if (err) { reject(new Error(err)) } else { resolve(data) } }) }) } }
JavaScript
class Chat extends Component { //messages is a list of messages sent //message content is what the user is typing //set the username as the socketid constructor() { super(); this.state = { messages: [], messageContent: "", username: "anonymous", notifications: [], typing: false, chatters: [], roomID: "" }; } //when a message event is emitted, make sure to prepend the message to the beginning of the message state componentDidMount() { this.setState({ roomID: window.location.href.substr( window.location.href.lastIndexOf("/") + 1 ) }); socket.on("connect", () => { socket.emit("join room", { roomID: this.state.roomID }); }); socket.on("send message", message => { console.log(message); this.setState({ messages: [message, ...this.state.messages] }); }); } //what happens when we type in a message handleSubmit = e => { const body = e.target.value; if (e.keyCode === 13 && body) { const message = { body, from: this.state.username }; socket.emit("message", message, this.state.roomID); e.target.value = ""; } }; handleUsername = e => { const username = e.target.value; if (e.keyCode === 13 && username) { this.setState({ username }); e.target.value = ""; } }; //what happens when we want to clear the chat handleClear = () => { this.setState({ messages: [] }); }; componentWillUnmount() { socket.removeAllListeners(); } render() { const messages = this.state.messages.map((message, index) => { return ( <li key={index}> <b>{message.from}: </b> {message.body} </li> ); }); const isTyping = this.state.chatters.map((username, index) => { return ( <div id="typing" key={index}> {username.from} is typing... </div> ); }); return ( <div id="chat"> <div id="chat-title">React Chat</div> <div className="chat"> {`You're appearing as "${this.state.username}" in this chat`} <div id="username"> <div id="username-title"> {this.state.username !== "anonymous" ? `Change your username` : `Choose a username`} </div> <form onSubmit={e => e.preventDefault()}> <input type="text" placeholder="Enter your username..." onKeyUp={this.handleUsername} maxLength={16} /> </form> </div> <div id="chat-header">Chat here</div> <div id="chat-messages">{messages}</div> <div id="chat-message"> <input type="text" placeholder="Enter a message..." onKeyUp={this.handleSubmit} maxLength={200} /> </div> <div id="clear-chat"> <input type="submit" value="clear chat" onClick={this.handleClear} /> </div> </div> </div> ); } }
JavaScript
class PlanetShaders { /** * Constructor. * * @param {WebGLRenderingContext} gl * The WebGL rendering context to use. * @param {*} nLon * Number of longitude divisions. * @param {*} nLat * Number of latitude divisions. * @param {*} a * Equatorial radius. * @param {*} b * Polar radius. * @param {*} lonGridStep * Longitude grid step. * @param {*} latGridStep * Latitude grid step. */ constructor(gl, nLon, nLat, a, b, lonGridStep, latGridStep) { this.gl = gl; this.a = a; this.b = b; this.nLat = nLat; this.nLon = nLon; this.lonGridStep = lonGridStep; this.latGridStep = latGridStep; this.colorGrid = [80, 80, 80]; this.colorMap = [80, 80, 127]; this.vertShaderSphere = `#version 300 es // an attribute is an input (in) to a vertex shader. // It will receive data from a buffer in vec4 a_position; in vec2 a_texcoord; // A matrix to transform the positions by uniform mat4 u_matrix; // a varying to pass the texture coordinates to the fragment shader out vec2 v_texcoord; // all shaders have a main function void main() { // Multiply the position by the matrix. gl_Position = u_matrix * a_position; // Pass the texcoord to the fragment shader. v_texcoord = a_texcoord; } `; this.fragShaderSphere = `#version 300 es precision highp float; #define PI 3.1415926538 #define A 6378137.0 #define B 6356752.314245 #define E 0.081819190842965 #define R_EARTH 6371000.0 // Passed in from the vertex shader. in vec2 v_texcoord; // The texture. uniform sampler2D u_imageDay; uniform sampler2D u_imageNight; uniform bool u_draw_texture; // uniform float u_decl; uniform float u_rA; uniform float u_LST; uniform float u_iss_x; uniform float u_iss_y; uniform float u_iss_z; uniform bool u_show_iss; // we need to declare an output for the fragment shader out vec4 outColor; float deg2rad(in float deg) { return 2.0 * PI * deg / 360.0; } float rad2deg(in float rad) { return 360.0 * rad / (2.0 * PI); } void main() { if (u_draw_texture) { float lon = 2.0 * PI * (v_texcoord.x - 0.5); float lat = PI * (0.5 - v_texcoord.y); float LSTlon = u_LST + lon; float h = LSTlon - u_rA; // For Intel GPUs, the argument for asin can be outside [-1, 1] unless limited. float altitude = asin(clamp(cos(h)*cos(u_decl)*cos(lat) + sin(u_decl)*sin(lat), -1.0, 1.0)); altitude = rad2deg(altitude); if (altitude > 0.0) { // Day. outColor = texture(u_imageDay, v_texcoord); } else if (altitude > -6.0) { // Civil twilight. outColor = mix(texture(u_imageNight, v_texcoord), texture(u_imageDay, v_texcoord), 0.75); } else if (altitude > -12.0) { // Nautical twilight. outColor = mix(texture(u_imageNight, v_texcoord), texture(u_imageDay, v_texcoord), 0.5); } else if (altitude > -18.0) { // Astronomical twilight. outColor = mix(texture(u_imageNight, v_texcoord), texture(u_imageDay, v_texcoord), 0.25); } else { // Night. outColor = texture(u_imageNight, v_texcoord); } if (u_show_iss) { float longitude = rad2deg(lon); float latitude = rad2deg(lat); // Surface coordinates. float sinLat = sin(deg2rad(latitude)); float N = A / sqrt(1.0 - E*E*sinLat*sinLat); float xECEF = N * cos(deg2rad(latitude)) * cos(deg2rad(longitude)); float yECEF = N * cos(deg2rad(latitude)) * sin(deg2rad(longitude)); float zECEF = (1.0 - E*E) * N * sin(deg2rad(latitude)); float normECEF = sqrt(xECEF * xECEF + yECEF * yECEF + zECEF * zECEF); float xDiff = u_iss_x - xECEF; float yDiff = u_iss_y - yECEF; float zDiff = u_iss_z - zECEF; float normDiff = sqrt(xDiff * xDiff + yDiff * yDiff + zDiff * zDiff); float dotProduct = xECEF * xDiff + yECEF * yDiff + zECEF * zDiff; float issAltitude = rad2deg(asin(dotProduct / (normECEF * normDiff))); if (issAltitude > 0.0) { outColor = outColor + vec4(0.2, 0.0, 0.0, 0.0); } } } else { outColor = vec4(1.0, 1.0, 1.0, 1.0); } } `; this.vertShaderGrid = `#version 300 es // an attribute is an input (in) to a vertex shader. // It will receive data from a buffer in vec4 a_position; in vec4 a_color; // A matrix to transform the positions by uniform mat4 u_matrix; // a varying the color to the fragment shader out vec4 v_color; // all shaders have a main function void main() { // Multiply the position by the matrix. gl_Position = u_matrix * a_position; // Pass the color to the fragment shader. v_color = a_color; } `; this.fragShaderGrid = `#version 300 es precision highp float; // the varied color passed from the vertex shader in vec4 v_color; // we need to declare an output for the fragment shader out vec4 outColor; void main() { outColor = v_color; } `; } /** * Initialize shaders, buffers and textures. * * @param {String} srcTextureDay * URL of the texture for the iluminated part of the sphere. * @param {String} srcTextureNight * URL of the texture for the non-iluminated part of the sphere. */ init(srcTextureDay, srcTextureNight) { let gl = this.gl; this.program = compileProgram(gl, this.vertShaderSphere, this.fragShaderSphere); this.programGrid = compileProgram(gl, this.vertShaderGrid, this.fragShaderGrid); // Get attribute and uniform locations. this.posAttrLocation = gl.getAttribLocation(this.program, "a_position"); this.texAttrLocation = gl.getAttribLocation(this.program, "a_texcoord"); this.matrixLocation = gl.getUniformLocation(this.program, "u_matrix"); this.posAttrLocationGrid = gl.getAttribLocation(this.programGrid, "a_position"); this.colorAttrLocationGrid = gl.getAttribLocation(this.programGrid, "a_color"); this.matrixLocationGrid = gl.getUniformLocation(this.programGrid, "u_matrix"); this.vertexArrayPlanet = gl.createVertexArray(); gl.bindVertexArray(this.vertexArrayPlanet); // Load planet vertex coordinates into a buffer. let positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); this.setGeometry(); gl.enableVertexAttribArray(this.posAttrLocation); gl.vertexAttribPointer(this.posAttrLocation, 3, gl.FLOAT, false, 0, 0); // Load texture vertex coordinates into a buffer. const texcoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer); this.setTexcoords(); gl.enableVertexAttribArray(this.texAttrLocation); gl.vertexAttribPointer(this.texAttrLocation, 2, gl.FLOAT, true, 0, 0); // Load grid coordinates. this.vertexArrayGrid = gl.createVertexArray(); gl.bindVertexArray(this.vertexArrayGrid); this.positionBufferGrid = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBufferGrid); this.setGeometryGrid(); gl.enableVertexAttribArray(this.posAttrLocationGrid); gl.vertexAttribPointer(this.posAttrLocationGrid, 3, gl.FLOAT, false, 0, 0); this.colorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); this.setColorsGrid(); gl.enableVertexAttribArray(this.colorAttrLocationGrid); gl.vertexAttribPointer(this.colorAttrLocationGrid, 3, gl.UNSIGNED_BYTE, true, 0, 0); // Initialize buffer for map coordinates. this.vertexArrayMap = gl.createVertexArray(); gl.bindVertexArray(this.vertexArrayMap); this.positionBufferMap = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBufferMap); gl.enableVertexAttribArray(this.posAttrLocationGrid); gl.vertexAttribPointer(this.posAttrLocationGrid, 3, gl.FLOAT, false, 0, 0); this.colorBufferMap = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBufferMap); gl.enableVertexAttribArray(this.colorAttrLocationGrid); gl.vertexAttribPointer(this.colorAttrLocationGrid, 3, gl.UNSIGNED_BYTE, true, 0, 0); // Load textures: const imageDay = new Image(); imageDay.src = srcTextureDay; const imageLocationDay = gl.getUniformLocation(this.program, "u_imageDay"); const imageNight = new Image(); imageNight.src = srcTextureNight; const imageLocationNight = gl.getUniformLocation(this.program, "u_imageNight"); this.numTextures = 0; let instance = this; imageDay.addEventListener('load', function() { instance.loadTexture(0, imageDay, imageLocationDay); }); imageNight.addEventListener('load', function() { instance.loadTexture(1, imageNight, imageLocationNight); }); gl.useProgram(this.program); this.loadMaps(); } /** * Load texture. * * @param {Number} index * Index of the texture. * @param {Image} image * The image to be loaded. * @param {WebGLUniformLocation} imageLocation * Uniform location for the texture. */ loadTexture(index, image, imageLocation) { let gl = this.gl; gl.useProgram(this.program); // Create a texture. var texture = gl.createTexture(); // use texture unit 0 gl.activeTexture(gl.TEXTURE0 + index); // bind to the TEXTURE_2D bind point of texture unit 0 gl.bindTexture(gl.TEXTURE_2D, texture); // Fill the texture with a 1x1 blue pixel. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 255, 255])); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.generateMipmap(gl.TEXTURE_2D); gl.uniform1i(imageLocation, index); this.numTextures = this.numTextures + 1; } /** * Insert array of numbers into Float32Array; * * @param {*} buffer * Target buffer. * @param {*} index * Start index. * @param {*} arrayIn * Array to be inserted. */ insertBufferFloat32(buffer, index, arrayIn) { for (let indArray = 0; indArray < arrayIn.length; indArray++) { buffer[index + indArray] = arrayIn[indArray]; } } /** * Insert square segment of a sphere into a Float32Buffer. * * @param {*} buffer * The target buffer. * @param {*} indRect * The index of the rectangle. * @param {*} lonStart * Longitude start of the rectangle. * @param {*} lonEnd * Longitude end of the rectangle. * @param {*} latStart * Latitude start of the rectangle. * @param {*} latEnd * Latitude end of the rectangle. */ insertRectGeo(buffer, indRect, lonStart, lonEnd, latStart, latEnd) { const indStart = indRect * 3 * 6; const x1 = this.a * Math.cos(latStart) * Math.cos(lonStart); const y1 = this.a * Math.cos(latStart) * Math.sin(lonStart); const z1 = this.b * Math.sin(latStart); const x2 = this.a * Math.cos(latStart) * Math.cos(lonEnd); const y2 = this.a * Math.cos(latStart) * Math.sin(lonEnd); const z2 = this.b * Math.sin(latStart); const x3 = this.a * Math.cos(latEnd) * Math.cos(lonEnd); const y3 = this.a * Math.cos(latEnd) * Math.sin(lonEnd); const z3 = this.b * Math.sin(latEnd); const x4 = this.a * Math.cos(latEnd) * Math.cos(lonStart); const y4 = this.a * Math.cos(latEnd) * Math.sin(lonStart); const z4 = this.b * Math.sin(latEnd); this.insertBufferFloat32(buffer, indStart, [x1,y1,z1, x2,y2,z2, x3,y3,z3, x1,y1,z1, x3,y3,z3, x4,y4,z4]); } /** * Fill vertex buffer for sphere triangles. */ setGeometry() { const gl = this.gl; const nTri = this.nLon * this.nLat * 2; const nPoints = nTri * 3; const positions = new Float32Array(nPoints * 3); for (let lonStep = 0; lonStep < this.nLon; lonStep++) { const lon = 2 * Math.PI * (lonStep / this.nLon - 0.5); const lonNext = 2 * Math.PI * ((lonStep + 1) / this.nLon - 0.5); for (let latStep = 0; latStep <= this.nLat-1; latStep++) { const lat = Math.PI * (latStep / this.nLat - 0.5); const latNext = Math.PI * ((latStep + 1) / this.nLat - 0.5); const indTri = latStep + lonStep * this.nLat; this.insertRectGeo(positions, indTri, lon, lonNext, lat, latNext, 1); } } gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); } /** * Insert a texture coordinates for a square segment. * * @param {*} buffer * Target buffer. * @param {*} indRect * Index of the rectangle. * @param {*} lonStart * Longitude start (radians). * @param {*} lonEnd * Longitude end (radians). * @param {*} latStart * Latitude start (radians). * @param {*} latEnd * Latitude end (radians). */ insertRectTex(buffer, indRect, lonStart, lonEnd, latStart, latEnd) { const indStart = indRect * 2 * 6; const uLonStart = (lonStart / (2 * Math.PI)) + 0.5; const uLonEnd = (lonEnd / (2 * Math.PI)) + 0.5; const uLatStart = -(latStart) / Math.PI + 0.5; const uLatEnd = -(latEnd) / Math.PI + 0.5; this.insertBufferFloat32(buffer, indStart, [uLonStart, uLatStart, uLonEnd, uLatStart, uLonEnd, uLatEnd, uLonStart, uLatStart, uLonEnd, uLatEnd, uLonStart, uLatEnd]); } /** * Fill vertex buffer for textures */ setTexcoords() { const gl = this.gl; const nTri = this.nLon * this.nLat * 2; const nPoints = nTri * 3; const positions = new Float32Array(nPoints * 2); for (let lonStep = 0; lonStep <= this.nLon; lonStep++) { const lon = 2 * Math.PI * (lonStep / this.nLon - 0.5); const lonNext = 2 * Math.PI * ((lonStep + 1) / this.nLon - 0.5); for (let latStep = 0; latStep <= this.nLat; latStep++) { const lat = Math.PI * (latStep / this.nLat - 0.5); const latNext = Math.PI * ((latStep + 1) / this.nLat - 0.5); const indTri = latStep + lonStep * this.nLat; this.insertRectTex(positions, indTri, lon, lonNext, lat, latNext); } } gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); } /** * Draw the planet. * * @param {*} viewMatrix * The view matrix. * @param {*} rA * The right ascension of the light source. * @param {*} decl * The declination of the light source. * @param {*} drawTexture * Whether to draw the texture. * @param {*} drawGrid * Whether to draw the grid. * @param {*} drawMap * Whether to draw the map. * @param {*} rECEF * ECEF coordinates of the satellite. Null if the drawing of visibility is skipped. */ draw(viewMatrix, rA, decl, LST, drawTexture, drawGrid, drawMap, rECEF) { if (this.numTextures < 2) { return; } const gl = this.gl; gl.useProgram(this.program); gl.uniformMatrix4fv(this.matrixLocation, false, viewMatrix); const raLocation = gl.getUniformLocation(this.program, "u_rA"); const declLocation = gl.getUniformLocation(this.program, "u_decl"); const lstLocation = gl.getUniformLocation(this.program, "u_LST"); const drawTextureLocation = gl.getUniformLocation(this.program, "u_draw_texture"); const issXLocation = gl.getUniformLocation(this.program, "u_iss_x"); const issYLocation = gl.getUniformLocation(this.program, "u_iss_y"); const issZLocation = gl.getUniformLocation(this.program, "u_iss_z"); const showIssLocation = gl.getUniformLocation(this.program, "u_show_iss"); gl.uniform1f(raLocation, rA); gl.uniform1f(declLocation, decl); gl.uniform1f(lstLocation, LST); if (drawTexture) { gl.uniform1f(drawTextureLocation, 1); } else { gl.uniform1f(drawTextureLocation, 0); } if (rECEF != null) { gl.uniform1f(showIssLocation, 1); gl.uniform1f(issXLocation, rECEF[0]); gl.uniform1f(issYLocation, rECEF[1]); gl.uniform1f(issZLocation, rECEF[2]); } else { gl.uniform1f(showIssLocation, 0); } // Draw the sphere. gl.bindVertexArray(this.vertexArrayPlanet); const nTri = this.nLon * this.nLat * 2; const count = nTri * 3; gl.drawArrays(gl.TRIANGLES, 0, count); gl.useProgram(this.programGrid); gl.bindVertexArray(this.vertexArrayGrid); gl.uniformMatrix4fv(this.matrixLocationGrid, false, viewMatrix); // Draw the grid. if (drawGrid) { gl.drawArrays(gl.LINES, 0, this.gridLines * 2); } if (drawMap) { gl.bindVertexArray(this.vertexArrayMap); gl.drawArrays(gl.LINES, 0, this.gridLinesMap * 2); } } // Fill the current ARRAY_BUFFER buffer with grid. setGeometryGrid() { let gl = this.gl; const points = []; let lonStep = 2.0; let latStep = this.latGridStep; let nLines = 0; let gridCoeff = 1.002; const nStepLat = Math.floor(90.0 / latStep); for (let lat = -nStepLat * latStep; lat <= nStepLat * latStep; lat += latStep) { for (let lon = -180.0; lon < 180.0; lon += lonStep) { const xStart = gridCoeff * this.a * MathUtils.cosd(lat) * MathUtils.cosd(lon); const yStart = gridCoeff * this.a * MathUtils.cosd(lat) * MathUtils.sind(lon); const zStart = gridCoeff * this.b * MathUtils.sind(lat); const xEnd = gridCoeff * this.a * MathUtils.cosd(lat) * MathUtils.cosd(lon + lonStep); const yEnd = gridCoeff * this.a * MathUtils.cosd(lat) * MathUtils.sind(lon + lonStep); const zEnd = gridCoeff * this.b * MathUtils.sind(lat); points.push([xStart, yStart, zStart]); points.push([xEnd, yEnd, zEnd]); nLines++; } } latStep = 2.0; lonStep = this.lonGridStep; const nStepLon = Math.floor(180.0 / lonStep); for (let lon = -nStepLon * lonStep; lon <= nStepLon * lonStep; lon += lonStep) { for (let lat = -90.0; lat < 90.0; lat += latStep) { const xStart = gridCoeff * this.a * MathUtils.cosd(lat) * MathUtils.cosd(lon); const yStart = gridCoeff * this.a * MathUtils.cosd(lat) * MathUtils.sind(lon); const zStart = gridCoeff * this.b * MathUtils.sind(lat); const xEnd = gridCoeff * this.a * MathUtils.cosd(lat + latStep) * MathUtils.cosd(lon); const yEnd = gridCoeff * this.a * MathUtils.cosd(lat + latStep) * MathUtils.sind(lon); const zEnd = gridCoeff * this.b * MathUtils.sind(lat + latStep); points.push([xStart, yStart, zStart]); points.push([xEnd, yEnd, zEnd]); nLines++; } } this.gridLines = nLines; var positions = new Float32Array(this.gridLines * 6); for (let indPoint = 0; indPoint < points.length; indPoint++) { let point = points[indPoint]; let indStart = indPoint * 3; positions[indStart] = point[0]; positions[indStart + 1] = point[1]; positions[indStart + 2] = point[2]; } gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); } /** * Update grid resolution. * * @param {*} lonRes * Longitude resolution in degrees. * @param {*} latRes * Latitude resolution in degrees. */ updateGrid(lonRes, latRes) { this.lonGridStep = lonRes; this.latGridStep = latRes; gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBufferGrid); this.setGeometryGrid(); gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); this.setColorsGrid(); } // Fill the current ARRAY_BUFFER buffer with colors for the 'F'. setColorsMap() { let gl = this.gl; const colorArray = new Uint8Array(this.gridLinesMap * 6); for (let indPoint = 0; indPoint < this.gridLinesMap * 2; indPoint++) { const startIndex = indPoint * 3; colorArray[startIndex] = this.colorMap[0]; colorArray[startIndex + 1] = this.colorMap[1]; colorArray[startIndex + 2] = this.colorMap[2]; } gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBufferMap); gl.bufferData(gl.ARRAY_BUFFER, colorArray, gl.STATIC_DRAW); } // Fill the current ARRAY_BUFFER buffer with colors for the 'F'. setColorsGrid() { let gl = this.gl; const colorArray = new Uint8Array(this.gridLines * 6); for (let indPoint = 0; indPoint < this.gridLines * 2; indPoint++) { const startIndex = indPoint * 3; colorArray[startIndex] = this.colorGrid[0]; colorArray[startIndex + 1] = this.colorGrid[1]; colorArray[startIndex + 2] = this.colorGrid[2]; } gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); gl.bufferData(gl.ARRAY_BUFFER, colorArray, gl.STATIC_DRAW); } loadMapPolygons() { const points = []; let nLines = 0; let gl = this.gl; let gridCoeff = 1.002; for (let indPoly = 0; indPoly < this.polygons.length; indPoly++) { const poly = this.polygons[indPoly]; for (let indPoint = 0; indPoint < poly.lon.length - 1; indPoint++) { const lonStart = poly.lon[indPoint]; const latStart = poly.lat[indPoint]; const lonEnd = poly.lon[indPoint + 1]; const latEnd = poly.lat[indPoint + 1]; const xStart = gridCoeff * this.a * MathUtils.cosd(latStart) * MathUtils.cosd(lonStart); const yStart = gridCoeff * this.a * MathUtils.cosd(latStart) * MathUtils.sind(lonStart); const zStart = gridCoeff * this.b * MathUtils.sind(latStart); const xEnd = gridCoeff * this.a * MathUtils.cosd(latEnd) * MathUtils.cosd(lonEnd); const yEnd = gridCoeff * this.a * MathUtils.cosd(latEnd) * MathUtils.sind(lonEnd); const zEnd = gridCoeff * this.b * MathUtils.sind(latEnd); points.push([xStart, yStart, zStart]); points.push([xEnd, yEnd, zEnd]); nLines++; } } this.gridLinesMap = nLines; const positions = new Float32Array(this.gridLinesMap * 6); for (let indPoint = 0; indPoint < points.length; indPoint++) { let point = points[indPoint]; let indStart = indPoint * 3; positions[indStart] = point[0]; positions[indStart + 1] = point[1]; positions[indStart + 2] = point[2]; } gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBufferMap); gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW); this.setColorsMap(); } loadMaps() { let polygons = []; /** * Add polygon to the polygon list. * The method transforms the polygon from a list of lon-lat pairs to arrays * of lat and lon coordinates. * * @param {*} polygon * Polygon as a list of lon-lat pairs. * @returns The number of points in the polygon. */ let addPolygon = function(polygon) { var numPoints = polygon.length; var pointsLon = []; var pointsLat = []; for (var indPoint = 0; indPoint < numPoints; indPoint++) { pointsLon.push(polygon[indPoint][0]); pointsLat.push(polygon[indPoint][1]); } polygons.push({lon : pointsLon, lat : pointsLat}); return numPoints; } this.polygons = []; const instance = this; var xmlHTTP = new XMLHttpRequest(); xmlHTTP.onreadystatechange = function() { console.log("readyState: " + this.readyState); console.log("status: " + this.status); if (this.readyState == 4 && this.status == 200) { // Parse JSON and initialize World map. let dataJSON = JSON.parse(this.responseText); console.log(dataJSON); var features = dataJSON.features; var numPointsTotal = 0; for (var index = 0; index < features.length; index++) { // Read polygons and multi-polygons. var feature = features[index]; var geometry = feature.geometry; // TBD: //var properties = feature.properties; if (geometry.type === "Polygon") { var coordinates = geometry.coordinates[0]; var numPoints = geometry.coordinates[0].length; numPointsTotal += addPolygon(coordinates); } if (geometry.type === "MultiPolygon") { var numPolygons = geometry.coordinates.length; for (var indPolygon = 0; indPolygon < numPolygons; indPolygon++) { var coordinates = geometry.coordinates[indPolygon][0]; numPointsTotal += addPolygon(coordinates); } } } console.log("Added " + numPointsTotal + " points"); instance.polygons = polygons; console.log(instance.polygons); instance.loadMapPolygons(); } } xmlHTTP.open("GET", "json/worldmap.json", true); xmlHTTP.send(); } }
JavaScript
class NTLMAuthentication { /** * * @param {Object} domain */ constructor(domain) { this.AUTHENTICATION_SERVICE_NTLM = 10; this.UNICODE_SUPPORTED = true; this.BASIC_FLAGS = NtlmFlags.NTLMSSP_REQUEST_TARGET | NtlmFlags.NTLMSSP_NEGOTIATE_NTLM | NtlmFlags.NTLMSSP_NEGOTIATE_OEM | NtlmFlags.NTLMSSP_NEGOTIATE_ALWAYS_SIGN | (this.UNICODE_SUPPORTED ? NtlmFlags.NTLMSSP_NEGOTIATE_UNICODE : 0); this.security; this.authenticationSource; this.lanManagerkey; this.seal; this.sign; this.keyExchange; this.useNtlm2sessionsecurity = false; this.useNtlmV2 = false; let user = domain.username; let password = domain.password; // FIXME: most of these came from properties and have these values by default this.lanManagerkey = false; this.seal = false; this.sign = false; this.keyExchange = false; const keyLength = 128; if (keyLength != null) { try { this.keyLength = Number.parseInt(keyLength); } catch (err) { throw new Error('Invalid key length: ' + keyLength); } } // this.useNtlm2sessionsecurity = true; // this.useNtlmV2 = true; this.domain = domain.domain; const security = new Security(); this.user = security.USERNAME; this.password = security.PASSWORD; this.credentials = {domain: domain.domain, username: user, password: password}; } /** * @return {Boolean} security value */ getSecurity() { return this.security; } /** * @return {String} */ getAuthenticationResource() { if (this.authenticationSource != null) { return this.authenticationSource; } return new AuthenticationSrouce.getDefaultInstance(); } getDefaultFlags() { var flags = this.BASIC_FLAGS; if (this.lanManagerkey) flags |= NtlmFlags.NTLMSSp_NEGOTIATE_LM_KEY; if (this.sign) flags |= NtlmFlags.NTLMSSP_NEGOTIATE_SIGN; if (this.sign) flags |= NtlmFlags.NTLMSSP_NEGOTIATE_SEAL; if (this.keyExchange) flags |= NtlmFlags.NTLMSSP_NEGOTIATE_KEY_EXCH; if (this.keyLength >= 56) flags |= NtlmFlags.NTLMSSP_NEGOTIATE_56; if (this.keyLength >= 128) flags |= NtlmFlags.NTLMSSP_NEGOTIATE_128; flags |= NtlmFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY; return flags; } adjustFlags(flags) { if (this.UNICODE_SUPPORTED && ((flags & NtlmFlags.NTLMSSP_NEGOTIATE_UNICODE) != 0)) { flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_OEM; flags |= NtlmFlags.NTLMSSP_NEGOTIATE_UNICODE; } else { flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_UNICODE; flags |= NtlmFlags.NTLMSSP_NEGOTIATE_OEM; } if (!this.lanManagerKey) flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_LM_KEY; if (!(this.sign || this.seal)) flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_SIGN; if (!this.seal) flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_SEAL; if (!this.keyExchange) flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_KEY_EXCH; if (this.keyLength < 128) flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_128; if (this.keyLength < 56) flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_56; // if (!useNtlm2sessionsecurity) // { // flags &= ~NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2; // } return flags; } createType1(domain) { var flags = this.getDefaultFlags(); return new Type1Message(null, flags, domain, os.hostname()); } createType2(type1) { var flags; if (type1 == null) { flags = this.getDefaultFlags(); } else { flags = this.adjustFlags(type1.getFlags()); } // challenge accept response flag flags |= 0x00020000; var type2Message = new Type2Message(flags, [1,2,3,4,5,6,7,8], this.credentials.domain); return type2Message; } /** * * @param {Type2Message} type2 * @param {Object} info * @return {Type3Message} */ createType3(type2, info) { let flags = type2.getFlags(); if ((flags & NtlmFlags.NTLMSSP_NEGOTIATE_DATAGRAM_STYLE) != 0) { flags = this.adjustFlags(flags); flags &= ~0x00020000; } let type3 = null; let clientNonce = new Array(8); const blob = null; let target = null; if (target == null) { target = info.domain.toUpperCase(); if (target == '') { target = this.getTargetFromTargetInformation(type2.getTargetInformation()); } } if (this.useNtlmV2) { clientNonce = [...(Crypto.randomBytes(8))]; try { const lmv2Response = new Responses().getLMv2Response(target, this.credentials.username, this.credentials.password, type2.getChallenge(), clientNonce); const retval = new Responses().getNTLMv2Response(target, this.credentials.username, this.credentials.password, type2.getTargetInformation(), type2.getChallenge(), clientNonce); const ntlmv2Response = retval[0]; type3 = new Type3Message(flags, lmv2Response, ntlmv2Response, target, this.credentials.username, new Type3Message().getDefaultWorkstation()); } catch (err) { throw new Error('Exception occured while forming NTLMv2 Type3Response', e); } } else if ((flags & NtlmFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY) != 0) { flags = this.adjustFlags(flags); flags &= ~0x00020000; const challenge = type2.getChallenge(); let lmResponse = new Array(24); clientNonce = [...(Crypto.randomBytes(8))]; let aux = clientNonce.slice(0, clientNonce.length); let aux_i = 0; while (aux.length > 0) lmResponse.splice(aux_i++, 1, aux.shift()); while (aux_i < lmResponse.length) lmResponse[aux_i++] = 0; let ntResponse; try { ntResponse = new Responses().getNTLM2SessionResponse( this.credentials.password, Buffer.from(challenge), Buffer.from(clientNonce)); } catch (e) { throw new Error('Exception occured while forming Session Security Type3Response',e); } type3 = new Type3Message(flags, lmResponse, ntResponse, target, this.credentials.username, os.hostname()); } else { const challenge = type2.getChallenge(); const lmResponse = NtlmPasswordAuthentication.getPreNTLMResponse( this.credentials.password, challenge); const ntResponse = NtlmPasswordAuthentication.getNTLMResposne( this.credentials.password, challenge); type3 = new Type3Message(flags, lmResponse, ntResponse, target, this.credentials.username, new Type3Message().getDefaultWorkstation()); if ((flags & NtlmFlags.NTLMSSP_NEGOTIATE_KEY_EXCH) != 0) { throw new RuntimeException('Key Exchange not supported by Library !'); } } if (this.useNtlm2sessionsecurity && (flags & NtlmFlags.NTLMSSP_NEGOTIATE_NTLM2) != 0) { var ntlmKeyFactory = new NTLMKeyFactory(); var userSessionKey; if (this.useNtlmV2) { try { userSessionKey = ntlmKeyFactory.getNTLMv2UserSessionKey(target, this.credentials.username, this.credentials.password, type2.getChallenge(), blob); } catch (e) { throw new Error("Exception occured while forming NTLMv2 with NTLM2 Session Security for Type3Response ",e); } } else { var servernonce; servernonce = type2.getChallenge().slice(0, type2.getChallenge().length); servernonce.concat(servernonce, clientNonce); try { userSessionKey = ntlmKeyFactory.getNTLM2SessionResponseUserSessionKey( this.credentials.password(), this.credentials.password(), servernonce); } catch (e) { throw new Error("Exception occured while forming Session Security for Type3Response ",e); } try { var secondayMasterKey = ntlmKeyFactory.getSecondarySessionKey(); type3.setSessionKey(ntlmKeyFactory.encryptSecondarySessionKey(secondayMasterKey, userSessionKey)); this.security = new Ntlm1(flags, secondayMasterKey,false); } catch (e) { throw new Error("Exception occured while forming Session Security for Type3Response",e); } } } return type3; } getTargetFromTargetInformation(targetInformation) { var target = null; var i = 0; while (i < targetInformation.length) { switch (new Encdec().dec_uint16le(targetInformation, i)) { case 1: i++; i++; var length = new Encdec.dec_uint16le(targetInformation, i); i++; i++ var domainb = new Array(length); domainb = targetInformation.slice(i, length); try { target = String(domainb); } catch (err) { return null; } i = i + length; i = targetInformation.length; break; default: i++; i++; length = new Encdec().dec_uint16le(targetInformation,i); i++; i++ i = i + length; } } return target; } createSecurityWhenServer(type3) { var type3Message = type3; var flags = type3Message.getFlags(); var ntlmKeyFactory = new ntlmKeyFactory(); var secondayMasterKey; var sessionResponseUserSessionKey = null; if (type3Message.getFlag(0x00000800)) { sessionResponseUserSessionKey = new Array(16); } else if (this.useNtlmV2) { // TODO: create the key var h = 0; } else { //now create the key for the session //this key will be used to RC4 a 16 byte random key and set to the type3 message var servernonce; var challenge = new Array(1,2,3,4,5,6,7,8); //challenge is fixed servernonce = challenge.slice(0, challenge.length); servernonce.concat(type3Message.getLMResponse().slice(0, 8));//first 8 bytes only , the rest are all 0x00 and not required. try { sessionResponseUserSessionKey = ntlmKeyFactory.getNTLM2SessionResponseUserSessionKey(this.credentials.password, servernonce); } catch (e) { throw new RuntimeException("Exception occured while forming Session Security from Type3 AUTH",e); } } try { //now RC4 decrypt the session key secondayMasterKey = ntlmKeyFactory.decryptSecondarySessionKey(type3Message.getSessionKey(), sessionResponseUserSessionKey); this.security = new Ntlm1(flags, secondayMasterKey,true); } catch (e){ throw new RuntimeException("Exception occured while forming Session Security Type3Response",e); } } }
JavaScript
class LoopService { static getLoopNames() { return fetch('/restservices/clds/v2/loop/getAllNames', { method: 'GET', credentials: 'same-origin' }) .then(function (response) { console.debug("GetLoopNames response received: ", response.status); if (response.ok) { return response.json(); } else { console.error("GetLoopNames query failed"); return {}; } }) .catch(function (error) { console.error("GetLoopNames error received", error); return {}; }); } static getLoop(loopName) { return fetch('/restservices/clds/v2/loop/' + loopName, { method: 'GET', headers: { "Content-Type": "application/json" }, credentials: 'same-origin' }) .then(function (response) { console.debug("GetLoop response received: ", response.status); if (response.ok) { return response.json(); } else { console.error("GetLoop query failed"); return {}; } }) .catch(function (error) { console.error("GetLoop error received", error); return {}; }); } static getSvg(loopName) { return fetch('/restservices/clds/v2/loop/svgRepresentation/' + loopName, { method: 'GET', credentials: 'same-origin' }) .then(function (response) { console.debug("svgRepresentation response received: ", response.status); if (response.ok) { return response.text(); } else { console.error("svgRepresentation query failed"); return ""; } }) .catch(function (error) { console.error("svgRepresentation error received", error); return ""; }); } static setMicroServiceProperties(loopName, jsonData) { return fetch('/restservices/clds/v2/loop/updateMicroservicePolicy/' + loopName, { method: 'POST', credentials: 'same-origin', headers: { "Content-Type": "application/json" }, body: JSON.stringify(jsonData) }) .then(function (response) { console.debug("updateMicroservicePolicy response received: ", response.status); if (response.ok) { return response.text(); } else { console.error("updateMicroservicePolicy query failed"); return ""; } }) .catch(function (error) { console.error("updateMicroservicePolicy error received", error); return ""; }); } static setOperationalPolicyProperties(loopName, jsonData) { return fetch('/restservices/clds/v2/loop/updateOperationalPolicies/' + loopName, { method: 'POST', credentials: 'same-origin', headers: { "Content-Type": "application/json" }, body: JSON.stringify(jsonData) }) .then(function (response) { console.debug("updateOperationalPolicies response received: ", response.status); if (response.ok) { return response.text(); } else { console.error("updateOperationalPolicies query failed"); return ""; } }) .catch(function (error) { console.error("updateOperationalPolicies error received", error); return ""; }); } static updateGlobalProperties(loopName, jsonData) { return fetch('/restservices/clds/v2/loop/updateGlobalProperties/' + loopName, { method: 'POST', credentials: 'same-origin', headers: { "Content-Type": "application/json" }, body: JSON.stringify(jsonData) }) .then(function (response) { console.debug("updateGlobalProperties response received: ", response.status); if (response.ok) { return response.text(); } else { console.error("updateGlobalProperties query failed"); return ""; } }) .catch(function (error) { console.error("updateGlobalProperties error received", error); return ""; }); } static refreshOpPolicyJson(loopName) { return fetch('/restservices/clds/v2/loop/refreshOpPolicyJsonSchema/' + loopName, { method: 'PUT', headers: { "Content-Type": "application/json" }, credentials: 'same-origin' }) .then(function (response) { console.debug("Refresh Operational Policy Json Schema response received: ", response.status); if (response.ok) { return response.json(); } else { console.error("Refresh Operational Policy Json Schema query failed"); return {}; } }) .catch(function (error) { console.error("Refresh Operational Policy Json Schema error received", error); return {}; }); } }
JavaScript
class DateTime extends implementationOf(DateTimeInterface) { /** * Constructor. * * @param {undefined|string|int|Date} [datetime] The datetime string or unix timestamp * @param {undefined|string|Jymfony.Contracts.DateTime.DateTimeZoneInterface} [timezone] The timezone of the datetime */ __construct(datetime = undefined, timezone = undefined) { if (undefined === datetime) { const d = new Date(); this._tm = new TimeDescriptor(timezone); this._tm.unixTimestamp = ~~(d.getTime() / 1000); } else if (isString(datetime)) { const p = new Parser(); this._tm = p.parse(datetime, timezone); } else if (isNumber(datetime)) { this._tm = new TimeDescriptor(timezone); this._tm.unixTimestamp = datetime; } else if (datetime instanceof Date) { const val = datetime.valueOf(); this._tm = new TimeDescriptor(timezone); this._tm.unixTimestamp = ~~(val / 1000); this._tm.milliseconds = val % 1000; } else if (datetime instanceof __self) { this._tm = datetime._tm.copy(); } else { throw new InvalidArgumentException('Argument 1 passed to new DateTime should be a string, a number or undefined'); } } /** * Parse a string into a new DateTime object according to the specified format * * @param {string} format * @param {string} time * @param {undefined|string|Jymfony.Contracts.DateTime.DateTimeZoneInterface} [timezone] * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ static createFromFormat(format, time, timezone = undefined) { const obj = new __self(); obj._tm = DateTimeFormatter.parse(format, time); if (timezone) { obj._tm.timeZone = timezone; } return obj; } /** * Gets a new DateTime representing the current datetime. * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ static get now() { return new DateTime(); } /** * Gets current timestamp. * * @returns {int} */ static get unixTime() { return (new DateTime()).timestamp; } /** * Gets a new DateTime representing midnight of today. * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ static get today() { return (new DateTime()).setTime(0, 0, 0); } /** * Gets a new DateTime representing midnight of today. * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ static get yesterday() { const dt = DateTime.today; dt._tm.add(new TimeSpan('P-1D')); return dt; } /** * Gets the year. * * @returns {int} */ get year() { return this._tm._year; } /** * Gets the month. * * @returns {int} */ get month() { return this._tm.month; } /** * Gets the day. * * @returns {int} */ get day() { return this._tm.day; } /** * Gets the hour. * * @returns {int} */ get hour() { return this._tm.hour; } /** * Gets the minutes. * * @returns {int} */ get minute() { return this._tm.minutes; } /** * Gets the seconds. * * @returns {int} */ get second() { return this._tm.seconds; } /** * Gets the milliseconds. * * @returns {int} */ get millisecond() { return this._tm.milliseconds; } /** * Gets the timezone. * * @returns {Jymfony.Contracts.DateTime.DateTimeZoneInterface} */ get timezone() { return this._tm.timeZone; } /** * Gets the UNIX timestamp. * * @returns {int} */ get timestamp() { return this._tm.unixTimestamp; } /** * Gets the UNIX timestamp with milliseconds. * * @returns {float} */ get microtime() { return this._tm.unixTimestamp + (this._tm.milliseconds / 1000); } /** * Gets the Day of Week of this instance. * 1 = Monday, 7 = Sunday * * @returns {int} */ get dayOfWeek() { return this._tm.weekDay; } /** * Gets the Day of Year of this instance (1-366). * * @returns {int} */ get dayOfYear() { return this._tm.yearDay; } /** * Indicates whether this instance of DateTime is within * the daylight saving time range for the current time zone. * * @returns {boolean} */ get isDST() { return this._tm.timeZone.isDST(this); } /** * Indicates whether the year of this instance of DateTime is a leap year. * * @returns {boolean} */ get isLeapYear() { return this._tm.leap; } /** * Modify the time. * * @param {int} hours * @param {int} minutes * @param {int} seconds * @param {int} [milliseconds = 0] * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ setTime(hours, minutes, seconds, milliseconds = 0) { if ( hours === this._tm.hour && minutes === this._tm.minutes && seconds === this._tm.seconds && milliseconds === this._tm.milliseconds ) { return this; } const val = this.copy(); val._tm.hour = hours; val._tm.minutes = minutes; val._tm.seconds = seconds; val._tm.milliseconds = milliseconds; return val; } /** * Modify the date. * * @param {int} year * @param {int} month * @param {int} day * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ setDate(year, month, day) { if ( year === this._tm._year && month === this._tm.month && day === this._tm.day ) { return this; } const val = this.copy(); val._tm._year = year; val._tm.month = month; val._tm.day = day; if (! val._tm.valid) { throw new InvalidArgumentException('Invalid date.'); } return val; } /** * Modify the timezone. * * @param {Jymfony.Contracts.DateTime.DateTimeZoneInterface} timezone * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ setTimeZone(timezone) { const val = this.copy(); if (timezone === val._tm.timeZone) { return this; } val._tm.timeZone = timezone; this._tm._updateTime(); return val; } /** * Adds or subtracts a TimeSpan interval. * * @param {Jymfony.Contracts.DateTime.TimeSpanInterface} interval * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ modify(interval) { const val = this.copy(); val._tm.add(interval); return val; } /** * Returns a copy of the current instance. * * @returns {Jymfony.Contracts.DateTime.DateTimeInterface} */ copy() { const retVal = new DateTime(); retVal._tm = this._tm.copy(); return retVal; } /** * Formats a DateTime. * * @param {string} format * * @returns {string} */ format(format) { return DateTimeFormatter.format(this, format); } /** * Returns a value indicating whether this object has * the same date time value of the specified instance. * * @param {Jymfony.Contracts.DateTime.DateTimeInterface} instance * * @returns {boolean} */ equals(instance) { return instance instanceof DateTimeInterface && instance.timestamp === this.timestamp && instance.millisecond === this.millisecond; } /** * @inheritdoc */ toString() { return this.format(DateTime.ISO8601); } /** * @inheritdoc */ get [Symbol.toStringTag]() { return 'DateTime'; } }
JavaScript
class TurnMemoryScope extends memoryScope_1.MemoryScope { /** * Initializes a new instance of the [TurnMemoryScope](xref:botbuilder-dialogs.TurnMemoryScope) class. */ constructor() { super(scopePath_1.ScopePath.turn, true); } /** * Get the backing memory for this scope. * @param dc The [DialogContext](xref:botbuilder-dialogs.DialogContext) for this turn. * @returns The memory for the scope. */ getMemory(dc) { let memory = dc.context.turnState.get(TURN_STATE); if (typeof memory != 'object') { memory = {}; dc.context.turnState.set(TURN_STATE, memory); } return memory; } /** * Changes the backing object for the memory scope. * @param dc The [DialogContext](xref:botbuilder-dialogs.DialogContext) for this turn. * @param memory Memory object to set for the scope. */ setMemory(dc, memory) { if (memory == undefined) { throw new Error(`TurnMemoryScope.setMemory: undefined memory object passed in.`); } dc.context.turnState.set(TURN_STATE, memory); } }
JavaScript
class IonDetailProductComponent { constructor() { this.selectedFavorite = new EventEmitter(); this.review = new EventEmitter(); this.groups = [ { name: '5', percent: '0%', sum: 0 }, { name: '4', percent: '0%', sum: 0 }, { name: '3', percent: '0%', sum: 0 }, { name: '2', percent: '0%', sum: 0 }, { name: '1', percent: '0%', sum: 0 } ]; // console.log('Hello IonListCategoryComponent Component'); } favorite(item) { this.selectedFavorite.emit(item); } createReview() { this.review.emit('createReview'); } }
JavaScript
class GeneralMerchantsDTO { /** * Constructs a new <code>GeneralMerchantsDTO</code>. * @alias module:model/GeneralMerchantsDTO * @class */ constructor() { } /** * Constructs a <code>GeneralMerchantsDTO</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/GeneralMerchantsDTO} obj Optional instance to populate. * @return {module:model/GeneralMerchantsDTO} The populated <code>GeneralMerchantsDTO</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new GeneralMerchantsDTO(); if (data.hasOwnProperty('salutation')) { obj['salutation'] = ApiClient.convertToType(data['salutation'], 'String'); } if (data.hasOwnProperty('companyname')) { obj['companyname'] = ApiClient.convertToType(data['companyname'], 'String'); } if (data.hasOwnProperty('forename')) { obj['forename'] = ApiClient.convertToType(data['forename'], 'String'); } if (data.hasOwnProperty('surname')) { obj['surname'] = ApiClient.convertToType(data['surname'], 'String'); } if (data.hasOwnProperty('dob')) { obj['dob'] = ApiClient.convertToType(data['dob'], 'String'); } if (data.hasOwnProperty('homepage')) { obj['homepage'] = ApiClient.convertToType(data['homepage'], 'String'); } if (data.hasOwnProperty('email')) { obj['email'] = ApiClient.convertToType(data['email'], 'String'); } if (data.hasOwnProperty('phone')) { obj['phone'] = ApiClient.convertToType(data['phone'], 'String'); } if (data.hasOwnProperty('address')) { obj['address'] = Address.constructFromObject(data['address']); } if (data.hasOwnProperty('payment_data')) { obj['payment_data'] = PaymentInformation.constructFromObject(data['payment_data']); } if (data.hasOwnProperty('legal_details')) { obj['legal_details'] = ApiClient.convertToType(data['legal_details'], [GeneralMerchantsLegalDetails]); } if (data.hasOwnProperty('checkout_options')) { obj['checkout_options'] = GeneralMerchantsCheckoutOptions.constructFromObject(data['checkout_options']); } if (data.hasOwnProperty('urls')) { obj['urls'] = ApiClient.convertToType(data['urls'], [GeneralMerchantsUrls]); } } return obj; } /** * Salutation * @member {String} salutation */ salutation = undefined; /** * companyname * @member {String} companyname */ companyname = undefined; /** * forename * @member {String} forename */ forename = undefined; /** * surname * @member {String} surname */ surname = undefined; /** * Date of birth * @member {String} dob */ dob = undefined; /** * Merchant homepage url or shop url * @member {String} homepage */ homepage = undefined; /** * Merchant email address * @member {String} email */ email = undefined; /** * Merchant phone number * @member {String} phone */ phone = undefined; /** * Address * @member {module:model/Address} address */ address = undefined; /** * Merchants bank account for the payout * @member {module:model/PaymentInformation} payment_data */ payment_data = undefined; /** * Legal details * @member {Array.<module:model/GeneralMerchantsLegalDetails>} legal_details */ legal_details = undefined; /** * Checkout options * @member {module:model/GeneralMerchantsCheckoutOptions} checkout_options */ checkout_options = undefined; /** * Urls * @member {Array.<module:model/GeneralMerchantsUrls>} urls */ urls = undefined; }
JavaScript
class AlphabetNav { constructor(el) { this.el = el || document.createElement('div'); this.el.classList.add('alphabet-jump-nav'); let letters = this.letters.map(letter=>`<div class="letter">${letter}</div>`); this.el.innerHTML = '<div class="bar">'+letters.join("\n")+'</div><div class="preview"></div>'; this.preview = this.el.querySelector('.preview'); this.el.querySelectorAll('.letter').forEach(el => { el.addEventListener('mousedown', this.onClick.bind(this)); el.addEventListener('mouseup', this.onClick.bind(this)); el.addEventListener('mousemove', this.onHover.bind(this)); el.addEventListener('mousemove', this.onDrug.bind(this)); el.addEventListener('mouseout', this.onTouchEnd.bind(this)); }); this.el.addEventListener('mousemove', this.throttle(this.onTouchMove.bind(this), 70)); this.el.addEventListener('mouseup', this.onTouchEnd.bind(this)); this.el.addEventListener('mouseout', this.onTouchEnd.bind(this)); this.mousedown = false; this.navbarTouched = false; this.el.onmousedown = this.onMouseDown.bind(this); this.el.onmouseup = this.onMouseUp.bind(this); } throttle(func, ms) { let isThrottled = false; let savedArgs; let savedThis; function wrapper() { if (isThrottled) { savedArgs = arguments; savedThis = this; return; } func.apply(this, arguments); isThrottled = true; setTimeout(function() { isThrottled = false; if (savedArgs) { wrapper.apply(savedThis, savedArgs); savedArgs = savedThis = null; } }, ms); } return wrapper; } onDrug(e) { if (this.mousedown) { this.onClick(e); } } linkTo(el) { this.listEl = el; this.starterRows = {}; let starterRows = {}; el.childNodes.forEach(ll => { if (!ll.dataset) return; let char = ll.dataset.title && ll.dataset.title[0]; if (!char) return; char = char.toLowerCase(); let charCode = char.charCodeAt(0) - 97; if (charCode < 0 || charCode >= 26) char = '#'; if (!starterRows[char]) starterRows[char] = ll; }); let last = null; // fill in missing rows this.letters.reverse().forEach(letter => { if (!starterRows[letter]) { starterRows[letter] = last; } else { last = starterRows[letter]; } }); this.starterRows = starterRows return this } appendTo(el) { this.parentEl = el; el.appendChild(this.el); this.parentEl.addEventListener('scroll', this.onScrollContent.bind(this)); return this; } onHover(el) { this.preview.innerHTML = el.target.innerText; } onClick(e) { // this.isTouching = true; for (let letter of this.el.children[0].children) { letter.classList.remove('active'); } e.target.classList.add('active'); this.preview.style.visibility = 'visible'; this.preview.style.top = (e.clientY - this.el.getBoundingClientRect().top - (this.preview.offsetHeight/2)) +'px'; this.scrollTo(e.currentTarget); } onTouchEnd(e){ this.isTouching = false; // this.scrollTo(e.currentTarget); setTimeout(() => { this.preview.style.visibility = 'hidden'; }, 100); } onTouchMove(e) { e.stopPropagation(); e.preventDefault(); // this.isTouching = true; let xPos = this.el.offsetLeft + (this.el.offsetWidth/2); let yPos = e.clientY; let el = document.elementFromPoint(xPos, yPos); // if (this.isTouching) { this.preview.style.visibility = 'visible'; this.preview.style.top = (yPos - this.el.getBoundingClientRect().top - (this.preview.offsetHeight/2)) +'px'; // } // SCROLL HERE! this.scrollTo(el); return false; } scrollTo(el) { if (!el || el == this.el || !this.el.contains(el)) return; let val = el.innerText.toLowerCase(); this.preview.innerHTML = val; if (this.lastTouched == val) return; this.lastTouched = val; if (!this.starterRows || !this.listEl) return; this.listEl.childNodes.forEach(node => { if (node.dataset && node.dataset.title === val) { node.scrollIntoView({behavior: "smooth", inline: "end"}); val = false; } }); if (!this.isTouching) this.lastTouched = null; } onScrollContent(e) { const list = e.target.children[0].children; const navbarList = this.el.children[0].children; if (!this.navbarTouched) { for (let i = 0; i < list.length; i++) { if ( AlphabetNav.isInViewport(list[i]) && list[i + 1] && list[i + 1].dataset.title != list[i].dataset.title ) { for (let letter of navbarList) { letter.classList.remove('active'); if (letter.innerText.toLowerCase() === list[i].dataset.title.toLowerCase()) { letter.classList.add('active'); } } break; } } } } onMouseDown() { this.mousedown = true; this.navbarTouched = true; clearTimeout(this.timeout); } onMouseUp() { this.mousedown = false; this.timeout = setTimeout(() => { this.navbarTouched = false; }, 2000); } static isInViewport(el) { const bounding = el.getBoundingClientRect(); return ( bounding.top >= 110 && bounding.left >= 0 && bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) ); } get letters() { return [].concat(Array .apply(null, {length: 26}) .map((x, i) => String.fromCharCode(97 + i)) ); } }
JavaScript
class Widget { bindModel() { this.reRender(this.render()); } append(parent) { this.parent = parent; this.bindModel(); } reRender(newRendered) { if (this.rendered && this.parent.contains(this.rendered)) { this.parent.replaceChild(newRendered, this.rendered); } else { this.parent.appendChild(newRendered); } this.rendered = newRendered; } renderOnce() { if (this.renderedToParent != this.parent) { this.renderedToParent = this.parent; this.reRender(this.render()); } } }
JavaScript
class DataForm extends React.Component{ constructor(props){ super(props); //inicjalizacja stanu komponentu //TODO: przerobić tak by wykorzystać jeszcze do edycji istniejącego eksperymentu if (props.obj === undefined || props.obj === null){ this.state = {name:null, desc:null, window:null, metricID:"", paper:"", private:false, product:undefined, metric:"", filename:"", metricGeneral:"", generated:false, file:"", loaded:false, samples:[], ingredients:[], metrics:[],exp:props.obj, prodBase:[], prodObj:[], metricsGeneral:[], metricsGeneralBase:[], metricsDetailedBase:[], metricsDetailed:[], sampleBase:[], idExp:undefined,externalFactorBase:[], productWindow:undefined, new:true, openDialog:false, user:props.user } }else{ this.state = { name:props.obj.name, desc:props.obj.description, window:null, metricID:"", paper:props.obj.link, private:props.obj.publicView, product:props.obj.product, metric:"", filename:"",metricGeneral:"", generated:false, file:"", loaded:false, samples:[], ingredients:[], metrics:[], openDialog:false, prodBase:[], prodObj:[], metricsGeneral:[], metricsGeneralBase:[], metricsDetailedBase:[], metricsDetailed:[], sampleBase:[],exp:props.obj,externalFactorBase:[], productWindow:null, new:false, idExp:props.obj.id, user:props.user } axios.get("api/experiment/Result/").then((res)=>{ if(res.data.find((v)=>{return v.experiment == this.props.obj.id})===undefined){ this.setState({new:true}) } }) } } //komponent odpowiedzialny za usuwalną linijkę z metryką szczegółową //props.obj - metryka szczegółowa do obskoczenia // props.onButton - funkcja do wywołania dla przycisku usuń Line = (props) => { if(this.state.sampleBase.length>0){ let lv = props.obj let s = this.state.sampleBase.find((samp)=>{return samp.id === lv.sample}) return(<div> {lv.metric+": (serii: "+lv.numberOfSeries+"; powtórzeń: "+lv.numberOfRepeat+")"+" Dodatki: "+ JSON.stringify(s.supplement)+" Czynnik:"+s.externalFactor} <Button type="button" onClick={(e) => props.onButton(props.obj)}> Usuń </Button> </div>) } else{ return null } } componentDidMount = () => { this.refresh() } componentWillUnmount = () => { } refresh = ()=> { //żądania typu get do API axios.get("/api/experiment/DetailedMetrics/").then((res)=>{ if(this.props.obj !==undefined && this.props.obj.detailedMetrics !== undefined) { let arr = res.data.filter((dm =>{return this.props.obj.detailedMetrics.includes(dm.id)})) this.setState({metrics:arr}) } this.setState({metricsDetailedBase:res.data}); axios.get("/api/experiment/Sample/").then((resS)=>{ let arr =resS.data.map((s)=>{ return [s.id,"Dodatki: "+ JSON.stringify(s.supplement)+" Czynnik:"+s.externalFactor] }) this.setState({sampleBase:resS.data, samples:arr}) }).catch(()=>{console.log("Sample failure <DataForm/>")}) }).catch(console.log("Metric failure \n")); axios.get("/api/experiment/Metrics/").then((res)=>{ var arr = []; //wyłuskanie nazw metryk res.data.forEach((obj)=>{arr.push([obj.name,obj.name,obj.unit]);}); this.setState({metricsGeneral:arr}); }).catch(console.log("Metric failure \n")); axios.get("/api/experiment/Product/").then((res)=>{ var arr = []; //wyłuskanie nazw metryk res.data.forEach((obj)=>{arr.push([obj.name, obj.name, obj.category])}) this.setState({prodBase:arr}); }).catch(console.log("Product failure \n")); axios.get("/api/experiment/ExternalFactor/").then(res=>{this.setState({externalFactorBase:res.data})}).catch(()=>{console.log("external factor problem")}) } // /api/experiment/Experiment/ handleChangeName = (event) => { this.setState({name: event.target.value});} handleChangeDesc = (event) => { this.setState({desc: event.target.value});} handleChangePaper = (event) => { this.setState({paper: event.target.value});} handlePrivate = (e) => { this.setState({private:!this.state.private}) } handleChangeMetric = (v)=>{ var arr = [] this.state.metricsDetailedBase.forEach((lv,i,a)=>{ if(v===lv.metric){ let s = this.state.sampleBase.find((samp)=>{return samp.id === lv.sample}) arr.push([lv.id,"(serii: "+lv.numberOfSeries+"; powtórzeń: "+lv.numberOfRepeat+")"," Dodatki: "+ JSON.stringify(s.supplement)+" Czynnik:"+s.externalFactor])}}) this.setState({ metricsDetailed : arr, metricGeneral: v, metricID:"" }) } handleChangeDetailedMetric = (v)=>{ if (v === ""){ this.setState({dialog: null, metric:null, metricID:""}) }else{ var obj = null this.state.metricsDetailedBase.forEach((lv) => {if (v==lv.id){obj = lv}}) //zmiana stanu i dałożenie okienka z właściwościami this.setState({metric: obj, metricID:v}) } } handleAddDM = (e)=>{if (this.state.metricID !=""){ var arr = this.state.metricsDetailedBase; var arr2 = this.state.metrics; var obj; arr.forEach((v,i,a)=>{if( v.id == this.state.metricID) obj = v}) arr2.push(obj) this.setState({metrics:arr2}); } } handleDelDM = (obj)=>{ let pred = (v,i,a)=>{return !(v.id == obj.id && obj.type==v.type)}; var arr2 = this.state.metrics; this.setState({metrics:arr2.filter(pred)}); } handleLoadXLSX = (e)=>{ this.setState({ filename: e.target.files[0].name, loaded:true, file:e.target.files[0]}); } handleSubmitXLSX = (e)=>{ if (this.state.file !=null){ this.setState({new:false}) let token = getCSRFToken() var formData = new FormData(); formData.append("file", this.state.file); formData.append("title", this.state.filename); axios.post('/api/experiment/readXlsx/', formData, { headers: { 'Content-Type': 'multipart/form-data', "X-CSRFTOKEN": token } }) .then((res)=>{alert("Udało się załodować eksperyment "+this.state.name); }) .catch((a)=>{console.log("Something's wrong with file uploading");alert("Nie udało się załodować eksperymentu "+this.state.name); this.setState({new:true})}) this.setState({file:null,filename:"", loaded:false}) } } handleInsert =(e) =>{if (! ( this.state.metrics.length<1 && this.state.name == "" && this.state.desc == "" && this.state.paper == "" && this.state.product == "")){ //pobranie znacznika CSRF z ciasteczka let token = getCSRFToken() //stworzenie odpowiedniego nagłówka zapytania const headers = {"X-CSRFTOKEN": token} //obiekt z danymi do bazy let arr = [] this.state.metrics.forEach((v)=>{arr.push(v.id)}) var userName = {"username":this.state.user} axios.post('/api/experiment/getUserNumber/',userName,{ headers: { 'Content-Type': 'multipart/form-data', "X-CSRFTOKEN": token } }) .then((res)=>{ var exp_head = { "name": this.state.name, "description": this.state.desc, "link": this.state.paper, "numberOfMeasuredProperties": arr.length, "publicView": this.state.private, "author": res.data.user_number, "product": this.state.product, "detailedMetrics": arr } axios.post("/api/experiment/Experiment/",exp_head,{ headers:headers }).then((res1)=>{ alert("Wstawiono"); this.setState({idExp:res1.data.id, exp:res1.data}) }).catch(()=>{console.log("Something's wrong with inserting experiment"); alert("Nie wstawiono")}) }) .catch((a)=>{alert("Nie można pobrać Id użytkownika");}) }else{ alert("Uzupełnij") } } handleChange =(e) =>{ //pobranie znacznika CSRF z ciasteczka let token = getCSRFToken() //stworzenie odpowiedniego nagłówka zapytania const headers = {"X-CSRFTOKEN": token} //obiekt z danymi do bazy let arr = [] this.state.metrics.forEach((v)=>{arr.push(v.id)}) var exp_head = { "name": this.state.name, "description": this.state.desc, "link": this.state.paper, "numberOfMeasuredProperties": arr.length, "publicView": this.state.private, "author": 1, "product": this.state.product, "detailedMetrics": arr, } let put = ()=>{ axios.put("/api/experiment/Experiment/"+this.state.idExp+"/",exp_head,{ headers:headers }).then(()=>{ alert("Zmieniono"); }).catch(()=>{console.log("Something's wrong with changing experiment"); alert("Nie dokonano zmian!")}) } let post = ()=>{ axios.delete("/api/experiment/Experiment/"+this.state.idExp+"/",{ headers:headers }).then(()=>{ axios.post("/api/experiment/Experiment/",exp_head,{ headers:headers }).then((res2)=>{ alert("Dokonano zmiany"); this.setState({idExp:res2.data.id, new:true}) }).catch(()=>{console.log("Something's wrong with inserting experiment"); alert("Usunięto, lecz nie wstawiono")}) }).catch(()=>{console.log("Something's wrong with changing experiment"); alert("Nie dokonano zmian!")}) } let open = ()=>{this.setState({openDialog:true})} let close = ()=>{this.setState({openDialog:false,dialog:undefined})} let dial = <Dialog open={open} onClose={close} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title">{"Czy chcesz zresetować eksperyment?"}</DialogTitle> <DialogContent> <DialogContentText id="alert-dialog-description"> Zmiana metryk w eksperymencie powoduje usunięcie dotychczasowych wyników. Czy jesteś pewien? </DialogContentText> </DialogContent> <DialogActions> <Button onClick={close} color="primary"> Nie </Button> <Button onClick={()=>{post();close()}} color="primary" autoFocus> Tak </Button> </DialogActions> </Dialog> var test = true this.state.exp.detailedMetrics.forEach(v =>{test=test&&arr.includes(v)}) if (test){ put() }else{ this.setState({dialog:dial}) } } handleSubmit = (event) => { if (! ( this.state.metrics.length<1 || this.state.name == "" || this.state.desc || "" && this.state.paper=="" || this.state.product=="")){ //pobranie znacznika CSRF z ciasteczka let token = getCSRFToken() //stworzenie odpowiedniego nagłówka zapytania const headers = {"X-CSRFTOKEN": token} var now = new Date();//Pobranie daty .getMonth() zwraca int<0,11>, zatem trzeba dodać 1 XD var metrics = []; //zmapowanie metryk z bazy na metryki do wygenerowania excela w nieładny sposób this.state.metrics.forEach((obj)=>{ let s = this.state.sampleBase.find((v)=>{return v.id === obj.sample}) let ef = this.state.externalFactorBase.find((v)=>{return v.name === s.externalFactor}) metrics.push( [obj.metric, obj.numberOfSeries, obj.numberOfRepeat, obj.sample,ef.numberOfValues, ef.values.split(','),obj.id]) }) //wyłuskanie wartości id //nagłówek eksperymentu var experiment_data = [this.state.name, this.state.desc,this.state.paper, 1, now.getDate()+"."+(now.getMonth()+1)+"."+now.getFullYear()] //obiekt z żądaniem var req = { experiment_data : experiment_data, metrics : metrics }; //wysłanie żądania do generowania excela axios.post("/api/experiment/geneerateXlsx/",req,{ headers:headers, withCredentials:true, responseType: 'blob'}).then((res)=>{ //sprytna funkcja do pobrania danych wzięta z repozytorium npm download(res.data,experiment_data[0]+"_"+experiment_data[3]+'.xlsx') this.setState({generated:true}); }).catch((e)=>{console.log("Something's wrong with file download"); alert("Problem z wygenerowaniem pliku")}) alert("Generowanie pliku") } else{ alert("Uzupełnij") } } refDM = (inv)=>{ let arr= [] axios.get("/api/experiment/DetailedMetrics/").then((res)=>{ this.setState({metricsDetailedBase:res.data}); let obj = undefined res.data.forEach((lv,i,a)=>{ if(this.state.metricGeneral===lv.metric){ if(lv.id===inv){obj = lv} let s = this.state.sampleBase.find((samp)=>{return samp.id === lv.sample}) arr.push([lv.id,"(serii: "+lv.numberOfSeries+"; powtórzeń: "+lv.numberOfRepeat+")", " Dodatki: "+ JSON.stringify(s.supplement)+" Czynnik:"+s.externalFactor])}}) this.setState({ metricsDetailed : arr, metricObj:obj, metricID:inv }) }).catch(console.log("Metric failure \n")); } addSampl = (s)=>{ this.refresh() } changeProductName = (v)=>{ this.refresh() this.setState({product:v}) } closeWindow =()=>{ this.setState({window:null}) } render(){ return( <div id="dataform"> <Button variant="contained" className="line" type="button" onClick={this.props.closeProc}>X</Button> <InputLabel className="line"> Nazwa eksperymentu*: <Input className="line" type="text" value={this.state.name} onChange={this.handleChangeName} /> </InputLabel> <InputLabel className="line"> Opis eksperymentu *: <TextareaAutosize className="line" type="text" value={this.state.desc} onChange={this.handleChangeDesc} /> </InputLabel> <InputLabel className="line"> URL pracy *: <Input className="line" type="text" value={this.state.paper} onChange={this.handleChangePaper} /> </InputLabel> <InputLabel className="line"> Produkt *: <Select className="line" array={this.state.prodBase} value={this.state.product} onChange={this.changeProductName}/> <span className="line"/> <Accordion> <AccordionSummary> Nowy produkt </AccordionSummary> <AccordionDetails> <ProductForm changeProductName={this.changeProductName} name={undefined} closeProc={()=>{this.setState({productWindow:undefined})}}/> </AccordionDetails> </Accordion> <Accordion> <AccordionSummary> Edytuj produkt </AccordionSummary> <AccordionDetails> <ProductForm changeProductName={this.changeProductName} name={this.state.product} closeProc={()=>{this.setState({productWindow:undefined})}}/> </AccordionDetails> </Accordion> </InputLabel> <InputLabel className="line"> <Checkbox checked={this.state.private} onChange={this.handlePrivate}/> Eksperyment {(this.state.private)?"prywatny":"publiczny"} </InputLabel> <InputLabel className="line"> <span className="line"> <InputLabel className="margin"> Metryka: <Select className="line" onChange={this.handleChangeMetric} array={this.state.metricsGeneral}/> </InputLabel> <InputLabel className="margin"> Metryka szczegółowa: <Select className="line" value={this.state.metricID} onChange={this.handleChangeDetailedMetric} array={this.state.metricsDetailed}/> </InputLabel> <span className="margin" ><Button className="line" variant="contained" type="button" onClick={this.handleAddDM}> Przypisz </Button> </span> </span> </InputLabel> {this.state.dialog} <Accordion className="line"> <AccordionSummary> Nowa metryka szczegółowa </AccordionSummary> <AccordionDetails> <DetailedMetricForm refreshDB={this.refDM} addSampl={this.addSampl} metric={this.state.metricGeneral} /> </AccordionDetails> </Accordion> <Accordion className="line"> <AccordionSummary> Edytuj metrykę szczegółową </AccordionSummary> <AccordionDetails> <DetailedMetricForm metricObj={this.state.metric} refreshDB={this.refDM} addSampl={this.addSampl} metric={this.state.metricGeneral}/> </AccordionDetails> </Accordion> <Accordion className="line"> <AccordionSummary className="line"> Dodane metryki szczegółowe </AccordionSummary> <AccordionDetails className="line"> {this.state.metrics.map((obj,n,a)=>{ return <this.Line obj={obj} onButton={this.handleDelDM}/>})} </AccordionDetails> </Accordion> <ButtonGroup className="line"> <span className="margin"><Button className="line" color="primary" variant="contained" type="button" onClick={this.handleInsert}>Dodaj</Button></span> <span className="margin" hidden={!this.state.new}><Button className="line" variant="contained" type="button" onClick={this.handleSubmit}>Pobierz arkusz eksperymentu</Button></span> <span className="margin" hidden={this.state.idExp == undefined}><Button className="line" variant="contained" type="button" onClick={this.handleChange}>Zmień</Button></span> </ButtonGroup> <div hidden={!this.state.new}><div className="line"> <Input type="file" id="XLSXFileChoose" name="XLSXChoose" accept=".xlsx" onChange ={this.handleLoadXLSX}/> <Button variant="contained" color="primary" className={"visible"+this.state.loaded.toString()} onClick={this.handleSubmitXLSX} type="button" >Załaduj</Button> </div></div> </div> ) //return <Line obj={obj} onButton={this.handleDelDM}></Line>})} } }
JavaScript
class UserManagerController { /** * Construct a new UserManagerController. * * @param {APIInterface} api An APIInterface object. */ constructor(api) { this.api = api; } /** * Create a new user. * * @param {string} username The username of the new user. * @param {boolean} passwordless Enable passwordless login for the user. * * @return {User} The newly created User object. */ async create_user(username, passwordless) { let user = new User(this.api); await user.create(username, passwordless); return user; } /** * Return an array of the users in the LibreSignage instance. */ async get_users() { return (await User.get_all(this.api)); } /** * Modify the groups of a user. * * @param {string} username The name of the User to modify. * @param {string[]} groups An array of group names. */ async save_user(username, groups) { let user = new User(this.api); await user.load(username); user.set_groups(groups); await user.save(); } /** * Remove a user. * * @param {string} username The name of the User to remove. */ async remove_user(username) { let user = new User(this.api); await user.load(username); await user.remove(); } }
JavaScript
class RecognizeCelebritiesCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "RekognitionClient"; const commandName = "RecognizeCelebritiesCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.RecognizeCelebritiesRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.RecognizeCelebritiesResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_json1_1_1.serializeAws_json1_1RecognizeCelebritiesCommand(input, context); } deserialize(output, context) { return Aws_json1_1_1.deserializeAws_json1_1RecognizeCelebritiesCommand(output, context); } }
JavaScript
class ArtistPage { /** * * @param {function} [setupFn] Function to be called when new page is loaded */ constructor ( setupFn ) { this.artistLinks = document.querySelectorAll( '.js-sjma-artist-link' ); this.templateContainer = document.querySelector( '#sjma-artist-outlet' ); this.subPageWrapper = document.querySelector( '#sjma-artist-subpage' ); this.currentTemplate = null; this.setup = setupFn; this.artistLinks.forEach( link => { link.addEventListener( 'click', this.handleArtistLinkClick.bind( this ) ); } ); // If the user arrived on the page with a hash in the URL, attempt to // load the appropriate sub-page; clear the hash if none is found if ( window.location.hash ) { try { var hash = window.location.hash, linkId = hash.replace( '#', 'js-link-' ), templateId = hash.replace( '#', 'js-template-' ), link = document.getElementById( linkId ); this.loadTemplate( templateId ); link.classList.add( ACTIVE_CLASS ); link.setAttribute( 'aria-selected', 'true' ); this.fetchCitation( link.href ); } catch ( e ) { window.history.replaceState(null, null, ' '); } } this.preloadImages(); } preloadImages () { // var subPageImages = document.querySelectorAll( 'template' ).map( template => { // return template.content.querySelectorAll( 'img' ); // } ); var subPageTemplates = document.querySelectorAll( 'template' ); var subPageImages = []; subPageTemplates.forEach( template => { var templateImages = template.content.querySelectorAll( 'img' ); templateImages.forEach( image => { subPageImages.push( image.src ); } ) } ); subPageImages.forEach( image => { var preloadLink = document.createElement( 'link' ); preloadLink.rel = 'preload'; preloadLink.href = image; preloadLink.as = 'image'; document.head.appendChild(preloadLink); } ); } /** * @param {*} event */ handleArtistLinkClick ( event ) { event.preventDefault(); var link = event.target, href = link.href, linkId = link.attributes.id.value, templateId = linkId.replace( 'js-link-', 'js-template-' ), pageId = linkId.replace( 'js-link-', '' ); if ( templateId !== this.currentTemplate ) { this.artistLinks.forEach( link => { link.classList.remove( ACTIVE_CLASS ) link.setAttribute( 'aria-selected', 'false' ); } ); link.classList.toggle( ACTIVE_CLASS ); link.setAttribute( 'aria-selected', 'true' ); this.loadTemplate( templateId ); window.history.replaceState( null, null, '#' + pageId ); this.fetchCitation( href ); setTimeout( () => { if ( this.setup ) { this.setup(); } }, 100 ) } else { this.scrollToSubpage(); } } /** * * @param {*} templateId */ loadTemplate ( templateId ) { var template = document.getElementById( templateId ), clone = template.content.cloneNode( true ); this.subPageWrapper.classList.add( ACTIVE_CLASS ); this.templateContainer.innerHTML = ''; this.templateContainer.appendChild( clone ); this.currentTemplate = templateId; this.scrollToSubpage(); } closeTemplate () { this.subPageWrapper.classList.remove( ACTIVE_CLASS ); this.templateContainer.innerHTML = ''; this.currentTemplate = null; window.history.replaceState(null, null, ' '); } updateHash ( hash ) { console.log( hash ); } scrollToSubpage () { // Using jQuery for animated scroll because Safari doesn't support behavior: smooth setTimeout( () => { var offset = $( '#sjma-artist-subpage' ).offset().top; $( 'html, body' ).animate( { scrollTop: ( offset - 48 ) }, 300, 'swing' ); }, 50 ); } fetchCitation ( href ) { $.ajax( { method: 'GET', url: href } ).done( html => { var citations = $( html ).find( '.cite-this' ); $( '.cite-this' ).each( ( index, citation ) => { citation.replaceWith( citations.get( index ) ); } ); } ) } }
JavaScript
class GUIServiceProvider { constructor(core) { this.core = core; this.contextmenu = new ContextMenu(core); } destroy() { const menu = document.getElementById('osjs-context-menu'); if (menu) { menu.remove(); } this.contextmenu.destroy(); } async init() { const contextmenuApi = { show: (...args) => this.contextmenu.show(...args), hide: (...args) => this.contextmenu.hide(...args) }; this.core.instance('osjs/contextmenu', (...args) => { if (args.length) { return contextmenuApi.show(...args); } return contextmenuApi; }); this.core.$root.addEventListener('contextmenu', (ev) => { if (validContextMenuTarget(ev)) { return; } ev.stopPropagation(); ev.preventDefault(); }); } start() { const callback = ev => { const menu = document.getElementById('osjs-context-menu'); const hit = menu.contains(ev.target); if (!hit && this.contextmenu) { this.contextmenu.hide(); } }; this.core.$root.addEventListener('click', callback, true); this.core.once('destroy', () => { this.core.$root.removeEventListener('click', callback, true); }); this.contextmenu.init(); } }
JavaScript
class UsersMovies extends React.Component { componentDidMount() { const { onLoad, movieList, showPlaceholder } = this.props; onLoad(movieList.isFetching); if (!movieList.isFetching) { movieList.length <= 0 ? showPlaceholder(true) : showPlaceholder(false); } } componentDidUpdate() { const { onLoad, movieList, showPlaceholder } = this.props; onLoad(movieList.isFetching); if (!movieList.isFetching) { movieList.length <= 0 ? showPlaceholder(true) : showPlaceholder(false); } } removeMovie = docId => this.props.dispatch(deleteMovieFromList(docId)); toggleWatched = (docId, isWatched) => { const watched = isWatched ? true : false; this.props.dispatch(setToggleMovie(docId, !watched)); }; render() { const { list } = this.props.movieList; if (list.length <= 0) return null; return ( <PaginateMovieList totalResults={list.length}> {list.map(movie => ( <RemovableMovieItem key={movie.docId} {...movie} onToggleWatched={() => this.toggleWatched(movie.docId, movie.watched) } onMovieRemove={() => this.removeMovie(movie.docId)} /> ))} </PaginateMovieList> ); } } // UsersMovies
JavaScript
class Errorme { constructor(app){ this.app = app; } /** * memberof Errorme# * @param {string} key - The name (key) of error object or the error code inside [ERRORS] object * @param {string} message - An optional parameter for describing the error * @description Returns error object based on the defined errors list * @returns {ErrormeError} * @author Karlen Manaseryan <[email protected]> */ getError(key, message){ let error; error = _getErrorByCode(key); if(!error) error = _getErrorByName(key); if(!error){ let e = new ReferenceError("The error object can't be get for the provided error name/code"); Error.captureStackTrace(e, this.getError); throw e; } error = new ErrormeError(error, this.getError, message); if(showLogs) console.warn("[errorme] Error code: " + error.code + ", Message: " + (error.message || error.defaultMessage)) return error; } /** * memberof Errorme# * @param {string} key - The name (key) of error object or the error code inside [ERRORS] object * @param {string} message - An optional parameter for describing the error * @description Returns http specific error object by the key name or the error code in [ERRORS] varant object * @returns {httpError} * @author Karlen Manaseryan <[email protected]> */ getHttpError(key, message){ return this.getError(key, message).parseTo('http'); } /** * memberof Errorme# * @param {function} app - express middleware app * @description Assign a function to errormeSend property of response object. * The function errormeSend() is the following: errormeSend(error: ErrormeError, data: Object), if error exist then send the appropriate http error, * otherwhise sends success with the provided data * @author Karlen Manaseryan <[email protected]> */ middleware(app){ if(!(app && typeof app.use == 'function')){ let e = Error("App argument should be valid express app"); Error.captureStackTrace(e, this.middleware); throw e; } app.use((req, res, next)=>{ res.errormeSend = (err, data)=>{ if(err && !(err instanceof ErrormeError)){ let e = Error("error argument is not instance of ErrormeError class"); Error.captureStackTrace(e, res.errormeSend); throw e; } if(err){ err = err.parseTo('http'); let response = { error:{ code: err.definedCode, message: err.message }, status: err.code, data: null } res.status(err.code); res.send(JSON.stringify(response)); }else{ let response = { error: null, data: data } res.status(200); res.send(JSON.stringify(response)); } } next(); }); } }
JavaScript
class ErrormeError extends Error{ constructor(error, stack, message){ super(message || error.DEFAULT_MESSAGE); this.name = "Errorme" + error.name; this.code = error.CODE; this.defaultMessage = error.DEFAULT_MESSAGE; this.httpCode = error.HTTP_CODE; Error.captureStackTrace(this, stack); } /** * memberof ErrormeError# * @param {string} lang - The error language in which it is required to parse * @description Parse the provided error into provided type (ex. http) specific object * @returns {httpError} * @author Karlen Manaseryan <[email protected]> */ parseTo(lang){ return _parseErrorTo(this, lang); } }
JavaScript
class WindowsOperatingSystemProfile { /** * Create a WindowsOperatingSystemProfile. * @member {object} [rdpSettings] The RDP settings. * @member {string} [rdpSettings.username] The username for the RDP user. * @member {string} [rdpSettings.password] The password for the RDP user. * @member {date} [rdpSettings.expiryDate] The RDP expiry date(YYYY-MM-DD). */ constructor() { } /** * Defines the metadata of WindowsOperatingSystemProfile * * @returns {object} metadata of WindowsOperatingSystemProfile * */ mapper() { return { required: false, serializedName: 'WindowsOperatingSystemProfile', type: { name: 'Composite', className: 'WindowsOperatingSystemProfile', modelProperties: { rdpSettings: { required: false, serializedName: 'rdpSettings', type: { name: 'Composite', className: 'RdpSettings' } } } } }; } }
JavaScript
class Sanction extends Command { /** * Creates an instance of Sanction * * @param {string} file */ constructor(file) { super(file); } /** * Sanction Crucian * * @param {Message} message */ async run(message) { let reaction = bot.lang.sanctionReaction.random(); message.channel.send(reaction); } }
JavaScript
class Charcoder { /** * Create a number converter. * @param {string} charset - Digits of your numeral system. */ constructor(charset = HEX) { this.charset = charset } /** * Encode a number into your numerals system. * @param {number} number - Number to convert. * @returns {string} - String representing the number. */ encode(number) { if (typeof number !== 'number') { throw new TypeError(`expected type: "number" (got: "${typeof number}")`) } if (isNaN(number)) { throw new TypeError('number is NaN') } const base = this.charset.length const result = [] do { result.push(this.charset[number % base]) number = Math.floor(number / base) } while (number) return result.reverse().join('') } /** * Decode a string into a number. * @param {string} string - String representing a number in your numeral system. * @returns {number} - Number that the string represents. */ decode(string) { if (typeof string !== 'string') { throw new TypeError(`expected type: "string" (got: "${typeof string}")`) } const base = this.charset.length let number = 0 string.split('').forEach(char => { const value = this.charset.indexOf(char) if (value === -1) { throw new TypeError(`character "${char}" not in charset`) } number *= base number += value }) return number } }
JavaScript
class Tw2ParticleDragForce extends Tw2ParticleForce { drag = 0.1; /** * Applies force * @param {Tw2ParticleElement} position - Position * @param {Tw2ParticleElement} velocity - Velocity * @param {Tw2ParticleElement} force - force * @param {Number} [dt] - unused * @param {Number} [mass] - unused */ ApplyForce(position, velocity, force, dt, mass) { force[0] += velocity.buffer[velocity.offset] * -this.drag; force[1] += velocity.buffer[velocity.offset + 1] * -this.drag; force[2] += velocity.buffer[velocity.offset + 2] * -this.drag; } /** * Black definition * @param {*} r * @returns {*[]} */ static black(r) { return [ ["drag", r.float], ]; } }
JavaScript
class Grid extends React.Component { render() { const width = (this.props.cols * 14); var rowsArr = []; var boxClass = ""; for (var i = 0; i < this.props.rows; i++) { for (var j = 0; j < this.props.cols; j++) { let boxId = i + "_" + j; boxClass = this.props.gridFull[i][j] ? "box on" : "box off"; rowsArr.push( <Box boxClass={boxClass} key={boxId} boxId={boxId} row={i} col={j} selectBox={this.props.selectBox} /> ); } } return ( <div className="grid" style={{width: width}}> {rowsArr} </div> ); } }
JavaScript
class Main extends React.Component { // define the state constructor() { super(); this.speed = 100; this.rows = 30; this.cols = 50; this.state = { generation: 0, gridFull: Array(this.rows) .fill() .map(() => Array(this.cols).fill(false)), // every grid element turned off }; } // never update a state directly, make a copy of the array instead // helper function - setState function --> updating a state selectBox = (row, col) => { let gridCopy = arrayClone(this.state.gridFull); gridCopy[row][col] = !gridCopy[row][col]; this.setState({ gridFull: gridCopy, }); }; seed = () => { let gridCopy = arrayClone(this.state.gridFull); for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.cols; j++) { if (Math.floor(Math.random() * 4) === 1) { gridCopy[i][j] = true; } } } this.setState({ gridFull: gridCopy, }); }; playButton = () => { clearInterval(this.intervalId); this.intervalId = setInterval(this.play, this.speed); }; pauseButton = () => { clearInterval(this.intervalId); }; slow = () => { this.speed = 1000; this.playButton(); }; fast = () => { this.speed = 100; this.playButton(); }; // refactor to call a function clear = () => { var grid = Array(this.rows).fill().map(() => Array(this.cols).fill(false)); this.setState({ gridFull: grid, generation: 0 }); } gridSize = (size) => { switch (size) { case "1": this.cols = 25; this.rows = 25; break; case "2": this.cols = 50; this.rows = 35; break; default: this.cols = 70; this.rows = 40; } this.clear(); } // Play Method & Game Logic play = () => { let g = this.state.gridFull; let g2 = arrayClone(this.state.gridFull); // rules from Conway's Game of Life - every element of the grid for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.cols; j++) { // how many neighbors? 8 potential neighbors - decide if it's going to die or live let count = 0; if (i > 0) if (g[i - 1][j]) count++; if (i > 0 && j > 0) if (g[i - 1][j - 1]) count++; if (i > 0 && j < this.cols - 1) if (g[i - 1][j - 1]) count++; if (j < this.cols - 1) if (g[i][j + 1]) count++; if (j > 0) if (g[i][j - 1]) count++; if (i < this.rows - 1) if (g[i + 1][j]) count++; if (i < this.rows - 1 && j > 0) if (g[i + 1][j - 1]) count++; if (i < this.rows - 1 && this.cols - 1) if (g[i + 1][j - 1]) count++; if (g[i][j] && (count < 2 || count > 3)) g2[i][j] = false; if (!g[i][j] && count === 3) g2[i][j] = true; } } this.setState({ gridFull: g2, generation: this.state.generation + 1, }); }; // life cycle hook componentDidMount() { // seeded on the grid this.seed(); // to start the game this.playButton(); } // will be used as props in the Grid component render() { return ( <div> <h1>The Game of Life</h1> <Buttons playButton={this.playButton} pauseButton={this.pauseButton} slow={this.slow} fast={this.fast} clear={this.clear} seed={this.seed} gridSize={this.gridSize} /> <Grid gridFull={this.state.gridFull} rows={this.rows} cols={this.cols} selectBox={this.selectBox} /> <h2>Generations: {this.state.generation}</h2> </div> ); } }
JavaScript
class Puzzle { size; grid; rules; constructor(size) { this.size = size; this.grid = Array.from(Array(this.size)).map(() => Array.from(Array(this.size)).map(() => new Cell())); this.rules = []; } addRules(...rules) { this.rules.push(...rules); } getValues(...indices) { return indices.map((x, y) => this.grid[y][x].value); } setValue(x, y, value) { this.grid[y][x].value = value; } check() { return this.rules.every(rule => { console.log(rule.name, rule.check(puzzle.grid)); return rule.check(puzzle.grid); }); } }