language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class FileSystemView extends OkitArtefactView { constructor(artefact=null, json_view) { if (!json_view.file_systems) json_view.file_systems = []; super(artefact, json_view); } get parent_id() {return this.artefact.compartment_id;} get parent() {return this.getJsonView().getCompartment(this.parent_id);} /* ** SVG Processing */ /* ** Property Sheet Load function */ loadProperties() { const self = this; $(jqId(PROPERTIES_PANEL)).load("propertysheets/file_system.html", () => {loadPropertiesSheet(self.artefact);}); } /* ** Load and display Value Proposition */ loadValueProposition() { $(jqId(VALUE_PROPOSITION_PANEL)).load("valueproposition/file_system.html"); } /* ** Static Functionality */ static getArtifactReference() { return FileSystem.getArtifactReference(); } static getDropTargets() { return [Compartment.getArtifactReference()]; } }
JavaScript
class NgRangeBarComponent { constructor() { this.range_slider_value = 0; this.minValue = 1; this.maxValue = 10; this.barColor = ""; this.onSelect = new EventEmitter(); } /** * @return {?} */ ngOnInit() { } /** * @param {?} val * @return {?} */ onInputChange(val) { this.offsetLeft = parseInt((((this.range_slider_value / this.maxValue) * 100) - 15) + ""); this.onSelect.emit(this.range_slider_value); } }
JavaScript
class SubjectColumn extends React.Component { /* eslint-disable */ constructor(props) { // converted this component to a class in order to implement gradeClassName. // don't need state, but need props. super(props); }; /* eslint-enable */ handleDelete = () => { const { subjectName, teacher } = this.props.subject; this.props.deleteSubject(subjectName, teacher); }; gradeClassName = (subject) => { if (subject.subjectName.toLowerCase() === 'tutorial') return 'grid-cell-hidden'; return this.props.subject.grade !== null && this.props.subject.grade !== '' ? 'grid-input' : 'grid-input invalid-scores'; }; render() { return ( <React.Fragment> <div className="grid-cell">{ this.props.subject.subjectName.toLowerCase() !== 'tutorial' ? this.props.subject.teacher.lastName : '' }</div> <div className="grid-cell">{ this.props.subject.subjectName }</div> { Object.keys(this.props.subject.scoring) .map((markType, i) => { const { excusedDays, stamps, halfStamps } = this.props.subject.scoring; const maxStamps = this.props.subject.subjectName.toLowerCase() !== 'tutorial' ? 20 - excusedDays * 4 : 8 - excusedDays * 2; const validScores = this.props.subject.scoring[markType] !== null && this.props.subject.scoring[markType] !== '' && excusedDays >= 0 ? (stamps + halfStamps) <= maxStamps : false; return ( <div className="grid-cell" key={ i }><input type="number" required onChange={ this.props.handleSubjectChange } className={validScores ? 'grid-input' : 'grid-input invalid-scores'} name={ `${this.props.subject.subjectName}-${markType}` } value={ this.props.subject.scoring[markType] === null ? '' : this.props.subject.scoring[markType]} /></div>); }) } {this.props.isElementaryStudent ? null : <div className="grid-cell"> <input type="text" className={this.gradeClassName(this.props.subject)} onChange={ this.props.handleSubjectChange } name={ `${this.props.subject.subjectName}-grade` } value={ this.props.subject.grade } required={this.props.subject.subjectName.toLowerCase() !== 'tutorial'}/> </div>} <div className={this.props.editing && this.props.subject.subjectName.toLowerCase() !== 'tutorial' ? 'grid-cell-delete' : 'grid-cell-hidden'}> <button type="button" onClick={ this.handleDelete }>X</button> </div> </React.Fragment> ); } }
JavaScript
class V1IPBlock { static getAttributeTypeMap() { return V1IPBlock.attributeTypeMap; } }
JavaScript
class ShiftdateTransform extends Serializer { serialize(date) { let type = typeof date; if (type == 'string') { const result = date.match(/^\s*\d{4}[/-]\d{1,2}[/-]\d{1,2}\s+\d{1,2}:\d{1,2}(:\d{1,2})?\s*$/); if (result && !result[1]) { return date+':00'; } } return date; } deserialize(date) { if (!date) { return date; } const result = date.match(/^\s*(\d{4}[/-]\d{1,2}[/-]\d{1,2}\s+\d{1,2}:\d{1,2})(:\d{1,2})?\s*$/); if (result) { return result[1]; } return date; } }
JavaScript
class Handshaking extends State { handleMessage (msg) { super.handleMessage(msg) const handleError = err => this.setState(Failed, err, this.buffered && this.buffered.callback) if (msg instanceof Error) return handleError(msg) const { status, stream, data, chunk } = msg if (status) { return handleError(new Error('unexpected status reply')) } if (!stream || !stream.sink) { return handleError(new Error('bad sink')) } this.ctx.sink = stream.sink this.setState(Requesting, this.buffered) } write (msg, encoding, callback) { this.buffered = { msg, encoding, callback } } final (callback) { this.buffered = { callback } } }
JavaScript
class Initiator { /** * @parma {object} props * @param {function} props.send - write to underlying connection * @param {string} props.to - target path * @param {string} props.path - source path * @param {string} props.method * @param {object} [props.stream] * @param {*} [props.data] * @param {buffer} [props.chunk] */ constructor ({ send, to, path, method, data, chunk, stream }) { this._send = send this.req = { to, path, method } this.res = undefined this._send({ to, from: path, method, data, chunk, stream }) const write = this.write.bind(this) const final = this.final.bind(this) const destroy = this.destroy.bind(this) if (stream) { this.req = new Writable({ objectMode: true, write, final, destroy }) this.state = new Handshaking(this) } else { this.req = Object.assign(new Emitter(), { destroy }) this.state = new Requested(this) } } /** * Besides type and range, * 1. a successful status should not have error * 2. an error or error status message should not have stream, data, chunk * * @param {object} msg * @param {number} [msg.status] - if provided, must be integer in range * @param {object} [msg.error] - non-null object * @param {object} [msg.stream] - non-null object * @param {*} [msg.data] - any JS value that could be encoded in JSON * @param {buffer} [msg.chunk] - node Buffer */ handleMessage ({ status, error, stream, data, chunk }) { // TODO validate if (error || isErrorStatus(status)) { const err = Object.assign(new Error(), error) if (status) { err.message = err.message || 'failed' err.code = 'EFAIL' err.status = status } else { err.message = err.message || 'aborted' err.code = 'EABORT' } this.state.handleMessage(err) } else { this.state.handleMessage({ status, stream, data, chunk }) } } /** * */ write (chunk, encoding, callback) { try { this.state.write(chunk, encoding, callback) } catch (e) { console.log(e) } } /** * */ final (callback) { try { this.state.final(callback) } catch (e) { console.log(e) } } read (size) { } destroy (err) { } }
JavaScript
class Model { constructor(tablename) { this.tablename = tablename; } /** * Gets all records in the table matching the specified conditions. * @param {Object} options - An object where the keys are column names and the * values are the current values to be matched. * @returns {Promise<Array>} A promise that is fulfilled with an array of objects * matching the conditions or is rejected with the the error that occurred during * the query. */ getAll(options) { if (!options) { let queryString = `SELECT * FROM ${this.tablename}`; return executeQuery(queryString); } let parsedOptions = parseData(options); let queryString = `SELECT * FROM ${this.tablename} WHERE ${parsedOptions.string.join(' AND ')}`; return executeQuery(queryString, parsedOptions.values); } /** * Gets one record in the table matching the specified conditions. * @param {Object} options - An object where the keys are column names and the * values are the current values to be matched. * @returns {Promise<Object>} A promise that is fulfilled with one object * containing the object matching the conditions or is rejected with the the * error that occurred during the query. Note that even if multiple objects match * the conditions provided, only one will be provided upon fulfillment. */ get(options) { let parsedOptions = parseData(options); let queryString = `SELECT * FROM ${this.tablename} WHERE ${parsedOptions.string.join(' AND ')} LIMIT 1`; return executeQuery(queryString, parsedOptions.values).then(results => results[0]); } /** * Creates a new record in the table. * @param {Object} options - An object with key/value pairs, where the keys should match * the column names and the values should be of the correct type for that table. See model * class definition for additional information about the schema. * @returns {Promise<Object>} A promise that is fulfilled with an object * containing the results of the query or is rejected with the the error that occurred * during the query. */ create(options) { let queryString = `INSERT INTO ${this.tablename} SET ?`; return executeQuery(queryString, options); } /** * Updates a record(s) in the table. * @param {Object} options - An object where the keys are column names and the * values are the current values. All records in the table matching the options will be * updated. * @param {Object} values - An object where the keys are column names and the values * are the new values. * @returns {Promise<Object>} A promise that is fulfilled with an object * containing the results of the query or is rejected with the the error that occurred * during the query. */ update(options, values) { let parsedOptions = parseData(options); let queryString = `UPDATE ${this.tablename} SET ? WHERE ${parsedOptions.string.join(' AND ')}`; return executeQuery(queryString, Array.prototype.concat(values, parsedOptions.values)); } /** * Deletes a record or records in the table. * @param {Object} options - An object where the keys are column names and * the values are the current values. All rows in the table matching options will be * deleted. * @returns {Promise<Object>} A promise that is fulfilled with an object * containing the results of the query or is rejected with the the error that occurred * during the query. */ delete(options) { let parsedOptions = parseData(options); let queryString = `DELETE FROM ${this.tablename} WHERE ${parsedOptions.string.join(' AND ')}`; return executeQuery(queryString, parsedOptions.values); } /** * Deletes all records in the table. * @returns {Promise<Object>} A promise that is fulfilled with an object * containing the results of the query or is rejected with the the error that occurred * during the query. */ deleteAll() { let queryString = `TRUNCATE TABLE ${this.tablename}`; return executeQuery(queryString); } }
JavaScript
class WorkspacePlugin extends Plugin { /** * @inheritdoc */ constructor(props) { super(props); this.openedFolders = []; this.openedFiles = []; this._selectedNodeInExplorer = undefined; this.onWorkspaceFileUpdated = this.onWorkspaceFileUpdated.bind(this); this.onWorkspaceFileContentChanged = this.onWorkspaceFileContentChanged.bind(this); this.onNodeSelectedInExplorer = this.onNodeSelectedInExplorer.bind(this); } get selectedNodeInExplorer() { return this._selectedNodeInExplorer; } set selectedNodeInExplorer(newT) { this._selectedNodeInExplorer = newT; } /** * @inheritdoc */ getID() { return PLUGIN_ID; } /** * On an opened file in workspace update */ onWorkspaceFileUpdated(file) { const { pref: { history } } = this.appContext; // prevent ast from saving to local storage const openedFiles = this.openedFiles.map((file) => { const newFile = _.clone(file); delete newFile._props.ast; return newFile; }); history.put(HISTORY.OPENED_FILES, this.openedFiles, skipEventAndCustomPropsSerialization); } /** * On content of a file updated */ onWorkspaceFileContentChanged({ file }) { const { command: { dispatch } } = this.appContext; dispatch(EVENTS.FILE_UPDATED, { file }); } /** * Upon tree node selection in explorer */ onNodeSelectedInExplorer(node) { if (!_.isNil(this.selectedNodeInExplorer) && (node.id !== this.selectedNodeInExplorer.id)) { this.selectedNodeInExplorer.active = false; } this.selectedNodeInExplorer = node; this.reRender(); const { editor } = this.appContext; if (editor.isFileOpenedInEditor(node.id)) { const targetEditor = editor.getEditorByID(node.id); editor.setActiveEditor(targetEditor); } } /** * Opens a file using related editor * * @param {String} filePath Path of the file. * @param {Boolean} activate activate upon open. * * @return {Promise} Resolves or reject with error. */ openFile(filePath, activate = true) { return new Promise((resolve, reject) => { const indexInOpenedFiles = _.findIndex(this.openedFiles, file => file.fullPath === filePath); const { command: { dispatch } } = this.appContext; // if not already opened if (indexInOpenedFiles === -1) { read(filePath) .then((file) => { this.openedFiles.push(file); const { pref: { history }, editor } = this.appContext; history.put(HISTORY.OPENED_FILES, this.openedFiles, skipEventAndCustomPropsSerialization); file.on(EVENTS.FILE_UPDATED, this.onWorkspaceFileUpdated); file.on(EVENTS.CONTENT_MODIFIED, this.onWorkspaceFileContentChanged); editor.open(file, activate); dispatch(EVENTS.FILE_OPENED, { file }); resolve(file); }) .catch((err) => { reject(JSON.stringify(err)); }); } else { dispatch(EDITOR_COMMANDS.ACTIVATE_EDITOR_FOR_FILE, { filePath, }); log.debug(`File ${filePath} is already opened.`); resolve(this.openedFiles[indexInOpenedFiles]); } }); } /** * Refresh Path in Explorer, if it's already opened * @param {String} filePath Target File Path */ refreshPathInExplorer(filePath) { const { command: { dispatch } } = this.appContext; dispatch(COMMAND_IDS.REFRESH_PATH_IN_EXPLORER, { filePath, }); } /** * Go To Give File in Explorer, if it's already opened * @param {String} filePath Target File Path */ goToFileInExplorer(filePath) { const { command: { dispatch } } = this.appContext; dispatch(COMMAND_IDS.GO_TO_FILE_IN_EXPLORER, { filePath, }); } /** * Gets the parent folder opened in explorer for the given file * @param {String} filePath target file path */ getExplorerFolderForPath(filePath) { return this.openedFolders.find((folder) => { return filePath.startsWith(folder.fullPath); }); } /** * Checks whether the given path is opened in explorer * @param {String} filePath target path */ isFilePathOpenedInExplorer(filePath) { return this.openedFolders.find((folder) => { return filePath.startsWith(folder.fullPath); }) !== undefined; } /** * Create a new file and opens it in a new tab */ createNewFile() { const { pref: { history }, editor, command: { dispatch } } = this.appContext; const supportedExts = editor.getSupportedExtensions(); let extension; if (supportedExts.length === 1) { extension = supportedExts[0]; } else { // provide user a choice on which type of file to create // TODO } const content = editor.getDefaultContent('temp.' + extension); const newFile = new File({ extension, content }); this.openedFiles.push(newFile); history.put(HISTORY.OPENED_FILES, this.openedFiles, skipEventAndCustomPropsSerialization); newFile.on(EVENTS.FILE_UPDATED, this.onWorkspaceFileUpdated); newFile.on(EVENTS.CONTENT_MODIFIED, this.onWorkspaceFileContentChanged); editor.open(newFile); dispatch(EVENTS.FILE_OPENED, { file: newFile }); } /** * Close an opened file * * @param {String} filePath Path of the file. * @return {Promise} Resolves or reject with error. */ closeFile(file) { return new Promise((resolve, reject) => { if (this.openedFiles.includes(file)) { _.remove(this.openedFiles, file); const { pref: { history }, command: { dispatch } } = this.appContext; history.put(HISTORY.OPENED_FILES, this.openedFiles, skipEventAndCustomPropsSerialization); file.off(EVENTS.FILE_UPDATED, this.onWorkspaceFileUpdated); file.off(EVENTS.CONTENT_MODIFIED, this.onWorkspaceFileContentChanged); dispatch(EVENTS.FILE_CLOSED, { file }); } else { reject(`File ${file.fullPath} cannot be found in opened file set.`); } }); } /** * Opens a folder in explorer * * @param {String} folderPath Path of the folder. * @return {Promise} Resolves or reject with error. */ openFolder(folderPath) { return new Promise((resolve, reject) => { // add path to opened folders list - if not added already if (_.findIndex(this.openedFolders, folder => folder.fullPath === folderPath) === -1) { this.openedFolders.push(new Folder({ fullPath: folderPath })); const { pref: { history } } = this.appContext; history.put(HISTORY.OPENED_FOLDERS, this.openedFolders); this.reRender(); } const { command: { dispatch } } = this.appContext; dispatch(LAYOUT_COMMANDS.SHOW_VIEW, { id: VIEW_IDS.EXPLORER }); resolve(); }); } /** * Remove an opened folder from explorer * * @param {String} folderPath Path of the folder. * @return {Promise} Resolves or reject with error. */ removeFolder(folderPath) { return new Promise((resolve, reject) => { if (_.findIndex(this.openedFolders, folder => folder.fullPath === folderPath) !== -1) { _.remove(this.openedFolders, folder => folder.fullPath === folderPath); const { pref: { history } } = this.appContext; history.put(HISTORY.OPENED_FOLDERS, this.openedFolders); this.reRender(); } resolve(); }); } /** * @inheritdoc */ init(config) { super.init(config); this.config = config; return { openFile: this.openFile.bind(this), openFolder: this.openFolder.bind(this), closeFile: this.closeFile.bind(this), removeFolder: this.removeFolder.bind(this), goToFileInExplorer: this.goToFileInExplorer.bind(this), isFilePathOpenedInExplorer: this.isFilePathOpenedInExplorer.bind(this), getExplorerFolderForPath: this.getExplorerFolderForPath.bind(this), refreshPathInExplorer: this.refreshPathInExplorer.bind(this), }; } /** * @inheritdoc */ activate(appContext) { super.activate(appContext); const { pref: { history } } = appContext; const serializedFolders = history.get(HISTORY.OPENED_FOLDERS) || []; this.openedFolders = serializedFolders.map((serializedFolder) => { return Object.assign(new Folder({}), serializedFolder); }); // make File objects for each serialized file const serializedFiles = history.get(HISTORY.OPENED_FILES) || []; this.openedFiles = serializedFiles.map((serializedFile) => { return Object.assign(new File({}), serializedFile); }); if (this.config && this.config.startupFile) { this.openFile(this.config.startupFile); } } /** * @inheritdoc */ onAfterInitialRender() { const { editor, command: { dispatch } } = this.appContext; this.openedFiles.forEach((file) => { file.on(EVENTS.FILE_UPDATED, this.onWorkspaceFileUpdated); file.on(EVENTS.CONTENT_MODIFIED, this.onWorkspaceFileContentChanged); // no need to activate this editor // as this is loading from history. // Editor plugin will decide which editor // to activate depending on editor tabs history editor.open(file, false); dispatch(EVENTS.FILE_OPENED, { file }); }); } /** * @inheritdoc */ getContributions() { const { COMMANDS, HANDLERS, MENUS, VIEWS, DIALOGS, TOOLS } = CONTRIBUTIONS; return { [COMMANDS]: getCommandDefinitions(this), [HANDLERS]: getHandlerDefinitions(this), [MENUS]: getMenuDefinitions(this), [VIEWS]: [ { id: VIEW_IDS.EXPLORER, component: WorkspaceExplorer, propsProvider: () => { return { workspaceManager: this, }; }, region: REGIONS.LEFT_PANEL, // region specific options for left-panel views regionOptions: { activityBarIcon: 'file-browse', panelTitle: 'Explorer', panelActions: [ { icon: 'refresh2', isActive: () => { return true; }, handleAction: () => { const { command: { dispatch } } = this.appContext; dispatch(COMMAND_IDS.REFRESH_EXPLORER, {}); }, description: 'Refresh', }, { icon: 'folder-open', isActive: () => { return true; }, handleAction: () => { const { command: { dispatch } } = this.appContext; dispatch(COMMAND_IDS.SHOW_FOLDER_OPEN_WIZARD, {}); }, description: 'Open Directory', }, ], }, displayOnLoad: true, }, ], [DIALOGS]: [ { id: DIALOG_IDS.OPEN_FILE, component: FileOpenDialog, propsProvider: () => { return { workspaceManager: this, }; }, }, { id: DIALOG_IDS.OPEN_FOLDER, component: FolderOpenDialog, propsProvider: () => { return { workspaceManager: this, }; }, }, { id: DIALOG_IDS.SAVE_FILE, component: FileSaveDialog, propsProvider: () => { return { workspaceManager: this, }; }, }, { id: DIALOG_IDS.REPLACE_FILE_CONFIRM, component: FileReplaceConfirmDialog, propsProvider: () => { return { workspaceManager: this, }; }, }, { id: DIALOG_IDS.DELETE_FILE_CONFIRM, component: FileDeleteConfirmDialog, propsProvider: () => { return { workspaceManager: this, }; }, }, ], [TOOLS]: [ { id: TOOL_IDS.NEW_FILE, group: TOOL_IDS.GROUP, icon: 'blank-document', commandID: COMMAND_IDS.CREATE_NEW_FILE, description: 'Create New', }, { id: TOOL_IDS.OPEN_FILE, group: TOOL_IDS.GROUP, icon: 'folder-open', commandID: COMMAND_IDS.SHOW_FILE_OPEN_WIZARD, description: 'Open File', }, { id: TOOL_IDS.SAVE_FILE, group: TOOL_IDS.GROUP, icon: 'save', commandID: COMMAND_IDS.SAVE_FILE, isActive: () => { const { editor } = this.appContext; const activeEditor = editor.getActiveEditor(); if (activeEditor && !_.isNil(activeEditor.file)) { return activeEditor.file.isDirty; } return false; }, description: 'Save File', }, ], }; } }
JavaScript
class TokenAuthService { /** *Creates an instance of TokenAuthService. * @param {string} uri The endpoint that hands out a JWT Token. * @memberof TokenAuthService */ constructor(uri) { this.events = new EventEmitter(); this.auth_uri = uri; } /** * Get notifications for state changes. * Currently only `authorized` is supported. * * @param {string} name of the event * @param {callback} fn To be invoked */ on = (name, fn) => { this.events.on(name, fn); }; /** * Obtains a JWT token with basic auth for the given username and password. * * @param {string} email The user name/email * @param {string} password The password * @returns A promise */ login = (email, password) => { return axios .get(this.auth_uri, { auth: { username: email, password: password } }) .then(response => { this.token = "Bearer " + response.data; this.events.emit("authorized", true); }); }; /** * Logs the user out by resetting the token. * * @returns A promis */ logout = () => { return new Promise((resolve, reject) => { this.token = null; resolve(null); this.events.emit("authorized", false); }); }; /** * Called by the EmulatorWebClient when the web endpoint * returns a 401. It will fire the `authorized` event. * * @memberof TokenAuthService * @see EmulatorWebClient */ unauthorized = ev => { this.token = null; this.events.emit("authorized", false); }; register = (email, password) => { return new Promise((resolve, reject) => { reject(new Error("Register not supported")); }); }; /** * * @memberof TokenAuthService * @returns True if a token is set. */ authorized = () => { return this.token != null; }; /** * Called by the EmulatorWebClient to obtain the authentication * headers * * @memberof TokenAuthService * @returns The authentication header for the web call * @see EmulatorWebClient */ authHeader = () => { return { Authorization: this.token }; }; }
JavaScript
class NoAuthService { constructor() { this.events = new EventEmitter(); this.loggedin = false; } on = (name, fn) => { this.events.on(name, fn); }; login = (email, password) => { return new Promise((resolve, reject) => { this.loggedin = true; resolve(null); this.events.emit("authorized", this.loggedin); }); }; logout = () => { return new Promise((resolve, reject) => { this.loggedin = false; resolve(null); this.events.emit("authorized", this.loggedin); }); }; register = (email, password) => { return new Promise((resolve, reject) => { reject(new Error("Register not supported")); }); }; unauthorized = ev => { this.loggedin = false; this.events.emit("authorized", this.loggedin); }; authorized = () => { return this.loggedin; }; authHeader = () => { return {}; }; }
JavaScript
class PlaybackControl{ constructor(playbackElementId, playbackModalId){ this.playbackElement = document.getElementById(playbackElementId); this.playbackModal = $(`#${playbackModalId}`); this.dialog = this.playbackModal.dialog({ autoOpen: false, width: "80%", modal: true, create: function(event, ui){ // Set maxWidth $(this).parent().css("maxWidth", "500px"); }, buttons: { Yes: function(){ this.playbackElement.play(); this.playbackModal.dialog("close"); }.bind(this), No: function(){ this.playbackElement.currentTime = 0; this.playbackModal.dialog("close"); }.bind(this) } }); let data = this.readFromUrl(); let vts = null; if(data.vts){ vts = parseInt(data.vts, 10); if(vts){ this.playbackElement.currentTime = vts; } } if(data.vte && vts !== null){ let vte = parseInt(data.vte, 10); if(vte > vts){ let clipLength = vte - vts; let interval = setInterval(function(){ if(this.playbackElement.currentTime >= vte || this.playbackElement.ended){ this.playbackElement.pause(); clearInterval(interval); } }.bind(this), 1000); if(data.title){ this.dialog.dialog("option", "title", "About to play a clip!"); this.playbackModal.empty().append(`<p>You are about to listen to a ${clipLength} second clip entitled: <br/> <strong>"${data.title}"</strong></p> <p>Would you like to play it?</p>`); this.dialog.dialog("open"); }else{ this.dialog.dialog("option", "title", "About to play a clip!"); this.playbackModal.empty().append(`<p>You are about to listen to a ${clipLength} second clip.</p> <p> Would you like to play it?</p> `); this.dialog.dialog("open"); } } } } readFromUrl(){ //Adapted from https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript let query = window.location.search; return query ? (/^[?#]/.test(query) ? query.slice(1) : query) .split('&') .reduce((params, param) => { let [key, value] = param.split('='); params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : ''; return params; }, {} ) : {}; } }
JavaScript
class WeatherView extends React.Component { state = { weather: null, apiUrl: this.props.apiUrl } componentDidMount() { this.fetchWeather(); this.interval = setInterval(() => { console.log("Refreshing weather..."); this.fetchWeather(); } , 10000); } componentWillUnmount() { clearInterval(this.interval); } /** * Openflorian API Access: * Fetch the current weather * * Request: * -> GET <API_URL>/data/media/all * Expected response: * -> application/json - PagedSessionList */ fetchWeather = () => { fetch(this.state.apiUrl + '/weather/current') .then(result => { return result.json(); }).then(this.renderWeather) } /** * Render received PagedSessionList */ renderWeather = (weather) => { console.log("Received weather", weather); const PRESSURE_STATE = { RISING: "wi pressure wi-direction-up-right", FALLING: "wi pressure wi-direction-down-right", STEADY: "wi pressure wi-direction-right" } let temperature = Intl.NumberFormat('de-DE', {style: 'decimal', maximumFractionDigits: 2}).format(weather.temperature) + " °C"; let humidity = Intl.NumberFormat('de-DE', {style: 'decimal', maximumFractionDigits: 2}).format(weather.humidity) + " %"; let pressure = Intl.NumberFormat('de-DE', {style: 'decimal', maximumFractionDigits: 2}).format(weather.pressure) + " hPa"; let windSpeed = Intl.NumberFormat('de-DE', {style: 'decimal', maximumFractionDigits: 2}).format(weather.windSpeed) + " km/h"; let windDirection = "wi windspeed wi-wind towards-" + weather.windDirection + "-deg"; const weatherCondition = (conditionCode) => ({ OPENWEATHERMAP: "wi weather-icon " + weatherConditions.OPENWEATHER_CONDITONS[conditionCode], YAHOOWEATHER: "wi weather-icon " + weatherConditions.YAHOOWEATHER_CONDITIONS[conditionCode] }) let weatherHtml = <div> <div className="weather-box"> <div> <div className={weatherCondition(weather.conditionCode)[weather.source]}></div> <div className="temp-humidity-box"> <div className="temperature-box"> <div className="wi wi-thermometer" />&nbsp; <div className="temperature">{temperature}</div> </div> </div> <div className="humidity-box"> <div className="wi wi-humidity">&nbsp;</div> <div className="humidity">{humidity}</div> </div> </div> <div className="pressure-box"> <div className="wi wi-barometer" />&nbsp; <div className="pressure">{pressure}</div> <div className={PRESSURE_STATE[weather.pressureState]}/> </div> <div className="wind-speed-box"> <div className="wi wi-strong-wind"/>&nbsp; <div className="windspeed">{windSpeed}</div>&nbsp; <div className={windDirection} /> </div> </div><br/><br/> <div className="weather-box-footer"> <div className="current-time">Last updated:</div> <div className="current-time">{new Date(weather.timestamp).toLocaleString()}</div> </div> </div> this.setState({weather: weatherHtml}) console.log("state", this.state.weather) } /** * Render WeaterView */ render() { return( <div> <div> {this.state.weather} </div> <div className="claim"> Served by: OpenFlorian <ul> <li>https://github.com/krausb/openflorian-ui</li> <li>https://github.com/krausb/openflorian-master</li> </ul> </div> </div> ) } }
JavaScript
class ApplyColormapFilter extends ImageToImageFilter { constructor(){ super(); this.addInputValidator(0, Image2D); // the default colormap style is jet (rainbow) this.setMetadata("style", "jet"); // flip the colormap (no by default) this.setMetadata("flip", false ); // min and max should come from the min and max of the input image, // thought they can be changed manually to adapt the colormap to a different range this.setMetadata("min", undefined ); this.setMetadata("max", undefined ); // how many color cluster? For smooth gradient, keep it null this.setMetadata("clusters", null ); // In case of using an image with more than 1 component per pxel (ncpp>1) // we must choose on which component is computer the colormap // (default: the 0th, so the Red for a RGB image) this.setMetadata("component", 0) } _run(){ if( ! this.hasValidInput()){ console.warn("A filter of type CropImageFilter requires 1 input of category '0' (Image2D)"); return; } var inputImage = this._getInput( 0 ); var inputWidth = inputImage.getWidth(); var inputHeight = inputImage.getHeight(); var ncpp = inputImage.getNcpp(); var component = this.getMetadata("component"); if( component >= ncpp ){ console.warn("The chosen component must be lower than the input ncpp"); return; } var min = this.getMetadata( "min" ) || inputImage.getMin(); var max = this.getMetadata( "max" ) || inputImage.getMax(); var clusters = this.getMetadata( "clusters" ); if( Math.abs(min - max) < 1e-6 ){ console.warn("Min and max values are similar, no interpolation is possible."); return; } var cm = new Colormap(); cm.setMetadata("flip", this.getMetadata("flip") ); cm.setStyle( this.getMetadata("style") ); var lookupFunction = cm.getValueAt.bind(cm); if( clusters ){ lookupFunction = cm.getValueAtWithClusters.bind(cm); } var inputData = inputImage.getData(); var outputImage = new Image2D({ width : inputWidth, height : inputHeight, color : new Uint8Array( [0, 0, 0] ) }) cm.buildLut(); for( var i=0; i<inputWidth; i++){ for( var j=0; j<inputHeight; j++){ var inputColor = inputImage.getPixel({ x: i, y: j})[component]; var normalizedIntensity = ( inputColor - min ) / ( max - min ); var color = lookupFunction( normalizedIntensity, clusters ) outputImage.setPixel( {x: i, y: j}, color ) } } this._output[ 0 ] = outputImage; } } /* END of class ApplyColormapFilter */
JavaScript
class App extends Component { state = { employees: [], search: "", sortOrder: "ASC" }; //this section allows the sorting via first name sortFirstName() { const sortedFirst = this.state.employees.sort(this.compareFirst); this.setState({ employees: sortedFirst }); const orderFirst = this.state.sortOrder ? "ASC" : "DESC"; this.setState({ sortOrder: orderFirst }) }; compareFirst(a, b) { if (a.firstName > b.firstName) return 1; if (b.firstName > a.firstName) return -1; return 0; }; //this section allows sorting via last name sortLastName() { const sortedLast = this.state.employees.sort(this.compareLast); this.setState({ employees: sortedLast }); const orderLast = this.state.sortOrder ? "ASC" : "DESC"; this.setState({ sortOrder: orderLast }) }; compareLast(a, b) { if (a.lastName > b.lastName) return 1; if (b.lastName > a.lastName) return -1; return 0; }; //this section allows for sorting via email sortEmail() { const sortedEmail = this.state.employees.sort(this.compareEmail); this.setState({ employees: sortedEmail }); const orderEmail = this.state.sortOrder ? "ASC" : "DESC"; this.setState({ sortOrder: orderEmail }) }; compareEmail(a, b) { if (a.email > b.email) return 1; if (b.email > a.email) return -1; return 0; }; //get the data for the employees via the API componentDidMount() { API.search().then((res) => { console.log(res); this.setState({ employees: res.data.results.map((employee, i) => ({ firstName: employee.name.first, lastName: employee.name.last, picture: employee.picture.large, email: employee.email, phone: employee.phone, city: employee.location.city, key: i, })), }); }) .catch((err) => console.log(err)); }; refreshPage() { window.location.reload(false); }; //this is the function for searching by name searchName = (filter) => { console.log("Search by name:", filter); const filterEmployees = this.state.employees.filter((employee) => { let values = Object.values(employee).join("").toLocaleLowerCase(); return values.indexOf(filter.toLowerCase()) !== -1; }); this.setState({ employees: filterEmployees }); }; //this is an event handler for input changing handleInputChange = (event) => { this.setState({ [event.target.name]: event.target.value, }); }; //this is an event handler for form submissions handleFormSubmit = (event) => { event.preventDefault(); this.searchName(this.state.search) }; //this section renders the page using the various props to populate information render() { return ( <Container> <div className = "row"> <Col size = "md-3"> </Col> <Col size = "md-6"> <h2>Employee Directory</h2> <SearchForm value = {this.state.search} handleInputChange = {this.handleInputChange} handleFormSubmit = {this.handleFormSubmit} /> </Col> <Col size = "md-3"> </Col> </div> <div className = "row"> <Col size = "md-12"> <table className = "table"> <thead> <tr> <th>Photo</th> <th onClick={() => { this.sortFirstName() }}>First Name</th> <th onClick={() => { this.sortLastName() }}>Last Name</th> <th onClick={() => { this.sortEmail() }}>Email</th> <th>Phone</th> <th>City</th> </tr> </thead> {[...this.state.employees].map((item) => ( <EmployeeCard picture = {item.picture} firstName = {item.firstName} lastName = {item.lastName} email = {item.email} phone = {item.phone} city = {item.city} key = {item.key} /> ))} </table> </Col> </div> </Container> ); }; }
JavaScript
class RatingList extends Component { state = { ratings: [] }; componentWillMount() { console.log('componentWillMount'); //debugger; /* axios.get(data)//https://rallycoding.herokuapp.com/api/music_albums .then(response => this.setState({ ratings: response.data } ));*/ this.setState({ ratings: data } ); } renderRatings() { return this.state.ratings.map(rating => <RatingDetail key={rating.title} rating={rating} /> ); } render() { return ( // <View> // <FAB /> <ScrollView> {this.renderRatings()} </ScrollView> // </View> ); } }
JavaScript
class Paginator extends Component{ next(){ MarvelActions.nextPage(); }; prev(){ MarvelActions.prevPage(); } render(){ return <div className="clearfix"> <a className="btn btn-primary pull-left" onClick={this.prev}>Avant</a> <a className="btn btn-primary pull-right" onClick={this.next}>Suivant</a> <div className="text-center">Page {CharacterStore.page} de {CharacterStore.totalPages}</div> </div> } }
JavaScript
class MissingRuleValueError extends RuleValueError { constructor(rule_name, node) { super(null, node); this.setRuleName(rule_name); } /** * @returns {string} */ getMessage() { var rule_name = this.getRuleName(); return `Must supply a value for rule <${rule_name}>`; } /** * @param {boolean} should_be_suppressed * @returns {self} */ setShouldBeSuppressed(should_be_suppressed) { this.should_be_suppressed = should_be_suppressed; return this; } /** * @returns {boolean} */ shouldBeSuppressed() { return this.should_be_suppressed; } }
JavaScript
class LocaleHelper { /** * @param {CommandoClient} client - The client that is used for this helper * @param {?Module} module - The module that is used for this helper * @private */ constructor(client, module) { /** * The client that is used for this helper. * @name LocaleHelper#client * @type {CommandoClient} * @readonly */ Object.defineProperty(this, 'client', { value: client }); /** * The module that is used for this helper, if associated with one. * @name LocaleHelper#module * @type {Module} * @readonly */ Object.defineProperty(this, 'module', { value: module }); } /** * Gets the translation of a key. * @param {string} namespace - The namespace * @param {string} key - The key * @param {GuildResolvable} [guild] - The guild * @param {Object} [vars] - Extra variables for the translator * @return {string} The translation. */ translate(namespace, key, guild, vars) { if (guild) { guild = this.client.resolver.resolveGuild(guild); } return this.client.localeProvider.translate( this.module ? this.module.id : null, namespace, key, guild && guild.language ? guild.language : this.client.language, vars ); } /** * Alias of {@link LocaleProvider#translate}. * @param {string} namespace - The namespace * @param {string} key - The key * @param {GuildResolvable} [guild] - The guild * @param {Object} [vars] - Extra variables for the translator * @return {string} The translation. */ tl(namespace, key, guild, vars) { return this.translate(namespace, key, guild, vars); } }
JavaScript
class AppStorage { constructor(storage) { this.storage = storage || window.localStorage; /** Is storage is supported or not */ if (!this.isSupported()) { throw new Error('Storage is not supported by browser!'); } } setItem(key, value) { let val = value; if (typeof value === 'object') { val = JSON.stringify(value); } this.storage.setItem(key, val); } getItem(key) { const val = this.storage.getItem(key); try { return JSON.parse(val); } catch (e) { return val; } } removeItem(key) { this.storage.removeItem(key); } clear() { this.storage.clear(); } /** * @description Check for storage support * @returns {boolean} supported * */ isSupported() { let supported = true; if (!this.storage) { supported = false; } return supported; } }
JavaScript
class OkapiPaths extends React.Component { static manifest = Object.freeze({ moduleDetails: { type: 'okapi', accumulate: true, fetch: false, }, moduleId: '', }); static propTypes = { stripes: PropTypes.shape({ connect: PropTypes.func.isRequired, }).isRequired, resources: PropTypes.shape({ moduleDetails: PropTypes.object, moduleId: PropTypes.object, }).isRequired, mutator: PropTypes.shape({ moduleDetails: PropTypes.object, }), }; constructor() { super(); this.state = { paths: {}, filter: '', }; } /** * read the list of modules from props.stripes.discovery.modules, then * request /_/proxy/modules/$i and parse the result to find the list of * paths supported by each implementation and store the result in state. */ componentDidMount() { const { mutator } = this.props; const modules = get(this.props.stripes, ['discovery', 'modules']) || {}; const paths = this.state.paths; Object.keys(modules).forEach(impl => { mutator.moduleDetails.GET({ path: `_/proxy/modules/${impl}` }).then(res => { const iface = this.implToInterface(impl); if (res.provides) { res.provides.forEach(i => { i.handlers.forEach(handler => { paths[handler.pathPattern] = { iface, impl, ramlsLink: <Link to={`//github.com/folio-org/${iface}/tree/master/ramls`}>{iface}</Link>, }; }); }); } this.setState({ paths }); }); }); } /** * map a module implementation string to an interface, hopefully. * given a string like "mod-users-16.2.0-SNAPSHOT.127" return "mod-users" */ implToInterface(impl) { const iface = impl.match(/^(.*)-[0-9].*/); return iface[1] ? iface[1] : ''; } /** * iterate through this.state.paths to find those matching this.state.filter * and return an array of nicely formatted <li> elements */ showPaths = () => { // dear ESLint: I just want you to know that // <li key={path}>{path} = {this.state.paths[path].ramlsLink}</li>); // is SO MUCH CLEARER than // <li key={path}> // {path} // = // {this.state.paths[path].ramlsLink} // </li> // AND it actually formats the way I want, with spaces around the equals. // Sometimes, and I hate to tell it to you this way, you suck at your job. return Object .keys(this.state.paths) .sort() .filter(path => path.indexOf(this.state.filter) >= 0) .map(path => <li key={path}>{path} = {this.state.paths[path].ramlsLink}</li>); // eslint-disable-line } handleFilter = (event) => { this.setState({ filter: event.target.value }); } render() { return ( <Pane defaultWidth="fill" paneTitle="Okapi paths" > <div> <h3>resource path to interface mapper</h3> <input type="text" name="" onChange={this.handleFilter} /> </div> <ul> {this.showPaths()} </ul> </Pane> ); } }
JavaScript
class Counter { constructor () { this.map = new Map() } update (string) { for (const token of tokenize(string)) { this.incr(token) } } incr (token) { this.map.set(token, this.get(token) + 1) } get (token) { return this.map.get(token) || 0 } }
JavaScript
class Location extends Component { constructor (props) { super(props); this.state = { scenicloc: [], id: props.match.params.scenicId, shops_list: [], selectedShop: [], snaps_list: [], selectedSnapshot:[], }; this.get_coffeeshops = this.get_coffeeshops.bind(this); this.get_snaps = this.get_snaps.bind(this); this.returnNoResults = this.returnNoResults.bind(this); }; // Initial load of the data for the individual location instance componentDidMount(props) { fetch('/getsceniclocation/' + this.state.id).then(results =>{ return results.json(); }).then(data=>{ let views = data.map((scenic) =>{ this.setState({scenicloc: scenic}); }) }) } // Get coffeshops nearby to the scenic location get_coffeeshops(){ fetch('/nearby_shops_from_scenic/' + this.state.scenicloc.scenic_id).then(results =>{ return results.json(); }).then(data=>{ let shops = data.map((shop) =>{ return( <div id="shop_instance" key={shop.shop_name} onClick={() =>{this.setState({navigateShop: true, navigateToShop: "/shop/" + shop.shop_id, selectedShop: shop})}}> <li className="col"> <img src={shop.shop_picture} style={{width: 200, height: 200}} alt="Photo1" /> <span className="picTextInstance"> <span><b>{shop.shop_name}</b></span></span> </li> </div> ) }) this.setState({shops_list: shops}); }) } // Get snapshots associated with the scenic location get_snaps(){ fetch('/snapshots_scenic/'+ this.state.scenicloc.scenic_id).then(results =>{ return results.json(); }).then(data=>{ let snapshots = data.map((snapshot) =>{ return( <div id="snap_instance" key={snapshot.snap_name} onClick={() =>{this.setState({navigateSnap: true, navigateTo: "/snapshot/" + snapshot.snap_id, selectedSnapshot: snapshot})}}> <li className="col"> <img src={snapshot.snap_picture} style={{width: 200, height: 200}} alt="Photo1"/> <span className="picTextInstance"><span><b>{snapshot.snap_name}</b></span></span> </li> </div> ); }); if(data.length == 0) { let snapshots = [<div></div>, this.returnNoResults()]; this.setState({snaps_list: snapshots}); } else { let snapshots = data.map((snapshot) =>{ return( <div id="snap_instance" key={snapshot.snap_name} onClick={() =>{this.setState({navigateSnap: true, navigateToSnap: "/snapshot/" + snapshot.snap_id, selectedSnapshot: snapshot})}}> <li className="col"> <img src={snapshot.snap_picture} style={{width: 200, height: 200}} alt="Photo1"/> <span className="picTextInstance"><span><b>{snapshot.snap_name}</b></span></span> </li> </div> ); }); this.setState({snaps_list: snapshots}); }; }); }; // If no results are found for coffeeshops nearby or associated snapshots returnNoResults() { return ( <div className="intro-text text-center bg-faded p-5 rounded"> <span className="section-heading-upper text-center">There are no snaps for this view</span> </div> ) } render() { if (this.state.navigateShop) { var instance_state = {}; instance_state = {shop: this.state.selectedShop}; window.open(this.state.navigateToShop, "_blank"); this.setState({navigateShop: false}) } else if (this.state.navigateSnap) { var instance_state = {}; instance_state = {snapshot: this.state.selectedSnapshot}; window.open(this.state.navigateToSnap, "_blank"); this.setState({navigateSnap: false}) } return ( <div> <div className="content"> <div className="col-sm-5 instance-details"> <div className="product-item"> <div className="product-item-title"> <div className="bg-faded p-5 d-flex ml-auto rounded"> <h2 className="section-heading mb-0"> <span className="section-heading-upper">Scenic Location:</span> <span className="section-heading-lower">{this.state.scenicloc.scenic_name}</span> </h2> </div> </div> </div> <div className="product-item-description mr-auto"> <div className="bg-faded p-5 rounded"> <p className="mb-0"><b>Address: </b>{this.state.scenicloc.scenic_address}</p> <p className="mb-0"><b>Rating: </b>{this.state.scenicloc.scenic_rating}/5</p> <p className="mb-0"><b>Reviews:</b></p> <p className="mb-0">{this.state.scenicloc.scenic_review1}</p> <p className="mb-0"></p> <p className="mb-0">{this.state.scenicloc.scenic_review2}</p> </div> </div> </div> <div className="col-sm-5 instance-pic"> <img className="product-item-img mx-auto rounded img-fluid mb-3 mb-lg-0" src={this.state.scenicloc.scenic_picture} alt={this.state.scenicloc.scenic_name} style={{width: 500, height: 500, marginTop: 50}} /> </div> </div> <div className="model-links"> <div class="row"> <div className="col-md-6"> <div className="text-center"> <button id="coffee_nearby" className="btn" type="button" onClick={this.get_coffeeshops}>COFFEESHOPS NEARBY</button> </div> </div> <div className="col-md-6"> <div className="text-center"> <button id="more_snaps" className="btn" type="button" onClick={this.get_snaps}>MORE SNAPS</button> </div> </div> </div> </div> <div class="row justify-content-center"> <section className="col-md-6"> <div class="container text-center"> <ul className="text-center img-list"> {this.state.shops_list} </ul> </div> </section> <section className="col-md-6"> <div class="container text-center"> <ul className="text-center img-list"> {this.state.snaps_list} </ul> </div> </section> </div> </div> ); } }
JavaScript
class InputWithTitle extends React.Component{ render(){ return ( <div className='InputWithTitle'> <p className='InputWithTitle_Label'> {this.props.labelText} </p> <br/> <input className='InputWithTitle_Input' id={this.props.labelText} type='text' name='url' placeholder={this.props.inputFieldPlaceholderText} onKeyUp={ (event)=>{this.tempOnInputTextChange(event)} } > </input> </div> ); } tempOnInputTextChange(e){ // this.props.onInputTextChange(e); if(e.currentTarget.id === 'API Endpoint'){ this.props.dispatch(textInputEditedAction(constants.kInputText_Api,e.currentTarget.value)); }else if(e.currentTarget.id === 'xPath with Format : [path_to_array].key_for_image'){ this.props.dispatch(textInputEditedAction(constants.kInputText_Xpath,e.currentTarget.value)); } } }
JavaScript
class Reporter { constructor(describeJson) { this.migrator = null; this.deployer = null; this.migration = null; this.currentGasTotal = new BN(0); this.currentCostTotal = new BN(0); this.finalCostTotal = new BN(0); this.deployments = 0; this.separator = "\n"; this.summary = []; this.currentFileIndex = -1; this.blockSpinner = null; this.currentBlockWait = ""; this.describeJson = describeJson; this.messages = new MigrationsMessages(this); } // ------------------------------------ Utilities ----------------------------------------------- /** * Sets a Migrator instance to be the current master migrator events emitter source * @param {Migration} migrator */ setMigrator(migrator) { this.migrator = migrator; } /** * Sets a Migration instance to be the current migrations events emitter source * @param {Migration} migration */ setMigration(migration) { this.migration = migration; } /** * Sets a Deployer instance as the current deployer events emitter source * @param {Deployer} deployer */ setDeployer(deployer) { this.deployer = deployer; } /** * Registers emitter handlers for the migrator */ listenMigrator() { // Migrator if (this.migrator && this.migrator.emitter) { this.migrator.emitter.on( "preAllMigrations", this.preAllMigrations.bind(this) ); this.migrator.emitter.on( "postAllMigrations", this.postAllMigrations.bind(this) ); } } /** * Registers emitter handlers for a migration/deployment */ listen() { // Migration if (this.migration && this.migration.emitter) { this.migration.emitter.on("preMigrate", this.preMigrate.bind(this)); this.migration.emitter.on( "startTransaction", this.startTransaction.bind(this) ); this.migration.emitter.on( "endTransaction", this.endTransaction.bind(this) ); this.migration.emitter.on("postMigrate", this.postMigrate.bind(this)); this.migration.emitter.on("error", this.error.bind(this)); } // Deployment if (this.deployer && this.deployer.emitter) { this.deployer.emitter.on("preDeploy", this.preDeploy.bind(this)); this.deployer.emitter.on("postDeploy", this.postDeploy.bind(this)); this.deployer.emitter.on("deployFailed", this.deployFailed.bind(this)); this.deployer.emitter.on("linking", this.linking.bind(this)); this.deployer.emitter.on("error", this.error.bind(this)); this.deployer.emitter.on("transactionHash", this.hash.bind(this)); this.deployer.emitter.on("confirmation", this.confirmation.bind(this)); this.deployer.emitter.on("block", this.block.bind(this)); this.deployer.emitter.on( "startTransaction", this.startTransaction.bind(this) ); this.deployer.emitter.on( "endTransaction", this.endTransaction.bind(this) ); } } /** * Retrieves gas usage totals per migrations file / totals since the reporter * started running. Calling this method resets the gas counters for migrations totals */ getTotals() { const gas = this.currentGasTotal.clone(); const cost = YOUChainUtils.fromLu(this.currentCostTotal, "you"); this.finalCostTotal = this.finalCostTotal.add(this.currentCostTotal); this.currentGasTotal = new BN(0); this.currentCostTotal = new BN(0); return { gas: gas.toString(10), cost: cost, finalCost: YOUChainUtils.fromLu(this.finalCostTotal, "you"), deployments: this.deployments.toString() }; } /** * Queries the user for a true/false response and resolves the result. * @param {String} type identifier the reporter consumes to format query * @return {Promise} */ askBoolean(type) { const self = this; const question = this.messages.questions(type); const exitLine = this.messages.exitLines(type); // NB: We need direct access to a writeable stream here. // This ignores `quiet` - but we only use that mode for `youbox test`. const input = readline.createInterface({ input: process.stdin, output: process.stdout }); const affirmations = ["y", "yes", "YES", "Yes"]; return new Promise(resolve => { input.question(question, answer => { if (affirmations.includes(answer.trim())) { input.close(); return resolve(true); } input.close(); self.deployer && self.deployer.logger.log(exitLine); resolve(false); }); }); } /** * Error dispatcher. Parses the error returned from web3 and outputs a more verbose error after * doing what it can to evaluate the failure context from data passed to it. * @param {Object} data info collected during deployment attempt */ async processDeploymentError(data) { const error = data.estimateError || data.error; data.reason = data.error ? data.error.reason : null; const errors = { ETH: error.message.includes("funds"), OOG: error.message.includes("out of gas"), INT: error.message.includes("base fee") || error.message.includes("intrinsic"), RVT: error.message.includes("revert"), BLK: error.message.includes("block gas limit"), NCE: error.message.includes("nonce"), INV: error.message.includes("invalid opcode"), GTH: error.message.includes("always failing transaction") }; let type = Object.keys(errors).find(key => errors[key]); switch (type) { // `Intrinsic gas too low` case "INT": return data.gas ? this.messages.errors("intWithGas", data) : this.messages.errors("intNoGas", data); // `Out of gas` case "OOG": return data.gas && !(data.gas === data.blockLimit) ? this.messages.errors("intWithGas", data) : this.messages.errors("oogNoGas", data); // `Revert` case "RVT": return data.reason ? this.messages.errors("rvtReason", data) : this.messages.errors("rvtNoReason", data); // `Invalid opcode` case "INV": return data.reason ? this.messages.errors("asrtReason", data) : this.messages.errors("asrtNoReason", data); // `Exceeds block limit` case "BLK": return data.gas ? this.messages.errors("blockWithGas", data) : this.messages.errors("blockNoGas", data); // `Insufficient funds` case "ETH": const balance = await data.contract.interfaceAdapter.getBalance( data.from ); data.balance = balance.toString(); return this.messages.errors("noMoney", data); // `Invalid nonce` case "NCE": return this.messages.errors("nonce", data); // Generic geth error case "GTH": return this.messages.errors("geth", data); default: return this.messages.errors("default", data); } } // ---------------------------- Interaction Handlers --------------------------------------------- async acceptDryRun() { return this.askBoolean("acceptDryRun"); } // ------------------------- Migrator File Handlers -------------------------------------------- /** * Run when before any migration has started * @param {Object} data */ async preAllMigrations(data) { const message = this.messages.steps("preAllMigrations", data); this.migrator.logger.log(message); } /** * Run after all migrations have finished * @param {Object} data */ async postAllMigrations(data) { const message = this.messages.steps("postAllMigrations", data); this.migrator.logger.log(message); } // ------------------------- Migration File Handlers -------------------------------------------- /** * Run when a migrations file is loaded, before deployments begin * @param {Object} data */ async preMigrate(data) { let message; if (data.isFirst) { message = this.messages.steps("firstMigrate", data); this.deployer.logger.log(message); } this.summary.push({ file: data.file, number: data.number, deployments: [] }); this.currentFileIndex++; message = this.messages.steps("preMigrate", data); this.deployer.logger.log(message); } /** * Run after a migrations file has completed and the migration has been saved. * @param {Boolean} isLast true if this the last file in the sequence. */ async postMigrate(isLast) { let data = {}; data.number = this.summary[this.currentFileIndex].number; data.cost = this.getTotals().cost; this.summary[this.currentFileIndex].totalCost = data.cost; let message = this.messages.steps("postMigrate", data); this.deployer.logger.log(message); if (isLast) { data.totalDeployments = this.getTotals().deployments; data.finalCost = this.getTotals().finalCost; this.summary.totalDeployments = data.totalDeployments; this.summary.finalCost = data.finalCost; message = this.messages.steps("lastMigrate", data); this.deployer.logger.log(message); } } // ---------------------------- Deployment Handlers -------------------------------------------- /** * Runs after pre-flight estimate has executed, before the sendTx is attempted * @param {Object} data */ async preDeploy(data) { let message; data.deployed ? (message = this.messages.steps("replacing", data)) : (message = this.messages.steps("deploying", data)); !this.deployingMany && this.deployer.logger.log(message); } /** * Run at intervals after the sendTx has executed, before the deployment resolves * @param {Object} data */ async block(data) { this.currentBlockWait = `Blocks: ${data.blocksWaited}`.padEnd(21) + `Seconds: ${data.secondsWaited}`; if (this.blockSpinner) { this.blockSpinner.text = this.currentBlockWait; } } /** * Run after a deployment instance has resolved. This handler collects deployment cost * data and stores it a `summary` map so that it can later be replayed in an interactive * preview (e.g. dry-run --> real). Also passes this data to the messaging utility for * output formatting. * @param {Object} data */ async postDeploy(data) { let message; if (data.deployed) { const tx = await data.contract.interfaceAdapter.getTransaction( data.receipt.transactionHash ); const block = await data.contract.interfaceAdapter.getBlock( data.receipt.blockNumber ); // if geth returns null, try again! if (!block) return this.postDeploy(data); data.timestamp = block.timestamp; const balance = await data.contract.interfaceAdapter.getBalance(tx.from); const gasPrice = new BN(tx.gasPrice); const gas = new BN(data.receipt.gasUsed); const value = new BN(tx.value); const cost = gasPrice.mul(gas).add(value); data.gasPrice = YOUChainUtils.fromLu(gasPrice, "glu"); data.gas = gas.toString(10); data.from = tx.from; data.value = YOUChainUtils.fromLu(value, "you"); data.cost = YOUChainUtils.fromLu(cost, "you"); data.balance = YOUChainUtils.fromLu(balance, "you"); this.currentGasTotal = this.currentGasTotal.add(gas); this.currentCostTotal = this.currentCostTotal.add(cost); this.currentAddress = this.from; this.deployments++; if (this.summary[this.currentFileIndex]) { this.summary[this.currentFileIndex].deployments.push(data); } message = this.messages.steps("deployed", data); } else { message = this.messages.steps("reusing", data); } this.deployer.logger.log(message); } /** * Runs on deployment error. Forwards err to the error parser/dispatcher after shutting down * any `pending` UI.any `pending` UI. Returns the error message OR logs it out from the reporter * if data.log is true. * @param {Object} data event args * @return {Promise} resolves string error message */ async deployFailed(data) { if (this.blockSpinner) { this.blockSpinner.stop(); } const message = await this.processDeploymentError(data); return data.log ? this.deployer.logger.error(message) : message; } // -------------------------- Transaction Handlers ------------------------------------------ /** * Run on `startTransaction` event. This is fired by migrations on save * but could also be fired within a migrations script by a user. * @param {Object} data */ async startTransaction(data) { const message = data.message || "Starting unknown transaction..."; this.deployer.logger.log(); this.blockSpinner = new ora({ text: message, spinner: indentedSpinner, color: "red" }); this.blockSpinner.start(); } /** * Run after a start transaction * @param {Object} data */ async endTransaction(data) { data.message = data.message || "Ending unknown transaction...."; const message = this.messages.steps("endTransaction", data); this.deployer.logger.log(message); } // ---------------------------- Library Event Handlers ------------------------------------------ linking(data) { let message = this.messages.steps("linking", data); this.deployer.logger.log(message); } // ---------------------------- PromiEvent Handlers -------------------------------------------- /** * For misc error reporting that requires no context specific UI mgmt * @param {Object} data */ async error(data) { const message = this.messages.errors(data.type, data); return data.log ? this.deployer.logger.error(message) : message; } /** * Fired on Web3Promievent 'transactionHash' event. Begins running a UI * a block / time counter. * @param {Object} data */ async hash(data) { if (this.migration.dryRun) return; let message = this.messages.steps("hash", data); this.deployer.logger.log(message); this.currentBlockWait = `Blocks: 0`.padEnd(21) + `Seconds: 0`; this.blockSpinner = new ora({ text: this.currentBlockWait, spinner: indentedSpinner, color: "red" }); this.blockSpinner.start(); } /** * Fired on Web3Promievent 'confirmation' event. * @param {Object} data */ async confirmation(data) { let message = this.messages.steps("confirmation", data); this.deployer.logger.log(message); } }
JavaScript
class ResetPassword extends Component { constructor(props){ super(props) this.state={ toastStyle: "toast" } } componentWillReceiveProps(nextProps) { this.props = {...nextProps}; } resetPassword = ()=>{ } storeCredentials = (e)=>{ this.setState({ [e.target.id]: e.target.value }); } render(){ return( <div className="wrapper"> <MuiThemeProvider muiTheme={getMuiTheme()}> <AppBar onRightIconButtonClick = { this.props.toggleDrawerState } iconElementRight={<i className="material-icons menu">menu</i>} showMenuIconButton={ false } title = "Réinitialiser le mot de passer" /> <div className={ this.state.toastStyle }>{ this.state.message }</div> <Drawer containerClassName="menu-drawer" docked={ true } zDepth = { 1000 } open={ this.props.drawerOpen } > <span id="login" onClick={ this.props.changeUserScreen }>S'identifier</span> <Divider /> <span id="register" onClick={ this.props.changeUserScreen }>Registre</span> <Divider /> <span id="reset" onClick={ this.props.changeUserScreen }>Réinitialiser le mot de passe</span> </Drawer> <TextField id="email" fullWidth = { true } hintText="[email protected]" floatingLabelText="Adresse e-mail" value = { this.state.email } floatingLabelFixed={true} onChange={this.storeCredentials} type="email" > </TextField><br/> <RaisedButton primary={true} fullWidth = {true} onClick={this.resetPassword} label="Réinitialiser le mot de passe" /> </MuiThemeProvider> </div> ) } }
JavaScript
class Products { constructor ({ httpClient }) { this.url = '/products'; this.__httpClient = httpClient; } /** * Get all the products. * @param {Object} options - The parameters to provider the API. * @param {Object} [options.params] - The query params for the API. * @link https://dvs-api-doc.dtone.com/#tag/Products/paths/~1products/get * @returns {AsyncIterator.<DVSAPIResponse>} */ get ({ params }) { return this.__httpClient.getWithPages({ params, url: this.url }); } /** * Get a product by its ID. * @param {Object} options - The parameters to provider the API. * @param {number} [options.productId] - The product ID. * @link https://dvs-api-doc.dtone.com/#tag/Products/paths/~1products~1{product_id}/get * @returns {Promise.<DVSAPIResponse>} */ async getByProductId ({ productId }) { const url = `${this.url}/${productId}`; return this.__httpClient.get({ url }); } }
JavaScript
class LiveOrderbook extends stream_1.Duplex { constructor(config) { super({ objectMode: true, highWaterMark: 1024 }); this.product = config.product; [this.baseCurrency, this.quoteCurrency] = this.product.split('-'); this.logger = config.logger; this._book = new BookBuilder_1.BookBuilder(this.logger); this.liveTicker = { productId: config.product, price: undefined, bid: undefined, ask: undefined, volume: types_1.ZERO, time: undefined, trade_id: undefined, size: undefined }; this.strictMode = config.strictMode; this.snapshotReceived = false; } log(level, message, meta) { if (!this.logger) { return; } this.logger.log(level, message, meta); } get sourceSequence() { return this._sourceSequence; } get numAsks() { return this._book.numAsks; } get numBids() { return this._book.numBids; } get bidsTotal() { return this._book.bidsTotal; } get asksTotal() { return this._book.asksTotal; } state() { return this._book.state(); } get book() { return this._book; } get ticker() { return this.liveTicker; } get sequence() { return this._book.sequence; } /** * The time (in seconds) since the last ticker update */ get timeSinceTickerUpdate() { const time = this.ticker.time ? this.ticker.time.valueOf() : 0; return (Date.now() - time); } /** * The time (in seconds) since the last orderbook update */ get timeSinceOrderbookUpdate() { const time = this.lastBookUpdate ? this.lastBookUpdate.valueOf() : 0; return (Date.now() - time); } /** * Return an array of (aggregated) orders whose sum is equal to or greater than `value`. The side parameter is from * the perspective of the purchaser, so 'buy' returns asks and 'sell' bids. */ ordersForValue(side, value, useQuote, startPrice) { return this._book.ordersForValue(side, types_1.Big(value), useQuote, startPrice); } _read() { } _write(msg, _encoding, callback) { // Pass the msg on to downstream users this.push(msg); // Process the message for the orderbook state if (msg.productId !== this.product) { return callback(); } if (!Messages_1.isStreamMessage(msg)) { return callback(); } switch (msg.type) { case 'ticker': this.updateTicker(msg); // ticker is emitted in pvs method break; case 'snapshot': this.processSnapshot(msg); break; case 'level': this.processLevelChange(msg); this.emit('LiveOrderbook.update', msg); break; case 'trade': // Trade messages don't affect the orderbook this.emit('LiveOrderbook.trade', msg); break; case 'newOrder': case 'orderDone': case 'changedOrder': this.processLevel3Messages(msg); this.emit('LiveOrderbook.update', msg); break; case 'cancelOrder': case 'error': case 'myOrderPlaced': case 'placeOrder': case 'tradeExecuted': case 'tradeFinalized': case 'unknown': break; default: asserts_1.staticAssertNever(msg); break; } callback(); } /** * Checks the given sequence number against the expected number for a message and returns a status result */ checkSequence(sequence) { if (sequence <= this.sequence) { return SequenceStatus.ALREADY_PROCESSED; } if (sequence !== this.sequence + 1) { // Dropped a message, restart the synchronising this.log('info', `Dropped a message. Expected ${this.sequence + 1} but received ${sequence}.`); const event = { expected_sequence: this.sequence + 1, sequence: sequence }; const diff = event.expected_sequence - event.sequence; if (this.strictMode) { const msg = `LiveOrderbook detected a skipped message. Expected ${event.expected_sequence}, but received ${event.sequence}. Diff = ${diff}`; throw new Error(msg); } this.emit('LiveOrderbook.skippedMessage', event); return SequenceStatus.SKIP_DETECTED; } this.lastBookUpdate = new Date(); this._book.sequence = sequence; return SequenceStatus.OK; } updateTicker(tickerMessage) { const ticker = this.liveTicker; ticker.price = tickerMessage.price; ticker.bid = tickerMessage.bid; ticker.ask = tickerMessage.ask; ticker.volume = tickerMessage.volume; ticker.time = tickerMessage.time; ticker.trade_id = tickerMessage.trade_id; ticker.size = tickerMessage.size; this.emit('LiveOrderbook.ticker', ticker); } processSnapshot(snapshot) { this._book.fromState(snapshot); this._sourceSequence = snapshot.sourceSequence; this.snapshotReceived = true; this.emit('LiveOrderbook.snapshot', snapshot); } /** * Handles order messages from aggregated books * @param msg */ processLevelChange(msg) { if (!msg.sequence) { return; } this._sourceSequence = msg.sourceSequence; const sequenceStatus = this.checkSequence(msg.sequence); if (sequenceStatus === SequenceStatus.ALREADY_PROCESSED) { return; } const level = BookBuilder_1.AggregatedLevelFactory(msg.size, msg.price, msg.side); this._book.setLevel(msg.side, level); } /** * Processes order messages from order-level books. */ processLevel3Messages(message) { // Can't do anything until we get a snapshot if (!this.snapshotReceived || !message.sequence) { return; } const sequenceStatus = this.checkSequence(message.sequence); if (sequenceStatus === SequenceStatus.ALREADY_PROCESSED) { return; } this._sourceSequence = message.sourceSequence; switch (message.type) { case 'newOrder': this.processNewOrderMessage(message); break; case 'orderDone': this.processDoneMessage(message); break; case 'changedOrder': this.processChangedOrderMessage(message); break; default: asserts_1.staticAssertNever(message); break; } } processNewOrderMessage(msg) { const order = { id: msg.orderId, size: types_1.Big(msg.size), price: types_1.Big(msg.price), side: msg.side }; if (!(this._book.add(order))) { this.emitError(msg); } } processDoneMessage(msg) { // If we're using an order pool, then we only remove orders that we're aware of. GDAX, for example might // send a done message for a stop order that is cancelled (and was not previously known to us). // Also filled orders will already have been removed by the time a GDAX done order reaches here if (!this._book.hasOrder(msg.orderId)) { return; } if (!(this._book.remove(msg.orderId))) { this.emitError(msg); } } processChangedOrderMessage(msg) { if (!msg.newSize && !msg.changedAmount) { return; } let newSize; const newSide = msg.side; if (msg.changedAmount) { const order = this.book.getOrder(msg.orderId); newSize = order.size.plus(msg.changedAmount); } else { newSize = types_1.Big(msg.newSize); } if (!(this._book.modify(msg.orderId, newSize, newSide))) { this.emitError(msg); } } emitError(message) { const err = new Error('An inconsistent orderbook state occurred'); err.msg = message; this.log('error', err.message, { message: message }); this.emit('error', err); } }
JavaScript
class SqLiteSequenceGenerator { constructor() { this.sequences = []; this.sequenceBlocks = []; this.generatingSequenceNumbers = false; } exists(dbEntity) { const generatedColumns = dbEntity.columns.filter(dbColumn => dbColumn.isGenerated); if (!generatedColumns.length) { return true; } const schemaSequences = this.sequences[dbEntity.schemaVersion.schema.index]; if (!schemaSequences) { return false; } const tableSequences = schemaSequences[dbEntity.index]; if (!tableSequences) { return false; } return generatedColumns.every(dbColumn => !!tableSequences[dbColumn.index]); } async initialize(sequences) { const sequenceDao = await container(this).get(SEQUENCE_DAO); if (!sequences) { sequences = await sequenceDao.findAll(); } this.addSequences(sequences); await sequenceDao.incrementCurrentValues(); setSeqGen(this); } async tempInit(sequences) { this.addSequences(sequences); setSeqGen(this); } async generateSequenceNumbers(dbColumns, numSequencesNeeded) { if (!dbColumns.length) { return []; } await this.waitForPreviousGeneration(); this.generatingSequenceNumbers = true; try { return await this.doGenerateSequenceNumbers(dbColumns, numSequencesNeeded); } finally { this.generatingSequenceNumbers = false; } } /** * Keeping return value as number[][] in case we ever revert back * to SequenceBlock-like solution * @param dbColumns * @param numSequencesNeeded */ async doGenerateSequenceNumbers(dbColumns, numSequencesNeeded) { const sequentialNumbers = []; const sequenceDao = await container(this).get(SEQUENCE_DAO); for (let i = 0; i < dbColumns.length; i++) { const dbColumn = dbColumns[i]; let numColumnSequencesNeeded = numSequencesNeeded[i]; const columnNumbers = ensureChildArray(sequentialNumbers, i); const dbEntity = dbColumn.propertyColumns[0].property.entity; const schema = dbEntity.schemaVersion.schema; let sequenceBlock = this.sequenceBlocks[schema.index][dbEntity.index][dbColumn.index]; const sequence = this.sequences[schema.index][dbEntity.index][dbColumn.index]; while (numColumnSequencesNeeded && sequenceBlock) { columnNumbers.push(sequence.currentValue - sequenceBlock + 1); numColumnSequencesNeeded--; sequenceBlock--; } if (numColumnSequencesNeeded) { const numNewSequencesNeeded = sequence.incrementBy + numColumnSequencesNeeded; const newSequence = { ...sequence }; newSequence.currentValue += numNewSequencesNeeded; await sequenceDao.save(newSequence); this.sequences[schema.index][dbEntity.index][dbColumn.index] = newSequence; sequenceBlock = numNewSequencesNeeded; while (numColumnSequencesNeeded) { columnNumbers.push(sequence.currentValue - sequenceBlock + 1); numColumnSequencesNeeded--; sequenceBlock--; } this.sequenceBlocks[schema.index][dbEntity.index][dbColumn.index] = sequenceBlock; } } return sequentialNumbers; } async waitForPreviousGeneration() { return new Promise(resolve => { this.isDoneGeneratingSeqNums(resolve); }); } isDoneGeneratingSeqNums(resolve) { if (this.generatingSequenceNumbers) { setTimeout(() => { this.isDoneGeneratingSeqNums(resolve); }, 20); } else { resolve(); } } addSequences(sequences) { for (const sequence of sequences) { ensureChildArray(ensureChildArray(this.sequences, sequence.schemaIndex), sequence.tableIndex)[sequence.columnIndex] = sequence; sequence.currentValue += sequence.incrementBy; ensureChildArray(ensureChildArray(this.sequenceBlocks, sequence.schemaIndex), sequence.tableIndex)[sequence.columnIndex] = sequence.incrementBy; } } }
JavaScript
class Alert extends Model { /** * Construct Alert Model class */ constructor () { // Run super super(...arguments); // Bind public methods this.sanitise = this.sanitise.bind(this); } /** * Create indexes on Alert */ static async initialize () { // Create indexes await this.createIndex('done', { 'done' : -1 }); } /** * Sanitise Alert * * @return {object} */ async sanitise () { // Check arguments if (arguments && arguments.length) { // Return sanitised with arguments return await super.__sanitiseModel(...arguments); } // Return sanitised with default return await super.__sanitiseModel({ 'field' : '_id', 'sanitisedField' : 'id', 'default' : false }, { 'field' : 'type', 'default' : 'info' }, { 'field' : 'opts', 'default' : '' }); } }
JavaScript
class JordanIdFrontRecognizerResult extends RecognizerResult { constructor(nativeResult) { super(nativeResult.resultState); /** * The Date Of Birth of the Jordan ID owner. */ this.dateOfBirth = nativeResult.dateOfBirth != null ? new Date(nativeResult.dateOfBirth) : null; /** * face image from the document if enabled with returnFaceImage property. */ this.faceImage = nativeResult.faceImage; /** * full document image if enabled with returnFullDocumentImage property. */ this.fullDocumentImage = nativeResult.fullDocumentImage; /** * The Name of the Jordan ID owner. */ this.name = nativeResult.name; /** * The National Number of the Jordan ID. */ this.nationalNumber = nativeResult.nationalNumber; /** * The Sex of the Jordan ID owner. */ this.sex = nativeResult.sex; } }
JavaScript
class JordanIdFrontRecognizer extends Recognizer { constructor() { super('JordanIdFrontRecognizer'); /** * Defines if glare detection should be turned on/off. * * */ this.detectGlare = true; /** * Defines if owner's date of birth should be extracted from Jordan ID * * */ this.extractDateOfBirth = true; /** * Defines if owner's name should be extracted from Jordan ID * * */ this.extractName = true; /** * Defines if owner's sex should be extracted from Jordan ID * * */ this.extractSex = true; /** * Property for setting DPI for full document images * Valid ranges are [100,400]. Setting DPI out of valid ranges throws an exception * * */ this.fullDocumentImageDpi = 250; /** * Sets whether face image from ID card should be extracted * * */ this.returnFaceImage = false; /** * Sets whether full document image of ID card should be extracted. * * */ this.returnFullDocumentImage = false; this.createResultFromNative = function (nativeResult) { return new JordanIdFrontRecognizerResult(nativeResult); } } }
JavaScript
class RichEditor extends React.Component { /** * Check if the current selection has a mark with `type` in it. * * @param {String} type * @return {Boolean} */ hasMark = type => { const { value } = this.props; return value.activeMarks.some(mark => mark.type === type); }; /** * Check if the any of the currently selected blocks are of `type`. * * @param {String} type * @return {Boolean} */ hasBlock = type => { const { value } = this.props; return value.blocks.some(node => node.type === type); }; /** * Store a reference to the `editor`. * * @param {Editor} editor */ ref = editor => { this.editor = editor; }; /** * Render. * * @return {Element} */ render() { return ( <div style={{ width: "80%", display: "flex", flexDirection: "column", margin: "0 auto" }} > <Toolbar> {this.renderMarkButton("bold", FormatBold)} {this.renderMarkButton("italic", FormatItalic)} {this.renderMarkButton("underlined", FormatUnderlined)} {this.renderMarkButton("code", Code)} {this.renderBlockButton("title", Title)} {this.renderBlockButton("block-quote", FormatQuote)} {this.renderBlockButton("numbered-list", FormatListNumbered)} {this.renderBlockButton("bulleted-list", FormatListBulleted)} </Toolbar> <Editor spellCheck autoFocus placeholder="Enter some rich text..." ref={this.ref} style={{ height: "50vh" }} value={this.props.value} onChange={this.onChange} onKeyDown={this.onKeyDown} renderNode={renderNode} renderMark={renderMark} /> </div> ); } /** * Render a mark-toggling toolbar button. * * @param {String} type * @param {String} icon * @return {Element} */ renderMarkButton = (type, IconComponent) => { const isActive = this.hasMark(type); return ( <Button active={isActive} onMouseDown={event => this.onClickMark(event, type)} > <IconComponent /> </Button> ); }; /** * Render a block-toggling toolbar button. * * @param {String} type * @param {String} icon * @return {Element} */ renderBlockButton = (type, IconComponent) => { let isActive = this.hasBlock(type); if (["numbered-list", "bulleted-list"].includes(type)) { const { value: { document, blocks } } = this.props; if (blocks.size > 0) { const parent = document.getParent(blocks.first().key); isActive = this.hasBlock("list-item") && parent && parent.type === type; } } return ( <Button active={isActive} onMouseDown={event => this.onClickBlock(event, type)} > <IconComponent /> </Button> ); }; /** * On change, save the new `value`. * * @param {Editor} editor */ onChange = ({ value }) => { this.props.onChange(value); }; /** * On key down, if it's a formatting command toggle a mark. * * @param {Event} event * @param {Editor} editor * @return {Change} */ onKeyDown = (event, editor, next) => { let mark; if (isBoldHotkey(event)) { mark = "bold"; } else if (isItalicHotkey(event)) { mark = "italic"; } else if (isUnderlinedHotkey(event)) { mark = "underlined"; } else if (isCodeHotkey(event)) { mark = "code"; } else { return next(); } event.preventDefault(); editor.toggleMark(mark); }; /** * When a mark button is clicked, toggle the current mark. * * @param {Event} event * @param {String} type */ onClickMark = (event, type) => { event.preventDefault(); this.editor.toggleMark(type); }; /** * When a block button is clicked, toggle the block type. * * @param {Event} event * @param {String} type */ onClickBlock = (event, type) => { event.preventDefault(); const { editor } = this; const { value } = editor; const { document } = value; // Handle everything but list buttons. if (type !== "bulleted-list" && type !== "numbered-list") { const isActive = this.hasBlock(type); const isList = this.hasBlock("list-item"); if (isList) { editor .setBlocks(isActive ? DEFAULT_NODE : type) .unwrapBlock("bulleted-list") .unwrapBlock("numbered-list"); } else { editor.setBlocks(isActive ? DEFAULT_NODE : type); } } else { // Handle the extra wrapping required for list buttons. const isList = this.hasBlock("list-item"); const isType = value.blocks.some(block => { return !!document.getClosest(block.key, parent => parent.type === type); }); if (isList && isType) { editor .setBlocks(DEFAULT_NODE) .unwrapBlock("bulleted-list") .unwrapBlock("numbered-list"); } else if (isList) { editor .unwrapBlock( type === "bulleted-list" ? "numbered-list" : "bulleted-list" ) .wrapBlock(type); } else { editor.setBlocks("list-item").wrapBlock(type); } } }; }
JavaScript
class HederaReceiptStatusError extends HederaStatusError_1.HederaStatusError { constructor(status, receipt, transactionId) { super(status); this.transactionId = transactionId; this.receipt = receipt; this.name = "HederaReceiptStatusError"; this.message = `Received receipt for transaction ${this.transactionId} with exceptional status: ${this.status}`; } static _throwIfError(code, receipt, transactionId) { const status = Status_1.Status._fromCode(code); if (status._isError()) { throw new HederaReceiptStatusError(status, receipt, transactionId); } } }
JavaScript
class MiradorViewer { /** */ constructor(config, viewerConfig = {}) { this.config = config; this.plugins = filterValidPlugins(viewerConfig.plugins || []); this.store = viewerConfig.store || createStore(getReducersFromPlugins(this.plugins), getSagasFromPlugins(this.plugins)); this.processConfig(); ReactDOM.render( <Provider store={this.store}> <HotApp plugins={this.plugins} /> </Provider>, document.getElementById(config.id), ); } /** * Process config with plugin configs into actions */ processConfig() { this.store.dispatch( importConfig( deepmerge(getConfigFromPlugins(this.plugins), this.config), ), ); } /** * Cleanup method to unmount Mirador from the dom */ unmount() { ReactDOM.unmountComponentAtNode(document.getElementById(this.config.id)); } }
JavaScript
class CreateJob extends React.Component { constructor(props) { super(props); let today = new Date(); let tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); this.state = { jobname: "", active: 0, secure: "all", jobStart: this.formatDateString(today), jobStop: this.formatDateString(tomorrow), protocol: "", host: "", uri: "", sourceip: "", method: "", statusCode: -1 //-1 indicates no requests have been issued to the backend // 0 indicates a request has been issued and a response is being awaited. //200 indicates job creation is succesful //400 indicates job creation is not succesful because of jobname conflicts. }; } formatDateString = date => { const offset = date.getTimezoneOffset(); let dateString = new Date(date.getTime() + offset * 60 * 1000); return dateString.toISOString().split("T")[0]; }; parseDate = s => { var b = s.split(/\D/); return new Date(b[0], --b[1], b[2]); }; onChangeDateCheck = (inputName, stateValue) => { let parsedStateValue = Date.parse(stateValue); let parsedTodayValue = Date.parse(new Date()); switch (inputName) { case "jobStart": if ( parsedStateValue < Date.parse(this.state.jobStop) && parsedStateValue >= parsedTodayValue ) this.setState({ jobStart: stateValue }); break; case "jobStop": if ( parsedStateValue > Date.parse(this.state.jobStart) && parsedStateValue > parsedTodayValue ) this.setState({ jobStop: stateValue }); break; } }; onChange(e) { let inputName = e.target.name; let stateValue = e.target.value; let checkboxValue = e.target.checked; switch (inputName) { case "jobname": this.setState({ jobname: stateValue }); break; case "jobStart": this.onChangeDateCheck(inputName, stateValue); break; case "jobStop": this.onChangeDateCheck(inputName, stateValue); break; case "secure": this.setState({ secure: stateValue }); break; case "protocol": this.setState({ protocol: stateValue }); break; case "host": this.setState({ host: stateValue }); break; case "uri": this.setState({ uri: stateValue }); break; case "sourceip": this.setState({ sourceip: stateValue }); break; case "statusCode": this.setState({ statusCode: Number(stateValue) }); break; case "method": this.setState({ method: stateValue }); break; } } buildForm = () => { let form = null; // This function builds a dynamic form. if (this.state.statusCode === -1) { let keys = Object.keys(this.state); form = keys.map(key => { //Never give the user the ability to set jobId //return null in that case if (key === "secure") { return ( <section className="col-12 col-md-6"> <h6>{nameMapper[key]}</h6> <select name={key} type="text" value={this.state[key]} onChange={e => this.onChange(e)} placeholder={placeholderValues[key]} > <option>all</option> <option>secure</option> <option>insecure</option> </select> </section> ); } else if (key === "jobStart" || key === "jobStop") { return ( <section className="col-12 col-md-6"> <h6>{nameMapper[key]}</h6> <input name={key} type="date" value={this.state[key]} onChange={e => this.onChange(e)} placeholder={placeholderValues[key]} /> </section> ); } else if (key !== "statusCode" && key !== "active") return ( <section className="col-12 col-md-6"> <h6>{nameMapper[key]}</h6> <input name={key} type="text" value={this.state[key]} onChange={e => this.onChange(e)} placeholder={placeholderValues[key]} /> </section> ); }); } else if (this.state.statusCode === 0) { form = ( <section className="spinner-grow text-success" role="status"> {" "} <span class="sr-only">Job is scheduling...</span> </section> ); } else if (this.state.statusCode === 200) { let stateKeys = Object.keys(this.state); form = ( <section> <h2>Job Creation Succesful</h2> <section className="container"></section> { <table className="table"> <thead> <tr> <th scope="col">Job Property Name</th> <th scope="col"> Job Property Value</th> </tr> {stateKeys.map(key => { if (key !== "statusCode") { return ( <tr> <td>{key}</td> <td>{this.state[key] || "empty field submitted"}</td> </tr> ); } else return null; })} </thead> </table> } <section className="container"></section> </section> ); } else if (this.state.statusCode === 404) { form = ( <section className="container card"> <h3 className="card-header">Internal Server Error</h3> <div className="card-body"> Internal Server Error encountered. Please try again later. </div> </section> ); } return form; }; onClick = () => { if (this.state.jobname !== "") { this.setState({ statusCode: 0 }); fetch("http://ec2-54-152-230-158.compute-1.amazonaws.com:7999/api/createJob", { method: "POST", headers: { "Content-Type": "application/json" }, body: this.onClickStateFormat() }).then(resp => { if (resp.status === 200) { this.setState({ statusCode: 200 }); } else if (resp.statusCode === 400) { this.setState({ statusCode: 400 }); } else { this.setState({ statusCode: 404 }); } }); } }; onClickStateFormat = () => { let json = { jobname: this.state.jobname, active: 0, jobStart: Date.parse(this.state.jobStart)/1000, jobStop: Date.parse(this.state.jobStop)/1000, secure: regExpMapper[this.state.secure], protocol: this.state.protocol, host: this.state.host, uri: this.state.uri, method: this.state.method, sourceip: this.state.sourceip }; return JSON.stringify(json); }; buildButton = () => { let retButton = ( <button class="btn btn-primary" type="button" name="pending" onClick={e => this.onClick(e)} > Create Job </button> ); if (this.state.statusCode === 0) { retButton = ( <button class="btn btn-primary" type="button" disabled> <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true" ></span> Creating Job... </button> ); } else if (this.state.statusCode === 200) { retButton = ( <button class="btn btn-primary" type="button" onClick={() => { this.setState({ jobname: "", // active: 0, jobStart: "", jobStop: "", secure: "", protocol: "", host: "", uri: "", method: "", sourceip: "", statusCode: -1 }); }} > Create Another Job </button> ); } else if (this.state.statusCode === 400 || this.state.statusCode === 404) { retButton = ( <button class="btn btn-primary" type="button" onClick={() => { this.setState({ statusCode: -1 }); }} > Retry </button> ); } return retButton; }; render = () => { // This function builds a dynamic form. let retVal = ( <div className="card"> <h3 className="card-header bg-success text-light"> //Schedule A Traffic Recording(); </h3> <section className="card-body container"> {this.state.statusCode === 400 ? ( //if 400 is returned as the error code, render the error notification. <ErrorMsg msg="The entered jobname must be unique." /> ) : null} {this.state.jobname === "" && this.state.statusCode === -1 ? ( //if 400 is returned as the error code, render the error notification. <ErrorMsg msg="The jobname is empty. This is a required field.Unable to dispatch request." header="Error" className="bg-danger" /> ) : null} <section class="card col-12 mx-0 px-0"> <div className="card-header bg-success"> Use Regex 101 to help build regex input values. Regex needs to be formatted into PCRE(PHP) format. </div> <a className="card-body" target="_blank" href="https://regex101.com/" > Link to regex101 </a> </section> <section class="row">{this.buildForm()}</section> <br></br> <section className="row">{this.buildButton()}</section> </section> </div> ); return retVal; }; }
JavaScript
class Statistics { static stdev(x, avg) { const count = x.length; let dev = 0; if (count <= 1) { return 0; } let i = 0; while (i < count) { dev += Math.pow(x[i] - avg, 2); ++i; } return Math.sqrt(dev / (count - 1)); } static average(values, prevSum, prevCount) { const half = Math.ceil(values.length * 0.35); const low = Math.ceil(values.length * 0.15); const valid = []; if (values.length == 0) { console.log('values length is zero'); return [0, 0, 0, 0]; } let results = []; values.sort((a,b) => a - b); results = values; let prev = 0; let sum = 0; let mina = results[0]; let count = 0; let i = 0; while (i < half) { if (i <= low || results[i] < prev * 1.2) { prev = results[i]; sum += results[i]; valid.push(results[i]); } ++i; } count = valid.length; if (count == 0) { return [0, 0, 0, 0]; } let avg = Math.round(sum / count); let std = 0; std = Statistics.stdev(valid, avg); std = Math.round(std); let minValue = Math.round(avg - std * 1.5); let maxValue = Math.round(avg + std * 1.5); let num = 0; let lastSum = sum; sum = 0; i = 0; while (i < count) { const v = valid[i]; if (v >= minValue && v <= maxValue) { sum += v; num += 1; } ++i; } if (num === 0) { sum = lastSum; num = count; } avg = Math.round((sum + prevSum) / (num + prevCount)); return [mina, avg, sum, num]; } static averageValues(x) { let sum = 0; for(let i = 0; i < x.length; ++i) { sum += x[i]; } return Math.round(sum / Math.max(x.length, 1)); } static averagePrevious(x, start, count) { let end = start - count; let c = 0; let sum = 0; for (let i = start; i >= end; --i) { if (i < 0) { let ri = x.length + i; if (ri >= 0 && ri < x.length) { sum += x[ri]; ++c; } } else { if (i < x.length) { sum += x[i]; ++c; } } } c = c <= 0 ? 1 : c; return Math.round(sum / c); } static min(values) { values.sort((a,b) => a - b); return values[0]; } }
JavaScript
class TilemapVisibility { constructor(shadowLayer) { this.shadowLayer = shadowLayer; this.activeRoom = null; } setActiveRoom(room) { // We only need to update the tiles if the active room has changed if (room !== this.activeRoom) { this.setRoomAlpha(room, 0); // Make the new room visible if (this.activeRoom) this.setRoomAlpha(this.activeRoom, 0.5); // Dim the old room this.activeRoom = room; } } // Helper to set the alpha on all tiles within a room to reduce opaqueness setRoomAlpha(room, alpha) { this.shadowLayer.forEachTile( (t) => (t.alpha = alpha), this, room.x, room.y, room.width, room.height ); } }
JavaScript
class Image { /** * Removes data attributes from an image. * @param {HTMLImageElement} img - Image where remove data attributes. */ static removeImgDataAttributes(img) { const attributesToRemove = []; const { attributes } = img; Object.keys(attributes).forEach((key) => { const attribute = attributes[key]; if (attribute !== undefined && attribute.name !== undefined && attribute.name.indexOf('data-') === 0) { // Is preferred keep an array and remove after the search // because when attribute is removed the array of attributes // is modified. attributesToRemove.push(attribute.name); } }); attributesToRemove.forEach((attribute) => { img.removeAttribute(attribute); }); } /** * @static * Clones all MathType image attributes from a HTMLImageElement to another. * @param {HTMLImageElement} originImg - The original image. * @param {HTMLImageElement} destImg - The destination image. */ static clone(originImg, destImg) { const customEditorAttributeName = Configuration.get('imageCustomEditorName'); if (!originImg.hasAttribute(customEditorAttributeName)) { destImg.removeAttribute(customEditorAttributeName); } const mathmlAttributeName = Configuration.get('imageMathmlAttribute'); const imgAttributes = [ mathmlAttributeName, customEditorAttributeName, 'alt', 'height', 'width', 'style', 'src', 'role', ]; imgAttributes.forEach((iterator) => { const originAttribute = originImg.getAttribute(iterator); if (originAttribute) { destImg.setAttribute(iterator, originAttribute); } }); } /** * Calculates the metrics of a MathType image given the the service response and the image format. * @param {HTMLImageElement} img - The HTMLImageElement. * @param {String} uri - The URI generated by the image service: can be a data URI scheme or a URL. * @param {Boolean} jsonResponse - True the response of the image service is a * JSON object. False otherwise. */ static setImgSize(img, uri, jsonResponse) { let ar; let base64String; let bytes; let svgString; if (jsonResponse) { // Cleaning data:image/png;base64. if (Configuration.get('imageFormat') === 'svg') { // SVG format. // If SVG is encoded in base64 we need to convert the base64 bytes into a SVG string. if (Configuration.get('saveMode') !== 'base64') { ar = Image.getMetricsFromSvgString(uri); } else { base64String = img.src.substr(img.src.indexOf('base64,') + 7, img.src.length); svgString = ''; bytes = Util.b64ToByteArray(base64String, base64String.length); for (let i = 0; i < bytes.length; i += 1) { svgString += String.fromCharCode(bytes[i]); } ar = Image.getMetricsFromSvgString(svgString); } // PNG format: we store all metrics information in the first 88 bytes. } else { base64String = img.src.substr(img.src.indexOf('base64,') + 7, img.src.length); bytes = Util.b64ToByteArray(base64String, 88); ar = Image.getMetricsFromBytes(bytes); } // Backwards compatibility: we store the metrics into createimage response. } else { ar = Util.urlToAssArray(uri); } let width = ar.cw; if (!width) { return; } let height = ar.ch; let baseline = ar.cb; const { dpi } = ar; if (dpi) { width = width * 96 / dpi; height = height * 96 / dpi; baseline = baseline * 96 / dpi; } img.width = width; img.height = height; img.style.verticalAlign = `-${height - baseline}px`; } /** * Calculates the metrics of an image which has been resized. Is used to restore the original * metrics of a resized image. * @param {HTMLImageElement } img - The resized HTMLImageElement. */ static fixAfterResize(img) { img.removeAttribute('style'); img.removeAttribute('width'); img.removeAttribute('height'); // In order to avoid resize with max-width css property. img.style.maxWidth = 'none'; if (img.src.indexOf('data:image') !== -1) { if (Configuration.get('imageFormat') === 'svg') { // ...data:image/svg+xml;charset=utf8, = 32. const svg = decodeURIComponent(img.src.substring(32, img.src.length)); Image.setImgSize(img, svg, true); } else { // ...data:image/png;base64, == 22. const base64 = img.src.substring(22, img.src.length); Image.setImgSize(img, base64, true); } } else { Image.setImgSize(img, img.src); } } /** * Returns the metrics (height, width and baseline) contained in a SVG image generated * by the MathType image service. This image contains as an extra custom attribute: * the baseline (wrs:baseline). * @param {String} svgString - The SVG image. * @return {Array} - The image metrics. */ static getMetricsFromSvgString(svgString) { let first = svgString.indexOf('height="'); let last = svgString.indexOf('"', first + 8, svgString.length); const height = svgString.substring(first + 8, last); first = svgString.indexOf('width="'); last = svgString.indexOf('"', first + 7, svgString.length); const width = svgString.substring(first + 7, last); first = svgString.indexOf('wrs:baseline="'); last = svgString.indexOf('"', first + 14, svgString.length); const baseline = svgString.substring(first + 14, last); if (typeof width !== 'undefined') { const arr = []; arr.cw = width; arr.ch = height; if (typeof baseline !== 'undefined') { arr.cb = baseline; } return arr; } return []; } /** * Returns the metrics (width, height, baseline and dpi) contained in a PNG byte array. * @param {Array.<Bytes>} bytes - png byte array. * @return {Array} The png metrics. */ static getMetricsFromBytes(bytes) { Util.readBytes(bytes, 0, 8); let width; let height; let typ; let baseline; let dpi; while (bytes.length >= 4) { typ = Util.readInt32(bytes); if (typ === 0x49484452) { width = Util.readInt32(bytes); height = Util.readInt32(bytes); // Read 5 bytes. Util.readInt32(bytes); Util.readByte(bytes); } else if (typ === 0x62615345) { // Baseline: 'baSE'. baseline = Util.readInt32(bytes); } else if (typ === 0x70485973) { // Dpis: 'pHYs'. dpi = Util.readInt32(bytes); dpi = (Math.round(dpi / 39.37)); Util.readInt32(bytes); Util.readByte(bytes); } Util.readInt32(bytes); } if (typeof width !== 'undefined') { const arr = []; arr.cw = width; arr.ch = height; arr.dpi = dpi; if (baseline) { arr.cb = baseline; } return arr; } return []; } }
JavaScript
class TableTree extends Component { /** * Creates an instance of Component. * * @param {object} arg_runtime - client runtime. * @param {object} arg_state - component state. * @param {string} arg_log_context - context of traces of this instance (optional). * * @returns {nothing} */ constructor(arg_runtime, arg_state, arg_log_context) { const log_context = arg_log_context ? arg_log_context : context super(arg_runtime, arg_state, log_context) this.is_table_tree_component = true this.init() } /** * Get container items count. * * @returns {nothing} */ ui_items_get_count() { } /** * Erase container items. * * @returns {nothing} */ ui_items_clear() { } /** * Append rows to the container. * * @param {array} arg_items_array - items array. * * @returns {nothing} */ ui_items_append(/*arg_items_array*/) { } /** * Prepend a row. * * @param {array} arg_items_array - rows array. * * @returns {nothing} */ ui_items_prepend(/*arg_items_array*/) { } /** * Remove a row at given position. * * @param {number} arg_index - row index. * * @returns {nothing} */ ui_items_remove_at_index(arg_index) { assert( T.isNumber(arg_index), context + ':ui_items_remove_at_index:bad index number' ) } /** * Remove a row at first position. * * @returns {nothing} */ ui_items_remove_first() { } /** * Remove a row at last position. * * @param {integer} arg_count - items count to remove. * * @returns {nothing} */ ui_items_remove_last(/*arg_count*/) { // console.log(context + ':ui_items_remove_last:arg_count', arg_count) } /** * Init view. * * @returns {nothing} */ init() { let styles = '<style type="text/css">\n' styles += '#content { margin-left: 50px; }\n' styles += '.node_branch { cursor: default; font-size: 0.8em; line-height:1em; }\n' styles += '.node_a { position: relative; cursor: pointer; }\n' styles += '.node_content { cursor: default; margin-left: 10px; font-site:0,1em; font-size: 0.8em; line-height:1em; }\n' styles += '</style>\n' $('head').append(styles) } /** * Update tree. * * @param {object} arg_tree - tree nodes. * * @returns {nothing} */ update_tree(arg_tree) { var self = this if (! arg_tree) { arg_tree = this.get_state_value('tree', {}) } if (arg_tree.datas) { arg_tree = arg_tree.datas } console.log('tree.update_tree', arg_tree) const pollers = this.get_state_value(['bindings', 'services', 0, 'options', 'method', 'pollers'], undefined) const svc_name = this.get_state_value(['bindings', 'services', 0, 'service'], undefined) const method_name = this.get_state_value(['bindings', 'services', 0, 'method'], undefined) if ( ! pollers && svc_name && method_name && this.unbind && this.unbind[svc_name] && this.unbind[svc_name][method_name] ) { this.unbind[svc_name][method_name]() } const tree_id = this.get_dom_id() if (! this.tree_jqo) { this.tree_jqo = $('#' + tree_id) this.tbody_jqo = $('tbody', this.tree_jqo) } else { $('tr', this.tbody_jqo).remove() } this.max_depth = this.get_state_value('max_depth', 20) this.max_depth = T.isNumber(this.max_depth) ? this.max_depth : 20 var collapsed = this.get_state_value('collapsed', false) const key = this.get_state_value(['bindings', 'services', 0, 'transform', 'fields', 0, 'name'], undefined) const sub_tree = key ? arg_tree[key] : arg_tree if (! sub_tree) { return } this.render_node(sub_tree, 1, this.get_state_value(label), ! collapsed) if (collapsed) { $('.node_branch', this.tree_jqo).hide() $('.node_content', this.tree_jqo).hide() $('span.node_opened', this.tree_jqo).hide() $('span.node_closed', this.tree_jqo).show() $('tr').removeClass('expanded').addClass('collapsed').hide() $('tr').filter( function () { return $(this).data('depth') == 1 } ).show() } else { $('.node_branch', this.tree_jqo).show() $('.node_content', this.tree_jqo).show() $('span.node_opened', this.tree_jqo).show() $('span.node_closed', this.tree_jqo).hide() $('tr').removeClass('collapsed').addClass('expanded').show() } $('a.node_a', this.tbody_jqo).click( function(ev) { // var el = $(ev.currentTarget) // var tr = el.closest('tr') var tr = $(ev.currentTarget).parent().parent() var children = self.find_children(tr) // console.log('a.click:children=', children) if ( tr.hasClass('collapsed') ) { // BECOME EXPANDED $('span.node_closed', tr).hide() $('span.node_opened', tr).show() tr.removeClass('collapsed').addClass('expanded') children.removeClass('collapsed').addClass('expanded').show() $('span.node_closed', children).hide() $('span.node_opened', children).show() } else { // BECOME COLLAPSED $('span.node_closed', tr).show() $('span.node_opened', tr).hide() tr.removeClass('expanded').addClass('collapsed') children.removeClass('expanded').addClass('collapsed').hide() $('span.node_closed', children).show() $('span.node_opened', children).hide() } } ) } /** * */ find_children(arg_tr) { var depth = arg_tr.data('depth') return arg_tr.nextUntil( $('tr').filter( function () { return $(this).data('depth') <= depth } ) ) } /** * Append a table row */ append_row(arg_key, arg_content, arg_depth, arg_expanded) { var id = 'tr_' + uid() var style = 'padding-left:' + arg_depth * 20 + 'px' // var style = '' var class_expanded = arg_expanded ? 'expanded' : 'collapsed' var html_row = '<tr id="' + id + '" class="node_content ' + class_expanded + '" data-depth="' + arg_depth + '">' html_row += '<td style="' + style + '">' + arg_key + '</td>' html_row += '<td>' + arg_content + '</td>' html_row += '</tr>' this.tbody_jqo.append(html_row) } /** * */ render_expandable_node(arg_label, arg_depth, arg_expanded) { var id = 'tr_' + uid() var style = 'padding-left:' + arg_depth * 20 + 'px' var class_expanded = arg_expanded ? 'expanded' : 'collapsed' var str = '' str += '<tr id="' + id + '" class="node_branch ' + class_expanded + '" data-depth="' + arg_depth + '"><td style="' + style + '">' str += '<a class="node_a">' str += '<span class="node_closed">\u25B9</span>' str += '<span class="node_opened">\u25BF</span>' str += '<b>' + arg_label + '</b>' str += '</a>' str += '</td><td></td></tr>' this.tbody_jqo.append(str) } /** * */ render_safe_string(arg_value) { // console.log('tree.render_safe_string', arg_value) // arg_value = arg_value.replace('<script>', 'AscriptB').replace('A/scriptB', '\A/script\B') if ( T.isString(arg_value) && arg_value.indexOf('<') > -1) { // console.log('Tree:render_safe_string: value=%s', arg_value) return '<code>' + arg_value.replace('<', '&lt;').replace('>', '&gt;') + '</code>' } var translations = { '<script>' :'!scripta!', '</script>':'!scriptb!', '<div>' :'!diva!', '</div>':'!divb!', '<li>' :'!lia!', '</li>' :'!lib!', '<ul>' :'!ula!', '</ul>' :'!ulb!', '<' :'!aaa!', '>' :'!bbb!' } // arg_value = arg_value ? arg_value.toString().replace('<div>', '!diva!').replace('</div>', '!divb!') : arg_value // return arg_value ? arg_value.toString().replace('<li>', '!lia!').replace('</li>', '!lib!').replace('<ul>', '!ula!').replace('</ul>', '!ulb!').replace('<', '!aaa!').replace('>', '!bbb!') : arg_value if ( T.isString(arg_value) ) { var tr = '' Object.keys(translations).forEach( function(key) { tr = translations[key] arg_value = arg_value.replace(key, tr) } ) } else { console.error('tree.render_safe_string: value is not a string', arg_value) } return arg_value } /** * */ render_node(arg_value, arg_depth, arg_label, arg_expanded) { // console.log('tree.render_node', arg_label) var self = this arg_depth = arg_depth ? arg_depth : 1 arg_label = arg_label == 0 ? '0' : arg_label arg_label = arg_label ? arg_label : 'no name' arg_label = '' + arg_label if (arg_depth > this.max_depth) { console.log('MAX DEPTH ' + this.max_depth + ' is reached') return } if (T.isString(arg_value)) { // console.log('tree.render_node with string content', arg_label) this.append_row(this.render_safe_string(arg_label), this.render_safe_string(arg_value), arg_depth, arg_expanded) return } if (T.isNumber(arg_value)) { // console.log('tree.render_node with number content', arg_label) this.append_row(this.render_safe_string(arg_label), arg_value, arg_depth, arg_expanded) return } if (T.isBoolean(arg_value)) { // console.log('tree.render_node with boolean content', arg_label) this.append_row(this.render_safe_string(arg_label), (arg_value ? 'true' : 'false'), arg_depth, arg_expanded) return } if (T.isArray(arg_value)) { // console.log('tree.render_node with array content', arg_label) if (arg_value.length == 0) { this.append_row(this.render_safe_string(arg_label), '[]', arg_depth, arg_expanded) return } this.render_expandable_node(arg_label, arg_depth, arg_expanded) try { arg_value.forEach( function(value, index) { self.render_node(value, arg_depth + 1, index, arg_expanded) } ) } catch(e) { // NOTHING TO DO console.error(e) } return } if (T.isObject(arg_value)) { // console.log('tree.render_node with object content', arg_label) this.render_expandable_node(arg_label, arg_depth, arg_expanded) try { Object.keys(arg_value).forEach( function(key) { self.render_node(arg_value[key], arg_depth + 1, key, arg_expanded) } ) } catch(e) { // NOTHING TO DO console.error(e) } return } if ( T.isNull(arg_value)) { // console.log('tree.render_node with null content', arg_label) return } console.error(arg_value, 'value is unknow, unknow node of type [' + (typeof arg_value) + ']') return } /** * On bindings refresh. * * @returns {nothing} */ do_refresh() { // console.log('new state', arg_operands) // this.update_tree(arg_operands.datas) this.load() } }
JavaScript
class Controller { /** * Constructor. * @param {!angular.Scope} $scope * @ngInject */ constructor($scope) { /** * @type {?angular.Scope} * @private */ this.scope_ = $scope; /** * @type {?Date} */ this['date'] = null; /** * @type {?number} */ this['hour'] = null; /** * @type {?number} */ this['minute'] = null; /** * @type {?number} */ this['second'] = null; /** * @dict */ this['dateOptions'] = { 'changeYear': true, 'changeMonth': true, 'yearRange': '1900:+10' }; $scope['required'] = $scope['isRequired'] || false; this.watchDate_(); $scope.$watch('disabled', function(val, old) { if (val === true) { $scope['required'] = false; } else { $scope['required'] = $scope['isRequired']; } }); $scope.$watch('isRequired', function(val, old) { // If its disabled, not required. Otherwise, check if its required $scope['required'] = $scope['disabled'] ? false : $scope['isRequired']; }); $scope.$on('reset', function(event, val) { if (val == this.scope_['value']) { var initialDate = new Date(this.scope_['value']); this['date'] = new Date(initialDate.getTime() + initialDate.getTimezoneOffset() * 60000); this['hour'] = initialDate.getUTCHours(); this['minute'] = initialDate.getUTCMinutes(); this['second'] = initialDate.getUTCSeconds(); } }.bind(this)); $scope.$on('$destroy', this.destroy_.bind(this)); } /** * Clear references to Angular/DOM elements. * * @private */ destroy_() { this['date'] = null; this.scope_ = null; } /** * Change handler for date picker. * * @private */ watchDate_() { this.scope_.$watch('value', function(newVal, oldVal) { if (newVal) { // offset local time so the ui-date control displays in UTC var initialDate = new Date(newVal); this['date'] = new Date(initialDate.getTime() + initialDate.getTimezoneOffset() * 60000); this['hour'] = initialDate.getUTCHours(); this['minute'] = initialDate.getUTCMinutes(); this['second'] = initialDate.getUTCSeconds(); } else { this['date'] = null; this['hour'] = null; this['minute'] = null; this['second'] = null; } }.bind(this)); this.unwatchDate_ = this.scope_.$watch('dateTimeCtrl.date', this.onDateChanged_.bind(this)); } /** * Change handler for date picker. * * @param {?Date} newVal * @param {?Date} oldVal * @private */ onDateChanged_(newVal, oldVal) { if (newVal && newVal != oldVal) { this.updateValue('date'); } } /** * Updates the scope value or reports an error. * * @param {string=} opt_type * @export */ updateValue(opt_type) { log.fine(logger, 'dateTime.updateValue'); // if the date was set, zero out any hour/min/sec fields that aren't set yet if (opt_type && opt_type === 'date' && goog.isDateLike(this['date']) && !isNaN(this['date'].getTime())) { if (this['hour'] == null) { this['hour'] = 0; } if (this['minute'] == null) { this['minute'] = 0; } if (this['second'] == null) { this['second'] = 0; } } if (goog.isDateLike(this['date']) && !isNaN(this['date'].getTime()) && this['hour'] != null && this['minute'] != null && this['second'] != null) { // update date field with hour/min/sec control values var utcDate = new Date(this['date'].getTime() - this['date'].getTimezoneOffset() * 60000); utcDate.setUTCHours(this['hour']); utcDate.setUTCMinutes(this['minute']); utcDate.setUTCSeconds(this['second']); // convert to ISO string and drop the milliseconds this.scope_['value'] = utcDate.toISOString().replace(/\.[0-9]{3}Z/, 'Z'); this['errorString'] = null; this.scope_['invalid'] = false; } else { this.scope_['invalid'] = true; this['errorString'] = null; this['requiredString'] = null; // display error string for missing/invalid value, preferring date > hour > min > sec if (this.scope_['required'] && !goog.isDateLike(this['date']) && this['hour'] == null && this['minute'] == null && this['second'] == null) { this['requiredString'] = 'Required!'; } else if (!goog.isDateLike(this['date'])) { this['errorString'] = 'Please provide a valid date.'; } else if (this['hour'] == null) { this['errorString'] = 'Hour field invalid! Range: 0-23'; } else if (this['minute'] == null) { this['errorString'] = 'Minute field invalid! Range: 0-59'; } else if (this['second'] == null) { this['errorString'] = 'Second field invalid! Range: 0-59'; } } } /** * Sets this field to the current time. * * @export */ setNow() { // set the inputs as dirty for validation $('.js-date-time__time-input').addClass('ng-dirty'); $('.js-wheel-date__date-input').addClass('ng-dirty'); // offset local time so the ui-date control displays in UTC var now = new Date(); this['date'] = new Date(now.getTime() + now.getTimezoneOffset() * 60000); this['hour'] = now.getUTCHours(); this['minute'] = now.getUTCMinutes(); this['second'] = now.getUTCSeconds(); this.updateValue(); if (this.scope_ && this.scope_['dateTimeForm']) { this.scope_['dateTimeForm'].$setDirty(); } } /** * Sets this field to the current time. * * @export */ reset() { this.unwatchDate_(); this['date'] = null; this['hour'] = null; this['minute'] = null; this['second'] = null; this.scope_['value'] = null; this['errorString'] = null; this.scope_['invalid'] = false; this.watchDate_(); } }
JavaScript
class BreadcrumbTitle extends Component { static propTypes = { experiment: PropTypes.instanceOf(Experiment).isRequired, // Optional because not all pages are nested under runs runUuids: PropTypes.arrayOf(PropTypes.string), runNames: PropTypes.arrayOf(PropTypes.string), title: PropTypes.any.isRequired, }; render() { const { experiment, runUuids, runNames, title } = this.props; const experimentId = experiment.getExperimentId(); const experimentLink = ( <Link to={Routes.getExperimentPageRoute(experimentId)} className='truncate-text single-line breadcrumb-title' > {experiment.getName()} </Link> ); let runsLink = null; if (runUuids) { runsLink = runUuids.length === 1 ? ( <Link to={Routes.getRunPageRoute(experimentId, runUuids[0])} key='link' className='truncate-text single-line breadcrumb-title' > {runNames[0]} </Link> ) : ( <Link to={Routes.getCompareRunPageRoute(runUuids, experimentId)} key='link' className='truncate-text single-line breadcrumb-title' > Comparing {runUuids.length} Runs </Link> ); } const chevron = <i className='fas fa-chevron-right breadcrumb-chevron' key='chevron' />; return ( <h1 className='breadcrumb-header'> {experimentLink} {chevron} {runsLink ? [runsLink, chevron] : []} <span className='truncate-text single-line breadcrumb-title'>{title}</span> </h1> ); } }
JavaScript
class ModelArray extends ItemArray { /** * Create the ModelArray with a provided Model to use as a reference. * @param {Array|class Nodal.Model} modelConstructor Must pass the constructor for the type of ModelArray you wish to create. */ constructor(modelConstructor) { super(); this.Model = modelConstructor; } /** * Convert a normal Array into a ModelArray * @param {Array} arr The array of child objects */ static from(arr) { if (!arr.length) { throw new Error(`service.error.empty_array`); } let modelArray = new this(arr[0].constructor); modelArray.push.apply(modelArray, arr); return modelArray; } /** * Creates an Array of plain objects from the ModelArray, with properties matching an optional interface * @param {Array} arrInterface Interface to use for object creation for each model */ toObject(arrInterface) { return this.map(m => m.toObject(arrInterface)); } /** * Checks if ModelArray has a model in it * @param {Nodal.Model} model */ has(model) { return this.filter(m => m.get('id') === model.get('id')).length > 0; } /** * Calls Model#read on each Model in the ModelArray * @param {Object} */ readAll(data) { this.forEach(model => model.read(data)); return true; } /** * Calls Model#read on each Model in the ModelArray * @param {Object} */ setAll(field, value) { this.forEach(model => model.set(field, value)); return true; } /** * Destroys (deletes) all models in the ModelArray from the database * @param {function} callback Method to invoke upon completion */ destroyAll(callback) { if (this.filter(m => !m.inStorage()).length) { return callback(new Error(`service.error.array_not_in_storage`)); } let db = this.Model.prototype.db; let params = this.map(m => m.get('id')); let sql = db.adapter.generateDeleteAllQuery(this.Model.table(), 'id', params); db.query( sql, params, (err, result) => { if (err) { return callback.call(this, new Error(err.message)); } this.forEach(m => m._inStorage = false); callback.call(this, null); } ); } /** * Destroys model and cascades all deletes. * @param {function} callback method to run upon completion */ destroyCascade(callback) { let db = this.Model.prototype.db; if (this.filter(m => !m.inStorage()).length) { return callback(new Error(`service.error.array_not_in_storage`)); } let params = this.map(m => m.get('id')); let txn = [ [db.adapter.generateDeleteAllQuery(this.Model.table(), 'id', params), params] ]; let children = this.Model.relationships().cascade(); txn = txn.concat( children.map(p => { return [db.adapter.generateDeleteAllQuery(p.getModel().table(), 'id', params, p.joins(null, this.Model.table())), params]; }) ).reverse(); db.transaction( txn, (err, result) => { if (err) { return callback(err); } this.forEach(m => m._inStorage = false); callback(null); } ); } /** * Saves / updates all models in the ModelArray. Uses beforeSave / afterSave. Will return an error and rollback if *any* model errors out. * @param {function} callback returning the error and reference to self */ saveAll(callback) { if (!this.length) { return callback.call(this, null, this); } async.series( this.map(m => m.beforeSave.bind(m)), err => { if (err) { return callback(err); } this.__saveAll__(err => { if (err) { return callback(err, this); } async.series( this.map(m => m.afterSave.bind(m)), err => callback(err || null, this) ); }); } ); } /** * save all models (outside of beforeSave / afterSave) * @param {function} callback Called with error, if applicable * @private */ __saveAll__(callback) { let firstErrorModel = this.filter(m => m.hasErrors()).shift(); if (firstErrorModel) { return callback.call(this, firstErrorModel.errorObject()); } async.series( this.map(m => m.__verify__.bind(m)), (err) => { if (err) { return callback.call(this, err); } let db = this.Model.prototype.db; db.transaction( this.map(m => { let query = m.__generateSaveQuery__(); return [query.sql, query.params]; }), (err, result) => { if (err) { return callback.call(this, new Error(err.message)); } this.forEach((m, i) => { m.__load__(result[i].rows[0], true); }); callback.call(this, null); } ); } ); } }
JavaScript
class Bone{ constructor( len=1 ){ this.order = 0; // Bone Order, Used to identify bone to vertices in shaders this.length = len; // Length of the Bone (Going UP) this.bind = new Transform(); // Default Local Transform For Bone, Allows to reset bones back to initial state. //................................... // Bind Pose is the inverted Hierachy Transform of the bone. Its used to "subtract" // an updated Transform to get the difference from the initial state. The Difference // is the Offset. That is the actual amount of rotation / translation we need to do. this.dqBindPose = new DualQuat(); // Initial Local-World Space this.dqOffset = new DualQuat(); // The Local-World Space difference from BindPose } static updateOffset( e ){ let dq = new DualQuat(); dq.set( e.Node.world.rot, e.Node.world.pos ); DualQuat.mul( dq, e.Bone.dqBindPose, e.Bone.dqOffset ); // offset = world * bindPose } }
JavaScript
class Armature{ constructor(){ this.bones = new Array(); // Main Bones Array : Ordered by Order Number this.names = {}; this.isModified = true; this.isActive = true; // Disable the Rendering of Armature this.flatOffset = null; // Flatten Bone DualQuat for Shaders this.flatScale = null; // Flatten Bone } /////////////////////////////////////////////////////////// // INITIALIZERS /////////////////////////////////////////////////////////// static $( e ){ if( e instanceof Entity && !e.Armature ) Entity.com_fromName( e, "Armature" ); return e; } static finalize( e ){ let arm = ( e instanceof Armature )? e : e.Armature; // Sort it by order // This is important when flattening the data for shader use arm.bones.sort( fSort_bone_order ); // Create Bind pose data for each bone in the armature Armature.bindPose( e ); // Create Flat Data array based on bone count. // NOTE: flatScale must be 4, not 3, because UBO's require 16 byte blocks // So a vec3 array has to be a vec4 array arm.flatOffset = new Float32Array( arm.bones.length * 8 ); arm.flatScale = new Float32Array( arm.bones.length * 4 ); // Create a Lookup map between Bone Names and Their Array Index. for( let i=0; i < arm.bones.length; i++ ){ arm.names[ arm.bones[i].info.name ] = i; } return e; } /////////////////////////////////////////////////////////// // BONES /////////////////////////////////////////////////////////// static addBone( arm, name, len = 1, pe = null, order = null ){ let e = App.ecs.entity( name, [ "Node", "Bone"] ); // Make it easier to create new bones e.Bone.length = len; e.Bone.order = ( order == null )? arm.bones.length : order; if( pe ){ App.node.addChild( pe, e ); e.Node.local.pos.y = pe.Bone.length; // Move start of bone to the end of the parent's } arm.bones.push( e ); return e; } static getBone( arm, name ){ if( arm.Armature ) arm = arm.Armature; // An entity weas passed in. let b; for(b of arm.bones){ if( b.info.name == name ) return b; } return null; } get_bone( bName ){ return this.bones[ this.names[ bName ] ]; } getParentPath( bName, incChild=true ){ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Get the heirarchy nodes let e = this.bones[ this.names[bName] ], tree = [ ]; if( incChild ) tree.push( e.Bone.order ); // Incase we do not what to add the requested entity to the world transform. while( e.Node.parent != null ){ tree.push( e.Node.parent.Bone.order ); e = e.Node.parent; } return tree; } set_rot_by_idx( i, q ){ this.bones[ i ].Node.local.rot.copy( q ); this.bones[ i ].Node.isModified = true; return this; } /////////////////////////////////////////////////////////// // POSE DATA /////////////////////////////////////////////////////////// static bindPose( e ){ let arm = ( e instanceof Armature )? e : e.Armature, ary = arm.bones.slice( 0 ).sort( fSort_bone_lvl ), dqWorld = new DualQuat(), eb; // Bone Entity for( eb of ary ){ //................................. // Update world space transform then save result as bind pose. App.node.updateWorldTransform( eb, false ); eb.Bone.bind.copy( eb.Node.local ); // Make a Copy as starting point to reset bones //................................. // Bind Pose is the initial Hierarchy transform of each bone, inverted. dqWorld.set( eb.Node.world.rot, eb.Node.world.pos ); dqWorld.invert( eb.Bone.dqBindPose ); } } static flattenData( e ){ let i, ii, iii, b, n, arm = e.Armature, off = arm.flatOffset, sca = arm.flatScale; for(i=0; i < arm.bones.length; i++){ b = arm.bones[i].Bone; ii = i * 8; iii = i * 4; off[ii+0] = b.dqOffset[0]; off[ii+1] = b.dqOffset[1]; off[ii+2] = b.dqOffset[2]; off[ii+3] = b.dqOffset[3]; off[ii+4] = b.dqOffset[4]; off[ii+5] = b.dqOffset[5]; off[ii+6] = b.dqOffset[6]; off[ii+7] = b.dqOffset[7]; n = arm.bones[i].Node.world; sca[iii+0] = n.scl[0]; sca[iii+1] = n.scl[1]; sca[iii+2] = n.scl[2]; sca[iii+3] = 0; //WARNING, This is because of UBO Array Requirements, Vec3 is treated as Vec4 } return this; } /////////////////////////////////////////////////////////// // MISC /////////////////////////////////////////////////////////// // Serialize the Bone Data static serialize( arm, incScale = false ){ let bLen = arm.bones.length, out = new Array( bLen ), i, e, bi; for( i=0; i < bLen; i++ ){ e = arm.bones[ i ]; bi = e.Bone.bind; out[ i ] = { name : e.info.name, lvl : e.Node.level, len : e.Bone.length, idx : e.Bone.order, p_idx : (e.Node.parent)? e.Node.parent.Bone.order : null, pos : [ bi.pos[0], bi.pos[1], bi.pos[2] ], rot : [ bi.rot[0], bi.rot[1], bi.rot[2], bi.rot[3] ], }; if( incScale ) out[ i ].scl = [ bi.scl[0], bi.scl[1], bi.scl[2] ]; } return out; } }
JavaScript
class BoneSystem extends System{ run( ecs ){ let ary = ecs.query_comp( "Bone" ); if( ary == null ) return; // No Bones Loaded, Exit Early let e, b, dq = new DualQuat(); for( b of ary ){ e = ecs.entities[ b.entityID ]; if( e.Node.isModified ){ dq.set( e.Node.world.rot, e.Node.world.pos ); DualQuat.mul( dq, e.Bone.dqBindPose, e.Bone.dqOffset ); } } } }
JavaScript
class ArmatureSystem extends System{ static init( ecs, priority = 801 ){ ecs.sys_add( new BoneSystem(), priority ); ecs.sys_add( new ArmatureSystem(), priority+1 ); //Armature needs to run after Bones are Updated. ecs.sys_add( new ArmatureCleanupSystem(), 1000 ); } run( ecs ){ let a, ary = ecs.query_comp( "Armature" ); if( ary == null ) return; // No Bones Loaded, Exit Early for( a of ary ) if( a.isModified ) Armature.flattenData( ecs.entities[ a.entityID ] ); } }
JavaScript
class ArmatureCleanupSystem extends System{ run( ecs ){ let a, ary = ecs.query_comp( "Armature" ); if( ary == null ) return; // No Bones Loaded, Exit Early for( a of ary ) if( a.isModified ) a.isModified = false; } }
JavaScript
class VersionsCommand extends BaseCommand { // hide the command from help static hidden = true // command arguments static args = [ { name: "mainFile", requried: true, description: "Main program file. Will be passed down to nodemon to start the development server." } ] /** * Initiate the class */ init() { super.init() // class attributes this._ngrokPorts = [] this._devConfigDir = path.join(os.tmpdir(), ".rb") this._devConfigLocation = `${this._devConfigDir}/dev-config.yaml` // ensure dev config dir exists if (!fs.existsSync(this._devConfigDir)) fs.mkdirSync(this._devConfigDir) } /** * Register ngrok URL for each application */ async ngrokConnect() { // server settings const envfile = path.join(os.tmpdir(), ".rb", ".env.server") const serverSettings = dotenv.parse(fs.readFileSync(envfile)) // get ngrok URL const ngrokURL = await ngrok.connect({ authtoken: process.env.NGROK_TOKEN, addr: serverSettings.RB_PORT, proto: "tcp" }) // remove host return (new URL(ngrokURL)).host } /** * Copy configs to tmp folder and update applications * with ngrok URL. */ async prepareDevConfigs() { // notify user cli.ux.action.start("Preparing development configs") // load yaml configs let files = (await readAllConfigs(process.cwd())).flatMap(yaml.loadAll) // update app configs files = files .map(async (file) => { // minimize load errors if (file.type && file.key) { // check if file is of type app // and set a new ngrok URL if (file.type === "App") { file.base_url = await this.ngrokConnect() } return file } }) // dump as long yaml const filesYaml = (await Promise.all(files)) .filter((file) => !!file) .map(yaml.dump) .join("---\n") // write development configs to tmp file writeConfig(filesYaml, this._devConfigLocation) // stop notification cli.ux.action.stop() } /** * Deploy development configs to user level. */ async deployDevConfigs() { // notify user about config deployment cli.ux.action.start("Deploying development configurations") // execute the rb deploy:user command const { email } = await this.jwt await DeployUser.run([email, "-c", this._devConfigDir, "--no-runDeployCommand"]) // stop spinner cli.ux.action.stop() } /** * Graceful shutdown for the development server */ async teardown() { // stop ngrok process await ngrok.kill() // kill process process.exit() } /** * Setup dev script. */ async setup() { // kill ngrok await ngrok.kill() // prepare dev configs // copy to tmp and update application yamls with ngrok url await this.prepareDevConfigs() // updating and deploying dev configs await this.deployDevConfigs() } /** * Execute the versions command */ async run() { // start nodemon nodemon({ script: this.args.mainFile, ext: "js,yaml,sh,tf,json" }) // define setup and teardown const that = this nodemon .on("start", () => { that.setup() }) .on("quit", () => { that.teardown() }) } }
JavaScript
class CustomImage extends LitElement { /* REQUIRED FOR TOOLING DO NOT TOUCH */ /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ tag() { return "custom-image"; } // life cycle constructor() { super(); } /** * life cycle, element is afixed to the DOM */ connectedCallback() { super.connectedCallback(); } // static get observedAttributes() { // return []; // } // disconnectedCallback() {} // attributeChangedCallback(attr, oldValue, newValue) {} }
JavaScript
class EveSOFDataLogo { textures = []; /** * Black definition * @param {*} r * @returns {*[]} */ static black(r) { return [ ["textures", r.array] ]; } }
JavaScript
class ShaderCache { constructor(sources) { this.sources = sources; // shader name -> source code this.shaders = new Map(); // name & permutations hashed -> compiled shader this.programs = new Map(); // (vertex shader, fragment shader) -> program // TODO: remove any // or /* style comments // resovle / expande sources (TODO: break include cycles) for (let [key, src] of this.sources) { let changed = false; for (let [includeName, includeSource] of this.sources) { //var pattern = RegExp(/#include</ + includeName + />/); const pattern = "#include <" + includeName + ">"; if(src.includes(pattern)) { // only replace the first occurance src = src.replace(pattern, includeSource); // remove the others while (src.includes(pattern)) { src = src.replace(pattern, ""); } changed = true; } } if(changed) { this.sources.set(key, src); } } } destroy() { for (let [, shader] of this.shaders.entries()) { WebGl.context.deleteShader(shader); shader = undefined; } this.shaders.clear(); for (let [, program] of this.programs) { program.destroy(); } this.programs.clear(); } // example args: "pbr.vert", ["NORMALS", "TANGENTS"] selectShader(shaderIdentifier, permutationDefines) { // first check shaders for the exact permutation // if not present, check sources and compile it // if not present, return null object const src = this.sources.get(shaderIdentifier); if(src === undefined) { console.log("Shader source for " + shaderIdentifier + " not found"); return null; } const isVert = shaderIdentifier.endsWith(".vert"); let hash = stringHash(shaderIdentifier); // console.log(shaderIdentifier); let defines = ""; for(let define of permutationDefines) { // console.log(define); hash ^= stringHash(define); defines += "#define " + define + "\n"; } let shader = this.shaders.get(hash); if(shader === undefined) { // console.log(defines); // compile this variant shader = WebGl.compileShader(shaderIdentifier, isVert, defines + src); this.shaders.set(hash, shader); } return hash; } getShaderProgram(vertexShaderHash, fragmentShaderHash) { const hash = combineHashes(vertexShaderHash, fragmentShaderHash); let program = this.programs.get(hash); if (program) // program already linked { return program; } else // link this shader program type! { let linkedProg = WebGl.linkProgram(this.shaders.get(vertexShaderHash), this.shaders.get(fragmentShaderHash)); if(linkedProg) { let program = new gltfShader(linkedProg, hash); this.programs.set(hash, program); return program; } } return undefined; } }
JavaScript
class Controller { controller; laser; constructor(inputSource) { // Used for the controller's laser and cursor material color this.color = new Color((Math.random()*0.5) + 0.5, (Math.random()*0.5) + 0.5, (Math.random()*0.5) + 0.5); this.inputSource = inputSource; switch (this.inputSource.targetRayMode) { case 'gaze': this.createCursor(); // this.createLaser(); // this.createController(); break; case 'tracked-pointer': this.createCursor(); this.createLaser(); this.createController(); break; case 'screen': default: } this.bind(getCurrentScene().scene); } bind(scene) { ['cursor', 'laser', 'controller'].forEach((item) => { if (this[item]) { scene.add(this[item]); } }); } unbind() { ['cursor', 'laser', 'controller'].forEach((item) => { if (this[item] && this[item].parent) { this[item].parent.remove(this[item]); } }); } createCursor() { this.cursor = new Mesh(new BoxGeometry(0.2, 0.2, 0.2), new MeshBasicMaterial({ color: this.color })); this.cursor.matrixAutoUpdate = false; this.cursor.raycast = () => null; // Disable raycast intersection } /** * Creates a basic laser mesh with no length at (0,0,0) */ createLaser() { const geometry = new Geometry(); geometry.vertices.push( new Vector3(0, 0, 0), new Vector3(0, 0, 0) ); const material = new LineBasicMaterial({ color: this.color }); this.laser = new Line(geometry, material); this.laser.raycast = () => []; // Disable raycast intersections } allDescendants(obj) { for (let i = 0; i < obj.children.length; i++) { const child = obj.children[i]; this.allDescendants(child); if (child.isObject3D === true) { child.raycast = () => []; } } } createController() { this.controller = meshCache.controller.scene.clone(); this.controller.matrixAutoUpdate = false; this.controller.name = 'controller'; this.allDescendants(this.controller); this.controller.raycast = () => []; // Disable raycast intersections console.log(this.controller); } /** * Returns controller mesh */ get mesh() { return this.controller; } update(xrFrame, intersection) { if (this.controller && this.inputSource.gripSpace) { this.controller.matrixAutoUpdate = false; // Get grip space pose for controller const gripPose = xrFrame.getPose(this.inputSource.gripSpace, XR.refSpace); if (gripPose) { // Get the grip transform matrix this.controller.matrix.fromArray(gripPose.transform.matrix); this.controller.updateMatrixWorld(true); } else { // TODO: hide the controller while WebXR doesn't know where it is. } } if (this.inputSource.targetRaySpace) { const rayPose = xrFrame.getPose(this.inputSource.targetRaySpace, XR.refSpace); /* global XRRay */ const ray = new XRRay(rayPose.transform); if (rayPose) { // If there was an intersection, get the intersection length else default laser to 100 const rayLength = intersection ? intersection.distance : 100; const origin = new Vector3( ray.origin.x, ray.origin.y, ray.origin.z ); const destination = new Vector3( ray.direction.x, ray.direction.y, ray.direction.z ).multiplyScalar(rayLength).add(origin); // If we have a laser then render it in if (this.laser) { this.updateLaser(origin, destination); } // If we have a cursor (which we will for most input source types) then move it to the end of the laser if (this.cursor) { this.cursor.matrix.setPosition(destination); this.cursor.updateMatrixWorld(true); } } else { // TODO: Hide the laser and cursor while WebXR doesn't know where they are. } } } /** * Updates the laser mesh vertices * @param {Vector3} origin * @param {Vector3} direction * @param {Number} length */ updateLaser(origin, destination) { // Set origin vertex this.laser.geometry.vertices[0] = origin; // Set end vertex by multiplying the direciton vector by the length // Add the origin so the end vertex is translated into the correct position this.laser.geometry.vertices[1] = new Vector3().copy(destination); this.laser.geometry.computeBoundingSphere(); this.laser.geometry.verticesNeedUpdate = true; } }
JavaScript
class HubProxy extends EventEmitter { /** * Initializes the proxy given the current client and the hub that the client is connected to. * @param {Client} client The current HubClient that is initialized. * @param {string} hubName The name of the hub that the user wishes to generate a proxy for. * @constructor */ constructor(client, hubName) { super(); this._state = {}; this._client = client; this._hubName = hubName; this._logger = new Logdown({prefix: hubName}); this.funcs = {}; this.server = {}; } /** * Invokes a server hub method with the given arguments. * @param {string} methodName The name of the server hub method * @param {Object} args The arguments to pass into the server hub method. * @returns {*} The return statement invokes the send method, which sends the information the server needs to invoke the correct method. * @function */ invoke(methodName, ...args) { let data = { H: this._hubName, M: methodName, A: args.map(a => (isFunction(a) || isUndefined(a)) ? null : a), I: this._client.invocationCallbackId }; const callback = minResult => { return new Promise((resolve, reject) => { const result = Protocol.expandServerHubResponse(minResult); // Update the hub state extend(this._state, result.State); if(result.Progress) { // TODO: Progress in promises? } else if(result.Error) { // Server hub method threw an exception, log it & reject the deferred if(result.StackTrace) { this._logger.error(`${result.Error}\n${result.StackTrace}.`); } // result.ErrorData is only set if a HubException was thrown const source = result.IsHubException ? 'HubException' : 'Exception'; const error = new Error(result.Error); error.source = source; error.data = result.ErrorData; this._logger.error(`${this._hubName}.${methodName} failed to execute. Error: ${error.message}`); reject(error); } else { // Server invocation succeeded, resolve the deferred this._logger.info(`Invoked ${this._hubName}\.${methodName}`); return resolve(result.Result); } }); }; this._client.invocationCallbacks[this._client.invocationCallbackId.toString()] = {scope: this, method: callback}; this._client.invocationCallbackId += 1; if(!isEmpty(this.state)) { data.S = this.state; } this._logger.info(`Invoking ${this._hubName}\.${methodName}`); return this._client.send(data); } }
JavaScript
class App extends Component { render() { return ( <div className="App"> <Navbar /> <header className="App-header"> <Modal /> </header> <Dropdown /> <Card /> <Button /> <Carousel /> <Footer /> </div> ); } }
JavaScript
class SupportValidation extends BaseFormatter { /** * Constructor for support validation formatter. * * @param {object} params * @param {object} params.supportValidation * @param {number} params.supportValidation.userId * @param {string} params.supportValidation.externalUserId * @param {object} params.supportValidation.userName * * @augments BaseFormatter * * @constructor */ constructor(params) { super(); const oThis = this; oThis.supportValidation = params.supportValidation; } /** * Validate the input objects. * * @returns {result} * @private */ _validate() { const oThis = this; const supportValidationConfig = { userId: { isNullAllowed: false }, externalUserId: { isNullAllowed: false }, userName: { isNullAllowed: false } }; return oThis.validateParameters(oThis.supportValidation, supportValidationConfig); } /** * Format the input object. * * @returns {object} * @private */ _format() { const oThis = this; return responseHelper.successWithData({ userId: oThis.supportValidation.userId, external_user_id: oThis.supportValidation.externalUserId, user_name: oThis.supportValidation.userName }); } }
JavaScript
class LoginSca extends React.Component { constructor() { super(); this.handleLogin = this.handleLogin.bind(this); this.handleCancel = this.handleCancel.bind(this); this.organizationChanged = this.organizationChanged.bind(this); this.verifyClientCertificate = this.verifyClientCertificate.bind(this); this.init = this.init.bind(this); this.setDefaultOrganization = this.setDefaultOrganization.bind(this); this.updateButtonState = this.updateButtonState.bind(this); this.state = {continueDisabled: true}; } componentWillMount() { this.init(); } init() { const props = this.props; const setDefaultOrganization = this.setDefaultOrganization; props.dispatch(initLoginSca(function(initSucceeded) { if (initSucceeded) { // Set the default organization after loading organizations unless chosen organization was previously set if (props.context.chosenOrganizationId === undefined) { setDefaultOrganization(); } } })); } handleLogin(event) { event.preventDefault(); const organizationId = this.props.context.chosenOrganizationId; const usernameField = "username" + "_" + organizationId; const username = ReactDOM.findDOMNode(this.refs[usernameField]); this.props.dispatch(authenticate(username.value, organizationId)); } handleCancel(event) { event.preventDefault(); const organizationId = this.props.context.chosenOrganizationId; const usernameField = "username" + "_" + organizationId; const username = ReactDOM.findDOMNode(this.refs[usernameField]); this.props.dispatch(cancel()); username.value = ""; } render() { return ( <div id="login"> {this.props.context.loading ? <Spinner/> : <form onSubmit={this.handleLogin}> {this.mainPanel()} </form> } </div> ) } mainPanel() { const organizations = this.props.context.organizations; if (organizations === undefined) { // Organization list is not loaded yet return undefined; } if (organizations.length === 1) { return this.singleOrganization(); } else if (organizations.length > 1 && organizations.length < 4) { return this.fewOrganizations(); } else if (organizations.length >= 4) { return this.manyOrganizations(); } else { this.props.dispatch(organizationConfigurationError()); } } singleOrganization() { const organizations = this.props.context.organizations; return ( <Panel> {this.banners(true)} {this.title()} {this.loginForm(organizations[0].organizationId)} </Panel> ) } fewOrganizations() { const formatMessage = this.props.intl.formatMessage; const organizations = this.props.context.organizations; return ( <Tabs defaultActiveKey={this.props.context.chosenOrganizationId} onSelect={key => this.organizationChanged(key)}> {organizations.map((org) => { return ( <Tab key={org.organizationId} eventKey={org.organizationId} title={formatMessage({id: org.displayNameKey})}> <Panel> {this.banners(org.organizationId === this.props.context.chosenOrganizationId)} {this.title()} {this.loginForm(org.organizationId)} </Panel> </Tab> ) })} </Tabs> ) } manyOrganizations() { const organizations = this.props.context.organizations; const chosenOrganizationId = this.props.context.chosenOrganizationId; const formatMessage = this.props.intl.formatMessage; let chosenOrganization = organizations[0]; organizations.forEach(function (org) { // perform i18n, the select component does not support i18n org.displayName = formatMessage({id: org.displayNameKey}); if (org.organizationId === chosenOrganizationId) { chosenOrganization = org; } }); return ( <Panel> <OrganizationSelect organizations={organizations} chosenOrganization={chosenOrganization} intl={this.props.intl} callback={organization => this.organizationChanged(organization.organizationId)} /> {this.banners(true)} {this.title()} {this.loginForm(chosenOrganizationId)} </Panel> ) } setDefaultOrganization() { const organizations = this.props.context.organizations; let defaultOrganizationId = organizations[0].organizationId; organizations.forEach(function (org) { if (org.default === true) { defaultOrganizationId = org.organizationId; } }); this.props.dispatch(selectOrganization(defaultOrganizationId)); } organizationChanged(organizationId) { this.props.dispatch(selectOrganization(organizationId)); } updateButtonState() { if (this.props.context.chosenOrganizationId === undefined) { return; } const usernameField = "username" + "_" + this.props.context.chosenOrganizationId; if (document.getElementById(usernameField).value.length === 0) { if (!this.state.continueDisabled) { this.setState({continueDisabled: true}); } } else { if (this.state.continueDisabled) { this.setState({continueDisabled: false}); } } } verifyClientCertificate() { const organizationId = this.props.context.chosenOrganizationId; const certificateVerificationUrl = this.props.context.clientCertificateVerificationUrl; const dispatch = this.props.dispatch; const callbackOnSuccess = function() { // Authentication is performed using client certificate dispatch(authenticate(null, organizationId)); }; dispatch(checkClientCertificate(certificateVerificationUrl, callbackOnSuccess)); } banners(timeoutCheckActive) { return ( <OperationTimeout timeoutCheckActive={timeoutCheckActive}/> ) } title() { return ( <FormGroup className="title"> <FormattedMessage id="login.pleaseLogIn"/> </FormGroup> ) } loginForm(organizationId) { const usernameField = "username" + "_" + organizationId; const formatMessage = this.props.intl.formatMessage; return( <div> {this.props.context.error ? ( <FormGroup className="message-error"> <FormattedMessage id={this.props.context.message}/> {(this.props.context.remainingAttempts > 0) ? ( <div> <FormattedMessage id="authentication.attemptsRemaining"/> {this.props.context.remainingAttempts} </div> ) : undefined } </FormGroup> ) : undefined } <FormGroup> <FormControl autoComplete="new-password" id={usernameField} ref={usernameField} type="text" maxLength={usernameMaxLength} placeholder={formatMessage({id: 'login.loginNumber'})} autoFocus onChange={this.updateButtonState.bind(this)}/> </FormGroup> {this.props.context.clientCertificateAuthenticationAvailable ? ( <div> <FormGroup> <div className="row"> <div className="col-xs-6"> &nbsp; </div> <div className="col-xs-6"> <Button bsSize="lg" type="submit" bsStyle="success" block> <FormattedMessage id="loginSca.confirmInit"/> </Button> </div> </div> </FormGroup> <hr/> <FormGroup> <div className="row"> <div className="col-xs-6 client-certificate-label"> <FormattedMessage id="clientCertificate.login"/> </div> <div className="col-xs-6"> {this.props.context.clientCertificateAuthenticationEnabled ? ( <a href="#" onClick={this.verifyClientCertificate} className="btn btn-lg btn-success"> <FormattedMessage id="clientCertificate.use"/> </a> ) : ( <div className="btn btn-lg btn-default disabled"> <FormattedMessage id="clientCertificate.use"/> </div> )} </div> </div> </FormGroup> <FormGroup> <div className="row"> <div className="col-xs-6"> <a href="#" onClick={this.handleCancel} className="btn btn-lg btn-default"> <FormattedMessage id="login.cancel"/> </a> </div> </div> </FormGroup> </div> ) : ( <FormGroup> <div className="row buttons"> <div className="col-xs-6"> <a href="#" onClick={this.handleCancel} className="btn btn-lg btn-default"> <FormattedMessage id="login.cancel"/> </a> </div> <div className="col-xs-6"> <Button bsSize="lg" type="submit" bsStyle="success" block disabled={this.state.continueDisabled}> <FormattedMessage id="loginSca.continue"/> </Button> </div> </div> </FormGroup> )} </div> ) } }
JavaScript
class EnvironmentForm extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { const { environment, onSave, onChange, nameEditable, onSelectSample, sampleEnabled } = this.props; return ( <form> <div className="form-group"> <label htmlFor="formEnvironmentName"><FormattedMessage {...commonMessages.name} /></label> { nameEditable ? ( <input type="text" className="form-control" id="formEnvironmentName" name="name" value={environment.name} onChange={onChange} /> ) : ( <input type="text" className="form-control" id="formEnvironmentName" readOnly name="name" value={environment.name} onChange={onChange} /> ) } </div> <div className="form-group"> <label htmlFor="formEnvironmentImage"><FormattedMessage {...commonMessages.dockerImage} /></label> <input type="text" className="form-control" id="formEnvironmentImage" name="image" value={environment.image} onChange={onChange} /> </div> { sampleEnabled && <div className="form-group"> <label htmlFor="formEnvironmentSample"><FormattedMessage {...commonMessages.chooseSample} /></label> <select className="form-control" onChange={onSelectSample} disabled={!nameEditable}> <option value="blank" /> <option value="node">Node</option> <option value="python">Python</option> </select> </div> } <a className="btn btn-primary" onClick={onSave}><FormattedMessage {...commonMessages.save} /></a> { ' ' } <Link to="/environments" className="btn btn-default"><FormattedMessage {...commonMessages.cancel} /></Link> </form> ); } }
JavaScript
class FrontCalculatorSymbolOperatorMultiplication extends FrontCalculatorSymbolOperatorAbstract { constructor() { super(); this.identifiers = ['*']; this.precedence = 200; } operate(leftNumber, rightNumber) { return leftNumber * rightNumber; } }
JavaScript
class SnapTower extends Tower { /** * The Snap Tower constructor * @param {Number} id * @param {Number} row * @param {Number} col * @param {Number} boardSize */ constructor(id, row, col, boardSize) { super(); this.type = "Snap"; this.name = "Snap Tower"; this.special = "Spike Tower"; this.text = "A one time only range fire tower"; this.levels = 6; this.size = 2; this.sound = "snap"; this.stuns = true; this.fire = true; this.costs = [ 50, 100, 150, 250, 400, 600 ]; this.damages = [ 100, 200, 400, 800, 1600, 3200 ]; this.ranges = [ 60, 60, 75, 75, 75, 90 ]; this.speeds = [ 1, 1, 1, 1, 1, 1 ]; this.init(id, row, col, boardSize); } /** * Creates a new Ammo * @param {Array.<Mob>} targets * @returns {SnapAmmo} */ createAmmo(targets) { return new SnapAmmo(this, targets, this.boardSize); } /** * Returns a list of Mobs in the range of the tower * @param {List.<Iterator>} mobs * @param {Mob} mob * @returns {Array.<Array.<Mob>>} */ getTargets(mobs, mob) { const targets = this.getRangeTargets(mobs); const result = []; for (let i = 0; i < targets.length; i += 1) { result.push([targets[i]]); } return result; } /** * Returns true if it will stun a mob * @returns {Boolean} */ get shouldStun() { return Utils.rand(0, 9) === 5; } }
JavaScript
class Controller { constructor(object, property, type, options) { /** * The dynamic property info chunk, if applicable. Carries the getter and setter for this object/property. * @type {Object} * @ignore */ this.__dyninfo = common.setupDynamicProperty(object, property); /** * The initial value of the given property; this is the reference for the * `isModified()` and other APIs. * @type {Any} */ this.initialValue = !this.__dyninfo ? object[property] : this.__dyninfo.getter.call(object); /** * Those who extend this class will put their DOM elements in here. * @type {DOMElement} */ this.domElement = document.createElement("div"); /** * The object to manipulate * @type {Object} */ this.object = object; /** * The name of the property to manipulate * @type {String} */ this.property = property; /** * The name of the controller. Default value is the controller *type*. * @type {String} */ this.name = type; /** * Keep track of the options */ this.__options = options || {}; /** * The function to be called on change. * @type {Function} * @private */ this.__onChange = undefined; /** * The function to be called before applying a change. * @type {Function} * @private */ this.__onBeforeChange = undefined; /** * The function to be called on finishing change. * @type {Function} * @private */ this.__onFinishChange = undefined; } /** * Specify a function which fires every time someone has changed the value with * this Controller. * * @param {Function} fnc This function will be called whenever the value * has been modified via this Controller. * @returns {Controller} this */ onChange(fnc) { this.__onChange = fnc; return this; } /** * Specify a function which fires every time when someone is about to change the value with * this Controller. * * @param {Function} fnc This function will be called whenever the value * is going to be modified via this Controller. * @returns {dat.controllers.Controller} this */ onBeforeChange(fnc) { this.__onBeforeChange = fnc; return this; } /** * Specify a function which fires every time someone "finishes" changing * the value with this Controller. Useful for values that change * incrementally like numbers or strings. * * @param {Function} fnc This function will be called whenever * someone "finishes" changing the value via this Controller. * @returns {dat.controllers.Controller} this */ onFinishChange(fnc) { this.__onFinishChange = fnc; return this; } /** * Fire the registered onChange function if it exists. The first argument will be the current * property value, while the second argument carries any optional user-specified extra event info. * * @param {object} event_info Optional user-specified extra event info. * * @returns {dat.controllers.Controller} this */ fireChange(event_info) { if (this.__onChange) { this.__onChange(this.getValue(), event_info); } return this; } /** * Fire the registered onBeforeChange function if it exists. The first argument will be the current * property value, while the second argument carries any optional user-specified extra event info. * * @param {object} event_info Optional user-specified extra event info. * * @returns {boolean} A truthy return value signals us to *not* apply the change; a falsey return * value permits the change to happen. */ fireBeforeChange(event_info) { if (this.__onBeforeChange) { return this.__onBeforeChange(this.getValue(), event_info); } return false; // default: you are cleared to apply the change. } /** * Fire the registered onFinishChange function if it exists. The first argument will be the current * property value, while the second argument carries any optional user-specified extra event info. * * @param {object} event_info Optional user-specified extra event info. * * @returns {dat.controllers.Controller} this */ fireFinishChange(event_info) { if (this.__onFinishChange) { this.__onFinishChange(this.getValue(), event_info); } return this; } /** * @internal * Change the value of <code>object[property]</code>. Do not fire any events. Invoked * by the `setValue()` API. * * @param {Object} newValue The new value of <code>object[property]</code> */ __setValue(newValue) { if (!this.__dyninfo) { this.object[this.property] = newValue; } else if (this.__dyninfo.setter) { this.__dyninfo.setter.call(this.object, newValue); } else { throw new Error( "Cannot modify the read-only " + (this.__dyninfo ? "dynamic " : "") + 'property "' + this.property + '"' ); } return this; } /** * Change the value of <code>object[property]</code> * * @param {Object} newValue The new value of <code>object[property]</code> * * @param {Boolean} silent If true, don't call the onChange handler */ setValue(newValue, silent) { const readonly = this.getReadonly(); const oldValue = this.getValue(); const changed = oldValue !== newValue; const msg = { newValue: newValue, oldValue: oldValue, isChange: changed, silent: silent, noGo: readonly, eventSource: "setValue", }; if (!silent) { // `newValue` will end up in the second argument of the event listener, thus // userland code can look at both existing and new values for this property // and decide what to do accordingly! msg.noGo = this.fireBeforeChange(msg); } if (!msg.noGo) { this.__setValue(msg.newValue); } // Always fire the change event; inform the userland code whether the change was 'real' // or aborted: if (!msg.silent) { this.fireChange(msg); } // Whenever you call `setValue`, the display will be updated automatically. // This reduces some clutter in subclasses. this.updateDisplay(); return this; } /** * Gets the value of <code>object[property]</code> * * @returns {Object} The current value of <code>object[property]</code> */ getValue() { return !this.__dyninfo ? this.object[this.property] : this.__dyninfo.getter.call(this.object); } getOption(name) { return this.__options[name]; } setOption(name, value) { this.__options[name] = value; } getReadonly() { // flag a read-only dynamic property irrespective of the actual option setting: if (this.__dyninfo && !this.__dyninfo.setter) { return true; } return this.getOption("readonly"); } setReadonly(value) { this.setOption("readonly", value); this.updateDisplay(); } /** * Refreshes the visual display of a Controller in order to keep sync * with the object's current value. * @returns {dat.controllers.Controller} this */ updateDisplay() { return this; } /** * @returns {boolean} true if the value has deviated from initialValue */ isModified() { return this.initialValue !== this.getValue(); } }
JavaScript
class FirehoseMetrics { static incomingBytesAverage(dimensions) { return { namespace: 'AWS/Firehose', metricName: 'IncomingBytes', dimensions, statistic: 'Average', }; } static incomingRecordsAverage(dimensions) { return { namespace: 'AWS/Firehose', metricName: 'IncomingRecords', dimensions, statistic: 'Average', }; } static backupToS3BytesAverage(dimensions) { return { namespace: 'AWS/Firehose', metricName: 'BackupToS3.Bytes', dimensions, statistic: 'Average', }; } static backupToS3DataFreshnessAverage(dimensions) { return { namespace: 'AWS/Firehose', metricName: 'BackupToS3.DataFreshness', dimensions, statistic: 'Average', }; } static backupToS3RecordsAverage(dimensions) { return { namespace: 'AWS/Firehose', metricName: 'BackupToS3.Records', dimensions, statistic: 'Average', }; } }
JavaScript
class Progression { /** * Creates an instance of Progression. * @param {boolean} _integerBased Send 'true' if this progression uses * integer steps exclusively (as opposed to * floating-point). * @param {string} _typeName A simple label for logging. */ constructor(_integerBased, // "integerBased" as opposed to floating point _typeName) { this._integerBased = _integerBased; this._typeName = _typeName; Utils.Assert(this._typeName !== ''); //NOTE: All progressions begin at zero, because the bounds of the range we traverse are inclusive. this._value = 0; } get integerBased() { return this._integerBased; } get typeName() { return this._typeName; } get value() { return this._value; } /** * Puts the progression in its initial state (_value = 0). */ Reset() { this._value = 0; } }
JavaScript
class WebGLContext { constructor(gl, version) { this.frameBufferBound = false; this.itemsToPoll = []; this.gl = gl; this.version = version; this.getExtensions(); this.vertexbuffer = this.createVertexbuffer(); this.framebuffer = this.createFramebuffer(); this.queryVitalParameters(); } allocateTexture(width, height, encoder, data) { const gl = this.gl; // create the texture const texture = gl.createTexture(); // bind the texture so the following methods effect this texture. gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); const buffer = data ? encoder.encode(data, width * height) : null; gl.texImage2D(gl.TEXTURE_2D, 0, // Level of detail. encoder.internalFormat, width, height, 0, // Always 0 in OpenGL ES. encoder.format, encoder.textureType, buffer); this.checkError(); return texture; } updateTexture(texture, width, height, encoder, data) { const gl = this.gl; gl.bindTexture(gl.TEXTURE_2D, texture); const buffer = encoder.encode(data, width * height); gl.texSubImage2D(gl.TEXTURE_2D, 0, // level 0, // xoffset 0, // yoffset width, height, encoder.format, encoder.textureType, buffer); this.checkError(); } attachFramebuffer(texture, width, height) { const gl = this.gl; // Make it the target for framebuffer operations - including rendering. gl.bindTexture(gl.TEXTURE_2D, texture); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // 0, we aren't using MIPMAPs this.checkError(); gl.viewport(0, 0, width, height); gl.scissor(0, 0, width, height); } readTexture(texture, width, height, dataSize, dataType, channels) { const gl = this.gl; if (!channels) { channels = 1; } if (!this.frameBufferBound) { this.attachFramebuffer(texture, width, height); } const encoder = this.getEncoder(dataType, channels); const buffer = encoder.allocate(width * height); // bind texture to framebuffer gl.bindTexture(gl.TEXTURE_2D, texture); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // 0, we aren't using MIPMAPs // TODO: Check if framebuffer is ready gl.readPixels(0, 0, width, height, gl.RGBA, encoder.textureType, buffer); this.checkError(); // unbind FB return encoder.decode(buffer, dataSize); } isFramebufferReady() { // TODO: Implement logic to check if the framebuffer is ready return true; } getActiveTexture() { const gl = this.gl; const n = gl.getParameter(this.gl.ACTIVE_TEXTURE); return `TEXTURE${(n - gl.TEXTURE0)}`; } getTextureBinding() { return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D); } getFramebufferBinding() { return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING); } setVertexAttributes(positionHandle, textureCoordHandle) { const gl = this.gl; gl.vertexAttribPointer(positionHandle, 3, gl.FLOAT, false, 20, 0); gl.enableVertexAttribArray(positionHandle); if (textureCoordHandle !== -1) { gl.vertexAttribPointer(textureCoordHandle, 2, gl.FLOAT, false, 20, 12); gl.enableVertexAttribArray(textureCoordHandle); } this.checkError(); } createProgram(vertexShader, fragShader) { const gl = this.gl; const program = gl.createProgram(); // the program consists of our shaders gl.attachShader(program, vertexShader); gl.attachShader(program, fragShader); gl.linkProgram(program); return program; } compileShader(shaderSource, shaderType) { const gl = this.gl; const shader = gl.createShader(shaderType); if (!shader) { throw new Error(`createShader() returned null with type ${shaderType}`); } gl.shaderSource(shader, shaderSource); gl.compileShader(shader); if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) === false) { throw new Error(`Failed to compile shader: ${gl.getShaderInfoLog(shader)} Shader source: ${shaderSource}`); } return shader; } deleteShader(shader) { this.gl.deleteShader(shader); } bindTextureToUniform(texture, position, uniformHandle) { const gl = this.gl; gl.activeTexture(gl.TEXTURE0 + position); this.checkError(); gl.bindTexture(gl.TEXTURE_2D, texture); this.checkError(); gl.uniform1i(uniformHandle, position); this.checkError(); } draw() { this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4); this.checkError(); } checkError() { if (onnxruntime_common_1.env.debug) { const gl = this.gl; const error = gl.getError(); let label = ''; switch (error) { case (gl.NO_ERROR): return; case (gl.INVALID_ENUM): label = 'INVALID_ENUM'; break; case (gl.INVALID_VALUE): label = 'INVALID_VALUE'; break; case (gl.INVALID_OPERATION): label = 'INVALID_OPERATION'; break; case (gl.INVALID_FRAMEBUFFER_OPERATION): label = 'INVALID_FRAMEBUFFER_OPERATION'; break; case (gl.OUT_OF_MEMORY): label = 'OUT_OF_MEMORY'; break; case (gl.CONTEXT_LOST_WEBGL): label = 'CONTEXT_LOST_WEBGL'; break; default: label = `Unknown WebGL Error: ${error.toString(16)}`; } throw new Error(label); } } deleteTexture(texture) { this.gl.deleteTexture(texture); } deleteProgram(program) { this.gl.deleteProgram(program); } getEncoder(dataType, channels, usage = 0 /* Default */) { if (this.version === 2) { return new DataEncoders.RedFloat32DataEncoder(this.gl, channels); } switch (dataType) { case 'float': if (usage === 1 /* UploadOnly */ || this.isRenderFloat32Supported) { return new DataEncoders.RGBAFloatDataEncoder(this.gl, channels); } else { return new DataEncoders.RGBAFloatDataEncoder(this.gl, channels, this.textureHalfFloatExtension.HALF_FLOAT_OES); } case 'int': throw new Error('not implemented'); case 'byte': return new DataEncoders.Uint8DataEncoder(this.gl, channels); default: throw new Error(`Invalid dataType: ${dataType}`); } } clearActiveTextures() { const gl = this.gl; for (let unit = 0; unit < this.maxTextureImageUnits; ++unit) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, null); } } dispose() { if (this.disposed) { return; } const gl = this.gl; gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.deleteFramebuffer(this.framebuffer); gl.bindBuffer(gl.ARRAY_BUFFER, null); gl.deleteBuffer(this.vertexbuffer); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); gl.finish(); this.disposed = true; } createDefaultGeometry() { // Sets of x,y,z(=0),s,t coordinates. return new Float32Array([ -1.0, 1.0, 0.0, 0.0, 1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, -1.0, 0.0, 1.0, 0.0 // lower right ]); } createVertexbuffer() { const gl = this.gl; const buffer = gl.createBuffer(); if (!buffer) { throw new Error('createBuffer() returned null'); } const geometry = this.createDefaultGeometry(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, geometry, gl.STATIC_DRAW); this.checkError(); return buffer; } createFramebuffer() { const fb = this.gl.createFramebuffer(); if (!fb) { throw new Error('createFramebuffer returned null'); } return fb; } queryVitalParameters() { const gl = this.gl; this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(); this.isRenderFloat32Supported = this.checkRenderFloat32(); this.isFloat32DownloadSupported = this.checkFloat32Download(); if (this.version === 1 && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) { throw new Error('both float32 and float16 TextureType are not supported'); } this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(); // this.maxCombinedTextureImageUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); this.maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); // this.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); // this.shadingLanguageVersion = gl.getParameter(gl.SHADING_LANGUAGE_VERSION); // this.webglVendor = gl.getParameter(gl.VENDOR); // this.webglVersion = gl.getParameter(gl.VERSION); if (this.version === 2) { // this.max3DTextureSize = gl.getParameter(WebGL2RenderingContext.MAX_3D_TEXTURE_SIZE); // this.maxArrayTextureLayers = gl.getParameter(WebGL2RenderingContext.MAX_ARRAY_TEXTURE_LAYERS); // this.maxColorAttachments = gl.getParameter(WebGL2RenderingContext.MAX_COLOR_ATTACHMENTS); // this.maxDrawBuffers = gl.getParameter(WebGL2RenderingContext.MAX_DRAW_BUFFERS); } } getExtensions() { if (this.version === 2) { this.colorBufferFloatExtension = this.gl.getExtension('EXT_color_buffer_float'); this.disjointTimerQueryWebgl2Extension = this.gl.getExtension('EXT_disjoint_timer_query_webgl2'); } else { this.textureFloatExtension = this.gl.getExtension('OES_texture_float'); this.textureHalfFloatExtension = this.gl.getExtension('OES_texture_half_float'); } } checkFloatTextureAttachableToFrameBuffer() { // test whether Float32 texture is supported: // STEP.1 create a float texture const gl = this.gl; const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // eslint-disable-next-line @typescript-eslint/naming-convention const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA; gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null); // STEP.2 bind a frame buffer const frameBuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer); // STEP.3 attach texture to framebuffer gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); // STEP.4 test whether framebuffer is complete const isComplete = gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE; gl.bindTexture(gl.TEXTURE_2D, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.deleteTexture(texture); gl.deleteFramebuffer(frameBuffer); return isComplete; } checkRenderFloat32() { if (this.version === 2) { if (!this.colorBufferFloatExtension) { return false; } } else { if (!this.textureFloatExtension) { return false; } } return this.isFloatTextureAttachableToFrameBuffer; } checkFloat32Download() { if (this.version === 2) { if (!this.colorBufferFloatExtension) { return false; } } else { if (!this.textureFloatExtension) { return false; } if (!this.gl.getExtension('WEBGL_color_buffer_float')) { return false; } } return this.isFloatTextureAttachableToFrameBuffer; } /** * Check whether GL_BLEND is supported */ checkFloat32Blend() { // it looks like currently (2019-05-08) there is no easy way to detect whether BLEND is supported // https://github.com/microsoft/onnxjs/issues/145 const gl = this.gl; let texture; let frameBuffer; let vertexShader; let fragmentShader; let program; try { texture = gl.createTexture(); frameBuffer = gl.createFramebuffer(); gl.bindTexture(gl.TEXTURE_2D, texture); // eslint-disable-next-line @typescript-eslint/naming-convention const internalFormat = this.version === 2 ? gl.RGBA32F : gl.RGBA; gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, 1, 1, 0, gl.RGBA, gl.FLOAT, null); gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); gl.enable(gl.BLEND); vertexShader = gl.createShader(gl.VERTEX_SHADER); if (!vertexShader) { return false; } gl.shaderSource(vertexShader, 'void main(){}'); gl.compileShader(vertexShader); fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); if (!fragmentShader) { return false; } gl.shaderSource(fragmentShader, 'precision highp float;void main(){gl_FragColor=vec4(0.5);}'); gl.compileShader(fragmentShader); program = gl.createProgram(); if (!program) { return false; } gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); gl.useProgram(program); gl.drawArrays(gl.POINTS, 0, 1); return gl.getError() === gl.NO_ERROR; } finally { gl.disable(gl.BLEND); if (program) { gl.deleteProgram(program); } if (vertexShader) { gl.deleteShader(vertexShader); } if (fragmentShader) { gl.deleteShader(fragmentShader); } if (frameBuffer) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.deleteFramebuffer(frameBuffer); } if (texture) { gl.bindTexture(gl.TEXTURE_2D, null); gl.deleteTexture(texture); } } } beginTimer() { if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { const gl2 = this.gl; const ext = this.disjointTimerQueryWebgl2Extension; const query = gl2.createQuery(); gl2.beginQuery(ext.TIME_ELAPSED_EXT, query); return query; } else { // TODO: add webgl 1 handling. throw new Error('WebGL1 profiling currently not supported.'); } } endTimer() { if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { const gl2 = this.gl; const ext = this.disjointTimerQueryWebgl2Extension; gl2.endQuery(ext.TIME_ELAPSED_EXT); return; } else { // TODO: add webgl 1 handling. throw new Error('WebGL1 profiling currently not supported'); } } isTimerResultAvailable(query) { let available = false, disjoint = false; if (this.version === 2 && this.disjointTimerQueryWebgl2Extension) { const gl2 = this.gl; const ext = this.disjointTimerQueryWebgl2Extension; available = gl2.getQueryParameter(query, gl2.QUERY_RESULT_AVAILABLE); disjoint = gl2.getParameter(ext.GPU_DISJOINT_EXT); } else { // TODO: add webgl 1 handling. throw new Error('WebGL1 profiling currently not supported'); } return available && !disjoint; } getTimerResult(query) { let timeElapsed = 0; if (this.version === 2) { const gl2 = this.gl; timeElapsed = gl2.getQueryParameter(query, gl2.QUERY_RESULT); gl2.deleteQuery(query); } else { // TODO: add webgl 1 handling. throw new Error('WebGL1 profiling currently not supported'); } // return miliseconds return timeElapsed / 1000000; } async waitForQueryAndGetTime(query) { await utils_1.repeatedTry(() => this.isTimerResultAvailable(query)); return this.getTimerResult(query); } async createAndWaitForFence() { const fenceContext = this.createFence(this.gl); return this.pollFence(fenceContext); } createFence(gl) { let isFencePassed; const gl2 = gl; const query = gl2.fenceSync(gl2.SYNC_GPU_COMMANDS_COMPLETE, 0); gl.flush(); if (query === null) { isFencePassed = () => true; } else { isFencePassed = () => { const status = gl2.clientWaitSync(query, 0, 0); return status === gl2.ALREADY_SIGNALED || status === gl2.CONDITION_SATISFIED; }; } return { query, isFencePassed }; } async pollFence(fenceContext) { return new Promise(resolve => { void this.addItemToPoll(() => fenceContext.isFencePassed(), () => resolve()); }); } pollItems() { // Find the last query that has finished. const index = linearSearchLastTrue(this.itemsToPoll.map(x => x.isDoneFn)); for (let i = 0; i <= index; ++i) { const { resolveFn } = this.itemsToPoll[i]; resolveFn(); } this.itemsToPoll = this.itemsToPoll.slice(index + 1); } async addItemToPoll(isDoneFn, resolveFn) { this.itemsToPoll.push({ isDoneFn, resolveFn }); if (this.itemsToPoll.length > 1) { // We already have a running loop that polls. return; } // Start a new loop that polls. await utils_1.repeatedTry(() => { this.pollItems(); // End the loop if no more items to poll. return this.itemsToPoll.length === 0; }); } }
JavaScript
class Dependency { /** * @param {!DependencyType} type * @param {string} filepath * @param {!Array<string>} closureSymbols * @param {!Array<!Import>} imports * @param {string=} language */ constructor(type, filepath, closureSymbols, imports, language = 'es3') { /** @const */ this.type = type; /** * Full path of this file on disc. * @const */ this.path = path.resolve(filepath); /** * Array of Closure symbols this file provides. * @const */ this.closureSymbols = closureSymbols; /** * Array of imports in this file. * @const */ this.imports = imports; for (const i of this.imports) { i.from = this; } /** * The language level of this file; e.g. "es3", "es6", etc. * @const */ this.language = language; } }
JavaScript
class Import { /** * @param {string} symOrPath */ constructor(symOrPath) { /** * Dependency this import is contained in. * @type {!Dependency} */ this.from; /** * The Closure symbol or path that is required. * @const */ this.symOrPath = symOrPath; } /** * Asserts that this import edge is valid. * @param {!Dependency} to * @abstract */ validate(to) {} /** * @return {boolean} * @abstract */ isGoogRequire() {} /** * @return {boolean} * @abstract */ isEs6Import() {} }
JavaScript
class Es6Import extends Import { /** @override */ toString() { return `import|export '${this.symOrPath}'`; } /** @override */ validate(to) { if (to.type !== DependencyType.ES6_MODULE) { throw new SourceError( 'Cannot import non-ES6 module: ' + to.path, this.from.path); } } /** @override */ isGoogRequire() { return false; } /** @override */ isEs6Import() { return true; } }
JavaScript
class ModuleResolver { /** * @param {string} fromPath The path of the module that is doing the * importing. * @param {string} importSpec The raw text of the import. * @return {string} The resolved path of the referenced module. */ resolve(fromPath, importSpec) {} }
JavaScript
class Graph { /** * @param {!Array<!Dependency>} dependencies * @param {!ModuleResolver=} moduleResolver */ constructor(dependencies, moduleResolver = new PathModuleResolver()) { /** @const {!Map<string, !Dependency>} */ this.depsBySymbol = new Map(); /** @const {!Map<string, !Dependency>} */ this.depsByPath = new Map(); /** @const */ this.moduleResolver = moduleResolver; for (const dep of dependencies) { if (this.depsByPath.has(dep.path)) { throw new Error('File registered twice? ' + dep.path); } this.depsByPath.set(dep.path, dep); for (const sym of dep.closureSymbols) { const previous = this.depsBySymbol.get(sym); if (previous) { throw new SourceError( `The symbol "${sym}" has already been defined at ` + previous.path, dep.path); } this.depsBySymbol.set(sym, dep); } } this.validate_(); } /** * Validates the dependency graph. * * This method uses Tarjan's algorithm to ensure Closure files are not part * of any cycle. Check it out: * https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm * @private */ validate_() { let index = 0; // Map that assigns each dependency an index in visit-order. const indexMap = new Map(); // Stack of dependencies that are potentially part of the current strongly // connected component. If any dependency has a back pointer it is kept // on the stack. Thus after recursion anything left on the stack above the // current dependency is part of the SCC. If the dependency has no back // pointer the SCC is created from all dependencies on the stack until the // current dependency is popped off and added to the SCC. const depStack = new Set(); const validate = (dep) => { const thisIndex = index++; indexMap.set(dep, thisIndex); let lowIndex = thisIndex; depStack.add(dep); for (const i of dep.imports) { const to = this.resolve_(i); if (!to) { throw new SourceError(`Could not find "${i.symOrPath}".`, dep.path); } i.validate(to); if (!indexMap.has(to)) { // "to" has not been visited, recurse. lowIndex = Math.min(lowIndex, validate(to)); } else if (depStack.has(to)) { // "to" is on the stack and thus a part of the SCC. lowIndex = Math.min(lowIndex, indexMap.get(to)); } // else visited but not on the stack, so it is not part of the SCC. It // is a common dependency of some other tree, but does not reach this // dependency and thus is not strongly connected. } if (lowIndex === thisIndex) { let anyClosure = false; const deps = [...depStack]; const scc = []; for (let i = deps.length - 1; i > -1; i--) { scc.push(deps[i]); depStack.delete(deps[i]); anyClosure = anyClosure || deps[i].type === DependencyType.CLOSURE_PROVIDE || deps[i].type === DependencyType.CLOSURE_MODULE; if (deps[i] === dep) { break; } } if (anyClosure && scc.length > 1) { throw new InvalidCycleError(scc); } } return lowIndex; }; for (const dep of this.depsByPath.values()) { if (!indexMap.has(dep)) { validate(dep); } } } /** * @param {!Import} i * @return {!Dependency} * @private */ resolve_(i) { return i instanceof GoogRequire ? this.depsBySymbol.get(i.symOrPath) : this.depsByPath.get( this.moduleResolver.resolve(i.from.path, i.symOrPath)); } /** * Provides a topological sorting of dependencies given the entrypoints. * * @param {...!Dependency} entrypoints * @return {!Array<!Dependency>} */ order(...entrypoints) { const deps = []; const visited = new Set(); const visit = (dep) => { if (visited.has(dep)) return; visited.add(dep); for (const i of dep.imports) { const next = this.resolve_(i); visit(next); } deps.push(dep); }; for (const entrypoint of entrypoints) { visit(entrypoint); } return deps; } }
JavaScript
class Pixel { static coordinatesToLocation (x, y, width) { return (y * width + x) * 4 } static locationToCoordinates (loc, width) { const y = Math.floor(loc / (width * 4)) const x = (loc % (width * 4)) / 4 return {x, y} } constructor (r = 0, g = 0, b = 0, a = 255, c = null) { this.loc = 0 this.r = r this.g = g this.b = b this.a = a this.c = c } setContext (c) { this.c = c } // Retrieves the X, Y location of the current pixel. The origin is at the bottom left corner of the image, like a normal coordinate system. locationXY () { if (!this.c) { throw new Error('Requires a CamanJS context') } const y = this.c.dimensions.height - Math.floor(this.loc / (this.c.dimensions.width * 4)) const x = (this.loc % (this.c.dimensions.width * 4)) / 4 return {x, y} } pixelAtLocation (loc) { if (!this.c) { throw new Error('Requires a CamanJS context') } return new Pixel( this.c.pixelData[loc], this.c.pixelData[loc + 1], this.c.pixelData[loc + 2], this.c.pixelData[loc + 3], this.c ) } // Returns an RGBA object for a pixel whose location is specified in relation to the current pixel. getPixelRelative (horiz, vert) { if (!this.c) { throw new Error('Requires a CamanJS context') } // We invert the vert_offset in order to make the coordinate system non-inverted. In laymans terms: -1 means down and +1 means up. const newLoc = this.loc + (this.c.dimensions.width * 4 * (vert * -1)) + (4 * horiz) if (newLoc > this.c.pixelData.length || newLoc < 0) { return new Pixel(0, 0, 0, 255, this.c) } return this.pixelAtLocation(newLoc) } // The counterpart to getPixelRelative, this updates the value of a pixel whose location is specified in relation to the current pixel. static putPixelRelative (horiz, vert, rgba) { if (!this.c) { throw new Error('Requires a CamanJS context') } const newLoc = this.loc + (this.c.dimensions.width * 4 * (vert * -1)) + (4 * horiz) if (newLoc > this.c.pixelData.length || newLoc < 0) { return } this.c.pixelData[newLoc] = rgba.r this.c.pixelData[newLoc + 1] = rgba.g this.c.pixelData[newLoc + 2] = rgba.b this.c.pixelData[newLoc + 3] = rgba.a return true } // Gets an RGBA object for an arbitrary pixel in the canvas specified by absolute X, Y coordinates getPixel (x, y) { if (!this.c) { throw new Error('Requires a CamanJS context') } const loc = this.coordinatesToLocation(x, y, this.width) return this.pixelAtLocation(loc) } // Updates the pixel at the given X, Y coordinate putPixel (x, y, rgba) { if (!this.c) { throw new Error('Requires a CamanJS context') } const loc = this.coordinatesToLocation(x, y, this.width) this.c.pixelData[loc] = rgba.r this.c.pixelData[loc + 1] = rgba.g this.c.pixelData[loc + 2] = rgba.b this.c.pixelData[loc + 3] = rgba.a } toString () { this.toKey() } toHex (includeAlpha = false) { let hex = `#${this.r.toString(16)}${this.g.toString(16)}${this.b.toString(16)}` if (includeAlpha) { hex += this.a.toString(16) } return hex } }
JavaScript
class App extends React.Component{ static displayName = 'App'; constructor(props){ super(props); this.state = SettingsStore.getSettings(); this.onChangeListener = this.onChange.bind(this); } componentDidMount() { SettingsStore.addChangeListener(this.onChangeListener); window.addEventListener('resize', this.onChangeListener); } componentWillUnmount() { SettingsStore.removeChangeListener(this.onChangeListener); window.removeEventListener('resize', this.onChangeListener); } onChange(){ let state = SettingsStore.getSettings(); this.setState(state); } render(){ return( <div> <Scene3D forceManualRender={false} cameraPosition={this.state.cameraPosition} cameraQuaternion={this.state.cameraQuaternion} > <World position={new THREE.Vector3(0, 0, 0)} worldRotation={this.state.worldRotation} > </World> <Model key={THREE.Math.generateUUID()} position={new THREE.Vector3(0, 0, 0)} parsedModel={this.state.parsedModel} mergeGeometries={this.state.mergeGeometries} /> </Scene3D> <Stats /> </div> ); } }
JavaScript
class Atm { constructor() { // constants // localStorage data name this.DATA_ATM = 'data_atm'; // balance actions this.NONE = 0; this.SHOW = 1; this.DEPOSIT = 2; this.WITHDRAW = 3; // private properties this.accounts = []; // current values being used this.current = { view: null, account: null, action: this.NONE }; // previous values, using an object for consistency with current this.previous = { view: null }; // View will hold all the DOM for the UI views this.View = { login: new ViewContainer('loginView'), // home screen new: new ViewContainer('newAccountView'), // new account creation account: new ViewContainer('accountView'), // account menu balance: new ViewContainer('balanceView'), // perform any action related to the balance (get, deposit, withdraw) changePIN: new ViewContainer('changePinView') // change current pin }; // controls this.Button = { login: document.getElementById('loginButton'), new: document.getElementById('newAccountButton'), balance: document.getElementById('balanceButton'), changePIN: document.getElementById('changePinButton'), deposit: document.getElementById('depositButton'), withdraw: document.getElementById('withdrawButton'), logout: document.getElementById('logoutButton') }; // alert system this.Alert = new Alert(null); // initialized with no view attached // initializes application and UI // prepare related controls this.prepareControls(); // load accounts from localStorage into accounts:Array this.loadData(); // initializes the UI to show the login view this.View.login.clearForm(); this.openView(this.View.login); console.log('ATM Ready.'); } // assigns control DOM elements and attaches events prepareControls() { // login view this.Button.login.onclick = () => this.login(); this.Button.new.onclick = () => this.openNewAccount(); // new account view this.View.new.setButtons({ accept: () => this.createAccount(), cancel: () => this.goBack() }); // account menu view this.Button.changePIN.onclick = () => this.openChangePIN(); this.Button.balance.onclick = () => this.openBalance(this.SHOW); this.Button.deposit.onclick = () => this.openBalance(this.DEPOSIT); this.Button.withdraw.onclick = () => this.openBalance(this.WITHDRAW); this.Button.logout.onclick = () => this.logout(); // balance form view this.View.balance.setButtons({ accept: () => this.updateBalance(), cancel: () => this.goBack() }); // change pin view this.View.changePIN.setButtons({ accept: () => this.updatePIN(), cancel: () => this.goBack() }); } // attemps to login by looking for the PIN provided login() { // check for validity if(!this.View.login.validateForm()) { return; // if the input is not valid we return the method, and HTML5 will handle the error message } let pin = this.View.login.getValues().pin; // find in accounts for account.pin == pin let validAccount = this.accounts.find(account => account.getPin() == pin); // pin is private in account, we use a getter if(validAccount) { // if found this.openAccountSession(validAccount); } else { // if not validAccount is undefined therefore falsy new Alert(this.View.login).error(ERROR.ACCOUNT_NOT_FOUND); } } /* Sets current account in use and opens the account menu @param account {Account} -> sets the current account for the session */ openAccountSession(account) { this.current.account = account; this.View.account.setText('#nameAccount', account.getName()); this.openView(this.View.account); } // closes current session and returns to login screen logout() { this.View.login.clearForm(); this.current.account = null; // removes the currently open account this.openView(this.View.login); } // open view to create new account openNewAccount() { this.View.new.clearForm(); // clear form inputs this.openView(this.View.new); } // validates the form an adds an account createAccount() { // check for validity on the this.View.new's {ViewContainer} form if(!this.View.new.validateForm()) { return; // stop method if anything in the form is invalid, HTML5 will handle error messages } let errorMessage = null; let values = this.View.new.getValues(); // get form values if(this.doesPINExist(values.pin)) { // if PIN is already used by another account errorMessage = ERROR.message(ERROR.INVALID_PIN); // sent error message } else if(isNaN(values.balance)) { // if balance is not a valid number different than blank errorMessage = ERROR.message(ERROR.INVALID_NUMBER, 'Balance');// sent error message and specified input } else if(parseFloat(values.balance) < 0) { // if balance is < than 0 errorMessage = ERROR.message(ERROR.NEGATIVE_NUMBER, 'Balance'); } // check for errors to show if(errorMessage !== null) { new Alert(this.View.new).error(errorMessage); return; // stop } else { values.balance = parseFloat(values.balance); } // if balance is blank, the account will have a starting balance of 0 let account = new Account(values); this.updateData(account); // open session this.openAccountSession(account); } /* Displays balance view for showing, deposit or withdraw @param action {number} default SHOW -> Identify the action we will be providing on the view */ openBalance(action = this.SHOW) { this.current.action = action; let title = ''; // will let us change the title of the view accordingly let readOnly = false; // for deposit and withdraw we change the input to writable switch(this.current.action) { case this.SHOW: title = 'Balance'; this.View.balance.setValue('amount', this.current.account.getBalance().toFixed(2)); // for show we change the input to readonly readOnly = true; break; case this.DEPOSIT: title = 'Deposit'; this.View.balance.clearForm(); break; case this.WITHDRAW: title = 'Withdraw'; this.View.balance.clearForm(); break; } // set title of the view this.View.balance.get('[name=amount]').readOnly = readOnly; this.View.balance.setText('#title', title); this.openView(this.View.balance); } // Validates values given and attempts to do Deposit and Withdrawal // @param operation {function} -> Account method to execute for the ammount // @return {boolean} -> Determines if the operation was executed balanceOperation(operation) { // check for validity on the this.View.balances's {ViewContainer} form if(!this.View.balance.validateForm()) { return false;// return that form is not valid, HTML5 will handle error messages } let amount = this.View.balance.getValues().amount; // get ammount value let errorMessage = null; if(isNaN(amount)) { // if amount is not a valid number different than blank errorMessage = ERROR.message(ERROR.INVALID_NUMBER, 'Amount'); } else if(parseFloat(amount) <= 0) { // if ammount is <= than 0 errorMessage = ERROR.message(ERROR.NEGATIVE_0_NUMBER, 'Amount'); } else if(!operation(amount)){// attempt to execute operation, if works continue // if doesnt work if(this.current.action === this.DEPOSIT) errorMessage = ERROR.message(ERROR.INVALID_OPERATION, 'operation'); else errorMessage = ERROR.message(ERROR.INVALID_WITHDRAWAL, this.current.account.getBalance()); } // check for errors to show if(errorMessage !== null) { // sent error message about not being a number and set invalid new Alert(this.View.balance).error(errorMessage); return false; } // if function ends normally all data is valid return true; } // update balance of the current account updateBalance() { // determine the action let operation; switch(this.current.action) { case this.SHOW: break; // do nothing case this.DEPOSIT: operation = (value) => this.current.account.deposit(value); // operation will be deposit, need to create anonymous function to keep scope of this case this.WITHDRAW: if(!operation) operation = (value) => this.current.account.withdraw(value); // if operation wasn't defined on deposit, is now withdraw if(!this.balanceOperation(operation)) return; // if there was an error we stop execution // show new balance on Account menu view for 4 seconds new Alert(this.View.account, 4 * 1000).success('Current balance: ' + this.current.account.getBalance().toFixed(2)); // update data this.updateData(); break; } this.current.action = this.NONE; this.goBack(); } openChangePIN() { this.View.changePIN.clearForm(); this.openView(this.View.changePIN); } updatePIN() { // check for validity on the this.View.changePin's {ViewContainer} form // TODO: Think of a reusable more efficient way to do this if(!this.View.changePIN.validateForm()) { return;// stop execution, HTML5 will handle error messages } let errorMessage = null; let values = this.View.changePIN.getValues(); // get values from changePin Form if(values.pin !== this.current.account.getPin()) { // validate the current pin before performing a change errorMessage = ERROR.message(ERROR.INCORRECT_PIN); } else if(this.doesPINExist(values.newPin)) { // checks if new PIN is already used by another account errorMessage = ERROR.message(ERROR.INVALID_PIN, 'new'); } else if(values.newPin !== values.confirmNewPin) {// validate the newPin matches the confirmation errorMessage = ERROR.message(ERROR.NEWPIN_NOT_MATCH); } // check for errors to show let alert = new Alert(this.View.changePIN); if(errorMessage !== null) { // sent error message about not being a number and set invalid alert.error(errorMessage); return; } // procede with the change this.current.account.setPin(values.newPin); // show message of success on account menu alert.setView(this.View.account).success('PIN changed succesfully.'); // udpate data this.updateData(); this.goBack(); } /* Searchs and determinates if the pin given already exists in the Account's list @parameter pin {string} -> PIN to be searched #return {boolean} -> Flag to determinate if the value was found */ doesPINExist(pin) { let exist = this.accounts.find(account => account.getPin() == pin); // find the first account that satisfies account.getPin() == pin return Boolean(exist); // gives a return in strict boolean value } /* Updates the array that contains the accounts and the localStorage @param account {Account} -> new account to be added to the array and storage */ updateData(account) { if(account) this.accounts.push(account); // TODO: find a more efficient way of storing the information on localStorage // Maps accounts into a JSON Array to storage as a string in the localStorage data_atm localStorage.setItem(this.DATA_ATM, JSON.stringify(this.accounts.map(item => item.getJSON()))); } // Initial load of the data from localStorage data_atm loadData() { // initialize data from localStorage if there is not data sets an empty array let data = JSON.parse(localStorage.getItem(this.DATA_ATM)) || []; if(data.length > 0){ // if there is data we need to map into an array of {Account} data = data.map(item => new Account(item)); } // data loaded this.accounts = data; } // hides current view and goes back to the previous View goBack() { if(this.previous.view !== null) { this.openView(this.previous.view); } } /* Hides the view containers that is currently visible and displays the specified one @param container {ViewContainer} -> Object that holds the container to be shown */ openView(view) { if(this.current.view !== null) { this.previous.view = this.current.view; this.current.view.close(); // closes current view } this.current.view = view; this.current.view.open(); // display requested view } }
JavaScript
class NumberBox extends Component { // intialize component constructor(props) { super(props); this.state = {}; this.state.value = this.props.value; } // when component updates componentDidUpdate(prevProps) { if (this.props.value !== prevProps.value) this.setState({ value: this.props.value }); } // when user changes field onChange = (event) => { this.setState({ value: event.target.value }); if (event.nativeEvent.data === undefined) this.onArrows(event.target.value); else this.onType(event.target.value); }; // when user presses key in box onKeyPress = (event) => { if (event.key.toLowerCase() === 'enter') event.target.blur(); }; // when user un-focuses field onBlur = (event) => { this.onSubmit(event.target.value); }; // when box changed via arrow buttons or arrow keys onArrows = (value) => { if (this.props.onArrows) this.props.onArrows(value); }; // when box changed via typing or copy/paste onType = (value) => { if (this.props.onType) this.props.onType(value); }; // when box change submitted onSubmit = (value) => { if (this.props.onSubmit) this.props.onSubmit(value); }; // display component render() { return ( <Tooltip text={this.props.tooltipText}> <input type='number' className='number_box' onChange={this.onChange} onKeyPress={this.onKeyPress} onBlur={this.onBlur} min={this.props.min} step={this.props.step} max={this.props.max} value={this.state.value} /> </Tooltip> ); } }
JavaScript
class TBackendManager extends iteeCore.TAbstractObject { get applications () { return this._applications } set applications ( value ) { this._applications = value; } setApplications ( value ) { this.applications = value; return this } addMiddleware ( middleware ) { this.applications.use( middleware ); return this } // Todo remove middleware get router () { return this._router } set router ( value ) { this._router = value; } setRouter ( value ) { this.router = value; return this } get databases () { return this._databases } set databases ( value ) { this._databases = value; } setDatabases ( value ) { this.databases = value; return this } addDatabase ( databaseName, database ) { this._databases.set( databaseName, database ); return this } get servers () { return this._servers } set servers ( value ) { this._servers = value; } setServers ( value ) { this.servers = value; return this } constructor ( parameters = {} ) { const _parameters = { ...{ logger: iteeCore.DefaultLogger, rootPath: __dirname, applications: [], databases: [], servers: [] }, ...parameters }; super( _parameters ); this.logger = _parameters.logger; this.rootPath = _parameters.rootPath; this.applications = express__default['default'](); this.router = express__default['default'].Router; this.databases = new Map(); this.servers = new Map(); this.connections = []; this._initApplications( _parameters.applications ); this._initDatabases( _parameters.databases ); this._initServers( _parameters.servers ); } get rootPath () { return this._rootPath } set rootPath ( value ) { if ( iteeValidators.isNull( value ) ) { throw new TypeError( 'Root path cannot be null ! Expect a non empty string.' ) } if ( iteeValidators.isUndefined( value ) ) { throw new TypeError( 'Root path cannot be undefined ! Expect a non empty string.' ) } if ( iteeValidators.isNotString( value ) ) { throw new TypeError( `Root path cannot be an instance of ${ value.constructor.name } ! Expect a non empty string.` ) } if ( iteeValidators.isEmptyString( value ) ) { throw new TypeError( 'Root path cannot be empty ! Expect a non empty string.' ) } if ( iteeValidators.isBlankString( value ) ) { throw new TypeError( 'Root path cannot contain only whitespace ! Expect a non empty string.' ) } this._rootPath = value; } setRootPath ( value ) { this.rootPath = value; return this } _initApplications ( config ) { if ( config.case_sensitive_routing ) { this.applications.set( 'case sensitive routing', config.case_sensitive_routing ); } if ( config.env ) { this.applications.set( 'env', config.env ); } if ( config.etag ) { this.applications.set( 'etag', config.etag ); } if ( config.jsonp_callback_name ) { this.applications.set( 'jsonp callback name', config.jsonp_callback_name ); } if ( config.jsonp_escape ) { this.applications.set( 'json escape', config.jsonp_escape ); } if ( config.jsonp_replacer ) { this.applications.set( 'json replacer', config.jsonp_replacer ); } if ( config.jsonp_spaces ) { this.applications.set( 'json spaces', config.jsonp_spaces ); } if ( config.query_parser ) { this.applications.set( 'query parser', config.query_parser ); } if ( config.strict_routing ) { this.applications.set( 'strict routing', config.strict_routing ); } if ( config.subdomain_offset ) { this.applications.set( 'subdomain offset', config.subdomain_offset ); } if ( config.trust_proxy ) { this.applications.set( 'trust proxy', config.trust_proxy ); } if ( config.views ) { this.applications.set( 'views', config.views ); } if ( config.view_cache ) { this.applications.set( 'view cache', config.view_cache ); } if ( config.view_engine ) { this.applications.set( 'view engine', config.view_engine ); } if ( config.x_powered_by ) { this.applications.set( 'x-powered-by', config.x_powered_by ); } this._initMiddlewares( config.middlewares ); this._initRouters( config.routers ); } _initMiddlewares ( middlewaresConfig ) { for ( let [ name, config ] of Object.entries( middlewaresConfig ) ) { if ( iteeValidators.isNotArray( config ) ) { throw new TypeError( `Invalid middlware configuration for ${ name }, expecting an array of arguments to spread to middleware module, got ${ config.constructor.name }` ) } if ( this._initPackageMiddleware( name, config ) ) { this.logger.log( `Use ${ name } middleware from node_modules` ); } else if ( this._initLocalMiddleware( name, config ) ) { this.logger.log( `Use ${ name } middleware from local folder` ); } else { this.logger.error( `Unable to register the middleware ${ name } the package and/or local file doesn't seem to exist ! Skip it.` ); } } } _initPackageMiddleware ( name, config ) { let success = false; try { this.applications.use( require( name )( ...config ) ); success = true; } catch ( error ) { if ( !error.code || error.code !== 'MODULE_NOT_FOUND' ) { this.logger.error( `The middleware "${ name }" seems to encounter internal error.` ); this.logger.error( error ); } } return success } _initLocalMiddleware ( name, config ) { let success = false; try { const localMiddlewaresPath = path__default['default'].join( this.rootPath, 'middlewares', name ); this.applications.use( require( localMiddlewaresPath )( ...config ) ); success = true; } catch ( error ) { this.logger.error( error ); } return success } _initRouters ( routers ) { for ( let [ baseRoute, routerPath ] of Object.entries( routers ) ) { if ( this._initPackageRouter( baseRoute, routerPath ) ) { this.logger.log( `Use ${ routerPath } router from node_modules over base route: ${ baseRoute }` ); } else if ( this._initLocalRouter( baseRoute, routerPath ) ) { this.logger.log( `Use ${ routerPath } router from local folder over base route: ${ baseRoute }` ); } else { this.logger.error( `Unable to register the router ${ routerPath } the package and/or local file doesn't seem to exist ! Skip it.` ); } } } _initPackageRouter ( baseRoute, routerPath ) { let success = false; try { this.applications.use( baseRoute, require( routerPath ) ); success = true; } catch ( error ) { if ( !error.code || error.code !== 'MODULE_NOT_FOUND' ) { this.logger.error( `The router "${ name }" seems to encounter internal error.` ); this.logger.error( error ); } } return success } _initLocalRouter ( baseRoute, routerPath ) { let success = false; try { const localRoutersPath = path__default['default'].join( this.rootPath, 'routers', routerPath ); this.applications.use( baseRoute, require( localRoutersPath ) ); success = true; } catch ( error ) { if ( error instanceof TypeError && error.message === 'Found non-callable @@iterator' ) { this.logger.error( `The router "${ name }" seems to encounter error ! Are you using an object instead an array for router configuration ?` ); } this.logger.error( error ); } return success } _initDatabases ( config ) { for ( let configIndex = 0, numberOfDatabasesConfigs = config.length ; configIndex < numberOfDatabasesConfigs ; configIndex++ ) { const databaseConfig = config[ configIndex ]; const dbType = databaseConfig.type; const dbFrom = databaseConfig.from; const dbName = `${ ( databaseConfig.name ) ? databaseConfig.name : `${ dbType }_${ configIndex }` }`; try { let database = null; if ( iteeValidators.isDefined( dbFrom ) ) { // In case user specify a package where take the database of type... const databasePackage = require( dbFrom ); database = new databasePackage[ dbType ]( { ...{ application: this.applications, router: this.router }, ...databaseConfig } ); } else { // // Else try to use auto registered database // database = new Databases[ dbType ]( { // ...{ // application: this.applications, // router: this.router // }, // ...databaseConfig // } ) } // Todo move in start database.connect(); this.databases.set( dbName, database ); } catch ( error ) { this.logger.error( `Unable to create database of type ${ dbType } due to ${ error.name }` ); this.logger.error( error.message ); this.logger.error( error.stack ); } } } _initServers ( config ) { const _config = ( iteeValidators.isArray( config ) ) ? config : [ config ]; for ( let configId = 0, numberOfConfigs = _config.length ; configId < numberOfConfigs ; configId++ ) { let configElement = _config[ configId ]; let server = null; if ( configElement.type === 'https' ) { const options = { pfx: configElement.pfx, passphrase: configElement.passphrase }; server = https__default['default'].createServer( options, this.applications ); } else { server = http__default['default'].createServer( this.applications ); } server.name = configElement.name || `${ ( configElement.name ) ? configElement.name : `Server_${ configId }` }`; server.maxHeadersCount = configElement.max_headers_count; server.timeout = configElement.timeout; server.type = configElement.type; server.host = configElement.host; server.port = configElement.port; server.env = configElement.env; server.listen( configElement.port, configElement.host, () => { this.logger.log( `${ server.name } start listening on ${ server.type }://${ server.host }:${ server.port } at ${ new Date() } under ${ server.env } environment.` ); } ); server.on( 'connection', connection => { this.connections.push( connection ); connection.on( 'close', () => { this.connections = this.connections.filter( curr => curr !== connection ); } ); } ); this.servers.set( server.name, server ); } } /** * * @param databaseKey * @param eventName * @param callback */ databaseOn ( databaseKey, eventName, callback ) {} // eslint-disable-line no-unused-vars serverOn ( serverName, eventName, callback ) { this.servers[ serverName ].on( eventName, callback ); } serversOn ( serverKey, eventName, callback ) { //TODO: filter availaible events // [ 'request', 'connection', 'close', 'timeout', 'checkContinue', 'connect', 'upgrade', 'clientError' ] for ( let serverKey in this.servers ) { this.serverOn( serverKey, eventName, callback ); } } start () { } stop ( callback ) { const numberOfServers = this.servers.size; const numberOfDatabases = this.databases.size; let shutDownServers = 0; let closedDatabases = 0; if ( allClosed() ) { return } for ( const [ databaseName, database ] of this.databases ) { database.close( () => { closedDatabases++; this.logger.log( `Connection to ${ databaseName } is closed.` ); allClosed(); } ); } for ( let connection of this.connections ) { connection.end(); } for ( const [ serverName, server ] of this.servers ) { server.close( () => { shutDownServers++; this.logger.log( `The ${ serverName } listening on ${ server.type }://${ server.host }:${ server.port } is shutted down.` ); allClosed(); } ); } function allClosed () { if ( shutDownServers < numberOfServers ) { return false } if ( closedDatabases < numberOfDatabases ) { return false } if ( callback ) { callback(); } } } closeServers () { } }
JavaScript
class App extends __WEBPACK_IMPORTED_MODULE_0_react___default.a.PureComponent { getChildContext() { return this.props.context; } render() { // NOTE: If you need to add or modify header, footer etc. of the app, // please do that inside the Layout component. return __WEBPACK_IMPORTED_MODULE_0_react___default.a.Children.only(this.props.children); } }
JavaScript
class ServerInterface { constructor(optionsData) { this.schema = optionsData.schema; this.optionsData = optionsData; } query({ query, variables, operationName }) { var _this = this; return _asyncToGenerator(function* () { try { let validationRules = __WEBPACK_IMPORTED_MODULE_0_graphql__["specifiedRules"]; const customValidationRules = _this.optionsData.validationRules; if (customValidationRules) { validationRules = validationRules.concat(customValidationRules); } const validationErrors = __WEBPACK_IMPORTED_MODULE_0_graphql__["validate"](_this.schema, query, validationRules); if (validationErrors.length > 0) { return { errors: validationErrors }; } const result = yield __WEBPACK_IMPORTED_MODULE_0_graphql__["execute"](_this.schema, query, _this.optionsData.rootValue, _this.optionsData.context, variables, operationName); return result; } catch (contextError) { return { errors: [contextError] }; } })(); } }
JavaScript
class InsufficientScopeError extends OAuthError { constructor(message = '', properties) { super(message, { code: 403, name: 'insufficient_scope', ...properties }); } }
JavaScript
class KibanaNotebooksPlugin { setup(core) { // Register an application into the side navigation menu core.application.register({ id: _common__WEBPACK_IMPORTED_MODULE_1__["PLUGIN_ID"], title: _common__WEBPACK_IMPORTED_MODULE_1__["PLUGIN_NAME"], category: _src_core_public__WEBPACK_IMPORTED_MODULE_0__["DEFAULT_APP_CATEGORIES"].kibana, order: 8040, async mount(params) { // Load application bundle const { renderApp } = await Promise.all(/*! import() */[__webpack_require__.e(0), __webpack_require__.e(1)]).then(__webpack_require__.bind(null, /*! ./application */ "./public/application.tsx")); // Get start services as specified in kibana.json const [coreStart, depsStart] = await core.getStartServices(); // Render the application return renderApp(coreStart, depsStart, params); } }); // Return methods that should be available to other plugins return {}; } start(core) { return {}; } stop() {} }
JavaScript
class TopicContainer extends React.Component { constructor() { super(); this.setSideBarContent = this.setSideBarContent.bind(this); } state = { sideBarContent: null, }; componentDidUpdate(prevProps) { const { dispatch, location, topicId, filters } = this.props; const snapshotIdChanged = location.query.snapshotId !== prevProps.location.query.snapshotId; if (snapshotIdChanged) { fetchAsyncData(dispatch, this.props); return; } const focusIdChanged = location.query.focusId !== prevProps.location.query.focusId; if (focusIdChanged) { // mark that we are startin the complicated async-driven parsing of filter vaules dispatch(updateTopicFilterParsingStatus(FILTER_PARSING_ONGOING)); pickDefaultFocusId(dispatch, topicId, filters.snapshotId, location.query.focusId, null, location, true); } } setSideBarContent(sideBarContent) { this.setState({ sideBarContent }); } render() { const { children, topicInfo, topicId, filters, snapshot, userIsAdmin } = this.props; let content = (<LoadingSpinner />); if (filters.parsingStatus === FILTER_PARSING_DONE) { // pass a handler to all the children so the can set the control bar side content if they need to const childrenWithExtraProp = React.Children.map(children, child => React.cloneElement(child, { setSideBarContent: this.setSideBarContent })); content = ( <> <TopicControlBar {...this.props} topicId={topicId} topic={topicInfo} sideBarContent={this.state.sideBarContent} // implements handleRenderFilters and evaluates showFilters /> <NeedsNewVersionWarning /> {childrenWithExtraProp} </> ); } return ( <div className="topic-container"> <PageTitle value={topicInfo.name} /> <TopicHeaderContainer topicId={topicId} topicInfo={topicInfo} currentVersion={snapshot ? snapshot.note : 1} filters={filters} /> { !userIsAdmin && ( <div className="warning-background"> <Grid> <Row> <Col lg={12}> <WarningNotice> <FormattedMessage {...localMessages.topicsReadOnly} /> </WarningNotice> </Col> </Row> </Grid> </div> )} {content} </div> ); } }
JavaScript
class RouteConfig { constructor(configs) { this.configs = configs; } }
JavaScript
class Route extends AbstractRoute { constructor({ name, useAsDefault, path, regex, serializer, data, component }) { super({ name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.aux = null; this.component = component; } }
JavaScript
class AuxRoute extends AbstractRoute { constructor({ name, useAsDefault, path, regex, serializer, data, component }) { super({ name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.component = component; } }
JavaScript
class AsyncRoute extends AbstractRoute { constructor({ name, useAsDefault, path, regex, serializer, data, loader }) { super({ name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.aux = null; this.loader = loader; } }
JavaScript
class Redirect extends AbstractRoute { constructor({ name, useAsDefault, path, regex, serializer, data, redirectTo }) { super({ name: name, useAsDefault: useAsDefault, path: path, regex: regex, serializer: serializer, data: data }); this.redirectTo = redirectTo; } }
JavaScript
class TargetElements extends core_1.Question { /** * @desc * * @param {string} description - A human-readable description to be used in the report * @param {protractor~Locator} locator - A locator to be used when locating the element */ constructor(description, locator) { super(`the ${description}`); this.description = description; this.locator = locator; this.list = new core_1.List(new lists_1.ElementArrayFinderListAdapter(this)); } /** * @desc * Retrieves a group of {@link WebElement}s located by `locator`, * resolved in the context of a `parent` {@link WebElement}. * * @param {Question<ElementFinder> | ElementFinder} parent * @returns {TargetNestedElements} * * @see {@link Target} */ of(parent) { return new TargetNestedElements_1.TargetNestedElements(parent, this); } /** * @desc * Returns the number of {@link ElementFinder}s matched by the `locator` * * @returns {@serenity-js/core/lib/screenplay~Question<Promise<number>>} * * @see {@link @serenity-js/core/lib/screenplay/questions~List} */ count() { return this.list.count(); } /** * @desc * Returns the first of {@link ElementFinder}s matched by the `locator` * * @returns {@serenity-js/core/lib/screenplay~Question<ElementFinder>} * * @see {@link @serenity-js/core/lib/screenplay/questions~List} */ first() { return this.list.first(); } /** * @desc * Returns the last of {@link ElementFinder}s matched by the `locator` * * @returns {@serenity-js/core/lib/screenplay~Question<ElementFinder>} * * @see {@link @serenity-js/core/lib/screenplay/questions~List} */ last() { return this.list.last(); } /** * @desc * Returns an {@link ElementFinder} at `index` for `locator` * * @param {number} index * * @returns {@serenity-js/core/lib/screenplay~Question<ElementFinder>} * * @see {@link @serenity-js/core/lib/screenplay/questions~List} */ get(index) { return this.list.get(index); } /** * @desc * Filters the list of {@link ElementFinder}s matched by `locator` to those that meet the additional {@link @serenity-js/core/lib/screenplay/questions~Expectation}s. * * @param {@serenity-js/core/lib/screenplay/questions~MetaQuestion<ElementFinder, Promise<Answer_Type> | Answer_Type>} question * @param {@serenity-js/core/lib/screenplay/questions~Expectation<any, Answer_type>} expectation * * @returns {@serenity-js/core/lib/screenplay/questions~List<ElementArrayFinderListAdapter, ElementFinder, ElementArrayFinder>} * * @see {@link @serenity-js/core/lib/screenplay/questions~List} */ where(question, expectation) { return this.list.where(question, expectation); } /** * @desc * Makes the provided {@link @serenity-js/core/lib/screenplay/actor~Actor} * answer this {@link @serenity-js/core/lib/screenplay~Question}. * * @param {AnswersQuestions & UsesAbilities} actor * @returns {Promise<void>} * * @see {@link @serenity-js/core/lib/screenplay/actor~Actor} * @see {@link @serenity-js/core/lib/screenplay/actor~AnswersQuestions} * @see {@link @serenity-js/core/lib/screenplay/actor~UsesAbilities} */ answeredBy(actor) { return (0, override_1.override)(abilities_1.BrowseTheWeb.as(actor).locateAll(this.locator), 'toString', TargetElements.prototype.toString.bind(this)); } }
JavaScript
class Blacksmith extends Location { constructor() { super({ type: 'tyrose-shoppes-blacksmith', displayName: "Jack Blacksmith", buttonText: "Blacksmith", description: "Standing before the forge is a swarthy man, heating the forge to a terrifying degree with his bellows. Noticing your presence, he ambles over.", image: 'locations/tyrose/weapon_shop.png', connectedLocations: [ 'tyrose-shoppes', ], shopEquipment: { 'weapons': { shopText: 'Buy Weapons', equipment: [ 'equipment-weapons-001_pine_club', 'equipment-weapons-002_ash_club', 'equipment-weapons-004_oak_club', 'equipment-weapons-006_ironwood_club', ], }, 'armour': { shopText: 'Buy Armour', equipment: [ 'equipment-armour-001_clothes', 'equipment-armour-003_padded_cloth', 'equipment-armour-005_patched_leather', 'equipment-armour-007_clean_leather', ] } }, shopItems: { 'premium': { shopText: 'Premium Goods', style: 'primary', items: [ 'consumables-ambrosia', 'blessed_key', 'boost-max_ap' ], }, } }); } /** * Get any extra description for the shop type the user is looking at. * * @param {Character} character - The character doing the shopping. * @param {string} shopType - The type of shop the character is shopping at. * * @return {string} */ getShopDescription(character, shopType) { let description = ''; if ('premium' === shopType) { description = "\n\n*\"Ah yes, an eye for the finer things,\"* he says. \"If you have any _Dragon Scales,_ I can sell you some of these highly exclusive items. _Dragon Scales_, of course, can be purchased just over here:\"\n\n" + Text.getBuyUrl(character); } return description + super.getShopDescription(character, shopType); } }
JavaScript
class ProxyPlayer extends Player { constructor(gameClient, player, nameReadOnly = false) { super(player.name); this.nameReadOnly = nameReadOnly; this.nameLocked = false; const setName = debounce((name) => { this.nameLocked = false; super.setName(name); }, ProxyPlayer.DebounceInterval); this.setName = (name) => { this.nameLocked = true; setName(name); }; this.updateName = (name) => { if (!this.nameLocked) super.setName(name); }; this.updateScore = super.setScore.bind(this); this.handleNameChanged = this.handleNameChanged.bind(this); this.handleScoreChanged = this.handleScoreChanged.bind(this); this.handleMoved = this.handleMoved.bind(this); this.setPlayer(player); this.setGameClient(gameClient); } setGameClient(gameClient) { this.gameClient = gameClient; } setPlayer(player) { if (this.player != null) { this.player.nameChanged.disconnect(this.handleNameChanged); this.player.scoreChanged.disconnect(this.handleScoreChanged); this.player.moved.disconnect(this.handleMoved); } this.player = player; if (this.player != null) { this.player.nameChanged.connect(this.handleNameChanged); this.player.scoreChanged.connect(this.handleScoreChanged); this.player.moved.connect(this.handleMoved); } } setName(name) { if (!this.player) return; if (this.nameReadOnly && this.name) { if (name !== this.player.name) // discard this.nameChanged(this.player.name); return; } this.player.setName(name); } setMatch(match) { super.setMatch(match); this.player.setMatch(match); } setIndex(index) { super.setIndex(index); this.player.setIndex(index); } setMark(mark) { super.setMark(mark); this.player.setMark(mark); } setScore(score) { this.player.setScore(score); } handleNameChanged(player) { this.gameClient.updatePlayer(this, 'name', player.name); } handleScoreChanged(player) { this.gameClient.updatePlayer(this, 'score', player.score); } handleMoved(player, row, column) { this.gameClient.movePlayer(this, row, column); } updatePlayer(action) { switch (action.propertyName) { case 'name': this.updateName(action.propertyValue); break; case 'score': this.updateScore(action.propertyValue); break; default: break; } } passMove() { this.player.passMove(); } move(row, column) { this.player.move(row, column); } movePlayer(action) { this.moved(this, action.row, action.column); } isSelf() { return this.gameClient.player === this.player; } }
JavaScript
class Demo3 extends React.Component { constructor(props) { super(props); // Setup the diagram engine this.engine = new RJD.DiagramEngine(); this.engine.registerNodeFactory(new RJD.DefaultNodeFactory()); this.engine.registerLinkFactory(new RJD.DefaultLinkFactory()); this.engine.registerNodeFactory(new DiamondWidgetFactory()); // Setup the diagram model this.model = new RJD.DiagramModel(); } componentDidMount() { setTimeout(() => { this.testSerialization(); }, 1000); } createNode(options) { const { name, color, x, y } = options; var node = new RJD.DefaultNodeModel(name, color); node.x = x; node.y = y; return node; } createPort(node, options) { const { isInput, id, name } = options; return node.addPort(new RJD.DefaultPortModel(isInput, id, name)); } linkNodes(port1, port2) { const link = new RJD.LinkModel(); link.setSourcePort(port1); link.setTargetPort(port2); return link; } testSerialization() { const { engine, model } = this; // We need this to help the system know what models to create form the JSON engine.registerInstanceFactory(new RJD.DefaultNodeInstanceFactory()); engine.registerInstanceFactory(new RJD.DefaultPortInstanceFactory()); engine.registerInstanceFactory(new RJD.LinkInstanceFactory()); engine.registerInstanceFactory(new DiamondNodeFactory()); engine.registerInstanceFactory(new DiamondPortFactory()); // Serialize the model const str = JSON.stringify(model.serializeDiagram()); console.log(str); // Deserialize the model const model2 = new RJD.DiagramModel(); model2.deSerializeDiagram(JSON.parse(str),engine); engine.setDiagramModel(model2); console.log(model2); } render() { const { engine, model } = this; // Create first node and port const node1 = this.createNode({ name: 'Node 1', color: 'rgb(0, 192, 255)', x: 100, y: 150 }); const port1 = this.createPort(node1, { isInput: false, id: 'out-1', name: 'Out' }); // Create the diamond node const diamondNode = new DiamondNodeModel(); diamondNode.x = 400; diamondNode.y = 100; // Create second node and port const node2 = this.createNode({ name: 'Node 2', color: 'red', x: 800, y: 150 }); const port2 = this.createPort(node2, { isInput: true, id: 'in-1', name: 'In' }); // Add the nodes and link to the model model.addNode(node1); model.addNode(diamondNode); model.addNode(node2); model.addLink(this.linkNodes(port1, diamondNode.ports['left'])); model.addLink(this.linkNodes(diamondNode.ports['right'], port2)); // Load the model into the diagram engine engine.setDiagramModel(model); // Render the canvas return <RJD.DiagramWidget diagramEngine={engine} />; } }
JavaScript
class AffinityInformation { /** * Create a AffinityInformation. * @property {string} affinityId An opaque string representing the location * of a compute node or a task that has run previously. You can pass the * affinityId of a compute node to indicate that this task needs to run on * that compute node. Note that this is just a soft affinity. If the target * node is busy or unavailable at the time the task is scheduled, then the * task will be scheduled elsewhere. */ constructor() { } /** * Defines the metadata of AffinityInformation * * @returns {object} metadata of AffinityInformation * */ mapper() { return { required: false, serializedName: 'AffinityInformation', type: { name: 'Composite', className: 'AffinityInformation', modelProperties: { affinityId: { required: true, serializedName: 'affinityId', type: { name: 'String' } } } } }; } }
JavaScript
class TaskConstraints { /** * Create a TaskConstraints. * @property {moment.duration} [maxWallClockTime] The maximum elapsed time * that the task may run, measured from the time the task starts. If the task * does not complete within the time limit, the Batch service terminates it. * If this is not specified, there is no time limit on how long the task may * run. * @property {moment.duration} [retentionTime] The minimum time to retain the * task directory on the compute node where it ran, from the time it * completes execution. After this time, the Batch service may delete the * task directory and all its contents. The default is 7 days, i.e. the task * directory will be retained for 7 days unless the compute node is removed * or the job is deleted. * @property {number} [maxTaskRetryCount] The maximum number of times the * task may be retried. The Batch service retries a task if its exit code is * nonzero. Note that this value specifically controls the number of retries * for the task executable due to a nonzero exit code. The Batch service will * try the task once, and may then retry up to this limit. For example, if * the maximum retry count is 3, Batch tries the task up to 4 times (one * initial try and 3 retries). If the maximum retry count is 0, the Batch * service does not retry the task after the first attempt. If the maximum * retry count is -1, the Batch service retries the task without limit. */ constructor() { } /** * Defines the metadata of TaskConstraints * * @returns {object} metadata of TaskConstraints * */ mapper() { return { required: false, serializedName: 'TaskConstraints', type: { name: 'Composite', className: 'TaskConstraints', modelProperties: { maxWallClockTime: { required: false, serializedName: 'maxWallClockTime', type: { name: 'TimeSpan' } }, retentionTime: { required: false, serializedName: 'retentionTime', type: { name: 'TimeSpan' } }, maxTaskRetryCount: { required: false, serializedName: 'maxTaskRetryCount', type: { name: 'Number' } } } } }; } }
JavaScript
class MVC { /** * @constructor * @param opts */ constructor(opts) { /** * Define scope * @property MVC.scope * @type {{eventManager, config}} */ this.scope = opts.scope || {}; /** * Define MVC Relationship from -> to * @property MVC.RELATIONS * @type {Array} */ this.RELATIONS = [ ['Controller', 'Model'], ['View', 'Controller'] ]; /** * Define local defaults * @type {string[]} */ const singular = [ 'Workspace', 'Page', 'Widget' ], plural = [ 'Workspaces', 'Pages', 'Widgets' ]; /** * Default logger config * @property MVC.LOGGER_CONFIG * @type {{ * show: boolean, * handle: boolean, * type: {warn: boolean, debug: boolean, log: boolean, error: boolean, info: boolean}, * namespaces: boolean * }} */ this.LOGGER_CONFIG = { handle: false, show: false, namespaces: false, type: { debug: false, log: false, info: false, error: false, warn: false } }; /** * Define reserved methods * @property MVC.RESERVED * @type {{ * create: {singular: Array}, * destroy: {singular: Array, plural: Array} * resize: {singular: Array, plural: Array} * }} */ this.RESERVED = { resize: { singular: singular, plural: plural }, create: { singular: singular }, destroy: { singular: singular, plural: plural } }; /** * Define default listeners * @property MVC.DEFAULT_LISTENERS * @type {{ * beforeInitConfig: string, * afterInitConfig: string, * successCreated: string, * successRendered: string, * afterCreateItem: string, * afterDestroyItem: string, * afterDestroyItems: string, * afterResizeWindow: string, * successRenderHeader: string, * successRenderFooter: string, * bindModelObserver: string, * defineGenericGetter: string, * openUrlOnEvent: string, * successCreateElement: string, * successBuildElement: string, * successDestroyElement: string * }} */ this.DEFAULT_LISTENERS = { beforeInitConfig: 'before.init.config', afterInitConfig: 'after.init.config', successCreated: 'success.created', successRendered: 'success.rendered', afterCreateItem: 'after.create.item', afterDestroyItem: 'after.destroy.item', afterDestroyItems: 'after.destroy.items', afterResizeWindow: 'after.resize.window', successRenderHeader: 'success.render.header', successRenderFooter: 'success.render.footer', bindModelObserver: 'bind.model.observer', defineGenericGetter: 'define.generic.getter', openUrlOnEvent: 'open.url.on.event', successCreateElement: 'success.create.element', successBuildElement: 'success.build.element', successDestroyElement: 'success.destroy.element' }; /** * Reset opts * @type {*} */ opts = opts || {}; /** * Apply Configure * Define selfConfig * @type {*} */ const selfConfig = opts.config[0] || {}; /** * Define selfDefaults * @type {*} */ const selfDefaults = opts.config[1] || {}; /** * Define scope config * @property MVC.scope * @type {*} */ this.scope.config = window.$.extend(true, {}, selfDefaults, selfConfig); /** * Define mvc components * @property MVC * @type {MVC.components} */ this.components = opts.components || []; /** * Define mvc force creating components * @property MVC * @type {boolean} */ this.force = !!opts.force; /** * Define mvc render * @property MVC * @type {boolean} */ this.render = typeof opts.render === 'undefined' ? true : opts.render; /** * Define event manager * @property BaseEvent * @type {Object} */ this.scope.eventManager = {}; this.init(); /** * Define local instance of eventList * @property BaseEvent.eventManager * @type {Object} */ const eventList = this.scope.eventManager.eventList; if (eventList) { // Publish before InitConfig event this.scope.observer.publish(eventList.beforeInitConfig, ['Config before create', Object.assign({}, this.scope.config)]); // Publish after InitConfig event this.scope.observer.publish(eventList.afterInitConfig, ['Config after create', this.scope.config]); } } /** * Init MVC * @property MVC */ init() { this.applyLogger(); this.defineContainment(); this.applyConfig(); this.applyMVC(); this.applyEventManager(); this.applyPermissions(); } /** * Define parent node * @property MVC */ defineContainment() { /** * @type {{containment, eventManager, config}} */ const scope = this.scope, config = scope.config; if (config.containment) { /** * Define parent node * @property AntHill * @type {*} */ scope.containment = config.containment; delete config.containment; } } /** * Define MVC * @property MVC * @param {Function|String} mvcPattern * @param {boolean} [force] * @returns {*} */ defineMVC(mvcPattern, force) { const scope = this.scope; let name = mvcPattern; if (mvcPattern) { /** * Define name space * @type {string} */ name = mvcPattern.name.replace(scope.name, ''); name = name.match(/[a-z]/g) ? name.toCamelCase() : name.toLowerCase(); /** * Define pattern * @type {*} */ scope[name] = new mvcPattern(null, scope); } else if (force) { /** * Define scope name * @type {string} */ const scopeName = scope.name.toLowerCase(); /** * Define function * @type {Function} */ const fn = new Function(scopeName, [ 'return function ', mvcPattern, '(null,', scopeName, ') { this.scope = ', scopeName, '; };' ].join('') ); scope[name.toLowerCase()] = new (new fn(scope))(scope); } return name; } /** * Set relation between MVC components * @property MVC */ setRelation() { const relations = this.RELATIONS, l = relations.length, scope = this.scope; let from, to; for (let i = 0; i < l; i += 1) { const relation = relations[i]; from = relation[0].toLowerCase(); to = relation[1].toLowerCase(); if (scope[from] && scope[to]) { /** * Define relation * @property {BaseController|BaseModel|BaseView} */ scope[from][to] = scope[to]; } } } /** * Apply MVC * @property MVC * @returns {boolean} */ applyMVC() { const l = this.components.length; for (let i = 0; i < l; i += 1) { /** * Get mvc component * @type {*} */ const mvc = this.components[i]; if (!mvc) { this.scope.logger.warn('Undefined pattern', i, this.components); return false; } const pattern = this.defineMVC(mvc, this.force), ref = this.scope[pattern]; /** * Define scope * @type {*} * @property {BaseController|BaseModel|BaseView} */ ref.scope = this.scope; this.applyMVCShims(pattern); } this.setRelation(); } /** * Apply MVC shims * @property MVC * @param pattern */ applyMVCShims(pattern) { // Get scope const scope = this.scope; if (pattern === 'view') { /** * Define elements * @property BaseView * @type {Object} */ scope.view.elements = {}; } if (!scope.controller) { scope.logger.warn('Undefined controller'); return false; } if (pattern === 'model' && scope.controller.isWidgetContent()) { /** * Define preferences * @property BaseModel * @type {Object} */ scope.model.preferences = scope.model.preferences || {}; } } /** * Apply config * @property MVC */ applyConfig() { const scope = this.scope, timestamp = scope.utils.ts.timestamp(this.scope.config.timestamp), config = scope.config; config.uuid = LibGenerator.UUID(this.scope.config.uuid); config.timestamp = timestamp; if (this.render) { config.html = config.html || {}; config.html.selector = scope.name.toDash(); } } /** * Apply event manager * @property MVC */ applyEventManager() { const scope = this.scope, eventManager = scope.eventManager; if (!eventManager || !eventManager.eventList) { scope.logger.warn('Undefined Event manager'); return false; } this.applyGlobalEvents(); eventManager.scope = scope; eventManager.abstract = eventManager.abstract || {}; const eventList = eventManager.eventList; for (let index in eventList) { if (Object.prototype.hasOwnProperty.call(eventList, index)) { const event = eventList[index]; const controller = scope.controller; if (controller) { const callback = eventManager.createCallback(scope, index, this.RESERVED); eventManager.subscribe({ event, callback }, true); } else { scope.logger.warn('Controller is not defined', event); } } } this.applyDefaultListeners(); scope.logger.debug('Subscribe events', eventManager); this.applyListeners('local'); this.applyListeners('global'); } /** * Apply default listeners * @property MVC */ applyDefaultListeners() { /** * Local instance of default listeners * @type {*} */ const listeners = this.DEFAULT_LISTENERS; const scope = this.scope; /** * @type {BaseController} */ const controller = scope.controller; if (!controller) { scope.logger.warn('Controller is not defined yet'); return false; } for (let index in listeners) { if (Object.prototype.hasOwnProperty.call(listeners, index)) { scope.eventManager.subscribe({ event: listeners[index], callback: controller[index] }, true); } } } /** * Apply global events * @property MVC */ applyGlobalEvents() { // Get scope const scope = this.scope, eventManager = scope.eventManager; if (scope.globalEvents) { for (let index in scope.globalEvents) { if (Object.prototype.hasOwnProperty.call(scope.globalEvents, index)) { let event = scope.globalEvents[index]; if (Object.prototype.hasOwnProperty.call(eventManager.eventList, index)) { scope.logger.warn('Event already defined', index, event); } else { scope.logger.debug('Add event', index, event); eventManager.eventList[index] = event; } } } } else { scope.logger.debug('No global events'); } } /** * Apply listeners * @property MVC */ applyListeners(type) { const scope = this.scope, listener = `${type}Listeners`; /** * Define scope listener * @type {globalListeners|localListeners} */ const scopeListener = scope[listener]; if (typeof scopeListener === 'object') { for (let index in scopeListener) { if (Object.prototype.hasOwnProperty.call(scopeListener, index)) { /** * Define local instance of an event * @type {*} */ let event = scopeListener[index]; scope.eventManager.subscribe({ event: { name: event.name, params: event.params, scope: event.scope }, callback: event.callback }, false); } } } scope.logger.debug(`Apply ${type} listeners`, scope[listener]); } /** * Define permissions * @property MVC * @returns {boolean} */ applyPermissions() { if (!Object.prototype.hasOwnProperty.call(this.scope.config, 'plugin')) { this._applyPermissions('local'); this._applyPermissions('global'); } /** * Get scope * @type {mvc.scope|{permission, controller, logger}} */ const scope = this.scope; /** * Get permissions * @type {BasePermission|{capability, init}} */ const permission = scope.permission; if (!permission) { scope.logger.warn('Undefined permissions'); return false; } permission.init ? permission.init() : scope.logger.warn('No permissions config (Extend BasePermission)', permission); scope.logger.debug('Local permissions', permission); } /** * Apply global permissions * @property MVC * @returns {*|boolean} */ _applyPermissions(type) { const scope = this.scope; if (!scope.controller) { scope.logger.warn('Controller must be defined for using permissions', type); return false; } const mode = scope.controller.getMode(), permission = `${type}Permissions`; /** * Define permission params * @type {globalPermissions|localPermissions} */ const scopePermission = scope[permission]; if (!mode) { scope.logger.warn(`Undefined ${type} mode`); return false; } if (!scopePermission) { scope.logger.warn(`Undefined ${type} permission`); scope.constructor.prototype[permission] = {}; } // Define capability const capabilities = (scopePermission || {})[mode]; if (!capabilities) { scope.logger.warn(`Undefined ${type} capabilities`, mode); scope.constructor.prototype[permission][mode] = {}; } scope.logger.debug(`Apply ${type} permissions`, capabilities); if (!scope.config.permission) { scope.config.permission = {}; } scope.config.permission = {...scope.config.permission, ...capabilities}; } /** * Apply Logger * @property MVC.applyLogger */ applyLogger() { this.scope.logger.setConfig(this.scope.config.logger || this.LOGGER_CONFIG); } }
JavaScript
class ViewTransaction extends Component { static navigationOptions = ({navigation}) => { const {transaction} = navigation.state.params return { title: 'View Transaction', headerRight: ( <TouchableOpacity onPress={() => navigation.navigate('UpdateTransaction', {transaction})} style={{paddingRight: 15}}> <Image source={require('../images/pencil.png')} style={{height: 25, width: 25}}/> </TouchableOpacity> ) } } componentWillMount(){ //Anzuzeigende Transaktion wird über Properties übergeben const {transaction} = this.props.navigation.state.params this.setState({ transaction }) } render() { const transaction = this.state.transaction return ( <View style={styles.container}> <View style={styles.item}> <Text style={styles.title}>Name</Text> <Text style={styles.input}>{transaction.name}</Text> </View> <View style={styles.item}> <Text style={styles.title}>Budget</Text> <Text style={styles.input}>{transaction.budget.name}</Text> </View> <View style={styles.item}> <Text style={styles.title}>Account</Text> <Text style={styles.input}>{transaction.account}</Text> </View> <View style={styles.item}> <Text style={styles.title}>Value</Text> <Text style={styles.input}>{transaction.value.toFixed(2)}</Text> </View> <View style={styles.item}> <Text style={styles.title}>Note</Text> <Text style={styles.input}>{transaction.note}</Text> </View> <View style={styles.item}> <Text style={styles.title}>Date</Text> <Text style={styles.input}>{transaction.date.toDateString()}</Text> </View> <View style={styles.item}> <Text style={styles.title}>Receipt</Text> <View style={[styles.input, {marginRight: 15}]}> <Button title="View" onPress={() => Alert.alert('Not implemented')}/> </View> </View> </View> ); } }
JavaScript
class AccountsModel { constructor(config) { this._cache = config.cache; this._logger = config.logger; this._requestProcessingTimeoutSeconds = config.requestProcessingTimeoutSeconds; this._dfspId = config.dfspId; this._requests = new MojaloopRequests({ logger: this._logger, peerEndpoint: config.alsEndpoint, dfspId: config.dfspId, tls: config.tls, jwsSign: config.jwsSign, jwsSigningKey: config.jwsSigningKey, wso2: config.wso2, }); } /** * Initializes the internal state machine object */ _initStateMachine (initState) { this._stateMachine = new StateMachine({ init: initState, transitions: [ { name: 'createAccounts', from: 'start', to: 'succeeded' }, { name: 'error', from: '*', to: 'errored' }, ], methods: { onTransition: this._handleTransition.bind(this), onAfterTransition: this._afterTransition.bind(this), onPendingTransition: (transition, from, to) => { // allow transitions to 'error' state while other transitions are in progress if(transition !== 'error') { throw new BackendError(`Transition requested while another transition is in progress: ${transition} from: ${from} to: ${to}`, 500); } } } }); return this._stateMachine[initState]; } /** * Updates the internal state representation to reflect that of the state machine itself */ _afterTransition() { this._logger.log(`State machine transitioned: ${this._data.currentState} -> ${this._stateMachine.state}`); this._data.currentState = this._stateMachine.state; } /** * Initializes the accounts model * * @param data {object} - The outbound API POST /accounts request body */ async initialize(data) { this._data = data; // add a modelId if one is not present e.g. on first submission if(!this._data.hasOwnProperty('modelId')) { this._data.modelId = uuid(); } // initialize the transfer state machine to its starting state if(!this._data.hasOwnProperty('currentState')) { this._data.currentState = 'start'; } if(!this._data.hasOwnProperty('response')) { this._data.response = []; } this._initStateMachine(this._data.currentState); } /** * Handles state machine transitions */ async _handleTransition(lifecycle, ...args) { this._logger.log(`Request ${this._data.requestId} is transitioning from ${lifecycle.from} to ${lifecycle.to} in response to ${lifecycle.transition}`); switch(lifecycle.transition) { case 'init': return; case 'createAccounts': return this._createAccounts(); case 'error': this._logger.log(`State machine is erroring with error: ${util.inspect(args)}`); this._data.lastError = args[0] || new BackendError('unspecified error', 500); break; default: this._logger.log(`Unhandled state transition for request ${this._data.requestId}`); } } async _executeCreateAccountsRequest(request) { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { const requestKey = `ac_${request.requestId}`; const subId = await this._cache.subscribe(requestKey, async (cn, msg, subId) => { try { let error; let message = JSON.parse(msg); if (message.type === 'accountsCreationErrorResponse') { error = new BackendError(`Got an error response creating accounts: ${util.inspect(message.data)}`, 500); error.mojaloopError = message.data; } else if (message.type !== 'accountsCreationSuccessfulResponse') { this._logger.push({ message }).log( `Ignoring cache notification for request ${requestKey}. ` + `Unknown message type ${message.type}.` ); return; } // cancel the timeout handler clearTimeout(timeout); // stop listening for account creation response messages. // no need to await for the unsubscribe to complete. // we dont really care if the unsubscribe fails but we should log it regardless this._cache.unsubscribe(requestKey, subId).catch(e => { this._logger.log(`Error unsubscribing (in callback) ${requestKey} ${subId}: ${e.stack || util.inspect(e)}`); }); if (error) { return reject(error); } const response = message.data; this._logger.push({ response }).log('Account creation response received'); return resolve(response); } catch(err) { return reject(err); } }); // set up a timeout for the request const timeout = setTimeout(() => { const err = new BackendError(`Timeout waiting for response to account creation request ${request.requestId}`, 504); // we dont really care if the unsubscribe fails but we should log it regardless this._cache.unsubscribe(requestKey, subId).catch(e => { this._logger.log(`Error unsubscribing (in timeout handler) ${requestKey} ${subId}: ${e.stack || util.inspect(e)}`); }); return reject(err); }, this._requestProcessingTimeoutSeconds * 1000); // now we have a timeout handler and a cache subscriber hooked up we can fire off // a POST /participants request to the switch try { const res = await this._requests.postParticipants(request); this._logger.push({ res }).log('Account creation request sent to peer'); } catch(err) { // cancel the timout and unsubscribe before rejecting the promise clearTimeout(timeout); // we dont really care if the unsubscribe fails but we should log it regardless this._cache.unsubscribe(requestKey, subId).catch(e => { this._logger.log(`Error unsubscribing (in error handler) ${requestKey} ${subId}: ${e.stack || util.inspect(e)}`); }); return reject(err); } }); } async _createAccounts() { const requests = this._buildRequests(); for await (let request of requests) { const response = await this._executeCreateAccountsRequest(request); this._data.response.push(...this._buildClientResponse(response)); } } _buildClientResponse(response) { return response.partyList.map(party => ({ idType: party.partyId.partyIdType, idValue: party.partyId.partyIdentifier, idSubValue: party.partyId.partySubIdOrType, ...!response.currency && { error: { statusCode: Errors.MojaloopApiErrorCodes.CLIENT_ERROR.code, message: 'Provided currency not supported', } }, ...party.errorInformation && { error: { statusCode: party.errorInformation.errorCode, message: party.errorInformation.errorDescription, }, }, })); } /** * Builds accounts creation requests payload from current state * * @returns {Array} - the account creation requests */ _buildRequests() { const MAX_ITEMS_PER_REQUEST = 10000; // As per API Spec 6.2.2.2 (partyList field) const requests = []; for (let account of this._data.accounts) { let request = requests.find(req => req.currency === account.currency && (req.partyList.length < MAX_ITEMS_PER_REQUEST)); if (!request) { request = { requestId: uuid(), partyList: [], currency: account.currency, }; requests.push(request); } request.partyList.push({ partyIdType: account.idType, partyIdentifier: account.idValue, partySubIdOrType: account.idSubValue, fspId: this._dfspId, }); } return requests; } /** * Returns an object representing the final state of the transfer suitable for the outbound API * * @returns {object} - Response representing the result of the transfer process */ getResponse() { // we want to project some of our internal state into a more useful // representation to return to the SDK API consumer const resp = { ...this._data }; switch(this._data.currentState) { case 'succeeded': resp.currentState = stateEnum.COMPLETED; break; case 'errored': resp.currentState = stateEnum.ERROR_OCCURRED; break; default: this._logger.log( `Account model response being returned from an unexpected state: ${this._data.currentState}. ` + 'Returning ERROR_OCCURRED state' ); resp.currentState = stateEnum.ERROR_OCCURRED; break; } return resp; } /** * Persists the model state to cache for reinitialisation at a later point */ async _save() { try { this._data.currentState = this._stateMachine.state; const res = await this._cache.set(`accountModel_${this._data.modelId}`, this._data); this._logger.push({ res }).log('Persisted account model in cache'); } catch(err) { this._logger.push({ err }).log('Error saving account model'); throw err; } } /** * Loads an accounts model from cache for resumption of the accounts management process * * @param modelId {string} - UUID of the model to load from cache */ async load(modelId) { try { const data = await this._cache.get(`accountModel_${modelId}`); if(!data) { throw new BackendError(`No cached data found for account model with id: ${modelId}`, 500); } await this.initialize(data); this._logger.push({ cache: this._data }).log('Account model loaded from cached state'); } catch(err) { this._logger.push({ err }).log('Error loading account model'); throw err; } } /** * Returns a promise that resolves when the state machine has reached a terminal state */ async run() { try { // run transitions based on incoming state switch(this._data.currentState) { case 'start': { await this._stateMachine.createAccounts(); const accounts = this._data.response; const failCount = accounts.filter((account) => account.error).length; const successCount = this._data.response.length - failCount; this._logger.log(`Accounts created: ${successCount} succeeded, ${failCount} failed`); // if (failCount > 0) { // throw new BackendError(`Failed to create ${failCount} account(s)`, 500); // } break; } case 'succeeded': // all steps complete so return this._logger.log('Accounts creation completed'); await this._save(); return this.getResponse(); case 'errored': // stopped in errored state this._logger.log('State machine in errored state'); return; } // now call ourslves recursively to deal with the next transition this._logger.log( `Account model state machine transition completed in state: ${this._stateMachine.state}. ` + 'Handling next transition.' ); return this.run(); } catch(err) { this._logger.log(`Error running account model: ${util.inspect(err)}`); // as this function is recursive, we dont want to error the state machine multiple times if(this._data.currentState !== 'errored') { // err should not have a executionState property here! if(err.executionState) { this._logger.log(`State machine is broken: ${util.inspect(err)}`); } // transition to errored state await this._stateMachine.error(err); // avoid circular ref between executionState.lastError and err err.executionState = JSON.parse(JSON.stringify(this.getResponse())); } throw err; } } }
JavaScript
class StateGraph { /** * @param startState state that gets executed when the state machine is launched. * @param graphDescription description of the state machine. * @stability stable */ constructor(startState, graphDescription) { this.startState = startState; this.graphDescription = graphDescription; /** * The accumulated policy statements. * * @stability stable */ this.policyStatements = new Array(); /** * All states in this graph */ this.allStates = new Set(); /** * A mapping of stateId -> Graph for all states in this graph and subgraphs */ this.allContainedStates = new Map(); this.allStates.add(startState); startState.bindToGraph(this); } /** * Register a state as part of this graph. * * Called by State.bindToGraph(). * * @stability stable */ registerState(state) { this.registerContainedState(state.stateId, this); this.allStates.add(state); } /** * Register a Policy Statement used by states in this graph. * * @stability stable */ registerPolicyStatement(statement) { if (this.superGraph) { this.superGraph.registerPolicyStatement(statement); } else { this.policyStatements.push(statement); } } /** * Register this graph as a child of the given graph. * * Resource changes will be bubbled up to the given graph. * * @stability stable */ registerSuperGraph(graph) { if (this.superGraph === graph) { return; } if (this.superGraph) { throw new Error('Every StateGraph can only be registered into one other StateGraph'); } this.superGraph = graph; this.pushContainedStatesUp(graph); this.pushPolicyStatementsUp(graph); } /** * Return the Amazon States Language JSON for this graph. * * @stability stable */ toGraphJson() { const states = {}; for (const state of this.allStates) { states[state.stateId] = state.toStateJson(); } return { StartAt: this.startState.stateId, States: states, TimeoutSeconds: this.timeout && this.timeout.toSeconds(), }; } /** * Return a string description of this graph. * * @stability stable */ toString() { const someNodes = Array.from(this.allStates).slice(0, 3).map(x => x.stateId); if (this.allStates.size > 3) { someNodes.push('...'); } return `${this.graphDescription} (${someNodes.join(', ')})`; } /** * Register a stateId and graph where it was registered */ registerContainedState(stateId, graph) { if (this.superGraph) { this.superGraph.registerContainedState(stateId, graph); } else { const existingGraph = this.allContainedStates.get(stateId); if (existingGraph) { throw new Error(`State with name '${stateId}' occurs in both ${graph} and ${existingGraph}. All states must have unique names.`); } this.allContainedStates.set(stateId, graph); } } /** * Push all contained state info up to the given super graph */ pushContainedStatesUp(superGraph) { for (const [stateId, graph] of this.allContainedStates) { superGraph.registerContainedState(stateId, graph); } } /** * Push all policy statements to into the given super graph */ pushPolicyStatementsUp(superGraph) { for (const policyStatement of this.policyStatements) { superGraph.registerPolicyStatement(policyStatement); } } }
JavaScript
class Store extends Collection { /** * Constructs a new store. * @param {AyameClient} client - The client. * @param {String} name - The plural name of this store. */ constructor(client, name) { super(); /** * The client. * @type {AyameClient} */ this.client = client; /** * The plural name of this store. * @type {String} */ this.name = name; /** * Directories to load from. * @type {Set<String>} */ this.directories = new Set(); } /** * Registers a new directory to load from. * @param {String} dir - The directory. */ registerDirectory(dir) { this.directories.add(join(dir, this.name)); return this; } /** * The user directory to this store. * @type {String} */ get userDirectory() { return join(this.client.userBaseDirectory, this.name); } /** * Adds a piece to this store. * @param {Piece} piece - The piece to load. * @returns {Piece} */ set(piece) { const exists = this.get(piece.name); if(exists) this.delete(piece.name); super.set(piece.name, piece); return piece; } delete(key) { const exists = this.get(key); if(!exists) return false; return super.delete(key); } /** * Loads a single file. * @param {String} dir - The directory. * @param {String} file - The file. * @returns {Piece} */ load(dir, file) { const filepath = join(dir, file); const Piece = (mod => mod.default || mod)(require(filepath)); if(typeof Piece !== "function" || typeof Piece.constructor !== "function") throw new TypeError(`The piece (${filepath}) does not export a class.`); const piece = this.set(new Piece(this.client, this, { path: file, name: parse(filepath).name })); delete require.cache[filepath]; module.children.pop(); return piece; } /** * Initializes all pieces calling their init() method. * @returns {Promise<*>} */ init() { return Promise.all(this.map((piece) => piece.enabled ? piece.init() : piece.unload())); } /** * Walks files and returns a promise that resolves with the amount of pieces loaded. * @param {String} dir - The directory to load from. * @returns {Promise<Number>} The amount of pieces loaded. */ async loadFiles(dir) { const files = await walk(dir, { // Make it easy for CoffeeScript users to use this framework. // If they load the coffeescript/register module it allows require()ing .coffee files. // so we'll assume they are using it and allow .coffee files. filter: (stats, file) => stats.isFile() && (file.endsWith(".js") || file.endsWith(".coffee")) }).catch(() => null); if(!files) return 0; for(const file of files.keys()) this.load(dir, relative(dir, file)); return this.size; } /** * Loads all pieces. * @returns {Promise<Number>} The amount of pieces loaded. */ async loadAll() { this.clear(); for(const dir of this.directories) await this.loadFiles(dir); await this.loadFiles(this.userDirectory); return this.size; } }
JavaScript
class Scheduler { constructor(data = {}) { this.scheduled = []; this.target = null; this.timeouts = new Map(); Object.assign(this, data); } setTarget(target) { this.target = target; this.start(); } schedule(ms, routine, ...args) { const time = new Date(); time.setMilliseconds(time.getMilliseconds() + ms); this.scheduled.push({time, routine, args}); this.start(); } start() { if (!this.target) { return; } const now = new Date(); this.scheduled .filter(scheduled => !this.timeouts.has(scheduled)) .forEach(scheduled => { const {routine, time, args} = scheduled; const ms = time.valueOf() - now.valueOf(); const timeout = setTimeout(() => { try { this.target[routine](...args); } catch (error) { console && console.error && console.error('Scheduler error:', error); } this.timeouts.delete(scheduled); const index = this.scheduled.indexOf(scheduled); if (index >= 0) { this.scheduled.splice(index, 1); } }, ms) this.timeouts.set(scheduled, timeout); }); } }
JavaScript
class ApiClientEx extends ApiClient { constructor( appStorage, wakeOnLanModulePath, serverAddress, clientName, applicationVersion, deviceName, deviceId, devicePixelRatio, localAssetManager) { super(appStorage, wakeOnLanModulePath, serverAddress, clientName, applicationVersion, deviceName, deviceId, devicePixelRatio); this.localAssetManager = localAssetManager; } getPlaybackInfo(itemId, options, deviceProfile) { const onFailure = () => ApiClient.prototype.getPlaybackInfo.call(instance, itemId, options, deviceProfile); if (isLocalId(itemId)) { return this.localAssetManager.getLocalItem(this.serverId(), stripLocalPrefix(itemId)).then(item => { // TODO: This was already done during the sync process, right? If so, remove it const mediaSources = item.Item.MediaSources.map(m => { m.SupportsDirectPlay = true; m.SupportsDirectStream = false; m.SupportsTranscoding = false; m.IsLocal = true; return m; }); return { MediaSources: mediaSources }; }, onFailure); } var instance = this; return this.localAssetManager.getLocalItem(this.serverId(), itemId).then(item => { if (item) { const mediaSources = item.Item.MediaSources.map(m => { m.SupportsDirectPlay = true; m.SupportsDirectStream = false; m.SupportsTranscoding = false; m.IsLocal = true; return m; }); return instance.localAssetManager.fileExists(item.LocalPath).then(exists => { if (exists) { const res = { MediaSources: mediaSources }; return Promise.resolve(res); } return ApiClient.prototype.getPlaybackInfo.call(instance, itemId, options, deviceProfile); }, onFailure); } return ApiClient.prototype.getPlaybackInfo.call(instance, itemId, options, deviceProfile); }, onFailure); } getItems(userId, options) { const serverInfo = this.serverInfo(); let i; if (serverInfo && options.ParentId === 'localview') { return this.getLocalFolders(serverInfo.Id, userId).then(items => { const result = { Items: items, TotalRecordCount: items.length }; return Promise.resolve(result); }); } else if (serverInfo && options && (isLocalId(options.ParentId) || isLocalId(options.SeriesId) || isLocalId(options.SeasonId) || isLocalViewId(options.ParentId) || isLocalId(options.AlbumIds))) { return this.localAssetManager.getViewItems(serverInfo.Id, userId, options).then(items => { items.forEach(item => { adjustGuidProperties(item); }); const result = { Items: items, TotalRecordCount: items.length }; return Promise.resolve(result); }); } else if (options && options.ExcludeItemIds && options.ExcludeItemIds.length) { const exItems = options.ExcludeItemIds.split(','); for (i = 0; i < exItems.length; i++) { if (isLocalId(exItems[i])) { return Promise.resolve(createEmptyList()); } } } else if (options && options.Ids && options.Ids.length) { const ids = options.Ids.split(','); let hasLocal = false; for (i = 0; i < ids.length; i++) { if (isLocalId(ids[i])) { hasLocal = true; } } if (hasLocal) { return this.localAssetManager.getItemsFromIds(serverInfo.Id, ids).then(items => { items.forEach(item => { adjustGuidProperties(item); }); const result = { Items: items, TotalRecordCount: items.length }; return Promise.resolve(result); }); } } return ApiClient.prototype.getItems.call(this, userId, options); } getUserViews(options, userId) { const instance = this; options = options || {}; const basePromise = ApiClient.prototype.getUserViews.call(instance, options, userId); if (!options.enableLocalView) { return basePromise; } return basePromise.then(result => { const serverInfo = instance.serverInfo(); if (serverInfo) { return getLocalView(instance, serverInfo.Id, userId).then(localView => { if (localView) { result.Items.push(localView); result.TotalRecordCount++; } return Promise.resolve(result); }); } return Promise.resolve(result); }); } getItem(userId, itemId) { if (!itemId) { throw new Error("null itemId"); } if (itemId) { itemId = itemId.toString(); } let serverInfo; if (isTopLevelLocalViewId(itemId)) { serverInfo = this.serverInfo(); if (serverInfo) { return getLocalView(this, serverInfo.Id, userId); } } if (isLocalViewId(itemId)) { serverInfo = this.serverInfo(); if (serverInfo) { return this.getLocalFolders(serverInfo.Id, userId).then(items => { const views = items.filter(item => item.Id === itemId); if (views.length > 0) { return Promise.resolve(views[0]); } // TODO: Test consequence of this return Promise.reject(); }); } } if (isLocalId(itemId)) { serverInfo = this.serverInfo(); if (serverInfo) { return this.localAssetManager.getLocalItem(serverInfo.Id, stripLocalPrefix(itemId)).then(item => { adjustGuidProperties(item.Item); return Promise.resolve(item.Item); }); } } return ApiClient.prototype.getItem.call(this, userId, itemId); } getLocalFolders(userId) { const serverInfo = this.serverInfo(); userId = userId || serverInfo.UserId; return this.localAssetManager.getViews(serverInfo.Id, userId); } getNextUpEpisodes(options) { if (options.SeriesId) { if (isLocalId(options.SeriesId)) { return Promise.resolve(createEmptyList()); } } return ApiClient.prototype.getNextUpEpisodes.call(this, options); } getSeasons(itemId, options) { if (isLocalId(itemId)) { options.SeriesId = itemId; options.IncludeItemTypes = 'Season'; return this.getItems(this.getCurrentUserId(), options); } return ApiClient.prototype.getSeasons.call(this, itemId, options); } getEpisodes(itemId, options) { if (isLocalId(options.SeasonId) || isLocalId(options.seasonId)) { options.SeriesId = itemId; options.IncludeItemTypes = 'Episode'; return this.getItems(this.getCurrentUserId(), options); } // get episodes by recursion if (isLocalId(itemId)) { options.SeriesId = itemId; options.IncludeItemTypes = 'Episode'; return this.getItems(this.getCurrentUserId(), options); } return ApiClient.prototype.getEpisodes.call(this, itemId, options); } getLatestOfflineItems(options) { // Supported options // MediaType - Audio/Video/Photo/Book/Game // Limit // Filters: 'IsNotFolder' or 'IsFolder' options.SortBy = 'DateCreated'; options.SortOrder = 'Descending'; const serverInfo = this.serverInfo(); if (serverInfo) { return this.localAssetManager.getViewItems(serverInfo.Id, null, options).then(items => { items.forEach(item => { adjustGuidProperties(item); }); return Promise.resolve(items); }); } return Promise.resolve([]); } getThemeMedia(userId, itemId, inherit) { if (isLocalViewId(itemId) || isLocalId(itemId) || isTopLevelLocalViewId(itemId)) { return Promise.reject(); } return ApiClient.prototype.getThemeMedia.call(this, userId, itemId, inherit); } getSpecialFeatures(userId, itemId) { if (isLocalId(itemId)) { return Promise.resolve([]); } return ApiClient.prototype.getSpecialFeatures.call(this, userId, itemId); } getSimilarItems(itemId, options) { if (isLocalId(itemId)) { return Promise.resolve(createEmptyList()); } return ApiClient.prototype.getSimilarItems.call(this, itemId, options); } updateFavoriteStatus(userId, itemId, isFavorite) { if (isLocalId(itemId)) { return Promise.resolve(); } return ApiClient.prototype.updateFavoriteStatus.call(this, userId, itemId, isFavorite); } getScaledImageUrl(itemId, options) { if (isLocalId(itemId) || (options && options.itemid && isLocalId(options.itemid))) { const serverInfo = this.serverInfo(); const id = stripLocalPrefix(itemId); return this.localAssetManager.getImageUrl(serverInfo.Id, id, options); } return ApiClient.prototype.getScaledImageUrl.call(this, itemId, options); } reportPlaybackStart(options) { if (!options) { throw new Error("null options"); } if (isLocalId(options.ItemId)) { return Promise.resolve(); } return ApiClient.prototype.reportPlaybackStart.call(this, options); } reportPlaybackProgress(options) { if (!options) { throw new Error("null options"); } if (isLocalId(options.ItemId)) { const serverInfo = this.serverInfo(); if (serverInfo) { const instance = this; return this.localAssetManager.getLocalItem(serverInfo.Id, stripLocalPrefix(options.ItemId)).then(item => { const libraryItem = item.Item; if (libraryItem.MediaType === 'Video' || libraryItem.Type === 'AudioBook') { libraryItem.UserData = libraryItem.UserData || {}; libraryItem.UserData.PlaybackPositionTicks = options.PositionTicks; libraryItem.UserData.PlayedPercentage = Math.min(libraryItem.RunTimeTicks ? (100 * ((options.PositionTicks || 0) / libraryItem.RunTimeTicks)) : 0, 100); return instance.localAssetManager.addOrUpdateLocalItem(item); } return Promise.resolve(); }); } return Promise.resolve(); } return ApiClient.prototype.reportPlaybackProgress.call(this, options); } reportPlaybackStopped(options) { if (!options) { throw new Error("null options"); } if (isLocalId(options.ItemId)) { const serverInfo = this.serverInfo(); const action = { Date: new Date().getTime(), ItemId: stripLocalPrefix(options.ItemId), PositionTicks: options.PositionTicks, ServerId: serverInfo.Id, Type: 0, // UserActionType.PlayedItem UserId: this.getCurrentUserId() }; return this.localAssetManager.recordUserAction(action); } return ApiClient.prototype.reportPlaybackStopped.call(this, options); } getIntros(itemId) { if (isLocalId(itemId)) { return Promise.resolve({ Items: [], TotalRecordCount: 0 }); } return ApiClient.prototype.getIntros.call(this, itemId); } getInstantMixFromItem(itemId, options) { if (isLocalId(itemId)) { return Promise.resolve({ Items: [], TotalRecordCount: 0 }); } return ApiClient.prototype.getInstantMixFromItem.call(this, itemId, options); } getItemDownloadUrl(itemId) { if (isLocalId(itemId)) { const serverInfo = this.serverInfo(); if (serverInfo) { return this.localAssetManager.getLocalItem(serverInfo.Id, stripLocalPrefix(itemId)).then(item => Promise.resolve(item.LocalPath)); } } return ApiClient.prototype.getItemDownloadUrl.call(this, itemId); } }
JavaScript
class PromptView{ /** * Instantiate a new {@link PromptView} instance. * * @param {Object} [opts={}] - Initial property values * @constructor */ constructor(opts = {}){ internalValues.set(this, { autoFocus: true, autoHide: false, autoHideHandler: null, }); // Setup DOM this.buildTree(opts = this.normaliseProps(opts)); if(atom){ this.panel = atom.workspace.addModalPanel({visible: false, item: this}); atom.commands.add(this.inputField.element, { "core:confirm": () => this.confirm(this.input), "core:cancel": () => this.confirm(null), }); } else this.inputField.element.addEventListener("keydown", event => { switch(event.keyCode){ case 13: this.confirm(this.input); break; case 27: this.confirm(null); break; } }); // Assign initial property values this.assignProps({ autoHide: true, elementClass: "prompt", headerClass: "prompt-header", footerClass: "prompt-footer", }, opts); } /** * Construct the elements which compose the {@link PromptView}'s modal dialogue. * * @param {Object} [opts={}] * @returns {PromptView} Reference to the calling instance * @internal */ buildTree(opts = {}){ const { elementTagName = "div", headerTagName = "header", footerTagName = "footer", } = opts; /** * @property {HTMLElement} element * @description Top-level wrapper representing {@link PromptView} in Atom's workspace. * * @property {HTMLElement} headerElement * @description Content block displayed above {@link #inputField}, empty unless * {@link headerText} or {@link headerHTML} has been assigned content. * * @property {TextEditor|HTMLFormElement} inputField * @description Miniature editing bar where user types their input. * * @property {HTMLElement} footerElement * @description Content block displayed below {@link #inputField}, empty * unless {@link headerText} or {@link headerHTML} have been assigned content. */ this.element = document.createElement(elementTagName); this.headerElement = document.createElement(headerTagName); this.footerElement = document.createElement(footerTagName); this.element.append(this.headerElement, this.footerElement); if(atom){ this.inputField = atom.workspace.buildTextEditor({mini: true, softTabs: false}); this.element.insertBefore(this.inputField.element, this.footerElement); } else{ this.inputField = this.buildFakeEditor(); this.element.insertBefore(this.inputField, this.footerElement); this.element.hidden = "dialog" !== this.elementTagName; document.body.appendChild(this.element); } return this; } /** * Construct a synthetic {@link TextEditor} component for browser environments. * * @param {Object} [opts={}] * @return {HTMLFormElement} * @internal */ buildFakeEditor(opts = {}){ // Entry field const input = document.createElement("input"); input.type = "text"; // Surrogate editor component const form = document.createElement("form"); Object.assign(form, { element: form.appendChild(input), getText: () => input.value, setText: to => input.value = to, getPlaceholderText: () => input.placeholder, setPlaceholderText: to => input.placeholder = to, }); // Hidden submission button const submit = document.createElement("input"); Object.assign(form.appendChild(submit), { type: "submit", value: "Confirm", hidden: true, }); // Confirmation handlers for(const el of [input, form]) el.addEventListener("submit", event => { this.confirm(input.value); event.preventDefault(); }); // Special handling for <dialog> tags if author's using one if("dialog" === opts.elementTagName){ form.method = "dialog"; this.panel = { show: () => form.show(), hide: () => form.close(), }; } return form; } /** * Update the instance's properties using values extracted from objects. * * @example view.assignProps({headerText: "Hello, world"}); * @param {...Object} opts * @return {PromptView} */ assignProps(...opts){ opts = Object.assign({}, ...opts); // Delete anything which isn't assigned normally delete opts.elementTagName; delete opts.headerTagName; delete opts.footerTagName; Object.assign(this, opts); return this; } /** * Normalise a value expected to provide instance properties. * * Strings are treated as shorthand for setting `headerText`; * objects are returned unmodified. Other types are invalid. * * @example view.normaliseProps("Title") == {headerText: "Title"}; * @throws {TypeError} If input isn't an object or string * @param {*} input * @return {Object} */ normaliseProps(input){ switch(typeof input){ case "string": return {headerText: input}; case "object": return input; } const message = `Object or string expected when ${typeof input} given`; throw new TypeError(message); } /** * Present the dialogue to the user, resolving once they confirm an answer. * * @async * @param {Object} [opts={}] * Instance properties to update. * @return {Promise} * Resolves to a {@link String} containing the user's input, or * the `null` value if the prompt was cancelled for any reason. * @example * <caption>A user is prompted and responds with <code>dd(1)</code></caption> * new PromptView().promptUser({ * headerText: "Enter the name of a manual-page", * footerHTML: "E.g., <code>perl</code>, <code>grep(5)</code>", * }).then(response => "dd(1)"); * @public */ promptUser(opts = {}){ // Return existing prompt which hasn't been confirmed yet const prompt = currentPrompts.get(this); if(prompt) return prompt.promise; // Otherwise, start a new one else{ this.input = ""; this.assignProps(this, opts); this.show(); let handler = null; const promise = new Promise(fn => handler = fn); currentPrompts.set(this, {promise, handler}); return promise; } } /** * Confirm user's response and invoke any unresolved prompt-handler. * * @param {String|null} input - Null values indicate cancelled prompts. * @internal */ confirm(input){ const prompt = currentPrompts.get(this); if(!prompt) return; currentPrompts.delete(this); this.input = ""; this.hide(); if("function" === typeof prompt.handler) prompt.handler.call(null, input); } /** * Reveal prompt-view and set focus without altering prompt state. * @internal */ show(){ this.autoFocus && this.saveFocus(); if(atom && this.panel) this.panel.show(); else "dialog" === this.elementTagName ? this.element.show() : this.element.hidden = false; this.autoFocus && this.inputField.element.focus(); } /** * Hide prompt-view and restore focus without resolving current prompt. * @internal */ hide(){ if(atom && this.panel) this.panel.hide(); else "dialog" === this.elementTagName ? this.element.close() : this.element.hidden = true; this.autoFocus && this.restoreFocus(); } /** * Save whatever DOM element has user focus before displaying a dialogue. * @internal */ saveFocus(){ this.previouslyFocussedElement = document.activeElement || null; } /** * Restore focus to whatever element was holding it at the time the PromptView * has been open. If the original element no longer exists in the DOM, focus is * shifted to {@link atom.workspace.element} as a last resort. * @internal */ restoreFocus(){ const el = this.previouslyFocussedElement; this.previouslyFocussedElement = null; if(el && document.documentElement.contains(el)) el.focus(); else atom ? atom.workspace.element.focus() : document.body.focus(); } /** * @property {Boolean} [autoFocus=true] * @description Set and restore focus when toggling prompt. */ get autoFocus(){ return internalValues.get(this).autoFocus; } set autoFocus(to){ const data = internalValues.get(this); if((to = !!to) === data.autoFocus) return; data.autoFocus = to; if(!to && this.previouslyFocussedElement) this.previouslyFocussedElement = null; } /** * @property {Boolean} [autoHide=true] * @description Hide the prompt upon losing focus. */ get autoHide(){ return internalValues.get(this).autoHide; } set autoHide(to){ const data = internalValues.get(this); if((to = !!to) === data.autoHide) return; switch(data.autoHide = to){ case true: data.autoHideHandler = () => this.confirm(null); this.inputField.element.addEventListener("blur", data.autoHideHandler); break; case false: this.inputField.element.removeEventListener("blur", data.autoHideHandler); data.autoHideHandler = null; break; } } /** * @readonly * @property {String} [elementTagName="div"] * @description Name of the HTML tag used to create {@link #headerElement}. * This property can only be set during construction, using the original * option-hash passed to the constructor function. */ get elementTagName(){ return this.element ? this.element.tagName.toLowerCase() : ""; } /** * @property {String} elementClass * @description List of CSS classes assigned to instance's wrapper {@link #element}. */ get elementClass(){ return this.element ? this.element.className : ""; } set elementClass(to){ if(this.element) this.element.className = to; } /** * @readonly * @property {String} [headerTagName="header"] * @description Name of the HTML tag used to create {@link #headerElement}. * This property can only be set during construction, using the original * option-hash passed to the constructor function. */ get headerTagName(){ return this.headerElement ? this.headerElement.tagName.toLowerCase() : ""; } /** * @property {String} headerClass * @description List of CSS classes assigned to instance's {@link #headerElement}. */ get headerClass(){ return this.headerElement ? this.headerElement.className : ""; } set headerClass(to){ if(this.headerElement) this.headerElement.className = to; } /** * @property {String} headerText * @description A plain-text representation of the {@link #headerElement}'s content. */ get headerText(){ return this.headerElement ? this.headerElement.textContent : ""; } set headerText(to){ if(this.headerElement) this.headerElement.textContent = to; } /** * @property {String} headerHTML * @description HTML representation of the {@link #headerElement|header}'s contents. */ get headerHTML(){ return this.headerElement ? this.headerElement.innerHTML : ""; } set headerHTML(to){ if(this.headerElement) this.headerElement.innerHTML = to; } /** * @readonly * @property {String} [footerTagName="footer"] * @description Name of the HTML tag used to create {@link #footerElement}. * This property can only be set during construction, using the original * option-hash passed to the constructor function. */ get footerTagName(){ return this.footerElement ? this.footerElement.tagName.toLowerCase() : ""; } /** * @property {String} footerClass * @description List of CSS classes assigned to instance's {@link #footerElement}. */ get footerClass(){ return this.footerElement ? this.footerElement.className : ""; } set footerClass(to){ if(this.footerElement) this.footerElement.className = to; } /** * @property {String} footerText * @description A plain-text representation of the {@link #footerElement}'s content. */ get footerText(){ return this.footerElement ? this.footerElement.textContent : ""; } set footerText(to){ if(this.footerElement) this.footerElement.textContent = to; } /** * @property {String} footerHTML * @description HTML representation of the {@link #footerElement|footer}'s contents. */ get footerHTML(){ return this.footerElement ? this.footerElement.innerHTML : ""; } set footerHTML(to){ if(this.footerElement) this.footerElement.innerHTML = to; } /** * @property {String} input * @description Text currently entered into the instance's {@link #inputField}. * Writing to this property will replace whatever text has been entered in the field. */ get input(){ return this.inputField ? this.inputField.getText() : ""; } set input(to){ if(this.inputField) this.inputField.setText(to); } /** * @readonly * @property {Boolean} [isPending=false] * @description Whether the view is waiting for user to confirm their input. */ get isPending(){ const prompt = currentPrompts.get(this); return !!(prompt && prompt.promise instanceof Promise); } /** * @property {String} [placeholder=""] * @description Placeholder text displayed by {@link #inputField} when empty. */ get placeholder(){ return this.inputField ? this.inputField.getPlaceholderText() || "" : ""; } set placeholder(to){ if(this.inputField) this.inputField.setPlaceholderText(to); } }
JavaScript
class PhotoSeq { /** * Constructs a PhotoSeq instance. Randomly selects numToShow photos from photos. * * @param {array} candidatePhotos Array of photos to select from. If photos contain a * weight field, it will be used adjust the random * selection. Higher weights are more likely to be selected. */ constructor(candidatePhotos, numToShow) { this.index = 0; this.photos = this.selectRandom(candidatePhotos, numToShow); } // Progresses the current photo to the next photo in the trial get moveToNext() { return ++this.index < this.photos.length; } get currentPhoto() { return this.photos[this.index]; } get hasCurrentPhoto() { return this.index < this.photos.length; } get percentComplete() { return 100 * (this.index + 1) / this.photos.length; } // Used internally. Selects the photos to be used in the trial // from the list of candidate photos selectRandom(photos, numToShow) { shuffleArray(photos); var result = []; // Pick out numToShow photos, based on optional weighting // Calculate total weight let total = 0; for (let i = photos.length - 1; i >= 0; i--) { // Assume weight of 1 if not specified total += photos[i].weight || 1; photos[i].cumulative = total; } // Calculate weight change between photos let inc = total / numToShow; for (let i = photos.length - 1; i >= 0; i--) { if (photos[i].cumulative >= result.length * inc) { result.push(photos[i]); } } return result; } }
JavaScript
class RedisClient extends AbstractClient { constructor(credential, region, profile) { super("redis.tencentcloudapi.com", "2018-04-12", credential, region, profile); } /** * 重置密码 * @param {ResetPasswordRequest} req * @param {function(string, ResetPasswordResponse):void} cb * @public */ ResetPassword(req, cb) { let resp = new ResetPasswordResponse(); this.request("ResetPassword", req, resp, cb); } /** * 升级实例 * @param {UpgradeInstanceRequest} req * @param {function(string, UpgradeInstanceResponse):void} cb * @public */ UpgradeInstance(req, cb) { let resp = new UpgradeInstanceResponse(); this.request("UpgradeInstance", req, resp, cb); } /** * 续费实例 * @param {RenewInstanceRequest} req * @param {function(string, RenewInstanceResponse):void} cb * @public */ RenewInstance(req, cb) { let resp = new RenewInstanceResponse(); this.request("RenewInstance", req, resp, cb); } /** * 查询Redis实例列表 * @param {DescribeInstancesRequest} req * @param {function(string, DescribeInstancesResponse):void} cb * @public */ DescribeInstances(req, cb) { let resp = new DescribeInstancesResponse(); this.request("DescribeInstances", req, resp, cb); } /** * 手动备份Redis实例 * @param {ManualBackupInstanceRequest} req * @param {function(string, ManualBackupInstanceResponse):void} cb * @public */ ManualBackupInstance(req, cb) { let resp = new ManualBackupInstanceResponse(); this.request("ManualBackupInstance", req, resp, cb); } /** * 修改redis密码 * @param {ModfiyInstancePasswordRequest} req * @param {function(string, ModfiyInstancePasswordResponse):void} cb * @public */ ModfiyInstancePassword(req, cb) { let resp = new ModfiyInstancePasswordResponse(); this.request("ModfiyInstancePassword", req, resp, cb); } /** * 获取备份配置 * @param {DescribeAutoBackupConfigRequest} req * @param {function(string, DescribeAutoBackupConfigResponse):void} cb * @public */ DescribeAutoBackupConfig(req, cb) { let resp = new DescribeAutoBackupConfigResponse(); this.request("DescribeAutoBackupConfig", req, resp, cb); } /** * 清空Redis实例的实例数据。 * @param {ClearInstanceRequest} req * @param {function(string, ClearInstanceResponse):void} cb * @public */ ClearInstance(req, cb) { let resp = new ClearInstanceResponse(); this.request("ClearInstance", req, resp, cb); } /** * 查询 CRS 实例备份列表 * @param {DescribeInstanceBackupsRequest} req * @param {function(string, DescribeInstanceBackupsResponse):void} cb * @public */ DescribeInstanceBackups(req, cb) { let resp = new DescribeInstanceBackupsResponse(); this.request("DescribeInstanceBackups", req, resp, cb); } /** * 查询订单信息 * @param {DescribeInstanceDealDetailRequest} req * @param {function(string, DescribeInstanceDealDetailResponse):void} cb * @public */ DescribeInstanceDealDetail(req, cb) { let resp = new DescribeInstanceDealDetailResponse(); this.request("DescribeInstanceDealDetail", req, resp, cb); } /** * 本接口查询指定可用区和实例类型下 Redis 的售卖规格, 如果用户不在购买白名单中,将不能查询该可用区或该类型的售卖规格详情。申请购买某地域白名单可以提交工单 * @param {DescribeProductInfoRequest} req * @param {function(string, DescribeProductInfoResponse):void} cb * @public */ DescribeProductInfo(req, cb) { let resp = new DescribeProductInfoResponse(); this.request("DescribeProductInfo", req, resp, cb); } /** * 用于查询任务结果 * @param {DescribeTaskInfoRequest} req * @param {function(string, DescribeTaskInfoResponse):void} cb * @public */ DescribeTaskInfo(req, cb) { let resp = new DescribeTaskInfoResponse(); this.request("DescribeTaskInfo", req, resp, cb); } /** * 设置自动备份时间 * @param {ModifyAutoBackupConfigRequest} req * @param {function(string, ModifyAutoBackupConfigResponse):void} cb * @public */ ModifyAutoBackupConfig(req, cb) { let resp = new ModifyAutoBackupConfigResponse(); this.request("ModifyAutoBackupConfig", req, resp, cb); } /** * 创建redis实例 * @param {CreateInstancesRequest} req * @param {function(string, CreateInstancesResponse):void} cb * @public */ CreateInstances(req, cb) { let resp = new CreateInstancesResponse(); this.request("CreateInstances", req, resp, cb); } }