language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class DefaultSlider extends Component { constructor( props ) { super( props ); this.state = { nChildren: 0, childDivs: null, currentSlide: 1 }; } componentDidMount() { this.createSlides(); if ( this.slider ) { this.slider.slickGoTo( this.props.goto ); } } componentDidUpdate( prevProps ) { if ( this.props.children !== prevProps.children ) { this.createSlides(); } if ( this.props.goto !== prevProps.goto && this.slider ) { this.slider.slickGoTo( this.props.goto ); } } createSlides() { let nChildren = 0; const childDivs = this.props.children && this.props.children.length > 0 ? React.Children.map( this.props.children, ( child ) => { if ( isLineButtons( child ) ) { return null; } nChildren += 1; return <div hidden={this.state.currentSlide !== nChildren ? true : void 0} > {child} </div>; }) : <div></div>; this.setState({ childDivs, nChildren }); } renderTitle() { if ( !this.props.title ) { return null; } const currentSlideDisplay = <span style={{ float: 'right' }}> {this.state.currentSlide} / {this.state.childDivs.length} </span>; if ( isString( this.props.title ) ) { return ( <Card.Header as="h3" > {this.props.title} {currentSlideDisplay} </Card.Header> ); } return ( <Card.Header > {this.props.title} {currentSlideDisplay} </Card.Header> ); } render() { if ( this.state.nChildren <= 1 ) { return <Alert variant="danger" >{this.props.t('missing-children')}</Alert>; } const settings = { className: 'centered', speed: 1000, slidesToShow: 1, slidesToScroll: 1, prevArrow: <PrevArrow pagination={this.props.pagination} onClick={this.props.onClick} t={this.props.t} />, nextArrow: <NextArrow pagination={this.props.pagination} onClick={this.props.onClick} t={this.props.t} />, ...this.props, beforeChange: ( oldIndex, newIndex ) => { this.setState({ currentSlide: newIndex+1 }, this.createSlides ); closeHintButtons( this.slider ); }, style: { userSelect: this.props.draggable ? 'none' : 'inherit' } }; if ( this.props.interval ) { settings.autoplay = true; settings.autoplaySpeed = this.props.interval; } return ( <Card size="large" className="slider-card" style={this.props.style} > {this.renderTitle()} <Card.Body style={{ paddingBottom: 40, paddingTop: this.props.pagination !== 'bottom' ? 40 : 0 }}> <Slider ref={( slider ) => { this.slider = slider; }} {...settings} > {this.state.childDivs} </Slider> </Card.Body> </Card> ); } }
JavaScript
class UploadService extends Service { /** * Executes a POST request against the <code>/statements</code> endpoint. The * statements which have to be added are provided through a readable stream. * This method is useful for library client who wants to upload a big data set * into the repository. * * @param {ReadableStream} readStream * @param {string} contentType is one of RDF mime type formats, * application/x-rdftransaction' for a transaction document or * application/x-www-form-urlencoded * @param {NamedNode|string} [context] optional context to restrict the * operation. Will be encoded as N-Triple if it is not already one * @param {string} [baseURI] optional uri against which any relative URIs * found in the data would be resolved. * * @return {ServiceRequest} a service request that will be resolved when the * stream has been successfully consumed by the server */ upload(readStream, contentType, context, baseURI) { const requestBuilder = this.getUploadRequest(readStream, contentType, context, baseURI); return new ServiceRequest(requestBuilder, () => { return this.httpRequestExecutor(requestBuilder).then((response) => { this.logger.debug(LoggingUtils.getLogPayload(response, { contentType, context, baseURI }), 'Uploaded data stream'); }); }); } /** * Executes a PUT request against the <code>/statements</code> endpoint. The * statements which have to be updated are provided through a readable stream. * This method is useful for overriding large set of statements that might be * provided as a readable stream e.g. reading from file. * * @param {ReadableStream} readStream * @param {string} contentType * @param {NamedNode|string} context restrict the operation. Will be encoded * as N-Triple if it is not already one * @param {string} [baseURI] optional uri against which any relative URIs * found in the data would be resolved. * * @return {ServiceRequest} a service request that will be resolved when the * stream has been successfully consumed by the server */ overwrite(readStream, contentType, context, baseURI) { const requestBuilder = this.getOverwriteRequest(readStream, contentType, context, baseURI); return new ServiceRequest(requestBuilder, () => { return this.httpRequestExecutor(requestBuilder).then((response) => { this.logger.debug(LoggingUtils.getLogPayload(response, { contentType, context, baseURI }), 'Overwritten data stream'); }); }); } /** * Uploads the file specified by the provided file path to the server. * * See {@link #upload} * * @param {string} filePath path to a file to be streamed to the server * @param {string} contentType MIME type of the file's content * @param {string|string[]} [context] restricts the operation to the given * context. Will be encoded as N-Triple if it is not already one * @param {string} [baseURI] used to resolve relative URIs in the data * * @return {ServiceRequest} a service request that will be resolved when the * file has been successfully consumed by the server */ addFile(filePath, contentType, context, baseURI) { const fileStream = FileUtils.getReadStream(filePath); const requestBuilder = this.getUploadRequest(fileStream, contentType, context, baseURI); return new ServiceRequest(requestBuilder, () => { return this.httpRequestExecutor(requestBuilder).then((response) => { this.logger.debug(LoggingUtils.getLogPayload(response, { filePath, contentType, context, baseURI }), 'Uploaded file'); }); }); } /** * Uploads the file specified by the provided file path to the server * overwriting any data in the server's repository. * * The overwrite will be restricted if the context parameter is specified. * * See {@link #overwrite} * * @param {string} filePath path to a file to be streamed to the server * @param {string} contentType MIME type of the file's content * @param {string} [context] restricts the operation to the given context. * Will be encoded as N-Triple if it is not already one * @param {string} [baseURI] used to resolve relative URIs in the data * * @return {ServiceRequest} a service request that will be resolved when the * file has been successfully consumed by the server */ putFile(filePath, contentType, context, baseURI) { const fileStream = FileUtils.getReadStream(filePath); const requestBuilder = this.getOverwriteRequest(fileStream, contentType, context, baseURI); return new ServiceRequest(requestBuilder, () => { return this.httpRequestExecutor(requestBuilder).then((response) => { this.logger.debug(LoggingUtils.getLogPayload(response, { filePath, contentType, context, baseURI }), 'Overwritten data from file'); }); }); } /** * Executes a POST request against the <code>/statements</code> endpoint. The * statements which have to be added are provided through a readable stream. * This method is useful for library client who wants to upload a big data set * into the repository. * * @private * * @param {ReadableStream} readStream * @param {string} contentType is one of RDF mime type formats, * application/x-rdftransaction' for a transaction document or * application/x-www-form-urlencoded * @param {NamedNode|string} [context] optional context to restrict the * operation. Will be encoded as N-Triple if it is not already one * @param {string} [baseURI] optional uri against which any relative URIs * found in the data would be resolved. * * @return {Promise<HttpResponse|Error>} a promise that will be resolved when * the stream has been successfully consumed by the server */ getUploadRequest(readStream, contentType, context, baseURI) { return HttpRequestBuilder.httpPost(PATH_STATEMENTS) .setData(readStream) .addContentTypeHeader(contentType) .setResponseType('stream') .setParams({ baseURI, context: TermConverter.toNTripleValues(context) }); } /** * Executes a PUT request against the <code>/statements</code> endpoint. The * statements which have to be updated are provided through a readable stream. * This method is useful for overriding large set of statements that might be * provided as a readable stream e.g. reading from file. * * @private * * @param {ReadableStream} readStream * @param {string} contentType * @param {NamedNode|string} context restrict the operation. Will be encoded * as N-Triple if it is not already one * @param {string} [baseURI] optional uri against which any relative URIs * found in the data would be resolved. * * @return {Promise<HttpResponse|Error>} a promise that will be resolved when * the stream has been successfully consumed by the server */ getOverwriteRequest(readStream, contentType, context, baseURI) { return HttpRequestBuilder.httpPut(PATH_STATEMENTS) .setData(readStream) .addContentTypeHeader(contentType) .setResponseType('stream') .setParams({ baseURI, context: TermConverter.toNTripleValues(context) }); } /** * @inheritDoc */ getServiceName() { return 'UploadService'; } }
JavaScript
class SequentialPaneDisplay extends Component { static propTypes = { activePaneId: PropTypes.string.isRequired, paneSequence: PropTypes.object.isRequired } /** * Routes to the next pane URL. */ _routeTo = nextId => { const { parentPath, routeTo } = this.props routeTo(`${parentPath}/${nextId}`) } _handleToNextPane = async e => { const { activePane } = this.props const nextId = activePane.nextId if (nextId) { // Don't submit the form if there are more steps to complete. e.preventDefault() // Execute pane-specific action, if any (e.g. save a user account) // when clicking next. if (typeof activePane.onNext === 'function') { await activePane.onNext() } this._routeTo(nextId) } } _handleToPrevPane = () => { const { activePane } = this.props this._routeTo(activePane.prevId) } render () { const { activePane = {} } = this.props const { disableNext, hideNavigation, nextId, pane: Pane, prevId, props, title } = activePane return ( <> <h1>{title}</h1> <SequentialPaneContainer> {Pane && <Pane {...props} />} </SequentialPaneContainer> {!hideNavigation && ( <FormNavigationButtons backButton={prevId && { onClick: this._handleToPrevPane, text: <FormattedMessage id='common.forms.back' /> }} okayButton={{ disabled: disableNext, onClick: this._handleToNextPane, text: nextId ? <FormattedMessage id='common.forms.next' /> : <FormattedMessage id='common.forms.finish' />, type: 'submit' }} /> )} </> ) } }
JavaScript
class App extends React.Component { render() { let menuOptions = [ {to: "/", text: "home"}, {to: "about", text: "About Natours"}, {to: "benefits", text: "Your benefits"}, {to: "popularTours", text: "Popular tours"}, {to: "stories", text: "Stories"}, {to: "book", text: "Book now"} ]; return ( <div> <Navigation options={menuOptions}/> <ErrorBoundary> <Switch> <Route exact path="/" component={LadingPage} /> <Route component={NotFoundPage}/> </Switch> </ErrorBoundary> </div> ); } }
JavaScript
class Environment extends Component { constructor(props) { super(props); this.state = { hidden: true, serverValue: props.server, appKeyValue: props.appKey, appSecretValue: props.appSecret, enabledValue: props.enabled, }; this.onServerChange = (e) => { this.setState({ serverValue: e.currentTarget.value, }); }; this.onAppKeyChange = (e) => { this.setState({ appKeyValue: e.currentTarget.value, }); }; this.onAppSecretChange = (e) => { this.setState({ appSecretValue: e.currentTarget.value, }); }; this.onToggleEnabled = () => { this.setState({ enabledValue: !this.state.enabledValue, }); }; this.onOk = () => { this.props.onSetData({ server: this.state.serverValue, enabled: this.state.enabledValue, appKey: this.state.appKeyValue, appSecret: this.state.appSecretValue, }); this.toggleEnv(); }; this.onCancel = () => { this.setState({ serverValue: this.props.server, enabledValue: this.props.enabled, appKeyValue: this.props.appKey, appSecretValue: this.props.appSecret, }); this.toggleEnv(); }; this.toggleEnv = () => { this.setState({ hidden: !this.state.hidden, }); }; if (typeof window !== 'undefined') { window.toggleEnv = this.toggleEnv; } } componentWillReceiveProps(nextProps) { if (nextProps.server !== this.props.server) { this.setState({ serverValue: nextProps.server, }); } if (nextProps.enabled !== this.props.enabled) { this.setState({ enabledValue: nextProps.enabled, }); } if (nextProps.appKey !== this.props.appKey) { this.setState({ appKeyValue: nextProps.appKey, }); } if (nextProps.appSecret !== this.props.appSecret) { this.setState({ appSecretValue: nextProps.appSecret, }); } } render() { if (this.state.hidden) { return null; } const hasChanges = !( this.state.serverValue === this.props.server && this.state.enabledValue === this.props.enabled && this.state.appKeyValue === this.props.appKey && this.state.appSecretValue === this.props.appSecret ); return ( <div className={styles.root}> <BackHeader onBackClick={this.onCancel} > Environment </BackHeader> <Panel classname={styles.content}> <Line> Server <TextInput value={this.state.serverValue} onChange={this.onServerChange} /> </Line> <Line> App Key <TextInput value={this.state.appKeyValue} onChange={this.onAppKeyChange} /> </Line> <Line> App Secret <TextInput value={this.state.appSecretValue} onChange={this.onAppSecretChange} /> </Line> <IconLine icon={ <Switch checked={this.state.enabledValue} onChange={this.onToggleEnabled} /> } > Enable </IconLine> <Line> Redirect Url <TextInput value={this.props.redirectUri} disabled /> </Line> <Line> <Button className={classnames(styles.saveButton, !hasChanges ? styles.disabled : null)} onClick={this.onOk} disabled={!hasChanges} > Save </Button> </Line> </Panel> </div> ); } }
JavaScript
class CommandDispatcher { /** * @param {Commander} client Client the dispatcher is for * @param {CommandRegistry} registry Registry the dispatcher will use */ constructor(commander, registry) { /** * Commander instance this dispatcher handles messages for * @type {Commander} * @readonly */ this.commander = commander; /** * Registry this dispatcher uses * @type {CommandRegistry} */ this.registry = registry; /** * Map object of {@link RegExp}s that match command messages, mapped by string prefix * @type {RegExp} * @private */ this._commandPattern; } /** * Parses a message to find details about command usage in it * @param {Message} message - The message * @return {?CommanderMessage} * @private */ parseMessage(message) { const prefix = this.commander._commandPrefix; if(!this._commandPattern) this.buildCommandPattern(prefix); const matches = this._commandPattern.exec(message.body); if(!matches) return null; const command = this.registry.findCommand(matches[2]); if(!command) return null; const argString = message.body.substring(matches[1].length + matches[2].length); const args = command.parseArgs(argString); return { command, args } } /** * Handle a new message or a message update * @param {Message} message - The message to handle * @return {Promise<void>} * @private */ async handleMessage(message) { const parsed = this.parseMessage(message); if(parsed && parsed.command) { const command = parsed.command; // Validations const chat = await message.getChat(); if(!command._globalEnabled) { return message.reply(`The \`\`\`${command.name}\`\`\` command has been temporarily disabled.`); } if(command.replyOnly && !message.hasQuotedMsg) { return message.reply(`The \`\`\`${command.name}\`\`\` command can only be used when replying to another message.`); } if(command.groupOnly && !chat.isGroup) { return message.reply(`The \`\`\`${command.name}\`\`\` command can only be used in a group chat.`); } const hasPermission = await command.hasPermission(message); if(!hasPermission || typeof hasPermission === 'string') { if(typeof hasPermission === 'string') return message.reply(hasPermission); else return message.reply(`You do not have permission to use the \`\`\`${command.name}\`\`\` command.`); } // Args const argsResult = await command.obtainArgs(message, parsed.args); if(argsResult.error) { return message.reply(`Invalid arguments provided. You can run \`\`\`!help ${command.name}\`\`\` to get more info.`); } const args = argsResult.values; // Run command try { await command.run(message, args); } catch(error) { console.error(error); message.reply('🔥 An error occurred while trying to execute the command!'); } } } /** * Creates a regular expression to match the command prefix and name in a message * @param {?string} prefix - Prefix to build the pattern for * @return {RegExp} * @private */ buildCommandPattern(prefix) { const myNumber = this.commander.client.info.wid.user; let pattern; if(prefix) { const escapedPrefix = escapeRegex(prefix); pattern = new RegExp( `^(@${myNumber}\\s+(?:${escapedPrefix}\\s*)?|${escapedPrefix}\\s*)([^\\s]+)`, 'i' ); } else { pattern = new RegExp(`(^@${myNumber}\\s+)([^\\s]+)`, 'i'); } this._commandPattern = pattern; return pattern; } }
JavaScript
class VolumeControl extends Component { constructor(props) { super(props); const audio = Player.getAudio(); this.state = { showVolume: false, volume: unsmoothifyVolume(audio.volume), muted: audio.muted, }; this.mute = this.mute.bind(this); this.showVolume = this.showVolume.bind(this); this.hideVolume = this.hideVolume.bind(this); this.setVolume = this.setVolume.bind(this); } getVolumeIcon(volume, muted) { if (muted || volume === 0) return 'volume-off'; if (volume < 0.5) return 'volume-down'; return 'volume-up'; } setVolume(value) { const smoothVolume = smoothifyVolume(value); PlayerActions.setVolume(smoothVolume); this.setState({ volume: smoothVolume }); } showVolume() { this.setState({ showVolume: true }); } hideVolume() { this.setState({ showVolume: false }); } mute(e) { if (e.target.classList.contains('player-control') || e.target.classList.contains('fa')) { const muted = !Player.isMuted(); PlayerActions.setMuted(muted); this.setState({ muted }); } } render() { const volumeClasses = classnames('volume-control', { visible: this.state.showVolume, }); return ( <button type="button" className="player-control volume" title="Volume" onMouseEnter={this.showVolume} onMouseLeave={this.hideVolume} onClick={this.mute} > <Icon name={this.getVolumeIcon(unsmoothifyVolume(this.state.volume), this.state.muted)} /> <div className={volumeClasses}> <Slider min={0} max={1} step={0.01} tooltip={false} value={unsmoothifyVolume(this.state.volume)} onChange={this.setVolume} /> </div> </button> ); } }
JavaScript
class CFWRenderer{ constructor(renderFunction){ this.renderFunction = renderFunction; this.defaultRenderDefinition = { // the data that should be rendered as an array data: null, // (Optional) name of the field that is used as the identifier of the data idfield: null, // (Optional) names of the fields that are used for a titles. Takes the first field from the first object if null titlefields: null, // The format of the title, use {0}, {1} ... {n} as placeholders, concatenates all title fields if null(default) titleformat: null, // (Optional) Names of the fields that should be rendered and in the current order. If null or undefined, will display all fields visiblefields: null, // (Optional) Names of the fields that data should be sorted by. (Note: Do not set this if you enable sorting for Dataviewer to avoid performance overhead) sortbyfields: null, // Direction of the sorting: "asc"|"desc" sortbydirection: "asc", // (Optional) Custom labels for fields, add them as "{fieldname}: {label}". If a label is not defined for a field, uses the capitalized field name labels: {}, // field containing the bootstrap style (primary, info, danger ...) that should be used as the background bgstylefield: null, // field containing the bootstrap style (primary, info, danger ...) that should be used as for texts textstylefield: null, // functions that return a customized htmlString to display a customized format, add as "<fieldname>: function(record, value)". Cannot return a JQuery object. customizers: {}, // array of functions that return html for buttons, add as "<fieldname>: function(record, id)". Cannot return a JQuery object. actions: [ ], // list of functions that should be working with multiple items. fieldname will be used as the button label bulkActions: null, // position of the multi actions, either top|bottom|both|none bulkActionsPos: "top", // settings specific for the renderer, add as "rendererSettings.{rendererName}.{setting}" rendererSettings: {}, getCustomizedValue: function(record, fieldname, rendererName){ var value = record[fieldname]; if(this.customizers[fieldname] == null){ return value; }else{ var customizer = this.customizers[fieldname]; return customizer(record, value, rendererName); } }, getTitleHTML: function(record){ var title = ""; if(!CFW.utils.isNullOrEmpty(this.titleformat)){ var title = this.titleformat; } for(var j = 0; j < this.titlefields.length; j++){ var fieldname = this.titlefields[j]; let value = this.getCustomizedValue(record,fieldname); if(!CFW.utils.isNullOrEmpty(this.titleformat)){ title = title.replace('{'+j+'}', value); }else{ title += ' '+value; } } title = title.replace(/\{\d\}/g, ''); return title.trim(); }, getTitleString: function(record){ var title = this.titleformat; for(var j = 0; j < this.titlefields.length; j++){ var fieldname = this.titlefields[j]; var value = record[fieldname]; if( value != null){ if(this.titleformat != null){ title = title.replace('{'+j+'}', value); }else{ title += ' '+value; } } } title = title.replace(/\{\d\}/g, ''); return title.trim(); }, }; } /******************************************** * Returns a String in the format YYYY-MM-DD ********************************************/ prepareDefinition(definition){ var data = definition.data; var firstObject = null; //--------------------------- // get first object if(Array.isArray(data)){ definition.datatype = "array"; if(data.length > 0){ firstObject = data[0]; } }else if(typeof data == "object"){ definition.datatype = "array"; definition.data = [data]; firstObject = data; }else { definition.datatype = typeof data; } //--------------------------- // Get Visible Fields if(firstObject != null && typeof firstObject == 'object'){ //-------------------------- // resolve default visible fields if(definition.visiblefields == null){ definition.visiblefields = []; for(let key in firstObject){ definition.visiblefields.push(key); } } //-------------------------- // resolve title fields if(definition.titlefields == null || definition.titlefields.length == 0 ){ if(definition.visiblefields.length > 0){ definition.titlefields = [definition.visiblefields[0]]; }else{ // Use first field for titles definition.titlefields = [Object.keys(firstObject)[0]]; } } } //--------------------------- // Create Labels for(let key in definition.visiblefields){ let fieldname = definition.visiblefields[key]; if(definition.labels[fieldname] == null){ definition.labels[fieldname] = CFW.format.fieldNameToLabel(fieldname); } } //--------------------------- // Lowercase definition.bulkActionsPos = definition.bulkActionsPos.toLowerCase(); //--------------------------- // Sort if( !CFW.utils.isNullOrEmpty(definition.sortbyfields) ){ let sortDirection = (definition.sortbydirection == null) ? ['asc'] : [definition.sortbydirection]; let sortFunctionArray = []; let sortDirectionArray = []; for(var index in definition.sortbyfields){ let sortbyField = definition.sortbyfields[index]; sortDirectionArray.push(sortDirection); sortFunctionArray.push( record => { if (typeof record[sortbyField] === 'string'){ // make lowercase to have proper string sorting return record[sortbyField].toLowerCase(); } return record[sortbyField]; } ); }; definition.data = _.orderBy(definition.data, sortFunctionArray, sortDirectionArray); } } /******************************************** * Returns a html string ********************************************/ render(renderDefinition){ var definition = Object.assign({}, this.defaultRenderDefinition, renderDefinition); this.prepareDefinition(definition); return this.renderFunction(definition); } }
JavaScript
class CFWFormField{ constructor(customOptions){ this.defaultOptions = { type: "text", name: null, label: null, value: null, description: null, disabled: false, attributes: {}, // value/label options like { "value": "Label", ... } options: {} }; this.options = Object.assign({}, this.defaultOptions, customOptions); if(this.options.label == null){ this.options.label = CFW.format.fieldNameToLabel(this.options.name); } if(this.options.attributes.placeholder == null){ this.options.attributes.placeholder = this.options.label; } if(this.options.disabled == true){ this.options.attributes.disabled = "disabled"; } } /******************************************** * Returns a String in the format YYYY-MM-DD ********************************************/ createHTML(){ var type = this.options.type.trim().toUpperCase(); //---------------------------- // Start and Label if(type != "HIDDEN"){ var htmlString = '<div class="form-group row ml-1">' +'<label class="col-sm-3 col-form-label" for="3">'+this.options.label+':</label>' +'<div class="col-sm-9">' //---------------------------- // Description Decorator if(this.options.description != null){ htmlString += '<span class="badge badge-info cfw-decorator" data-toggle="tooltip" data-placement="top" data-delay="500" title=""' +'data-original-title="'+this.options.description+'"><i class="fa fa-sm fa-info"></i></span>' } } //---------------------------- // Field HTML this.options.attributes.name = this.options.name; switch(type){ case 'TEXT': this.options.attributes.value = this.options.value; htmlString += '<input type="text" class="form-control" '+this.getAttributesString()+'/>'; break; case 'TEXTAREA': htmlString += this.createTextAreaHTML(); break; case 'BOOLEAN': htmlString += this.createBooleanRadios(); break; case 'SELECT': htmlString += this.createSelectHTML(); break; case 'NUMBER': this.options.attributes.value = this.options.value; htmlString += '<input type="number" class="form-control" '+this.getAttributesString()+'/>'; break; case 'HIDDEN': this.options.attributes.value = this.options.value; htmlString += '<input type="hidden" '+this.getAttributesString()+'/>'; break; case 'EMAIL': this.options.attributes.value = this.options.value; htmlString += '<input type="email" class="form-control" '+this.getAttributesString()+'/>'; break; case 'PASSWORD': this.options.attributes.value = this.options.value; htmlString += '<input type="password" class="form-control" '+this.getAttributesString()+'/>'; break; } //---------------------------- // End if(type != "HIDDEN"){ htmlString += '</div>' +'</div>'; } return htmlString; } /*********************************************************************************** * Create a text area ***********************************************************************************/ createTextAreaHTML() { if(this.options.attributes.rows == null) { this.options.attributes.rows = 5; } var value = ""; if(this.options.value !== null && this.options.value !== undefined ) { value = this.options.value; } return "<textarea class=\"form-control\" "+this.getAttributesString()+">"+value+"</textarea>"; } /*********************************************************************************** * Create Boolean Radio Buttons ***********************************************************************************/ createBooleanRadios() { var falseChecked = ""; var trueChecked = ""; var value = this.options.value; if(value != null && value.toString().toLowerCase() == "true") { trueChecked = "checked"; }else { falseChecked = "checked"; } var disabled = ""; if(this.options.disabled) { disabled = "disabled=\"disabled\""; }; var htmlString = '<div class="form-check form-check-inline col-form-labelmt-5">' + ' <input class="form-check-input" type="radio" value="true" name='+this.options.name+' '+disabled+' '+trueChecked+'/>' + ' <label class="form-check-label" for="inlineRadio1">true</label>' + '</div>' + '<div class="form-check form-check-inline col-form-label">' + ' <input class="form-check-input" type="radio" value="false" name='+this.options.name+' '+disabled+' '+falseChecked+'/>' + ' <label class="form-check-label" for="inlineRadio1">false</label>' + '</div>'; return htmlString; } /*********************************************************************************** * Create a select ***********************************************************************************/ createSelectHTML() { var value = ""; if(this.options.value !== null && this.options.value !== undefined ) { value = this.options.value; } var html = '<select class="form-control" '+this.getAttributesString()+' >'; //----------------------------------- // handle options var options = this.options.options; if(options != null) { for(var currentVal in options) { var label = options[currentVal]; if(currentVal == value) { html += '<option value="'+currentVal+'" selected>' + label + '</option>'; }else { html += '<option value="'+currentVal+'">' + label + '</option>'; } } } html += '</select>'; return html; } /******************************************** * ********************************************/ getAttributesString(){ var result = ''; for(var key in this.options.attributes) { var value = this.options.attributes[key]; if(value != null && value !== "") { result += ' '+key+'="'+value+'" '; } } return result; } }
JavaScript
class CFWToggleButton{ constructor(url, params, isEnabled){ this.url = url; this.params = params; this.isLocked = false; this.button = $('<button class="btn btn-sm">'); this.button.data('instance', this); this.button.attr('onclick', 'cfw_toggleTheToggleButton(this)'); this.button.html($('<i class="fa"></i>')); if(isEnabled){ this.setEnabled(); }else{ this.setDisabled(); } } /******************************************** * Change the display of the button to locked. ********************************************/ setLocked(){ this.isLocked = true; this.button .prop('disabled', this.isLocked) .attr('title', "Cannot be changed") .find('i') .removeClass('fa-check') .removeClass('fa-ban') .addClass('fa-lock'); } /******************************************** * Change the display of the button to enabled. ********************************************/ setEnabled(){ this.isEnabled = true; this.button.addClass("btn-success") .removeClass("btn-danger") .attr('title', "Click to Disable") .find('i') .addClass('fa-check') .removeClass('fa-ban'); } /******************************************** * Change the display of the button to locked. ********************************************/ setDisabled(){ this.isEnabled = false; this.button.removeClass("btn-success") .addClass("btn-danger") .attr('title', "Click to Enable") .find('i') .removeClass('fa-check') .addClass('fa-ban'); } /******************************************** * toggle the Button ********************************************/ toggleButton(){ if(this.isEnabled){ this.setDisabled(); }else{ this.setEnabled(); } } /******************************************** * Send the request and toggle the button if * successful. ********************************************/ onClick(){ var button = this.button; CFW.http.getJSON(this.url, this.params, function(data){ if(data.success){ var instance = $(button).data('instance'); instance.toggleButton(); CFW.ui.addToast("Saved!", null, "success", CFW.config.toastDelay); } } ); } /******************************************** * Returns the button ********************************************/ getButton(){ return this.button; } /******************************************** * Toggle the table filter, default is true. ********************************************/ appendTo(parent){ parent.append(this.button); } }
JavaScript
class RecorderTrack { /** * @ignore * @hideconstructor * private constructor */ constructor(id,track,encoding) { //Store track info this.id = id; this.track = track; this.encoding = encoding; //Create event emitter this.emitter = new EventEmitter(); //Listener for stop track events this.onTrackStopped = () => { //stop recording this.stop(); }; //Listen for track stop event this.track.once("stopped", this.onTrackStopped); } /** * Get recorder track id */ getId() { return this.id; } /** * Get incoming stream track * @returns {IncomingStreamTrack} */ getTrack() { return this.track; } /** * Get incoming encoding * @returns {Object} */ getEncoding() { return this.encoding; } /** * Add event listener * @param {String} event - Event name * @param {function} listener - Event listener * @returns {RecorderTrack} */ on() { //Delegate event listeners to event emitter this.emitter.on.apply(this.emitter, arguments); //Return object so it can be chained return this; } /** * Add event listener once * @param {String} event - Event name * @param {function} listener - Event listener * @returns {IncomingStream} */ once() { //Delegate event listeners to event emitter this.emitter.once.apply(this.emitter, arguments); //Return object so it can be chained return this; } /** * Remove event listener * @param {String} event - Event name * @param {function} listener - Event listener * @returns {RecorderTrack} */ off() { //Delegate event listeners to event emitter return this.emitter.removeListener.apply(this.emitter, arguments); //Return object so it can be chained return this; } /** * Stop recording this track */ stop() { //Don't call it twice if (!this.track) return; //Remove listener this.track.off("stopped",this.onTrackStopped); /** * OutgoingStreamTrack stopped event * * @name stopped * @memberof RecorderTrack * @kind event * @argument {RecorderTrack} recorderTrack */ this.emitter.emit("stopped",this); //Remove track this.track = null; this.encoding = null; } }
JavaScript
class MR26 extends EventEmitter { constructor (port) { super(); if (typeof port === "string") { this.port = port; this.sp = new SerialPort(this.port, { autoOpen: false, baudRate: 9600, dataBits: 8, stopBits: 1, rtscts: true, parser: parser() }); } else { // support passing anything that works like a SerialPort // required for testing this.sp = port; } let mr26 = this; this.sp.on("error", err => mr26.emit("error", err)); } listen (cb) { let mr26 = this; // each transmission is five bytes // the first byte is the "leader" and always the same (0xd5) // the second byte is _supposed to be_ the first of two data bytes // the third byte is _supposed to be_ the two's complement of the previous byte // the fourth byte is the second data byte // the fifth byte is _supposed to be_ the two's complement of the previous byte // realworld testing revealed: // the first and fifth bytes never change // the third byte is the first of two data bytes this.sp.on("data", data => { let func; let byte = Buffer.from([reverse(data[2]), reverse(data[3])]); const FLAG_HOUSE_CODE = parseInt("00001111", 2); const FLAG_OFF = parseInt("00000100", 2); let houseCode = byte[0] & FLAG_HOUSE_CODE; let isOff = byte[1] & FLAG_OFF; let firstTwoBits = (byte[1] & 2) << 1; let thirdBit = (byte[1] >> 3) & 3; let fourthBit = (byte[0] & parseInt("00100000", 2)) >> 2; let unitCodeIndex = firstTwoBits | thirdBit | fourthBit; // 2 on 0_0 = 0 // 3 off 1_0 = 2 // 4 dim 1_1 = 3 // 5 bright 0_1 = 1 if (isOff) { // off func = 3; } else { // on func = 2; } switch(byte[1]) { case 0x11: // bright func = 5; unitCodeIndex = null; break; case 0x19: // dim func = 4; unitCodeIndex = null; break; } let address; if (unitCodeIndex !== null) { address = new X10Address([houseCode, "" + (unitCodeIndex + 1)]); } else { address = new X10HouseCode(houseCode); } let command = new X10Command(func); mr26.emit("data", address.toString() + command.toString()); }); this.sp.open(cb); } }
JavaScript
class Constraint extends Component { render(){ const data = this.props.data if(!data || !data.constraint) return null return ( <> &nbsp;extends&nbsp; <Type data={{type: data.constraint}}/> </> ) } }
JavaScript
class RedrawButton extends Component { render() { return ( <button onClick={this.next}>REDRAW</button> ); } next() { this.props.history.push("/lottery-drawing") } }
JavaScript
class HotjarTracker extends BaseTracker { constructor(...args) { super(...args) this.hjSessionKeyName = "_hjid" } /** * Static method for getting the tracker from window * @returns {Object | Proxy} the hj object, if the function is not existed in `window.hj`, * this method will return Proxy to avoid error * @static */ static getTracker() { if (window.hj) { return window.hj } debug("warning! Seems like window.hj is not defined") return () => {} } /** * send the identity of this user to HotjarTracker * - the identity of the user is the return from `options.mapUserIdentity(profile)` * - the user detail is the return from `options.mapUserProfile(profile)` * @param {Object} profile the user object */ identifyUser(profile) { // For UserID Tracking view debug("=== Hotjar identifyUser running... ===") debug("user data %o => ", profile) const identity = this.mapUserIdentity(profile) const attribute = this.mapUserProfile(profile) debug("hj(identify, %s, %o)", identity, attribute) HotjarTracker.getTracker()("identify", identity, attribute) debug("=== Hotjar identifyUser finished... ===") } /** * This method is removing Hotjar session with Local Storage and Cookie * for getting a newer Hotjar session for recording correct a new user logged in */ logout() { debug("=== Hotjar logout running... ===") debug("Remove local storage and cookie with: %s", this.hjSessionKeyName) removeLocalStorageItem(this.hjSessionKeyName) removeLocalItem(this.hjSessionKeyName) debug("=== Hotjar logout finished... ===") } }
JavaScript
class ParseRequest { static getInteger(request, name, defaultValue, min, max) { let value = request.query[name]; if (_.isNil(value) && _.isNil(defaultValue)) return Promise.reject(invalid(`${name} parameter required`)); if (_.isNil(value)) return Promise.resolve(defaultValue); value = parseInt(value, 10); if (isNaN(value)) return Promise.reject(invalid(`${name} must be an integer`)); if (!_.isNil(min) && value < min) return Promise.reject(invalid(`${name} must be greater than or equal to ${min}`)); if (!_.isNil(max) && value > max) return Promise.reject(invalid(`${name} must be less than or equal to ${max}`)); return Promise.resolve(value); } static getOffset(request) { return ParseRequest.getInteger(request, 'offset', 0, 0); } static getLimit(request, defaultValue, max) { if (_.isNil(defaultValue)) defaultValue = Config.catalog_limit_default; if (_.isNil(max)) max = Config.catalog_limit_max; return ParseRequest.getInteger(request, 'limit', defaultValue, 0, max); } static getEntity(request) { const id = request.query.entity_id; if (_.isEmpty(id)) return Promise.reject(invalid(`entity id required`)); return EntityLookup.byID(id, request.token); } static getEntities(request) { const ids = request.query.entity_id; if (_.isNil(ids)) return Promise.resolve([]); if (ids === '') return Promise.reject(notFound('entity_id cannot be empty')); return EntityLookup.byIDs(ids, request.token); } static getDataset(request) { const datasetID = request.query.dataset_id; if (_.isNil(datasetID)) return Promise.resolve(null); if (datasetID === '') return Promise.reject(notFound('dataset_id cannot be empty')); const tree = Sources.search(datasetID); if (_.isNil(tree)) return Promise.reject(notFound(`dataset not found: ${datasetID}`)); const topic = _.first(_.values(tree)); if (_.size(topic.datasets) !== 1) return Promise.reject(invalid(`expected variable but found topic: ${datasetID}`)); const dataset = _.first(_.values(topic.datasets)); return Promise.resolve(dataset); } static getQuery(request) { const query = request.query.query; if (_.isNil(query)) return Promise.reject(invalid('query parameter required')); return Promise.resolve(query); } }
JavaScript
class EntityVisitor { /** * Callback called when none entity is encountered * * @param {None} none None * @return {*} Object */ acceptNone(none) { // eslint-disable-line no-unused-vars throw new Error("acceptNone isn't implemented"); } /** * Callback called when wall entity is encountered * * @param {Wall} wall Wall * @return {*} Object */ acceptWall(wall) { // eslint-disable-line no-unused-vars throw new Error("acceptWall isn't implemented"); } /** * Callback called when player entity is encountered * * @param {Player} player Player * @return {*} Object */ acceptPlayer(player) { // eslint-disable-line no-unused-vars throw new Error("acceptPlayer isn't implemented"); } /** * Callback called when chest entity is encountered * * @param {Chest} chest Chest * @return {*} Object */ acceptChest(chest) { // eslint-disable-line no-unused-vars throw new Error("acceptChest isn't implemented"); } /** * Callback called when monster entity is encountered * * @param {Monster} monster Monster * @return {*} Object */ acceptMonster(monster) { // eslint-disable-line no-unused-vars throw new Error("acceptMonster isn't implemented"); } /** * Callback called when trap entity is encountered * * @param {Trap} trap Trap * @return {*} Object */ acceptTrap(trap) { // eslint-disable-line no-unused-vars throw new Error("acceptTrap isn't implemented"); } /** * Callback called when monster spawn entity is encountered * * @param {MonsterSpawn} spawn Monster spawn * @return {*} Object */ acceptMonsterSpawn(spawn) { // eslint-disable-line no-unused-vars throw new Error("acceptMonsterSpawn isn't implemented"); } }
JavaScript
class Visitable { /** * Call the suitable callback of the given visitor for this instance * * @param {EntityVisitor} visitor Visitor * @return {*} Object returned by the callback */ visit(visitor) { // eslint-disable-line no-unused-vars throw new Error("visit isn't implemented"); } }
JavaScript
class VisitableEntity extends Entity { /** * Call the suitable callback of the given visitor for this instance * * @param {EntityVisitor} visitor Visitor * @return {*} Object returned by the callback */ visit(visitor) { // eslint-disable-line no-unused-vars throw new Error("visit isn't implemented"); } }
JavaScript
class Flowchart extends container_1.default { get name() { return "flowchart"; } get dir() { return true; } /** * Returns the resize policy for this flowchart container */ get reSizePolicy() { return this.$.reSizePolicy; } /** * @description creates a flowchart component * @param options customizable options */ createItem(options) { switch (options.name) { case "proc": return new process_1.default(this, options); case "cond": return new flowCond_1.default(this, options); case "start": return new flowstart_1.default(this, options); case "end": return new flowend_1.default(this, options); case "inout": return new flowInOut_1.default(this, options); default: throw new Error(`unknown flowchart`); } } bond(thisObj, thisNode, ic, icNode) { if (!this.hasItem(thisObj.id) || !this.hasItem(ic.id)) return false; //directional components can only be connected to other directional components or wires //directional components have a specific amount of origin|destination bonds let thisFlow, icFlow; if (((thisFlow = thisObj instanceof flowComp_1.default) && thisObj.outs >= thisObj.outputs) || ((icFlow = ic instanceof flowComp_1.default) && ic.ins >= ic.inputs)) { return false; } else if (this.bondOneWay(thisObj, thisNode, ic, icNode, 0) // from A to B && this.bondOneWay(ic, icNode, thisObj, thisNode, 1)) // back B to A { //internal hack thisFlow && (thisObj.$.outs++); icFlow && (ic.$.ins++); return true; } return false; } unbond(thisObj, node, id) { let data = super.unbond(thisObj, node, id); if (data != undefined) { let icId = (0, extra_1.getItem)(this.$, id); decrement(data, thisObj, thisObj instanceof flowComp_1.default, icId.t, icId.t instanceof flowComp_1.default); return data; } return; } /** * @description fully unbonds a component node * @param thisObj component * @param node 0-base node * @returns an structure with unbonded information */ unbondNode(thisObj, node) { let res = super.unbondNode(thisObj, node); if (res != undefined) { let objflow = thisObj instanceof flowComp_1.default, data = { dir: res.dir, id: res.id, node: res.node }; //the should be only one connection for flowcharts res.bonds.forEach((obj) => { let icId = (0, extra_1.getItem)(this.$, obj.id); data.toId = obj.id; data.toNode = obj.node; decrement(data, thisObj, objflow, icId.t, icId.t instanceof flowComp_1.default); }); } return res; } defaults() { return (0, misc_1.extend)(super.defaults(), { reSizePolicy: "expand", }); } }
JavaScript
class Discovery { /** * Returns the host port * @param {String} myContainerPort - Port that is listened to * @return {Object} = Object containing host and port members */ static discoverMe(myContainerPort) { if (process.env.CONTAINER_MAPPING) { try { let containerMapping = JSON.parse(process.env.CONTAINER_MAPPING); if (containerMapping.hostIp && containerMapping.portMapping[myContainerPort]) { return { host: containerMapping.hostIp, port: String(containerMapping.portMapping[myContainerPort]) }; } else { let msg = 'Failed to discover the external host:port mapping. ' + process.env.CONTAINER_MAPPING; logger.error(msg); throw new Error(msg); } } catch (e) { logger.error('Container mapping error was:', e); throw e; } } else { let externalHost = getPublicIp(); let externalPort = settings.get('mh:internal:port'); return { host: externalHost, port: String(externalPort) }; } } }
JavaScript
class Actor { constructor(actorName, animatedModelDescriptor, rectBox, processFunc = () => {}, attributes = {}, baseActor = null) { this.name = actorName; this.baseActor = baseActor; /* TODO add actor attributes; use base actor */ this.animatedModelDescriptor = animatedModelDescriptor; this.box = rectBox; this.processFunc = processFunc; this.attributes = attributes; } getName() { return this.name; } getAnimatedModelDescriptor() { return this.animatedModelDescriptor; } getBaseActor() { return this.baseActor; } getBox() { return this.box; } getProcessFunction() { return this.processFunc; } getAttributes() { return this.attributes; } }
JavaScript
class loadingScene extends Phaser.Scene { /** * Constructor * @constructor */ constructor() { super({ key: 'Loading' }); } /** * Load all assets (for all scenes) */ preload() { // get game width and height let gw = this.sys.game.config.width; let gh = this.sys.game.config.height; // load fonts (using the web font file loader) this.load.addFile(new WebFontFile(this.load, ['VT323'])); // show logo let logo = this.add.image(gw/2, gh / 2, 'logo').setScale(5, 5); // logo is already preloaded in 'Boot' scene // text this.add.text(gw/2, gh * 0.20, 'CLOWNGAMING', {fontSize: '70px', color: '#FFFF00', fontStyle: 'bold'}).setOrigin(0.5); this.add.text(gw/2, gh * 0.73, 'Loading', {fontSize: '30px', color: '#4888b7'}).setOrigin(0.5); // progress bar background let bgBar = this.add.graphics(); let barW = gw * 0.3; // progress bar width let barH = barW * 0.1; // progress bar height let barX = gw / 2 - barW / 2; // progress bar x coordinate (origin is 0, 0) let barY = gh * 0.8 - barH / 2; // progress bar y coordinate (origin is 0, 0) bgBar.setPosition(barX, barY); bgBar.fillStyle(0x4888b7, 1); bgBar.fillRect(0, 0, barW, barH); // position is 0, 0 as it was already set with ".setPosition()" // progress bar let progressBar = this.add.graphics(); progressBar.setPosition(barX, barY); // listen to the 'progress' event (fires every time an asset is loaded and 'value' is the relative progress from 0 (nothing loaded) to 1 (fully loaded)) this.load.on('progress', function(value) { // clearing progress bar (to draw it again) progressBar.clear(); // set style progressBar.fillStyle(0x8cefb6, 1); // draw rectangle progressBar.fillRect(0, 0, value * barW, barH); }, this); // load images this.load.image('background', 'assets/images/background.png'); // game background this.load.image('menu', 'assets/images/Menu.png'); // menu background this.load.image('danger', 'assets/images/Danger.png'); // danger block this.load.image('indicator', 'assets/images/Indicator.png'); // mirror indicator this.load.image('pointer', 'assets/images/Pointer.png'); // mirror indicator pointer this.load.image('arrow', 'assets/images/Arrow.png'); // arrow (for the tasks) this.load.image('frame', 'assets/images/Frame.png'); // frame (for text) this.load.image('note', 'assets/images/Note.png'); // note (for music composer) // load spritesheets this.load.spritesheet('block1', 'assets/images/Block1.png', {frameWidth: 25, frameHeight: 25}); // block 1 (normal) this.load.spritesheet('block2', 'assets/images/Block2.png', {frameWidth: 25, frameHeight: 25}); // block 2 (pirate) this.load.spritesheet('block3', 'assets/images/Block3.png', {frameWidth: 25, frameHeight: 25}); // block 3 (glasses) this.load.spritesheet('checkpoint', 'assets/images/Checkpoints.png', {frameWidth: 25, frameHeight: 25}); // checkpoints this.load.spritesheet('eyes', 'assets/images/Eyes.png', {frameWidth: 240, frameHeight: 44}); // inspector eyes // load audio this.load.audio('cnorm', 'assets/audio/Cnorm.mp3'); // playing, C, normal this.load.audio('fnorm', 'assets/audio/Fnorm.mp3'); // playing, F, normal this.load.audio('gnorm', 'assets/audio/Gnorm.mp3'); // playing, G, normal this.load.audio('anorm', 'assets/audio/Anorm.mp3'); // playing, Am, normal this.load.audio('cfast', 'assets/audio/Cfast.mp3'); // playing, C, fast this.load.audio('ffast', 'assets/audio/Ffast.mp3'); // playing, C, fast this.load.audio('gfast', 'assets/audio/Gfast.mp3'); // playing, C, fast this.load.audio('afast', 'assets/audio/Afast.mp3'); // playing, C, fast this.load.audio('cmenu', 'assets/audio/Cmenu.mp3'); // menu, C this.load.audio('fmenu', 'assets/audio/Fmenu.mp3'); // menu, F this.load.audio('gmenu', 'assets/audio/Gmenu.mp3'); // menu, G this.load.audio('amenu', 'assets/audio/Amenu.mp3'); // menu, Am this.load.audio('gameover', 'assets/audio/GameOver.mp3'); // Game Over this.load.audio('level', 'assets/audio/LevelComplete.mp3'); // level complete this.load.audio('mission', 'assets/audio/Mission.mp3'); // mission complete this.load.audio('game', 'assets/audio/GameComplete.mp3'); // game complete } /** * Add the animations and change to "Home" scene, directly after loading */ create() { // add animations (for all scenes) this.addAnimations(); // change to the "Home" scene and provide the default chord progression / sequence this.scene.start('Home', {sequence: [0, 1, 2, 3, 0, 1, 2, 3]}); } /** * Adds all animations (inspector eye animations) for all scenes */ addAnimations() { // eyes animations (moving eyes of the inspector) let frameRate = 50; // frame rate of the animation // from mid to right this.anims.create({ key: 'midToRight', frames: this.anims.generateFrameNames('eyes', {frames: [0, 1, 2, 3, 4, 5]}), frameRate: frameRate, paused: true }); // from right to mid this.anims.create({ key: 'rightToMid', frames: this.anims.generateFrameNames('eyes', {frames: [5, 4, 3, 2, 1, 0]}), frameRate: frameRate, paused: true }); // from mid to left this.anims.create({ key: 'midToLeft', frames: this.anims.generateFrameNames('eyes', {frames: [0, 6, 7, 8, 9, 10]}), frameRate: frameRate, paused: true }); // from left to mid this.anims.create({ key: 'leftToMid', frames: this.anims.generateFrameNames('eyes', {frames: [10, 9, 8, 7, 6, 0]}), frameRate: frameRate, paused: true }); // from left to right this.anims.create({ key: 'leftToRight', frames: this.anims.generateFrameNames('eyes', {frames: [10, 9, 8, 7, 6, 0, 1, 2, 3, 4, 5]}), frameRate: frameRate, paused: true }); // from right to left this.anims.create({ key: 'rightToLeft', frames: this.anims.generateFrameNames('eyes', {frames: [5, 4, 3, 2, 1, 0, 6, 7, 8, 9, 10]}), frameRate: frameRate, paused: true }); } }
JavaScript
class Range { /** * @param {number} [location=-1] - Starting index of the range. * @param {number} [length=0] - Number of characters in the range. */ constructor( location = -1, length = 0) { this.location = location; this.length = length; } /* eslint no-inline-comments: 0 */ /** * Gets the end index of the range, which indicates the character * immediately after the last one in the range. * * @returns {number} *//** * Sets the end index of the range, which indicates the character * immediately after the last one in the range. * * @param {number} [value] - End of the range. * * @returns {number} */ max( value) { if (typeof value == "number") { this.length = value - this.location; } // the NSMaxRange() function in Objective-C returns this value return this.location + this.length; } /** * Returns whether the range contains a location >= 0. * * @returns {boolean} */ isValid() { return (this.location > -1); } /** * Returns an array of the range's start and end indexes. * * @returns {Array<number>} */ toArray() { return [this.location, this.max()]; } /** * Returns a string representation of the range's open interval. * * @returns {string} */ toString() { if (this.location == -1) { return "invalid range"; } else { return "[" + this.location + "," + this.max() + ")"; } } }
JavaScript
class Game extends Component { constructor(props) { super(props); this.state = { currentRound: 0, currentActiveCell: 0, numberOfCorrectAnswers: 0, numberOfWrongAnswers: 0, previousActiveCells: [], userAnswer: USER_ANSWER_RESULT.NOT_ANSWERED, settings: { difficulty: props.difficulty, }, }; } componentDidMount() { this.startGameTimer(); } componentWillUnmount() { this.clearTimer(); } startGameTimer = () => { this.updateGameState(); this.timer = setInterval(this.updateGameState, DEFAULT_GAME_TICK_TIME); }; clearTimer = () => { clearInterval(this.timer); }; clearState() {} updateGameState = () => { const { currentRound, previousActiveCells, currentActiveCell } = this.state; const nextActiveCell = getNextItemIndex( currentActiveCell, DEFAULT_NUMBER_OF_CELLS, ); this.setState({ userAnswer: false, currentRound: currentRound + 1, currentActiveCell: nextActiveCell, previousActiveCells: [...previousActiveCells, ...[currentActiveCell]], }); }; processUserInput = () => { const { previousActiveCells, currentActiveCell, settings: { difficulty }, } = this.state; const previousNAnswer = previousActiveCells[previousActiveCells.length - difficulty]; if (previousNAnswer === currentActiveCell) { this.setState({ userAnswer: USER_ANSWER_RESULT.CORRECT, numberOfCorrectAnswers: this.state.numberOfCorrectAnswers + 1, }); } else { this.setState({ userAnswer: USER_ANSWER_RESULT.INCORRECT, numberOfWrongAnswers: this.state.numberOfWrongAnswers + 1, }); } }; handlerKeyDown = ({ code }) => { if (USER_INPUT_CODES.includes(code)) { this.processUserInput(); } if (STOP_CODES.includes(code)) { this.stopGame(); } }; updateSettings = settings => { this.setState({ ...this.state, settings }); }; stopGame = () => { this.clearTimer(); }; render() { return ( <main className="play-grid-container"> <Results correctAnswers={this.state.numberOfCorrectAnswers} wrongAnswers={this.state.numberOfWrongAnswers} /> <GlobalKeyDownHandler onKeyDown={this.handlerKeyDown} /> <PlayGrid activeCellIndex={this.state.currentActiveCell} userAnswer={this.state.userAnswer} onClick={this.processUserInput} numberOfCells={DEFAULT_NUMBER_OF_CELLS} tickTime={DEFAULT_GAME_TICK_TIME} /> <Settings settings={this.state.settings} onChange={this.updateSettings} /> </main> ); } }
JavaScript
class GameOver extends React.Component { state = { } // render(){ // return ( // <div> // <h2>All Scores</h2> // <div> // {this.props.score.map(s => <p>{s.username}</p>)} // </div> // </div> // ) // } // } // import React from 'react'; // import { Switch, Route } from 'react-router-dom'; // import ScoreContainer from './ScoreContainer'; }
JavaScript
class Task extends BaseInterface { constructor(...args) { // Initialise BaseInterface super() // State defaults extendr.defaults(this.state, { result: null, error: null, status: 'created' }) // Configuration defaults extendr.defaults(this.config, { // Standard storeResult: null, destroyOnceDone: true, parent: null, // Unique to Task method: null, errorOnExcessCompletions: true, ambi: true, domain: null, args: null }) // Apply user configuration this.setConfig(...args) } // =================================== // Typing Helpers /** The type of our class. Used for the purpose of duck typing which is needed when working with node virtual machines as instanceof will not work in those environments. @type {String} @default 'task' @access private */ get type() { return 'task' } /** A helper method to check if the passed argument is a {Task} via instanceof and duck typing. @param {Task} item - The possible instance of the {Task} that we want to check @return {Boolean} Whether or not the item is a {Task} instance. @static @access public */ static isTask(item) { return (item && item.type === 'task') || item instanceof this } // =================================== // Accessors /** An {Array} of the events that we may emit. @type {Array} @default ['events', 'error', 'pending', 'running', 'failed', 'passed', 'completed', 'done', 'destroyed'] @access protected */ get events() { return [ 'events', 'error', 'pending', 'running', 'failed', 'passed', 'completed', 'done', 'destroyed' ] } /** Fetches the interpreted value of storeResult @type {boolean} @access private */ get storeResult() { return this.config.storeResult !== false } // ----------------------------------- // State Accessors /** The first {Error} that has occured. @type {Error} @access protected */ get error() { return this.state.error } /** A {String} containing our current status. See our {Task} description for available values. @type {String} @access protected */ get status() { return this.state.status } /** An {Array} representing the returned result or the passed {Arguments} of our method (minus the first error argument). If no result has occured yet, or we don't care, it is null. @type {?Array} @access protected */ get result() { return this.state.result } // --------------------------------- // Status Accessors /** Have we started execution yet? @type {Boolean} @access private */ get started() { return this.state.status !== 'created' } /** Have we finished execution yet? @type {Boolean} @access private */ get exited() { switch (this.state.status) { case 'failed': case 'passed': case 'destroyed': return true default: return false } } /** Have we completed execution yet? @type {Boolean} @access private */ get completed() { switch (this.state.status) { case 'failed': case 'passed': return true default: return false } } // --------------------------------- // State Changers /** Reset the result. At this point this method is internal, as it's functionality may change in the future, and it's outside use is not yet confirmed. If you need such an ability, let us know via the issue tracker. @chainable @returns {this} @access private */ resetResult() { this.state.result = null return this } /** Clear the domain @chainable @returns {this} @access private */ clearDomain() { const taskDomain = this.state.taskDomain if (taskDomain) { taskDomain.exit() taskDomain.removeAllListeners() this.state.taskDomain = null } return this } // =================================== // Initialization /** Set the configuration for our instance. @param {Object} [config] @param {String} [config.name] - What we would like our name to be, useful for debugging. @param {Function} [config.done] - Passed to {@link Task#onceDone} (aliases are `onceDone`, and `next`) @param {Function} [config.whenDone] - Passed to {@link Task#whenDone} @param {Object} [config.on] - A map of event names linking to listener functions that we would like bounded via {EventEmitter.on} @param {Object} [config.once] - A map of event names linking to listener functions that we would like bounded via {EventEmitter.once} @param {Boolean} [config.storeResult] - Whether or not to store the result, if `false` will not store @param {Boolean} [config.destroyOnceDone=true] - Whether or not to automatically destroy the task once it's done to free up resources @param {TaskGroup} [config.parent] - A parent {@link TaskGroup} that we may be attached to @param {Function} [config.method] - The {Function} to execute for our {Task} @param {Boolean} [config.errorOnExcessCompletions=true] - Whether or not to error if the task completes more than once @param {Boolean} [config.ambi=true] - Whether or not to use bevry/ambi to determine if the method is asynchronous or synchronous and execute it appropriately @param {Boolean} [config.domain] - If not `false` will wrap the task execution in a domain to attempt to catch background errors (aka errors that are occuring in other ticks than the initial execution), if `true` will fail if domains aren't available @param {Array} [config.args] - Arguments that we would like to forward onto our method when we execute it @chainable @returns {this} @access public */ setConfig(...args) { const opts = {} // Extract the configuration from the arguments args.forEach(function (arg) { if (arg == null) return const type = typeof arg switch (type) { case 'string': opts.name = arg break case 'function': opts.method = arg break case 'object': extendr.deep(opts, arg) break default: { throw new Error( `Unknown argument type of [${type}] given to Task::setConfig()` ) } } }) // Apply the configuration directly to our instance eachr(opts, (value, key) => { if (value == null) return switch (key) { case 'on': eachr(value, (value, key) => { if (value) this.on(key, value) }) break case 'once': eachr(value, (value, key) => { if (value) this.once(key, value) }) break case 'whenDone': this.whenDone(value) break case 'onceDone': case 'done': case 'next': this.onceDone(value) break case 'onError': case 'pauseOnError': case 'includeInResults': case 'sync': case 'timeout': case 'exit': throw new Error( `Deprecated configuration property [${key}] given to Task::setConfig()` ) default: this.config[key] = value break } }) // Chain return this } // =================================== // Workflow /** What to do when our task method completes. Should only ever execute once, if it executes more than once, then we error. @param {...*} args - The arguments that will be applied to the {@link Task#result} variable. First argument is the {Error} if it exists. @chainable @returns {this} @access private */ itemCompletionCallback(...args) { // Store the first error let error = this.state.error if (args[0] && !error) { this.state.error = error = args[0] } // Complete for the first (and hopefully only) time if (!this.exited) { // Apply the result if we want to and it exists if (this.storeResult) { this.state.result = args.slice(1) } } // Finish up this.finish() // Chain return this } /** @NOTE Perhaps at some point, we can add abort/exit functionality, but these things have to be considered: What will happen to currently running items? What will happen to remaining items? Should it be two methods? .halt() and .abort(error?) Should it be a state? Should it alter the state? Should it clear or destroy? What is the definition of pausing with this? Perhaps we need to update the definition of pausing to be halted instead? How can we apply this to Task and TaskGroup consistently? @access private @returns {void} */ abort() { throw new Error('not yet implemented') } /** Set our task to the completed state. @chainable @returns {this} @access private */ finish() { const error = this.state.error // Complete for the first (and hopefully only) time if (!this.exited) { // Set the status and emit depending on success or failure status const status = error ? 'failed' : 'passed' this.state.status = status this.emit(status, error) // Notify our listeners we have completed const args = [error] if (this.state.result) args.push(...this.state.result) this.emit('completed', ...args) // Prevent the error from persisting this.state.error = null // Destroy if desired if (this.config.destroyOnceDone) { this.destroy() } } // Error as we have already completed before else if (this.config.errorOnExcessCompletions) { const source = ( this.config.method.unbounded || this.config.method || 'no longer present' ).toString() const completedError = new Error( `The task [${this.names}] just completed, but it had already completed earlier, this is unexpected.\nTask Source: ${source}` ) this.emit('error', completedError) } // Chain return this } /** Destroy ourself and prevent ourself from executing ever again. @chainable @returns {this} @access public */ destroy() { // Update our status and notify our listeners this.state.status = 'destroyed' this.emit('destroyed') // Clear the domain this.clearDomain() // Clear result, in case it keeps references to something this.resetResult() // Remove all listeners this.removeAllListeners() // Chain return this } /** Fire the task method with our config arguments and wrapped in a domain. @chainable @returns {this} @access private */ fire() { // Prepare const taskArgs = (this.config.args || []).slice() let taskDomain = this.state.taskDomain const exitMethod = unbounded.binder.call(this.itemCompletionCallback, this) let method = this.config.method // Check that we have a method to fire if (!method) { const error = new Error( `The task [${this.names}] failed to run as no method was defined for it.` ) this.emit('error', error) return this } // Bind method method = unbounded.binder.call(method, this) // Handle domains if (domain) { // Prepare the task domain if we want to and if it doesn't already exist if (!taskDomain && this.config.domain !== false) { this.state.taskDomain = taskDomain = domain.create() taskDomain.on('error', exitMethod) } } else if (this.config.domain === true) { const error = new Error( `The task [${this.names}] failed to run as it requested to use domains but domains are not available.` ) this.emit('error', error) return this } // Domains, as well as process.nextTick, make it so we can't just use exitMethod directly // Instead we cover it up like so, to ensure the domain exits, as well to ensure the arguments are passed const completeMethod = (...args) => { if (taskDomain) { this.clearDomain() taskDomain = null exitMethod(...args) } else { // Use the next tick workaround to escape the try...catch scope // Which would otherwise catch errors inside our code when it shouldn't therefore suppressing errors queue(function () { exitMethod(...args) }) } } // Our fire function that will be wrapped in a domain or executed directly const fireMethod = () => { // Execute with ambi if appropriate if (this.config.ambi !== false) { ambi(method, ...taskArgs) } // Otherwise execute directly if appropriate else { method(...taskArgs) } } // Add the competion callback to the arguments our method will receive taskArgs.push(completeMethod) // Notify that we are now running this.state.status = 'running' this.emit('running') // Fire the method within the domain if desired, otherwise execute directly if (taskDomain) { taskDomain.run(fireMethod) } else { try { fireMethod() } catch (error) { exitMethod(error) } } // Chain return this } /** Start the execution of the task. Will emit an `error` event if the task has already started before. @chainable @returns {this} @access public */ run() { // Already started? if (this.state.status !== 'created') { const error = new Error( `Invalid run status for the Task [${this.names}], it was [${this.state.status}] instead of [created].` ) this.emit('error', error) return this } // Put it into pending state this.state.status = 'pending' this.emit('pending') // Queue the actual running so we can give time for the listeners to complete before continuing queue(() => this.fire()) // Chain return this } }
JavaScript
class Model { /** * Create a Model. * @property {string} [name] * @property {string} [description] * @property {boolean} [isHidden] * @property {string} [version] * @property {string} [culture] * @property {string} [pbitimeZone] * @property {date} [modifiedTime] * @property {object} [pbimashup] * @property {boolean} [pbimashup.fastCombine] * @property {boolean} [pbimashup.allowNativeQueries] * @property {object} [pbimashup.queriesMetadata] * @property {string} [pbimashup.document] * @property {array} [annotations] * @property {array} [entities] * @property {array} [relationships] * @property {array} [referenceModels] */ constructor() { } /** * Defines the metadata of Model * * @returns {object} metadata of Model * */ mapper() { return { required: false, serializedName: 'Model', type: { name: 'Composite', className: 'Model', modelProperties: { name: { required: false, serializedName: 'name', type: { name: 'String' } }, description: { required: false, serializedName: 'description', type: { name: 'String' } }, isHidden: { required: false, serializedName: 'isHidden', type: { name: 'Boolean' } }, version: { required: false, serializedName: 'version', type: { name: 'String' } }, culture: { required: false, serializedName: 'culture', type: { name: 'String' } }, pbitimeZone: { required: false, serializedName: 'pbi:timeZone', type: { name: 'String' } }, modifiedTime: { required: false, serializedName: 'modifiedTime', type: { name: 'DateTime' } }, pbimashup: { required: false, serializedName: 'pbi:mashup', type: { name: 'Composite', className: 'Mashup' } }, annotations: { required: false, serializedName: 'annotations', type: { name: 'Sequence', element: { required: false, serializedName: 'AnnotationElementType', type: { name: 'Composite', className: 'Annotation' } } } }, entities: { required: false, serializedName: 'entities', type: { name: 'Sequence', element: { required: false, serializedName: 'EntityElementType', type: { name: 'Composite', className: 'Entity' } } } }, relationships: { required: false, serializedName: 'relationships', type: { name: 'Sequence', element: { required: false, serializedName: 'RelationshipElementType', type: { name: 'Composite', className: 'Relationship' } } } }, referenceModels: { required: false, serializedName: 'referenceModels', type: { name: 'Sequence', element: { required: false, serializedName: 'ReferenceModelElementType', type: { name: 'Composite', className: 'ReferenceModel' } } } } } } }; } }
JavaScript
class MmxModel { /** * Allow to press Enter inside the CodeTool textarea * @returns {boolean} * @public */ static get enableLineBreaks() { return true; } /** * Get Tool toolbox settings * icon - Tool icon's SVG * title - title to show in toolbox * * @return {{icon: string, title: string}} */ static get toolbox() { return { // icon: svgIcon, icon: '<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="18px" height="14px" viewBox="0 0 18 14"><g transform="translate(0,-283)"><path d="M 15.125,290.875 H 10.75 c -0.483164,0 -0.875,0.39184 -0.875,0.875 v 4.375 c 0,0.48316 0.391836,0.875 0.875,0.875 h 4.375 C 15.608164,297 16,296.60816 16,296.125 v -4.375 c 0,-0.48316 -0.391836,-0.875 -0.875,-0.875 z m -0.4375,4.8125 h -3.5 v -3.5 h 3.5 z M 5.5,290 C 3.56707,290 2,291.56707 2,293.5 2,295.43293 3.56707,297 5.5,297 7.43293,297 9,295.43293 9,293.5 9,291.56707 7.43293,290 5.5,290 Z m 0,5.6875 c -1.206133,0 -2.1875,-0.98137 -2.1875,-2.1875 0,-1.20613 0.981367,-2.1875 2.1875,-2.1875 1.206133,0 2.1875,0.98137 2.1875,2.1875 0,1.20613 -0.981367,2.1875 -2.1875,2.1875 z m 10.362734,-7.18758 -2.923321,-4.9998 C 12.744726,283.1668 12.403476,283 12.0625,283 c -0.340977,0 -0.682227,0.1668 -0.876914,0.50012 l -2.92332,4.9998 C 7.872344,289.16656 8.359606,290 9.139179,290 h 5.846641 c 0.77957,0 1.266836,-0.83344 0.876914,-1.50008 z m -6.189805,0.18758 2.389571,-4.08707 2.38957,4.08707 z"/></g></svg>', title: 'Model' }; } /** * Render plugin`s main Element and fill it with saved data * @param {TableData} data — previously saved data * @param {object} config - user config for Tool * @param {object} api - Editor.js API */ constructor({data, config, api}) { this.api = api; this._tableConstructor = new TableConstructor(data, config, api); } /** * Return Tool's view * @returns {HTMLDivElement} * @public */ render() { return this._tableConstructor.htmlElement; } /** * Extract Tool's data from the view * @returns {TableData} - saved data * @public */ save(toolsContent) { // modified by xiaowy 2020/09/21 // const table = toolsContent.querySelector('table'); // const table = toolsContent.querySelector('table.tc-table'); // // console.log(table); // const data = []; // const rows = table.rows; // for (let i = 0; i < rows.length; i++) { // const row = rows[i]; // const cols = Array.from(row.cells); // const inputs = cols.map(cell => cell.querySelector('.' + CSS.input)); // const isWorthless = inputs.every(this._isEmpty); // if (isWorthless) { // continue; // } // data.push(inputs.map(input => input.innerHTML)); // } // // added by xiaowy 2020/09/21 for 板块名称 // const blockName = toolsContent.querySelector('.mmxModelDecsTitle'); // if (blockName !== null) { // return { // name : blockName.innerHTML, // content: data // }; // } // else { // return { // content: data // } // } // return { // content: this._tableConstructor.getJsonResult() // }; let ret = this._tableConstructor.getJsonResult() console.log('save:', ret); return ret; } /** * @private * * Check input field is empty * @param {HTMLElement} input - input field * @return {boolean} */ _isEmpty(input) { return !input.textContent.trim(); } }
JavaScript
class SubmitPicksStore { userAddress = null isDialogShowing = false userEmail = '' receiveUpdates = false submissionStatus = { state: 'pending' } constructor() { makeAutoObservable(this); this.getConnectedWallet(); } async getConnectedWallet() { const userAddress = await window.ethereum.request({ method: "eth_requestAccounts", }); if (userAddress.length) { this.userAddress = userAddress[0]; } } signInWithEthereum(firebase, address) { this.userAddress = address; } submitPicks() { this.isDialogShowing = true; this.submissionStatus = { state: 'pending' } } setPicksSuccess(txnHash, entryIndex) { this.submissionStatus = { state: 'succeeded', transactionHash: txnHash, submitter: this.userAddress } } setPicksFailure(message) { this.submissionStatus = { state: 'failed', message } } hideSubmitPicksDialog() { this.isDialogShowing = false } clearStore() { this.isDialogShowing = false this.userEmail = '' this.receiveUpdates = false this.submissionStatus = { state: 'pending' } } }
JavaScript
class Accordion extends Component { constructor (attributes) { // @debug // console.log('LVL99:Accordion:constructor') super(attributes) } extend () { // @debug // console.log('LVL99:Accordion:extend') // Merge the properties with the instantiated attributes super.extend(AccordionProperties, ...arguments) } init () { // @debug // console.log('LVL99:Accordion:init', this.NS, this) // No element found? Error if (!this.getElem() || !this.getElem().length) { throw new Error(`${this.NS}:init: elem is missing`) } // Turn children into {ToggleableComponent}s (if not already {ToggleableComponent}s) if (!this.getAttr('$items') || !this.getAttr('$items').length) { let $items = this.getElem().find(this.getAttr('_accordionItemSelector')) this.setAttr('$items', $items) // @debug // console.log(`${this.NS}:init`, { // component: this, // $items: this.getAttr('$items') // }) // No items! if (!this.getAttr('$items').length) { console.warn(`[${this.NS}:init] Warning: no $items were found to assign to this Accordion`) } else { // Turn child into {ToggleableComponent} using the app's `createComponentInstance` method $items.each((i, item) => { let $item = $(item) // If already set as active item, ensure it is set correctly if ($item.is(`.${this.getAttr('_accordionClassItemActive')}`)) { this.setActiveItem($item) } // Setup for a11y if (this.getAttr('_a11y')) { let $itemToggle = $item.find(this.getAttr('_accordionItemToggleSelector')) let $itemContent = $item.find(this.getAttr('_accordionItemContentSelector')) // Ensure the toggle is tabbable and is a button $itemToggle.attr('tabindex', $itemToggle.attr('tabindex') || 1) $itemToggle.attr('role', 'button') } // Create the component instance, or reference the component instance let accordionToggleableItem if (!$item.attr('data-component-id')) { accordionToggleableItem = this._app.createComponentInstance('LVL99:ToggleableComponent', merge({ // Regular {ToggleableComponent} attributes $classTarget: $item, $elem: $item }, this.getAttr('_accordionItemToggleableAttributes'))) } else { accordionToggleableItem = this._app.getComponentInstance($item.attr('data-component-id')) } // Set special _controllers reference since this item was dynamically instantiated within another component accordionToggleableItem.extend({ _controllers: { accordion: { $elem: this.getElem(), controller: this } } }) }) } } // Special a11y enhancements if (this.getAttr('a11y')) { this.getElem().on('focus', `${this.getAttr('_accordionItemSelector')} ${ this.getAttr('_accordionItemToggleSelector')}`, (jQueryEvent) => { let $item = $(jQueryEvent.target).closest(this.getAttr('_accordionItemSelector')) $item.trigger('LVL99:ToggleableComponent:open') }) } // Attach eventListener to elem to hide other children when {ToggleableComponent} child is opened if (this.getAttr('_accordionCloseOthersOnOpen')) { this.getElem().on('LVL99:ToggleableComponent:open', this.getAttr('_accordionItemSelector'), (jQueryEvent) => { let $item = $(jQueryEvent.target).closest(this.getAttr('_accordionItemSelector')) if (!$item.is(`.${this.getAttr('_accordionClassItemActive')}`)) { let $otherItems = this.getAttr('$items').not($item) jQueryEvent.preventDefault() jQueryEvent.stopPropagation() $otherItems.trigger('LVL99:ToggleableComponent:close') this.unsetActiveItem($otherItems) } }) } // Trigger ToggleableComponent:open when the item's toggle is interacted with this.getElem().on(events.inputstart, `${this.getAttr('_accordionItemSelector')} ${this.getAttr('_accordionItemToggleSelector')}`, (jQueryEvent) => { let $item = $(jQueryEvent.target).closest(this.getAttr('_accordionItemSelector')) jQueryEvent.preventDefault() $item.trigger('LVL99:ToggleableComponent:open') this.setActiveItem($item) }) super.init(...arguments) } /** * Set an item within the accordion to be active. * Note: This does not actually open the item! (unless the CSS class opens the item) * * @param item */ setActiveItem (item) { let $item = $(item) // Add to $activeItem if ($item.is(`.${this.getAttr('_accordionClassItemActive')}`) || (this.getAttr('$activeItem') && this.getAttr('$activeItem').find($item).length)) { // Empty or unset if (!this.getAttr('$activeItem')) { this.setAttr('$activeItem', $item) } else { this.setAttr('$activeItem', this.getAttr('$activeItem').add($item)) } } // Add the active class $item.addClass(this.getAttr('_accordionClassItemActive')) } /** * Unset an item within the accordion to be active * * @param item */ unsetActiveItem (item) { let $item = $(item) // Currently active if ($item.is(`.${this.getAttr('_accordionClassItemActive')}`) || (this.getAttr('$activeItem') && this.getAttr('$activeItem').find($item).length)) { // Empty or unset if (this.getAttr('$activeItem') && this.getAttr('$activeItem').length && this.getAttr('$activeItem').find($item).length) { this.setAttr('$activeItem', this.getAttr('$activeItem').not($item)) } } // Remove the active class $item.removeClass(this.getAttr('_accordionClassItemActive')) } }
JavaScript
class Tagged { /** * Creates an instance of Tagged. * * @param {Number} tag - the number of the tag * @param {any} value - the value inside the tag * @param {Error} err - the error that was thrown parsing the tag, or null */ constructor (tag, value, err) { this.tag = tag this.value = value this.err = err if (typeof this.tag !== 'number') { throw new Error('Invalid tag type (' + (typeof this.tag) + ')') } if ((this.tag < 0) || ((this.tag | 0) !== this.tag)) { throw new Error('Tag must be a positive integer: ' + this.tag) } } /** * Convert to a String * * @returns {String} string of the form '1(2)' */ toString () { return `${this.tag}(${JSON.stringify(this.value)})` } /** * Push the simple value onto the CBOR stream * * @param {cbor.Encoder} gen The generator to push onto * @returns {number} */ encodeCBOR (gen) { gen._pushTag(this.tag) return gen.pushAny(this.value) } /** * If we have a converter for this type, do the conversion. Some converters * are built-in. Additional ones can be passed in. If you want to remove * a built-in converter, pass a converter in whose value is 'null' instead * of a function. * * @param {Object} converters - keys in the object are a tag number, the value * is a function that takes the decoded CBOR and returns a JavaScript value * of the appropriate type. Throw an exception in the function on errors. * @returns {any} - the converted item */ convert (converters) { var er, f f = converters != null ? converters[this.tag] : undefined if (typeof f !== 'function') { f = Tagged['_tag' + this.tag] if (typeof f !== 'function') { return this } } try { return f.call(Tagged, this.value) } catch (error) { er = error this.err = er return this } } }
JavaScript
class Header extends PureComponent { /** * @param {HTMLElement} root This parameter specifies the root PureComponent to render the PureComponent. * @param {Number} index This parameter specifies index number of page. */ constructor(root) { super(root); super.render(HeaderTemplate()); } }
JavaScript
class LoremIpsum { constructor(text) { this._text = text; } [Symbol.iterator]() { const re = /\S+/g; const text = this._text; return { next() { const match = re.exec(text); if (match) { return { value: match[0], done: false }; } return { value: undefined, done: true }; } }; } }
JavaScript
class Control extends BaseObject { /** * Constructor * * @param {Object} [options] Control options. * @param {boolean} [options.active = true] Whether the control is active or not. * @param {HTMLElement} [options.element] The HTML element used to render the control. * @param {HTMLElement} [options.target] The HTML element where to render the element property. Default is the map's element. * @param {HTMLElement} [options.render] Render function called whenever the control needs to be rerendered. */ constructor(options = {}) { super(options); this.defineProperties(options); const { active } = { active: options.active !== false, ...options, }; /** * @ignore */ this.active = active; } /** * Define control's properties. * * @ignore */ defineProperties(options) { const { target, element, render } = { ...options, }; Object.defineProperties(this, { active: { get: () => { return this.get('active'); }, set: (newActive) => { this.set('active', newActive); if (newActive) { this.activate(); } else { this.deactivate(); } this.render(); }, }, map: { get: () => { return this.get('map'); }, set: (map) => { // Remove previous node. if (this.map && this.element && this.element.parentNode) { this.element.parentNode.removeChild(this.element); } // Clean listeners this.deactivate(); this.set('map', map); if (this.map) { // Add new node const targett = this.target || this.map.getContainer(); if (!this.element) { this.createDefaultElement(); } if (this.element) { targett.appendChild(this.element); } // Add listeners if (this.active) { this.activate(); } } this.render(); }, }, target: { value: target, }, element: { value: element, writable: true, }, render: { /** * @ignore */ value: render || this.render, writable: true, }, }); } /** * Add listeners then renders the control. * To be defined in inherited classes. */ activate() { this.deactivate(); } /** * Remove listeners added by activate() function then renders the control. * To be defined in inherited classes. */ // eslint-disable-next-line class-methods-use-this deactivate() {} /** * The default render function. It renders content in the HTML element. * To be defined in inherited classes. */ render() {} /** * The default element to display if this.element is not defined. * To be defined in inherited classes. * @private */ // eslint-disable-next-line class-methods-use-this createDefaultElement() {} }
JavaScript
class Home extends Component { constructor(props) { super(props); this.state = { loading: true, tcounter: 0, titleList: [] } } // Called immediately after a component is mounted. Setting state here will trigger re-rendering. componentDidMount = async () => { let response = await titleAPI.listTitle(0) if (response.status === 200) { let counter = response.data.length this.setState({titleList: response.data, tcounter: counter, loading: false}) } else { this.setState({loading: false}) } const ob = new IntersectionObserver(entries => { entries.forEach((item) => { if(item.isIntersecting){ this.loadmoredata() } }) }) ob.observe(document.getElementById("tmore")) } loadmoredata = async () => { let response = await titleAPI.listTitle(this.state.tcounter) if (response.status === 200) { let list = this.state.titleList.concat(response.data) this.setState({titleList: list, tcounter: list.length}) } } homelayout(){ return ( <section className="home hero"> <div className="hero-body"> <div className="columns is-centered"> <div className="column is-8"> <TitleList data={this.state.titleList} /> <hr id="tmore"/> </div> </div> </div> </section> ) } render() { const {loading} = this.state if(loading) { return ( <div> {this.homelayout( <span className="icon has-text-info"> <i className="fa fa-spinner fa-pulse fa-2x"/> </span> )} </div> ); } else { return( <div> {this.homelayout()} </div> ) } } }
JavaScript
class ItemFactory extends EntityFactory { /** * Create a new instance of an item by EntityReference. Resulting item will * not be held or equipped and will _not_ have its default contents. If you * want it to also populate its default contents you must manually call * `item.hydrate(state)` * * @param {Area} area * @param {string} entityRef * @return {Item} */ create(area, entityRef) { const item = this.createByType(area, entityRef, Item); item.area = area; return item; } }
JavaScript
class CreateAccount extends Component { constructor(props) { super(props); this.state = { step: 1, seed: null, file: null, name: '' }; } copyPhrases = async () => { Clipboard.setString(this.props.stringPhrases); } componentDidMount = () => { if (this.props.restore) this.setState({ step: 4 }); } back = () => { if (this.state.step === 1 || this.state.step === 4) { this.props.close(); } else { this.setState({ step: this.state.step - 1 }); } } continue = (values) => { const seed = this.props.phrases.slice(); if (!this.props.restore) { while (seed.reduce((prev, curr) => prev + +(curr === ''), 6) < 0) { const k = Math.floor(Math.random() * (seed.length - 1)); seed[k] = ''; } if (this.state.step === 3) { this.setState({ step: 5 }); } else { this.setState({ seed, step: 2 }); } } else if (this.state.step !== 3) { for (let index = 0; index < values.length; index += 1) { if (values[index] === '') { toast(this.props.screenProps.t('Initial:error2')); return; } } this.setState({ step: 3, seed }); } else if (this.state.step === 3) { this.setState({ step: 5 }); } } confirm = (values) => { if (this.props.phrases.length !== values.length) { return; } for (let index = 0; index <= values.length; index += 1) { if (values[index] !== this.props.phrases[index]) { toast(this.props.screenProps.t('Initial:error3')); return; } } this.setState({ step: 3 }); } createAccount = (pin, callback) => { this.props.createNewAccount({ pin, seed: this.props.stringPhrases, name: this.state.name }, () => { callback(); }); } closePin = () => { this.setState({ file: null }); } getFile = async () => { const res = await DocumentPicker.pick({ type: [DocumentPicker.types.allFiles], }); this.setState({ file: res.uri }); } restoreAccountWithFile = (pin) => { RNFS.readFile(this.state.file).then(async (res) => { const bytes = await bitcoin.decrypt(res, await bitcoin.sha256(pin)); const decryptedData = JSON.parse(bytes); this.setState({ file: null }); this.props.restoreWithFile(pin, decryptedData); }).catch(() => { toast(this.props.screenProps.t("Initial:error1")); }); } restoreAccount = (pin, values) => { let phrases; for (let index = 0; index < values.length; index += 1) { if (index === 0) { phrases = values[index]; } else { // eslint-disable-next-line prefer-template phrases = phrases + " " + values[index]; } } this.props.restoreWithPhrase(pin, phrases, this.state.name); } setName = (name) => { this.setState({ name }); } componentWillUnmount = () => { this.closePin(); this.props.close(); } render() { const { open, close, phrases, screenProps } = this.props; const action = this.props.restore ? this.restoreAccount : this.createAccount; const values = (this.state.step !== 1 && this.state.step !== 4) ? this.state.seed : phrases; const rule = !!(this.state.step === 1 || this.state.step === 4 || this.state.step === 3); const restoreWithFile = !!this.state.file; const minHeight = this.state.step === 3 ? styles.NameHeight : styles.otherHeight; const disabled = !!(this.state.step === 3 && this.state.name.length < 4); return ( <Formik enableReinitialize onSubmit={this.confirm} initialValues={values} > {({ values, setFieldValue, handleSubmit }) => ( <Modal isVisible={open} onBackdropPress={() => close('openModalPhoto')} swipeDirection={['up', 'left', 'right', 'down']} avoidKeyboard style={{ margin: 0, justifyContent: 'flex-end', }} > <View style={[styles.container, minHeight]}> <RestoreFile open={restoreWithFile} close={this.closePin} config action={this.restoreAccountWithFile} text={screenProps.t('Initial:textBackup')} /> {/* --------------------- Component header --------------------- */} {this.state.step === 1 && ( <View testID="TextCreateAccount"> <Text style={{ textAlign: 'center', padding: 10, fontSize: 23 }}> {screenProps.t('Initial:titleCreateAccount')} </Text> <Text style={{ paddingHorizontal: 10 }}> {screenProps.t('Initial:subTitleCreateAccount')} </Text> </View> )} {this.state.step === 2 && ( <View testID="TextConfirmWords"> <Text style={{ textAlign: 'center', padding: 10, fontSize: 23 }}> {screenProps.t('Initial:titleConfirm')} </Text> <Text style={{ paddingHorizontal: 10 }}> {screenProps.t('Initial:subTitleCorfirm')} </Text> </View> )} {this.state.step === 5 && ( <View testID="TextPin"> <Text style={{ textAlign: 'center', padding: 10, fontSize: 23 }}> {screenProps.t('Initial:titlePin')} </Text> <Text style={{ paddingHorizontal: 10 }}> {screenProps.t('Initial:subtitlePin')} </Text> </View> )} {this.state.step === 3 && ( <View testID="TextUserName"> <Text style={{ textAlign: 'center', padding: 10, fontSize: 23 }}> {screenProps.t('Initial:titleUsername')} </Text> <Text style={{ paddingHorizontal: 10 }}> {screenProps.t('Initial:textUsername')} </Text> </View> )} {this.state.step === 4 && ( <View testID="TextRestoreAccount"> <Text style={{ textAlign: 'center', padding: 10, fontSize: 23 }}> {screenProps.t('Initial:titleRestore')} </Text> <Text style={{ paddingHorizontal: 10 }}> {screenProps.t('Initial:subtitleRestore')} </Text> </View> )} {/* --------------------- End header --------------------- */} {/* ----------------------- Component body ------------------ */} {this.state.step !== 3 && this.state.step !== 5 && ( <Phrases values={values} setFieldValue={setFieldValue} /> )} {this.state.step === 4 && ( <View testID="ButtonRestore" style={{ alignItems: "center", justifyContent: "center", marginBottom: 40, marginTop: 20 }} > <Button success onPress={this.getFile} style={{ justifyContent: 'center', minWidth: 150, marginHorizontal: 10 }} > <Text>{`${screenProps.t('Initial:buttonFile')}`.toUpperCase()}</Text> </Button> </View> )} {this.state.step === 3 && ( <View> <AddName screenProps={screenProps} setName={this.setName} name={this.state.name} /> </View> )} {this.state.step === 5 && ( <View> <PinView back={this.back} createAccount={action} values={values} /> </View> )} {/* ----------------------- End body ------------------ */} <View style={styles.buttonContainer}> {this.state.step !== 5 && ( <Button light testID="buttonBack" onPress={this.back} style={{ justifyContent: 'center', minWidth: 100, marginHorizontal: 10 }} > <Text>{`${screenProps.t('Initial:back')}`.toUpperCase()}</Text> </Button> )} {rule && ( <Button testID="buttonContinue" disabled={disabled} onPress={() => this.continue(values)} style={{ marginHorizontal: 10, justifyContent: 'center', backgroundColor: '#fbc233', minWidth: 100 }} > <Text>{`${screenProps.t('Initial:next')}`.toUpperCase()}</Text> </Button> )} {this.state.step === 2 && ( <Button testID="buttonComfirm" onPress={handleSubmit} style={{ marginHorizontal: 10, justifyContent: 'center', backgroundColor: '#fbc233', minWidth: 100 }} > <Text>{`${screenProps.t('Initial:confirm')}`.toUpperCase()}</Text> </Button> )} </View> </View> </Modal> )} </Formik> ); } }
JavaScript
class ValidationError extends Error { /** * Create an error. * @param {String} message description of the error * @return {error} to be used to throw or reject */ constructor(message = '') { super(message); this.message = message; this.name = 'ValidationError'; } }
JavaScript
class Size { constructor (w, h) { this.w = w this.h = h } toString () { return '(' + this.w + ', ' + this.h + ')' } getHalfSize () { return new Size(this.w >>> 1, this.h >>> 1) } length () { return this.w * this.h } }
JavaScript
class CreateAssetProperty extends LightningElement { // The property object is passed in from the HTML creating this object @api property // The propertie's value is modified by a user in the displayed HTML @track value /** * getPropertyId can be called by parent classes to * get the id of the contained property */ @api getPropertyId() { return this.property.id; } /** * getPropertyValue can be called by parent classes to * get the value of the contained property */ @api getPropertyValue() { return this.value; } /** * handleChange updates the property's value whenever * this property's HTML is modified * @param {*} event The user generated event affecting this property */ handleChange(event) { this.value = event.detail.value; } }
JavaScript
class FindItem extends Event { static WEIGHT = WEIGHT; static operateOn(player, opts = {}, forceItem) { let item = forceItem; if(!forceItem) { item = ItemGenerator.generateItem(null, player.calcLuckBonusFromValue(player.stats.luk)); const playerItem = player.equipment[item.type]; const text = playerItem.score > item.score ? 'weak' : 'strong'; if(!player.canEquip(item)) { const message = `%player came across %item, but it was too ${text} for %himher, so %she sold it for %gold gold.`; const gold = player.sellItem(item); const parsedMessage = this._parseText(message, player, { gold, item: item.fullname }); this.emitMessage({ affected: [player], eventText: parsedMessage, category: MessageCategories.ITEM }); return; } } const id = Event.chance.guid(); const message = `Would you like to equip «${item.fullname}»?`; const eventText = this.eventText('findItem', player, { item: item.fullname }); const extraData = { item, eventText }; player.addChoice({ id, message, extraData, event: 'FindItem', choices: ['Yes', 'No'] }); return [player]; } static makeChoice(player, id, response) { if(response !== 'Yes') return; const choice = _.find(player.choices, { id }); player.equip(new Equipment(choice.extraData.item)); this.emitMessage({ affected: [player], eventText: choice.extraData.eventText, category: MessageCategories.ITEM }); } }
JavaScript
class Game { constructor(svgGameElem) { // Svg Game this.svgGameElem = svgGameElem; this.s = Snap(this.svgGameElem); this.levels = levels.concat(test_levels) // Append test levels after normal ones // Get the highest finished level if (localStorage.getItem("highestFinishedLevel") === null) { this.highestFinishedLevel = 0; localStorage.setItem("highestFinishedLevel", this.highestFinishedLevel); } else { this.highestFinishedLevel = parseInt(localStorage.getItem("highestFinishedLevel")); } // Get the current level if (localStorage.getItem("currentLevel") === null) { howToPlayDialogElem.style.display = "block"; // Show the how to play dialog for the first time this.currentLevel = 1; localStorage.setItem("currentLevel", this.currentLevel); } else { this.currentLevel = parseInt(localStorage.getItem("currentLevel")); } this.levelNumber = this.currentLevel - 1; // Level number, 0 indexed // 0=Instant, 1=Fast, 2=Bounce if (localStorage.getItem("moveAnimation") === null) { this.moveAnimation = (isMobile ? 0 : 2); localStorage.setItem("moveAnimation", this.moveAnimation) } else { this.moveAnimation = parseInt(localStorage.getItem("moveAnimation")); } this.loadLevelData(); // And create the level } /** * Controls */ nextLevel() { if ((this.levelNumber < this.levels.length-1 && this.levelNumber < this.highestFinishedLevel) || DEBUG) { this.levelNumber++; this.loadLevelData(); } } prevLevel() { if (this.levelNumber > 0) { this.levelNumber--; this.loadLevelData(); } } reloadLevel() { this.loadLevelData(); } /** * Create shared defs for later use. */ createDefs() { // Patterns this.striped = this.s.path("M10-5-10,15M15,0,0,15M0-5-20,15").attr({ stroke: "rgba(255,211,147,0.85)", strokeWidth: 5 }).pattern(0, 0, 10, 10); } /** * Setup a new level */ clearLevel() { this.s.clear(); // Clear all svg elements this.createDefs(); // Create defs like shadow levelFinishDialogElem.style.display = "none"; // Hide finish banner this.levelFinished = false; // Is the level finished this.shapes = []; // List of all shapes this.activeShape = false; // The shape which is selected this.reactiveShapes = []; // Other shapes in shape group as active shape this.dragCount = 0; // Drag points source this.dragFromX = 0; this.dragFromY = 0; this.lastDir = ""; // Last direction this.futureGrid = []; // The game grid containing the next move } /** * Loads json level data */ loadLevelData() { let that = this; let xhr = new XMLHttpRequest(); xhr.responseType = "json"; xhr.onload = function(e) { that.levelData = xhr.response; that.clearLevel(); that.createLevel(); }; xhr.open("get", "levels/" + this.levels[this.levelNumber].f, true); xhr.send(); } /** * Create the level from the data */ createLevel() { this.currentLevel = this.levelNumber + 1; localStorage.setItem("currentLevel", this.currentLevel); this.levelTitle = this.levelData.settings.title; this.minMoves = this.levelData.settings.minMoves; // Get level grid dimensions this.gridWidth = this.levelData.settings.gridWidth; this.gridHeight = this.levelData.settings.gridHeight; let screenWidth = window.innerWidth; let maxGameHeight = window.innerHeight - headerElem.offsetHeight - footerElem.offsetHeight - statusElem.offsetHeight; // Adjust the svg element dimensions accordingly this.cellSize = Math.floor(screenWidth / this.gridWidth); // Check height if (this.cellSize * this.gridHeight > maxGameHeight) this.cellSize = Math.floor(maxGameHeight / this.gridHeight); this.gameWidth = this.cellSize * this.gridWidth; this.gameHeight = this.cellSize * this.gridHeight; this.svgGameElem.style.width = this.gameWidth + "px"; this.svgGameElem.style.height = this.gameHeight + "px"; headerElem.style.width = this.svgGameElem.style.width; this.updateStatus(); this.updateHeader(); this.drawGrid(); // Create the internal game grid this.grid = new Array(this.gridHeight).fill(0); for (let y = 0; y < this.gridHeight; y++) { this.grid[y] = new Array(this.gridWidth).fill(0); } // Seen grid is used to know if the game is finished // Create the internal game grid this.seenGrid = new Array(this.gridHeight).fill(false); for (let y = 0; y < this.gridHeight; y++) { this.seenGrid[y] = new Array(this.gridWidth).fill(false); } let shapeId = 1; for (let i = 0; i < this.levelData.elements.length; i++) { for (let j = 0; j < this.levelData.elements[i].shapes.length; j++) { // Loop through all the related shapes let shape = new Shape( shapeId++, // shapeId i + 1, // groupId this.levelData.elements[i].shapes[j], // shapeData this.levelData.elements[i].attr // attr ); this.shapes.push(shape); } } // Add the checkpoints this.gameCheckpoints = this.levelData.settings.checkpoints; this.checkpointShapeGroup = this.s.g(); let quarterCellSize = Math.floor(this.cellSize / 4); for (let checkpoint of this.gameCheckpoints) { let shape = this.s.circle( checkpoint.x * this.cellSize + quarterCellSize * 2, checkpoint.y * this.cellSize + quarterCellSize * 2, quarterCellSize ); this.checkpointShapeGroup.add(shape); } this.checkpointShapeGroup.attr({ fill: FINISH_FILL_COLOR, stroke: "white", strokeWidth: 3, strokeOpacity: 0.5 }); // Show navigation if (this.levelNumber > 0 || DEBUG) prevLevelElem.style.opacity = 1; if (this.levelNumber < this.levels.length-1 && this.highestFinishedLevel > this.levelNumber || DEBUG) nextLevelElem.style.opacity = 1; if (DRAW_GRID_COORDS) this.drawGridCoords(); if (DEBUG) { console.log(this.levels[this.levelNumber].f) console.log("minMoves:" + this.minMoves + " Next step:" + this.minMoves * STAR_STEP_FACTOR) } } clearSeenGrid() { for (let y = 0; y < this.gridHeight; y++) for (let x = 0; x < this.gridWidth; x++) this.seenGrid[y][x] = false; } /* * Check if player has found a solution */ checkFinish(x, y, finished) { if (DISABLE_FINISH) return false; // Skip checking for finish if (finished || this.grid[y][x] === 0 || this.seenGrid[y][x] === true) return finished; // Found a solution, alreay seen the cell or the cell is empty else this.seenGrid[y][x] = true; // Mark this cell as seen if (this.grid[y][x] !== null && this.gameCheckpoints[1].x == x && this.gameCheckpoints[1].y == y) { this.getShapeAtPos(x, y).shape.attr({ fill: FINISH_FILL_COLOR }); return true; // Finish was found } // Check all directions if (x < this.gridWidth - 1) finished = this.checkFinish(x + 1, y, finished); // Right if (x > 0) finished = this.checkFinish(x - 1, y, finished); // Left if (y > 0) finished = this.checkFinish(x, y - 1, finished); // Up if (y < this.gridHeight - 1) finished = this.checkFinish(x, y + 1, finished); // Down if (finished === true) { this.getShapeAtPos(x, y).shape.attr({ fill: FINISH_FILL_COLOR }); } return finished; } /** * Draws x,y coordinates for the grid */ drawGridCoords() { let coords = this.s.g(); // group lines and apply for (let y = 0; y <= this.gridHeight; y++) { for (let x = 0; x <= this.gridWidth; x++) { // Draw cell on the grid coords.add(this.s.text(x * this.cellSize + 5, (y + 1) * this.cellSize - 5, x + "," + y)); } } coords.attr({ fill: "#0000ff", opacity: 0.5, "font-size": "18px", "cursor": "default" }); } /** * Draws a grid */ drawGrid() { let visibleGrid = this.s.g(); // group lines and apply for (let x = 0; x <= this.gridWidth; x++) { visibleGrid.add(this.s.line(x * this.cellSize, 0, x * this.cellSize, this.gameHeight)); } for (let y = 0; y <= this.gridHeight; y++) { visibleGrid.add(this.s.line(0, y * this.cellSize, this.gameWidth, y * this.cellSize)); } visibleGrid.attr({ stroke: "#fff", opacity: 0.25 }); } getShapeById(shapeId) { for (let shape of this.shapes) if (shape.shapeId == shapeId) return shape; return false; } getShapeAtPos(x, y) { let gridCell = this.grid[y][x]; if (gridCell !== 0) return this.getShapeById(gridCell.shapeId); else return false; } getGameGridPos(x, y) { let pos = {}; pos.x = Math.floor(x / this.cellSize); pos.y = Math.floor(y / this.cellSize); return pos; } getReactiveShapes(groupId, excludeShapeId) { let reactiveShapes = []; for (let shape of this.shapes) if (shape.shapeId != excludeShapeId && shape.groupId == groupId) reactiveShapes.push(shape); return reactiveShapes; } setAttrForActiveGroup(attr) { this.activeShape.shape.attr(attr); for (let shape of this.reactiveShapes) shape.shape.attr(attr); } startDrag(x, y) { if (this.levelFinished) return; let pos = this.getGameGridPos(x, y); this.activeShape = this.getShapeAtPos(pos.x, pos.y); // Player can only move active shapes if (this.activeShape && this.activeShape.attr.type != "active") { this.activeShape = false; return; } this.reactiveShapes = this.getReactiveShapes(this.activeShape.groupId, this.activeShape.shapeId); if (this.activeShape) { this.setAttrForActiveGroup({ fill: this.activeShape.attr.actCol }); this.dragFromX = x; this.dragFromY = y; } } onDrag(x, y) { if (!this.levelFinished && this.activeShape) { let deltaX, deltaY; let dir = this.lastDir; let moved = false; deltaX = Math.abs(this.dragFromX - x); deltaY = Math.abs(this.dragFromY - y); if (deltaX > deltaY) { if (this.dragFromX > x) dir = "L"; else if (this.dragFromX < x) dir = "R"; } else { if (this.dragFromY > y) dir = "U"; else if (this.dragFromY < y) dir = "D"; } let dragFactor = (dir == this.lastDir ? 1 : 0.5); if (dir == "L" && deltaX > this.cellSize * dragFactor) { // Move left moved = this.activeShape.move(-1, 0, true); } else if (dir == "R" && deltaX > this.cellSize * dragFactor) { // Move right moved = this.activeShape.move(1, 0, true); } else if (dir == "U" && deltaY > this.cellSize * dragFactor) { // Move up moved = this.activeShape.move(0, -1, true); } else if (dir == "D" && deltaY > this.cellSize * dragFactor) { // Move down moved = this.activeShape.move(0, 1, true); } if (moved) { this.dragFromX = x; this.dragFromY = y; this.lastDir = dir; this.dragCount++; this.updateStatus(); this.setAttrForActiveGroup({ opacity: 1 }); // Show all shapes in group enabled // Is the level finished this.clearSeenGrid(); this.levelFinished = this.checkFinish(this.gameCheckpoints[0].x, this.gameCheckpoints[0].y, false); if (this.levelFinished) { this.checkpointShapeGroup.attr({ fill: "#ffffff" }); game.s.selectAll("#icon").attr({ opacity: 0.5 // display: "none" }); // If this level is your new record if (this.levelNumber < this.levels.length-1 && this.levelNumber == this.highestFinishedLevel) { this.highestFinishedLevel++; localStorage.setItem("highestFinishedLevel", this.highestFinishedLevel); } if (this.levelNumber < this.levels.length-1) { nextLevelElem.style.opacity = 1; // Show next level arrow moreLevelsElem.style.display = "inline-block"; // Also link in finish dialog } else moreLevelsElem.style.display = "none"; // Display the level finish banner let starCount = 1; // Everybody get one star if (this.minMoves * STAR_STEP_FACTOR >= this.dragCount) starCount = 2; if (this.minMoves >= this.dragCount) starCount = 3; levelFinishMessageElem.textContent = levelFinishMessage[starCount - 1]; levelFinishStarsElems[1].src = (starCount >= 2) ? "img/logo.svg" : "img/gray-x-logo.svg"; levelFinishStarsElems[2].src = (starCount >= 3) ? "img/logo.svg" : "img/gray-x-logo.svg"; levelfinishMoveCountElem.textContent = this.dragCount; // Show msg if this was the last normal level if (this.levelNumber == levels.length - 1) noMoreLevelsElem.style.display = "block"; else noMoreLevelsElem.style.display = "none"; setTimeout(function() { levelFinishDialogElem.style.display = "block"; }, 650); // Show the level finish dialog after 0.65 second } // End level finished } } } endDrag() { if (this.activeShape) { if (!this.levelFinished) this.setAttrForActiveGroup({ opacity: 1, stroke: "#ffffff", fill: this.activeShape.attr.col }); // Reset shape in group this.activeShape = false; this.reactiveShapes = []; } } updateStatus() { statusElem.textContent = "moves " + this.dragCount; statusElem.style.opacity = 1; } updateHeader() { let caption = 'Level ' + (this.levelNumber + 1) + '<span>(' + this.levelTitle.toLowerCase() + ')</span>'; levelTitleElem.innerHTML = caption; headerElem.style.opacity = 1; // Unhide header } }
JavaScript
class Player extends Component { constructor(props) { super(props); this.callOrCheck = this.callOrCheck.bind(this); this.raise = this.raise.bind(this); this.fold = this.fold.bind(this); this.handleRaiseChange = this.handleRaiseChange.bind(this); this.state = { raiseAmount: 0, }; } callOrCheck() { if (this.props.playerData.requiredCall === 0) { this.props.updateGame(this.props.index, "checkOrCall"); } else { this.props.updateGame(this.props.index, "checkOrCall"); } } raise() { this.props.updateGame( this.props.index, "raise", Number(this.state.raiseAmount) ); } fold() { this.props.updateGame(this.props.index, "fold"); } handleRaiseChange(event) { const value = event.target.value; this.setState({ raiseAmount: value, }); } render() { return ( <div style={ !this.props.playerData.turn || this.props.playerData.fold ? { opacity: 0.5 } : {} } > <div className="max-w-m bg-teal-600 rounded overflow-hidden shadow-lg m-4"> <span className="inline-block px-3 py-1 text-base font-semibold text-gray-100 mr-2"> Name : {this.props.playerData.name} </span> <span className="inline-block px-3 py-1 text-base font-semibold text-gray-100 mr-2"> Cash : {this.props.playerData.cash} </span> <span className="inline-block px-3 py-1 text-base font-semibold text-yellow-400 mr-2"> Required Call: {this.props.playerData.requiredCall} </span> </div> <div className="inline-flex"> <button disabled={!this.props.playerData.turn || this.props.playerData.fold} className="bg-green-400 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 mx-2 rounded shadow" onClick={this.callOrCheck} > {this.props.playerData.requiredCall === 0 ? "Check" : "Call"} </button> <input className="text-blue-800 px-2 mx-2 rounded shadow" onChange={this.handleRaiseChange} min={this.props.maxRaise} max={this.props.playerData.cash} value={this.state.raiseAmount} name="raiseAmount" type="number" /> <button disabled={!this.props.playerData.turn || this.props.playerData.fold} className="bg-orange-300 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 mx-2 rounded shadow" onClick={this.raise} > Raise </button> <button disabled={!this.props.playerData.turn || this.props.playerData.fold} className="bg-red-500 hover:bg-gray-400 text-gray-800 font-bold py-2 px-4 mx-2 rounded shadow" onClick={this.fold} > Fold </button> </div> </div> ); } }
JavaScript
class Window_Time extends Window_Base { /** * @constructor * @param {Rectangle} rect The shape representing this window. */ constructor(rect) { super(rect); this.opacity = 0; this.generateBackground(); this.initMembers(); }; /** * Replaces the background of the time window with what will look like a standard * "dimmed" window gradient. */ generateBackground() { const c1 = ColorManager.dimColor1(); const c2 = ColorManager.dimColor2(); const x = -4; const y = -4; const w = this.contentsBack.width + 8; const h = this.contentsBack.height + 8; this.contentsBack.gradientFillRect(x, y, w, h, c1, c2, true); this.contentsBack.strokeRect(x, y, w, h, c1); }; /** * Initializes all members of this class. */ initMembers() { this.time = null; this._frames = 0; this._alternating = false; this.refresh(); }; /** * Updates the frames and refreshes the window's contents once every half second. */ update() { super.update(); // don't actually update rendering the time if time isn't active. if (!$gameTime.isActive() || $gameTime.isBlocked()) return; this._frames++; if (this._frames % $gameTime.getTickSpeed() === 0) { this.refresh(); } if (this._frames % 60 === 0) { this._alternating = !this._alternating; this.refresh(); } }; /** * Refreshes the window by clearing it and redrawing everything. */ refresh() { this.time = $gameTime.currentTime(); this.contents.clear(); this.drawContent(); }; /** * Draws the contents of the window. */ drawContent() { const colon1 = this._alternating ? ":" : " "; const colon2 = this._alternating ? " " : ":"; const ampm = this.time.hours > 11 ? "PM" : "AM"; const lh = this.lineHeight(); const seconds = this.time.seconds.padZero(2); const minutes = this.time.minutes.padZero(2); const hours = this.time.hours.padZero(2); const timeOfDayName = this.time.timeOfDayName; const timeOfDayIcon = this.time.timeOfDayIcon; const seasonName = this.time.seasonOfTheYearName; const seasonIcon = this.time.seasonOfTheYearIcon; const days = this.time.days.padZero(2); const months = this.time.months.padZero(2); const years = this.time.years.padZero(4); this.drawTextEx(`\\I[2784]${hours}${colon1}${minutes}${colon2}${seconds} \\}${ampm}`, 0, lh * 0, 200); this.drawTextEx(`\\I[${timeOfDayIcon}]${timeOfDayName}`, 0, lh * 1, 200); this.drawTextEx(`\\I[${seasonIcon}]${seasonName}`, 0, lh * 2, 200); this.drawTextEx(`${years}/${months}/${days}`, 0, lh * 3, 200); }; }
JavaScript
class Time_Snapshot { /** * @constructor * @param {number} seconds The seconds of the current time. * @param {number} minutes The minutes of the current time. * @param {number} hours The hours of the current time. * @param {number} days The days of the current time. * @param {number} months The months of the current time. * @param {number} years The years of the current time. * @param {number} timeOfDayId The id of the time of day. * @param {number} seasonOfYearId The id of the season of the year. */ constructor(seconds, minutes, hours, days, months, years, timeOfDayId, seasonOfYearId) { /** * The seconds of the current time. * @type {number} */ this.seconds = seconds; /** * The minutes of the current time. * @type {number} */ this.minutes = minutes; /** * The hours of the current time. * @type {number} */ this.hours = hours; /** * The days of the current time. * @type {number} */ this.days = days; /** * The months of the current time. * @type {number} */ this.months = months; /** * The years of the current time. * @type {number} */ this.years = years; /** * The id of the time of day. * @type {number} */ this._timeOfDayId = timeOfDayId; /** * The id of the season of the year. * @type {number} */ this._seasonOfYearId = seasonOfYearId; }; //#region statics /** * Translates the numeric season of the year into it's proper name. * @param {number} seasonId The numeric representation of the season of the year. * @returns {string} */ static SeasonsName(seasonId) { switch (seasonId) { case 0: return "Spring"; case 1: return "Summer"; case 2: return "Autumn"; case 3: return "Winter"; default: return `${seasonId} is not a valid season id.`; } }; /** * Translates the numeric season of the year into it's icon index. * @param {number} seasonId The numeric representation of the season of the year. * @returns {string} */ static SeasonsIconIndex(seasonId) { switch (seasonId) { case 0: return 887; case 1: return 888; case 2: return 889; case 3: return 890; default: return `${seasonId} is not a valid season id.`; } }; /** * Translates the numeric time of the day into it's proper name. * @param {number} timeOfDayId The numeric representation of the time of the day. * @returns {string} */ static TimesOfDayName(timeOfDayId) { switch (timeOfDayId) { case 0: return "Night"; // midnight-4am case 1: return "Dawn"; // 4am-8am case 2: return "Morning"; // 8am-noon case 3: return "Afternoon"; // noon-4pm case 4: return "Evening"; // 4pm-8pm case 5: return "Twilight"; // 8pm-midnight default: return `${timeOfDayId} is not a valid time of day id.`; } }; /** * Translates the numeric time of the day into it's icon index. * @param {number} timeOfDayId The numeric representation of the time of the day. * @returns {string} */ static TimesOfDayIcon(timeOfDayId) { switch (timeOfDayId) { case 0: return 2256; // midnight-4am case 1: return 2260; // 4am-8am case 2: return 2261; // 8am-noon case 3: return 2261; // noon-4pm case 4: return 2257; // 4pm-8pm case 5: return 2256; // 8pm-midnight default: return `${timeOfDayId} is not a valid time of day id.`; } }; //#endregion statics /** * Gets the name of the current season of the year. * @type {string} */ get seasonOfTheYearName() { return Time_Snapshot.SeasonsName(this._seasonOfYearId); }; /** * Gets the icon index of the current season of the year. * @type {number} */ get seasonOfTheYearIcon() { return Time_Snapshot.SeasonsIconIndex(this._seasonOfYearId); }; /** * Gets the name of the current time of the day. * @type {string} */ get timeOfDayName() { return Time_Snapshot.TimesOfDayName(this._timeOfDayId); }; /** * Gets the icon index of the current time of the day. * @type {number} */ get timeOfDayIcon() { return Time_Snapshot.TimesOfDayIcon(this._timeOfDayId); }; }
JavaScript
class AsyncMutex { constructor() { this.queue = [ ] this.acquired = false } /** * This method returns a promise that resolves * as soon as all other callers of acquire() * have invoked release(). When the promise * resolves, you can access to critical section * or protected resource * * @method acquire * @return {Promise} */ acquire() { let self = this return new Promise(function(resolve, reject) { if(self.acquired) { self.queue.push(resolve) } else { self.acquired = true resolve() } }) } /** * This method indicates that you are done * with the critical section and will give * control to the next caller to acquire() * * @method release */ release() { let next = this.queue.shift() if(next) { next() } else { this.acquired = false } } /** * This method returns the length of the * number of threads waiting to acquire * this lock */ queueSize() { return this.queue.length } }
JavaScript
class MockResponse { status() { return 200 } ok() { return true } body() { return {} } get() { return jest.fn() } toError() { return jest.fn() } }
JavaScript
class HackathonBody extends Component { /** * * @param {number} index To determine the index of the row selected by the user. * @returns {void} */ onRegister(index) { let arr = JSON.parse(localStorage.getItem("hackathon-data")); console.log("arr", arr, index); arr = arr.filter(e => e.location === this.props.city); let data = arr[index]; alert("Thank you for registering for: " + data.title); } /** * @constructor * @param {object} props Gets the props object as a parameter */ constructor(props) { super(props); this.onRegister = this.onRegister.bind(this); let hackathonData = JSON.parse(localStorage.getItem("hackathon-data")); /** * @state * @property {array} hackathonData Contains all the static hackathon data */ this.state = { hackathonData, }; } render() { let arr = this.state.hackathonData.filter( (elem) => elem.location === this.props.city ); return ( <div> {arr.length > 0 ? ( arr.map((e, index) => { const { title, description, duration, posterUrl, date, location, } = e; // let ind = index; return ( <div className="hack-body"> <div className="hackathon-image-block"> <img src={posterUrl} alt="new" className="hack-poster" /> </div> <div className="hackathon-description"> <div> <p className="hackathon-title">{title}</p> <p className="hackathon-description-text">{description}</p> <HackData data={{ label: "Duration:", value: duration }} /> <HackData data={{ label: "Location:", value: location }} /> <HackData data={{ label: "Date:", value: date, }} /> <button className="register-btn" onClick={() => this.onRegister(index)} > Register </button> </div> </div> </div> ); }) ) : ( <h4 style={{ textAlign: "center", marginTop: "3rem" }}> No Hackathons Found </h4> )} </div> ); } }
JavaScript
class Planet extends GameObject { /** * Constructor. */ constructor(inConfig) { // Construct object. super((function() { return webix.extend(inConfig, { pixWidth : 64, pixHeight : 64, frameCount : 1, baseName : "planet" } ); }())); // Load frames. super.loadFrames({ x : 0, y : 492, playfield : inConfig.playfield, hidden : true }); // Randomly position the planet somewhere. Any time it collides with the player, try again. // When we have a good position, show the planet. while (this.randomlyPosition()) { this.randomlyPosition(); } } /* End constructor. */ } /* End Planet. */
JavaScript
class WebpageUserBaseController { constructor (modelName) { if (typeof(modelName) !== 'string') { modelName = 'Annotation' } this.modelName = modelName } setModel (model) { this.modelName = model } get model () { //console.log('App/Models/' + this.modelName) return use('App/Models/' + this.modelName) } get hasDeletedColumn () { return true } async indexMy ({ request, webpage, user }) { let condition = request.all() await ReadingActivityLog.log(webpage, user, this.modelName + '.indexMy', condition) let cacheKey = `${this.modelName}.indexMy.${webpage.id}.${user.id}.${JSON.stringify(condition)}` return await Cache.rememberWait(Cache.buildTags(webpage, user, this.modelName), Config.get('view.indexCacheMinute'), cacheKey, async () => { //return await Cache.get(cacheKey, async () => { let query = this.model .query() .where('webpage_id', webpage.primaryKeyValue) .where('user_id', user.primaryKeyValue) .orderBy('created_at', 'asc') if (this.hasDeletedColumn === true) { query.where('deleted', false) } if (typeof(condition) === 'object') { query.where(condition) } let output = await query.fetch() //await Cache.put(cacheKey, output, Config.get('view.indexCacheMinute')) return output }) } async indexOthers ({ request, webpage, user }) { let condition = request.all() await ReadingActivityLog.log(webpage, user, this.modelName + '.indexOthers', condition) let cacheKey = `${this.modelName}.indexOthers.${webpage.id}.${user.id}.${JSON.stringify(condition)}` return await Cache.rememberWait(Cache.buildTags(webpage, user, this.modelName), Config.get('view.indexCacheMinute'), cacheKey, async () => { //return await Cache.get(cacheKey, async () => { let others = await user.getOtherUsersInGroup(webpage) let query = this.model .query() .where('webpage_id', webpage.primaryKeyValue) .whereIn('user_id', others) if (this.hasDeletedColumn === true) { query.where('deleted', false) } if (typeof(condition) === 'object') { query.where(condition) } let output = await query.fetch() //await Cache.put(cacheKey, output, Config.get('view.indexCacheMinute')) return output }) } // async indexOthers ({ request, webpage, user }) { async create({request, webpage, user}) { let id = -1 let data = request.all() await ReadingActivityLog.log(webpage, user, this.modelName + '.create', data) if (this.hasDeletedColumn === false) { let instance = new this.model instance.webpage_id = webpage.primaryKeyValue instance.user_id = user.primaryKeyValue for (let name in data) { instance[name] = data[name] } await instance.save() id = instance.id } else { let condition = { webpage_id: webpage.primaryKeyValue, user_id: user.primaryKeyValue, } for (let name in data) { condition[name] = data[name] } let instance = await this.model.findOrCreate(condition) if (instance.deleted === true) { instance.deleted = false await instance.save() id = instance.id } } return id } // async create({request, webpage, user}) { async update ({request, webpage, user}) { let data = request.all() await ReadingActivityLog.log(webpage, user, this.modelName + '.update', data) let id = data.id if (typeof(id) !== 'number' && typeof(id) !== 'string') { throw new HttpException('No id') } let instance = await this.model.find(id) if (instance.user_id !== user.id) { throw new HttpException('You are not owner of it.') } for (let name in data) { if (name === 'id') { continue } else { instance[name] = data[name] } } await instance.save() return 1 } // async update ({request, webpage, user}) { async destroy({request, webpage, user}) { let data = request.all() await ReadingActivityLog.log(webpage, user, this.modelName + '.destroy', data) let id = data.id if (typeof(id) === 'string' && isNaN(id) === false) { id = parseInt(id, 10) } if (typeof(id) !== 'number') { throw new HttpException('No id') } let instance = await this.model.find(id) if (instance === null || instance.user_id !== user.id) { throw new HttpException('You are not owner of it.') } if (typeof(instance.deleted) === 'boolean' && instance.deleted === false) { instance.deleted = true await instance.save() } else { await instance.delete() } return 1 } // async destroy({request, webpage, user}) { }
JavaScript
class JournalEntryData { /** * Constructs a new <code>JournalEntryData</code>. * @alias module:model/JournalEntryData */ constructor() { JournalEntryData.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>JournalEntryData</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/JournalEntryData} obj Optional instance to populate. * @return {module:model/JournalEntryData} The populated <code>JournalEntryData</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new JournalEntryData(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('officeId')) { obj['officeId'] = ApiClient.convertToType(data['officeId'], 'Number'); } if (data.hasOwnProperty('glAccountId')) { obj['glAccountId'] = ApiClient.convertToType(data['glAccountId'], 'Number'); } if (data.hasOwnProperty('glAccountType')) { obj['glAccountType'] = EnumOptionData.constructFromObject(data['glAccountType']); } if (data.hasOwnProperty('transactionDate')) { obj['transactionDate'] = ApiClient.convertToType(data['transactionDate'], 'Date'); } if (data.hasOwnProperty('entryType')) { obj['entryType'] = EnumOptionData.constructFromObject(data['entryType']); } if (data.hasOwnProperty('amount')) { obj['amount'] = ApiClient.convertToType(data['amount'], 'Number'); } if (data.hasOwnProperty('transactionId')) { obj['transactionId'] = ApiClient.convertToType(data['transactionId'], 'String'); } if (data.hasOwnProperty('rowIndex')) { obj['rowIndex'] = ApiClient.convertToType(data['rowIndex'], 'Number'); } } return obj; } }
JavaScript
class Trainer { /* constructor [constructor]: - parameters: none - action: creates a new Pokemon Trainer - return value: a new Pokemon Trainer */ constructor() { this.firstName = 'Shdave' this.lastName = 'D' this.age = 30 this.energy = 80 this.happiness = 50 this.slogan = 'Happiness only with success' this.energy = 75 this.happiness = 75 this.confidence = 75 this.intelligence = 75 this.strength = 75 } /* Note: For all of the specs below, assume the trainer has firstName: `Ash` and lastName: `Ketchum` */ /* getFullName [method]: - Parameters: none - Action: constructs the trainer's full name from the trainer's {firstName} and {lastName} - Return Value: full name [string] - Example: `Ash Ketchum` [string] */ getFullName() { return `${this.firstName} ${this.lastName}` } /* getReverseName [method]: - Parameters: none - Action: constructs the trainer's 'reverse' name from the trainer's {lastName} and {firstName} - Return Value: reverse name [string] - Example: `Ketchum, Ash` [string] */ getReverseName() { return `${this.lastName}, ${this.firstName}` } /* getDoubleFullName [method]: - Parameters: none - Action: constructs the trainer's 'double full name' from the trainer's {firstName} and {lastName} - Return Value: double full name [string] - Example: `Ash Ash Ketchum Ketchum` [string] */ getDoubleFullName() { return `${this.firstName} ${this.firstName} ` + `${this.lastName} ${this.lastName}` } /* getDoubleReverseName [method]: - Parameters: none - Action: constructs the trainer's 'double reverse name' from the trainer's {firstName} and {lastName} - Return Value: double reverse name [string] - Example: `Ketchum Ketchum, Ash Ash` [string] */ getDoubleReverseFullName() { return `${this.lastName} ${this.lastName}, ${this.firstName} ${this.firstName} ` } /* getFirstNameLastInitial [method]: - Parameters: none - Action: constructs a string containing the trainer's {firstName} and the first letter of the the trainer's {lastName} followed by a period - Return Value: first name last initial [string] - Example: `Ash K.` [string] */ getFirstNameLastInitial() { return `${this.firstName} ${this.lastName[0]}.` } /* getFirstInitialLastName [method]: - Parameters: none - Action: constructs a string containing the first letter of the trainer's {firstName} followed by a period and the trainer's {lastName} - Example: `A. Ketchum` [string] - Return Value: first initial last name [string] */ getFirstInitialLastName() { return `${this.firstName[0]}. ${this.lastName}` } /* getElementWeakestAgainst [method]: - Parameters: none - Action: constructs a string indicating what element this trainer is weakest against based on the trainer's favorite element. The rules are: * Water is weakest against Plant * Plant is weakest against Fire * Fire is weakest against Water (We're assuming the trainer's favorite element is 'Water', 'Fire', or 'Plant' only) - Return Value: element weakest against [string] - Example: For a trainer whose favorite element is 'Water', this method should return `Plant` [string]. - Extra Credit: If the trainer's element is not 'Water', 'Fire', or 'Plant', the method should return 'Error! Element not recognized' */ getElementWeakestAgainst() { if (this.favoriteElement === 'Water') { return 'Plant' } else if (this.favoriteElement === 'Fire') { return 'Water' } else if (this.favoriteElement === 'Plant') { return 'Fire' } else { return 'Error! Element not recognized' } } /* getElementStrongestAgainst [method]: - Parameters: none - Action: constructs a string indicating what element this trainer is strongest against based on the trainer's favorite element. The rules are: * Water is strongest against Fire * Plant is strongest against Water * Fire is strongest against Plant (We're assuming the trainer's favorite element is 'Water', 'Fire', or 'Plant' only) - Return Value: element weakest against [string] - Example: For a trainer whose favorite element is 'Water', this method should return `Fire` [string]. - Extra Credit: If the trainer's element is not 'Water', 'Fire', or 'Plant', the method should return 'Error! Element not recognized' */ getElementStrongestAgainst() { if (this.favoriteElement === 'Water') { return 'Fire' } else if (this.favoriteElement === 'Fire') { return 'Plant' } else if (this.favoriteElement === 'Plant') { return 'Water' } else { return 'Error! Element not recognized' } } /* writeHi [method]: - Parameters: none - Action: creates a chat bubble near the trainer's picture that prints out 'Hi'. - Return Value: none - Hint: Look for a function in the API docs that can create a chat bubble with the string you give it. */ writeHi() { createChatBubble("Hi") } /* writeSlogan [method]: - Parameters: none - Action: creates a chat bubble near the trainer's picture that prints out the trainer's slogan - Return Value: none */ writeSlogan() { createChatBubble(this.slogan) } /* write [method]: - Parameters: message [string] - Action: creates a chat bubble near the trainer's picture that prints out the {message} given - Return Value: none */ write(message) { createChatBubble(message) } /* sayHi [method]: - Parameters: none - Action: speaks the word 'Hi' out loud on your computer's speakers. - Return Value: none - Hint: Look for a function in the API docs that can speak words out loud by converting text to speech. */ sayHi() { textToSpeech("Hi!") } /* saySlogan [method]: - Parameters: none - Action: speaks your trainer's slogan out loud on your computer's speakers. - Return Value: none */ saySlogan() { textToSpeech(this.slogan) } /* say [method]: - Parameters: message [string] - Action: speaks out loud whatever {message} is given, using your computer's speakers. - Return Value: none */ say(message) { textToSpeech(message) } getAgeInMonths() { return this.age * 12 } getAgeInWeeks() { return this.age * 52 } getAgeInDays() { return this.age * 365 } getAgeInHours() { return getAgeInDays() * 24 } getAgeInMinutes() { return getAgeInHours() * 60 } getAgeInSeconds() { return getAgeInHours() * 60 } work() { this.coins += 50 this.energy -= 20 this.happiness -= 10 this.confidence += 5 } rest() { this.energy += 20 this.intelligence += 10 } eat() { } exercise() { } /* Returns the name of the Pokemon's image file. The image changes based on the Pokemon's species and whether it is alive or not. For example: a Charmander pokemon's image file should be: 'Charmander.png' if it is alive and 'Charmander-Dead.png' if it is dead. a Blastoise pokemon's image file should be: 'Blastoise.png' if it is alive and 'Blastoise-Dead.png' if it is dead. */ getImageFileName() { return this.getFullName() + '.png' } getAgeDescription() { var description = '' if (this.age < 10) { description = 'kid' } else if (this.age < 13) { description = 'pre-teen' } else if (this.age < 20) { description = 'teenager' } else { description = 'adult' } return description } getHappinessDescription() { var description = '' if (this.happiness <= 20) { description = 'very sad' } else if (this.happiness <= 40) { description = 'sad' } else if (this.happiness <= 60) { description = 'neutral' } else if (this.happiness <= 80) { description = 'happy' } else if (this.happiness <= 100) { description = 'very happy' } return description } getConfidenceDescription() { var description = '' if (this.confidence <= 34) { description = 'not confident' } else if (this.confidence <= 67) { description = 'modestly confident' } else if (this.confidence <= 100) { description = 'very confident' } return description } }
JavaScript
class human { constructor(name, age, task, career) { this.name = name; this.age = age; this.task = task; this.career = career; } greeting() { return ("I am a " + this.career); } }
JavaScript
class WorkingBot extends Bot { // Override connect to figure out when connection breaks connect() { super.connect(); let id = 0; let lastResponse = new Date(); // Capture pong responses this.ws.on('message', (resp) => { if (JSON.parse(resp).type == 'pong') { lastResponse = new Date(); } }); // Send ping requests periodicallly const interval = setInterval(() => { const state = this.ws.readyState; if (state === this.ws.CLOSING || state === this.ws.CLOSED) { // Prevent further calling of this instance of bot return clearInterval(interval); } // If connection timeouts const elapsedTime = new Date() - lastResponse; if (elapsedTime > PING_TIMEOUT) { console.error(`Connection timeout, last response is ${ elapsedTime / 1000 }s old!`); return this.ws.close(); } // Otherwise determine whether connection is open and send ping if (state === this.ws.OPEN) { this.ws.send(JSON.stringify({ id: `ping_${id++}`, type: 'ping' }), (error) => { // Capture connection error if (error) { console.error(error); this.ws.close(); } }); } }, PING_INTERVAL); } }
JavaScript
class ToolboxLabel extends Blockly.ToolboxItem { /** * Constructor for a label in the toolbox. * @param {!Blockly.utils.toolbox.ToolboxItemInfo} toolboxItemDef The toolbox * item definition. This comes directly from the toolbox definition. * @param {!Blockly.IToolbox} parentToolbox The toolbox that holds this * toolbox item. * @override */ constructor(toolboxItemDef, parentToolbox) { super(toolboxItemDef, parentToolbox); /** * The button element. * @type {?HTMLLabelElement} */ this.label = null; } /** * Init method for the label. * @override */ init() { // Create the label. this.label = document.createElement('label'); // Set the name. this.label.textContent = this.toolboxItemDef_['name']; // Set the color. this.label.style.color = this.toolboxItemDef_['colour']; // Any attributes that begin with css- will get added to a cssconfig. const cssConfig = this.toolboxItemDef_['cssconfig']; // Add the class. if (cssConfig) { this.label.classList.add(cssConfig['label']); } } /** * Gets the div for the toolbox item. * @return {HTMLLabelElement} The label element. * @override */ getDiv() { return this.label; } }
JavaScript
class ErrorResponse extends Error { constructor(statusCode, message, errorCode = 'error') { super(message); this.statusCode = statusCode; this.errorCode = errorCode; } }
JavaScript
class SavedGame { /** * Creates a new instance of the SavedGame class * @param {Uint8Array} decompressedArrayBuffer - Saved game data * @param {string} name - Default filename to use when exporting */ constructor(decompressedArrayBuffer, zipFilename) { this.zipFilename = zipFilename; this.initialize(decompressedArrayBuffer); } /** * Initializes (or re-initializes) the class * @param {Uint8Array} decompressedArrayBuffer - Saved game data */ initialize(decompressedArrayBuffer) { this.index = {}; this.files = []; this.decompressed = decompressedArrayBuffer; this.position = 0; // Saved game format is repeated blocks of // {BSTR Filename, UInt32 dataSize, byte[] dataContent } // until you hit the end of the file while (!this.eof()) { var filename = this.readString(); var filesize = this.readInt32(); var entry = { filename: filename, filesize: filesize, offset: this.position }; this.files.push(entry); this.index[entry.filename] = entry; Log("Found file '" + filename + "' length " + filesize + " at offset " + this.position); this.skipBytes(filesize); } } /** * Reads a single unsigned byte from the saved game data and * advances the position in the file by one byte * @return {number} Read value */ readByte() { return this.decompressed[this.position++]; } /** * Reads a unsigned 16-bit word from the saved game data and * advances the position in the file by two byte * @return {number} Read value */ readInt16() { return this.readByte() + 0x100 * this.readByte(); } /** * Reads a unsigned 32-bit long from the saved game data and * advances the position in the file by two byte * @return {number} Read value */ readInt32() { return this.readInt16() + 0x10000 * this.readInt16(); } /** * Reads a BSTR from the saved game data and advances the * position in the file to just past the end of the string * @return {string} Read value */ readString() { var strLen = this.readInt32(); if (strLen > 4096) throw new Error("Found a string longer than 4K"); var string = ""; for (var i = 0; i < strLen; i++) { string += String.fromCharCode(this.readInt16()); } return string; } /** * Advances the position in the file by the specified number of bytes * @param {number} count - Bytes to skip */ skipBytes(count) { this.position += count; } /** * Checks for the end of the file * @return {boolean} True if EOF, otherwise false */ eof() { return this.position >= this.decompressed.byteLength; } /** * Compresses the data and presents the user with the save dialog */ export() { // GZip up the data var compressed = pako.gzip(this.decompressed); // Export it var blob = new Blob([compressed]); if (window.navigator.msSaveOrOpenBlob) window.navigator.msSaveBlob(blob, this.zipFilename); else { var a = window.document.createElement("a"); a.href = window.URL.createObjectURL(blob, { type: "application/octet-stream" }); a.download = this.zipFilename; document.body.appendChild(a); a.click(); document.body.removeChild(a); } } /** * Gets the bytes associated with the specific file in the saved game data * @param {string} filename - The name of the file (player.dat, city_1.dat, etc) * @return {Uint8Array} File contents (as bytes) */ getBytes(filename) { var file = this.index[filename]; if (file == null) throw new Error("File '" + filename + "' not found in index"); // Should never happen return this.decompressed.slice(file.offset, file.offset + file.filesize); } /** * Returns a file from inside the save game as a JSON string * @param {string} filename - The name of the file (player.dat, city_1.dat, etc) * @return {string} File contents (as JSON string) */ getJsonString(filename) { return Utf8ToString(this.getBytes(filename)); } /** * Returns a file from inside the save game as a JSON object * @param {string} filename - The name of the file (player.dat, city_1.dat, etc) * @return {object} Data as a JSON object */ getJson(filename) { return JSON.parse(this.getJsonString(filename)); } /** * Maps then saved game name of a character to the name shown in the actual game UI * @param {string} name - Name as it appears in the saved game file * @returns {string} Name as it appears in the game UI */ mapCharacterName(name) { switch (name) { case "Wolfter": return "Dzhulbars"; case "Gexogen": return "Hexogen"; default: return name; } } /** * Updates (but does not export) a JSON file * @param {string} filename - The name of the file (player.dat, city_1.dat, etc) * @param {object} jsonObj - JSON object */ updateJson(filename, jsonObj) { Log(`'${filename}' has been updated, converting JSON to UTF8 byte array and updating in-memory copy of saved game.`); var jsonString = JSON.stringify(jsonObj); var jsonBytes = StringToUtf8(jsonString); var jsonByteLength = jsonBytes.length; var file = this.index[filename]; var buffer = new Uint8Array(this.decompressed.byteLength - file.filesize + jsonByteLength); buffer.set(this.decompressed.slice(0, file.offset - 4), 0); // Everything before the updated file buffer.set(this.writeUInt32(jsonByteLength), file.offset - 4); // Size of the updated file buffer.set(jsonBytes, file.offset); // The updated file buffer.set(this.decompressed.slice(file.offset + file.filesize), file.offset + jsonByteLength); // Everything after the updated file Log("Reinitializing saved game object..."); this.initialize(buffer); } /** * Writes a Uint32 name to a buffer * @param {number} unit32 - The value to be written * @return {Uint8Array} The generated buffer */ writeUInt32(uint32) { var temp = new Uint8Array(4); temp[0] = uint32 % 0x100; temp[1] = (uint32 >> 8) % 0x100; temp[2] = (uint32 >> 16) % 0x100; temp[3] = (uint32 >> 24) % 0x100; return temp; } /* Not currently used writeUnicode(str) { var len = str.length; var temp = new Uint8Array(len * 2); for (var i = 0; i < str.length; i++) { var charCode = str.charAt(i); temp[i * 2] = charCode % 0x100; temp[i * 2 + 1] = (charCode >> 8) % 0x100; } return temp; } */ }
JavaScript
class QueryForm extends Component { state = { keywords: '', selectedLocations: {}, selectAll: true, tweetsPerLocation: 50 } // calls to parent function to create a new query when the submit button is pressed submitQuery = (e) => { // prevents the default HTML action to redirect the user e.preventDefault() // create an array of the fullnames of the selected locations let locations = []; Object.keys(this.state.selectedLocations).forEach(k => { if (this.state.selectedLocations[k]) { locations.push(k) } }) // call parent function to pass up data to top level to create a query this.props.createQuery( this.state.keywords, this.state.tweetsPerLocation, locations ) } componentDidMount() { // insert into state a dict to track which locations are selected // by default they are all selected let selectedLocations = {}; allStates.forEach(state => { selectedLocations[state.fullname] = true }); this.setState({ selectedLocations: selectedLocations }) } render() { const totalLocations = Object.keys(this.state.selectedLocations).map(k => { return this.state.selectedLocations[k] }).reduce((total, value) => { return total + value }, 0) // create array of list items with a checkbox and location name for each US state // when one of the checkboxes are toggled, the location's value in the dictionary under the component's selectedLocations state is updated const locationInputs = allStates.map(state => <li> <LocationLabel> <LocationCheckbox type="checkbox" checked={this.state.selectedLocations[state.fullname]} onChange={() => { // toggle location's boolean value in state dict // create copy of selectedLocations let newSelectedLocations = this.state.selectedLocations // toggle value and update state newSelectedLocations[state.fullname] = !newSelectedLocations[state.fullname] this.setState({ selectedLocations: newSelectedLocations }) }} /> {state.fullname} </LocationLabel> </li> ) return ( <Container> <form onSubmit={this.submitQuery}> {/* text input field for keywords */} <InputLabel> Query <TextInput type="text" value={this.state.keywords} placeholder="Keywords" onChange={(e) => this.setState({ keywords: e.target.value })} required /> </InputLabel> {/* list of locations with checkboxes */} <InputLabel> Included locations <LocationLabel> <LocationCheckbox type="checkbox" checked={this.state.selectAll} onChange={() => { // create mutable instance of selectedLocations let selectedLocations = this.state.selectedLocations; // change every location to opposite of current selectAll boolean Object.keys(selectedLocations).forEach(k => { selectedLocations[k] = !this.state.selectAll; }) // update selectedLocations and toggle selectAll this.setState({ selectedLocations: selectedLocations, selectAll: !this.state.selectAll }) }} /> Select all </LocationLabel> <LocationSelection> <LocationSelectionList> {locationInputs} </LocationSelectionList> </LocationSelection> </InputLabel> {/* numerical or slider input for the number of tweets to be retrieved for every location */} <InputLabel> Tweets per location <RangeSlider type="range" min="1" max="100" step="1" value={this.state.tweetsPerLocation} onChange={e => this.setState({ tweetsPerLocation: e.target.value })} /> <NumberInput type="number" min="1" max="100" step="1" value={this.state.tweetsPerLocation} onChange={e => { this.setState({ tweetsPerLocation: e.target.value }) }} /> {/* provides an estimate of the total number of tweets given the selected locations and the number of tweets per location. This is provided because of the usage limits on the Twitter API so that it can be estimated how much API usage a query will consume */} <TotalTweetCount><i>Total tweets: {this.state.tweetsPerLocation * totalLocations}</i></TotalTweetCount> </InputLabel> <SubmitButton variant="btn btn-success" type="submit"> Submit </SubmitButton> </form> </Container> ); } }
JavaScript
class Mouse extends Input { /** * Create a Mouse object */ //TODO pass flag to disabledDefault on contextmenu constructor(eventTarget, camera, disableContextMenu = false) { super(eventTarget, "mousedown", "mouseup", "button"); this._x = 0; this._y = 0; this.camera = camera; // this will not call _onMouseMove directly eventTarget.addEventListener("mousemove", event => { this._onMouseMove(event); }); //TODO test this if (disableContextMenu) { eventTarget.addEventListener("contextmenu", event => { event.preventDefault(); }); } } /** * Gets the MouseButton cooresponding to this mouse event * @param {number} mouseButton - The button code for this mouse button */ getButton(buttonCode) { let button = this._pressables[buttonCode]; if (button) { return button; } button = new MouseButton(); this._pressables[buttonCode] = button; return button; } /** * @type {number} */ get x() { return this._x + this.camera.transform.position.absoluteX; } /** * @type {number} */ get y() { return this._y + this.camera.transform.position.absoluteY; } _onMouseMove(event) { const rect = this.camera._canvas.getBoundingClientRect(); this._x = event.clientX - Math.round(rect.left - 0.5) - this.camera._x; this._y = -(event.clientY - Math.round(rect.top - 0.5) - this.camera._y); } }
JavaScript
class FieldConfigurationItem { /** * Constructs a new <code>FieldConfigurationItem</code>. * A field within a field configuration. * @alias module:model/FieldConfigurationItem * @param id {String} The ID of the field within the field configuration. */ constructor(id) { FieldConfigurationItem.initialize(this, id); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj, id) { obj['id'] = id; } /** * Constructs a <code>FieldConfigurationItem</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/FieldConfigurationItem} obj Optional instance to populate. * @return {module:model/FieldConfigurationItem} The populated <code>FieldConfigurationItem</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new FieldConfigurationItem(); if (data.hasOwnProperty('description')) { obj['description'] = ApiClient.convertToType(data['description'], 'String'); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('isHidden')) { obj['isHidden'] = ApiClient.convertToType(data['isHidden'], 'Boolean'); } if (data.hasOwnProperty('isRequired')) { obj['isRequired'] = ApiClient.convertToType(data['isRequired'], 'Boolean'); } } return obj; } }
JavaScript
class GrpcCallMock extends EventEmitter { /** * @param {SinonSandbox} sinon * @param {Object} request */ constructor(sinon, request = {}) { super(); this.write = sinon.stub(); this.end = sinon.stub(); this.request = request; } }
JavaScript
class TextContentUpdater extends NodeUpdater { constructor(node, expression) { super(node); this.expression = expression; } update(data) { this.node.textContent = this.evaluate(this.expression, data); } }
JavaScript
class UpdaterCollection { constructor(updaters) { this.updaters = updaters; } update(data) { this.updaters.forEach(updater => { updater.update(data); }); } }
JavaScript
class UpdaterDescriptor { constructor (address, updaterClass, ...updaterArgs) { this.address = address; this.updaterClass = updaterClass; this.updaterArgs = updaterArgs; } createUpdater(root) { const node = nodeAtAddress(root, this.address); const updater = new this.updaterClass(node, ...this.updaterArgs); return updater; } }
JavaScript
class NanoBuffer { /** * Creates a `NanoBuffer` instance. * * @param {Number} [maxSize=10] - The initial buffer size. */ constructor(maxSize = 10) { if (typeof maxSize !== 'number') { throw new TypeError('Expected maxSize to be a number'); } if (isNaN(maxSize) || maxSize < 0) { throw new RangeError('Expected maxSize to be zero or greater'); } /** * The buffer where the values are stored. * @type {Array} * @access private */ this._buffer = Array(maxSize | 0); /** * The index of the newest value in the buffer. * @type {Number} * @access private */ this._head = 0; /** * The maximum number of values to store in the buffer. * @type {Number} * @access private */ this._maxSize = maxSize; /** * The number of values in the buffer. * @type {Number} * @access private */ this._size = 0; } /** * Returns the index of the newest value in the buffer. * * @returns {Number} * @access public */ get head() { return this._head; } /** * Returns the maximum number of values in the buffer. * * @returns {Number} * @access public */ get maxSize() { return this._maxSize; } /** * Changes the maximum number of values allowed in the buffer. * * @param {Number} newMaxSize - The new max size of the buffer. * @access public */ set maxSize(newMaxSize) { if (typeof newMaxSize !== 'number') { throw new TypeError('Expected new max size to be a number'); } if (isNaN(newMaxSize) || newMaxSize < 0) { throw new RangeError('Expected new max size to be zero or greater'); } if (newMaxSize === this._maxSize) { // nothing to do return; } // somewhat lazy, but we create a new buffer, then manually copy // ourselves into it, then steal back the internal values const tmp = new NanoBuffer(newMaxSize); for (const value of this) { tmp.push(value); } this._buffer = tmp._buffer; this._head = tmp._head; this._maxSize = tmp._maxSize; this._size = tmp._size; tmp._buffer = null; } /** * Returns the number of values in the buffer. * * @returns {Number} * @access public */ get size() { return this._size; } /** * Inserts a new value into the buffer. * * @param {*} value - The value to store. * @returns {NanoBuffer} * @access public */ push(value) { if (this._maxSize) { if (this._size > 0) { this._head++; } if (this._head >= this._maxSize) { // we wrapped this._head = 0; } this._size = Math.min(this._size + 1, this._maxSize); this._buffer[this._head] = value; } return this; } /** * Removes all values in the buffer. * * @returns {NanoBuffer} * @access public */ clear() { this._buffer = Array(this._maxSize); this._head = 0; this._size = 0; return this; } /** * Creates an iterator function for this buffer. * * @return {Function} * @access public */ [Symbol.iterator]() { let i = 0; return { next: () => { // just in case the size changed i = Math.min(i, this._maxSize); // calculate the index let j = this._head + i - (this._size - 1); if (j < 0) { j += this._maxSize; } // console.log('\ni=' + i + ' head=' + this._head + ' size=' + this._size + ' maxSize=' + this._maxSize + ' j=' + j); const done = i++ >= this._size; return { value: done ? undefined : this._buffer[j], done }; } }; } }
JavaScript
class SmartiProxy { static get smartiAuthToken() { return RocketChat.settings.get('Assistify_AI_Smarti_Auth_Token'); } static get smartiUrl() { return RocketChat.settings.get('Assistify_AI_Smarti_Base_URL'); } /** * Propagates requests to Smarti. * Make sure all requests to Smarti are using this function. * * @param {String} method - the HTTP method to use * @param {String} path - the path to call * @param {Object} [body=null] - the payload to pass (optional) * @param {Function} onError=null - custom error handler * * @returns {Object} */ static propagateToSmarti(method, path, body = null, onError = null) { const url = `${ SmartiProxy.smartiUrl }${ path }`; const header = { 'X-Auth-Token': SmartiProxy.smartiAuthToken, 'Content-Type': 'application/json; charset=utf-8' }; try { SystemLogger.debug('Sending request to Smarti', method, 'to', url, 'body', JSON.stringify(body)); const response = HTTP.call(method, url, {data: body, headers: header}); if (response.statusCode < 400) { return response.data || response.content; //.data if it's a json-response } else { SystemLogger.debug('Got unexpected result from Smarti', method, 'to', url, 'response', JSON.stringify(response)); } } catch (error) { if (error && onError) { const recoveryResult = onError(error); if (recoveryResult !== undefined) { return recoveryResult; } } SystemLogger.error('Could not complete', method, 'to', url, error.response); SystemLogger.debug(error); return {error}; } } }
JavaScript
class NamedNode extends Term { /** * @constructor * @param iri {String} * @param ln {String|undefined} The term, if applicable */ constructor (iri, ln = undefined) { super() this.termType = NamedNode.termType this.term = undefined if (iri && iri.termType === NamedNode.termType) { // param is a named node iri = iri.value } if (!iri) { throw new Error('Missing IRI for NamedNode') } if (!iri.includes(':')) { throw new Error('NamedNode IRI "' + iri + '" must be absolute.') } if (iri.includes(' ')) { var message = 'Error: NamedNode IRI "' + iri + '" must not contain unencoded spaces.' throw new Error(message) } const existing = NamedNode.nsMap[iri] if (existing) { return existing } this.value = iri NamedNode.mem(this, ln) } /** * Returns an $rdf node for the containing directory, ending in slash. */ dir () { var str = this.uri.split('#')[0] var p = str.slice(0, -1).lastIndexOf('/') var q = str.indexOf('//') if ((q >= 0 && p < q + 2) || p < 0) return null return NamedNode.find(str.slice(0, p + 1)) } /** * Returns an NN for the whole web site, ending in slash. * Contrast with the "origin" which does NOT have a trailing slash */ site () { var str = this.uri.split('#')[0] var p = str.indexOf('//') if (p < 0) throw new Error('This URI does not have a web site part (origin)') var q = str.indexOf('/', p+2) if (q < 0) throw new Error('This URI does not have a web site part. (origin)') return NamedNode.find(str.slice(0, q + 1)) } doc () { if (this.uri.indexOf('#') < 0) { return this } else { return NamedNode.find(this.uri.split('#')[0]) } } generateString () { return '<' + this.uri + '>' } /** * Legacy getter and setter alias, node.uri */ get uri () { return this.value } set uri (uri) { this.value = uri } /** * Retrieve or create a NamedNode by its IRI * @param iri {string} The IRI of the blank node * @param ln {string} Property accessor-friendly string representation. * @return {NamedNode} The resolved or created NamedNode */ static find(iri, ln = undefined) { if (iri && iri.termType) { iri = iri.value } const fromMap = Term.nsMap[iri] if (fromMap !== undefined) { return fromMap } return new NamedNode(iri, ln) } /** * Retrieve a NamedNode by its store index * @param sI {integer} The store index of the NamedNode * @return {NamedNode | undefined} */ static findByStoreIndex(sI) { const term = Term.termMap[sI] if (!term) { return undefined } if (term.termType === "NamedNode") { return term } return undefined } /** * Assigns an index number and adds a NamedNode instance to the indices * @private * @param nn {NamedNode} The NamedNode instance to register * @param ln? {string} Property accessor-friendly string representation. * @return {NamedNode} The updated NamedNode instance */ static mem(nn, ln) { if (nn.sI) { throw new Error(`NamedNode ${nn} already registered`) } nn.sI = ++Term.termIndex nn.term = ln Term.termMap[nn.sI] = Term.nsMap[nn.value] = nn return nn } static fromValue (value) { return NamedNode.find(value) } }
JavaScript
class SearchBar extends Component { constructor(props) { super(props); // whenever input changes (from typing) search term changes (and re-render) this.state = { term: ''}; } onInputChange(term) { // set state and call callback we got from App this.setState({term}); this.props.onSearchTermChange(term); } render () { // render must return jsx return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.onInputChange(event.target.value)} /> </div> ); } }
JavaScript
class ErrorBoundary extends React.Component { constructor(...args) { super(...args); this.state = { error: null, prevTrigger: null }; } static getDerivedStateFromError(error) { return { error }; } static getDerivedStateFromProps({ trigger }, { prevTrigger }) { const newTrigger = JSON.stringify({ trigger }); return prevTrigger !== newTrigger ? { error: null, prevTrigger: newTrigger } : null; } componentDidCatch(error) { const { doThrow, onError } = this.props; onError && onError(); if (doThrow) { throw error; } } render() { const { children, error: errorProps, t } = this.props; const { error } = this.state; const displayError = errorProps || error; return displayError ? /*#__PURE__*/_jsx("article", { className: "error extraMargin", children: t('Uncaught error. Something went wrong with the query and rendering of this component. {{message}}', { replace: { message: displayError.message } }) }) : children; } }
JavaScript
class Buttons extends Component { constructor(props) { super(props); this.state = { data: [], isConnectionOpen: true }; } componentDidMount() { sse.addEventListener("state", e =>{ var obj = JSON.parse(e.data); if(obj.id==="switch-button-r"&&obj.value===true){ this.setState({data:this.state.data.concat('r')}); }else if(obj.id==="switch-button-b"&&obj.value===true){ this.setState({data:this.state.data.concat('b')}); } }, true); // clearData(); // hasConnection(hasConnection => this.setState({ isConnectionOpen: hasConnection })); // handleBuzzer(data => { // if (this.state.isConnectionOpen) { // this.setState({ data }); // } // }); } render() { return ( <div className="buzzers"> <div className={!!this.state.data[0] ? `buzzer active ${this.state.data[0]}` : 'buzzer'}></div> <div className={!!this.state.data[1] ? `buzzer active ${this.state.data[1]}` : 'buzzer'}></div> <div className={!!this.state.data[2] ? `buzzer active ${this.state.data[2]}` : 'buzzer'}></div> <div className={!!this.state.data[3] ? `buzzer active ${this.state.data[3]}` : 'buzzer'}></div> <div className={!!this.state.data[4] ? `buzzer active ${this.state.data[4]}` : 'buzzer'}></div> <div className={!!this.state.data[5] ? `buzzer active ${this.state.data[5]}` : 'buzzer'}></div> </div> ); } }
JavaScript
class Modal extends Component { constructor(props) { super(props); this.state = {}; } onClose = () => { this.setState({ open: false }); setTimeout(() => this.setState({ open: undefined }), 1); }; render() { const { exit, children } = this.props; return ( <Layer position="right" full="vertical" modal onEsc={() => exit()} onClickOutside={() => exit()} > {children} </Layer> ); } }
JavaScript
class VirtualServerZenRTCPeerManager extends PhantomCollection { /** * Gets the unique key to identify a peer. * * @param {string} clientDeviceAddress * @param {string} clientSignalBrokerId * @return {string} */ static getPeerKey(clientDeviceAddress, clientSignalBrokerId) { return `${clientDeviceAddress}-${clientSignalBrokerId}`; } // TODO: Document constructor({ realmId, channelId, deviceAddress, socket, iceServers, sharedWritableSyncObject, }) { super(); this._realmId = realmId; this._channelId = channelId; this._deviceAddress = deviceAddress; this._socket = socket; this._iceServers = iceServers; this._sharedWritableSyncObject = sharedWritableSyncObject; } // TODO: Document addChild(virtualServerZenRTCPeer, clientDeviceAddress, clientSignalBrokerId) { if (!(virtualServerZenRTCPeer instanceof VirtualServerZenRTCPeer)) { throw new TypeError( "virtualServerZenRTCPeer is not a VirtualServerZenRTCPeer instance" ); } const peerKey = VirtualServerZenRTCPeerManager.getPeerKey( clientDeviceAddress, clientSignalBrokerId ); return super.addChild(virtualServerZenRTCPeer, peerKey); } /** * @param {string} clientSocketId * @param {string} clientDeviceAddress * @param {string} clientSignalBrokerId * @return {VirtualServerZenRTCPeer} */ getOrCreateZenRTCPeer( clientSocketId, clientDeviceAddress, clientSignalBrokerId ) { const existingPeer = this.getChildWithKey( VirtualServerZenRTCPeerManager.getPeerKey( clientDeviceAddress, clientSignalBrokerId ) ); if (existingPeer) { return existingPeer; } else { // Create peer const readOnlySyncObject = new SyncObject(); const virtualServerZenRTCPeer = new VirtualServerZenRTCPeer({ ourSocket: this._socket, iceServers: this._iceServers, realmId: this._realmId, channelId: this._channelId, clientSocketId, clientSignalBrokerId, // zenRTCSignalBrokerId: zenRTCSignalBrokerId, // NOTE: The writable is shared between all of the participants and // does not represent a single participant (it symbolized all of them) writableSyncObject: this._sharedWritableSyncObject, readOnlySyncObject, }); // Destruct read-only sync object when peer is destructed virtualServerZenRTCPeer.registerCleanupHandler(() => { readOnlySyncObject.destroy(); }); virtualServerZenRTCPeer.on(EVT_CONNECTED, () => { this.emit(EVT_PEER_CONNECTED, virtualServerZenRTCPeer); }); // IMPORTANT: Listening to readOnlySyncObject, not the peer, here readOnlySyncObject.on(EVT_UPDATED, updatedState => { this.emit(EVT_PEER_SHARED_STATE_UPDATED, [ virtualServerZenRTCPeer, updatedState, ]); }); virtualServerZenRTCPeer.on( EVT_OUTGOING_MEDIA_STREAM_TRACK_ADDED, mediaStreamTrack => { this.emit(EVT_PEER_OUTGOING_MEDIA_STREAM_TRACK_ADDED, [ virtualServerZenRTCPeer, mediaStreamTrack, ]); } ); virtualServerZenRTCPeer.on( EVT_OUTGOING_MEDIA_STREAM_TRACK_REMOVED, mediaStreamTrack => { this.emit(EVT_PEER_OUTGOING_MEDIA_STREAM_TRACK_REMOVED, [ virtualServerZenRTCPeer, mediaStreamTrack, ]); } ); virtualServerZenRTCPeer.on( EVT_INCOMING_MEDIA_STREAM_TRACK_ADDED, mediaStreamTrack => { this.emit(EVT_PEER_INCOMING_MEDIA_STREAM_TRACK_ADDED, [ virtualServerZenRTCPeer, mediaStreamTrack, ]); } ); virtualServerZenRTCPeer.on( EVT_INCOMING_MEDIA_STREAM_TRACK_REMOVED, mediaStreamTrack => { this.emit(EVT_PEER_INCOMING_MEDIA_STREAM_TRACK_REMOVED, [ virtualServerZenRTCPeer, mediaStreamTrack, ]); } ); virtualServerZenRTCPeer.on(EVT_DISCONNECTED, () => { this.emit(EVT_PEER_DISCONNECTED, virtualServerZenRTCPeer); }); virtualServerZenRTCPeer.on(EVT_DESTROYED, () => { this.emit(EVT_PEER_DESTROYED, virtualServerZenRTCPeer); }); // Register the peer in the collection // NOTE: This child will be destructed once the collection is this.addChild( virtualServerZenRTCPeer, clientDeviceAddress, clientSignalBrokerId ); // Automatically connect virtualServerZenRTCPeer.connect(); return virtualServerZenRTCPeer; } } /** * @return {VirtualServerZenRTCPeer[]} */ getConnectedZenRTCPeers() { return this.getChildren().filter(zenRTCPeer => zenRTCPeer.getIsConnected()); } /** * @return {Promise<void>} */ async destroy() { return super.destroy(async () => { await this.destroyAllChildren(); }); } }
JavaScript
class VerifiableSocialShareRule extends SocialShareRule { constructor(crules, levelId, config) { super(crules, levelId, config) // Compute the hashes for the post content, in all the configured languages. this.contentHashes = [this._hashContent(this.content.post.tweet.default)] for (const translation of this.content.post.tweet.translations) { this.contentHashes.push(this._hashContent(translation.text)) } } /** * Hashes content for verification of the user's post. * * Important: Make sure to keep this hash function in sync with * the one used in the bridge server. * See infra/bridge/src/utils/webhook-helpers.js * * @param text * @returns {string} Hash of the text, hexadecimal encoded. * @private */ _hashContent(text) { return crypto .createHash('md5') .update(text) .digest('hex') } /** * Returns true if the event's content hash (stored in customId) belongs to the * set of hashes configured in the rule. * @param {string} customId: hashed content of the post. * @returns {boolean} */ customIdFilter(customId) { return this.contentHashes.includes(customId) } }
JavaScript
class ViewBase extends require('Common/Entity/View/ViewBase') { /** * Constructor */ constructor(params) { super(params); this.init(); } /** * Initialise */ async init() { this.element = this.getPlaceholder(this.scope(), this.model || {}, this.state || {}); await this.update(); this.trigger('ready'); } /** * Structure */ structure() { super.structure(); this.def(HTMLElement, 'element', null); this.def(Object, 'events', {}); this.def(Object, 'partials', {}); this.def(Object, 'namedElements', {}); this.def(Boolean, 'isUpdating', false); } /** * Gets the placeholder element * * @return {HTMLElement} Placeholder */ getPlaceholder() { let element = document.createElement('div'); element.className = 'placeholder'; return element; } /** * Checks if this view is visible in the DOM * * @return {Boolean} Is valid */ isValid() { return !!this.element && !!this.element.parentElement; } /** * Adds an event handler to this view * * @param {String} type * @param {Function} handler */ on(type, handler) { checkParam(type, 'type', String, true); checkParam(handler, 'handler', Function, true); if(!this.events) { this.events = {} } if(!this.events[type]) { this.events[type] = []; } this.events[type].push(handler); return this; } /** * Triggers an event * * @param {String} type * @param {Array} params */ trigger(type, ...params) { checkParam(type, 'type', String, true); if(!this.events || !this.events[type]) { return; } try { for(let handler of this.events[type]) { handler.call(this, ...params); } } catch(e) { this.setErrorState(e); } } /** * Sets the view state * * @param {String} name * @param {Object} properties */ setState(name, properties = null) { if(properties) { this.state = properties; } this.state.name = name; this.render(); } /** * Sets the view state as an error * * @param {Error} error */ setErrorState(error) { this.state.name = 'error'; this.state.message = error.message; debug.error(error, this.constructor, true); this.render(); } /** * Gets a widget constructor by an alias * * @param {String} alias * * @return {HashBrown.Entity.View.Widget.WidgetBase} Widget */ getWidget(alias) { for(let name in HashBrown.Entity.View.Widget) { if(name.toLowerCase() === alias) { return HashBrown.Entity.View.Widget[name]; } } return null; } /** * Renders a partial * * @param {String} name * * @return {HTMLElement} Render result */ renderPartial(name) { checkParam(name, 'name', String); if(!this.partials[name]) { return null; } let element = this.partials[name].render(this.scope(), this.model, this.state); this.partials[name].element.parentElement.replaceChild(element, this.partials[name].element); this.partials[name].element = element; return element; } /** * Scope * * @return {Object} Scope */ scope() { return new Proxy({}, { get: (target, name, receiver) => { // Return any valid function starting with "on", like "onClick", "onChange", etc. // We are only including event handlers in the scope, because we want to minimise the use of logic in templates if(name.substring(0, 2) === 'on' && typeof this[name] === 'function') { return (...args) => { try { this[name].call(this, ...args); } catch(e) { this.setErrorState(e); } }; } // Look up recognised names switch(name) { // A simple conditional case 'if': return(statement, ...content) => { if(!statement) { return null; } return content; }; // Loop an array or object case 'each': return (items, callback) => { let content = []; for(let key in items) { let value = items[key]; if(!isNaN(key)) { key = parseFloat(key); } content.push(callback(key, value)); } return content; }; // Recurse through an array case 'recurse': return (items, key, callback) => { if(!items || !Array.isArray(items)) { return []; } let content = []; for(let i in items) { let item = items[i]; if(!item) { continue; } let children = this.scope().recurse(item[key], key, callback); let element = callback(i, item, children); content.push(element); } return content; }; // Render HTML case 'html': return (html) => { let wrapper = document.createElement('div'); wrapper.innerHTML = html; return Array.from(wrapper.childNodes); }; // Render an included template case 'include': return (template, model) => { if(typeof template !== 'function') { return ''; } return template(this.scope(), model || this.model, this.state); }; // Register a partial case 'partial': return (partialName, renderFunction) => { if(typeof renderFunction !== 'function') { return null; } let content = renderFunction(this.scope(), this.model, this.state); this.partials[partialName] = { render: renderFunction, element: content } return content; }; // Render a field case 'field': return (model, ...content) => { return require('template/field/fieldBase')( this.scope(), model, { editorTemplate: (_, model, state) => { return content; }, } ); }; // Any unrecognised key will be interpreted as an element constructor // This means that, for instance, calling "_.div" will return a <div> HTMLElement default: // First check if we have a custom widget matching the key let widget = this.getWidget(name); if(widget) { return (attributes = {}) => { let child = new widget({model: attributes}); if(attributes && attributes.name) { this.namedElements[attributes.name] = child; } return child.element; }; } // If not, render a native element return (attributes = {}, ...content) => { let element = this.createElement(name, attributes, content); if(attributes && attributes.name) { this.namedElements[attributes.name] = element; } return element; } } } }); } /** * Appends content to an element * * @param {HTMLElement} element * @param {Array} content */ appendToElement(element, content) { if(!content) { return; } if(content.constructor === Array) { for(let item of content) { this.appendToElement(element, item); } } else { if(content && content.element instanceof Node) { content = content.element; } else if(content && content[0] && content[0] instanceof Node) { content = content[0]; } else if(typeof content === 'function') { content = content(); } element.append(content); } } /** * Renders an element * * @param {String} type * @param {Object} attributes * @param {Array} content * * @return {HTMLElement} Element */ createElement(type, ...params) { let element = document.createElement(type); let attributes = {}; let content = []; // The first parameter could be a collection of attributes if(params && params[0] && params[0].constructor === Object) { attributes = params.shift(); } // The remaining parameters are content content = params; // Adopt all attributes for(let key in attributes) { let value = attributes[key]; if(value === null || value === undefined || value === false) { continue; } if(typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') { element.setAttribute(key, value); } else { element[key] = value; } } // Append all content this.appendToElement(element, content); return element; } /** * Fetches the model */ async fetch() {} /** * Resets the view */ async reset() { this.state = {}; await this.update(); } /** * Updates the view */ async update() { if(this.isUpdating) { return; } this.isUpdating = true; try { await this.fetch(); } catch(e) { this.setErrorState(e); } finally { this.render(); this.isUpdating = false; } } /** * Removes this element */ remove() { if(!this.isValid()) { return; } this.element.parentElement.removeChild(this.element); } /** * Runs before rendering */ prerender() {} /** * Runs after rendering */ postrender() {} /** * Renders the template * * @return {HTMLElement} Element */ render() { this.prerender(); let output = super.render(); let element = null; if(output instanceof Node) { element = output; } else if(typeof output === 'string') { let wrapper = document.createElement('div'); wrapper.innerHTML = output; element = wrapper.firstElementChild; } if(this.isValid() && element) { this.element.parentElement.replaceChild(element, this.element); } this.element = element; this.postrender(); return this.element; } }
JavaScript
class KeyboardEvent { constructor(keyboard, event) { if (event) { this.key = event.keyCode; this.element = event.target; this.event = event; } else { this.key = null; this.element = null; this.event = null; } } }
JavaScript
class Engineer extends Employee { // constructor adds 'gitHub' to employee properties' constructor(id, name, email, gitHub) { super(id, name, email); this.gitHub = gitHub; } // method getRole() overwrites 'Employee' and returns 'Engineer' getRole() { return "Engineer"; } // method getGithub() returns user's github profile name getGithub() { return this.gitHub; } // method getColor() returns color-code for role type (info = engineer) getColor() { return "info"; } }
JavaScript
class MapTouchZoomHandler extends Handler { addHooks() { addDomEvent(this.target._containerDOM, 'touchstart', this._onTouchStart, this); } removeHooks() { removeDomEvent(this.target._containerDOM, 'touchstart', this._onTouchStart); } _onTouchStart(event) { const map = this.target; if (!event.touches || event.touches.length !== 2 || map.isZooming()) { return; } const container = map._containerDOM; const p1 = getEventContainerPoint(event.touches[0], container), p2 = getEventContainerPoint(event.touches[1], container); this._startDist = p1.distanceTo(p2); this._startZoom = map.getZoom(); const size = map.getSize(); this._Origin = new Point(size['width'] / 2, size['height'] / 2); addDomEvent(document, 'touchmove', this._onTouchMove, this); addDomEvent(document, 'touchend', this._onTouchEnd, this); preventDefault(event); map.onZoomStart(null, this._Origin); /** * touchzoomstart event * @event Map#touchzoomstart * @type {Object} * @property {String} type - touchzoomstart * @property {Map} target - the map fires event * @property {Number} from - zoom level zooming from */ map._fireEvent('touchzoomstart', { 'from' : this._startZoom }); } _onTouchMove(event) { const map = this.target; if (!event.touches || event.touches.length !== 2 || !map.isZooming()) { return; } const container = map._containerDOM, p1 = getEventContainerPoint(event.touches[0], container), p2 = getEventContainerPoint(event.touches[1], container), scale = p1.distanceTo(p2) / this._startDist; this._scale = scale; const res = map._getResolution(this._startZoom) / scale; const zoom = map.getZoomFromRes(res); map.onZooming(zoom, this._Origin); /** * touchzooming event * @event Map#touchzooming * @type {Object} * @property {String} type - touchzooming * @property {Map} target - the map fires event */ map._fireEvent('touchzooming'); } _onTouchEnd() { const map = this.target; if (!map._zooming) { map._zooming = false; return; } map._zooming = false; off(document, 'touchmove', this._onTouchMove, this); off(document, 'touchend', this._onTouchEnd, this); const scale = this._scale; const res = map._getResolution(this._startZoom) / scale; const zoom = map.getZoomFromRes(res); map.onZoomEnd(zoom, this._Origin); /** * touchzoomend event * @event Map#touchzoomend * @type {Object} * @property {String} type - touchzoomend * @property {Map} target - the map fires event */ map._fireEvent('touchzoomend'); } }
JavaScript
class CertificatesSearchBuilder extends SearchBuilder { /** * @param {!InternalOpenGateAPI} parent - Instance of our InternalOpenGateAPI */ constructor(parent) { super(parent, {}, new FieldFinder(parent, BASE_URL)); this._url = BASE_URL; this._fetch = false; this._assignable = false; } /** * The search result will have all certificates which can be assignable to some device * ogapi.certificatesSearchBuilder().assignable() * @return {CertificatesSearchBuilder} */ assignable() { this._assignable = true; return this; } /** * The search result will have all certificates which can be administered by the user * @example * ogapi.certificatesSearchBuilder().administrable() * @return {CertificatesSearchBuilder} **/ administrable() { this._assignable = false; return this; } /** * Set fecth value * @example * ogapi.certificatesSearchBuilder().withFetch(true) * @param {!flag} flag * @throws {Error} throw error when flag is not a number * @return {CertificatesSearchBuilder} */ withFetch(flag) { if (flag === true || flag === false) { this._fetch = flag; } else { throw new Error('Flag fecth incorrect'); } return this; } _buildUrl() { let url = this._url; if (this._fetch === true) { this._urlParams.fetch = 1; } if (this._assignable === true) { this._urlParams.visibility = 'assignable'; } return url; } }
JavaScript
class UtilRoutes extends BaseRoute { coverage() { return { path: '/coverage/{param*}', method: 'GET', config: { auth: false, }, handler: { directory: { path: join(__dirname, '../../coverage'), redirectToSlash: true, index: true, }, }, } } }
JavaScript
class Card extends Component { constructor(props, defaultProps) { super(props, defaultProps) this.state = { cardForm: { deviceId: 2, deviceType: Platform.OS, }, cvc: '•••', expiry: '••/••', name: 'YOUR NAME', number: '•••• •••• •••• ••••', } } /** * @method focusNextField * @param nextField * @description focuses on the next text input field onSubmitEditing * @note borrowed from ~/routes/auth/signup/components/signup.js * @todo scope into standalone module with handleValueChanged */ focusNextField(nextField) { this.refs[nextField].focus() } // /** * @method handleValueChanged * @param values * @description onChange form object builder * @note borrowed from ~/routes/auth/signup/components/signup.js * @todo scope into standalone module with focusNextField */ handleValueChange(values) { this.setState({ cardForm: values }) } componentWillMount(props) { // Set all the things we want rendered on FIRST load } componentWillReceiveProps(nextProps) { // Compare incoming props to current props or state, and deciding what to render based on that comparison } focusNextField(nextField) { this.refs[nextField].focus(); } render() { /** * @const * @description two-way data binding text input values to this.state.form * @note borrowed from ~/routes/auth/signup/components/signup.js */ const { cvc, expiry, name, number, } = this.state.cardForm return ( <View style={styles.container}> <FlipCard clickable={true} flip={false} flipHorizontal={true} flipVertical={false} friction={6} onFlipped={(isFlipped)=>{console.log('isFlipped', isFlipped)}} perspective={1000} style={styles.cardContainer} > <View style={styles.cardFront}> <Image style={styles.float__cardChip} /> <Image source={{uri: cardBackgroundImages.visa}} style={styles.float__cardImageLogo} /> <Text style={styles.float__number}>{this.state.number.split(' ').map((number) => number).join(' ')}</Text> <Text style={styles.float__name}>{this.state.name.split(' ').map((name) => name).join(' ')}</Text> <Text style={styles.float__expiry}>{this.state.expiry.split(' ').map((expiry) => expiry).join(' ')}</Text> </View> <View style={styles.cardBack}> <View style={styles.barAbove} /> <View style={styles.barBelow} /> <Text style={styles.float__cvc}>{this.state.cvc.split(' ').map((cvc) => cvc).join(' ')}</Text> </View> </FlipCard> <View style={styles.formContainer}> <GiftedForm clearOnClose={true} formName='cardForm' onValueChange={this.handleValueChange.bind(this)} scrollEnabled={false} style={{ backgroundColor: 'transparent' }} > <GiftedForm.TextInputWidget autoCorrect={false} clearButtonMode='while-editing' clearTextOnFocus={true} defaultValue={this.props.number} keyboardType='numeric' name='number' onChangeText={(number) => this.setState({number})} onSubmitEditing={() => this.focusNextField('2')} placeholder={this.props.number.toString()} ref='1' returnKeyType='next' style={styles.textInputFull} value={number} /> <GiftedForm.TextInputWidget clearTextOnFocus={true} defaultValue={this.props.name} keyboardType='default' onChangeText={(name) => this.setState({name})} onSubmitEditing={() => this.focusNextField('3')} placeholder={this.props.name.toString()} ref='2' style={styles.textInputFull} value={name} /> <View style={styles.row}> <GiftedForm.TextInputWidget clearTextOnFocus={true} defaultValue={this.props.expiry} keyboardType='numeric' onChangeText={(expiry) => this.setState({expiry})} onSubmitEditing={() => this.focusNextField('4')} placeholder={this.props.expiry} ref='3' style={styles.textInputHalf} value={expiry} /> <GiftedForm.TextInputWidget clearTextOnFocus={true} defaultValue={this.props.cvc} keyboardType='numeric' onChangeText={(cvc) => this.setState({cvc})} placeholder={this.props.cvc} ref='4' style={styles.textInputHalf} value={cvc} /> </View> </GiftedForm> </View> </View> ) } }
JavaScript
class Control extends HTMLElement { constructor() { super(); this.value = ''; this.text = ''; } }
JavaScript
class MasonryGallery { // Define constructor function for instantiation constructor(options) { this.options = options; // A calculation we'll do often is the percentage of a grid cell in CSS // We'll do it once and save it here this._baseGridXPercentage = 100 / this.options.baseGridX; this._baseGridYPercentage = 100 / this.options.baseGridY; // We'll also save how tall the maximum number of grid rows should be drawn on the Y axis this._maxGridY = this.options.baseGridY * this.options.gridRepeatCount; // We'll cut the height of the viewport at wherever the lowest item on the Y axis is this._lowestGridY = null; // Keep track of what current grid we are iterating through this._currentGridX = 0; this._currentGridY = 0; // When we've rendered all of the images, we'll mark this as true this._gridComplete = false; // Generate the gallery and save the gallery element this.el = this.generateGalleryElement(); // Set the width & height of the gallery container this.el.style.width = (this._currentGridX / this.options.baseGridX) * 100 + 'vw'; this.el.style.height = (this._lowestGridY / this.options.baseGridY) * 100 + 'vh'; // Bind events on the Gallery element this._bindEvents(); } // Define a function for generating the gallery items generateGalleryElement() { // Create a container element for the gallery items var container = document.createElement('div'); container.classList.add('masonry-gallery'); // Iterate through the number of image elements that need to be created and generate them var i, imagesData = this.options.imagesData, imagePathsCount = imagesData.length - 1, imageIdx = 0, imageData, imagePositionData; while(!this._gridComplete) { imageData = imagesData[imageIdx]; // Get information about where the image should be positioned imagePositionData = this._getImagePositionData(imageData.type); // Get a new image element and append it to the container container.appendChild(this._generateImageElementContainer(imageData, imagePositionData, imageIdx)); // Update the grid offests for the next run this._updateGridOffsets(imagePositionData); // Set the next available image index if (imagePathsCount > imageIdx) { imageIdx++; } else { imageIdx = 0; } } return container; } // Method for generating an image container element from imageData _generateImageElementContainer(imageData, imagePositionData, imageIdx) { // Create a container for the element var imageContainer = document.createElement('div'); imageContainer.classList.add('gallery-image-container'); imageContainer.classList.add(imageData.type); // Create an inner-container that will handle scaling the image and UI beyond the current wrapper var innerContainer = document.createElement('div'); innerContainer.classList.add('gallery-image-inner-container'); // Create a container for 'liked' states var likedUiContainer = document.createElement('div'); likedUiContainer.classList.add('gallery-image-liked-ui'); // Create an image element for the container var image = document.createElement('img'); image.src = imageData.src; image.classList.add('gallery-image'); // Create a UI element for the container we'll use for hover states var uiContainer = document.createElement('div'); uiContainer.classList.add('gallery-image-ui'); // Save the image's index as a data attribute here uiContainer.setAttribute('data-image-index', imageIdx); // Apply styles to the imageContainer for its absolute positioning imageContainer.style.top = imagePositionData.top + 'vh'; imageContainer.style.left = imagePositionData.left + 'vw'; imageContainer.style.width = imagePositionData.width + 'vw'; imageContainer.style.height = imagePositionData.height + 'vh'; // Append the liked UI container to the ui container uiContainer.appendChild(likedUiContainer); // Append the UI element to the image container innerContainer.appendChild(uiContainer); // Append the image to the image container innerContainer.appendChild(image); // Append the innerContainer to the imageContainer imageContainer.appendChild(innerContainer); // Return the container return imageContainer; } _getImagePositionData(imageType) { // Get information about the masonry grid var baseGridX = this.options.baseGridX, baseGridY = this.options.baseGridY, baseGridXPercentage = this._baseGridXPercentage, baseGridYPercentage = this._baseGridYPercentage, startGridX = this._currentGridX, startGridY = this._currentGridY, left = startGridX * baseGridXPercentage, top = startGridY * baseGridYPercentage, width = baseGridXPercentage, endGridX = startGridX + 1, height, endGridY; /* * For this demo, we're assuming that tall images are twice as tall as wide ones, * and that wide images are twice as wide as tall ones! * */ // Switch the offset values depending on the imageType switch(imageType) { case 'wide': height = baseGridYPercentage; endGridY = startGridY + 1; break; case 'tall': height = baseGridYPercentage * 2; endGridY = startGridY + 2; break; } return { top : top, left : left, width : width, height : height, startGridX : startGridX, startGridY : startGridY, endGridX : endGridX, endGridY : endGridY }; } // Update the grid offsets so image generators put the images in the correct places _updateGridOffsets(imagePositionData) { var newCurrentGridX = imagePositionData.startGridX, newCurrentGridY = imagePositionData.endGridY; if (newCurrentGridY >= this._maxGridY) { // Save this value, it will be used to add a "bottom" to the page overflow if (this._lowestGridY === null || newCurrentGridY < this._lowestGridY) { this._lowestGridY = newCurrentGridY; } newCurrentGridY = 0; newCurrentGridX++; // If we've filled the amount of columns we want to fill, stop drawing if (newCurrentGridX >= this.options.baseGridX) { this._gridComplete = true; } } this._currentGridX = newCurrentGridX; this._currentGridY = newCurrentGridY; } // Bind DOM events on the gallery _bindEvents() { // When the gallery has a click event bubble up, bind to it this.el.addEventListener('click', this._triggerImageSelectedEvent.bind(this)); } // Trigger custom events for selecting a specific image _triggerImageSelectedEvent(e) { // If the target is one, throw a custom event that returns the image src index of the element var customEvent = new CustomEvent('image-selected', { detail : { index : this.getElementImageIndex( e.target ) } }); // Dispatch the event on this.el this.el.dispatchEvent(customEvent); } getElementImageIndex(targetElement) { return parseInt(targetElement.getAttribute('data-image-index'), 10); } getImageContainerFromUIElement(uiElement) { return uiElement.parentNode.parentNode; } }
JavaScript
class RuleContext { /** * Creates an instance of the rule context with the engine, the rule and its path. * * @param {InfernalEngine} engine The parent InfernalEngine * @param {Function} rule The rule to execute. * @param {String} path The path of the rule. */ constructor(engine, rule, path) { this.engine = engine; this.rule = rule; this.path = path; this.facts = []; } /** * Execute the rule within its context returning the * resulting object to its contextualized facts. */ async execute() { let params = []; this.facts.forEach(inputFact => { params.push(this.engine._facts.get(inputFact)); }); if(this.engine._trace) { this.engine._trace({ action: "execute", rule: path, inputs: params }); } let result = await this.rule.apply(null, params); if (!result) { return; } let context = infernalUtils.getContext(this.path); for (let key in result) { if (!result.hasOwnProperty(key)) continue; if (!key.startsWith("#")) { let path = key.startsWith("/") ? key : context + key; let value = result[key]; let valueType = infernalUtils.typeof(value); if (valueType === "object") { await this.engine.import(value, path); } else if (valueType === "function") { await this.engine.defRule(path, value); } else { await this.engine.assert(path, value); } continue; } let action = result[key]; switch (key) { case "#assert": await this.engine.assert(action.path, action.value); break; case "#retract": await this.engine.retract(action.path); break; case "#def": case "#defRule": await this.engine.def(action.path, action.value); break; case "#undef": case "#undefRule": await this.engine.undef(action.path); break; case "#import": await this.engine.import(action.value, action.path); break; default: throw new Error(`Invalid action: '${key}'.`); } } } }
JavaScript
class WatcherHandler { constructor(server, client, config) { this.server = server; this.config = !config ? getConfiguration(server) : config; this.log = new Log(this.config.app_name, this.server, 'watcher_handler'); this.client = !client ? getElasticsearchClient({server, config: this.config}) : client; this.siren = isKibi(server); this.kable = new KableClient(server); this.timelion = new TimelionClient(server); } /** * Execute actions * * @param {object} payload data from Elasticsearch * @param {object} server of Kibana * @param {object} actions of watcher * @parms {object} task watcher */ doActions(payload, server, actions, task) { actionFactory(server, actions, payload, task); } /** * Get user from user index */ async getUser(watcherId) { if (watcherId.includes(this.config.es.watcher_type)) { watcherId = watcherId.split(':')[1]; } try { return await this.client.get({ index: this.config.es.default_index, type: this.config.es.default_type, id: this.config.es.user_type + ':' + watcherId, }); } catch (err) { throw new Error('get user: ' + err.toString()); } } /** * Count watchers * * @return {object} count data */ async getCount() { const request = { index: this.config.es.default_index, type: this.config.es.default_type, body: { query: { exists: { field: this.config.es.watcher_type } } } }; try { return await this.client.count(request); } catch (err) { throw new Error('count watchers: ' + err.toString()); } } /** * Get watchers * * @param {number} count - number of watchers to get * @return {object} watchers all data */ async getWatchers(count) { const request = { index: this.config.es.default_index, type: this.config.es.default_type, size: count, body: { query: { exists: { field: this.config.es.watcher_type } } } }; try { return await this.search(request); } catch (err) { throw new Error('get watchers: ' + err.toString()); } } /** * Search * * @param {object} request query * @param {string} method name * @return {object} data from ES */ async search(request, method = 'search') { try { return await this.client[method](request); } catch (err) { throw new Error('input search: ' + err.toString()); } } /** * Get all watcher actions * * @param {object} actions * @return {object} actions in normalized form */ getActions(actions) { const filteredActions = {}; forEach(actions, (settings, name) => { filteredActions[name] = settings; }); return filteredActions; } /** * Execute condition * * @param {object} payload data from Elasticsearch * @param {object} condition * @param {boolean} isAnomaly * @param {boolean} isRange * @return {object} null or warning message */ _executeCondition(payload, condition, isAnomaly = false, isRange = false) { this.log.debug(`condition: ${JSON.stringify(condition, null, 2)}`); if (condition.never) { throw new Error('warning, action execution is disabled'); } // script if (has(condition, 'script.script')) { try { if (!eval(condition.script.script)) { // eslint-disable-line no-eval return new WarningAndLog(this.log, 'no data satisfy "script" condition'); } } catch (err) { throw new Error('apply condition "script": ' + err.toString()); } } // compare if (condition.compare) { try { if (!compare.valid(payload, condition)) { return new WarningAndLog(this.log, 'no data satisfy "compare" condition'); } } catch (err) { throw new Error('apply condition "compare": ' + err.toString()); } } // compare array if (condition.array_compare) { try { if (!compareArray.valid(payload, condition)) { return new WarningAndLog(this.log, 'no data satisfy "array compare" condition'); } } catch (err) { throw new Error('apply condition "array compare": ' + err.toString()); } } // find anomalies if (isAnomaly) { try { payload = anomaly.check(payload, condition); } catch (err) { throw new Error('apply condition "anomaly": ' + err.toString()); } } // find hits outside range if (isRange) { try { payload = range.check(payload, condition); } catch (err) { throw new Error('apply condition "range": ' + err.toString()); } } return new SuccessAndLog(this.log, 'successfully applied condition', { payload }); } /** * Execute transform * * @param {object} payload data from Elasticsearch * @param {object} transform * @param {string} ES search method name * @return {object} null or warning message */ async _executeTransform(payload, transform, method) { this.log.debug(`transform: ${JSON.stringify(transform, null, 2)}`); const bulkTransform = async (link) => { // validate JS script in transform if (has(link, 'script.script')) { try { // transform global payload eval(link.script.script); // eslint-disable-line no-eval } catch (err) { throw new Error('apply transform "script": ' + err.toString()); } } // search in transform if (has(link, 'search.request')) { try { payload = await this.search(link.search.request, method); } catch (err) { throw new Error('apply transform "search": ' + err.toString()); } } return null; }; if (transform && transform.chain && size(transform.chain)) { // transform chain return Promise.each(transform.chain, (link) => bulkTransform(link)).then(() => { if (!payload || !size(payload)) { return new WarningAndLog(this.log, 'no data was found after "chain" transform was applied'); } return new SuccessAndLog(this.log, 'successfully applied "chain" transform', { payload }); }).catch((err) => { throw new Error('apply transform "chain": ' + err.toString()); }); } else if (transform && size(transform)) { // transform try { await bulkTransform(transform); if (!payload || !size(payload)) { return new WarningAndLog(this.log, 'no data was found after transform was applied'); } return new SuccessAndLog(this.log, 'successfully applied transform', { payload }); } catch (err) { throw new Error('apply transform: ' + err.toString()); } } return new SuccessAndLog(this.log, 'no transform found'); } /** * Execute watcher * * @param {object} task watcher * @param {string} ES search method name * @param {object} ES search request or kable * @param {object} condition of watcher * @param {object} transform of watcher * @param {object} actions of watcher * @return {object} success or warning message */ async _execute(task, method, search, condition, transform, actions) { const isAnomaly = has(task._source, 'sentinl.condition.anomaly') ? true : false; const isRange = has(task._source, 'sentinl.condition.range') ? true : false; let payload; if (search.timelion) { try { payload = await this.timelion.run(search.timelion); } catch (err) { throw new Error('timelion payload: ' + err.toString()); } } else if (search.kable) { try { payload = await this.kable.run(search.kable); } catch (err) { throw new Error('get kable payload: ' + err.toString()); } } else if (search.request) { try { payload = await this.search(search.request, method); // data from Elasticsearch } catch (err) { throw new Error('get payload: ' + err.toString()); } } else { throw new Error('unknown input: ' + JSON.stringify(search)); } try { const resp = this._executeCondition(payload, condition, isAnomaly, isRange); if (resp && resp.warning) { return resp; // payload is empty, do not execute actions } if (resp.payload) { payload = resp.payload; } } catch (err) { throw new Error('exec condition: ' + err.toString()); } try { const resp = await this._executeTransform(payload, transform, method); if (resp && resp.warning) { return resp; // payload is empty, do not execute actions } if (resp.payload) { payload = resp.payload; } } catch (err) { throw new Error('exec transform: ' + err.toString()); } this.doActions(payload, this.server, actions, task); return new SuccessAndLog(this.log, 'successfuly executed'); } _checkWatcher(task) { this.log.info('executing'); let method = 'search'; try { if (sirenFederateHelper.federateIsAvailable(this.server)) { method = sirenFederateHelper.getClientMethod(this.client); } } catch (err) { this.log.warning('Siren federate: "elasticsearch.plugins" is not available when running from kibana: ' + err.toString()); } const actions = this.getActions(task._source.actions); let search = get(task._source, 'input.search'); // search.request, search.kable, search.timelion let condition = task._source.condition; let transform = task._source.transform; if (!search) { throw new Error('search request or kable is malformed'); } if (!condition) { throw new Error('condition is malformed'); } return {method, search, condition, transform, actions}; } /** * Execute watcher. * * @param {object} task - Elasticsearch watcher object */ async execute(task) { this.log = new Log(this.config.app_name, this.server, `watcher ${task._id}`); if (!isEmpty(this.getActions(task._source.actions))) { try { const {method, search, condition, transform, actions} = this._checkWatcher(task); if (this.config.settings.authentication.impersonate || task._source.impersonate) { this.client = await this.getImpersonatedClient(task._id); } return await this._execute(task, method, search, condition, transform, actions); } catch (err) { logHistory({ server: this.server, watcherTitle: task._source.title, message: 'execute advanced watcher: ' + err.toString(), level: 'high', isError: true, }); throw new Error('execute watcher: ' + err.toString()); } } return new WarningAndLog(this.log, 'no actions found'); } /** * Impersonate ES client * * @return {promise} client - impersonated client */ async getImpersonatedClient(watcherId) { try { const user = await this.getUser(watcherId); if (!user.found) { throw new Error('fail to impersonate watcher, user was not found. Create watcher user first.'); } return getElasticsearchClient({ server: this.server, config: this.config, impersonateUsername: get(user, '_source.username') || get(user, `_source[${this.config.es.user_type}].username`), impersonateSha: get(user, '_source.sha') || get(user, `_source[${this.config.es.user_type}].sha`), impersonatePassword: get(user, '_source.password') || get(user, `_source[${this.config.es.user_type}].password`), impersonateId: user._id, isSiren: this.siren, }); } catch (err) { throw new Error('impersonate Elasticsearch API client: ' + err.toString()); } } }
JavaScript
class UserProfileRequest extends RequestMessage { constructor () { super() this.type = Symbol.keyFor(Message.types.USER_PROFILE_REQUEST) } }
JavaScript
class PostBodyRequestSwagger { /** * Constructs a new <code>PostBodyRequestSwagger</code>. * @alias module:model/PostBodyRequestSwagger */ constructor() { PostBodyRequestSwagger.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>PostBodyRequestSwagger</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/PostBodyRequestSwagger} obj Optional instance to populate. * @return {module:model/PostBodyRequestSwagger} The populated <code>PostBodyRequestSwagger</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new PostBodyRequestSwagger(); if (data.hasOwnProperty('officeId')) { obj['officeId'] = ApiClient.convertToType(data['officeId'], 'Number'); } if (data.hasOwnProperty('firstname')) { obj['firstname'] = ApiClient.convertToType(data['firstname'], 'String'); } if (data.hasOwnProperty('lastname')) { obj['lastname'] = ApiClient.convertToType(data['lastname'], 'String'); } if (data.hasOwnProperty('externalId')) { obj['externalId'] = ApiClient.convertToType(data['externalId'], 'String'); } if (data.hasOwnProperty('dateFormat')) { obj['dateFormat'] = ApiClient.convertToType(data['dateFormat'], 'String'); } if (data.hasOwnProperty('locale')) { obj['locale'] = ApiClient.convertToType(data['locale'], 'String'); } if (data.hasOwnProperty('active')) { obj['active'] = ApiClient.convertToType(data['active'], 'Boolean'); } if (data.hasOwnProperty('activationDate')) { obj['activationDate'] = ApiClient.convertToType(data['activationDate'], 'String'); } if (data.hasOwnProperty('submittedOnDate')) { obj['submittedOnDate'] = ApiClient.convertToType(data['submittedOnDate'], 'String'); } } return obj; } }
JavaScript
class GuestDriver { /** * Sends a query to the guest that repeatedly runs a query selector until * it returns an element. * * @param {string} query the querySelector to run in the guest. * @param {string=} opt_property a property to request on the found element. * @param {Object=} opt_commands test commands to execute on the element. * @return Promise<string> JSON.stringify()'d value of the property, or * tagName if unspecified. */ async waitForElementInGuest(query, opt_property, opt_commands = {}) { /** @type {TestMessageQueryData} */ const message = {testQuery: query, property: opt_property}; await testMessageHandlersReady; const result = /** @type {TestMessageResponseData} */ ( await guestMessagePipe.sendMessage( 'test', {...message, ...opt_commands})); return result.testQueryResult; } }
JavaScript
class PoppableMap extends Map { pop (k) { /* If the Map has the key, delete the key and return its value, otherwise return undefined. */ if (!this.has(k)) { return undefined } const v = this.get(k) this.delete(k) return v } }
JavaScript
class Grid{ constructor(width, height){ // localStorage.setItem('mapList',JSON.stringify([MAP_TEMPLATE])) /*the canvas must be width 800px,height 400px*/ this.width = width || 800 this.height = height || 400 this.ele = window.document.querySelector("#canvas") this.c = this.ele.getContext('2d') this.step = 8 //step means how many pixels tank goes when press button, it's like "control resolution ratio" this.gridBlock = 2 //a block consists of 16 pixels this.len = this.gridBlock * this.step } init(){ this.c.textBaseline = "top" this.c.fillStyle = "#000" this.c.fillRect(0,0,this.width,this.height) } /*basic methods*/ _drawBlock(row, col, type, self){ if(self === undefined) self = this let x = col * self.step + this.oX, y = row * self.step + this.oY, img = ImageManager.getBitMap(type) if(type === "void"){ self.c.fillStyle = "#000" self.c.fillRect(x, y, self.step, self.step) return } img && self.c.drawImage(img, x, y, self.step, self.step) } _drawGiantBlock(col, row, type, self, accuracy= false){ if(self === undefined) self = this let x = accuracy ? col : col * self.step, y = accuracy ? row : row * self.step, img = ImageManager.getBitMap(type) img && self.c.drawImage(img, x, y, self.len, self.len) } static _adaptor(material){ return material.map(k=>{ return k.map(k=>Grid.materialData[k]) }) } //add all the blocks here static get materialData(){ return { 0: 0, 1: "gra", 2: "wate", 3: "stee", 4: "wall" } } }
JavaScript
class PhysicsWorld { constructor() { this.physicsWorld = undefined; this.tmpTrans = undefined; this.rigidBodies = []; // Collision groups & maskeverdier: this.groups = { colGroupPlane: 1, colGroupBall: 2, colGroupBox: 4, colGroupHingeSphere: 8, colGroupStick:16 //... osv. ; // Binært 1, 10, 100, 1000, 10000, 100000 osv }; } setup() { this.tmpTrans = new Ammo.btTransform(); // Hjelpeobjekt. let collisionConfiguration = new Ammo.btDefaultCollisionConfiguration(), dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration), overlappingPairCache= new Ammo.btDbvtBroadphase(), solver = new Ammo.btSequentialImpulseConstraintSolver(); this.physicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration); this.physicsWorld.setGravity(new Ammo.btVector3(0, -9.81, 0)); } update( deltaTime ){ if (!this.tmpTrans) return; // Step physics world: this.physicsWorld.stepSimulation( deltaTime, 10 ); // Update rigid bodies for ( let i = 0; i < this.rigidBodies.length; i++ ) { let objThree = this.rigidBodies[ i ]; let objAmmo = objThree.userData.physicsBody; let ms = objAmmo.getMotionState(); if ( ms ) { ms.getWorldTransform( this.tmpTrans ); let p = this.tmpTrans.getOrigin(); let q = this.tmpTrans.getRotation(); objThree.position.set( p.x(), p.y(), p.z() ); objThree.quaternion.set( q.x(), q.y(), q.z(), q.w() ); } } } addRB(rigidBody, group, mask) { if (group && mask) { if (this.physicsWorld) this.physicsWorld.addRigidBody(rigidBody, group, mask); } else { if (this.physicsWorld) this.physicsWorld.addRigidBody(rigidBody); } } addConstraint(constraint, disableCollisions) { this.physicsWorld.addConstraint(constraint, disableCollisions); } }
JavaScript
class ExpressServer extends server_1.default { /** * @param app The express application. Must have express.json installed as a middleware. * @param opts The server options */ constructor(app, opts) { super(opts); if (!app) { if (!express) throw new Error('You must have the `express` module installed before using this server.'); app = express(); app.use(express.json()); } this.app = app; } /** * Adds middleware to the Express server. * @param middleware The middleware to add. */ addMiddleware(middleware) { this.app.use(middleware); return this; } /** Alias for {@link ExpressServer#addMiddleware} */ use(middleware) { return this.addMiddleware(middleware); } /** * Sets an Express setting. * @param setting Express setting string * @param value The value to set the setting to * @see http://expressjs.com/en/4x/api.html#app.settings.table */ set(setting, value) { this.app.set(setting, value); return this; } /** @private */ createEndpoint(path, handler) { this.app.post(path, (req, res) => handler({ headers: req.headers, body: req.body, request: req, response: res }, async (response) => { res.status(response.status || 200); if (response.headers) for (const key in response.headers) res.set(key, response.headers[key]); res.send(response.body); })); } /** @private */ async listen(port = 8030, host = 'localhost') { if (this.alreadyListening) return; this.app.listen(port, host); } }
JavaScript
class PageInstance extends RenderableInstance { /** * Perform any initialization needed, and in particular, async operations. * * When this function is finished, then the renderable should be ready to * be rendered as a string. * @function * @async * @param {Object} [data={}] * The initialization data. */ async init(data={}) { // Add the default CSS & Javascript Files. this.context.engine.library.require(this.context, 'Materialize'); // Add any library JavaScript & CSS. this.context.engine.library.process(this.context); await super.init(data); } }
JavaScript
class WebexService extends DRP_Service { constructor(serviceName, drpNode, priority, weight, scope) { super(serviceName, drpNode, "WebexService", null, false, priority, weight, drpNode.Zone, scope, null, null, 1); // Define global methods this.webex = require('webex/env'); this.ClientCmds = { getOpenAPIDoc: async function (cmdObj) { return openAPIDoc; }, listRooms: async () => { let response = await this.webex.rooms.list(); return response.items; } }; } }
JavaScript
class sfc32 { constructor(a, b, c, d) { this.a = a; this.b = b; this.c = c; this.d = d; } getUInt32() { this.a >>>= 0; this.b >>>= 0; this.c >>>= 0; this.d >>>= 0; var t = (this.a + this.b) | 0; this.a = this.b ^ this.b >>> 9; this.b = this.c + (this.c << 3) | 0; this.c = (this.c << 21 | this.c >>> 11); this.d = this.d + 1 | 0; t = t + this.d | 0; this.c = this.c + t | 0; return t >>> 0; } // returns float normalized to [0, 1) getRandom() { return this.getInt32() / 4294967296; } }
JavaScript
class Plane extends WebGLObject { /** * @param {Object} opts * @constructor */ constructor(opts) { super(opts); } }
JavaScript
class Calls extends ApiAdapter { /** * Make a call * Required params : cnumber, snumber * @param data * @returns {Promise<nomadoResponse>} */ make(data = {}) { const endpoint = 'calls/make'; const requiredParams = [ 'snumber', 'cnumber', ]; Validator.validateRequiredParams(requiredParams, data, endpoint); return this._call(endpoint, data); } }
JavaScript
class Monetize { /** * Initialize the class. */ constructor() { /** * Default settings. * * @type {{ * classes: { * stopped: string, pending: string, sending: string, disabled: string, enabled: string * }, * addClasses: boolean * }} */ this._default = { addClasses: false, classes: { disabled: 'js-monetization-disabled', enabled: 'js-monetization-enabled', pending: 'js-monetization-pending', stopped: 'js-monetization-stopped', sending: 'js-monetization-sending', }, }; /** * Main configuration. */ this.config = this._default; // Monetization meta tag holder. this.tag = null; // todo: Add watcher for pointer changes. this.activePointer = this.detectPointerFromMetaTag(); this.init(); this._observeHead(); } /** * Setup _default values and verify support for Monetization API. */ init() { this.watcher = new Watcher(); this.amount = new Amount(); this.config = merge(this._default, this.config); if (!document.monetization) { this.enabled = false; return; } this.enabled = true; } /** * Watch head tag for changes to update thr active pointer. * @private */ _observeHead() { (new MutationObserver(() => { const pointer = this.detectPointerFromMetaTag(); if (pointer && pointer !== this.activePointer) { this.watcher.dispatchCustomEvent('pointer_changed', pointer); } this.activePointer = pointer || null; })).observe(document.head, { childList: true }); } /** * Update the configuration object. * @param {object} options * @returns {Monetize} */ setup(options) { this.config = merge(this._default, options); if (this.config.addClasses) { this._addServiceStatusClass(); } return this; } /** * if the Monetization API is enable it will Add a new wallet pointer to the page * then register the required events for the monetization. * @param {null|string} pointer * @returns {PromiseLoop} */ pointer(pointer = null) { return new PromiseLoop((resolve, reject) => { if (!this.isEnabled()) { reject(new Error('Web monetization is not enabled in this browser.')); return true; } if (this.config.addClasses) { this._registerCssClasses(); } if (pointer) { this._setupMetaTag(pointer); } else if (!this.detectPointerFromMetaTag()) { reject(new Error('You have to provide a wallet.')); return true; } document.monetization.addEventListener('monetizationstart', (event) => { resolve(this.watcher.initializedWith(event, this.amount)); }); return true; }); } /** * Sequentially cycle through the given pointers. * @param {string[]} pointers list to pick from. * @param {number} timeout how often the pointer should be changed. * @param {function} callback an optional callback to control how a pointer is chosen. * It must return a pointer otherwise it will be ignored. * @returns {PromiseLoop} */ cycle(pointers, timeout = 3000, callback = null) { // Remove old intervals. clearInterval(this._timer); let lastIndex = 0; this._timer = setInterval(() => { let pointer; if (typeof callback === 'function') { pointer = callback(pointers); } if (!pointer) { pointer = pointers[lastIndex]; lastIndex = lastIndex + 1 <= pointers.length - 1 ? lastIndex + 1 : 0; } this.set(pointer); }, timeout); return this.pointer(pointers[0]); } /** * Randomly select a pointer from the list. * @param {Object.<string, number>} pointers * @param {number} timeout how often the pointer should be changed. * @returns {PromiseLoop} */ probabilisticCycle(pointers, timeout = 3000) { // Remove old intervals. clearInterval(this._timer); this._timer = setInterval(() => { this.set(this._getLuckyPointer(pointers)); }, timeout); return this.pointer(this._getLuckyPointer(pointers)); } /** * Randomly select a pointer from the list. * @param {string[] | Object.<string, number>} pointers * @returns {PromiseLoop} */ pluck(pointers) { if (Array.isArray(pointers)) { const index = this._randomNumber(0, pointers.length - 1); return this.pointer(pointers[index]); } return this.pointer(this._getLuckyPointer(pointers)); } // eslint-disable-next-line class-methods-use-this _getLuckyPointer(pointers) { const sum = Object.values(pointers).reduce((acc, weight) => acc + weight, 0); let choice = Math.random() * sum; // eslint-disable-next-line no-restricted-syntax for (const pointer in pointers) { if (pointers.hasOwnProperty(pointer)) { const weight = pointers[pointer]; choice -= weight; if (choice <= 0) { return pointer; } } } return null; } /** * Update the meta tag with the given pointer. * @param {string} pointer a new pointer to use. * @returns {Monetize} */ set(pointer) { this._setupMetaTag(pointer); return this; } /** * Detect if there's a pointer in the page. * @returns {string | null} */ detectPointerFromMetaTag() { const currentTag = document.querySelector('meta[name="monetization"]'); return (currentTag && currentTag.getAttribute('content')) || null; } /** * Create a meta tag with the provided pointer. * @param {string} pointer A pointer to add. * @private */ _setupMetaTag(pointer) { const currentTag = document.querySelector('meta[name="monetization"]'); if (currentTag) { currentTag.remove(); } const tag = document.createElement('meta'); tag.name = 'monetization'; tag.content = pointer; document.head.appendChild(tag); this.tag = tag; } /** * Add a CSS class for Monetization State to Body tag. * @private */ _registerCssClasses() { const showProgressClasses = () => { document.body.classList.remove(this.config.classes.stopped); document.body.classList.remove(this.config.classes.pending); document.body.classList.add(this.config.classes.sending); }; document.monetization.addEventListener('monetizationpending', () => { document.body.classList.remove(this.config.classes.stopped); document.body.classList.remove(this.config.classes.sending); document.body.classList.add(this.config.classes.pending); }); document.monetization.addEventListener('monetizationstart', showProgressClasses); document.monetization.addEventListener('monetizationprogress', showProgressClasses); document.monetization.addEventListener('monetizationstop', () => { document.body.classList.remove(this.config.classes.pending); document.body.classList.remove(this.config.classes.sending); document.body.classList.add(this.config.classes.stopped); }); } /** * Add a class that indicate whether the Web monetization API is supported. * @private */ _addServiceStatusClass() { if (this.isEnabled()) { document.body.classList.remove(this.config.classes.disabled); document.body.classList.add(this.config.classes.enabled); } else { document.body.classList.remove(this.config.classes.enabled); document.body.classList.add(this.config.classes.disabled); } } /** * Get a random number withing range. * @param min * @param max * @returns {number} * @private */ _randomNumber(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } /** * Destroy the watchers and previous states. * @returns {Monetize} */ refresh() { this.init(); clearInterval(this._timer); return this; } /** * Proxy for watcher. * @returns {PromiseLoop} */ when(...args) { return this.watcher.when(...args); } /** * Check if the Monetization API is supported by the current browser. * @returns {boolean} */ isEnabled() { return this.enabled; } /** * Check if there's a monetization stream going on. * @returns {boolean} */ isSending() { return this.isEnabled() && document.monetization.state === 'started'; } /** * Check if the service is idle. * @returns {boolean} */ isStopped() { return this.isEnabled() && document.monetization.state === 'stopped'; } /** * Check if the service is waiting for the first payment. * @returns {boolean} */ isPending() { return this.isEnabled() && document.monetization.state === 'pending'; } }
JavaScript
class ConfigManager { /** * @param {{}} rawConfig */ constructor(rawConfig) { must.be.object(rawConfig) this._rawConfig = rawConfig } /** * Freeze the config * @returns {ConfigManager} */ freeze() { this._rawConfig = this._deepFreeze(this._rawConfig) return this } /** * Config accessor * - to get value call it with () * - to get prop use . * - it throws no errors whatever long chain of non-existing props you build, finally you get value of undefined * * config.app.disableTasks() //false * config.app.disableTasks.bar.baz() //undefined * * @returns {ProxyfiedAccessor} */ getAccessor() { return new ProxyfiedAccessor(this._rawConfig) } /** * Deep freezing * @param {{}|[]} node * @returns {{}|[]} * @private */ _deepFreeze(node) { const props = Object.getOwnPropertyNames(node) for (let name of props) { let value = node[name] const isArray = check.array(value) const isObject = check.object(value) if (isArray || isObject) { if (isArray) { value.forEach(el => this._deepFreeze(el)) } this._deepFreeze(value) } } return Object.freeze(node) } }
JavaScript
class UserSettings extends Component { state = { formData: {}, isSaving: false, saveComplete: false, } /** * Save the latest settings modified by the user. Debounced to save * at most once per second. */ saveLatestSettings = _debounce(settings => { this.setState({isSaving: true, saveComplete: false}) this.props.updateUserSettings(this.props.user.id, settings).then(() => this.setState({isSaving: false, saveComplete: true}) ) }, 750, {leading: true}) /** Invoked when the form data is modified */ changeHandler = ({formData}) => { this.setState({formData, saveComplete: false}) this.saveLatestSettings(formData) } render() { const userSettings = _merge({}, this.props.user.settings, this.state.formData) let saveIndicator = null if (this.state.isSaving) { saveIndicator = <BusySpinner inline /> } else if (this.state.saveComplete) { saveIndicator = <SvgSymbol sym="check-icon" viewBox="0 0 20 20" /> } return ( <div className={classNames("user-profile__user-settings", this.props.className)}> <h2 className="subtitle"> <FormattedMessage {...messages.header} /> {saveIndicator} </h2> <Form schema={jsSchema(this.props.intl)} uiSchema={uiSchema} FieldTemplate={CustomFieldTemplate} liveValidate noHtml5Validate showErrorList={false} formData={userSettings} onChange={this.changeHandler}> <div className="form-controls" /> </Form> </div> ) } }