language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class OnvifCameraForm extends api.exported.CameraForm { /** * Cemra form * * @param {number} id An identifier * @param {string} plugin A plugin * @param {string} name Camera's name * @param {boolean} def Camera's default * @param {string} ip Camera's IP * @param {string} port Camera's port * @param {string} username Camera's username * @param {string} password Camera's password * @param {boolean} archive Archive pictures * @param {boolean} cv Computer vision * @param {boolean} cvfps Computer vision FPS * @param {boolean} cvlive Computer vision live view * @returns {CameraForm} The instance */ constructor(id, plugin, name, def = false, ip, port, username, password, archive = true, cv = false, cvfps = 3, cvlive = false) { super(id, plugin, name, def, ip, port, username, password, archive, cv, cvfps, cvlive); /** * @Property("ip"); * @Type("string"); * @Enum("getOnVifDevices"); * @EnumNames("getOnVifDevices"); */ this.ip = ip; /** * @Property("port"); * @Type("number"); * @Hidden(true); * @Default(80); */ this.port = port; } /** * Get onvif devices * * @param {...object} inject The onvif devices list array * @returns {Array} The onvif devices */ static getOnVifDevices(...inject) { return inject[0]; } /** * Convert JSON data to object * * @param {object} data Some data * @returns {CameraForm} An instance */ json(data) { return super.json(data); } }
JavaScript
class Onvif extends api.exported.Camera { /** * Sumpple camera * * @param {PluginAPI} api A plugin api * @param {number} [id=null] An id * @param {object} [configuration=null] The configuration for camera * @returns {Sumpple} The instance */ constructor(api, id, configuration) { super(api, id, configuration); this.mjpegUrl = false; this.cam = null; if (this.configuration && this.configuration.ip) { if (ports[this.configuration.ip]) { this.configuration.port = parseInt(ports[this.configuration.ip]); this.updateConfiguration(); } if (this.configuration.snapshotUrl) { this.snapshotUrl = this.configuration.snapshotUrl; } if (this.configuration.rtspUrl) { this.rtspUrl = this.configuration.rtspUrl; } this.cam = new onvif.Cam({ hostname: this.configuration.ip, username: this.configuration.username, password: this.configuration.password, port: this.configuration.port }, (err) => { if (err) { api.exported.Logger.err(err); } else { this.cam.getSnapshotUri((err, res) => { if (err) { api.exported.Logger.err(err); } else { this.snapshotUrl = res.uri.replace(/\n/g, "").replace(/\r/g, ""); this.configuration.snapshotUrl = this.snapshotUrl; api.configurationAPI.saveData(this.configuration); } this.cam.getStreamUri((err, res) => { if (err) { api.exported.Logger.err(err); } else { this.rtspUrl = res.uri.replace(/\n/g, "").replace(/\r/g, ""); this.configuration.rtspUrl = this.rtspUrl; api.configurationAPI.saveData(this.configuration); } }); }); } }); } } }
JavaScript
class Ray extends LinearShape { constructor(options) { super(options); } /** * @inheritdoc */ approx(other, tolerance) { var uHat = vec3.normalize([], this.vec); var vHat = vec3.normalize([], other.vec); return other instanceof KraGL.math.Ray && KraGL.math.Vectors.approx(this.p1, other.p1, tolerance) && KraGL.math.Vectors.approx(uHat, vHat, tolerance); } /** * @inheritdoc */ clone() { return new Ray({ p1: this.p1, p2: this.p2 }); } /** * @inheritdoc */ containsProjection(alpha) { return alpha >= 0; } }
JavaScript
class File { /** * The complete id of the file, including folder and name * @type string */ get id() { return this._id; } /** * The fully url to the file, can be directly used to link the file, i.e. in link tags ot image sources * @type string */ get url() { if (this.isFolder) { throw new Error("Url can not be created for folders."); } if (!this._url) { this._url = this._db.createURL(this.id, this.bucket != 'www'); } return this._url; } /** * The name of the file * @type string */ get name() { if (!this._name) this._name = this._id.substring(this._id.lastIndexOf('/', this._id.length - 2) + 1); return this._name; } /** * The mimeType of the file, only accessible after fetching the metadata or downloading/uploading/providing the file * @type string */ get mimeType() { if (this.isFolder) { throw new Error("A folder has no mimeType"); } this._checkAvailable(); return this._mimeType; } /** * The current file acl, only accessible after fetching the metadata or downloading/uploading/providing the file * @type string */ get acl() { this._checkAvailable(); return this._acl; } /** * The last modified date of the file, only accessible after fetching the metadata or downloading/uploading/providing the eTag * @type string */ get lastModified() { if (this.isFolder) { throw new Error("A folder has no lastModified"); } this._checkAvailable(); return this._lastModified; } /** * The eTag of the file, only accessible after fetching the metadata or downloading/uploading/providing the file * @type string */ get eTag() { if (this.isFolder) { throw new Error("A folder has no eTag"); } this._checkAvailable(); return this._eTag; } /** * The size of the file, only accessible after fetching the metadata or downloading/uploading/providing the file * @type string */ get size() { if (this.isFolder) { throw new Error("A folder has no size"); } this._checkAvailable(); return this._size; } get bucket() { return this.id.substring(LEN + 1, this.id.indexOf('/', LEN + 1)); } get key() { return this.id.substring(this.id.indexOf('/', LEN + 1) + 1); } /** * The full path of the file. * @type string */ get path() { return this.id.substring(LEN); } /** * The parent folder of the file. * @type string */ get parent() { return this.id.substring(LEN, this.id.lastIndexOf('/', this.id.length - 2)); } /** * Indicates if the metadata are loaded. * @type boolean */ get isMetadataLoaded() { return this._available; } /** * Creates a new file object which represents the a file at the given id. Data are provided to the constructor will * be uploaded by invoking {@link upload()} * @param {object|string} fileOptions The fileOptions used to create a new file object, or just the id of the * file object * @param {string=} fileOptions.id The id of the file. * @param {string=} fileOptions.name The filename without the id. If omitted and data is provided as a file object, the * {@link File#name} will be used otherwise a uuid will be generated. * @param {string} [fileOptions.parent="/www"] The parent folder which contains the file * @param {string} [fileOptions.path="/www"] The full path of the file. You might either specifiy the path of the file or a combination of parent and file name. * @param {string|Blob|File|ArrayBuffer|json=} fileOptions.data The initial file content, which will be uploaded by * invoking {@link #upload} later on. * @param {string=} fileOptions.type A optional type hint used to correctly interpret the provided data * @param {string=} fileOptions.mimeType The mimType of the file. Defaults to the mimeType of the provided data if * it is a file object, blob or data-url * @param {string=} fileOptions.eTag The optional current ETag of the file * @param {string=} fileOptions.lastModified The optional last modified date * @param {Acl=} fileOptions.acl The file acl which will be set, if the file is uploaded afterwards */ constructor(fileOptions) { fileOptions = fileOptions || {}; this._available = false; if (Object(fileOptions) instanceof String) { let id = fileOptions; let nameSeparator = id.indexOf('/', '/file/'.length); if (nameSeparator == -1 || id.indexOf('/file/') != 0) { throw new Error('Invalid file reference ' + id); } this._id = id; } else if (fileOptions.id) { this._id = fileOptions.id; this._setMetadata(fileOptions); } else { let path; if (fileOptions.path) { path = fileOptions.path; } else { let parent = fileOptions.parent || '/www'; if (parent.charAt(parent.length - 1) != '/') parent = parent + '/'; if (parent.length < 3) { throw new Error('Invalid parent name: ' + parent); } let name = fileOptions.name || (fileOptions.data && fileOptions.data.name) || util.uuid(); path = parent + name; } if (path.charAt(0) != '/') path = '/' + path; if (path.indexOf('//') != -1 || path.length < 3) throw new Error('Invalid path: ' + path); this._id = PREFIX + path; this._setMetadata(fileOptions); } /** * Specifies whether this file is a folder. * @type {boolean} */ this.isFolder = this._id.charAt(this._id.length - 1) == '/'; } /** * Uploads the file content which was provided in the constructor or by uploadOptions.data * @param {object=} uploadOptions The upload options * @param {string|Blob|File|ArrayBuffer|json=} uploadOptions.data The initial file content, which will be uploaded by * invoking {@link #upload} later on. * @param {string=} uploadOptions.type A optional type hint used to correctly interpret the provided data * @param {string=} uploadOptions.mimeType The mimType of the file. Defaults to the mimeType of the provided data if * it is a file object, blob or data-url * @param {string=} uploadOptions.eTag The optional current ETag of the file * @param {string=} uploadOptions.lastModified The optional last modified date * @param {Acl=} uploadOptions.acl The file acl which will be set, if the file is uploaded afterwards * @param {boolean} [uploadOptions.force=false] force the upload and overwrite any existing files without validating it * @param {connector.Message~progressCallback} [uploadOptions.progress] listen to progress changes during upload * @param {binding.File~fileCallback=} doneCallback The callback is invoked after the upload succeed successfully * @param {binding.File~failCallback=} failCallback The callback is invoked if any error is occurred * @return {Promise<binding.File>} A promise which will be fulfilled with this file object where the metadata is updated */ upload(uploadOptions, doneCallback, failCallback) { uploadOptions = uploadOptions || {}; if (this.isFolder) { throw new Error("A folder cannot be uploaded"); } this._setMetadata(uploadOptions); const uploadMessage = new message.UploadFile(this.bucket, this.key) .entity(this._data, this._type) .acl(this._acl); uploadMessage.progress(uploadOptions.progress); if (this._size) { uploadMessage.contentLength(this._size); } if (this._mimeType) { uploadMessage.mimeType(this._mimeType); } this._conditional(uploadMessage, uploadOptions); this._db.addToBlackList(this.id); return this._db.send(uploadMessage).then((response) => { this._data = null; this._type = null; this.fromJSON(response.entity); return this; }).then(doneCallback, failCallback); } /** * Download a file and providing it in the requested type * @param {object=} downloadOptions The download options * @param {string} [downloadOptions.type="blob"] The type used to provide the file * @param {string} [downloadOptions.refresh=false] Indicates to make a revalidation request and not use the cache * @param {binding.File~downloadCallback=} doneCallback The callback is invoked after the download succeed successfully * @param {binding.File~failCallback=} failCallback The callback is invoked if any error is occurred * @return {Promise<string|Blob|File|ArrayBuffer|json>} A promise which will be fulfilled with the downloaded file content */ download(downloadOptions, doneCallback, failCallback) { downloadOptions = downloadOptions || {}; if (this.isFolder) { throw new Error("A folder cannot be downloaded"); } var type = downloadOptions.type || 'blob'; var downloadMessage = new message.DownloadFile(this.bucket, this.key) .responseType(type); this._db.ensureCacheHeader(this.id, downloadMessage, downloadOptions.refresh); return this._db.send(downloadMessage).then((response) => { this._db.addToWhiteList(this.id); this._fromHeaders(response.headers); return response.entity; }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { return null; } else { throw e; } }).then(doneCallback, failCallback); } /** * Deletes a file * @param {object=} deleteOptions The delete options * @param {boolean} [deleteOptions.force=false] force the deletion without verifying any version * @param {binding.File~deleteCallback=} doneCallback The callback is invoked after the deletion succeed successfully * @param {binding.File~failCallback=} failCallback The callback is invoked if any error is occurred * @return {Promise<binding.File>} A promise which will be fulfilled with this file object */ delete(deleteOptions, doneCallback, failCallback) { deleteOptions = deleteOptions || {}; if (this.isFolder) { throw new Error("A folder cannot be deleted"); } var deleteMessage = new message.DeleteFile(this.bucket, this.key); this._conditional(deleteMessage, deleteOptions); this._db.addToBlackList(this.id); return this._db.send(deleteMessage).then(function() { return this; }).then(doneCallback, failCallback); } _conditional(message, options) { if (!options.force) { if (this._lastModified) message.ifUnmodifiedSince(this._lastModified); if (this._eTag) message.ifMatch(this._eTag); if (!this._lastModified && !this._eTag) message.ifNoneMatch('*'); } } /** * Gets the file metadata of a file * @param {Object} options The load metadata options * @param {Object} [options.refresh=false] Force a revalidation while fetching the metadata * @param {binding.File~fileCallback=} doneCallback The callback is invoked after the metadata is fetched * @param {binding.File~failCallback=} failCallback The callback is invoked if any error has occurred * @return {Promise<binding.File>} A promise which will be fulfilled with this file */ loadMetadata(options, doneCallback, failCallback) { options = options || {}; if (this.isFolder) { throw new Error("A folder has no matadata"); } let msg = new message.GetFileMetadata(this.bucket, this.key); this._db.ensureCacheHeader(this.id, msg, options.refresh); return this._db.send(msg).then((response) => { // do not white list the file, because head-request does not revalidate the cache. this._fromHeaders(response.headers); return this; }, (e) => { if (e.status == StatusCode.OBJECT_NOT_FOUND) { return null; } else { throw e; } }).then(doneCallback, failCallback); } /** * Updates the matadata of this file. * @param {boolean} [options.force=false] force the update and overwrite the existing metadata without validating it * @return {Promise<binding.File>} A promise which will be fulfilled with this file */ saveMetadata(options, doneCallback, failCallback) { options = options || {}; let metadata = this.toJSON(); metadata.id = this._id; let msg = new message.UpdateFileMetadata(this.bucket, this.key) .entity(metadata); this._conditional(msg, options); return this._db.send(msg).then((response) => { this.fromJSON(response); return this; }); } /** * Validates and sets the file metadata based on the given options * @param {Object} options * @private */ _setMetadata(options) { let data = options.data; let type = options.type; let eTag = options.eTag; let acl = options.acl; let size = options.size; let mimeType = options.mimeType; let lastModified = options.lastModified; if (!data) { this._available = false; } else { if (typeof Blob !== "undefined" && data instanceof Blob) { mimeType = mimeType || data.type; } else if (type == 'data-url') { let match = data.match(/^data:(.+?)(;base64)?,.*$/); mimeType = mimeType || match[1]; } this._data = data; this._type = type; this._size = size; this._mimeType = mimeType; this._acl = acl || this._acl || new Acl(); this._available = true; } this._eTag = eTag || this._eTag; if (lastModified) { this._lastModified = new Date(lastModified); } } _fromHeaders(headers) { this.fromJSON({ eTag: headers.etag ? headers.etag.substring(1, headers.etag.length - 1) : null, lastModified: headers['last-modified'], mimeType: headers['content-type'], acl: headers['baqend-acl'] && JSON.parse(headers['baqend-acl']), contentLength: +headers['baqend-size'] }); } fromJSON(metadata) { if (metadata.mimeType) this._mimeType = metadata.mimeType; if (metadata.lastModified) this._lastModified = new Date(metadata.lastModified); if (metadata.eTag) this._eTag = metadata.eTag; this._acl = this._acl || new Acl(); if (metadata.acl) this._acl.fromJSON(metadata.acl); if (metadata.contentLength) this._size = metadata.contentLength; this._available = true; } toJSON() { var result = { mimeType: this._mimeType, eTag: this._eTag, acl: this._acl, contentLength: this._size }; if (this._lastModified) { result.lastModified = this._lastModified.toISOString(); } return result; } _checkAvailable() { if (!this._available) { throw new error.PersistentError('The file metadata of ' + this.id + ' is not available.'); } } /** * The database connection to use * @member {EntityManager} _db * @private */ }
JavaScript
class EncryptionServiceProvider extends ServiceProvider_1.default { /** * Registers Service Provider */ register() { this.app.singleton({ provider: { name: 'Haluka/Core/Encryptor', alias: 'Encryption' }, content: function () { const key = config('app.key'); if (!key) throw new Exceptions_1.FatalException('No Application Key Found in .env file'); return new Encryption_1.Encryptor(key, config('app.cipher')); } }); } }
JavaScript
class DemoReparentNodeHandler extends ReparentNodeHandler { /** * In general, this method determines whether the current gesture that * can be determined through the context is a reparent gesture. In this * case, it returns true, if the base implementation returns true or if the * current node is green. * @param {IInputModeContext} context The context that provides information about the * user input. * @param {INode} node The node that will possibly be reparented. * @return {boolean} Whether this is a reparenting gesture. * @see Overrides {@link ReparentNodeHandler#isReparentGesture} * @see Specified by {@link IReparentNodeHandler#isReparentGesture}. */ isReparentGesture(context, node) { return super.isReparentGesture(context, node) || node.tag === 'green' } /** * In general, this method determines whether the user may detach the * given node from its current parent in order to reparent it. In this case, * it returns false for red nodes. * @param {IInputModeContext} context The context that provides information about the * user input. * @param {INode} node The node that is about to be detached from its * current parent. * @return {boolean} Whether the node may be detached and reparented. * @see Overrides {@link ReparentNodeHandler#shouldReparent} * @see Specified by {@link IReparentNodeHandler#shouldReparent}. */ shouldReparent(context, node) { return !(node.tag === 'firebrick') } /** * In general, this method determines whether the provided node * may be reparented to the given <code>newParent</code>. * @param {IInputModeContext} context The context that provides information about the * user input. * @param {INode} node The node that will be reparented. * @param {INode} newParent The potential new parent. * @return {boolean} Whether <code>newParent</code> is a valid new parent * for <code>node</code>. * @see Overrides {@link ReparentNodeHandler#isValidParent} * @see Specified by {@link IReparentNodeHandler#isValidParent}. */ isValidParent(context, node, newParent) { // Obtain the tag from the designated child const nodeTag = node.tag // and from the designated parent. const parentTag = newParent === null ? null : newParent.tag if (nodeTag === null) { // Newly created nodes or nodes without a tag in general can be reparented freely return true } // Otherwise allow nodes to be moved only if their tags are the same color if (typeof nodeTag === 'string' && typeof parentTag === 'string') { return nodeTag === parentTag } // Finally, if there is no new parent, this is ok, too return newParent === null } }
JavaScript
class ServicesPlacesCtrl { constructor() { this.create = this.constructor.create.bind(this); this.searchService = this.constructor.searchService.bind(this); this.searchPlaces = this.constructor.searchPlaces.bind(this); } /** * [create is a function of add a new Service Places] * @param {Function} next [create] * @return {json} [return 201 when is created a new objet in db] */ static async create(req, res, next) { try { const data = await servicesPlacesMdl.create(req.body); res.status(201).send({ message: `ID: ${data}` }); } catch (e) { next(e); } } /** * [searchService is a function to get services by id] * @param {[int]} req [id] * @return {json} [returns the object in case that exist or 400 if doesn't exists] */ static async searchService(req, res, next) { try { const data = await servicesPlacesMdl.findByService(req.params.serviceID); // In case user was not found if (data.length === 0) { res.status(400).send({ message: 'Service not found' }); return; } res.status(200).send({ data }); } catch (e) { next(e); } } /** * [searchPlaces is a function to get Places by id] * @param {[int]} req [id] * @return {json} [returns the object in case that exist or 400 if doesn't exists] */ static async searchPlaces(req, res, next) { try { console.log(req.params); const data = await servicesPlacesMdl.findByPlace(req.params.placeID); // In case user was not found if (data.length === 0) { res.status(400).send({ message: 'Places not found' }); return; } res.status(200).send({ data }); } catch (e) { next(e); } } }
JavaScript
class Message { constructor (errorCallback) { this.errorCallback = errorCallback || function () { } this.checkInterval = null const self = this setTimeout(() => { self.connect() }, 400) } getPort () { chrome = typeof browser === 'undefined' ? chrome : browser return typeof chrome.runtime === 'undefined' ? chrome.extension : chrome.runtime } connect () { if (this.port) { return } const messageCallbacks = this.messageCallbacks = [] this.port = this.getPort().connect({name: 'riteforge-connect'}) this.port.onDisconnect.addListener(() => { console.log('port disconnected') }) this.port.onMessage.addListener((msg) => { messageCallbacks.forEach((callback) => { if (callback.id === msg.id) { callback.fn(msg) callback.remove = true } }) }) const self = this this.checkInterval = setInterval(function () { self.sendMessage({action: 'test'}, () => { }) }, 5000) } setErrorCalback (callback) { this.errorCallback = callback } sendMessage (message, callback) { if (!this.port) { this.connect() } if (callback) { const id = Math.random() message.id = id this.messageCallbacks.push({ fn: callback, id: id, remove: false }) } try { this.port.postMessage(message) } catch (error) { if (this.checkInterval) { clearInterval(this.checkInterval) } this.errorCallback(error, this) } } disconnect () { try { this.port.disconnect() } catch (ignore) { console.log(ignore) } this.port = null } reconnect () { this.disconnect() this.connect() } }
JavaScript
class RitekitModal { constructor () { window.addEventListener('message', function (e) { if (e.data === 'closeRitetagModal') { // window.focus(); let els = document.querySelectorAll('#rtagWindow') for (let i = 0; i < els.length; i++) { let el = els[i] try { el.parentNode.removeChild(el) } catch (ignore) { } } } else if (e.data.command === 'save-token-2') { // todo simplify messenger.sendMessage({action: 'save-token', payload: e.data.data.result}, (message) => { console.log(message) window.close() }) } }) } openModalUrl (src, onclose) { const win = window.open(src, '_blank') win.focus() let errors = 0 if (onclose) { let modalCloseInterval = setInterval(() => { try { // console.log(win) // console.log("is closed: " + win.closed) if (win.closed) { clearInterval(modalCloseInterval) onclose() } } catch (e) { // console.log("error") // console.log(e) errors++ if (errors > 4) { clearInterval(modalCloseInterval) onclose() } } }, 150) } } }
JavaScript
class ActionCard extends Card { /** * Creates a title, description, and a continue button * and adds them to the card. * * @param {Phaser.Scene} scene The scene this belongs to. * @param {GameManager} game The game instance this belongs to. * @param {CardConfig} config The card configuration to observe. * @param {Player} player The player instance this card acts upon. */ constructor(scene, game, config, player) { super(scene, game); this.player = player; const title = new Phaser.GameObjects.Text(this.scene, 0, -250, config.name, CardStyle); title.setStyle({ fixedWidth: this.background.width, wordWrap: {width: this.background.width - 50, useAdvancedWrap: true} }); title.setX(title.x - (title.width /2)); this.continueButton = new Button(this.scene, -190, 240, 380, 50, "Continue", Buttons.AMBER); this.add([title, this.continueButton]); } }
JavaScript
class Contributor { /** * Constructs a new <code>Contributor</code>. * Get repository contributors * @alias module:model/Contributor */ constructor() { Contributor.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>Contributor</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/Contributor} obj Optional instance to populate. * @return {module:model/Contributor} The populated <code>Contributor</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new Contributor(); if (data.hasOwnProperty('additions')) { obj['additions'] = ApiClient.convertToType(data['additions'], 'String'); } if (data.hasOwnProperty('commits')) { obj['commits'] = ApiClient.convertToType(data['commits'], 'String'); } if (data.hasOwnProperty('deletions')) { obj['deletions'] = ApiClient.convertToType(data['deletions'], 'String'); } if (data.hasOwnProperty('email')) { obj['email'] = ApiClient.convertToType(data['email'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } } return obj; } }
JavaScript
class HostingPlans extends Component { constructor(props) { super(props); this.state = { updatedSubscriptions : this.props.subscriptions, plans: [] } } render() { var hostingPlans = null if(this.props.subscriptions) { var updatedSubscriptions = setHostingPlans(this.state.updatedSubscriptions, this.state.plans); hostingPlans = updatedSubscriptions.map(subscription => { const date = subscription.renewDate.substring(8,10) return( <React.Fragment> <div> <div className='segment'> <p className='standard'>{subscription.name}</p> <p className='standard'></p> <p className='good'>Online</p> <p className='standard'>{date}th</p> {/* TODO: <p onClick={e => this.manageHosting(subscription.subscription.name, subscription.renewDate)} className='standard manage-hosting-link'>Manage<img src='/images/icons/carrot-down.png' alt='Open Manage Menu Button' className='dropdown-carrot' /></p> */} </div> </div> </React.Fragment> ) }); } console.log() if(hostingPlans.length === 0) { return ( <React.Fragment> <h2>No hosting plans yet</h2> <button class='sub-btn'><NavLink className='no-link-style' to='/get-hosting'>Add Hosting Plan</NavLink></button> </React.Fragment> ) } else { return ( <React.Fragment> <div className='subscriptions-container'> <h3>My Hosting Plans</h3> {hostingPlans} </div> </React.Fragment> ) } } manageHosting(name, renewDate) { console.log(name, renewDate) } async componentWillMount() { let IDs = this.props.subscriptions.map(subIDs => subIDs.subscription) let res = await axios.post(GET_PLAN_FROM_ID, {id: IDs }) this.setState({ plans: res.data }) } }
JavaScript
class BookList extends Component { renderList(){ return this.props.books.map((book) => { return ( <li key={book.title} onClick={() => this.props.selectBook(book)} className="list-group-item"> {book.title} </li> ); }) } render(){ return ( <ul className="list-group col-sm-4"> {this.renderList()} </ul> ) } }
JavaScript
class Kucing { // Property mata = 2; kaki = 4; nama = 'Langit'; // Method berjalan() { console.log( `Hallo, nama saya ${this.nama} mata saya ${this.mata} kaki saya ${this.kaki}` ); } }
JavaScript
class RotationAwareGroupBoundsCalculator extends BaseClass(IGroupBoundsCalculator) { /** * Calculates the minimum bounds for the given group node to enclose all its children plus insets. * @param {IGraph} graph * @param {INode} groupNode * @return {Rect} */ calculateBounds(graph, groupNode) { let bounds = Rect.EMPTY graph.getChildren(groupNode).forEach(node => { const styleWrapper = node.style if (styleWrapper instanceof RotatableNodeStyleDecorator) { // if the node supports rotation: add the outer bounds of the rotated layout bounds = Rect.add(bounds, styleWrapper.getRotatedLayout(node).bounds) } else { // in all other cases: add the node's layout bounds = Rect.add(bounds, node.layout.toRect()) } }) // if we have content: add insets return bounds.isEmpty ? bounds : bounds.getEnlarged(getInsets(groupNode)) } }
JavaScript
class InValidationRule extends ValidationRule { /** * The class constructor. * * @param {?string[]} [params] An array of strings containing some additional parameters the validation should take care of. * * @throws {InvalidArgumentException} If an invalid array of parameters is given. * @throws {InvalidArgumentException} If an empty list of possible options is given. */ constructor(params) { super(params); /** * @type {string[]} _expectedValues An array of strings containing the possible options for the values being validated. * * @protected */ this._expectedValues = []; if ( params === null || params.length === 0 ){ throw new InvalidArgumentException('No possible option given.', 1); } this._expectedValues = params; } /** * Validates a given value. * * @param {*} value The value to validate, usually a string, however, no type validation is performed allowing to pass an arbitrary value. * @param {Validator} validator An instance of the "Validator" class representing the validator this rule is used in. * @param {Object.<string, *>} params An object containing all the parameters being validated by the validator this rule is used in. * * @returns {boolean} If validation passes will be returned "true". */ validate(value, validator, params){ return this._expectedValues.indexOf(value) >= 0; } /** * Returns the error message that should be returned whenever this validation rule fails. * * @returns {string} A string containing the error message. */ getMessage() { return 'Field {fieldName} must be one of the following: ' + this._expectedValues.join(', ') + '.'; } }
JavaScript
class InitResponse extends UploadOptionsBase { /** * Constructs a new instance of an init call response. * * @param {objects} options The options controlling the overall process. * @param {DirectBinaryUploadOptions} uploadOptions The options controlling the upload process. * @param {Array} uploadFiles List of UploadFile instances that are being uploaded. * @param {object} initData The raw data as provided by the init request's response. */ constructor(options, uploadOptions, uploadFiles, initData) { super(options, uploadOptions); this.uploadFiles = uploadFiles; this.initData = initData; } /** * Retrieves the list of files initialized by the init request. * * @returns {Array} Information on initialized files. Each item in the array is an * InitResponseFile instance. */ getFiles() { const { files = [] } = this.initData; return files.map((file, index) => new InitResponseFile( this.getOptions(), this.getUploadOptions(), this.uploadFiles[index], file, )); } /** * Retrieves all the parts for all the files in the upload. The list will be grouped by * file, in the same order in which the files were provided to the upload process; the * parts themselves will be sorted in the order by which they should be uploaded. * * @returns {Array} A list of InitResponseFilePart instances. */ getAllParts() { const parts = []; this.getFiles().forEach(initFile => { initFile.getParts().forEach(initFilePart => { parts.push(initFilePart); }); }); return parts; } /** * Retrieves the URI that can be called as-is for completing the upload process. * * @returns {string} URI to invoke for completing the upload process. */ getCompleteUri() { let { completeURI } = this.initData; // older versions of the API return file-specific completeURIs. In this case, use the // first file's URI. if (!completeURI && this.getFiles().length > 0) { const fileCompleteURI = this.getFiles()[0].getFileData('completeURI'); if (fileCompleteURI) { completeURI = fileCompleteURI; } } // older versions of the API return absolute URIs for the completeURI. In this case, // convert the URI to relative if (completeURI) { completeURI = URL.parse(encodeURI(completeURI)).pathname; // remove instance context path, if necessary const contentIndex = completeURI.indexOf('/content/dam'); if (contentIndex > 0) { completeURI = completeURI.substr(contentIndex); } } return `${this.getUploadOptions().getUrlPrefix()}${completeURI}`; } /** * Converts the class instance into a single object form containing all relevant information. * * @returns {object} Simplified view of the object's data. */ toJSON() { return this.initData; } }
JavaScript
class FileConfigurationService extends PlantWorksBaseService { // #region Constructor constructor(parent) { super(parent); this.$cacheMap = {}; } // #endregion // #region setup/teardown code /** * @async * @function * @override * @instance * @memberof FileConfigurationService * @name _setup * * @returns {boolean} Boolean true/false. * * @summary Sets up the file watcher to watch for changes on the fly. */ async _setup() { try { await super._setup(); const chokidar = require('chokidar'), path = require('path'); const rootPath = path.dirname(path.dirname(require.main.filename)); this.$watcher = chokidar.watch(path.join(rootPath, `config${path.sep}${plantworksEnv}`), { 'ignored': /[/\\]\./, 'ignoreInitial': true }); this.$watcher .on('add', this._onNewConfiguration.bind(this)) .on('change', this._onUpdateConfiguration.bind(this)) .on('unlink', this._onDeleteConfiguration.bind(this)); return null; } catch(err) { throw new PlantWorksSrvcError(`${this.name}::_setup error`, err); } } /** * @async * @function * @override * @instance * @memberof FileConfigurationService * @name _teardown * * @returns {boolean} Boolean true/false. * * @summary Shutdown the file watcher that watches for changes on the fly. */ async _teardown() { try { this.$watcher.close(); await super._teardown(); return null; } catch(err) { throw new PlantWorksSrvcError(`${this.name}::_teardown error`, err); } } // #endregion // #region API /** * @async * @function * @instance * @memberof FileConfigurationService * @name loadConfiguration * * @param {PlantWorksBaseModule} plantworksModule - Instance of the {@link PlantWorksBaseModule} that requires configuration. * * @returns {Object} - The plantworksModule's file-based configuration. * * @summary Retrieves the configuration of the plantworksModule requesting for it. */ async loadConfiguration(plantworksModule) { try { let config = null; const plantworksModulePath = this.$parent._getPathForModule(plantworksModule); if(this.$cacheMap[plantworksModulePath]) return this.$cacheMap[plantworksModulePath]; const fs = require('fs'), mkdirp = require('mkdirp'), path = require('path'), promises = require('bluebird'); const filesystem = promises.promisifyAll(fs); const mkdirAsync = promises.promisifyAll(mkdirp); const rootPath = path.dirname(path.dirname(require.main.filename)); const configPath = path.join(rootPath, `config${path.sep}${plantworksEnv}`, `${plantworksModulePath}.js`); await mkdirAsync(path.dirname(configPath)); const doesExist = await this._exists(configPath, filesystem.R_OK); if(doesExist) config = require(configPath).config; this.$cacheMap[plantworksModulePath] = config; return config; } catch(err) { throw new PlantWorksSrvcError(`${this.name}::loadConfig::${plantworksModule.name} error`, err); } } /** * @async * @function * @instance * @memberof FileConfigurationService * @name saveConfiguration * * @param {PlantWorksBaseModule} plantworksModule - Instance of the {@link PlantWorksBaseModule} that requires configuration. * @param {Object} config - The {@link PlantWorksBaseModule}'s' configuration that should be persisted. * * @returns {Object} - The plantworksModule configuration. * * @summary Saves the configuration of the plantworksModule requesting for it. */ async saveConfiguration(plantworksModule, config) { try { const deepEqual = require('deep-equal'), fs = require('fs'), mkdirp = require('mkdirp'), path = require('path'), promises = require('bluebird'); const plantworksModulePath = this.$parent._getPathForModule(plantworksModule); if(deepEqual(this.$cacheMap[plantworksModulePath], config)) return config; this.$cacheMap[plantworksModulePath] = config; const rootPath = path.dirname(path.dirname(require.main.filename)); const configPath = path.join(rootPath, `config${path.sep}${plantworksEnv}`, `${plantworksModulePath}.js`); const mkdirpAsync = promises.promisifyAll(mkdirp); await mkdirpAsync(path.dirname(configPath)); const configString = `exports.config = ${JSON.stringify(config, undefined, '\t')};\n`; const filesystem = promises.promisifyAll(fs); await filesystem.writeFileAsync(configPath, configString); return config; } catch(err) { throw new PlantWorksSrvcError(`${this.name}::saveConfig::${plantworksModule.name} error`, err); } } /** * @async * @function * @instance * @memberof FileConfigurationService * @name getModuleState * * @param {PlantWorksBaseModule} plantworksModule - Instance of the {@link PlantWorksBaseModule} that requires its state. * * @returns {boolean} - Boolean true always, pretty much. * * @summary Empty method, since the file-based configuration module doesn't manage the state. */ async getModuleState(plantworksModule) { return !!plantworksModule; } /** * @async * @function * @instance * @memberof FileConfigurationService * @name setModuleState * * @param {PlantWorksBaseModule} plantworksModule - Instance of the {@link PlantWorksBaseModule} that requires its state. * @param {boolean} enabled - State of the module. * * @returns {Object} - The state of the plantworksModule. * * @summary Empty method, since the file-based configuration module doesn't manage the state. */ async setModuleState(plantworksModule, enabled) { return enabled; } /** * @async * @function * @instance * @memberof FileConfigurationService * @name getModuleId * * @returns {null} - Nothing. * * @summary Empty method, since the file-based configuration module doesn't manage module ids. */ async getModuleId() { return null; } // #endregion // #region Private Methods /** * @async * @function * @instance * @private * @memberof FileConfigurationService * @name _processConfigChange * * @param {PlantWorksBaseModule} configUpdateModule - The plantworksModule for which the configuration changed. * @param {Object} config - The updated configuration. * * @returns {null} - Nothing. * * @summary Persists the configuration to the filesystem. */ async _processConfigChange(configUpdateModule, config) { try { const deepEqual = require('deep-equal'), fs = require('fs'), mkdirp = require('mkdirp'), path = require('path'), promises = require('bluebird'); if(deepEqual(this.$cacheMap[configUpdateModule], config)) return; const rootPath = path.dirname(path.dirname(require.main.filename)); const configPath = path.join(rootPath, `config${path.sep}${plantworksEnv}`, configUpdateModule); this.$cacheMap[configUpdateModule] = config; const mkdirpAsync = promises.promisifyAll(mkdirp); await mkdirpAsync(path.dirname(configPath)); const configString = `exports.config = ${JSON.stringify(config, undefined, '\t')};`; const filesystem = promises.promisifyAll(fs); await filesystem.writeFileAsync(`${configPath}.js`, configString); } catch(err) { console.error(`Process changed configuration to file error: ${err.message}\n${err.stack}`); } } /** * @async * @function * @instance * @private * @memberof FileConfigurationService * @name _processStateChange * * @returns {null} - Nothing. * * @summary Empty method, since the file-based configuration module doesn't manage module states. */ async _processStateChange() { return null; } /** * @async * @function * @instance * @private * @memberof FileConfigurationService * @name _onNewConfiguration * * @param {string} filePath - The absolute path of the new configuration file. * * @returns {null} - Nothing. * * @summary Reads the new configuration, maps it to a loaded plantworksModule, and tells the rest of the configuration services to process it. */ async _onNewConfiguration(filePath) { try { const path = require('path'); const rootPath = path.dirname(path.dirname(require.main.filename)); const plantworksModulePath = path.relative(rootPath, filePath).replace(`config${path.sep}${plantworksEnv}${path.sep}`, '').replace('.js', ''); this.$cacheMap[plantworksModulePath] = require(filePath).config; this.$parent.emit('new-config', this.name, plantworksModulePath, this.$cacheMap[plantworksModulePath]); } catch(err) { console.error(`Process new configuration in ${filePath} error: ${err.message}\n${err.stack}`); } } /** * @async * @function * @instance * @private * @memberof FileConfigurationService * @name _onUpdateConfiguration * * @param {string} filePath - The absolute path of the updated configuration file. * * @returns {null} - Nothing. * * @summary Reads the new configuration, maps it to a loaded plantworksModule, and tells the rest of the configuration services to process it. */ async _onUpdateConfiguration(filePath) { try { const deepEqual = require('deep-equal'), path = require('path'); const rootPath = path.dirname(path.dirname(require.main.filename)); const plantworksModulePath = path.relative(rootPath, filePath).replace(`config${path.sep}${plantworksEnv}${path.sep}`, '').replace('.js', ''); delete require.cache[filePath]; await snooze(500); if(deepEqual(this.$cacheMap[plantworksModulePath], require(filePath).config)) return; this.$cacheMap[plantworksModulePath] = require(filePath).config; this.$parent.emit('update-config', this.name, plantworksModulePath, require(filePath).config); } catch(err) { console.error(`Process updated configuration in ${filePath} error: ${err.message}\n${err.stack}`); } } /** * @async * @function * @instance * @private * @memberof FileConfigurationService * @name _onDeleteConfiguration * * @param {string} filePath - The absolute path of the deleted configuration file. * * @returns {null} - Nothing. * * @summary Removes configuration from the cache, etc., and tells the rest of the configuration services to process it. */ async _onDeleteConfiguration(filePath) { try { const path = require('path'); const rootPath = path.dirname(path.dirname(require.main.filename)); const plantworksModulePath = path.relative(rootPath, filePath).replace(`config${path.sep}${plantworksEnv}${path.sep}`, '').replace('.js', ''); delete require.cache[filePath]; delete this.$cacheMap[plantworksModulePath]; this.$parent.emit('delete-config', this.name, plantworksModulePath); } catch(err) { console.error(`Process deleted configuration in ${filePath} error: ${err.message}\n${err.stack}`); } } // #endregion // #region Properties /** * @override */ get basePath() { return __dirname; } // #endregion }
JavaScript
class FeesEstimateError { /** * Constructs a new <code>FeesEstimateError</code>. * An unexpected error occurred during this operation. * @alias module:client/models/FeesEstimateError * @class * @param type {String} An error type, identifying either the receiver or the sender as the originator of the error. * @param code {String} An error code that identifies the type of error that occurred. * @param message {String} A message that describes the error condition in a human-readable form. * @param detail {module:client/models/FeesEstimateErrorDetail} */ constructor(type, code, message, detail) { this['Type'] = type; this['Code'] = code; this['Message'] = message; this['Detail'] = detail; } /** * Constructs a <code>FeesEstimateError</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:client/models/FeesEstimateError} obj Optional instance to populate. * @return {module:client/models/FeesEstimateError} The populated <code>FeesEstimateError</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new FeesEstimateError(); if (data.hasOwnProperty('Type')) { obj['Type'] = ApiClient.convertToType(data['Type'], 'String'); } if (data.hasOwnProperty('Code')) { obj['Code'] = ApiClient.convertToType(data['Code'], 'String'); } if (data.hasOwnProperty('Message')) { obj['Message'] = ApiClient.convertToType(data['Message'], 'String'); } if (data.hasOwnProperty('Detail')) { obj['Detail'] = FeesEstimateErrorDetail.constructFromObject(data['Detail']); } } return obj; } /** * An error type, identifying either the receiver or the sender as the originator of the error. * @member {String} Type */ 'Type' = undefined; /** * An error code that identifies the type of error that occurred. * @member {String} Code */ 'Code' = undefined; /** * A message that describes the error condition in a human-readable form. * @member {String} Message */ 'Message' = undefined; /** * @member {module:client/models/FeesEstimateErrorDetail} Detail */ 'Detail' = undefined; }
JavaScript
class BoxUtils { static CheckBoxRequirements(box) { var _a; if (!(box === null || box === void 0 ? void 0 : box._BoxConfig)) throw new Error('HyperBox-JS: Must set _BoxConfig on box'); if (!((_a = box === null || box === void 0 ? void 0 : box._BoxConfig) === null || _a === void 0 ? void 0 : _a.name)) throw new Error('HyperBox-JS: Must set _BoxConfig name on box'); } /** * Build a function name that uses a certain prefix. * * @param { String } prefix prefix string e.g. 'get' * @param { String } variableName variable name e.g. 'name' */ static BuildPrefixedFunctionName(prefix, variableName) { let returnName = BoxUtils.CapitalizeFirstLetter(variableName); returnName = `${prefix}${returnName}`; return returnName; } /** * Build the setter name for a variable name. * * @param { String } variableName variable name. */ static BuildSetterName(variableName) { return BoxUtils.BuildPrefixedFunctionName('set', variableName); } /** * Build the geter name for a variable name. * * @param { String } variableName variable name. */ static BuildGetterName(variableName) { return BoxUtils.BuildPrefixedFunctionName('get', variableName); } /** * Capitalise the first letter in a string. * * @param { String } value string value. * @returns { String } Capitalised string. */ static CapitalizeFirstLetter(value) { if (value && value.length) { const firstChar = value[0].toUpperCase(); return `${firstChar}${value.substr(1, value.length)}`; } return value; } /** * Load JSON. * * @param { String } path json path. * @returns { Promise<any> } Promise of JSON object. */ static LoadJSON(path) { return new Promise((resolve) => { const request = new XMLHttpRequest(); request.overrideMimeType('application/json'); request.open('GET', path, true); request.onreadystatechange = () => { console.log('request args', request.readyState, request.status); if (request.readyState === 4 && request.status === 200) { resolve(JSON.parse(request.response)); } }; request.send(null); }); } /** * After a change is needed, re-use the box display function to re-set inner html. * * @param {*} box */ static DisplayBox(box) { if (box && typeof box.display === 'function') { BoxUtils.LoadDOMAttributes(box); const newMarkup = box.display(box); box.innerHTML = newMarkup; if (box._pid) { // Then refresh! Bravo! 👌 const parent = document.getElementById(box._pid); parent.replaceChild(box, parent); } if (box._init && typeof box.boxOnRedisplayed === 'function') { box.boxOnRedisplayed(); } } } /** * Build box interfaces (setters and getters) if _BoxInterface present. * * @param { any } box box. */ static BuildBoxInterfaces(box) { if (box) { const boxInterface = box.constructor._BoxInterface; if (boxInterface === null || boxInterface === void 0 ? void 0 : boxInterface.Inputs) BoxUtils.BuildBoxGettersAndSetters(box, boxInterface.Inputs); if (boxInterface === null || boxInterface === void 0 ? void 0 : boxInterface.Vars) BoxUtils.BuildBoxGettersAndSetters(box, boxInterface.Vars); if (boxInterface === null || boxInterface === void 0 ? void 0 : boxInterface.Outputs) BoxUtils.BuildBoxOutputs(box, boxInterface.Outputs); } } static BuildBoxGettersAndSetters(box, inputsObject) { const inputsWithStockProperties = Object.assign({ _parentBoxId: null }, inputsObject); Object.keys(inputsWithStockProperties).forEach(interfaceProp => { const setterName = BoxUtils.BuildSetterName(interfaceProp); const getterName = BoxUtils.BuildGetterName(interfaceProp); box[setterName] = (value) => { box[interfaceProp] = value; box.detectBoxChanges(); }; box[getterName] = () => box[interfaceProp]; if (inputsWithStockProperties[interfaceProp] !== null && typeof inputsWithStockProperties[interfaceProp] !== 'undefined') { // If there is a value, set it (apply defaults...) box[interfaceProp] = inputsWithStockProperties[interfaceProp]; } }); } static BuildBoxOutputs(box, outputsObject) { Object.keys(outputsObject).forEach(interfaceProp => { const newBoxOutputEvent = new CustomEvent(`(${interfaceProp})`, { detail: box }); const eventBoxName = `_event_${interfaceProp}`; box[eventBoxName] = newBoxOutputEvent; // Add the dispatch function. box[BoxUtils.BuildPrefixedFunctionName('dispatch', interfaceProp)] = (...args) => { box.dispatchEvent(box[eventBoxName]); }; // Add the listen function. let setCallback = () => { }; box[BoxUtils.BuildPrefixedFunctionName('add', `${interfaceProp}Listener`)] = (callback) => { setCallback = callback; box.addEventListener(`(${interfaceProp})`, setCallback, false); }; // Add the remove listener function. box[BoxUtils.BuildPrefixedFunctionName('remove', `${interfaceProp}Listener`)] = () => { box.removeEventListener(`(${interfaceProp})`, setCallback); }; }); } /** * Build the standard variables that go on boxes. * * @param { any } box box. */ static BuildBoxStandardVariables(box) { const contextPath = `SharedBoxCore.loadedBoxes.get('${box._name}').get('${box._boxId}')`; box._context = contextPath; } /** * Load attributes from the DOM if they have been specified in the _BoxInterface! * * @param { any } box box. */ static LoadDOMAttributes(box) { if (box.attributes) { const boxInterface = box.constructor._BoxInterface; if (boxInterface) { for (let i = 0; i < box.attributes.length; i++) { const boxAttribute = box.attributes.item(i); BoxUtils.LoadAttributeOntoBox(box, boxAttribute); } } } } static LoadAttributeOntoBox(box, boxAttribute) { const boxInterface = box.constructor._BoxInterface; const { name: attributeName, value: attributeValue } = boxAttribute; if (BoxUtils.IsVariableInputProperty(attributeName) && (boxInterface === null || boxInterface === void 0 ? void 0 : boxInterface.Inputs[attributeName])) { const setterName = BoxUtils.BuildSetterName(attributeName); if (typeof box[setterName] === 'function') { box[attributeName] = boxAttribute.value; } } else if (BoxUtils.IsOutputProperty(attributeName) && (boxInterface === null || boxInterface === void 0 ? void 0 : boxInterface.Outputs[attributeName])) { // Add the listener. const functionName = BoxUtils.GetFunctionNameFromFunctionCallString(attributeValue); const parentBox = box.getParentBox(); box.addEventListener(attributeName, (ev) => parentBox[functionName](ev)); } else { if (attributeName === "_pid") box.pid === boxAttribute.value; // Is normal stirng or number input property. const setterName = BoxUtils.BuildSetterName(attributeName); if (typeof box[setterName] === 'function') { box[attributeName] = boxAttribute.value; } } } /** * Check if a property name is an input. * * @param { String } propertyName property name. */ static IsVariableInputProperty(propertyName) { if (propertyName && propertyName.length) { return (propertyName.length > 2 && propertyName[0] === '[' && propertyName[propertyName.length - 1] === ']'); } } static GetFunctionNameFromFunctionCallString(functionCallString) { return functionCallString; } /** * Check if a property name is an output. * * @param { String } propertyName property name. */ static IsOutputProperty(propertyName) { if (propertyName && propertyName.length) { return (propertyName.length > 2 && propertyName[0] === '(' && propertyName[propertyName.length - 1] === ')'); } } /** * Remove the first and last char of a string. * * @param { Stirng } propertyName property name. */ static TrimFirstAndLastChar(propertyName) { let returnString = propertyName; if (propertyName && propertyName.length > 2) { returnString = returnString.slice(1, (propertyName.length - 1)); } return returnString; } }
JavaScript
class Box extends HtmlClass { constructor() { super(...arguments); this.detectBoxChanges = () => BoxUtils.DisplayBox(this); } /** * Initialise our special box! */ connectedCallback() { const boxConfig = this.constructor._BoxConfig; this._boxId = HyperBoxCore.GetNewBoxId(boxConfig); if (!this.id) this.id = this._boxId; this._name = boxConfig.name; BoxUtils.CheckBoxRequirements(this.constructor); BoxUtils.BuildBoxStandardVariables(this); BoxUtils.BuildBoxInterfaces(this); BoxUtils.DisplayBox(this); if (typeof this.boxOnDisplayed === 'function') this.boxOnDisplayed(); HyperBoxCore.AddBoxToLoadedBoxes(this); this._init = true; } /** * Get the parent box from the parentBoxId set. */ getParentBox() { return document.getElementById(this._parentBoxId); } /** * Allows any box to terminate itself. */ terminateSelf() { this.remove(); if (typeof this.boxOnDestroyed === 'function') this.boxOnDestroyed(); } /** * Get box element by id. * * @param { Number } id box id. */ getBoxElementById(id) { const element = document.getElementById(`${this._boxId}-${id}`); return element; } /** * Box disconnected callback. */ disconnectedCallback() { if (typeof this.boxOnDestroyed === 'function') this.boxOnDestroyed(); } }
JavaScript
class NavigatorBox extends Box { constructor() { super(...arguments); /** * Connect the navigator to the parent box. */ this.boxOnDisplayed = () => { this.dispatchNavigatorOnLoaded(); }; this.dispatchNavigatorOnLoaded = () => { }; } get innerBox() { var _a; if (!((_a = this.children) === null || _a === void 0 ? void 0 : _a.length)) return null; return this.children[0]; } setRoutes(routes) { this._routes = routes; } cleanupOldBox() { var _a; (_a = this.innerBox) === null || _a === void 0 ? void 0 : _a.terminateSelf(); } addArgumentsToCurrentBox(argumentsObject) { var _a; if (!argumentsObject || !this.innerBox) return; this.innerBox._routeContext = argumentsObject; safeExec((_a = this.innerBox) === null || _a === void 0 ? void 0 : _a.detectBoxChanges); } setCurrentBox(box) { const { _BoxConfig: config } = box; if (!(config === null || config === void 0 ? void 0 : config.name)) throw new Error('HyperBox-JS: Tried to set a route box without a _BoxConfig name'); this.innerHTML = `<${config.name}></${config.name}>`; } gotoRoute(route, argumentsObject) { const routeEntry = this._routes[route]; if (!route) throw new Error(`BoxJS: Could not find route "${route}"`); this.cleanupOldBox(); this._activeRoute = route; const { box } = routeEntry; // Go to the new route. this.setCurrentBox(box); this.addEventListener('DOMNodeInserted', function (event) { if (event.target.parentNode.id == this.id) { //direct descendant // Set the args. this.addArgumentsToCurrentBox(argumentsObject); safeExec(this.innerBox.onNaviagatedTo); } ; }, false); } }
JavaScript
class DialogBox extends Box { constructor() { super(); this.display = () => { return ` <div class="dialog-underlay" onclick="${this._context}.underlayOnClicked()"> <div class="dialog-container"> <div> <div class="dialog-header"> ${this.getTitle()} </div> <div id="${this._boxId}-container"> <!-- Box is inserted here... --> ${this.getInnerBox()} </div> </div> <div class="dialog-footer"> ${this.getCancelButton()} ${this.getAcceptButton()} </div> </div> </div> `; }; } /** * Insert the dialog inner box. * * @param { String } boxClassName box class name * @param { any } argumentsObject args object. * @param { function } onSuccess sucess callback. * @param { function } onError error callback */ insertDialogInnerBox(boxClassName, argumentsObject, onSuccess, onError) { // We can make our dynamic box by calling make and chaining it with set parent call. this.innerHTML = `<${boxClassName}></${boxClassName}>`; this.set_dialogContext(Object.assign({}, argumentsObject)); this.innerBox._dialogContext = { closeOnSuccess: (...args) => { this.innerBox.terminateSelf(); this.terminateSelf(); onSuccess(args); }, closeOnError: (...args) => { this.innerBox.terminateSelf(); this.terminateSelf(); onError(args); }, arguments: Object.assign({}, argumentsObject) }; if (typeof this.innerBox.boxOnNavigatedTo === 'function') { this.innerBox.boxOnNavigatedTo(); } } /** * Getter for cancel button. */ getCancelButton() { if (this._dialogContext.cancelButtonText) { return ` <button class="margin-right-8" onclick="${this._context}.innerBox._dialogContext.closeOnSuccess(false)" > ${this._dialogContext.cancelButtonText} </button> `; } return ''; } /** * Getter for accept button. */ getAcceptButton() { if (this._dialogContext.acceptButtonText) { return ` <button onclick="${this._context}.innerBox._dialogContext.closeOnSuccess(true)" > ${this._dialogContext.acceptButtonText} </button> `; } return ''; } /** * Getter for title. */ getTitle() { if (this._dialogContext.title) { return `<h2>${this._dialogContext.title}<h2>`; } return ''; } /** * Getter for the inner box. */ getInnerBox() { if (this.innerBox) { return this.innerBox.display(this.innerBox); } return ''; } /** * Underlay was clicked handler. */ underlayOnClicked() { if (this.innerBox && this._dialogContext.closeable) { this.innerBox._dialogContext.closeOnSuccess(true); } } }
JavaScript
class DificultadService { postDificultad(callback, dificultad){ baseService.post(callback, "nuevaPartida/" + dificultad); } }
JavaScript
class GameBoard{ constructor(){ this.aiActor=null; } /**Get the function that copies a game state. * @return {function} */ getStateCopier(){} /**Get the first move. * @param {GFrame} frame * @return {any} */ getFirstMove(frame){} /**Get the list of next possible moves. * @param {GFrame} frame * @return {any[]} */ getNextMoves(frame){} /**Calculate the score. * @param {GFrame} frame * @param {number} depth * @param {number} maxDepth * @return {number} */ evalScore(frame,depth,maxDepth){} /**Check if game is a draw. * @param {GFrame} frame * @return {boolean} */ isStalemate(frame){} /**Check if game is over. * @param {GFrame} frame * @return {boolean} */ isOver(frame,move){} /**Reverse previous move. * @param {GFrame} frame * @param {any} move */ unmakeMove(frame, move){ if(!this.undoMove) throw Error("Need Implementation"); this.switchPlayer(frame); this.undoMove(frame, move); } //undoMove(frame, move){} //doMove(frame, move){ } /**Make a move. * @param {GFrame} frame * @param {any} move */ makeMove(frame, move){ if(!this.doMove) throw Error("Need Implementation!"); this.doMove(frame, move); this.switchPlayer(frame); } /**Take a snapshot of current game state. * @return {GFrame} */ takeGFrame(){} /**Switch to the other player. * @param {GFrame} snap */ switchPlayer(snap){ let t = snap.cur; snap.cur= snap.other; snap.other= t; } /**Get the other player. * @param {any} pv player * @return {any} */ getOtherPlayer(pv){ if(pv === this.actors[1]) return this.actors[2]; if(pv === this.actors[2]) return this.actors[1]; } /**Get the current player. * @return {any} */ getPlayer(){ return this.actors[0] } /**Run the algo and get a move. * @param {any} seed * @param {any} actor * @return {any} the next move */ run(seed,actor){ this.getAlgoActor=()=>{ return actor } this.syncState(seed,actor); let pos= this.getFirstMove(); if(_.nichts(pos)) pos= _$.evalMiniMax(this); return pos; } }
JavaScript
class TaskManagement extends Component { render() { return ( <DndProvider backend={HTML5Backend}> <Lanes {...this.props} CardComponent={this.props.CardComponent} LaneComponent={this.props.LaneComponent} /> </DndProvider> ); } }
JavaScript
class TrackingHTTP { /** * Performs an HTTP POST request and returns a promise with the JSON value of the response * @param {string} url The URL of the POST request * @param {any} form_data The body or form data of the POST request * @param {Object} headers The headers of the POST request * @param {number} timeout The timeout, in seconds, of the GET request * @returns {Promise<Object|string>} A promise to the HTTP response */ static post(url, form_data, headers={}, timeout=15000) { return new Promise(function(resolve, reject){ var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if(this.readyState == 4) { if(this.status == 200) { try { resolve(JSON.parse(this.responseText)); } catch(e) { console.log(e); console.log(this.responseText); reject(Error('Unable to parse output.')); } } else { console.log(url); reject(Error('Unable to fetch data from the server.')); } } }; xhttp.ontimeout = function(e) { reject(Error('The request has timed out.')); } xhttp.open("POST", url, true); xhttp.timeout = timeout; Object.keys(headers).forEach(function(key, index) { xhttp.setRequestHeader(key, headers[key]); }); xhttp.send(form_data); }); } }
JavaScript
class HackData extends Component { render() { const {data} = this.props; const {label, value} = data; return ( <div className="hackathon-details"> <p className="hack-duration">{label}</p> <p className="hack-data">{value}</p> </div> ); } }
JavaScript
class ResponseBody extends AsyncObject { constructor (response) { super(response) } syncCall () { return (response) => { return response.body } } }
JavaScript
class MyMarker extends MyGameElement { constructor(scene, graph, pickId = -1) { super(scene, graph, pickId) this.spritesLoaded = false; this.blackPoints = 0; this.whitePoints = 0; this.player = 1; this.winner = null; } setGraph(graph) { this.graph = graph; this.setSprites(); this.setMarker(this.blackPoints, this.whitePoints, this.player, this.winner); } setSprites() { this.blackMarker = this.graph.nodes['blackMarker'].sprites[0] this.whiteMarker = this.graph.nodes['whiteMarker'].sprites[0] this.playerMarker = this.graph.nodes['playerMarker'].sprites[0] this.spritesLoaded = true; } setMarker(blackPoints, whitePoints, player, winner = null) { this.blackPoints = blackPoints; this.whitePoints = whitePoints; this.player = player; this.winner = winner; this.blackMarker.setText(String(this.blackPoints)); this.whiteMarker.setText(String(this.whitePoints)); if (this.winner == null) { this.playerMarker.setText((player == 1 ? "Black" : "White") + "'s turn") return; } switch (this.winner) { case 0: this.playerMarker.setText("It's a tie!") break; case 1: this.playerMarker.setText("Black won!") break; case -1: this.playerMarker.setText("White won!") break; } } display() { if (!this.spritesLoaded) this.setSprites(); this.graph.display(); } }
JavaScript
class FullscreenOverlayView extends Component { update = false; constructor(props) { super(props); this.update = props.update || false; } shouldComponentUpdate() { return this.update; } render() { return ( <div className={`container fullscreen-view ${this.props.className || ""}`} > <span className="fullscreen-menu-background" onClick={this.props.onBackgroundClick} /> <div className="fullscreen-menu-actual-wrapper flex-center"> <div className="fullscreen-menu-actual"> <TitleBoxView title={this.props.title}> {this.props.children} </TitleBoxView> </div> </div> </div> ); } }
JavaScript
class Searcher { /** * Create a Searcher object. * * @param repoUri The URI of the NPM registry to use. * @param cdnUri The URI of the CDN to use for fetching full package data. */ constructor(repoUri = 'https://registry.npmjs.org/', cdnUri = 'https://unpkg.com') { this.repoUri = repoUri; this.cdnUri = cdnUri; } /** * Search for a jupyterlab extension. * * @param query The query to send. `keywords:"jupyterlab-extension"` will be appended to the query. * @param page The page of results to fetch. * @param pageination The pagination size to use. See registry API documentation for acceptable values. */ searchExtensions(query, page = 0, pageination = 250) { const uri = new URL('/-/v1/search', this.repoUri); // Note: Spaces are encoded to '+' signs! const text = `${query} keywords:"jupyterlab-extension"`; uri.searchParams.append('text', text); uri.searchParams.append('size', pageination.toString()); uri.searchParams.append('from', (pageination * page).toString()); return fetch(uri.toString()).then((response) => { if (response.ok) { return response.json(); } return []; }); } /** * Fetch package.json of a package * * @param name The package name. * @param version The version of the package to fetch. */ fetchPackageData(name, version) { const uri = new URL(`/${name}@${version}/package.json`, this.cdnUri); return fetch(uri.toString()).then((response) => { if (response.ok) { return response.json(); } return null; }); } }
JavaScript
class Quote extends Command { constructor(client) { super(client, { name: "Quote", description: "Gets a random motivational quote", enabled: true, usage: `${client.config.prefix}quote`, aliases: ["coach", "dailymessage", "inspireme"], permissionLevel: "User", }); this.loadQuotes() } async run(message, args, level) { try { this.log(message); if (!this.quotes.length) { this.loadQuotes() } let quote = this.quotes[Math.floor(Math.random() * this.quotes.length)] message.channel.send(`\`"${quote.text}" ~${quote.author || "Anonymous"}\``) } catch (e) { super.run(message); this.client.logger.error(e); } } async loadQuotes() { let response = await axios.get("https://type.fit/api/quotes") this.quotes = response.data } }
JavaScript
class Storage { /** * Get an item by its key * @param {String} key The key to fetch * @returns {Promise.<*|null>} A promise that resolves with the item, or * null if the item doesn't exist * @memberof Storage */ getItem(key) { return Promise.resolve(null); } /** * Initialise the storage * This usually entails reading the store from the storage so that it is * immediately available * @returns {Promise} A promise that resolves once initialisation has * completed * @memberof Storage */ initialise() { return Promise.resolve(); } /** * Remove an item from storage * @param {String} key The key to remove * @returns {Promise} A promise that resolves once the key has been removed * @memberof Storage */ removeItem(key) { return Promise.resolve(); } /** * Set an item * @param {String} key The key to set the value for * @param {*} value The value to set * @returns {Promise} A promise that resolves once the value has been * stored * @memberof Storage */ setItem(key, value) { return Promise.resolve(); } /** * Shutdown the storage instance * @returns {Promise} A promise that resolves once the shutdown procedure is complete * @memberof Storage */ shutdown() { return Promise.resolve(); } /** * Stream all items * @returns {Promise.<ReadableStream>} A promise that resolves with the readable stream * @memberof Storage */ streamItems() { return Promise.resolve(objectStream.fromArray([])); } }
JavaScript
class Generator { // Define constructor constructor(dt, seq, amp) { // Define default attributes and their initial value this.t = 0; this.dt = 0.001; this.sequence = []; this.amplitude = []; // Change default value if given as arguments if(arguments.length == 3) { this.dt = dt; this.sequence = seq; this.amplitude = amp; } } // Restart generator restart() { this.t = 0; var N = this.sequence.length; for(var i = 0; i < N; i++) { this.sequence[i].pos = 0; } } // Get value for all sources ping() { // Define output variable var output = []; // Add time data output.push(this.t); this.t += this.dt; // Add value from all sequences var N = this.sequence.length; for(var i = 0; i < N; i++) { var out = this.sequence[i].ping(); out *= this.amplitude[i]; output.push(out); } return output; } // Define test function -- 20180520.1649 ok static test() { // Define time step var dt = 0.001; // s // Define pattern for sequence as voltage source var ptn1 = [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ]; var ptn2 = [ 0, 0, 1, 1 ]; // Define sequences var seq1 = new Sequence(ptn1); var seq2 = new Sequence(ptn2); // Define signal amplitudo var amp1 = 8; // V var amp2 = 10; // V // Define generator var gen = new Generator(dt, [seq1, seq2], [amp1, amp2]); var N = 15; for(var i = 0; i < N; i++) { var signal = gen.ping(); console.log(signal); } } }
JavaScript
class NavItem extends LitElement { static get properties() { return { href: { type: String }, active: { type: Boolean }, }; } static get styles() { return [ theme, css` a { display: block; margin-top: var(--pzsh-menu-item-gap); padding: var(--pzsh-menu-item-padding-vertical) var(--pzsh-menu-item-padding-horizontal); color: var(--pzsh-menu-fg); background-color: var(--pzsh-menu-bg-alt); text-decoration: none; white-space: nowrap; } :host(:focus) a, a:hover, a:active, a:focus { color: var(--pzsh-menu-active); } @media (min-width: 800px) { :host { line-height: var(--pzsh-nav-line-height); } a { margin: 0; padding: 0 var(--pzsh-nav-item-padding-horizontal-desktop); color: var(--pzsh-nav-fg); background-color: transparent; } a, :host(:focus) a, a:hover, a:active, a:focus { color: var(--pzsh-nav-fg); } a > div { padding: var(--pzsh-nav-item-padding-horizontal-desktop) 0 calc(var(--pzsh-nav-item-padding-horizontal-desktop) - 5px) 0; border-bottom: 5px solid transparent; } :host(:focus) a > div, a:hover > div, a:active > div, a:focus > div, a.active > div { border-color: var(--pzsh-nav-active); } } `, ]; } constructor() { super(); this.href = "#"; this.active = false; } connectedCallback() { super.connectedCallback(); // Make component focusable if (!this.hasAttribute("tabindex")) { this.setAttribute("tabindex", 0); } } render() { return html`<a class=${classMap({ active: this.active })} href="${this.href}" role="menuitem" part="pzsh-nav-item" > <div><slot></slot></div> </a>`; } }
JavaScript
class PlayerOrderPrompt extends UiPrompt { constructor(game, playerNameOrder = []) { super(game); this.playerNameOrder = playerNameOrder; } get currentPlayer() { this.lazyFetchPlayers(); return this.players[0]; } lazyFetchPlayers() { if(!this.players) { if(this.playerNameOrder.length === 0) { this.players = this.game.getPlayersInFirstPlayerOrder(); } else { this.players = this.playerNameOrder.map(playerName => this.game.getPlayerByName(playerName)); } } } skipPlayers() { this.lazyFetchPlayers(); this.players = this.players.filter(p => !this.skipCondition(p)); } skipCondition() { return false; } completePlayer() { this.lazyFetchPlayers(); this.players.shift(); } setPlayers(players) { this.players = players; } isComplete() { this.lazyFetchPlayers(); return this.players.length === 0; } activeCondition(player) { return player === this.currentPlayer; } continue() { this.skipPlayers(); return super.continue(); } }
JavaScript
class Block { constructor(code, lineNumber, lineDefined, blockType, language) { this.code = code; if (!this.code) return; this.lineNumber = lineNumber; this.lineDefined = lineDefined; this.blockType = blockType; this.language = language; this.lines = this.code.split('\n'); this.isClosed = this.checkIfClosed(); this.isOpened = this.checkIfOpened(); this.isFinished = this.isClosed && this.isOpened; } checkIfClosed() { return ( this.lines[this.lines.length - 1].match( this.language.brackets.close ) !== null ); } checkIfOpened() { return this.lines[0].match(this.language.brackets.open) !== null; } }
JavaScript
class Link { constructor(title, href){ this.title = title; this.href = href; } }
JavaScript
class SalaryGraphService { constructor($http) { this.$http = $http; } static getClassName() { return 'SalaryGraphService'; } getClassName() { return SalaryGraphService.getClassName(); } getDefaultGraphData() { return [ [65, 59, 80, 81, 56, 55, 40], [135, 159, 80, 31, 50, 55, 23] ]; } getFilterListData() { return this.$http.get('http://localhost:3001/api/Stock'); } }
JavaScript
class SalaryGraphSeedService { getFilterListData() { // return wrapped fake $http promise let data = [ { title: 'Google', symbol: 'GOOG', value: 2300, category: 'Tech', sales: 23, color: 'aero', icon: 'fa-google' }, { title: 'Facebook', symbol: 'FB', value: 59, category: 'Tech', sales: 11, color: 'blue', icon: 'fa-facebook' }, { title: 'Apple', symbol: 'AAPL', value: 25, category: 'Tech', sales: 19, color: 'aero', icon: 'fa-apple' }, { title: 'Microsoft', symbol: 'MSFT', value: 350, category: 'Tech', sales: 35, color: 'aero', icon: 'fa-windows' }, { title: 'Amazon', symbol: 'AMZN', value: 470, category: 'Tech', sales: 47, color: 'blue', icon: 'fa-amazon' } ]; return data; } }
JavaScript
class AuroLockup extends LitElement { constructor() { super(); this.path = '/'; this.standard = false; this.oneworld = false; } // function to define props used within the scope of this component static get properties() { return { // ...super.properties, path: { type: String }, standard: { type: Boolean }, oneworld: { type: Boolean } } } static get styles() { return css` ${styleCss} `; } /** * @private Internal function to generate the HTML for the icon to use * @param {string} svgContent - The imported svg icon * @returns {TemplateResult} - The html template for the icon */ generateIconHtml(svgContent) { const dom = new DOMParser().parseFromString(svgContent, 'text/html'), svg = dom.body.firstChild; return html`${svg}`; } // When using auroElement, use the following attribute and function when hiding content from screen readers. // aria-hidden="${this.hideAudible(this.hiddenAudible)}" // function that renders the HTML and CSS into the scope of the component render() { const classes = { 'logoIcon': true, 'logoDivider': !this.oneworld } /* eslint-disable indent */ return html` <a href=${this.path} class="headerLinkBox"> <div class="${classMap(classes)}"> ${ifDefined(this.standard && this.oneworld ? this.generateIconHtml(logoStandard.svg) : this.generateIconHtml(logoOfficial.svg)) } </div> ${ifDefined(this.oneworld ? html` <div class="oneworldLogo"> ${this.generateIconHtml(logoOneworld.svg)} </div> ` : html` <div class="headerTitle"> <span class="headerTitle-title"> <slot name="title"></slot> </span> <span class="headerTitle-tagline"> <slot name="subtitle"></slot> </span> </div> `)} </a> `; } }
JavaScript
class Stylesheet extends CSSParser { /** * Initialize Stylesheet * @param {string} stylesheet */ constructor(stylesheet, filename = null) { super() this.cssText = stylesheet this.filename = filename this.parse(this.cssText) return this } }
JavaScript
class Session extends React.Component { /** * Create the Session class with the state containing * information to create a session an if the expanded * information should be showing. * * @param props Empty optional props for Authors */ constructor(props) { super(props); this.state = { showing: false, sessionId: 1, contentId: 1, title: "", data: [] } } /** * The render method to create the JSX/HTML content * for the page with class states and properties. * * @returns {JSX.Element} The fully rendered JSX object */ render() { const {showing} = this.state; return ( <div className="session" id={this.props.details.sessionId}> <h3 className="session-info-expander" onClick={() => this.setState({showing: !showing})}>{this.props.details.title} &#9660;</h3> {showing ? <SessionInfo details={this.props.details} authorsExist={this.state.data} authors={this.state.data.map((data, id) => <span key={id}>{data.name}, </span>)}/> : null} </div> ) } /** * Method for handling when the component mounts * ad sending an API request to fetch authors * corresponding to the content ID. */ componentDidMount() { const url = "http://unn-w18013094.newnumyspace.co.uk/chi2018/part1/api/authorsforcontent?contentId=" + this.props.details.contentId + "&limit=1"; fetch(url) .then((res) => res.json()) .then((data) => { this.setState({data: data.data}) }) .catch((err) => { console.log("Something went wrong: ", err) }) } }
JavaScript
class Event { /** * @param {String} type - the type of event, this can be anything, but its a good idea just to make it a string * @param {Emitter} target - the emitter that is firing this event * @param {Array} args - an array of arguments that is used on the listener functions * @return {Event} */ constructor(type, args, target) { if (typeof type !== "string") throw new Error("Event.type has to be a string"); /** * the type of event * @type {String} */ this.type = type; /** * an array of arguments that are used when calling the listener function * @type {Array} */ this.args = args || []; /** * a reference to the emitter that fired the event * @type {Emitter} */ this.target = target; } }
JavaScript
class Bus { constructor() { this.passengers = {} } // 车内广播, 中介者约定API broadcast(passenger, message = passenger) { if(Object.keys(this.passengers).length){ // 特殊情况给传入的passenger听 if(passenger.id && passenger.listen) { if(this.passengers[passenger.id]) { this.passengers[passenger.id].listen(message) } // 否则就给所有的乘客听 message = passenger(也就是那个对象消息) } else { Object.keys(this.passengers).forEach(passenger => { if(this.passengers[passenger].listen) { this.passengers[passenger].listen(message) } }) } } } // 上车的passenger 登记id board(passenger) { this.passengers[passenger.id] = passenger } off(passenger) { this.passengers[passenger.id] = null delete this.passengers[passenger.id] console.log(`乘客${passenger.id}下车`) } /* 发车和停车都是广播所有人 (二参没有传) 一参当然也没有passage.id*/ // 发车 start() { this.broadcast({type: 1, content: "开车,请系好安全带"}) } // 停车 end() { this.broadcast({type: 2, content: "停车,要下车的请注意~"}) } }
JavaScript
class BeforeExitListener { constructor() { /** * Call the listener function with no arguments. */ this.invoke = () => global[LISTENER_SYMBOL](); /** * Reset the listener to a no-op function. */ this.reset = () => (global[LISTENER_SYMBOL] = NO_OP_LISTENER); /** * Set the listener to the provided function. */ this.set = (listener) => (global[LISTENER_SYMBOL] = listener); this.reset(); } }
JavaScript
class PushNotifications { /** * @constructor */ constructor() { } /** * sends push notification to the main process * @param {PushOptions} options * @param {PushCallbacks} callbacks */ send(options, callbacks = {}) { if ( os.type() === 'Darwin' ) { this.sendOSXNotificaion(options, callbacks); } else { this.sendDefaultNotification(options, callbacks); } } /** * @param {PushOptions} options * @param {PushCallbacks} callbacks */ sendOSXNotificaion(options, callbacks) { let notificationOptions = { title : options.title, subtitle : options.subtitle, icon : options.image, body : options.message }, notification = new Notification(notificationOptions); if ( typeof callbacks['click'] === 'function' ) { notification.on('click', callbacks['click']); } notification.show(); } /** * Here we use node-notifier module to send notifications on Linus, Windows and others * * @param {PushOptions} options * @param {PushCallbacks} callbacks */ sendDefaultNotification(options, callbacks) { /** * Assemble data from passed options * @type {NotifierOptions} */ let notifierOption = { appIcon : this.icon, title : options.title || this.title, subtitle : options.subtitle, contentImage : options.image, message : options.message, timeout : 10 }; if ( callbacks.length > 0 ) { notifierOption.wait = true; } if ( typeof callbacks['click'] === 'function' ) { notifier.once('click', callbacks['click']); } notifier.notify(notifierOption); } }
JavaScript
class Foo { constructor() { }; test() { class Bar { constructor() { } test() { return Foo === Bar } } return new Bar().test(); } }
JavaScript
class PlotVegaLite { view() { return m('div', {style: {width: '100%', height: '100%'}}) } plot(vnode) { let {data, specification, listeners} = vnode.attrs; // change-sets are not currently supported. Data is manually inserted here. // long term, if change-sets are not returned, it would be better to remove the data argument from this component if (data) specification.data = {values: data}; let newSpecification = JSON.stringify(specification); let {width, height} = vnode.dom.getBoundingClientRect(); if (this.isPlotting) return; if (this.specification !== newSpecification || this.width !== width || this.height !== height || this.theme !== localStorage.getItem('plotTheme')) { this.isPlotting = true; this.specification = newSpecification; if (width) this.width = width; if (height) this.height = height; this.dataKeys = undefined; this.theme = localStorage.getItem('plotTheme'); // include padding in width/height calculations if (!('autosize' in specification)) specification.autosize = { "type": "fit", "contains": "padding" }; // if ('vconcat' in specification) specification.vconcat.forEach(spec => spec.width = this.width); // change-sets are not currently supported // if (data) specification.data = {name: 'embedded'}; let options = {actions: true, theme: this.theme || 'default'}; if ('vconcat' in specification) width && specification.vconcat.forEach(spec => spec.width = 'width' in spec ? spec.width : width); else if ('hconcat' in specification) height && specification.hconcat.forEach(spec => spec.height = 'height' in spec ? spec.height : height); else { if (width && !specification?.encoding?.column) specification.width = 'width' in specification ? specification.width : width; if (height && !specification?.encoding?.row) specification.height = 'height' in specification ? specification.height : height; } // by default, make sure labels on all plots are limited to 50 pixels ['axisX', 'axisY'].forEach(axis => setDefaultDeep(specification, ['config', axis, 'labelLimit'], 100)); // setDefaultRecursive(specification, [['config', {}], ['background', 'transparent']]); vegaEmbed(vnode.dom, specification, options).then(result => { let addThemeSetter = theme => { const themeAction = document.createElement('a'); themeAction.textContent = "Theme: " + theme; themeAction.onclick = () => { localStorage.setItem('plotTheme', theme); vnode.dom.querySelector('details').removeAttribute('open'); m.redraw(); } vnode.dom.querySelector('.vega-actions').appendChild(themeAction); } ['default', 'excel', 'ggplot2', 'quartz', 'vox', 'fivethirtyeight', 'latimes', 'dark'].map(addThemeSetter) // attach event listeners Object.entries(listeners || {}).forEach(([name, callback]) => result.view.addSignalListener(name, (n, v) => callback(v))) // vegalite only gets close to the width/height set in the config let {width, height} = vnode.dom.getBoundingClientRect(); this.width = width; this.height = height; // change-sets are not currently supported // this.instance = result.view; // if (data) { // this.dataKeys = new Set(); // this.diff(vnode); // } this.isPlotting = false; m.redraw() }) } // this is the optimized path for the optional data attr // check for existence of dataKeys because the initial plotting is asynchronous // else if (data && this.dataKeys) this.diff(vnode); } // diff(vnode) { // let {data, identifier} = vnode.attrs; // let newData = data.filter(datum => !this.dataKeys.has(datum[identifier])); // // this.dataKeys = new Set(data.map(datum => datum[identifier])); // this.instance // .change('embedded', vega.changeset() // .insert(newData) // .remove(datum => !this.dataKeys.has(datum[identifier]))) // .run(); // } oncreate(vnode) {this.plot(vnode)} onupdate(vnode) {this.plot(vnode)} }
JavaScript
class FileList { /** * @param {Array} patterns * @param {Array} excludes * @param {EventEmitter} emitter * @param {Function} preprocess * @param {number} autoWatchBatchDelay */ constructor (patterns, excludes, emitter, preprocess, autoWatchBatchDelay) { // Store options this._patterns = patterns this._excludes = excludes this._emitter = emitter this._preprocess = Promise.promisify(preprocess) this._autoWatchBatchDelay = autoWatchBatchDelay // The actual list of files this.buckets = new Map() // Internal tracker if we are refreshing. // When a refresh is triggered this gets set // to the promise that `this._refresh` returns. // So we know we are refreshing when this promise // is still pending, and we are done when it's either // resolved or rejected. this._refreshing = Promise.resolve() // Emit the `file_list_modified` event. // This function is debounced to the value of `autoWatchBatchDelay` // to avoid reloading while files are still being modified. const emit = () => { this._emitter.emit('file_list_modified', this.files) } const debouncedEmit = _.debounce(emit, this._autoWatchBatchDelay) this._emitModified = (immediate) => { immediate ? emit() : debouncedEmit() } } // Private Interface // ----------------- // Is the given path matched by any exclusion filter // // path - String // // Returns `undefined` if no match, otherwise the matching // pattern. _isExcluded (path) { return _.find(this._excludes, (pattern) => mm(path, pattern)) } // Find the matching include pattern for the given path. // // path - String // // Returns the match or `undefined` if none found. _isIncluded (path) { return _.find(this._patterns, (pattern) => mm(path, pattern.pattern)) } // Find the given path in the bucket corresponding // to the given pattern. // // path - String // pattern - Object // // Returns a File or undefined _findFile (path, pattern) { if (!path || !pattern) return if (!this.buckets.has(pattern.pattern)) return return _.find(Array.from(this.buckets.get(pattern.pattern)), (file) => { return file.originalPath === path }) } // Is the given path already in the files list. // // path - String // // Returns a boolean. _exists (path) { const patterns = this._patterns.filter((pattern) => mm(path, pattern.pattern)) return !!_.find(patterns, (pattern) => this._findFile(path, pattern)) } // Check if we are currently refreshing _isRefreshing () { return this._refreshing.isPending() } // Do the actual work of refreshing _refresh () { const buckets = this.buckets const matchedFiles = new Set() let promise promise = Promise.map(this._patterns, (patternObject) => { const pattern = patternObject.pattern const type = patternObject.type if (helper.isUrlAbsolute(pattern)) { buckets.set(pattern, new Set([new Url(pattern, type)])) return Promise.resolve() } const mg = new Glob(pathLib.normalize(pattern), GLOB_OPTS) const files = mg.found buckets.set(pattern, new Set()) if (_.isEmpty(files)) { log.warn('Pattern "%s" does not match any file.', pattern) return } return Promise.map(files, (path) => { if (this._isExcluded(path)) { log.debug('Excluded file "%s"', path) return Promise.resolve() } if (matchedFiles.has(path)) { return Promise.resolve() } matchedFiles.add(path) const mtime = mg.statCache[path].mtime const doNotCache = patternObject.nocache const type = patternObject.type const file = new File(path, mtime, doNotCache, type) if (file.doNotCache) { log.debug('Not preprocessing "%s" due to nocache', pattern) return Promise.resolve(file) } return this._preprocess(file).then(() => { return file }) }) .then((files) => { files = _.compact(files) if (_.isEmpty(files)) { log.warn('All files matched by "%s" were excluded or matched by prior matchers.', pattern) } else { buckets.set(pattern, new Set(files)) } }) }) .then(() => { if (this._refreshing !== promise) { return this._refreshing } this.buckets = buckets this._emitModified(true) return this.files }) return promise } // Public Interface // ---------------- get files () { const uniqueFlat = (list) => { return _.uniq(_.flatten(list), 'path') } const expandPattern = (p) => { return Array.from(this.buckets.get(p.pattern) || []).sort(byPath) } const served = this._patterns.filter((pattern) => { return pattern.served }) .map(expandPattern) const lookup = {} const included = {} this._patterns.forEach((p) => { // This needs to be here sadly, as plugins are modifiying // the _patterns directly resulting in elements not being // instantiated properly if (p.constructor.name !== 'Pattern') { p = createPatternObject(p) } const bucket = expandPattern(p) bucket.forEach((file) => { const other = lookup[file.path] if (other && other.compare(p) < 0) return lookup[file.path] = p if (p.included) { included[file.path] = file } else { delete included[file.path] } }) }) return { served: uniqueFlat(served), included: _.values(included) } } // Reglob all patterns to update the list. // // Returns a promise that is resolved when the refresh // is completed. refresh () { this._refreshing = this._refresh() return this._refreshing } // Set new patterns and excludes and update // the list accordingly // // patterns - Array, the new patterns. // excludes - Array, the new exclude patterns. // // Returns a promise that is resolved when the refresh // is completed. reload (patterns, excludes) { this._patterns = patterns this._excludes = excludes // Wait until the current refresh is done and then do a // refresh to ensure a refresh actually happens return this.refresh() } // Add a new file from the list. // This is called by the watcher // // path - String, the path of the file to update. // // Returns a promise that is resolved when the update // is completed. addFile (path) { // Ensure we are not adding a file that should be excluded const excluded = this._isExcluded(path) if (excluded) { log.debug('Add file "%s" ignored. Excluded by "%s".', path, excluded) return Promise.resolve(this.files) } const pattern = this._isIncluded(path) if (!pattern) { log.debug('Add file "%s" ignored. Does not match any pattern.', path) return Promise.resolve(this.files) } if (this._exists(path)) { log.debug('Add file "%s" ignored. Already in the list.', path) return Promise.resolve(this.files) } const file = new File(path) this.buckets.get(pattern.pattern).add(file) return Promise.all([ fs.statAsync(path), this._refreshing ]).spread((stat) => { file.mtime = stat.mtime return this._preprocess(file) }) .then(() => { log.info('Added file "%s".', path) this._emitModified() return this.files }) } // Update the `mtime` of a file. // This is called by the watcher // // path - String, the path of the file to update. // // Returns a promise that is resolved when the update // is completed. changeFile (path) { const pattern = this._isIncluded(path) const file = this._findFile(path, pattern) if (!pattern || !file) { log.debug('Changed file "%s" ignored. Does not match any file in the list.', path) return Promise.resolve(this.files) } return Promise.all([ fs.statAsync(path), this._refreshing ]).spread((stat) => { if (stat.mtime <= file.mtime) throw new Promise.CancellationError() file.mtime = stat.mtime return this._preprocess(file) }) .then(() => { log.info('Changed file "%s".', path) this._emitModified() return this.files }) .catch(Promise.CancellationError, () => { return this.files }) } // Remove a file from the list. // This is called by the watcher // // path - String, the path of the file to update. // // Returns a promise that is resolved when the update // is completed. removeFile (path) { return Promise.try(() => { const pattern = this._isIncluded(path) const file = this._findFile(path, pattern) if (!pattern || !file) { log.debug('Removed file "%s" ignored. Does not match any file in the list.', path) return this.files } this.buckets.get(pattern.pattern).delete(file) log.info('Removed file "%s".', path) this._emitModified() return this.files }) } }
JavaScript
class DifferentialFuzzSuppressions extends mutator.Mutator { get visitor() { let thisMutator = this; return { // Clean up strings containing the magic section prefix. Those can come // e.g. from CrashTests and would confuse the deduplication in // v8_foozzie.py. StringLiteral(path) { if (path.node.value.startsWith(SECTION_PREFIX)) { const postfix = path.node.value.substring(SECTION_PREFIX.length); path.node.value = CLEANED_PREFIX + postfix; thisMutator.annotate(path.node, 'Replaced magic string'); } }, // Known precision differences: https://crbug.com/1063568 BinaryExpression(path) { if (path.node.operator == '**') { path.node.operator = '+'; thisMutator.annotate(path.node, 'Replaced **'); } }, // Unsupported language feature: https://crbug.com/1020573 MemberExpression(path) { if (path.node.property.name == "arguments") { let replacement = common.randomVariable(path); if (!replacement) { replacement = babelTypes.thisExpression(); } thisMutator.annotate(replacement, 'Replaced .arguments'); thisMutator.replaceWithSkip(path, replacement); } }, }; } }
JavaScript
class DifferentialFuzzMutator extends mutator.Mutator { constructor(settings) { super(); this.settings = settings; } /** * Looks for the dummy node that marks the beginning of an input file * from the corpus. */ isSectionStart(path) { return !!common.getOriginalPath(path.node); } /** * Create print statements for printing the magic section prefix that's * expected by v8_foozzie.py to differentiate different source files. */ getSectionHeader(path) { const orig = common.getOriginalPath(path.node); return printValue({ VALUE: babelTypes.stringLiteral(SECTION_PREFIX + orig), }); } /** * Create statements for extra printing at the end of a section. We print * the number of caught exceptions, a generic hash of all observed values * and the contents of all variables in scope. */ getSectionFooter(path) { const variables = common.availableVariables(path); const statements = variables.map(prettyPrintStatement); statements.unshift(printCaught()); statements.unshift(printHash()); const statement = babelTypes.tryStatement( babelTypes.blockStatement(statements), babelTypes.catchClause( babelTypes.identifier('e'), babelTypes.blockStatement([]))); this.annotate(statement, 'Print variables and exceptions from section'); return statement; } /** * Helper for printing the contents of several variables. */ printVariables(path, nodes) { const statements = []; for (const node of nodes) { if (!babelTypes.isIdentifier(node) || !common.isVariableIdentifier(node.name)) continue; statements.push(prettyPrintExtraStatement(node)); } if (statements.length) { this.annotate(statements[0], 'Extra variable printing'); this.insertAfterSkip(path, statements); } } get visitor() { const thisMutator = this; const settings = this.settings; return { // Replace existing normal print statements with deep printing. CallExpression(path) { if (babelTypes.isIdentifier(path.node.callee) && path.node.callee.name == 'print') { path.node.callee = babelTypes.identifier('__prettyPrintExtra'); thisMutator.annotate(path.node, 'Pretty printing'); } }, // Either print or track caught exceptions, guarded by a probability. CatchClause(path) { const probability = random.random(); if (probability < settings.DIFF_FUZZ_EXTRA_PRINT && path.node.param && babelTypes.isIdentifier(path.node.param)) { const statement = prettyPrintExtraStatement(path.node.param); path.node.body.body.unshift(statement); } else if (probability < settings.DIFF_FUZZ_TRACK_CAUGHT) { path.node.body.body.unshift(incCaught()); } }, // Insert section headers and footers between the contents of two // original source files. We detect the dummy no-op nodes that were // previously tagged with the original path of the file. Noop(path) { if (!thisMutator.isSectionStart(path)) { return; } const header = thisMutator.getSectionHeader(path); const footer = thisMutator.getSectionFooter(path); thisMutator.insertBeforeSkip(path, footer); thisMutator.insertBeforeSkip(path, header); }, // Additionally we print one footer in the end. Program: { exit(path) { const footer = thisMutator.getSectionFooter(path); path.node.body.push(footer); }, }, // Print contents of variables after assignments, guarded by a // probability. ExpressionStatement(path) { if (!babelTypes.isAssignmentExpression(path.node.expression) || !random.choose(settings.DIFF_FUZZ_EXTRA_PRINT)) { return; } const left = path.node.expression.left; if (babelTypes.isMemberExpression(left)) { thisMutator.printVariables(path, [left.object]); } else { thisMutator.printVariables(path, [left]); } }, // Print contents of variables after declaration, guarded by a // probability. VariableDeclaration(path) { if (babelTypes.isLoop(path.parent) || !random.choose(settings.DIFF_FUZZ_EXTRA_PRINT)) { return; } const identifiers = path.node.declarations.map(decl => decl.id); thisMutator.printVariables(path, identifiers); }, }; } }
JavaScript
class Rally extends Component { constructor(props) { super(props); this.state = { data: null, Rallies: [] }; } componentDidMount() { this.getVenueInfo(); //this.renderMap(); } getVenueInfo() { // this gets the event id from the URL params let search = window.location.search; let params = new URLSearchParams(search); let theID = params.get("id"); // save the id to the redux store // this.props.setEventID(params.get("id")); // this gets all the rally information, then passes it to redux //--------------------------------------------------------------- // we have the apiURL in redux, grab that and make url for axios //let theAPI = this.props.getAPIURL; //console.log("apiURL:" + theAPI); axios({ method: "get", url: "https://evgvlc22t1.execute-api.us-east-1.amazonaws.com/UAT/event/retrieve", params: { eventId: theID } }).then(res => { console.log(res); this.setState({ Rallies: res.data }); }); } render() { return ( <ul> {this.state.Rallies.map(rally => ( <div> <h1>P8 Rally Information</h1> <h2>Venue Information</h2> <div className='Venue'> <EventDate eventDate={rally.eDate} /> <div className='VenueName'>{rally.vName}</div> <div className='VenueAddress'> {rally.vStreet} <br /> {rally.vCity}, {rally.vState} {rally.vZipcode} </div> <EventTimes startTime={rally.eStartTime} endTime={rally.eEndTime} /> <div> <img src={rally.eGraphics} width='400' /> </div> <Link className='btn btn-primary' to={"/register?id=" + rally.eid} > <button color='success'>REGISTER NOW!</button> </Link> <div className='EventComments'> {rally.eventNotes} </div> <div className='FurtherInfo'> If you need further information, please contact your CR state rep, or you can contact the supporting state rep. <br /> </div> <div className='StateRepInfo'> <font className='stateRepName'> {rally.eStateRepName} </font> <br /> <font className='stateRepEmail'> {rally.eStateRepEmail} </font> <br /> <font className='stateRepPhone'> {rally.eStateRepPhone} </font> </div> <div className='VenueMap'> <div id='map'></div> {rally.vMapLink} </div> </div> {/* {console.log('eid:' + this.props.eid)} {console.log('eDate:' + this.props.eDate)} {console.log('starttime:' + this.props.eStart)} {console.log('rally:' + this.props.rally.eDate)} */} </div> ))} </ul> ); } }
JavaScript
class HTMLPrimitive { constructor(tag, attributes, value) { this.tag = tag; if (Array.isArray(attributes) || typeof attributes !== "object") { [attributes, value] = [{}, attributes]; } this.attributes = attributes; this.value = value; } render() { let element = document.createElement(this.tag); Object.entries(this.attributes).forEach(([name, value]) => { if (name.startsWith("on")) { element.addEventListener( name.substring(2).toLowerCase(), value ); } else { element.setAttribute(name, value); } }); if (Array.isArray(this.value)) { this.value.forEach((child) => { if (child instanceof HTMLPrimitive) { element.appendChild(child.render()); } else { element.appendChild( document.createTextNode(child.toString()) ); } }); } else if (this.value !== undefined) { element.innerHTML = this.value.toString(); } return element; } }
JavaScript
class ErrorLogs { /** * Get high severity string. * * @return {String} */ get highSeverity() { return 'high'; } /** * Get medium severity string. * * @return {String} */ get mediumSeverity() { return 'medium'; } /** * Get low severity string. * * @return {String} */ get lowSeverity() { return 'low'; } /** * Get created status string. * * @return {String} */ get createdStatus() { return 'created'; } /** * Get processed status string. * * @return {String} */ get processedStatus() { return 'processed'; } /** * Get failed status string. * * @return {String} */ get failedStatus() { return 'failed'; } /** * Get failed status string. * * @return {String} */ get completelyFailedStatus() { return 'completelyFailed'; } /** * Get query limits for severities. * * @return {*} */ get queryLimits() { const oThis = this; return { [oThis.highSeverity]: 100, [oThis.mediumSeverity]: 100, [oThis.lowSeverity]: 100 }; } get walletSdkInternalAppName() { return 'wallet-sdk-internal'; } get walletSdkPlatformApiAppName() { return 'wallet-sdk-platform-api'; } get pepoApiAppName() { return 'pepo-api'; } /** * Get all appNames. * * @return {*[]} */ get appNames() { const oThis = this; return [oThis.walletSdkInternalAppName, oThis.walletSdkPlatformApiAppName, oThis.pepoApiAppName]; } /** * Get all severities. * * @return {*[]} */ get severities() { const oThis = this; return [oThis.highSeverity, oThis.mediumSeverity, oThis.lowSeverity]; } }
JavaScript
class MySecurityCamera extends CGFobject{ /** * Create the security camera, it's texture and it's shader. * @param {XMLScene} scene */ constructor(scene){ super(scene); // The rectangle is the object where the security texture will be placed. It's dimensions allow it to sit at the bottom right corner of the screen, occupying 25% of the screen // in both direction this.screen = new MyRectangle(scene,"sec_cam",0.5,1,-1,-0.5); // Create the RTT texture that will contain a "snapshot" of the scene from the perspective of the security camera this.cameraTex = new CGFtextureRTT(this.scene, this.scene.gl.canvas.width, this.scene.gl.canvas.height); // Bind the texture to the sampler "slot" of the shader this.cameraTex.bind(0); // GLSL shader that changes the rectangle so be placed as an overlay and applies the texture and post-processing efects this.cameraScreenShader = new CGFshader(this.scene.gl, "shaders/camera_shader.vert", "shaders/camera_shader.frag"); } /** * @method attachToFrameBuffer * * Wrapper function that attaches the camera texture to the frame buffer. This way the next time the scene is rendered it will be rendered to the texture. */ attachToFrameBuffer(){ this.cameraTex.attachToFrameBuffer(); } /** * @method detachFromFrameBuffer * * Wrapper function that detaches the camera texture to the frame buffer. This way the next time the scene is rendered it will be rendered to the screen. */ detachFromFrameBuffer(){ this.cameraTex.detachFromFrameBuffer(); } /** * @method setUniformsValues * * Wrapper function that updates the security camera shader's uniform values * @param {Object of Uniform values} obj */ setUniformsValues(obj){ this.cameraScreenShader.setUniformsValues(obj); } /** * @method reload * * Create the rtt texture again. This function is meant to be used as an handler for the window resize event in order to update the securitu camera * in case the window resizes. */ reload(){ this.cameraTex = new CGFtextureRTT(this.scene, this.scene.gl.canvas.width, this.scene.gl.canvas.height); this.cameraTex.bind(0); } /** * @method diplay * * Display the security camera */ display(){ // Display the security camera screen this.scene.setActiveShader(this.cameraScreenShader); this.scene.gl.disable(this.scene.gl.DEPTH_TEST); this.cameraTex.bind(0); this.screen.display(); this.scene.gl.enable(this.scene.gl.DEPTH_TEST); this.scene.setActiveShader(this.scene.defaultShader); } }
JavaScript
class Either { /** * @static * @property {Right} Right - Either right. */ static get Right() { return Right; } /** * @static * @property {Left} Left - Either left. */ static get Left() { return Left; } /** * Returns a {@link Either} that resolves all of the eithers in the collection into a single Either. * @static * @member * @param {Either[]} eithers - Collection of eithers. * @return {Either} A {@link Either} representing all {@link Right} values or a singular {@link Left}. * @example * * const e1 = fs.readFileSync(filePath1); * // => Right(contents1) * * const e2 = fs.readFileSync(filePath2); * // => Right(contents2) * * const e3 = fs.readFileSync(filePath3); * // => Left(error3) * * const e4 = fs.readFileSync(filePath4); * // => Left(error4) * * Either.all([e1, e2]); * // => Right([contents1, contents2]) * * Either.all([e1, e2, e3]); * // => Left(error3) * * Either.all([e1, e2, e3, e4]); * // => Left(error3) */ static all(eithers) { return find(Either.isLeft, eithers) || Either.of(stream(eithers).map(get("value")).reduce(concat, [])); } /** * Returns the first {@link Right} in the collection or finally a {@link Left}. * @static * @member * @param {Either[]} eithers - Collection of eithers. * @return {Either} First {@link Right} or finally a {@link Left}. * @example * * const e1 = fs.readFileSync(filePath1); * // => Right(contents1) * * const e2 = fs.readFileSync(filePath2); * // => Right(contents2) * * const e3 = fs.readFileSync(filePath3); * // => Left(error3) * * const e4 = fs.readFileSync(filePath4); * // => Left(error4) * * Either.any([e1, e2]); * // => Right(contents1) * * Either.any([e2, e3]); * // => Right(contents2) * * Either.any([e3, e4]); * // => Left(error3) */ static any(either) { return find(Either.isRight, either) || find(Either.isLeft, either); } /** * Creates a new {@link Either} from a <code>value</code>. If the <code>value</code> is already a {@link Either} * instance, the <code>value</code> is returned unchanged. Otherwise, a new {@link Right} is made with the * <code>value</code>. * @static * @member * @param {*} value - Value to wrap in a {@link Either}. * @return {Either} {@link Either} when is the <code>value</code> already wrapped or {@link Right} wrapped * <code>value</code>. * * Either.from(); * // => Right() * * Either.from(true); * // => Right(true) * * Either.from(Right.from(value)); * // => Right(value) * * Either.from(Left.from(error)); * // => Left(error) */ static from(value) { return this.isEither(value) ? value : this.of(value); } /** * Determines whether or not the value is a {@link Either}. * @static * @member * @param {*} value - Value to check. * @return {Boolean} <code>true</code> for {@link Either}; <code>false</code> for anything else. * @example * * isEither(); * // => false * * isEither(Right.from()); * // => true * * isEither(Left.from(error)); * // => true */ static isEither(value) { return value instanceof Either; } /** * Determines whether or not the value is a {@link Left}. * @static * @member * @param {*} value - Value to check. * @return {Boolean} <code>true</code> for {@link Left}; <code>false</code> for {@link Right}. * @example * * isLeft(); * // => false * * isLeft(Left.from(error)); * // => true * * isLeft(Right.from()); * // => false */ static isLeft(value) { return value instanceof Left; } /** * Determines whether or not the value is a {@link Right}. * @static * @member * @param {*} value - Value to check. * @return {Boolean} <code>true</code> for {@link Right}; <code>false</code> for {@link Left}. * @example * * isRight(); * // => false * * isRight(Right.from()); * // => true * * isRight(Left.from(error)); * // => false */ static isRight(value) { return value instanceof Right; } /** * Wraps the <code>value</code> in a {@link Right}. No parts of <code>value</code> are checked. * @static * @member * @param {*} value - Value to wrap. * @return {Right} {@link Right} wrapped <code>value</code>. * @example * * Either.of(); * // => Right() * * Either.of(true); * // => Right(true) * * Either.of(Right.from(value)); * // => Right(Right(value)) * * Either.of(Left.from(error)); * // => Right(Left(error)) */ static of(value) { return new Right(value); } /** * Tries to invoke a <code>supplier</code>. The result of the <code>supplier</code> is returned in a {@link Right}. * If an exception is thrown, the error is returned in a {@link Left}. The <code>function</code> takes no arguments. * @static * @member * @param {Supplier} supplier - Function to invoke. * @return {Either} {@link Right} wrapped supplier result or {@link Left} wrapped <code>error</code>. * @example * * Either.try(normalFunction); * // => Right(returnValue) * * Either.try(throwableFunction); * // => Left(error) */ static try(method) { try { return Right.from(method()); } catch (error) { return Left.from(error); } } constructor(value) { this.value = value; } /** * Applies the function contained in the instance of a {@link Right} to the value contained in the provided * {@link Right}, producing a {@link Right} containing the result. If the instance is a {@link Left}, the result * is the {@link Left} instance. If the instance is a {@link Right} and the provided {@link Either} is {@link Left}, * the result is the provided {@link Left}. * @abstract * @function ap * @memberof Either * @instance * @param {Either} other - Value to apply to the function wrapped in the {@link Right}. * @return {Either} {@link Right} wrapped applied function or {@link Left}. * @example <caption>Right#ap</caption> * * const findPerson = curryN(3, Person.find); // Person.find(name, birthdate, address) * * Right.from(findPerson) // => Right(findPerson) * .ap(Right.try(getName())) // => Right(name) * .ap(Right.try(getBirthdate())) // => Right(birthdate) * .ap(Right.try(getAddress())) // => Right(address) * .ifRight(console.log); // => Log Person.find() response */ /** * Transforms a {@link Either} by applying the first function to the contained value for a {@link Left} or the * second function for a {@link Right}. The result of each map is wrapped in the corresponding type. * @abstract * @function bimap * @memberof Either * @instance * @param {Function} failureMap - Map to apply to the {@link Left}. * @param {Function} successMap - Map to apply to the {@link Right}. * @return {Either} {@link Either} wrapped value mapped with the corresponding mapping function. * @example * * // Using lodash/fp/get * Either.try(loadFile) * .bimap(get("message"), parseFile) * // ... other actions in workflow */ /** * Applies the provided function to the value contained for a {@link Right}. The function should return the value * wrapped in a {@link Either}. If the instance is a {@link Left}, the function is ignored and then instance is * returned unchanged. * @abstract * @function chain * @memberof Either * @instance * @param {Chain.<Either>} method - The function to invoke with the value. * @return {Either} {@link Either} wrapped value returned by the provided <code>method</code>. * @example <caption>Right#chain</caption> * * // Using lodash/fp/curry and getOr * const getConfigOption = curry((path, config) => Either.Right.from(getOr( * Either.Left.from(`Value not found at "${path}"`), * path, * config * ))); * * Either.of(config) * .chain(getConfigOption("path.to.option")) */ /** * Determines whether or not the <code>other</code> is equal in value to the current (<code>this</code>). This is * <strong>not</strong> a reference check. * @param {*} other - Other value to check. * @return {Boolean} <code>true</code> if the two Eithers are equal; <code>false</code> if not equal. * @example <caption>Reflexivity</caption> * * v1.equals(v1) === true; * // => true * * @example <caption>Symmetry</caption> * * v1.equals(v2) === v2.equals(v1); * // => true * * @example <caption>Transitivity</caption> * * (v1.equals(v2) === v2.equals(v3)) && v1.equals(v3) * // => true */ equals(other) { return isEqual(this, other); } /** * Extends the Either. This is used for workflow continuation where the context has shifted. * @abstract * @function extend * @memberof Either * @instance * @param {Extend.<Either>} - method - The function to invoke with the value. * @return {Either} * @example <caption>Workflow continuation</caption> * * // Workflow from makeRequest.js * const makeRequest = requestOptions => requestAsPromise(requestOptions) * .then(Right.from) * .catch(Left.from); * * // Workflow from savePerson.js * const savePerson = curry((requestOptions, eitherPerson) => eitherPerson * .map(Person.from) * .map(person => set("body", person, requestOptions)) * .map(makeRequest) * ); * * // Workflow from processResponse.js * const processResponse = eitherResponse => eitherResponse * .ifLeft(console.error) * .ifRight(console.log); * * Either.of(person) * .extend(savePerson({ method: "POST" })) * .extend(processResponse); */ /** * Returns the value if the instance is a {@link Right} otherwise the <code>null</code>. * @function get * @memberof Either * @instance * @return {*} * @example <caption>Right#get</caption> * * Right.from(value).get(); * // => value * * @example <caption>Left#get</caption> * * Left.from(error).get(); * // => null */ /** * Applies the provided function to the value contain for a {@link Left}. Any return value from the function is * ignored. If the instance is a {@link Right}, the function is ignored and the instance is returned. * @abstract * @function ifLeft * @memberof Either * @instance * @param {Consumer} method - The function to invoke with the value. * @return {Either} Current instance. * @example <caption>Right#ifLeft</caption> * * Right.from(value).ifLeft(doSomething); // void * // => Right(value) * * @example <caption>Left#ifLeft</caption> * * Left.from(error).ifLeft(doSomething); // doSomething(error) * // => Left(error) */ /** * Applies the provided function to the value contain for a {@link Right}. Any return value from the function is * ignored. If the instance is a {@link Left}, the function is ignored and the instance is returned. * @abstract * @function ifRight * @memberof Either * @instance * @param {Consumer} method - The function to invoke with the value. * @return {Either} Current instance. * @example <caption>Right#ifRight</caption> * * Right.from(value).ifRight(doSomething); // doSomething(value) * // => Right(value) * * @example <caption>Left#ifRight</caption> * * Left.from(error).ifRight(doSomething); // void * // => Left(error) */ /** * Determines whether or not the instance is a {@link Left}. * @return {Boolean} <code>true</code> if the instance is a {@link Left}; <code>false</code> is not. * @example <caption>Right#isLeft</caption> * * Right.from(value).isLeft(); * // => false * * @example <caption>Left#isLeft</caption> * * Left.from(error).isLeft(); * // => true */ isLeft() { return this instanceof Left; } /** * Determines whether or not the instance is a {@link Right}. * @return {Boolean} <code>true</code> if the instance is a {@link Right}; <code>false</code> is not. * @example <caption>Right</caption> * * Right.from(value).isLeft(); * // => true * * @example <caption>Left#isRight</caption> * * Left.from(error).isLeft(); * // => false */ isRight() { return this instanceof Right; } /** * Applies the provided function to the value contained for a {@link Right} which is, in turn, wrapped in a * {@link Right}. If the instance is a {@link Left}, the function is ignored and then instance is returned unchanged. * @abstract * @function map * @memberof Either * @instance * @param {Function} method - The function to invoke with the value. * @return {Either} {@link Either} wrapped value mapped with the provided <code>method</code>. * @example * * // Using lodash/fp/flow and sort * Right.from([1, 3, 2]).map(flow(sort, join(", "))); * // => Right("1, 2, 3") * * Left.from(error).map(flow(sort, join(", "))); * // => Left(error) */ /** * @see Either.of */ of(value) { return Either.of(value); } /** * Returns the value if the instance is a {@link Right} otherwise returns the value supplied if the instance is a * {@link Left}. * @abstract * @function orElse * @memberof Either * @instance * @param {Consumer} method - The function to invoke with the value. * @return {*} * @example <caption>Right#orElse</caption> * * Right.from(value).orElse(otherValue); * // => value * * @example <caption>Left#orElse</caption> * * Left.from(error).orElse(otherValue); * // => otherValue */ /** * Return the value if the instance is a {@link Right} otherwise returns the value from the function provided. * @abstract * @function orElseGet * @memberof Either * @instance * @param {Supplier} method - The function supplying the optional value. * @return {*} * @example <caption>Right#orElseGet</caption> * * Right.from(value).orElseGet(getOtherValue); * // => value * * @example <caption>Left#orElseGet</caption> * * Left.from(error).orElse(getOtherValue); * // => otherValue */ /** * Returns the value if the instance is a {@link Right} otheriwse throws the <code>Error</code> supplied by the * function provided. The function receives the value of the {@link Left} as its argument. * @abstract * @function orElseThrow * @memberof Either * @instance * @param {Function} method - The function to invoke with the value. * @return {*} * @throws {Error} returned by the provided function. * @example <caption>Right#orElseThrow</caption> * * Right.from(value).orElseThrow(createException); * // => value * * @example <caption>Left#orElseThrow</caption> * * Left.from(error).orElseThrow(createException); // throw createException(error) */ /** * Converts the Either to a {@link Maybe}. {@link Right} becomes {@link Just} and {@link Left} becomes * {@link Nothing}. * @abstract * @function toMaybe * @memberof Either * @instance * @param {Maybe} maybe - Maybe implementation. * @return {Maybe} {@link Maybe} wrapped <code>value</code>. * @example <caption>Right#toMaybe</caption> * * Right.from(value).toMaybe(Maybe); * // => Maybe.Just(value); * * @example <caption>Left#toMaybe</caption> * * Left.from(error).toMaybe(Maybe); * // => Maybe.Nothing(); */ /** * Converts the Either to a <code>Promise</code> using the provided <code>Promise</code> implementation. * @abstract * @function toPromise * @memberof Either * @instance * @param {Promise} promise - Promise implementation. * @return {Promise} <code>Promise</code> wrapped <code>value</code>. * @example <caption>Right#toPromise</caption> * * const Bluebird = require("bluebird"); * * Right.from(value).toPromise(Bluebird); * // => Promise.resolve(value); * * @example <caption>Left#toPromise</caption> * * const Bluebird = require("bluebird"); * * Left.from(error).toPromise(Bluebird); * // => Promise.reject(error); */ /** * Returns a <code>String</code> representation of the {@link Either}. * @abstract * @function toString * @memberof Either * @instance * @return {String} <code>String</code> representation. * @example <caption>Right#toString</caption> * * Right.from(1).toString(); * // => "Either.Right(1)" * * @example <caption>Left#toString</caption> * * Left.from(error).toString(); * // => "Either.Left(error)" */ /** * Converts the Either to a {@link Validation}. {@link Right} becomes {@link Success} and {@link Left} becomes * {@link Failure}. * @abstract * @function toValidation * @memberof Either * @instance * @param {Validation} validation - Validation implementation. * @return {Validation} {@link Validation} wrapped <code>value</code>. * @example <caption>Right#toValidation</caption> * * Right.from(value).toValidation(Validation); * // => Validation.Success(value); * * @example <caption>Left#toValidation</caption> * * Left.from(error).toValidation(Validation); * // => Validation.Failure(); */ }
JavaScript
class Left extends Either { /** * Creates a new {@link Left} from a <code>value</code>. If the <code>value</code> is already a {@link Either} * instance, the <code>value</code> is returned unchanged. Otherwise, a new {@link Left} is made with the * <code>value</code>. * @static * @param {*} value - Value to wrap in a {@link Left}. * @return {Either} {@link Either} when is the <code>value</code> already wrapped or {@link Left} wrapped * <code>value</code>. * @example <caption>Left from nothing</caption> * * Left.from(); * // => Left() * * @example <caption>Left from arbitrary value</caption> * * Left.from(error); * // => Left(error) * * @example <caption>Left from Right</caption> * * Left.from(Right.from(value)); * // => Right.from(value) * * @example <caption>Left from another Left</caption> * * Left.from(Left.from(error)); * // => Left(error) */ static from(value) { return Either.isEither(value) ? value : new Left(value); } constructor(value) { super(value); } ap() { return this; } bimap(leftMap) { return Left.from(leftMap(this.value)); } chain() { return this; } extend() { return this; } get() { return null; } ifLeft(method) { method(); return this; } ifRight() { return this; } map() { return this; } orElse(value) { return value; } orElseGet(method) { return method(); } orElseThrow(method) { throw method(this.value); } toMaybe(maybe) { return new maybe.Nothing(); } toPromise(promise) { return promise.reject(this.value); } toString() { return `Either.Left(${this.value})`; } toValidation(validation) { return new validation.Failure(this.value); } }
JavaScript
class Right extends Either { /** * Creates a new {@link Right} from a <code>value</code>. If the <code>value</code> is already a {@link Either} * instance, the <code>value</code> is returned unchanged. Otherwise, a new {@link Right} is made with the * <code>value</code>. * @static * @param {*} value - Value to wrap in a {@link Right}. * @return {Either} {@link Either} when is the <code>value</code> already wrapped or {@link Right} wrapped * <code>value</code>. * @example <caption>Right from nothing</caption> * * Right.from(); * // => Right() * * @example <caption>Right from arbitrary value</caption> * * Right.from(true); * // => Right(true) * * @example <caption>Right from another Right</caption> * * Right.from(Right.from(value)); * // => Right(value) * * @example <caption>Right from Left</caption> * * Right.from(Left.from(error)); * // => Left(error) */ static from(value) { return Either.isEither(value) ? value : new Right(value); } constructor(value) { super(value); } ap(other) { return other.map(this.value); } bimap(leftMap, rightMap) { return Right.from(rightMap(this.value)); } chain(method) { return Either.from(method(this.value)); } extend(method) { return Either.from(method(this)); } get() { return this.value; } ifLeft() { return this; } ifRight(method) { method(this.value); return this; } map(method) { return Right.of(method(this.value)); } orElse() { return this.value; } orElseGet() { return this.value; } orElseThrow() { return this.value; } toMaybe(maybe) { return new maybe.Just(this.value); } toPromise(promise) { return promise.resolve(this.value); } toString() { return `Either.Right(${this.value})`; } toValidation(validation) { return new validation.Success(this.value); } }
JavaScript
class GetUser extends Component { state = { user : { userId: "10", name: "nk", lastName: "malviya", phone: "7742401557", address: "pali rajasthan" } }; submitHandler = ()=>{ // TODO: send to request with server to getUser detail } render() { return ( <div> <h1>Get User By Id</h1> <div className="form-group m-2"> <label htmlFor="userId" >User Id:</label> <input type="text" className="form-control m-2" placeholder="Enter userId" id="userId" /> <button type="submit" className="btn btn-primary m-2"> Submit </button> </div> <User user={this.state.user} /> </div> ); } }
JavaScript
class CodeMapAssetService { /* @ngInject */ /** * @external {MeshLambertMaterial} https://threejs.org/docs/api/materials/MeshLambertMaterial.html * @external {BoxGeometry} https://threejs.org/docs/?q=box#Reference/Geometries/BoxGeometry * @constructor * @param {object} codeMapMaterialFactory */ constructor(codeMapMaterialFactory) { /** * @typedef {object} CodeMapMaterialPack * @property {MeshLambertMaterial} positive * @property {MeshLambertMaterial} neutral * @property {MeshLambertMaterial} negative * @property {MeshLambertMaterial} odd * @property {MeshLambertMaterial} even * @property {MeshLambertMaterial} selected * @property {MeshLambertMaterial} hovered * @property {MeshLambertMaterial} default * @property {MeshLambertMaterial} positiveDelta * @property {MeshLambertMaterial} negativeDelta */ /** * @type {CodeMapMaterialPack} */ this.materials = { positive: codeMapMaterialFactory.positive(), neutral: codeMapMaterialFactory.neutral(), negative: codeMapMaterialFactory.negative(), odd: codeMapMaterialFactory.odd(), even: codeMapMaterialFactory.even(), selected: codeMapMaterialFactory.selected(), default: codeMapMaterialFactory.default(), positiveDelta: codeMapMaterialFactory.positiveDelta(), negativeDelta: codeMapMaterialFactory.negativeDelta() }; /** * @type {BoxGeometry} */ this.cubeGeo = new THREE.BoxGeometry(1,1,1); } /** * @return {BoxGeometry} */ getCubeGeo() { return this.cubeGeo; } /** * @return {MeshLambertMaterial} */ positive() { return this.materials.positive; } /** * @return {MeshLambertMaterial} */ neutral() { return this.materials.neutral; } /** * @return {MeshLambertMaterial} */ negative() { return this.materials.negative; } /** * @return {MeshLambertMaterial} */ odd() { return this.materials.odd; } /** * @return {MeshLambertMaterial} */ even() { return this.materials.even; } /** * @return {MeshLambertMaterial} */ selected() { return this.materials.selected; } /** * @return {MeshLambertMaterial} */ default() { return this.materials.default; } /** * @return {MeshLambertMaterial} */ positiveDelta() { return this.materials.positiveDelta; } /** * @return {MeshLambertMaterial} */ negativeDelta() { return this.materials.negativeDelta; } }
JavaScript
class SortableDataGrid extends React.Component { constructor(props) { super(props); this.state = { sortField: undefined, sortDirection: undefined }; this.handleSortChange = this.handleSortChange.bind(this); } /** * Handles change in sort data * * @param sortField field to which we should sort by */ handleSortChange(sortField) { const sortDirection = SortService.getSortDirection(sortField, this.state.sortField, this.state.sortDirection); this.setState({sortDirection, sortField}); } render() { const {sortField, sortDirection} = this.state; const items = sortDirection !== undefined ? SortService.sortItems([...this.props.items], sortField, sortDirection): this.props.items; const sortIndicator = SortService.getSortIndicator(sortDirection); return ( <DataGrid {...this.props} sortIndicator={sortIndicator} items={items} sortField={sortField} sortDirection={sortDirection} handleSortChange={this.handleSortChange} /> ); } }
JavaScript
class RollingList { constructor(feedName, filePrefix, maxItems = 20, allowDuplicateItems = true, uniqueIdentifierDelegate = null) { this._feedName = feedName; this._filePrefix = filePrefix; this._listFilePath = this._filePrefix + '/' + this._feedName + '.json'; if (maxItems == 'unlimited' || maxItems <= 0) { this._maxItems = 0; } else { this._maxItems = maxItems; } this._uncommitedMap = {}; this._allowDuplicateItems = allowDuplicateItems; if (!allowDuplicateItems) { if (!uniqueIdentifierDelegate) { throw Error('Item duplication is not allowed but ' + 'unique identifier delegate.'); } // From item Id to its appearance date in the archive this._itemExistanceMap = {}; this._getUniqueIdentifier = uniqueIdentifierDelegate; } } addItem(item, targetDate) { if (item) { // Duplication? if (!this._allowDuplicateItems) { let duplicationRemovalResult = this.removePossibleDuplicate(item, targetDate); if (duplicationRemovalResult == 1) { // The new item is rejected return; } } if (!this._uncommitedMap[targetDate]) { this._uncommitedMap[targetDate] = []; } this._uncommitedMap[targetDate].push(item); if (!this._allowDuplicateItems) { // update the existance map this._itemExistanceMap[this._getUniqueIdentifier(item)] = targetDate; } } } removePossibleDuplicate(item, targetDate) { let previousItemAppearanceDate = this._itemExistanceMap[this._getUniqueIdentifier(item)]; if (previousItemAppearanceDate) { // Remove the newer one; if (moment(previousItemAppearanceDate).isBefore(moment(targetDate))) { AppContext.getInstance().Logger.debug( `Item ${JSON.stringify(item)} got rejected. ` + 'An older version of this item is published already!' ); // Reject the new item (there is an older version) return 1; } else { // Remove the currently persisted version and save the new one this.removeItem(item, targetDate); AppContext.getInstance().Logger.debug( `Item ${JSON.stringify(item)} overrides an already persisted version.` ); return -1; } } return 0; } removeItem(item, fromDate) { // Search both history and uncommited map. It must be somewhere! if (this._fullHistory && this._fullHistory[fromDate]) { for (let i = this._fullHistory[fromDate].length - 1; i >= 0; i--) { if (this._getUniqueIdentifier(item) === this._getUniqueIdentifier(this._fullHistory[fromDate][i])) { // Remove this._fullHistory[fromDate].splice(i, 1); return; } } } if (this._uncommitedMap && this._uncommitedMap[fromDate]) { for (let i = this._uncommitedMap[fromDate].length - 1; i > 0; i--) { if ( this._getUniqueIdentifier(item) === this._getUniqueIdentifier(this._uncommitedMap[fromDate][i])) { // Remove this._uncommitedMap[fromDate].splice(i, 1); return; } } } throw Error(`Data inconsistency detected! Item ${JSON.stringify(item)}` + ` must have existed in history but we could not locate it for removal`); } loadHistroy() { if (!this._fullHistory) { if (fs.existsSync(this._listFilePath)) { this._fullHistory = JSON.parse( fs.readFileSync(this._listFilePath, 'utf-8') ); } else { this._fullHistory = {}; } // rebuild the existance map if (!this._allowDuplicateItems) { this.rebuildExistanceMap(); } } } rebuildExistanceMap() { for (let date of Object.keys(this._fullHistory)) { for (let item of this._fullHistory[date]) { let duplicationRemovalResult = this.removePossibleDuplicate(item, date); if (duplicationRemovalResult == 0 || duplicationRemovalResult == -1) { // 0: No duplicates. Add this item // -1: the other item removed. The new one should be referenced; this._itemExistanceMap[this._getUniqueIdentifier(item)] = date; } // Else, this item is a duplicate, nothing to add to the map } } } /** * Flushes list data down to disk (also applies feed capacity and timeout) * @param {String} pruneByDate the date for which we remove all items * before that (excluding) */ flush(pruneByDate) { if (this.commit() > 0) { // Now sort, filter and save. Good news is that acsending string sort // works for us just fine let sortedDates = Object.keys(this._fullHistory).sort(); if (pruneByDate) { sortedDates = sortedDates.filter((date) => { return (date.localeCompare(pruneByDate) >= 0); }); } let feedCapacity = this._maxItems; let filteredHistory = {}; for (let date of sortedDates.reverse()) { // if not unlimited if (this._maxItems !== 0) { // start from newest to oldest if (feedCapacity - this._fullHistory[date].length > 0) { filteredHistory[date] = this._fullHistory[date]; feedCapacity -= this._fullHistory[date].length; } else { // enough, no more room to fit another day break; } } else { // add anything in the sortedDates filteredHistory[date] = this._fullHistory[date]; } } this._fullHistory = filteredHistory; // Save fs.writeFileSync( this._listFilePath, JSON.stringify(this._fullHistory, null, 2) ); } } commit() { let commitedDatesCount = 0; if (Object.keys(this._uncommitedMap).length > 0) { this.loadHistroy(); for (let date in this._uncommitedMap) { if (this._uncommitedMap[date]) { // Update the values for date with the new ones this._fullHistory[date] = this._uncommitedMap[date]; commitedDatesCount++; } } } return commitedDatesCount; } // This is where we reassemble the items from different dates, note that // this function is only called once a day to update feeds, so I am not // worried about it doing some heavy-lifting work getItems(forDate) { // commit any uncommited changes this.flush(); // We are sure that this._fullHistory is sorted based on date (older first) // Therefore we iterate and append values together up to the date let result = []; let includedDates = Object.keys(this._fullHistory).filter((itemDate) => { // Dates before or equal 'forDate' // lexical ordering will be used return (itemDate.localeCompare(forDate) <= 0); }); for (let date of includedDates) { result = result.concat(this._fullHistory[date]); } return result; } }
JavaScript
class DelonAuthConfig { constructor() { /** * 存储KEY值 */ this.store_key = '_token'; /** * 无效时跳转至登录页,包括: * - 无效token值 * - token已过期(限JWT) */ this.token_invalid_redirect = true; /** * token过期时间偏移值,默认:`10` 秒(单位:秒) */ this.token_exp_offset = 10; /** * 发送token参数名,默认:token */ this.token_send_key = 'token'; /** * 发送token模板(默认为:`${token}`),使用 `${token}` 表示token点位符,例如: * * - `Bearer ${token}` */ // tslint:disable-next-line:no-invalid-template-strings this.token_send_template = '${token}'; /** * 发送token参数位置,默认:header */ this.token_send_place = 'header'; /** * 登录页路由地址 */ this.login_url = `/login`; /** * 忽略TOKEN的URL地址列表,默认值为:[ /\/login/, /assets\//, /passport\// ] */ this.ignores = [/\/login/, /assets\//, /passport\//]; /** * 允许匿名登录KEY,若请求参数中带有该KEY表示忽略TOKEN */ this.allow_anonymous_key = `_allow_anonymous`; /** * 是否校验失效时命中后继续调用后续拦截器的 `intercept` 方法,默认:`true` */ this.executeOtherInterceptors = true; } }
JavaScript
class MemoryStore { constructor() { this.cache = {}; } /** * @param {?} key * @return {?} */ get(key) { return this.cache[key] || (/** @type {?} */ ({})); } /** * @param {?} key * @param {?} value * @return {?} */ set(key, value) { this.cache[key] = value; return true; } /** * @param {?} key * @return {?} */ remove(key) { this.cache[key] = null; } }
JavaScript
class SessionStorageStore { /** * @param {?} key * @return {?} */ get(key) { return JSON.parse(sessionStorage.getItem(key) || '{}') || {}; } /** * @param {?} key * @param {?} value * @return {?} */ set(key, value) { sessionStorage.setItem(key, JSON.stringify(value)); return true; } /** * @param {?} key * @return {?} */ remove(key) { sessionStorage.removeItem(key); } }
JavaScript
class HttpAuthInterceptorHandler { /** * @param {?} next * @param {?} interceptor */ constructor(next, interceptor) { this.next = next; this.interceptor = interceptor; } /** * @param {?} req * @return {?} */ handle(req) { return this.interceptor.intercept(req, this.next); } }
JavaScript
class JWTTokenModel { /** * 获取载荷信息 * @return {?} */ // tslint:disable-next-line:no-any get payload() { /** @type {?} */ const parts = (this.token || '').split('.'); if (parts.length !== 3) throw new Error('JWT must have 3 parts'); /** @type {?} */ const decoded = urlBase64Decode(parts[1]); return JSON.parse(decoded); } /** * 检查Token是否过期,`payload` 必须包含 `exp` 时有效 * * @param {?=} offsetSeconds 偏移量 * @return {?} */ isExpired(offsetSeconds = 0) { /** @type {?} */ const decoded = this.payload; if (!decoded.hasOwnProperty('exp')) return null; /** @type {?} */ const date = new Date(0); date.setUTCSeconds(decoded.exp); return !(date.valueOf() > new Date().valueOf() + offsetSeconds * 1000); } }
JavaScript
class JWTInterceptor extends BaseInterceptor { /** * @param {?} options * @return {?} */ isAuth(options) { this.model = this.injector .get(DA_SERVICE_TOKEN) .get(JWTTokenModel); return CheckJwt((/** @type {?} */ (this.model)), options.token_exp_offset); } /** * @param {?} req * @param {?} options * @return {?} */ setReq(req, options) { return req.clone({ setHeaders: { Authorization: `Bearer ${this.model.token}`, }, }); } }
JavaScript
class JWTGuard { /** * @param {?} srv * @param {?} injector * @param {?} cog */ constructor(srv, injector, cog) { this.srv = srv; this.injector = injector; this.cog = Object.assign({}, new DelonAuthConfig(), cog); } /** * @return {?} */ process() { /** @type {?} */ const res = CheckJwt(this.srv.get(JWTTokenModel), this.cog.token_exp_offset); if (!res) { ToLogin(this.cog, this.injector, this.url); } return res; } // lazy loading /** * @param {?} route * @param {?} segments * @return {?} */ canLoad(route, segments) { this.url = route.path; return this.process(); } // all children route /** * @param {?} childRoute * @param {?} state * @return {?} */ canActivateChild(childRoute, state) { this.url = state.url; return this.process(); } // route /** * @param {?} route * @param {?} state * @return {?} */ canActivate(route, state) { this.url = state.url; return this.process(); } }
JavaScript
class SimpleInterceptor extends BaseInterceptor { /** * @param {?} options * @return {?} */ isAuth(options) { this.model = (/** @type {?} */ (this.injector.get(DA_SERVICE_TOKEN).get())); return CheckSimple((/** @type {?} */ (this.model))); } // tslint:disable-next-line:no-any /** * @param {?} req * @param {?} options * @return {?} */ setReq(req, options) { /** @type {?} */ const token = options.token_send_template.replace(/\$\{([\w]+)\}/g, (_, g) => this.model[g]); switch (options.token_send_place) { case 'header': /** @type {?} */ const obj = {}; obj[options.token_send_key] = token; req = req.clone({ setHeaders: obj, }); break; case 'body': /** @type {?} */ const body = req.body || {}; body[options.token_send_key] = token; req = req.clone({ body, }); break; case 'url': req = req.clone({ params: req.params.append(options.token_send_key, token), }); break; } return req; } }
JavaScript
class SimpleGuard { /** * @param {?} srv * @param {?} injector * @param {?} cog */ constructor(srv, injector, cog) { this.srv = srv; this.injector = injector; this.cog = Object.assign({}, new DelonAuthConfig(), cog); } /** * @return {?} */ process() { /** @type {?} */ const res = CheckSimple(this.srv.get()); if (!res) { ToLogin(this.cog, this.injector, this.url); } return res; } // lazy loading /** * @param {?} route * @param {?} segments * @return {?} */ canLoad(route, segments) { this.url = route.path; return this.process(); } // all children route /** * @param {?} childRoute * @param {?} state * @return {?} */ canActivateChild(childRoute, state) { this.url = state.url; return this.process(); } // route /** * @param {?} route * @param {?} state * @return {?} */ canActivate(route, state) { this.url = state.url; return this.process(); } }
JavaScript
class Rowset extends Array { constructor(type) { super() // if (!type) throw new Error("Type required"); this.type = type; this.columns = this.type.columns; this._cmp = null; this.query = null; this.skip = 0; this.limit = -1; this.indexes = {}; this.subsets = []; } sort(spec) { if (typeof(spec) === 'function') return super.sort(spec); if (spec) { this._cmp = sort.comparator(spec); this._cmp.spec = spec; log('info', "Sorting using comparator: #bbk[%s]", this._cmp); super.sort(this._cmp); } else { this._cmp = null; } return this; } insert(row) { if (this._cmp) { let idx = sort.index(this, row, this._cmp); // log('info', "Inserting sorted #byl[%s] at #bl[%s]", row, idx); super.splice(idx, 0, row); } else { this.push(row); } for (let key in this.indexes) { let index = this.indexes[key]; index._insert(row); } return this; } update(row) { if (typeof(row) === 'string' && arguments.length > 1) { let item = this.get.apply(this, arguments); return this.update(item); } else if (row == null) { return this; } for (let key in this.indexes) { let index = this.indexes[key]; index._update(row); } return this; } delete(row) { if (typeof(row) === 'string' && arguments.length > 1) { let item = this.get.apply(this, arguments); return this.delete(item); } else if (row == null) { return this; } let idx = this.indexOf(row); // log('info', "index #gr[%s]", idx); this.splice(idx, 1); for (let key in this.indexes) { let index = this.indexes[key]; // log('info', "deleting row in index #gr[%s]", index); index._delete(row); } return this; } ensureIndex(key, opts) { let index = this.indexes[key]; if (!index) { let keys = key.split(/\s*,/g); index = this.indexes[key] = Index.provider(this, keys, opts); // log('info', "Using strategy #gr[%s] for keys #gr[%s]", index, keys); for (let row of this) { index._insert(row); } } return this; } index(key) { let index = this.indexes[key]; if (!index) { this.ensureIndex(key, {}); index = this.indexes[key]; } return index; } get(key, ...vals) { let index = this.index(key); return index.get(vals); } }
JavaScript
class GraphFechaIngreso extends React.Component { componentDidMount() { this.mounted = true; fetch('https://censovenezolanoback.herokuapp.com/censos/estadisticas') .then(res => res.json()) .then(json => { let datos = json.estadisticas; let fechaIngreso_datos = [ datos.fechaIngreso.enero_2016, datos.fechaIngreso.febrero_2016, datos.fechaIngreso.marzo_2016, datos.fechaIngreso.abril_2016, datos.fechaIngreso.mayo_2016, datos.fechaIngreso.junio_2016, datos.fechaIngreso.julio_2016, datos.fechaIngreso.agosto_2016, datos.fechaIngreso.septiembre_2016, datos.fechaIngreso.octubre_2016, datos.fechaIngreso.noviembre_2016, datos.fechaIngreso.diciembre_2016, datos.fechaIngreso.enero_2017, datos.fechaIngreso.febrero_2017, datos.fechaIngreso.marzo_2017, datos.fechaIngreso.abril_2017, datos.fechaIngreso.mayo_2017, datos.fechaIngreso.junio_2017, datos.fechaIngreso.julio_2017, datos.fechaIngreso.agosto_2017, datos.fechaIngreso.septiembre_2017, datos.fechaIngreso.octubre_2017, datos.fechaIngreso.noviembre_2017, datos.fechaIngreso.diciembre_2017, datos.fechaIngreso.enero_2018, datos.fechaIngreso.febrero_2018, datos.fechaIngreso.marzo_2018, datos.fechaIngreso.abril_2018, datos.fechaIngreso.mayo_2018, datos.fechaIngreso.junio_2018, datos.fechaIngreso.julio_2018, datos.fechaIngreso.agosto_2018, datos.fechaIngreso.septiembre_2018, datos.fechaIngreso.octubre_2018, datos.fechaIngreso.noviembre_2018, datos.fechaIngreso.diciembre_2018 ]; let fechaIngresos_label = [ 'enero-2016', 'febrero-2016', 'marzo-2016', 'abril-2016', 'mayo-2016', 'junio-2016', 'julio-2016', 'agosto-2016', 'septiembre-2016', 'octubre-2016', 'noviembre-2016', 'diciembre-2016', 'enero-2017', 'febrero-2017', 'marzo-2017', 'abril-2017', 'mayo-2017', 'junio-2017', 'julio-2017', 'agosto-2017', 'septiembre-2017', 'octubre-2017', 'noviembre-2017', 'diciembre-2017', 'enero-2018', 'febrero-2018', 'marzo-2018', 'abril-2018', 'mayo-2018', 'junio-2018', 'julio-2018', 'agosto-2018', 'septiembre-2018', 'octubre-2018', 'noviembre-2018', 'diciembre-2018' ]; if (this.mounted) { this.setState({ data: [ { type: 'scatter', mode: 'lines', name: 'Fecha de ingreso', x: fechaIngresos_label, y: fechaIngreso_datos, line: { color: '#17BECF' } } ], layout: { title: 'Inmigracion venezolana por fecha', width: 800, height: 600, xaxis: { autorange: false, range: ['2016-01-01', '2018-12-28'], rangeslider: { range: ['2016-01-01', '2018-12-28'] }, type: 'Number' }, yaxis: { autorange: true, range: [0, 50], type: 'linear' } }, frames: [], config: {} }); } }); } componentWillUnmount() { this.mounted = false; } constructor(props) { super(props); this.state = { data: [ { type: 'scatter', mode: 'lines', name: 'Fecha de ingreso', x: [], y: [], line: { color: '#17BECF' } } ], layout: { title: 'Inmigracion venezolana por fecha', width: 800, height: 600, xaxis: { autorange: false, range: [], rangeslider: { range: [] }, type: 'Number' }, yaxis: { autorange: true, range: [0, 50], type: 'linear' } }, frames: [], config: {} }; } render() { return ( <Plot data={this.state.data} layout={this.state.layout} frames={this.state.frames} config={this.state.config} onInitialized={figure => this.setState(figure)} onUpdate={figure => this.setState(figure)} /> ); } }
JavaScript
class BasePool extends EventEmitter { constructor(config, params) { super(); let cfg = config.pool || { min: 2, max: 5 }; cfg.min = cfg.min || 2; cfg.max = cfg.max || 5; this.pool = genericPool.createPool(this.createPool(config, params), cfg); this.poolErr = null; this.pool.on("factoryCreateError", err => { this.poolErr = err; const clientResourceRequest = this.pool._waitingClientsQueue.dequeue(); if (clientResourceRequest) { clientResourceRequest.reject(err); } }); } acquire() { return new Promise((resolve, reject) => { this.pool .acquire() .then(res => { if (res instanceof errors.OrientDBError) { reject(res); } resolve(res); }) .catch(err => { reject(this.createError(err)); }); }); } hasError() { return this.poolErr; } createError(err) { if (err) { return err; } return new errors.Connection(2, "Connection Error"); } createPool(config, params) {} release(resource) { return this.pool.release(resource); } size() { return this.pool.size; } available() { return this.pool.available; } borrowed() { return this.pool.borrowed; } pending() { return this.pool.pending; } close() { return this.pool.drain().then(() => { return this.pool.clear(); }); } }
JavaScript
class Engineer extends Employee { constructor (name, id, email, github) { // evoke the employee class super (name, id, email); this.github = github; } // return the github username from the inquirer response getGithub () { return this.github; } // engineer overrides the employee role getRole () { return "Engineer"; } }
JavaScript
class EditableChildObject extends ModelBase { //region Constructor /** * Creates a new asynchronous editable child object instance. * * _The name of the model type available as: * __&lt;instance&gt;.constructor.modelType__, returns 'EditableChildObject'._ * * Valid parent model types are: * * * EditableRootCollection * * EditableChildCollection * * EditableRootObject * * EditableChildObject * * @param {string} uri - The URI of the model. * @param {object} parent - The parent business object. * @param {bo.common.EventHandlerList} [eventHandlers] - The event handlers of the instance. * * @throws {@link bo.system.ArgumentError Argument error}: * The parent object must be an EditableChildCollection, EditableRootObject or * EditableChildObject instance. * @throws {@link bo.system.ArgumentError Argument error}: * The event handlers must be an EventHandlerList object or null. */ constructor( name, uri, properties, rules, extensions, parent, eventHandlers ) { super(); /** * The name of the model. However, it can be hidden by a model property with the same name. * * @member {string} EditableChildObject#$modelName * @readonly */ this.$modelName = name; /** * The URI of the model. * * @member {string} EditableChildObject#$modelUri * @readonly */ this.$modelUri = uri; // Initialize the instance. initialize.call( this, name, properties, rules, extensions, parent, eventHandlers ); } //endregion //region Properties /** * The name of the model type. * * @member {string} EditableChildObject.modelType * @default EditableChildObject * @readonly */ static get modelType() { return ModelType.EditableChildObject; } //endregion //region Mark object state /** * Notes that a child object has changed. * <br/>_This method is called by child objects._ * * @function EditableChildObject#childHasChanged * @protected */ childHasChanged() { markAsChanged.call( this, false ); } //endregion //region Show object state /** * Gets the state of the model. Valid states are: * pristine, created, changed, markedForRemoval and removed. * * @function EditableChildObject#getModelState * @returns {string} The state of the model. */ getModelState() { return MODEL_STATE.getName( _state.get( this ) ); } /** * Indicates whether the business object has been created newly and * not has been yet saved, i.e. its state is created. * * @function EditableChildObject#isNew * @returns {boolean} True when the business object is new, otherwise false. */ isNew() { return _state.get( this ) === MODEL_STATE.created; } /** * Indicates whether the business object itself or any of its child objects differs the one * that is stored in the repository, i.e. its state is created, changed or markedForRemoval. * * @function EditableChildObject#isDirty * @returns {boolean} True when the business object has been changed, otherwise false. */ isDirty() { const state = _state.get( this ); return state === MODEL_STATE.created || state === MODEL_STATE.changed || state === MODEL_STATE.markedForRemoval; } /** * Indicates whether the business object itself, ignoring its child objects, differs the one * that is stored in the repository. * * @function EditableChildObject#isSelfDirty * @returns {boolean} True when the business object itself has been changed, otherwise false. */ isSelfDirty() { return _isDirty.get( this ); } /** * Indicates whether the business object will be deleted from the repository, * i.e. its state is markedForRemoval. * * @function EditableChildObject#isDeleted * @returns {boolean} True when the business object will be deleted, otherwise false. */ isDeleted() { return _state.get( this ) === MODEL_STATE.markedForRemoval; } //endregion //region Transfer object methods /** * Determines that the passed data contains current values of the model key. * * @function EditableChildObject#keyEquals * @protected * @param {object} data - Data object whose properties can contain the values of the model key. * @param {internal~getValue} getPropertyValue - A function that returns * the current value of the given property. * @returns {boolean} True when the values are equal, false otherwise. */ keyEquals( data ) { const properties = _properties.get( this ); return properties.keyEquals( data, getPropertyValue.bind( this ) ); } /** * Transforms the business object collection to a plain object array to send to the server. * <br/>_This method is usually called by the parent object._ * * @function EditableChildCollection#toDto * @returns {Array.<object>} The data transfer object. */ toDto() { const self = this; const dto = {}; const properties = _properties.get( this ); properties .filter( property => { return property.isOnDto; } ) .forEach( property => { dto[ property.name ] = getPropertyValue.call( self, property ); } ); properties .children() .forEach( property => { dto[ property.name ] = getPropertyValue.call( self, property ).toDto(); } ); return dto; } fromDto( dto ) { const self = this; const properties = _properties.get( this ); properties .filter( property => { return property.isOnDto; } ) .forEach( property => { if (dto.hasOwnProperty( property.name ) && typeof dto[ property.name ] !== 'function') { setPropertyValue.call( self, property, dto[ property.name ] ); } } ); properties .children() .forEach( property => { if (dto.hasOwnProperty( property.name )) { getPropertyValue.call( self, property ).fromDto( dto[ property.name ] ); } } ); } //endregion //region Actions /** * Initializes a newly created business object. * <br/>_This method is called by the parent object._ * * @function EditableChildObject#create * @protected * @returns {Promise.<EditableChildObject>} Returns a promise to the new editable child object. */ create() { return data_create.call( this ); } /** * Initializes a business object with data retrieved from the repository. * <br/>_This method is called by the parent object._ * * @function EditableChildObject#fetch * @protected * @param {object} [data] - The data to load into the business object. * @param {string} [method] - An alternative fetch method to check for permission. * @returns {Promise.<EditableChildObject>} Returns a promise to the retrieved editable child object. */ fetch( data, method ) { return data_fetch.call( this, data, method || M_FETCH ); } /** * Marks the business object to be deleted from the repository on next save. * * @function EditableChildObject#remove */ remove() { markForRemoval.call( this ); } //endregion //region Validation /** * Indicates whether all the validation rules of the business object, including * the ones of its child objects, succeeds. A valid business object may have * broken rules with severity of success, information and warning. * * _This method is called by the parent object._ * * @function EditableChildObject#isValid * @protected * @returns {boolean} True when the business object is valid, otherwise false. */ isValid() { if (!_isValidated.get( this )) this.checkRules(); const brokenRules = _brokenRules.get( this ); return brokenRules.isValid() && childrenAreValid.call( this ); } /** * Executes all the validation rules of the business object, including the ones * of its child objects. * * _This method is called by the parent object._ * * @function EditableChildObject#checkRules * @protected */ checkRules() { const brokenRules = _brokenRules.get( this ); brokenRules.clear(); _brokenRules.set( this, brokenRules ); const context = new ValidationContext( _store.get( this ), brokenRules ); const properties = _properties.get( this ); const rules = _rules.get( this ); properties.forEach( property => { rules.validate( property, context ); } ); checkChildRules.call( this ); _isValidated.set( this, true ); } /** * Gets the broken rules of the business object. * * _This method is called by the parent object._ * * @function EditableChildObject#getBrokenRules * @protected * @param {string} [namespace] - The namespace of the message keys when messages are localizable. * @returns {bo.rules.BrokenRulesOutput} The broken rules of the business object. */ getBrokenRules( namespace ) { const brokenRules = _brokenRules.get( this ); let bro = brokenRules.output( namespace ); bro = getChildBrokenRules.call( this, namespace, bro ); return bro.$length ? bro : null; } //endregion }
JavaScript
class EditableChildObjectFactory { //region Constructor /** * Creates a definition for an editable child object. * * Valid child model types are: * * * ReadOnlyChildCollection * * ReadOnlyChildObject * * @param {string} name - The name of the model. * @param {bo.common.PropertyManager} properties - The property definitions. * @param {bo.common.RuleManager} rules - The validation and authorization rules. * @param {bo.common.ExtensionManager} extensions - The customization of the model. * @returns {EditableChildObject} The constructor of an asynchronous editable child object. * * @throws {@link bo.system.ArgumentError Argument error}: The model name must be a non-empty string. * @throws {@link bo.system.ArgumentError Argument error}: The properties must be a PropertyManager object. * @throws {@link bo.system.ArgumentError Argument error}: The rules must be a RuleManager object. * @throws {@link bo.system.ArgumentError Argument error}: The extensions must be a ExtensionManager object. * * @throws {@link bo.common.ModelError Model error}: * The child objects must be EditableChildCollection or EditableChildObject instances. */ constructor( name, properties, rules, extensions ) { const check = Argument.inConstructor( ModelType.EditableChildObject ); name = check( name ).forMandatory( 'name' ).asString(); properties = check( properties ).forMandatory( 'properties' ).asType( PropertyManager ); rules = check( rules ).forMandatory( 'rules' ).asType( RuleManager ); extensions = check( extensions ).forMandatory( 'extensions' ).asType( ExtensionManager ); // Verify the model types of child objects. properties.modelName = name; properties.verifyChildTypes( [ ModelType.EditableChildCollection, ModelType.EditableChildObject ] ); // Create model definition. const Model = EditableChildObject.bind( undefined, nameFromPhrase( name ), uriFromPhrase( name ), properties, rules, extensions ); /** * The name of the model type. * * @member {string} EditableChildObject.modelType * @default EditableChildObject * @readonly */ Model.modelType = ModelType.EditableChildObject; //region Factory methods /** * Creates a new uninitialized editable child object instance. * <br/>_This method is called by the parent object._ * * @function EditableChildObject.empty * @protected * @param {object} parent - The parent business object. * @param {bo.common.EventHandlerList} [eventHandlers] - The event handlers of the instance. * @returns {EditableChildObject} Returns a new editable child object. */ Model.empty = function ( parent, eventHandlers ) { const instance = new Model( parent, eventHandlers ); markAsCreated.call( instance ); return instance; }; /** * Creates a new editable child object instance. * <br/>_This method is called by the parent object._ * * @function EditableChildObject.create * @protected * @param {object} parent - The parent business object. * @param {bo.common.EventHandlerList} [eventHandlers] - The event handlers of the instance. * @returns {Promise.<EditableChildObject>} Returns a promise to the new editable child object. * * @throws {@link bo.rules.AuthorizationError Authorization error}: * The user has no permission to execute the action. * @throws {@link bo.apiAccess.ApiClientError Data portal error}: * Creating the business object has failed. */ Model.create = function ( parent, eventHandlers ) { const instance = new Model( parent, eventHandlers ); return instance.create(); }; /** * Initializes an editable child object width data retrieved from the repository. * <br/>_This method is called by the parent object._ * * @function EditableChildObject.load * @protected * @param {object} parent - The parent business object. * @param {object} data - The data to load into the business object. * @param {bo.common.EventHandlerList} [eventHandlers] - The event handlers of the instance. * @returns {Promise.<EditableChildObject>} Returns a promise to the retrieved editable child object. * * @throws {@link bo.rules.AuthorizationError Authorization error}: * The user has no permission to execute the action. */ Model.load = function ( parent, data, eventHandlers ) { const instance = new Model( parent, eventHandlers ); return instance.fetch( data, undefined ); }; //endregion // Immutable definition class. Object.freeze( Model ); return Model; } //endregion }
JavaScript
class ResourceLoader { /** * ResourceLoader constructor * * @param {Object} lib - `{ uri:<URI>, version:<STRING>, type:<STRING> }` * @param {String} lib.uri - URI * @param {String} lib.version - version * @param {String} lib.type - [Reserved] * @param {CraftBootloader.LibLoader} delegate - caller */ constructor(lib,delegate){ this.lib = lib; this.delegate = delegate; } /** * Prepare resource from IndexedDB * @protected */ prepareFromCache(){ window.bootConfig.Context.libStore.get(this.lib.uri,(content)=>{ this.lib.content = content; this.delegate.checker(this.lib); }); } /** * Prepare resource from remote this.lib.uri * @protected */ prepareFromRemote(){ let http = new XMLHttpRequest(); http.onload = (e) => { this.lib.content = http.responseText; // version guarantees content window.bootConfig.Context.libStore.put(this.lib.uri,this.lib.content, () => { window.bootConfig.Context.verStore.put(this.lib.uri,this.lib.version, () => { this.delegate.checker(this.lib); }); }); }; http.onerror = (e) => { alert('Cannot load'); }; http.ontimeout = () => { alert('Timeout'); }; http.open('GET',this.lib.uri); //http.withCredentials = true; http.send(); } /** * Prepare resource content * @public */ prepare(){ window.bootConfig.Context.verStore.get(this.lib.uri,(version)=>{ if( this.lib.version !== version ){ this.prepareFromRemote(); }else{ this.prepareFromCache(); } }); } /** * Abstruct method. * * Child must implement how to laod the resource into the DOM tree. * * @protected */ load(){ // you should implement your content loader } }
JavaScript
class Explosions{ preload () { this.load.path = 'assets/animations/'; this.load.image('explosion1', ''); this.load.image('explosion2', ''); this.load.image('explosion3', ''); this.load.image('explosion4', ''); // put explosion images } create () { this.anims.create({ key: 'snooze', frames: [ { key: 'explosion1' }, { key: 'explosion2' }, { key: 'explosion3' }, { key: 'explosion4', duration: 40 } ], frameRate: 5, }); this.add.sprite(this.rocket.x, this.rocket.y, 'explosion1').play('explode'); } }
JavaScript
class XRFieldOfView { constructor(upDegrees, downDegrees, leftDegrees, rightDegrees){ this._upDegrees = upDegrees this._downDegrees = downDegrees this._leftDegrees = leftDegrees this._rightDegrees = rightDegrees } get upDegrees(){ return this._upDegrees } get downDegrees(){ return this._downDegrees } get leftDegrees(){ return this._leftDegrees } get rightDegrees(){ return this._rightDegrees } }
JavaScript
class DelegateInputLabel extends Base { // Forward any ARIA label to the input element. get ariaLabel() { return this[state].ariaLabel; } set ariaLabel(ariaLabel) { if (!this[state].removingAriaAttribute) { this[setState]({ ariaLabel: String(ariaLabel), }); } } // Forward ARIA labelledby as an aria-label to the input element. // Note the lowercase "b" in the name, necessary to support the actual // attribute name "aria-labelledby", which has no hyphen before the "by". get ariaLabelledby() { return this[state].ariaLabelledby; } set ariaLabelledby(ariaLabelledby) { if (!this[state].removingAriaAttribute) { this[setState]({ ariaLabelledby: String(ariaLabelledby), }); } } // @ts-ignore get [defaultState]() { return Object.assign(super[defaultState] || {}, { ariaLabel: null, ariaLabelledby: null, inputLabel: null, removingAriaAttribute: false, }); } [render](changed) { if (super[render]) { super[render](changed); } if (this[firstRender]) { // Refresh the input label on focus. This refresh appears to happen fast // enough that the screen reader will announce the refreshed label. this.addEventListener("focus", () => { this[raiseChangeEvents] = true; const inputLabel = refreshInputLabel(this, this[state]); this[setState]({ inputLabel }); this[raiseChangeEvents] = false; }); } // Apply the latest input label to the input delegate. if (changed.inputLabel) { const { inputLabel } = this[state]; if (inputLabel) { this[inputDelegate].setAttribute("aria-label", inputLabel); } else { this[inputDelegate].removeAttribute("aria-label"); } } } [rendered](changed) { if (super[rendered]) { super[rendered](changed); } if (this[firstRender]) { // Refresh the label on first render. This is not guaranteed to pick up // labels defined by another element, as that element (or elements) may // not be in the DOM yet. For that reason, we'll also refresh the label // on focus. The reason to do it now is to handle the common cases where // the element defining the label does exist so that accessibility // testing tools can confirm that the input delegate does have a label. // Because this refresh can entail multiple searches of the tree, we // defer the refresh to idle time. // @ts-ignore const idleCallback = window.requestIdleCallback || setTimeout; idleCallback(() => { const inputLabel = refreshInputLabel(this, this[state]); this[setState]({ inputLabel }); }); } // Once we've obtained an aria-label or aria-labelledby from the host, we // remove those attirbutes so that the labels don't get announced twice. // We use a flag to distinguish between us removing our own ARIA // attributes (which should not update state), and someone removing // those attributes from the outside (which should update state). const { ariaLabel, ariaLabelledby } = this[state]; if (changed.ariaLabel && !this[state].removingAriaAttribute) { if (this.getAttribute("aria-label")) { this.setAttribute("delegated-label", ariaLabel); this[setState]({ removingAriaAttribute: true }); this.removeAttribute("aria-label"); } } if (changed.ariaLabelledby && !this[state].removingAriaAttribute) { if (this.getAttribute("aria-labelledby")) { this.setAttribute("delegated-labelledby", ariaLabelledby); this[setState]({ removingAriaAttribute: true }); this.removeAttribute("aria-labelledby"); } } if (changed.removingAriaAttribute && this[state].removingAriaAttribute) { // We've done whatever removal we needed, and can now reset our flag. this[setState]({ removingAriaAttribute: false }); } } [stateEffects](state, changed) { const effects = super[stateEffects] ? super[stateEffects](state, changed) : {}; // If the ariaLabel changes, we can update our inputLabel state // immediately. Among other things, this facilitates scenarios where we // have nested elements using DelegateInputLabelMixin: the outermost // element can use whatever label approach it wants, the inner elements // will all use ariaLabel. // // We also update the label if we're focused, using ariaLabelledby, and // the selectedText changes. One pattern with select-like elements is to // have them include their own ID in the IDs specified by aria-labelledby. // This can incorporate the element's own `selectedText` in the announced // label. That `selectedText` can change while the element has focus, in // which case we'll refresh. if ( (changed.ariaLabel && state.ariaLabel) || (changed.selectedText && state.ariaLabelledby && this.matches(":focus-within")) ) { const inputLabel = refreshInputLabel(this, state); Object.assign(effects, { inputLabel }); } return effects; } }
JavaScript
class App extends Component { state={ gameId:null } setGameId = (id) =>{ this.setState({gameId:id}) } render() { console.log(this.state) return ( <div className="App"> <Switch> <Route path="/gameHost" render={() => <GameHost setGameId={this.setGameId}/>} /> <Route path="/user" render={() => <User gameId={this.state.gameId}/>} /> </Switch> <Header /> <GameWelcomePage /> </div> ); } }
JavaScript
class CreatePPLKB extends Component { constructor(props) { super(props); this.state = { expanded: 'panel1', open: false, } } render() { return ( <div className="animated fadeIn"> <Row> <Col xs="12" md="12"> <Card> <CardBody> <Row> <Col md="12"> <div className="titleFilter"><i className="icon-clipboard3"></i> Pendafataran PPLKB</div> </Col> <Col xs="12" md="12"><hr style={{ borderBottom: '1px solid orange', marginTop: '5px' }} /></Col> <Col sm="12"> <h6>IDENTITAS PPLKB</h6> <div style={{ position: 'absolute', right: '0', marginTop: '-30px', fontSize: '12px' }}>{this.props.currentStep} {this.props.totalSteps}</div> <CardBody> <FormGroup> <Row> <Col md="4"> <Label>1. NAMA</Label> </Col> <Col md="8"> <Input type="text" id="text-input" name="text-input" /> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col md="12" xs="12"> <Label>2. ALAMAT</Label> <Row> <Col md="4" xs="12" style={{ paddingTop: '10px' }}> <Label>a. Jalan :</Label> </Col> <Col md="4" style={{ paddingTop: '10px' }}> <Input type="text" id="text-input" name="text-input" /> </Col> <Col md="2" xs="4" style={{ paddingTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>RT :</Label></Col> <Col md="8" xs="8"><Input type="text" id="text-input" name="text-input" /></Col> </Row> </Col> <Col md="2" xs="4" style={{ paddingTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>RW :</Label></Col> <Col md="8" xs="8"><Input type="text" id="text-input" name="text-input" /></Col> </Row> </Col> </Row> <Row> <Col md="4" style={{ marginTop: '10px' }}> <Label>b. Desa/Kelurahan :</Label> </Col> <Col md="4" xs="9" style={{ marginTop: '10px' }}> <Input type="text" id="text-input" name="text-input" /> </Col> <Col md="3" xs="6" style={{ paddingTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>Kode :</Label></Col> <Col md="8" xs="8"><Input type="text" id="text-input" name="text-input" /></Col> </Row> </Col> </Row> <Row> <Col md="4" style={{ marginTop: '10px' }}> <Label>c. Kecamatan :</Label> </Col> <Col md="4" xs="9" style={{ marginTop: '10px' }}> <Input type="text" id="text-input" name="text-input" value="" /> </Col> <Col md="3" xs="6" style={{ paddingTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>Kode :</Label></Col> <Col md="8" xs="8"><Input type="text" id="text-input" name="text-input" /></Col> </Row> </Col> </Row> <Row> <Col md="4" style={{ marginTop: '10px' }}> <Label>d. Kabupaten :</Label> </Col> <Col md="4" xs="9" style={{ marginTop: '10px' }}> <Input type="text" id="text-input" name="text-input" value="" /> </Col> <Col md="3" xs="6" style={{ paddingTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>Kode :</Label></Col> <Col md="8" xs="8"><Input type="text" id="text-input" name="text-input" /></Col> </Row> </Col> </Row> <Row> <Col md="4" style={{ marginTop: '10px' }}> <Label>e. Provinsi :</Label> </Col> <Col md="4" xs="9" style={{ marginTop: '10px' }}> <Input type="text" id="text-input" name="text-input" value="" /> </Col> <Col md="3" xs="6" style={{ paddingTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>Kode :</Label></Col> <Col md="8" xs="8"><Input type="text" id="text-input" name="text-input" /></Col> </Row> </Col> </Row> <Row> <Col md="4" style={{ marginTop: '10px' }}> <Label>f. Telepon :</Label> </Col> <Col md="4" xs="9" style={{ marginTop: '10px' }}> <Input type="number" id="text-input" name="text-input" value="" /> </Col> <Col md="3" xs="6" style={{ marginTop: '10px' }}> <Row> <Col md="4" xs="4"><Label>e-Mail :</Label></Col> <Col md="8" xs="8"><Input type="email" id="text-input" name="text-input" value="" /></Col> </Row> </Col> </Row> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col md="4" > <Label>3. JENIS KELAMIN :</Label><br /> </Col> <Col md="7" style={{ paddingLeft: '35px' }}> <Row> <Col md="4" xs="6"> <Input type="radio" name="jenis-kelamin" />{' '} 1. Laki-laki </Col> <Col md="4" xs="6"> <Input type="radio" name="jenis-kelamin" />{' '} 2. Perempuan </Col> </Row> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col md="4"> <Label>4. NAMA JABATAN PETUGAS KB : <i>(Pilih Salah Satu)</i></Label><br /> <Label>Tingkat Kecamatan</Label> </Col> <Col md="7" style={{ paddingLeft: '35px' }}> <Row> <Col md="4" xs="6"> <Input type="radio" name="radio7" />{' '} 1. PPLKB </Col> <Col md="4" xs="6"> <Input type="radio" name="radio7" />{' '} 2. Ka. UPT </Col> <Col md="4" xs="6"> <Input type="radio" name="radio7" />{' '} 3. Koordinator PLKB </Col> </Row> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col> <Row> <Col md="4" xs="12"> <Label>5. Angka Kredit PKB</Label> </Col> <Col md="3" xs="5"> <Input type="number" id="text-input" name="text-input" value="Bali" /> </Col> <Col md="2" xs="3" className="d-flex justify-content-end"> <Label>TMT :</Label> </Col> <Col md="3" xs="4"> <Input type="text" id="text-input" name="text-input" value="" /> </Col> </Row> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col> <Row> <Col md="4" xs="12"> <Label>6. NIP</Label> </Col> <Col md="3"> <Input type="number" id="text-input" name="text-input" value="Bali" /> </Col> </Row> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col> <Row> <Col md="4" xs="12"> <Label>7. NIK</Label> </Col> <Col md="3" xs="10"> <Input type="number" id="text-input" name="text-input" value="Bali" /> </Col> <Col md="1" xs="1"> <Button className="btn btn-dark"> <i className="icon-search4"></i> </Button> </Col> </Row> </Col> </Row> <Row> <Col md="12" style={{ paddingTop: '20px' }}></Col> <Col> <Label>8. PENDIDIKAN TERAKHIR </Label> <FormGroup> <Row style={{ paddingLeft: '50px' }}> <Col md="6" xs="6"> <Row> <Col md="4"> <Input type="radio" name="radio10" />{' '} 1. SMA </Col> <Col md="4"> <Input type="radio" name="radio10" />{' '} 2. D1 </Col> <Col md="4"> <Input type="radio" name="radio10" />{' '} 3. D2 </Col> </Row> </Col> <Col md="6" xs="6"> <Row> <Col md="4"> <Input type="radio" name="radio10" />{' '} 4. D3 </Col> <Col md="4"> <Input type="radio" name="radio10" />{' '} 5. S1 </Col> <Col md="4"> <Input type="radio" name="radio10" />{' '} 6. S2 </Col> </Row> </Col> </Row> </FormGroup> </Col> </Row> </FormGroup> </CardBody> </Col> </Row> </CardBody> </Card> </Col> </Row > </div > ) } }
JavaScript
class XMLBuilderImpl { /** * Initializes a new instance of `XMLBuilderNodeImpl`. * * @param domNode - the DOM node to wrap */ constructor(domNode) { this._domNode = domNode; } /** @inheritdoc */ get node() { return this._domNode; } /** @inheritdoc */ set(options) { this._options = util_1.applyDefaults(util_1.applyDefaults(this._options, options, true), // apply user settings interfaces_1.DefaultBuilderOptions); // provide defaults return this; } /** @inheritdoc */ ele(p1, p2, p3) { let namespace; let name; let attributes; let lastChild = null; if (util_1.isString(p1) && /^\s*</.test(p1)) { // parse XML string const contents = "<TEMP_ROOT>" + p1 + "</TEMP_ROOT>"; const domParser = dom_1.createParser(); const doc = domParser.parseFromString(dom_1.sanitizeInput(contents, this._options.invalidCharReplacement), "text/xml"); /* istanbul ignore next */ if (doc.documentElement === null) { throw new Error("Document element is null."); } dom_1.throwIfParserError(doc); for (const child of doc.documentElement.childNodes) { const newChild = doc.importNode(child, true); lastChild = new XMLBuilderImpl(newChild); this._domNode.appendChild(newChild); } if (lastChild === null) { throw new Error("Could not create any elements with: " + p1.toString() + ". " + this._debugInfo()); } return lastChild; } else if (util_1.isString(p1) && /^\s*[\{\[]/.test(p1)) { // parse JSON string const obj = JSON.parse(p1); return this.ele(obj); } else if (util_1.isObject(p1)) { // ele(obj: ExpandObject) [namespace, name, attributes] = [undefined, p1, undefined]; } else if ((p1 === null || util_1.isString(p1)) && util_1.isString(p2)) { // ele(namespace: string, name: string, attributes?: AttributesObject) [namespace, name, attributes] = [p1, p2, p3]; } else if (p1 !== null) { // ele(name: string, attributes?: AttributesObject) [namespace, name, attributes] = [undefined, p1, util_1.isObject(p2) ? p2 : undefined]; } else { throw new Error("Element name cannot be null. " + this._debugInfo()); } if (attributes) { attributes = util_1.getValue(attributes); } if (util_1.isFunction(name)) { // evaluate if function lastChild = this.ele(name.apply(this)); } else if (util_1.isArray(name) || util_1.isSet(name)) { util_1.forEachArray(name, item => lastChild = this.ele(item), this); } else if (util_1.isMap(name) || util_1.isObject(name)) { // expand if object util_1.forEachObject(name, (key, val) => { if (util_1.isFunction(val)) { // evaluate if function val = val.apply(this); } if (!this._options.ignoreConverters && key.indexOf(this._options.convert.att) === 0) { // assign attributes if (key === this._options.convert.att) { lastChild = this.att(val); } else { lastChild = this.att(key.substr(this._options.convert.att.length), val); } } else if (!this._options.ignoreConverters && key.indexOf(this._options.convert.text) === 0) { // text node if (util_1.isMap(val) || util_1.isObject(val)) { // if the key is #text expand child nodes under this node to support mixed content lastChild = this.ele(val); } else { lastChild = this.txt(val); } } else if (!this._options.ignoreConverters && key.indexOf(this._options.convert.cdata) === 0) { // cdata node if (util_1.isArray(val) || util_1.isSet(val)) { util_1.forEachArray(val, item => lastChild = this.dat(item), this); } else { lastChild = this.dat(val); } } else if (!this._options.ignoreConverters && key.indexOf(this._options.convert.comment) === 0) { // comment node if (util_1.isArray(val) || util_1.isSet(val)) { util_1.forEachArray(val, item => lastChild = this.com(item), this); } else { lastChild = this.com(val); } } else if (!this._options.ignoreConverters && key.indexOf(this._options.convert.ins) === 0) { // processing instruction if (util_1.isString(val)) { const insIndex = val.indexOf(' '); const insTarget = (insIndex === -1 ? val : val.substr(0, insIndex)); const insValue = (insIndex === -1 ? '' : val.substr(insIndex + 1)); lastChild = this.ins(insTarget, insValue); } else { lastChild = this.ins(val); } } else if ((util_1.isArray(val) || util_1.isSet(val)) && util_1.isEmpty(val)) { // skip empty arrays lastChild = this._dummy(); } else if ((util_1.isMap(val) || util_1.isObject(val)) && util_1.isEmpty(val)) { // empty objects produce one node lastChild = this.ele(key); } else if (!this._options.keepNullNodes && (val == null)) { // skip null and undefined nodes lastChild = this._dummy(); } else if (util_1.isArray(val) || util_1.isSet(val)) { // expand list by creating child nodes util_1.forEachArray(val, item => { const childNode = {}; childNode[key] = item; lastChild = this.ele(childNode); }, this); } else if (util_1.isMap(val) || util_1.isObject(val)) { // create a parent node lastChild = this.ele(key); // expand child nodes under parent lastChild.ele(val); } else if (val) { // leaf element node with a single text node lastChild = this.ele(key); lastChild.txt(val); } else { // leaf element node lastChild = this.ele(key); } }, this); } else { [namespace, name] = this._extractNamespace(dom_1.sanitizeInput(namespace, this._options.invalidCharReplacement), dom_1.sanitizeInput(name, this._options.invalidCharReplacement), true); // inherit namespace from parent if (namespace === undefined) { const [prefix] = algorithm_1.namespace_extractQName(name); namespace = this.node.lookupNamespaceURI(prefix); } // create a child element node const childNode = (namespace !== undefined && namespace !== null ? this._doc.createElementNS(namespace, name) : this._doc.createElement(name)); this.node.appendChild(childNode); lastChild = new XMLBuilderImpl(childNode); // update doctype node if the new node is the document element node const oldDocType = this._doc.doctype; if (childNode === this._doc.documentElement && oldDocType !== null) { const docType = this._doc.implementation.createDocumentType(this._doc.documentElement.tagName, oldDocType.publicId, oldDocType.systemId); this._doc.replaceChild(docType, oldDocType); } // create attributes if (attributes && !util_1.isEmpty(attributes)) { lastChild.att(attributes); } } if (lastChild === null) { throw new Error("Could not create any elements with: " + name.toString() + ". " + this._debugInfo()); } return lastChild; } /** @inheritdoc */ remove() { const parent = this.up(); parent.node.removeChild(this.node); return parent; } /** @inheritdoc */ att(p1, p2, p3) { if (util_1.isMap(p1) || util_1.isObject(p1)) { // att(obj: AttributesObject) // expand if object util_1.forEachObject(p1, (attName, attValue) => this.att(attName, attValue), this); return this; } // get primitive values if (p1 !== undefined && p1 !== null) p1 = util_1.getValue(p1 + ""); if (p2 !== undefined && p2 !== null) p2 = util_1.getValue(p2 + ""); if (p3 !== undefined && p3 !== null) p3 = util_1.getValue(p3 + ""); let namespace; let name; let value; if ((p1 === null || util_1.isString(p1)) && util_1.isString(p2) && (p3 === null || util_1.isString(p3))) { // att(namespace: string, name: string, value: string) [namespace, name, value] = [p1, p2, p3]; } else if (util_1.isString(p1) && (p2 == null || util_1.isString(p2))) { // ele(name: string, value: string) [namespace, name, value] = [undefined, p1, p2]; } else { throw new Error("Attribute name and value not specified. " + this._debugInfo()); } if (this._options.keepNullAttributes && (value == null)) { // keep null attributes value = ""; } else if (value == null) { // skip null|undefined attributes return this; } if (!util_2.Guard.isElementNode(this.node)) { throw new Error("An attribute can only be assigned to an element node."); } let ele = this.node; [namespace, name] = this._extractNamespace(namespace, name, false); name = dom_1.sanitizeInput(name, this._options.invalidCharReplacement); namespace = dom_1.sanitizeInput(namespace, this._options.invalidCharReplacement); value = dom_1.sanitizeInput(value, this._options.invalidCharReplacement); const [prefix, localName] = algorithm_1.namespace_extractQName(name); const [elePrefix, eleLocalName] = algorithm_1.namespace_extractQName(ele.prefix ? ele.prefix + ':' + ele.localName : ele.localName); // check if this is a namespace declaration attribute // assign a new element namespace if it wasn't previously assigned let eleNamespace = null; if (prefix === "xmlns") { namespace = infra_1.namespace.XMLNS; if (ele.namespaceURI === null && elePrefix === localName) { eleNamespace = value; } } else if (prefix === null && localName === "xmlns" && elePrefix === null) { namespace = infra_1.namespace.XMLNS; eleNamespace = value; } // re-create the element node if its namespace changed // we can't simply change the namespaceURI since its read-only if (eleNamespace !== null) { const newEle = algorithm_1.create_element(this._doc, eleLocalName, eleNamespace, elePrefix); for (const attr of ele.attributes) { newEle.setAttributeNodeNS(attr.cloneNode()); } for (const childNode of ele.childNodes) { newEle.appendChild(childNode.cloneNode()); } const parent = ele.parentNode; /* istanbul ignore next */ if (parent === null) { throw new Error("Parent node is null." + this._debugInfo()); } parent.replaceChild(newEle, ele); this._domNode = newEle; ele = newEle; } if (namespace !== undefined) { ele.setAttributeNS(namespace, name, value); } else { ele.setAttribute(name, value); } return this; } /** @inheritdoc */ removeAtt(p1, p2) { if (!util_2.Guard.isElementNode(this.node)) { throw new Error("An attribute can only be removed from an element node."); } // get primitive values p1 = util_1.getValue(p1); if (p2 !== undefined) { p2 = util_1.getValue(p2); } let namespace; let name; if (p1 !== null && p2 === undefined) { name = p1; } else if ((p1 === null || util_1.isString(p1)) && p2 !== undefined) { namespace = p1; name = p2; } else { throw new Error("Attribute namespace must be a string. " + this._debugInfo()); } if (util_1.isArray(name) || util_1.isSet(name)) { // removeAtt(names: string[]) // removeAtt(namespace: string, names: string[]) util_1.forEachArray(name, attName => namespace === undefined ? this.removeAtt(attName) : this.removeAtt(namespace, attName), this); } else if (namespace !== undefined) { // removeAtt(namespace: string, name: string) name = dom_1.sanitizeInput(name, this._options.invalidCharReplacement); namespace = dom_1.sanitizeInput(namespace, this._options.invalidCharReplacement); this.node.removeAttributeNS(namespace, name); } else { // removeAtt(name: string) name = dom_1.sanitizeInput(name, this._options.invalidCharReplacement); this.node.removeAttribute(name); } return this; } /** @inheritdoc */ txt(content) { const child = this._doc.createTextNode(dom_1.sanitizeInput(content, this._options.invalidCharReplacement)); this.node.appendChild(child); return this; } /** @inheritdoc */ com(content) { const child = this._doc.createComment(dom_1.sanitizeInput(content, this._options.invalidCharReplacement)); this.node.appendChild(child); return this; } /** @inheritdoc */ dat(content) { const child = this._doc.createCDATASection(dom_1.sanitizeInput(content, this._options.invalidCharReplacement)); this.node.appendChild(child); return this; } /** @inheritdoc */ ins(target, content = '') { if (util_1.isArray(target) || util_1.isSet(target)) { util_1.forEachArray(target, item => { item += ""; const insIndex = item.indexOf(' '); const insTarget = (insIndex === -1 ? item : item.substr(0, insIndex)); const insValue = (insIndex === -1 ? '' : item.substr(insIndex + 1)); this.ins(insTarget, insValue); }, this); } else if (util_1.isMap(target) || util_1.isObject(target)) { util_1.forEachObject(target, (insTarget, insValue) => this.ins(insTarget, insValue), this); } else { const child = this._doc.createProcessingInstruction(dom_1.sanitizeInput(target, this._options.invalidCharReplacement), dom_1.sanitizeInput(content, this._options.invalidCharReplacement)); this.node.appendChild(child); } return this; } /** @inheritdoc */ dec(options) { this._options.version = options.version || "1.0"; this._options.encoding = options.encoding; this._options.standalone = options.standalone; return this; } /** @inheritdoc */ dtd(options) { const name = dom_1.sanitizeInput((options && options.name) || (this._doc.documentElement ? this._doc.documentElement.tagName : "ROOT"), this._options.invalidCharReplacement); const pubID = dom_1.sanitizeInput((options && options.pubID) || "", this._options.invalidCharReplacement); const sysID = dom_1.sanitizeInput((options && options.sysID) || "", this._options.invalidCharReplacement); // name must match document element if (this._doc.documentElement !== null && name !== this._doc.documentElement.tagName) { throw new Error("DocType name does not match document element name."); } // create doctype node const docType = this._doc.implementation.createDocumentType(name, pubID, sysID); if (this._doc.doctype !== null) { // replace existing doctype this._doc.replaceChild(docType, this._doc.doctype); } else { // insert before document element node or append to end this._doc.insertBefore(docType, this._doc.documentElement); } return this; } /** @inheritdoc */ import(node) { const hostNode = this._domNode; const hostDoc = this._doc; const importedNode = node.node; if (util_2.Guard.isDocumentNode(importedNode)) { // import document node const elementNode = importedNode.documentElement; if (elementNode === null) { throw new Error("Imported document has no document element node. " + this._debugInfo()); } const clone = hostDoc.importNode(elementNode, true); hostNode.appendChild(clone); } else if (util_2.Guard.isDocumentFragmentNode(importedNode)) { // import child nodes for (const childNode of importedNode.childNodes) { const clone = hostDoc.importNode(childNode, true); hostNode.appendChild(clone); } } else { // import node const clone = hostDoc.importNode(importedNode, true); hostNode.appendChild(clone); } return this; } /** @inheritdoc */ doc() { if (this._doc._isFragment) { let node = this.node; while (node && node.nodeType !== interfaces_2.NodeType.DocumentFragment) { node = node.parentNode; } /* istanbul ignore next */ if (node === null) { throw new Error("Node has no parent node while searching for document fragment ancestor."); } return new XMLBuilderImpl(node); } else { return new XMLBuilderImpl(this._doc); } } /** @inheritdoc */ root() { const ele = this._doc.documentElement; if (!ele) { throw new Error("Document root element is null. " + this._debugInfo()); } return new XMLBuilderImpl(ele); } /** @inheritdoc */ up() { const parent = this._domNode.parentNode; if (!parent) { throw new Error("Parent node is null. " + this._debugInfo()); } return new XMLBuilderImpl(parent); } /** @inheritdoc */ prev() { const node = this._domNode.previousSibling; if (!node) { throw new Error("Previous sibling node is null. " + this._debugInfo()); } return new XMLBuilderImpl(node); } /** @inheritdoc */ next() { const node = this._domNode.nextSibling; if (!node) { throw new Error("Next sibling node is null. " + this._debugInfo()); } return new XMLBuilderImpl(node); } /** @inheritdoc */ first() { const node = this._domNode.firstChild; if (!node) { throw new Error("First child node is null. " + this._debugInfo()); } return new XMLBuilderImpl(node); } /** @inheritdoc */ last() { const node = this._domNode.lastChild; if (!node) { throw new Error("Last child node is null. " + this._debugInfo()); } return new XMLBuilderImpl(node); } /** @inheritdoc */ each(callback, self = false, recursive = false, thisArg) { let result = this._getFirstDescendantNode(this._domNode, self, recursive); while (result[0]) { callback.call(thisArg, new XMLBuilderImpl(result[0]), result[1], result[2]); result = this._getNextDescendantNode(this._domNode, result[0], recursive, result[1], result[2]); } return this; } /** @inheritdoc */ map(callback, self = false, recursive = false, thisArg) { let result = []; this.each((node, index, level) => result.push(callback.call(thisArg, node, index, level)), self, recursive); return result; } /** @inheritdoc */ reduce(callback, initialValue, self = false, recursive = false, thisArg) { let value = initialValue; this.each((node, index, level) => value = callback.call(thisArg, value, node, index, level), self, recursive); return value; } /** @inheritdoc */ find(predicate, self = false, recursive = false, thisArg) { let result = this._getFirstDescendantNode(this._domNode, self, recursive); while (result[0]) { const builder = new XMLBuilderImpl(result[0]); if (predicate.call(thisArg, builder, result[1], result[2])) { return builder; } result = this._getNextDescendantNode(this._domNode, result[0], recursive, result[1], result[2]); } return undefined; } /** @inheritdoc */ filter(predicate, self = false, recursive = false, thisArg) { let result = []; this.each((node, index, level) => { if (predicate.call(thisArg, node, index, level)) { result.push(node); } }, self, recursive); return result; } /** @inheritdoc */ every(predicate, self = false, recursive = false, thisArg) { let result = this._getFirstDescendantNode(this._domNode, self, recursive); while (result[0]) { const builder = new XMLBuilderImpl(result[0]); if (!predicate.call(thisArg, builder, result[1], result[2])) { return false; } result = this._getNextDescendantNode(this._domNode, result[0], recursive, result[1], result[2]); } return true; } /** @inheritdoc */ some(predicate, self = false, recursive = false, thisArg) { let result = this._getFirstDescendantNode(this._domNode, self, recursive); while (result[0]) { const builder = new XMLBuilderImpl(result[0]); if (predicate.call(thisArg, builder, result[1], result[2])) { return true; } result = this._getNextDescendantNode(this._domNode, result[0], recursive, result[1], result[2]); } return false; } /** @inheritdoc */ toArray(self = false, recursive = false) { let result = []; this.each(node => result.push(node), self, recursive); return result; } /** @inheritdoc */ toString(writerOptions) { writerOptions = writerOptions || {}; if (writerOptions.format === undefined) { writerOptions.format = "xml"; } return this._serialize(writerOptions); } /** @inheritdoc */ toObject(writerOptions) { writerOptions = writerOptions || {}; if (writerOptions.format === undefined) { writerOptions.format = "object"; } return this._serialize(writerOptions); } /** @inheritdoc */ end(writerOptions) { writerOptions = writerOptions || {}; if (writerOptions.format === undefined) { writerOptions.format = "xml"; } return this.doc()._serialize(writerOptions); } /** * Gets the next descendant of the given node of the tree rooted at `root` * in depth-first pre-order. Returns a three-tuple with * [descendant, descendant_index, descendant_level]. * * @param root - root node of the tree * @param self - whether to visit the current node along with child nodes * @param recursive - whether to visit all descendant nodes in tree-order or * only the immediate child nodes */ _getFirstDescendantNode(root, self, recursive) { if (self) return [this._domNode, 0, 0]; else if (recursive) return this._getNextDescendantNode(root, root, recursive, 0, 0); else return [this._domNode.firstChild, 0, 1]; } /** * Gets the next descendant of the given node of the tree rooted at `root` * in depth-first pre-order. Returns a three-tuple with * [descendant, descendant_index, descendant_level]. * * @param root - root node of the tree * @param node - current node * @param recursive - whether to visit all descendant nodes in tree-order or * only the immediate child nodes * @param index - child node index * @param level - current depth of the XML tree */ _getNextDescendantNode(root, node, recursive, index, level) { if (recursive) { // traverse child nodes if (node.firstChild) return [node.firstChild, 0, level + 1]; if (node === root) return [null, -1, -1]; // traverse siblings if (node.nextSibling) return [node.nextSibling, index + 1, level]; // traverse parent's next sibling let parent = node.parentNode; while (parent && parent !== root) { if (parent.nextSibling) return [parent.nextSibling, algorithm_1.tree_index(parent.nextSibling), level - 1]; parent = parent.parentNode; level--; } } else { if (root === node) return [node.firstChild, 0, level + 1]; else return [node.nextSibling, index + 1, level]; } return [null, -1, -1]; } /** * Converts the node into its string or object representation. * * @param options - serialization options */ _serialize(writerOptions) { if (writerOptions.format === "xml") { const writer = new writers_1.XMLWriter(this._options); return writer.serialize(this.node, writerOptions); } else if (writerOptions.format === "map") { const writer = new writers_1.MapWriter(this._options); return writer.serialize(this.node, writerOptions); } else if (writerOptions.format === "object") { const writer = new writers_1.ObjectWriter(this._options); return writer.serialize(this.node, writerOptions); } else if (writerOptions.format === "json") { const writer = new writers_1.JSONWriter(this._options); return writer.serialize(this.node, writerOptions); } else { throw new Error("Invalid writer format: " + writerOptions.format + ". " + this._debugInfo()); } } /** * Creates a dummy element node without adding it to the list of child nodes. * * Dummy nodes are special nodes representing a node with a `null` value. * Dummy nodes are created while recursively building the XML tree. Simply * skipping `null` values doesn't work because that would break the recursive * chain. * * @returns the new dummy element node */ _dummy() { return new XMLBuilderImpl(this._doc.createElement('dummy_node')); } /** * Extracts a namespace and name from the given string. * * @param namespace - namespace * @param name - a string containing both a name and namespace separated by an * '@' character * @param ele - `true` if this is an element namespace; otherwise `false` */ _extractNamespace(namespace, name, ele) { // extract from name const atIndex = name.indexOf("@"); if (atIndex > 0) { if (namespace === undefined) namespace = name.slice(atIndex + 1); name = name.slice(0, atIndex); } if (namespace === undefined) { // look-up default namespace namespace = (ele ? this._options.defaultNamespace.ele : this._options.defaultNamespace.att); } else if (namespace !== null && namespace[0] === "@") { // look-up namespace aliases const alias = namespace.slice(1); namespace = this._options.namespaceAlias[alias]; if (namespace === undefined) { throw new Error("Namespace alias `" + alias + "` is not defined. " + this._debugInfo()); } } return [namespace, name]; } /** * Returns the document owning this node. */ get _doc() { const node = this.node; if (util_2.Guard.isDocumentNode(node)) { return node; } else { const docNode = node.ownerDocument; /* istanbul ignore next */ if (!docNode) throw new Error("Owner document is null. " + this._debugInfo()); return docNode; } } /** * Returns debug information for this node. * * @param name - node name */ _debugInfo(name) { const node = this.node; const parentNode = node.parentNode; name = name || node.nodeName; const parentName = parentNode ? parentNode.nodeName : ''; if (!parentName) { return "node: <" + name + ">"; } else { return "node: <" + name + ">, parent: <" + parentName + ">"; } } /** * Gets or sets builder options. */ get _options() { const doc = this._doc; /* istanbul ignore next */ if (doc._xmlBuilderOptions === undefined) { throw new Error("Builder options is not set."); } return doc._xmlBuilderOptions; } set _options(value) { const doc = this._doc; doc._xmlBuilderOptions = value; } }
JavaScript
class HeadMountedDisplay { constructor(space){ scope = this; this.name = 'HeadMountedDisplay'; this.space = space; navigator.getVRDisplays() .then( function ( displays ) { if ( displays.length > 0 ) { const display = displays[ 0 ]; space.renderer.vr.setDevice( display ); space.renderer.vr.enabled = true; space.scene.fog.far = _DEFAULT.FOG.FAR; //Important! space.device = scope; log(`[${scope.name}] - Press (Space) + (Enter) to enter VR`, scope.name, true) document.addEventListener('dblclick', (event) => { event.stopPropagation(); event.preventDefault(); display.isPresenting ? display.exitPresent() : display.requestPresent( [ { source: space.renderer.domElement } ] ); }); addEventListener('dblclick', (event) => { event.stopPropagation(); event.preventDefault(); display.isPresenting ? display.exitPresent() : display.requestPresent( [ { source: space.renderer.domElement } ] ); }) document.addEventListener( 'keydown', (event) => { switch ( event.keyCode ) { case 13: //enter keys.enter = true; break; case 27: //escape keys.esc = true; break; case 32: //space keys.space = true; break; } if(keys.enter&&keys.space){ log(`[${scope.name}] - ${!display.isPresenting?'Entered':'Exited'} VR`, scope.name, true) display.isPresenting ? display.exitPresent() : display.requestPresent( [ { source: space.renderer.domElement } ] ); } }, false ); document.addEventListener( 'keyup', (event) => { switch ( event.keyCode ) { case 13: //enter keys.enter = false; break; case 27: //escape keys.esc = false; break; case 32: //space keys.space = false; break; } }, false ); } else { //No VR } } ); function onThumbpadDown0(){ console.log(this.name+' - onThumbpadDown0') } function onThumbpadUp0(){ console.log('onThumbpadUp0') } function onMenuDown0(){ console.log('onMenuDown0') } function onMenuUp0(){ console.log('onMenuUp0') } function onGripsDown0(){ console.log('onGripsDown0') } function onGripsUp0(){ console.log('onGripsUp0') } this.controller1 = new ViveController( 0 ); this.controller1.standingMatrix = scope.space.renderer.vr.getStandingMatrix(); //console.log(scope.space.renderer.vr.getStandingMatrix()) this.controller1.addEventListener( 'triggerdown', scope.onTriggerDown1 ); this.controller1.addEventListener( 'triggerup', scope.onTriggerUp1); this.controller1.addEventListener( 'thumbpaddown', onThumbpadDown0 ); this.controller1.addEventListener( 'thumbpadup', onThumbpadUp0 ); this.controller1.addEventListener( 'menudown', onMenuDown0 ); this.controller1.addEventListener( 'menuup', ()=>{Space.clear({events:false})} ); this.controller1.addEventListener( 'gripsdown', onGripsDown0 ); this.controller1.addEventListener( 'gripsup', onGripsUp0 ); scope.space.scene.add(scope.controller1); this.controller2 = new ViveController( 1 ); this.controller2.standingMatrix = scope.space.renderer.vr.getStandingMatrix(); this.controller2.addEventListener( 'triggerdown', scope.onTriggerDown2 ); this.controller2.addEventListener( 'triggerup', scope.onTriggerUp2); this.controller2.addEventListener( 'thumbpaddown', onThumbpadDown0 ); this.controller2.addEventListener( 'thumbpadup', onThumbpadUp0 ); this.controller2.addEventListener( 'menudown', onMenuDown0 ); this.controller2.addEventListener( 'menuup', ()=>{Space.clear({events:false})} ); this.controller2.addEventListener( 'gripsdown', onGripsDown0 ); this.controller2.addEventListener( 'gripsup', onGripsUp0 ); scope.space.scene.add(scope.controller2); if(config.device.headMountedDisplay.controllerModels){ var loader = new OBJLoader(); loader.setPath( '/static/models/vive-controller/' ); loader.load( 'vr_controller_vive_1_5.obj', function ( object ) { var loader = new TextureLoader(); loader.setPath( '/static/models/vive-controller/' ); var controller = object.children[ 0 ]; controller.material.map = loader.load( 'onepointfive_texture.png' ); controller.material.specularMap = loader.load( 'onepointfive_spec.png' ); controller.castShadow = true; controller.receiveShadow = true; var pivot = new Mesh( new IcosahedronGeometry( 0.01, 2 ) ); pivot.name = 'pivot'; pivot.position.y = -0.016; pivot.position.z = -0.043; pivot.rotation.x = Math.PI / 5.5; controller.add( pivot ); pivot.material = pivot.material.clone(); scope.controller1.add( controller.clone() ); scope.controller2.add( controller.clone() ); }); }else{ var pivot = new Mesh( new SphereGeometry( .025, 2, 2 ), new MeshBasicMaterial({color:0x0000ff}) ); pivot.name = 'pivot'; scope.controller1.add( pivot ); scope.controller2.add( pivot.clone() ); } } onTriggerDown2(controller){ let data = [{ position : new Vector3().setFromMatrixPosition(scope.controller2.matrixWorld) }]; if(scope.controller2) data.push( { position : new Vector3().setFromMatrixPosition(scope.controller1.matrixWorld) } ); if(touchedMeta2){ touchedMeta2.go('touch', data, touchedMeta2); }else{ scope.space.go('touch', data[0], scope.space); } } onTriggerUp2(controller){ let data = [{ position : new Vector3().setFromMatrixPosition(scope.controller2.matrixWorld) }]; if(scope.controller2) data.push( { position : new Vector3().setFromMatrixPosition(scope.controller1.matrixWorld) } ); if(touchedMeta2){ touchedMeta2.go('release', data, touchedMeta2); }else{ scope.space.go('release', data[0], scope.space); } } onTriggerDown1(){ let position = new Vector3().setFromMatrixPosition(scope.controller1.matrixWorld) let data = [{ position: position }]; if(scope.controller2) data.push( { position : new Vector3().setFromMatrixPosition(scope.controller2.matrixWorld) } ); if(touchedMeta1){ touchedMeta1.go('touch', data, touchedMeta1); }else{ scope.space.go('touch', data[0], scope.space); } } onTriggerUp1(mode = true){ let data = [{ position : new Vector3().setFromMatrixPosition(scope.controller1.matrixWorld) }]; if(scope.controller2) data.push( { position : new Vector3().setFromMatrixPosition(scope.controller2.matrixWorld) } ); if(touchedMeta1){ touchedMeta1.go('release', data, touchedMeta1); }else{ scope.space.go('release', data[0], scope.space); } } intersect1(){ scope.space.Meta.forEach((Meta) => { let point = new Vector3().setFromMatrixPosition(scope.controller1.matrixWorld); let box = new Box3().setFromObject(Meta.graphics.mesh); let distance = box.distanceToPoint(point); const data = [{ hand:0, distance: distance, position: point }] if(scope.controller2){ let point = new Vector3().setFromMatrixPosition(scope.controller2.matrixWorld); let box = new Box3().setFromObject(Meta.graphics.mesh); let distance = box.distanceToPoint(point); data.push({ hand:1, distance: distance, position: point }); } if(distance<=0){ touchedMeta1 = Meta; touchedMetaData1 = data; if(!Meta._entered1){ Meta.go('touch', data, Meta) Meta.go('enter', data, Meta) Meta._entered1 = true; } }else{ if(Meta._entered1){ touchedMeta1 = false; touchedMetaData1 = data; Meta.go('leave', data, Meta) Meta._entered1 = false; } } }); } intersect2(){ scope.space.Meta.forEach((Meta) => { let point = new Vector3().setFromMatrixPosition(scope.controller2.matrixWorld); let box = new Box3().setFromObject(Meta.graphics.mesh); let distance = box.distanceToPoint(point); const data = [{ distance: distance, position: point }] if(scope.controller2){ let point = new Vector3().setFromMatrixPosition(scope.controller1.matrixWorld); let box = new Box3().setFromObject(Meta.graphics.mesh); let distance = box.distanceToPoint(point); data.push({ distance: distance, position: point }); } if(distance<=0){ touchedMeta2 = Meta; touchedMetaData2 = data; if(!Meta._entered2){ Meta.go('enter', data, Meta) Meta._entered2= true; } }else{ if(Meta._entered2){ touchedMeta2 = false; touchedMetaData2 = data; Meta.go('leave', data, Meta) Meta._entered2 = false; }; }; }); }; render(){ scope.controller1.update(); scope.controller2.update(); if(scope.controller1) scope.intersect1(); if(scope.controller2) scope.intersect2(); } }
JavaScript
class ChildEventBridge extends PhantomCore { /** * IMPORTANT: This bridge is destructed by the collection itself and does not * need to listen for EVT_DESTROYED from PhantomCollection. * * @param {PhantomCollection} phantomCollection The collection this bridge * should be bound to. */ constructor(phantomCollection) { if (!(phantomCollection instanceof PhantomCollection)) { throw new TypeError( "phantomCollection is not a PhantomCollection instance" ); } super(); /** * @type {PhantomCollection} The parent PhantomCollection. */ this._phantomCollection = phantomCollection; this.registerShutdownHandler(() => delete this._phantomCollection); /** * @type {string[]} The event names this bridge currently (i.e. at any given * time) maintains mappings for events which can emit from child instances * and relay out the parent collection. */ this._bridgeEventNames = [...DEFAULT_BRIDGE_EVENT_NAMES]; /** * FIXME: This type isn't really valid, but describes the structure enough * for human parsing * @type {Object<key: uuid, value: Object: <key: eventName, value: eventHandler>>} */ this._linkedChildEventHandlers = {}; this._handleChildInstanceAdded = this._handleChildInstanceAdded.bind(this); this._handleChildInstanceRemoved = this._handleChildInstanceRemoved.bind(this); // Bind child _...added/removed handlers (() => { // NOTE: Since this instance is bound directly to the PhantomCollection // "off" event handlers aren't added here; they could work but just // aren't needed this._phantomCollection.on( EVT_CHILD_INSTANCE_ADDED, this._handleChildInstanceAdded ); this._phantomCollection.on( EVT_CHILD_INSTANCE_REMOVED, this._handleChildInstanceRemoved ); })(); // Invoked when new proxying event name is added this.on(EVT_BRIDGE_EVENT_NAME_ADDED, eventName => { const children = this.getChildren(); for (const child of children) { this._mapChildEvent(child, eventName); } }); // Invoked when proxying event name is removed this.on(EVT_BRIDGE_EVENT_NAME_REMOVED, eventName => { const children = this.getChildren(); for (const child of children) { this._unmapChildEvent(child, eventName); } }); } /** * @return {Promise<void>} */ async destroy() { // Unbind child _...added/removed handlers (() => { this._phantomCollection.off( EVT_CHILD_INSTANCE_ADDED, this._handleChildInstanceAdded ); this._phantomCollection.off( EVT_CHILD_INSTANCE_REMOVED, this._handleChildInstanceRemoved ); })(); // Unmap all associated bridge event handlers from the children (() => { const children = this.getChildren(); for (const child of children) { for (const eventName of this._bridgeEventNames) { this._unmapChildEvent(child, eventName); } } })(); return super.destroy(); } /** * Retrieves an array of PhantomCore children for the associated * PhantomCollection. * * @return {PhantomCore[]} */ getChildren() { return this._phantomCollection.getChildren(); } /** * Internally invoked when the collection adds a new child. * * @param {PhantomCore} childInstance * @return {void} */ _handleChildInstanceAdded(childInstance) { const childUUID = childInstance.getUUID(); this._linkedChildEventHandlers[childUUID] = {}; // Add linked child event handlers this._bridgeEventNames.forEach(eventName => this._mapChildEvent(childInstance, eventName) ); } /** * Internally invoked when the collection removes a child. * * @param {PhantomCore} childInstance * @return {void} */ _handleChildInstanceRemoved(childInstance) { const childUUID = childInstance.getUUID(); // Clear out linked child event handlers this._bridgeEventNames.forEach(eventName => this._unmapChildEvent(childInstance, eventName) ); delete this._linkedChildEventHandlers[childUUID]; } /** * Adds an event name to a specific child and registers a wrapping event * handler which will proxy out the PhantomCollection when triggered. * * Subsequent attempts to add the same event will be silently ignored. * * @param {PhantomCore} childInstance * @param {string | symbol} eventName * @return {void} */ _mapChildEvent(childInstance, eventName) { const childUUID = childInstance.getUUID(); // Silently ignore previously linked events with same name if (!this._linkedChildEventHandlers[childUUID][eventName]) { // Re-emits the mapped child event data out the parent collection const _handleChildEvent = eventData => { this._phantomCollection.emit(eventName, eventData); }; childInstance.on(eventName, _handleChildEvent); // Keep track of the event handler so it can be removed (via // this._unmapChildEvent) this._linkedChildEventHandlers[childUUID][eventName] = _handleChildEvent; } } /** * Removes the wrapping event handler with the given even name from the * relevant child instance. * * @param {PhantomCore} childInstance * @param {string | symbol} eventName * @return {void} */ _unmapChildEvent(childInstance, eventName) { const childUUID = childInstance.getUUID(); const eventHandler = this._linkedChildEventHandlers[childUUID][eventName]; if (eventHandler) { childInstance.off(eventName, eventHandler); delete this._linkedChildEventHandlers[childUUID][eventName]; } } /** * Adds an event name which will bind to each child and emit out the * PhantomCollection when triggered. * * @param {string | symbol} eventName * @return {void} */ addBridgeEventName(eventName) { const prevLength = this._bridgeEventNames.length; // Add only unique values this._bridgeEventNames = [ ...new Set([...this._bridgeEventNames, eventName]), ]; const nextLength = this._bridgeEventNames.length; if (nextLength > prevLength) { this.emit(EVT_BRIDGE_EVENT_NAME_ADDED, eventName); } } /** * Removes an event name from each child which previously would emit out the * PhantomCollection when triggered. * * @param {string | symbol} eventName * @return {void} */ removeBridgeEventName(eventName) { const prevLength = this._bridgeEventNames.length; this._bridgeEventNames = this._bridgeEventNames.filter( predicate => predicate !== eventName ); const nextLength = this._bridgeEventNames.length; if (nextLength < prevLength) { this.emit(EVT_BRIDGE_EVENT_NAME_REMOVED, eventName); } } /** * Returns the mapped child event names which this class will proxy out the * collection. * * @return {string[] | symbol[]} Can be a mix of strings and symbols. */ getBridgeEventNames() { return this._bridgeEventNames; } }
JavaScript
class Material { // eslint-disable-line no-unused-vars /** * Material constructor * @param {number} mass Entity mass * @param {number} elasticity Coefficient of restitution * @param {number} mu Coefficient of friction */ constructor(mass, elasticity, mu) { /** * Entity mass * @type {number} */ this.mass = mass; /** * Coefficient of restitution * @type {number} */ this.e = elasticity; /** * Coefficient of friction * @type {number} */ this.mu = mu; } }
JavaScript
class NetworkSettings extends models['BaseModel'] { /** * Create a NetworkSettings. * @member {object} dnsSettings The DNS (Domain Name System) settings of * device. * @member {string} [dnsSettings.primaryDnsServer] The primary IPv4 DNS * server for the device * @member {string} [dnsSettings.primaryIpv6DnsServer] The primary IPv6 DNS * server for the device * @member {array} [dnsSettings.secondaryDnsServers] The secondary IPv4 DNS * server for the device * @member {array} [dnsSettings.secondaryIpv6DnsServers] The secondary IPv6 * DNS server for the device * @member {object} networkAdapters The network adapter list of device. * @member {array} [networkAdapters.value] The value. * @member {object} webproxySettings The webproxy settings of device. * @member {string} [webproxySettings.connectionUri] The connection URI. * @member {string} [webproxySettings.authentication] The authentication * type. Possible values include: 'Invalid', 'None', 'Basic', 'NTLM' * @member {string} [webproxySettings.username] The webproxy username. */ constructor() { super(); } /** * Defines the metadata of NetworkSettings * * @returns {object} metadata of NetworkSettings * */ mapper() { return { required: false, serializedName: 'NetworkSettings', type: { name: 'Composite', className: 'NetworkSettings', 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' } }, kind: { required: false, serializedName: 'kind', type: { name: 'Enum', allowedValues: [ 'Series8000' ] } }, dnsSettings: { required: true, serializedName: 'properties.dnsSettings', type: { name: 'Composite', className: 'DNSSettings' } }, networkAdapters: { required: true, serializedName: 'properties.networkAdapters', type: { name: 'Composite', className: 'NetworkAdapterList' } }, webproxySettings: { required: true, serializedName: 'properties.webproxySettings', type: { name: 'Composite', className: 'WebproxySettings' } } } } }; } }
JavaScript
class ProfilePagePastTour extends React.Component { constructor() { super(); this.state = { tourNUM: null, currentTour: 0, currentImg: logo1, isOpen: false, curr: null, id: 0, explicitTour: null, }; } async componentDidMount() { try { const response = await api.get('/pastTours/'+localStorage.getItem("tourID")); this.setState({explicitTour: response.data}) this.setState({tourNUM: parseFloat(localStorage.getItem("tourID"))}); //localStorage.removeItem("tourID"); // This is just some data for you to see what is available. // Feel free to remove it. console.log('request to:', this.state.explicitTour); // See here to get more data. console.log(response); } catch (error) { alert(`Something went wrong while fetching the users: \n${handleError(error)}`); } } toggleState = (clickedTour, clickedImage) => { this.setState({ isOpen: !this.state.isOpen, currentTour: clickedTour, currentImg: clickedImage, curr: this.state.tourList[clickedTour], }); } back() { localStorage.removeItem("tourID"); this.props.history.push('/pastTours'); } render() { const exTour = this.state.explicitTour; let info; let tourName; let picId if (exTour != null){ info = <PastTourInformationSmall Tour={this.state.explicitTour}/> tourName = info.props.Tour.name picId = info.props.Tour.tourPictureKey } else{ info = <div></div> } return <ParallaxProvider> <style>{'body { background-color: grey; }'}</style> <Background></Background> <FormContainer>Tour: {tourName}</FormContainer> <ButtonContainer2><Button width="100%" onClick={() => { this.back(); }}>Back</Button></ButtonContainer2> <ButtonContainer> <Button width="100%" onClick={() => { this.props.history.push('/chat'); }}>Go to Chat</Button> </ButtonContainer> <Form> <TourContainer> <Image cloudName="sopra-group-7" publicID= {picId} width='200px' height='200px' /> {info} </TourContainer> </Form> <br></br> {/* <Review></Review> */} <br></br> </ParallaxProvider> } }
JavaScript
class GalleryItem extends React.Component { constructor(props) { super(props); this.state = { item: props.item, isVideo: props.item.type === "video", dialogOpen: false }; this.imageClicked = this.imageClicked.bind(this); this.dialogClose = this.dialogClose.bind(this); } imageClicked() { this.setState({ dialogOpen: true }); } dialogClose() { this.setState({ dialogOpen: false }); } getDateString() { var date = new Date(this.state.item.takenAt * 1000); var string = date.toLocaleDateString() + " " + date.toLocaleTimeString(); return string; } // https://stackoverflow.com/a/20732091/5028730 humanFileSize(size) { var i = Math.floor( Math.log(size) / Math.log(1024) ); return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i]; }; render() { // Decide whether to show a video or an image element let viewElement; let viewElementBig; const previewURL = getBackendURL() + "/thumbnail?id=" + this.state.item.id; const fullURL = getBackendURL() + "/file?id=" + this.state.item.id; if (this.state.isVideo) { viewElement = <video src={fullURL} controls preload={"none"} poster={previewURL}></video> viewElementBig = <video src={fullURL} controls preload={"none"} className={"gallery-content-big"} poster={previewURL}></video>; } else { viewElement = <img src={previewURL} alt=""></img> viewElementBig = <a href={fullURL} target="_blank" rel="noreferrer"><img src={fullURL} className={"gallery-content-big"} alt=""></img></a>; } return ( <Grid item xs={isSM ? 12 : 4}> <Paper onClick={this.imageClicked} elevation={2} className={"grid-cell"}> {viewElement} </Paper> <Dialog fullScreen={isSM} open={this.state.dialogOpen} onClose={this.dialogClose} aria-labelledby="responsive-dialog-title"> <DialogContent> {viewElementBig} <div className={"gallery-content-bar"}> <a download={this.state.item.fileName} href={fullURL}><Button color="primary"><i className={"fas fa-download"}></i> Download</Button></a> </div> <TableContainer> <Table> <TableBody> <TableRow> <TableCell><b>Type</b></TableCell> <TableCell align="right">{this.state.item.type === "video" ? "Video" : "Screenshot"}</TableCell> </TableRow> <TableRow> <TableCell><b>Taken at</b></TableCell> <TableCell align="right">{this.getDateString()}</TableCell> </TableRow> <TableRow> <TableCell><b>Game</b></TableCell> <TableCell align="right">{this.state.item.game}</TableCell> </TableRow> <TableRow> <TableCell><b>Stored at</b></TableCell> <TableCell align="right">{this.state.item.storedAt === "sd" ? "SD Card" : "Internal Storage"}</TableCell> </TableRow> <TableRow> <TableCell><b>Size</b></TableCell> <TableCell align="right">{this.humanFileSize(this.state.item.fileSize)}</TableCell> </TableRow> </TableBody> </Table> </TableContainer> </DialogContent> <DialogActions> <Button color="primary" onClick={this.dialogClose}>Close</Button> </DialogActions> </Dialog> </Grid> ); } }
JavaScript
class App extends React.Component { constructor(props) { super(props); this.state = { galleryContent: [], currentPage: 1, maxPages: 1, currentTheme: "light", stats: { numScreenshots: 0, numVideos: 0, indexTime: 0 }, error: false }; } componentDidMount() { // Fetch the gallery directly at the beginning this.fetchGallery(); } fetchGallery() { fetch(getBackendURL() + "/gallery?page=" + this.state.currentPage) .then(res => res.json()) .then((result) => { this.setState({ galleryContent: result.gallery, maxPages: result.pages, currentTheme: result.theme, stats: result.stats, error: false }) }, (error) => { this.setState({ error: true }); }); } onPageChange(e, page) { this.setState({ currentPage: page }, () => { this.fetchGallery(); }); } render() { return ( <ThemeProvider theme={this.state.currentTheme === "light" ? lightTheme : darkTheme}> <CssBaseline/> <Container style={{flexGrow: 1, padding: "8px"}}> <Typography variant="h2" color="textPrimary" align="center">NXGallery<a href={"https://github.com/iUltimateLP/NXGallery"} target={"_blank"} rel={"noreferrer"}><i className={`fab fa-github ${this.state.currentTheme}`}></i></a></Typography> <Typography variant="h6" color="textSecondary" align="center" style={{paddingBottom: "16px", fontWeight: "100"}}>Indexed {this.state.stats.numScreenshots} photos and {this.state.stats.numVideos} videos in {this.state.stats.indexTime.toPrecision(3)} seconds.</Typography> <Grid container spacing={2} justifyContent="center"> {this.state.galleryContent.map((value) => ( <GalleryItem key={value.takenAt} item={value}/> ))} </Grid> {this.state.error && <Typography variant="h6" color="error" align="center">Oh no, an error has occured :(</Typography> } {(this.state.galleryContent.length === 0 && !this.state.error) && <Container align="center" style={{paddingTop: "20px"}}> <CircularProgress color="primary"></CircularProgress> </Container> } {(this.state.galleryContent.length > 0 && !this.state.error) && <Container align="center" style={{paddingTop: "20px", paddingBottom: "12px"}}> <Pagination count={this.state.maxPages} className={"pagination"} onChange={(e, page) => this.onPageChange(e, page)}/> </Container> } <Container align="center" className={"footer"}> <Typography variant="overline" color="textSecondary" align="center">Made with</Typography> <Icon className={"heart"}>favorite</Icon> <Typography variant="overline" color="textSecondary" align="center">in Bremen, Germany</Typography><br/> </Container> </Container> </ThemeProvider> ); } }
JavaScript
class I18n extends React.Component { constructor(props) { super(props) this._polyglot = new Polyglot({ locale: props.locale, phrases: props.messages, }) } componentWillReceiveProps(newProps) { if (newProps.locale !== this.props.locale) { this._polyglot.locale(newProps.locale) } if (newProps.messages !== this.props.messages) { this._polyglot.replace(newProps.messages) } } render() { const { children } = this.props return ( <I18nContext.Provider value={this._polyglot.t.bind(this._polyglot)}> {React.Children.only(children)} </I18nContext.Provider> ) } }
JavaScript
class Game { // the gamepad is passed to the contructor constructor(gui, gamepad) { // link the game gamepad.setGame(this, this.manageRequest) // set the gamepad and the gui this.gamepad = gamepad this.gui = gui } /* --- Game handlers --- */ // all the requests are passed to this function manageRequest(request, back, old) { let result, promise // if a method is called and the request is not old the game is updated // // using the 'magicJson' options the json need to be changed only the first // time the request is passed to this function // // if the request is old the json will be automatically updated before the request is passed // to this function // // infact, in the methods's handlers below, the 'back' argument is not passed // and there's no code to remove the changes of the json on back requests if (['PATH', 'REPEAT', 'TURN', 'MOVE'].includes(request.method) && !old) // update the game result = this[request.method].apply(this, [].concat(request.args, request)) // check the game status this.checkGameStatus(request, back, old) // update the gui promise = this.gui.manageRequest(request, back) // you can return a promise return promise.then(() => result) } // load a level loadLevel(level) { // update maxBlocks setting if ('maxBlocks' in level) // if the start block is used add 1 Blockly.getMainWorkspace().options.maxBlocks = level.maxBlocks + (start ? 1 : 0) else // no max Blockly.getMainWorkspace().options.maxBlocks = Infinity // update the toolbox if ('blocks' in level) // load some blocks/categories from the xml this.gamepad.setToolbox({ blocks: level.blocks }) else // load all the blocks/categories from the xml this.gamepad.setToolbox({ all: true }) // update the magicJson this.gamepad.level = level.game // set the id this.id = level.id // load the gui this.gui.load(this.id) // reset the workspace and kill the requests of the previous game if it wasn't finished this.gamepad.reset() // restore the old code from the localStorage this.gamepad.restore('' + this.id + start) } // load the code loadCode() { // load the code, the json is resetted this.gamepad.load() // save the code in localStorage this.gamepad.save('' + this.id + start) // reset the gui this.gui.load() // load first 'START' request this.gamepad.forward() } /* --- Game utils --- */ // check the game status checkGameStatus(request, back, old) { let pegman = this.gamepad.level.pegman, marker = this.gamepad.level.marker // if the game is finished show win/lose alert if (request.method == Blockly.Gamepad['STATES']['FINISHED'] && !back) { if (pegman.x == marker.x && pegman.y == marker.y) alert('you won!') else alert('you lost!') } // log the request and the pegman // the pegman is parsed to look better in the console because gamepad.level is not a normal object (see documentation) console.group() console.info('request: ', request) console.info('request type: ', back ? 'backward' : 'forward') console.info('request age: ', old ? 'old' : 'new') console.info('\n') console.info('pegman: ', JSON.parse(JSON.stringify(pegman))) console.groupEnd() } // get the { x, y } offset of the next position // from a given direction getNextPosition(direction) { // the direction is one of these inputs // // Blockly.Gamepad['INPUTS'] = { // 'FORWARD': '0', // 'RIGHT': '1', // 'BACKWARD': '2', // 'LEFT': '3' // } return [{ // UP x: 0, y: 1 }, { // RIGHT x: 1, y: 0 }, { // DOWN x: 0, y: -1 }, { // LEFT x: -1, y: 0 } ][direction] } // check if the pegman can update its position // from the given offset canMove(path, pegman, position) { let x = pegman.x + position.x, y = pegman.y + position.y // check if the path exist return path.find(element => element[0] == x && element[1] == y) != undefined } /* --- Game methods --- */ // // with the 'magicJson' options these methods will be called only if the // request is not old // // infact in these methods there's no code to change the json on back requests // because it will be automatically updated on all the old requests // 'repeat until' method REPEAT() { let pegman = this.gamepad.level.pegman, marker = this.gamepad.level.marker // the return: value // if true the cycle continues, otherwise it stops // while ( value ) {...} return { return: pegman.x != marker.x || pegman.y != marker.y } } // 'if path' methods PATH(direction) { let path = this.gamepad.level.path, pegman = this.gamepad.level.pegman, // because of the directions's values range from 0 to 3 // it's possible to use the direction as an offset and then use the modulus // (direction is a string so it's parsed) // // Blockly.Gamepad['INPUTS'] = { // 'FORWARD': '0', // 'RIGHT': '1', // 'BACKWARD': '2', // 'LEFT': '3' //} position = this.getNextPosition((pegman.direction + direction) % 4) // the return: value // if ( value ) {...} else {...} return { return: this.canMove(path, pegman, position) } } // 'move forward' method MOVE(request) { let path = this.gamepad.level.path, pegman = this.gamepad.level.pegman, position = this.getNextPosition(pegman.direction), canMove = this.canMove(path, pegman, position) // if the pegman can move the position is updated if (canMove) { pegman.x += position.x pegman.y += position.y } // decorate the request with some data // this data will be used in the gui request.data = [ // if the pegman has moved canMove, // the direction of the pegman pegman.direction ] } // 'turn' method TURN(direction, request) { // because of the directions's values range from 0 to 3 // it's possible to increment the value and then use the modulus // // Blockly.Gamepad['INPUTS'] = { // 'FORWARD': '0', // 'RIGHT': '1', // 'BACKWARD': '2', // 'LEFT': '3' // } this.gamepad.level.pegman.direction += direction this.gamepad.level.pegman.direction %= 4 // decorate the request with some data // the data will be used in the gui request.data = [ // if the rotation is in a clockwise direction direction == Blockly.Gamepad['INPUTS']['RIGHT'] ] } }
JavaScript
class BaseState { /** * Returns timeline tracks collection. * * @type {TrackCollection} */ constructor(timeline) { /** * A reference to the timeline on which the state should be installed. * @type {Timeline} */ this.timeline = timeline; } /** * Returns timeline tracks collection. * * @type {TrackCollection<Track>} */ get tracks() { return this.timeline.tracks; } /** * Returns all registered layers. * * @type {Array<Layer>} */ get layers() { return this.timeline.tracks.layers; } /** * Called when the timeline is entering the state. */ enter() {} /** * Called when the timeline is leaving the state. */ exit() {} /** * Main interface method to override when creating a new `State`. Handle event * from mouse or keyboard, should define behavior according to the event * (aka. mousedown, mouseup, ...). * * @param {WaveEvent} e - the event to process. * @param {Array} hitLayers - the layers hit by the mouse event (if surface * event). */ handleEvent(e, hitLayers) {} }
JavaScript
class AutoCompleteComboBox extends Base { get defaultState() { return Object.assign(super.defaultState, { inputRole: AutoCompleteInput }); } [symbols.render](/** @type {PlainObject} */ changed) { super[symbols.render](changed); if (changed.texts) { if ('texts' in this.$.input) { /** @type {any} */ (this.$.input).texts = this.state.texts; } } } }
JavaScript
class DbbrainClient extends AbstractClient { constructor(credential, region, profile) { super("dbbrain.tencentcloudapi.com", "2021-05-27", credential, region, profile); } /** * This API is used to query the download link of a security audit log export file. Currently, log file download only provides a Tencent Cloud private network address. Please download it by using a CVM instance in the Guangzhou region. * @param {DescribeSecurityAuditLogDownloadUrlsRequest} req * @param {function(string, DescribeSecurityAuditLogDownloadUrlsResponse):void} cb * @public */ DescribeSecurityAuditLogDownloadUrls(req, cb) { let resp = new DescribeSecurityAuditLogDownloadUrlsResponse(); this.request("DescribeSecurityAuditLogDownloadUrls", req, resp, cb); } /** * This API is used to get the email sending configuration, including the email configuration for database inspection and the email sending configuration for scheduled task health reports. * @param {DescribeMailProfileRequest} req * @param {function(string, DescribeMailProfileResponse):void} cb * @public */ DescribeMailProfile(req, cb) { let resp = new DescribeMailProfileResponse(); this.request("DescribeMailProfile", req, resp, cb); } /** * This API is used to create the regular generation time of health reports and the regular email sending configuration. Please pass in the regular generation time of health reports as a parameter (Monday to Sunday) to set the regular generation time, and save the corresponding regular email sending configuration. * @param {CreateSchedulerMailProfileRequest} req * @param {function(string, CreateSchedulerMailProfileResponse):void} cb * @public */ CreateSchedulerMailProfile(req, cb) { let resp = new CreateSchedulerMailProfileResponse(); this.request("CreateSchedulerMailProfile", req, resp, cb); } /** * This API is used to get the real-time space statistics of top databases of an instance. The returned results are sorted by size by default. * @param {DescribeTopSpaceSchemasRequest} req * @param {function(string, DescribeTopSpaceSchemasResponse):void} cb * @public */ DescribeTopSpaceSchemas(req, cb) { let resp = new DescribeTopSpaceSchemasResponse(); this.request("DescribeTopSpaceSchemas", req, resp, cb); } /** * This API is used to query the real-time thread list of a relational database. * @param {DescribeMySqlProcessListRequest} req * @param {function(string, DescribeMySqlProcessListResponse):void} cb * @public */ DescribeMySqlProcessList(req, cb) { let resp = new DescribeMySqlProcessListResponse(); this.request("DescribeMySqlProcessList", req, resp, cb); } /** * This API is used to query the list of health report generation tasks. * @param {DescribeDBDiagReportTasksRequest} req * @param {function(string, DescribeDBDiagReportTasksResponse):void} cb * @public */ DescribeDBDiagReportTasks(req, cb) { let resp = new DescribeDBDiagReportTasksResponse(); this.request("DescribeDBDiagReportTasks", req, resp, cb); } /** * This API is used to get the information of the contact group in the email. * @param {DescribeAllUserGroupRequest} req * @param {function(string, DescribeAllUserGroupResponse):void} cb * @public */ DescribeAllUserGroup(req, cb) { let resp = new DescribeAllUserGroupResponse(); this.request("DescribeAllUserGroup", req, resp, cb); } /** * This API is used to get the slow log statistics histogram. * @param {DescribeSlowLogTimeSeriesStatsRequest} req * @param {function(string, DescribeSlowLogTimeSeriesStatsResponse):void} cb * @public */ DescribeSlowLogTimeSeriesStats(req, cb) { let resp = new DescribeSlowLogTimeSeriesStatsResponse(); this.request("DescribeSlowLogTimeSeriesStats", req, resp, cb); } /** * This API is used to get the statistical distribution chart of slow log source addresses. * @param {DescribeSlowLogUserHostStatsRequest} req * @param {function(string, DescribeSlowLogUserHostStatsResponse):void} cb * @public */ DescribeSlowLogUserHostStats(req, cb) { let resp = new DescribeSlowLogUserHostStatsResponse(); this.request("DescribeSlowLogUserHostStats", req, resp, cb); } /** * This API is used to get the real-time space statistics of top tables of an instance. The returned results are sorted by size by default. * @param {DescribeTopSpaceTablesRequest} req * @param {function(string, DescribeTopSpaceTablesResponse):void} cb * @public */ DescribeTopSpaceTables(req, cb) { let resp = new DescribeTopSpaceTablesResponse(); this.request("DescribeTopSpaceTables", req, resp, cb); } /** * This API is used to query the overview of instance space usage during a specified time period, including disk usage growth (MB), available disk space (MB), total disk space (MB), and estimated number of available days. * @param {DescribeDBSpaceStatusRequest} req * @param {function(string, DescribeDBSpaceStatusResponse):void} cb * @public */ DescribeDBSpaceStatus(req, cb) { let resp = new DescribeDBSpaceStatusResponse(); this.request("DescribeDBSpaceStatus", req, resp, cb); } /** * This API is used to create the email configuration. The input parameter `ProfileType` represents the type of the email configuration. Valid values: `dbScan_mail_configuration` (email configuration of database inspection report) and `scheduler_mail_configuration` (email sending configuration of scheduled task health report). Please always select Guangzhou for `Region`, regardless of the region where the instance resides. * @param {CreateMailProfileRequest} req * @param {function(string, CreateMailProfileResponse):void} cb * @public */ CreateMailProfile(req, cb) { let resp = new CreateMailProfileResponse(); this.request("CreateMailProfile", req, resp, cb); } /** * This API is used to get the health score and deduction for exceptions in the specified time period (30 minutes) based on the instance ID. * @param {DescribeHealthScoreRequest} req * @param {function(string, DescribeHealthScoreResponse):void} cb * @public */ DescribeHealthScore(req, cb) { let resp = new DescribeHealthScoreResponse(); this.request("DescribeHealthScore", req, resp, cb); } /** * This API is used to create a security audit log export task. * @param {CreateSecurityAuditLogExportTaskRequest} req * @param {function(string, CreateSecurityAuditLogExportTaskResponse):void} cb * @public */ CreateSecurityAuditLogExportTask(req, cb) { let resp = new CreateSecurityAuditLogExportTaskResponse(); this.request("CreateSecurityAuditLogExportTask", req, resp, cb); } /** * This API is used to delete a security audit log export task. * @param {DeleteSecurityAuditLogExportTasksRequest} req * @param {function(string, DeleteSecurityAuditLogExportTasksResponse):void} cb * @public */ DeleteSecurityAuditLogExportTasks(req, cb) { let resp = new DeleteSecurityAuditLogExportTasksResponse(); this.request("DeleteSecurityAuditLogExportTasks", req, resp, cb); } /** * This API is used to get and sort the top slow SQL statements in a specified time period by the aggregation mode of SQL template plus schema. * @param {DescribeSlowLogTopSqlsRequest} req * @param {function(string, DescribeSlowLogTopSqlsResponse):void} cb * @public */ DescribeSlowLogTopSqls(req, cb) { let resp = new DescribeSlowLogTopSqlsResponse(); this.request("DescribeSlowLogTopSqls", req, resp, cb); } /** * This API is used to query the list of security audit log export tasks. * @param {DescribeSecurityAuditLogExportTasksRequest} req * @param {function(string, DescribeSecurityAuditLogExportTasksResponse):void} cb * @public */ DescribeSecurityAuditLogExportTasks(req, cb) { let resp = new DescribeSecurityAuditLogExportTasksResponse(); this.request("DescribeSecurityAuditLogExportTasks", req, resp, cb); } /** * This API is used to get the information of the contact in the email. * @param {DescribeAllUserContactRequest} req * @param {function(string, DescribeAllUserContactResponse):void} cb * @public */ DescribeAllUserContact(req, cb) { let resp = new DescribeAllUserContactResponse(); this.request("DescribeAllUserContact", req, resp, cb); } /** * This API is used to get the details of an instance exception diagnosis event. * @param {DescribeDBDiagEventRequest} req * @param {function(string, DescribeDBDiagEventResponse):void} cb * @public */ DescribeDBDiagEvent(req, cb) { let resp = new DescribeDBDiagEventResponse(); this.request("DescribeDBDiagEvent", req, resp, cb); } /** * This API is used to get the list of instance diagnosis events. * @param {DescribeDBDiagHistoryRequest} req * @param {function(string, DescribeDBDiagHistoryResponse):void} cb * @public */ DescribeDBDiagHistory(req, cb) { let resp = new DescribeDBDiagHistoryResponse(); this.request("DescribeDBDiagHistory", req, resp, cb); } /** * This API is used to create a health report and send it via email as configured. * @param {CreateDBDiagReportTaskRequest} req * @param {function(string, CreateDBDiagReportTaskResponse):void} cb * @public */ CreateDBDiagReportTask(req, cb) { let resp = new CreateDBDiagReportTaskResponse(); this.request("CreateDBDiagReportTask", req, resp, cb); } /** * This API is used to get the instance information list. Please always select Guangzhou for `Region`. * @param {DescribeDiagDBInstancesRequest} req * @param {function(string, DescribeDiagDBInstancesResponse):void} cb * @public */ DescribeDiagDBInstances(req, cb) { let resp = new DescribeDiagDBInstancesResponse(); this.request("DescribeDiagDBInstances", req, resp, cb); } /** * This API is used to add the recipient name and email. The returned value is the ID of the successfully added recipient. * @param {AddUserContactRequest} req * @param {function(string, AddUserContactResponse):void} cb * @public */ AddUserContact(req, cb) { let resp = new AddUserContactResponse(); this.request("AddUserContact", req, resp, cb); } /** * This API is used to get the daily space data of top databases consuming the most instance space. The data is daily collected by DBbrain during a specified time period. The returned results are sorted by size by default. * @param {DescribeTopSpaceSchemaTimeSeriesRequest} req * @param {function(string, DescribeTopSpaceSchemaTimeSeriesResponse):void} cb * @public */ DescribeTopSpaceSchemaTimeSeries(req, cb) { let resp = new DescribeTopSpaceSchemaTimeSeriesResponse(); this.request("DescribeTopSpaceSchemaTimeSeries", req, resp, cb); } /** * This API is used to get SQL statement optimization suggestions. * @param {DescribeUserSqlAdviceRequest} req * @param {function(string, DescribeUserSqlAdviceResponse):void} cb * @public */ DescribeUserSqlAdvice(req, cb) { let resp = new DescribeUserSqlAdviceResponse(); this.request("DescribeUserSqlAdvice", req, resp, cb); } /** * This API is used to get the daily space data of top tables consuming the most instance space. The data is daily collected by DBbrain during a specified time period. The returned results are sorted by size by default. * @param {DescribeTopSpaceTableTimeSeriesRequest} req * @param {function(string, DescribeTopSpaceTableTimeSeriesResponse):void} cb * @public */ DescribeTopSpaceTableTimeSeries(req, cb) { let resp = new DescribeTopSpaceTableTimeSeriesResponse(); this.request("DescribeTopSpaceTableTimeSeries", req, resp, cb); } /** * This API is used to enable/disable instance inspection. * @param {ModifyDiagDBInstanceConfRequest} req * @param {function(string, ModifyDiagDBInstanceConfResponse):void} cb * @public */ ModifyDiagDBInstanceConf(req, cb) { let resp = new ModifyDiagDBInstanceConfResponse(); this.request("ModifyDiagDBInstanceConf", req, resp, cb); } /** * This API is used to interrupt the current session according to the session ID. It needs to be called twice to commit the session interruption task in two stages. In the pre-commit stage, the stage value is `Prepare`, and the returned value is `SqlExecId’. In the commit stage, the stage value is `Commit`, and `SqlExecId` will be passed in as a parameter. Then the session process will be terminated. * @param {KillMySqlThreadsRequest} req * @param {function(string, KillMySqlThreadsResponse):void} cb * @public */ KillMySqlThreads(req, cb) { let resp = new KillMySqlThreadsResponse(); this.request("KillMySqlThreads", req, resp, cb); } /** * This API is used to create a URL for a health report. * @param {CreateDBDiagReportUrlRequest} req * @param {function(string, CreateDBDiagReportUrlResponse):void} cb * @public */ CreateDBDiagReportUrl(req, cb) { let resp = new CreateDBDiagReportUrlResponse(); this.request("CreateDBDiagReportUrl", req, resp, cb); } }
JavaScript
class TweenBase { constructor(targetElement, startObject, endObject, opsObject) { // element animation is applied to this.element = targetElement; this.playing = false; this._startTime = null; this._startFired = false; this.valuesEnd = endObject; // valuesEnd this.valuesStart = startObject; // valuesStart // OPTIONS const options = opsObject || {}; // internal option to process inline/computed style at start instead of init // used by to() method and expects object : {} / false this._resetStart = options.resetStart || 0; // you can only set a core easing function as default this._easing = typeof (options.easing) === 'function' ? options.easing : connect.processEasing(options.easing); this._duration = options.duration || defaultOptions.duration; // duration option | default this._delay = options.delay || defaultOptions.delay; // delay option | default // set other options Object.keys(options).forEach((op) => { const internalOption = `_${op}`; if (!(internalOption in this)) this[internalOption] = options[op]; }); // callbacks should not be set as undefined // this._onStart = options.onStart // this._onUpdate = options.onUpdate // this._onStop = options.onStop // this._onComplete = options.onComplete // queue the easing const easingFnName = this._easing.name; if (!onStart[easingFnName]) { onStart[easingFnName] = function easingFn(prop) { if (!KUTE[prop] && prop === this._easing.name) KUTE[prop] = this._easing; }; } return this; } // tween prototype // queue tween object to main frame update // move functions that use the ticker outside the prototype to be in the same scope with it start(time) { // now it's a good time to start add(this); this.playing = true; this._startTime = typeof time !== 'undefined' ? time : KUTE.Time(); this._startTime += this._delay; if (!this._startFired) { if (this._onStart) { this._onStart.call(this); } queueStart.call(this); this._startFired = true; } if (!Tick) Ticker(); return this; } stop() { if (this.playing) { remove(this); this.playing = false; if (this._onStop) { this._onStop.call(this); } this.close(); } return this; } close() { // scroll|transformMatrix need this Object.keys(onComplete).forEach((component) => { Object.keys(onComplete[component]).forEach((toClose) => { onComplete[component][toClose].call(this, toClose); }); }); // when all animations are finished, stop ticking after ~3 frames this._startFired = false; stop.call(this); } chain(args) { this._chain = []; this._chain = args.length ? args : this._chain.concat(args); return this; } stopChainedTweens() { if (this._chain && this._chain.length) this._chain.forEach((tw) => tw.stop()); } update(time) { const T = time !== undefined ? time : KUTE.Time(); let elapsed; if (T < this._startTime && this.playing) { return true; } elapsed = (T - this._startTime) / this._duration; elapsed = (this._duration === 0 || elapsed > 1) ? 1 : elapsed; // calculate progress const progress = this._easing(elapsed); // render the update Object.keys(this.valuesEnd).forEach((tweenProp) => { KUTE[tweenProp](this.element, this.valuesStart[tweenProp], this.valuesEnd[tweenProp], progress); }); // fire the updateCallback if (this._onUpdate) { this._onUpdate.call(this); } if (elapsed === 1) { // fire the complete callback if (this._onComplete) { this._onComplete.call(this); } // now we're sure no animation is running this.playing = false; // stop ticking when finished this.close(); // start animating chained tweens if (this._chain !== undefined && this._chain.length) { this._chain.map((tw) => tw.start()); } return false; } return true; } }
JavaScript
class Fragment { constructor (fragments) { this.expect = chai.expect this[ELEMENTS] = new Map() this[FRAGMENTS] = fragments && Array.isArray(fragments) ? fragments : null } /** * Gets the HTML element(s) referenced by the selector passed. * @param {string} selector - The CSS selector associated with the HTML element(s). * @returns {Object} The associated HTML element(s). */ getElement (selector) { if (!selector || typeof selector !== 'string') throw new TypeError('getElement(selector): selector must be a populated String') const el = this[ELEMENTS].get(selector) if (!el) throw new ReferenceError('getElement(selector): element is undefined') return el } /** * Sets the HTML element(s) referenced by the selector passed. * @param {string} selector - The CSS selector associated with the HTML element(s). * @param {boolean} [all=false] - The optional parameter to specify whether to select all matching HTML elements. * @returns {Object} The associated HTML element(s). */ setElement (selector, all = false) { if (!selector || typeof selector !== 'string') throw new TypeError('setElement(selector): selector must be a populated String') const el = all ? $$(selector) : $(selector) this[ELEMENTS].set(selector, el) return el } /** * [`async`] Test method that provides the minimal test pass capabilities, which are calling `testElements` on all of its associated Fragments and checking if all of its associated HTML elements exist. This should be overridden by classes extending Fragment to define the desired tests on your Fragment. * @returns {Promise} The results of the `testExists` method. */ async testElements () { if (this[FRAGMENTS]) { await Promise.all(this[FRAGMENTS].map((fragment) => fragment.testElements())) } return this.testExists() } /** * [`async`] Test method that checks for the existence of all the HTML elements associated with the Fragment. * @returns {Promise} The results of all the `isPresent` assertions on HTML elements. */ async testExists () { return Promise.all(Array.from(this[ELEMENTS], ([selector, element]) => { return this.expect(element.isPresent()).to.eventually.be.true() })) } /** * [`async`] Test method that tests the text value of an associated HTML element. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @param {string} text - The text to test the HTML element's content against. * @returns {Promise} The results of the test text assertion. */ async testText (selector, text) { if (!text || typeof text !== 'string') throw new TypeError('testText(selector, text): text must be a populated String') return this.expect(this.getElement(selector).getText()).to.eventually.equal(text) } /** * [`async`] Test method that tests the state of an associated HTML element. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @param {string|Array<string>} state - The desired states you wish to test. Currently, the supported states are: `displayed`, `enabled`, and `selected`. * @returns {Promise} The results of the test state assertion(s). */ async testState (selector, state) { if (!state || !state.length) throw new TypeError('testState(selector, state): state must be a populated String|Array') if (typeof state === 'string' && STATE_HASH[state]) { return this.expect(this.getElement(selector)[STATE_HASH[state]]()).to.eventually.be.true() } return Promise.all(state.map(value => this.testState(selector, value))) } /** * [`async`] Test method that tests the desired attribute of an associated HTML element. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @param {string} attribute - The desired HTML attribute you want to test. * @param {string} text - The expected text to test against the HTML attribute. * @returns {Promise} The results of the test attribute assertion. */ async testAttribute (selector, attribute, text) { if (!attribute || typeof attribute !== 'string') throw new TypeError('testAttribute(selector, attribute, text): attribute must be a populated String') if (!text || typeof text !== 'string') throw new TypeError('testAttribute(selector, attribute, text): text must be a populated String') return this.expect(this.getElement(selector).getAttribute(attribute)).to.eventually.equal(text) } /** * [`async`] Action method used to clear the any value set on an associated HTML element. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @returns {Promise} The results of the `clear` method on the element. */ async elementClear (selector) { return this.getElement(selector).clear() } /** * [`async`] Action method used to simulate a click on an associated HTML element. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @returns {Promise} The results of the `click` method on the element. */ async elementClick (selector) { return this.getElement(selector).click() } /** * [`async`] Action method used to simulate keyboard user input on an associated HTML element. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @param {string|Array<string>} keys - The <a href="https://www.protractortest.org/#/api?view=webdriver.WebElement.prototype.sendKeys">keys</a> you wish to simulate. * @returns {Promise} The results of the `sendKeys` method on the element. */ async elementSendKeys (selector, keys) { if (!keys || !keys.length) throw new TypeError('elementSendKeys(selector, keys): keys must be a populated String|Array') const el = this.getElement(selector) return Array.isArray(keys) ? el.sendKeys(...keys) : el.sendKeys(keys) } /** * [`async`] Action method used to simulate submitting an associated HTML form. * @param {string} selector - The CSS selector associated with the desired HTML element to test. * @returns {Promise} The results of the `submit` method on the element. */ async elementSubmit (selector) { return this.getElement(selector).submit() } }