language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class NotificationPayload { constructor ({msgid, title, msg, icon, time, validity, actionid, actiondata, dispbehavior } = {}) { /** * @property {string} msgid - a unqiue id for the notification message. */ this.msgid = msgid /** * @property {string} title - the title to be displayed on a notification. */ this.title = title /** * @property {string} msg - the message in the body of the notification. */ this.msg = msg /** * @property {string} icon - a filepath? for an icon to display in the notification. */ this.icon = icon /** * @property {timestamp} time - the time when to show the notification, format is: <format> */ this.time = time || DEFAULT_DATE_FORMAT /** * @property {timestamp} validity - the time till when the notification is valid. null * if the notification never expires. */ this.validity = validity /** * @property {string} actionid - the id of the action to perform when clicking on this * notification. */ this.actionid = actionid /** * @property {string} actiondata - data to pass to the action handler. */ this.actiondata = actiondata /** * @property {string} disbehavior - the behaviour when displaying, either "<option>" or "<opt>". */ this.dispbehavior = dispbehavior /** * schema - Schema validation, Which is used to validate the payload object strucutre. */ this.schema = Joi.object().keys({ 'msgid': Joi.string().required(), 'title': Joi.string().required(), 'msg': Joi.string().empty(''), 'icon': Joi.string().empty(''), 'time': Joi.string().required(), 'validity': Joi.number(), 'actionid': Joi.number(), 'actiondata': Joi.object().keys({ announcementId: Joi.string().required() }).required(), 'dispbehavior': Joi.string().empty('') }).unknown() } /** * Used to validate the playload strucutre * @return {boolean} If the playload is in valid structure then it will returns the true else false */ validate () { let validation = Joi.validate(this, this.schema, { abortEarly: false }) if (validation.error != null) { let messages = [] _.forEach(validation.error.details, (error, index) => { messages.push({ field: error.path[0], description: error.message }) }) return { error: messages, isValid: false, payload: this } } return { isValid: true, payload: this } } getPayload() { return { "msgid": this.msgid, "title": this.title, "msg": this.msg, "time": this.time, "validity": this.validity, "actionid": this.actionid, "actiondata": this.actiondata, "icon": this.icon, "dispbehavior": this.dispbehavior } } }
JavaScript
class UserController { /** * @description - Creates a new user * @static * * @param {object} request - HTTP Request * @param {object} response- HTTP Response * * @memberof userController * */ static signupUser(req, res) { const password = bcrypt.hashSync(req.body.password.trim(), 10); const { name, email, } = req.body; const user = ` INSERT INTO users ( name, email, password ) VALUES ( '${name}', '${email}', '${password}' ) RETURNING *;`; client.query(user) .then((newUser) => { const token = createToken(newUser.rows[0]); return res.status(201) .json({ data: { user: { id: newUser.rows[0].id, name, email, role: newUser.rows[0].role, }, token, }, message: 'user created successfully', status: 'success', }); }).catch((err) => { res.status(500).send(err); }); } /** * @description - logs in a user * @static * * @param {object} request - HTTP Request * @param {object} response - HTTP Response * * @memberof userController * */ static signinUser(req, res) { const { email, password } = req.body; const findUser = `SELECT * FROM users WHERE email = '${email}'`; client.query(findUser) .then((foundUser) => { if (!foundUser.rows[0]) { return res.status(404) .json({ message: 'user does not exist', status: 'fail', }); } if (!bcrypt.compareSync(password.trim(), foundUser.rows[0].password)) { return res.status(401) .json({ message: 'please try again, password or email is incorrect', status: 'fail', }); } const token = createToken(foundUser.rows[0]); return res.status(200) .json({ data: { user: { id: foundUser.rows[0].id, name: foundUser.rows[0].name, email, role: foundUser.rows[0].role, }, token, }, message: 'user logged in successfully', status: 'success', }); }).catch((err) => { res.status(500).send(err); }); } }
JavaScript
class UploadChunkRange { /** * Create a UploadChunkRange. * @member {string} [startPosition] The start position of the portion of the * file. It's represented by the number of bytes. * @member {string} [endPosition] The end position of the portion of the * file. It's represented by the number of bytes. */ constructor() { } /** * Defines the metadata of UploadChunkRange * * @returns {object} metadata of UploadChunkRange * */ mapper() { return { required: false, serializedName: 'UploadChunkRange', type: { name: 'Composite', className: 'UploadChunkRange', modelProperties: { startPosition: { required: false, serializedName: 'StartPosition', type: { name: 'String' } }, endPosition: { required: false, serializedName: 'EndPosition', type: { name: 'String' } } } } }; } }
JavaScript
class LinkedList { constructor(value) { this.value = value; this.next = null; } }
JavaScript
class Validator { static async mail(req, res, next) { if (!req.body.email || !req.body.message || !req.body.name) { res.status(400).json({ status: res.statusCode, message: 'Please, supply all the required information', }); } return next(); } }
JavaScript
class Sandbox { constructor({ globals = { }, pathPrefix = null, urlPrefix = null, fetch = async (url, type, ctx) => { void ctx; if (!url.startsWith(urlPrefix)) { throw new Error(`URL does not start with the correct prefix`); } const path = pathPrefix + url.slice(urlPrefix.length); switch (type) { case 'code': case 'text': case 'json': return readFile(path, 'utf-8'); case 'arrayBuffer': return readFile(path); default: throw new TypeError; } }, requirePath = Path.resolve(__dirname, '../require.js'), requireCode = FS.readFileSync(requirePath, 'utf-8'), } = { }) { const ctx = VM.createContext({ ...globals, }, { codeGeneration: { strings: false, wasm: false, }, }); const global = this.global = exec('this'); function exec(code, path) { return new VM.Script(code, { filename: path, }).runInContext(ctx, { breakOnSigint: true, }); } function execWith(code, path, closure) { // evaluates and returns only the first expression of `code` code = `(function (${ Object.keys(closure) }) { return ${ code }; });`; return exec(code, path).apply(ctx, Object.values(closure)); } function fetchShim(url) { return { then: _=>_({ arrayBuffer() { return global.Promise.resolve(fetch(url, 'arrayBuffer', global).then( data => new global.ArrayBuffer((data.buffer ? data : Buffer.from(data)).buffer)) ); }, json() { return global.Promise.resolve(fetch(url, 'json', global).then(global.JSON.parse)); }, text() { return global.Promise.resolve(fetch(url, 'text', global).then(_=>_ +'')); }, }), }; } const exports = execWith(requireCode, requirePath, { URL, URLSearchParams, fetch: Object.hasOwnProperty.call(globals, 'fetch') ? /**@type{any}*/(globals).fetch : fetchShim, }); const { defaultGetCallingScript, } = exports._utils; if (pathPrefix == null) { pathPrefix = Path.dirname(defaultGetCallingScript(1)) +'/'; } if (urlPrefix == null) { urlPrefix = 'file://'+ pathPrefix; } exports.config({ callingScriptResolver(offset = 0) { return defaultGetCallingScript(offset + 1); }, async defaultLoader(path) { try { void exec((await fetch(path, 'code', global)), path); } catch (error) { console.warn(`failed to load script ${path}:`, error); throw error; } // browsers would (only) print network or syntax errors }, baseUrl: urlPrefix, }); this.require = exports.require; this.define = exports.define; this.module = exports.module; this.Module = exports.Module; this.config = exports.config; this._utils = exports._utils; } }
JavaScript
class WorkspaceManager extends ArcPreferences { /** * @param {?Number} windowIndex An index of opened renderer window. * By Default it is `0` meaning that `workspace.json` is used. Otherwise * it uses `workspace.{index}.json`. Note, this option is ignored if * `file` or `fileName` is set on the `opts` object. * @param {?Object} opts - Initialization options: * - file - Path to a workspace state file. It overrides other settings and * uses this file as a final store. * - fileName - A name for the state file. By default it's `workspace.json` * - filePath - Path to the state file. By default it's system's * application directory for user profile. */ constructor(windowIndex, opts) { if (!opts) { opts = {}; } if (!opts.fileName) { if (!windowIndex) { opts.fileName = 'workspace.json'; } else { opts.fileName = `workspace.${windowIndex}.json`; } } super(opts); log.info('State file is ', this.settingsFile); /** * Store data debounce timer. * By default it's 500 ms. * @type {Number} */ this.storeDebounce = 500; this._readHandler = this._readHandler.bind(this); this._changeHandler = this._changeHandler.bind(this); } /** * Observers window custom events */ observe() { window.addEventListener('workspace-state-read', this._readHandler); window.addEventListener('workspace-state-store', this._changeHandler); } /** * Removed web event listeners from ythe window object */ unobserve() { window.removeEventListener('workspace-state-read', this._readHandler); window.removeEventListener('workspace-state-store', this._changeHandler); } /** * Generates the default settings. It is used by the parten class when * settings are not avaiolable. * @return {Promise} */ defaultSettings() { return Promise.resolve({ requests: [], selected: 0, environment: 'default' }); } /** * Handler for web `workspace-state-read` custom event. * @param {CustomEvent} e */ _readHandler(e) { if (e.defaultPrevented) { return; } e.preventDefault(); e.stopPropagation(); e.detail.result = this.restore(); } /** * Handler for web `workspace-state-store` custom event. * @param {CustomEvent} e */ _changeHandler(e) { if (e.defaultPrevented) { return; } e.preventDefault(); e.stopPropagation(); if (!e.detail.value) { const message = 'workspace-state-store event has no value'; log.warn(message); console.error(message); return; } this.__settings = e.detail.value; this.storeWorkspace(); } /** * Restores state file. * * @return {Promise} Promise resolved to content of the file. */ restore() { log.info('Restoring workspace data from', this.settingsFile); return this.load() .then((data) => { log.info('Restored workspace data from', this.settingsFile); this.initialized = true; this._processRestoredPayload(data); return data; }) .catch((cause) => { log.info('Unable to restore workspace data', cause); this.initialized = true; return {}; }); } /** * Stores current data to state file. * * This task is async and delayed * * @param {Object} data Store file contents */ storeWorkspace() { if (!this.initialized) { return; } if (this.__storeDebouncer) { return; } this.__storeDebouncer = true; setTimeout(() => { this.__storeDebouncer = false; log.info('Storing workspace data to', this.settingsFile); this.store() .catch((cause) => { log.error('Unable to store workspace data.', this.settingsFile, cause); console.error(cause); }); }, this.storeDebounce); } /** * Updates state of the request entries. * * @param {Object} requests List of ARC requests objects. * @return {Promise} Promise resolved when data is saved. */ updateRequestsSate(requests) { if (!this.initialized) { return; } log.info('Updating workspace request data...'); if (!this.__settings) { this.__settings = {}; } return this._processRequests(requests) .then((data) => { this.__settings.requests = data; this.storeWorkspace(); }); } /** * Updates selected request data. * * @param {Number} selected Selected request */ updateSelected(selected) { if (!this.initialized) { return; } log.info('Updating workspace selection data...'); if (!this.__settings) { this.__settings = {}; } this.__settings.selected = selected; this.storeWorkspace(); } /** * Processes requests payloads and transforms them to string if needed. * * @param {Array<Object>} requests List of ARC requests * @param {?Number} index Index of processed request * @param {?Array} result Result of processing. * @return {Promise} Promise resolved when all requests has been processed. * Resolved promise contains the copy of request objects. */ _processRequests(requests, index, result) { index = index || 0; result = result || []; const item = requests[index]; if (!item) { return Promise.resolve(result); } return PayloadProcessor.payloadToString() .then((request) => { result[index] = request; index++; return this._processRequests(requests, index, result); }); } /** * When restoring data it processes requests payload data. * @param {Object} state */ _processRestoredPayload(state) { if (!state || !state.requests || !state.requests.length) { return; } for (let i = 0, len = state.requests.length; i < len; i++) { if (state.requests[i].multipart) { try { state.requeststs[i].payload = PayloadProcessor.restoreMultipart( state.requests[i].multipart); delete state.requests[i].multipart; } catch (_) {} } else if (state.requests[i].blob) { try { state.requeststs[i].payload = PayloadProcessor._dataURLtoBlob( state.requests[i].blob); delete state.requests[i].blob; } catch (_) {} } } } }
JavaScript
class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } }
JavaScript
class SvelteComponentDev extends SvelteComponent { constructor(options) { if (!options || (!options.target && !options.$$inline)) { throw new Error("'target' is a required option"); } super(); } $destroy() { super.$destroy(); this.$destroy = () => { console.warn('Component was already destroyed'); // eslint-disable-line no-console }; } $capture_state() { } $inject_state() { } }
JavaScript
class RouteItem { /** * Initializes the object and creates a regular expression from the path, using regexparam. * * @param {string} path - Path to the route (must start with '/' or '*') * @param {SvelteComponent|WrappedComponent} component - Svelte component for the route, optionally wrapped */ constructor(path, component) { if (!component || typeof component != "function" && (typeof component != "object" || component._sveltesparouter !== true)) { throw Error("Invalid component object"); } // Path must be a regular or expression, or a string starting with '/' or '*' if (!path || typeof path == "string" && (path.length < 1 || path.charAt(0) != "/" && path.charAt(0) != "*") || typeof path == "object" && !(path instanceof RegExp)) { throw Error("Invalid value for \"path\" argument - strings must start with / or *"); } const { pattern, keys } = regexparam(path); this.path = path; // Check if the component is wrapped and we have conditions if (typeof component == "object" && component._sveltesparouter === true) { this.component = component.component; this.conditions = component.conditions || []; this.userData = component.userData; this.props = component.props || {}; } else { // Convert the component to a function that returns a Promise, to normalize it this.component = () => Promise.resolve(component); this.conditions = []; this.props = {}; } this._pattern = pattern; this._keys = keys; } /** * Checks if `path` matches the current route. * If there's a match, will return the list of parameters from the URL (if any). * In case of no match, the method will return `null`. * * @param {string} path - Path to test * @returns {null|Object.<string, string>} List of paramters from the URL if there's a match, or `null` otherwise. */ match(path) { // If there's a prefix, check if it matches the start of the path. // If not, bail early, else remove it before we run the matching. if (prefix) { if (typeof prefix == "string") { if (path.startsWith(prefix)) { path = path.substr(prefix.length) || "/"; } else { return null; } } else if (prefix instanceof RegExp) { const match = path.match(prefix); if (match && match[0]) { path = path.substr(match[0].length) || "/"; } else { return null; } } } // Check if the pattern matches const matches = this._pattern.exec(path); if (matches === null) { return null; } // If the input was a regular expression, this._keys would be false, so return matches as is if (this._keys === false) { return matches; } const out = {}; let i = 0; while (i < this._keys.length) { // In the match parameters, URL-decode all values try { out[this._keys[i]] = decodeURIComponent(matches[i + 1] || "") || null; } catch(e) { out[this._keys[i]] = null; } i++; } return out; } /** * Dictionary with route details passed to the pre-conditions functions, as well as the `routeLoading`, `routeLoaded` and `conditionsFailed` events * @typedef {Object} RouteDetail * @property {string|RegExp} route - Route matched as defined in the route definition (could be a string or a reguar expression object) * @property {string} location - Location path * @property {string} querystring - Querystring from the hash * @property {object} [userData] - Custom data passed by the user * @property {SvelteComponent} [component] - Svelte component (only in `routeLoaded` events) * @property {string} [name] - Name of the Svelte component (only in `routeLoaded` events) */ /** * Executes all conditions (if any) to control whether the route can be shown. Conditions are executed in the order they are defined, and if a condition fails, the following ones aren't executed. * * @param {RouteDetail} detail - Route detail * @returns {bool} Returns true if all the conditions succeeded */ async checkConditions(detail) { for (let i = 0; i < this.conditions.length; i++) { if (!await this.conditions[i](detail)) { return false; } } return true; } }
JavaScript
class SerializerPluginBase extends PluginEntity { /** * Create a new instance of {SerializerPluginBase}. * * @param args - The arguments. * @constructor * @public */ constructor (...args) { super(...args) this.setType(CONSTS.INTERNALS.TYPE.VALUE) .setScope(CONSTS.INTERNALS.SCOPE.VALUE) } /** * An unimplemented abstract function to serialize an object. * * @throws {NotImplementedError} */ serialize () { throw new NotImplementedError('serialize() is not implemented') } /** * An unimplemented abstract function to unserialize a string or a buffer. * * @throws {NotImplementedError} */ unserialize () { throw new NotImplementedError('unserialize() is not implemented') } }
JavaScript
class GetKeys extends Readable { constructor(options = {}){ options.objectMode = true; super(options); this.riak = options.riak; this.bucket = options.bucket; } _read(){ this.riak.listKeys({ stream: true, bucket: this.bucket }, (err, data) =>{ if(err) { return this.emit('error', err); } if(data.keys) { this.push(JSON.stringify(data.keys)) } if(data.done) { return this.push(null) } }) } }
JavaScript
class Node extends Base { constructor (options) { super({ ...DEFAULT_OPTIONS, ...options }); this.opts.logIdent = `${this.opts.port}::NODE`; this._onCycle = this._onCycle.bind(this); this._onEpoch = this._onEpoch.bind(this); this._onTick = this._onTick.bind(this); this._onIRIHealth = this._onIRIHealth.bind(this); this._removeNeighbor = this._removeNeighbor.bind(this); this._removeNeighbors = this._removeNeighbors.bind(this); this._addNeighbor = this._addNeighbor.bind(this); this._addNeighbors = this._addNeighbors.bind(this); this.connectPeer = this.connectPeer.bind(this); this.reconnectPeers = this.reconnectPeers.bind(this); this.end = this.end.bind(this); this._ready = false; this.sockets = new Map(); this.opts.autoStart && this.start(); } /** * Starts the node server, getting public IP, IRI interface, Peer List and Heart. */ start () { return this._setPublicIP().then(() => { return this._getIRI().then((iri) => { if (!iri) { throw new Error('IRI could not be started'); } return this._getList().then(() =>{ const { cycleInterval, epochInterval, beatInterval, silent } = this.opts; this._createServer(); this.heart = new Heart({ silent, cycleInterval, epochInterval, beatInterval, logIdent: `${this.opts.port}::HEART`, onCycle: this._onCycle, onTick: this._onTick, onEpoch: this._onEpoch, }); this._ready = true; this.opts.onReady(this); this.heart.start(); return this; }).catch((err) => { throw err; }) }).catch((err) => { throw err; }) }); } /** * Ends the node, closing HTTP server and IRI backend. * @returns {Promise.<boolean>} */ end () { this.log('terminating...'); this.heart && this.heart.end(); const closeServer = () => { return new Promise((resolve) => { if (this.server) { this.server.close(); } return this._removeNeighbors(Array.from(this.sockets.keys())).then(() => { this.sockets = new Map(); resolve(true); }); }) }; return closeServer().then(() => { this._ready = false; return this.iri ? this.iri.end() : true; }) } /** * Sets a new peer list and returns a list of loaded peers. * @returns {Promise.<Peer[]>} * @private */ _getList () { const { localNodes, temporary, silent, neighbors, dataPath, isMaster } = this.opts; this.list = new PeerList({ multiPort: localNodes, temporary, silent, dataPath, isMaster, logIdent: `${this.opts.port}::LIST` }); return this.list.load(neighbors.filter((n) => { const tokens = n.split('/'); return !this.isMyself(tokens[0], tokens[1]); })); } /** * Sets and returns an IRI instance * @returns {Promise.<IRI>} * @private */ _getIRI () { const { IRIHostname, IRIPort, silent } = this.opts; return (new IRI({ logIdent: `${this.opts.port}::IRI`, hostname: IRIHostname, port: IRIPort, onHealthCheck: this._onIRIHealth, silent })).start().then((iri) => { this.iri = iri; return iri; }) } /** * Tries to get the public IPs of this node. * @private * @returns {Promise} */ _setPublicIP () { if (this.opts.localNodes) { return Promise.resolve(0); } return new Promise((resolve) => { pip((err, ip) => { if (!err) { this.ipv4 = ip; resolve(0); } }); }) } /** * Creates HTTP server for Nelson * @private */ _createServer () { this.server = new WebSocket.Server({ port: this.opts.port, verifyClient: (info, cb) => { const { req } = info; const deny = () => cb(false, 401); const accept = () => cb(true); this._canConnect(req).then(accept).catch(deny); } }); this.server.on('connection', (ws, req) => { this.log('incoming connection established'.green, req.connection.remoteAddress); const { remoteAddress: address } = req.connection; const { port, TCPPort, UDPPort } = this._getHeaderIdentifiers(req.headers); this.list.add(address, port, TCPPort, UDPPort).then((peer) => { this._bindWebSocket(ws, peer, true); }).catch((e) => { this.log('Error binding/adding'.red, address, port, e); this.sockets.delete(Array.from(this.sockets.keys()).find(p => this.sockets.get(p) === ws)); ws.close(); ws.terminate(); }); }); this.server.on('headers', (headers) => { const myHeaders = this._getHeaders(); Object.keys(myHeaders).forEach((key) => headers.push(`${key}: ${myHeaders[key]}`)); }); this.log('server created...'); } /** * Resolves promise if the client is allowed to connect, otherwise rejection. * @param {object} req * @returns {Promise} * @private */ _canConnect (req) { const { remoteAddress: address } = req.connection; const headers = this._getHeaderIdentifiers(req.headers); const { port, nelsonID, version } = headers || {}; const wrongRequest = !headers; return new Promise((resolve, reject) => { if (wrongRequest || !isSameMajorVersion(version)) { this.log('Wrong request or other Nelson version', address, port, version, nelsonID, req.headers); return reject(); } if (!this.iri || !this.iri.isHealthy) { this.log('IRI down, denying connections meanwhile', address, port, nelsonID); return reject(); } if (this.isMyself(address, port, nelsonID)) { return reject(); } this.list.findByAddress(address, port).then((peers) => { if(peers.length && this.sockets.get(peers[0])) { this.log('Peer already connected', address, port); return reject(); } // Deny too frequent connections from the same peer. if (peers.length && this.isSaturationReached() && peers[0].data.dateLastConnected && getSecondsPassed(peers[0].data.dateLastConnected) < this.opts.epochInterval * 2) { return reject(); } const maxSlots = this.opts.isMaster ? this.opts.incomingMax + this.opts.outgoingMax : this.opts.incomingMax; const topCount = parseInt(Math.sqrt(this.list.all().length) / 2); const topPeers = this.list.getWeighted(300).sort((a, b) => a[1] - b[1]).map(p => p[0]) .slice(0, topCount); let isTop = false; peers.forEach((p) => { if (topPeers.includes(p)) { isTop = true; } }); // The usual way, accept based on personality. const normalPath = () => { if (this._getIncomingSlotsCount() >= maxSlots) { reject(); } // TODO: additional protection measure: make the client solve a computational riddle! this.isAllowed(address, port).then((allowed) => allowed ? resolve() : reject()); }; // Accept old, established nodes. if (isTop && this.list.all().filter(p => p.data.connected).length > topCount) { if (this._getIncomingSlotsCount() >= maxSlots) { this._dropRandomNeighbors(1, true).then(resolve); } else { resolve(); } } // Accept new nodes more easily. else if (!peers.length || getSecondsPassed(peers[0].data.dateCreated) < this.list.getAverageAge() / 2) { if (this._getIncomingSlotsCount() >= maxSlots) { const candidates = Array.from(this.sockets.keys()) .filter(p => getSecondsPassed(p.data.dateCreated) < this.list.getAverageAge()); if (candidates.length) { this._removeNeighbor(candidates.splice(getRandomInt(0, peers.length), 1)[0]).then(resolve); } else { normalPath(); } } else { resolve(); } } else { normalPath(); } }); }); } /** * Binds the websocket to the peer and adds callbacks. * @param {WebSocket} ws * @param {Peer} peer * @param {boolean} asServer * @private */ _bindWebSocket (ws, peer, asServer=false) { const removeNeighbor = (e) => { if (!ws || ws.removingNow) { return; } ws.removingNow = true; this._removeNeighbor(peer).then(() => { this.log('connection closed'.red, this.formatNode(peer.data.hostname, peer.data.port), `(${e})`); }); }; const onConnected = () => { this.log('connection established'.green, this.formatNode(peer.data.hostname, peer.data.port)); this._sendNeighbors(ws); const addWeight = !asServer && getSecondsPassed(peer.data.dateLastConnected) > this.opts.epochInterval * this.opts.epochsBetweenWeight; this.list.markConnected(peer, addWeight) .then(() => this.iri.addNeighbors([ peer ])) .then(() => this.opts.onPeerConnected(peer)); }; let promise = null; ws.isAlive = true; ws.incoming = asServer; this.sockets.set(peer, ws); if (asServer) { onConnected(); } else { ws.on('headers', (headers) => { // Check for valid headers const head = this._getHeaderIdentifiers(headers); if (!head) { this.log('!!', 'wrong headers received', head); return removeNeighbor(); } const { port, nelsonID, TCPPort, UDPPort } = head; this.list.update(peer, { port, nelsonID, TCPPort, UDPPort }).then((peer) => { promise = Promise.resolve(peer); }) }); ws.on('open', onConnected); } ws.on('message', (data) => this._addNeighbors(data, ws.incoming ? 0 : peer.data.weight) ); ws.on('close', () => removeNeighbor('socket closed')); ws.on('error', () => removeNeighbor('remotely dropped')); ws.on('pong', () => { ws.isAlive = true }); } /** * Parses the headers passed between nelson instances * @param {object} headers * @returns {object} * @private */ _getHeaderIdentifiers (headers) { const version = headers['nelson-version']; const port = headers['nelson-port']; const nelsonID = headers['nelson-id']; const TCPPort = headers['nelson-tcp']; const UDPPort = headers['nelson-udp']; if (!version || !port || ! nelsonID || !TCPPort || !UDPPort) { return null; } return { version, port, nelsonID, TCPPort, UDPPort }; } /** * Sends list of neighbors through the given socket. * @param {WebSocket} ws * @private */ _sendNeighbors (ws) { ws.send(JSON.stringify(this.getPeers().map((p) => `${p[0].getHostname()}/${p[1]}`))) } /** * Adds a neighbor to known neighbors list. * @param {string} neighbor * @param {number} weight of the neighbor to assign * @returns {Promise} * @private */ _addNeighbor (neighbor, weight) { // this.log('adding neighbor', neighbor); const tokens = neighbor.split('/'); if (!isFinite(tokens[1]) || !isFinite(tokens[2]) || !isFinite(tokens[3])) { return Promise.resolve(null); } return this.isMyself(tokens[0], tokens[1]) ? Promise.resolve(null) : this.list.add( tokens[0], tokens[1], tokens[2], tokens[3], false, weight * parseFloat(tokens[4] || 0) * this.opts.weightDeflation ); } /** * Parses raw data from peer's response and adds the provided neighbors. * @param {string} data raw from peer's response * @param {number} weight to assign to the parsed neighbors. * @returns {Promise} * @private */ _addNeighbors (data, weight) { // this.log('add neighbors', data); return new Promise((resolve, reject) => { try { Promise.all(JSON.parse(data).slice(0, this.opts.maxShareableNodes).map( (neighbor) => this._addNeighbor(neighbor, weight) )).then(resolve) } catch (e) { reject(e); } }) } /** * Returns Nelson headers for request/response purposes * @returns {Object} * @private */ _getHeaders () { return { 'Content-Type': 'application/json', 'Nelson-Version': getVersion(), 'Nelson-Port': `${this.opts.port}`, 'Nelson-ID': this.heart.personality.publicId, 'Nelson-TCP': this.opts.TCPPort, 'Nelson-UDP': this.opts.UDPPort } } /** * Returns amount of incoming connections * @returns {Number} * @private */ _getIncomingSlotsCount () { const arr = Array.from(this.sockets.values()).filter(ws => ws.readyState < 2); return arr.filter(ws => ws.incoming).length } /** * Returns amount of outgoing connections * @returns {Number} * @private */ _getOutgoingSlotsCount () { const arr = Array.from(this.sockets.values()).filter(ws => ws.readyState < 2); return arr.filter(ws => !ws.incoming).length } /** * Disconnects a peer. * @param {Peer} peer * @returns {Promise<Peer>} * @private */ _removeNeighbor (peer) { if (!this.sockets.get(peer)) { return Promise.resolve([]); } // this.log('removing neighbor', this.formatNode(peer.data.hostname, peer.data.port)); return this._removeNeighbors([ peer ]); } /** * Disconnects several peers. * @param {Peer[]} peers * @returns {Promise<Peer[]>} * @private */ _removeNeighbors (peers) { // this.log('removing neighbors'); const doRemove = () => { peers.forEach((peer) => { const ws = this.sockets.get(peer); if (ws) { ws.close(); ws.terminate(); } this.sockets.delete(peer); this.opts.onPeerRemoved(peer); }); return peers; }; if (!this.iri || !this.iri.isHealthy) { return Promise.resolve(doRemove()); } return this.iri.removeNeighbors(peers).then(doRemove).catch(doRemove); } /** * Randomly removes a given amount of peers from current connections. * @param {number} amount * @returns {Promise.<Peer[]>} removed peers * @private */ _dropRandomNeighbors (amount=1, incomingOnly=false) { const peers = incomingOnly ? Array.from(this.sockets.keys()).filter(p => this.sockets.get(p).incoming) : Array.from(this.sockets.keys()); const selectRandomPeer = () => peers.splice(getRandomInt(0, peers.length), 1)[0]; const toRemove = []; for (let x = 0; x < amount; x++) { toRemove.push(selectRandomPeer()); } return this._removeNeighbors(toRemove); } /** * Connects to a peer, checking if it's online and trying to get its peers. * @param {Peer} peer * @returns {Peer} */ connectPeer (peer) { this.log('connecting peer'.yellow, this.formatNode(peer.data.hostname, peer.data.port)); this.list.update(peer, { dateTried: new Date(), tried: (peer.data.tried || 0) + 1 }); this._bindWebSocket(new WebSocket(`ws://${peer.data.hostname}:${peer.data.port}`, { headers: this._getHeaders(), handshakeTimeout: 5000 }), peer); return peer; } /** * Connects the node to a new set of random addresses that comply with the out/in rules. * Up to a soft maximum. * @returns {Peer[]} List of new connected peers */ reconnectPeers () { // TODO: remove old peers by inverse weight, maybe? Not urgent. Can be added at a later point. // this.log('reconnectPeers'); // If max was reached, do nothing. const toTry = this.opts.outgoingMax - this._getOutgoingSlotsCount(); if (!this.iri || !this.iri.isHealthy || toTry < 1 || this.isMaster || this._getOutgoingSlotsCount() >= this.opts.outgoingMax) { return []; } // Get allowed peers: return this.list.getWeighted(192, this.list.all().filter((p) => !p.data.dateTried || getSecondsPassed(p.data.dateTried) > this.opts.beatInterval * Math.max(2, 2 * p.data.tried || 0))) .filter((p) => !this.sockets.get(p[0])) .slice(0, toTry) .map((p) => this.connectPeer(p[0])); } /** * Returns a set of peers ready to be shared with their respective weight ratios. * @returns {Array[]} */ getPeers () { return this.list.getWeighted(this.opts.maxShareableNodes); } /** * Each epoch, disconnect all peers and reconnect new ones. * @private */ _onEpoch () { this.log('new epoch and new id:', this.heart.personality.id); if (!this.isSaturationReached()) { return Promise.resolve(false); } // Master node should recycle all its connections if (this.opts.isMaster) { return this._removeNeighbors(Array.from(this.sockets.keys())).then(() => { this.reconnectPeers(); return false; }); } return this._dropRandomNeighbors(getRandomInt(0, this._getOutgoingSlotsCount())) .then(() => { this.reconnectPeers(); return false; }) } /** * Checks whether expired peers are still connectable. * If not, disconnect/remove them. * @private */ _onCycle () { this.log('new cycle'); const promises = []; // Remove closed or dead sockets. Otherwise set as not alive and ping: this.sockets.forEach((ws, peer) => { if (ws.readyState > 1 || !ws.isAlive) { promises.push(this._removeNeighbor(peer)); } else { ws.isAlive = false; ws.ping('', false, true); } }); return Promise.all(promises).then(() => false); } /** * Try connecting to more peers. * @returns {Promise} * @private */ _onTick () { terminal.nodes({ nodes: this.list.all(), connected: Array.from(this.sockets.keys()) .filter((p) => this.sockets.get(p).readyState === 1) .map((p) => p.data) }); const maxSlots = this.opts.isMaster ? this.opts.incomingMax + this.opts.outgoingMax : this.opts.incomingMax; // Try connecting more peers. Master nodes do not actively connect (no outgoing connections). if (!this.opts.isMaster && this._getOutgoingSlotsCount() < this.opts.outgoingMax) { return new Promise((resolve) => { this.reconnectPeers(); resolve(false); }) } // If for some reason the maximal nodes were overstepped, drop one. else if (this._getIncomingSlotsCount() > maxSlots) { return this._dropRandomNeighbors(1, true).then(() => false); } else { return Promise.resolve(false); } } /** * Callback for IRI to check for health and neighbors. * If unhealthy, disconnect all. Otherwise, disconnect peers that are not in IRI list any more for any reason. * @param {boolean} healthy * @param {string[]} neighbors * @private */ _onIRIHealth (healthy, neighbors) { if (!healthy) { this.log('IRI gone... closing all Nelson connections'.red); return this._removeNeighbors(Array.from(this.sockets.keys())); } return Promise.all(neighbors.map(getIP)).then((neighbors) => { const toRemove = []; Array.from(this.sockets.keys()) // It might be that the neighbour was just added and not yet included in IRI... .filter(p => getSecondsPassed(p.data.dateLastConnected) > 5) .forEach((peer) => { if (!neighbors.includes(peer.data.hostname) && peer.data.ip && !neighbors.includes(peer.data.ip)) { toRemove.push(peer); } }); if (toRemove.length) { this.log('Disconnecting Nelson nodes that are missing in IRI:'.red, toRemove.map((p) => p.getUDPURI())); return this._removeNeighbors(toRemove); } return([]); }); } /** * Returns whether the provided address/port/id matches this node * @param {string} address * @param {number|string} port * @param {string|null} nelsonID * @returns {boolean} */ isMyself (address, port, nelsonID=null) { const isPrivate = ip.isPrivate(address) || [ '127.0.0.1', 'localhost' ].includes(address); const sameAddress = isPrivate || address === this.ipv4; const samePort = parseInt(port) === this.opts.port; const sameID = this.heart && this.heart.personality && nelsonID === this.heart.personality.publicId; return sameID || (sameAddress && (!this.opts.localNodes || samePort)); } /** * Returns whether certain address can contact this instance. * @param {string} address * @param {number} port * @param {boolean} checkTrust - whether to check for trusted peer * @param {number} easiness - how "easy" it is to get in * @returns {Promise<boolean>} */ isAllowed (address, port, checkTrust=true, easiness=24) { const allowed = () => getPeerIdentifier(`${this.heart.personality.id}:${this.opts.localNodes ? port : address}`) .slice(0, this._getMinEasiness(easiness)) .indexOf(this.heart.personality.feature) >= 0; return checkTrust ? this.list.findByAddress(address, port).then((ps) => ps.filter((p) => p.isTrusted()).length || allowed()) : Promise.resolve(allowed()); } /** * Returns whether the amount of connected nodes has reached a certain threshold. * @returns {boolean} */ isSaturationReached () { const ratioConnected = ( this._getOutgoingSlotsCount() + this._getIncomingSlotsCount()) / (this.opts.outgoingMax + this.opts.incomingMax); return ratioConnected >= 0.75 } /** * For new nodes, make it easy to find nodes and contact them * @param {number} easiness - how easy it is to get in/out * @returns {number} updated easiness value * @private */ _getMinEasiness (easiness) { // New nodes are trusting less the incoming connections. // As the node matures in the community, it becomes more welcoming for inbound requests. const l = this.list.all().filter(p => p.data.connected).length; return Math.min(easiness, Math.max(5, parseInt(l/2))); } }
JavaScript
class MapSelector extends Component { /** *Creates an instance of MapSelector. * @param {*} props * @memberof MapSelector */ constructor(props) { super(props); } /** *This handles the change of the dropdown menu. * * @param {event} e this is the event from the dropdown * @memberof MapSelector */ handleMapChange = (e) => { this.props.dispatch(changeMapDispatch(parseInt(e.target.value))); } /** *This renders the dropdown menu. * * @return {JSX} * @memberof MapSelector */ render() { return ( <div className="is-centered" style={{paddingBottom: '25px'}}> <div style={{paddingBottom: '5px'}}>Karte</div> <div className="select is-small is-dark" style={{marginBottom: '10px'}}> <select id="map_selector" onChange={this.handleMapChange.bind(this)} defaultValue='1'> <option value="0">Kreise (Gebietsstand 2015)</option> <option value="1">Arbeitsmarktregionen (Stand 2012)</option> <option value="2">Arbeitsmarktregionen (Stand 2015)</option> <option value="3">Arbeitsmarktregionen (Stand 2020)</option> <option value="4">Raumordnungsregionen</option> <option value="5">Bundesländer</option> </select> </div> </div> ); } }
JavaScript
class GifToWebp { file bar gifsicleArgs = [] gif2webpArgs = [] constructor(file, barDescription = ``) { if (typeof file === `object`) { this.file = file.absolutePath } else { this.file = file } const description = barDescription || `Processing ${path.basename( this.file )} :add [:bar] :current KB/:total KB :elapsed secs :percent` this.bar = new ProgressBar(description, { // complete: RED, // incomplete: GREEN, // stream: process.stderr, total: 0, width: 30, }) } /** * Selects if metadata should be stripped. * @param metadata boolean Truthy keeps metadata, falsy drops it. */ withMetadata(metadata = true) { const METADATA_ALL = `-metadata all` const METADATA_NONE = `-metadata none` // Don't add duplicate options. if (metadata && !this.gif2webpArgs.includes(METADATA_ALL)) { // Filter options for the opposite. if (this.gif2webpArgs.includes(METADATA_NONE)) { this.gif2webpArgs = this.gif2webpArgs.filter( (elem) => elem !== METADATA_NONE ) } // Add option. this.gif2webpArgs.push(METADATA_ALL) } else if (!metadata && !this.gif2webpArgs.includes(METADATA_NONE)) { // Filter options for the opposite. if (this.gif2webpArgs.includes(METADATA_ALL)) { this.gif2webpArgs = this.gif2webpArgs.filter( (elem) => elem !== METADATA_ALL ) } // Add option. this.gif2webpArgs.push(METADATA_NONE) } } /** * Adds resize options according to given width and height. * @param width int Width to resize to. * @param height int Height to resize to. * @return {boolean} Returns false if neither width nor height are given. */ resize(width, height) { if (!width && !height) return false // First remove options possibly set previously. this.gifsicleArgs = this.gifsicleArgs.filter( (elem) => Array.isArray(elem) && !elem[0].startsWith(`--resize`) ) if (width && !height) { // Add option to resize width respecting aspect ratio. this.gifsicleArgs.push([`--resize-width`, width]) } else if (!width && height) { // Add option to resize height respecting aspect ratio. this.gifsicleArgs.push([`--resize-height`, height]) } else { // Add option to resize to set width & height. this.gifsicleArgs.push([`--resize`, `${width}x${height}`]) } } /** * Returns a base64 encoded string with the first gif frame. * @return {Promise<null|*>} * TODO: add variables for outputType & frames choice to gifFrameOptions */ async toBase64() { let fileToProcess = this.file if (this.gifsicleArgs.length !== 0) { fileToProcess = temp.path({ suffix: '.gif' }) await this.toGif(fileToProcess) } const gifFrameOptions = { url: fileToProcess, frames: 0, cumulative: true, } return gifFrames(gifFrameOptions) } /** * Processes a gif with the given options. * @param outputPath string Path to save the processed gif to. * @return {Promise<void>} */ async toGif(outputPath) { const currentGifsicleArgs = [ `--no-warnings`, `--output`, outputPath, ...this.uniqueArgs(this.gifsicleArgs), this.file, ] this.createProgressWatcher(this.file, outputPath, `to GIF`) return execFile(gifsicle, this.flatten(currentGifsicleArgs), {}) } /** * Converts a gif to webp with the given options, processes gif if need be. * @param outputPath string Path to save the final webp to. * @return {Promise<void>} */ async toWebp(outputPath) { let tempFileName = `` if (this.gifsicleArgs.length !== 0) { tempFileName = temp.path({ suffix: '.gif' }) await this.toGif(tempFileName) } const currentGif2webpArgs = [ ...this.uniqueArgs(this.gif2webpArgs), `-mt`, `-quiet`, tempFileName || this.file, `-o`, outputPath, ] this.createProgressWatcher(tempFileName || this.file, outputPath, `to WebP`) return execFile(gif2webp(), this.flatten(currentGif2webpArgs), {}) } /** * Returns a new array with unique values. * @param arr Array Array to be processed. * @return {*} */ uniqueArgs = (arr) => arr.filter((elem, index, self) => index === self.indexOf(elem)) /** * Returns a new flattened array. * @param arr * @return {*} */ flatten = (arr) => arr.reduce( (acc, val) => Array.isArray(val) ? acc.concat(this.flatten(val)) : acc.concat(val), [] ) /** * Creates a file watcher to update the progress bar. * @param originalFile String Original file to compare to. * @param outputPath String File to watch. * @param addText String Optional string to add to progress bar. * TODO: return watch handler and stop watching after processing... */ createProgressWatcher(originalFile, outputPath, addText = ``) { try { const originalFileStatus = fs.statSync(originalFile) this.bar.total = Math.floor(originalFileStatus.size / 1024) fs.closeSync(fs.openSync(outputPath, 'a')) fs.watch(outputPath, { persistent: false }, (event, filename) => { const currStats = fs.statSync(outputPath) const updateSize = currStats.size / originalFileStatus.size this.bar.update(updateSize, { add: addText }) }) } catch (error) { throw error } } }
JavaScript
class NotAcceptableError extends HttpError { constructor(message) { super(406); this.name = 'NotAcceptableError'; Object.setPrototypeOf(this, NotAcceptableError.prototype); if (message) this.message = message; } }
JavaScript
class PolygonConverter extends LineStringConverter { /** * @inheritDoc */ create(feature, geometry, style, context) { createAndAddPolygon(feature, geometry, style, context); return true; } /** * @inheritDoc */ update(feature, geometry, style, context, primitive) { if (this.isFillBeingAdded(style, context, primitive)) { return false; } return this.updateInternal(feature, geometry, style, context, primitive); } /** * @param {!Feature} feature * @param {!Geometry} geometry * @param {!Style} style * @param {!VectorContext} context * @param {!Cesium.Primitive} primitive * @return {boolean} * @protected */ updateInternal(feature, geometry, style, context, primitive) { if (Array.isArray(primitive)) { for (let i = 0, n = primitive.length; i < n; i++) { if (!this.updateInternal(feature, geometry, style, context, primitive[i])) { return false; } } return true; } if (this.isFillBeingRemoved(style, context, primitive)) { // leave it dirty so it will be removed return true; } return super.update(feature, geometry, style, context, primitive); } /** * @param {!Style} style * @param {!VectorContext} context * @param {!Array<!Cesium.Primitive>|!Cesium.Primitive} primitive * @return {boolean} */ isFillBeingAdded(style, context, primitive) { const styleHasFill = style.getFill() ? getColor(style, context, GeometryInstanceId.GEOM).alpha > 0 : false; const primitiveHasFill = Array.isArray(primitive) ? primitive.some(isPolygonFill) : isPolygonFill(primitive); return styleHasFill && !primitiveHasFill; } /** * @param {!Style} style * @param {!VectorContext} context * @param {!Cesium.Primitive} primitive * @return {boolean} */ isFillBeingRemoved(style, context, primitive) { if (isPolygonFill(primitive)) { return style.getFill() ? getColor(style, context, GeometryInstanceId.GEOM).alpha === 0 : true; } return false; } }
JavaScript
class FerretError extends Error { constructor (name, msg, scope, error) { super(msg) this.name = name || 'FireFerretError' this.msg = msg || '' this.scope = scope || '' if (error) this._error = error } }
JavaScript
class Clan extends Base { constructor(data) { super(); this.patch(data); } patch(data) { // eslint-disable-line if (data.tag) { /** * This clans's tag * @type {string} * @since 3.0.0 */ this.tag = data.tag; } if (data.name) { /** * This clan's name * @type {string} * @since 3.0.0 */ this.name = data.name; } if (data.description) { /** * This clan's description * @type {string} * @since 3.0.0 */ this.description = data.description; } if (data.type) { /** * This clan's type * @type {string} * @since 3.0.0 */ this.type = data.type; } if (data.score) { /** * This clan's score * @type {number} * @since 3.0.0 */ this.score = data.score; } if (data.memberCount) { /** * This clan's member count * @type {number} * @since 3.0.0 */ this.memberCount = data.memberCount; } if (data.requiredScore) { /** * Required score for a player to join this clan * @type {number} * @since 3.0.0 */ this.requiredScore = data.requiredScore; } if (data.donations) { /** * This clan's donation count. * @type {numbeR} * @since 3.0.0 */ this.donations = data.donations; } if (data.clanChest) { this.clanChest = data.clanChest; } if (data.badge) { /** * This clan's badge * @type {URL} * @since 3.0.0 */ this.badge = data.badge.image; } if (data.location) { /** * This clan's location * @type {*} * @since 3.0.0 */ this.location = data.location; } if (data.tracking) { /** * This clan's tracking information * @type {*} * @since 3.0.0 */ this.tracking = data.tracking; } if (data.members) { /** * This clan's members * @type {*[]} * @since 3.0.0 */ this.members = data.members; } } }
JavaScript
class SourceControl extends models['ProxyResource'] { /** * Create a SourceControl. * @member {string} [repoUrl] The repo url of the source control. * @member {string} [branch] The repo branch of the source control. Include * branch as empty string for VsoTfvc. * @member {string} [folderPath] The folder path of the source control. * @member {boolean} [autoSync] The auto sync of the source control. Default * is false. * @member {boolean} [publishRunbook] The auto publish of the source control. * Default is true. * @member {string} [sourceType] The source type. Must be one of VsoGit, * VsoTfvc, GitHub. Possible values include: 'VsoGit', 'VsoTfvc', 'GitHub' * @member {string} [description] The description. * @member {date} [creationTime] The creation time. * @member {date} [lastModifiedTime] The last modified time. */ constructor() { super(); } /** * Defines the metadata of SourceControl * * @returns {object} metadata of SourceControl * */ mapper() { return { required: false, serializedName: 'SourceControl', type: { name: 'Composite', className: 'SourceControl', modelProperties: { id: { required: false, readOnly: true, serializedName: 'id', type: { name: 'String' } }, name: { required: false, readOnly: true, serializedName: 'name', type: { name: 'String' } }, type: { required: false, readOnly: true, serializedName: 'type', type: { name: 'String' } }, repoUrl: { required: false, serializedName: 'properties.repoUrl', type: { name: 'String' } }, branch: { required: false, serializedName: 'properties.branch', type: { name: 'String' } }, folderPath: { required: false, serializedName: 'properties.folderPath', type: { name: 'String' } }, autoSync: { required: false, serializedName: 'properties.autoSync', type: { name: 'Boolean' } }, publishRunbook: { required: false, serializedName: 'properties.publishRunbook', type: { name: 'Boolean' } }, sourceType: { required: false, serializedName: 'properties.sourceType', type: { name: 'String' } }, description: { required: false, serializedName: 'properties.description', type: { name: 'String' } }, creationTime: { required: false, nullable: false, serializedName: 'properties.creationTime', type: { name: 'DateTime' } }, lastModifiedTime: { required: false, nullable: false, serializedName: 'properties.lastModifiedTime', type: { name: 'DateTime' } } } } }; } }
JavaScript
class TextField { constructor( element ) { this.element = element; this.type = ''; if( element.selectionEnd ) this.type = 'input'; // behaves same as textarea if( element.getAttribute('contenteditable') ) this.type = 'contenteditable'; this.rangeCache = null; } // Returns { top, left } relative to window getAbsoluteCaretPosition = () => { // calculate the absolute position const caret = this.type === 'input' ? this._getCaretPositionInput() : this._getCaretPositionCE(); const fontHeight = parseInt( window .getComputedStyle(this.element) .getPropertyValue('font-size') .match(/(.*)px/)[1] ); return { top: caret.top + fontHeight, left: caret.left } } // Modified from https://github.com/component/textarea-caret-position // Licensed under The MIT License (MIT) // Returns { top, left, height } _getCaretPositionInput = () => { const position = this.element.selectionEnd; // We'll copy the properties below into the mirror div. // Note that some browsers, such as Firefox, do not concatenate properties // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), // so we have to list every single property explicitly. const properties = [ 'direction', // RTL support 'boxSizing', 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does 'height', 'overflowX', 'overflowY', // copy the scrollbar for IE 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderStyle', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', // https://developer.mozilla.org/en-US/docs/Web/CSS/font 'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily', 'textAlign', 'textTransform', 'textIndent', 'textDecoration', // might not make a difference, but better be safe 'letterSpacing', 'wordSpacing', 'tabSize', 'MozTabSize' ]; const debug = false; // The mirror div will replicate the textarea's style var div = document.createElement('div'); div.id = 'input-textarea-caret-position-mirror-div'; document.body.appendChild(div); var style = div.style; var computed = window.getComputedStyle ? window.getComputedStyle(this.element) : this.element.currentStyle; // currentStyle for IE < 9 var isInput = this.element.nodeName === 'INPUT'; // Default textarea styles style.whiteSpace = 'pre-wrap'; if (!isInput) style.wordWrap = 'break-word'; // only for textarea-s // Position off-screen style.position = 'absolute'; // required to return coordinates properly if (!debug) style.visibility = 'hidden'; // not 'display: none' because we want rendering // Transfer the element's properties to the div properties.forEach(function (prop) { if (isInput && prop === 'lineHeight') { // Special case for <input>s because text is rendered centered and line height may be != height if (computed.boxSizing === "border-box") { var height = parseInt(computed.height); var outerHeight = parseInt(computed.paddingTop) + parseInt(computed.paddingBottom) + parseInt(computed.borderTopWidth) + parseInt(computed.borderBottomWidth); var targetHeight = outerHeight + parseInt(computed.lineHeight); if (height > targetHeight) { style.lineHeight = height - outerHeight + "px"; } else if (height === targetHeight) { style.lineHeight = computed.lineHeight; } else { style.lineHeight = 0; } } else { style.lineHeight = computed.height; } } else { style[prop] = computed[prop]; } }); style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' div.textContent = this.element.value.substring(0, position); // The second special handling for input type="text" vs textarea: // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 if (isInput) div.textContent = div.textContent.replace(/\s/g, '\u00a0'); var span = document.createElement('span'); // Wrapping must be replicated *exactly*, including when a long word gets // onto the next line, with whitespace at the end of the line before (#7). // The *only* reliable way to do that is to copy the *entire* rest of the // textarea's content into the <span> created at the caret position. // For inputs, just '.' would be enough, but no need to bother. span.textContent = this.element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all div.appendChild(span); const parentRect = this.element.getClientRects()[0]; var coordinates = { top: span.offsetTop + parseInt(computed['borderTopWidth']) + parentRect.top - this.element.scrollTop, left: span.offsetLeft + parseInt(computed['borderLeftWidth']) + parentRect.left - this.element.scrollLeft // height: parseInt(computed['lineHeight']) }; if (debug) { span.style.backgroundColor = '#aaa'; } else { document.body.removeChild(div); } return coordinates; } // Returns { top, left } _getCaretPositionCE = () => { this._cacheRange(); let top = 0, left = 0; if (typeof window.getSelection !== "undefined") { const sel = window.getSelection(); if (sel.rangeCount !== 0) { const range = sel.getRangeAt(0).cloneRange(); range.collapse(true); const rect = range.getClientRects()[0]; if (rect) { top = rect.top; left = rect.left; } } } return { top, left }; } // for contenteditables, remember the cursor position when the position // request is made in case an insertion is made _cacheRange = () => { if( this.type === 'input' ) return; let sel = window.getSelection(); this.rangeCache = sel.getRangeAt && sel.rangeCount ? sel.getRangeAt(0) : null; } /*=== Inserting values ===*/ // Inserts the text, overwriting the previous "padding" count of letters. // Used, for example, to overwrite ":thumb" with the thumbs up emoji insert = (text, padding) => { switch( this.type ) { case 'input': this._insertInput( text, padding ); break; case 'contenteditable': this._insertCE( text, padding ); break; default: console.log("Didn't insert anything", this.type); } } _insertInput = (text, padding) => { let start = this.element.selectionStart; if ( this.element.selectionStart || this.element.selectionStart == '0' ) { const currentText = this.element.value; // The start and end should the the same, as the caret is in a single // position. Adjust the start backwards to accommodate the length of // the text being replaced const start = this.element.selectionStart - (padding + 1); // "+1" to remove the ":" const end = this.element.selectionEnd; this.element.value = currentText.substring(0, start) + text + currentText.substring(end, currentText.length); } // Set the correct focus and range this.element.focus(); this.element.setSelectionRange(start, start); } _insertCE = (text, padding) => { const textNode = document.createTextNode(text); if (this.rangeCache) { this.element.focus(); // create deletion range const range = document.createRange(); range.setStart( this.rangeCache.startContainer, this.rangeCache.startOffset - 1 ); range.setEnd( this.rangeCache.startContainer, this.rangeCache.startOffset + padding ); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); // Delete and insert the text node range.deleteContents(); range.insertNode( textNode ); // create range to set cursor position sel.removeAllRanges(); range.setStart( textNode, 1 ); range.setEnd( textNode, 1 ); sel.addRange(range); } } get value() { if( this.type === 'input' ) return this.element.value; if( this.type === 'contenteditable' ) return this.element.innerHTML; } }
JavaScript
class Line { constructor (color, lineWidth, startX, startY, endX, endY) { this.color = color this.lineWidth = lineWidth this.startX = startX this.startY = startY this.endX = endX this.endY = endY } draw (ctx) { const { color, lineWidth, startX, startY, endX, endY } = this ctx.save() ctx.beginPath() ctx.strokeStyle = color ctx.lineWidth = lineWidth ctx.moveTo(startX, startY) ctx.lineTo(endX, endY) ctx.stroke() ctx.restore() } }
JavaScript
class Spinner { /** * init * @return {Object} The class options */ constructor (options) { this.init(options) this.build() return this } /** * [init description] * @param {?} options [description] * @return {?} [description] */ init (options) { // merge options this.options = Object.assign({}, defaults, options || {}) // define class // assign modules Object.assign(this, insert) } /** * Build function for item * @return {Object} This class instance */ build (options) { this.root = create(this.options.tag) classify(this.root, this.options) if (this.options.type === 'circular') { this.root.innerHTML = this.options.circular } if (this.options.type === 'indeterminate') { this.bar = create('div', 'bar') insert(this.bar, this.root) } else { this.bar = create('div', 'bar') insert(this.bar, this.root) this.set(this.options.progress) } if (this.options.container) { insert(this.root, this.options.container) } return this } set (progress) { this.bar.setAttribute('style', 'width: ' + progress) } }
JavaScript
class KeyboardAwareScrollView extends KeyboardAwareBase { static displayName = 'KeyboardAwareScrollView'; static PropTypes = { getTextInputRefs: PropTypes.func, onScroll: PropTypes.func }; static defaultProps = { ...KeyboardAwareBase.defaultProps, getTextInputRefs: () => { return []; } }; render() { return ( <ScrollView {...this.props} {...this.style} contentInset={{bottom: this.state.keyboardHeight}} ref={r => { this._keyboardAwareView = r; }} onLayout={layoutEvent => { this._onKeyboardAwareViewLayout(layoutEvent.nativeEvent.layout); }} onScroll={event => { this._onKeyboardAwareViewScroll(event.nativeEvent.contentOffset); if (this.props.onScroll) { this.props.onScroll(event); } }} onContentSizeChange={() => { this._updateKeyboardAwareViewContentSize(); }} scrollEventThrottle={200} /> ); } }
JavaScript
class CommandRegistry { constructor() { this.commands = {}; this.timedCommands = {}; } /** * Executes the given command. * * @param {string} name * @param {string} [message] * @param {object} [flags] */ executeCommand(name, message, flags) { message = message || ''; flags = flags || {}; for (let c in this.commands) { if (!this.commands.hasOwnProperty(c) || !this.commands[c].isCommandName(name) || !this.commands[c].canExecuteCommand(flags) || this.commands[c].isOnCooldown() ) { continue; } this.commands[c].execute(message); break; } } /** * Returns the given command if it exists. * * @param {string} name * @return {null|AbstractCommand} */ getCommand(name) { if (!this.commands.hasOwnProperty(name)) { return null; } return this.commands[name]; } /** * Registers a command. * * @param {AbstractCommand} command */ registerCommand(command) { this.commands[command.getCommandName()] = command; } /** * Registers a timed command. * * @param {AbstractCommand} command */ registerTimedCommand(command) { this.timedCommands[command.getCommandName()] = command; setInterval(command.execute.bind(command), command.getCooldown() * 1000); } }
JavaScript
class InsertNodeFromWorkflowCommand extends InsertNodeCommand { execute (params, context) { const workflow = this.config.workflow context.editorSession.getRootComponent().send('startWorkflow', workflow) } }
JavaScript
class SoundResponse { constructor(id, bytes, playbackOptions, profaneWords = [], error = null) { this.id = id; this.bytes = bytes; this.playbackOptions = playbackOptions; this.profaneWords = profaneWords; this.error = error; } success = () => { return this.bytes && this.profaneWords.length === 0 && !this.error; }; profanityMessage = () => { if (!this.profaneWords || this.profaneWords.length === 0) { return null; } return i18n.textToSpeechProfanity({ profanityCount: this.profaneWords.length, profaneWords: this.profaneWords.join(', ') }); }; errorMessage = () => { if (!this.error) { return null; } switch (this.error.status) { case 429: return i18n.azureTtsTooManyRequests(); default: return i18n.azureTtsDefaultError(); } }; }
JavaScript
class AzureTextToSpeech { /** * Instantiate or get class singleton. Using this is recommended to take advantage of caching. */ static getSingleton() { if (!singleton) { singleton = new AzureTextToSpeech(); } return singleton; } constructor() { this.playing = false; this.queue_ = []; this.cachedSounds_ = {}; this.playbackOptions_ = { volume: 1.0, loop: false, forceHTML5: false, allowHTML5Mobile: true, onEnded: this.onSoundComplete_ }; Sounds.getSingleton().onStopAllAudio(this.onAudioEnded_); } /** * * @param {function} soundPromise A thunk that returns a promise, which resolves to a SoundResponse. */ enqueueAndPlay = soundPromise => { this.enqueue_(soundPromise); this.asyncPlayFromQueue_(this.playBytes_); }; /** * A thunk that returns a promise representing a TTS sound that can be enqueued and played. Utilizes a sound cache -- * will check for a cache hit to avoid duplicate network requests, and caches network responses for re-use. * @param {Object} opts * @param {string} opts.text * @param {string} opts.gender * @param {string} opts.locale * @param {string} opts.authenticityToken Rails authenticity token. Optional. * @param {function(string)} opts.onFailure Called with an error message if the sound will not be played. * @returns {function} A thunk that returns a promise, which resolves to a SoundResponse. Example usage: * const soundPromise = createSoundPromise(options); * const soundResponse = await soundPromise(); */ createSoundPromise = opts => () => { const {text, gender, locale, authenticityToken, onFailure} = opts; const id = this.cacheKey_(locale, gender, text); const cachedSound = this.getCachedSound_(locale, gender, text); const wrappedSetCachedSound = soundResponse => { this.setCachedSound_(locale, gender, text, soundResponse); }; const wrappedCreateSoundResponse = this.createSoundResponse_; // If we have the sound already, resolve immediately. if (cachedSound) { const {bytes, profaneWords} = cachedSound; return new Promise(resolve => { if (profaneWords && profaneWords.length > 0) { const soundResponse = wrappedCreateSoundResponse({profaneWords}); onFailure(soundResponse.profanityMessage()); resolve(soundResponse); } else { resolve(wrappedCreateSoundResponse({id, bytes})); } }); } // Otherwise, check the text for profanity and request the TTS sound. return new Promise(async resolve => { try { const profaneWords = await findProfanity( text, locale, authenticityToken ); if (profaneWords && profaneWords.length > 0) { const soundResponse = wrappedCreateSoundResponse({profaneWords}); onFailure(soundResponse.profanityMessage()); wrappedSetCachedSound(soundResponse); resolve(soundResponse); return; } const bytes = await this.convertTextToSpeech( text, gender, locale, authenticityToken ); const soundResponse = wrappedCreateSoundResponse({id, bytes}); wrappedSetCachedSound(soundResponse); resolve(soundResponse); } catch (error) { const soundResponse = wrappedCreateSoundResponse({error}); onFailure(soundResponse.errorMessage()); resolve(soundResponse); } }); }; /** * * @param {string} text * @param {string} gender * @param {string} locale * @param {string} authenticityToken Rails authenticity token. Optional. * @returns {Promise<ArrayBuffer>} A promise that resolves to an ArrayBuffer. */ convertTextToSpeech = (text, gender, locale, authenticityToken = null) => { let request = { url: '/dashboardapi/v1/text_to_speech/azure', method: 'POST', dataType: 'binary', responseType: 'arraybuffer', data: {text, gender, locale} }; if (authenticityToken) { request.headers = {'X-CSRF-Token': authenticityToken}; } return $.ajax(request); }; /** * Plays the next sound in the queue. Automatically ends playback if the SoundResponse was unsuccessful. * @param {function(ArrayBuffer, Object)} play Function that plays sound bytes. * @private */ asyncPlayFromQueue_ = async play => { if (this.playing) { return; } const nextSoundPromise = this.dequeue_(); if (!nextSoundPromise) { return; } this.playing = true; let response = await nextSoundPromise(); if (response.success()) { const {id, bytes, playbackOptions} = response; play(id, bytes.slice(0), playbackOptions); } else { response.playbackOptions.onEnded(); } }; /** * A wrapper for the Sounds.getSingleton().playBytes function to aid in testability. * @param {string} id * @param {ArrayBuffer} bytes * @param {Object} playbackOptions * @private */ playBytes_ = (id, bytes, playbackOptions) => { Sounds.getSingleton().playBytes(id, bytes, playbackOptions); }; /** * Called when a TTS sound is done playing. Set as part of this.playbackOptions_. * @private */ onSoundComplete_ = () => { this.playing = false; this.asyncPlayFromQueue_(this.playBytes_); }; /** * Called when audio has stopped. * @private */ onAudioEnded_ = () => { this.playing = false; this.clearQueue_(); }; /** * Generates the cache key, which is an MD5 hash of the composite key (locale-gender-text). * We hash the composite key to avoid extra-long cache keys (as the text is part of the key). * @param {string} locale * @param {string} gender * @param {string} text * @returns {string} MD5 hash string * @private */ cacheKey_ = (locale, gender, text) => { return hashString([locale, gender, text].join('-')); }; /** * Returns the cached SoundResponse if it exists. * @param {string} locale * @param {string} gender * @param {string} text * @returns {SoundResponse|undefined} * @private */ getCachedSound_ = (locale, gender, text) => { const key = this.cacheKey_(locale, gender, text); return this.cachedSounds_[key]; }; /** * Adds the given SoundResponse to the cache. * @param {string} locale * @param {string} gender * @param {string} text * @param {SoundResponse} SoundResponse * @private */ setCachedSound_ = (locale, gender, text, soundResponse) => { const key = this.cacheKey_(locale, gender, text); this.cachedSounds_[key] = soundResponse; }; /** * Add to the end of the queue. * @param {function} promise A thunk that returns a promise, which resolves to a SoundResponse. * @private */ enqueue_ = promise => { this.queue_.push(promise); }; /** * Get the next item in the queue. * @returns {function} A thunk that returns a promise, which resolves to a SoundResponse. * @private */ dequeue_ = () => { return this.queue_.shift(); }; /** * Clears the queue. * @private */ clearQueue_ = () => { this.queue_ = []; }; /** * Wrapper for creating a new SoundResponse. * @param {Object} opts * @param {string} opts.id * @param {ArrayBuffer} opts.bytes Bytes representing the sound to be played. * @param {Array<string>} opts.profaneWords Profanity present in requested TTS text. * @param {Error} opts.error Any error during the TTS request. * @returns {SoundResponse} * @private */ createSoundResponse_ = opts => { return new SoundResponse( opts.id, opts.bytes, this.playbackOptions_, opts.profaneWords, opts.error ); }; }
JavaScript
class App extends React.Component { //state: lets us store information within a component that's going to change constructor(props) { super(props); //always needed for constructors in React component this.state = { //sets the state, must be an object in React, can only be done once with an = sign numberofExclamationPoints: 1, }; } buttonClicked = () => { console.log('button clicked'); // this.state.numberofExclamationPoints++ doesn't work. React treats states specially. this.setState({ numberofExclamationPoints: this.state.numberofExclamationPoints + 1 }); } render() { let exclamationPoints = ''; for (let i = 0; i < this.state.numberofExclamationPoints; i++) { exclamationPoints += '!'; } return ( <div> <header> <Header /> <h2>Get excited! {this.state.numberofExclamationPoints} {exclamationPoints}</h2> <button onClick={this.buttonClicked}>Get more excited!</button> <Button variant='light'>Bootstrap capital B Button</Button> </header> <main> <Main /> </main> <footer> <Footer /> </footer> </div> ); } }
JavaScript
class CaptIntf { //////// // §2.2.1: Constructor // @todo Incorporate use of gulp and versioner module above to automatically insert current // in text strings. Currently planning it to take the form @since »current« /** * Construct an interface for collecting screenshots. * @constructs CaptIntf * @param {readline.Interface} intf - Instance of readline.Interface. * @since 0.0.0 */ constructor( intf ) { // Private properties let initialized = false; let inst = this; // Public properties this.intf = intf; this.lastLine = undefined; this.nextStep = 0; this.inpErr = false; this.validFnPrefixFound = false; this.msgs = { // @todo Incorporate use of versioner above. welcome: "\nWebsiteMapper 0.0.0, by Daniel C. Rieck | Screen Capture Mode\nEnter " + "'exit' to quit. Default option is indicated by a '†', freeform input by a '*'.\n" + "--------------------------------------------------------------------------------" + "-----", // @todo Update the fatal error message with instructions for contacting author. fatalErr: "\nBecause a fatal error was encountered, the process will now close." + " Thank you for trying to use WsMapper. Goodbye!\n", exit: "\nSure, this process will now exit. Thank you for using WsMapper. Goodbye!\n", captTypeInpErr: "\nYour input of '%s' does not match one of the available capture" + " modes. Please try again.", urlInpErr: "\nYour input of '%s' is not a properly encoded URL string in a format I" + " recognize. Please try again.", captBasisErr: "\nI could not interpret your input of '%s' into a valid selector" + " string for an element to serve as the basis for screen capture. Please try again.", vwNaN: "\nYour input of '%s' is not a number. Please try entering a width again.", vwOoB: "\nThe viewport width of '%s' pixels you entered is out of bounds. Please" + " enter a different width.", invalFnPrefChars: "\nI found invalid characters in the file name prefix you entered." + " Please enter a different prefix.", invalFnPrefFromSUrl: "\nUnfortunately, after I converted the URL into a file name" + " prefix, I found invalid characters in the result0. Please manually enter a" + " prefix.", denseFnPrefEntry: "Sorry friend; like I said earlier, the URL is not going to work." + " C'est la vie! Please manually enter a prefix.", endOfDevReached: "You have reached the current endpoint to which WsMapper has been" + " developed. Thank you for trying it out; good bye!" }; this.multiUrls = false; this.prompts = { captType: "\nWhat type of capture do you want to perform?\n(†s/ingle|m/ultiple)\n> ", url: "\nEnter the URL of the website you want to capture\n(http://*|https://*)\n> ", urls: "\nEnter the URLs of the website you want to capture. Use a comma (, ) " + "separated list.\n(e.g., https://*, https://*, https://*)\n> ", viewportW: "\nEnter the width of the viewport in pixels.\n(†1188|*)\n> ", captBasisElem: "\nEnter the selector string for the element that will serve as the " + "basis for screen capture.\n(†body|*) (e.g., 'main', '#wsuwp-main', " + "'.main-column', etc.])\n> ", fnPrefix: "\nEnter a file name prefix for storing screen captures:\n(†u/se url|*)\n> ", }; this.execSteps = { displayWelcome: 1, inpCaptType: 2, chkCaptType: 3, inpUrl: 4, inpUrls: 5, chkUrls: 6, inpViewportW: 7, chkViewportW: 8, inpCaptBasisElem: 9, chkCaptBasisElem: 10, inpFnPrefix: 11, chkFnPrefix: 12, confirmSettings: 13, procUrls: 14, finished: 15, endOfDevReached: 16 }; this.modeStrStart = "OPERATING MODE SELECTIONS:\n"; this.modeStr = this.modeStrStart; this.consoleDim = { rows: process.stdout.rows, cols: process.stdout.columns } // Protected function declarations this.isInitialized = function() { return initialized; } this.begin = function() { initialized = true; inst.execNextStep(); } // Event bindings this.intf.on( 'line', async ( line ) => { inst.lastLine = line; inst.execNextStep(); } ).on( 'close', async () => { process.exit( 0 ); } ); } //////// // §2.2.3: Public methods /** * Prompt user for the element that will serve as the basis for capture. * @since 0.0.0 */ askForCaptBasisElem() { this.checkSelf( "askForCaptBasisElem" ); this.nextStep = this.execSteps.chkCaptBasisElem; this.prompt( this.prompts.captBasisElem ); } /** * Prompt user for the capture type. * @since 0.0.0 */ askForCaptType() { this.checkSelf( "askForCaptType" ); this.nextStep = this.execSteps.chkCaptType; this.prompt( this.prompts.captType ); } /** * Prompt user for the file name prefix that will be used to store the screen capture. * @since 0.0.0 */ askForFnPrefix() { this.checkSelf( "askForFnPrefix" ); this.nextStep = this.execSteps.chkFnPrefix; this.prompt( this.prompts.fnPrefix ); } /** * Prompt user for a single URL to the web page that will be screen captured. * @since 0.0.0 */ askForUrl() { this.checkSelf( "askForUrl" ); this.nextStep = this.execSteps.chkUrls; this.prompt( this.prompts.url ); } /** * Prompt user for multiple URLs to the collection web pages that will be screen captured. * @since 0.0.0 */ askForUrls() { this.checkSelf( "askForUrls" ); this.nextStep = this.execSteps.chkUrls; this.prompt( this.prompts.urls ); } /** * Prompt the user for the width of the viewport. * @since 0.0.0 */ askForViewportW() { this.checkSelf( "askForViewportW" ); this.nextStep = this.execSteps.chkViewportW; this.prompt( this.prompts.viewportW ); } /** * Calculate the number of rows that the console output occupies, including the latest error * message if applicable. * @since 0.0.0 */ calcRowsForMsgs() { let totRows = 0; if ( this.inpErr ) { totRows += (this.lastErr.match(/\n/g) || []).length + 1; } totRows += (this.curPrompt.match(/\n/g) || []).length + 1; return totRows; } /** * Ensure that the user properly entered either the body tag, an element ID, or a class-based * element selector for isolating the DOM element that will serve as the basis for the screen * capture. * @since 0.0.0 */ checkCaptBasisElem() { this.checkSelf( "checkCaptBasisElem" ); const selNeedle = "^(body|#[-_a-zA-Z]|#[-_a-zA-Z][^-0-9][-_a-zA-Z0-9]*|\\.[-_a-zA-Z]|\\.[" + "-_a-zA-Z][^-0-9][-_a-zA-Z0-9]*)$"; const reSearch = new RegExp( selNeedle ); const match = reSearch.exec( this.lastLine ); let validCaptBasisFound = false; if ( match != null ) { validCaptBasisFound = true; this.captBasisSel = this.lastLine; if ( this.captBasisSel == 'body' ) { this.captBasisType = 'body'; } else if ( this.captBasisSel.charAt( 0 ) == '#' ) { this.captBasisType = 'id'; } else if ( this.captBasisSel.charAt( 0 ) == '.' ) { this.captBasisType = 'class'; } } else if ( this.lastLine == "" ) { validCaptBasisFound = true; this.captBasisSel = 'body'; this.captBasisType = 'body'; } if ( validCaptBasisFound ) { this.nextStep = this.execSteps.inpViewportW; this.reprintOpModeSels( "Capture Basis Selector = " + this.captBasisSel ); } else { this.reportInpErr( this.msgs.captBasisErr ); this.nextStep = this.execSteps.inpCaptBasisElem; } this.execNextStep(); } /** * Ensure that the user properly indicated either a single- or multiple-url capture type. * @since 0.0.0 */ checkCaptType() { this.checkSelf( "checkCaptType" ); if ( this.lastLine == "" || this.lastLine == "s" || this.lastLine == "single" ) { this.nextStep = this.execSteps.inpUrl; this.reprintOpModeSels( "Capture mode = Single" ); } else if ( this.lastLine == "m" || this.lastLine == "multiple" ) { this.multiUrls = true; this.nextStep = this.execSteps.inpUrls; this.reprintOpModeSels( "Capture mode = Multiple" ); } else { this.reportInpErr( this.msgs.captTypeInpErr ); this.nextStep = this.execSteps.inpCaptType; } this.execNextStep(); } /** * Check the user's latest input for the exit command. * @since 0.0.0 */ checkForExitStr() { this.checkSelf( "checkForExitStr" ); if ( this.lastLine == "exit" ) { this.closeInterface( this.msgs.exit ); } } /** * Check the validity the file name prefix entered by the user. * @todo Finish writing function. * @since 0.0.0 */ checkFnPrefix() { this.checkSelf( "checkFnPrefix" ); let validUrlsFound = false; // @todo Handle the case where the user wants the url to be interpreted as the file name // prefix. if ( this.lastLine == "" || this.lastLine == "u" || this.lastLine == "use url" ) { this.lastLine = "url"; } // Check for the presence characters that are invalid for file path names in Windows OS. const invalFnPrefNeedle = "^[^\\/:*?\"<>|]+$"; const reSearch = new RegExp( invalFnPrefNeedle ); const match = reSearch.exec( this.lastLine ); if ( match !== null ) { this.validFnPrefixFound = true; this.fnPrefix = [ this.lastLine ]; this.nextStep = this.execSteps.endOfDevReached; } else { this.reportInpErr( this.msgs.invalFnPrefChars ); this.nextStep = this.execSteps.inpFnPrefix; } this.execNextStep(); } /** * Ensure that this instance of CaptIntf was properly initialized. * @throws {Error} Will throw an error if the instance was not initialized via the method * isInitalized. * @since 0.0.0 */ checkSelf( funcThatChecked ) { if ( !this.isInitialized() ) { throw new Error( "An instance of WsMapper.CaptIntf attempted to execute method " + "'" + funcThatChecked +"' without being initialized via the 'begin' method." ); } } /** * Check that the viewport width input by the user is a number that falls within acceptable * bounds. * @since 0.0.0 */ checkViewportW() { this.checkSelf( "checkViewportW" ); this.viewportW = this.lastLine == "" ? 1188 : Number( this.lastLine ); const vwInpIsNum = this.viewportW !== NaN; const vwInpInBounds = vwInpIsNum && ( this.viewportW >= 320 && this.viewportW <= 3840 ); if ( !vwInpIsNum ) { this.reportInpErr( this.msgs.vwNaN ); this.nextStep = this.execSteps.inpViewportW; } else if ( !vwInpInBounds ) { this.reportInpErr( this.msgs.vwOoB ); this.nextStep = this.execSteps.inpViewportW; } else { this.nextStep = this.execSteps.inpFnPrefix; this.reprintOpModeSels( "Viewport Width = " + this.viewportW + "px" ); } this.execNextStep(); } /** * Check the validity of the URL(s) the user entered for the web page(s) that will be screen * captured. * @todo Finish writing multiple URL sequence. * @since 0.0.0 */ checkUrls() { this.checkSelf( "checkUrls" ); let validUrlsFound = false; if ( this.multiUrls == true ) { // TODO: Finish implementation of multiple URL inputs this.closeInterface( "\nMultiple URL queries not yet implented; exiting now. Thank " + "you for using WsMapper. Goodbye!" ); } else { const urlNeedle = "^https?:\/\/(([a-zA-Z0-9]|%[A-F0-9]{2})+\.)+([a-zA-Z0-9]|%[A-F0-9]" + "{2})+(\/([a-zA-Z0-9_~-]|%[A-F0-9]{2})+)*(\/|([a-zA-Z0-9_~-]|%[A-F0-9]{2})+\.([a-" + "zA-Z0-9_~-]|%[A-F0-9]{2})+)?$"; const reSearch = new RegExp( urlNeedle ); const match = reSearch.exec( this.lastLine ); if ( match !== null ) { validUrlsFound = true; this.urls = [ this.lastLine ]; } else { this.reportInpErr( this.msgs.urlInpErr ); } } if ( validUrlsFound ) { this.nextStep = this.execSteps.inpCaptBasisElem; this.reprintOpModeSels( "URLs = " + this.lastLine ); } else { this.nextStep = this.multiUrls ? this.execSteps.inpUrls : this.execSteps.inpUrl; } this.execNextStep(); } /** * Close the interface because the user has finished capturing screenshots of websites. * @since 0.0.0 */ closeInterface( msg ) { if ( msg === undefined || typeof msg !== 'string' ) { console.log( "Typeof 'msg' is %s.", typeof msg ); msg = this.msgs.exit; } console.log( msg ); this.intf.close(); } /** * Display the welcome message to the user. * @since 0.0.0 */ dispWelcomeMsg() { this.checkSelf( "dispWelcomeMsg" ); console.log( this.msgs.welcome ); this.nextStep = this.execSteps.inpCaptType; this.execNextStep(); } /** * Execute the next step in the sequence of operations involved in performing one or more screen * captures as instructed by the user. * Needs to be asynchronous because of the web browser-mediated processes that occur after * settings are prompted from the user. * @since 0.0.0 */ async execNextStep() { try { let steps = this.execSteps; this.checkSelf( "execNextStep" ); this.checkForExitStr(); switch( this.nextStep ) { case steps.displayWelcome: this.dispWelcomeMsg(); break; case steps.inpCaptType: this.askForCaptType(); break; case steps.chkCaptType: this.checkCaptType(); break; case steps.endOfDevReached: this.handleEndOfDevReached(); break; case steps.inpUrl: this.askForUrl(); break; case steps.inpUrls: this.askForUrls(); break; case steps.chkUrls: this.checkUrls(); break; case steps.inpCaptBasisElem: this.askForCaptBasisElem(); break; case steps.chkCaptBasisElem: this.checkCaptBasisElem(); break; case steps.inpViewportW: this.askForViewportW(); break; case steps.chkViewportW: this.checkViewportW(); break; case steps.inpFnPrefix: this.askForFnPrefix(); break; case steps.chkFnPrefix: this.checkFnPrefix(); break; case steps.procUrls: this.procUrls(); break; case steps.finished: this.closeInterface(); break; default: this.openInterface(); } } catch ( err ) { console.log( "Fatal error: " + err.message ); this.closeInterface( this.msgs.fatalErr ); } } /** * Handle the case where a user/tester has reached the current end point in the development of * WsMapper. * @since 0.0.0 */ handleEndOfDevReached() { this.checkSelf( "handleEndOfDevReached" ); this.closeInterface( this.msgs.endOfDevReached ); } /** * Open the screen capture interface represented by this instance and begin interacting with the * user. * @since 0.0.0 */ openInterface() { this.checkSelf( "openInterface" ); this.nextStep = this.execSteps.displayWelcome; this.execNextStep(); } /** * Prompt the user for input with the specified message. * @since 0.0.0 */ prompt( msg ) { this.checkSelf( 'prompt' ); this.curPrompt = msg; this.intf.setPrompt( msg ); this.intf.prompt(); } /** * Report an input error to the user. * @since 0.0.0 */ reportInpErr( msg ) { readline.moveCursor( process.stdout, 0, -1 * this.calcRowsForMsgs() ); readline.clearScreenDown( process.stdout ); this.inpErr = true; this.lastErr = msg; console.log( msg, this.lastLine ); } /** * Reprint the settings that have been collected from the user that will determine how the * screen capture is performed. * @since 0.0.0 */ reprintOpModeSels( latestSel ) { let totRows = 0; totRows += this.calcRowsForMsgs(); if ( this.modeStr != this.modeStrStart ) { totRows += (this.modeStr.match(/\n/g) || []).length + 1; latestSel = " | " + latestSel; } readline.moveCursor( process.stdout, 0, -1 * totRows ); readline.clearScreenDown( process.stdout ); this.inpErr = false; this.modeStr += latestSel; console.log( "\x1b[36m" + this.modeStr + "\x1b[0m" ); } }
JavaScript
class RedisManager { /** * API reference. * * @type {null} */ api = null /** * Hash with all instantiate clients. * * @type {{}} */ clients = {} /** * Callbacks. * * @type {{}} */ clusterCallbacks = {} /** * Cluster callback timeouts. * * @type {{}} */ clusterCallbackTimeouts = {} /** * Subscription handlers. * * @type {{}} */ subscriptionHandlers = {} /** * Redis manager status. * * @type {{subscribed: boolean}} */ status = { subscribed: false } /** * Constructor. * * @param api API reference. */ constructor (api) { // save api reference object this.api = api // subscription handlers this.subscriptionHandlers[ 'do' ] = message => { if (!message.connectionId || (this.api.connections.connections[ message.connectionId ])) { let cmdParts = message.method.split('.') let cmd = cmdParts.shift() if (cmd !== 'api') { throw new Error('cannot operate on a outside of the api object') } let method = this.api.utils.stringToHash(api, cmdParts.join('.')) let callback = () => { let responseArgs = Array.apply(null, arguments).sort() process.nextTick(() => { this.respondCluster(message.requestId, responseArgs) }) } let args = message.args if (args === null) { args = [] } if (!Array.isArray(args)) { args = [ args ] } args.push(callback) if (method) { method.apply(null, args) } else { this.api.log(`RP method '${cmdParts.join('.')}' not found`, 'warning') } } } this.subscriptionHandlers[ 'doResponse' ] = message => { if (this.clusterCallbacks[ message.requestId ]) { clearTimeout(this.clusterCallbackTimeouts[ message.requestId ]) this.clusterCallbacks[ message.requestId ].apply(null, message.response) delete this.clusterCallbacks[ message.requestId ] delete this.clusterCallbackTimeouts[ message.requestId ] } } } initialize (callback) { let jobs = [] // array with the queues to create let queuesToCreate = [ 'client', 'subscriber', 'tasks' ] queuesToCreate.forEach(r => { jobs.push(done => { if (this.api.config.redis[ r ].buildNew === true) { // get arguments var args = this.api.config.redis[ r ].args // create a new instance this.clients[ r ] = new this.api.config.redis[ r ].constructor(args) // on error event this.clients[ r ].on('error', error => { this.api.log(`Redis connection ${r} error`, error) }) // on connect event this.clients[ r ].on('connect', () => { this.api.log(`Redis connection ${r} connected`, 'info') done() }) } else { this.clients[ r ] = this.api.config.redis[ r ].constructor(this.api.config.redis[ r ].args) this.clients[ r ].on('error', error => { this.api.log(`Redis connection ${r} error`, 'error', error) }) this.api.log(`Redis connection ${r} connected`, 'info') done() } }) }) if (!this.status.subscribed) { jobs.push(done => { // ensures that clients subscribe the default channel this.clients.subscriber.subscribe(this.api.config.general.channel) this.status.subscribed = true // on 'message' event execute the handler this.clients.subscriber.on('message', (messageChannel, message) => { // parse the JSON message if exists try { message = JSON.parse(message) } catch (e) { message = {} } if (messageChannel === this.api.config.general.channel && message.serverToken === this.api.config.general.serverToken) { if (this.subscriptionHandlers[ message.messageType ]) { this.subscriptionHandlers[ message.messageType ](message) } } }) // execute the callback done() }) } async.series(jobs, callback) } /** * Publish a payload to the redis server. * * @param payload Payload to be published. */ publish (payload) { // get default Redis channel let channel = this.api.config.general.channel // publish redis message this.clients.client.publish(channel, JSON.stringify(payload)) } // ------------------------------------------------------------------------------------------------------------- [RPC] doCluster (method, args, connectionId) { return new Promise((resolve, reject) => { this._doCluster(method, args, connectionId, (error, res) => { if (error) { return reject(error) } resolve(res) }) }) } _doCluster (method, args, connectionId, callback) { let requestId = uuid.v4() let payload = { messageType: 'do', serverId: this.api.id, serverToken: this.api.config.general.serverToken, requestId: requestId, method: method, connectionId: connectionId, args: args } this.publish(payload) if (typeof callback === 'function') { this.clusterCallbacks[ requestId ] = callback this.clusterCallbackTimeouts[ requestId ] = setTimeout((requestId) => { if (typeof this.clusterCallbacks[ requestId ] === 'function') { this.clusterCallbacks[ requestId ](new Error('RPC Timeout')) } delete this.clusterCallbacks[ requestId ] delete this.clusterCallbackTimeouts[ requestId ] }, this.api.config.general.rpcTimeout, requestId) } } respondCluster (requestId, response) { let payload = { messageType: 'doResponse', serverId: this.api.id, serverToken: this.api.config.general.serverToken, requestId: requestId, response: response // args to pass back, including error } this.publish(payload) } }
JavaScript
class AccessFlags { /** * To create a new AccessFlags * @param {*} pVisibility Visiblity bitmap. Default is PUBLIC (only) * @constructor */ constructor(pVisibility=PUBLIC_FLAG){ this.visibility = pVisibility; this._match = 0; } /** * @field */ set public(pParam){ this.visibility |= PUBLIC_FLAG; if(this.visibility & PRIVATE_FLAG) this.visibility ^= PRIVATE_FLAG; if(this.visibility & PROTECTED_FLAG) this.visibility ^= PROTECTED_FLAG; } get public(){ return (this.visibility & PUBLIC_FLAG)>0; } /** * @field */ set private(pParam){ this.visibility |= PRIVATE_FLAG; if(this.visibility & PUBLIC_FLAG) this.visibility ^= PUBLIC_FLAG; if(this.visibility & PROTECTED_FLAG) this.visibility ^= PROTECTED_FLAG; } get private(){ return (this.visibility & PRIVATE_FLAG)>0; } /** * @field */ set static(pParam){ this.visibility |= STATIC_FLAG; } get static(){ return (this.visibility & STATIC_FLAG)>0; } /** * @field */ set protected(pParam){ this.visibility |= PROTECTED_FLAG; if(this.visibility & PRIVATE_FLAG) this.visibility ^= PRIVATE_FLAG; if(this.visibility & PUBLIC_FLAG) this.visibility ^= PUBLIC_FLAG; } get protected(){ return (this.visibility & PROTECTED_FLAG)>0; } /** * @field */ set final(pParam){ this.visibility |= FINAL_FLAG; } get final(){ return (this.visibility & FINAL_FLAG)>0; } /** * @field */ set construct(pParam){ this.visibility |= CONSTRUCT_FLAG; } get construct(){ return (this.visibility & CONSTRUCT_FLAG)>0; } /** * @field */ set varargs(pParam){ this.visibility |= VARARGS_FLAG; } get varargs(){ return (this.visibility & VARARGS_FLAG)>0; } /** * @field */ set bridge(pParam){ this.visibility |= BRIDGE_FLAG; } get bridge(){ return (this.visibility & BRIDGE_FLAG)>0; } /** * @field */ set native(pParam){ this.visibility |= NATIVE_FLAG; } get native(){ return (this.visibility & NATIVE_FLAG)>0; } /** * @field */ set abstract(pParam){ this.visibility |= ABSTRACT_FLAG; } get abstract(){ return (this.visibility & ABSTRACT_FLAG)>0; } /** * @field */ set interface(pParam){ this.visibility |= INTERFACE_FLAG; } get interface(){ return (this.visibility & INTERFACE_FLAG)>0; } /** * @field */ set strictfp(pParam){ this.visibility |= STRICTFP_FLAG; } get strictfp(){ return (this.visibility & STRICTFP_FLAG)>0; } /** * @field */ set transient(pParam){ this.visibility |= TRANS_FLAG; } get transient(){ return (this.visibility & TRANS_FLAG)>0; } /** * @field */ set declsync(pParam){ this.visibility |= DECLSYNC_FLAG; } get declsync(){ return (this.visibility & DECLSYNC_FLAG)>0; } /** * @field */ set enum(pParam){ this.visibility |= ENUM_FLAG; } get enum(){ return (this.visibility & ENUM_FLAG)>0; } /** * @field */ set volatile(pParam){ this.visibility |= VOLATILE_FLAG; } get volatile(){ return (this.visibility & VOLATILE_FLAG)>0; } /** * @field */ set synchronized(pParam){ this.visibility |= SYNC_FLAG; } get synchronized(){ return (this.visibility & SYNC_FLAG)>0; } /** * @field */ set synthetic(pParam){ this.visibility |= SYNTH_FLAG; } get synthetic(){ return (this.visibility & SYNTH_FLAG)>0; } /** * To transform a set of access flags as a simple object ready to be serialized * * @returns {Object} Simple object containing enabled access flags * @method */ toJsonObject(){ let o = new Object(); o.visibility = this.visibility; if(this.public) o.public = true; if(this.protected) o.protected = true; if(this.private) o.private = true; if(this.native) o.native = true; if(this.transient) o.transient = true; if(this.strictfp) o.strictfp = true; if(this.declsync) o.declsync = true; if(this.construct) o.construct = true; if(this.enum) o.enum = true; if(this.interface) o.interface = true; if(this.abstract) o.abstract = true; if(this.static) o.static = true; if(this.final) o.final = true; if(this.synthetic) o.synthetic = true; if(this.synchronized) o.synchronized = true; if(this.volatile) o.volatile = true; return o; }; /** * To print access flags * * @returns {String} A string which represents access flags * @method */ sprint(){ let dbg="[" if(this.public) dbg += "public,"; if(this.protected) dbg += "protected,"; if(this.private) dbg += "private,"; if(this.transient) dbg += "transient,"; if(this.strictfp) dbg += "strictfp,"; if(this.declsync) dbg += "declsync,"; if(this.construct) dbg += "construct,"; if(this.enum) dbg += "enum,"; if(this.interface) dbg += "interface,"; if(this.abstract) dbg += "abstract,"; if(this.static) dbg += "static,"; if(this.final) dbg += "final,"; if(this.synchronized) dbg += "synchronized,"; if(this.synthetic) dbg += "synthetic,"; if(this.volatile) dbg += "volatile,"; return dbg+"]"; } }
JavaScript
class DefaultInterceptor { intercept(req, next) { return next.handle(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["mergeMap"])((event) => { return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["of"])(event); }), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__["catchError"])((err) => { return Object(rxjs__WEBPACK_IMPORTED_MODULE_1__["of"])(err); })); } }
JavaScript
class PaginationResponseDto { /** * Creates a new instance of a pagination response. * @param results The results of the query * @param total The total amount of items, without the applied pagination options * @param paginationOptions The given pagination options */ constructor(results, total, paginationOptions) { this.offset = paginationOptions.offset; this.results = results; this.total = total; this.limit = paginationOptions.limit; } }
JavaScript
class FormSectionTwo extends FBP(LitElement) { /** * flow is ready lifecycle method * @private */ _FBPReady() { super._FBPReady(); // this._FBPTraceWires(); } static get properties() { return {}; } static get styles() { // language=CSS return [ css` :host { display: block; } :host([hidden]) { display: none; } `, ]; } injectEntity(entity) { this._FBPTriggerWire('--entity', entity); } disable() { this._FBPTriggerWire('--disable', true); } /** * @private * @returns {TemplateResult|TemplateResult} */ render() { // language=HTML return html` <furo-form-layouter> <div> <furo-ui5-data-textarea-input-labeled ƒ-.disabled="--disable" ƒ-bind-data="--entity(*.data.furo_data_textarea_input)" ></furo-ui5-data-textarea-input-labeled> </div> </furo-form-layouter> `; } }
JavaScript
class StrokeStyle { constructor(opts) { this.initializer(opts) } /** * initializes the stroke style object from an options object * @param {StrokeStyleOptions} [opts] * @private */ _initStrokeStyleFromOptions(opts) { if (opts) { if (typeof opts.strokeColor !== "undefined") { this.strokeColor = opts.strokeColor } if (typeof opts.strokeOpacity !== "undefined") { this.strokeOpacity = opts.strokeOpacity } if (typeof opts.strokeWidth !== "undefined") { this.strokeWidth = opts.strokeWidth } if (typeof opts.lineMiter !== "undefined") { this.lineJoin = opts.lineMiter } if (typeof opts.lineCap !== "undefined") { this.lineCap = opts.lineCap } if (typeof opts.dashPattern !== "undefined") { this.dashPattern = opts.dashPattern } if (typeof opts.dashOffset !== "undefined") { this.dashOffset = opts.dashOffset } } } /** * Initializer method to initialize a stroke style. Used for both initializing * via base-class and mixin hierarchy. * @param {StrokeStyleOptions} [opts] * @protected */ initializer(opts) { this._strokeColor = new ColorRGBA("black") this._strokeWidth = 0 this._lineJoin = JoinEnum.MITER this._lineCap = CapEnum.BUTT this._dashPattern = [] this._dashOffset = 0 this._initStrokeStyleFromOptions(opts) } /** * Sets the stroke color * @param {string} strokeColor Color as a string, "rgb()", "rgba()", "#......", or a color keyword (i.e. "black") * @return {StrokeStyle} */ set strokeColor(strokeColor) { this._strokeColor.value = strokeColor return this } /** * Gets the stroke color of the style * @return {string} */ get strokeColor() { return this._strokeColor.value } /** * Sets the opacity of the stroke style * @param {number} opacity [0,1] * @return {StrokeStyle} */ set strokeOpacity(opacity) { this._strokeColor.opacity = opacity } /** * Gets the current opacity of the stroke style [0,1] * @return {number} Opacity in the range [0,1] */ get strokeOpacity() { return this._strokeColor.opacity } /** * Sets the stroke color of the style defined as a 32-bit int * @param {number} packedStrokeColor Color value as a 32-bit int (i.e. 0xFFFFFFFF) * @return {StrokeStyle} */ set packedStrokeColor(packedStrokeColor) { this._strokeColor.packedValue = packedStrokeColor } /** * Gets the current value of the color of the stroke style as a 32-bit int * @return {number} i.e. 0xFFFFFFFF */ get packedStrokeColor() { return this._strokeColor.packedValue } /** * Sets the stroke width * @param {number} strokeWidth * @return {StrokeStyle} */ set strokeWidth(strokeWidth) { validateStrokeWidth(strokeWidth) this._strokeWidth = strokeWidth return this } /** * Gets the current stroke width * @return {number} */ get strokeWidth() { return this._strokeWidth } /** * Sets how lines should be joined * @param {string} lineJoin One of "miter", "round", or "bevel" * @return {StrokeStyle} */ set lineJoin(lineJoin) { const enumVal = validateLineJoin(lineJoin) this._lineJoin = enumVal return this } /** * Gets the current line join * @return {string} */ get lineJoin() { return lineJoinOpts[this._lineJoin] } /** * Sets how lines should be capped * @param {string} lineCap One of "butt", "square", or "round" * @return {StrokeStyle} */ set lineCap(lineCap) { const enumVal = validateLineCap(lineCap) this._lineCap = enumVal return this } /** * Gets the current line cap of the style * @return {string} */ get lineCap() { return lineCapOpts[this._lineJoin] } /** * Sets the dash pattern of the style * @param {number[]} dashPattern A list of numbers that specifies distances to alternately * draw a line and a gap (in screen units) * @return {StrokeStyle} */ set dashPattern(dashPattern) { validateDashPattern(dashPattern) this._dashPattern = dashPattern.slice() return this } /** * Gets the current dash pattern of the style * @return {number[]} */ get dashPattern() { return this._dashPattern.slice() } /** * Sets the dash offset of the style * @param {number} dashOffset * @return {StrokeStyle} */ set dashOffset(dashOffset) { validateDashOffset(dashOffset) this._dashOffset = dashOffset return this } /** * Gets the current dash offset * @return {number} */ get dashOffset() { return this._dashOffset } /** * Returns true if the stroke style is visible, i.e. it is not fully transparent * and has a width > 0 * @return {Boolean} */ isStrokeVisible() { return this._strokeColor.opacity > 0 && this._strokeWidth > 0 } /** * Returns true if stroke is partially transparent, i.e. opacity < 1 * @return {Boolean} [description] */ isTransparent() { return this._strokeColor.isTransparent() } /** * Sets the stroke style state of a 2d rendering context * @param {CanvasRenderingContext2D} ctx */ setStrokeCtx(ctx) { ctx.strokeStyle = this.strokeColor ctx.lineWidth = this._strokeWidth ctx.lineJoin = this._lineJoin ctx.lineCap = this._lineCap ctx.setLineDash(this._dashPattern) ctx.lineDashOffset = this._dashOffset } /** * Copies the properties of one stroke style to another * @param {StrokeStyle} srcStyle StrokeStyle object to copy from * @param {StrokeStyle} dstStyle StrokeStyle object to copy to */ static copyStrokeStyle(srcStyle, dstStyle) { if (typeof srcStyle.packedStrokeColor === "undefined") { if (typeof srcStyle.strokeColor !== "undefined") { dstStyle.strokeColor = srcStyle.strokeColor } if (typeof srcStyle.strokeOpacity !== "undefined") { dstStyle.strokeOpacity = srcStyle.strokeOpacity } } else { dstStyle.packedStrokeColor = srcStyle.packedStrokeColor } if (typeof srcStyle.strokeWidth !== "undefined") { dstStyle.strokeWidth = srcStyle.strokeWidth } if (typeof srcStyle.lineJoin !== "undefined") { dstStyle.lineJoin = srcStyle.lineJoin } if (typeof srcStyle.lineCap !== "undefined") { dstStyle.lineCap = srcStyle.lineCap } if (typeof srcStyle.dashPattern !== "undefined") { dstStyle.dashPattern = srcStyle.dashPattern } if (typeof srcStyle.dashOffset !== "undefined") { dstStyle.dashOffset = srcStyle.dashOffset } } /** * Comparison operator between two StrokeStyle objects. This is primarily * used for sorting to minimize context switching of a 2d renderer * @param {StrokeStyle} strokeStyleA * @param {StrokeStyle} strokeStyleB * @return {number} Returns < 0 if strokeStyleA < strokeStyleB, > 0 if strokeStyleA > strokeStyleB, or 0 if they are equal. */ static compareStrokeStyle(strokeStyleA, strokeStyleB) { let valA = strokeStyleA.isStrokeVisible() let valB = strokeStyleB.isStrokeVisible() if (valA !== valB) { return valA - valB } valA = strokeStyleA.packedStrokeColor valB = strokeStyleB.packedStrokeColor if (valA !== valB) { return valA - valB } valA = strokeStyleA.strokeWidth valB = strokeStyleB.strokeWidth if (valA !== valB) { return valA - valB } valA = strokeStyleA._lineJoin valB = strokeStyleB._lineJoin if (valA !== valB) { return valA - valB } valA = strokeStyleA._lineCap valB = strokeStyleB._lineCap if (valA !== valB) { return valA - valB } valA = strokeStyleA._dashPattern valB = strokeStyleB._dashPattern if (valA.length === valB.length && valA.length > 0) { for (let i = 0; i < valA.length; i += 1) { if (valA[i] !== valB[i]) { return valA[i] - valB[i] } } return strokeStyleA.dashOffset - strokeStyleB.dashOffset } return valA.length - valB.length } /** * Returns a json object of a StrokeStyle object * @param {StrokeStyle} strokeStyleObj * @return {{strokeColor: string, * strokeWidth: number, * lineJoin: string, * lineCap: string, * dashPattern: number[], * dashOffset: number * }} */ static toJSON(strokeStyleObj) { return { strokeColor: strokeStyleObj.strokeColor, strokeWidth: strokeStyleObj.strokeWidth, lineJoin: strokeStyleObj.lineJoin, lineCap: strokeStyleObj.lineCap, dashPattern: strokeStyleObj.dashPattern, dashOffset: strokeStyleObj.dashOffset } } }
JavaScript
class ModelClassWrapper { /** * Create the Model class Wrapper. * @param {class} cls Model class to wrap. * @param {*} modelData Model data. */ constructor(cls, modelData) { // store class we wrap + mongore model data this._class = cls; this._md = modelData; } /** * Read this object from DB. * @param {*} query The object id or a query dictionary. * @param {Function} onSuccess Callback to invoke on success. * @param {Function} onNotFound Callback to call if not found. If not defined will treat it like error. * @param {Function} onError Callback to invoke on error. If not defined, we'll get exception instead. */ load(query, onSuccess, onNotFound, onError) { // create instance to return var ret = new this._class(); // if query is not an object, set default query to use the _id field if (typeof query !== "object") { query = {_id: query} }; // attempt load DbClient.findOne(query, this.collectionName, (data) => { ret.mongore._setFromDBDocument(data, true); if (onSuccess) { onSuccess(ret); } }, onError, onNotFound); // return object even if not ready return ret; } /** * Delete one or more objects that match the query. * @param {*} query The object id or a query dictionary. * @param {Function} onSuccess Callback to invoke on success. * @param {Function} onError Callback to invoke on error. If not defined, we'll get exception instead. */ deleteMany(query, onSuccess, onError) { // if query is not an object, set default query to use the _id field if (typeof query !== "object") { query = {_id: query} }; // attempt delete DbClient.deleteMany(query, this.collectionName, onSuccess, onError); } /** * Delete one object that match the query. * @param {*} query The object id or a query dictionary. * @param {Function} onSuccess Callback to invoke on success. * @param {Function} onError Callback to invoke on error. If not defined, we'll get exception instead. */ delete(query, onSuccess, onError) { // if query is not an object, set default query to use the _id field if (typeof query !== "object") { query = {_id: query} }; // attempt delete DbClient.deleteOne(query, this.collectionName, onSuccess, onError); } /** * Create the collection for this model. * This set validators, db indexes, ect automatically. * @param {Function} onSuccess Callback to invoke on success. * @param {Function} onError Callback to invoke on error. If not defined, we'll get exception instead. */ createCollection(onSuccess, onError) { var collectionOptions = this.getCollectionOptions(); // notify creation DbClient.logger.debug(`Create collection '${this.collectionName}' with properties: ${JSON.stringify(collectionOptions)}`); // create the collection DbClient.createCollection(this.collectionName, collectionOptions, () => { DbClient.logger.debug(`Collection '${this.collectionName}' created successfully. Create indexes..`); var indexes = []; var uniqueIndexes = []; for (var field in this._md.fields) { if (this._md.fields[field].isIndex) { var index = {}; index[field] = this._md.fields[field].indexType; (this._md.fields[field].isUniqueIndex ? uniqueIndexes : indexes).push(index); } } DbClient.createIndex(this.collectionName, indexes, {unique: false}, () => { DbClient.createIndex(this.collectionName, uniqueIndexes, {unique: true}, () => { DbClient.logger.debug(`Done creating collection: '${this.collectionName}'.`); if (onSuccess) onSuccess(); }, onError); }, onError); }, onError); } /** * Drop this Model's collection. */ dropCollection(onSuccess, onError) { DbClient.dropCollection(this.collectionName, onSuccess, onError); } /** * Get the collection's options dictionary. */ getCollectionOptions() { // create collection options dictionary var collectionOptions = {}; // get list of mandatory fields var mandatoryFields = []; for (var field in this._md.fields) { if (this._md.fields[field].isMandatory) { mandatoryFields.push(field); } } // get all fields properties var properties = {}; for (var field in this._md.fields) { properties[field] = this._md.fields[field].getValidatorProperties(); } // set validators collectionOptions.validator = { $jsonSchema: { bsonType: "object", required: mandatoryFields, properties: properties, } } // set size and max limit if (this._md.maxSizeInBytes) { collectionOptions.size = this._md.maxSizeInBytes; collectionOptions.capped = true; } // set max count if (this._md.maxCount) { collectionOptions.max = this._md.maxCount; } return collectionOptions; } /** * Get all field names. */ get fieldNames() { return Object.keys(this._md.fields); } /** * Get the field descriptor for a given field name. */ getFieldDescriptor(fieldName) { return this._md.fields[fieldName]; } /** * Get field default value. * @param {String} fieldName Field name to get default value for. */ getDefault(fieldName) { return this.getFieldDescriptor(fieldName).default; } /** * Get collection name of this object type. */ get collectionName() { return this._md.collectionName || this._class.name + 's'; } }
JavaScript
class UserEndpoints { static main = API_URL + 'users/'; static whoAmI = `${UserEndpoints.main}whoami/`; static login = () => { return `${UserEndpoints.main}login/` }; static userRegistration = () => { return `${UserEndpoints.main}register/` }; }
JavaScript
class Event { constructor() { this._emitter = new Emitter() } /** * Adds a listener. * * @public * @param {string} event * @param {array|function} callback */ on(event, callback) { this._registerEvent('on', event, callback) } /** * Adds a listener to be executed once. * * @public * @param {string} event * @param {array|function} callback */ once(event, callback) { this._registerEvent('once', event, callback) } /** * Emits an event to all listeners. * * @public * @param {string} event * @param {array} params */ emit(event, ...params) { this._emitter.emit(event, ...params) } /** * Gets all the registered listeners. * * @public * @param {string} event * @returns {array} */ listeners(event) { return this._emitter.listeners(event) } /** * Counts registered listeners. * * @public * @param {string} event * @returns {int} */ count(event) { return this._emitter.listenerCount(event) } /** * Gets the names of all the registered events. * * @public * @returns {array} */ names() { return this._emitter.eventNames() } /** * Checks the type of the callback and registers * the listeners accordinhly. * * @private * @param {string} type * @param {string} event * @param {array|function} callback * @throws {InvalidEventHandler} if the callback isn't a function */ _registerEvent(type, event, callback) { if (Array.isArray(callback)) { callback.forEach(cb => { this._addListener(type, event, cb) }) } else if (typeof callback === 'function' || callback instanceof BaseEvent) this._addListener(type, event, callback) else throw new InvalidEventHandler(`Event.${type} expects a function or an array of functions as event handlers.`) } /** * Adds a listener for the event. * * @private * @param {string} type * @param {string} event * @param {array|function} callback */ _addListener(type, event, callback) { this._emitter[type](event, this._checkForBaseType(callback)) } /** * Checks if the callback is in instance of * BaseEvent and automatically get it's "listen" * method. * * @private * @param {function} callback * @returns {function} * @throws {InvalidEventHandler} if the instance doesn't implement a "listen" method */ _checkForBaseType(callback) { if (callback instanceof BaseEvent) { if (!callback.listen) throw new InvalidEventHandler(`Event class that extends BaseEvent must declare a "listen" method.`) return callback.listen } return callback } }
JavaScript
class User extends React.Component { constructor(fbookId, name, profPic) { super(); this.state = { facebookId: fbookId, name: name, picture: profPic, } } render() { return ( <View> </View> ); } }
JavaScript
class Buttons extends Component { // special thanks to f_youngblood#1697 for this one state = { quote: '', author: '', context: '', source: '', date: '' } fetchQuote = (rows) => { // const message = JSON.stringify(rows) const quote = rows._array[0].quote const author = rows._array[0].author const context = rows._array[0].context const source = rows._array[0].source const date = rows._array[0].date this.setState({quote}) this.setState({author}) this.setState({context}) this.setState({source}) this.setState({date}) } RandQuote = () => { console.log("About to open SQLite database...") db.transaction( tx => { tx.executeSql( // https://stackoverflow.com/questions/2279706 `SELECT * FROM fortunes ORDER BY RANDOM() LIMIT 1`, [], (_, {rows}) => this.fetchQuote(rows), (txObj, error) => alert(error) ) }, error => console.log("Something went wrong:" + error), () => console.log("Database transaction is a success!") ) } render() { return ( <View style={{flex: 1, flexDirection: 'column', justifyContent: 'space-between'}}> <Text style={styles.quoteText}> {this.state.quote}{"\n\n"} {this.state.author}{"\n\n"} {this.state.context}{"\n\n"} {this.state.source}{"\n\n"} {this.state.date} </Text> <ActionButton buttonColor="rgba(231,76,60,1)"> <ActionButton.Item buttonColor='#00695C' title="" onPress={()=>this.RandQuote()}> <Icon name="navigate-next" style={styles.actionButtonIcon} /> </ActionButton.Item> </ActionButton> </View> ); } }
JavaScript
class SupportInfo extends BaseFormatter { /** * Constructor for supportInfo info formatter. * * @param {object} params * @param {object} params.supportInfo * * @augments BaseFormatter * * @constructor */ constructor(params) { super(); const oThis = this; oThis.supportInfo = params.supportInfo; } /** * Validate the input objects. * * @returns {result} * @private */ _validate() { const oThis = this; const supportInfoInfoKeyConfig = { id: { isNullAllowed: false }, url: { isNullAllowed: false }, uts: { isNullAllowed: false } }; return oThis.validateParameters(oThis.supportInfo, supportInfoInfoKeyConfig); } /** * Format the input object. * * @returns {result} * @private */ _format() { const oThis = this; return responseHelper.successWithData(oThis.supportInfo); } }
JavaScript
class ListNode { constructor(val) { this.val = val; this.next = null; } }
JavaScript
class EventManager extends EventEmitter { constructor(events, name = "node-platform") { super(); this.events = events; this.name = name; Object.freeze(this.name); // avoid changing EventManager name } /** * * @param {EventType[]} event * @param {...any} args * @returns {EventManager} */ emit(event, ...args) { const evtName=event.toString().slice(7,-1) // remove "Symbol()" from description if (!this.events[evtName] || this.events[evtName] != event) { throw new Error("EventManager (" + this.name + ") have no event: " + evtName) } super.emit(event, ...args) return this; } /** @callback listenerCb @param {...Object} args */ /** * * @param {EventType[]} event * @param {listenerCb} listener * @returns {EventManager} */ on(event, listener) { const evtName=event.toString().slice(7,-1) // remove "Symbol()" from description if (!this.events[evtName] || this.events[evtName] != event) { throw new Error("EventManager (" + this.name + ") have no event: " + evtName) } super.on(event, listener) return this; } }
JavaScript
class App extends Component { constructor(props) { super(props) this.state = { view: 1, city_id: null, city_name: null, city_paths: [], city_path: null } this.selectCity = this.selectCity.bind(this) this.goHome = this.goHome.bind(this) this.selectPath = this.selectPath.bind(this) } selectCity(city_id, city_name){ console.log(city_id) const view = 1 if(city_id != null || city_id == this.state.city_id) { view = 2 } Meteor.call('getCityPaths', city_id, (error, city_paths)=>{ console.log(city_paths) if(!error) this.setState({city_id, view, city_name, city_paths}) }) } selectPath(path){ console.log(path) this.setState({view: 3, city_path: path}) } goHome(){ this.setState({view: 1, city_id: null, city_paths: [], city_path: null}) } render() { switch(this.state.view){ case 1: return <Home selectCity={this.selectCity} goHome={this.goHome}/> case 2: return <CityPaths cityPaths={this.state.city_paths} cityName={this.state.city_name} selectPath={this.selectPath} goHome={this.goHome} /> case 3: return <Path cityPath={this.state.city_path} cityName={this.state.city_name} goHome={this.goHome}/> default: return } } }
JavaScript
class ListManagementTerm { /** * Create a ListManagementTerm. * @param {ContentModeratorClient} client Reference to the service client. */ constructor(client) { this.client = client; this._addTerm = _addTerm; this._deleteTerm = _deleteTerm; this._getAllTerms = _getAllTerms; this._deleteAllTerms = _deleteAllTerms; } /** * Add a term to the term list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Object>} - The deserialized result object. * * @reject {Error} - The error object. */ addTermWithHttpOperationResponse(listId, term, language, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._addTerm(listId, term, language, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Add a term to the term list with list Id equal to list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Object} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ addTerm(listId, term, language, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._addTerm(listId, term, language, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._addTerm(listId, term, language, options, optionalCallback); } } /** * Deletes a term from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error} - The error object. */ deleteTermWithHttpOperationResponse(listId, term, language, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._deleteTerm(listId, term, language, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Deletes a term from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} term Term to be deleted * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {String} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {string} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ deleteTerm(listId, term, language, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._deleteTerm(listId, term, language, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._deleteTerm(listId, term, language, options, optionalCallback); } } /** * Gets all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {number} [options.offset] The pagination start index. * * @param {number} [options.limit] The max limit. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Terms>} - The deserialized result object. * * @reject {Error} - The error object. */ getAllTermsWithHttpOperationResponse(listId, language, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._getAllTerms(listId, language, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Gets all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {number} [options.offset] The pagination start index. * * @param {number} [options.limit] The max limit. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {Terms} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link Terms} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ getAllTerms(listId, language, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._getAllTerms(listId, language, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._getAllTerms(listId, language, options, optionalCallback); } } /** * Deletes all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<String>} - The deserialized result object. * * @reject {Error} - The error object. */ deleteAllTermsWithHttpOperationResponse(listId, language, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._deleteAllTerms(listId, language, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Deletes all terms from the list with list Id equal to the list Id passed. * * @param {string} listId List Id of the image list. * * @param {string} language Language of the terms. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {String} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {string} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ deleteAllTerms(listId, language, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._deleteAllTerms(listId, language, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._deleteAllTerms(listId, language, options, optionalCallback); } } }
JavaScript
class AccessibilityHandler { constructor(session, contentChannel) { this._contentPage = contentChannel.connect(session.sessionId() + 'page'); } async getFullAXTree(params) { return await this._contentPage.send('getFullAXTree', params); } dispose() { this._contentPage.dispose(); } }
JavaScript
class Recurrence { /** * Create a Recurrence. * @member {string} frequency the recurrence frequency. How often the * schedule profile should take effect. This value must be Week, meaning each * week will have the same set of profiles. Possible values include: 'None', * 'Second', 'Minute', 'Hour', 'Day', 'Week', 'Month', 'Year' * @member {object} schedule the scheduling constraints for when the profile * begins. * @member {string} [schedule.timeZone] the timezone for the hours of the * profile. Some examples of valid timezones are: Dateline Standard Time, * UTC-11, Hawaiian Standard Time, Alaskan Standard Time, Pacific Standard * Time (Mexico), Pacific Standard Time, US Mountain Standard Time, Mountain * Standard Time (Mexico), Mountain Standard Time, Central America Standard * Time, Central Standard Time, Central Standard Time (Mexico), Canada * Central Standard Time, SA Pacific Standard Time, Eastern Standard Time, US * Eastern Standard Time, Venezuela Standard Time, Paraguay Standard Time, * Atlantic Standard Time, Central Brazilian Standard Time, SA Western * Standard Time, Pacific SA Standard Time, Newfoundland Standard Time, E. * South America Standard Time, Argentina Standard Time, SA Eastern Standard * Time, Greenland Standard Time, Montevideo Standard Time, Bahia Standard * Time, UTC-02, Mid-Atlantic Standard Time, Azores Standard Time, Cape Verde * Standard Time, Morocco Standard Time, UTC, GMT Standard Time, Greenwich * Standard Time, W. Europe Standard Time, Central Europe Standard Time, * Romance Standard Time, Central European Standard Time, W. Central Africa * Standard Time, Namibia Standard Time, Jordan Standard Time, GTB Standard * Time, Middle East Standard Time, Egypt Standard Time, Syria Standard Time, * E. Europe Standard Time, South Africa Standard Time, FLE Standard Time, * Turkey Standard Time, Israel Standard Time, Kaliningrad Standard Time, * Libya Standard Time, Arabic Standard Time, Arab Standard Time, Belarus * Standard Time, Russian Standard Time, E. Africa Standard Time, Iran * Standard Time, Arabian Standard Time, Azerbaijan Standard Time, Russia * Time Zone 3, Mauritius Standard Time, Georgian Standard Time, Caucasus * Standard Time, Afghanistan Standard Time, West Asia Standard Time, * Ekaterinburg Standard Time, Pakistan Standard Time, India Standard Time, * Sri Lanka Standard Time, Nepal Standard Time, Central Asia Standard Time, * Bangladesh Standard Time, N. Central Asia Standard Time, Myanmar Standard * Time, SE Asia Standard Time, North Asia Standard Time, China Standard * Time, North Asia East Standard Time, Singapore Standard Time, W. Australia * Standard Time, Taipei Standard Time, Ulaanbaatar Standard Time, Tokyo * Standard Time, Korea Standard Time, Yakutsk Standard Time, Cen. Australia * Standard Time, AUS Central Standard Time, E. Australia Standard Time, AUS * Eastern Standard Time, West Pacific Standard Time, Tasmania Standard Time, * Magadan Standard Time, Vladivostok Standard Time, Russia Time Zone 10, * Central Pacific Standard Time, Russia Time Zone 11, New Zealand Standard * Time, UTC+12, Fiji Standard Time, Kamchatka Standard Time, Tonga Standard * Time, Samoa Standard Time, Line Islands Standard Time * @member {array} [schedule.days] the collection of days that the profile * takes effect on. Possible values are Sunday through Saturday. * @member {array} [schedule.hours] A collection of hours that the profile * takes effect on. Values supported are 0 to 23 on the 24-hour clock (AM/PM * times are not supported). * @member {array} [schedule.minutes] A collection of minutes at which the * profile takes effect at. */ constructor() { } /** * Defines the metadata of Recurrence * * @returns {object} metadata of Recurrence * */ mapper() { return { required: false, serializedName: 'Recurrence', type: { name: 'Composite', className: 'Recurrence', modelProperties: { frequency: { required: true, serializedName: 'frequency', type: { name: 'Enum', allowedValues: [ 'None', 'Second', 'Minute', 'Hour', 'Day', 'Week', 'Month', 'Year' ] } }, schedule: { required: true, serializedName: 'schedule', type: { name: 'Composite', className: 'RecurrentSchedule' } } } } }; } }
JavaScript
class VcVisitSummaryCard extends React.Component { constructor(props) { super(props); this.timelineList = React.createRef(); } scrollToBottom = () => { if (this.timelineList && this.timelineList.current) { const scrollHeight = this.timelineList.current.scrollHeight; this.timelineList.current.scrollTop = scrollHeight; } }; renderTimelineEvent = timelineEvent => { return ( <React.Fragment key={timelineEvent.message}> <ListItem className={this.props.classes.timelineItem}> <Grid container justify="flex-start"> <Grid item xs={4}> <Typography className={this.props.classes.timelineText}> {timelineEvent.timeStamp} </Typography> </Grid> <Grid item xs={8}> <Typography className={this.props.classes.timelineText}> {timelineEvent.message} </Typography> </Grid> </Grid> </ListItem> <Divider component="li" className={this.props.classes.divider} /> </React.Fragment> ); }; componentDidMount() { this.scrollToBottom(); } componentDidUpdate() { this.scrollToBottom(); } render() { return ( <Paper className={cx(this.props.classes.root, this.props.className)} square > <div className={this.props.classes.cardHeader}> <Typography variant="subtitle1" className={this.props.classes.cardHeaderText} > {this.props.cardHeader} </Typography> </div> <Grid container className={this.props.classes.content}> <Grid container className={this.props.classes.summary}> <Grid item xs={12}> <RootRef rootRef={this.timelineList}> <List className={cx( this.props.classes.timeline, this.props.className )} > {this.props.timeline.map(this.renderTimelineEvent)} </List> </RootRef> </Grid> </Grid> </Grid> {this.props.onEndVisit !== undefined ? ( <Grid container justify="flex-end" className={this.props.classes.actions} > <VcButton value={this.props.endVisitText} color="primary" squared size="small" onClick={this.props.onEndVisit} /> </Grid> ) : ( <div /> )} </Paper> ); } }
JavaScript
class TrajectoryPlayer { /** * make trajectory player * @param {Trajectory} traj - the trajectory * @param {TrajectoryPlayerParameters} [params] - parameter object */ constructor(traj, params = {}) { this.signals = { startedRunning: new Signal(), haltedRunning: new Signal() }; this._run = false; this._previousTime = 0; this._currentTime = 0; this._currentStep = 1; traj.signals.playerChanged.add((player) => { if (player !== this) { this.pause(); } }, this); const n = defaults(traj.frameCount, 1); this.traj = traj; this.parameters = createParams(params, TrajectoryPlayerDefaultParameters); this.parameters.end = Math.min(defaults(params.end, n - 1), n - 1); this.parameters.step = defaults(params.step, Math.ceil((n + 1) / 100)); this._currentFrame = this.parameters.start; this._direction = this.parameters.direction === 'bounce' ? 'forward' : this.parameters.direction; traj.signals.countChanged.add((n) => { this.parameters.end = Math.min(defaults(this.parameters.end, n - 1), n - 1); }, this); this._animate = this._animate.bind(this); } get isRunning() { return this._run; } /** * set player parameters * @param {TrajectoryPlayerParameters} [params] - parameter object */ setParameters(params = {}) { updateParams(this.parameters, params); if (params.direction !== undefined && this.parameters.direction !== 'bounce') { this._direction = this.parameters.direction; } } _animate() { if (!this._run) return; this._currentTime = window.performance.now(); const dt = this._currentTime - this._previousTime; const step = this.parameters.interpolateType ? this.parameters.interpolateStep : 1; const timeout = this.parameters.timeout / step; const traj = this.traj; if (traj && traj.frameCount && !traj.inProgress && dt >= timeout) { if (this.parameters.interpolateType) { if (this._currentStep > this.parameters.interpolateStep) { this._currentStep = 1; } if (this._currentStep === 1) { this._currentFrame = this._nextInterpolated(); } if (traj.hasFrame(this._currentFrame)) { this._currentStep += 1; const t = this._currentStep / (this.parameters.interpolateStep + 1); const [i, ip, ipp, ippp] = this._currentFrame; traj.setFrameInterpolated(i, ip, ipp, ippp, t, this.parameters.interpolateType); this._previousTime = this._currentTime; } else { traj.loadFrame(this._currentFrame); } } else { const i = this._next(); if (traj.hasFrame(i)) { traj.setFrame(i); this._previousTime = this._currentTime; } else { traj.loadFrame(i); } } } window.requestAnimationFrame(this._animate); } _next() { const p = this.parameters; let i; if (this._direction === 'forward') { i = this.traj.currentFrame + p.step; } else { i = this.traj.currentFrame - p.step; } if (i > p.end || i < p.start) { if (p.direction === 'bounce') { if (this._direction === 'forward') { this._direction = 'backward'; } else { this._direction = 'forward'; } } if (p.mode === 'once') { this.pause(); if (p.direction === 'forward') { i = p.end; } else if (p.direction === 'backward') { i = p.start; } else { if (this._direction === 'forward') { i = p.start; } else { i = p.end; } } } else { if (this._direction === 'forward') { i = p.start; if (p.interpolateType) { i = Math.min(p.end, i + p.step); } } else { i = p.end; if (p.interpolateType) { i = Math.max(p.start, i - p.step); } } } } return i; } _nextInterpolated() { const p = this.parameters; const i = this._next(); let ip, ipp, ippp; if (this._direction === 'forward') { ip = Math.max(p.start, i - p.step); ipp = Math.max(p.start, i - 2 * p.step); ippp = Math.max(p.start, i - 3 * p.step); } else { ip = Math.min(p.end, i + p.step); ipp = Math.min(p.end, i + 2 * p.step); ippp = Math.min(p.end, i + 3 * p.step); } return [i, ip, ipp, ippp]; } /** * toggle between playing and pausing the animation * @return {undefined} */ toggle() { if (this._run) { this.pause(); } else { this.play(); } } /** * start the animation * @return {undefined} */ play() { if (!this._run) { if (this.traj.player !== this) { this.traj.setPlayer(this); } this._currentStep = 1; const p = this.parameters; const frame = this.traj.currentFrame; // snap to the grid implied by this.step division and multiplication // thus minimizing cache misses let i = Math.ceil(frame / p.step) * p.step; // wrap when restarting from the limit (i.e. end or start) if (p.direction === 'forward' && frame >= p.end) { i = p.start; } else if (p.direction === 'backward' && frame <= p.start) { i = p.end; } this.traj.setFrame(i); this._run = true; this._animate(); this.signals.startedRunning.dispatch(); } } /** * pause the animation * @return {undefined} */ pause() { this._run = false; this.signals.haltedRunning.dispatch(); } /** * stop the animation (pause and go to start-frame) * @return {undefined} */ stop() { this.pause(); this.traj.setFrame(this.parameters.start); } }
JavaScript
class SMAAWeightsMaterial extends ShaderMaterial { /** * Constructs a new SMAA weights material. * * @param {Vector2} [texelSize] - The absolute screen texel size. */ constructor(texelSize = new Vector2()) { super({ type: "SMAAWeightsMaterial", defines: { SMAA_MAX_SEARCH_STEPS_INT: "8", SMAA_MAX_SEARCH_STEPS_FLOAT: "8.0", SMAA_AREATEX_MAX_DISTANCE: "16.0", SMAA_AREATEX_PIXEL_SIZE: "(1.0 / vec2(160.0, 560.0))", SMAA_AREATEX_SUBTEX_SIZE: "(1.0 / 7.0)" }, uniforms: { tDiffuse: new Uniform(null), tArea: new Uniform(null), tSearch: new Uniform(null), texelSize: new Uniform(texelSize) }, fragmentShader: fragment, vertexShader: vertex, depthWrite: false, depthTest: false }); /** * The area pattern recognition image. Encoded as base64. * * @type {String} */ this.areaImage = areaImage; /** * The search image. Encoded as base64. * * @type {String} */ this.searchImage = searchImage; } }
JavaScript
class ArticleView extends AbstractDetailView { /** * Constructor * Add Article to the page if required. */ constructor() { super('view-article'); } }
JavaScript
class LiveEvents { /** * Create a LiveEvents. * @param {AzureMediaServices} client Reference to the service client. */ constructor(client) { this.client = client; this._list = _list; this._get = _get; this._create = _create; this._update = _update; this._deleteMethod = _deleteMethod; this._start = _start; this._stop = _stop; this._reset = _reset; this._beginCreate = _beginCreate; this._beginUpdate = _beginUpdate; this._beginDeleteMethod = _beginDeleteMethod; this._beginStart = _beginStart; this._beginStop = _beginStop; this._beginReset = _beginReset; this._listNext = _listNext; } /** * @summary List Live Events * * Lists the Live Events in the account. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEventListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listWithHttpOperationResponse(resourceGroupName, accountName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._list(resourceGroupName, accountName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary List Live Events * * Lists the Live Events in the account. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEventListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEventListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName, accountName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._list(resourceGroupName, accountName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._list(resourceGroupName, accountName, options, optionalCallback); } } /** * @summary Get Live Event * * Gets a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEvent>} - The deserialized result object. * * @reject {Error} - The error object. */ getWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._get(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Get Live Event * * Gets a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEvent} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEvent} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._get(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._get(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary Create Live Event * * Creates a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.autoStart] The flag indicates if the resource * should be automatically started on creation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEvent>} - The deserialized result object. * * @reject {Error} - The error object. */ createWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._create(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Create Live Event * * Creates a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.autoStart] The flag indicates if the resource * should be automatically started on creation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEvent} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEvent} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._create(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._create(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback); } } /** * Updates a existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEvent>} - The deserialized result object. * * @reject {Error} - The error object. */ updateWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._update(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Updates a existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEvent} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEvent} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._update(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._update(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback); } } /** * @summary Delete Live Event * * Deletes a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._deleteMethod(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Delete Live Event * * Deletes a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._deleteMethod(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._deleteMethod(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary Start Live Event * * Starts an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ startWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._start(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Start Live Event * * Starts an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ start(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._start(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._start(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary Stop Live Event * * Stops an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters LiveEvent stop parameters * * @param {boolean} [parameters.removeOutputsOnStop] The flag indicates if * remove LiveOutputs on Stop. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ stopWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._stop(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Stop Live Event * * Stops an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters LiveEvent stop parameters * * @param {boolean} [parameters.removeOutputsOnStop] The flag indicates if * remove LiveOutputs on Stop. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ stop(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._stop(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._stop(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback); } } /** * @summary Reset Live Event * * Resets an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ resetWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._reset(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Reset Live Event * * Resets an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ reset(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._reset(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._reset(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary Create Live Event * * Creates a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.autoStart] The flag indicates if the resource * should be automatically started on creation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEvent>} - The deserialized result object. * * @reject {Error} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginCreate(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Create Live Event * * Creates a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {boolean} [options.autoStart] The flag indicates if the resource * should be automatically started on creation. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEvent} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEvent} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginCreate(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginCreate(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback); } } /** * Updates a existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEvent>} - The deserialized result object. * * @reject {Error} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginUpdate(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Updates a existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters Live Event properties needed for creation. * * @param {string} [parameters.description] The Live Event description. * * @param {object} parameters.input The Live Event input. * * @param {string} parameters.input.streamingProtocol The streaming protocol * for the Live Event. This is specified at creation time and cannot be * updated. Possible values include: 'FragmentedMP4', 'RTMP' * * @param {object} [parameters.input.accessControl] The access control for * LiveEvent Input. * * @param {object} [parameters.input.accessControl.ip] The IP access control * properties. * * @param {string} [parameters.input.keyFrameIntervalDuration] ISO 8601 * timespan duration of the key frame interval duration. * * @param {string} [parameters.input.accessToken] A unique identifier for a * stream. This can be specified at creation time but cannot be updated. If * omitted, the service will generate a unique value. * * @param {array} [parameters.input.endpoints] The input endpoints for the Live * Event. * * @param {object} [parameters.preview] The Live Event preview. * * @param {array} [parameters.preview.endpoints] The endpoints for preview. * * @param {object} [parameters.preview.accessControl] The access control for * LiveEvent preview. * * @param {object} [parameters.preview.accessControl.ip] The IP access control * properties. * * @param {array} [parameters.preview.accessControl.ip.allow] The IP allow * list. * * @param {string} [parameters.preview.previewLocator] The identifier of the * preview locator in Guid format. Specifying this at creation time allows the * caller to know the preview locator url before the event is created. If * omitted, the service will generate a random identifier. This value cannot * be updated once the live event is created. * * @param {string} [parameters.preview.streamingPolicyName] The name of * streaming policy used for the LiveEvent preview. This value is specified at * creation time and cannot be updated. * * @param {string} [parameters.preview.alternativeMediaId] An Alternative Media * Identifier associated with the StreamingLocator created for the preview. * This value is specified at creation time and cannot be updated. The * identifier can be used in the CustomLicenseAcquisitionUrlTemplate or the * CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the * StreamingPolicyName field. * * @param {object} [parameters.encoding] The Live Event encoding. * * @param {string} [parameters.encoding.encodingType] The encoding type for * Live Event. This value is specified at creation time and cannot be updated. * Possible values include: 'None', 'Basic', 'Standard' * * @param {string} [parameters.encoding.presetName] The encoding preset name. * This value is specified at creation time and cannot be updated. * * @param {object} [parameters.crossSiteAccessPolicies] The Live Event access * policies. * * @param {string} [parameters.crossSiteAccessPolicies.clientAccessPolicy] The * content of clientaccesspolicy.xml used by Silverlight. * * @param {string} [parameters.crossSiteAccessPolicies.crossDomainPolicy] The * content of crossdomain.xml used by Silverlight. * * @param {boolean} [parameters.vanityUrl] Specifies whether to use a vanity * url with the Live Event. This value is specified at creation time and * cannot be updated. * * @param {array} [parameters.streamOptions] The options to use for the * LiveEvent. This value is specified at creation time and cannot be updated. * * @param {object} [parameters.tags] Resource tags. * * @param {string} [parameters.location] The Azure Region of the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEvent} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEvent} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginUpdate(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginUpdate(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback); } } /** * @summary Delete Live Event * * Deletes a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginDeleteMethod(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Delete Live Event * * Deletes a Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginDeleteMethod(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginDeleteMethod(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary Start Live Event * * Starts an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginStartWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginStart(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Start Live Event * * Starts an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginStart(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginStart(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginStart(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary Stop Live Event * * Stops an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters LiveEvent stop parameters * * @param {boolean} [parameters.removeOutputsOnStop] The flag indicates if * remove LiveOutputs on Stop. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginStopWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, parameters, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginStop(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Stop Live Event * * Stops an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} parameters LiveEvent stop parameters * * @param {boolean} [parameters.removeOutputsOnStop] The flag indicates if * remove LiveOutputs on Stop. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginStop(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginStop(resourceGroupName, accountName, liveEventName, parameters, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginStop(resourceGroupName, accountName, liveEventName, parameters, options, optionalCallback); } } /** * @summary Reset Live Event * * Resets an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error} - The error object. */ beginResetWithHttpOperationResponse(resourceGroupName, accountName, liveEventName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._beginReset(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Reset Live Event * * Resets an existing Live Event. * * @param {string} resourceGroupName The name of the resource group within the * Azure subscription. * * @param {string} accountName The Media Services account name. * * @param {string} liveEventName The name of the Live Event. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {null} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ beginReset(resourceGroupName, accountName, liveEventName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._beginReset(resourceGroupName, accountName, liveEventName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._beginReset(resourceGroupName, accountName, liveEventName, options, optionalCallback); } } /** * @summary List Live Events * * Lists the Live Events in the account. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LiveEventListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary List Live Events * * Lists the Live Events in the account. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {LiveEventListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link LiveEventListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listNext(nextPageLink, options, optionalCallback); } } }
JavaScript
class AngleMeasurement extends Component { /** * @private */ constructor(plugin, cfg = {}) { super(plugin.viewer.scene, cfg); /** * The {@link AngleMeasurementsPlugin} that owns this AngleMeasurement. * @type {AngleMeasurementsPlugin} */ this.plugin = plugin; this._container = cfg.container; if (!this._container) { throw "config missing: container"; } var scene = this.plugin.viewer.scene; this._originMarker = new Marker(scene, cfg.origin); this._cornerMarker = new Marker(scene, cfg.corner); this._targetMarker = new Marker(scene, cfg.target); this._originWorld = new Float32Array(3); this._cornerWorld = new Float32Array(3); this._targetWorld = new Float32Array(3); this._wp = new Float32Array(12); this._vp = new Float32Array(12); this._pp = new Float32Array(12); this._cp = new Int16Array(6); this._originDot = new Dot(this._container, {}); this._cornerDot = new Dot(this._container, {}); this._targetDot = new Dot(this._container, {}); this._originWire = new Wire(this._container, {color: "blue", thickness: 1}); this._targetWire = new Wire(this._container, {color: "red", thickness: 1}); this._angleLabel = new Label(this._container, {fillColor: "#00BBFF", prefix: "", text: ""}); this._wpDirty = false; this._vpDirty = false; this._cpDirty = false; this._visible = false; this._originVisible = false; this._cornerVisible = false; this._targetVisible = false; this._originWireVisible = false; this._targetWireVisible = false; this._angleVisible = false; this._originMarker.on("worldPos", (value) => { this._originWorld.set(value || [0, 0, 0]); this._wpDirty = true; this._needUpdate(0); // No lag }); this._cornerMarker.on("worldPos", (value) => { this._cornerWorld.set(value || [0, 0, 0]); this._wpDirty = true; this._needUpdate(0); // No lag }); this._targetMarker.on("worldPos", (value) => { this._targetWorld.set(value || [0, 0, 0]); this._wpDirty = true; this._needUpdate(0); // No lag }); this._onViewMatrix = scene.camera.on("viewMatrix", () => { this._vpDirty = true; this._needUpdate(0); // No lag }); this._onProjMatrix = scene.camera.on("projMatrix", () => { this._cpDirty = true; this._needUpdate(); }); this._onCanvasBoundary = scene.canvas.on("boundary", () => { this._cpDirty = true; this._needUpdate(0); // No lag }); this.visible = cfg.visible; this.originVisible = cfg.originVisible; this.cornerVisible = cfg.cornerVisible; this.targetVisible = cfg.targetVisible; this.originWireVisible = cfg.originWireVisible; this.targetWireVisible = cfg.targetWireVisible; this.angleVisible = cfg.angleVisible; } _update() { if (!this._visible) { return; } const scene = this.plugin.viewer.scene; if (this._wpDirty) { this._wp[0] = this._originWorld[0]; this._wp[1] = this._originWorld[1]; this._wp[2] = this._originWorld[2]; this._wp[3] = 1.0; this._wp[4] = this._cornerWorld[0]; this._wp[5] = this._cornerWorld[1]; this._wp[6] = this._cornerWorld[2]; this._wp[7] = 1.0; this._wp[8] = this._targetWorld[0]; this._wp[9] = this._targetWorld[1]; this._wp[10] = this._targetWorld[2]; this._wp[11] = 1.0; this._wpDirty = false; this._vpDirty = true; } if (this._vpDirty) { math.transformPositions4(scene.camera.viewMatrix, this._wp, this._vp); this._vp[3] = 1.0; this._vp[7] = 1.0; this._vp[11] = 1.0; this._vpDirty = false; this._cpDirty = true; } if (this._cpDirty) { const near = -0.3; const zOrigin = this._originMarker.viewPos[2]; const zCorner = this._cornerMarker.viewPos[2]; const zTarget = this._targetMarker.viewPos[2]; if (zOrigin > near || zCorner > near || zTarget > near) { this._originDot.setVisible(false); this._cornerDot.setVisible(false); this._targetDot.setVisible(false); this._originWire.setVisible(false); this._targetWire.setVisible(false); this._angleLabel.setVisible(false); return; } math.transformPositions4(scene.camera.project.matrix, this._vp, this._pp); var pp = this._pp; var cp = this._cp; var canvas = scene.canvas.canvas; var offsets = canvas.getBoundingClientRect(); var top = offsets.top; var left = offsets.left; var aabb = scene.canvas.boundary; var canvasWidth = aabb[2]; var canvasHeight = aabb[3]; var j = 0; const metrics = this.plugin.viewer.scene.metrics; const scale = metrics.scale; const units = metrics.units; const unitInfo = metrics.unitsInfo[units]; const unitAbbrev = unitInfo.abbrev; for (var i = 0, len = pp.length; i < len; i += 4) { cp[j] = left + Math.floor((1 + pp[i + 0] / pp[i + 3]) * canvasWidth / 2); cp[j + 1] = top + Math.floor((1 - pp[i + 1] / pp[i + 3]) * canvasHeight / 2); j += 2; } this._originDot.setPos(cp[0], cp[1]); this._cornerDot.setPos(cp[2], cp[3]); this._targetDot.setPos(cp[4], cp[5]); this._originWire.setStartAndEnd(cp[0], cp[1], cp[2], cp[3]); this._targetWire.setStartAndEnd(cp[2], cp[3], cp[4], cp[5]); this._angleLabel.setPosBetweenWires(cp[0], cp[1], cp[2], cp[3], cp[4], cp[5]); math.subVec3(this._originWorld, this._cornerWorld, originVec); math.subVec3(this._targetWorld, this._cornerWorld, targetVec); var validVecs = (originVec[0] !== 0 || originVec[1] !== 0 || originVec[2] !== 0) && (targetVec[0] !== 0 || targetVec[1] !== 0 || targetVec[2] !== 0); if (validVecs) { math.normalizeVec3(originVec); math.normalizeVec3(targetVec); var angle = Math.abs(math.angleVec3(originVec, targetVec)); this._angle = angle / math.DEGTORAD; this._angleLabel.setText("" + this._angle.toFixed(2) + "°"); } else { this._angleLabel.setText(""); } // this._angleLabel.setText((Math.abs(math.lenVec3(math.subVec3(this._targetWorld, this._originWorld, distVec3)) * scale).toFixed(2)) + unitAbbrev); this._originDot.setVisible(this._visible && this._originVisible); this._cornerDot.setVisible(this._visible && this._cornerVisible); this._targetDot.setVisible(this._visible && this._targetVisible); this._originWire.setVisible(this._visible && this._originWireVisible); this._targetWire.setVisible(this._visible && this._targetWireVisible); this._angleLabel.setVisible(this._visible && this._angleVisible); this._cpDirty = false; } } /** * Gets the origin {@link Marker}. * * @type {Marker} */ get origin() { return this._originMarker; } /** * Gets the corner {@link Marker}. * * @type {Marker} */ get corner() { return this._cornerMarker; } /** * Gets the target {@link Marker}. * * @type {Marker} */ get target() { return this._targetMarker; } /** * Gets the angle between two connected 3D line segments, given * as three positions on the surface(s) of one or more {@link Entity}s. * * @type {Number} */ get angle() { this._update(); return this._angle; } /** * Sets whether this AngleMeasurement is visible or not. * * @type Boolean */ set visible(value) { value = value !== false; this._visible = value; this._originDot.setVisible(this._visible && this._originVisible); this._cornerDot.setVisible(this._visible && this._cornerVisible); this._targetDot.setVisible(this._visible && this._targetVisible); this._originWire.setVisible(this._visible && this._originWireVisible); this._targetWire.setVisible(this._visible && this._targetWireVisible); this._angleLabel.setVisible(this._visible && this._angleVisible); } /** * Gets whether this AngleMeasurement is visible or not. * * @type Boolean */ get visible() { return this._visible; } /** * Sets if the origin {@link Marker} is visible. * * @type {Boolean} */ set originVisible(value) { value = value !== false; this._originVisible = value; this._originDot.setVisible(this._visible && this._originVisible); } /** * Gets if the origin {@link Marker} is visible. * * @type {Boolean} */ get originVisible() { return this._originVisible; } /** * Sets if the corner {@link Marker} is visible. * * @type {Boolean} */ set cornerVisible(value) { value = value !== false; this._cornerVisible = value; this._cornerDot.setVisible(this._visible && this._cornerVisible); } /** * Gets if the corner {@link Marker} is visible. * * @type {Boolean} */ get cornerVisible() { return this._cornerVisible; } /** * Sets if the target {@link Marker} is visible. * * @type {Boolean} */ set targetVisible(value) { value = value !== false; this._targetVisible = value; this._targetDot.setVisible(this._visible && this._targetVisible); } /** * Gets if the target {@link Marker} is visible. * * @type {Boolean} */ get targetVisible() { return this._targetVisible; } /** * Sets if the wire between the origin and the corner is visible. * * @type {Boolean} */ set originWireVisible(value) { value = value !== false; this._originWireVisible = value; this._originWire.setVisible(this._visible && this._originWireVisible); } /** * Gets if the wire between the origin and the corner is visible. * * @type {Boolean} */ get originWireVisible() { return this._originWireVisible; } /** * Sets if the wire between the target and the corner is visible. * * @type {Boolean} */ set targetWireVisible(value) { value = value !== false; this._targetWireVisible = value; this._targetWire.setVisible(this._visible && this._targetWireVisible); } /** * Gets if the wire between the target and the corner is visible. * * @type {Boolean} */ get targetWireVisible() { return this._targetWireVisible; } /** * Sets if the angle label is visible. * * @type {Boolean} */ set angleVisible(value) { value = value !== false; this._angleVisible = value; this._angleLabel.setVisible(this._visible && this._angleVisible); } /** * Gets if the angle label is visible. * * @type {Boolean} */ get angleVisible() { return this._angleVisible; } /** * @private */ destroy() { const scene = this.plugin.viewer.scene; if (this._onViewMatrix) { scene.camera.off(this._onViewMatrix); } if (this._onProjMatrix) { scene.camera.off(this._onProjMatrix); } if (this._onCanvasBoundary) { scene.canvas.off(this._onCanvasBoundary); } this._originDot.destroy(); this._cornerDot.destroy(); this._targetDot.destroy(); this._originWire.destroy(); this._targetWire.destroy(); this._angleLabel.destroy(); super.destroy(); } }
JavaScript
class MoviesResults extends Component { render() { return ( <div> <h4>Results:</h4> <ul className="list-group"> { this.props.movies.map(function(movie, i) { return <Movie movie={movie} key={i} /> }) } </ul> </div> ) } }
JavaScript
class AdministerQuizComponent extends Component { constructor(props){ super(props); this.state = { quizData: [], quizDataLoaded: false, selectedQuiz: '', selectedQuestion: '', selectedQuestionIndex: -1, currQuizData: [{problems: []}], answers: [], questionActive: false, responses: [], responseCounts: [0,0,0,0] }; this.getQuizData(); this.handleQuizChange = this.handleQuizChange.bind(this); this.handleQuestionChange = this.handleQuestionChange.bind(this); this.administerQuestion = this.administerQuestion.bind(this); this.stopAdministeringQuestion = this.stopAdministeringQuestion.bind(this); } componentDidMount(){ this.getQuizData(); } componentWillReceiveProps(nextProps){ this.getQuizData(); } handleQuizChange(event, name){ if(event.target.value === 'none selected'){ this.setState({ [name]: event.target.value, currQuizData: [{problems: []}] }); return; } this.setState({ [name]: event.target.value, currQuizData: this.state.quizData.filter((key, _) => key.quizTitle === event.target.value) }); }; handleQuestionChange(event, name){ this.setState({ [name]: event.target.value, answers: this.state.currQuizData[0].problems.filter((key, _) => key[0] === event.target.value)[0][1] }); }; administerQuestion(event){ this.setState({ questionActive: true }); this.activateQuestion(); }; stopAdministeringQuestion(event){ this.setState({ questionActive: false }); this.deActivateQuestion(); }; activateQuestion = () => { axios.post("http://localhost:3001/api/submitInclassQuizData", { classId: cookies.get('currentClass'), quizTitle: this.state.selectedQuiz, question: this.state.selectedQuestion, answers: this.state.answers, responses: [], isActive: true }) .then(res => console.log(res.data)) } deActivateQuestion = () => { axios.post("http://localhost:3001/api/updateActiveInclassQuiz", { classId: cookies.get('currentClass'), quizTitle: this.state.selectedQuiz, question: this.state.selectedQuestion, isActive: false }) .then(res => console.log(res.data)) .then(() => { axios.get('http://localhost:3001/api/getInclassQuizResponseData', {params: { classId: cookies.get('currentClass'), quizTitle: this.state.selectedQuiz, question: this.state.selectedQuestion}}) .then(res => { console.log("getting response data", res.data.data[0].responses) this.setState({ responses: res.data.data.responses, }); var i; let numResponses = [0,0,0,0]; for (i = 0; i < res.data.data[0].responses.length; i++) { console.log("response", res.data.data[0].responses[i][1]); if(res.data.data[0].responses[i][1] > 3 || res.data.data[0].responses[i][1] < 0){ continue; } numResponses[res.data.data[0].responses[i][1]]++; } console.log("num responses", numResponses); this.setState({ responseCounts: numResponses, }); }) }) } getQuizData = () => { //class: cookies.get('currentClass') axios.get('http://localhost:3001/api/getInclassQuizzes', {params: {class: cookies.get('currentClass')}}) .then(res => { console.log(res.data.data, cookies.get('currentClass')); this.setState({ quizData: res.data.data, quizDataLoaded: true }); }) } // renders this.state.answers into answer fields // first is a select correct answer, then a text input, and then a delete render(){ let quizData = this.state.quizData; let currQuizData = this.state.currQuizData; return( <div> <Grid container justify="center" alignItems="center" spacing={24} item > <Grid item xs> <FormControl> <InputLabel htmlFor="age-native-simple" style={{color: 'white'}} > Select Quiz </InputLabel> <Select native value={this.state.age} onChange={(event) => {this.handleQuizChange(event, 'selectedQuiz')}} inputProps={{ name: 'selectQuiz', }} style={{ color: 'red' }} > <option value="none selected" /> {quizData.map((key, index) => ( <option value={key.quizTitle} key={index}>{key.quizTitle}</option> ))} </Select> </FormControl> </Grid> <Grid item xs> <FormControl> <InputLabel htmlFor="age-native-simple" style={{color: 'white'}} > Select Question </InputLabel> <Select native value={this.state.age} onChange={(event) => {this.handleQuestionChange(event, 'selectedQuestion')}} inputProps={{ name: 'selectQuestion', }} style={{ color: 'red' }} > <option value="" /> {currQuizData[0].problems.map((key, index) => ( <option value={key[0]}>{key[0]}</option> )) } </Select> </FormControl> </Grid> </Grid> <Grid container direction="column" justify="center" alignItems="center" spacing={24} > <Grid container justify="center" alignItems="center" spacing={24} item > <Grid item xs> <label> Quiz Question </label> </Grid> </Grid> <Grid container justify="center" alignItems="center" spacing={24} item > <Grid item xs> {(() => { if(this.state.answers.length < 1){ return (<label>No Answer in database</label> ); } return (<label>A. {this.state.answers[0]}</label>); })()} </Grid> <Grid item xs> {(() => { if(this.state.answers.length < 2){ return (<label>No Answer in database</label> ); } return (<label>B. {this.state.answers[1]}</label>); })()} </Grid> </Grid> <Grid container justify="center" alignItems="center" spacing={24} item > <Grid item xs> {(() => { if(this.state.answers.length < 3){ return (<label>No Answer in database</label> ); } return (<label>C. {this.state.answers[2]}</label>); })()} </Grid> <Grid item xs> {(() => { if(this.state.answers.length < 4){ return (<label>No Answer in database</label> ); } return (<label>D. {this.state.answers[3]}</label>); })()} </Grid> </Grid> <Grid container justify="center" alignItems="center" spacing={24} item > <Grid item xs> {(() => { if(this.state.questionActive === false){ return (<button onClick={this.administerQuestion}>Administer Question</button> ); } return (<button onClick={this.stopAdministeringQuestion}>Stop Administering Question</button>); })()} </Grid> </Grid> <Grid container justify="center" alignItems="center" spacing={24} item > <Chart width={'500px'} height={'300px'} chartType="BarChart" loader={<div>Loading Chart</div>} data={[ [ 'Element', 'Responses', { role: 'style' }, { sourceColumn: 0, role: 'annotation', type: 'string', calc: 'stringify', }, ], [this.state.answers[0], this.state.responseCounts[0], 'blue', null], [this.state.answers[1], this.state.responseCounts[1], 'red', null], [this.state.answers[2], this.state.responseCounts[2], 'green', null], [this.state.answers[3], this.state.responseCounts[3], 'yellow', null], ]} options={{ title: 'Response Frequency', width: 600, height: 400, bar: { groupWidth: '95%' }, legend: { position: 'none' }, }} // For tests rootProps={{ 'data-testid': '6' }} /> </Grid> </Grid> </div> ) } }
JavaScript
class Profile { /** * Constructs a new <code>Profile</code>. * Object hosting user profile information. * @alias module:sunshine-conversations-client/sunshine-conversations-client.model/Profile */ constructor() { Profile.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>Profile</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:sunshine-conversations-client/sunshine-conversations-client.model/Profile} obj Optional instance to populate. * @return {module:sunshine-conversations-client/sunshine-conversations-client.model/Profile} The populated <code>Profile</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Profile(); if (data.hasOwnProperty('givenName')) { obj['givenName'] = ApiClient.convertToType(data['givenName'], 'String'); } if (data.hasOwnProperty('surname')) { obj['surname'] = ApiClient.convertToType(data['surname'], 'String'); } if (data.hasOwnProperty('email')) { obj['email'] = ApiClient.convertToType(data['email'], 'String'); } if (data.hasOwnProperty('avatarUrl')) { obj['avatarUrl'] = ApiClient.convertToType(data['avatarUrl'], 'String'); } if (data.hasOwnProperty('locale')) { obj['locale'] = ApiClient.convertToType(data['locale'], 'String'); } } return obj; } /** * Returns The user's given name (first name). * @return {String} */ getGivenName() { return this.givenName; } /** * Sets The user's given name (first name). * @param {String} givenName The user's given name (first name). */ setGivenName(givenName) { this['givenName'] = givenName; } /** * Returns The user's surname (last name). * @return {String} */ getSurname() { return this.surname; } /** * Sets The user's surname (last name). * @param {String} surname The user's surname (last name). */ setSurname(surname) { this['surname'] = surname; } /** * Returns The user's email address. * @return {String} */ getEmail() { return this.email; } /** * Sets The user's email address. * @param {String} email The user's email address. */ setEmail(email) { this['email'] = email; } /** * Returns The user's avatar. * @return {String} */ getAvatarUrl() { return this.avatarUrl; } /** * Sets The user's avatar. * @param {String} avatarUrl The user's avatar. */ setAvatarUrl(avatarUrl) { this['avatarUrl'] = avatarUrl; } /** * Returns End-user's locale information in BCP 47 format. * @return {String} */ getLocale() { return this.locale; } /** * Sets End-user's locale information in BCP 47 format. * @param {String} locale End-user's locale information in BCP 47 format. */ setLocale(locale) { this['locale'] = locale; } }
JavaScript
class UserSelect { //This class is based on a template that it later going to be added to another DOM Node. //Therefore, no DOM references are kept as properties. constructor(currentUser, personnelList) { //Set arguments as properties. this.currentUser = currentUser; this.personnelList = personnelList; //Import and build leg edition node. const templateEl = document.getElementById("select-user-template"); this.element = document.importNode(templateEl.content, true); //============================ DATA SECTION ============================ //Reach to user select. const userSelect = this.element.getElementById("user"); //Populate select. DOMGeneric.populateSelect( userSelect, personnelList.map( (entry) => `${entry.id}.- ${entry.name} - ${entry.institution}` ) ); //Focus matching option on the select with the current user. const matchedUserIdx = personnelList.findIndex( (entry) => entry.id == currentUser.id ); if (matchedUserIdx > -1) { userSelect.value = userSelect.children[matchedUserIdx].value; DOMGeneric.removeFirstEmptyOption(userSelect); } //Set change event listeners. userSelect.addEventListener("change", this.userChangedHandler.bind(this)); } userChangedHandler() { //Get select value. const selectedUser = document.getElementById("user").value; //Find the entry in the personnel list and assign their values to the current user object. Object.assign( this.currentUser, this.personnelList.find((entry) => selectedUser.includes(entry.name)) ); } }
JavaScript
class Permutation { constructor(items) { this.queue = [...items]; } /** * Get the next permutation * @return {Array} the next permutation */ next() { let division = this.queue.length - 2; let swap = this.queue.length - 1; // find the first smaller number from tail while (division > 0 && this.queue[division] > this.queue[division + 1]) { division -= 1; } // find the first larger number than the first smaller number from tail while (swap > division && this.queue[division] > this.queue[swap]) { swap -= 1; } // reverse queue if it is the last permutation if (division === 0 && swap === 0) { this.reverse(0); } else { // swap the first smaller number and the first larger number than smaller number this.swap(division, swap); // reverse the rest of the queue from the first smaller number this.reverse(division + 1); } return this.queue; } /** * Swap two numbers through its index * @param {Number} from * @param {Number} target */ swap(from, target) { let temp = this.queue[from]; this.queue[from] = this.queue[target]; this.queue[target] = temp; } /** * Reverse the rest of the queue from specific start * @param {Number} start * @param {Number} end (default is the length of queue) */ reverse(start, end = this.queue.length - 1) { while (start < end) { this.swap(start, end); start += 1; end -= 1; } } }
JavaScript
class PouchDbStore { constructor(options) { this._options = extend({ name: "http://localhost:5984/user-roles", docId: "acl" }, options); this._db = new PouchDb(this._options); } /* Gets the ACL. @param {function(err, user)} callback - called on completion. */ get(callback) { const id = this._options.docId; this._db.get(id, (err, doc) => { if (!err) { doc = doc.list; } else if (err.status === 404) { err = null doc = []; } callback(err, doc); }); } /* Updates the ACL. @param {object} acl - The ACL record. @param {function(err)} calllback - Called on completion. */ put(acl, callback) { var doc = extend(true, {}, { list: acl }); doc._id = this._options.docId; this._db.get(doc._id, (err, oldAcl) => { if (!err) { doc._rev = oldAcl._rev this._db.put(doc, err => callback(err)); } else if (err.status === 404) { this._db.put(doc, err => callback(err)); } else { callback(new Error(JSON.stringify(err))); } }); } }
JavaScript
class ExternalClient extends IOClient_1.IOClient { constructor(baseURL, context, options) { const { authToken } = context; const headers = options && options.headers || {}; super(context, Object.assign({}, options, { baseURL, headers: Object.assign({}, headers, { 'Proxy-Authorization': authToken }) })); } }
JavaScript
class EventDispatcher { constructor() { this.listeners = {} } addEventListener = (type, callback) => { if (!(type in this.listeners)) { this.listeners[type] = [] } this.listeners[type].push(callback) return function() { this.removeEventListener(type, callback) } } removeEventListener = (type, callback) => { if (!(type in this.listeners)) { return } var stack = this.listeners[type] for (var i = 0, l = stack.length; i < l; i++) { if (stack[i] === callback) { stack.splice(i, 1) return this.removeEventListener(type, callback) } } } dispatchEvent = (event) => { if (!(event.type in this.listeners)) { return } var stack = this.listeners[event.type] event.target = this event.preventDefault = function() { event.defaultPrevented = true } for (var i = 0, l = stack.length; i < l; i++) { stack[i].call(this, event) if (event.defaultPrevented) { return event } } return event } }
JavaScript
class OnHome extends EventAbstract { /** * Execute the action to the event. */ exec() { this.event.preventDefault(); var node = this.getElement('first'); if (node) { node.focus(); } } }
JavaScript
class WatchexecWatcher extends EventEmitter { constructor(dir, opts) { super(); common.assignOptions(this, opts); this.root = path.resolve(dir); this._process = execa( 'watchexec', ['-n', '--', 'node', __dirname + '/watchexec_client.js'], { cwd: dir } ); this._process.stdout.on('data', _messageHandler.bind(this)); this._readyTimer = setTimeout(this.emit.bind(this, 'ready'), 1000); } close(callback) { clearTimeout(this._readyTimer); this.removeAllListeners(); this._process && !this._process.killed && this._process.kill(); if (typeof callback === 'function') { setImmediate(callback.bind(null, null, true)); } } /** * Transform and emit an event comming from the poller. * * @param {EventEmitter} monitor * @public */ emitEvent(type, file, stat) { this.emit(type, file, this.root, stat); this.emit(ALL_EVENT, type, file, this.root, stat); } }
JavaScript
class ErrorHandler { constructor(server) { this.server = server; this.server = server; } /** * Registers handlers for uncaught exceptions and other unhandled errors. */ register() { process.on('uncaughtException', err => { console.error('Uncaught exception'); logger_1.sendCrashResponse({ err, res: latestRes, callback: killInstance }); }); process.on('unhandledRejection', err => { console.error('Unhandled rejection'); logger_1.sendCrashResponse({ err, res: latestRes, callback: killInstance }); }); process.on('exit', code => { logger_1.sendCrashResponse({ err: new Error(`Process exited with code ${code}`), res: latestRes, silent: code === 0, }); }); ['SIGINT', 'SIGTERM'].forEach(signal => { process.on(signal, () => { logger_1.sendCrashResponse({ err: new Error(`Received ${signal}`), res: latestRes, silent: true, callback: () => { // eslint-disable-next-line no-process-exit process.exit(); }, }); }); }); } }
JavaScript
class DeviceTokenCredentials { constructor(options) { if (!options) { options = {}; } if (!options.username) { options.username = '[email protected]'; } if (!options.environment) { options.environment = AzureEnvironment.Azure; } if (!options.domain) { options.domain = azureConstants.AAD_COMMON_TENANT; } if (!options.clientId) { options.clientId = azureConstants.DEFAULT_ADAL_CLIENT_ID; } if (!options.authorizationScheme) { options.authorizationScheme = Constants.HeaderConstants.AUTHORIZATION_SCHEME; } if (!options.tokenCache) { options.tokenCache = new adal.MemoryCache(); } if (options.tokenAudience && options.tokenAudience.toLowerCase() === 'graph' && options.domain.toLowerCase() === 'common') { throw new Error('If the tokenAudience is specified as \'graph\' then \'domain\' cannot be the default \'commmon\' tenant. ' + 'It must be the actual tenant (preferrably a string in a guid format).'); } this.tokenAudience = options.tokenAudience; this.username = options.username; this.environment = options.environment; this.domain = options.domain; this.clientId = options.clientId; this.authorizationScheme = options.authorizationScheme; this.tokenCache = options.tokenCache; let authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain; this.context = new adal.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache); } retrieveTokenFromCache(callback) { let self = this; let resource = self.environment.activeDirectoryResourceId; if (self.tokenAudience) { resource = self.tokenAudience; if (self.tokenAudience.toLowerCase() === 'graph') { resource = self.environment.activeDirectoryGraphResourceId; } else if (self.tokenAudience.toLowerCase() === 'batch') { resource = self.environment.batchResourceId; } } self.context.acquireToken(resource, self.username, self.clientId, function (err, result) { if (err) return callback(err); return callback(null, result.tokenType, result.accessToken, result); }); } getToken(callback) { this.retrieveTokenFromCache(function (err, scheme, token, result) { if (err) return callback(err); return callback(null, result); }); } /** * Signs a request with the Authentication header. * * @param {webResource} The WebResource to be signed. * @param {function(error)} callback The callback function. * @return {undefined} */ signRequest(webResource, callback) { return this.retrieveTokenFromCache(function (err, scheme, token) { if (err) return callback(err); webResource.headers[Constants.HeaderConstants.AUTHORIZATION] = `${scheme} ${token}`; return callback(null); }); } }
JavaScript
class Sourceanalytix extends utils.Adapter { /** * @param {Partial<ioBroker.AdapterOptions>} [options={}] */ constructor(options) { // @ts-ignore super({ ...options, // @ts-ignore name: adapterName, }); this.on('ready', this.onReady.bind(this)); this.on('objectChange', this.onObjectChange.bind(this)); this.on('stateChange', this.onStateChange.bind(this)); // this.on('message', this.onMessage.bind(this)); this.on('unload', this.onUnload.bind(this)); // Unit and price definitions, will be loaded at adapter start. this.unitPriceDef = { unitConfig: {}, pricesConfig: {} }; this.activeStates = {}; // Array of activated states for SourceAnalytix } /** * Is called when databases are connected and adapter received configuration. */ async onReady() { try { this.log.info('Welcome to SourceAnalytix, making things ready ... '); // Block all calculation functions during startup calcBlock = true; // Load Unit definitions from helper library to workable memory array await this.definitionLoader(); // Store current data/time information to memory await this.refreshDates(); // Load global store store settings //TODO: Rename variable storeSettings.storeWeeks = this.config.store_weeks; storeSettings.storeMonths = this.config.store_months; storeSettings.storeQuarters = this.config.store_quarters; console.log('Initializing enabled states for SourceAnalytix'); // get all objects with custom configuration items const customStateArray = await this.getObjectViewAsync('custom', 'state', {}); console.log(`All states with custom items : ${JSON.stringify(customStateArray)}`); // Get all active state for Sourceanalytix if (customStateArray && customStateArray.rows) { for (let i = 0, l = customStateArray.rows.length; i < l; i++) { if (customStateArray.rows[i].value) { const id = customStateArray.rows[i].id; history[id] = customStateArray.rows[i].value; if (history[id].enabled !== undefined) { history[id] = history[id].enabled ? { 'history.0': history[id] } : null; if (!history[id]) { this.log.warn('undefined id'); continue; } } // If enabled for SourceAnalytix, handle routine to store relevant data to memory if (!history[id][this.namespace] || history[id][this.namespace].enabled === false) { // Not SourceAnalytix relevant ignore } else { await this.buildStateDetailsArray(id); } } } } // Initialize all discovered states let count = 1; for (const stateID in this.activeStates) { this.log.info(`Initialising (${count} of ${Object.keys(this.activeStates).length}) state ${stateID}`); await this.initialize(stateID); this.log.info(`Initialization (${count} of ${Object.keys(this.activeStates).length}) finished for : ${stateID}`); count = count + 1; } // Start Daily reset function by cron job await this.resetStartValues(); // Subscribe on all foreign objects to detect (de)activation of sourceanalytix enabled states this.subscribeForeignObjects('*'); // Enable all calculations with timeout of 500 ms if (delay) { clearTimeout(delay); delay = null; } delay = setTimeout(function () { calcBlock = false; }, 500); this.log.info(`SourceAnalytix initialisation finalized, will handle calculations ... for : ${JSON.stringify(this.activeStates)}`); } catch (error) { this.errorHandling('onReady', error); } } // Load calculation factors from helper library and store to memory //ToDO: Implement error handling async definitionLoader() { // Load energy definitions let catArray = ['Watt', 'Watt_hour']; const unitStore = this.unitPriceDef.unitConfig; for (const item in catArray) { const unitItem = adapterHelpers.units.electricity[catArray[item]]; for (const unitCat in unitItem) { unitStore[unitItem[unitCat].unit] = { exponent: unitItem[unitCat].exponent, category: catArray[item], }; } } // Load volumes definitions catArray = ['Liter', "Cubic_meter"]; for (const item in catArray) { const unitItem = adapterHelpers.units.volume[catArray[item]]; for (const unitCat in unitItem) { unitStore[unitItem[unitCat].unit] = { exponent: unitItem[unitCat].exponent, category: catArray[item], }; } } // Load price definition to memory const pricesConfig = this.config.pricesDefinition; const priceStore = this.unitPriceDef.pricesConfig; for (const priceDef in pricesConfig) { priceStore[pricesConfig[priceDef].cat] = { cat: pricesConfig[priceDef].cat, uDes: pricesConfig[priceDef].cat, uPpU: pricesConfig[priceDef].uPpU, uPpM: pricesConfig[priceDef].uPpM, costType: pricesConfig[priceDef].costType, unitType: pricesConfig[priceDef].unitType, }; } console.debug(`All Unit category's ${JSON.stringify(this.unitPriceDef)}`); } async buildStateDetailsArray(stateID) { try { // Load configuration as provided in state settings const stateInfo = await this.getForeignObjectAsync(stateID); if (!stateInfo) { this.log.error(`Can't get information for ${stateID}, statechange will be ignored`); return; } // Replace not allowed characters for state name const newDeviceName = stateID.split('.').join('__'); // Check if configuration for SourceAnalytix is present, trow error in case of issue in configuration if (stateInfo && stateInfo.common && stateInfo.common.custom && stateInfo.common.custom[this.namespace]) { const customData = stateInfo.common.custom[this.namespace]; const commonData = stateInfo.common; // Load start value from config to memory (avoid wrong calculations at meter reset, set to 0 if empty) const valueAtDeviceReset = (customData.valueAtDeviceReset && customData.valueAtDeviceReset !== 0) ? customData.valueAtDeviceReset : 0; // Read current known total value to memory (if present) let currentValue = await this.getCurrentTotal(stateID, newDeviceName); currentValue = currentValue ? currentValue : 0; // Check and load unit definition let useUnit = ''; if ( customData.selectedUnit !== 'automatically' && customData.selectedUnit !== 'automatisch' && customData.selectedUnit !== 'автоматически' && customData.selectedUnit !== 'automaticamente' && customData.selectedUnit !== 'automatisch' && customData.selectedUnit !== 'automatiquement' && customData.selectedUnit !== 'automaticamente' && customData.selectedUnit !== 'automáticamente' && customData.selectedUnit !== 'automatycznie' && customData.selectedUnit !== '自动' ) { useUnit = customData.selectedUnit; } else if (commonData.unit && commonData.unit !== '' && !this.unitPriceDef.unitConfig[commonData.unit] ) { this.log.error(`Automated united detection for ${stateID} failed, cannot execute calculations !`); this.log.error(`Please choose unit manually in state configuration`); return; } else if (commonData.unit && commonData.unit !== '' && this.unitPriceDef.unitConfig[commonData.unit] ) { useUnit = commonData.unit; } else if (!commonData.unit || commonData.unit === '') { this.log.error(`No unit defined for ${stateID}, cannot execute calculations !`); this.log.error(`Please choose unit manually in state configuration`); return; } // Load state price definition if (!customData.selectedPrice || customData.selectedPrice === '' || customData.selectedPrice === 'Choose') { this.log.error(`Cannot execute calculations for ${stateID} adjust settings !`); this.log.error(`No cost type defined for ${stateID}, please Select Type of calculation at state setting`); return; } if ( !this.unitPriceDef.pricesConfig[customData.selectedPrice] ) { this.log.error(`Cannot execute calculations for ${stateID} adjust settings !`); this.log.error(`Selected Type ${customData.selectedPrice} does not exist in Price Definitions`); this.log.error(`Please choose proper type for state ${stateID}`); this.log.error(`Or add price definition ${customData.selectedPrice} in adapter settings`); return; } const stateType = this.unitPriceDef.pricesConfig[customData.selectedPrice].costType; // Load state settings to memory this.activeStates[stateID] = { stateDetails: { alias: customData.alias.toString(), consumption: customData.consumption, costs: customData.costs, deviceName: newDeviceName.toString(), financialCategory: stateType, headCategory: stateType === 'earnings' ? 'delivered' : 'consumed', meter_values: customData.meter_values, name: stateInfo.common.name, stateType: customData.selectedPrice, stateUnit: useUnit, useUnit: this.unitPriceDef.pricesConfig[customData.selectedPrice].unitType, }, calcValues: { currentValue: currentValue, start_day: customData.start_day, start_month: customData.start_month, start_quarter: customData.start_quarter, start_week: customData.start_week, start_year: customData.start_year, valueAtDeviceReset: valueAtDeviceReset, }, prices: { basicPrice: this.unitPriceDef.pricesConfig[customData.selectedPrice].uPpM, unitPrice: this.unitPriceDef.pricesConfig[customData.selectedPrice].uPpU, }, }; if (stateInfo.common.unit === 'w') { this.activeStates[stateID].calcValues.previousReadingWatt = null; this.activeStates[stateID].calcValues.previousReadingWattTs = null; } this.log.debug(`[buildStateDetailsArray] of ${stateID}: with content ${JSON.stringify(this.activeStates[stateID])}`); } } catch (error) { // Send code failure to sentry this.errorHandling(`[buildStateDetailsArray] for ${stateID}`, error); } } // Create object tree and states for all devices to be handled async initialize(stateID) { try { this.log.debug(`Initialising ${stateID} with configuration ${JSON.stringify(this.activeStates[stateID])}`); // Shorten configuration details for easier access if (!this.activeStates[stateID]) { this.log.error(`Cannot handle initialisation for ${stateID}`); return; } const stateDetails = this.activeStates[stateID].stateDetails; this.log.debug(`Defined calculation attributes for ${stateID} : ${JSON.stringify(this.activeStates[stateID])}`); // Check if alias is used and update object with new naming (if changed) let alias = stateDetails.name; if (stateDetails.alias && stateDetails.alias !== '') { alias = stateDetails.alias; } this.log.debug('Name after alias renaming' + alias); // Create Device Object await this.extendObjectAsync(stateDetails.deviceName, { type: 'device', common: { name: alias }, native: {}, }); // create states for day value storage for (const x in weekdays) { if (this.config.currentYearDays === true) { await this.doLocalStateCreate(stateID, `currentWeek.${weekdays[x]}`, weekdays[x], false, false, true) } else if (stateDeletion) { this.log.debug(`Deleting states for week ${weekdays[x]} (if present)`); await this.doLocalStateCreate(stateID, `currentWeek.${weekdays[x]}`, weekdays[x], false, true,true); } if (this.config.currentYearPrevious === true) { await this.doLocalStateCreate(stateID, `previousWeek.${weekdays[x]}`, weekdays[x], false, false, true) } else if (stateDeletion) { this.log.debug(`Deleting states for week ${weekdays[x]} (if present)`); await this.doLocalStateCreate(stateID, `previousWeek.${weekdays[x]}`, weekdays[x], false, true,true); } } // create states for weeks for (let y = 1; y < 54; y++) { let weekNr; if (y < 10) { weekNr = '0' + y; } else { weekNr = y.toString(); } const weekRoot = `weeks.${weekNr}`; if (this.config.store_weeks) { this.log.debug(`Creating states for week ${weekNr}`); await this.doLocalStateCreate(stateID, weekRoot, weekNr); } else if (stateDeletion) { this.log.debug(`Deleting states for week ${weekNr} (if present)`); await this.doLocalStateCreate(stateID, weekRoot, weekNr, false, true); } } // create states for months for (const month in months) { const monthRoot = `months.${months[month]}`; if (this.config.store_months) { this.log.debug(`Creating states for month ${month}`); await this.doLocalStateCreate(stateID, monthRoot, months[month]); } else if (stateDeletion) { this.log.debug(`Deleting states for month ${month} (if present)`); await this.doLocalStateCreate(stateID, monthRoot, months[month], false, true); } } // create states for quarters for (let y = 1; y < 5; y++) { const quarterRoot = `quarters.Q${y}`; if (this.config.store_quarters) { this.log.debug(`Creating states for quarter ${quarterRoot}`); await this.doLocalStateCreate(stateID, quarterRoot, `Q${y}`); } else if (stateDeletion) { this.log.debug(`Deleting states for quarter ${quarterRoot} (if present)`); await this.doLocalStateCreate(stateID, quarterRoot, quarterRoot, false, true); } } // Create basic current states for (const state of basicStates) { await this.doLocalStateCreate(stateID, state, state, false,false,true); } // Create basic current states for previous periods if (this.config.currentYearPrevious){ for (const state of basicPreviousStates) { await this.doLocalStateCreate(stateID, state, state, false,false,true); } } // Create state for current reading const stateName = 'Current_Reading'; await this.doLocalStateCreate(stateID, stateName, 'Current Reading', true); // Handle calculation const value = await this.getForeignStateAsync(stateID); this.log.debug(`First time calc result after initialising`); if (value) { await this.calculationHandler(stateID, value); } // Subscribe state, every state change will trigger calculation now automatically this.subscribeForeignStates(stateID) } catch (error) { this.log.error(`[initialize failed for ${stateID}] error: ${error.message}, stack: ${error.stack}`); // Send code failure to sentry this.errorHandling(`[buildStateDetailsArray] for ${stateID}`, error); } } /** * Is called if an object changes to ensure (de-) activation of calculation or update configuration settings * @param {string} id * @param {ioBroker.Object | null | undefined} obj */ async onObjectChange(id, obj) { if (calcBlock) return; // cancel operation if calculation block is activate try { const stateID = id; // Check if object is activated for SourceAnalytix if (obj && obj.common) { // @ts-ignore : from does exist on states // if (obj.from === `system.adapter.${this.namespace}`) return; // Ignore object change if cause by SourceAnalytix to prevent overwrite // Verify if custom information is available regarding SourceAnalytix if (obj.common.custom && obj.common.custom[this.namespace] && obj.common.custom[this.namespace].enabled) { // ignore object changes when caused by SA (memory is handled internally) // if (obj.from !== `system.adapter.${this.namespace}`) { this.log.debug(`Object array of SourceAnalytix activated state changed : ${JSON.stringify(obj)} stored config : ${JSON.stringify(this.activeStates)}`); const newDeviceName = stateID.split('.').join('__'); // Verify if the object was already activated, if not initialize new device if (!this.activeStates[stateID]) { this.log.debug(`Enable SourceAnalytix for : ${stateID}`); await this.buildStateDetailsArray(id); this.log.debug(`Active state array after enabling ${stateID} : ${JSON.stringify(this.activeStates)}`); await this.initialize(stateID); } else { this.log.debug(`Updated SourceAnalytix configuration for : ${stateID}`); await this.buildStateDetailsArray(id); this.log.debug(`Active state array after updating configuration of ${stateID} : ${JSON.stringify(this.activeStates)}`); await this.initialize(stateID); } } else if (this.activeStates[stateID]) { this.activeStates[stateID] = null; this.log.info(`Disabled SourceAnalytix for : ${stateID}`); this.log.debug(`Active state array after deactivation of ${stateID} : ${JSON.stringify(this.activeStates)}`); this.unsubscribeForeignStates(stateID); } } else { // Object change not related to this adapter, ignoring } } catch (error) { this.log.error(`[onObjectChange ${JSON.stringify(obj)}] error: ${error.message}, stack: ${error.stack}`); // Send code failure to sentry this.errorHandling(`[onObjectChange] for ${id}`, error); } } /** * Is called if a subscribed state changes * @param {string} id * @param {ioBroker.State | null | undefined} state */ onStateChange(id, state) { if (calcBlock) return; // cancel operation if global calculation block is activate try { if (state) { // The state was changed this.log.debug(`state ${id} changed : ${JSON.stringify(state)} SourceAnalytix calculation executed`); //ToDo: Implement x ignore time (configurable) to avoid overload of unneeded calculations // Avoid unneeded calculation if value is equal to known value in memory if (previousStateVal[id] !== state.val) { this.calculationHandler(id, state); previousStateVal[id] = state.val; } else { this.log.debug(`Update osf state ${id} received with equal value ${state.val} ignoring`); } } } catch (error) { this.log.error(`[onStateChane ${id}] error: ${error.message}, stack: ${error.stack}`); this.errorHandling(`[onObjectChange] for ${id}`, error); } } // Function to calculate current week number getWeekNumber(d) { // Copy date so don't modify original d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); // Get first day of year const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1)); // Calculate full weeks to nearest Thursday // @ts-ignore subtracting dates is fine let weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7).toString(); if (weekNo.length === 1) { weekNo = '0' + weekNo; } // Return week number return weekNo; } async resetStartValues() { try { const resetDay = new schedule('0 0 * * *', async () => { // const resetDay = new schedule('* * * * *', async () => { // testing schedule calcBlock = true; // Pause all calculations const beforeReset = await this.refreshDates(); // Reset date values in memory // Read state array and write Data for every active state for (const stateID in this.activeStates) { this.log.info(`Reset start values for : ${stateID}`) console.log(stateID); try { const stateValues = this.activeStates[stateID].calcValues; const stateDetails = this.activeStates[stateID].stateDetails; // get current meter value const reading = this.activeStates[stateID].calcValues.currentValue; if (reading === null || reading === undefined) continue; this.log.debug(`Memory values for ${stateID} before reset : ${JSON.stringify(this.activeStates[stateID])}`); this.log.debug(`Current known state values : ${JSON.stringify(stateValues)}`) // Prepare custom object and store correct values const obj = {}; obj.common = {}; obj.common.custom = {}; obj.common.custom[this.namespace] = { currentValue: reading, start_day: reading, start_week: beforeReset.week === actualDate.week ? stateValues.start_week : reading, start_month: beforeReset.month === actualDate.month ? stateValues.start_month : reading, start_quarter: beforeReset.quarter === actualDate.quarter ? stateValues.start_quarter : reading, start_year: beforeReset.year === actualDate.year ? stateValues.start_year : reading, valueAtDeviceReset: stateValues.valueAtDeviceReset !== undefined ? stateValues.valueAtDeviceReset : 0 }; // Extend object with start value [type] & update memory obj.common.custom[this.namespace].start_day = reading; this.activeStates[stateID].calcValues = obj.common.custom[this.namespace]; //At week reset ensure current week value are moved to previous week and current set to 0 if (beforeReset.week !== actualDate.week){ for (const x in weekdays) { if (this.config.currentYearDays ) { // Handle consumption states consumption states if (stateDetails.consumption) { switch (stateDetails.headCategory) { case 'consumed': await this.setPreviousValues(`${stateID}.currentYear.consumed.currentWeek${weekdays[x]}`, `${stateID}.currentYear.consumed.previousWeek.${weekdays[x]}`); await this.setStateAsync(`${stateID}.currentYear.consumed.currentWeek${weekdays[x]}`, {val : 0, ack: true}) break; case 'delivered': await this.setPreviousValues(`${stateID}.currentYear.delivered.currentWeek.${weekdays[x]}`, `${stateID}.currentYear.delivered.previousWeek.${weekdays[x]}`); await this.setStateAsync(`${stateID}.currentYear.delivered.currentWeek${weekdays[x]}`, {val : 0, ack: true}) break; default: } } // Handle financial states consumption states switch (stateDetails.financialCategory) { case 'costs': await this.setPreviousValues(`${stateID}.currentYear.costs.currentWeek.${weekdays[x]}`, `${stateID}.currentYear.costs.previousWeek.${weekdays[x]}`); await this.setStateAsync(`${stateID}.currentYear.costs.currentWeek${weekdays[x]}`, {val : 0, ack: true}) break; case 'earnings': await this.setPreviousValues(`${stateID}.currentYear.earnings.currentWeek.${weekdays[x]}`, `${stateID}.currentYear.earnings.previousWeek.${weekdays[x]}`); await this.setStateAsync(`${stateID}.currentYear.earnings.currentWeek${weekdays[x]}`, {val : 0, ack: true}) break; default: } // Handle meter reading states await this.setPreviousValues(`${stateID}.currentYear.meterReadings.currentWeek.${weekdays[x]}`, `${stateID}.currentYear.meterReadings.previousWeek.${weekdays[x]}`); await this.setStateAsync(`${stateID}.currentYear.meterReadings.currentWeek${weekdays[x]}`, {val : 0, ack: true}) } } } // Handle all "previous states" if (this.config.currentYearPrevious) { // Handle consumption states consumption states if (stateDetails.consumption) { switch (stateDetails.headCategory) { case 'consumed': if (beforeReset.day !== actualDate.day) { await this.setPreviousValues(`${stateID}.currentYear.consumed.01_currentDay`, `${stateID}.currentYear.consumed.01_previousDay`); } if (beforeReset.week !== actualDate.week) { await this.setPreviousValues(`${stateID}.currentYear.consumed.02_currentWeek`,`${stateID}.currentYear.consumed.02_previousWeek`); } if (beforeReset.month !== actualDate.month) { await this.setPreviousValues(`${stateID}.currentYear.consumed.03_currentMonth`, `${stateID}.currentYear.consumed.03_previousMonth`); } if (beforeReset.quarter !== actualDate.quarter) { await this.setPreviousValues(`${stateID}.currentYear.consumed.04_currentQuarter`, `${stateID}.currentYear.consumed.04_previousQuarter`); } if (beforeReset.year !== actualDate.year) { await this.setPreviousValues(`${stateID}.currentYear.consumed.05_currentYear`, `${stateID}.currentYear.consumed.05_previousYear`); } break; case 'delivered': if (beforeReset.day !== actualDate.day) { await this.setPreviousValues(`${stateID}.currentYear.delivered.01_currentDay`, `${stateID}.currentYear.delivered.01_previousDay`); } if (beforeReset.week !== actualDate.week) { await this.setPreviousValues(`${stateID}.currentYear.delivered.02_currentWeek`, `${stateID}.currentYear.delivered.02_previousWeek`); } if (beforeReset.month !== actualDate.month) { await this.setPreviousValues(`${stateID}.currentYear.delivered.03_currentMonth`, `${stateID}.currentYear.delivered.03_previousMonth`); } if (beforeReset.quarter !== actualDate.quarter) { await this.setPreviousValues(`${stateID}.currentYear.delivered.04_currentQuarter`, `${stateID}.currentYear.delivered.04_previousQuarter`); } if (beforeReset.year !== actualDate.year) { await this.setPreviousValues(`${stateID}.currentYear.delivered.05_currentYear`, `${stateID}.currentYear.delivered.05_previousYear`); } break; default: } } // Handle financial states consumption states switch (stateDetails.financialCategory) { case 'costs': if (beforeReset.day !== actualDate.day) { await this.setPreviousValues(`${stateID}.currentYear.costs.01_currentDay`, `${stateID}.currentYear.costs.01_previousDay`); } if (beforeReset.week !== actualDate.week) { await this.setPreviousValues(`${stateID}.currentYear.costs.02_currentWeek`, `${stateID}.currentYear.costs.02_previousWeek`); } if (beforeReset.month !== actualDate.month) { await this.setPreviousValues(`${stateID}.currentYear.costs.03_currentMonth`, `${stateID}.currentYear.costs.03_previousMonth`); } if (beforeReset.quarter !== actualDate.quarter) { await this.setPreviousValues(`${stateID}.currentYear.costs.04_currentQuarter`, `${stateID}.currentYear.costs.04_previousQuarter`); } if (beforeReset.year !== actualDate.year) { await this.setPreviousValues(`${stateID}.currentYear.costs.05_currentYear`, `${stateID}.currentYear.costs.05_previousYear`); } break; case 'earnings': if (beforeReset.day !== actualDate.day) { await this.setPreviousValues(`${stateID}.currentYear.costs.01_currentDay`, `${stateID}.currentYear.costs.01_previousDay`); } if (beforeReset.week !== actualDate.week) { await this.setPreviousValues(`${stateID}.currentYear.costs.02_currentWeek`, `${stateID}.currentYear.earnings.02_previousWeek`); } if (beforeReset.month !== actualDate.month) { await this.setPreviousValues(`${stateID}.currentYear.costs.03_currentMonth`, `${stateID}.currentYear.earnings.03_previousMonth`); } if (beforeReset.quarter !== actualDate.quarter) { await this.setPreviousValues(`${stateID}.currentYear.costs.04_currentQuarter`, `${stateID}.currentYear.earnings.04_previousQuarter`); } if (beforeReset.year !== actualDate.year) { await this.setPreviousValues(`${stateID}.currentYear.costs.05_currentYear`, `${stateID}.currentYear.earnings.05_previousYear`); } break; default: } //ToDo: Think / discuss what to do with meter readings // Handle meter reading states // if (this.config.currentYearPrevious) await this.setStateAsync(`${stateID}.currentYear.meterReadings.previousWeek.${weekdays[x]}`, { // val: await this.getStateAsync(`${stateID}.currentYear.meterReadings.previousWeek.${weekdays[x]}`), // ack: true // }) } await this.extendForeignObject(stateID, obj); this.log.info(`Memory values for ${stateID} after reset : ${JSON.stringify(this.activeStates[stateID])}`); const value = await this.getForeignStateAsync(stateID) this.calculationHandler(stateID, value); } catch (error) { this.log.error(`[reset values error for ${stateID}: ${error.message}, stack: ${error.stack}`); // Send code failure to sentry this.errorHandling(`[resetStartValues] for ${stateID}`, error); } } // Enable all calculations with timeout of 500 ms if (delay) { clearTimeout(delay); delay = null; } delay = setTimeout(function () { calcBlock = false; }, 500); }); resetDay.start(); } catch (error) { this.log.error(`[reset values error: ${error.message}, stack: ${error.stack}`); // Send code failure to sentry this.errorHandling(`[resetStartValues]`, error); calcBlock = false; // Continue all calculations } } /** * Function to handle previousState values * @param {string} [currentState]- RAW state ID currentValue * @param {string} previousState - RAW state ID currentValue */ async setPreviousValues(currentState, previousState) { // Only set previous state if option is chosen if (this.config.currentYearPrevious) { // Check if function input is correctly if (currentState && previousState) { // Get value of currentState const currentVal = await this.getStateAsync(currentState); if (currentVal) { // Set current value to previous state await this.setStateAsync(previousState, { val: currentVal.val, ack: true }) } } else { this.log.debug(``) } } } /** * Function to handle state creation * @param {string} [stateID]- RAW state ID of monitored state * @param {string} stateRoot - Root folder location * @param {string} name - Name of state (also used for state ID ! * @param {boolean} [atDeviceRoot=FALSE] - store value at root instead of Year-Folder * @param {boolean} [deleteState=FALSE] - Set to true will delete the state * @param {boolean} [isCurrent=FALSE] - Store value in current Year */ async doLocalStateCreate(stateID, stateRoot, name, atDeviceRoot, deleteState, isCurrent) { try { const stateDetails = this.activeStates[stateID].stateDetails; const dateRoot = isCurrent ? `currentYear` : actualDate.year; let stateName = null; // Common object content const commonData = { name: name, type: 'number', role: 'value', read: true, write: false, unit: stateDetails.useUnit, def: 0, }; // Define if state should be created at root level if (atDeviceRoot) { stateName = `${stateDetails.deviceName}.${stateRoot}`; this.log.debug(`Try creating states ${stateName} Data : ${JSON.stringify(commonData)}`); await this.localSetObject(stateName, commonData); } else { // Create consumption states if (!deleteState && stateDetails.consumption) { switch (stateDetails.headCategory) { case 'consumed': await this.localSetObject(`${stateDetails.deviceName}.${dateRoot}.consumed.${stateRoot}`, commonData); await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.delivered.${stateRoot}`); break; case 'delivered': await this.localSetObject(`${stateDetails.deviceName}.${dateRoot}.delivered.${stateRoot}`, commonData); await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.consumed.${stateRoot}`); break; default: } } else if (deleteState || !stateDetails.consumption) { // If state deletion chosen, clean everything up else define state name await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.consumed.${stateRoot}`); this.log.debug(`Try deleting state ${stateDetails.deviceName}.${dateRoot}.consumed.${stateRoot}`); await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.delivered.${stateRoot}`); this.log.debug(`Try deleting state ${stateDetails.deviceName}.${dateRoot}.delivered.${stateRoot}`); } // Create MeterReading states if (!deleteState && stateDetails.meter_values) { // Do not create StateRoot values if (!basicStates.includes(stateRoot)) { await this.localSetObject(`${stateDetails.deviceName}.${dateRoot}.meterReadings.${stateRoot}`, commonData); } } else if (deleteState || !stateDetails.meter_values) { // If state deletion chosen, clean everything up else define state name await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.meterReadings.${stateRoot}`); } // Create cost states if (!deleteState && stateDetails.costs) { commonData.unit = '€'; // Switch Unit to money switch (stateDetails.financialCategory) { case 'costs': // await this.ChannelCreate(device, head_category, head_category); await this.localSetObject(`${stateDetails.deviceName}.${dateRoot}.costs.${stateRoot}`, commonData); await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.earnings.${stateRoot}`); break; case 'earnings': // await this.ChannelCreate(device, head_category, head_category); await this.localSetObject(`${stateDetails.deviceName}.${dateRoot}.earnings.${stateRoot}`, commonData); await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.costs.${stateRoot}`); break; default: } } else if (!stateDetails.costs) { // If state deletion chosen, clean everything up else define state name await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.costs.${stateRoot}`); this.log.debug(`Try deleting state ${stateDetails.deviceName}.${dateRoot}.costs.${stateRoot}`); await this.localDeleteState(`${stateDetails.deviceName}.${dateRoot}.earnings.${stateRoot}`); this.log.debug(`Try deleting state ${stateDetails.deviceName}.${dateRoot}.earnings.${stateRoot}`); } } } catch (error) { this.log.error(`[localStateCreate ${stateID}] error: ${error.message}, stack: ${error.stack}`); // Send code failure to sentry this.errorHandling(`[localStateCreate] for ${stateID}`, error); } } // Set object routine to simplify code //TODO: Check with JS-Controller 3.x if check is still required async localSetObject(stateName, commonData) { await this.setObjectNotExistsAsync(stateName, { type: 'state', common: commonData, native: {}, }); // Ensure name and unit changes are propagated await this.extendObjectAsync(stateName, { type: 'state', common: { name: commonData.name, unit: commonData.unit, }, native: {}, }); } async localDeleteState(state) { try { if (stateDeletion) { const obj = await this.getObjectAsync(state); if (obj) { await this.delObjectAsync(state); } } } catch (error) { // do nothing } } // Calculation handler async calculationHandler(stateID, value) { try { const calcValues = this.activeStates[stateID].calcValues; const stateDetails = this.activeStates[stateID].stateDetails; const statePrices = this.activeStates[stateID].prices; const currentCath = this.unitPriceDef.unitConfig[stateDetails.stateUnit].category; const targetCath = this.unitPriceDef.unitConfig[stateDetails.useUnit].category; const date = new Date(); this.log.debug(`Calculation for ${stateID} with values : ${JSON.stringify(value)} and configuration : ${JSON.stringify(this.activeStates[stateID])}`); console.log(`Calculation for ${stateID} with value : ${JSON.stringify(value)}`); let stateName = `${this.namespace}.${stateDetails.deviceName}`; // Define proper calculation value let reading; // Convert volume liter to cubic //TODO: Should be handle by library if (currentCath === 'Watt'){ // Convert watt to watt hours reading = await this.wattToWattHour(stateID, value); } else if (currentCath === 'Liter' && targetCath === 'Cubic_meter' ) { reading = value.val / 1000; } else if (currentCath === 'Cubic_meter' && targetCath === 'Liter' ) { reading = value.val * 1000; } else { reading = value.val } const currentExponent = this.unitPriceDef.unitConfig[stateDetails.stateUnit].exponent; const targetExponent = this.unitPriceDef.unitConfig[stateDetails.useUnit].exponent; if (reading && typeof(reading) === 'number') { reading = reading * Math.pow(10, (currentExponent - targetExponent)); if (currentCath === 'Watt'){ // Add calculated watt reading to stored totals reading = reading + calcValues.currentValue; } } else { reading = value.val * Math.pow(10, (currentExponent - targetExponent)); } this.log.debug(`Recalculated value ${reading}`); if (reading === null || reading === undefined) return; // Detect meter reset & ensure Cumulative calculation if (reading < calcValues.currentValue && currentCath !== 'Watt') { this.log.debug(`New reading ${reading} lower than stored value ${calcValues.currentValue}`); // Threshold of 1 to detect reset of meter if (reading < 1 && !deviceResetHandled[stateID]) { this.log.warn(`Device reset detected for ${stateID} store current value ${calcValues.currentValue} to value of reset`); deviceResetHandled[stateID] = true; // Prepare object array for extension const obj = {}; obj.common = {}; obj.common.custom = {}; obj.common.custom[this.namespace] = {}; // Extend valueAtDeviceReset with currentValue at object and memory obj.common.custom[this.namespace].valueAtDeviceReset = calcValues.currentValue; this.activeStates[stateID].calcValues.valueAtDeviceReset = calcValues.currentValue; //TODO: Add all attributes to extend object ensuring propper obj values await this.extendForeignObject(stateID, obj); // Calculate proper reading reading = reading + this.activeStates[stateID].calcValues.valueAtDeviceReset; } else { this.log.debug(`Adding ${reading} to stored value ${this.activeStates[stateID].calcValues.valueAtDeviceReset}`); // Add current reading to value in memory reading = reading + this.activeStates[stateID].calcValues.valueAtDeviceReset; this.log.debug(`Calculation outcome ${reading} valueAtDeviceReset ${this.activeStates[stateID].calcValues.valueAtDeviceReset}`); // Reset device reset variable if (reading > 1) deviceResetHandled[stateID] = false; } } else { this.log.debug(`New reading ${reading} bigger than stored value ${calcValues.currentValue} processing normally`); } this.log.debug(`Set calculated value ${reading} on state : ${stateDetails.deviceName}.Current_Reading}`); // Update current value to memory this.activeStates[stateID]['calcValues'].currentValue = reading; this.log.debug(`ActiveStatesArray ${JSON.stringify(this.activeStates[stateID]['calcValues'])})`) await this.setStateChangedAsync(`${stateDetails.deviceName}.Current_Reading`, { val: await this.roundDigits(reading), ack: true }); //TODO; implement counters // // Handle impuls counters // if (obj_cust.state_type == 'impulse'){ // // cancel calculation in case of impuls counter // return; // } //TODO: Implement periods // temporary set to Zero, this value will be used later to handle period calculations const reading_start = 0; //obj_cust.start_meassure; this.log.debug(`previousCalculationRounded for ${stateID} : ${JSON.stringify(previousCalculationRounded)}`); // Store meter values if (stateDetails.meter_values === true) { // Always write generic meterReadings for current year stateName = `${this.namespace}.${stateDetails.deviceName}.currentYear.meterReadings`; const readingRounded = await this.roundDigits(reading); // Weekdays if (readingRounded){ await this.setStateChangedAsync(`${stateName}.currentWeek.${weekdays[date.getDay()]}`, { val: readingRounded, ack: true }); stateName = `${`${this.namespace}.${stateDetails.deviceName}`}.${actualDate.year}.meterReadings`; if (storeSettings.storeWeeks) await this.setStateChangedAsync(`${stateName}.weeks.${actualDate.week}`, { val: readingRounded, ack: true }); // Month if (storeSettings.storeMonths) await this.setStateChangedAsync(`${stateName}.months.${actualDate.month}`, { val: readingRounded, ack: true }); // Quarter if (storeSettings.storeQuarters) await this.setStateChangedAsync(`${stateName}.quarters.Q${actualDate.quarter}`, { val: readingRounded, ack: true }); } } const calculations = { consumedDay: ((reading - calcValues.start_day) - reading_start), consumedWeek: ((reading - calcValues.start_week) - reading_start), consumedMonth: ((reading - calcValues.start_month) - reading_start), consumedQuarter: ((reading - calcValues.start_quarter) - reading_start), consumedYear: ((reading - calcValues.start_year) - reading_start), priceDay: statePrices.unitPrice * ((reading - calcValues.start_day) - reading_start), priceWeek: statePrices.unitPrice * ((reading - calcValues.start_week) - reading_start), priceMonth: statePrices.unitPrice * ((reading - calcValues.start_month) - reading_start), priceQuarter: statePrices.unitPrice * ((reading - calcValues.start_quarter) - reading_start), priceYear: statePrices.unitPrice * ((reading - calcValues.start_year) - reading_start), }; const calculationRounded = { consumedDay: await this.roundDigits(calculations.consumedDay), consumedWeek: await this.roundDigits(calculations.consumedWeek), consumedMonth: await this.roundDigits(calculations.consumedMonth), consumedQuarter: await this.roundDigits(calculations.consumedQuarter), consumedYear: await this.roundDigits(calculations.consumedYear), priceDay: await this.roundCosts(statePrices.unitPrice * calculations.consumedDay), priceWeek: await this.roundCosts(statePrices.unitPrice * calculations.consumedWeek), priceMonth: await this.roundCosts(statePrices.unitPrice * calculations.consumedMonth), priceQuarter: await this.roundCosts(statePrices.unitPrice * calculations.consumedQuarter), priceYear: await this.roundCosts(statePrices.unitPrice * calculations.consumedYear), }; // Store consumption if (stateDetails.consumption) { // Always write generic meterReadings for current year stateName = `${this.namespace}.${stateDetails.deviceName}.currentYear.${stateDetails.headCategory}`; // Generic await this.setStateChangedAsync(`${stateName}.01_currentDay`, { val: calculationRounded.consumedDay, ack: true }); await this.setStateChangedAsync(`${stateName}.02_currentWeek`, { val: calculationRounded.consumedWeek, ack: true }); await this.setStateChangedAsync(`${stateName}.03_currentMonth`, { val: calculationRounded.consumedMonth, ack: true }); await this.setStateChangedAsync(`${stateName}.04_currentQuarter`, { val: calculationRounded.consumedQuarter, ack: true }); await this.setStateChangedAsync(`${stateName}.05_currentYear`, { val: calculationRounded.consumedYear, ack: true }); // Weekdays await this.setStateChangedAsync(`${stateName}.currentWeek.${weekdays[date.getDay()]}`, { val: calculationRounded.consumedDay, ack: true }); stateName = `${this.namespace}.${stateDetails.deviceName}.${actualDate.year}.${stateDetails.headCategory}`; // Week if (storeSettings.storeWeeks) await this.setStateChangedAsync(`${stateName}.weeks.${actualDate.week}`, { val: calculationRounded.consumedWeek, ack: true }); // Month if (storeSettings.storeMonths) await this.setStateChangedAsync(`${stateName}.months.${actualDate.month}`, { val: calculationRounded.consumedMonth, ack: true }); // Quarter if (storeSettings.storeQuarters) await this.setStateChangedAsync(`${stateName}.quarters.${actualDate.quarter}`, { val: calculationRounded.consumedQuarter, ack: true }); } // Store prices if (stateDetails.costs) { stateName = `${this.namespace}.${stateDetails.deviceName}.currentYear.${stateDetails.financialCategory}`; // Generic await this.setStateChangedAsync(`${stateName}.01_currentDay`, { val: calculationRounded.priceDay, ack: true }); await this.setStateChangedAsync(`${stateName}.02_currentWeek`, { val: calculationRounded.priceWeek, ack: true }); await this.setStateChangedAsync(`${stateName}.03_currentMonth`, { val: calculationRounded.priceMonth, ack: true }); await this.setStateChangedAsync(`${stateName}.04_currentQuarter`, { val: calculationRounded.priceQuarter, ack: true }); await this.setStateChangedAsync(`${stateName}.05_currentYear`, { val: calculationRounded.priceYear, ack: true }); // Weekdays await this.setStateChangedAsync(`${stateName}.currentWeek.${weekdays[date.getDay()]}`, { val: calculationRounded.priceDay, ack: true }); stateName = `${this.namespace}.${stateDetails.deviceName}.${actualDate.year}.${stateDetails.financialCategory}`; // Week if (storeSettings.storeWeeks) await this.setStateChangedAsync(`${stateName}.weeks.${actualDate.week}`, { val: calculationRounded.priceWeek, ack: true }); // Month if (storeSettings.storeMonths) await this.setStateChangedAsync(`${stateName}.months.${actualDate.month}`, { val: calculationRounded.priceMonth, ack: true }); // Quarter if (storeSettings.storeQuarters) await this.setStateChangedAsync(`${stateName}.quarters.${actualDate.quarter}`, { val: calculationRounded.priceQuarter, ack: true }); } // Store results of current calculation to memory //ToDo : Build JSON array for current values to have widget & information easy accessible in vis previousCalculationRounded[stateID] = calculationRounded; this.log.debug(`Calculation for ${stateID} : ${JSON.stringify(calculations)}`); this.log.debug(`CalculationRounded for ${stateID} : ${JSON.stringify(calculationRounded)}`); this.log.debug(`Meter Calculation executed consumed data for ${stateID} : ${JSON.stringify(calculationRounded)}`); } catch (error) { this.log.error(`[calculationHandler ${stateID}] error: ${error.message}, stack: ${error.stack}`); this.errorHandling('calculationHandler', error) } } /** * @param {number} [value] - Number to round with , separator */ async roundDigits(value) { let rounded try { rounded = Number(value); rounded = Math.round(rounded * 1000) / 1000; this.log.debug(`roundDigits with ${value} rounded ${rounded}`); if (!rounded) return value; return rounded; } catch (error) { this.log.error(`[roundDigits ${value}`); this.errorHandling('roundDigits', error) rounded = value return rounded; } } /** * @param {number} [value] - Number to round with . separator */ async roundCosts(value) { try { let rounded = Number(value); rounded = Math.round(rounded * 100) / 100; this.log.debug(`roundCosts with ${value} rounded ${rounded}`); if(!rounded) return value; return rounded; } catch (error) { this.log.error(`[roundCosts ${value}`); this.errorHandling('roundCosts', error) } } /** * @param {string} [stateID]- ID of state * @param {object} [value] - Current value in wH */ async wattToWattHour(stateID, value) { try { const calcValues = this.activeStates[stateID].calcValues; this.log.debug(`Watt to kWh for ${stateID} current reading : ${value.val} previousReading : ${JSON.stringify(this.activeStates[stateID])}`); // Prepare needed data to handle calculations const readingData = { previousReadingWatt: Number(calcValues.previousReadingWatt), previousReadingWattTs: Number(calcValues.previousReadingWattTs), currentReadingWatt: Number(value.val), currentReadingWattTs: Number(value.ts), }; // Prepare function return let calckWh; if (readingData.previousReadingWatt && readingData.previousReadingWattTs) { // Calculation logic W to kWh calckWh = (((readingData.currentReadingWattTs - readingData.previousReadingWattTs)) * readingData.previousReadingWatt / 3600000); this.log.debug(`Calc kWh current timing : ${calckWh} adding current value ${readingData.currentValuekWh}`); // Update timestamp current reading to memory this.activeStates[stateID]['calcValues'].previousReadingWatt = readingData.currentReadingWatt; this.activeStates[stateID]['calcValues'].previousReadingWattTs = readingData.currentReadingWattTs; } else { // Update timestamp current reading to memory this.activeStates[stateID]['calcValues'].previousReadingWatt = readingData.currentReadingWatt; this.activeStates[stateID]['calcValues'].previousReadingWattTs = readingData.currentReadingWattTs; calckWh = calcValues.currentValue; } this.log.debug(`Watt to kWh outcome for ${stateID} : ${JSON.stringify(this.activeStates[stateID].calcValues)}`); return calckWh; } catch (error) { this.log.error(`[wattToKwh ${stateID}] vale ${value} error: ${error.message}, stack: ${error.stack}`); this.errorHandling('wattToWattHour', error) } } /** * @param {string} [stateID]- ID of state * @param {object} [deviceName] - Name of device */ async getCurrentTotal(stateID, deviceName) { let calckWh; // Check if previous reading exist in state const previousReadingV4 = await this.getStateAsync(`${deviceName}.Current_Reading`); // temporary indicate source of kWh value let valueSource; // Check if previous reading exist in state (routine for <4 version ) if (!previousReadingV4 || previousReadingV4.val === 0) { const previousReadingVold = await this.getStateAsync(`${deviceName}.Meter_Readings.Current_Reading`); if (!previousReadingVold || previousReadingVold.val === 0) { calckWh = 0; } else { calckWh = previousReadingVold.val; // temporary indicate source of kWh value valueSource = 'Version < 4'; this.log.debug(`for state ${stateID} Previous watt calculated reading used ${valueSource} from ${JSON.stringify(previousReadingVold)}`); } } else { calckWh = previousReadingV4.val; // use previous stored value valueSource = 'Version > 4'; this.log.debug(`for state ${stateID} Previous watt calculated reading used ${valueSource} from ${JSON.stringify(previousReadingV4)}`); } return calckWh; } // Daily reset of start values for states async refreshDates() { const today = new Date(); // Get current date in Unix time format // Store current used data memory const previousDates = { // day: actualDate.day, week: actualDate.week, month: actualDate.month, quarter: actualDate.quarter, year: actualDate.year }; // actualDate.Day = weekdays[today.getDay()]; actualDate.week = await this.getWeekNumber(new Date()); actualDate.month = months[today.getMonth()]; actualDate.quarter = Math.floor((today.getMonth() + 3) / 3); actualDate.year = (new Date().getFullYear()); return previousDates; } /** * @param {string} [codePart]- Message Prefix * @param {object} [error] - Sentry message */ errorHandling(codePart, error) { this.log.error(`[${codePart}] error: ${error.message}, stack: ${error.stack}`); if (this.supportsFeature && this.supportsFeature('PLUGINS') && sendSentry) { const sentryInstance = this.getPluginInstance('sentry'); if (sentryInstance) { sentryInstance.getSentryObject().captureException(error); } } } /** * Is called when adapter shuts down - callback has to be called under any circumstances! * @param {() => void} callback */ onUnload(callback) { try { this.log.info(`SourceAnalytix stopped, now you have to calculate by yourself :'( ...`); callback(); } catch (e) { callback(); } } }
JavaScript
class ChromeDriver { static async build({ responsive, port, headless, language, proxyUrl }) { const args = ["load-extension=build/chrome"]; if (responsive) args.push("--auto-open-devtools-for-tabs"); if (headless) args.push("--headless"); if (language) args.push(`--lang=${language}`); if (proxyUrl) args.push("ignore-certificate-errors"); const options = new chrome.Options().addArguments(args); if (proxyUrl) { options.setProxy(proxy.manual({ http: proxyUrl, https: proxyUrl })); } const builder = new Builder().forBrowser("chrome").setChromeOptions(options); if (port) { const service = new chrome.ServiceBuilder().setPort(port); builder.setChromeService(service); } const driver = builder.build(); const chromeDriver = new ChromeDriver(driver); const extensionId = await chromeDriver.getExtensionIdByName("Edge Translate"); return { driver, extensionId, extensionUrl: `chrome-extension://${extensionId}`, }; } /** * @constructor * @param {!ThenableWebDriver} driver - a {@code WebDriver} instance */ constructor(driver) { this._driver = driver; } /** * Returns the extension ID for the given extension name * @param {string} extensionName - the extension name * @returns {Promise<string|undefined>} the extension ID */ async getExtensionIdByName(extensionName) { await this._driver.get("chrome://extensions"); // Wait for the extension to load. await new Promise((resolve) => setTimeout(resolve, 500)); return await this._driver.executeScript(` const extensions = document.querySelector("extensions-manager").shadowRoot .querySelector("extensions-item-list").shadowRoot .querySelectorAll("extensions-item") for (let i = 0; i < extensions.length; i++) { const extension = extensions[i].shadowRoot const name = extension.querySelector('#name').textContent if (name === "${extensionName}") { return extensions[i].getAttribute("id") } } return undefined `); } }
JavaScript
class Header extends React.Component { render() { return ( <Navbar bsStyle="pills"> <Navbar.Header> <Navbar.Brand> <Link to={'/'}> Dare </Link> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav> <NavItem> <Link to="/challenge">Challenge</Link> </NavItem> <NavItem> <Link to="/ideas">Ideas</Link> </NavItem> </Nav> <Nav pullRight> <NavItem> <Link to="/about">About this page</Link> </NavItem> </Nav> </Navbar.Collapse> </Navbar> ); } }
JavaScript
class CardManager { constructor() { this[Cards] = List([]) } get state() { return this[Cards] } /** * Add card to memory * @param card * @returns {CardManager} */ add(card) { if (! card) return this card = Map.isMap(card) ? card : Map(card) this[Cards] = this[Cards].push(Map(card)) return this } /** * Get template for a type of card * @param type * @returns {*} */ type(type) { // no cards or no type requested, ignore if (this[Cards].count() === 0 || type === undefined) return return this[Cards].filter(map => map.get('type') === type).get(0).get('template') } }
JavaScript
class MiscTemplateMigration extends schematics_1.Migration { constructor() { super(...arguments); // Only enable this rule if the migration targets version 6. The rule // currently only includes migrations for V6 deprecations. this.enabled = this.targetVersion === schematics_1.TargetVersion.V6; } visitTemplate(template) { // Migration for: https://github.com/angular/components/pull/10398 (v6) (0, schematics_1.findOutputsOnElementWithTag)(template.content, 'selectionChange', ['mat-list-option']).forEach(offset => { this.failures.push({ filePath: template.filePath, position: template.getCharacterAndLineOfPosition(template.start + offset), message: `Found deprecated "selectionChange" output binding on "mat-list-option". ` + `Use "selectionChange" on "mat-selection-list" instead.`, }); }); // Migration for: https://github.com/angular/components/pull/10413 (v6) (0, schematics_1.findOutputsOnElementWithTag)(template.content, 'selectedChanged', ['mat-datepicker']).forEach(offset => { this.failures.push({ filePath: template.filePath, position: template.getCharacterAndLineOfPosition(template.start + offset), message: `Found deprecated "selectedChanged" output binding on "mat-datepicker". ` + `Use "dateChange" or "dateInput" on "<input [matDatepicker]>" instead.`, }); }); // Migration for: https://github.com/angular/components/commit/f0bf6e7 (v6) (0, schematics_1.findInputsOnElementWithTag)(template.content, 'selected', ['mat-button-toggle-group']).forEach(offset => { this.failures.push({ filePath: template.filePath, position: template.getCharacterAndLineOfPosition(template.start + offset), message: `Found deprecated "selected" input binding on "mat-radio-button-group". ` + `Use "value" instead.`, }); }); } }
JavaScript
class Head { /** * generates mesh for head of Protagonist */ constructor() { this.material = new THREE.MeshLambertMaterial({ color: 0xffffff, transparent: false, opacity: 0.8 }); this.mesh = new THREE.Mesh(Head.geometry, this.material); } /** * positions the head according to given coordinates * @param {number} x * @param {number} y * @param {number} z */ position(x, y, z) { this.mesh.position.set(x, y, z); } /** * adds the head to a group * @param {THREE.Group} group */ addToGroup(group) { group.add(this.mesh); } /** * loads the head from json file (blender) * @param {Promise} promise */ static init() { let loader = new THREE.JSONLoader(); return new Promise((resolve, reject)=>{ loader.load('/blender/head.json', function(geometry, materials) { Head.geometry = geometry; resolve(); }); }); } }
JavaScript
class MediaService extends Service.extend(Evented) { // Ember only sets Ember.testing when tests are starting // eslint-disable-next-line ember/no-ember-testing-in-module-scope _mocked = Ember.testing; _mockedBreakpoint = 'desktop'; /** * @property _matches * @type Array */ @tracked _matches; /** * A set of matching matchers. * * @property matches * @type Array */ get matches() { if (this._matches) { return this._matches } return (Ember.testing && this._mocked) ? [this._mockedBreakpoint] : []; } set matches(value) { this._matches = value; } /** * A hash of listeners indexed by their matcher's names * * @property * @type Object */ listeners = {}; /** * A hash of matchers by breakpoint name */ matchers = {}; /** * The matcher to use for testing media queries. * * @property matcher * @type matchMedia * @default window.matchMedia * @private */ mql = detectMatchMedia(); /** * Initialize the service based on the breakpoints config * * @method init * */ constructor() { super(...arguments); const breakpoints = getOwner(this).lookup('breakpoints:main'); if (breakpoints) { Object.keys(breakpoints).forEach((name) => { const cpName = `is${classify(name)}`; defineProperty( this, cpName, dependentKeyCompat({ get() { return this.matches.indexOf(name) > -1; }, }) ); defineProperty( this, name, dependentKeyCompat({ get() { return this[cpName]; }, }) ); this.match(name, breakpoints[name]); }); } } /** * A string composed of all the matching matchers' names, turned into * friendly, dasherized class-names that are prefixed with `media-`. * * @property classNames * @type string */ get classNames() { return this.matches.map(function(name) { return `media-${dasherize(name)}`; }).join(' '); } _triggerMediaChanged() { this.trigger('mediaChanged', {}); } _triggerEvent() { once(this, this._triggerMediaChanged); } /** * Adds a new matcher to the list. * * After this method is called, you will be able to access the result * of the matcher as a property on this object. * * **Adding a new matcher** * * ```javascript * media = Ember.Responsive.Media.create(); * media.match('all', 'all'); * media.get('all'); * // => instanceof window.matchMedia * media.get('all.matches'); * // => true * ``` * * @param string name The name of the matcher * @param string query The media query to match against * @method match */ match(name, query) { // see https://github.com/ember-cli/eslint-plugin-ember/pull/272 if (Ember.testing && this._mocked) { return; } const mql = this.mql; const matcher = mql(query); const listener = (matcher) => { if (this.isDestroyed) { return; } set(this, `matchers.${name}`, matcher); if (matcher.matches) { this.matches = Array.from(new Set([...this.matches, name])); } else { this.matches = Array.from(new Set(this.matches.filter(key => key !== name))); } this._triggerEvent(); }; this.listeners[name] = listener; if (matcher.addListener) { matcher.addListener(function(matcher){ run(null, listener, matcher); }); } listener(matcher); } }
JavaScript
class DfuTransportNfc extends DfuTransportPrn { constructor(reader, packetReceiveNotification = 16, protocol = 2, maxMtu = 200) { super(packetReceiveNotification); this.reader = reader; this.protocol = protocol; // convert MTU to max payload length sending over NFC ( MTU - 1 byte OP code length) this.mtu = maxMtu - 1; } writeCommand(bytes) { const bytesBuf = Buffer.from(bytes); debug(' ctrl --> ', bytesBuf); let rxBuf; let that = this; return new Promise((res, rej) => { this.reader.transmit(bytesBuf, 255, this.protocol, function(err, data) { if (err) { console.log(err); return rej(err); } else { debug(' recv <-- ', data); rxBuf = Buffer.from(data); that.onData(rxBuf); return res(); } }); }); } // Given some payload bytes, pack them into a 0x08 command. // The length of the bytes is guaranteed to be under this.mtu thanks // to the DfuTransportPrn functionality. writeData(bytes) { const dataBytes = new Uint8Array(bytes.length + 1); dataBytes.set([0x08], 0); // "Write" opcode dataBytes.set(bytes, 1); debug(`send ${dataBytes.length} bytes data --> `); let rxBuf; let that = this; return new Promise((res, rej) => { const readerTransmit = () => { this.reader.transmit(dataBytes, 255, this.protocol, function(err, data) { if (err) { console.log(err); return rej(err); } else { debug(' recv <-- ', data); if(data[0] === 0x60) { rxBuf = Buffer.from(data); that.onData(rxBuf); return res(); } else if((data[0] === 0x90) && (data[1] === 0x00)) { debug(' transmit data unit ok'); return res(); } else if((data[0] === 0x63) && (data[1] === 0x86)) { debug(' Resend frame after 100ms'); setTimeout(() => { readerTransmit(); }, 100); } } }); }; readerTransmit(); }); } // Abstract method, called before any operation that would send bytes. // Concrete subclasses **must**: // - Check validity of the connection, // - Re-initialize connection if needed, including // - Set up PRN // - Request MTU (only if the transport has a variable MTU) // - Return a Promise whenever the connection is ready. ready() { if (this.readyPromise) { return this.readyPromise; } this.readyPromise = this.writeCommand(new Uint8Array([ 0x02, // "Set PRN" opcode // eslint-disable-next-line no-bitwise this.prn & 0xFF, // PRN LSB // eslint-disable-next-line no-bitwise (this.prn >> 8) & 0xFF, // PRN MSB ])) .then(this.read.bind(this)) .then(this.assertPacket(0x02, 0)) // Request MTU .then(() => this.writeCommand(new Uint8Array([ 0x07, // "Request MTU" opcode ]))) .then(this.read.bind(this)) .then(this.assertPacket(0x07, 2)) .then(bytes => { let target_mtu = (bytes[1] * 256) + bytes[0]; // Convert target MTU into max payload of payload sent over NFCbefore SLIP encoding: // This takes into account: // DFU command ( -1 ) target_mtu -= 1; Math.min(target_mtu, this.mtu); this.mtu = Math.min(target_mtu, this.mtu);; // Round down to multiples of 4. // This is done to avoid errors while writing to flash memory: // writing an unaligned number of bytes will result in an // error in most chips. this.mtu -= this.mtu % 4; debug(`NFC MTU: ${this.mtu}`); }); return this.readyPromise; } }
JavaScript
class RoleTree extends RoleSelect { /** * @param {boolean} multiSelectable */ set multiSelectable(multiSelectable) { this.setAttr(ARIAMultiSelectable, multiSelectable) } /** * @returns {boolean} */ get multiSelectable() { return this.getAttr(ARIAMultiSelectable) } /** * @param {string} orientation */ set orientation(orientation) { super.orientation = orientation } /** * @returns {string} */ get orientation() { return super.orientation || 'vertical' } /** * @param {boolean} required */ set required(required) { this.setAttr(ARIARequired, required) } /** * @returns {boolean} */ get required() { return this.getAttr(ARIARequired) } /** * @returns {RoleTreeItem[]} */ get items() { return this.findAll(RoleTreeItem) } /** * @returns {boolean} */ static get abstract() { return false } }
JavaScript
class Panel extends React.Component { static propTypes = { workspace: PropTypes.object.isRequired, location: PropTypes.oneOf([ 'top', 'bottom', 'left', 'right', 'header', 'footer', 'modal', ]).isRequired, children: PropTypes.element.isRequired, getItem: PropTypes.func, options: PropTypes.object, onDidClosePanel: PropTypes.func, visible: PropTypes.bool, } static defaultProps = { options: {}, getItem: ({portal, subtree}) => portal, onDidClosePanel: panel => {}, visible: true, } componentDidMount() { this.setupPanel(); } componentWillReceiveProps(newProps) { if (this.didCloseItem) { // eslint-disable-next-line no-console console.error('Unexpected update in `Panel`: the contained panel has been destroyed'); } if (this.panel && this.props.visible !== newProps.visible) { this.panel[newProps.visible ? 'show' : 'hide'](); } } render() { return <Portal ref={c => { this.portal = c; }}>{this.props.children}</Portal>; } setupPanel() { if (this.panel) { return; } // "left" => "Left" const location = this.props.location.substr(0, 1).toUpperCase() + this.props.location.substr(1); const methodName = `add${location}Panel`; const item = this.props.getItem({portal: this.portal, subtree: this.portal.getRenderedSubtree()}); const options = {...this.props.options, visible: this.props.visible, item}; this.panel = this.props.workspace[methodName](options); this.subscriptions = this.panel.onDidDestroy(() => { this.didCloseItem = true; this.props.onDidClosePanel(this.panel); }); } componentWillUnmount() { this.subscriptions && this.subscriptions.dispose(); if (this.panel) { this.panel.destroy(); } } getPanel() { return this.panel; } }
JavaScript
class AbstractController { action(action) { if (this[action]) { // return coExpress(this[action].bind(this)); return this[action].bind(this); } throw new Error('No action "' + action + '" in controller "' + this.constructor.name + '"'); } /** * Attach dependencies for this controller. E.g. RequestAdapters and Validators * @param request_handlers * @param default_handlers */ wireEndpointDependencies(request_handlers, default_handlers) { const handlers = request_handlers || default_handlers; _.forOwn(handlers, (handler, handler_id) => { if (_.isString(handler_id)) { // convert handler name tp _handlerName format. E.g. DataAdapter -> _dataAdapter const handlerName = handler_id.charAt(0).toLowerCase() + handler_id.slice(1); // attach the handler to the Controller instance this[`_${handlerName}`] = handler; } }); } }
JavaScript
class EditorEventBuilder extends UnderEventBuilder { // eslint-disable-line no-unused-vars /** * Build event from json data * @override * @param {JSON} json Event json data * @return {GameEvent} Generated event */ build(json) { return new EditorEvent(super.build(json)); } }
JavaScript
class Reason { constructor() { this.common = new daoCommon(); } /** * Tries to find an entity using its Id / Primary Key * @params id * @return entity */ async findById(id) { let sqlRequest = "SELECT * FROM reason WHERE id=$id"; let sqlParams = {$id: id}; const row = await this.common.findOne(sqlRequest, sqlParams); return new reason(row.id, row.description, row.work, row.active); }; /** * Tries to find all entities * @return entity */ async findAll() { let sqlRequest = "SELECT * FROM reason"; const rows = await this.common.findAll(sqlRequest); let reasons = []; for (const row of rows) { reasons.push(new reason(row.id, row.description, row.work, row.active)); } return reasons; }; /** * Creates the given entity in the database * @params Employee * returns database insertion status */ create(reason) { let sqlRequest = "INSERT into reason (description, work, active) " + "VALUES ($description, $work, $active)"; let sqlParams = { $description: reason.description, $work: reason.work, $active: reason.active }; return this.common.run(sqlRequest, sqlParams); }; /** * Updates the given entity in the database * @params Employee * @return true if the entity has been updated, false if not found and not updated */ update(reason) { let sqlRequest = `UPDATE reason SET description=$description, work=$work, active=$active WHERE id=$id`; let sqlParams = { $id: reason.id, $description: reason.description, $work: reason.work, $active: reason.active }; return this.common.run(sqlRequest, sqlParams); }; /** * Deletes an entity using its Id / Primary Key * @params id * returns database deletion status */ deleteById(id) { let sqlRequest = "DELETE FROM reason WHERE id=$id"; let sqlParams = {$id: id}; return this.common.run(sqlRequest, sqlParams); }; }
JavaScript
class IcosahedronFactory { // 2. Define a static create method to return new icosahedrons static createMesh( spec = {} ) { // 3. Setup default values or use arguments let { color = '#FF00FF', radius = 1, detail = 0, // greater than 1, it's effectively a sphere. wireframe = true, } = spec; // 4. Use ThreeJS to define a 3D icosahedron var geometry = new THREE.IcosahedronGeometry(radius, detail); var material = new THREE.MeshBasicMaterial({ color: color, wireframe: wireframe }); return { geometry, material } } // 2. Define a static create method to return new icosahedrons static create( spec = {} ) { // 3. Setup default values or use arguments let { name = "icosahedron", x = 0.0, y = 0.0, z = 0.0, mesh = IcosahedronFactory.createMesh( spec ), } = spec; let { geometry, material } = mesh; // 4. Use ThreeJS to define a 3D icosahedron var icosahedron = new THREE.Mesh( geometry, material ); // 5. Use the name property to specify a type icosahedron.name = name; // 6. Using ThreeJS methods on the icosahedron, move it to a specific offset icosahedron.translateX(x); icosahedron.translateY(y); icosahedron.translateZ(z); // 7. Return the new icosahedron return icosahedron; } static createRing( spec = {} ) { let { sides = 6, yPos = 0.0, worldRadius = 5, shapeRadius = 1, shapeColors = [ "#000000", "#0000FF" ], } = spec; var step = 2 * Math.PI / sides; var meshList = []; for( var j = 0; j < shapeColors.length; j++ ) { meshList.push( IcosahedronFactory.createMesh( { ...spec, color: shapeColors[j], radius: shapeRadius, wireframe: j === 0, }) ); } var ringGroup = new THREE.Group(); for (var i = 0, angle = 0; i < sides; i++, angle += step) { var xPos = worldRadius * Math.cos(angle); var zPos = worldRadius * Math.sin(angle); for( var m = 0; m < meshList.length; m++ ) { ringGroup.add(IcosahedronFactory.create({ mesh: meshList[ m ], x: xPos, y: yPos, z: zPos, })) } } ringGroup.name = "ring"; return ringGroup; } }
JavaScript
class Friend { /** *Creates an instance of Friend. * @param {*} $b * @memberof Friend */ constructor($b) { if (!$b) $b = {}; this.FriendUserId = $b.id; this.OwnerId = $b.ownerId; this.FriendUsername = $b.friendUsername; this.FriendStatus = $b.friendStatus; this.IsAccepted = $b.isAccepted; this.UserStatus = new UserStatus($b.userStatus); this.LatestMessageTime = $b.latestMessageTime; this.Profile = new UserProfile($b.profile); } /** * * * @param {Friend} other * @memberof Friend */ IsSame(other) { if ( this.FriendUserId === other.FriendUserId && this.OwnerId === other.OwnerId && this.FriendUsername === other.FriendUsername && this.IsAccepted === other.IsAccepted && this.FriendStatus === other.FriendStatus && this.LatestMessageTime === other.LatestMessageTime && this.UserStatus.IsSame(other.UserStatus) ) return true; return false; } }
JavaScript
class Events { constructor(element) { this.touch = false; this.element = element; this.attach(); } attach() { this.element.addEventListener('touchstart', this.touchstart.bind(this), { passive: true }); this.element.addEventListener('touchmove', this.touchmove.bind(this), { passive: true }); this.element.addEventListener('touchend', this.touchend.bind(this), { passive: true }); this.element.addEventListener('mousedown', this.mousedown.bind(this)); this.element.addEventListener('mousemove', this.mousemove.bind(this)); this.element.addEventListener('mouseup', this.mouseup.bind(this)); } detach() { this.element.removeEventListener('touchstart', this.touchstart); this.element.removeEventListener('touchmove', this.touchmove); this.element.removeEventListener('touchend', this.touchend); this.element.removeEventListener('mousedown', this.mousedown); this.element.removeEventListener('mousemove', this.mousemove); this.element.removeEventListener('mouseup', this.mouseup); } touchstart(event) { this.touch = true; const custom = new TouchEvent('smolka::down', event); this.element.dispatchEvent(custom); } touchmove(event) { this.touch = true; const custom = new TouchEvent('smolka::move', event); this.element.dispatchEvent(custom); } touchend(event) { this.touch = true; const custom = new TouchEvent('smolka::up', event); this.element.dispatchEvent(custom); } mousedown(event) { if (!this.touch) { const custom = new MouseEvent('smolka::down', event); this.element.dispatchEvent(custom); } } mousemove(event) { if (!this.touch) { const custom = new MouseEvent('smolka::move', event); this.element.dispatchEvent(custom); } } mouseup(event) { if (!this.touch) { const custom = new MouseEvent('smolka::up', event); this.element.dispatchEvent(custom); } this.touch = false; } }
JavaScript
class App extends React.Component { constructor(props) { super(props); this.state = { user: { username: "", password: "", email: "", }, roles: "manager", isUserActive: false } } // componentDidMount() { // //Add .right by default // this.rightSide.classList.add("right"); // } // changeState() { // const { isLogginActive } = this.state; // if (isLogginActive) { // this.rightSide.classList.remove("right"); // this.rightSide.classList.add("left"); // } else { // this.rightSide.classList.remove("left"); // this.rightSide.classList.add("right"); // } // this.setState(prevState => ({ isLogginActive: !prevState.isLogginActive })); // } render() { const isUserActive = Cookies.get('access_token')!=null && Cookies.get('access_token')!==""; // const isUserActive = true; return ( <div className="App"> <Router> <Header className="App-header"> </Header> {/* <header className="App-header"> <Chatbot config={config} actionProvider={ActionProvider} messageParser={MessageParser} /> </header> */} {!isUserActive ? (<Login />) : ( <div> <Navbar /> <Switch> <Route path='/' exact component={App1} /> <Route path='/faq' exact component={Faq} /> <Route path='/calendar' exact component={Calendar} /> <Route path='/setting' exact component={SettingsPane} /> <Route path='/App1' exact component={App1} /> <Route path='/repository' exact component={Repository1} /> <Route path='/messages' exact component={Messages} /> <Route path='/team' exact component={team} /> <Route path='/logout' exact component={Logout} /> </Switch> {/* <App1></App1> */} </div> )} <Footer> </Footer> </Router> </div> ); } }
JavaScript
class NumericInput extends React.Component { static propTypes = { /** * Optional label for this field. */ label: PropTypes.string, /** * The minimum value for the input element. */ min: PropTypes.number, /** * The maximum value for the input element. */ max: PropTypes.number, /** * The step of the input field. Use 1 for integer only. */ step: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Placeholder string of the input field. */ placeholder: PropTypes.string, /** * The numeric input field value. */ value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Whether the input field is disabled or not. */ disabled: PropTypes.bool, /** * A callback called when the input field value changes. * * @param {number} value the new value of the input field. */ onChange: PropTypes.func, } /** * Renders the input label if it was passed via props. * * @public * @method * @returns {JSX} */ renderLabel() { const {label} = this.props; if (label) { return <FormLabel>{label}</FormLabel>; } } render() { const {min, max, step, placeholder, value, disabled, onChange, style} = this.props; return ( <> {this.renderLabel()} <input type="number" min={min} max={max} step={step} placeholder={placeholder} value={value || ''} disabled={disabled} onChange={e => onChange(Number(e.target.value))} style={style} className="numeric-input-wrapper" /> </> ); } }
JavaScript
class Person extends Mammal { // Inheritance reuse all methods validations etc. constructor(name, age) { super(age) //constructor are invokeed from main class //super have to be used BEFORE using THIS. This way "this" is defined this._name = name; } say(text) { console.log(`${this._name}: ${text} `); } walk() { //- this way walk is overriden super.walk(); //this way first Mammal walk will be invoked console.log("Person walk invoking"); } }
JavaScript
class Matrix { constructor(hot) { /** * Handsontable instance. * * @type {Core} */ this.hot = hot; /** * List of all cell values with theirs precedents. * * @type {Array} */ this.data = []; /** * List of all created and registered cell references. * * @type {Array} */ this.cellReferences = []; } /** * Get cell value at given row and column index. * * @param {Number} row Physical row index. * @param {Number} column Physical column index. * @returns {CellValue|null} Returns CellValue instance or `null` if cell not found. */ getCellAt(row, column) { let result = null; arrayEach(this.data, (cell) => { if (cell.row === row && cell.column === column) { result = cell; return false; } }); return result; } /** * Get all out of date cells. * * @returns {Array} */ getOutOfDateCells() { return arrayFilter(this.data, cell => cell.isState(CellValue.STATE_OUT_OFF_DATE)); } /** * Add cell value to the collection. * * @param {CellValue|Object} cellValue Cell value object. */ add(cellValue) { if (!arrayFilter(this.data, cell => cell.isEqual(cellValue)).length) { this.data.push(cellValue); } } /** * Remove cell value from the collection. * * @param {CellValue|Object|Array} cellValue Cell value object. */ remove(cellValue) { const isArray = Array.isArray(cellValue); const isEqual = (cell, values) => { let result = false; if (isArray) { arrayEach(values, (value) => { if (cell.isEqual(value)) { result = true; return false; } }); } else { result = cell.isEqual(values); } return result; }; this.data = arrayFilter(this.data, cell => !isEqual(cell, cellValue)); } /** * Get cell dependencies using visual coordinates. * * @param {Object} cellCoord Visual cell coordinates object. */ getDependencies(cellCoord) { /* eslint-disable arrow-body-style */ const getDependencies = (cell) => { return arrayReduce(this.data, (acc, cellValue) => { if (cellValue.hasPrecedent(cell) && acc.indexOf(cellValue) === -1) { acc.push(cellValue); } return acc; }, []); }; var resultLength = 0; var maxDependenciesDeep = this.hot && this.hot.getSettings().maxDependenciesDeep > -1 ? this.hot.getSettings().maxDependenciesDeep : -1; const getTotalDependencies = (cell) => { if(maxDependenciesDeep > -1 && resultLength > maxDependenciesDeep) { return []; } let deps = getDependencies(cell); if (deps.length) { arrayEach(deps, (cellValue) => { if (cellValue.hasPrecedents() && (maxDependenciesDeep > -1 && resultLength < maxDependenciesDeep|| maxDependenciesDeep === -1)) { deps = deps.concat(getTotalDependencies({ row: this.hot.toVisualRow(cellValue.row), column: this.hot.toVisualColumn(cellValue.column) })); } }); resultLength +=deps.length; } return deps; }; return getTotalDependencies(cellCoord); } /** * Get cell dependencies using visual coordinates. * * @param {Object} cellCoord Visual cell coordinates object. */ getDependenciesCustom(cellCoord) { /* eslint-disable arrow-body-style */ let result = []; let startCell = cellCoord; var cellCode = this.coordsToA1([startCell[1] || startCell.column, (startCell[0] || startCell.row) + 1]); function distinctFilter(array) { var seenIt = {}; return array.reverse().filter(function (val) { let key = `${val.row}-${val.column}`; if (seenIt[key]) { return false; } return seenIt[key] = true; }).reverse(); } this.data.forEach(dataCell => { if (dataCell.precedentsList && dataCell.precedentsList[cellCode]) { result.push(this.getCellAt( dataCell.row, dataCell.column, )); } }); result.forEach(parentCell => { result.push(...this.getDependenciesCustom([parentCell.row, parentCell.column])); }); return distinctFilter(result); } /** * */ coordsToA1(coords) { return this.stringifyCol(coords[0]) + coords[1]; } /** * Stringify column from number to. * * @param {*} value */ stringifyCol(value) { if (typeof value === 'string') { return value; } let col = ''; while (value >= 0) { if (value / 26 >= 1) { col += String.fromCharCode(64 + Math.floor(value / 26)); value = value % 26; } else { col += String.fromCharCode(65 + value); value = -1; } } return col; } /** * Register cell reference to the collection. * * @param {CellReference|Object} cellReference Cell reference object. */ registerCellRef(cellReference) { if (!arrayFilter(this.cellReferences, cell => cell.isEqual(cellReference)).length) { this.cellReferences.push(cellReference); } } /** * Remove cell references from the collection. * * @param {Object} start Start visual coordinate. * @param {Object} end End visual coordinate. * @returns {Array} Returns removed cell references. */ removeCellRefsAtRange({ row: startRow, column: startColumn }, { row: endRow, column: endColumn }) { const removed = []; const rowMatch = cell => (startRow === void 0 ? true : cell.row >= startRow && cell.row <= endRow); const colMatch = cell => (startColumn === void 0 ? true : cell.column >= startColumn && cell.column <= endColumn); this.cellReferences = arrayFilter(this.cellReferences, (cell) => { if (rowMatch(cell) && colMatch(cell)) { removed.push(cell); return false; } return true; }); return removed; } /** * Reset matrix data. */ reset() { this.data.length = 0; this.cellReferences.length = 0; } }
JavaScript
class NgxsRootModule { /** * @param {?} factory * @param {?} internalStateOperations * @param {?} store * @param {?} select * @param {?=} states * @param {?=} lifecycleStateManager */ constructor(factory, internalStateOperations, store, select, states = [], lifecycleStateManager) { // add stores to the state graph and return their defaults /** @type {?} */ const results = factory.addAndReturnDefaults(states); internalStateOperations.setStateToTheCurrentWithNew(results); // connect our actions stream factory.connectActionHandlers(); // dispatch the init action and invoke init and bootstrap functions after lifecycleStateManager.ngxsBootstrap(new InitState(), results); } }
JavaScript
class NgxsFeatureModule { /** * @param {?} store * @param {?} internalStateOperations * @param {?} factory * @param {?} states * @param {?} lifecycleStateManager */ constructor(store, internalStateOperations, factory, states, lifecycleStateManager) { // Since FEATURE_STATE_TOKEN is a multi token, we need to // flatten it [[Feature1State, Feature2State], [Feature3State]] /** @type {?} */ const flattenedStates = ((/** @type {?} */ ([]))).concat(...states); // add stores to the state graph and return their defaults /** @type {?} */ const results = factory.addAndReturnDefaults(flattenedStates); if (results.states.length) { internalStateOperations.setStateToTheCurrentWithNew(results); // dispatch the update action and invoke init and bootstrap functions after lifecycleStateManager.ngxsBootstrap(new UpdateState(), results); } } }
JavaScript
class Jellyfin { constructor({HTTPS, jfIP, jfPort, jfToken}) { return {error: "Not yet implemented"}; } async GetNowScreening() { return {error: "Not yet implemented"}; } async GetOnDemand() { return {error: "Not yet implemented"}; } }
JavaScript
class TkColor extends TkStateObject { /** * Initialize a new TkColor object with a given color string. * * @param {String} value The color string to parse for a valid color. * Accepts the same values as CSS colors. * @param {Number} alpha (optional) The value to set for the alpha channel. * If the color string that was specified before sets its own alpha value, * this will override it. */ constructor(value, alpha) { super(); this._h = -1; this._s = -1; this._l = -1; this._r = -1; this._g = -1; this._b = -1; this._a = -1; // Read the actual color value if(TkObject.is(value, TkColor)) { // Existing TkColor this.setString(value.asHsla()); } else { // Color String this.setString(value); } if (this._h === -1 || this._s === -1 || this._l === -1 || this._a === -1 || this._r === -1 || this._g === -1 || this._b === -1) { this.isValid = false; } // Override alpha value from this.setString() if specified // and in a valid range if (alpha !== undefined && TkNumber.in(alpha, 0, 1)) this._a = alpha; this.hasIntialized = true; } /** * Parse a given CSS color string and set the color value * to match it. * * @param {String} colorString The string to parse for a valid color. */ setString(colorString) { // Blank strings do nothing if (colorString.trim().length == 0) { this.isValid = false; return; } // Store old hsla let oldH = this._h; let oldS = this._s; let oldL = this._l; let oldA = this._a; let value = colorString.toLowerCase(); let formatValue = (unformattedValue) => { // Strip out unneeded chars let toRemove = ["(", ")", "rgba", "hsla", "rgb", "hsl"]; let formattedValue = unformattedValue; for (let removeStr of toRemove) formattedValue = formattedValue.replace(removeStr, ""); return formattedValue; }; try { if (value.startsWith("#")) { // hex this.setHex(value); } else if (value.startsWith("hsl")) { // hsl(a) let hslaValues = formatValue(value).split(","); let h = parseInt(hslaValues[0]); let s = parseInt(hslaValues[1]); let l = parseInt(hslaValues[2]); let a = (hslaValues.length == 4) ? parseFloat(hslaValues[3]) : 1; this.setHsla(h, s, l, a); } else if (value.startsWith("rgb")) { // rbg(a) let rgbaValues = formatValue(value).split(","); let r = parseInt(rgbaValues[0]); let g = parseInt(rgbaValues[1]); let b = parseInt(rgbaValues[2]); let a = (rgbaValues.length == 4) ? parseFloat(rgbaValues[3]) : 1; this.setRgba(r, g, b, a); } else { // named this.setName(value); } this.isValid = true; } catch (ex) { console.log(`Error parsing color: ${ex}`); // If the color hasn't been set before and // there's an error interpreting the color, // default to black, else revert to last valid // color if (this.hasIntialized) this.setRgba(0, 0, 0, 1); else this.setHsla(oldH, oldS, oldL, oldA); // Set isValid flag to false this.isValid = false; } } /** * Red (0 - 255). * @type {Number} */ get r() { return this._r; } set r(value) { this.setRgba(value, this._g, this._b, this._a); } /** * Green (0 - 255). * @type {Number} */ get g() { return this._g; } set g(value) { this.setRgba(this._r, value, this._b, this._a); } /** * Blue (0 - 255). * @type {Number} */ get b() { return this._b; } set b(value) { this.setRgba(this._r, this._g, value, this._a); } /** * Hue (0 - 360). * @type {Number} */ get h() { return this._h; } set h(value) { this.setHsla(value, this._s, this._l, this._a); } /** * Saturation (0 - 100). * @type {Number} */ get s() { return this._s; } set s(value) { this.setHsla(this._h, value, this._l, this._a); } /** * Lightness (0 - 100). * @type {Number} */ get l() { return this._l; } set l(value) { this.setHsla(this._h, this._s, value, this._a); } /** * Alpha (0 - 1). * @type {Number} */ get a() { return this._a; } set a(value) { this._a = value; } /** * Create an exact copy of this TkColor instance. * * @returns {TkColor} A deep copy of this TkColor. */ clone() { return new TkColor(this.asHsla()); } /** * Check if another TkColor has an identical color to this one. * * @param {TkColor} otherColor The color to compare to this one. * * @returns {Boolean} If the color of this TkColor is identical to the other TkColor. */ equals(otherColor) { return (otherColor.h == this._h && otherColor.s == this._s && otherColor.l == this._l && otherColor.a == this._a); } /** * Finds a color with a given name and sets it to be the current color. * Searches first for registered colors by a given name, then named CSS * colors after that. * * @param {String} name The name of the color to search for. */ setName(name) { let formattedName = name.toLowerCase(); let registeredColor = _TkRegisteredColors.get(formattedName); if (registeredColor) this.setString(registeredColor); else this.setCssName(formattedName); } /** * Get the name of the color that matches the value of this color. * * @param {Boolean} ignoreAlpha (optional) If the alpha channel should be ignored when * searching for a color from the registered colors and CSS named colors. Defaults to false. * * @returns {String} The name of the color found or empty string if none is found. */ asName(ignoreAlpha = false) { let hexValue = ignoreAlpha ? this.asSolidHex() : this.asHex(); let matchingName = ""; _TkRegisteredColors.forEach((value, key) => { if (value == hexValue) matchingName = key; }); if (matchingName == "") matchingName = this.asCssName(ignoreAlpha); return matchingName; } /** * Set the value of this color to the value of a CSS color with a given * name. * * @param {String} name The name of the CSS color to set. */ setCssName(name) { let formattedName = name.toLowerCase(); this.setHex(TkCssColors[formattedName] ?? ""); } /** * Get a named CSS color that has the same hex value as this color. * * Note: Because named CSS colors don't have an alpha channel, this function * ignores it if ignoreAlpha == true. This is the default functionality. * * @param {Boolean} ignoreAlpha (optional) If the alpha channel should be ignored. * * @returns {String} The name of the CSS color that matches this color, * or an empty string, if none is found. */ asCssName(ignoreAlpha = true) { let hexValue = ignoreAlpha ? this.asSolidHex() : this.asHex(); for (let cssColor in TkCssColors) if (TkCssColors[cssColor] == hexValue) return cssColor; return ""; } /** * Set this color from a hex code. * * @param {String} hex The hex code. */ setHex(hex) { let rgba = TkColor.hexToRgba(hex); // Check if the converted RGBA values fall within expected ranges let validRgba = TkNumber.in(rgba.r, 0, 255) && TkNumber.in(rgba.g, 0, 255) && TkNumber.in(rgba.b, 0, 255) && TkNumber.in(rgba.a, 0, 1); if (validRgba) { this.setRgba(rgba.r, rgba.g, rgba.b, rgba.a); this.isValid = true; } else { this.isValid = false; } } /** * @param {Boolean} forceAlpha (optional) If the resulting hex code could should include * an alpha channel, even if there is no transparency (alpha == 1), defaults to false. * * @returns {String} The hex code representing this color. */ asHex(forceAlpha = false) { return TkColor.rgbaToHex(this._r, this._g, this._b, this._a, forceAlpha); } /** * @returns The hex code representing this color, stripped of its alpha channel. */ asSolidHex() { return TkColor.rgbaToHex(this._r, this._g, this._b); } /** * Set the color's hue, saturation, lightness, and alpha. * * @param {Number} h The hue of the color (0 - 360). * @param {Number} s The saturation of the color (0 - 100). * @param {Number} l The lightness of the color (0 - 100). * @param {Number} a (optional) The alpha value (0 - 1), defaults to 1. */ setHsla(h, s, l, a = 1) { // Check if the given params fall within valid ranges let validParams = TkNumber.in(h, 0, 360) && TkNumber.in(s, 0, 100) && TkNumber.in(l, 0, 100) && TkNumber.in(a, 0, 1); if (validParams) { let rgb = TkColor.hslaToRgba(h, s, l); this._r = rgb.r; this._g = rgb.g; this._b = rgb.b; this._h = h; this._s = s; this._l = l; this._a = a; this.isValid = true; } else { this.isValid = false; } } /** * Get the color as an hsla() string that can be used by CSS. * * @param {Number} digits (optional) The number of digits to round each value to, defaults to 0. * @param {Number} digitsA (optional) The number of digits to round the alpha to, defaults to 2. * * @returns {String} The CSS hsla() value of this color. */ asHsla(digits = 0, digitsA = 2) { return `hsla(${TkNumber.fixed(this._h, digits)}, ${TkNumber.fixed(this._s, digits)}%, ${TkNumber.fixed(this._l, digits)}%, ${TkNumber.fixed(this._a, digitsA)})`; } /** * Set the rgba of this color. * * @param {Number} r The red value (0 - 255). * @param {Number} g The green value (0 - 255). * @param {Number} b The blue value (0 - 255). * @param {Number} a The alpha value (0 - 1). */ setRgba(r, g, b, a = 1) { let hsla = TkColor.rgbaToHsla(r, g, b); // Check if the given parameters fall within valid ranges let validParams = TkNumber.in(r, 0, 255) && TkNumber.in(g, 0, 255) && TkNumber.in(b, 0, 255) && TkNumber.in(a, 0, 1); // Check if the converted HSLA values fall within valid ranges let validHsla = TkNumber.in(hsla.h, 0, 360) && TkNumber.in(hsla.s, 0, 100) && TkNumber.in(hsla.l, 0, 100); if (validParams && validHsla) { this._r = r; this._g = g; this._b = b; this._h = hsla.h; this._s = hsla.s; this._l = hsla.l; this._a = a; this.isValid = true; } else { this.isValid = false; } } /** * Get the color as an rgba() string that can be used by CSS. * * @param {Number} digits (optional) The number of digits to round each value to, defaults to 0. * @param {Number} digitsA (optional) The number of digits to round the alpha to, defaults to 2. * * @returns {String} The rgba() string representing this color. */ asRgba(digits = 0, digitsA = 2) { return `rgba(${TkNumber.fixed(this._r, digits)}, ${TkNumber.fixed(this._g, digits)}, ${TkNumber.fixed(this._b, digits)}, ${TkNumber.fixed(this._a, digitsA)})`; } /** * Get the luminance of this color. * * @returns {Number} The color's luminance. */ getLuminance() { let a = [this._r, this._g, this._b].map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }); return (a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722) * this._a; } /** * Calculate the factor that this color contrasts with another color by. * * @param {TkColor} otherColor The other color to contrast with. * * @returns {Number} The contrast factor with the other color. */ contrastWith(otherColor) { return (otherColor.getLuminance() + 0.05) / (this.getLuminance() + 0.05); } /** * @returns {Boolean} If this color is dark (i.e. contrasts with white by a factor > 2.5). */ isDark() { return this.contrastWith(new TkColor("white")) > 2.5; } /** * @returns {Boolean} If this color is light (i.e. contrasts with white by a factor <= 2.5). */ isLight() { return !this.isDark(); } /** * @returns {Boolean} If this color is gray (i.e. has no saturation). */ isGray() { return this.s == 0; } /** * Register certain color values to be used across all TkColor instances * through the setName() and asName() functions. * * @param {String} name The name of the color. * @param {String} value The value to set is as. */ static register(name, value) { let registeredColor = new TkColor(value); _TkRegisteredColors.set(name, registeredColor.asHex()); } /** * Get the computed property of an element and if it's a color, create an new TkColor from it. * * @param {String|HTMLElement|TkView} from The target to read the property from, accepts the same values * as options.from in the TkView constructor. * @param {String} propertyName The name of the property. * * @returns {TkColor} The color extracted from that property, if it is a valid color, null if not. */ static fromProperty(from, propertyName) { let propertyValue = new TkView({ from: from }).getComputed(propertyName); let extractedColor = new TkColor(propertyValue); return (extractedColor.isValid) ? extractedColor : null; } /** * Check if a string results in a valid color. * * @param {String} colorString The color string to check. * * @returns {Boolean} If the given string is a valid color. */ static isColor(colorString) { let testColor = new TkColor(colorString); return testColor.isValid; } /** * Converts HSLA values to RGBA values. * * @param {Number} h The hue of the color (0 - 360). * @param {Number} s The saturation of the color (0 - 100). * @param {Number} l The lightness of the color (0 - 100). * @param {Number} a (optional) The alpha value (0 - 1), defaults to 1. * @param {Number} digits (optional) The number of digits to round each value to, defaults to 3. * * @returns {{r: Number, g: Number, b: Number, a: Number}} The converted RGBA values. */ static hslaToRgba(h, s, l, a = 1, digits = 3) { let r, g, b; if (h > 0) h /= 360; if (s > 0) s /= 100; if (l > 0) l /= 100; if (s == 0) { r = g = b = l; // achromatic } else { let hue2rgb = (p, q, t) => { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } let q = l < 0.5 ? l * (1 + s) : l + s - l * s; let p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: TkNumber.fixed(r * 255, digits), g: TkNumber.fixed(g * 255, digits), b: TkNumber.fixed(b * 255, digits), a: TkNumber.fixed(a, digits) }; } /** * Convert RGBA values to HSLA values. * * @param {Number} r The red value (0 - 255). * @param {Number} g The green value (0 - 255). * @param {Number} b The blue value (0 - 255). * @param {Number} a (optional) The alpha value (0 - 1), defaults to 1. * @param {Number} digits (optional) The number of digits to round each value to, defaults to 3. * * @returns {{ h: Number, s: Number, l: Number, a: Number }} The RGBA values converted to HSLA. */ static rgbaToHsla(r, g, b, a = 1, digits = 3) { r /= 255, g /= 255, b /= 255; let max = Math.max(r, g, b); let min = Math.min(r, g, b); let h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { let d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: TkNumber.fixed(h * 360, digits), s: TkNumber.fixed(s * 100, digits), l: TkNumber.fixed(l * 100, digits), a: TkNumber.fixed(a, digits) }; } /** * Convert a hex code to HSLA. * * @param {String} hex The hex code. * * @returns {{h: Number, s: Number, l: Number, a: Number}} The hex value converted to HSLA. */ static hexToHsla(hex) { let rgba = TkColor.hexToRgba(hex); return TkColor.rgbaToHsla(rgba.r, rgba.g, rgba.b, rgba.a); } /** * Convert a hex code to RGBA. * * @param {String} hex The hex code. * * @returns {{r: Number, g: Number, b: Number, a: Number}} The hex value converted to RGBA. */ static hexToRgba(hex) { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b); // If #rrggbb or #rrggbbaa let hexRegex = (hex.length == 7) ? /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i : /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; let result = hexRegex.exec(hex); let alpha = 1; if (result[4]) alpha = Math.round(parseInt(result[4], 16))/255.0; return result ? { r: Math.round(parseInt(result[1], 16)), g: Math.round(parseInt(result[2], 16)), b: Math.round(parseInt(result[3], 16)), a: alpha } : { r: -1, g: -1, b: -1, a: -1 }; } /** * Convert HSLA values to a hex code. * * @param {Number} h The hue of a color (0 - 360). * @param {Number} s The saturation of a color (0 - 100). * @param {Number} l The lightness of a color (0 - 100). * @param {Number} a (optional) The alpha of a color (0 - 1), defaults to 1. * @param {Boolean} forceAlpha (optional) If the resulting hex code should include an alpha channel, * even if there is no transparency (alpha == 1), defaults to false. * * @returns {String} The HSLA value as a hex code. */ static hslaToHex(h, s, l, a = 1, forceAlpha = false) { let rgba = this.hslaToRgba(h, s, l, a); return this.rgbaToHex(rgba.r, rgba.g, rgba.b, rgba.a, forceAlpha); } /** * Convert RGBA values to a hex code. * * @param {Number} r The red value of a color (0 - 255). * @param {Number} g The green value of a color (0 - 255). * @param {Number} b The blue value of a color (0 - 255). * @param {Number} a (optional) The alpha of a color (0 - 1), defaults to 1. * @param {Boolean} forceAlpha (optional) If the resulting hex code could should include an alpha channel, * even if there is no transparency (alpha == 1), defaults to false. * * @returns {String} The resulting hex code reprenting the color. */ static rgbaToHex(r, g, b, a = 1, forceAlpha = false) { let hex = `#${((1 << 24) + (Math.round(r) << 16) + (Math.round(g) << 8) + Math.round(b)).toString(16).slice(1)}`; if (a < 1 || forceAlpha) // Include alpha if it has it or forceAlpha == true return hex + Math.round(a * 255).toString(16).padStart(2, "0"); else return hex; } /** * Get a list of CSS colors as TkColor objects with their names. * * @returns {{ name: String, color: TkColor, raw: String }} A list of CSS colors, as TkColors. */ static get cssColors() { let cssColors = []; for (let colorName of Object.keys(TkCssColors)) { let colorValue = TkCssColors[colorName]; cssColors.push({ name: colorName, color: new TkColor(colorValue), raw: colorValue }); } return cssColors; } /** * Get a list of CSS colors as TkColor objects with their names, ordered by hue (color.h), * with grays, blacks, and whites on top (i.e. color.s == 0). * * @returns {{ name: String, color: TkColor, raw: String }} A list of CSS colors, as TkColors. */ static get hueOrderedCssColors() { function weighColor(color) { return (color.h) + (color.s == 0 ? color.l - 360 : 0); } return TkColor.cssColors.sort((a, b) => { return weighColor(a.color) - weighColor(b.color); }); } /** * Returns the TkColor as a string. The same * this as calling this.asHsla(). */ toString() { return this.asHsla(); } }
JavaScript
class TkGradient { /** * Create a linear-gradient at a given angle and with * an array of colors. * * @param {Number} angle The linear-gradient's angle. * @param {String[]} colors An array of color strings. */ static linear(angle, colors) { let gradient = `linear-gradient(${angle}deg`; for (let i = 0; i < colors.length; i++) gradient += (`, ${colors[i]} ${TkNumber.toPercentStr(i, colors.length - 1, 4)}`); return gradient + ")"; } }
JavaScript
class Pagetitle { /** * Render plugin`s main Element and fill it with saved data * * @param {{data: PagetitleData, config: PagetitleConfig, api: object}} * data — previously saved data * config - user config for Tool * api - Editor.js API * readOnly - read only mode flag */ constructor({ data, config, api, readOnly }) { this.api = api; this.readOnly = readOnly; /** * Styles * * @type {object} */ this._CSS = { block: this.api.styles.block, settingsButton: this.api.styles.settingsButton, settingsButtonActive: this.api.styles.settingsButtonActive, wrapper: 'ce-pagetitle', }; /** * Tool's settings passed from Editor * * @type {PagetitleConfig} * @private */ this._settings = config; /** * Block's data * * @type {PagetitleData} * @private */ this._data = this.normalizeData(data); /** * List of settings buttons * * @type {HTMLElement[]} */ this.settingsButtons = []; /** * Main Block wrapper * * @type {HTMLElement} * @private */ this._element = this.getTag(); } /** * Normalize input data * * @param {PagetitleData} data - saved data to process * * @returns {PagetitleData} * @private */ normalizeData(data) { const newData = {}; if (typeof data !== 'object') { data = {}; } newData.text = data.text || ''; return newData; } /** * Return Tool's view * * @returns {HTMLHeadingElement} * @public */ render() { return this._element; } /** * Validate Text block data: * - check for emptiness * * @param {PagetitleData} blockData — data received after saving * @returns {boolean} false if saved data is not correct, otherwise true * @public */ validate(blockData) { return blockData.text.trim() !== ''; } /** * Extract Tool's data from the view * * @param {HTMLHeadingElement} toolsContent - Text tools rendered view * @returns {PagetitleData} - saved data * @public */ save(toolsContent) { return { text: toolsContent.innerHTML }; } /** * Allow Header to be converted to/from other blocks */ static get conversionConfig() { return { export: 'text', // use 'text' property for other blocks import: 'text', // fill 'text' property from other block's export string }; } /** * Sanitizer Rules */ static get sanitize() { return { text: {} }; } /** * Returns true to notify core that read-only is supported * * @returns {boolean} */ static get isReadOnlySupported() { return true; } /** * Get current Tools`s data * * @returns {PagetitleData} Current data * @private */ get data() { this._data.text = this._element.innerHTML; return this._data; } /** * Store data in plugin: * - at the this._data property * - at the HTML * * @param {PagetitleData} data — data to set * @private */ set data(data) { this._data = this.normalizeData(data); /** * If level is set and block in DOM * then replace it to a new block */ if (data.level !== undefined && this._element.parentNode) { /** * Create a new tag * * @type {HTMLHeadingElement} */ const newHeader = this.getTag(); /** * Save Block's content */ newHeader.innerHTML = this._element.innerHTML; /** * Replace blocks */ this._element.parentNode.replaceChild(newHeader, this._element); /** * Save new block to private variable * * @type {HTMLHeadingElement} * @private */ this._element = newHeader; } /** * If data.text was passed then update block's content */ if (data.text !== undefined) { this._element.innerHTML = this._data.text || ''; } } /** * Get tag for target level * By default returns second-leveled header * * @returns {HTMLElement} */ getTag() { /** * Create element for current Block's level */ const tag = document.createElement('h1'); /** * Add text to block */ tag.innerHTML = this._data.text || ''; /** * Add styles class */ tag.classList.add(this._CSS.wrapper); /** * Make tag editable */ tag.contentEditable = this.readOnly ? 'false' : 'true'; /** * Add Placeholder */ tag.dataset.placeholder = this.api.i18n.t(this._settings.placeholder || ''); return tag; } /** * Handle H1-H6 tags on paste to substitute it with header Tool * * @param {PasteEvent} event - event with pasted content */ onPaste(event) { const content = event.detail.data; this.data = { text: content.innerHTML, }; } /** * Used by Editor.js paste handling API. * Provides configuration to handle H1 tags. * * @returns {{handler: (function(HTMLElement): {text: string}), tags: string[]}} */ static get pasteConfig() { return { tags: ['H1'], }; } /** * Get Tool toolbox settings * icon - Tool icon's SVG * title - title to show in toolbox * * @returns {{icon: string, title: string}} */ static get toolbox() { return { icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200"><path fill="#fff" d="M38.5 181.5V51.7l33.2-33.2h89.8v163z"/><path d="M158.5 21.5v157h-117V53L73 21.5h85.5m6-6h-94l-35 35v134h129v-169z"/><path fill="none" stroke="#000" stroke-width="6" stroke-linecap="square" stroke-miterlimit="10" d="M73 22v32H41"/><g><path d="M64.2 70.7h72.2l.1 24.2H133c-1.1-8.7-4.4-14.5-9.7-17.6-3-1.7-7.5-2.6-13.5-2.8v63.2c0 4.4.8 7.3 2.3 8.8s4.8 2.2 9.6 2.2v3H79.1v-3c4.7 0 7.8-.7 9.3-2.2 1.5-1.5 2.3-4.4 2.3-8.8V74.6c-5.9.2-10.4 1.1-13.5 2.8-5.7 3.1-9 9-9.7 17.6H64l.2-24.3z"/></g></svg>`, title: 'Page title', }; } }
JavaScript
class AEMInitiateUpload extends AsyncGeneratorFunction { /** * Construct the AEMInitiateUpload function. * * @param {AEMInitiateUploadOptions} [options] Options to initiate upload */ constructor(options) { super(); this.options = options; } /** * Check if the given asset can be added to the batch of assets * * @param {TransferAsset[]} batch Current batch of transfer assets (may be empty) * @param {TransferAsset} transferAsset Transfer asset to check * @returns {Boolean} True if the asset can be added to */ checkAddBatch(batch, transferAsset) { const batchTarget = batch[0].target; const target = transferAsset.target; return batchTarget.folderUrl.toString() === target.folderUrl.toString(); } /** * Initiates the upload of the given assets * * notifyBefore: For each transfer asset added to the batch * notifyAfter: For each transfer asset after the initiate upload * notifyYield: For each transfer asset after it is yielded * * @generator * @param {TransferAsset[]|Generator||AsyncGenerator} assets Transfer assets, target going to AEM * @param {TransferController} controller Transfer controller * @yields {TransferAsset} Transfer asset */ async* execute(transferAssets, controller) { const assets = []; const form = new URLSearchParams(); for await (const transferAsset of transferAssets) { controller.notify(TransferEvents.AEM_INITIATE_UPLOAD, this.name, transferAsset); assets.push(transferAsset); form.append("fileName", transferAsset.target.filename); form.append("fileSize", transferAsset.metadata.contentLength); } if (assets.length === 0) { logger.warn("AEMInitiateUpload.execute on empty set of transfer assets"); return; } try { const folderUrl = assets[0].target.folderUrl; const headers = assets[0].target.headers || {}; // eslint-disable-next-line no-undef if ((typeof window !== 'undefined') && (typeof window.document !== 'undefined')) { const origin = new URL(folderUrl).origin; headers['csrf-token'] = await getCSRFToken(origin, this.options, assets[0].target.headers); } const initiateResponse = await retry(async () => { return postForm(`${folderUrl}.initiateUpload.json`, form, { timeout: this.options && this.options.timeout, headers }); }, this.options); if (!Array.isArray(initiateResponse.files)) { throw new UploadError('Target AEM instance must have direct binary upload enabled', ErrorCodes.NOT_SUPPORTED); } else if (!Array.isArray(initiateResponse.files) || (initiateResponse.files.length !== assets.length)) { throw Error(`'files' field incomplete in initiateUpload response (expected files: ${assets.length}): ${JSON.stringify(initiateResponse)}`); } else if (typeof initiateResponse.completeURI !== "string") { throw Error(`'completeURI' field invalid in initiateUpload response: ${JSON.stringify(initiateResponse)}`); } // yield one or more smaller transfer parts if the source accepts ranges and the content length is large enough const files = initiateResponse.files; const completeUrl = new URL(initiateResponse.completeURI, folderUrl); for (let i = 0; i < assets.length; ++i) { const transferAsset = assets[i]; const { minPartSize, maxPartSize, uploadURIs, mimeType, uploadToken } = files[i]; // validate response from the server if (!Number.isFinite(minPartSize) || !Number.isFinite(maxPartSize) || !Array.isArray(uploadURIs) || (uploadURIs.length === 0)) { throw Error(`invalid multi-part information for ${transferAsset.target.url}: ${JSON.stringify(files[i])}`); } if (minPartSize < 1) { throw Error(`invalid minPartSize for ${transferAsset.target.url}: ${JSON.stringify(files[i])}`); } if (maxPartSize < minPartSize) { throw Error(`invalid maxPartSize for ${transferAsset.target.url}: ${JSON.stringify(files[i])}`); } if (uploadURIs.findIndex(value => typeof value !== "string") !== -1) { throw Error(`invalid upload url for ${transferAsset.target.url}: ${JSON.stringify(files[i])}`); } if (mimeType && typeof mimeType !== "string") { throw Error(`invalid mimetype for ${transferAsset.target.url}: ${JSON.stringify(files[i])}`); } if (typeof uploadToken !== "string") { throw Error(`invalid uploadToken for ${transferAsset.target.url}: ${JSON.stringify(files[i])}`); } // if the client has no mimetype specified, use the mimetype provided by AEM // if AEM cannot detect a mimetype default to application/octet-stream if (!transferAsset.metadata.contentType) { let contentType = mimeType; if (!contentType) { contentType = MIMETYPE.APPLICATION_OCTET_STREAM; } transferAsset.metadata = new AssetMetadata( transferAsset.metadata.filename, contentType, transferAsset.metadata.contentLength ); } transferAsset.multipartTarget = new AssetMultipart( uploadURIs, minPartSize, maxPartSize, transferAsset.target.multipartHeaders, completeUrl, uploadToken ); } for (const transferAsset of assets) { controller.notify(TransferEvents.AFTER_AEM_INITIATE_UPLOAD, this.name, transferAsset); yield transferAsset; } } catch (error) { for (const transferAsset of assets) { controller.notifyError(this.name, error, transferAsset); } } } }
JavaScript
class App extends Component { render() { return ( <AuthProvider> <AppLayout /> </AuthProvider> ); } }
JavaScript
class ConfigLoader { constructor(path, { encoding = "utf8" }) { argcheck({ path, encoding }, { path: argcheck.is(String), encoding: argcheck.is(String) }); this.path = path; this.encoding = encoding; } load() { return readJson(this.path, this.encoding); } }
JavaScript
class Config { /** * Constructs new config * @param {string} path Config file path * @param {object} options Options * @param {string} [options.encoding] Config file encoding */ constructor(path, { encoding = "utf8", validation }) { this.loader = new ConfigLoader(path, { encoding }); if (validation === null) { this.validator = new NullValidator(); } else { let { directory, base, encoding: valEncoding } = validation; this.validator = new SchemaValidator({ directory, base, encoding: valEncoding ? valEncoding : encoding }); } } /** * @private * Is config loaded? */ get loaded() { return Boolean(this.data); } /** * Loads config from file * @returns {Promise} Promise */ load() { return this.loader.load() .then((data) => Config.remap(data)) .then((data) => this.validator.validate(data)) .then((data) => this.data = data); } /** * Retrieves config property * Note: if property in config file is prepended with '#' symbol, then associated env variable will be returned. * @param {string} path Path to property * @param {any} def Default value * @returns {any} Config property */ get(path, def) { if (!this.loaded) { throw new Error("Config isn't loaded yet!"); } return _.get(this.data, path, def); } static remap(data) { _.forOwn(data, (v, k) => { if (typeof v === "string" && v[0] === "#") { data[k] = process.env[v.substring(1)]; } else if (typeof v === "object") { data[k] = Config.remap(v); } }); return data; } }
JavaScript
class FactoryExtensionMap { constructor(extensions, data) { this.data = data && typeof data === 'object' ? data : {}; this.extensions = reduce(extensions, (stack, extension, name) => { const ext = typeof extension === 'function' ? new extension() : extension; if (ext instanceof FactoryExtension) { stack[name] = ext; } return stack; }, {}); } requestStarted() { forEach(this.extensions, ext => ext.requestStarted()); } requestEnded() { forEach(this.extensions, ext => ext.requestEnded()); // compile the extension data into a single object reduce(this.extensions, (data, extension, name) => { data[name] = extension.data; return data; }, this.data); } parsingStarted() { forEach(this.extensions, ext => ext.parsingStarted()); } parsingEnded() { forEach(this.extensions, ext => ext.parsingEnded()); } validationStarted() { forEach(this.extensions, ext => ext.validationStarted()); } validationEnded() { forEach(this.extensions, ext => ext.validationEnded()); } resolveStarted(...args) { return map(this.extensions, ext => ext.resolveStarted(...args)); } resolveEnded(dataMap, error) { Object.keys(this.extensions).forEach((name, i) => { const ext = this.extensions[name]; ext.resolveEnded(dataMap[i], error); }); } executionStarted() { forEach(this.extensions, ext => ext.executionStarted()); } executionEnded() { forEach(this.extensions, ext => ext.executionEnded()); } warning(value) { forEach(this.extensions, ext => ext.warning(value)); } }
JavaScript
class Srvem { /** * Constructs a new Srvem application. */ constructor() { /** * An array to store middlewares (and handlers that are tranformed into middlewares). */ this.middleware = []; this.server = http_1.createServer(async (request, response) => { const ctx = new Context_1.Context(request, response); for (const m of this.middleware) await m.main(ctx); ctx.finish(); }); } /** * Adds middleware to be executed, with order (including handlers), * whenever the Srvem server receives a request. * * @param middleware Srvem middleware */ use(...middleware) { for (const m of middleware) this.middleware.push(m); } /** * Adds request handler callback function(s), set to be executed, with order * (including middleware), whenever the Srvem server receives a request. * * @param handlers Callback function that handles requests like a middleware */ handle(...handlers) { for (const handler of handlers) this.middleware.push(new (class M extends MiddlewareBlueprint_1.MiddlewareBlueprint { async main(ctx) { return handler(ctx); } })()); } }
JavaScript
class HardBreak extends BaseHardBreak { toMarkdown(state) { if (!state.atBlank()) state.write(' \n'); } }
JavaScript
class MilesianCalendar { constructor (id,pldr) { this.id = id; this.pldr = pldr; } /* Basic references for the Milesian calendar */ canvas = "iso8601" stringFormat = "fields" // formatting options for Milesian calendars partsFormat = { era : {mode : "field"}, year : {mode : "pldr"}, month : {mode : "pldr"} } milesianClockwork = new Cbcce ( { //calendRule object, used with Posix epoch timeepoch : -62168083200000, // Unix timestamp of 1 1m 000 00h00 UTC in ms coeff : [ {cyclelength : 12622780800000, ceiling : Infinity, subCycleShift : 0, multiplier : 400, target : "year"}, {cyclelength : 3155673600000, ceiling : 3, subCycleShift : 0, multiplier : 100, target : "year"}, {cyclelength : 126230400000, ceiling : Infinity, subCycleShift : 0, multiplier : 4, target : "year"}, {cyclelength : 31536000000, ceiling : 3, subCycleShift : 0, multiplier : 1, target : "year"}, {cyclelength : 5270400000, ceiling : Infinity, subCycleShift : 0, multiplier : 2, target : "month"}, {cyclelength : 2592000000, ceiling : 1, subCycleShift : 0, multiplier : 1, target : "month"}, {cyclelength : 86400000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "day"}, {cyclelength : 3600000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "hours"}, {cyclelength : 60000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "minutes"}, {cyclelength : 1000, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "seconds"}, {cyclelength : 1, ceiling : Infinity, subCycleShift : 0, multiplier : 1, target : "milliseconds"} ], canvas : [ {name : "year", init : 0}, {name : "month", init : 1}, {name : "day", init : 1}, {name : "hours", init : 0}, {name : "minutes", init : 0}, {name : "seconds", init : 0}, {name : "milliseconds", init : 0}, ] }) // end of calendRule milesianWeek = new WeekClock ( { originWeekday: 4, // Use day part of Posix timestamp, week of day of 1970-01-01 is Thursday daysInYear: (year) => (Cbcce.isGregorianLeapYear( year + 1 ) ? 366 : 365), // leap year rule for Milesian calendar characDayIndex: (year) => ( Math.floor(this.counterFromFields({year : year, month : 1, day : 7})/Milliseconds.DAY_UNIT) ), startOfWeek : 0, // week start with 0 characWeekNumber : 0, // we have a week 0 and the characteristic day for this week is 7 1m. dayBase : 0, // use 0..6 display for weekday weekBase : 0, // number of week begins with 0 weekLength : 7 // the Milesian week is the 7-days well-known week } ) /* Field control */ solveAskedFields (askedFields) { var fields = {...askedFields}; if (fields.year != undefined && fields.fullYear != undefined) { if (fields.year != fields.fullYear) throw new TypeError ('Unconsistent year and fullYear fields: ' + fields.year + ', ' + fields.fullYear) } else { if (fields.year != undefined) { fields.fullYear = fields.year } else if (fields.fullYear != undefined) fields.year = fields.fullYear }; return fields } /* Basic conversion methods */ fieldsFromCounter (timeStamp) { // year, month, day, from Posix timestamp, UTC // let TZOffset = TZ == "UTC" ? 0 : new ExtDate("iso8601",timeStamp).getRealTZmsOffset(); // decide not to use TZ here let fields = this.milesianClockwork.getObject (timeStamp); fields.fullYear = fields.year; return fields } counterFromFields (fields) { // Posix timestamp at UTC, from year, month, day and possibly time in Milesian let myFields = { year : 0, month : 1, day : 1, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 }; myFields = Object.assign (myFields, this.solveAskedFields(fields)); return this.milesianClockwork.getNumber( myFields ) } buildDateFromFields (fields, construct = ExtDate) { // Construct an ExtDate object from the date in this calendar (UTC) // let timeStamp = this.counterFromFields (fields, TZ); return new construct (this, this.counterFromFields(fields)) } weekFieldsFromCounter (timeStamp) { // week coordinates : number of week, weekday, last/this/next year, weeks in weekyear //let characDayFields = this.fieldsFromCounter (timeStamp); characDayFields.month = 1; characDayFields.day = 7; let fields = this.milesianClockwork.getObject (timeStamp), myFigures = this.milesianWeek.getWeekFigures(Math.floor(timeStamp/Milliseconds.DAY_UNIT), fields.year); return {weekYearOffset : myFigures[2], weekYear : fields.year + myFigures[2], weekNumber : myFigures[0], weekday : myFigures[1], weeksInYear : myFigures[3], hours : fields.hours, minutes : fields.minutes, seconds : fields.seconds, milliseconds : fields.milliseconds} } counterFromWeekFields (fields) { // Posix timestamp at UTC, from weekYear, weekNumber, dayOfWeek and time in Milesian let myFields = { weekYear : 0, weekNumber : 0, weekday : 0, hours : 0, minutes : 0, seconds : 0, milliseconds : 0 }; myFields = Object.assign (myFields, fields); return this.milesianWeek.getNumberFromWeek (myFields.weekYear, myFields.weekNumber, myFields.weekday) * Milliseconds.DAY_UNIT + myFields.hours * Milliseconds.HOUR_UNIT + myFields.minutes * Milliseconds.MINUTE_UNIT + myFields.seconds * Milliseconds.SECOND_UNIT + myFields.milliseconds; } /* Simple properties and method as inspired by Temporal */ eras = null // list of code values for eras. No era in Milesian calendar. inLeapYear (fields) { // is the Milesian year of this date a Milesian leap year. return Cbcce.isGregorianLeapYear ( fields.year + 1 ) } }