language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class WelcomeDialog extends ComponentDialog { constructor(userDataAccessor) { super(WelcomeDialog.name); // validate what was passed in if (!userDataAccessor) throw new Error('Missing parameter. userDataAccessor is required'); this.addDialog(new WaterfallDialog(WELCOME_DIALOG, [ this.welcomeStep.bind(this) ])); // Save off our state accessor for later use this.userDataAccessor = userDataAccessor; } /** * Waterfall Dialog step function. * * @param {WaterfallStepContext} step contextual information for the current step being executed */ async welcomeStep(step) { // if (userData === undefined) => It's a bug!!! const userData = await this.userDataAccessor.get(step.context); const locale = userData.locale; await step.context.sendActivity(this.getWelcomeCard(locale)); await step.context.sendActivity(localizer.gettext(locale, 'welcome.readyPrompt')); await Utils.showMainMenu(step.context, locale); return await step.endDialog(); } getWelcomeCard(locale) { const welcomeLogoUrl = `${ process.env.publicResourcesUrl }/public/welcome_logo.png`; const welcomeTittle = localizer.gettext(locale, 'welcome.tittle'); // Restart command should be localized. const restartCommand = localizer.gettext(locale, 'restartCommand'); const welcomeSubtittle = localizer.gettext(locale, 'welcome.subtittle', restartCommand); const welcomeAction = localizer.gettext(locale, 'welcome.privacy'); const language = locale.substring(0, 2); const welcomeActionUrl = `${ process.env.publicResourcesUrl }/public/privacy_policy_${ language }.pdf`; const card = Utils.adaptiveCardDataBind(welcomeCard, { welcomeLogoUrl, welcomeTittle, welcomeSubtittle, welcomeAction, welcomeActionUrl }); return { attachments: [card] }; } }
JavaScript
class Farkled extends Rule { verify(state, dice) { return this.result('Farkled', !didFarkle(dice)); } }
JavaScript
class EChartsWebComponent extends HTMLElement { static get echarts() { if (!EChartsWebComponent._echarts) { EChartsWebComponent._echarts = window.echarts } return EChartsWebComponent._echarts; } static set echarts(val) { EChartsWebComponent._echarts = val; } static get observedAttributes() { return ["style", "option"]; } constructor() { super(); const shadowRoot = this.attachShadow({ mode: 'open' }); shadowRoot.innerHTML = ` <div id="container" style="width: 100%; height: 100%;"></div> `; } connectedCallback() { if (!this.chart) { let container = this.shadowRoot.querySelector("#container"); this.chart = EChartsWebComponent.echarts.init(container); this.updateChart(); } } disconnectedCallback() { let container = this.shadowRoot.querySelector("#container"); if (container) { container.innerHTML = ""; } if (this.chart) { this.chart.dispose(); } this.chart = null; } attributeChangedCallback(name, oldValue, newValue) { if (name === "option") { this.updateChart(); } else if (name === "style") { let container = this.shadowRoot.querySelector("#container"); if (container) { container.style = newValue; } this.resizeChart(); } } updateChart() { if (!this.chart) return; let option = JSON.parse(this.option || "{}"); this.chart.setOption(option);; } resizeChart() { if (!this.chart) return; this.chart.resize(); } get option() { if (this.hasAttribute("option")) { return this.getAttribute("option"); } else { return "{}"; } } set option(val) { if (val) { this.setAttribute("option", val); } else { this.setAttribute("option", "{}"); } this.updateChart(); } }
JavaScript
class Repository { /** * Construct a Repository with a name * @param {string} name */ constructor(name = 'default') { this.name = name; this.suites = []; this.report = {}; this.isFinished = false; } /** * Check whether {obj} is repository * @param {any} obj * @return {boolean} */ isRepository(obj) { return obj && obj[RepositoryType]; } /** * Register a suite to the repository * @param {Suite} suite * @return {void} */ addSuite(suite) { this.isFinished = false; this.suites.push(suite); } /** * Run all suites (and all benches under suites) and generate a report * @return {Promise<Object, *>} */ run() { if (this.isFinished) return Promise.resolve(this.report); logger(this); return compose(this.suites).then(() => { this.isFinished = true; const report = {}; for (const suite of this.suites) { report[suite.name] = suite.report; } this.report = report; return report; }); } }
JavaScript
class MeanVSMedian extends Component { constructor( props ) { super( props ); this.state = { mu: 0, sigma: 1, lognormalData: [], lognormalDomain: { x: [ 0, 4 ], y: [ 0, 3 ] }, meanLognormalGuess: 1, medianLognormalGuess: 1, showLognormalMean: false, showLognormalMedian: false }; const opts = {}; if ( props.seed ) { opts.seed = props.seed; } this.rand = randu.factory( opts ); this.singleAccMean = incrmean(); this.groupAccMean = incrmean(); this.singleAccMedian = incrmean(); this.groupAccMedian = incrmean(); } componentDidMount() { this.generateData(); const session = this.context; this.unsubscribe = session.subscribe( ( type, action ) => { if ( type === MEMBER_ACTION ) { if ( action.type === 'MEDIAN_GUESS_DISTANCE' ) { const value = action.value; this.groupAccMedian( value ); this.forceUpdate(); } else if ( action.type === 'MEAN_GUESS_DISTANCE' ) { const value = action.value; this.groupAccMean( value ); this.forceUpdate(); } } }); } componentWillUnmount() { if ( this.unsubscribe ) { this.unsubscribe(); } } medianEvaluation = ( evt ) => { evt.stopPropagation(); if ( !this.state.showLognormalMedian ) { let distance = abs( lognormal.median( this.state.mu, this.state.sigma ) - this.state.medianLognormalGuess ); let msg = this.props.t('a-bit-off'); let xmax = this.state.lognormalDomain.x[ 1 ]; if ( distance < xmax/10 ) { msg = this.props.t('good'); } if ( distance < xmax/20 ) { msg = this.props.t('very-good'); } this.singleAccMedian( distance ); const session = this.context; session.addNotification({ title: this.props.t('score'), message: msg, position: 'tc', level: 'success' }); session.log({ id: this.props.id, type: 'MEDIAN_GUESS_DISTANCE', value: distance }); this.setState({ showLognormalMedian: true }); } }; meanEvaluation = ( evt ) => { evt.stopPropagation(); if ( !this.state.showLognormalMean ) { let distance = abs( lognormal.mean( this.state.mu, this.state.sigma ) - this.state.meanLognormalGuess ); let msg = this.props.t('a-bit-off'); let xmax = this.state.lognormalDomain.x[ 1 ]; if ( distance < xmax/10 ) { msg = this.props.t('good'); } if ( distance < xmax/20 ) { msg = this.props.t('very-good'); } this.singleAccMean( distance ); const session = this.context; session.addNotification({ title: this.props.t('score'), message: msg, position: 'tc', level: 'success' }); session.log({ id: this.props.id, type: 'MEAN_GUESS_DISTANCE', value: distance }); this.setState({ showLognormalMean: true }); } }; generateData = () => { let mu = this.rand() * 1.0 - 0.5; let sigma = this.rand() * 2.0 + 0.01; let xmax = 4 + lognormal.stdev( mu, sigma ); let x = linspace( 0, xmax, 80 ); let lognormalData = x.map( d => { return { x: d, y: lognormal.pdf( d, mu, sigma ) }; }); this.setState({ lognormalData, mu, sigma, lognormalDomain: { x: [ 0.0, xmax ], y: [ 0.0, lognormal.pdf( lognormal.mode( mu, sigma ), mu, sigma ) ] }, showLognormalMean: false, showLognormalMedian: false }); }; renderMeanPanel() { const { t } = this.props; return ( <Card> <Card.Header as="h4"> {t('mean')} </Card.Header> <Card.Body> <VictoryChart domain={this.state.lognormalDomain} containerComponent={ <VictoryCursorContainer events={{ onClick: this.meanEvaluation }} cursorDimension="x" cursorLabel={( d ) => `${roundn( d.x, -1 )}`} onCursorChange={( value ) => { debug( `Received cursor change: ${value}` ); if ( !this.state.showLognormalMean ) { this.setState({ meanLognormalGuess: value }); } }} /> }> <VictoryLine data={this.state.lognormalData} x="x" y="y" /> { this.state.showLognormalMean ? <VictoryLine data={[ { x: this.state.meanLognormalGuess, y: 0 }, { x: this.state.meanLognormalGuess, y: this.state.lognormalDomain.y[ 1 ] } ]} labels={[ 'Your Guess', '' ]} /> : null } { this.state.showLognormalMean ? <VictoryLine data={[ { x: lognormal.mean( this.state.mu, this.state.sigma ), y: 0 }, { x: lognormal.mean( this.state.mu, this.state.sigma ), y: this.state.lognormalDomain.y[ 1 ] } ]} labels={[ '', 'True Mean' ]} /> : null } </VictoryChart> </Card.Body> </Card> ); } renderMedianPanel() { const { t } = this.props; return ( <Card> <Card.Header as="h4"> {t('median')} </Card.Header> <Card.Body> <VictoryChart domain={this.state.lognormalDomain} containerComponent={ <VictoryCursorContainer events={{ onClick: this.medianEvaluation }} cursorDimension="x" cursorLabel={( d ) => `${roundn( d.x, -1 )}`} onCursorChange={( value ) => { if ( !this.state.showLognormalMedian ) { this.setState({ medianLognormalGuess: value }); } }} /> }> <VictoryLine data={this.state.lognormalData} x="x" y="y" /> { this.state.showLognormalMedian ? <VictoryLine data={[ { x: this.state.medianLognormalGuess, y: 0 }, { x: this.state.medianLognormalGuess, y: this.state.lognormalDomain.y[ 1 ] } ]} labels={[ 'Your Guess', '' ]} /> : null } { this.state.showLognormalMedian ? <VictoryLine data={[ { x: lognormal.median( this.state.mu, this.state.sigma ), y: 0 }, { x: lognormal.median( this.state.mu, this.state.sigma ), y: this.state.lognormalDomain.y[ 1 ] } ]} labels={[ '', 'True Median' ]} /> : null } </VictoryChart> </Card.Body> </Card> ); } render() { const { t } = this.props; return ( <Card style={this.props.style} > <Card.Header as="h3"> {this.props.header ? this.props.header : t('measures-of-location-header')} </Card.Header> <Card.Body> <Container> {this.props.intro} <Row> <Col md={6}> {this.renderMeanPanel()} </Col> <Col md={6}> {this.renderMedianPanel()} </Col> </Row> <Row> <div style={{ paddingTop: '20px', maxWidth: 400, margin: '0 auto 10px' }}> <Button variant="primary" size="lg" onClick={this.generateData} > {t('generate-new-data')} </Button> </div> </Row> <Row> {this.props.showStatistics ? <Table bordered> <thead> <tr> <th></th> <th>{t('you')}</th> <th>{t('group')}</th> </tr> </thead> <tbody> <tr> <th>{t('average-distance-from-mean')}</th> <td>{roundn( this.singleAccMean(), -2 )}</td> <td>{roundn( this.groupAccMean(), -2 )}</td> </tr> <tr> <th>{t('average-distance-from-median')}</th> <td>{roundn( this.singleAccMedian(), -2 )}</td> <td>{roundn( this.groupAccMedian(), -2 )}</td> </tr> </tbody> </Table> : null } </Row> </Container> {this.props.feedback ? <FeedbackButtons id="mean-vs-median" /> : null } </Card.Body> </Card> ); } }
JavaScript
class MySum { constructor(initialValue = 42) { this.sum = initialValue } add(value) { this.sum += value return this } }
JavaScript
class LinearFunction { slope; // Number intercept; // Number constructor(slope, intercept) { doTypeCheck(slope, "number", "Linear Function's Slope"); doTypeCheck(intercept, "number", "Linear Function's Intercept"); this.slope = slope; this.intercept = intercept; } get(x) { return x * this.slope + this.intercept; } toJSON() { return { "slope": this.slope, "intercept": this.intercept }; } static fromJSON(json) { return new LinearFunction( json["slope"], json["intercept"] ); } }
JavaScript
class TruncatedNormalDistribution { mean; // Number stdDeviation; // Number min; // Number max; // Number constructor(mean, stdDeviation, min, max) { doTypeCheck(mean, "number", "Truncated Normal Distribution's Mean"); doTypeCheck(stdDeviation, "number", "Truncated Normal Distribution's Std. Deviation"); doTypeCheck(min, "number", "Truncated Normal Distribution's Minimum Value"); doTypeCheck(max, "number", "Truncated Normal Distribution's Maximum Value"); this.mean = mean; this.stdDeviation = stdDeviation; this.min = min; this.max = max; } /** * Randomly samples this distribution. */ sample() { if (this.stdDeviation <= 0) return Math.max(this.min, Math.min(this.mean, this.max)); let value; let iterations = 0; do { if (iterations++ >= 100) { throw new Error( "Unable to sample value for TruncatedNormalDistribution " + JSON.stringify(this.toJSON()) ); } value = this.mean + randNormal() * this.stdDeviation; } while (value < this.min || value > this.max); return value; } toJSON() { return { "mean": this.mean, "stdDeviation": this.stdDeviation, "min": this.min, "max": this.max }; } static fromJSON(json) { return new TruncatedNormalDistribution( json["mean"], json["stdDeviation"], json["min"], json["max"] ); } static exactly(value) { return new TruncatedNormalDistribution(value, 0, value, value); } static zero() { return TruncatedNormalDistribution.exactly(0); } }
JavaScript
class Dashboard extends React.PureComponent { defaultLocale = store.getState().SettingsReducer.language; strings = getStrings().Dashboard; static navigationOptions = { header: null } constructor(props) { super(props); this.state = { containerHeight: null, items: {}, calendarOpened: false, snackbarVisible: false, snackbarTime: 3000, snackbarText: '', showMonth: false, month: '', modalVisible: false, deleteDialogVisible: false, shouldShowModal: false, modalInfo: {}, eventsPopover: false, knobPopover: false, createPopover: false }; updateNavigation('Dashboard', props.navigation.state.routeName); LocaleConfig.defaultLocale = this.defaultLocale; } renderItem(item, // changeInfo, setState ) { let category; if (item.category === 'Course') { category = this.props.courseColor; } else if (item.category === 'FixedEvent') { category = this.props.fixedEventsColor; } else if (item.category === 'NonFixedEvent') { category = this.props.nonFixedEventsColor; } else { category = white; } // let props = this.props; // let strings = this.strings; return ( <View style={styles.rowItem}> <View style={[styles.item, {backgroundColor: category} ]}> {/* <Checkbox /> */} <TouchableOpacity // onPress={() => changeInfo(category, item, props, strings, setState)} > <View style={{marginLeft:10}}> <Text style={styles.itemText}>{item.name}</Text> <Text style={styles.itemText}>{item.time}</Text> </View> </TouchableOpacity> </View> </View> ); } renderEmptyData = () => { return <View> <Text style={styles.eventsDayTitle}>{this.strings.eventsDayTitle}</Text> <View style={styles.noEvents}> <Text style={styles.noEventsText}>{this.strings.noEventsText}</Text> </View> </View>; } rowHasChanged = (r1, r2) => { return r1.name !== r2.name; } shouldChangeDay = (r1, r2) => { return r1 !== r2; } getMonth(date) { const month = date - 1; this.setState({ month: this.strings.months[month], showMonth: true }); } componentDidMount() { this.willFocusSubscription = this.props.navigation.addListener( 'willFocus', () => { this.setDashboardDataService(); this.setState({eventsPopover: !this.props.showTutorial}); if (!this.props.showTutorial) { this.darkenStatusBar(); } if (store.getState().NavigationReducer.successfullyInsertedEvents) { this.setState({ snackbarText: 'Event(s) successfully added', snackbarVisible: true }); this.props.dispatch(setNavigationScreen({successfullyInsertedEvents: null})); } this.refreshAgenda(); } ); } componentWillMount() { this.setDashboardDataService(); const currentDate = moment(); const month = currentDate.format('M'); this.getMonth(month); } componentWillUnmount() { this.willFocusSubscription.remove(); } setDashboardDataService = () => { getDataforDashboard() .then(items => { setTimeout(() => { let dict = sortEventsInDictonary(items); this.props.dispatch(setDashboardData(dict)); this.setState({items: dict}); },2000); }) .catch(err => { console.log('err', err); }); } dismissModal = () => { this.setState({modalVisible: false}); } /** * Goes to the appropriate Edit Screen */ navigateEditScreen = (editScreen) => { let param = {}; switch(editScreen) { case 'Course': param.editTitle = getStrings().Course.editTitle; break; case 'FixedEvent': param.editTitle = getStrings().FixedEvent.editTitle; break; case 'NonFixedEvent': param.editTitle = getStrings().NonFixedEvent.editTitle; break; } this.props.navigation.navigate('Edit' + editScreen, param); } // showDeleteModal = () => { // this.setState({deleteDialogVisible: true, shouldShowModal: true}); // } // dismissDeleteModal = () => { // } changeInfo = (category, item, props, strings, setModalInfo) => { let categoryColor; let lightCategoryColor; let categoryIcon; let details; let editScreen; let detailHeight; if (category === 'SchoolSchedule') { categoryColor = props.courseColor; lightCategoryColor = props.insideCourseColor; categoryIcon = 'school'; details = <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.location}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.location}</Text> </View>; detailHeight = 45; editScreen = 'Course'; } else if (category === 'FixedEvent') { categoryColor = props.fixedEventsColor; lightCategoryColor = props.insideFixedEventsColor; categoryIcon = 'calendar-today'; details = <View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.location}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.location}</Text> </View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.description}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.description}</Text> </View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.recurrence}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.recurrence}</Text> </View> </View>; detailHeight = 80; editScreen = 'FixedEvent'; } else { if (item.category === 'NonFixedEvent') { categoryColor = props.nonFixedEventsColor; lightCategoryColor = props.insideNonFixedEventsColor; } else { categoryColor = '#ababab'; lightCategoryColor = '#ababab'; } categoryIcon = 'face'; details = <View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.recurrence}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.recurrence}</Text> </View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.priority}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.priorityLevel}</Text> </View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.location}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.location}</Text> </View> <View style={styles.modalDetailView}> <Text style={styles.modalDetailsSubtitle}>{strings.description}</Text> <Text style={[styles.modalDetailsText, {color: semiTransparentWhite}]}>{item.description}</Text> </View> </View>; detailHeight = 100; editScreen = 'NonFixedEvent'; } setModalInfo( { categoryColor, categoryIcon, lightCategoryColor, details, detailHeight, editScreen, date: item.date, time: item.time, eventTitle: item.name }, true ); } setModalInfo = (modalInfo, modalVisible) => { this.setState({ modalInfo, modalVisible }); } darkenStatusBar = () => { if (Platform.OS === 'android') { StatusBar.setBackgroundColor(statusBarLightPopover, true); } } restoreStatusBar = () => { if (Platform.OS === 'android') { StatusBar.setBackgroundColor(statusBarDark, true); } } refreshAgenda = () => { if (Platform.OS !== 'ios') { this.setState({agendaKey: Math.random()}); } } render() { const {calendarOpened, snackbarVisible, snackbarTime, snackbarText, month, agendaKey} = this.state; let showCloseFab; let showMonthView; if (calendarOpened) { showCloseFab = <View style={styles.closeCalendarView}> <FAB style={styles.closeCalendarFab} small theme={{colors:{accent:dark_blue}}} icon="close" onPress={() => this.refs.agenda.chooseDay(this.refs.agenda.state.selectedDay)} /> </View>; showMonthView = null; } else { showCloseFab = null; showMonthView = <View style={styles.calendarBack}> <Text style={styles.calendarBackText}>{month}</Text> </View>; } return( <View style={styles.container}> <View style={styles.content}> <StatusBar translucent={true} animated barStyle={Platform.OS === 'ios' ? 'dark-content' : 'default'} backgroundColor={statusBarDark} /> {showMonthView} <View style={styles.calendar}> <Agenda ref='agenda' key={agendaKey} items={this.state.items} renderItem={(item) => this.renderItem(item, this.changeInfo, this.setModalInfo)} listTitle={this.strings.eventsDayTitle} renderEmptyData={this.renderEmptyData} onDayChange={(date) => { this.getMonth(date.month); }} onDayPress={(date) => { this.getMonth(date.month); }} rowHasChanged={this.rowHasChanged} showOnlyDaySelected={true} shouldChangeDay={this.shouldChangeDay} theme={{agendaKnobColor: dark_blue}} onCalendarToggled={(calendarOpened) => { this.setState({calendarOpened}, () => { LayoutAnimation.configureNext(LayoutAnimation.create(400, 'easeInEaseOut', 'opacity')); }); }} /> </View> { calendarOpened ? null : <TouchableOpacity onPress={() => this.props.navigation.navigate(ReviewEventRoute, {title: getStrings().ReviewEvent.title})} style={{position:'absolute', bottom: 13 , right:10}} ref='create'> <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center', height: 45, width: 110, backgroundColor: dark_blue, borderRadius: 22.5, ...Platform.select({ ios: { shadowColor: black, shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.3, shadowRadius: 3, }, android: { elevation: 4, }, }) }}> <Text style={{color: white, fontFamily: 'Raleway-Bold', marginRight: 5}}>{getStrings().Dashboard.create}</Text> <MaterialCommunityIcons size={20} name="calendar-multiple-check" color={white}/> </View> </TouchableOpacity> } </View> {showCloseFab} <Popover popoverStyle={styles.tooltipView} isVisible={this.state.eventsPopover} onClose={() => this.setState({eventsPopover:false})} doneClosingCallback={() => this.setState({knobPopover:true})}> <TouchableOpacity onPress={() => this.setState({eventsPopover:false})}> <Text style={styles.tooltipText}>{this.strings.eventsPopover}</Text> </TouchableOpacity> </Popover> <Popover popoverStyle={styles.tooltipView} verticalOffset={Platform.OS === 'ios' ? 90 : 55} fromView={this.refs.agenda} isVisible={this.state.knobPopover} onClose={() => this.setState({knobPopover:false})} doneClosingCallback={() => this.setState({createPopover:true})}> <TouchableOpacity onPress={() => this.setState({knobPopover:false})}> <Text style={styles.tooltipText}>{this.strings.knobPopover}</Text> </TouchableOpacity> </Popover> <Popover popoverStyle={styles.tooltipView} verticalOffset={Platform.OS === 'ios' ? 0 : -(StatusBar.currentHeight + 2)} isVisible={this.state.createPopover} fromView={this.refs.create} placement={'top'} onClose={() => { this.setState({createPopover:false}); this.props.dispatch(setTutorialStatus('dashboard', true)); this.restoreStatusBar(); }}> <TouchableOpacity onPress={() => { this.setState({createPopover:false}); this.props.dispatch(setTutorialStatus('dashboard', true)); this.restoreStatusBar(); }}> <Text style={styles.tooltipText}>{this.strings.createPopover}</Text> </TouchableOpacity> </Popover> <Snackbar visible={snackbarVisible} onDismiss={() => this.setState({snackbarVisible: false})} style={styles.snackbar} duration={snackbarTime}> {snackbarText} </Snackbar> {/* <ModalEvent visible={this.state.modalVisible} dismiss={this.dismissModal} navigateEditScreen={this.navigateEditScreen} showDeleteModal={this.showDeleteModal} categoryColor={this.state.modalInfo.categoryColor} eventTitle={this.state.modalInfo.eventTitle} date={this.state.modalInfo.date} time={this.state.modalInfo.time} categoryIcon={this.state.modalInfo.categoryIcon} detailHeight={this.state.modalInfo.detailHeight} details={this.state.modalInfo.details} editScreen={this.state.modalInfo.editScreen} /> <DeleteModal visible={this.state.deleteDialogVisible} dismiss={this.dismissDelete} shouldShowModal={this.state.shouldShowModal} deleteEvent={this.deleteEvent} showModal={this.showModal} /> */} </View> ); } }
JavaScript
class CheckMark extends Nuxeo.Element { static get template() { return html` <style> :host { display: inline-block; width: var(--nuxeo-checkmark-width, 18px); height: var(--nuxeo-checkmark-height, 18px); cursor: pointer; border-radius: 50%; border: 2px solid var(--nuxeo-checkmark-border-color, var(--nuxeo-border, gray)); background-color: var(--nuxeo-checkmark-background-color, transparent); color: var(--nuxeo-icon-color, transparent); padding: 0; margin: 0; } :host([hidden]) { display: none !important; } :host(:focus) { outline: none; } :host(:hover) { border: 2px solid var(--nuxeo-checkmark-border-color, var(--nuxeo-border, gray)); background-color: var(--nuxeo-checkmark-background-color-hover, transparent); color: var(--nuxeo-icon-color-hover, black); } :host([checked]) { border: 2px solid var(--nuxeo-checkmark-border-color-checked, var(--nuxeo-primary-color, blue)); background-color: var(--nuxeo-checkmark-background-color-checked, var(--nuxeo-primary-color, blue)); color: var(--nuxeo-icon-color-checked, white); } iron-icon { --iron-icon-width: 100%; --iron-icon-height: 100%; vertical-align: top; } </style> <iron-icon icon="nuxeo:check" on-click="_tap"></iron-icon> `; } static get is() { return 'nuxeo-checkmark'; } static get properties() { return { checked: { type: Boolean, reflectToAttribute: true, value: false, }, disabled: { type: Boolean, reflectToAttribute: true, value: false, }, }; } _tap() { if (!this.disabled) { this.checked = !this.checked; } } }
JavaScript
class Randomizer { /** * @param {number?} seed */ constructor (seed = undefined) { this._counter = 2 this._seed = seed || Number(process.env.RANDOM_SEED) || this.generateSeed() } /** * @returns {number|undefined} */ seed () { return this._seed } /** * @returns {number} */ random () { if (!this._seed) return Math.random() const r = Math.PI * (this._counter++ ^ this._seed) return r - Math.floor(r) } /** * @param {number} min * @param {number} max * @returns {number} */ range (min, max) { return (this.random() * (max - min + 1)) + min } /** * @param {number} min * @param {number} max * @returns {number} */ rangeInt (min, max) { return Math.floor(this.range(min, max)) } /** * @param {Array} arr */ element (arr) { const len = arr.length if (len === 0) return return arr[this.range(0, len)] } /** * @returns {boolean} */ bool () { const r = this.range(1, 100) return (r % 2) === 0 } /** * @returns {number} */ generateSeed () { return this.rangeInt(1, 100) } /** * @returns {Randomizer} */ fork () { return new Randomizer(this.generateSeed()) } }
JavaScript
class PersistentMapControlCapability extends SimpleToggleCapability { getType() { return PersistentMapControlCapability.TYPE; } }
JavaScript
class ClosedBannersStorage { constructor(key = closedBannersStorageKey) { this.storageKey = key; if (this.getAll() === null) { this.write([]); } } /** * @param {Array<string>} data */ write(data) { try { window.localStorage.setItem(this.storageKey, JSON.stringify(data)); } catch (e) { // nothing here } } /** * @return {Array<string>|null} */ getAll() { let rawValue = null; try { rawValue = window.localStorage.getItem(this.storageKey); } catch (e) { // nothing here } return !!rawValue ? JSON.parse(rawValue) : null; // eslint-disable-line no-extra-boolean-cast } /** * @public * @api * @return {boolean} */ has(bannerId) { const closedBanners = this.getAll(); return Array.isArray(closedBanners) ? closedBanners.indexOf(bannerId) > -1 : false; } /** * @public * @api */ add(bannerId) { const closedBanners = this.getAll(); const alreadyExist = closedBanners.indexOf(bannerId) !== -1; if (!alreadyExist) { closedBanners.push(bannerId); this.write(closedBanners); } } /** * @public * @api */ clear() { this.write([]); } /** * @public * @api */ destroy() { try { window.localStorage.removeItem(this.storageKey); } catch (e) { // nothing here } } }
JavaScript
class CustomStone extends PureComponent { render() { const lastMove = this.props.coor[0] === this.props.last[0] && this.props.coor[1] === this.props.last[1] return ( <div className="coordinate" key={this.props.coor} onClick={() => this.props.game === 0 ? this.props.onRemove(this.props.coor) : this.props.onMove(this.props.coor)} > {this.props.value === '+' ? '+' : <img src={lastMove ? `./${this.props.color}-last.png` : `./${this.props.color}.png` } alt={this.props.color}/>} <Hoshi value={this.props.value} coor={this.props.coor} size={this.props.size}></Hoshi> </div> ) } }
JavaScript
class Contact { constructor (pointerdownEvent, options) { options = options || {}; this.options = { "DEBUG" : false }; for (let key in options){ this.options[key] = options[key]; } this.DEBUG = this.options.DEBUG; this.id = new Date().getTime(); // a map of all active PointerInput instances this.pointerInputs = {}; this.activePointerInputs = {}; this.primaryPointerId = pointerdownEvent.pointerId; // initialPointerEvent holds the correct event.target for bubbling if pointerListener is bound to a "ancestor element" this.initialPointerEvent = pointerdownEvent; this.currentPointerEvent = pointerdownEvent; this.addPointer(pointerdownEvent); this.isActive = true; // global timings this.startTimestamp = pointerdownEvent.timeStamp; this.currentTimestamp = this.startTimestamp; this.endTimestamp = null; // multipointer parameters this.multipointer = { liveParameters : { centerMovement : null, centerMovementVector : null, distanceChange : null, // px relativeDistanceChange : null, // % rotationAngle : null, //deg ccw[0,360], cw[0,-360] vectorAngle : null // angle between the 2 vectors performed by the pointer. This differs from rotationAngle }, globalParameters : { centerMovement : null, centerMovementVector : null, distanceChange : null, relativeDistanceChange: null, rotationAngle : null, vectorAngle : null } }; } // add more pointers addPointer (pointerdownEvent) { this.currentPointerEvent = pointerdownEvent; var pointerInputOptions = { "DEBUG" : this.DEBUG }; var pointerInput = new PointerInput(pointerdownEvent, pointerInputOptions); this.pointerInputs[pointerdownEvent.pointerId] = pointerInput; this.activePointerInputs[pointerdownEvent.pointerId] = pointerInput; } removePointer (pointerId) { delete this.activePointerInputs[pointerId]; } // return a specific pointer input by its identifier getPointerInput (pointerId) { var hasPointerId = Object.prototype.hasOwnProperty.call(this.pointers, pointerId); if (hasPointerId){ let pointerInput = this.pointers[pointerId]; return pointerInput; } else { let msg = "invalid pointerId: " + pointerId + ". Pointer not found in Contact.pointers" throw new Error(msg); } } // return the pointer input which started this specific contact phenomenon getPrimaryPointerInput () { return this.pointerInputs[this.primaryPointerId]; } // currently, on 2 Inputs are supported getMultiPointerInputs () { var pointerId_1 = Object.keys(this.activePointerInputs)[0]; var pointerInput_1 = this.activePointerInputs[pointerId_1]; var pointerId_2 = Object.keys(this.activePointerInputs)[1]; var pointerInput_2 = this.activePointerInputs[pointerId_2]; var multiPointerInputs = [pointerInput_1, pointerInput_2]; return multiPointerInputs; } // pointermove contains only one single pointer, not multiple like on touch events (touches, changedTouches,...) onPointerMove (pointermoveEvent) { this.currentPointerEvent = pointermoveEvent; this.currentTimestamp = pointermoveEvent.timeStamp; var movedPointer = this.pointerInputs[pointermoveEvent.pointerId]; movedPointer.onMove(pointermoveEvent); if (this.DEBUG === true) { console.log(this.pointerInputs); } this.updateState(); } // pointerup event: finger released, or mouse button released onPointerUp (pointerupEvent) { var pointerId = pointerupEvent.pointerId; this.currentPointerEvent = pointerupEvent; this.currentTimestamp = pointerupEvent.timeStamp; var removedPointer = this.pointerInputs[pointerId]; removedPointer.onUp(pointerupEvent); this.removePointer(pointerId); this.updateState(); } onPointerCancel (pointercancelEvent) { this.onPointerUp(pointercancelEvent); if (this.DEBUG == true){ console.log("[Contact] pointercancel detected"); } } // also covers pointerleave // not necessary - using element.setPointerCapture and element.releasePointerCapture instead onPointerLeave (pointerleaveEvent){ this.onPointerUp(pointerleaveEvent); if (this.DEBUG == true){ console.log("[Contact] pointerleave detected"); } } // if the contact idles (no Momvement), the time still passes // therefore, the pointerInput has to be updated onIdle () { for (let pointerInputId in this.activePointerInputs){ let activePointer = this.activePointerInputs[pointerInputId]; activePointer.onIdle(); } } // update this contact instance. invoked on pointermove, pointerup and pointercancel events updateState () { var isActive = false; if (Object.keys(this.activePointerInputs).length > 0){ isActive = true; } this.isActive = isActive; if ( this.isActive == false ) { this.endTimestamp = this.currentTimestamp; } else if (Object.keys(this.activePointerInputs).length >= 2){ this.updateMultipointerParameters(); } } // functions for multi pointer gestures, currently only 2 pointers are supported updateMultipointerParameters () { var multiPointerInputs = this.getMultiPointerInputs() var pointerInput_1 = multiPointerInputs[0]; var pointerInput_2 = multiPointerInputs[1]; var vector_1 = pointerInput_1.liveParameters.vector; var vector_2 = pointerInput_2.liveParameters.vector; if (vector_1 != null && vector_2 != null){ var currentCenter = getCenter(vector_1.startPoint, vector_2.startPoint); this.multipointer.liveParameters.center = currentCenter; var centerMovementVector = this.calculateCenterMovement(vector_1, vector_2); this.multipointer.liveParameters.centerMovementVector = centerMovementVector; this.multipointer.liveParameters.centerMovement = centerMovementVector.vectorLength; var liveDistanceChange = this.calculateDistanceChange(vector_1, vector_2); this.multipointer.liveParameters.distanceChange = liveDistanceChange.absolute; this.multipointer.liveParameters.relativeDistanceChange = liveDistanceChange.relative; // calculate rotation angle. imagine the user turning a wheel with 2 fingers var liveRotationAngle = this.calculateRotationAngle(vector_1, vector_2); this.multipointer.liveParameters.rotationAngle = liveRotationAngle; // calculate the simple vectorAngle for determining if the fingers moved into the same direction var liveVectorAngle = this.calculateVectorAngle(vector_1, vector_2) this.multipointer.liveParameters.vectorAngle = liveVectorAngle; } // global distance change and rotation var globalVector_1 = pointerInput_1.globalParameters.vector; var globalVector_2 = pointerInput_2.globalParameters.vector; if (globalVector_1 != null && globalVector_2 != null){ var globalCenter = getCenter(globalVector_1.startPoint, globalVector_2.startPoint); this.multipointer.globalParameters.center = globalCenter; var globalCenterMovementVector = this.calculateCenterMovement(globalVector_1, globalVector_2); this.multipointer.globalParameters.centerMovementVector = globalCenterMovementVector; this.multipointer.globalParameters.centerMovement = globalCenterMovementVector.vectorLength; var globalDistanceChange = this.calculateDistanceChange(globalVector_1, globalVector_2); this.multipointer.globalParameters.distanceChange = globalDistanceChange.absolute; this.multipointer.globalParameters.relativeDistanceChange = globalDistanceChange.relative; var globalRotationAngle = this.calculateRotationAngle(globalVector_1, globalVector_2); this.multipointer.globalParameters.rotationAngle = globalRotationAngle; var globalVectorAngle = this.calculateVectorAngle(globalVector_1, globalVector_2) this.multipointer.liveParameters.vectorAngle = globalVectorAngle; } if (this.DEBUG === true){ console.log("[Contact] 2 fingers: centerMovement between pointer #" + pointerInput_1.pointerId + " and pointer #" + pointerInput_2.pointerId + " : " + this.multipointer.liveParameters.centerMovement + "px"); console.log("[Contact] 2 fingers: distanceChange: between pointer #" + pointerInput_1.pointerId + " and pointer #" + pointerInput_2.pointerId + " : " + this.multipointer.liveParameters.distanceChange + "px"); console.log("[Contact] 2 fingers live angle: " + this.multipointer.liveParameters.rotationAngle + "deg"); console.log("[Contact] 2 fingers global angle: " + this.multipointer.globalParameters.rotationAngle + "deg"); } } calculateCenterMovement (vector_1, vector_2){ // start point is the center between the starting points of the 2 vectors var startPoint = getCenter(vector_1.startPoint, vector_2.startPoint); // center between the end points of the vectors var endPoint = getCenter(vector_1.endPoint, vector_2.endPoint); var vectorBetweenCenterPoints = new Vector(startPoint, endPoint); return vectorBetweenCenterPoints; } calculateDistanceChange (vector_1, vector_2) { var vectorBetweenStartPoints = new Vector(vector_1.startPoint, vector_2.startPoint); var vectorBetweenEndPoints = new Vector(vector_1.endPoint, vector_2.endPoint); var absoluteDistanceChange = vectorBetweenEndPoints.vectorLength - vectorBetweenStartPoints.vectorLength; var relativeDistanceChange = vectorBetweenEndPoints.vectorLength / vectorBetweenStartPoints.vectorLength; var distanceChange = { absolute : absoluteDistanceChange, relative : relativeDistanceChange }; return distanceChange; } /* * CALCULATE ROTATION * this is not a trivial problem * required output is: angle and direction (cw //ccw) * direction is relative to the first touch with two fingers, not absolute to the screens default coordinate system * to determine rotation direction, 3 points on the circle - with timestamps - are required * imagine a steering wheel * - initial state is 0 deg (0) * - if the wheel has been turned ccw, its state has a negative angle * - if the wheel has been turned cw, its state has a positive angle * - possible values for the angle: [-360,360] */ calculateRotationAngle (vector_1, vector_2) { // vector_ are vectors between 2 points in time, same finger // angleAector_ are vectors between 2 fingers var angleVector_1 = new Vector(vector_1.startPoint, vector_2.startPoint); // in time: occured first var angleVector_2 = new Vector(vector_1.endPoint, vector_2.endPoint); // in time: occured second var origin = new Point(0,0); // translate the points of the vector, so that their startPoints are attached to (0,0) /* ^ / / / x 0 */ var translationVector_1 = new Vector(angleVector_1.startPoint, origin); var translatedEndPoint_1 = translatePoint(angleVector_1.endPoint, translationVector_1); //var v_1_translated = new Vector(origin, translatedEndPoint_1); var translationVector_2 = new Vector(angleVector_2.startPoint, origin); var translatedEndPoint_2 = translatePoint(angleVector_2.endPoint, translationVector_2); //var v2_translated = new Vector(origin, translatedEndPoint_2); // rotate the first angle vector so its y-coordinate becomes 0 /* x-------> 0 */ var rotationAngle = calcAngleRad(translatedEndPoint_1) * (-1); // rottation matrix //var x_1_rotated = ( translatedEndPoint_1.x * Math.cos(rotationAngle) ) - ( translatedEndPoint_1.y * Math.sin(rotationAngle) ); //var y_1_rotated = Math.round(( translatedEndPoint_1.x * Math.sin(rotationAngle) ) + ( translatedEndPoint_1.y * Math.cos(rotationAngle) )); // should be 0 //var v_1_rotated = new Vector(origin, new Point(x_1_rotated, y_1_rotated)); // rotate the second vector (in time: after 1st) var x_2_rotated = ( translatedEndPoint_2.x * Math.cos(rotationAngle) ) - ( translatedEndPoint_2.y * Math.sin(rotationAngle) ); var y_2_rotated = Math.round(( translatedEndPoint_2.x * Math.sin(rotationAngle) ) + ( translatedEndPoint_2.y * Math.cos(rotationAngle) )); //var v_2_rotated = new Vector(origin, new Point(x_2_rotated, y_2_rotated)); // calculate the angle between v_1 and v_2 var angleDeg = Math.atan2(y_2_rotated, x_2_rotated) * 180 / Math.PI; return angleDeg; } calculateVectorAngle (vector_1, vector_2) { var angleDeg = null; if (vector_1.vectorLength > 0 && vector_2.vectorLength > 0){ var cos = ( (vector_1.x * vector_2.x) + (vector_1.y * vector_2.y) ) / (vector_1.vectorLength * vector_2.vectorLength); var angleRad = Math.acos(cos); angleDeg = rad2deg(angleRad); } return angleDeg; } }
JavaScript
class Gesture { constructor (domElement, options){ this.domElement = domElement; this.isActive = false; this.state = GESTURE_STATE_POSSIBLE; // the PointerEvent when the gesture has been recognized, used for some global calculations // it is not always reasonable to use contact.pointerdownEvent, because the user could first rotate and object, and after some time perform a pinch // the starting point of the pinch then is not contact.pointerdownEvent this.initialPointerEvent = null; this.boolParameters = { requiresPointerMove : null, requiresActivePointer : null } // intervals before a gesture is detected for the first time this.initialMinMaxParameters = { pointerCount : [null, null], // minimum number of fingers currently on the surface duration : [null, null], // ms currentSpeed : [null, null], // px/s averageSpeed : [null, null], // px/s finalSpeed : [null, null], // px/s distance : [null, null] // px }; // intervals to use if the gesture is active this.activeStateMinMaxParameters = { pointerCount : [null, null], // minimum number of fingers currently on the surface duration : [null, null], // ms currentSpeed : [null, null], // px/s averageSpeed : [null, null], // px/s finalSpeed : [null, null], // px/s distance : [null, null] // px } let defaultOptions = { "bubbles" : true, "blocks" : [], "DEBUG" : false }; this.options = options || {}; for (let key in defaultOptions){ if (!(key in this.options)){ this.options[key] = defaultOptions[key]; } } this.DEBUG = this.options.DEBUG; } validateMinMax (minMaxParameters, parameterName, value){ var minValue = minMaxParameters[parameterName][0]; var maxValue = minMaxParameters[parameterName][1]; if (this.DEBUG == true){ console.log("[Gestures] checking " + parameterName + "[gesture.isActive: " + this.isActive.toString() + "]" + " minValue: " + minValue + ", maxValue: " + maxValue + ", current value: " + value); } if (minValue != null && value != null && value < minValue){ if (this.DEBUG == true){ console.log("dismissing min" + this.eventBaseName + ": required " + parameterName + ": " + minValue + ", current value: " + value); } return false; } if (maxValue != null && value != null && value > maxValue){ if (this.DEBUG == true){ console.log("dismissing max" + this.eventBaseName + ": required " + parameterName + ": " + maxValue + ", current value: " + value); } return false; } return true; } validateBool (parameterName, value) { // requiresPointerMove = null -> it does not matter if the pointer has been moved var requiredValue = this.boolParameters[parameterName]; if (requiredValue != null && value != null && requiredValue === value){ return true; } else if (requiredValue == null){ return true; } if (this.DEBUG == true){ console.log("[Gestures] dismissing " + this.eventBaseName + ": " + parameterName + " required: " + requiredValue + ", actual value: " + value); } return false; } getMinMaxParameters (contact) { var primaryPointerInput = contact.getPrimaryPointerInput(); var minMaxParameters = { pointerCount : Object.keys(contact.activePointerInputs).length, duration : primaryPointerInput.globalParameters.duration, currentSpeed : primaryPointerInput.liveParameters.speed, averageSpeed : primaryPointerInput.globalParameters.averageSpeed, finalSpeed : primaryPointerInput.globalParameters.finalSpeed, distance : primaryPointerInput.liveParameters.vector.vectorLength }; return minMaxParameters; } getBoolParameters (contact) { var primaryPointerInput = contact.getPrimaryPointerInput(); var boolParameters = { requiresPointerUp : primaryPointerInput.isActive === false, requiresActivePointer : primaryPointerInput.isActive === true, requiresPointerMove : primaryPointerInput.globalParameters.hasBeenMoved === true }; return boolParameters; } validate (contact){ var isValid = false; if (this.state == GESTURE_STATE_BLOCKED) { return false; } var primaryPointerInput = contact.getPrimaryPointerInput(); if (this.DEBUG == true){ console.log("[Gestures] running recognition for " + this.eventBaseName); } var contactBoolParameters = this.getBoolParameters(contact); for (let boolParameterName in this.boolParameters){ let boolValue = contactBoolParameters[boolParameterName]; isValid = this.validateBool(boolParameterName, boolValue); if (isValid == false){ return false; //break; } } var contactMinMaxParameters = this.getMinMaxParameters(contact); var minMaxParameters; // check duration if (this.isActive == true){ minMaxParameters = this.activeStateMinMaxParameters; } else { minMaxParameters = this.initialMinMaxParameters; } for (let minMaxParameterName in minMaxParameters){ let value = contactMinMaxParameters[minMaxParameterName]; isValid = this.validateMinMax(minMaxParameters, minMaxParameterName, value); if (isValid == false){ return false; //break; } } // check direction var hasSupportedDirections = Object.prototype.hasOwnProperty.call(this.options, "supportedDirections"); if (hasSupportedDirections == true && this.options.supportedDirections.length > 0){ if (this.options.supportedDirections.indexOf(primaryPointerInput.liveParameters.vector.direction) == -1){ if (this.DEBUG == true){ console.log("[Gestures] dismissing " + this.eventBaseName + ": supported directions: " + this.options.supportedDirections + ", current direction: " + primaryPointerInput.liveParameters.vector.direction); } return false; } } return true; } recognize (contact) { var isValid = this.validate(contact); if (isValid == true && this.isActive == false && this.state == GESTURE_STATE_POSSIBLE){ this.onStart(contact); } if (isValid == true && this.isActive == true && this.state == GESTURE_STATE_POSSIBLE){ this.emit(contact); } else if (this.isActive == true && isValid == false){ this.onEnd(contact); } } block (gesture) { if (this.options.blocks.indexOf(gesture) == -1){ this.options.blocks.push(gesture); } } unblock (gesture) { if (this.options.blocks.indexOf(gesture) != -1){ this.options.blocks.splice(this.options.blocks.indexOf(gesture), 1); } } blockGestures () { for (let g=0; g<this.options.blocks.length; g++){ let gesture = this.options.blocks[g]; if (gesture.isActive == false) { if (this.DEBUG == false){ console.log("[Gesture] blocking " + gesture.eventBaseName); } gesture.state = GESTURE_STATE_BLOCKED; } } } unblockGestures () { for (let g=0; g<this.options.blocks.length; g++){ let gesture = this.options.blocks[g]; gesture.state = GESTURE_STATE_POSSIBLE; } } getEventData (contact) { // provide short-cuts to the values collected in the Contact object // match this to the event used by hammer.js var eventData = { contact : contact, recognizer : this }; return eventData; } // fire events emit (contact, eventName) { // fire general event like "pan" , "pinch", "rotate" eventName = eventName || this.eventBaseName; if (this.DEBUG === true){ console.log("[Gestures] detected and firing event " + eventName); } var eventData = this.getEventData(contact); var eventOptions = { detail: eventData, bubbles : this.options.bubbles }; var event = new CustomEvent(eventName, eventOptions); var initialTarget = contact.initialPointerEvent.target; if (eventOptions.bubbles == true){ initialTarget.dispatchEvent(event); } else { this.domElement.dispatchEvent(event); } // fire direction specific events var currentDirection = eventData.live.direction; var hasSupportedDirections = Object.prototype.hasOwnProperty.call(this.options, "supportedDirections"); if (hasSupportedDirections == true){ for (let d=0; d<this.options.supportedDirections.length; d++){ let direction = this.options.supportedDirections[d]; if (direction == currentDirection){ let directionEventName = eventName + direction; if (this.DEBUG == true){ console.log("[Gestures] detected and firing event " + directionEventName); } let directionEvent = new CustomEvent(directionEventName, eventOptions); if (eventOptions.bubbles == true){ initialTarget.dispatchEvent(directionEvent); } else { this.domElement.dispatchEvent(directionEvent); } } } } } onStart (contact) { this.blockGestures(); this.isActive = true; this.initialPointerEvent = contact.currentPointerEvent; var eventName = "" + this.eventBaseName + "start"; if (this.DEBUG === true) { console.log("[Gestures] firing event: " + eventName); } // fire gestureend event var eventData = this.getEventData(contact); var event = new CustomEvent(eventName, { detail: eventData }); this.domElement.dispatchEvent(event); } onEnd (contact) { this.unblockGestures(); this.isActive = false; var eventName = "" + this.eventBaseName + "end"; if (this.DEBUG === true) { console.log("[Gestures] firing event: " + eventName); } // fire gestureend event let eventData = this.getEventData(contact); var event = new CustomEvent(eventName, { detail: eventData }); this.domElement.dispatchEvent(event); } // provide the ability to react (eg block) to touch events onTouchStart () {} onTouchMove () {} onTouchEnd () {} onTouchCancel (){} }
JavaScript
class Pan extends SinglePointerGesture { constructor (domElement, options){ options = options || {}; super(domElement, options); this.eventBaseName = "pan"; this.initialMinMaxParameters["pointerCount"] = [1,1]; // 1: no pan recognized at the pointerup event. 0: pan recognized at pointerup this.initialMinMaxParameters["duration"] = [0, null]; this.initialMinMaxParameters["distance"] = [10, null]; this.activeStateMinMaxParameters["pointerCount"] = [1,1]; this.boolParameters["requiresPointerMove"] = true; this.boolParameters["requiresActivePointer"] = true; this.swipeFinalSpeed = 600; this.isSwipe = false; this.initialSupportedDirections = DIRECTION_ALL; var hasSupportedDirections = Object.prototype.hasOwnProperty.call(options, "supportedDirections"); if (!hasSupportedDirections){ this.options.supportedDirections = DIRECTION_ALL; } else { this.initialSupportedDirections = options.supportedDirections; } } validate (contact) { // on second recognition allow all directions. otherwise, the "pan" mode would end if the finger was moved right and then down during "panleft" mode if (this.isActive == true){ this.options.supportedDirections = DIRECTION_ALL; } var isValid = super.validate(contact); return isValid; } onStart (contact) { this.isSwipe = false; super.onStart(contact); } // check if it was a swipe onEnd (contact) { var primaryPointerInput = contact.getPrimaryPointerInput(); if (this.swipeFinalSpeed < primaryPointerInput.globalParameters.finalSpeed){ this.isSwipe = true; this.emit(contact, "swipe"); } super.onEnd(contact); this.options.supportedDirections = this.initialSupportedDirections; } onTouchMove (event) { if (this.isActive == true) { if (this.DEBUG == true){ console.log("[Pan] preventing touchmove default"); } event.preventDefault(); event.stopPropagation(); } } }
JavaScript
class Tap extends SinglePointerGesture { constructor (domElement, options) { options = options || {}; super(domElement, options); this.eventBaseName = "tap"; this.initialMinMaxParameters["pointerCount"] = [0,0]; // count of fingers touching the surface. a tap is fired AFTER the user removed his finger this.initialMinMaxParameters["duration"] = [0, 200]; // milliseconds. after a certain touch duration, it is not a TAP anymore this.initialMinMaxParameters["distance"] = [null, 30]; // if a certain distance is detected, TAP becomes impossible this.boolParameters["requiresPointerMove"] = null; this.boolParameters["requiresActivePointer"] = false; } recognize (contact) { var isValid = this.validate(contact); if (isValid == true && this.state == GESTURE_STATE_POSSIBLE){ this.initialPointerEvent = contact.currentPointerEvent; this.emit(contact); } } }
JavaScript
class Press extends SinglePointerGesture { constructor (domElement, options) { options = options || {}; super(domElement, options); this.eventBaseName = "press"; this.initialMinMaxParameters["pointerCount"] = [1, 1]; // count of fingers touching the surface. a press is fired during an active contact this.initialMinMaxParameters["duration"] = [600, null]; // milliseconds. after a certain touch duration, it is not a TAP anymore this.initialMinMaxParameters["distance"] = [null, 10]; // if a certain distance is detected, Press becomes impossible this.boolParameters["requiresPointerMove"] = null; this.boolParameters["requiresActivePointer"] = true; // only Press has this parameter this.hasBeenEmitted = false; // as the global vector length is used, press should not trigger if the user moves away from the startpoint, then back, then stays this.hasBeenInvalidatedForContactId = null; } // distance has to use the global vector getMinMaxParameters (contact) { var minMaxParameters = super.getMinMaxParameters(contact); var primaryPointerInput = contact.getPrimaryPointerInput(); minMaxParameters.distance = primaryPointerInput.globalParameters.vector.vectorLength; return minMaxParameters; } recognize (contact) { var isValid = this.validate(contact); var primaryPointerInput = contact.getPrimaryPointerInput(); if (this.hasBeenInvalidatedForContactId != null && this.hasBeenInvalidatedForContactId != contact.id) { this.hasBeenInvalidatedForContactId = null; } if (isValid == false) { if (primaryPointerInput.globalParameters.vector.vectorLength > this.initialMinMaxParameters["distance"][1]){ this.hasBeenInvalidatedForContactId = contact.id; } } if (isValid == true && this.hasBeenEmitted == false && this.hasBeenInvalidatedForContactId == null){ this.initialPointerEvent = contact.currentPointerEvent; this.emit(contact); this.hasBeenEmitted = true; } else { let duration = primaryPointerInput.globalParameters.duration; if (this.hasBeenEmitted == true && duration <= this.initialMinMaxParameters["duration"][0]){ this.hasBeenEmitted = false; } } } }
JavaScript
class Pinch extends TwoPointerGesture { constructor (domElement, options) { options = options || {}; super(domElement, options); this.eventBaseName = "pinch"; this.initialMinMaxParameters["centerMovement"] = [0, 50]; //px this.initialMinMaxParameters["distanceChange"] = [5, null]; // distance between 2 fingers this.initialMinMaxParameters["rotationAngle"] = [null, 20]; // distance between 2 fingers this.initialMinMaxParameters["vectorAngle"] = [10, null]; } }
JavaScript
class Rotate extends TwoPointerGesture { constructor (domElement, options) { options = options || {}; super(domElement, options); this.eventBaseName = "rotate"; this.initialMinMaxParameters["centerMovement"] = [0, 50]; this.initialMinMaxParameters["distanceChange"] = [null, 50]; this.initialMinMaxParameters["rotationAngle"] = [5, null]; } }
JavaScript
class TwoFingerPan extends TwoPointerGesture { constructor (domElement, options) { options = options || {}; super(domElement, options); this.eventBaseName = "twofingerpan"; this.initialMinMaxParameters["centerMovement"] = [3, null]; this.initialMinMaxParameters["distanceChange"] = [null, 50]; this.initialMinMaxParameters["rotationAngle"] = [null, null]; this.initialMinMaxParameters["vectorAngle"] = [null, 150]; } }
JavaScript
class TransportV3 extends WinstonTransport { log (info, cb) { this.emit('test-log', info) cb() } }
JavaScript
class RSAKey { constructor() { /** @type {BigInteger | null} */ this.n = null; this.e = 0; /** @type {BigInteger | null} */ this.d = null; /** @type {BigInteger | null} */ this.p = null; /** @type {BigInteger | null} */ this.q = null; /** @type {BigInteger | null} */ this.dmp1 = null; /** @type {BigInteger | null} */ this.dmq1 = null; /** @type {BigInteger | null} */ this.coeff = null; } /** * Set the public key fields N and e from hex strings * @param {string} N * @param {string} E */ setPublic(N, E) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); } else throw "Invalid RSA public key"; } /** * Perform raw public operation on "x": return x^e (mod n) * @param {BigInteger} x * @returns {BigInteger} */ doPublic(x) { return x.modPowInt(this.e, this.n); } /** * @param {string} text * @returns {string | null} the PKCS#1 RSA encryption of "text" as an even-length hex string */ encrypt(text) { let m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3); if (m == null) return null; let c = this.doPublic(m); if (c == null) return null; let h = c.toString(16); if ((h.length & 1) == 0) return h; else return "0" + h; } /** * @param {string} text * @returns {string | null} the PKCS#1 RSA encryption of "text" as a Base64-encoded string */ encrypt_b64(text) { let h = this.encrypt(text); if (h) return hex2b64(h); else return null; } /** * Set the private key fields N, e, and d from hex strings * @param {string | null} N * @param {string | null} E * @param {string} D */ setPrivate(N, E, D) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); this.d = parseBigInt(D, 16); } else throw "Invalid RSA private key"; } /** * Set the private key fields N, e, d and CRT params from hex strings * @param {string} N * @param {string} E * @param {string} D * @param {string} P * @param {string} Q * @param {string} DP * @param {string} DQ * @param {string} C */ setPrivateEx(N, E, D, P, Q, DP, DQ, C) { if (N != null && E != null && N.length > 0 && E.length > 0) { this.n = parseBigInt(N, 16); this.e = parseInt(E, 16); this.d = parseBigInt(D, 16); this.p = parseBigInt(P, 16); this.q = parseBigInt(Q, 16); this.dmp1 = parseBigInt(DP, 16); this.dmq1 = parseBigInt(DQ, 16); this.coeff = parseBigInt(C, 16); } else throw "Invalid RSA private key"; } /** * Generate a new random private key B bits long, using public expt E * @param {number} B * @param {string} E */ generate(B, E) { let rng = new SecureRandom(); let qs = B >> 1; this.e = parseInt(E, 16); let ee = new BigInteger(E, 16); for (; ;) { for (; ;) { this.p = new BigInteger(B - qs, 1, rng); if (this.p.subtract(BigInteger.ONE()).gcd(ee).compareTo(BigInteger.ONE()) == 0 && this.p.isProbablePrime(10)) break; } for (; ;) { this.q = new BigInteger(qs, 1, rng); if (this.q.subtract(BigInteger.ONE()).gcd(ee).compareTo(BigInteger.ONE()) == 0 && this.q.isProbablePrime(10)) break; } if (this.p.compareTo(this.q) <= 0) { let t = this.p; this.p = this.q; this.q = t; } let p1 = this.p.subtract(BigInteger.ONE()); let q1 = this.q.subtract(BigInteger.ONE()); let phi = p1.multiply(q1); if (phi.gcd(ee).compareTo(BigInteger.ONE()) == 0) { this.n = this.p.multiply(this.q); this.d = ee.modInverse(phi); this.dmp1 = this.d.mod(p1); this.dmq1 = this.d.mod(q1); this.coeff = this.q.modInverse(this.p); break; } } } /** * @protected * @param {BigInteger} x * @returns {BigInteger} Perform raw private operation on "x": return x^d (mod n) */ doPrivate(x) { if (this.p == null || this.q == null) return x.modPow(this.d, this.n); // TODO: re-calculate any missing CRT params let xp = x.mod(this.p).modPow(this.dmp1, this.p); let xq = x.mod(this.q).modPow(this.dmq1, this.q); while (xp.compareTo(xq) < 0) xp = xp.add(this.p); return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq); } /** * Return the PKCS#1 RSA decryption of "ctext". * "ctext" is an even-length hex string and the output is a plain string. * @param {string} ctext * @returns {string | null} */ decrypt(ctext) { let c = parseBigInt(ctext, 16); let m = this.doPrivate(c); if (m == null) return null; return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3); } /** * Return the PKCS#1 RSA decryption of "ctext". * "ctext" is a Base64-encoded string and the output is a plain string. * @param {string} ctext * @returns {string | null} */ decrypt_b64(ctext) { let h = b64tohex(ctext); if (h) return this.decrypt(h); else return null; } }
JavaScript
class Factory { /** * Get factory instance. * * @param {String} imageVar */ getInstance(imageVar, initParams) { const oThis = this; switch (imageVar) { case imageVarConstants.subjectImage: { return new oThis._subjectImageClass(initParams); } case imageVarConstants.actorImage: { return new oThis._actorImageClass(initParams); } default: { throw new Error(`Unrecognized imageVar: ${imageVar}`); } } } get _subjectImageClass() { return require(rootPrefix + '/lib/notification/response/imageVar/subjectImage'); } get _actorImageClass() { return require(rootPrefix + '/lib/notification/response/imageVar/actorImage'); } }
JavaScript
class GameEngine { // static canvas = document.getElementById("game").getContext("2d"); static canvas; static background; static offset = 0; static currentScene; /** * Start the game * (Add the objects to the canvas **after** this method.) * @param {Number} time Time between frame draws, in milliseconds. (Default 20) */ static initialize(time = 20, width = 1000, height = 500) { var canvas = document.getElementById("game"); canvas.width = width; canvas.height = height; this.width = width; this.height = height; this.canvas = canvas.getContext("2d"); setInterval(function () { EventHandler.fireEvent(UpdateEvent, new UpdateEvent()); }, time); EventHandler.registerHandler(UpdateEvent, onGUpdate); /* Handle the key events for the KeyHandler Class. */ window.addEventListener("keydown", function (e) { if (!KeyHandler.keysDown.includes(e.key)) KeyHandler.keysDown.push(e.key); }); window.addEventListener("keyup", function (e) { KeyHandler.keysDown.splice(KeyHandler.keysDown.indexOf(e.key), 1); }); window.addEventListener("mousedown", e => { var canvBound = canvas.getBoundingClientRect(); var x = e.clientX - canvBound.left; var y = e.clientY - canvBound.top; if (x < 0 || x > width) return; if (y < 0 || y > height) return; EventHandler.fireEvent(MouseDownEvent, new MouseDownEvent(x, y)); }); window.addEventListener("mousemove", e => { var canvBound = canvas.getBoundingClientRect(); var x = e.clientX - canvBound.left; var y = e.clientY - canvBound.top; if (x < 0 || x > width) return; if (y < 0 || y > height) return; EventHandler.fireEvent(MouseMoveEvent, new MouseMoveEvent(x, y)); }); var rect = new Rectangle(); rect.setPosition(0, 0); rect.setColor("white"); rect.setScale(this.width, this.height); GameEngine.background = rect; oldTime = Date.now(); } /** * Set the background of the game. * @param back The Canvas Object for the background. */ static setBackground(back) { GameEngine.background = back; } /** * Get the background of the game. * @returns The background as a Canvas Object */ static getBackground() { return GameEngine.background; } /** * Get Delta Time. */ static deltaTime = 0; static disable(clearScreen = false) { if (clearScreen) { GameEngine.canvas.clearRect(0, 0, document.getElementById("game").width, document.getElementById("game").height); } EventHandler.handlers = []; } /** * Set the scene. * @param {Scene} scene The scene to be rendered * @param {boolean} reset If you want the entire screen to be cleared when the defined scene is loaded. */ static setScene(scene, reset = false) { if (reset) GameObjects.clear(); else { for (let i in GameEngine.getCurrentScene().listOfObjects) { GameObjects.remove(GameEngine.getCurrentScene().listOfObjects[i]); } } for (let i in scene.listOfObjects) { GameObjects.add(scene.listOfObjects[i]); } GameEngine.currentScene = scene; } /** * Update the current scene after any additions or removals. * @param {boolean} reset If you want the entire screen to be cleared when the defined scene is loaded. */ static updateCurrentScene(reset = false) { if (reset) GameObjects.clear(); else { for (let i in GameEngine.getCurrentScene().listOfObjects) { GameObjects.remove(GameEngine.getCurrentScene().listOfObjects[i]); } } for (let i in GameEngine.getCurrentScene().listOfObjects) { GameObjects.add(GameEngine.getCurrentScene().listOfObjects[i]); } GameEngine.currentScene = scene; } /** * Get the current scene. */ static getCurrentScene() { return GameEngine.currentScene; } }
JavaScript
class GameObjects { static gameObjectsList = []; /** * Add an object to the render list. * @param {*} obj The Canvas Object to add. * @deprecated Use #add() instead. Will be removed in future update. */ static addGameObject(obj) { GameObjects.gameObjectsList.push(obj); } /** * Add an object ot the render list. * @param {*} obj The Canvas Object to add. * @deprecated Use ObjectManager instead. */ static add(obj) { GameObjects.gameObjectsList.push(obj); } /** * Remove an object from the render list. * @param {*} obj The object to remove. * @deprecated Use ObjectManager instead. */ static remove(obj) { GameObjects.gameObjectsList.splice(GameObjects.gameObjectsList.indexOf(obj), 1); } /** * Remove all of a type from the render list. * Example: Remove all Rectangles. * @param {*} type The type (Ex: Rectangle) * @deprecated Use ObjectManager instead. */ static removeType(type) { for (var i = 0; i < GameObjects.gameObjectsList.length; i++) { if (GameObjects.gameObjectsList[i] instanceof type) { GameObjects.remove(GameObjects.gameObjectsList[i]); } } } /** * @deprecated Use ObjectManager instead. */ static clear() { GameObjects.gameObjectsList = []; } /** * Get the list of game objects. * @deprecated Use ObjectManager instead. */ static getGameObjects() { return GameObjects.gameObjectsList; } }
JavaScript
class Rectangle { constructor() { this.scaleX = 20; this.scaleY = 20; this.color = "red"; this.posX = 0; this.posY = 0; } setScale(sx, sy) { this.scaleX = sx; this.scaleY = sy; return this; } setPosition(x, y) { this.posX = x; this.posY = y; return this; } setColor(c) { this.color = c; return this; } getPosition() { return new Vector(this.posX, this.posY); } getScale() { return new Vector(this.scaleX, this.scaleY); } getColor() { return this.color; } translateBy(x, y) { this.posX += x; this.posY += y; } draw() { if (this.getScale().getX() === undefined || this.getScale().getY() === undefined) { throw "Rectange scale not defined."; } if (this.getPosition().getX() === undefined || this.getPosition().getY() === undefined) { throw "Rectange position not defined."; } GameEngine.canvas.fillStyle = this.getColor(); GameEngine.canvas.fillRect(this.getPosition().getX(), this.getPosition().getY(), this.getScale().getX(), this.getScale().getY()); } }
JavaScript
class GText { /** * Create a text string! (Note: Text align must be set using the method.) * @param {String} txt The text. * @param {Number} x X Position * @param {Number} y Y Position * @param {String} color The color * @param {String} size The size * @param {String} font The font */ constructor(txt = "default", x = 0, y = 0, color = "black", size = "40px", font = "serif") { this.text = txt; this.posX = x; this.posY = y; this.color = color; this.size = size; this.font = font; this.textAlign = "center"; } setText(txt) { this.text = txt; return this; } setPosition(x, y) { this.posX = x; this.posY = y; return this; } setColor(c) { this.color = c; return this; } setSize(siz) { this.size = siz; return this; } setFont(fnt) { this.font = fnt; return this; } setTextAlign(ta) { this.textAlign = ta; return this; } getText() { return this.text; } getPosition() { return new Vector(this.posX, this.posY); } getColor() { return this.color; } getSize() { return this.size; } getFont() { return this.font; } getTextAlign() { return this.textAlign; } translateBy(x, y) { this.posX += x; this.posY += y; } draw() { GameEngine.canvas.font = this.size + " " + this.font; GameEngine.canvas.fillStyle = this.color; GameEngine.canvas.textAlign = this.textAlign; GameEngine.canvas.fillText(this.text, this.posX, this.posY); } }
JavaScript
class Sound { /** * @param {String} src The source sound file. */ constructor(src) { this.sound = document.createElement("audio"); this.sound.src = src; this.sound.setAttribute("preload", "auto"); this.sound.setAttribute("controls", "none"); this.sound.style.display = "none"; document.appendChild(this.sound); } play() { this.sound.play(); } stop() { this.sound.stop(); } }
JavaScript
class UpdateEvent { getDeltaTime() { return GameEngine.deltaTime; } }
JavaScript
class KeyHandler { static keysDown = []; static isKeyDown(key) { return KeyHandler.keysDown.includes(key); } }
JavaScript
class SiteModal extends _polymerElement.PolymerElement { /** * Store the tag name to make it easier to obtain directly. * @notice function name must be here for tooling to operate correctly */ static get tag() { return "site-modal"; } constructor() { super(); new Promise((res, rej) => _require.default(["../../../../../@polymer/paper-tooltip/paper-tooltip.js"], res, rej)); } // render function static get template() { return _polymerElement.html` <style> :host { display: block; } paper-icon-button { @apply --site-modal-icon; } paper-tooltip { @apply --site-modal-tooltip; } simple-modal-template { @apply --site-modal-modal; } </style> <paper-icon-button disabled$="[[disabled]]" id="btn" icon="[[icon]]" title="[[buttonLabel]]" ></paper-icon-button> <paper-tooltip for="btn" position="[[position]]" offset="14"> [[buttonLabel]] </paper-tooltip> <simple-modal-template id="smt" title="[[title]]"> <div id="content" slot="content"></div> </simple-modal-template> `; } static get properties() { return { disabled: { type: Boolean, reflectToAttribute: true }, title: { type: String, value: "Dialog" }, icon: { type: String, value: "icons:menu" }, buttonLabel: { type: String, value: "Open dialog" }, position: { type: String, value: "bottom" } }; } connectedCallback() { super.connectedCallback(); this.$.smt.associateEvents(this.$.btn); const nodes = (0, _polymerDom.dom)(this).getEffectiveChildNodes(); for (var i in nodes) { this.$.content.appendChild(nodes[i]); } } disconnectedCallback() { super.disconnectedCallback(); } }
JavaScript
class ModifierCalculator extends CharacterTrait { constructor(characterTrait) { super(characterTrait.trait, characterTrait.listKey, characterTrait.getCharacter); this.characterTrait = characterTrait; this.modifiers = this._getItemTotalModifiers(this.characterTrait.trait).concat(this._getItemTotalModifiers(this.characterTrait.parentTrait)); } cost() { return this.characterTrait.cost(); } costMultiplier() { return this.characterTrait.costMultiplier(); } activeCost() { let activeCost = this.cost() * (1 + this.advantages().reduce((a, b) => a + b.cost, 0)); return common.roundInPlayersFavor(activeCost); } realCost() { let realCost = common.roundInPlayersFavor(this.activeCost() / (1 - this.limitations().reduce((a, b) => a + b.cost, 0))); if (this.characterTrait.parentTrait !== undefined && SKILL_ENHANCERS.includes(this.characterTrait.parentTrait.xmlid.toUpperCase())) { realCost = realCost - 1 <= 0 ? 1 : realCost - 1; } return realCost; } label() { return this.characterTrait.label(); } attributes() { return this.characterTrait.attributes(); } definition() { return this.characterTrait.definition(); } roll() { return this.characterTrait.roll(); } advantages() { return this.modifiers.filter(m => m.cost >= 0); } limitations() { return this.modifiers.filter(m => m.cost < 0); } _getItemTotalModifiers(trait) { let totalModifiers = []; let modifierCost = 0; if (trait === null || trait === undefined || !trait.hasOwnProperty('modifier')) { return totalModifiers; } if (trait.hasOwnProperty('modifier')) { let decorated = null; if (Array.isArray(trait.modifier)) { for (let modifier of trait.modifier) { decorated = modifierDecorator.decorate(modifier, trait); totalModifiers.push({ label: decorated.label(), cost: decorated.cost(), }); } } else { decorated = modifierDecorator.decorate(trait.modifier, trait); totalModifiers.push({ label: decorated.label(), cost: decorated.cost(), }); } } return totalModifiers; } }
JavaScript
class HuglaConfig { constructor() { this.config = {}; } /** * Merges given object into config * @param {object} config Configuration object to merge */ addConfig(config) { this.config = Object.assign(this.config, config); } /** * Merges env variables into config */ addEnv() { this.config = Object.assign(this.config, process.env); } /** * Merges given js or json file contents into config * * @param {string} path Path to config file (json or js) */ addFile(path) { const fileConfig = require(path); this.config = Object.assign(this.config, fileConfig); } }
JavaScript
class CatTwo extends Animal { constructor(name, usesLitter) { super(name); this._usesLitter = usesLitter; } }
JavaScript
class HospitalEmployee { constructor(name) { this._name = name; this._remainingVacationDays = 20; } get name() { return this._name; } get remainingVacationDays () { return this._remainingVacationDays ; } takeVacationDays(daysOff){ this._remainingVacationDays -= daysOff; } static generatePassword() { const randonNumber = Math.floor(Math.random() * 10000); return randonNumber; } }
JavaScript
class User { constructor(fName, lName, age) { this.fName = fName; this.lName = lName; this.age = age; } getInfo() { return `Second Example: I'm ${this.fName} ${this.lName} of ${this.age} yrs old.` } }
JavaScript
class User1 extends User { constructor(fName, lName, age, city) { super(fName, lName, age); this.city = city; } getMoreInfo() { return `Third Example: I'm ${this.fName} ${this.lName} of ${this.age} yrs from ${this.city}`; } }
JavaScript
class BagReader { constructor(filelike) { this.file = filelike; this._lastChunkInfo = undefined; this._lastReadResult = undefined; } // reads the header block from the rosbag file // generally you call this first // because you need the header information to call readConnectionsAndChunkInfo // the callback is in the form (err: Error?, header: BagHeader?) => void readHeader(callback) { const offset = 13; this.file.read(0, offset, (error, buffer) => { if (this.file.size() < offset) { return callback(new Error("Missing file header.")); } if (error) { return callback(error); } if (buffer.toString() !== "#ROSBAG V2.0\n") { return callback(new Error("Cannot identify bag format.")); } return this.file.read(offset, BagReader.HEADER_READAHEAD, (error, buffer) => { if (error) { return callback(error); } const read = buffer.length; if (read < 8) { return callback(new Error(`Record at position ${offset} is truncated.`)); } const headerLength = buffer.readInt32LE(0); if (read < headerLength + 8) { return callback(new Error(`Record at position ${offset} header too large: ${headerLength}.`)); } const header = this.readRecordFromBuffer(buffer, offset); return callback(null, header); }); }); } // reads connection and chunk information from the bag // you'll generally call this after reading the header so you can get connection metadata // and chunkInfos which allow you to seek to individual chunks & read them // the callback is in the form: // (err: Error?, response?: { connections: Array<Connection>, chunkInfos: Array<ChunkInfo> }) readConnectionsAndChunkInfo(fileOffset, connectionCount, chunkCount, callback) { this.file.read(fileOffset, this.file.size() - fileOffset, (err, buffer) => { if (err) { return callback(err); } const connections = this.readRecordsFromBuffer(buffer, connectionCount, fileOffset); const connectionBlockLength = connections[connectionCount - 1].end - connections[0].offset; const chunkInfos = this.readRecordsFromBuffer( buffer.slice(connectionBlockLength), chunkCount, fileOffset + connectionBlockLength ); if (chunkCount > 0) { for (let i = 0; i < chunkCount - 1; i++) { chunkInfos[i].nextChunk = chunkInfos[i + 1]; } chunkInfos[chunkCount - 1].nextChunk = null; } return callback(null, { connections, chunkInfos }); }); } // read individual raw messages from the bag at a given chunk // filters to a specific set of connection ids, start time, & end time // the callback is in the form (err: Error?, response?: Array<Record>) // generally the records will be of type MessageData readChunkMessages(chunkInfo, connections, startTime, endTime, decompress, each, callback) { const start = startTime || new Time(0, 0); const end = endTime || new Time(Number.MAX_VALUE, Number.MAX_VALUE); const conns = connections || chunkInfo.connections.map((connection) => { return connection.conn; }); this.readChunk(chunkInfo, decompress, (error, result) => { if (error) { return callback(error); } const chunk = result.chunk; const indices = {}; result.indices.forEach((index) => { indices[index.conn] = index; }); const presentConnections = conns.filter((conn) => { return indices[conn] !== undefined; }); const iterables = presentConnections.map((conn) => { return indices[conn].indices[Symbol.iterator](); }); const iter = nmerge((a, b) => Time.compare(a.time, b.time), ...iterables); const entries = []; let item = iter.next(); while (!item.done) { const { value } = item; item = iter.next(); if (Time.isGreaterThan(start, value.time)) { continue; } if (Time.isGreaterThan(value.time, end)) { break; } entries.push(value); } const messages = entries.map((entry, i) => { const msg = this.readRecordFromBuffer(chunk.data.slice(entry.offset), chunk.dataOffset); return (each && each(msg, i)) || msg; }); return callback(null, messages); }); } // reads a single chunk record && its index records given a chunkInfo readChunk(chunkInfo, decompress, callback) { // if we're reading the same chunk a second time return the cached version // to avoid doing decompression on the same chunk multiple times which is expensive if (chunkInfo === this._lastChunkInfo) { // always callback async, even if we have the result // https://oren.github.io/blog/zalgo.html return setImmediate(() => callback(null, this._lastReadResult)); } this._lastChunkInfo = chunkInfo; const { nextChunk } = chunkInfo; const readLength = nextChunk ? nextChunk.chunkPosition - chunkInfo.chunkPosition : this.file.size() - chunkInfo.chunkPosition; this.file.read(chunkInfo.chunkPosition, readLength, (err, buffer) => { if (err) { return callback(err); } const chunk = this.readRecordFromBuffer(buffer, chunkInfo.chunkPosition); const { compression } = chunk; if (compression !== "none") { const decompressFn = decompress[compression]; if (!decompressFn) { return callback(new Error(`Unsupported compression type ${chunk.compression}`)); } const result = decompressFn(chunk.data); chunk.data = result; } const indices = this.readRecordsFromBuffer( buffer.slice(chunk.length), chunkInfo.count, chunkInfo.chunkPosition + chunk.length ); this._lastReadResult = { chunk, indices }; return callback(null, this._lastReadResult); }); } // reads count records from a buffer starting at fileOffset readRecordsFromBuffer(buffer, count, fileOffset) { const records = []; let bufferOffset = 0; for (let i = 0; i < count; i++) { const record = this.readRecordFromBuffer(buffer.slice(bufferOffset), fileOffset + bufferOffset); bufferOffset += record.end - record.offset; records.push(record); } return records; } // read an individual record from a buffer readRecordFromBuffer(buffer, fileOffset) { const headerLength = buffer.readInt32LE(0); const record = parseHeader(buffer.slice(4, 4 + headerLength)); const dataOffset = 4 + headerLength + 4; const dataLength = buffer.readInt32LE(4 + headerLength); const data = buffer.slice(dataOffset, dataOffset + dataLength); record.parseData(data); record.offset = fileOffset; record.dataOffset = record.offset + 4 + headerLength + 4; record.end = record.dataOffset + dataLength; record.length = record.end - record.offset; return record; } }
JavaScript
class Dialog extends View { /** * @param {!ViewName} name View name of the dialog. */ constructor(name) { super(name, true); /** * @type {!HTMLButtonElement} * @private */ this.positiveButton_ = assertInstanceof( this.root.querySelector('.dialog-positive-button'), HTMLButtonElement); /** * @type {!HTMLButtonElement} * @private */ this.negativeButton_ = assertInstanceof( this.root.querySelector('.dialog-negative-button'), HTMLButtonElement); /** * @type {!HTMLElement} * @private */ this.messageHolder_ = assertInstanceof( this.root.querySelector('.dialog-msg-holder'), HTMLElement); this.positiveButton_.addEventListener('click', () => this.leave(true)); if (this.negativeButton_) { this.negativeButton_.addEventListener('click', () => this.leave()); } } /** * @override */ entering({message, cancellable = false} = {}) { message = assertString(message); this.messageHolder_.textContent = message; if (this.negativeButton_) { this.negativeButton_.hidden = !cancellable; } } /** * @override */ focus() { this.positiveButton_.focus(); } }
JavaScript
class CheckboxLegend extends React.Component { constructor(props) { super(props); this.state = { initialized: false, selected: [] //[name1, name2, ...] } ; } componentWillReceiveProps(nextProps, nextContext) { if(nextProps.palette && this.state.initialized === false) { let selected = Object.keys(nextProps.palette); this.setState({initialized: true, selected: selected}, () => this.props.onClick(selected)); } } /** * onClick function for a checkbox entry * @param key string name of the entry that was clicked. */ clickCallback(key){ let checked = this.state.selected.indexOf(key) !== -1; if(!checked) { //Add to selected let selected = this.state.selected; selected.push(key); this.setState({selected: selected}, () => this.props.onClick(selected)); } else { //Remove from selected let selected = this.state.selected; selected.splice(selected.indexOf(key),1); this.setState({selected: selected}, () => this.props.onClick(selected)); } } selectAllAuthors(){ let ticked = Object.keys(this.props.palette).length === this.state.selected.length; if(ticked){ this.setState({selected: []}, () => this.props.onClick([])); }else{ let selected = Object.keys(this.props.palette); this.setState({selected: selected}, () => this.props.onClick(selected)); } } render() { let items = []; if(this.state.initialized) { let otherCommitters = this.props.otherCommitters; _.each(Object.keys(this.props.palette), (key) => { let text = key; if(text === 'others' && otherCommitters) text = '' + otherCommitters + ' Others'; if (this.state.selected.indexOf(key) > -1) { items.push(<CheckboxLegendLine id={key} key={key} text={text} color={this.props.palette[key]} checked={true} onClick={this.clickCallback.bind(this)} split={this.props.split}/>); } else { items.push(<CheckboxLegendLine id={key} key={key} text={text} color={this.props.palette[key]} checked={false} onClick={this.clickCallback.bind(this)} split={this.props.split}/>); } }); } let loading = ( <p>Loading... <i className="fas fa-spinner fa-pulse"/></p> ); let checked = false; if(this.state.selected && this.props.palette){ checked = Object.keys(this.props.palette).length === this.state.selected.length; } let explanation; if(this.props.palette) { if (this.props.split) { let keys = Object.keys(this.props.palette); let color1 = chroma(this.props.palette[keys[0]]).hex(); let color2 = chroma(this.props.palette[keys[0]]).darken(0.5).hex(); explanation = <LegendCompact text="Additions | Deletions (# lines per author)" color={color1} color2={color2}/> } else { let keys = Object.keys(this.props.palette); let color = this.props.palette[keys[0]]; explanation = <LegendCompact text="Number of commits (per author)" color={color}/> } } return (<div> <label className="label"><input type="checkbox" checked={checked} onChange={this.selectAllAuthors.bind(this)}/>{this.props.title}</label> {explanation} <div className={styles.legend}> {(items.length === 0 || items)} {(items.length > 0 || loading)} </div> </div>); } }
JavaScript
class Matrix extends superCtor { static get [Symbol.species]() { return this; } /** * Constructs a Matrix with the chosen dimensions from a 1D array * @param {number} newRows - Number of rows * @param {number} newColumns - Number of columns * @param {Array} newData - A 1D array containing data for the matrix * @return {Matrix} - The new matrix */ static from1DArray(newRows, newColumns, newData) { var length = newRows * newColumns; if (length !== newData.length) { throw new RangeError('Data length does not match given dimensions'); } var newMatrix = new this(newRows, newColumns); for (var row = 0; row < newRows; row++) { for (var column = 0; column < newColumns; column++) { newMatrix.set(row, column, newData[row * newColumns + column]); } } return newMatrix; } /** * Creates a row vector, a matrix with only one row. * @param {Array} newData - A 1D array containing data for the vector * @return {Matrix} - The new matrix */ static rowVector(newData) { var vector = new this(1, newData.length); for (var i = 0; i < newData.length; i++) { vector.set(0, i, newData[i]); } return vector; } /** * Creates a column vector, a matrix with only one column. * @param {Array} newData - A 1D array containing data for the vector * @return {Matrix} - The new matrix */ static columnVector(newData) { var vector = new this(newData.length, 1); for (var i = 0; i < newData.length; i++) { vector.set(i, 0, newData[i]); } return vector; } /** * Creates an empty matrix with the given dimensions. Values will be undefined. Same as using new Matrix(rows, columns). * @param {number} rows - Number of rows * @param {number} columns - Number of columns * @return {Matrix} - The new matrix */ static empty(rows, columns) { return new this(rows, columns); } /** * Creates a matrix with the given dimensions. Values will be set to zero. * @param {number} rows - Number of rows * @param {number} columns - Number of columns * @return {Matrix} - The new matrix */ static zeros(rows, columns) { return this.empty(rows, columns).fill(0); } /** * Creates a matrix with the given dimensions. Values will be set to one. * @param {number} rows - Number of rows * @param {number} columns - Number of columns * @return {Matrix} - The new matrix */ static ones(rows, columns) { return this.empty(rows, columns).fill(1); } /** * Creates a matrix with the given dimensions. Values will be randomly set. * @param {number} rows - Number of rows * @param {number} columns - Number of columns * @param {function} [rng=Math.random] - Random number generator * @return {Matrix} The new matrix */ static rand(rows, columns, rng) { if (rng === undefined) rng = Math.random; var matrix = this.empty(rows, columns); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { matrix.set(i, j, rng()); } } return matrix; } /** * Creates a matrix with the given dimensions. Values will be random integers. * @param {number} rows - Number of rows * @param {number} columns - Number of columns * @param {number} [maxValue=1000] - Maximum value * @param {function} [rng=Math.random] - Random number generator * @return {Matrix} The new matrix */ static randInt(rows, columns, maxValue, rng) { if (maxValue === undefined) maxValue = 1000; if (rng === undefined) rng = Math.random; var matrix = this.empty(rows, columns); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { var value = Math.floor(rng() * maxValue); matrix.set(i, j, value); } } return matrix; } /** * Creates an identity matrix with the given dimension. Values of the diagonal will be 1 and others will be 0. * @param {number} rows - Number of rows * @param {number} [columns=rows] - Number of columns * @param {number} [value=1] - Value to fill the diagonal with * @return {Matrix} - The new identity matrix */ static eye(rows, columns, value) { if (columns === undefined) columns = rows; if (value === undefined) value = 1; var min = Math.min(rows, columns); var matrix = this.zeros(rows, columns); for (var i = 0; i < min; i++) { matrix.set(i, i, value); } return matrix; } /** * Creates a diagonal matrix based on the given array. * @param {Array} data - Array containing the data for the diagonal * @param {number} [rows] - Number of rows (Default: data.length) * @param {number} [columns] - Number of columns (Default: rows) * @return {Matrix} - The new diagonal matrix */ static diag(data, rows, columns) { var l = data.length; if (rows === undefined) rows = l; if (columns === undefined) columns = rows; var min = Math.min(l, rows, columns); var matrix = this.zeros(rows, columns); for (var i = 0; i < min; i++) { matrix.set(i, i, data[i]); } return matrix; } /** * Returns a matrix whose elements are the minimum between matrix1 and matrix2 * @param {Matrix} matrix1 * @param {Matrix} matrix2 * @return {Matrix} */ static min(matrix1, matrix2) { matrix1 = this.checkMatrix(matrix1); matrix2 = this.checkMatrix(matrix2); var rows = matrix1.rows; var columns = matrix1.columns; var result = new this(rows, columns); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j))); } } return result; } /** * Returns a matrix whose elements are the maximum between matrix1 and matrix2 * @param {Matrix} matrix1 * @param {Matrix} matrix2 * @return {Matrix} */ static max(matrix1, matrix2) { matrix1 = this.checkMatrix(matrix1); matrix2 = this.checkMatrix(matrix2); var rows = matrix1.rows; var columns = matrix1.columns; var result = new this(rows, columns); for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j))); } } return result; } /** * Check that the provided value is a Matrix and tries to instantiate one if not * @param {*} value - The value to check * @return {Matrix} */ static checkMatrix(value) { return Matrix.isMatrix(value) ? value : new this(value); } /** * Returns true if the argument is a Matrix, false otherwise * @param {*} value - The value to check * @return {boolean} */ static isMatrix(value) { return value != null && value.klass === 'Matrix'; } /** * @prop {number} size - The number of elements in the matrix. */ get size() { return this.rows * this.columns; } /** * Applies a callback for each element of the matrix. The function is called in the matrix (this) context. * @param {function} callback - Function that will be called with two parameters : i (row) and j (column) * @return {Matrix} this */ apply(callback) { if (typeof callback !== 'function') { throw new TypeError('callback must be a function'); } var ii = this.rows; var jj = this.columns; for (var i = 0; i < ii; i++) { for (var j = 0; j < jj; j++) { callback.call(this, i, j); } } return this; } /** * Returns a new 1D array filled row by row with the matrix values * @return {Array} */ to1DArray() { var array = new Array(this.size); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { array[i * this.columns + j] = this.get(i, j); } } return array; } /** * Returns a 2D array containing a copy of the data * @return {Array} */ to2DArray() { var copy = new Array(this.rows); for (var i = 0; i < this.rows; i++) { copy[i] = new Array(this.columns); for (var j = 0; j < this.columns; j++) { copy[i][j] = this.get(i, j); } } return copy; } /** * @return {boolean} true if the matrix has one row */ isRowVector() { return this.rows === 1; } /** * @return {boolean} true if the matrix has one column */ isColumnVector() { return this.columns === 1; } /** * @return {boolean} true if the matrix has one row or one column */ isVector() { return this.rows === 1 || this.columns === 1; } /** * @return {boolean} true if the matrix has the same number of rows and columns */ isSquare() { return this.rows === this.columns; } /** * @return {boolean} true if the matrix is square and has the same values on both sides of the diagonal */ isSymmetric() { if (this.isSquare()) { for (var i = 0; i < this.rows; i++) { for (var j = 0; j <= i; j++) { if (this.get(i, j) !== this.get(j, i)) { return false; } } } return true; } return false; } /** * Sets a given element of the matrix. mat.set(3,4,1) is equivalent to mat[3][4]=1 * @abstract * @param {number} rowIndex - Index of the row * @param {number} columnIndex - Index of the column * @param {number} value - The new value for the element * @return {Matrix} this */ set(rowIndex, columnIndex, value) { // eslint-disable-line no-unused-vars throw new Error('set method is unimplemented'); } /** * Returns the given element of the matrix. mat.get(3,4) is equivalent to matrix[3][4] * @abstract * @param {number} rowIndex - Index of the row * @param {number} columnIndex - Index of the column * @return {number} */ get(rowIndex, columnIndex) { // eslint-disable-line no-unused-vars throw new Error('get method is unimplemented'); } /** * Creates a new matrix that is a repetition of the current matrix. New matrix has rowRep times the number of * rows of the matrix, and colRep times the number of columns of the matrix * @param {number} rowRep - Number of times the rows should be repeated * @param {number} colRep - Number of times the columns should be re * @return {Matrix} * @example * var matrix = new Matrix([[1,2]]); * matrix.repeat(2); // [[1,2],[1,2]] */ repeat(rowRep, colRep) { rowRep = rowRep || 1; colRep = colRep || 1; var matrix = new this.constructor[Symbol.species](this.rows * rowRep, this.columns * colRep); for (var i = 0; i < rowRep; i++) { for (var j = 0; j < colRep; j++) { matrix.setSubMatrix(this, this.rows * i, this.columns * j); } } return matrix; } /** * Fills the matrix with a given value. All elements will be set to this value. * @param {number} value - New value * @return {Matrix} this */ fill(value) { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, value); } } return this; } /** * Negates the matrix. All elements will be multiplied by (-1) * @return {Matrix} this */ neg() { return this.mulS(-1); } /** * Returns a new array from the given row index * @param {number} index - Row index * @return {Array} */ getRow(index) { (0, _util.checkRowIndex)(this, index); var row = new Array(this.columns); for (var i = 0; i < this.columns; i++) { row[i] = this.get(index, i); } return row; } /** * Returns a new row vector from the given row index * @param {number} index - Row index * @return {Matrix} */ getRowVector(index) { return this.constructor.rowVector(this.getRow(index)); } /** * Sets a row at the given index * @param {number} index - Row index * @param {Array|Matrix} array - Array or vector * @return {Matrix} this */ setRow(index, array) { (0, _util.checkRowIndex)(this, index); array = (0, _util.checkRowVector)(this, array); for (var i = 0; i < this.columns; i++) { this.set(index, i, array[i]); } return this; } /** * Swaps two rows * @param {number} row1 - First row index * @param {number} row2 - Second row index * @return {Matrix} this */ swapRows(row1, row2) { (0, _util.checkRowIndex)(this, row1); (0, _util.checkRowIndex)(this, row2); for (var i = 0; i < this.columns; i++) { var temp = this.get(row1, i); this.set(row1, i, this.get(row2, i)); this.set(row2, i, temp); } return this; } /** * Returns a new array from the given column index * @param {number} index - Column index * @return {Array} */ getColumn(index) { (0, _util.checkColumnIndex)(this, index); var column = new Array(this.rows); for (var i = 0; i < this.rows; i++) { column[i] = this.get(i, index); } return column; } /** * Returns a new column vector from the given column index * @param {number} index - Column index * @return {Matrix} */ getColumnVector(index) { return this.constructor.columnVector(this.getColumn(index)); } /** * Sets a column at the given index * @param {number} index - Column index * @param {Array|Matrix} array - Array or vector * @return {Matrix} this */ setColumn(index, array) { (0, _util.checkColumnIndex)(this, index); array = (0, _util.checkColumnVector)(this, array); for (var i = 0; i < this.rows; i++) { this.set(i, index, array[i]); } return this; } /** * Swaps two columns * @param {number} column1 - First column index * @param {number} column2 - Second column index * @return {Matrix} this */ swapColumns(column1, column2) { (0, _util.checkColumnIndex)(this, column1); (0, _util.checkColumnIndex)(this, column2); for (var i = 0; i < this.rows; i++) { var temp = this.get(i, column1); this.set(i, column1, this.get(i, column2)); this.set(i, column2, temp); } return this; } /** * Adds the values of a vector to each row * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ addRowVector(vector) { vector = (0, _util.checkRowVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) + vector[j]); } } return this; } /** * Subtracts the values of a vector from each row * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ subRowVector(vector) { vector = (0, _util.checkRowVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) - vector[j]); } } return this; } /** * Multiplies the values of a vector with each row * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ mulRowVector(vector) { vector = (0, _util.checkRowVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) * vector[j]); } } return this; } /** * Divides the values of each row by those of a vector * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ divRowVector(vector) { vector = (0, _util.checkRowVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) / vector[j]); } } return this; } /** * Adds the values of a vector to each column * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ addColumnVector(vector) { vector = (0, _util.checkColumnVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) + vector[i]); } } return this; } /** * Subtracts the values of a vector from each column * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ subColumnVector(vector) { vector = (0, _util.checkColumnVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) - vector[i]); } } return this; } /** * Multiplies the values of a vector with each column * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ mulColumnVector(vector) { vector = (0, _util.checkColumnVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) * vector[i]); } } return this; } /** * Divides the values of each column by those of a vector * @param {Array|Matrix} vector - Array or vector * @return {Matrix} this */ divColumnVector(vector) { vector = (0, _util.checkColumnVector)(this, vector); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { this.set(i, j, this.get(i, j) / vector[i]); } } return this; } /** * Multiplies the values of a row with a scalar * @param {number} index - Row index * @param {number} value * @return {Matrix} this */ mulRow(index, value) { (0, _util.checkRowIndex)(this, index); for (var i = 0; i < this.columns; i++) { this.set(index, i, this.get(index, i) * value); } return this; } /** * Multiplies the values of a column with a scalar * @param {number} index - Column index * @param {number} value * @return {Matrix} this */ mulColumn(index, value) { (0, _util.checkColumnIndex)(this, index); for (var i = 0; i < this.rows; i++) { this.set(i, index, this.get(i, index) * value); } return this; } /** * Returns the maximum value of the matrix * @return {number} */ max() { var v = this.get(0, 0); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { if (this.get(i, j) > v) { v = this.get(i, j); } } } return v; } /** * Returns the index of the maximum value * @return {Array} */ maxIndex() { var v = this.get(0, 0); var idx = [0, 0]; for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { if (this.get(i, j) > v) { v = this.get(i, j); idx[0] = i; idx[1] = j; } } } return idx; } /** * Returns the minimum value of the matrix * @return {number} */ min() { var v = this.get(0, 0); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { if (this.get(i, j) < v) { v = this.get(i, j); } } } return v; } /** * Returns the index of the minimum value * @return {Array} */ minIndex() { var v = this.get(0, 0); var idx = [0, 0]; for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { if (this.get(i, j) < v) { v = this.get(i, j); idx[0] = i; idx[1] = j; } } } return idx; } /** * Returns the maximum value of one row * @param {number} row - Row index * @return {number} */ maxRow(row) { (0, _util.checkRowIndex)(this, row); var v = this.get(row, 0); for (var i = 1; i < this.columns; i++) { if (this.get(row, i) > v) { v = this.get(row, i); } } return v; } /** * Returns the index of the maximum value of one row * @param {number} row - Row index * @return {Array} */ maxRowIndex(row) { (0, _util.checkRowIndex)(this, row); var v = this.get(row, 0); var idx = [row, 0]; for (var i = 1; i < this.columns; i++) { if (this.get(row, i) > v) { v = this.get(row, i); idx[1] = i; } } return idx; } /** * Returns the minimum value of one row * @param {number} row - Row index * @return {number} */ minRow(row) { (0, _util.checkRowIndex)(this, row); var v = this.get(row, 0); for (var i = 1; i < this.columns; i++) { if (this.get(row, i) < v) { v = this.get(row, i); } } return v; } /** * Returns the index of the maximum value of one row * @param {number} row - Row index * @return {Array} */ minRowIndex(row) { (0, _util.checkRowIndex)(this, row); var v = this.get(row, 0); var idx = [row, 0]; for (var i = 1; i < this.columns; i++) { if (this.get(row, i) < v) { v = this.get(row, i); idx[1] = i; } } return idx; } /** * Returns the maximum value of one column * @param {number} column - Column index * @return {number} */ maxColumn(column) { (0, _util.checkColumnIndex)(this, column); var v = this.get(0, column); for (var i = 1; i < this.rows; i++) { if (this.get(i, column) > v) { v = this.get(i, column); } } return v; } /** * Returns the index of the maximum value of one column * @param {number} column - Column index * @return {Array} */ maxColumnIndex(column) { (0, _util.checkColumnIndex)(this, column); var v = this.get(0, column); var idx = [0, column]; for (var i = 1; i < this.rows; i++) { if (this.get(i, column) > v) { v = this.get(i, column); idx[0] = i; } } return idx; } /** * Returns the minimum value of one column * @param {number} column - Column index * @return {number} */ minColumn(column) { (0, _util.checkColumnIndex)(this, column); var v = this.get(0, column); for (var i = 1; i < this.rows; i++) { if (this.get(i, column) < v) { v = this.get(i, column); } } return v; } /** * Returns the index of the minimum value of one column * @param {number} column - Column index * @return {Array} */ minColumnIndex(column) { (0, _util.checkColumnIndex)(this, column); var v = this.get(0, column); var idx = [0, column]; for (var i = 1; i < this.rows; i++) { if (this.get(i, column) < v) { v = this.get(i, column); idx[0] = i; } } return idx; } /** * Returns an array containing the diagonal values of the matrix * @return {Array} */ diag() { var min = Math.min(this.rows, this.columns); var diag = new Array(min); for (var i = 0; i < min; i++) { diag[i] = this.get(i, i); } return diag; } /** * Returns the sum by the argument given, if no argument given, * it returns the sum of all elements of the matrix. * @param {string} by - sum by 'row' or 'column'. * @return {Matrix|number} */ sum(by) { switch (by) { case 'row': return (0, _util.sumByRow)(this); case 'column': return (0, _util.sumByColumn)(this); default: return (0, _util.sumAll)(this); } } /** * Returns the mean of all elements of the matrix * @return {number} */ mean() { return this.sum() / this.size; } /** * Returns the product of all elements of the matrix * @return {number} */ prod() { var prod = 1; for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { prod *= this.get(i, j); } } return prod; } /** * Returns the norm of a matrix. * @param {string} type - "frobenius" (default) or "max" return resp. the Frobenius norm and the max norm. * @return {number} */ norm(type = 'frobenius') { var result = 0; if (type === 'max') { return this.max(); } else if (type === 'frobenius') { for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { result = result + this.get(i, j) * this.get(i, j); } } return Math.sqrt(result); } else { throw new RangeError(`unknown norm type: ${type}`); } } /** * Computes the cumulative sum of the matrix elements (in place, row by row) * @return {Matrix} this */ cumulativeSum() { var sum = 0; for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { sum += this.get(i, j); this.set(i, j, sum); } } return this; } /** * Computes the dot (scalar) product between the matrix and another * @param {Matrix} vector2 vector * @return {number} */ dot(vector2) { if (Matrix.isMatrix(vector2)) vector2 = vector2.to1DArray(); var vector1 = this.to1DArray(); if (vector1.length !== vector2.length) { throw new RangeError('vectors do not have the same size'); } var dot = 0; for (var i = 0; i < vector1.length; i++) { dot += vector1[i] * vector2[i]; } return dot; } /** * Returns the matrix product between this and other * @param {Matrix} other * @return {Matrix} */ mmul(other) { other = this.constructor.checkMatrix(other); if (this.columns !== other.rows) { // eslint-disable-next-line no-console console.warn('Number of columns of left matrix are not equal to number of rows of right matrix.'); } var m = this.rows; var n = this.columns; var p = other.columns; var result = new this.constructor[Symbol.species](m, p); var Bcolj = new Array(n); for (var j = 0; j < p; j++) { for (var k = 0; k < n; k++) { Bcolj[k] = other.get(k, j); } for (var i = 0; i < m; i++) { var s = 0; for (k = 0; k < n; k++) { s += this.get(i, k) * Bcolj[k]; } result.set(i, j, s); } } return result; } strassen2x2(other) { var result = new this.constructor[Symbol.species](2, 2); var a11 = this.get(0, 0); var b11 = other.get(0, 0); var a12 = this.get(0, 1); var b12 = other.get(0, 1); var a21 = this.get(1, 0); var b21 = other.get(1, 0); var a22 = this.get(1, 1); var b22 = other.get(1, 1); // Compute intermediate values. var m1 = (a11 + a22) * (b11 + b22); var m2 = (a21 + a22) * b11; var m3 = a11 * (b12 - b22); var m4 = a22 * (b21 - b11); var m5 = (a11 + a12) * b22; var m6 = (a21 - a11) * (b11 + b12); var m7 = (a12 - a22) * (b21 + b22); // Combine intermediate values into the output. var c00 = m1 + m4 - m5 + m7; var c01 = m3 + m5; var c10 = m2 + m4; var c11 = m1 - m2 + m3 + m6; result.set(0, 0, c00); result.set(0, 1, c01); result.set(1, 0, c10); result.set(1, 1, c11); return result; } strassen3x3(other) { var result = new this.constructor[Symbol.species](3, 3); var a00 = this.get(0, 0); var a01 = this.get(0, 1); var a02 = this.get(0, 2); var a10 = this.get(1, 0); var a11 = this.get(1, 1); var a12 = this.get(1, 2); var a20 = this.get(2, 0); var a21 = this.get(2, 1); var a22 = this.get(2, 2); var b00 = other.get(0, 0); var b01 = other.get(0, 1); var b02 = other.get(0, 2); var b10 = other.get(1, 0); var b11 = other.get(1, 1); var b12 = other.get(1, 2); var b20 = other.get(2, 0); var b21 = other.get(2, 1); var b22 = other.get(2, 2); var m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11; var m2 = (a00 - a10) * (-b01 + b11); var m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22); var m4 = (-a00 + a10 + a11) * (b00 - b01 + b11); var m5 = (a10 + a11) * (-b00 + b01); var m6 = a00 * b00; var m7 = (-a00 + a20 + a21) * (b00 - b02 + b12); var m8 = (-a00 + a20) * (b02 - b12); var m9 = (a20 + a21) * (-b00 + b02); var m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12; var m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21); var m12 = (-a02 + a21 + a22) * (b11 + b20 - b21); var m13 = (a02 - a22) * (b11 - b21); var m14 = a02 * b20; var m15 = (a21 + a22) * (-b20 + b21); var m16 = (-a02 + a11 + a12) * (b12 + b20 - b22); var m17 = (a02 - a12) * (b12 - b22); var m18 = (a11 + a12) * (-b20 + b22); var m19 = a01 * b10; var m20 = a12 * b21; var m21 = a10 * b02; var m22 = a20 * b01; var m23 = a22 * b22; var c00 = m6 + m14 + m19; var c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15; var c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18; var c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17; var c11 = m2 + m4 + m5 + m6 + m20; var c12 = m14 + m16 + m17 + m18 + m21; var c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14; var c21 = m12 + m13 + m14 + m15 + m22; var c22 = m6 + m7 + m8 + m9 + m23; result.set(0, 0, c00); result.set(0, 1, c01); result.set(0, 2, c02); result.set(1, 0, c10); result.set(1, 1, c11); result.set(1, 2, c12); result.set(2, 0, c20); result.set(2, 1, c21); result.set(2, 2, c22); return result; } /** * Returns the matrix product between x and y. More efficient than mmul(other) only when we multiply squared matrix and when the size of the matrix is > 1000. * @param {Matrix} y * @return {Matrix} */ mmulStrassen(y) { var x = this.clone(); var r1 = x.rows; var c1 = x.columns; var r2 = y.rows; var c2 = y.columns; if (c1 !== r2) { // eslint-disable-next-line no-console console.warn(`Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`); } // Put a matrix into the top left of a matrix of zeros. // `rows` and `cols` are the dimensions of the output matrix. function embed(mat, rows, cols) { var r = mat.rows; var c = mat.columns; if (r === rows && c === cols) { return mat; } else { var resultat = Matrix.zeros(rows, cols); resultat = resultat.setSubMatrix(mat, 0, 0); return resultat; } } // Make sure both matrices are the same size. // This is exclusively for simplicity: // this algorithm can be implemented with matrices of different sizes. var r = Math.max(r1, r2); var c = Math.max(c1, c2); x = embed(x, r, c); y = embed(y, r, c); // Our recursive multiplication function. function blockMult(a, b, rows, cols) { // For small matrices, resort to naive multiplication. if (rows <= 512 || cols <= 512) { return a.mmul(b); // a is equivalent to this } // Apply dynamic padding. if (rows % 2 === 1 && cols % 2 === 1) { a = embed(a, rows + 1, cols + 1); b = embed(b, rows + 1, cols + 1); } else if (rows % 2 === 1) { a = embed(a, rows + 1, cols); b = embed(b, rows + 1, cols); } else if (cols % 2 === 1) { a = embed(a, rows, cols + 1); b = embed(b, rows, cols + 1); } var halfRows = parseInt(a.rows / 2, 10); var halfCols = parseInt(a.columns / 2, 10); // Subdivide input matrices. var a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1); var b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1); var a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1); var b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1); var a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1); var b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1); var a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1); var b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1); // Compute intermediate values. var m1 = blockMult(Matrix.add(a11, a22), Matrix.add(b11, b22), halfRows, halfCols); var m2 = blockMult(Matrix.add(a21, a22), b11, halfRows, halfCols); var m3 = blockMult(a11, Matrix.sub(b12, b22), halfRows, halfCols); var m4 = blockMult(a22, Matrix.sub(b21, b11), halfRows, halfCols); var m5 = blockMult(Matrix.add(a11, a12), b22, halfRows, halfCols); var m6 = blockMult(Matrix.sub(a21, a11), Matrix.add(b11, b12), halfRows, halfCols); var m7 = blockMult(Matrix.sub(a12, a22), Matrix.add(b21, b22), halfRows, halfCols); // Combine intermediate values into the output. var c11 = Matrix.add(m1, m4); c11.sub(m5); c11.add(m7); var c12 = Matrix.add(m3, m5); var c21 = Matrix.add(m2, m4); var c22 = Matrix.sub(m1, m2); c22.add(m3); c22.add(m6); // Crop output to the desired size (undo dynamic padding). var resultat = Matrix.zeros(2 * c11.rows, 2 * c11.columns); resultat = resultat.setSubMatrix(c11, 0, 0); resultat = resultat.setSubMatrix(c12, c11.rows, 0); resultat = resultat.setSubMatrix(c21, 0, c11.columns); resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns); return resultat.subMatrix(0, rows - 1, 0, cols - 1); } return blockMult(x, y, r, c); } /** * Returns a row-by-row scaled matrix * @param {number} [min=0] - Minimum scaled value * @param {number} [max=1] - Maximum scaled value * @return {Matrix} - The scaled matrix */ scaleRows(min, max) { min = min === undefined ? 0 : min; max = max === undefined ? 1 : max; if (min >= max) { throw new RangeError('min should be strictly smaller than max'); } var newMatrix = this.constructor.empty(this.rows, this.columns); for (var i = 0; i < this.rows; i++) { var scaled = (0, _mlArrayRescale2.default)(this.getRow(i), { min, max }); newMatrix.setRow(i, scaled); } return newMatrix; } /** * Returns a new column-by-column scaled matrix * @param {number} [min=0] - Minimum scaled value * @param {number} [max=1] - Maximum scaled value * @return {Matrix} - The new scaled matrix * @example * var matrix = new Matrix([[1,2],[-1,0]]); * var scaledMatrix = matrix.scaleColumns(); // [[1,1],[0,0]] */ scaleColumns(min, max) { min = min === undefined ? 0 : min; max = max === undefined ? 1 : max; if (min >= max) { throw new RangeError('min should be strictly smaller than max'); } var newMatrix = this.constructor.empty(this.rows, this.columns); for (var i = 0; i < this.columns; i++) { var scaled = (0, _mlArrayRescale2.default)(this.getColumn(i), { min: min, max: max }); newMatrix.setColumn(i, scaled); } return newMatrix; } /** * Returns the Kronecker product (also known as tensor product) between this and other * See https://en.wikipedia.org/wiki/Kronecker_product * @param {Matrix} other * @return {Matrix} */ kroneckerProduct(other) { other = this.constructor.checkMatrix(other); var m = this.rows; var n = this.columns; var p = other.rows; var q = other.columns; var result = new this.constructor[Symbol.species](m * p, n * q); for (var i = 0; i < m; i++) { for (var j = 0; j < n; j++) { for (var k = 0; k < p; k++) { for (var l = 0; l < q; l++) { result[p * i + k][q * j + l] = this.get(i, j) * other.get(k, l); } } } } return result; } /** * Transposes the matrix and returns a new one containing the result * @return {Matrix} */ transpose() { var result = new this.constructor[Symbol.species](this.columns, this.rows); for (var i = 0; i < this.rows; i++) { for (var j = 0; j < this.columns; j++) { result.set(j, i, this.get(i, j)); } } return result; } /** * Sorts the rows (in place) * @param {function} compareFunction - usual Array.prototype.sort comparison function * @return {Matrix} this */ sortRows(compareFunction) { if (compareFunction === undefined) compareFunction = compareNumbers; for (var i = 0; i < this.rows; i++) { this.setRow(i, this.getRow(i).sort(compareFunction)); } return this; } /** * Sorts the columns (in place) * @param {function} compareFunction - usual Array.prototype.sort comparison function * @return {Matrix} this */ sortColumns(compareFunction) { if (compareFunction === undefined) compareFunction = compareNumbers; for (var i = 0; i < this.columns; i++) { this.setColumn(i, this.getColumn(i).sort(compareFunction)); } return this; } /** * Returns a subset of the matrix * @param {number} startRow - First row index * @param {number} endRow - Last row index * @param {number} startColumn - First column index * @param {number} endColumn - Last column index * @return {Matrix} */ subMatrix(startRow, endRow, startColumn, endColumn) { (0, _util.checkRange)(this, startRow, endRow, startColumn, endColumn); var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, endColumn - startColumn + 1); for (var i = startRow; i <= endRow; i++) { for (var j = startColumn; j <= endColumn; j++) { newMatrix[i - startRow][j - startColumn] = this.get(i, j); } } return newMatrix; } /** * Returns a subset of the matrix based on an array of row indices * @param {Array} indices - Array containing the row indices * @param {number} [startColumn = 0] - First column index * @param {number} [endColumn = this.columns-1] - Last column index * @return {Matrix} */ subMatrixRow(indices, startColumn, endColumn) { if (startColumn === undefined) startColumn = 0; if (endColumn === undefined) endColumn = this.columns - 1; if (startColumn > endColumn || startColumn < 0 || startColumn >= this.columns || endColumn < 0 || endColumn >= this.columns) { throw new RangeError('Argument out of range'); } var newMatrix = new this.constructor[Symbol.species](indices.length, endColumn - startColumn + 1); for (var i = 0; i < indices.length; i++) { for (var j = startColumn; j <= endColumn; j++) { if (indices[i] < 0 || indices[i] >= this.rows) { throw new RangeError(`Row index out of range: ${indices[i]}`); } newMatrix.set(i, j - startColumn, this.get(indices[i], j)); } } return newMatrix; } /** * Returns a subset of the matrix based on an array of column indices * @param {Array} indices - Array containing the column indices * @param {number} [startRow = 0] - First row index * @param {number} [endRow = this.rows-1] - Last row index * @return {Matrix} */ subMatrixColumn(indices, startRow, endRow) { if (startRow === undefined) startRow = 0; if (endRow === undefined) endRow = this.rows - 1; if (startRow > endRow || startRow < 0 || startRow >= this.rows || endRow < 0 || endRow >= this.rows) { throw new RangeError('Argument out of range'); } var newMatrix = new this.constructor[Symbol.species](endRow - startRow + 1, indices.length); for (var i = 0; i < indices.length; i++) { for (var j = startRow; j <= endRow; j++) { if (indices[i] < 0 || indices[i] >= this.columns) { throw new RangeError(`Column index out of range: ${indices[i]}`); } newMatrix.set(j - startRow, i, this.get(j, indices[i])); } } return newMatrix; } /** * Set a part of the matrix to the given sub-matrix * @param {Matrix|Array< Array >} matrix - The source matrix from which to extract values. * @param {number} startRow - The index of the first row to set * @param {number} startColumn - The index of the first column to set * @return {Matrix} */ setSubMatrix(matrix, startRow, startColumn) { matrix = this.constructor.checkMatrix(matrix); var endRow = startRow + matrix.rows - 1; var endColumn = startColumn + matrix.columns - 1; (0, _util.checkRange)(this, startRow, endRow, startColumn, endColumn); for (var i = 0; i < matrix.rows; i++) { for (var j = 0; j < matrix.columns; j++) { this[startRow + i][startColumn + j] = matrix.get(i, j); } } return this; } /** * Return a new matrix based on a selection of rows and columns * @param {Array<number>} rowIndices - The row indices to select. Order matters and an index can be more than once. * @param {Array<number>} columnIndices - The column indices to select. Order matters and an index can be use more than once. * @return {Matrix} The new matrix */ selection(rowIndices, columnIndices) { var indices = (0, _util.checkIndices)(this, rowIndices, columnIndices); var newMatrix = new this.constructor[Symbol.species](rowIndices.length, columnIndices.length); for (var i = 0; i < indices.row.length; i++) { var rowIndex = indices.row[i]; for (var j = 0; j < indices.column.length; j++) { var columnIndex = indices.column[j]; newMatrix[i][j] = this.get(rowIndex, columnIndex); } } return newMatrix; } /** * Returns the trace of the matrix (sum of the diagonal elements) * @return {number} */ trace() { var min = Math.min(this.rows, this.columns); var trace = 0; for (var i = 0; i < min; i++) { trace += this.get(i, i); } return trace; } /* Matrix views */ /** * Returns a view of the transposition of the matrix * @return {MatrixTransposeView} */ transposeView() { return new _transpose2.default(this); } /** * Returns a view of the row vector with the given index * @param {number} row - row index of the vector * @return {MatrixRowView} */ rowView(row) { (0, _util.checkRowIndex)(this, row); return new _row2.default(this, row); } /** * Returns a view of the column vector with the given index * @param {number} column - column index of the vector * @return {MatrixColumnView} */ columnView(column) { (0, _util.checkColumnIndex)(this, column); return new _column2.default(this, column); } /** * Returns a view of the matrix flipped in the row axis * @return {MatrixFlipRowView} */ flipRowView() { return new _flipRow2.default(this); } /** * Returns a view of the matrix flipped in the column axis * @return {MatrixFlipColumnView} */ flipColumnView() { return new _flipColumn2.default(this); } /** * Returns a view of a submatrix giving the index boundaries * @param {number} startRow - first row index of the submatrix * @param {number} endRow - last row index of the submatrix * @param {number} startColumn - first column index of the submatrix * @param {number} endColumn - last column index of the submatrix * @return {MatrixSubView} */ subMatrixView(startRow, endRow, startColumn, endColumn) { return new _sub2.default(this, startRow, endRow, startColumn, endColumn); } /** * Returns a view of the cross of the row indices and the column indices * @example * // resulting vector is [[2], [2]] * var matrix = new Matrix([[1,2,3], [4,5,6]]).selectionView([0, 0], [1]) * @param {Array<number>} rowIndices * @param {Array<number>} columnIndices * @return {MatrixSelectionView} */ selectionView(rowIndices, columnIndices) { return new _selection2.default(this, rowIndices, columnIndices); } /** * Returns a view of the row indices * @example * // resulting vector is [[1,2,3], [1,2,3]] * var matrix = new Matrix([[1,2,3], [4,5,6]]).rowSelectionView([0, 0]) * @param {Array<number>} rowIndices * @return {MatrixRowSelectionView} */ rowSelectionView(rowIndices) { return new _rowSelection2.default(this, rowIndices); } /** * Returns a view of the column indices * @example * // resulting vector is [[2, 2], [5, 5]] * var matrix = new Matrix([[1,2,3], [4,5,6]]).columnSelectionView([1, 1]) * @param {Array<number>} columnIndices * @return {MatrixColumnSelectionView} */ columnSelectionView(columnIndices) { return new _columnSelection2.default(this, columnIndices); } /** * Calculates and returns the determinant of a matrix as a Number * @example * new Matrix([[1,2,3], [4,5,6]]).det() * @return {number} */ det() { if (this.isSquare()) { var a, b, c, d; if (this.columns === 2) { // 2 x 2 matrix a = this.get(0, 0); b = this.get(0, 1); c = this.get(1, 0); d = this.get(1, 1); return a * d - b * c; } else if (this.columns === 3) { // 3 x 3 matrix var subMatrix0, subMatrix1, subMatrix2; subMatrix0 = this.selectionView([1, 2], [1, 2]); subMatrix1 = this.selectionView([1, 2], [0, 2]); subMatrix2 = this.selectionView([1, 2], [0, 1]); a = this.get(0, 0); b = this.get(0, 1); c = this.get(0, 2); return a * subMatrix0.det() - b * subMatrix1.det() + c * subMatrix2.det(); } else { // general purpose determinant using the LU decomposition return new _lu2.default(this).determinant; } } else { throw Error('Determinant can only be calculated for a square matrix.'); } } /** * Returns inverse of a matrix if it exists or the pseudoinverse * @param {number} threshold - threshold for taking inverse of singular values (default = 1e-15) * @return {Matrix} the (pseudo)inverted matrix. */ pseudoInverse(threshold) { if (threshold === undefined) threshold = Number.EPSILON; var svdSolution = new _svd2.default(this, { autoTranspose: true }); var U = svdSolution.leftSingularVectors; var V = svdSolution.rightSingularVectors; var s = svdSolution.diagonal; for (var i = 0; i < s.length; i++) { if (Math.abs(s[i]) > threshold) { s[i] = 1.0 / s[i]; } else { s[i] = 0.0; } } // convert list to diagonal s = this.constructor[Symbol.species].diag(s); return V.mmul(s.mmul(U.transposeView())); } /** * Creates an exact and independent copy of the matrix * @return {Matrix} */ clone() { var newMatrix = new this.constructor[Symbol.species](this.rows, this.columns); for (var row = 0; row < this.rows; row++) { for (var column = 0; column < this.columns; column++) { newMatrix.set(row, column, this.get(row, column)); } } return newMatrix; } }
JavaScript
class Random { /** * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random. */ constructor(seedOrRandom = Math.random) { if (typeof seedOrRandom === 'number') { var xsadd = new XSAdd(seedOrRandom); this.randomGenerator = xsadd.random; } else { this.randomGenerator = seedOrRandom; } } choice(values, options) { if (typeof values === 'number') { return (0, _choice2.default)(values, options, this.randomGenerator); } return (0, _choice2.default)(values, options, this.randomGenerator); } /** * Draw a random number from a uniform distribution on [0,1) * @return The random number */ random() { return this.randomGenerator(); } /** * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low) * @param low - The lower bound of the uniform distribution interval. * @param high - The higher bound of the uniform distribution interval. */ randInt(low, high) { if (high === undefined) { high = low; low = 0; } return low + Math.floor(this.randomGenerator() * (high - low)); } /** * Draw several random number from a uniform distribution on [0, 1) * @param size - The number of number to draw * @return - The list of drawn numbers. */ randomSample(size) { var result = []; for (var i = 0; i < size; i++) { result.push(this.random()); } return result; } }
JavaScript
class ConfusionMatrix { constructor(matrix, labels) { if (matrix.length !== matrix[0].length) { throw new Error('Confusion matrix must be square'); } if (labels.length !== matrix.length) { throw new Error('Confusion matrix and labels should have the same length'); } this.labels = labels; this.matrix = matrix; } /** * Construct confusion matrix from the predicted and actual labels (classes). Be sure to provide the arguments in * the correct order! * @param {Array<any>} actual - The predicted labels of the classification * @param {Array<any>} predicted - The actual labels of the classification. Has to be of same length as * predicted. * @param {object} [options] - Additional options * @param {Array<any>} [options.labels] - The list of labels that should be used. If not provided the distinct set * of labels present in predicted and actual is used. Labels are compared using the strict equality operator * '===' * @return {ConfusionMatrix} - Confusion matrix */ static fromLabels(actual, predicted, options = {}) { if (predicted.length !== actual.length) { throw new Error('predicted and actual must have the same length'); } var distinctLabels = void 0; if (options.labels) { distinctLabels = new Set(options.labels); } else { distinctLabels = new Set([...actual, ...predicted]); } distinctLabels = Array.from(distinctLabels); if (options.sort) { distinctLabels.sort(options.sort); } // Create confusion matrix and fill with 0's var matrix = Array.from({ length: distinctLabels.length }); for (var i = 0; i < matrix.length; i++) { matrix[i] = new Array(matrix.length); matrix[i].fill(0); } for (var _i = 0; _i < predicted.length; _i++) { var actualIdx = distinctLabels.indexOf(actual[_i]); var predictedIdx = distinctLabels.indexOf(predicted[_i]); if (actualIdx >= 0 && predictedIdx >= 0) { matrix[actualIdx][predictedIdx]++; } } return new ConfusionMatrix(matrix, distinctLabels); } /** * Get the confusion matrix * @return {Array<Array<number> >} */ getMatrix() { return this.matrix; } getLabels() { return this.labels; } /** * Get the total number of samples * @return {number} */ getTotalCount() { var predicted = 0; for (var i = 0; i < this.matrix.length; i++) { for (var j = 0; j < this.matrix.length; j++) { predicted += this.matrix[i][j]; } } return predicted; } /** * Get the total number of true predictions * @return {number} */ getTrueCount() { var count = 0; for (var i = 0; i < this.matrix.length; i++) { count += this.matrix[i][i]; } return count; } /** * Get the total number of false predictions. * @return {number} */ getFalseCount() { return this.getTotalCount() - this.getTrueCount(); } /** * Get the number of true positive predictions. * @param {any} label - The label that should be considered "positive" * @return {number} */ getTruePositiveCount(label) { var index = this.getIndex(label); return this.matrix[index][index]; } /** * Get the number of true negative predictions * @param {any} label - The label that should be considered "positive" * @return {number} */ getTrueNegativeCount(label) { var index = this.getIndex(label); var count = 0; for (var i = 0; i < this.matrix.length; i++) { for (var j = 0; j < this.matrix.length; j++) { if (i !== index && j !== index) { count += this.matrix[i][j]; } } } return count; } /** * Get the number of false positive predictions. * @param {any} label - The label that should be considered "positive" * @return {number} */ getFalsePositiveCount(label) { var index = this.getIndex(label); var count = 0; for (var i = 0; i < this.matrix.length; i++) { if (i !== index) { count += this.matrix[i][index]; } } return count; } /** * Get the number of false negative predictions. * @param {any} label - The label that should be considered "positive" * @return {number} */ getFalseNegativeCount(label) { var index = this.getIndex(label); var count = 0; for (var i = 0; i < this.matrix.length; i++) { if (i !== index) { count += this.matrix[index][i]; } } return count; } /** * Get the number of real positive samples. * @param {any} label - The label that should be considered "positive" * @return {number} */ getPositiveCount(label) { return this.getTruePositiveCount(label) + this.getFalseNegativeCount(label); } /** * Get the number of real negative samples. * @param {any} label - The label that should be considered "positive" * @return {number} */ getNegativeCount(label) { return this.getTrueNegativeCount(label) + this.getFalsePositiveCount(label); } /** * Get the index in the confusion matrix that corresponds to the given label * @param {any} label - The label to search for * @throws if the label is not found * @return {number} */ getIndex(label) { var index = this.labels.indexOf(label); if (index === -1) throw new Error('The label does not exist'); return index; } /** * Get the true positive rate a.k.a. sensitivity. Computes the ratio between the number of true positive predictions and the total number of positive samples. * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity} * @param {any} label - The label that should be considered "positive" * @return {number} - The true positive rate [0-1] */ getTruePositiveRate(label) { return this.getTruePositiveCount(label) / this.getPositiveCount(label); } /** * Get the true negative rate a.k.a. specificity. Computes the ration between the number of true negative predictions and the total number of negative samples. * {@link https://en.wikipedia.org/wiki/Sensitivity_and_specificity} * @param {any} label - The label that should be considered "positive" * @return {number} */ getTrueNegativeRate(label) { return this.getTrueNegativeCount(label) / this.getNegativeCount(label); } /** * Get the positive predictive value a.k.a. precision. Computes TP / (TP + FP) * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values} * @param {any} label - The label that should be considered "positive" * @return {number} */ getPositivePredictiveValue(label) { var TP = this.getTruePositiveCount(label); return TP / (TP + this.getFalsePositiveCount(label)); } /** * Negative predictive value * {@link https://en.wikipedia.org/wiki/Positive_and_negative_predictive_values} * @param {any} label - The label that should be considered "positive" * @return {number} */ getNegativePredictiveValue(label) { var TN = this.getTrueNegativeCount(label); return TN / (TN + this.getFalseNegativeCount(label)); } /** * False negative rate a.k.a. miss rate. * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates} * @param {any} label - The label that should be considered "positive" * @return {number} */ getFalseNegativeRate(label) { return 1 - this.getTruePositiveRate(label); } /** * False positive rate a.k.a. fall-out rate. * {@link https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#False_positive_and_false_negative_rates} * @param {any} label - The label that should be considered "positive" * @return {number} */ getFalsePositiveRate(label) { return 1 - this.getTrueNegativeRate(label); } /** * False discovery rate (FDR) * {@link https://en.wikipedia.org/wiki/False_discovery_rate} * @param {any} label - The label that should be considered "positive" * @return {number} */ getFalseDiscoveryRate(label) { var FP = this.getFalsePositiveCount(label); return FP / (FP + this.getTruePositiveCount(label)); } /** * False omission rate (FOR) * @param {any} label - The label that should be considered "positive" * @return {number} */ getFalseOmissionRate(label) { var FN = this.getFalseNegativeCount(label); return FN / (FN + this.getTruePositiveCount(label)); } /** * F1 score * {@link https://en.wikipedia.org/wiki/F1_score} * @param {any} label - The label that should be considered "positive" * @return {number} */ getF1Score(label) { var TP = this.getTruePositiveCount(label); return 2 * TP / (2 * TP + this.getFalsePositiveCount(label) + this.getFalseNegativeCount(label)); } /** * Matthews correlation coefficient (MCC) * {@link https://en.wikipedia.org/wiki/Matthews_correlation_coefficient} * @param {any} label - The label that should be considered "positive" * @return {number} */ getMatthewsCorrelationCoefficient(label) { var TP = this.getTruePositiveCount(label); var TN = this.getTrueNegativeCount(label); var FP = this.getFalsePositiveCount(label); var FN = this.getFalseNegativeCount(label); return (TP * TN - FP * FN) / Math.sqrt((TP + FP) * (TP + FN) * (TN + FP) * (TN + FN)); } /** * Informedness * {@link https://en.wikipedia.org/wiki/Youden%27s_J_statistic} * @param {any} label - The label that should be considered "positive" * @return {number} */ getInformedness(label) { return this.getTruePositiveRate(label) + this.getTrueNegativeRate(label) - 1; } /** * Markedness * @param {any} label - The label that should be considered "positive" * @return {number} */ getMarkedness(label) { return this.getPositivePredictiveValue(label) + this.getNegativePredictiveValue(label) - 1; } /** * Get the confusion table. * @param {any} label - The label that should be considered "positive" * @return {Array<Array<number> >} - The 2x2 confusion table. [[TP, FN], [FP, TN]] */ getConfusionTable(label) { return [[this.getTruePositiveCount(label), this.getFalseNegativeCount(label)], [this.getFalsePositiveCount(label), this.getTrueNegativeCount(label)]]; } /** * Get total accuracy. * @return {number} - The ratio between the number of true predictions and total number of classifications ([0-1]) */ getAccuracy() { var correct = 0; var incorrect = 0; for (var i = 0; i < this.matrix.length; i++) { for (var j = 0; j < this.matrix.length; j++) { if (i === j) correct += this.matrix[i][j];else incorrect += this.matrix[i][j]; } } return correct / (correct + incorrect); } /** * Returns the element in the confusion matrix that corresponds to the given actual and predicted labels. * @param {any} actual - The true label * @param {any} predicted - The predicted label * @return {number} - The element in the confusion matrix */ getCount(actual, predicted) { var actualIndex = this.getIndex(actual); var predictedIndex = this.getIndex(predicted); return this.matrix[actualIndex][predictedIndex]; } /** * Compute the general prediction accuracy * @deprecated Use getAccuracy * @return {number} - The prediction accuracy ([0-1] */ get accuracy() { return this.getAccuracy(); } /** * Compute the number of predicted observations * @deprecated Use getTotalCount * @return {number} */ get total() { return this.getTotalCount(); } }
JavaScript
class PotentialRegression extends _mlRegressionBase2.default { /** * @constructor * @param x: Independent variable * @param y: Dependent variable * @param M */ constructor(x, y, M) { super(); if (x === true) { // reloading model this.A = y.A; this.M = y.M; } else { var n = x.length; if (n !== y.length) { throw new RangeError('input and output array have a different length'); } var linear = new _mlRegressionPolynomial2.default(x, y, [M]); this.A = linear.coefficients[0]; this.M = M; } } _predict(x) { return this.A * Math.pow(x, this.M); } toJSON() { return { name: 'potentialRegression', A: this.A, M: this.M }; } toString(precision) { return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + ' * x^' + this.M; } toLaTeX(precision) { if (this.M >= 0) { return 'f(x) = ' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + 'x^{' + this.M + '}'; } else { return 'f(x) = \\frac{' + (0, _mlRegressionBase.maybeToPrecision)(this.A, precision) + '}{x^{' + -this.M + '}}'; } } static load(json) { if (json.name !== 'potentialRegression') { throw new TypeError('not a potential regression model'); } return new PotentialRegression(true, json); } }
JavaScript
class AirConditionModel extends Status_1.Status { constructor(status, ac) { super(status); this.keys = []; this.serialId = ''; this.name = ''; this.rmodel = ''; this.keyValue = ''; this.temperature = ''; this.mode = ''; this.speed = ''; this.horizontalWing = ''; this.verticalWing = ''; this.power = ''; this.mode = status.slice(0, 2); this.speed = status.slice(2, 4); this.temperature = status.slice(4, 6); this.verticalWing = status.slice(6, 8); this.horizontalWing = status.slice(8, 10); if (ac) { this.keys = ac.keys; this.serialId = ac.serialId; this.deviceType = ac.deviceType; this.index = ac.indexOsm; this.name = ac.name; this.rmodel = ac.rmodel; this.keyValue = ac.keyValue; // this.init() } } init() { if (!this.keyValue) return; if (['on', 'off'].includes(this.keyValue)) { this.setPower(this.keyValue); } else { const keys = this.keyValue.split('_'); if (keys.filter(i => i).length) this.setPower('on'); keys[0] && this.setMode(keys[0]); keys[1] && this.setSpeed(keys[1]); this.setTemperature(keys[2] || '1a'); keys[3] && this.setVerticalWing(keys[3]); keys[4] && this.setHorizontalWing(keys[4]); } } getKeys() { return this.keys; } getKeyValue() { return this.keyValue; } getSerialId() { return this.serialId; } getDeviceType() { return this.deviceType; } getIndex() { return this.index; } getName() { return this.name; } getrModel() { return this.rmodel; } setTemperature(tmp) { this.temperature = tmp; return this; } getTemperature() { return this.temperature; } setMode(mode) { this.mode = mode; return this; } getMode() { return this.mode; } setSpeed(speed) { this.speed = speed; return this; } getSpeed() { return this.speed; } setHorizontalWing(wing) { this.horizontalWing = wing; return this; } getHorizontalWing() { return this.horizontalWing; } setVerticalWing(wing) { this.verticalWing = wing; return this; } getVerticalWing() { return this.verticalWing; } setPower(power) { this.power = power; return this; } getPower() { return this.power; } }
JavaScript
class WireAirConditionModel extends Status_1.Status { constructor(status) { super(status); this.temperature = ''; // 设置温度 this.mode = ''; // 模式 this.speed = ''; // 风速 this.horizontalWing = ''; // 左右摆风 this.verticalWing = ''; // 上下摆风 this.power = ''; // 电源 this.preserve = status.slice(0, 2); this.mode = status.slice(2, 4); this.power = status.slice(2, 4); this.speed = status.slice(4, 6); this.temperature = status.slice(6, 8); this.verticalWing = status.slice(8, 10); this.horizontalWing = status.slice(10, 12); this.roomTemp = status.slice(12, 14) || '32'; } setTemperature(tmp) { this.temperature = tmp; return this; } getTemperature() { return this.temperature; } setMode(mode) { this.mode = mode; return this; } getMode() { return this.mode; } setSpeed(speed) { this.speed = speed; return this; } getSpeed() { return this.speed; } setHorizontalWing(wing) { this.horizontalWing = wing; return this; } getHorizontalWing() { return this.horizontalWing; } setVerticalWing(wing) { this.verticalWing = wing; return this; } getVerticalWing() { return this.verticalWing; } setPower(power) { this.power = power; return this; } getPower() { return this.power; } }
JavaScript
class Main extends Component { render() { return ( <View style={{ flex: 1 }}> <StatusBar barStyle="light-content" /> <Router store={store} getSceneStyle={getSceneStyle} navigationBarStyle={Platform.OS === 'ios' ? styles.headerIOS : styles.headerAndroid} titleStyle={getTitleStyle()} backButtonImage={ require(`../assets/left-arr.png`) } > <Scene key="root"> <Scene initial key="login" hideNavBar={true} component={Login} type="reset" /> <Scene key="home" component={Home} panHandlers={null} hideBackImage={true} hideNavBar onBack={_.noop} onRight={_.noop} type="reset" statusBarStyle="light-content" /> <Scene key="calendar" title="Calendar" hideNavBar={false} component={Calendar} panHandlers={null} /> <Scene key="activity" hideNavBar={false} component={Activity} /> <Scene key="availableSlots" hideNavBar={false} component={AvailableSlots} /> <Scene key="news" title="Notifications" hideNavBar={false} component={News} /> <Scene key="projects" title="Projects" hideNavBar={false} component={Projects} /> <Scene key="projectDetails" title="projects-details" hideNavBar={false} component={ProjectDetails} /> <Scene key="pdf" title="pdf" hideNavBar={false} component={PDFViewer} /> <Scene key="marks" title="Marks" hideNavBar={false} component={Marks} /> <Scene key="markDetails" title="marks-details" hideNavBar={false} component={MarkDetails} onRight={() => store.marks.sort()} rightButtonImage={require('../assets/sort.png')} rightButtonIconStyle={getImageStyle()} /> <Scene key="ranking" title="Ranking" hideNavBar={false} component={Ranking} onRight={() => { if (store.ui.isConnected) { return store.ranking.computePromotion({ refreshCache: true }) } }} rightButtonImage={require('../assets/reload.png')} rightButtonIconStyle={getImageStyle()} /> <Scene key="token" title="Tokens" hideNavBar={false} component={Token} /> <Scene key="links" title="Links" hideNavBar={false} component={Links} /> <Scene key="documents" title="Documents" hideNavBar={false} component={Documents} /> </Scene> </Router> </View> ); } }
JavaScript
class PlatformLoggerServiceImpl { constructor(container) { this.container = container; } // In initial implementation, this will be called by installations on // auth token refresh, and installations will send this string. getPlatformInfoString() { const providers = this.container.getProviders(); // Loop through providers and get library/version pairs from any that are // version components. return providers .map(provider => { if (isVersionServiceProvider(provider)) { const service = provider.getImmediate(); return `${service.library}/${service.version}`; } else { return null; } }) .filter(logString => logString) .join(' '); } }
JavaScript
class FirebaseAppImpl { constructor(options, config, container) { this._isDeleted = false; this._options = Object.assign({}, options); this._config = Object.assign({}, config); this._name = config.name; this._automaticDataCollectionEnabled = config.automaticDataCollectionEnabled; this._container = container; this.container.addComponent(new Component('app', () => this, "PUBLIC" /* PUBLIC */)); } get automaticDataCollectionEnabled() { this.checkDestroyed(); return this._automaticDataCollectionEnabled; } set automaticDataCollectionEnabled(val) { this.checkDestroyed(); this._automaticDataCollectionEnabled = val; } get name() { this.checkDestroyed(); return this._name; } get options() { this.checkDestroyed(); return this._options; } get config() { this.checkDestroyed(); return this._config; } get container() { return this._container; } get isDeleted() { return this._isDeleted; } set isDeleted(val) { this._isDeleted = val; } /** * This function will throw an Error if the App has already been deleted - * use before performing API actions on the App. */ checkDestroyed() { if (this.isDeleted) { throw ERROR_FACTORY.create("app-deleted" /* APP_DELETED */, { appName: this._name }); } } }
JavaScript
class CheckRunner { constructor(modified) { this.annotations = []; this.stats = { suggestions: 0, warnings: 0, errors: 0 }; this.modified = modified; } /** * Convert Vale's JSON `output` into an array of annotations. */ makeAnnotations(output) { const alerts = JSON.parse(output); for (const filename of Object.getOwnPropertyNames(alerts)) { for (const alert of alerts[filename]) { if (onlyAnnotateModifiedLines && !git_1.wasLineAddedInPR(this.modified[filename], alert.Line)) { continue; } switch (alert.Severity) { case 'suggestion': this.stats.suggestions += 1; break; case 'warning': this.stats.warnings += 1; break; case 'error': this.stats.errors += 1; break; default: break; } this.annotations.push(CheckRunner.makeAnnotation(filename, alert)); } } } /** * Show the results of running Vale. * * NOTE: Support for annotation is still a WIP: * * - https://github.com/actions/toolkit/issues/186 * - https://github.com/actions-rs/clippy-check/issues/2 */ executeCheck(options) { return __awaiter(this, void 0, void 0, function* () { core.info(`Vale: ${this.getSummary()}`); const client = github.getOctokit(options.token, { userAgent: USER_AGENT }); let checkRunId; try { checkRunId = yield this.createCheck(client, options); } catch (error) { // NOTE: `GITHUB_HEAD_REF` is set only for forked repos. if (process.env.GITHUB_HEAD_REF) { core.warning(`Unable to create annotations; printing Vale alerts instead.`); this.dumpToStdout(); if (this.getConclusion() == 'failure') { throw new Error('Exiting due to Vale errors'); } return; } else { throw error; } } try { if (this.isSuccessCheck()) { // We don't have any alerts to report ... yield this.successCheck(client, checkRunId, options); } else { // Vale found some alerts to report ... yield this.runUpdateCheck(client, checkRunId, options); } } catch (error) { yield this.cancelCheck(client, checkRunId, options); throw error; } }); } /** * Create our initial check run. * * See https://developer.github.com/v3/checks/runs/#create-a-check-run. */ createCheck(client, options) { return __awaiter(this, void 0, void 0, function* () { const response = yield client.checks.create({ owner: options.owner, repo: options.repo, name: options.name, head_sha: options.head_sha, status: 'in_progress' }); if (response.status != 201) { core.warning(`[createCheck] Unexpected status code ${response.status}`); } return response.data.id; }); } /** * End our check run. * * NOTE: The Checks API only allows 50 annotations per request, so we send * multiple "buckets" if we have more than 50. */ runUpdateCheck(client, checkRunId, options) { return __awaiter(this, void 0, void 0, function* () { let annotations = this.getBucket(); while (annotations.length > 0) { let req = { owner: options.owner, repo: options.repo, name: options.name, check_run_id: checkRunId, output: { title: options.name, summary: this.getSummary(), text: this.getText(options.context), annotations: annotations } }; if (this.annotations.length > 0) { // There will be more annotations later ... req.status = 'in_progress'; } else { req.status = 'completed'; req.conclusion = this.getConclusion(); req.completed_at = new Date().toISOString(); } const response = yield client.checks.update(req); if (response.status != 200) { core.warning(`[updateCheck] Unexpected status code ${response.status}`); } annotations = this.getBucket(); } return; }); } /** * Indicate that no alerts were found. */ successCheck(client, checkRunId, options) { return __awaiter(this, void 0, void 0, function* () { let req = { owner: options.owner, repo: options.repo, name: options.name, check_run_id: checkRunId, status: 'completed', conclusion: this.getConclusion(), completed_at: new Date().toISOString(), output: { title: options.name, summary: this.getSummary(), text: this.getText(options.context) } }; const response = yield client.checks.update(req); if (response.status != 200) { core.warning(`[successCheck] Unexpected status code ${response.status}`); } return; }); } /** * Something went wrong; cancel the check run and report the exception. */ cancelCheck(client, checkRunId, options) { return __awaiter(this, void 0, void 0, function* () { let req = { owner: options.owner, repo: options.repo, name: options.name, check_run_id: checkRunId, status: 'completed', conclusion: 'cancelled', completed_at: new Date().toISOString(), output: { title: options.name, summary: 'Unhandled error', text: 'Check was cancelled due to unhandled error. Check the Action logs for details.' } }; const response = yield client.checks.update(req); if (response.status != 200) { core.warning(`[cancelCheck] Unexpected status code ${response.status}`); } return; }); } /** * Print Vale's output to stdout. * * NOTE: This should only happen if we can't create annotations (see * `executeCheck` above). * * TODO: Nicer formatting? */ dumpToStdout() { console.dir(this.annotations, { depth: null, colors: true }); } /** * Create buckets of at most 50 annotations for the API. * * See https://developer.github.com/v3/checks/runs/#output-object. */ getBucket() { let annotations = []; while (annotations.length < 50) { const annotation = this.annotations.pop(); if (annotation) { annotations.push(annotation); } else { break; } } core.debug(`Prepared next annotations bucket, ${annotations.length} size`); return annotations; } /** * Report a summary of the alerts found by Vale. */ getSummary() { const sn = this.stats.suggestions; const wn = this.stats.warnings; const en = this.stats.errors; return `Found ${sn} suggestion(s), ${wn} warning(s), and ${en} error(s).`; } /** * Create a Markdown-formatted summary of the alerts found by Vale. */ getText(context) { return `Vale ${context.vale}`; } /** * If Vale found an error-level alerts, we mark the check result as "failure". */ getConclusion() { if (this.stats.errors > 0) { return 'failure'; } else { return 'success'; } } /** * No alerts found. */ isSuccessCheck() { return (this.stats.suggestions == 0 && this.stats.warnings == 0 && this.stats.errors == 0); } /** * Convert Vale-formatted JSON object into an array of annotations: * * { * "README.md": [ * { * "Check": "DocsStyles.BadWords", * "Description": "", * "Line": 6, * "Link": "", * "Message": "'slave' should be changed", * "Severity": "error", * "Span": [ * 22, * 26 * ], * "Hide": false, * "Match": "slave" * } * ] * } * * See https://developer.github.com/v3/checks/runs/#annotations-object. */ static makeAnnotation(name, alert) { let annotation_level; switch (alert.Severity) { case 'suggestion': annotation_level = 'notice'; break; case 'warning': annotation_level = 'warning'; break; default: annotation_level = 'failure'; break; } let annotation = { path: name, start_line: alert.Line, end_line: alert.Line, start_column: alert.Span[0], end_column: alert.Span[1], annotation_level: annotation_level, title: `[${alert.Severity}] ${alert.Check}`, message: alert.Message }; return annotation; } }
JavaScript
class Commands { /** * Set a default for a file argument * * @param {object} argv the inbound argument values object * @param {string} argName the argument name * @param {string} argDefaultName the argument default name * @param {Function} argDefaultFun how to compute the argument default * @returns {object} a modified argument object */ static setDefaultFileArg(argv, argName, argDefaultName, argDefaultFun) { if(!argv[argName]){ Logger.info(`Loading a default ${argDefaultName} file.`); argv[argName] = argDefaultFun(argv, argDefaultName); } let argExists = true; argExists = Fs.existsSync(argv[argName]); if (!argExists){ throw new Error(`A ${argDefaultName} file is required. Try the --${argName} flag or create a ${argDefaultName}.`); } else { return argv; } } /** * Set default params before we parse a sample text * * @param {object} argv the inbound argument values object * @returns {object} a modfied argument object */ static validateParseArgs(argv) { argv = Commands.setDefaultFileArg(argv, 'sample', 'sample.md', ((argv, argDefaultName) => { return argDefaultName; })); if(argv.verbose) { Logger.info(`parse sample ${argv.sample} (or docx, pdf) printing intermediate transformations.`); } return argv; } /** * Parse a sample markdown * * @param {string} samplePath to the sample file * @param {string} outputPath to an output file * @param {object} [options] configuration options * @param {boolean} [options.cicero] whether to further transform for Cicero * @param {boolean} [options.slate] whether to further transform for Slate * @param {boolean} [options.html] whether to further transform for HTML * @param {boolean} [options.noQuote] whether to avoid quoting Cicero variables * @param {boolean} [options.verbose] verbose output * @returns {object} Promise to the result of parsing */ static async parse(samplePath, outputPath, options) { const { cicero, slate, html, noQuote, verbose } = options; console.log('OPTIONS ' + JSON.stringify(options)); const commonOptions = {}; commonOptions.tagInfo = true; const commonMark = new CommonMarkTransformer(commonOptions); const ciceroMark = new CiceroMarkTransformer(); const slateMark = new SlateTransformer(); const htmlMark = new HtmlTransformer(); const docx = new DocxTransformer(); const pdf = new PdfTransformer(); let result = null; if(samplePath.endsWith('.pdf')) { const pdfBuffer = Fs.readFileSync(samplePath); result = await pdf.toCiceroMark(pdfBuffer, 'json'); } else if(samplePath.endsWith('.docx')) { const docxBuffer = Fs.readFileSync(samplePath); result = await docx.toCiceroMark(docxBuffer, 'json'); } else { const markdownText = Fs.readFileSync(samplePath, 'utf8'); result = commonMark.fromMarkdown(markdownText, 'json'); } if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } if (cicero || slate || html) { const ciceroOptions = {}; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.fromCommonMark(result, 'json', ciceroOptions); if(verbose) { Logger.info('=== CiceroMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } if (slate) { result = slateMark.fromCiceroMark(result); if(verbose) { Logger.info('=== Slate DOM ==='); Logger.info(JSON.stringify(result, null, 4)); } } else if (html) { result = htmlMark.toHtml(result); } if (!html) { result = JSON.stringify(result, null, 4); } if (outputPath) { Logger.info('Creating file: ' + outputPath); Fs.writeFileSync(outputPath, result); } return Promise.resolve(result); } /** * Set default params before we draft a sample text * * @param {object} argv the inbound argument values object * @returns {object} a modfied argument object */ static validateDraftArgs(argv) { argv = Commands.setDefaultFileArg(argv, 'data', 'data.json', ((argv, argDefaultName) => { return argDefaultName; })); if(argv.verbose) { Logger.info(`draft sample from ${argv.data} printing intermediate transformations.`); } return argv; } /** * Parse a sample markdown/pdf/docx * * @param {string} dataPath to the sample file * @param {string} outputPath to an output file * @param {object} [options] configuration options * @param {boolean} [options.cicero] whether to further transform for Cicero * @param {boolean} [options.slate] whether to further transform for Slate * @param {boolean} [options.plainText] whether to remove rich text formatting * @param {boolean} [options.noWrap] whether to avoid wrapping Cicero variables in XML tags * @param {boolean} [options.noQuote] whether to avoid quoting Cicero variables * @param {boolean} [options.noIndex] do not index ordered list (i.e., use 1. everywhere) * @param {boolean} [options.verbose] verbose output * @returns {object} Promise to the result of parsing */ static draft(dataPath, outputPath, options) { const { cicero, slate, html, plainText, noWrap, noQuote, noIndex, verbose } = options; const commonOptions = {}; commonOptions.tagInfo = true; commonOptions.noIndex = noIndex ? true : false; const commonMark = new CommonMarkTransformer(commonOptions); const ciceroMark = new CiceroMarkTransformer(); const slateMark = new SlateTransformer(); const htmlMark = new HtmlTransformer(); let result = Fs.readFileSync(dataPath, 'utf8'); if (!html) { result = JSON.parse(result); } if (cicero) { const ciceroOptions = {}; ciceroOptions.wrapVariables = noWrap ? false : true; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.toCommonMark(result, 'json', ciceroOptions); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } else if (slate) { result = slateMark.toCiceroMark(result, 'json'); if(verbose) { Logger.info('=== CiceroMark ==='); Logger.info(JSON.stringify(result, null, 4)); } const ciceroOptions = {}; ciceroOptions.wrapVariables = noWrap ? false : true; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.toCommonMark(result, 'json', ciceroOptions); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } else if (html) { result = htmlMark.toCiceroMark(result, 'json'); if(verbose) { Logger.info('=== CiceroMark ==='); Logger.info(JSON.stringify(result, null, 4)); } const ciceroOptions = {}; ciceroOptions.wrapVariables = noWrap ? false : true; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.toCommonMark(result, 'json', ciceroOptions); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } result = commonMark.toMarkdown(result); if (outputPath) { Logger.info('Creating file: ' + outputPath); Fs.writeFileSync(outputPath, result); } return Promise.resolve(result); } /** * Set default params before we normalize a sample text * * @param {object} argv the inbound argument values object * @returns {object} a modfied argument object */ static validateNormalizeArgs(argv) { argv = Commands.setDefaultFileArg(argv, 'sample', 'sample.md', ((argv, argDefaultName) => { return argDefaultName; })); if(argv.verbose) { Logger.info(`normalize sample ${argv.sample} printing intermediate transformations.`); } return argv; } /** * Normalize a sample markdown * * @param {string} samplePath to the sample file * @param {string} outputPath to an output file * @param {object} [options] configuration options * @param {boolean} [options.cicero] whether to further transform for Cicero * @param {boolean} [options.slate] whether to further transform for Slate * @param {boolean} [options.plainText] whether to remove rich text formatting * @param {boolean} [options.noWrap] whether to avoid wrapping Cicero variables in XML tags * @param {boolean} [options.noQuote] whether to avoid quoting Cicero variables * @param {boolean} [options.noIndex] do not index ordered list (i.e., use 1. everywhere) * @param {boolean} [options.verbose] verbose output * @returns {object} Promise to the result of parsing */ static normalize(samplePath, outputPath, options) { const { cicero, slate, html, plainText, noWrap, noQuote, noIndex, verbose } = options; const commonOptions = {}; commonOptions.tagInfo = true; commonOptions.noIndex = noIndex ? true : false; const commonMark = new CommonMarkTransformer(commonOptions); const ciceroMark = new CiceroMarkTransformer(); const slateMark = new SlateTransformer(); const htmlMark = new HtmlTransformer(); const markdownText = Fs.readFileSync(samplePath, 'utf8'); let result = commonMark.fromMarkdown(markdownText, 'json'); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } if (cicero || slate || html) { const ciceroOptions = {}; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.fromCommonMark(result, 'json', ciceroOptions); if(verbose) { Logger.info('=== CiceroMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } if (slate) { result = slateMark.fromCiceroMark(result); if(verbose) { Logger.info('=== Slate DOM ==='); Logger.info(JSON.stringify(result, null, 4)); } } else if (html) { result = htmlMark.toHtml(result); if(verbose) { Logger.info('=== HTML ==='); Logger.info(result); } } if (cicero) { const ciceroOptions = {}; ciceroOptions.wrapVariables = noWrap ? false : true; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.toCommonMark(result, 'json', ciceroOptions); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } else if (slate) { result = slateMark.toCiceroMark(result, 'json'); if(verbose) { Logger.info('=== CiceroMark ==='); Logger.info(JSON.stringify(result, null, 4)); } const ciceroOptions = {}; ciceroOptions.wrapVariables = noWrap ? false : true; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.toCommonMark(result, 'json', ciceroOptions); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } else if (html) { result = htmlMark.toCiceroMark(result, 'json'); if(verbose) { Logger.info('=== CiceroMark ==='); Logger.info(JSON.stringify(result, null, 4)); } const ciceroOptions = {}; ciceroOptions.wrapVariables = noWrap ? false : true; ciceroOptions.quoteVariables = noQuote ? false : true; result = ciceroMark.toCommonMark(result, 'json', ciceroOptions); result = plainText ? commonMark.removeFormatting(result) : result; if(verbose) { Logger.info('=== CommonMark ==='); Logger.info(JSON.stringify(result, null, 4)); } } result = commonMark.toMarkdown(result); if (outputPath) { Logger.info('Creating file: ' + outputPath); Fs.writeFileSync(outputPath, result); } return Promise.resolve(result); } }
JavaScript
class Spline extends Line { /** * Spline constructor * @param {PositionDefinition} positionDefinition - First point * @param {Array<PositionDefinition>|PositionDefinition} points - Set of points to go through or a single target point * @param {Number} [tension=Spline.defaultTension] - Ratio of tension between points (0 means straight line, can take any value, but with weird results above 1) * @param {LineOptions} [options] - Drawing options */ constructor (positionDefinition, points, tension = Spline.defaultTension, options) { super(positionDefinition, points, options); /** * @type {Number} */ this.tension = tension; } /** * Draw the spline * @param {Path2D} path - Current drawing path * @return {Spline} Itself */ trace (path) { if (this.points.length === 1 || equals(this.tension, 0)) { super.trace(path); } else { path.moveTo(0, 0); Spline.splineThrough(path, [new Position(0, 0)].concat(this.points), this.tension); } return this; } /** * @inheritDoc */ toJSON () { const { tension } = this; return { ...super.toJSON(), tension, }; } /** * @inheritDoc * @param {Object} definition - Spline definition * @return {Spline} */ static from (definition) { return new Spline(definition.position, definition.points, definition.tension, definition.options); } /** * Default ratio of tension * @return {Number} */ static get defaultTension () { return 0.2; } /** * Draw a spline through points using a tension (first point should be current position) * @param {Path2D} path - Current drawing path * @param {Array<PositionDefinition>} points - Points to use (need at least 2 points) * @param {Number} [tension=Spline.defaultTension] - Ratio of tension */ static splineThrough (path, points, tension = Spline.defaultTension) { if (points.length < 2) { throw new RangeError(`Need at least 2 points to spline, but only ${points.length} given.`); } const positions = points.map(point => Position.from(point)); if (positions.length === 2) { path.lineTo(positions[1].x, positions[1].y); return; } const getCtrlPts = Spline.getControlPoint; let previousControls = [null, positions[0]]; for (let i = 1, l = positions.length; i < l; ++i) { const controlPoints = i < l - 1 ? getCtrlPts(positions.slice(i - 1, i + 2), tension) : [positions[i], null]; path.bezierCurveTo( previousControls[1].x, previousControls[1].y, controlPoints[0].x, controlPoints[0].y, positions[i].x, positions[i].y, ); previousControls = controlPoints; } } /** * Returns control points for a point in a spline (needs before and after, 3 points in total) * @param {Array<PositionDefinition>} points - 3 points to use (before, target, after) * @param {Number} [tension=Spline.defaultTension] - Ratio of tension * @return {Array<Position>} */ static getControlPoint (points, tension = Spline.defaultTension) { if (points.length < 3) { throw new RangeError(`Need exactly 3 points to compute control points, but ${points.length} given.`); } const positions = points.map(point => Position.from(point)); const diff = positions[2].clone().subtract(positions[0]).multiply(tension); return [ positions[1].clone().subtract(diff), positions[1].clone().add(diff), ]; } }
JavaScript
class ViewAdapter { /** * @constructor */ constructor(Application) { this.Application = Application; this.applicationFactory = Application.getContainer('factory'); this.componentFactory = this.applicationFactory.component; this.stateFactory = this.applicationFactory.state; this.localeFactory = this.applicationFactory.locale; this.root = null; } /** * Creates the main instance for the view layer. * Is used on startup process of the main application. * * @param renderElement * @param router * @param providers * @memberOf module:app/adapter/view/vue * @returns {object} */ init(renderElement, router, providers) { warn( 'init', ` You need to overwrite the init method which expect these arguments: ${renderElement} ${router} ${providers} ` ); return this.root; } /** * Initializes all core components as Vue components. * * @memberOf module:app/adapter/view/vue * @returns {Object} */ initComponents(renderElement, router, providers) { warn( 'initComponents', ` You need to overwrite the initComponents method which expect these arguments: ${renderElement} ${router} ${providers} ` ); } /** * Returns the component as a Vue component. * Includes the full rendered template with all overrides. * * @param componentName * @memberOf module:app/adapter/view/vue * @returns {Function} */ createComponent(componentName) { warn( 'createComponent', ` You need to overwrite the createComponent method which expect these arguments: ${componentName} ` ); } /** * Returns a final Vue component by its name. * * @param componentName * @memberOf module:app/adapter/view/vue * @returns {null|Component} */ getComponent(componentName) { warn( 'getComponent', ` You need to overwrite the getComponent method which expect these arguments: ${componentName} ` ); } /** * Returns the complete set of available Vue components. * * @memberOf module:app/adapter/view/vue * @returns {Object} */ getComponents() { warn( 'getComponents', 'You need to overwrite the getComponents method' ); } /** * Returns the adapter wrapper * * @memberOf module:app/adapter/view/vue * @returns {Vue} */ getWrapper() { warn( 'getWrapper', 'You need to overwrite the getWrapper method' ); } /** * Returns the name of the adapter * * @memberOf module:app/adapter/view/vue * @returns {string} */ getName() { warn( 'getName', 'You need to overwrite the getName method' ); } /** * Returns the Vue.set function * * @memberOf module:app/adapter/view/vue * @returns {function} */ setReactive() { warn( 'setReactive', 'You need to overwrite the setReactive method' ); } /** * Returns the Vue.delete function * * @memberOf module:app/adapter/view/vue * @returns {function} */ deleteReactive() { warn( 'deleteReactive', 'You need to overwrite the deleteReactive method' ); } }
JavaScript
class P1WsClient extends EventEmitter { /** Create a new insance of P1 web socket client. * * @param {?object} options - Optional parameters. * @param {string} [options.host='127.0.0.1:8088'] - _hostname_`:`_port_ * of the web socket server. * @param {?int} [options.timeout=5] - Timeout in seconds to wait for next * telegram from the P1. Must be between 5 and 120. When `options.dsmr22` * has been set, a default of 5 is used. * @throws `TypeError` - When a parameter has an invalid type. * @throws `RangeError` - When a parameter has an invalid value. * @throws `SyntaxError` - When a mandatory parameter is missing or an * optional parameter is not applicable. */ constructor (options) { super() this._options = { hostname: '127.0.0.1', port: 8088, timeout: 5 } const optionParser = new homebridgeLib.OptionParser(this._options) optionParser.hostKey() optionParser.intKey('timeout', 5, 120) optionParser.parse(options) this._ws = {} this._timeout = {} } async connect (path) { const url = 'ws://' + this._options.hostname + ':' + this._options.port + '/' + path const ws = new WebSocket(url) this._ws[path] = ws ws.on('open', () => { this.emit('connect', url) this._setTimeout(path) }) ws.on('close', () => { if (this._timeout[path] != null) { clearTimeout(this._timeout[path]) } ws.removeAllListeners() delete this._ws[path] this.emit('disconnect', url) }) ws.on('message', (message) => { this._setTimeout(path) if (path !== 'telegram') { try { message = JSON.parse(message) } catch (error) { this.emit('error', error) } } this.emit(path, message) }) ws.on('error', (error) => { this.emit('error', error) }) } isConnected (path) { return this._ws[path] != null } _setTimeout (path) { if (this._timeout[path] != null) { clearTimeout(this._timeout[path]) } this._timeout[path] = setTimeout(() => { this.emit('error', new Error( `no data recevied in ${this._options.timeout} seconds` )) this._ws[path].terminate() // this.disconnect(path) }, this._options.timeout * 1000) } disconnect (path) { if (this._ws[path] != null) { this._ws[path].close() } } }
JavaScript
class ComponentsToasts { constructor() { // References to page items that might require an update this._liveToast = null; this._selectToastPlacement = null; // Initialization of the page plugins this._initLiveToast(); this._initToastPlacement(); } _initLiveToast() { const liveToastEl = document.getElementById('liveToast'); const liveToastBtnEl = document.getElementById('liveToastBtn'); if (liveToastEl && liveToastBtnEl) { this._liveToast = new bootstrap.Toast(document.getElementById('liveToast')); liveToastBtnEl.addEventListener('click', (event) => { this._liveToast && this._liveToast.show(); }); } } _initToastPlacement() { const selectToastPlacementEl = document.getElementById('selectToastPlacement'); const toastPlacementEl = document.getElementById('toastPlacement'); if (selectToastPlacementEl && toastPlacementEl) { selectToastPlacementEl.addEventListener('change', (event) => { toastPlacementEl.className = `toast-container position-absolute p-3 ${selectToastPlacementEl.value}`; }); } } }
JavaScript
class InvenioRequestSerializer { _addAggregations(getParams, aggregations) { aggregations.forEach(aggregation => { const rootKey = Object.keys(aggregation)[0]; /** * The selection represent any one of the aggregation values clicked at any level of depth. * Its value is the whole path e.g. for Type -> Publication -> (Subtype)Article * the value will be type.publication.subtype.article from which the array will be created * @type {string[]} */ const selection = aggregation[rootKey]['value'].split('.'); /** * For each category:name pair (e.g. subtype:article) in the path * add it to the request if not already present */ for (let i = 0, j = 1; j <= selection.length; i += 2, j += 2) { const key = selection[i]; const value = selection[j]; key in getParams ? getParams[key].push(value) : (getParams[key] = [value]); } }); } /** * Return a serialized version of the app state `query` for the API backend. * @param {object} stateQuery the `query` state to serialize */ serialize = stateQuery => { const { queryString, sortBy, sortOrder, page, size, aggregations, } = stateQuery; const getParams = {}; if (queryString !== null) { getParams['q'] = queryString; } if (sortBy !== null) { getParams['sort'] = sortBy; if (sortOrder !== null) { getParams['sort'] = sortOrder === 'desc' ? `-${sortBy}` : sortBy; } } if (page > 0) { getParams['page'] = page; } if (size > 0) { getParams['size'] = size; } this._addAggregations(getParams, aggregations); return Qs.stringify(getParams, { arrayFormat: 'repeat' }); }; }
JavaScript
class Select3 { constructor(config) { this.container = qsi(config.containerId); this.update(config); } update(config) { this.config = config; this.filteredData = config.data; var ctx = this; this.selected = newElement("div", { class: "select-box-selected" }, "", { click: this.toggleCollapse.bind(this, ctx) }); this.container.beforeEnd(this.selected); if (this.config.allowClear) { this.cleaner = newElement("p", { class: "cleaner" }, "&#9747;", { click: this.clearSelected.bind(this, ctx) }); this.container.beforeEnd(this.cleaner); } if (this.config.withSearch) { this.searcher = newElement("input", { type: "text", placeholder: "Search" }, "", { keyup: this.onSearch.bind(this, ctx) }); this.container.beforeEnd(this.searcher); } this.items = newElement("div", { tabindex: 0, class: "select-box-items" }, "", { keydown: this.onkeydown.bind(this, ctx) }); this.container.beforeEnd(this.items); this.container.addClass("select-box-values"); this.selectedInput = newElement("input", { type: "text", name: config.containerId, value: this.val() }); this.container.afterEnd(this.selectedInput); this.render(); } render() { if (this.config.disabled) { this.selected.addClass("select-disabled"); this.collapse(); } else { this.selected.class("-select-disabled"); } this.renderSelected(); this.renderData(); } renderSelected() { var st = this.displayLabels(); if (st === "") { this.selected.innerText = this.config.placeholder; this.selected.class("select-novalue"); } else { this.selected.innerText = st; this.selected.class("-select-novalue"); } this.selectedInput.val(this.val()); } displayLabels() { var label = this.filteredData.filter(x => x.selected === true).map(x => x.label).join(","); return label; } redraw() { this.filteredData = this.config.data; this.renderData(); this.renderSelected(); } clearSelected() { for (var i = 0; i < this.config.data.length; i++) { var it = this.config.data[i]; if (!it.optgroup && !it.disabled && !it.locked) { this.config.data[i].selected = false; } } this.redraw(); } inverseSelection() { for (var i = 0; i < this.config.data.length; i++) { var it = this.config.data[i]; if (!it.optgroup && !it.disabled && !it.locked) { it.selected = !it.selected; } } this.redraw(); } selectAll() { for (var i = 0; i < this.config.data.length; i++) { var it = this.config.data[i]; if (!it.optgroup && !it.disabled && !it.locked) { it.selected = true; } } this.redraw(); } renderData() { this.items.html(""); var ctx = this; let index = 0; for (let option of this.filteredData) { this.renderOption(option, index, ctx); } this.container.css({ width: this.items.outerWidth() }); var style = {}; if (ctx.config.size) { style.height = "" + (Math.min(+ctx.config.size, ctx.filteredData.length) * 28) + "px"; ctx.items.css(style); } } renderOption(option, index, ctx) { if (!option.optgroup) { var cl = "select-box-value"; if (option.selected) { cl += " select-box-value-active"; } let item = newElement("div", { i: index, class: cl, value: option.value }, option.label); if (!option.disabled && !option.locked) { item.on("click", this.onClickValue.bind(this, ctx, item)); } if (option.disabled) { item.class("select-box-disabled"); } this.items.beforeEnd(item); index++; } else { let item = newElement("div", { class: "select-box-title" }, option.label); this.items.beforeEnd(item); } } onkeydown(ctx, ev) { console.log("key", ev.keyCode); if (ev.keyCode === 38 || ev.keyCode === 40) { let index = 0; let selected = this.items.qs(".select-box-value-active"); if (selected == null) { selected = this.items.childNodes[0]; } if (ev.keyCode === 40) { //down index = +selected.attr("i") + 1; } else if (ev.keyCode === 38) { //up index = +selected.attr("i") - 1; if (index < 0) { index = this.items.childNodes.length - 1; } } var newSelected = this.items.qs("[i='" + index + "']"); if (newSelected == null) { newSelected = this.items.childNodes[0]; } selected.class("-select-box-value-active"); newSelected.class("select-box-value-active"); if (newSelected.hasClass("select-box-disabled")) { this.onkeydown(ctx, ev); } //newSelected.scrollIntoView(); } else if (ev.keyCode === 13) { //enter let selected = this.items.qs(".select-box-value-active"); this.onClickValue(ctx, selected, ev); } else if (ev.keyCode === 65 && ev.ctrlKey && ctx.config.maximumSelectionLength !== 1) { ev.cancelBubble = true; ev.preventDefault(); ev.stopImmediatePropagation(); this.selectAll(); } else if (ev.keyCode === 73 && ev.ctrlKey && ctx.config.maximumSelectionLength !== 1) { this.inverseSelection(); } } onSearch(ctx, ev) { console.log(ev); var text = ctx.searcher.val(); ctx.filteredData = ctx.config.data.filter(x => x.label.startsWith(text)); ctx.renderData(); } onClickValue(ctx, item, ev) { var val = item.val(); var found = ctx.filteredData.find(x => x.value == val); found.selected = !found.selected; if (!ev.ctrlKey) { ctx.filteredData.filter(x => x !== found && x.selected === true).forEach(x => x.selected = false); ctx.items.childNodes.class("-select-box-value-active"); } if (found.selected) { item.class("select-box-value-active"); } else { item.class("-select-box-value-active"); } if (!ctx.config.maximumSelectionLength === 1) { if (!found.selected) { item.removeClass("select-box-value-active"); } else { item.addClass("select-box-value-active"); } } this.renderSelected(); if (ctx.closeOnSelect) { ctx.collapse(); } } collapse() { this.items.show(false); if (isDef(this.searcher)) { this.searcher.show(false); } } uncollapse() { this.items.show(); if (isDef(this.searcher)) { this.searcher.show(true); } } toggleCollapse() { if (!this.config.disabled) { this.items.toggleVisible(); if (this.items.isVisible()) { this.items.focus(); this.selected.class("select-box-selected-up"); } else { this.selected.class("-select-box-selected-up"); } if (isDef(this.searcher)) { this.searcher.toggleVisible(); if (this.searcher.isVisible()) { this.searcher.focus(); } } } } val(value) { if (arguments.length >= 1) { var found = this.items.find(x => x.val() === value); if (found) { found.addClass("select-box-value-active"); } else { console.error("value " + value + " not found"); } } else { var label = this.filteredData.filter(x => x.selected === true).map(x => x.value).join(","); return label; } } }
JavaScript
class MediaLiveEventIncomingDataChunkDroppedEventData { /** * Create a MediaLiveEventIncomingDataChunkDroppedEventData. * @member {string} [timestamp] Gets the timestamp of the data chunk dropped. * @member {string} [trackType] Gets the type of the track (Audio / Video). * @member {number} [bitrate] Gets the bitrate of the track. * @member {string} [timescale] Gets the timescale of the Timestamp. * @member {string} [resultCode] Gets the result code for fragment drop * operation. * @member {string} [trackName] Gets the name of the track for which fragment * is dropped. */ constructor() { } /** * Defines the metadata of MediaLiveEventIncomingDataChunkDroppedEventData * * @returns {object} metadata of MediaLiveEventIncomingDataChunkDroppedEventData * */ mapper() { return { required: false, serializedName: 'MediaLiveEventIncomingDataChunkDroppedEventData', type: { name: 'Composite', className: 'MediaLiveEventIncomingDataChunkDroppedEventData', modelProperties: { timestamp: { required: false, readOnly: true, serializedName: 'timestamp', type: { name: 'String' } }, trackType: { required: false, readOnly: true, serializedName: 'trackType', type: { name: 'String' } }, bitrate: { required: false, readOnly: true, serializedName: 'bitrate', type: { name: 'Number' } }, timescale: { required: false, readOnly: true, serializedName: 'timescale', type: { name: 'String' } }, resultCode: { required: false, readOnly: true, serializedName: 'resultCode', type: { name: 'String' } }, trackName: { required: false, readOnly: true, serializedName: 'trackName', type: { name: 'String' } } } } }; } }
JavaScript
class VigenereCipheringMachine { constructor(reverse) { this.reverse = reverse === false ? true : false; this.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } encryptString(string, key) { let result = ""; let counter = 0; for (let i = 0; i < string.length; i++) { if (counter === key.length) counter = 0; if (!this.alphabet.includes(string[i])) { result += string[i]; } else { const letterIndex = (this.alphabet.indexOf(string[i]) + this.alphabet.indexOf(key[counter])) % 26; console.log(letterIndex); result += this.alphabet[letterIndex]; counter++; } } return this.reverse ? result.split("").reverse().join("") : result; } decryptString(string, key) { let result = ""; let counter = 0; for (let i = 0; i < string.length; i++) { if (counter === key.length) counter = 0; if (!this.alphabet.includes(string[i])) { result += string[i]; } else { let letterIndex = (this.alphabet.indexOf(string[i]) - this.alphabet.indexOf(key[counter])) % 26; letterIndex = letterIndex < 0 ? letterIndex + 26 : letterIndex; result += this.alphabet[letterIndex]; counter++; } } return this.reverse ? result.split("").reverse().join("") : result; } encrypt(string, key) { if (!string || !key) throw new Error("Incorrect arguments!"); const upperCasedString = string.toUpperCase(); const upperCasedKey = key.toUpperCase(); return this.encryptString(upperCasedString, upperCasedKey); } decrypt(string, key) { if (!string || !key) throw new Error("Incorrect arguments!"); const upperCasedString = string.toUpperCase(); const upperCasedKey = key.toUpperCase(); return this.decryptString(upperCasedString, upperCasedKey); } }
JavaScript
class Services { async getCategories(toolshedUrl) { const paramsString = `tool_shed_url=${toolshedUrl}&controller=categories`; const url = `${getAppRoot()}api/tool_shed/request?${paramsString}`; try { const response = await axios.get(url); return response.data; } catch (e) { rethrowSimple(e); } } async getRepositories(params) { const paramsString = this._getParamsString(params); const url = `${getAppRoot()}api/tool_shed/request?controller=repositories&${paramsString}`; try { const response = await axios.get(url); const data = response.data; const incoming = data.hits.map((x) => x.repository); incoming.forEach((x) => { x.owner = x.repo_owner_username; x.times_downloaded = this._formatCount(x.times_downloaded); x.repository_url = `${data.hostname}repository?repository_id=${x.id}`; }); return incoming; } catch (e) { rethrowSimple(e); } } async getRepository(toolshedUrl, repositoryId) { const paramsString = `tool_shed_url=${toolshedUrl}&id=${repositoryId}&controller=repositories&action=metadata`; const url = `${getAppRoot()}api/tool_shed/request?${paramsString}`; try { const response = await axios.get(url); const data = response.data; const table = Object.keys(data).map((key) => data[key]); if (table.length === 0) { throw "Repository does not contain any installable revisions."; } table.sort((a, b) => b.numeric_revision - a.numeric_revision); table.forEach((x) => { if (Array.isArray(x.tools)) { x.profile = x.tools.reduce( (value, current) => (current.profile > value ? current.profile : value), null ); } }); return table; } catch (e) { rethrowSimple(e); } } async getRepositoryByName(toolshedUrl, repositoryName, repositoryOwner) { const params = `tool_shed_url=${toolshedUrl}&name=${repositoryName}&owner=${repositoryOwner}`; const url = `${getAppRoot()}api/tool_shed/request?controller=repositories&${params}`; try { const response = await axios.get(url); const length = response.data.length; if (length > 0) { const result = response.data[0]; result.repository_url = `${toolshedUrl}repository?repository_id=${result.id}`; return result; } else { throw "Repository details not found."; } } catch (e) { rethrowSimple(e); } } async getInstalledRepositories(options = {}) { const Galaxy = getGalaxyInstance(); const url = `${getAppRoot()}api/tool_shed_repositories/?uninstalled=False`; try { const response = await axios.get(url); const repositories = this._groupByNameOwnerToolshed(response.data, options.filter, options.selectLatest); this._fixToolshedUrls(repositories, Galaxy.config.tool_shed_urls); return repositories; } catch (e) { rethrowSimple(e); } } async getInstalledRepositoriesByName(repositoryName, repositoryOwner) { const paramsString = `name=${repositoryName}&owner=${repositoryOwner}`; const url = `${getAppRoot()}api/tool_shed_repositories?${paramsString}`; try { const response = await axios.get(url); const data = response.data; const result = {}; data.forEach((x) => { const d = { status: x.status, installed: !x.deleted && !x.uninstalled, }; result[x.changeset_revision] = result[x.installed_changeset_revision] = d; }); return result; } catch (e) { rethrowSimple(e); } } async installRepository(payload) { const url = `${getAppRoot()}api/tool_shed_repositories`; try { const response = await axios.post(url, payload); return response.data; } catch (e) { rethrowSimple(e); } } async uninstallRepository(params) { const paramsString = Object.keys(params).reduce(function (previous, key) { return `${previous}${key}=${params[key]}&`; }, ""); const url = `${getAppRoot()}api/tool_shed_repositories?${paramsString}`; try { const response = await axios.delete(url); return response.data; } catch (e) { rethrowSimple(e); } } _groupByNameOwnerToolshed(incoming, filter, selectLatest) { if (selectLatest) { const getSortValue = (x, y) => { return x === y ? 0 : x < y ? -1 : 1; }; incoming = incoming.sort((a, b) => { return ( getSortValue(a.name, b.name) || getSortValue(a.owner, b.owner) || getSortValue(a.tool_shed, b.tool_shed) || getSortValue(parseInt(b.ctx_rev), parseInt(a.ctx_rev)) ); }); } const hash = {}; const repositories = []; incoming.forEach((x) => { const hashCode = `${x.name}_${x.owner}_${x.tool_shed}`; if (!filter || filter(x)) { if (!hash[hashCode]) { hash[hashCode] = true; repositories.push(x); } } }); return repositories; } _fixToolshedUrls(incoming, urls) { incoming.forEach((x) => { for (const url of urls) { if (url.includes(x.tool_shed)) { x.tool_shed_url = url; break; } } }); } _formatCount(value) { if (value > 1000) { return `>${Math.floor(value / 1000)}k`; } return value; } _getParamsString(params) { if (params) { return Object.keys(params).reduce(function (previous, key) { return `${previous}${key}=${params[key]}&`; }, ""); } else { return ""; } } }
JavaScript
class ReflectionMethod { /** * Constructor. * * @param {ReflectionClass} reflectionClass * @param {string} methodName */ constructor(reflectionClass, methodName) { /** * @type {ReflectionClass} * * @private */ this._class = reflectionClass; /** * @type {string} * * @private */ this._name = methodName; /** * @type {Function} * * @private */ this._method = undefined; /** * @type {boolean} * * @private */ this._static = false; let method; if ((method = reflectionClass._methods[methodName])) { this._method = method; } else if ((method = reflectionClass._staticMethods[methodName])) { this._method = method; this._static = true; } else { throw new ReflectionException('Unknown method "' + methodName + '\''); } /** * @type {string} * * @private */ this._type = isGeneratorFunction(this._method) ? ReflectionMethod.GENERATOR : ReflectionMethod.FUNCTION; /** * @type {boolean} * * @private */ this._async = isAsyncFunction(this._method); const classConstructor = reflectionClass.getConstructor(); /** * @type {string} * * @private */ this._docblock = (this._static ? classConstructor[methodName] : classConstructor.prototype[methodName])[Symbol.docblock]; } /** * Gets the reflection class. * * @returns {ReflectionClass} */ get reflectionClass() { return this._class; } /** * Gets the method name. * * @returns {string} */ get name() { return this._name; } /** * Gets if this method is static. * * @returns {boolean} */ get isStatic() { return this._static; } /** * Gets if the function is a generator. * * @returns {boolean} */ get isGenerator() { return this._type === ReflectionMethod.GENERATOR; } /** * Is this function async? * * @returns {boolean} */ get isAsync() { return this._async; } /** * Docblock. * * @returns {string} */ get docblock() { return this._docblock; } /** * Gets the class metadata. * * @returns {[Function, *][]} */ get metadata() { return MetadataStorage.getMetadata(this._class.getConstructor(), this._name); } }
JavaScript
class BaseChart { constructor(svg) { this.svg = svg.attr("class", "").html(""); this.selections = {}; this.margin = { top: 10, right: 10, bottom: 30, left: 40, }; } setHeight(d) { this.svg.attr("height", d); this.outerHeight = d; this.height = d - this.margin.top - this.margin.bottom; return this; } setWidth(d) { this.svg.attr("width", d); this.outerWidth = d; this.width = d - this.margin.left - this.margin.right; return this; } set(property, value) { this[property] = value; return this; } }
JavaScript
class MountainCar { /** * Constructor of MountainCar. */ constructor() { // Constants that characterize the system. this.minPosition = -1.2; this.maxPosition = 0.6; this.maxSpeed = 0.07; this.minSpeed = -0.07; this.goalPosition = 0.5; this.goalVelocity = 0; this.gravity = 0.0025; this.carWidth = 0.2; this.carHeight = 0.1; this.force = 0.0013; this.setRandomState(); } /** * Set the state of the mountain car system randomly. */ setRandomState() { // The state variables of the mountain car system. // Car position this.position = Math.random() / 5 - 0.6; // Car velocity. this.velocity = 0; } /** * Get current state as a tf.Tensor of shape [1, 2]. */ getStateTensor() { return [this.position, this.velocity]; } /** * Update the mountain car system using an action. * @param {number} action Only the sign of `action` matters. * Action is an integer, in [-1, 0, 1] * A value of 1 leads to a rightward force of a fixed magnitude. * A value of -1 leads to a leftward force of the same fixed magnitude. * A value of 0 leads to no force applied. * @returns {bool} Whether the simulation is done. */ update(action) { this.velocity += action * this.force - Math.cos(3 * this.position) * this.gravity; this.velocity = Math.min(Math.max(this.velocity, this.minSpeed), this.maxSpeed); this.position += this.velocity this.position = Math.min(Math.max(this.position, this.minPosition), this.maxPosition); if (this.position === this.minPosition && this.velocity < 0 ) this.velocity = 0; return this.isDone(); } /** * Determine whether this simulation is done. * * A simulation is done when `position` reaches `goalPosition` * and `velocity` is greater than zero. * * @returns {bool} Whether the simulation is done. */ isDone() { return ( this.position >= this.goalPosition ) && ( this.velocity >= this.goalVelocity ); } render(canvas){ if (!canvas.style.display) { canvas.style.display = 'block'; } const X_MIN = this.minPosition; const X_MAX = this.maxPosition; const xRange = X_MAX - X_MIN; const scale = canvas.width / xRange; const context = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); const halfW = canvas.width / 2; // Draw the cart. const cartW = this.carWidth * scale; const cartH = this.carHeight * scale; const cartX = (this.position - this.minPosition) * scale; const cartY = canvas.height - (Math.sin(3 * this.position) * 0.45 + 0.55) * scale; //Set the origin to the center of the cart context.setTransform(1, 0, 0, 1, cartX, cartY); //Rotate the canvas around the origin context.rotate(- Math.cos(3 * this.position)); //Draw the cart context.strokeStyle = '#000000'; context.lineWidth = 2; context.strokeRect(- cartW / 2, -1.5 * cartH, cartW, cartH); // Draw the wheels under the cart. const wheelRadius = cartH / 4; for (const offsetX of [-1, 1]) { context.beginPath(); context.lineWidth = 2; context.arc( - cartW / 4 * offsetX, wheelRadius - cartH / 2, wheelRadius, 0, 2 * Math.PI); context.stroke(); } // Restore canvas state as saved from above context.setTransform(1,0,0,1,0,0); // Draw the ground. context.beginPath(); context.strokeStyle = '#000000'; context.lineWidth = 1; const step = (this.maxPosition - this.minPosition) / 100; for (let x = this.minPosition; x < this.maxPosition; x += step) { const y = canvas.height - (Math.sin(3 * x) * 0.45 + 0.55) * scale; context.lineTo((x - this.minPosition) * scale, y); context.moveTo((x - this.minPosition) * scale, y); } context.stroke(); } }
JavaScript
class SkinInstanceCachedObject extends RefCountedObject { constructor(skin, skinInstance) { super(); this.skin = skin; this.skinInstance = skinInstance; } }
JavaScript
class SkinInstanceCache { // map of SkinInstances allowing those to be shared between // (specifically a single glb with multiple render components) // It maps a rootBone to an array of SkinInstanceCachedObject // this allows us to find if a skin instance already exists for a rootbone, and a specific skin static _skinInstanceCache = new Map(); // #if _DEBUG // function that logs out the state of the skin instances cache static logCachedSkinInstances() { console.log("CachedSkinInstances"); SkinInstanceCache._skinInstanceCache.forEach(function (array, rootBone) { console.log(`${rootBone.name}: Array(${array.length})`); for (let i = 0; i < array.length; i++) { console.log(` ${i}: RefCount ${array[i].getRefCount()}`); } }); } // #endif // returns cached or creates a skin instance for the skin and a rootBone, to be used by render component // on the specified entity static createCachedSkinedInstance(skin, rootBone, entity) { // try and get skin instance from the cache let skinInst = SkinInstanceCache.getCachedSkinInstance(skin, rootBone); // don't have skin instance for this skin if (!skinInst) { skinInst = new SkinInstance(skin); skinInst.resolve(rootBone, entity); // add it to the cache SkinInstanceCache.addCachedSkinInstance(skin, rootBone, skinInst); } return skinInst; } // returns already created skin instance from skin, for use on the rootBone // ref count of existing skinInstance is increased static getCachedSkinInstance(skin, rootBone) { let skinInstance = null; // get an array of cached object for the rootBone const cachedObjArray = SkinInstanceCache._skinInstanceCache.get(rootBone); if (cachedObjArray) { // find matching skin const cachedObj = cachedObjArray.find((element) => element.skin === skin); if (cachedObj) { cachedObj.incRefCount(); skinInstance = cachedObj.skinInstance; } } return skinInstance; } // adds skin instance to the cache, and increases ref count on it static addCachedSkinInstance(skin, rootBone, skinInstance) { // get an array for the rootBone let cachedObjArray = SkinInstanceCache._skinInstanceCache.get(rootBone); if (!cachedObjArray) { cachedObjArray = []; SkinInstanceCache._skinInstanceCache.set(rootBone, cachedObjArray); } // find entry for the skin let cachedObj = cachedObjArray.find((element) => element.skin === skin); if (!cachedObj) { cachedObj = new SkinInstanceCachedObject(skin, skinInstance); cachedObjArray.push(cachedObj); } cachedObj.incRefCount(); } // removes skin instance from the cache. This decreases ref count, and when that reaches 0 it gets destroyed static removeCachedSkinInstance(skinInstance) { if (skinInstance) { const rootBone = skinInstance.rootBone; if (rootBone) { // an array for boot bone const cachedObjArray = SkinInstanceCache._skinInstanceCache.get(rootBone); if (cachedObjArray) { // actual skin instance const cachedObjIndex = cachedObjArray.findIndex((element) => element.skinInstance === skinInstance); if (cachedObjIndex >= 0) { // dec ref on the object const cachedObj = cachedObjArray[cachedObjIndex]; cachedObj.decRefCount(); // last reference, needs to be destroyed if (cachedObj.getRefCount() === 0) { cachedObjArray.splice(cachedObjIndex, 1); // if the array is empty if (!cachedObjArray.length) { SkinInstanceCache._skinInstanceCache.delete(rootBone); } // destroy the skin instance if (skinInstance) { skinInstance.destroy(); cachedObj.skinInstance = null; } } } } } } } }
JavaScript
class App extends React.Component { constructor(){ super() this.state={ collapsed:true, isAuthenticated:!!localStorage.getItem('token'), modal: false } } toggleNavbar =() =>{ this.setState({ collapsed: !this.state.collapsed }) } toggle = () => { this.setState(prevState => ({ modal: !prevState.modal })) } handleIsAuthenticated=(bool)=>{ this.setState(()=>({ isAuthenticated:bool })) } render() { return ( <BrowserRouter> <div> <Navbar className="navbar navbar-expand-sm ml-auto" color="faded" light > <NavItem className="nav"><Link to="/" className="nav-link" > CODE Platform </Link></NavItem> <NavbarToggler onClick={this.toggleNavbar} className="mr-2" /> <Collapse isOpen={!this.state.collapsed} navbar> <Nav navbar className="navbar-nav mr-auto" > <NavItem> <Link to="/courses" className="navlink mr-3" > Courses </Link> </NavItem> <NavItem> <Link to="/tracks" className="navlink mr-3" > Tracks </Link> </NavItem> <NavItem> <Link to="/forum" className="navlink mr-3" > Forum </Link> </NavItem> </Nav> <Nav navbar className="rightNav mr-1"> <NavItem> <Button className='btn btn-primary' onClick={this.toggle}>Sign In</Button> </NavItem> </Nav> </Collapse> </Navbar> <Switch> <Route path="/register" component={Register} exact={true} /> <Route path="/google/signin" component={GoogleAuthentication} exact={true} /> </Switch> <Modal className='modal-lg' isOpen={this.state.modal} toggle={this.toggle}> <ModalHeader toggle={this.toggle}>Sign In With</ModalHeader> <ModalBody> <Register /> <hr/> <div className='text-center'> <div className='btn-group'> <Google /> <Facebook /> <Github /> </div> </div> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.toggle}>Cancel</Button> </ModalFooter> </Modal> </div> </BrowserRouter> ) } }
JavaScript
class I18n { /** * Creates an I18n instance. * * @returns {I18n} */ constructor() { i18n = i18n ? i18n : this; return i18n; } /** * Changes localization options. * * @param {Object} options * @param {Object} options.strings * @param {string} options.currency * @param {string} options.locale * @returns {this} */ use({strings = {}, currency = '$', locale = 'en-US'} = {}) { this.strings = strings; this.currency = currency; this.locale = locale; return this; } /** * Tag function for template string. Uses i18n instance localization options for translation. * * @param {Array<string>} literals * @param {...*} values * @returns {string} */ translate(literals, ...values) { let translationKey = buildKey(literals); let translationString; if (this.strings[translationKey]) { translationString = this.strings[translationKey][this.locale]; } if (!translationString) { translationString = translationKey; } if (translationString) { let typeInfoForValues = literals.slice(1).map(extractTypeInfo); let localizedValues = values.map((value, index) => localize(value, this, typeInfoForValues[index])); return buildMessage(translationString, ...localizedValues); } return 'Error: translation missing!'; } }
JavaScript
class YoudaoTranslator { constructor() { this.MAX_RETRY = 3; // Max retry times after failure. this.HOST = "http://fanyi.youdao.com"; // Youdao translation url this.sign = ""; // one of request parameters // this.languages = {}; /** * Request headers */ this.HEADERS = { // accept: "*/*", // "accept-language": // "en,zh;q=0.9,en-GB;q=0.8,en-CA;q=0.7,en-AU;q=0.6,en-ZA;q=0.5,en-NZ;q=0.4,en-IN;q=0.3,zh-CN;q=0.2", "content-type": "application/x-www-form-urlencoded; charset=UTF-8", Cookie: "[email protected]; UM_distinctid=1746d0c442e97f-042f749d1c0fb3-1711424a-1fa400-1746d0c442f8a3; OUTFOX_SEARCH_USER_ID_NCOO=608404064.645282; _ntes_nnid=15061f9646bde23f26634549a2af10f6,1599559922661; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcEdBWwXs8mW8MJ2vXrx; ___rl__test__cookies=1599639537705", Referer: "http://fanyi.youdao.com/?keyfrom=dict2.index" }; /** * Language to translator language code. */ this.LAN_TO_CODE = new Map(LANGUAGES); /** * Translator language code to language. */ this.CODE_TO_LAN = new Map(LANGUAGES.map(([lan, code]) => [code, lan])); /** * TTS audio instance. */ this.AUDIO = new Audio(); } /** * Parse the translate result. * * @param {Object} result translate result * @returns {Object} parsed result */ parseResult(result) { let resText = result.translateResult && result.translateResult[0] && result.translateResult[0][0] ? result.translateResult[0][0].tgt : ""; let originText = resText ? result.translateResult[0][0].src : ""; // console.log('resText:', resText); let parsed = {}; parsed.originalText = originText; parsed.mainMeaning = resText; return parsed; /* code below is from baidu.js */ // if (result.trans_result.phonetic) // parsed.tPronunciation = result.trans_result.phonetic // .map(e => e.trg_str) // .reduce((t1, t2) => t1 + " " + t2); // get the result by splicing the array // // japanese target pronunciation // if (result.trans_result.jp_pinyin) { // parsed.tPronunciation = result.trans_result.jp_pinyin[0].dst; // } // // dictionary is not in the result // if (result.dict_result) { // if (result.dict_result.simple_means) { // parsed.sPronunciation = result.dict_result.simple_means.symbols[0].ph_en; // parsed.detailedMeanings = []; // for (let part of result.dict_result.simple_means.symbols[0].parts) { // let meaning = {}; // meaning.pos = part.part; // part of speech // meaning.meaning = part.means.reduce( // (meaning1, meaning2) => meaning1 + "\n" + meaning2 // ); // parsed.detailedMeanings.push(meaning); // } // } // if (result.dict_result.edict) { // parsed.definitions = []; // // iterate pos // for (let item of result.dict_result.edict.item) { // // iterate meaning of each pos // for (let tr of item.tr_group) { // let meaning = {}; // meaning.pos = item.pos; // meaning.meaning = tr.tr[0]; // meaning.example = tr.example[0]; // meaning.synonyms = tr.similar_word; // parsed.definitions.push(meaning); // } // } // } // if (result.dict_result.content) { // parsed.sPronunciation = result.dict_result.voice[0].en_phonic; // if (!parsed.detailedMeanings) parsed.detailedMeanings = []; // for (let item of result.dict_result.content[0].mean) { // let meaning = {}; // meaning.pos = item.pre; // meaning.meaning = Object.keys(item.cont)[0]; // parsed.detailedMeanings.push(meaning); // } // } // } // if (result.liju_result.double) { // parsed.examples = []; // let examples = result.liju_result.double; // examples = JSON.parse(examples); // for (let sentence of examples) { // let example = {}; // // source language examples // example.source = sentence[0] // .map(a => { // if (a.length > 4) return a[0] + a[4]; // return a[0]; // }) // .reduce((a1, a2) => a1 + a2); // // target language examples // example.target = sentence[1] // .map(a => { // if (a.length > 4) return a[0] + a[4]; // return a[0]; // }) // .reduce((a1, a2) => a1 + a2); // parsed.examples.push(example); // } // } // return parsed; } /** * Get supported languages of this API. * * @returns {Set<String>} supported languages */ supportedLanguages() { return new Set(this.LAN_TO_CODE.keys()); } /** * Detect language of given text. * * @param {String} text text to detect * @returns {Promise} then(result) used to return request result. catch(error) used to catch error */ detect(text) { // return axios({ // url: "langdetect", // method: "post", // baseURL: this.HOST, // headers: this.HEADERS, // data: new URLSearchParams({ // query: text // }), // timeout: 5000 // }).then(result => { // if (result.data.msg === "success") // return Promise.resolve(this.CODE_TO_LAN.get(result.data.lan)); // else return Promise.reject(result.data); // }); } /** * Translate given text. * * @param {String} text text to translate * @param {String} from source language * @param {String} to target language * @returns {Promise} then(result) used to return request result. catch(error) used to catch error */ translate(text, from = "AUTO", to = "AUTO") { let reTryCount = 0; // send translation request one time // if the first request fails, resend requests no more than {this.MAX_RETRY} times let translateOneTime = async function() { let detectedFrom = from; if (detectedFrom === "auto") { // detectedFrom = await this.detect(text); } let toCode = this.LAN_TO_CODE.get(to), fromCode = this.LAN_TO_CODE.get(detectedFrom); return axios({ url: "/translate_o", // + "?" + "from=" + fromCode + "&to=" + toCode, method: "post", baseURL: this.HOST, headers: this.HEADERS, data: this.getQueryStr(text), // includes sign timeout: 5000 }).then(result => { //console.log("HTTP status:", result.status); // console.log("HTTP statusText:", result.statusText); // console.log("result.data\n", result.data); if (result.data.errorCode !== 0) { if (reTryCount < this.MAX_RETRY) { reTryCount++; // get new token and gtk return translateOneTime(); } else return Promise.reject(result); } else return Promise.resolve(this.parseResult(result.data)); }); }.bind(this); // return translateOneTime(); } /** * Pronounce given text. * * @param {String} text text to pronounce * @param {String} language language of text * @param {String} speed "fast" or "slow" * * @returns {Promise<void>} pronounce finished */ // pronounce(text, language, speed) { // // Pause audio in case that it's playing. // this.stopPronounce(); // // Set actual speed value. // let speedValue = speed === "fast" ? "7" : "3"; // this.AUDIO.src = // this.HOST + // "gettts?lan=" + // this.LAN_TO_CODE.get(language) + // "&text=" + // encodeURIComponent(text) + // "&spd=" + // speedValue + // "&source=web"; // return this.AUDIO.play(); // } /** * Pause pronounce. */ // stopPronounce() { // if (!this.AUDIO.paused) { // this.AUDIO.pause(); // } // } /* eslint-disable */ /** * get query string that includes necessary data for Youdao API. * * @param {String} text text to translate * @param {String} from source language * @param {String} to target language * @returns {String} uri encoded string */ getQueryStr(text = "", from = "AUTO", to = "AUTO") { let sign = this.generateSign(text); // TODO support languages selecting let QSObj = { i: text, from: "AUTO", to: "AUTO", smartresult: "dict", client: "fanyideskweb", doctype: "json", version: "2.1", keyfrom: "fanyi.web", action: "FY_BY_REALTlME", ...sign }; const qs = querystring.stringify(QSObj); // console.log("qs\n", qs); return qs; } /** * get Youdai sign object * * @param {String} text text to translate * @returns {Object} sign object */ generateSign(text = "") { let t = crypto .createHash("md5") .update(navigator.appVersion) .digest("hex"), // n.md5(navigator.appVersion) r = "" + new Date().getTime(), i = r + parseInt(10 * Math.random(), 10); let raw = "fanyideskweb" + text + i + "]BjuETDhU)zqSxf-=B#7m"; let sign = crypto .createHash("md5") .update(raw) .digest("hex"); return { lts: r, // date getTime ms bv: t, // md5 navigator.appVersion string salt: i, // radom number sign }; } /* eslint-enable */ }
JavaScript
class Message { constructor (event, body = {}, groupId) { if (event instanceof Message) return event; this.event = event; this.body = body; this.groupId = groupId; } /** * Creates a message from a window.MessageEvent * * @param {MessageEvent} messageEvent * @return {Message} */ static createFromMessageEvent (messageEvent, debug = debug) { let data = messageEvent.data; // Parse a MessageEvent which originates from a relay if (typeof data === 'string') { debug('attempting to parse a relay-like message', data); data = dataFromRelayMessageEvent(messageEvent, debug); } if (!data) return; return new Message(data.event, data.body, data.groupId); } }
JavaScript
class CryptoCurrencyAPI { getValueFromAPI(coin) { alert("Calling External API..."); switch (coin) { case "Bitcoin": return "Bitcoin: $1,000"; case "Ethereum": return "Ethereum: $500"; case "Litecoin": return "Litecoin: $300"; } } }
JavaScript
class ConfigPicker extends PolymerElement { constructor() { super(); } static get is() { return 'tfma-config-picker'; } /** @return {!HTMLTemplateElement} */ static get template() { return template; } /** @return {!PolymerElementProperties} */ static get properties() { return { /** * A map where the keys are output names and the values are list of * classes for that output. * @type {!Object<!Array<number|string>>} */ allConfigs: {type: Object}, /** * The list of all outputs. * @private {!Array<string>} */ availableOutputs_: { type: Array, computed: 'computeAvailableOutputs_(allConfigs)', observer: 'availableOutputsChanged_', }, /** * The list of selected outputs. * @private {!Array<string>} */ selectedOutputs_: { type: Array, value: () => [], }, availableCombos_: { type: Array, computed: 'computeAvailableCombos_(allConfigs, selectedOutputs_)', }, /** * The values to be rendered. Each element represents a row. If the * original data is not a 1d array, the values are turned into a string * like "[[1, 2, 3], [4,5,6]]". * @type {!Array<number|string>} */ availableClasses_: { type: Array, computed: 'computeAvailableClasses_(availableCombos_)', observer: 'availableClassesChanged_', }, /** * The list of selected classes. * @private {!Array<string>} */ selectedClasses_: {type: Array}, /** * An object representing selected config. The keys are the name of the * output and the values are the class ids selected for that output. * @private {!Object<number|string>} */ selectedConfigs: { type: Object, computed: 'computeSelectedConfigs_(' + 'availableCombos_, availableClasses_, selectedClasses_)', notify: true, } }; } /** * Determines the list of available outputs. * @param {!Object} allConfigs * @return {!Array<string>} * @private */ computeAvailableOutputs_(allConfigs) { return Object.keys(allConfigs).sort(); } /** * Observer for the property data. It will update the arrayData property. * @param {!Array<string>} availableOutputs * @private */ availableOutputsChanged_(availableOutputs) { // Clears selected classes when available outputs changed. this.selectedClasses_ = []; // If there is only one output, select it automatically. if (availableOutputs.length == 1) { this.selectedOutputs_ = [availableOutputs[0]]; } } /** * Determines all available combinations of configurations. * @param {!Object<!Array<string|number>>} allConfigs * @param {!Array<string>} selectedOutputs * @return {!Array<!Object>} * @private */ computeAvailableCombos_(allConfigs, selectedOutputs) { const availableCombo = []; // If there are more than one output, we should prepend output name to help // differentiate bewteen the same class ids from different outputs. const prependOutputName = selectedOutputs.length > 1; selectedOutputs.forEach(outputName => { const classes = allConfigs[outputName] || []; classes.forEach(classId => { availableCombo.push({ outputName: outputName, classId: classId, prependOutputName: prependOutputName, }); }); }); return availableCombo; } /** * Builds the list of available classes from all possible configuration. * @param {!Array<!Object>} availableCombos * @return {!Array<string>} * @private */ computeAvailableClasses_(availableCombos) { const maybeAddOutputPrefix = (combo) => combo.prependOutputName ? (combo.outputName || 'Empty Output') + ', ' : ''; const determineClassIdToDisplay = (combo) => (combo.classId == '' ? 'No class' : combo.classId); return availableCombos.reduce((acc, combo) => { acc.push(maybeAddOutputPrefix(combo) + determineClassIdToDisplay(combo)); return acc; }, []); } /** * Observer for property availableClassses. * @param {!Array<string>} availableClasses * @private */ availableClassesChanged_(availableClasses) { // If there is only one class, select it automatically. if (availableClasses.length == 1) { this.selectedClasses_ = [availableClasses[0]]; } } /** * Builds the selected config from what available and what's selected. * @param {!Array<!Object>} availableCombos * @param {!Array<string>} availableClasses * @param {!Array<string>} selectedClasses * @return {!Object<!Object<string>>} * @private */ computeSelectedConfigs_(availableCombos, availableClasses, selectedClasses) { const config = {}; if (availableCombos && availableClasses && selectedClasses) { selectedClasses.forEach(selectedClass => { // Use index lookup to avoid parsing the generated strings which might // contain output names. const index = availableClasses.indexOf(selectedClass); const selectedCombo = availableCombos[index]; if (selectedCombo) { const outputName = selectedCombo.outputName; if (config[outputName]) { config[outputName].push(selectedCombo.classId); } else { config[outputName] = [selectedCombo.classId]; } } }); } return config; } /** * @param {!Array} array * @return {boolean} True if the given array has more than one element. * @private */ show_(array) { return !!array && array.length > 1; } }
JavaScript
class SampleTest extends PRuntime { afterBoot() { puzzle.module = "SampleTest" } }
JavaScript
class Logger { /** * @param {String} name The name of the logger, if passing __filename it will be extracted automatically. */ constructor(name) { name = Logger._extractFilename(name); if (loggers[name]) { return loggers[name]; } this.name = name; this.setLogLevel(defaultLogLevel); loggers[name] = this; return this; } setLogLevel(level) { _.forEach(["error", "warn", "info", "debug", "trace"], method => { // Binding their context to console ensures that they work just like calling directly on console, including correct line number reference. // Node.js doesn't have debug() and trace(). var methodExists = typeof console !== "undefined" && console[method]; if (methodExists && Logger.LogLevel[method.toLocaleUpperCase()] >= level) { this[method] = Function.prototype.bind.call(console[method], console, "[" + this.name + "]"); } else { this[method] = noop; } }); } static _extractFilename(filename) { if (_.endsWith(filename, ".js")) { var sep; if (_.includes(filename, "/")) { sep = "/"; } else { sep = "\\"; } var start = filename.lastIndexOf(sep) + 1; var end = filename.lastIndexOf("."); return filename.substr(start, end - start); } else { return filename; } } static setLogLevelAll(level) { defaultLogLevel = level; _.forEach(loggers, logger => { logger.setLogLevel(level); }); } }
JavaScript
class MenuItem extends React.Component { static propTypes = { /** * Children elements */ children: PropTypes.node.isRequired, /** * Custom className */ className: PropTypes.string, /** * onClick handler */ onClick: PropTypes.func, /** * Adds an icon to the menu item. */ icon: PropTypes.string, /** * Defines which direction the submenu will hang eg. left/right */ submenuDirection: PropTypes.string, /** * Is the menu item the currently selected item. */ selected: PropTypes.bool, /** * (for submenus) renders with a divide between items. */ divide: PropTypes.bool, /** * A title for the menu item that has a submenu. */ submenu: PropTypes.oneOfType([ PropTypes.string, PropTypes.object ]), /** * The href to use for the menu item. */ href: PropTypes.string, /** * The to link to use for the menu item. */ to: PropTypes.string, /** * The target to use for the menu item. */ target: PropTypes.string } static defaultProps = { submenuDirection: 'right' } /** * Determines what content will be rendered for the menu item. * * @return {Object} JSX */ get content() { // if does not have a submenu, just render the children if (!this.props.submenu) { return this.props.children; } // if it does have a submenu, render the following: const submenuClasses = classNames( 'carbon-menu-item__submenu', `carbon-menu-item__submenu--${this.props.submenuDirection}` ); return ( <React.Fragment> <MenuItem className='carbon-menu-item__submenu-title' href={ this.props.href } to={ this.props.to } > { this.props.submenu } </MenuItem> <ul className={ submenuClasses }> { React.Children.map( this.props.children, child => <li className='carbon-menu-item__submenu-item'>{ child }</li> ) } </ul> </React.Fragment> ); } /** * Returns the classes for the component. * * @method classes * @return {String} */ get classes() { return classNames( 'carbon-menu-item', this.props.className, { 'carbon-menu-item--divide': this.props.divide, 'carbon-menu-item--has-link': this.props.href || this.props.to || this.props.onClick, 'carbon-menu-item--has-submenu': this.props.submenu, 'carbon-menu-item--selected': this.props.selected } ); } /** * @method render */ render() { const component = this.props.submenu ? 'div' : Link; let props = { className: this.classes, href: this.props.href, to: this.props.to, target: this.props.target, onClick: this.props.onClick, icon: this.props.icon }; props = assign({}, props, tagComponent('menu-item', this.props)); return ( React.createElement( component, props, this.content ) ); } }
JavaScript
class ProxyCommand extends Command { constructor(command, opts) { super(opts); this.command = command; } runCommand(accessor, args) { return this.command.runCommand(accessor, args); } }
JavaScript
class ASTMStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ASTMStandard; if (null == bucket) cim_data.ASTMStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ASTMStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "ASTMStandard"; base.parse_attribute (/<cim:ASTMStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:ASTMStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.ASTMStandard; if (null == bucket) context.parsed.ASTMStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "ASTMStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "ASTMStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ASTMStandard_collapse" aria-expanded="true" aria-controls="ASTMStandard_collapse" style="margin-left: 10px;">ASTMStandard</a></legend> <div id="ASTMStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionASTMStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in ASTMStandardEditionKind) obj["standardEditionASTMStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberASTMStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in ASTMStandardKind) obj["standardNumberASTMStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionASTMStandardEditionKind"]; delete obj["standardNumberASTMStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ASTMStandard_collapse" aria-expanded="true" aria-controls="{{id}}_ASTMStandard_collapse" style="margin-left: 10px;">ASTMStandard</a></legend> <div id="{{id}}_ASTMStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionASTMStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionASTMStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberASTMStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberASTMStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ASTMStandard" }; super.submit (id, obj); temp = ASTMStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ASTMStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = ASTMStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ASTMStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class FinancialInfo extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.FinancialInfo; if (null == bucket) cim_data.FinancialInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.FinancialInfo[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "FinancialInfo"; base.parse_element (/<cim:FinancialInfo.account>([\s\S]*?)<\/cim:FinancialInfo.account>/g, obj, "account", base.to_string, sub, context); base.parse_element (/<cim:FinancialInfo.actualPurchaseCost>([\s\S]*?)<\/cim:FinancialInfo.actualPurchaseCost>/g, obj, "actualPurchaseCost", base.to_string, sub, context); base.parse_element (/<cim:FinancialInfo.costDescription>([\s\S]*?)<\/cim:FinancialInfo.costDescription>/g, obj, "costDescription", base.to_string, sub, context); base.parse_element (/<cim:FinancialInfo.costType>([\s\S]*?)<\/cim:FinancialInfo.costType>/g, obj, "costType", base.to_string, sub, context); base.parse_element (/<cim:FinancialInfo.financialValue>([\s\S]*?)<\/cim:FinancialInfo.financialValue>/g, obj, "financialValue", base.to_string, sub, context); base.parse_element (/<cim:FinancialInfo.plantTransferDateTime>([\s\S]*?)<\/cim:FinancialInfo.plantTransferDateTime>/g, obj, "plantTransferDateTime", base.to_datetime, sub, context); base.parse_element (/<cim:FinancialInfo.purchaseDateTime>([\s\S]*?)<\/cim:FinancialInfo.purchaseDateTime>/g, obj, "purchaseDateTime", base.to_datetime, sub, context); base.parse_element (/<cim:FinancialInfo.purchaseOrderNumber>([\s\S]*?)<\/cim:FinancialInfo.purchaseOrderNumber>/g, obj, "purchaseOrderNumber", base.to_string, sub, context); base.parse_attribute (/<cim:FinancialInfo.quantity\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "quantity", sub, context); base.parse_element (/<cim:FinancialInfo.valueDateTime>([\s\S]*?)<\/cim:FinancialInfo.valueDateTime>/g, obj, "valueDateTime", base.to_datetime, sub, context); base.parse_element (/<cim:FinancialInfo.warrantyEndDateTime>([\s\S]*?)<\/cim:FinancialInfo.warrantyEndDateTime>/g, obj, "warrantyEndDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:FinancialInfo.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); let bucket = context.parsed.FinancialInfo; if (null == bucket) context.parsed.FinancialInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "FinancialInfo", "account", "account", base.from_string, fields); base.export_element (obj, "FinancialInfo", "actualPurchaseCost", "actualPurchaseCost", base.from_string, fields); base.export_element (obj, "FinancialInfo", "costDescription", "costDescription", base.from_string, fields); base.export_element (obj, "FinancialInfo", "costType", "costType", base.from_string, fields); base.export_element (obj, "FinancialInfo", "financialValue", "financialValue", base.from_string, fields); base.export_element (obj, "FinancialInfo", "plantTransferDateTime", "plantTransferDateTime", base.from_datetime, fields); base.export_element (obj, "FinancialInfo", "purchaseDateTime", "purchaseDateTime", base.from_datetime, fields); base.export_element (obj, "FinancialInfo", "purchaseOrderNumber", "purchaseOrderNumber", base.from_string, fields); base.export_attribute (obj, "FinancialInfo", "quantity", "quantity", fields); base.export_element (obj, "FinancialInfo", "valueDateTime", "valueDateTime", base.from_datetime, fields); base.export_element (obj, "FinancialInfo", "warrantyEndDateTime", "warrantyEndDateTime", base.from_datetime, fields); base.export_attribute (obj, "FinancialInfo", "Asset", "Asset", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#FinancialInfo_collapse" aria-expanded="true" aria-controls="FinancialInfo_collapse" style="margin-left: 10px;">FinancialInfo</a></legend> <div id="FinancialInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#account}}<div><b>account</b>: {{account}}</div>{{/account}} {{#actualPurchaseCost}}<div><b>actualPurchaseCost</b>: {{actualPurchaseCost}}</div>{{/actualPurchaseCost}} {{#costDescription}}<div><b>costDescription</b>: {{costDescription}}</div>{{/costDescription}} {{#costType}}<div><b>costType</b>: {{costType}}</div>{{/costType}} {{#financialValue}}<div><b>financialValue</b>: {{financialValue}}</div>{{/financialValue}} {{#plantTransferDateTime}}<div><b>plantTransferDateTime</b>: {{plantTransferDateTime}}</div>{{/plantTransferDateTime}} {{#purchaseDateTime}}<div><b>purchaseDateTime</b>: {{purchaseDateTime}}</div>{{/purchaseDateTime}} {{#purchaseOrderNumber}}<div><b>purchaseOrderNumber</b>: {{purchaseOrderNumber}}</div>{{/purchaseOrderNumber}} {{#quantity}}<div><b>quantity</b>: {{quantity}}</div>{{/quantity}} {{#valueDateTime}}<div><b>valueDateTime</b>: {{valueDateTime}}</div>{{/valueDateTime}} {{#warrantyEndDateTime}}<div><b>warrantyEndDateTime</b>: {{warrantyEndDateTime}}</div>{{/warrantyEndDateTime}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_FinancialInfo_collapse" aria-expanded="true" aria-controls="{{id}}_FinancialInfo_collapse" style="margin-left: 10px;">FinancialInfo</a></legend> <div id="{{id}}_FinancialInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_account'>account: </label><div class='col-sm-8'><input id='{{id}}_account' class='form-control' type='text'{{#account}} value='{{account}}'{{/account}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_actualPurchaseCost'>actualPurchaseCost: </label><div class='col-sm-8'><input id='{{id}}_actualPurchaseCost' class='form-control' type='text'{{#actualPurchaseCost}} value='{{actualPurchaseCost}}'{{/actualPurchaseCost}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_costDescription'>costDescription: </label><div class='col-sm-8'><input id='{{id}}_costDescription' class='form-control' type='text'{{#costDescription}} value='{{costDescription}}'{{/costDescription}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_costType'>costType: </label><div class='col-sm-8'><input id='{{id}}_costType' class='form-control' type='text'{{#costType}} value='{{costType}}'{{/costType}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_financialValue'>financialValue: </label><div class='col-sm-8'><input id='{{id}}_financialValue' class='form-control' type='text'{{#financialValue}} value='{{financialValue}}'{{/financialValue}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_plantTransferDateTime'>plantTransferDateTime: </label><div class='col-sm-8'><input id='{{id}}_plantTransferDateTime' class='form-control' type='text'{{#plantTransferDateTime}} value='{{plantTransferDateTime}}'{{/plantTransferDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_purchaseDateTime'>purchaseDateTime: </label><div class='col-sm-8'><input id='{{id}}_purchaseDateTime' class='form-control' type='text'{{#purchaseDateTime}} value='{{purchaseDateTime}}'{{/purchaseDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_purchaseOrderNumber'>purchaseOrderNumber: </label><div class='col-sm-8'><input id='{{id}}_purchaseOrderNumber' class='form-control' type='text'{{#purchaseOrderNumber}} value='{{purchaseOrderNumber}}'{{/purchaseOrderNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_quantity'>quantity: </label><div class='col-sm-8'><input id='{{id}}_quantity' class='form-control' type='text'{{#quantity}} value='{{quantity}}'{{/quantity}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_valueDateTime'>valueDateTime: </label><div class='col-sm-8'><input id='{{id}}_valueDateTime' class='form-control' type='text'{{#valueDateTime}} value='{{valueDateTime}}'{{/valueDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_warrantyEndDateTime'>warrantyEndDateTime: </label><div class='col-sm-8'><input id='{{id}}_warrantyEndDateTime' class='form-control' type='text'{{#warrantyEndDateTime}} value='{{warrantyEndDateTime}}'{{/warrantyEndDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "FinancialInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_account").value; if ("" !== temp) obj["account"] = temp; temp = document.getElementById (id + "_actualPurchaseCost").value; if ("" !== temp) obj["actualPurchaseCost"] = temp; temp = document.getElementById (id + "_costDescription").value; if ("" !== temp) obj["costDescription"] = temp; temp = document.getElementById (id + "_costType").value; if ("" !== temp) obj["costType"] = temp; temp = document.getElementById (id + "_financialValue").value; if ("" !== temp) obj["financialValue"] = temp; temp = document.getElementById (id + "_plantTransferDateTime").value; if ("" !== temp) obj["plantTransferDateTime"] = temp; temp = document.getElementById (id + "_purchaseDateTime").value; if ("" !== temp) obj["purchaseDateTime"] = temp; temp = document.getElementById (id + "_purchaseOrderNumber").value; if ("" !== temp) obj["purchaseOrderNumber"] = temp; temp = document.getElementById (id + "_quantity").value; if ("" !== temp) obj["quantity"] = temp; temp = document.getElementById (id + "_valueDateTime").value; if ("" !== temp) obj["valueDateTime"] = temp; temp = document.getElementById (id + "_warrantyEndDateTime").value; if ("" !== temp) obj["warrantyEndDateTime"] = temp; temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Asset", "0..1", "0..1", "Asset", "FinancialInfo"] ] ) ); } }
JavaScript
class UKMinistryOfDefenceStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.UKMinistryOfDefenceStandard; if (null == bucket) cim_data.UKMinistryOfDefenceStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.UKMinistryOfDefenceStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "UKMinistryOfDefenceStandard"; base.parse_attribute (/<cim:UKMinistryOfDefenceStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:UKMinistryOfDefenceStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.UKMinistryOfDefenceStandard; if (null == bucket) context.parsed.UKMinistryOfDefenceStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "UKMinistryOfDefenceStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "UKMinistryOfDefenceStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#UKMinistryOfDefenceStandard_collapse" aria-expanded="true" aria-controls="UKMinistryOfDefenceStandard_collapse" style="margin-left: 10px;">UKMinistryOfDefenceStandard</a></legend> <div id="UKMinistryOfDefenceStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionUKMinistryOfDefenceStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in UKMinistryOfDefenceStandardEditionKind) obj["standardEditionUKMinistryOfDefenceStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberUKMinistryofDefenceStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in UKMinistryofDefenceStandardKind) obj["standardNumberUKMinistryofDefenceStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionUKMinistryOfDefenceStandardEditionKind"]; delete obj["standardNumberUKMinistryofDefenceStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_UKMinistryOfDefenceStandard_collapse" aria-expanded="true" aria-controls="{{id}}_UKMinistryOfDefenceStandard_collapse" style="margin-left: 10px;">UKMinistryOfDefenceStandard</a></legend> <div id="{{id}}_UKMinistryOfDefenceStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionUKMinistryOfDefenceStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionUKMinistryOfDefenceStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberUKMinistryofDefenceStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberUKMinistryofDefenceStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "UKMinistryOfDefenceStandard" }; super.submit (id, obj); temp = UKMinistryOfDefenceStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#UKMinistryOfDefenceStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = UKMinistryofDefenceStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#UKMinistryofDefenceStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class AssetHealthEvent extends Common.ActivityRecord { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetHealthEvent; if (null == bucket) cim_data.AssetHealthEvent = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetHealthEvent[obj.id]; } parse (context, sub) { let obj = Common.ActivityRecord.prototype.parse.call (this, context, sub); obj.cls = "AssetHealthEvent"; base.parse_element (/<cim:AssetHealthEvent.actionRecommendation>([\s\S]*?)<\/cim:AssetHealthEvent.actionRecommendation>/g, obj, "actionRecommendation", base.to_string, sub, context); base.parse_element (/<cim:AssetHealthEvent.actionTimeline>([\s\S]*?)<\/cim:AssetHealthEvent.actionTimeline>/g, obj, "actionTimeline", base.to_string, sub, context); base.parse_element (/<cim:AssetHealthEvent.effectiveDateTime>([\s\S]*?)<\/cim:AssetHealthEvent.effectiveDateTime>/g, obj, "effectiveDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:AssetHealthEvent.Analytic\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Analytic", sub, context); let bucket = context.parsed.AssetHealthEvent; if (null == bucket) context.parsed.AssetHealthEvent = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.ActivityRecord.prototype.export.call (this, obj, false); base.export_element (obj, "AssetHealthEvent", "actionRecommendation", "actionRecommendation", base.from_string, fields); base.export_element (obj, "AssetHealthEvent", "actionTimeline", "actionTimeline", base.from_string, fields); base.export_element (obj, "AssetHealthEvent", "effectiveDateTime", "effectiveDateTime", base.from_datetime, fields); base.export_attribute (obj, "AssetHealthEvent", "Analytic", "Analytic", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetHealthEvent_collapse" aria-expanded="true" aria-controls="AssetHealthEvent_collapse" style="margin-left: 10px;">AssetHealthEvent</a></legend> <div id="AssetHealthEvent_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.ActivityRecord.prototype.template.call (this) + ` {{#actionRecommendation}}<div><b>actionRecommendation</b>: {{actionRecommendation}}</div>{{/actionRecommendation}} {{#actionTimeline}}<div><b>actionTimeline</b>: {{actionTimeline}}</div>{{/actionTimeline}} {{#effectiveDateTime}}<div><b>effectiveDateTime</b>: {{effectiveDateTime}}</div>{{/effectiveDateTime}} {{#Analytic}}<div><b>Analytic</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Analytic}}");}); return false;'>{{Analytic}}</a></div>{{/Analytic}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetHealthEvent_collapse" aria-expanded="true" aria-controls="{{id}}_AssetHealthEvent_collapse" style="margin-left: 10px;">AssetHealthEvent</a></legend> <div id="{{id}}_AssetHealthEvent_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.ActivityRecord.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_actionRecommendation'>actionRecommendation: </label><div class='col-sm-8'><input id='{{id}}_actionRecommendation' class='form-control' type='text'{{#actionRecommendation}} value='{{actionRecommendation}}'{{/actionRecommendation}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_actionTimeline'>actionTimeline: </label><div class='col-sm-8'><input id='{{id}}_actionTimeline' class='form-control' type='text'{{#actionTimeline}} value='{{actionTimeline}}'{{/actionTimeline}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_effectiveDateTime'>effectiveDateTime: </label><div class='col-sm-8'><input id='{{id}}_effectiveDateTime' class='form-control' type='text'{{#effectiveDateTime}} value='{{effectiveDateTime}}'{{/effectiveDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Analytic'>Analytic: </label><div class='col-sm-8'><input id='{{id}}_Analytic' class='form-control' type='text'{{#Analytic}} value='{{Analytic}}'{{/Analytic}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetHealthEvent" }; super.submit (id, obj); temp = document.getElementById (id + "_actionRecommendation").value; if ("" !== temp) obj["actionRecommendation"] = temp; temp = document.getElementById (id + "_actionTimeline").value; if ("" !== temp) obj["actionTimeline"] = temp; temp = document.getElementById (id + "_effectiveDateTime").value; if ("" !== temp) obj["effectiveDateTime"] = temp; temp = document.getElementById (id + "_Analytic").value; if ("" !== temp) obj["Analytic"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Analytic", "1", "0..*", "Analytic", "AssetHealthEvent"] ] ) ); } }
JavaScript
class EPAStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.EPAStandard; if (null == bucket) cim_data.EPAStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.EPAStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "EPAStandard"; base.parse_attribute (/<cim:EPAStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:EPAStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.EPAStandard; if (null == bucket) context.parsed.EPAStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "EPAStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "EPAStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#EPAStandard_collapse" aria-expanded="true" aria-controls="EPAStandard_collapse" style="margin-left: 10px;">EPAStandard</a></legend> <div id="EPAStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionEPAStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in EPAStandardEditionKind) obj["standardEditionEPAStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberEPAStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in EPAStandardKind) obj["standardNumberEPAStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionEPAStandardEditionKind"]; delete obj["standardNumberEPAStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_EPAStandard_collapse" aria-expanded="true" aria-controls="{{id}}_EPAStandard_collapse" style="margin-left: 10px;">EPAStandard</a></legend> <div id="{{id}}_EPAStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionEPAStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionEPAStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberEPAStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberEPAStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "EPAStandard" }; super.submit (id, obj); temp = EPAStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#EPAStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = EPAStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#EPAStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class InUseDate extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.InUseDate; if (null == bucket) cim_data.InUseDate = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.InUseDate[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "InUseDate"; base.parse_element (/<cim:InUseDate.inUseDate>([\s\S]*?)<\/cim:InUseDate.inUseDate>/g, obj, "inUseDate", base.to_string, sub, context); base.parse_element (/<cim:InUseDate.notReadyForUseDate>([\s\S]*?)<\/cim:InUseDate.notReadyForUseDate>/g, obj, "notReadyForUseDate", base.to_string, sub, context); base.parse_element (/<cim:InUseDate.readyForUseDate>([\s\S]*?)<\/cim:InUseDate.readyForUseDate>/g, obj, "readyForUseDate", base.to_string, sub, context); let bucket = context.parsed.InUseDate; if (null == bucket) context.parsed.InUseDate = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_element (obj, "InUseDate", "inUseDate", "inUseDate", base.from_string, fields); base.export_element (obj, "InUseDate", "notReadyForUseDate", "notReadyForUseDate", base.from_string, fields); base.export_element (obj, "InUseDate", "readyForUseDate", "readyForUseDate", base.from_string, fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#InUseDate_collapse" aria-expanded="true" aria-controls="InUseDate_collapse" style="margin-left: 10px;">InUseDate</a></legend> <div id="InUseDate_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#inUseDate}}<div><b>inUseDate</b>: {{inUseDate}}</div>{{/inUseDate}} {{#notReadyForUseDate}}<div><b>notReadyForUseDate</b>: {{notReadyForUseDate}}</div>{{/notReadyForUseDate}} {{#readyForUseDate}}<div><b>readyForUseDate</b>: {{readyForUseDate}}</div>{{/readyForUseDate}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); } uncondition (obj) { super.uncondition (obj); } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_InUseDate_collapse" aria-expanded="true" aria-controls="{{id}}_InUseDate_collapse" style="margin-left: 10px;">InUseDate</a></legend> <div id="{{id}}_InUseDate_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_inUseDate'>inUseDate: </label><div class='col-sm-8'><input id='{{id}}_inUseDate' class='form-control' type='text'{{#inUseDate}} value='{{inUseDate}}'{{/inUseDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_notReadyForUseDate'>notReadyForUseDate: </label><div class='col-sm-8'><input id='{{id}}_notReadyForUseDate' class='form-control' type='text'{{#notReadyForUseDate}} value='{{notReadyForUseDate}}'{{/notReadyForUseDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_readyForUseDate'>readyForUseDate: </label><div class='col-sm-8'><input id='{{id}}_readyForUseDate' class='form-control' type='text'{{#readyForUseDate}} value='{{readyForUseDate}}'{{/readyForUseDate}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "InUseDate" }; super.submit (id, obj); temp = document.getElementById (id + "_inUseDate").value; if ("" !== temp) obj["inUseDate"] = temp; temp = document.getElementById (id + "_notReadyForUseDate").value; if ("" !== temp) obj["notReadyForUseDate"] = temp; temp = document.getElementById (id + "_readyForUseDate").value; if ("" !== temp) obj["readyForUseDate"] = temp; return (obj); } }
JavaScript
class Asset extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.Asset; if (null == bucket) cim_data.Asset = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.Asset[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "Asset"; base.parse_attribute (/<cim:Asset.acceptanceTest\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "acceptanceTest", sub, context); base.parse_element (/<cim:Asset.baselineCondition>([\s\S]*?)<\/cim:Asset.baselineCondition>/g, obj, "baselineCondition", base.to_string, sub, context); base.parse_element (/<cim:Asset.baselineLossOfLife>([\s\S]*?)<\/cim:Asset.baselineLossOfLife>/g, obj, "baselineLossOfLife", base.to_string, sub, context); base.parse_element (/<cim:Asset.critical>([\s\S]*?)<\/cim:Asset.critical>/g, obj, "critical", base.to_boolean, sub, context); base.parse_attribute (/<cim:Asset.electronicAddress\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "electronicAddress", sub, context); base.parse_attribute (/<cim:Asset.inUseDate\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "inUseDate", sub, context); base.parse_attribute (/<cim:Asset.inUseState\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "inUseState", sub, context); base.parse_attribute (/<cim:Asset.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context); base.parse_attribute (/<cim:Asset.lifecycleDate\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "lifecycleDate", sub, context); base.parse_attribute (/<cim:Asset.lifecycleState\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "lifecycleState", sub, context); base.parse_element (/<cim:Asset.lotNumber>([\s\S]*?)<\/cim:Asset.lotNumber>/g, obj, "lotNumber", base.to_string, sub, context); base.parse_element (/<cim:Asset.position>([\s\S]*?)<\/cim:Asset.position>/g, obj, "position", base.to_string, sub, context); base.parse_element (/<cim:Asset.purchasePrice>([\s\S]*?)<\/cim:Asset.purchasePrice>/g, obj, "purchasePrice", base.to_string, sub, context); base.parse_attribute (/<cim:Asset.retiredReason\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "retiredReason", sub, context); base.parse_element (/<cim:Asset.serialNumber>([\s\S]*?)<\/cim:Asset.serialNumber>/g, obj, "serialNumber", base.to_string, sub, context); base.parse_attribute (/<cim:Asset.status\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "status", sub, context); base.parse_element (/<cim:Asset.type>([\s\S]*?)<\/cim:Asset.type>/g, obj, "type", base.to_string, sub, context); base.parse_element (/<cim:Asset.utcNumber>([\s\S]*?)<\/cim:Asset.utcNumber>/g, obj, "utcNumber", base.to_string, sub, context); base.parse_attributes (/<cim:Asset.ConfigurationEvents\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ConfigurationEvents", sub, context); base.parse_attribute (/<cim:Asset.AssetDeployment\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetDeployment", sub, context); base.parse_attributes (/<cim:Asset.AssetPropertyCurves\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetPropertyCurves", sub, context); base.parse_attributes (/<cim:Asset.ProcedureDataSet\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ProcedureDataSet", sub, context); base.parse_attributes (/<cim:Asset.OrganisationRoles\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "OrganisationRoles", sub, context); base.parse_attributes (/<cim:Asset.ScheduledEvents\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ScheduledEvents", sub, context); base.parse_attributes (/<cim:Asset.ErpRecDeliveryItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpRecDeliveryItems", sub, context); base.parse_attributes (/<cim:Asset.ReplacementWorkTasks\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ReplacementWorkTasks", sub, context); base.parse_attribute (/<cim:Asset.ErpInventory\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInventory", sub, context); base.parse_attributes (/<cim:Asset.Medium\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Medium", sub, context); base.parse_attributes (/<cim:Asset.AssetGroup\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetGroup", sub, context); base.parse_attributes (/<cim:Asset.AnalyticScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AnalyticScore", sub, context); base.parse_attributes (/<cim:Asset.Reconditionings\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Reconditionings", sub, context); base.parse_attributes (/<cim:Asset.PowerSystemResources\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "PowerSystemResources", sub, context); base.parse_attributes (/<cim:Asset.Measurements\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Measurements", sub, context); base.parse_attribute (/<cim:Asset.ErpItemMaster\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpItemMaster", sub, context); base.parse_attribute (/<cim:Asset.AssetContainer\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetContainer", sub, context); base.parse_attributes (/<cim:Asset.Procedures\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Procedures", sub, context); base.parse_attributes (/<cim:Asset.ReliabilityInfos\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ReliabilityInfos", sub, context); base.parse_attribute (/<cim:Asset.FinancialInfo\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "FinancialInfo", sub, context); base.parse_attributes (/<cim:Asset.WorkTasks\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WorkTasks", sub, context); base.parse_attributes (/<cim:Asset.Ownerships\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Ownerships", sub, context); base.parse_attribute (/<cim:Asset.ProductAssetModel\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ProductAssetModel", sub, context); base.parse_attribute (/<cim:Asset.AssetInfo\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetInfo", sub, context); base.parse_attributes (/<cim:Asset.OperationalTags\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "OperationalTags", sub, context); base.parse_attribute (/<cim:Asset.BreakerOperation\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "BreakerOperation", sub, context); base.parse_attributes (/<cim:Asset.AssetFunction\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetFunction", sub, context); base.parse_attribute (/<cim:Asset.Location\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Location", sub, context); base.parse_attributes (/<cim:Asset.ActivityRecords\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ActivityRecords", sub, context); base.parse_attributes (/<cim:Asset.Analytic\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Analytic", sub, context); let bucket = context.parsed.Asset; if (null == bucket) context.parsed.Asset = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "Asset", "acceptanceTest", "acceptanceTest", fields); base.export_element (obj, "Asset", "baselineCondition", "baselineCondition", base.from_string, fields); base.export_element (obj, "Asset", "baselineLossOfLife", "baselineLossOfLife", base.from_string, fields); base.export_element (obj, "Asset", "critical", "critical", base.from_boolean, fields); base.export_attribute (obj, "Asset", "electronicAddress", "electronicAddress", fields); base.export_attribute (obj, "Asset", "inUseDate", "inUseDate", fields); base.export_attribute (obj, "Asset", "inUseState", "inUseState", fields); base.export_attribute (obj, "Asset", "kind", "kind", fields); base.export_attribute (obj, "Asset", "lifecycleDate", "lifecycleDate", fields); base.export_attribute (obj, "Asset", "lifecycleState", "lifecycleState", fields); base.export_element (obj, "Asset", "lotNumber", "lotNumber", base.from_string, fields); base.export_element (obj, "Asset", "position", "position", base.from_string, fields); base.export_element (obj, "Asset", "purchasePrice", "purchasePrice", base.from_string, fields); base.export_attribute (obj, "Asset", "retiredReason", "retiredReason", fields); base.export_element (obj, "Asset", "serialNumber", "serialNumber", base.from_string, fields); base.export_attribute (obj, "Asset", "status", "status", fields); base.export_element (obj, "Asset", "type", "type", base.from_string, fields); base.export_element (obj, "Asset", "utcNumber", "utcNumber", base.from_string, fields); base.export_attributes (obj, "Asset", "ConfigurationEvents", "ConfigurationEvents", fields); base.export_attribute (obj, "Asset", "AssetDeployment", "AssetDeployment", fields); base.export_attributes (obj, "Asset", "AssetPropertyCurves", "AssetPropertyCurves", fields); base.export_attributes (obj, "Asset", "ProcedureDataSet", "ProcedureDataSet", fields); base.export_attributes (obj, "Asset", "OrganisationRoles", "OrganisationRoles", fields); base.export_attributes (obj, "Asset", "ScheduledEvents", "ScheduledEvents", fields); base.export_attributes (obj, "Asset", "ErpRecDeliveryItems", "ErpRecDeliveryItems", fields); base.export_attributes (obj, "Asset", "ReplacementWorkTasks", "ReplacementWorkTasks", fields); base.export_attribute (obj, "Asset", "ErpInventory", "ErpInventory", fields); base.export_attributes (obj, "Asset", "Medium", "Medium", fields); base.export_attributes (obj, "Asset", "AssetGroup", "AssetGroup", fields); base.export_attributes (obj, "Asset", "AnalyticScore", "AnalyticScore", fields); base.export_attributes (obj, "Asset", "Reconditionings", "Reconditionings", fields); base.export_attributes (obj, "Asset", "PowerSystemResources", "PowerSystemResources", fields); base.export_attributes (obj, "Asset", "Measurements", "Measurements", fields); base.export_attribute (obj, "Asset", "ErpItemMaster", "ErpItemMaster", fields); base.export_attribute (obj, "Asset", "AssetContainer", "AssetContainer", fields); base.export_attributes (obj, "Asset", "Procedures", "Procedures", fields); base.export_attributes (obj, "Asset", "ReliabilityInfos", "ReliabilityInfos", fields); base.export_attribute (obj, "Asset", "FinancialInfo", "FinancialInfo", fields); base.export_attributes (obj, "Asset", "WorkTasks", "WorkTasks", fields); base.export_attributes (obj, "Asset", "Ownerships", "Ownerships", fields); base.export_attribute (obj, "Asset", "ProductAssetModel", "ProductAssetModel", fields); base.export_attribute (obj, "Asset", "AssetInfo", "AssetInfo", fields); base.export_attributes (obj, "Asset", "OperationalTags", "OperationalTags", fields); base.export_attribute (obj, "Asset", "BreakerOperation", "BreakerOperation", fields); base.export_attributes (obj, "Asset", "AssetFunction", "AssetFunction", fields); base.export_attribute (obj, "Asset", "Location", "Location", fields); base.export_attributes (obj, "Asset", "ActivityRecords", "ActivityRecords", fields); base.export_attributes (obj, "Asset", "Analytic", "Analytic", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Asset_collapse" aria-expanded="true" aria-controls="Asset_collapse" style="margin-left: 10px;">Asset</a></legend> <div id="Asset_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#acceptanceTest}}<div><b>acceptanceTest</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{acceptanceTest}}");}); return false;'>{{acceptanceTest}}</a></div>{{/acceptanceTest}} {{#baselineCondition}}<div><b>baselineCondition</b>: {{baselineCondition}}</div>{{/baselineCondition}} {{#baselineLossOfLife}}<div><b>baselineLossOfLife</b>: {{baselineLossOfLife}}</div>{{/baselineLossOfLife}} {{#critical}}<div><b>critical</b>: {{critical}}</div>{{/critical}} {{#electronicAddress}}<div><b>electronicAddress</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{electronicAddress}}");}); return false;'>{{electronicAddress}}</a></div>{{/electronicAddress}} {{#inUseDate}}<div><b>inUseDate</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{inUseDate}}");}); return false;'>{{inUseDate}}</a></div>{{/inUseDate}} {{#inUseState}}<div><b>inUseState</b>: {{inUseState}}</div>{{/inUseState}} {{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}} {{#lifecycleDate}}<div><b>lifecycleDate</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{lifecycleDate}}");}); return false;'>{{lifecycleDate}}</a></div>{{/lifecycleDate}} {{#lifecycleState}}<div><b>lifecycleState</b>: {{lifecycleState}}</div>{{/lifecycleState}} {{#lotNumber}}<div><b>lotNumber</b>: {{lotNumber}}</div>{{/lotNumber}} {{#position}}<div><b>position</b>: {{position}}</div>{{/position}} {{#purchasePrice}}<div><b>purchasePrice</b>: {{purchasePrice}}</div>{{/purchasePrice}} {{#retiredReason}}<div><b>retiredReason</b>: {{retiredReason}}</div>{{/retiredReason}} {{#serialNumber}}<div><b>serialNumber</b>: {{serialNumber}}</div>{{/serialNumber}} {{#status}}<div><b>status</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{status}}");}); return false;'>{{status}}</a></div>{{/status}} {{#type}}<div><b>type</b>: {{type}}</div>{{/type}} {{#utcNumber}}<div><b>utcNumber</b>: {{utcNumber}}</div>{{/utcNumber}} {{#ConfigurationEvents}}<div><b>ConfigurationEvents</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ConfigurationEvents}} {{#AssetDeployment}}<div><b>AssetDeployment</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetDeployment}}");}); return false;'>{{AssetDeployment}}</a></div>{{/AssetDeployment}} {{#AssetPropertyCurves}}<div><b>AssetPropertyCurves</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetPropertyCurves}} {{#ProcedureDataSet}}<div><b>ProcedureDataSet</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ProcedureDataSet}} {{#OrganisationRoles}}<div><b>OrganisationRoles</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/OrganisationRoles}} {{#ScheduledEvents}}<div><b>ScheduledEvents</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ScheduledEvents}} {{#ErpRecDeliveryItems}}<div><b>ErpRecDeliveryItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpRecDeliveryItems}} {{#ReplacementWorkTasks}}<div><b>ReplacementWorkTasks</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ReplacementWorkTasks}} {{#ErpInventory}}<div><b>ErpInventory</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpInventory}}");}); return false;'>{{ErpInventory}}</a></div>{{/ErpInventory}} {{#Medium}}<div><b>Medium</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Medium}} {{#AssetGroup}}<div><b>AssetGroup</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetGroup}} {{#AnalyticScore}}<div><b>AnalyticScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AnalyticScore}} {{#Reconditionings}}<div><b>Reconditionings</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Reconditionings}} {{#PowerSystemResources}}<div><b>PowerSystemResources</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/PowerSystemResources}} {{#Measurements}}<div><b>Measurements</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Measurements}} {{#ErpItemMaster}}<div><b>ErpItemMaster</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ErpItemMaster}}");}); return false;'>{{ErpItemMaster}}</a></div>{{/ErpItemMaster}} {{#AssetContainer}}<div><b>AssetContainer</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetContainer}}");}); return false;'>{{AssetContainer}}</a></div>{{/AssetContainer}} {{#Procedures}}<div><b>Procedures</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Procedures}} {{#ReliabilityInfos}}<div><b>ReliabilityInfos</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ReliabilityInfos}} {{#FinancialInfo}}<div><b>FinancialInfo</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{FinancialInfo}}");}); return false;'>{{FinancialInfo}}</a></div>{{/FinancialInfo}} {{#WorkTasks}}<div><b>WorkTasks</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/WorkTasks}} {{#Ownerships}}<div><b>Ownerships</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Ownerships}} {{#ProductAssetModel}}<div><b>ProductAssetModel</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ProductAssetModel}}");}); return false;'>{{ProductAssetModel}}</a></div>{{/ProductAssetModel}} {{#AssetInfo}}<div><b>AssetInfo</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetInfo}}");}); return false;'>{{AssetInfo}}</a></div>{{/AssetInfo}} {{#OperationalTags}}<div><b>OperationalTags</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/OperationalTags}} {{#BreakerOperation}}<div><b>BreakerOperation</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{BreakerOperation}}");}); return false;'>{{BreakerOperation}}</a></div>{{/BreakerOperation}} {{#AssetFunction}}<div><b>AssetFunction</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetFunction}} {{#Location}}<div><b>Location</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Location}}");}); return false;'>{{Location}}</a></div>{{/Location}} {{#ActivityRecords}}<div><b>ActivityRecords</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ActivityRecords}} {{#Analytic}}<div><b>Analytic</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Analytic}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["inUseStateInUseStateKind"] = [{ id: '', selected: (!obj["inUseState"])}]; for (let property in InUseStateKind) obj["inUseStateInUseStateKind"].push ({ id: property, selected: obj["inUseState"] && obj["inUseState"].endsWith ('.' + property)}); obj["kindAssetKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in AssetKind) obj["kindAssetKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)}); obj["lifecycleStateAssetLifecycleStateKind"] = [{ id: '', selected: (!obj["lifecycleState"])}]; for (let property in AssetLifecycleStateKind) obj["lifecycleStateAssetLifecycleStateKind"].push ({ id: property, selected: obj["lifecycleState"] && obj["lifecycleState"].endsWith ('.' + property)}); obj["retiredReasonRetiredReasonKind"] = [{ id: '', selected: (!obj["retiredReason"])}]; for (let property in RetiredReasonKind) obj["retiredReasonRetiredReasonKind"].push ({ id: property, selected: obj["retiredReason"] && obj["retiredReason"].endsWith ('.' + property)}); if (obj["ConfigurationEvents"]) obj["ConfigurationEvents_string"] = obj["ConfigurationEvents"].join (); if (obj["AssetPropertyCurves"]) obj["AssetPropertyCurves_string"] = obj["AssetPropertyCurves"].join (); if (obj["ProcedureDataSet"]) obj["ProcedureDataSet_string"] = obj["ProcedureDataSet"].join (); if (obj["OrganisationRoles"]) obj["OrganisationRoles_string"] = obj["OrganisationRoles"].join (); if (obj["ScheduledEvents"]) obj["ScheduledEvents_string"] = obj["ScheduledEvents"].join (); if (obj["ErpRecDeliveryItems"]) obj["ErpRecDeliveryItems_string"] = obj["ErpRecDeliveryItems"].join (); if (obj["ReplacementWorkTasks"]) obj["ReplacementWorkTasks_string"] = obj["ReplacementWorkTasks"].join (); if (obj["Medium"]) obj["Medium_string"] = obj["Medium"].join (); if (obj["AssetGroup"]) obj["AssetGroup_string"] = obj["AssetGroup"].join (); if (obj["AnalyticScore"]) obj["AnalyticScore_string"] = obj["AnalyticScore"].join (); if (obj["Reconditionings"]) obj["Reconditionings_string"] = obj["Reconditionings"].join (); if (obj["PowerSystemResources"]) obj["PowerSystemResources_string"] = obj["PowerSystemResources"].join (); if (obj["Measurements"]) obj["Measurements_string"] = obj["Measurements"].join (); if (obj["Procedures"]) obj["Procedures_string"] = obj["Procedures"].join (); if (obj["ReliabilityInfos"]) obj["ReliabilityInfos_string"] = obj["ReliabilityInfos"].join (); if (obj["WorkTasks"]) obj["WorkTasks_string"] = obj["WorkTasks"].join (); if (obj["Ownerships"]) obj["Ownerships_string"] = obj["Ownerships"].join (); if (obj["OperationalTags"]) obj["OperationalTags_string"] = obj["OperationalTags"].join (); if (obj["AssetFunction"]) obj["AssetFunction_string"] = obj["AssetFunction"].join (); if (obj["ActivityRecords"]) obj["ActivityRecords_string"] = obj["ActivityRecords"].join (); if (obj["Analytic"]) obj["Analytic_string"] = obj["Analytic"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["inUseStateInUseStateKind"]; delete obj["kindAssetKind"]; delete obj["lifecycleStateAssetLifecycleStateKind"]; delete obj["retiredReasonRetiredReasonKind"]; delete obj["ConfigurationEvents_string"]; delete obj["AssetPropertyCurves_string"]; delete obj["ProcedureDataSet_string"]; delete obj["OrganisationRoles_string"]; delete obj["ScheduledEvents_string"]; delete obj["ErpRecDeliveryItems_string"]; delete obj["ReplacementWorkTasks_string"]; delete obj["Medium_string"]; delete obj["AssetGroup_string"]; delete obj["AnalyticScore_string"]; delete obj["Reconditionings_string"]; delete obj["PowerSystemResources_string"]; delete obj["Measurements_string"]; delete obj["Procedures_string"]; delete obj["ReliabilityInfos_string"]; delete obj["WorkTasks_string"]; delete obj["Ownerships_string"]; delete obj["OperationalTags_string"]; delete obj["AssetFunction_string"]; delete obj["ActivityRecords_string"]; delete obj["Analytic_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Asset_collapse" aria-expanded="true" aria-controls="{{id}}_Asset_collapse" style="margin-left: 10px;">Asset</a></legend> <div id="{{id}}_Asset_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_acceptanceTest'>acceptanceTest: </label><div class='col-sm-8'><input id='{{id}}_acceptanceTest' class='form-control' type='text'{{#acceptanceTest}} value='{{acceptanceTest}}'{{/acceptanceTest}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_baselineCondition'>baselineCondition: </label><div class='col-sm-8'><input id='{{id}}_baselineCondition' class='form-control' type='text'{{#baselineCondition}} value='{{baselineCondition}}'{{/baselineCondition}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_baselineLossOfLife'>baselineLossOfLife: </label><div class='col-sm-8'><input id='{{id}}_baselineLossOfLife' class='form-control' type='text'{{#baselineLossOfLife}} value='{{baselineLossOfLife}}'{{/baselineLossOfLife}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_critical'>critical: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_critical' class='form-check-input' type='checkbox'{{#critical}} checked{{/critical}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_electronicAddress'>electronicAddress: </label><div class='col-sm-8'><input id='{{id}}_electronicAddress' class='form-control' type='text'{{#electronicAddress}} value='{{electronicAddress}}'{{/electronicAddress}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_inUseDate'>inUseDate: </label><div class='col-sm-8'><input id='{{id}}_inUseDate' class='form-control' type='text'{{#inUseDate}} value='{{inUseDate}}'{{/inUseDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_inUseState'>inUseState: </label><div class='col-sm-8'><select id='{{id}}_inUseState' class='form-control custom-select'>{{#inUseStateInUseStateKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/inUseStateInUseStateKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindAssetKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindAssetKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lifecycleDate'>lifecycleDate: </label><div class='col-sm-8'><input id='{{id}}_lifecycleDate' class='form-control' type='text'{{#lifecycleDate}} value='{{lifecycleDate}}'{{/lifecycleDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lifecycleState'>lifecycleState: </label><div class='col-sm-8'><select id='{{id}}_lifecycleState' class='form-control custom-select'>{{#lifecycleStateAssetLifecycleStateKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/lifecycleStateAssetLifecycleStateKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_lotNumber'>lotNumber: </label><div class='col-sm-8'><input id='{{id}}_lotNumber' class='form-control' type='text'{{#lotNumber}} value='{{lotNumber}}'{{/lotNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_position'>position: </label><div class='col-sm-8'><input id='{{id}}_position' class='form-control' type='text'{{#position}} value='{{position}}'{{/position}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_purchasePrice'>purchasePrice: </label><div class='col-sm-8'><input id='{{id}}_purchasePrice' class='form-control' type='text'{{#purchasePrice}} value='{{purchasePrice}}'{{/purchasePrice}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_retiredReason'>retiredReason: </label><div class='col-sm-8'><select id='{{id}}_retiredReason' class='form-control custom-select'>{{#retiredReasonRetiredReasonKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/retiredReasonRetiredReasonKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_serialNumber'>serialNumber: </label><div class='col-sm-8'><input id='{{id}}_serialNumber' class='form-control' type='text'{{#serialNumber}} value='{{serialNumber}}'{{/serialNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_status'>status: </label><div class='col-sm-8'><input id='{{id}}_status' class='form-control' type='text'{{#status}} value='{{status}}'{{/status}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_type'>type: </label><div class='col-sm-8'><input id='{{id}}_type' class='form-control' type='text'{{#type}} value='{{type}}'{{/type}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_utcNumber'>utcNumber: </label><div class='col-sm-8'><input id='{{id}}_utcNumber' class='form-control' type='text'{{#utcNumber}} value='{{utcNumber}}'{{/utcNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetDeployment'>AssetDeployment: </label><div class='col-sm-8'><input id='{{id}}_AssetDeployment' class='form-control' type='text'{{#AssetDeployment}} value='{{AssetDeployment}}'{{/AssetDeployment}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetPropertyCurves'>AssetPropertyCurves: </label><div class='col-sm-8'><input id='{{id}}_AssetPropertyCurves' class='form-control' type='text'{{#AssetPropertyCurves}} value='{{AssetPropertyCurves_string}}'{{/AssetPropertyCurves}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_OrganisationRoles'>OrganisationRoles: </label><div class='col-sm-8'><input id='{{id}}_OrganisationRoles' class='form-control' type='text'{{#OrganisationRoles}} value='{{OrganisationRoles_string}}'{{/OrganisationRoles}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ScheduledEvents'>ScheduledEvents: </label><div class='col-sm-8'><input id='{{id}}_ScheduledEvents' class='form-control' type='text'{{#ScheduledEvents}} value='{{ScheduledEvents_string}}'{{/ScheduledEvents}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpRecDeliveryItems'>ErpRecDeliveryItems: </label><div class='col-sm-8'><input id='{{id}}_ErpRecDeliveryItems' class='form-control' type='text'{{#ErpRecDeliveryItems}} value='{{ErpRecDeliveryItems_string}}'{{/ErpRecDeliveryItems}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ReplacementWorkTasks'>ReplacementWorkTasks: </label><div class='col-sm-8'><input id='{{id}}_ReplacementWorkTasks' class='form-control' type='text'{{#ReplacementWorkTasks}} value='{{ReplacementWorkTasks_string}}'{{/ReplacementWorkTasks}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpInventory'>ErpInventory: </label><div class='col-sm-8'><input id='{{id}}_ErpInventory' class='form-control' type='text'{{#ErpInventory}} value='{{ErpInventory}}'{{/ErpInventory}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Medium'>Medium: </label><div class='col-sm-8'><input id='{{id}}_Medium' class='form-control' type='text'{{#Medium}} value='{{Medium_string}}'{{/Medium}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetGroup'>AssetGroup: </label><div class='col-sm-8'><input id='{{id}}_AssetGroup' class='form-control' type='text'{{#AssetGroup}} value='{{AssetGroup_string}}'{{/AssetGroup}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_PowerSystemResources'>PowerSystemResources: </label><div class='col-sm-8'><input id='{{id}}_PowerSystemResources' class='form-control' type='text'{{#PowerSystemResources}} value='{{PowerSystemResources_string}}'{{/PowerSystemResources}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ErpItemMaster'>ErpItemMaster: </label><div class='col-sm-8'><input id='{{id}}_ErpItemMaster' class='form-control' type='text'{{#ErpItemMaster}} value='{{ErpItemMaster}}'{{/ErpItemMaster}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetContainer'>AssetContainer: </label><div class='col-sm-8'><input id='{{id}}_AssetContainer' class='form-control' type='text'{{#AssetContainer}} value='{{AssetContainer}}'{{/AssetContainer}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Procedures'>Procedures: </label><div class='col-sm-8'><input id='{{id}}_Procedures' class='form-control' type='text'{{#Procedures}} value='{{Procedures_string}}'{{/Procedures}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ReliabilityInfos'>ReliabilityInfos: </label><div class='col-sm-8'><input id='{{id}}_ReliabilityInfos' class='form-control' type='text'{{#ReliabilityInfos}} value='{{ReliabilityInfos_string}}'{{/ReliabilityInfos}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_FinancialInfo'>FinancialInfo: </label><div class='col-sm-8'><input id='{{id}}_FinancialInfo' class='form-control' type='text'{{#FinancialInfo}} value='{{FinancialInfo}}'{{/FinancialInfo}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WorkTasks'>WorkTasks: </label><div class='col-sm-8'><input id='{{id}}_WorkTasks' class='form-control' type='text'{{#WorkTasks}} value='{{WorkTasks_string}}'{{/WorkTasks}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ProductAssetModel'>ProductAssetModel: </label><div class='col-sm-8'><input id='{{id}}_ProductAssetModel' class='form-control' type='text'{{#ProductAssetModel}} value='{{ProductAssetModel}}'{{/ProductAssetModel}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetInfo'>AssetInfo: </label><div class='col-sm-8'><input id='{{id}}_AssetInfo' class='form-control' type='text'{{#AssetInfo}} value='{{AssetInfo}}'{{/AssetInfo}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_BreakerOperation'>BreakerOperation: </label><div class='col-sm-8'><input id='{{id}}_BreakerOperation' class='form-control' type='text'{{#BreakerOperation}} value='{{BreakerOperation}}'{{/BreakerOperation}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Location'>Location: </label><div class='col-sm-8'><input id='{{id}}_Location' class='form-control' type='text'{{#Location}} value='{{Location}}'{{/Location}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ActivityRecords'>ActivityRecords: </label><div class='col-sm-8'><input id='{{id}}_ActivityRecords' class='form-control' type='text'{{#ActivityRecords}} value='{{ActivityRecords_string}}'{{/ActivityRecords}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Analytic'>Analytic: </label><div class='col-sm-8'><input id='{{id}}_Analytic' class='form-control' type='text'{{#Analytic}} value='{{Analytic_string}}'{{/Analytic}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "Asset" }; super.submit (id, obj); temp = document.getElementById (id + "_acceptanceTest").value; if ("" !== temp) obj["acceptanceTest"] = temp; temp = document.getElementById (id + "_baselineCondition").value; if ("" !== temp) obj["baselineCondition"] = temp; temp = document.getElementById (id + "_baselineLossOfLife").value; if ("" !== temp) obj["baselineLossOfLife"] = temp; temp = document.getElementById (id + "_critical").checked; if (temp) obj["critical"] = true; temp = document.getElementById (id + "_electronicAddress").value; if ("" !== temp) obj["electronicAddress"] = temp; temp = document.getElementById (id + "_inUseDate").value; if ("" !== temp) obj["inUseDate"] = temp; temp = InUseStateKind[document.getElementById (id + "_inUseState").value]; if (temp) obj["inUseState"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#InUseStateKind." + temp; else delete obj["inUseState"]; temp = AssetKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetKind." + temp; else delete obj["kind"]; temp = document.getElementById (id + "_lifecycleDate").value; if ("" !== temp) obj["lifecycleDate"] = temp; temp = AssetLifecycleStateKind[document.getElementById (id + "_lifecycleState").value]; if (temp) obj["lifecycleState"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetLifecycleStateKind." + temp; else delete obj["lifecycleState"]; temp = document.getElementById (id + "_lotNumber").value; if ("" !== temp) obj["lotNumber"] = temp; temp = document.getElementById (id + "_position").value; if ("" !== temp) obj["position"] = temp; temp = document.getElementById (id + "_purchasePrice").value; if ("" !== temp) obj["purchasePrice"] = temp; temp = RetiredReasonKind[document.getElementById (id + "_retiredReason").value]; if (temp) obj["retiredReason"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#RetiredReasonKind." + temp; else delete obj["retiredReason"]; temp = document.getElementById (id + "_serialNumber").value; if ("" !== temp) obj["serialNumber"] = temp; temp = document.getElementById (id + "_status").value; if ("" !== temp) obj["status"] = temp; temp = document.getElementById (id + "_type").value; if ("" !== temp) obj["type"] = temp; temp = document.getElementById (id + "_utcNumber").value; if ("" !== temp) obj["utcNumber"] = temp; temp = document.getElementById (id + "_AssetDeployment").value; if ("" !== temp) obj["AssetDeployment"] = temp; temp = document.getElementById (id + "_AssetPropertyCurves").value; if ("" !== temp) obj["AssetPropertyCurves"] = temp.split (","); temp = document.getElementById (id + "_OrganisationRoles").value; if ("" !== temp) obj["OrganisationRoles"] = temp.split (","); temp = document.getElementById (id + "_ScheduledEvents").value; if ("" !== temp) obj["ScheduledEvents"] = temp.split (","); temp = document.getElementById (id + "_ErpRecDeliveryItems").value; if ("" !== temp) obj["ErpRecDeliveryItems"] = temp.split (","); temp = document.getElementById (id + "_ReplacementWorkTasks").value; if ("" !== temp) obj["ReplacementWorkTasks"] = temp.split (","); temp = document.getElementById (id + "_ErpInventory").value; if ("" !== temp) obj["ErpInventory"] = temp; temp = document.getElementById (id + "_Medium").value; if ("" !== temp) obj["Medium"] = temp.split (","); temp = document.getElementById (id + "_AssetGroup").value; if ("" !== temp) obj["AssetGroup"] = temp.split (","); temp = document.getElementById (id + "_PowerSystemResources").value; if ("" !== temp) obj["PowerSystemResources"] = temp.split (","); temp = document.getElementById (id + "_ErpItemMaster").value; if ("" !== temp) obj["ErpItemMaster"] = temp; temp = document.getElementById (id + "_AssetContainer").value; if ("" !== temp) obj["AssetContainer"] = temp; temp = document.getElementById (id + "_Procedures").value; if ("" !== temp) obj["Procedures"] = temp.split (","); temp = document.getElementById (id + "_ReliabilityInfos").value; if ("" !== temp) obj["ReliabilityInfos"] = temp.split (","); temp = document.getElementById (id + "_FinancialInfo").value; if ("" !== temp) obj["FinancialInfo"] = temp; temp = document.getElementById (id + "_WorkTasks").value; if ("" !== temp) obj["WorkTasks"] = temp.split (","); temp = document.getElementById (id + "_ProductAssetModel").value; if ("" !== temp) obj["ProductAssetModel"] = temp; temp = document.getElementById (id + "_AssetInfo").value; if ("" !== temp) obj["AssetInfo"] = temp; temp = document.getElementById (id + "_BreakerOperation").value; if ("" !== temp) obj["BreakerOperation"] = temp; temp = document.getElementById (id + "_Location").value; if ("" !== temp) obj["Location"] = temp; temp = document.getElementById (id + "_ActivityRecords").value; if ("" !== temp) obj["ActivityRecords"] = temp.split (","); temp = document.getElementById (id + "_Analytic").value; if ("" !== temp) obj["Analytic"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["ConfigurationEvents", "0..*", "0..1", "ConfigurationEvent", "ChangedAsset"], ["AssetDeployment", "0..1", "0..1", "AssetDeployment", "Asset"], ["AssetPropertyCurves", "0..*", "0..*", "AssetPropertyCurve", "Assets"], ["ProcedureDataSet", "0..*", "0..1", "ProcedureDataSet", "Asset"], ["OrganisationRoles", "0..*", "0..*", "AssetOrganisationRole", "Assets"], ["ScheduledEvents", "0..*", "0..*", "ScheduledEvent", "Assets"], ["ErpRecDeliveryItems", "0..*", "0..*", "ErpRecDelvLineItem", "Assets"], ["ReplacementWorkTasks", "0..*", "0..*", "WorkTask", "OldAsset"], ["ErpInventory", "0..1", "0..1", "ErpInventory", "Asset"], ["Medium", "0..*", "0..*", "Medium", "Asset"], ["AssetGroup", "0..*", "0..*", "AssetGroup", "Asset"], ["AnalyticScore", "0..*", "0..1", "AnalyticScore", "Asset"], ["Reconditionings", "0..*", "0..1", "Reconditioning", "Asset"], ["PowerSystemResources", "0..*", "0..*", "PowerSystemResource", "Assets"], ["Measurements", "0..*", "0..1", "Measurement", "Asset"], ["ErpItemMaster", "0..1", "0..1", "ErpItemMaster", "Asset"], ["AssetContainer", "0..1", "0..*", "AssetContainer", "Assets"], ["Procedures", "0..*", "0..*", "Procedure", "Assets"], ["ReliabilityInfos", "0..*", "0..*", "ReliabilityInfo", "Assets"], ["FinancialInfo", "0..1", "0..1", "FinancialInfo", "Asset"], ["WorkTasks", "0..*", "0..*", "WorkTask", "Assets"], ["Ownerships", "0..*", "0..1", "Ownership", "Asset"], ["ProductAssetModel", "0..1", "0..*", "ProductAssetModel", "Asset"], ["AssetInfo", "0..1", "0..*", "AssetInfo", "Assets"], ["OperationalTags", "0..*", "0..1", "OperationalTag", "Asset"], ["BreakerOperation", "0..1", "1", "SwitchOperationSummary", "Breaker"], ["AssetFunction", "0..*", "0..1", "AssetFunction", "Asset"], ["Location", "0..1", "0..*", "Location", "Assets"], ["ActivityRecords", "0..*", "0..*", "ActivityRecord", "Assets"], ["Analytic", "0..*", "0..*", "Analytic", "Asset"] ] ) ); } }
JavaScript
class Specimen extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.Specimen; if (null == bucket) cim_data.Specimen = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.Specimen[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "Specimen"; base.parse_element (/<cim:Specimen.ambientTemperatureAtSampling>([\s\S]*?)<\/cim:Specimen.ambientTemperatureAtSampling>/g, obj, "ambientTemperatureAtSampling", base.to_string, sub, context); base.parse_element (/<cim:Specimen.humidityAtSampling>([\s\S]*?)<\/cim:Specimen.humidityAtSampling>/g, obj, "humidityAtSampling", base.to_string, sub, context); base.parse_element (/<cim:Specimen.specimenID>([\s\S]*?)<\/cim:Specimen.specimenID>/g, obj, "specimenID", base.to_string, sub, context); base.parse_element (/<cim:Specimen.specimenSampleDateTime>([\s\S]*?)<\/cim:Specimen.specimenSampleDateTime>/g, obj, "specimenSampleDateTime", base.to_datetime, sub, context); base.parse_element (/<cim:Specimen.specimenToLabDateTime>([\s\S]*?)<\/cim:Specimen.specimenToLabDateTime>/g, obj, "specimenToLabDateTime", base.to_datetime, sub, context); base.parse_attributes (/<cim:Specimen.LabTestDataSet\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "LabTestDataSet", sub, context); base.parse_attribute (/<cim:Specimen.AssetTestSampleTaker\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetTestSampleTaker", sub, context); let bucket = context.parsed.Specimen; if (null == bucket) context.parsed.Specimen = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "Specimen", "ambientTemperatureAtSampling", "ambientTemperatureAtSampling", base.from_string, fields); base.export_element (obj, "Specimen", "humidityAtSampling", "humidityAtSampling", base.from_string, fields); base.export_element (obj, "Specimen", "specimenID", "specimenID", base.from_string, fields); base.export_element (obj, "Specimen", "specimenSampleDateTime", "specimenSampleDateTime", base.from_datetime, fields); base.export_element (obj, "Specimen", "specimenToLabDateTime", "specimenToLabDateTime", base.from_datetime, fields); base.export_attributes (obj, "Specimen", "LabTestDataSet", "LabTestDataSet", fields); base.export_attribute (obj, "Specimen", "AssetTestSampleTaker", "AssetTestSampleTaker", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Specimen_collapse" aria-expanded="true" aria-controls="Specimen_collapse" style="margin-left: 10px;">Specimen</a></legend> <div id="Specimen_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#ambientTemperatureAtSampling}}<div><b>ambientTemperatureAtSampling</b>: {{ambientTemperatureAtSampling}}</div>{{/ambientTemperatureAtSampling}} {{#humidityAtSampling}}<div><b>humidityAtSampling</b>: {{humidityAtSampling}}</div>{{/humidityAtSampling}} {{#specimenID}}<div><b>specimenID</b>: {{specimenID}}</div>{{/specimenID}} {{#specimenSampleDateTime}}<div><b>specimenSampleDateTime</b>: {{specimenSampleDateTime}}</div>{{/specimenSampleDateTime}} {{#specimenToLabDateTime}}<div><b>specimenToLabDateTime</b>: {{specimenToLabDateTime}}</div>{{/specimenToLabDateTime}} {{#LabTestDataSet}}<div><b>LabTestDataSet</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/LabTestDataSet}} {{#AssetTestSampleTaker}}<div><b>AssetTestSampleTaker</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetTestSampleTaker}}");}); return false;'>{{AssetTestSampleTaker}}</a></div>{{/AssetTestSampleTaker}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["LabTestDataSet"]) obj["LabTestDataSet_string"] = obj["LabTestDataSet"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["LabTestDataSet_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Specimen_collapse" aria-expanded="true" aria-controls="{{id}}_Specimen_collapse" style="margin-left: 10px;">Specimen</a></legend> <div id="{{id}}_Specimen_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ambientTemperatureAtSampling'>ambientTemperatureAtSampling: </label><div class='col-sm-8'><input id='{{id}}_ambientTemperatureAtSampling' class='form-control' type='text'{{#ambientTemperatureAtSampling}} value='{{ambientTemperatureAtSampling}}'{{/ambientTemperatureAtSampling}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_humidityAtSampling'>humidityAtSampling: </label><div class='col-sm-8'><input id='{{id}}_humidityAtSampling' class='form-control' type='text'{{#humidityAtSampling}} value='{{humidityAtSampling}}'{{/humidityAtSampling}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_specimenID'>specimenID: </label><div class='col-sm-8'><input id='{{id}}_specimenID' class='form-control' type='text'{{#specimenID}} value='{{specimenID}}'{{/specimenID}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_specimenSampleDateTime'>specimenSampleDateTime: </label><div class='col-sm-8'><input id='{{id}}_specimenSampleDateTime' class='form-control' type='text'{{#specimenSampleDateTime}} value='{{specimenSampleDateTime}}'{{/specimenSampleDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_specimenToLabDateTime'>specimenToLabDateTime: </label><div class='col-sm-8'><input id='{{id}}_specimenToLabDateTime' class='form-control' type='text'{{#specimenToLabDateTime}} value='{{specimenToLabDateTime}}'{{/specimenToLabDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetTestSampleTaker'>AssetTestSampleTaker: </label><div class='col-sm-8'><input id='{{id}}_AssetTestSampleTaker' class='form-control' type='text'{{#AssetTestSampleTaker}} value='{{AssetTestSampleTaker}}'{{/AssetTestSampleTaker}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "Specimen" }; super.submit (id, obj); temp = document.getElementById (id + "_ambientTemperatureAtSampling").value; if ("" !== temp) obj["ambientTemperatureAtSampling"] = temp; temp = document.getElementById (id + "_humidityAtSampling").value; if ("" !== temp) obj["humidityAtSampling"] = temp; temp = document.getElementById (id + "_specimenID").value; if ("" !== temp) obj["specimenID"] = temp; temp = document.getElementById (id + "_specimenSampleDateTime").value; if ("" !== temp) obj["specimenSampleDateTime"] = temp; temp = document.getElementById (id + "_specimenToLabDateTime").value; if ("" !== temp) obj["specimenToLabDateTime"] = temp; temp = document.getElementById (id + "_AssetTestSampleTaker").value; if ("" !== temp) obj["AssetTestSampleTaker"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["LabTestDataSet", "0..*", "0..1", "LabTestDataSet", "Specimen"], ["AssetTestSampleTaker", "0..1", "0..*", "AssetTestSampleTaker", "Specimen"] ] ) ); } }
JavaScript
class AssetGroup extends Common.Document { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetGroup; if (null == bucket) cim_data.AssetGroup = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetGroup[obj.id]; } parse (context, sub) { let obj = Common.Document.prototype.parse.call (this, context, sub); obj.cls = "AssetGroup"; base.parse_attribute (/<cim:AssetGroup.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context); base.parse_attributes (/<cim:AssetGroup.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); base.parse_attributes (/<cim:AssetGroup.Analytic\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Analytic", sub, context); base.parse_attributes (/<cim:AssetGroup.AnalyticScore\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AnalyticScore", sub, context); let bucket = context.parsed.AssetGroup; if (null == bucket) context.parsed.AssetGroup = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.Document.prototype.export.call (this, obj, false); base.export_attribute (obj, "AssetGroup", "kind", "kind", fields); base.export_attributes (obj, "AssetGroup", "Asset", "Asset", fields); base.export_attributes (obj, "AssetGroup", "Analytic", "Analytic", fields); base.export_attributes (obj, "AssetGroup", "AnalyticScore", "AnalyticScore", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetGroup_collapse" aria-expanded="true" aria-controls="AssetGroup_collapse" style="margin-left: 10px;">AssetGroup</a></legend> <div id="AssetGroup_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.Document.prototype.template.call (this) + ` {{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Asset}} {{#Analytic}}<div><b>Analytic</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Analytic}} {{#AnalyticScore}}<div><b>AnalyticScore</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AnalyticScore}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["kindAssetGroupKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in AssetGroupKind) obj["kindAssetGroupKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)}); if (obj["Asset"]) obj["Asset_string"] = obj["Asset"].join (); if (obj["Analytic"]) obj["Analytic_string"] = obj["Analytic"].join (); if (obj["AnalyticScore"]) obj["AnalyticScore_string"] = obj["AnalyticScore"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["kindAssetGroupKind"]; delete obj["Asset_string"]; delete obj["Analytic_string"]; delete obj["AnalyticScore_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetGroup_collapse" aria-expanded="true" aria-controls="{{id}}_AssetGroup_collapse" style="margin-left: 10px;">AssetGroup</a></legend> <div id="{{id}}_AssetGroup_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.Document.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindAssetGroupKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindAssetGroupKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset_string}}'{{/Asset}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Analytic'>Analytic: </label><div class='col-sm-8'><input id='{{id}}_Analytic' class='form-control' type='text'{{#Analytic}} value='{{Analytic_string}}'{{/Analytic}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetGroup" }; super.submit (id, obj); temp = AssetGroupKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetGroupKind." + temp; else delete obj["kind"]; temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp.split (","); temp = document.getElementById (id + "_Analytic").value; if ("" !== temp) obj["Analytic"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["Asset", "0..*", "0..*", "Asset", "AssetGroup"], ["Analytic", "0..*", "0..*", "Analytic", "AssetGroup"], ["AnalyticScore", "0..*", "0..1", "AnalyticScore", "AssetGroup"] ] ) ); } }
JavaScript
class TestStandard extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.TestStandard; if (null == bucket) cim_data.TestStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.TestStandard[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "TestStandard"; base.parse_attribute (/<cim:TestStandard.testMethod\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testMethod", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardASTM\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardASTM", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardCIGRE\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardCIGRE", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardDIN\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardDIN", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardDoble\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardDoble", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardEPA\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardEPA", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardIEC\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardIEC", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardIEEE\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardIEEE", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardISO\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardISO", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardLaborelec\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardLaborelec", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardTAPPI\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardTAPPI", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardUKMinistryOfDefence\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardUKMinistryOfDefence", sub, context); base.parse_attribute (/<cim:TestStandard.testStandardWEP\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testStandardWEP", sub, context); base.parse_attribute (/<cim:TestStandard.testVariant\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "testVariant", sub, context); base.parse_attributes (/<cim:TestStandard.AssetString\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetString", sub, context); base.parse_attributes (/<cim:TestStandard.AssetAnalog\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetAnalog", sub, context); base.parse_attributes (/<cim:TestStandard.AssetDiscrete\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetDiscrete", sub, context); let bucket = context.parsed.TestStandard; if (null == bucket) context.parsed.TestStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "TestStandard", "testMethod", "testMethod", fields); base.export_attribute (obj, "TestStandard", "testStandardASTM", "testStandardASTM", fields); base.export_attribute (obj, "TestStandard", "testStandardCIGRE", "testStandardCIGRE", fields); base.export_attribute (obj, "TestStandard", "testStandardDIN", "testStandardDIN", fields); base.export_attribute (obj, "TestStandard", "testStandardDoble", "testStandardDoble", fields); base.export_attribute (obj, "TestStandard", "testStandardEPA", "testStandardEPA", fields); base.export_attribute (obj, "TestStandard", "testStandardIEC", "testStandardIEC", fields); base.export_attribute (obj, "TestStandard", "testStandardIEEE", "testStandardIEEE", fields); base.export_attribute (obj, "TestStandard", "testStandardISO", "testStandardISO", fields); base.export_attribute (obj, "TestStandard", "testStandardLaborelec", "testStandardLaborelec", fields); base.export_attribute (obj, "TestStandard", "testStandardTAPPI", "testStandardTAPPI", fields); base.export_attribute (obj, "TestStandard", "testStandardUKMinistryOfDefence", "testStandardUKMinistryOfDefence", fields); base.export_attribute (obj, "TestStandard", "testStandardWEP", "testStandardWEP", fields); base.export_attribute (obj, "TestStandard", "testVariant", "testVariant", fields); base.export_attributes (obj, "TestStandard", "AssetString", "AssetString", fields); base.export_attributes (obj, "TestStandard", "AssetAnalog", "AssetAnalog", fields); base.export_attributes (obj, "TestStandard", "AssetDiscrete", "AssetDiscrete", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#TestStandard_collapse" aria-expanded="true" aria-controls="TestStandard_collapse" style="margin-left: 10px;">TestStandard</a></legend> <div id="TestStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#testMethod}}<div><b>testMethod</b>: {{testMethod}}</div>{{/testMethod}} {{#testStandardASTM}}<div><b>testStandardASTM</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardASTM}}");}); return false;'>{{testStandardASTM}}</a></div>{{/testStandardASTM}} {{#testStandardCIGRE}}<div><b>testStandardCIGRE</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardCIGRE}}");}); return false;'>{{testStandardCIGRE}}</a></div>{{/testStandardCIGRE}} {{#testStandardDIN}}<div><b>testStandardDIN</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardDIN}}");}); return false;'>{{testStandardDIN}}</a></div>{{/testStandardDIN}} {{#testStandardDoble}}<div><b>testStandardDoble</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardDoble}}");}); return false;'>{{testStandardDoble}}</a></div>{{/testStandardDoble}} {{#testStandardEPA}}<div><b>testStandardEPA</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardEPA}}");}); return false;'>{{testStandardEPA}}</a></div>{{/testStandardEPA}} {{#testStandardIEC}}<div><b>testStandardIEC</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardIEC}}");}); return false;'>{{testStandardIEC}}</a></div>{{/testStandardIEC}} {{#testStandardIEEE}}<div><b>testStandardIEEE</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardIEEE}}");}); return false;'>{{testStandardIEEE}}</a></div>{{/testStandardIEEE}} {{#testStandardISO}}<div><b>testStandardISO</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardISO}}");}); return false;'>{{testStandardISO}}</a></div>{{/testStandardISO}} {{#testStandardLaborelec}}<div><b>testStandardLaborelec</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardLaborelec}}");}); return false;'>{{testStandardLaborelec}}</a></div>{{/testStandardLaborelec}} {{#testStandardTAPPI}}<div><b>testStandardTAPPI</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardTAPPI}}");}); return false;'>{{testStandardTAPPI}}</a></div>{{/testStandardTAPPI}} {{#testStandardUKMinistryOfDefence}}<div><b>testStandardUKMinistryOfDefence</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardUKMinistryOfDefence}}");}); return false;'>{{testStandardUKMinistryOfDefence}}</a></div>{{/testStandardUKMinistryOfDefence}} {{#testStandardWEP}}<div><b>testStandardWEP</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{testStandardWEP}}");}); return false;'>{{testStandardWEP}}</a></div>{{/testStandardWEP}} {{#testVariant}}<div><b>testVariant</b>: {{testVariant}}</div>{{/testVariant}} {{#AssetString}}<div><b>AssetString</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetString}} {{#AssetAnalog}}<div><b>AssetAnalog</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetAnalog}} {{#AssetDiscrete}}<div><b>AssetDiscrete</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetDiscrete}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["testMethodTestMethod"] = [{ id: '', selected: (!obj["testMethod"])}]; for (let property in TestMethod) obj["testMethodTestMethod"].push ({ id: property, selected: obj["testMethod"] && obj["testMethod"].endsWith ('.' + property)}); obj["testVariantTestVariantKind"] = [{ id: '', selected: (!obj["testVariant"])}]; for (let property in TestVariantKind) obj["testVariantTestVariantKind"].push ({ id: property, selected: obj["testVariant"] && obj["testVariant"].endsWith ('.' + property)}); if (obj["AssetString"]) obj["AssetString_string"] = obj["AssetString"].join (); if (obj["AssetAnalog"]) obj["AssetAnalog_string"] = obj["AssetAnalog"].join (); if (obj["AssetDiscrete"]) obj["AssetDiscrete_string"] = obj["AssetDiscrete"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["testMethodTestMethod"]; delete obj["testVariantTestVariantKind"]; delete obj["AssetString_string"]; delete obj["AssetAnalog_string"]; delete obj["AssetDiscrete_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_TestStandard_collapse" aria-expanded="true" aria-controls="{{id}}_TestStandard_collapse" style="margin-left: 10px;">TestStandard</a></legend> <div id="{{id}}_TestStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testMethod'>testMethod: </label><div class='col-sm-8'><select id='{{id}}_testMethod' class='form-control custom-select'>{{#testMethodTestMethod}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/testMethodTestMethod}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardASTM'>testStandardASTM: </label><div class='col-sm-8'><input id='{{id}}_testStandardASTM' class='form-control' type='text'{{#testStandardASTM}} value='{{testStandardASTM}}'{{/testStandardASTM}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardCIGRE'>testStandardCIGRE: </label><div class='col-sm-8'><input id='{{id}}_testStandardCIGRE' class='form-control' type='text'{{#testStandardCIGRE}} value='{{testStandardCIGRE}}'{{/testStandardCIGRE}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardDIN'>testStandardDIN: </label><div class='col-sm-8'><input id='{{id}}_testStandardDIN' class='form-control' type='text'{{#testStandardDIN}} value='{{testStandardDIN}}'{{/testStandardDIN}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardDoble'>testStandardDoble: </label><div class='col-sm-8'><input id='{{id}}_testStandardDoble' class='form-control' type='text'{{#testStandardDoble}} value='{{testStandardDoble}}'{{/testStandardDoble}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardEPA'>testStandardEPA: </label><div class='col-sm-8'><input id='{{id}}_testStandardEPA' class='form-control' type='text'{{#testStandardEPA}} value='{{testStandardEPA}}'{{/testStandardEPA}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardIEC'>testStandardIEC: </label><div class='col-sm-8'><input id='{{id}}_testStandardIEC' class='form-control' type='text'{{#testStandardIEC}} value='{{testStandardIEC}}'{{/testStandardIEC}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardIEEE'>testStandardIEEE: </label><div class='col-sm-8'><input id='{{id}}_testStandardIEEE' class='form-control' type='text'{{#testStandardIEEE}} value='{{testStandardIEEE}}'{{/testStandardIEEE}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardISO'>testStandardISO: </label><div class='col-sm-8'><input id='{{id}}_testStandardISO' class='form-control' type='text'{{#testStandardISO}} value='{{testStandardISO}}'{{/testStandardISO}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardLaborelec'>testStandardLaborelec: </label><div class='col-sm-8'><input id='{{id}}_testStandardLaborelec' class='form-control' type='text'{{#testStandardLaborelec}} value='{{testStandardLaborelec}}'{{/testStandardLaborelec}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardTAPPI'>testStandardTAPPI: </label><div class='col-sm-8'><input id='{{id}}_testStandardTAPPI' class='form-control' type='text'{{#testStandardTAPPI}} value='{{testStandardTAPPI}}'{{/testStandardTAPPI}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardUKMinistryOfDefence'>testStandardUKMinistryOfDefence: </label><div class='col-sm-8'><input id='{{id}}_testStandardUKMinistryOfDefence' class='form-control' type='text'{{#testStandardUKMinistryOfDefence}} value='{{testStandardUKMinistryOfDefence}}'{{/testStandardUKMinistryOfDefence}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testStandardWEP'>testStandardWEP: </label><div class='col-sm-8'><input id='{{id}}_testStandardWEP' class='form-control' type='text'{{#testStandardWEP}} value='{{testStandardWEP}}'{{/testStandardWEP}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_testVariant'>testVariant: </label><div class='col-sm-8'><select id='{{id}}_testVariant' class='form-control custom-select'>{{#testVariantTestVariantKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/testVariantTestVariantKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "TestStandard" }; super.submit (id, obj); temp = TestMethod[document.getElementById (id + "_testMethod").value]; if (temp) obj["testMethod"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TestMethod." + temp; else delete obj["testMethod"]; temp = document.getElementById (id + "_testStandardASTM").value; if ("" !== temp) obj["testStandardASTM"] = temp; temp = document.getElementById (id + "_testStandardCIGRE").value; if ("" !== temp) obj["testStandardCIGRE"] = temp; temp = document.getElementById (id + "_testStandardDIN").value; if ("" !== temp) obj["testStandardDIN"] = temp; temp = document.getElementById (id + "_testStandardDoble").value; if ("" !== temp) obj["testStandardDoble"] = temp; temp = document.getElementById (id + "_testStandardEPA").value; if ("" !== temp) obj["testStandardEPA"] = temp; temp = document.getElementById (id + "_testStandardIEC").value; if ("" !== temp) obj["testStandardIEC"] = temp; temp = document.getElementById (id + "_testStandardIEEE").value; if ("" !== temp) obj["testStandardIEEE"] = temp; temp = document.getElementById (id + "_testStandardISO").value; if ("" !== temp) obj["testStandardISO"] = temp; temp = document.getElementById (id + "_testStandardLaborelec").value; if ("" !== temp) obj["testStandardLaborelec"] = temp; temp = document.getElementById (id + "_testStandardTAPPI").value; if ("" !== temp) obj["testStandardTAPPI"] = temp; temp = document.getElementById (id + "_testStandardUKMinistryOfDefence").value; if ("" !== temp) obj["testStandardUKMinistryOfDefence"] = temp; temp = document.getElementById (id + "_testStandardWEP").value; if ("" !== temp) obj["testStandardWEP"] = temp; temp = TestVariantKind[document.getElementById (id + "_testVariant").value]; if (temp) obj["testVariant"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TestVariantKind." + temp; else delete obj["testVariant"]; return (obj); } relations () { return ( super.relations ().concat ( [ ["AssetString", "0..*", "0..1", "AssetStringMeasurement", "TestStandard"], ["AssetAnalog", "0..*", "0..1", "AssetAnalog", "TestStandard"], ["AssetDiscrete", "0..*", "0..1", "AssetDiscrete", "TestStandard"] ] ) ); } }
JavaScript
class DobleStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.DobleStandard; if (null == bucket) cim_data.DobleStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.DobleStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "DobleStandard"; base.parse_attribute (/<cim:DobleStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:DobleStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.DobleStandard; if (null == bucket) context.parsed.DobleStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "DobleStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "DobleStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#DobleStandard_collapse" aria-expanded="true" aria-controls="DobleStandard_collapse" style="margin-left: 10px;">DobleStandard</a></legend> <div id="DobleStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionDobleStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in DobleStandardEditionKind) obj["standardEditionDobleStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberDobleStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in DobleStandardKind) obj["standardNumberDobleStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionDobleStandardEditionKind"]; delete obj["standardNumberDobleStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_DobleStandard_collapse" aria-expanded="true" aria-controls="{{id}}_DobleStandard_collapse" style="margin-left: 10px;">DobleStandard</a></legend> <div id="{{id}}_DobleStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionDobleStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionDobleStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberDobleStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberDobleStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "DobleStandard" }; super.submit (id, obj); temp = DobleStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#DobleStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = DobleStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#DobleStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class Manufacturer extends Common.OrganisationRole { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.Manufacturer; if (null == bucket) cim_data.Manufacturer = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.Manufacturer[obj.id]; } parse (context, sub) { let obj = Common.OrganisationRole.prototype.parse.call (this, context, sub); obj.cls = "Manufacturer"; base.parse_attributes (/<cim:Manufacturer.ProductAssetModels\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ProductAssetModels", sub, context); let bucket = context.parsed.Manufacturer; if (null == bucket) context.parsed.Manufacturer = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.OrganisationRole.prototype.export.call (this, obj, false); base.export_attributes (obj, "Manufacturer", "ProductAssetModels", "ProductAssetModels", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Manufacturer_collapse" aria-expanded="true" aria-controls="Manufacturer_collapse" style="margin-left: 10px;">Manufacturer</a></legend> <div id="Manufacturer_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.OrganisationRole.prototype.template.call (this) + ` {{#ProductAssetModels}}<div><b>ProductAssetModels</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ProductAssetModels}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["ProductAssetModels"]) obj["ProductAssetModels_string"] = obj["ProductAssetModels"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["ProductAssetModels_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Manufacturer_collapse" aria-expanded="true" aria-controls="{{id}}_Manufacturer_collapse" style="margin-left: 10px;">Manufacturer</a></legend> <div id="{{id}}_Manufacturer_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.OrganisationRole.prototype.edit_template.call (this) + ` </div> </fieldset> ` ); } submit (id, obj) { obj = obj || { id: id, cls: "Manufacturer" }; super.submit (id, obj); return (obj); } relations () { return ( super.relations ().concat ( [ ["ProductAssetModels", "0..*", "0..1", "ProductAssetModel", "Manufacturer"] ] ) ); } }
JavaScript
class AssetInfo extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetInfo; if (null == bucket) cim_data.AssetInfo = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetInfo[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "AssetInfo"; base.parse_attribute (/<cim:AssetInfo.CatalogAssetType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CatalogAssetType", sub, context); base.parse_attributes (/<cim:AssetInfo.PowerSystemResources\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "PowerSystemResources", sub, context); base.parse_attributes (/<cim:AssetInfo.Assets\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Assets", sub, context); base.parse_attribute (/<cim:AssetInfo.ProductAssetModel\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ProductAssetModel", sub, context); let bucket = context.parsed.AssetInfo; if (null == bucket) context.parsed.AssetInfo = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "AssetInfo", "CatalogAssetType", "CatalogAssetType", fields); base.export_attributes (obj, "AssetInfo", "PowerSystemResources", "PowerSystemResources", fields); base.export_attributes (obj, "AssetInfo", "Assets", "Assets", fields); base.export_attribute (obj, "AssetInfo", "ProductAssetModel", "ProductAssetModel", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetInfo_collapse" aria-expanded="true" aria-controls="AssetInfo_collapse" style="margin-left: 10px;">AssetInfo</a></legend> <div id="AssetInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#CatalogAssetType}}<div><b>CatalogAssetType</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{CatalogAssetType}}");}); return false;'>{{CatalogAssetType}}</a></div>{{/CatalogAssetType}} {{#PowerSystemResources}}<div><b>PowerSystemResources</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/PowerSystemResources}} {{#Assets}}<div><b>Assets</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Assets}} {{#ProductAssetModel}}<div><b>ProductAssetModel</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{ProductAssetModel}}");}); return false;'>{{ProductAssetModel}}</a></div>{{/ProductAssetModel}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["PowerSystemResources"]) obj["PowerSystemResources_string"] = obj["PowerSystemResources"].join (); if (obj["Assets"]) obj["Assets_string"] = obj["Assets"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["PowerSystemResources_string"]; delete obj["Assets_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetInfo_collapse" aria-expanded="true" aria-controls="{{id}}_AssetInfo_collapse" style="margin-left: 10px;">AssetInfo</a></legend> <div id="{{id}}_AssetInfo_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_CatalogAssetType'>CatalogAssetType: </label><div class='col-sm-8'><input id='{{id}}_CatalogAssetType' class='form-control' type='text'{{#CatalogAssetType}} value='{{CatalogAssetType}}'{{/CatalogAssetType}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_ProductAssetModel'>ProductAssetModel: </label><div class='col-sm-8'><input id='{{id}}_ProductAssetModel' class='form-control' type='text'{{#ProductAssetModel}} value='{{ProductAssetModel}}'{{/ProductAssetModel}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetInfo" }; super.submit (id, obj); temp = document.getElementById (id + "_CatalogAssetType").value; if ("" !== temp) obj["CatalogAssetType"] = temp; temp = document.getElementById (id + "_ProductAssetModel").value; if ("" !== temp) obj["ProductAssetModel"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["CatalogAssetType", "0..1", "0..1", "CatalogAssetType", "AssetInfo"], ["PowerSystemResources", "0..*", "0..1", "PowerSystemResource", "AssetDatasheet"], ["Assets", "0..*", "0..1", "Asset", "AssetInfo"], ["ProductAssetModel", "0..1", "0..1", "ProductAssetModel", "AssetInfo"] ] ) ); } }
JavaScript
class FailureEvent extends Common.ActivityRecord { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.FailureEvent; if (null == bucket) cim_data.FailureEvent = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.FailureEvent[obj.id]; } parse (context, sub) { let obj = Common.ActivityRecord.prototype.parse.call (this, context, sub); obj.cls = "FailureEvent"; base.parse_attribute (/<cim:FailureEvent.breakerFailureReason\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "breakerFailureReason", sub, context); base.parse_element (/<cim:FailureEvent.corporateCode>([\s\S]*?)<\/cim:FailureEvent.corporateCode>/g, obj, "corporateCode", base.to_string, sub, context); base.parse_attribute (/<cim:FailureEvent.failureClassification\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "failureClassification", sub, context); base.parse_element (/<cim:FailureEvent.failureDateTime>([\s\S]*?)<\/cim:FailureEvent.failureDateTime>/g, obj, "failureDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:FailureEvent.failureIsolationMethod\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "failureIsolationMethod", sub, context); base.parse_attribute (/<cim:FailureEvent.failureMode\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "failureMode", sub, context); base.parse_element (/<cim:FailureEvent.faultLocatingMethod>([\s\S]*?)<\/cim:FailureEvent.faultLocatingMethod>/g, obj, "faultLocatingMethod", base.to_string, sub, context); base.parse_element (/<cim:FailureEvent.location>([\s\S]*?)<\/cim:FailureEvent.location>/g, obj, "location", base.to_string, sub, context); base.parse_element (/<cim:FailureEvent.rootCause>([\s\S]*?)<\/cim:FailureEvent.rootCause>/g, obj, "rootCause", base.to_string, sub, context); base.parse_attribute (/<cim:FailureEvent.transformerFailureReason\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "transformerFailureReason", sub, context); let bucket = context.parsed.FailureEvent; if (null == bucket) context.parsed.FailureEvent = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.ActivityRecord.prototype.export.call (this, obj, false); base.export_attribute (obj, "FailureEvent", "breakerFailureReason", "breakerFailureReason", fields); base.export_element (obj, "FailureEvent", "corporateCode", "corporateCode", base.from_string, fields); base.export_attribute (obj, "FailureEvent", "failureClassification", "failureClassification", fields); base.export_element (obj, "FailureEvent", "failureDateTime", "failureDateTime", base.from_datetime, fields); base.export_attribute (obj, "FailureEvent", "failureIsolationMethod", "failureIsolationMethod", fields); base.export_attribute (obj, "FailureEvent", "failureMode", "failureMode", fields); base.export_element (obj, "FailureEvent", "faultLocatingMethod", "faultLocatingMethod", base.from_string, fields); base.export_element (obj, "FailureEvent", "location", "location", base.from_string, fields); base.export_element (obj, "FailureEvent", "rootCause", "rootCause", base.from_string, fields); base.export_attribute (obj, "FailureEvent", "transformerFailureReason", "transformerFailureReason", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#FailureEvent_collapse" aria-expanded="true" aria-controls="FailureEvent_collapse" style="margin-left: 10px;">FailureEvent</a></legend> <div id="FailureEvent_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.ActivityRecord.prototype.template.call (this) + ` {{#breakerFailureReason}}<div><b>breakerFailureReason</b>: {{breakerFailureReason}}</div>{{/breakerFailureReason}} {{#corporateCode}}<div><b>corporateCode</b>: {{corporateCode}}</div>{{/corporateCode}} {{#failureClassification}}<div><b>failureClassification</b>: {{failureClassification}}</div>{{/failureClassification}} {{#failureDateTime}}<div><b>failureDateTime</b>: {{failureDateTime}}</div>{{/failureDateTime}} {{#failureIsolationMethod}}<div><b>failureIsolationMethod</b>: {{failureIsolationMethod}}</div>{{/failureIsolationMethod}} {{#failureMode}}<div><b>failureMode</b>: {{failureMode}}</div>{{/failureMode}} {{#faultLocatingMethod}}<div><b>faultLocatingMethod</b>: {{faultLocatingMethod}}</div>{{/faultLocatingMethod}} {{#location}}<div><b>location</b>: {{location}}</div>{{/location}} {{#rootCause}}<div><b>rootCause</b>: {{rootCause}}</div>{{/rootCause}} {{#transformerFailureReason}}<div><b>transformerFailureReason</b>: {{transformerFailureReason}}</div>{{/transformerFailureReason}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["breakerFailureReasonBreakerFailureReasonKind"] = [{ id: '', selected: (!obj["breakerFailureReason"])}]; for (let property in BreakerFailureReasonKind) obj["breakerFailureReasonBreakerFailureReasonKind"].push ({ id: property, selected: obj["breakerFailureReason"] && obj["breakerFailureReason"].endsWith ('.' + property)}); obj["failureClassificationAssetFailureClassification"] = [{ id: '', selected: (!obj["failureClassification"])}]; for (let property in AssetFailureClassification) obj["failureClassificationAssetFailureClassification"].push ({ id: property, selected: obj["failureClassification"] && obj["failureClassification"].endsWith ('.' + property)}); obj["failureIsolationMethodFailureIsolationMethodKind"] = [{ id: '', selected: (!obj["failureIsolationMethod"])}]; for (let property in FailureIsolationMethodKind) obj["failureIsolationMethodFailureIsolationMethodKind"].push ({ id: property, selected: obj["failureIsolationMethod"] && obj["failureIsolationMethod"].endsWith ('.' + property)}); obj["failureModeAssetFailureMode"] = [{ id: '', selected: (!obj["failureMode"])}]; for (let property in AssetFailureMode) obj["failureModeAssetFailureMode"].push ({ id: property, selected: obj["failureMode"] && obj["failureMode"].endsWith ('.' + property)}); obj["transformerFailureReasonTransformerFailureReasonKind"] = [{ id: '', selected: (!obj["transformerFailureReason"])}]; for (let property in TransformerFailureReasonKind) obj["transformerFailureReasonTransformerFailureReasonKind"].push ({ id: property, selected: obj["transformerFailureReason"] && obj["transformerFailureReason"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["breakerFailureReasonBreakerFailureReasonKind"]; delete obj["failureClassificationAssetFailureClassification"]; delete obj["failureIsolationMethodFailureIsolationMethodKind"]; delete obj["failureModeAssetFailureMode"]; delete obj["transformerFailureReasonTransformerFailureReasonKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_FailureEvent_collapse" aria-expanded="true" aria-controls="{{id}}_FailureEvent_collapse" style="margin-left: 10px;">FailureEvent</a></legend> <div id="{{id}}_FailureEvent_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.ActivityRecord.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_breakerFailureReason'>breakerFailureReason: </label><div class='col-sm-8'><select id='{{id}}_breakerFailureReason' class='form-control custom-select'>{{#breakerFailureReasonBreakerFailureReasonKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/breakerFailureReasonBreakerFailureReasonKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_corporateCode'>corporateCode: </label><div class='col-sm-8'><input id='{{id}}_corporateCode' class='form-control' type='text'{{#corporateCode}} value='{{corporateCode}}'{{/corporateCode}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_failureClassification'>failureClassification: </label><div class='col-sm-8'><select id='{{id}}_failureClassification' class='form-control custom-select'>{{#failureClassificationAssetFailureClassification}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/failureClassificationAssetFailureClassification}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_failureDateTime'>failureDateTime: </label><div class='col-sm-8'><input id='{{id}}_failureDateTime' class='form-control' type='text'{{#failureDateTime}} value='{{failureDateTime}}'{{/failureDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_failureIsolationMethod'>failureIsolationMethod: </label><div class='col-sm-8'><select id='{{id}}_failureIsolationMethod' class='form-control custom-select'>{{#failureIsolationMethodFailureIsolationMethodKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/failureIsolationMethodFailureIsolationMethodKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_failureMode'>failureMode: </label><div class='col-sm-8'><select id='{{id}}_failureMode' class='form-control custom-select'>{{#failureModeAssetFailureMode}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/failureModeAssetFailureMode}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_faultLocatingMethod'>faultLocatingMethod: </label><div class='col-sm-8'><input id='{{id}}_faultLocatingMethod' class='form-control' type='text'{{#faultLocatingMethod}} value='{{faultLocatingMethod}}'{{/faultLocatingMethod}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_location'>location: </label><div class='col-sm-8'><input id='{{id}}_location' class='form-control' type='text'{{#location}} value='{{location}}'{{/location}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_rootCause'>rootCause: </label><div class='col-sm-8'><input id='{{id}}_rootCause' class='form-control' type='text'{{#rootCause}} value='{{rootCause}}'{{/rootCause}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_transformerFailureReason'>transformerFailureReason: </label><div class='col-sm-8'><select id='{{id}}_transformerFailureReason' class='form-control custom-select'>{{#transformerFailureReasonTransformerFailureReasonKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/transformerFailureReasonTransformerFailureReasonKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "FailureEvent" }; super.submit (id, obj); temp = BreakerFailureReasonKind[document.getElementById (id + "_breakerFailureReason").value]; if (temp) obj["breakerFailureReason"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#BreakerFailureReasonKind." + temp; else delete obj["breakerFailureReason"]; temp = document.getElementById (id + "_corporateCode").value; if ("" !== temp) obj["corporateCode"] = temp; temp = AssetFailureClassification[document.getElementById (id + "_failureClassification").value]; if (temp) obj["failureClassification"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetFailureClassification." + temp; else delete obj["failureClassification"]; temp = document.getElementById (id + "_failureDateTime").value; if ("" !== temp) obj["failureDateTime"] = temp; temp = FailureIsolationMethodKind[document.getElementById (id + "_failureIsolationMethod").value]; if (temp) obj["failureIsolationMethod"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#FailureIsolationMethodKind." + temp; else delete obj["failureIsolationMethod"]; temp = AssetFailureMode[document.getElementById (id + "_failureMode").value]; if (temp) obj["failureMode"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetFailureMode." + temp; else delete obj["failureMode"]; temp = document.getElementById (id + "_faultLocatingMethod").value; if ("" !== temp) obj["faultLocatingMethod"] = temp; temp = document.getElementById (id + "_location").value; if ("" !== temp) obj["location"] = temp; temp = document.getElementById (id + "_rootCause").value; if ("" !== temp) obj["rootCause"] = temp; temp = TransformerFailureReasonKind[document.getElementById (id + "_transformerFailureReason").value]; if (temp) obj["transformerFailureReason"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TransformerFailureReasonKind." + temp; else delete obj["transformerFailureReason"]; return (obj); } }
JavaScript
class ProductAssetModel extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ProductAssetModel; if (null == bucket) cim_data.ProductAssetModel = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ProductAssetModel[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "ProductAssetModel"; base.parse_element (/<cim:ProductAssetModel.catalogueNumber>([\s\S]*?)<\/cim:ProductAssetModel.catalogueNumber>/g, obj, "catalogueNumber", base.to_string, sub, context); base.parse_attribute (/<cim:ProductAssetModel.corporateStandardKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "corporateStandardKind", sub, context); base.parse_element (/<cim:ProductAssetModel.drawingNumber>([\s\S]*?)<\/cim:ProductAssetModel.drawingNumber>/g, obj, "drawingNumber", base.to_string, sub, context); base.parse_element (/<cim:ProductAssetModel.instructionManual>([\s\S]*?)<\/cim:ProductAssetModel.instructionManual>/g, obj, "instructionManual", base.to_string, sub, context); base.parse_element (/<cim:ProductAssetModel.modelNumber>([\s\S]*?)<\/cim:ProductAssetModel.modelNumber>/g, obj, "modelNumber", base.to_string, sub, context); base.parse_element (/<cim:ProductAssetModel.modelVersion>([\s\S]*?)<\/cim:ProductAssetModel.modelVersion>/g, obj, "modelVersion", base.to_string, sub, context); base.parse_element (/<cim:ProductAssetModel.overallLength>([\s\S]*?)<\/cim:ProductAssetModel.overallLength>/g, obj, "overallLength", base.to_string, sub, context); base.parse_element (/<cim:ProductAssetModel.styleNumber>([\s\S]*?)<\/cim:ProductAssetModel.styleNumber>/g, obj, "styleNumber", base.to_string, sub, context); base.parse_attribute (/<cim:ProductAssetModel.usageKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "usageKind", sub, context); base.parse_element (/<cim:ProductAssetModel.weightTotal>([\s\S]*?)<\/cim:ProductAssetModel.weightTotal>/g, obj, "weightTotal", base.to_string, sub, context); base.parse_attribute (/<cim:ProductAssetModel.Manufacturer\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Manufacturer", sub, context); base.parse_attributes (/<cim:ProductAssetModel.OperationalRestrictions\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "OperationalRestrictions", sub, context); base.parse_attributes (/<cim:ProductAssetModel.AssetModelCatalogueItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetModelCatalogueItems", sub, context); base.parse_attribute (/<cim:ProductAssetModel.CatalogAssetType\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CatalogAssetType", sub, context); base.parse_attributes (/<cim:ProductAssetModel.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); base.parse_attribute (/<cim:ProductAssetModel.AssetInfo\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetInfo", sub, context); let bucket = context.parsed.ProductAssetModel; if (null == bucket) context.parsed.ProductAssetModel = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "ProductAssetModel", "catalogueNumber", "catalogueNumber", base.from_string, fields); base.export_attribute (obj, "ProductAssetModel", "corporateStandardKind", "corporateStandardKind", fields); base.export_element (obj, "ProductAssetModel", "drawingNumber", "drawingNumber", base.from_string, fields); base.export_element (obj, "ProductAssetModel", "instructionManual", "instructionManual", base.from_string, fields); base.export_element (obj, "ProductAssetModel", "modelNumber", "modelNumber", base.from_string, fields); base.export_element (obj, "ProductAssetModel", "modelVersion", "modelVersion", base.from_string, fields); base.export_element (obj, "ProductAssetModel", "overallLength", "overallLength", base.from_string, fields); base.export_element (obj, "ProductAssetModel", "styleNumber", "styleNumber", base.from_string, fields); base.export_attribute (obj, "ProductAssetModel", "usageKind", "usageKind", fields); base.export_element (obj, "ProductAssetModel", "weightTotal", "weightTotal", base.from_string, fields); base.export_attribute (obj, "ProductAssetModel", "Manufacturer", "Manufacturer", fields); base.export_attributes (obj, "ProductAssetModel", "OperationalRestrictions", "OperationalRestrictions", fields); base.export_attributes (obj, "ProductAssetModel", "AssetModelCatalogueItems", "AssetModelCatalogueItems", fields); base.export_attribute (obj, "ProductAssetModel", "CatalogAssetType", "CatalogAssetType", fields); base.export_attributes (obj, "ProductAssetModel", "Asset", "Asset", fields); base.export_attribute (obj, "ProductAssetModel", "AssetInfo", "AssetInfo", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ProductAssetModel_collapse" aria-expanded="true" aria-controls="ProductAssetModel_collapse" style="margin-left: 10px;">ProductAssetModel</a></legend> <div id="ProductAssetModel_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#catalogueNumber}}<div><b>catalogueNumber</b>: {{catalogueNumber}}</div>{{/catalogueNumber}} {{#corporateStandardKind}}<div><b>corporateStandardKind</b>: {{corporateStandardKind}}</div>{{/corporateStandardKind}} {{#drawingNumber}}<div><b>drawingNumber</b>: {{drawingNumber}}</div>{{/drawingNumber}} {{#instructionManual}}<div><b>instructionManual</b>: {{instructionManual}}</div>{{/instructionManual}} {{#modelNumber}}<div><b>modelNumber</b>: {{modelNumber}}</div>{{/modelNumber}} {{#modelVersion}}<div><b>modelVersion</b>: {{modelVersion}}</div>{{/modelVersion}} {{#overallLength}}<div><b>overallLength</b>: {{overallLength}}</div>{{/overallLength}} {{#styleNumber}}<div><b>styleNumber</b>: {{styleNumber}}</div>{{/styleNumber}} {{#usageKind}}<div><b>usageKind</b>: {{usageKind}}</div>{{/usageKind}} {{#weightTotal}}<div><b>weightTotal</b>: {{weightTotal}}</div>{{/weightTotal}} {{#Manufacturer}}<div><b>Manufacturer</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Manufacturer}}");}); return false;'>{{Manufacturer}}</a></div>{{/Manufacturer}} {{#OperationalRestrictions}}<div><b>OperationalRestrictions</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/OperationalRestrictions}} {{#AssetModelCatalogueItems}}<div><b>AssetModelCatalogueItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/AssetModelCatalogueItems}} {{#CatalogAssetType}}<div><b>CatalogAssetType</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{CatalogAssetType}}");}); return false;'>{{CatalogAssetType}}</a></div>{{/CatalogAssetType}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Asset}} {{#AssetInfo}}<div><b>AssetInfo</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetInfo}}");}); return false;'>{{AssetInfo}}</a></div>{{/AssetInfo}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["corporateStandardKindCorporateStandardKind"] = [{ id: '', selected: (!obj["corporateStandardKind"])}]; for (let property in CorporateStandardKind) obj["corporateStandardKindCorporateStandardKind"].push ({ id: property, selected: obj["corporateStandardKind"] && obj["corporateStandardKind"].endsWith ('.' + property)}); obj["usageKindAssetModelUsageKind"] = [{ id: '', selected: (!obj["usageKind"])}]; for (let property in AssetModelUsageKind) obj["usageKindAssetModelUsageKind"].push ({ id: property, selected: obj["usageKind"] && obj["usageKind"].endsWith ('.' + property)}); if (obj["OperationalRestrictions"]) obj["OperationalRestrictions_string"] = obj["OperationalRestrictions"].join (); if (obj["AssetModelCatalogueItems"]) obj["AssetModelCatalogueItems_string"] = obj["AssetModelCatalogueItems"].join (); if (obj["Asset"]) obj["Asset_string"] = obj["Asset"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["corporateStandardKindCorporateStandardKind"]; delete obj["usageKindAssetModelUsageKind"]; delete obj["OperationalRestrictions_string"]; delete obj["AssetModelCatalogueItems_string"]; delete obj["Asset_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ProductAssetModel_collapse" aria-expanded="true" aria-controls="{{id}}_ProductAssetModel_collapse" style="margin-left: 10px;">ProductAssetModel</a></legend> <div id="{{id}}_ProductAssetModel_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_catalogueNumber'>catalogueNumber: </label><div class='col-sm-8'><input id='{{id}}_catalogueNumber' class='form-control' type='text'{{#catalogueNumber}} value='{{catalogueNumber}}'{{/catalogueNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_corporateStandardKind'>corporateStandardKind: </label><div class='col-sm-8'><select id='{{id}}_corporateStandardKind' class='form-control custom-select'>{{#corporateStandardKindCorporateStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/corporateStandardKindCorporateStandardKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_drawingNumber'>drawingNumber: </label><div class='col-sm-8'><input id='{{id}}_drawingNumber' class='form-control' type='text'{{#drawingNumber}} value='{{drawingNumber}}'{{/drawingNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_instructionManual'>instructionManual: </label><div class='col-sm-8'><input id='{{id}}_instructionManual' class='form-control' type='text'{{#instructionManual}} value='{{instructionManual}}'{{/instructionManual}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_modelNumber'>modelNumber: </label><div class='col-sm-8'><input id='{{id}}_modelNumber' class='form-control' type='text'{{#modelNumber}} value='{{modelNumber}}'{{/modelNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_modelVersion'>modelVersion: </label><div class='col-sm-8'><input id='{{id}}_modelVersion' class='form-control' type='text'{{#modelVersion}} value='{{modelVersion}}'{{/modelVersion}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_overallLength'>overallLength: </label><div class='col-sm-8'><input id='{{id}}_overallLength' class='form-control' type='text'{{#overallLength}} value='{{overallLength}}'{{/overallLength}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_styleNumber'>styleNumber: </label><div class='col-sm-8'><input id='{{id}}_styleNumber' class='form-control' type='text'{{#styleNumber}} value='{{styleNumber}}'{{/styleNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_usageKind'>usageKind: </label><div class='col-sm-8'><select id='{{id}}_usageKind' class='form-control custom-select'>{{#usageKindAssetModelUsageKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/usageKindAssetModelUsageKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_weightTotal'>weightTotal: </label><div class='col-sm-8'><input id='{{id}}_weightTotal' class='form-control' type='text'{{#weightTotal}} value='{{weightTotal}}'{{/weightTotal}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Manufacturer'>Manufacturer: </label><div class='col-sm-8'><input id='{{id}}_Manufacturer' class='form-control' type='text'{{#Manufacturer}} value='{{Manufacturer}}'{{/Manufacturer}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_CatalogAssetType'>CatalogAssetType: </label><div class='col-sm-8'><input id='{{id}}_CatalogAssetType' class='form-control' type='text'{{#CatalogAssetType}} value='{{CatalogAssetType}}'{{/CatalogAssetType}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetInfo'>AssetInfo: </label><div class='col-sm-8'><input id='{{id}}_AssetInfo' class='form-control' type='text'{{#AssetInfo}} value='{{AssetInfo}}'{{/AssetInfo}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ProductAssetModel" }; super.submit (id, obj); temp = document.getElementById (id + "_catalogueNumber").value; if ("" !== temp) obj["catalogueNumber"] = temp; temp = CorporateStandardKind[document.getElementById (id + "_corporateStandardKind").value]; if (temp) obj["corporateStandardKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#CorporateStandardKind." + temp; else delete obj["corporateStandardKind"]; temp = document.getElementById (id + "_drawingNumber").value; if ("" !== temp) obj["drawingNumber"] = temp; temp = document.getElementById (id + "_instructionManual").value; if ("" !== temp) obj["instructionManual"] = temp; temp = document.getElementById (id + "_modelNumber").value; if ("" !== temp) obj["modelNumber"] = temp; temp = document.getElementById (id + "_modelVersion").value; if ("" !== temp) obj["modelVersion"] = temp; temp = document.getElementById (id + "_overallLength").value; if ("" !== temp) obj["overallLength"] = temp; temp = document.getElementById (id + "_styleNumber").value; if ("" !== temp) obj["styleNumber"] = temp; temp = AssetModelUsageKind[document.getElementById (id + "_usageKind").value]; if (temp) obj["usageKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetModelUsageKind." + temp; else delete obj["usageKind"]; temp = document.getElementById (id + "_weightTotal").value; if ("" !== temp) obj["weightTotal"] = temp; temp = document.getElementById (id + "_Manufacturer").value; if ("" !== temp) obj["Manufacturer"] = temp; temp = document.getElementById (id + "_CatalogAssetType").value; if ("" !== temp) obj["CatalogAssetType"] = temp; temp = document.getElementById (id + "_AssetInfo").value; if ("" !== temp) obj["AssetInfo"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Manufacturer", "0..1", "0..*", "Manufacturer", "ProductAssetModels"], ["OperationalRestrictions", "0..*", "0..1", "OperationalRestriction", "ProductAssetModel"], ["AssetModelCatalogueItems", "0..*", "0..1", "AssetModelCatalogueItem", "AssetModel"], ["CatalogAssetType", "0..1", "0..*", "CatalogAssetType", "ProductAssetModel"], ["Asset", "0..*", "0..1", "Asset", "ProductAssetModel"], ["AssetInfo", "0..1", "0..1", "AssetInfo", "ProductAssetModel"] ] ) ); } }
JavaScript
class AssetDeployment extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetDeployment; if (null == bucket) cim_data.AssetDeployment = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetDeployment[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "AssetDeployment"; base.parse_attribute (/<cim:AssetDeployment.breakerApplication\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "breakerApplication", sub, context); base.parse_attribute (/<cim:AssetDeployment.deploymentDate\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "deploymentDate", sub, context); base.parse_attribute (/<cim:AssetDeployment.deploymentState\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "deploymentState", sub, context); base.parse_attribute (/<cim:AssetDeployment.facilityKind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "facilityKind", sub, context); base.parse_element (/<cim:AssetDeployment.likelihoodOfFailure>([\s\S]*?)<\/cim:AssetDeployment.likelihoodOfFailure>/g, obj, "likelihoodOfFailure", base.to_string, sub, context); base.parse_attribute (/<cim:AssetDeployment.transformerApplication\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "transformerApplication", sub, context); base.parse_attribute (/<cim:AssetDeployment.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); base.parse_attribute (/<cim:AssetDeployment.BaseVoltage\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "BaseVoltage", sub, context); let bucket = context.parsed.AssetDeployment; if (null == bucket) context.parsed.AssetDeployment = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_attribute (obj, "AssetDeployment", "breakerApplication", "breakerApplication", fields); base.export_attribute (obj, "AssetDeployment", "deploymentDate", "deploymentDate", fields); base.export_attribute (obj, "AssetDeployment", "deploymentState", "deploymentState", fields); base.export_attribute (obj, "AssetDeployment", "facilityKind", "facilityKind", fields); base.export_element (obj, "AssetDeployment", "likelihoodOfFailure", "likelihoodOfFailure", base.from_string, fields); base.export_attribute (obj, "AssetDeployment", "transformerApplication", "transformerApplication", fields); base.export_attribute (obj, "AssetDeployment", "Asset", "Asset", fields); base.export_attribute (obj, "AssetDeployment", "BaseVoltage", "BaseVoltage", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetDeployment_collapse" aria-expanded="true" aria-controls="AssetDeployment_collapse" style="margin-left: 10px;">AssetDeployment</a></legend> <div id="AssetDeployment_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#breakerApplication}}<div><b>breakerApplication</b>: {{breakerApplication}}</div>{{/breakerApplication}} {{#deploymentDate}}<div><b>deploymentDate</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{deploymentDate}}");}); return false;'>{{deploymentDate}}</a></div>{{/deploymentDate}} {{#deploymentState}}<div><b>deploymentState</b>: {{deploymentState}}</div>{{/deploymentState}} {{#facilityKind}}<div><b>facilityKind</b>: {{facilityKind}}</div>{{/facilityKind}} {{#likelihoodOfFailure}}<div><b>likelihoodOfFailure</b>: {{likelihoodOfFailure}}</div>{{/likelihoodOfFailure}} {{#transformerApplication}}<div><b>transformerApplication</b>: {{transformerApplication}}</div>{{/transformerApplication}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}} {{#BaseVoltage}}<div><b>BaseVoltage</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{BaseVoltage}}");}); return false;'>{{BaseVoltage}}</a></div>{{/BaseVoltage}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["breakerApplicationBreakerApplicationKind"] = [{ id: '', selected: (!obj["breakerApplication"])}]; for (let property in BreakerApplicationKind) obj["breakerApplicationBreakerApplicationKind"].push ({ id: property, selected: obj["breakerApplication"] && obj["breakerApplication"].endsWith ('.' + property)}); obj["deploymentStateDeploymentStateKind"] = [{ id: '', selected: (!obj["deploymentState"])}]; for (let property in DeploymentStateKind) obj["deploymentStateDeploymentStateKind"].push ({ id: property, selected: obj["deploymentState"] && obj["deploymentState"].endsWith ('.' + property)}); obj["facilityKindFacilityKind"] = [{ id: '', selected: (!obj["facilityKind"])}]; for (let property in FacilityKind) obj["facilityKindFacilityKind"].push ({ id: property, selected: obj["facilityKind"] && obj["facilityKind"].endsWith ('.' + property)}); obj["transformerApplicationTransformerApplicationKind"] = [{ id: '', selected: (!obj["transformerApplication"])}]; for (let property in TransformerApplicationKind) obj["transformerApplicationTransformerApplicationKind"].push ({ id: property, selected: obj["transformerApplication"] && obj["transformerApplication"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["breakerApplicationBreakerApplicationKind"]; delete obj["deploymentStateDeploymentStateKind"]; delete obj["facilityKindFacilityKind"]; delete obj["transformerApplicationTransformerApplicationKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetDeployment_collapse" aria-expanded="true" aria-controls="{{id}}_AssetDeployment_collapse" style="margin-left: 10px;">AssetDeployment</a></legend> <div id="{{id}}_AssetDeployment_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_breakerApplication'>breakerApplication: </label><div class='col-sm-8'><select id='{{id}}_breakerApplication' class='form-control custom-select'>{{#breakerApplicationBreakerApplicationKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/breakerApplicationBreakerApplicationKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_deploymentDate'>deploymentDate: </label><div class='col-sm-8'><input id='{{id}}_deploymentDate' class='form-control' type='text'{{#deploymentDate}} value='{{deploymentDate}}'{{/deploymentDate}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_deploymentState'>deploymentState: </label><div class='col-sm-8'><select id='{{id}}_deploymentState' class='form-control custom-select'>{{#deploymentStateDeploymentStateKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/deploymentStateDeploymentStateKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_facilityKind'>facilityKind: </label><div class='col-sm-8'><select id='{{id}}_facilityKind' class='form-control custom-select'>{{#facilityKindFacilityKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/facilityKindFacilityKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_likelihoodOfFailure'>likelihoodOfFailure: </label><div class='col-sm-8'><input id='{{id}}_likelihoodOfFailure' class='form-control' type='text'{{#likelihoodOfFailure}} value='{{likelihoodOfFailure}}'{{/likelihoodOfFailure}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_transformerApplication'>transformerApplication: </label><div class='col-sm-8'><select id='{{id}}_transformerApplication' class='form-control custom-select'>{{#transformerApplicationTransformerApplicationKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/transformerApplicationTransformerApplicationKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_BaseVoltage'>BaseVoltage: </label><div class='col-sm-8'><input id='{{id}}_BaseVoltage' class='form-control' type='text'{{#BaseVoltage}} value='{{BaseVoltage}}'{{/BaseVoltage}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetDeployment" }; super.submit (id, obj); temp = BreakerApplicationKind[document.getElementById (id + "_breakerApplication").value]; if (temp) obj["breakerApplication"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#BreakerApplicationKind." + temp; else delete obj["breakerApplication"]; temp = document.getElementById (id + "_deploymentDate").value; if ("" !== temp) obj["deploymentDate"] = temp; temp = DeploymentStateKind[document.getElementById (id + "_deploymentState").value]; if (temp) obj["deploymentState"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#DeploymentStateKind." + temp; else delete obj["deploymentState"]; temp = FacilityKind[document.getElementById (id + "_facilityKind").value]; if (temp) obj["facilityKind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#FacilityKind." + temp; else delete obj["facilityKind"]; temp = document.getElementById (id + "_likelihoodOfFailure").value; if ("" !== temp) obj["likelihoodOfFailure"] = temp; temp = TransformerApplicationKind[document.getElementById (id + "_transformerApplication").value]; if (temp) obj["transformerApplication"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TransformerApplicationKind." + temp; else delete obj["transformerApplication"]; temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp; temp = document.getElementById (id + "_BaseVoltage").value; if ("" !== temp) obj["BaseVoltage"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["Asset", "0..1", "0..1", "Asset", "AssetDeployment"], ["BaseVoltage", "1", "0..*", "BaseVoltage", "NetworkAssetDeployment"] ] ) ); } }
JavaScript
class CatalogAssetType extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.CatalogAssetType; if (null == bucket) cim_data.CatalogAssetType = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.CatalogAssetType[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "CatalogAssetType"; base.parse_element (/<cim:CatalogAssetType.estimatedUnitCost>([\s\S]*?)<\/cim:CatalogAssetType.estimatedUnitCost>/g, obj, "estimatedUnitCost", base.to_string, sub, context); base.parse_attribute (/<cim:CatalogAssetType.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context); base.parse_attribute (/<cim:CatalogAssetType.quantity\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "quantity", sub, context); base.parse_element (/<cim:CatalogAssetType.stockItem>([\s\S]*?)<\/cim:CatalogAssetType.stockItem>/g, obj, "stockItem", base.to_boolean, sub, context); base.parse_element (/<cim:CatalogAssetType.type>([\s\S]*?)<\/cim:CatalogAssetType.type>/g, obj, "type", base.to_string, sub, context); base.parse_attributes (/<cim:CatalogAssetType.ErpInventoryIssues\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpInventoryIssues", sub, context); base.parse_attributes (/<cim:CatalogAssetType.ErpBomItemDatas\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpBomItemDatas", sub, context); base.parse_attribute (/<cim:CatalogAssetType.TypeAssetCatalogue\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TypeAssetCatalogue", sub, context); base.parse_attribute (/<cim:CatalogAssetType.AssetInfo\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetInfo", sub, context); base.parse_attributes (/<cim:CatalogAssetType.ErpReqLineItems\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ErpReqLineItems", sub, context); base.parse_attributes (/<cim:CatalogAssetType.ProductAssetModel\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "ProductAssetModel", sub, context); base.parse_attributes (/<cim:CatalogAssetType.CompatibleUnits\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "CompatibleUnits", sub, context); let bucket = context.parsed.CatalogAssetType; if (null == bucket) context.parsed.CatalogAssetType = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "CatalogAssetType", "estimatedUnitCost", "estimatedUnitCost", base.from_string, fields); base.export_attribute (obj, "CatalogAssetType", "kind", "kind", fields); base.export_attribute (obj, "CatalogAssetType", "quantity", "quantity", fields); base.export_element (obj, "CatalogAssetType", "stockItem", "stockItem", base.from_boolean, fields); base.export_element (obj, "CatalogAssetType", "type", "type", base.from_string, fields); base.export_attributes (obj, "CatalogAssetType", "ErpInventoryIssues", "ErpInventoryIssues", fields); base.export_attributes (obj, "CatalogAssetType", "ErpBomItemDatas", "ErpBomItemDatas", fields); base.export_attribute (obj, "CatalogAssetType", "TypeAssetCatalogue", "TypeAssetCatalogue", fields); base.export_attribute (obj, "CatalogAssetType", "AssetInfo", "AssetInfo", fields); base.export_attributes (obj, "CatalogAssetType", "ErpReqLineItems", "ErpReqLineItems", fields); base.export_attributes (obj, "CatalogAssetType", "ProductAssetModel", "ProductAssetModel", fields); base.export_attributes (obj, "CatalogAssetType", "CompatibleUnits", "CompatibleUnits", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#CatalogAssetType_collapse" aria-expanded="true" aria-controls="CatalogAssetType_collapse" style="margin-left: 10px;">CatalogAssetType</a></legend> <div id="CatalogAssetType_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#estimatedUnitCost}}<div><b>estimatedUnitCost</b>: {{estimatedUnitCost}}</div>{{/estimatedUnitCost}} {{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}} {{#quantity}}<div><b>quantity</b>: {{quantity}}</div>{{/quantity}} {{#stockItem}}<div><b>stockItem</b>: {{stockItem}}</div>{{/stockItem}} {{#type}}<div><b>type</b>: {{type}}</div>{{/type}} {{#ErpInventoryIssues}}<div><b>ErpInventoryIssues</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpInventoryIssues}} {{#ErpBomItemDatas}}<div><b>ErpBomItemDatas</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpBomItemDatas}} {{#TypeAssetCatalogue}}<div><b>TypeAssetCatalogue</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{TypeAssetCatalogue}}");}); return false;'>{{TypeAssetCatalogue}}</a></div>{{/TypeAssetCatalogue}} {{#AssetInfo}}<div><b>AssetInfo</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetInfo}}");}); return false;'>{{AssetInfo}}</a></div>{{/AssetInfo}} {{#ErpReqLineItems}}<div><b>ErpReqLineItems</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ErpReqLineItems}} {{#ProductAssetModel}}<div><b>ProductAssetModel</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/ProductAssetModel}} {{#CompatibleUnits}}<div><b>CompatibleUnits</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/CompatibleUnits}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["kindAssetKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in AssetKind) obj["kindAssetKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)}); if (obj["ErpInventoryIssues"]) obj["ErpInventoryIssues_string"] = obj["ErpInventoryIssues"].join (); if (obj["ErpBomItemDatas"]) obj["ErpBomItemDatas_string"] = obj["ErpBomItemDatas"].join (); if (obj["ErpReqLineItems"]) obj["ErpReqLineItems_string"] = obj["ErpReqLineItems"].join (); if (obj["ProductAssetModel"]) obj["ProductAssetModel_string"] = obj["ProductAssetModel"].join (); if (obj["CompatibleUnits"]) obj["CompatibleUnits_string"] = obj["CompatibleUnits"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["kindAssetKind"]; delete obj["ErpInventoryIssues_string"]; delete obj["ErpBomItemDatas_string"]; delete obj["ErpReqLineItems_string"]; delete obj["ProductAssetModel_string"]; delete obj["CompatibleUnits_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_CatalogAssetType_collapse" aria-expanded="true" aria-controls="{{id}}_CatalogAssetType_collapse" style="margin-left: 10px;">CatalogAssetType</a></legend> <div id="{{id}}_CatalogAssetType_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_estimatedUnitCost'>estimatedUnitCost: </label><div class='col-sm-8'><input id='{{id}}_estimatedUnitCost' class='form-control' type='text'{{#estimatedUnitCost}} value='{{estimatedUnitCost}}'{{/estimatedUnitCost}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindAssetKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindAssetKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_quantity'>quantity: </label><div class='col-sm-8'><input id='{{id}}_quantity' class='form-control' type='text'{{#quantity}} value='{{quantity}}'{{/quantity}}></div></div> <div class='form-group row'><div class='col-sm-4' for='{{id}}_stockItem'>stockItem: </div><div class='col-sm-8'><div class='form-check'><input id='{{id}}_stockItem' class='form-check-input' type='checkbox'{{#stockItem}} checked{{/stockItem}}></div></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_type'>type: </label><div class='col-sm-8'><input id='{{id}}_type' class='form-control' type='text'{{#type}} value='{{type}}'{{/type}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TypeAssetCatalogue'>TypeAssetCatalogue: </label><div class='col-sm-8'><input id='{{id}}_TypeAssetCatalogue' class='form-control' type='text'{{#TypeAssetCatalogue}} value='{{TypeAssetCatalogue}}'{{/TypeAssetCatalogue}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetInfo'>AssetInfo: </label><div class='col-sm-8'><input id='{{id}}_AssetInfo' class='form-control' type='text'{{#AssetInfo}} value='{{AssetInfo}}'{{/AssetInfo}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "CatalogAssetType" }; super.submit (id, obj); temp = document.getElementById (id + "_estimatedUnitCost").value; if ("" !== temp) obj["estimatedUnitCost"] = temp; temp = AssetKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#AssetKind." + temp; else delete obj["kind"]; temp = document.getElementById (id + "_quantity").value; if ("" !== temp) obj["quantity"] = temp; temp = document.getElementById (id + "_stockItem").checked; if (temp) obj["stockItem"] = true; temp = document.getElementById (id + "_type").value; if ("" !== temp) obj["type"] = temp; temp = document.getElementById (id + "_TypeAssetCatalogue").value; if ("" !== temp) obj["TypeAssetCatalogue"] = temp; temp = document.getElementById (id + "_AssetInfo").value; if ("" !== temp) obj["AssetInfo"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["ErpInventoryIssues", "0..*", "0..1", "ErpIssueInventory", "TypeAsset"], ["ErpBomItemDatas", "0..*", "0..1", "ErpBomItemData", "TypeAsset"], ["TypeAssetCatalogue", "0..1", "0..*", "TypeAssetCatalogue", "TypeAssets"], ["AssetInfo", "0..1", "0..1", "AssetInfo", "CatalogAssetType"], ["ErpReqLineItems", "0..*", "0..1", "ErpReqLineItem", "TypeAsset"], ["ProductAssetModel", "0..*", "0..1", "ProductAssetModel", "CatalogAssetType"], ["CompatibleUnits", "0..*", "0..1", "CompatibleUnit", "GenericAssetModel"] ] ) ); } }
JavaScript
class DINStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.DINStandard; if (null == bucket) cim_data.DINStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.DINStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "DINStandard"; base.parse_attribute (/<cim:DINStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:DINStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.DINStandard; if (null == bucket) context.parsed.DINStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "DINStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "DINStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#DINStandard_collapse" aria-expanded="true" aria-controls="DINStandard_collapse" style="margin-left: 10px;">DINStandard</a></legend> <div id="DINStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionDINStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in DINStandardEditionKind) obj["standardEditionDINStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberDINStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in DINStandardKind) obj["standardNumberDINStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionDINStandardEditionKind"]; delete obj["standardNumberDINStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_DINStandard_collapse" aria-expanded="true" aria-controls="{{id}}_DINStandard_collapse" style="margin-left: 10px;">DINStandard</a></legend> <div id="{{id}}_DINStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionDINStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionDINStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberDINStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberDINStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "DINStandard" }; super.submit (id, obj); temp = DINStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#DINStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = DINStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#DINStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class TAPPIStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.TAPPIStandard; if (null == bucket) cim_data.TAPPIStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.TAPPIStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "TAPPIStandard"; base.parse_attribute (/<cim:TAPPIStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:TAPPIStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.TAPPIStandard; if (null == bucket) context.parsed.TAPPIStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "TAPPIStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "TAPPIStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#TAPPIStandard_collapse" aria-expanded="true" aria-controls="TAPPIStandard_collapse" style="margin-left: 10px;">TAPPIStandard</a></legend> <div id="TAPPIStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionTAPPIStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in TAPPIStandardEditionKind) obj["standardEditionTAPPIStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberTAPPIStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in TAPPIStandardKind) obj["standardNumberTAPPIStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionTAPPIStandardEditionKind"]; delete obj["standardNumberTAPPIStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_TAPPIStandard_collapse" aria-expanded="true" aria-controls="{{id}}_TAPPIStandard_collapse" style="margin-left: 10px;">TAPPIStandard</a></legend> <div id="{{id}}_TAPPIStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionTAPPIStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionTAPPIStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberTAPPIStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberTAPPIStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "TAPPIStandard" }; super.submit (id, obj); temp = TAPPIStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TAPPIStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = TAPPIStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#TAPPIStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class AssetOrganisationRole extends Common.OrganisationRole { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.AssetOrganisationRole; if (null == bucket) cim_data.AssetOrganisationRole = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.AssetOrganisationRole[obj.id]; } parse (context, sub) { let obj = Common.OrganisationRole.prototype.parse.call (this, context, sub); obj.cls = "AssetOrganisationRole"; base.parse_attributes (/<cim:AssetOrganisationRole.Assets\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Assets", sub, context); let bucket = context.parsed.AssetOrganisationRole; if (null == bucket) context.parsed.AssetOrganisationRole = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.OrganisationRole.prototype.export.call (this, obj, false); base.export_attributes (obj, "AssetOrganisationRole", "Assets", "Assets", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#AssetOrganisationRole_collapse" aria-expanded="true" aria-controls="AssetOrganisationRole_collapse" style="margin-left: 10px;">AssetOrganisationRole</a></legend> <div id="AssetOrganisationRole_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.OrganisationRole.prototype.template.call (this) + ` {{#Assets}}<div><b>Assets</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Assets}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["Assets"]) obj["Assets_string"] = obj["Assets"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["Assets_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_AssetOrganisationRole_collapse" aria-expanded="true" aria-controls="{{id}}_AssetOrganisationRole_collapse" style="margin-left: 10px;">AssetOrganisationRole</a></legend> <div id="{{id}}_AssetOrganisationRole_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.OrganisationRole.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Assets'>Assets: </label><div class='col-sm-8'><input id='{{id}}_Assets' class='form-control' type='text'{{#Assets}} value='{{Assets_string}}'{{/Assets}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "AssetOrganisationRole" }; super.submit (id, obj); temp = document.getElementById (id + "_Assets").value; if ("" !== temp) obj["Assets"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["Assets", "0..*", "0..*", "Asset", "OrganisationRoles"] ] ) ); } }
JavaScript
class ProcedureDataSet extends Common.Document { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ProcedureDataSet; if (null == bucket) cim_data.ProcedureDataSet = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ProcedureDataSet[obj.id]; } parse (context, sub) { let obj = Common.Document.prototype.parse.call (this, context, sub); obj.cls = "ProcedureDataSet"; base.parse_element (/<cim:ProcedureDataSet.completedDateTime>([\s\S]*?)<\/cim:ProcedureDataSet.completedDateTime>/g, obj, "completedDateTime", base.to_datetime, sub, context); base.parse_attributes (/<cim:ProcedureDataSet.Properties\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Properties", sub, context); base.parse_attribute (/<cim:ProcedureDataSet.WorkTask\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "WorkTask", sub, context); base.parse_attribute (/<cim:ProcedureDataSet.Procedure\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Procedure", sub, context); base.parse_attribute (/<cim:ProcedureDataSet.Asset\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "Asset", sub, context); base.parse_attributes (/<cim:ProcedureDataSet.TransformerObservations\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "TransformerObservations", sub, context); base.parse_attributes (/<cim:ProcedureDataSet.MeasurementValue\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "MeasurementValue", sub, context); let bucket = context.parsed.ProcedureDataSet; if (null == bucket) context.parsed.ProcedureDataSet = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Common.Document.prototype.export.call (this, obj, false); base.export_element (obj, "ProcedureDataSet", "completedDateTime", "completedDateTime", base.from_datetime, fields); base.export_attributes (obj, "ProcedureDataSet", "Properties", "Properties", fields); base.export_attribute (obj, "ProcedureDataSet", "WorkTask", "WorkTask", fields); base.export_attribute (obj, "ProcedureDataSet", "Procedure", "Procedure", fields); base.export_attribute (obj, "ProcedureDataSet", "Asset", "Asset", fields); base.export_attributes (obj, "ProcedureDataSet", "TransformerObservations", "TransformerObservations", fields); base.export_attributes (obj, "ProcedureDataSet", "MeasurementValue", "MeasurementValue", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ProcedureDataSet_collapse" aria-expanded="true" aria-controls="ProcedureDataSet_collapse" style="margin-left: 10px;">ProcedureDataSet</a></legend> <div id="ProcedureDataSet_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.Document.prototype.template.call (this) + ` {{#completedDateTime}}<div><b>completedDateTime</b>: {{completedDateTime}}</div>{{/completedDateTime}} {{#Properties}}<div><b>Properties</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/Properties}} {{#WorkTask}}<div><b>WorkTask</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{WorkTask}}");}); return false;'>{{WorkTask}}</a></div>{{/WorkTask}} {{#Procedure}}<div><b>Procedure</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Procedure}}");}); return false;'>{{Procedure}}</a></div>{{/Procedure}} {{#Asset}}<div><b>Asset</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{Asset}}");}); return false;'>{{Asset}}</a></div>{{/Asset}} {{#TransformerObservations}}<div><b>TransformerObservations</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/TransformerObservations}} {{#MeasurementValue}}<div><b>MeasurementValue</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{.}}");}); return false;'>{{.}}</a></div>{{/MeasurementValue}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); if (obj["Properties"]) obj["Properties_string"] = obj["Properties"].join (); if (obj["TransformerObservations"]) obj["TransformerObservations_string"] = obj["TransformerObservations"].join (); if (obj["MeasurementValue"]) obj["MeasurementValue_string"] = obj["MeasurementValue"].join (); } uncondition (obj) { super.uncondition (obj); delete obj["Properties_string"]; delete obj["TransformerObservations_string"]; delete obj["MeasurementValue_string"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ProcedureDataSet_collapse" aria-expanded="true" aria-controls="{{id}}_ProcedureDataSet_collapse" style="margin-left: 10px;">ProcedureDataSet</a></legend> <div id="{{id}}_ProcedureDataSet_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Common.Document.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_completedDateTime'>completedDateTime: </label><div class='col-sm-8'><input id='{{id}}_completedDateTime' class='form-control' type='text'{{#completedDateTime}} value='{{completedDateTime}}'{{/completedDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Properties'>Properties: </label><div class='col-sm-8'><input id='{{id}}_Properties' class='form-control' type='text'{{#Properties}} value='{{Properties_string}}'{{/Properties}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_WorkTask'>WorkTask: </label><div class='col-sm-8'><input id='{{id}}_WorkTask' class='form-control' type='text'{{#WorkTask}} value='{{WorkTask}}'{{/WorkTask}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Procedure'>Procedure: </label><div class='col-sm-8'><input id='{{id}}_Procedure' class='form-control' type='text'{{#Procedure}} value='{{Procedure}}'{{/Procedure}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_Asset'>Asset: </label><div class='col-sm-8'><input id='{{id}}_Asset' class='form-control' type='text'{{#Asset}} value='{{Asset}}'{{/Asset}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_TransformerObservations'>TransformerObservations: </label><div class='col-sm-8'><input id='{{id}}_TransformerObservations' class='form-control' type='text'{{#TransformerObservations}} value='{{TransformerObservations_string}}'{{/TransformerObservations}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_MeasurementValue'>MeasurementValue: </label><div class='col-sm-8'><input id='{{id}}_MeasurementValue' class='form-control' type='text'{{#MeasurementValue}} value='{{MeasurementValue_string}}'{{/MeasurementValue}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ProcedureDataSet" }; super.submit (id, obj); temp = document.getElementById (id + "_completedDateTime").value; if ("" !== temp) obj["completedDateTime"] = temp; temp = document.getElementById (id + "_Properties").value; if ("" !== temp) obj["Properties"] = temp.split (","); temp = document.getElementById (id + "_WorkTask").value; if ("" !== temp) obj["WorkTask"] = temp; temp = document.getElementById (id + "_Procedure").value; if ("" !== temp) obj["Procedure"] = temp; temp = document.getElementById (id + "_Asset").value; if ("" !== temp) obj["Asset"] = temp; temp = document.getElementById (id + "_TransformerObservations").value; if ("" !== temp) obj["TransformerObservations"] = temp.split (","); temp = document.getElementById (id + "_MeasurementValue").value; if ("" !== temp) obj["MeasurementValue"] = temp.split (","); return (obj); } relations () { return ( super.relations ().concat ( [ ["Properties", "0..*", "0..*", "UserAttribute", "ProcedureDataSets"], ["WorkTask", "0..1", "0..*", "WorkTask", "ProcedureDataSet"], ["Procedure", "0..1", "0..*", "Procedure", "ProcedureDataSets"], ["Asset", "0..1", "0..*", "Asset", "ProcedureDataSet"], ["TransformerObservations", "0..*", "0..*", "TransformerObservation", "ProcedureDataSets"], ["MeasurementValue", "0..*", "0..*", "MeasurementValue", "ProcedureDataSet"] ] ) ); } }
JavaScript
class ISOStandard extends base.Element { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.ISOStandard; if (null == bucket) cim_data.ISOStandard = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.ISOStandard[obj.id]; } parse (context, sub) { let obj = base.Element.prototype.parse.call (this, context, sub); obj.cls = "ISOStandard"; base.parse_attribute (/<cim:ISOStandard.standardEdition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardEdition", sub, context); base.parse_attribute (/<cim:ISOStandard.standardNumber\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "standardNumber", sub, context); let bucket = context.parsed.ISOStandard; if (null == bucket) context.parsed.ISOStandard = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = []; base.export_attribute (obj, "ISOStandard", "standardEdition", "standardEdition", fields); base.export_attribute (obj, "ISOStandard", "standardNumber", "standardNumber", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#ISOStandard_collapse" aria-expanded="true" aria-controls="ISOStandard_collapse" style="margin-left: 10px;">ISOStandard</a></legend> <div id="ISOStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.template.call (this) + ` {{#standardEdition}}<div><b>standardEdition</b>: {{standardEdition}}</div>{{/standardEdition}} {{#standardNumber}}<div><b>standardNumber</b>: {{standardNumber}}</div>{{/standardNumber}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["standardEditionISOStandardEditionKind"] = [{ id: '', selected: (!obj["standardEdition"])}]; for (let property in ISOStandardEditionKind) obj["standardEditionISOStandardEditionKind"].push ({ id: property, selected: obj["standardEdition"] && obj["standardEdition"].endsWith ('.' + property)}); obj["standardNumberISOStandardKind"] = [{ id: '', selected: (!obj["standardNumber"])}]; for (let property in ISOStandardKind) obj["standardNumberISOStandardKind"].push ({ id: property, selected: obj["standardNumber"] && obj["standardNumber"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["standardEditionISOStandardEditionKind"]; delete obj["standardNumberISOStandardKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_ISOStandard_collapse" aria-expanded="true" aria-controls="{{id}}_ISOStandard_collapse" style="margin-left: 10px;">ISOStandard</a></legend> <div id="{{id}}_ISOStandard_collapse" class="collapse in show" style="margin-left: 10px;"> ` + base.Element.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardEdition'>standardEdition: </label><div class='col-sm-8'><select id='{{id}}_standardEdition' class='form-control custom-select'>{{#standardEditionISOStandardEditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardEditionISOStandardEditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_standardNumber'>standardNumber: </label><div class='col-sm-8'><select id='{{id}}_standardNumber' class='form-control custom-select'>{{#standardNumberISOStandardKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/standardNumberISOStandardKind}}</select></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "ISOStandard" }; super.submit (id, obj); temp = ISOStandardEditionKind[document.getElementById (id + "_standardEdition").value]; if (temp) obj["standardEdition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ISOStandardEditionKind." + temp; else delete obj["standardEdition"]; temp = ISOStandardKind[document.getElementById (id + "_standardNumber").value]; if (temp) obj["standardNumber"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#ISOStandardKind." + temp; else delete obj["standardNumber"]; return (obj); } }
JavaScript
class Seal extends Core.IdentifiedObject { constructor (template, cim_data) { super (template, cim_data); let bucket = cim_data.Seal; if (null == bucket) cim_data.Seal = bucket = {}; bucket[template.id] = template; } remove (obj, cim_data) { super.remove (obj, cim_data); delete cim_data.Seal[obj.id]; } parse (context, sub) { let obj = Core.IdentifiedObject.prototype.parse.call (this, context, sub); obj.cls = "Seal"; base.parse_element (/<cim:Seal.appliedDateTime>([\s\S]*?)<\/cim:Seal.appliedDateTime>/g, obj, "appliedDateTime", base.to_datetime, sub, context); base.parse_attribute (/<cim:Seal.condition\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "condition", sub, context); base.parse_attribute (/<cim:Seal.kind\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "kind", sub, context); base.parse_element (/<cim:Seal.sealNumber>([\s\S]*?)<\/cim:Seal.sealNumber>/g, obj, "sealNumber", base.to_string, sub, context); base.parse_attribute (/<cim:Seal.AssetContainer\s+rdf:resource\s*?=\s*?(["'])([\s\S]*?)\1\s*?\/>/g, obj, "AssetContainer", sub, context); let bucket = context.parsed.Seal; if (null == bucket) context.parsed.Seal = bucket = {}; bucket[obj.id] = obj; return (obj); } export (obj, full) { let fields = Core.IdentifiedObject.prototype.export.call (this, obj, false); base.export_element (obj, "Seal", "appliedDateTime", "appliedDateTime", base.from_datetime, fields); base.export_attribute (obj, "Seal", "condition", "condition", fields); base.export_attribute (obj, "Seal", "kind", "kind", fields); base.export_element (obj, "Seal", "sealNumber", "sealNumber", base.from_string, fields); base.export_attribute (obj, "Seal", "AssetContainer", "AssetContainer", fields); if (full) base.Element.prototype.export.call (this, obj, fields); return (fields); } template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#Seal_collapse" aria-expanded="true" aria-controls="Seal_collapse" style="margin-left: 10px;">Seal</a></legend> <div id="Seal_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.template.call (this) + ` {{#appliedDateTime}}<div><b>appliedDateTime</b>: {{appliedDateTime}}</div>{{/appliedDateTime}} {{#condition}}<div><b>condition</b>: {{condition}}</div>{{/condition}} {{#kind}}<div><b>kind</b>: {{kind}}</div>{{/kind}} {{#sealNumber}}<div><b>sealNumber</b>: {{sealNumber}}</div>{{/sealNumber}} {{#AssetContainer}}<div><b>AssetContainer</b>: <a href='#' onclick='require(["cimmap"], function(cimmap) {cimmap.select ("{{AssetContainer}}");}); return false;'>{{AssetContainer}}</a></div>{{/AssetContainer}} </div> </fieldset> ` ); } condition (obj) { super.condition (obj); obj["conditionSealConditionKind"] = [{ id: '', selected: (!obj["condition"])}]; for (let property in SealConditionKind) obj["conditionSealConditionKind"].push ({ id: property, selected: obj["condition"] && obj["condition"].endsWith ('.' + property)}); obj["kindSealKind"] = [{ id: '', selected: (!obj["kind"])}]; for (let property in SealKind) obj["kindSealKind"].push ({ id: property, selected: obj["kind"] && obj["kind"].endsWith ('.' + property)}); } uncondition (obj) { super.uncondition (obj); delete obj["conditionSealConditionKind"]; delete obj["kindSealKind"]; } edit_template () { return ( ` <fieldset> <legend class='col-form-legend'><a class="collapse-link" data-toggle="collapse" href="#{{id}}_Seal_collapse" aria-expanded="true" aria-controls="{{id}}_Seal_collapse" style="margin-left: 10px;">Seal</a></legend> <div id="{{id}}_Seal_collapse" class="collapse in show" style="margin-left: 10px;"> ` + Core.IdentifiedObject.prototype.edit_template.call (this) + ` <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_appliedDateTime'>appliedDateTime: </label><div class='col-sm-8'><input id='{{id}}_appliedDateTime' class='form-control' type='text'{{#appliedDateTime}} value='{{appliedDateTime}}'{{/appliedDateTime}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_condition'>condition: </label><div class='col-sm-8'><select id='{{id}}_condition' class='form-control custom-select'>{{#conditionSealConditionKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/conditionSealConditionKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_kind'>kind: </label><div class='col-sm-8'><select id='{{id}}_kind' class='form-control custom-select'>{{#kindSealKind}}<option value='{{id}}'{{#selected}} selected{{/selected}}>{{id}}</option>{{/kindSealKind}}</select></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_sealNumber'>sealNumber: </label><div class='col-sm-8'><input id='{{id}}_sealNumber' class='form-control' type='text'{{#sealNumber}} value='{{sealNumber}}'{{/sealNumber}}></div></div> <div class='form-group row'><label class='col-sm-4 col-form-label' for='{{id}}_AssetContainer'>AssetContainer: </label><div class='col-sm-8'><input id='{{id}}_AssetContainer' class='form-control' type='text'{{#AssetContainer}} value='{{AssetContainer}}'{{/AssetContainer}}></div></div> </div> </fieldset> ` ); } submit (id, obj) { let temp; obj = obj || { id: id, cls: "Seal" }; super.submit (id, obj); temp = document.getElementById (id + "_appliedDateTime").value; if ("" !== temp) obj["appliedDateTime"] = temp; temp = SealConditionKind[document.getElementById (id + "_condition").value]; if (temp) obj["condition"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#SealConditionKind." + temp; else delete obj["condition"]; temp = SealKind[document.getElementById (id + "_kind").value]; if (temp) obj["kind"] = "http://iec.ch/TC57/2016/CIM-schema-cim17#SealKind." + temp; else delete obj["kind"]; temp = document.getElementById (id + "_sealNumber").value; if ("" !== temp) obj["sealNumber"] = temp; temp = document.getElementById (id + "_AssetContainer").value; if ("" !== temp) obj["AssetContainer"] = temp; return (obj); } relations () { return ( super.relations ().concat ( [ ["AssetContainer", "0..1", "0..*", "AssetContainer", "Seals"] ] ) ); } }