language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class Results extends React.Component { onOutsideEvent = (event) => { if(event.target.id != 'charles-search-field') { this.props.getSearchResults(""); } } render() { var resArray = this.props.searchResults.results; var resultsDivs = []; if(resArray) { for (var i = 0; i < resArray.length; i++) { resultsDivs.push( <SearchResult id={"search-result-" + i} key={"search-result-" + i} link={resArray[i].link} title={resArray[i].title} text={resArray[i].highlight} /> ); } } return ( resultsDivs.length > 0 ? <div id="resultsPanel" className="resultsPanel"> <div className="suggestionGroupClass" id="suggestions"> { resultsDivs.map( function(result){ return result; } ) } </div> <PageNumbers getSearchResults={this.props.getSearchResults} results={this.props.searchResults} id="paginator" key="paginator" /> </div> : null ); } }
JavaScript
class BarcodeTest extends Component { // 构造 constructor (props) { super(props); // 初始状态 this.state = { viewAppear: false, }; } render () { return ( <View style={{flex: 1, backgroundColor: 'black', justifyContent: 'center', alignItems: 'center',}}> {this.state.viewAppear ? <Barcode style={{flex: 1, alignSelf: 'stretch', }} ref={ component => this._barCode = component } onBarCodeRead={this._onBarCodeRead}/> : null} {!this.state.viewAppear ? this._renderActivityIndicator() : null} </View> ) } // //{!this.state.viewAppear ? //<View style={{ position: 'absolute', left: 0, top: 0, width: deviceWidth, deviceHeight: deviceHeight, justifyContent: 'center', alignItems: 'center'}}> //{this._renderActivityIndicator()} //</View> : null} componentDidMount () { let viewAppearCallBack = (event) => { this.setTimeout(() => { this.setState({ viewAppear: true, }) }, 255) } this._listeners = [ this.props.navigator.navigationContext.addListener('didfocus', viewAppearCallBack) ] } componentWillUnmount () { this._listeners && this._listeners.forEach(listener => listener.remove()); } _onBarCodeRead = (e) => { console.log(`e.nativeEvent.data.type = ${e.nativeEvent.data.type}, e.nativeEvent.data.code = ${e.nativeEvent.data.code}`) this._stopScan() Alert.alert(e.nativeEvent.data.type, e.nativeEvent.data.code, [ { text: 'OK', onPress: () => this._startScan() }, ]) } _startScan = (e) => { this._barCode.startScan() } _stopScan = (e) => { this._barCode.stopScan() } _renderActivityIndicator () { return ActivityIndicator ? ( <ActivityIndicator style={{position: 'relative', left: 1, top: 1,}} animating={true} size={'large'}/> ) : Platform.OS == 'android' ? ( <ProgressBarAndroid styleAttr={'large'}/> ) : ( <ActivityIndicatorIOS animating={true} size={'large'}/> ) } }
JavaScript
class List { listItems; /** * * @param {ListItem[]?} list */ constructor(list) { this.listItems = list ?? []; } /** * Trims leading and trailing spaces from ListItem and pushes it to the array (this List object) * * @param {ListItem} listItem */ addItem(listItem) { listItem.taskValue = listItem.taskValue.trim(); this.listItems.push(listItem); } /** * Removes the specified index from the array * * @param {number} index */ removeItem(index) { this.listItems.splice(index, 1); } /** * sets the index with new value * * @param {number} index * @param {ListItem} newValue */ setItem(index, newValue) { this.listItems[index] = newValue; } /** * Toggles done status for single index (currently unused) * * @param {number} index */ toggleDone(index) { /** @type {ListItem} */ const item = this.listItems[index]; this.setItem(index, { taskValue: item.taskValue, isDone: !item.isDone, }); } /** * @returns {ListItem[]} */ toJSON() { return this.listItems; } /** * @returns {string} */ toString() { return JSON.stringify(this.listItems); } }
JavaScript
class App extends BaseModel { static initialize(sequelize) { App.init({ id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true}, slug: {type: DataTypes.STRING, allowNull: false, comment: 'Unique in within account; letters, numbers, dashes'}, version: {type: DataTypes.INTEGER, allowNull: false}, name: {type: DataTypes.STRING, allowNull: false}, environment: {type: DataTypes.STRING, allowNull: false}, description: {type: DataTypes.STRING}, moduleTemplateId: {type: DataTypes.INTEGER, allowNull: true}, parameters: {type: DataTypes.JSONB, allowNull: true}, primitive: {type: DataTypes.BOOLEAN, allowNull: true, comment: 'Is this a core app?'}, }, { sequelize, modelName: MODEL_NAME, tableName: TABLE_NAME, }); } static associate(models) { App.belongsTo(models.ModuleTemplate); App.belongsTo(models.DevAccount); App.hasMany(models.WidgetClass); App.hasMany(models.ModuleInstanceSetup); } }
JavaScript
class Controller { constructor(view) { this.view = view; this.computing = false; //to avoid computing two instances at the same time this.webWorker = null; } //load an instance and calculate result. Result is shown in the log section of the GUI. loadAndSolve(instanceSource, instance, algorithm, algoParams) { if (this.computing === true) { this.view.log("Error! Already computing!"); return; } this._updateViewButtons(this.view, true, false); this.instanceSource = instanceSource; this.instance = instance; this.algorithm = algorithm; this.computing = true; this.loadInstance(instanceSource, instance, (text) => { if (this.computing === false) return; //stop if the user pressed stop before instance was load this.view.log("Data loaded"); if (algorithm !== "SIMPLEX") this._createWorker(text); else this._solveWithSimplex(text); }, error => { this.view.log(error); this.computing = false; this._updateViewButtons(self.view, false, false); }); } _solveWithSimplex(text) { var self = this; this.view.log("Executing algorithm..."); GLPKSolver.solve(text, result => { if (result === Infinity) this.view.log("No feasible solution found"); else this.view.log("Best LP solution has cost " + result.toFixed(3)); this._updateViewButtons(self.view, false, false); this.computing = false; }); } //create a worker to solve an instance using one metaheuristic _createWorker(text) { if (typeof Worker === "undefined") { this.view.log("Sorry, your browser does not support workers."); return; } var self = this; this.view.log("Executing algorithm..."); this.webWorker = new Worker("js/GAPSolverWorker.js?v=2"); this.webWorker.postMessage(text); this.webWorker.postMessage(this.algorithm); this.webWorker.onmessage = function (event) { self.solution = event.data; Object.setPrototypeOf(self.solution, GAPSolution.prototype); Object.setPrototypeOf(self.solution.getInstance(), GAPInstance.prototype); self.computing = false; if (self.solution.isFeasible()) { self.view.log("Done: solution has cost " + self.solution.getCost()); self.view.log(self.solution); self._updateViewButtons(self.view, false, true); } else { self.view.log("Sorry, could not find a feasible solution!"); self._updateViewButtons(self.view, false, false); } }; } _updateViewButtons(view, isCalculating, isResultReady) { view.setSolveButtonClickable(!isCalculating); view.setStopButtonClickable(isCalculating); view.setSaveButtonClickable(isResultReady); } //blocks the computation. stopComputation() { if (this.algorithm == "SIMPLEX") { GLPKSolver.stop(); } else { if (this.webWorker !== null) this.webWorker.terminate(); this.webWorker = null; } this.view.log("Stopped algorithm execution"); this.computing = false; this._updateViewButtons(this.view, false, false); } //loads instance from web and calls callback on the received text loadInstance(selectedSource, instance, onsuccess, onerror) { var url; switch (selectedSource) { case "astarte": url = instance; break; case "sqlite": url = "getInstance.aspx?instanceId=" + instance; break; } this._directInstanceDownload(url, onsuccess, onerror); } _directInstanceDownload(url, onsuccess, onerror) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { onsuccess(this.responseText); } else if (this.readyState === 4) { onerror("Error downloading data! Returned status " + this.status); } }; xhttp.open("GET", url, true); xhttp.send(); } //saves the result of a SQLite instance back into the DB, using AJAX remoteSave() { this.solution.cost = this.solution.getCost(); this.solution.algorithm = this.algorithm; var url = "putSolution.aspx?instanceId=" + this.instance; var xhttp = new XMLHttpRequest(); var self = this; xhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { self.view.log("Data saved remotely"); } else if (this.readyState === 4) { self.view.log("Error saving data remotely: error " + this.status); } }; xhttp.open("POST", url, true); xhttp.setRequestHeader('Content-type', 'application/json; charset=utf-8'); xhttp.send(JSON.stringify(this.solution)); } }
JavaScript
class DevotionalContentItem extends PureComponent { static propTypes = { /** The id of the devotional item */ id: PropTypes.string.isRequired, content: PropTypes.shape({ /** The devotional title */ title: PropTypes.string, }), /** Toggles placeholders */ loading: PropTypes.bool, navigation: PropTypes.shape({}), }; /** * Function to get the scripture references from the larger scripture object. * Props: full scripture array of objects * Returns: an array of scripture references. */ getScriptureReferences = (scripture) => { let arrayOfRefrences = null; if (scripture) { arrayOfRefrences = scripture.map( (ref) => // only add refs to the array if they exist ref.reference || '' ); } return arrayOfRefrences; }; /** * The route that TabView uses to render the ContentTab. * Note: navigationState gets passed down automatically from the TabView. */ contentRoute = ({ scriptures, loading }) => (navigationState) => ( <ContentTab id={this.props.id} references={this.getScriptureReferences(scriptures)} title={this.props.content.title} navigationState={navigationState} navigation={this.props.navigation} isLoading={this.props.loading || loading} /> ); /** * The route that TabView uses to render the ScriptureTab */ scriptureRoute = ({ scriptures, loading }) => () => ( <ScriptureTab id={this.props.id} scripture={scriptures} navigation={this.props.navigation} isLoading={this.props.loading || loading} /> ); renderLoading = () => <ContentTab title={''} isLoading />; renderTabs = ({ data, error, loading }) => { if (error) return <ErrorCard error={error} />; const scriptures = get(data, 'node.scriptures', []); // only include scriptures where the references are not null const validScriptures = scriptures ? scriptures.filter((scripture) => scripture.reference != null) : []; const hasScripture = loading || validScriptures.length; const tabRoutes = [{ title: 'Devotional', key: 'content' }]; const map = { content: this.contentRoute({ scriptures, loading }), }; if (hasScripture) { tabRoutes.push({ title: 'Scripture', key: 'scripture' }); map.scripture = this.scriptureRoute({ scriptures, loading }); } return tabRoutes.length < 2 ? ( map[tabRoutes[0].key]() ) : ( <TabView routes={tabRoutes} renderScene={SceneMap(map)} /> ); }; render() { return ( <BackgroundView> <FlexedSafeAreaView forceInset={{ top: 'always' }}> <Query query={GET_SCRIPTURE} variables={{ itemId: this.props.id }}> {({ data, loading, error }) => loading ? this.renderLoading() : this.renderTabs({ data, loading, error }) } </Query> </FlexedSafeAreaView> </BackgroundView> ); } }
JavaScript
class QnAMaker { /** * Creates a new QnAMaker instance. * @param endpoint The endpoint of the knowledge base to query. * @param options (Optional) additional settings used to configure the instance. */ constructor(endpoint, options) { this.endpoint = endpoint; // Initialize options this.options = Object.assign({ scoreThreshold: 0.3, top: 1, answerBeforeNext: false }, options); } onTurn(context, next) { // Filter out non-message activities if (context.activity.type !== botbuilder_1.ActivityTypes.Message) { return next(); } // Route request if (this.options.answerBeforeNext) { // Attempt to answer user and only call next() if not answered return this.answer(context).then((answered) => { return !answered ? next() : Promise.resolve(); }); } else { // Call next() and then attempt to answer only if nothing else responded return next().then(() => { return !context.responded ? this.answer(context).then(() => { }) : Promise.resolve(); }); } } /** * Calls [generateAnswer()](#generateanswer) and sends the answer as a message ot the user. * * @remarks * Returns a value of `true` if an answer was found and sent. If multiple answers are * returned the first one will be delivered. * @param context Context for the current turn of conversation with the user. */ answer(context) { const { top, scoreThreshold } = this.options; return this.generateAnswer(context.activity.text, top, scoreThreshold).then((answers) => { return this.emitTraceInfo(context, answers).then(() => { if (answers.length > 0) { return context.sendActivity({ text: answers[0].answer, type: 'message' }).then(() => true); } else { return Promise.resolve(false); } }); }); } /** * Calls the QnA Maker service to generate answer(s) for a question. * * @remarks * The returned answers will be sorted by score with the top scoring answer returned first. * @param question The question to answer. * @param top (Optional) number of answers to return. Defaults to a value of `1`. * @param scoreThreshold (Optional) minimum answer score needed to be considered a match to questions. Defaults to a value of `0.001`. */ generateAnswer(question, top, scoreThreshold) { const q = question ? question.trim() : ''; if (q.length > 0) { return this.callService(this.endpoint, question, typeof top === 'number' ? top : 1).then((answers) => { const minScore = typeof scoreThreshold === 'number' ? scoreThreshold : 0.001; return answers.filter((ans) => ans.score >= minScore).sort((a, b) => b.score - a.score); }); } return Promise.resolve([]); } /** * Called internally to query the QnA Maker service. * * @remarks * This is exposed to enable better unit testing of the service. */ callService(endpoint, question, top) { const url = `${endpoint.host}/knowledgebases/${endpoint.knowledgeBaseId}/generateanswer`; const headers = {}; if (endpoint.host.endsWith('v2.0') || endpoint.host.endsWith('v3.0')) { headers['Ocp-Apim-Subscription-Key'] = endpoint.endpointKey; } else { headers['Authorization'] = `EndpointKey ${endpoint.endpointKey}`; } return request({ url: url, method: 'POST', headers: headers, json: { question: question, top: top } }).then(result => { return result.answers.map((ans) => { ans.score = ans.score / 100; ans.answer = htmlentities.decode(ans.answer); if (ans.qnaId) { ans.id = ans.qnaId; delete ans['qnaId']; } return ans; }); }); } /** * Emits a trace event detailing a QnA Maker call and its results. * * @param context Context for the current turn of conversation with the user. * @param answers Answers returned by QnA Maker. */ emitTraceInfo(context, answers) { let traceInfo = { message: context.activity, queryResults: answers, knowledgeBaseId: this.endpoint.knowledgeBaseId, scoreThreshold: this.options.scoreThreshold, top: this.options.top, strictFilters: [{}], metadataBoost: [{}], }; return context.sendActivity({ type: 'trace', valueType: QNAMAKER_TRACE_TYPE, name: QNAMAKER_TRACE_NAME, label: QNAMAKER_TRACE_LABEL, value: traceInfo }); } }
JavaScript
class Role { /** * Constructor. * * @param {string} role */ __construct(role) { if (cache.hasOwnProperty(role)) { return cache[role]; } cache[role] = this; /** * The role identifier. * * @type {string} * * @private */ this._role = role; // Make object immutable. Object.freeze(this); } /** * Gets the role identifier. * * @returns {string} */ get role() { return this._role; } /** * Gets the string representation of this role (the identifier). * * @returns {string} */ toString() { return this._role; } }
JavaScript
class Panel extends React.Component { constructor(props) { super(props); this.state = { mappedProps: props.propMapper.mapProps() }; } componentDidMount() { this.props.propMapper.subscribe((mappedProps) => { if (!shallowequal(mappedProps, this.state.mappedProps)) { this.setState({ mappedProps }); } }); } componentWillUnmount() { this.props.propMapper.unsubscribe(); } render() { const Cmp = this.props.cmp; const props = this.state.mappedProps; return <Cmp {...props} />; } }
JavaScript
class StringValueNotFoundError extends Error { constructor(message, ...args) { super(message, ...args); } }
JavaScript
class ProjectReport { /** * Returns the enum for the report type. * @returns {ReportType} */ get type() { return ReportType.PROJECT; } /** * Initializes ProjectReport with default values. * * @param {Array<ModuleReport>} moduleReports - An array of ModuleReports for each module / file processed. * * @param {object} settings - An object hash of the settings used in generating this report via * ESComplexProject. */ constructor(moduleReports = void 0, settings = { serializeModules: true }) { /** * Stores the settings used to generate the project report. * @type {object} */ this.settings = typeof settings === 'object' ? settings : { serializeModules: true }; /** * Stores a compacted form of the adjacency matrix. Each row index corresponds to the same report index. * Each row entry corresponds to a report index. These relationships dictate the dependencies between all * report ModuleReports given the source paths. * * @type {Array<Array<number>>} */ this.adjacencyList = void 0; /** * Measures the average percentage of modules affected when one module / file in the project is changed. * Lower is better. * @type {number} */ this.changeCost = 0; /** * Measures the percentage of modules that are widely depended on which also depend on other modules. * Lower is better. * @type {number} */ this.coreSize = 0; /** * Stores any analysis errors. * @type {Array} */ this.errors = []; /** * Measures the percentage of all possible internal dependencies that are actually realized in the project. * Lower is better. * @type {number} */ this.firstOrderDensity = 0; /** * Stores the average module metric data. * @type {ModuleAverage} */ this.moduleAverage = new ModuleAverage(); /** * Stores all ModuleReport data for the project sorted by the module / files `srcPath`. * @type {Array<ModuleReport>} */ this.modules = Array.isArray(moduleReports) ? moduleReports.sort((lhs, rhs) => { return StringUtil.compare(lhs.srcPath, rhs.srcPath); }) : []; /** * Stores a compacted form of the visibility matrix. Each row index corresponds to the same report index. * Each row entry corresponds to a report index. These relationships dictate the reverse visibility between all * report ModuleReports which may indirectly impact the given module / file. * * @type {Array<Array<number>>} */ this.visibilityList = void 0; } /** * Clears all errors stored in the project report and by default any module reports. * * @param {boolean} clearChildren - (Optional) If false then class and module method errors are not cleared; * default (true). */ clearErrors(clearChildren = true) { this.errors = []; if (clearChildren) { this.modules.forEach((report) => { report.clearErrors(); }); } } /** * Finalizes the ProjectReport. If `settings.serializeModules` is false output just `filePath`, `srcPath` & * `srcPathAlias` entries of modules. * * @param {object} options - (Optional) Allows overriding of ModuleReport serialization. * @property {boolean} serializeModules - Allows overriding of ModuleReport serialization; default: true. * * @returns {ProjectReport} */ finalize(options = {}) { if (typeof options !== 'object') { throw new TypeError(`finalize error: 'options' is not an 'object'.`); } let serializeModules = this.getSetting('serializeModules', true); // Allow an override opportunity. if (typeof options.serializeModules === 'boolean') { serializeModules = options.serializeModules; } if (serializeModules) { this.modules.forEach((report) => { report.finalize(); }); } else { this.modules = this.modules.map((report) => { return { filePath: report.filePath, srcPath: report.srcPath, srcPathAlias: report.srcPathAlias }; }); } return MathUtil.toFixedTraverse(this); } /** * Gets all errors stored in the project report and by default any module reports. * * @param {object} options - Optional parameters. * @property {boolean} includeChildren - If false then module errors are not included; default (true). * @property {boolean} includeReports - If true then the result will be an array of object hashes containing * `source` (the source report object of the error) and `error` * (an AnalyzeError instance) keys and related `module`, `class` entries as; * default (false). * * @returns {Array<AnalyzeError|{error: AnalyzeError, source: *}>} */ getErrors(options = { includeChildren: true, includeReports: false }) { /* istanbul ignore if */ if (typeof options !== 'object') { throw new TypeError(`getErrors error: 'options' is not an 'object'.`); } // By default set includeChildren to true if not already defined. /* istanbul ignore if */ if (typeof options.includeChildren !== 'boolean') { options.includeChildren = true; } // If `includeReports` is true then return an object hash with the source and error otherwise return the error. let errors = options.includeReports ? this.errors.map((entry) => { return { error: entry, source: this }; }) : [].concat(...this.errors); // If `includeChildren` is true then traverse all children reports for errors. if (options.includeChildren) { this.modules.forEach((report) => { errors.push(...report.getErrors(options)); }); } // If `options.query` is defined then filter errors against the query object. if (typeof options.query === 'object') { errors = errors.filter((error) => ObjectUtil.safeEqual(options.query, error)); } return errors; } /** * Returns the supported transform formats. * * @returns {Object[]} */ static getFormats() { return TransformFormat.getFormats(ReportType.PROJECT); } /** * Returns the name / id associated with this report. * @returns {string} */ getName() { return ''; } /** * Returns the setting indexed by the given key. * * @param {string} key - A key used to store the setting parameter. * @param {*} defaultValue - A default value to return if no setting for the given key is currently stored. * * @returns {*} */ getSetting(key, defaultValue = undefined) { /* istanbul ignore if */ if (typeof key !== 'string' || key === '') { throw new TypeError(`getSetting error: 'key' is not a 'string' or is empty.`); } return typeof this.settings === 'object' && typeof this.settings[key] !== 'undefined' ? this.settings[key] : defaultValue; } /** * Deserializes a JSON object representing a ProjectReport. * * @param {object} object - A JSON object of a ProjectReport that was previously serialized. * * @param {object} options - Optional parameters. * @property {boolean} skipFinalize - If true then automatic finalization is skipped where applicable. * * @returns {ProjectReport} */ static parse(object, options = { skipFinalize: false }) { /* istanbul ignore if */ if (typeof object !== 'object') { throw new TypeError(`parse error: 'object' is not an 'object'.`); } /* istanbul ignore if */ if (typeof options !== 'object') { throw new TypeError(`parse error: 'options' is not an 'object'.`); } const projectReport = Object.assign(new ProjectReport(), object); if (projectReport.modules.length > 0) { projectReport.modules = projectReport.modules.map((report) => ModuleReport.parse(report)); } // Must automatically finalize if serializeModules is false. if (!options.skipFinalize && !projectReport.getSetting('serializeModules', true)) { projectReport.finalize(); } return projectReport; } /** * Sets the setting indexed by the given key and returns true if successful. * * @param {string} key - A key used to store the setting parameter. * @param {*} value - A value to set to `this.settings[key]`. * * @returns {boolean} */ setSetting(key, value) { /* istanbul ignore if */ if (typeof key !== 'string' || key === '') { throw new TypeError(`setSetting error: 'key' is not a 'string' or is empty.`); } if (this.settings === 'object') { this.settings[key] = value; return true; } return false; } /** * Formats this ProjectReport given the type. * * @param {string} name - The name of formatter to use. * * @param {object} options - (Optional) One or more optional parameters to pass to the formatter. * * @returns {string} */ toFormat(name, options = undefined) { return TransformFormat.format(this, name, options); } }
JavaScript
class DragElement { constructor(el, elementToDrag) { this.pos1 = 0; this.pos2 = 0; this.pos3 = 0; this.pos4 = 0; this.el = elementToDrag; this.dragging = false; this.activationElement = el; if (document.getElementById(`${el.d}header`)) { document.getElementById(`${el.id}header`).onmousedown = this.dragMouseDown.bind(this); } else { this.activationElement.onmousedown = this.dragMouseDown.bind(this); } } dragMouseDown(e) { const event = e || window.event; event.preventDefault(); this.pos3 = event.clientX; this.pos4 = event.clientY; this.dragging = true; document.onmouseup = this.closeDragElement.bind(this); document.onmousemove = this.elementDrag.bind(this); } elementDrag(e) { const event = e || window.event; event.preventDefault(); // calculate the new cursor position: this.pos1 = this.pos3 - event.clientX; this.pos2 = this.pos4 - event.clientY; this.pos3 = event.clientX; this.pos4 = event.clientY; // set the element's new position: this.el.style.top = `${this.el.offsetTop - this.pos2}px`; this.el.style.left = `${this.el.offsetLeft - this.pos1}px`; } closeDragElement() { // stop moving when mouse button is released: document.onmouseup = null; document.onmousemove = null; this.dragging = false; } }
JavaScript
class PluginManager { /** * Creates a new plugin manager. */ constructor() { /** * @type {Array<Plugin>} the list of plugins which this object manages. */ this.pluginList = []; } /** * @param {Plugin} plugin the plugin to register. */ registerPlugin(plugin) { this.pluginList.push(plugin); } }
JavaScript
class WWBackground extends WWBBase { constructor(options) { const { timeout, foreground, background } = options; super(timeout, background, foreground); if (options.init) options.init.apply(this); if (background && background.init) { background.init.apply(this); } this._id = 0; // Use evens. // Listen for messages from the UI. // eslint-disable-next-line no-restricted-globals self.addEventListener('message', this._onMessage.bind(this)); } /* Post a message _from_ the web worker. */ // eslint-disable-next-line class-methods-use-this _postMessage(dir, name, id, ...args) { // eslint-disable-next-line no-restricted-globals self.postMessage([dir, name, id, ...args]); } }
JavaScript
class GraphEdgeLabels extends Component { // when component updates componentDidUpdate() { this.update(); } // update update = () => { const data = this.props.graph; const layer = d3.select('#graph_edge_label_layer'); const edgeLabels = layer.selectAll('.graph_edge_label').data(data.edges); edgeLabels .enter() .append('text') .on('click', this.props.onNodeEdgeClick) .on('mouseenter', this.props.onNodeEdgeHover) .on('mouseleave', this.props.onNodeEdgeUnhover) .merge(edgeLabels) .attr('class', 'graph_edge_label') .attr('font-size', edgeFontSize) .attr('font-weight', 500) .attr('text-anchor', 'middle') .attr('user-select', 'none') .attr('fill', inkColor) .style('cursor', 'pointer') .text((d) => d.kind); edgeLabels.exit().remove(); }; // display component render() { return <></>; } }
JavaScript
class SqlResult extends HTMLElement { // print prints SQL query result as a table print(result) { this.applyPrinter(result, printer.printResult); } // printTables prints table list as a table printTables(tables) { this.applyPrinter(tables, printer.printTables); } // applyPrinter prints data structure // with specified printer function applyPrinter(data, printFunc) { if (!result) { this.clear(); return; } this.innerHTML = printFunc(data); } // clear hides the table clear() { this.innerHTML = ""; } }
JavaScript
class Api { /** * Construct a new Api instance with the given http and websockets URLs. * Second parameter can specify options object for wsUrl and any additional headers. * If the websockets URL is not provided it is derived by replacing the protocol on the http URL. * @param url * @param wsUrl * @param headers * @param fetch Fetch API implementation, e.g. node-fetch in node, defaults to window.fetch * @param onError A function with the signature (message: string, error: object) => void */ constructor (url, { wsUrl, headers = {}, fetch = window.fetch.bind(window), onError } = {}) { const protocol = url.match(/^(https?):\/\//)[1] if (!protocol) throw new Error(`Unexpected API URL [${url}]`) const isSecure = protocol.match(/s$/) this.url = url this.wsUrl = wsUrl || [`ws${isSecure ? "s" : ""}:`, url.split("//").slice(1)].join("//") this.fetch = fetch this.headers = headers this.onError = (err) => { const msg = typeof err === "string" ? err : (err && err.message) || "GraphQL error. Try: Check network connection / Turn off ad blockers" if (typeof onError === "function") { onError(msg, err) } err = err instanceof Error ? err : new Error(msg) throw err } } set log (fn) { if (typeof fn === "function") { this._log = fn if (this.socket) this.socket.log = fn } } /** * Execute a query or mutation. * @param query * @param variables * @returns {Promise<void>} */ async run (query, variables) { const headers = { ...standardOptions.headers, ...this.headers } let response try { response = await this.fetch(this.url, { ...standardOptions, headers, body: JSON.stringify({ query, variables }) }) } catch (err) { this.onError(err) } const { errors, data } = await response.json() if (Array.isArray(errors) && errors.length) { this.onError(errors[0]) } return data } subscribe (query, variables = {}, channelName = randChannelName()) { const message = { id: channelName, type: "start", payload: { query, variables } } const startSub = () => this.socket.webSocket.send(JSON.stringify(message)) if (this.socket) { if (this.socket.subscriptions[channelName]) { throw new Error(`Subscription already exists for channel [${channelName}]`) } if (this.socket.connected) { startSub() } else { this.socket.connectedHandlers.push(startSub) } } else { this.socket = new Socket(this.wsUrl, this.headers, startSub) if (this.log) this.socket.log = this.log } const socketSubscription = this.socket.subscriptions[channelName] = {} const result = { onData (handler) { socketSubscription.onData = handler return result }, close () { delete this.socket.subscriptions[channelName] } } return result } }
JavaScript
@autobind class VerticalAccordion extends React.Component { constructor(props) { super(props); this.state = { show: false, shownStyles: this.chosenStyles(props, false), }; } componentWillReceiveProps(nextProps) { if ((this.props.groupKey !== undefined) && this.props.onToggleAccordion) { const show = nextProps.groupKey === nextProps.activeGroupKey; this.setState({ shownStyles: this.chosenStyles(nextProps, show), show }); } else { this.setState({ shownStyles: this.chosenStyles(nextProps, this.state.show) }); } } // Style when body is hidden getNullStyles() { return [ { data: <div />, key: "body", style: { height: spring(0, { stiffness: 90, damping: 16 }), opacity: spring(0, { stiffness: 30, damping: 15 }), } } ]; } // "default" style when initializing the component getDefaultStyles() { return [ { key: "body", style: { height: 0, opacity: 0 } } ]; } // style when body is shown. You need to specify props because this might be // changing due to caller changing eg content of body. getShownStyles(props) { return [ { data: React.isValidElement(props.children) ? props.children : <Aux>{props.children}</Aux>, key: "body", style: { height: spring(props.height || 100, { stiffness: 110, damping: 14 }), opacity: spring(1, { stiffness: 65, damping: 35 }), } } ]; } // this returns the chosen style based on the passed props chosenStyles(props, show) { if (show && props.children) { return this.getShownStyles(props); } else { return this.getNullStyles(); } } onToggleAccordion() { if ((this.props.groupKey !== undefined) && this.props.onToggleAccordion) { this.props.onToggleAccordion(this.props.groupKey, this.state.show); } else { this.setState({ show: !this.state.show, shownStyles: this.chosenStyles(this.props, !this.state.show), }); } } render() { const classNames = [ "vertical-accordion", this.state.show ? "active" : "", this.props.className || "", ].join(" "); return ( <div className={classNames}> <div className="vertical-accordion-header" onClick={this.onToggleAccordion} > {this.props.header} <div className="vertical-accordion-arrow" /> </div> <div className="vertical-accordion-body"> <TransitionMotionWrapper styles={this.state.shownStyles} defaultStyles={this.getDefaultStyles()} /> </div> </div> ); } }
JavaScript
class About extends React.Component { componentDidMount () { window.scrollTo(0, 0) } render () { return ( <div> <div className='row centered'> <div className='col-md-8 col-md-offset-2'> <h2>About</h2> <p>Stock-Vis keeps you up to date on the going-ons of the finanical world, providing fast and easy access to price trends and comparisons - at the touch of your fingertips.</p> <p>We can show you the world - of stocks - both in sets of individual data (conveniently as a candlestick graph for quick analysis) or as comparisons to other leading stocks</p> <p>We have daily stock data, sourced from <a href='https://www.quandl.com'>Quandl.</a></p> <img src='/sample.jpg' /> <p>The application uses node.js for its back end, and React and Redux for its front end.</p> </div> </div> </div> ) } }
JavaScript
class SessionRequest { /** * Initialization of session request * * @param {SessionMessage} requestMessage Session message with join request's data * @param {function} decidedCallback Callback to handle result. * Message with generated response is passed in the argument. */ constructor(requestMessage, decidedCallback) { this._requestMessage = requestMessage; this._responseMessage = null; this._decidedCallback = decidedCallback; } /** * It agrees on joining to the session by the author of request * * @returns {SessionRequest} */ confirm() { this._prepateResponseMessage('session.confirm'); this._decidedCallback(this.responseMessage); return this; } /** * It rejectes the session join request * * @returns {SessionRequest} */ reject() { this._prepateResponseMessage('session.reject'); this._decidedCallback(this.responseMessage); return this; } /** * Factory of response messages. * It automatically generate response message with the given type * which is compatible with data given in request. * * @param {string} type Type of response message * @private */ _prepateResponseMessage(type) { this._responseMessage = new SessionMessage( type, this._requestMessage.sessionId, this._requestMessage.user ); } /** * Message with request data * * @readonly * @property * @type {SessionMessage} */ get requestMessage() { return this._requestMessage; } /** * Message with response data. It's available only after the user take a decision about the request. * * @readonly * @property * @type {SessionMessage|*} */ get responseMessage() { return this._responseMessage; } }
JavaScript
class TypeGroupBy extends BaseGroupBy { /** * Constructor. */ constructor() { super(); } /** * @inheritDoc */ getGroupIds(node) { /** * @type {Array<!string>} */ var ids = []; /** * @type {?string} */ var val = null; try { if (node instanceof DescriptorNode) { var d = /** @type {DescriptorNode} */ (node).getDescriptor(); val = d.getType(); } else { // Unclear what these types are expected to be, but rather than risk breaking behavior we'll cast the type as // a generic object. var obj = /** @type {!Object} */ (node); if ('getType' in obj) { val = obj['getType'](); } else if ('type' in obj) { val = obj['type']; } } } catch (e) { } if (!val) { val = 'No Type'; } googArray.insert(ids, val); return ids; } /** * @inheritDoc */ createGroup(node, id) { var group = new SlickTreeNode(); group.setId(id); group.setLabel(id); group.setCheckboxVisible(false); return group; } }
JavaScript
class Exporter { constructor() {} /** * Exports the target to an export data object. This is then usually passed to a * downloader to process and download to the client's machine. * * @param {String} exportType the export type for the target * @param {*} target the target to export * @returns {ExportData} the processed export data that represents the target's current state */ exportTarget(exportType, target) { return Promise.resolve({ name: 'untitled.json', type: 'text', data: JSON.stringify(target) }); } /** * The representive icon class for this exporter. * * @returns {React.Component} the icon component class */ getIconClass() { return null; } /** * The label for the exporter. */ getLabel() { return 'Export'; } /** * The hint for the exporter. */ getTitle() { return 'Export'; } }
JavaScript
class MovementTrack extends Component { constructor(props) { super(props); this.state = { movement: { forward: false, backward: false, right: false, left: false, }, active: false } } handleKeyPress(event) { if (event.key === "Enter") { this.setState({ active: !this.state.active }, function updateFirebase() { const rootRef = firebase.database().ref(); const controlRef = rootRef.child('control'); // console.log(this.state.movement); controlRef.set({ active: this.state.active }); }); } } handleKeyDown(event) { if (!this.state.active) { // console.log(event.key) // Allow no key presses to stop the rover return; } // console.log("Active") let obj; switch(event.key) { case "ArrowUp": obj = { forward: true, backward: false, right: false, left: false, }; break; case "ArrowDown": obj = { forward: false, backward: true, right: false, left: false, }; break; case "ArrowRight": obj = { forward: false, backward: false, right: true, left: false, }; break; case "ArrowLeft": obj = { forward: false, backward: false, right: false, left: true, }; break; default: obj = { forward: false, backward: false, right: false, left: false, }; break; } this.setState({ movement: obj }, function updateFirebase() { const rootRef = firebase.database().ref(); const movementRef = rootRef.child('movement'); // console.log(this.state.movement); movementRef.set(obj); }); } render() { return ( <div id="meter-movement-track" className="" onKeyPress={(event) => this.handleKeyPress(event)} onKeyDown={(event) => this.handleKeyDown(event)} tabIndex="0" > {this.props.children} </div> ); } }
JavaScript
class DataTrack extends Component { constructor(props) { super(props); this.state = { data: { motorSpeed: 0, leftIR: 0, midIR: 0, rightIR: 0, } } } componentDidMount() { // Track changes in firebase for 'data' child const rootRef = firebase.database().ref(); const dataRef = rootRef.child('data') dataRef.on('value', snap => { this.setState({ data: snap.val() }); }); } generateItem(item) { return <ValueLabelFormat key={item.label} value={item.value} label={item.label} /> } render() { const sensors = [ { value: this.state.data.leftIR, label: "Left IR" }, { value: this.state.data.midIR, label: "Mid IR" }, { value: this.state.data.rightIR, label: "Right IR" } ]; return( <MovementTrack> <DashHeader /> <div className="container text-dark"> <div className="mx-auto mb-auto text-dark"> <div className="row"> <div id="motor-speed-value" className="col container text-center">{this.state.data.motorSpeed}</div> </div> <div className="row mb-5"> <div id="motor-speed-label" className="col container text-center">RPM</div> </div> </div> <div className="mx-auto mb-auto text-dark row"> {sensors.map(this.generateItem)} </div> </div> <DashFooter /> </MovementTrack> ); } }
JavaScript
class Meter extends Component { componentDidMount() { document.title = 'Meter | NOMAD' } render() { return ( <FullPage id="meter"> <DataTrack /> </FullPage> ); } }
JavaScript
class FormsLibService { constructor() { } /** * @return {?} */ getDefaultForm() { return null; // DEFAULT_FORM().template; } /** * @param {?} id * @param {?=} disabled * @return {?} */ getFormById(id, disabled = false) { return null; // FORMS_VALUES(disabled)[id]; } /** * @private * @param {?} clone * @return {?} */ generateCleanConfiguration(clone) { return JSON.parse(JSON.stringify(clone)); } /** * @param {?} model * @return {?} */ getModelFields(model) { // for each model prop test type and generate appropriate formfield /** @type {?} */ const fields = Object.keys(model); /** @type {?} */ const fieldConfig = []; for (const field of fields) { /** @type {?} */ const fieldFn = field.toUpperCase(); /** @type {?} */ let fieldOps = {}; if (typeof ELEMENTS[fieldFn] === 'function') { // console.log('FormsLib ELEMENTS contains: ', fieldFn); fieldOps = ELEMENTS[fieldFn](); fieldConfig.push(fieldOps); } else { console.log('FormsLib ELEMENTS does not contain field: ', field); } } // console.log(fieldConfig); return fieldConfig; } }
JavaScript
class RepeatSectionComponent extends FieldArrayType { /** * @param {?} builder */ constructor(builder) { super(builder); } }
JavaScript
class InputChipsComponent extends FieldType { constructor() { super(...arguments); this.onDestroy$ = new Subject(); this.itemControl = new FormControl(); this.selectable = true; this.removable = true; this.addOnBlur = true; this.separatorKeysCodes = [ENTER, COMMA]; } /** * @return {?} */ ngOnInit() { super.ngOnInit(); this.filter = this.itemControl.valueChanges.pipe(takeUntil(this.onDestroy$), startWith(null), map((/** * @param {?} item * @return {?} */ (item) => item ? this._filter(item) : this._filter('')))); } /** * @return {?} */ ngAfterViewInit() { super.ngAfterViewInit(); // temporary fix for https://github.com/angular/material2/issues/6728 ((/** @type {?} */ (this.matAutocomplete)))._formField = this.formField; } /** * @return {?} */ ngOnDestroy() { this.onDestroy$.next(); this.onDestroy$.complete(); } /** * @return {?} */ get empty() { return this.formControl.value.length === 0; } /** * @param {?} event * @return {?} */ add(event) { // Add item only when MatAutocomplete is not open // To make sure this does not conflict with OptionSelected Event if (!this.matAutocomplete.isOpen) { /** @type {?} */ const input = event.input; /** @type {?} */ const value = event.value; // Add item if ((value || '').trim()) { this.formControl.setValue([ ...this.formControl.value, value.trim(), ]); } // Reset the input value if (input) { input.value = ''; } this.itemControl.setValue(null); } } /** * @param {?} event * @return {?} */ selected(event) { this.formControl.setValue([ ...this.formControl.value, event.option.viewValue, ]); this.itemControl.setValue(null); } /** * @param {?} i * @return {?} */ remove(i) { /** @type {?} */ const value = this.formControl.value; this.formControl.setValue([ ...value.slice(0, i), ...value.slice(i + 1, value.length) ]); this.formControl.markAsTouched(); } /** * @private * @param {?} value * @return {?} */ _filter(value) { if (!this.to.filter) { return []; } if (!value) { return this.to.filter.slice(); } /** @type {?} */ const filterValue = value.toLowerCase(); return this.to.filter.filter((/** * @param {?} item * @return {?} */ item => item.toLowerCase().indexOf(filterValue) === 0)); } /** * @return {?} */ onBlur() { this.formControl.markAsTouched(); this.field.focus = false; } }
JavaScript
class InputPercentageComponent extends FieldType$1 { /** * @param {?} rawValue * @return {?} */ limitToHundred(rawValue) { /** @type {?} */ const value = parseInt(rawValue, 10); if (value < 100) { if (value < 10) { return [/\d/, ' %']; } else { return [/\d/, /\d/, ' %']; } } else { return ['100 %']; } } }
JavaScript
class AlertList extends Component { // eslint-disable-next-line react/state-in-constructor state = { selectedAlerts: [], selectedPages: [], }; /** * @function * @name handleOnSelectAlert * @description Handle select a single alert action * * @param {object} alert selected alert object * * @version 0.1.0 * @since 0.1.0 */ handleOnSelectAlert = alert => { const { selectedAlerts } = this.state; this.setState({ selectedAlerts: concat([], selectedAlerts, alert) }); }; /** * @function * @name handleFilterByStatus * @description Handle filter alerts by status action * * @version 0.1.0 * @since 0.1.0 */ handleFilterByStatus = () => { // if (status === 'All') { // filterStakeholders({}); // } else if (status === 'Active') { // filterStakeholders({}); // } else if (status === 'Archived') { // filterStakeholders({}); // } }; /** * @function * @name handleSelectAll * @description Handle select all alerts actions from current page * * @version 0.1.0 * @since 0.1.0 */ handleSelectAll = () => { const { selectedAlerts, selectedPages } = this.state; const { alerts, page } = this.props; const selectedList = uniqBy([...selectedAlerts, ...alerts], '_id'); const pages = uniq([...selectedPages, page]); this.setState({ selectedAlerts: selectedList, selectedPages: pages, }); }; /** * @function * @name handleDeselectAll * @description Handle deselect all alerts in a current page * * @returns {undefined} * * @version 0.1.0 * @since 0.1.0 */ handleDeselectAll = () => { const { alerts, page } = this.props; const { selectedAlerts, selectedPages } = this.state; const selectedList = uniqBy([...selectedAlerts], '_id'); const pages = uniq([...selectedPages]); remove(pages, item => item === page); alerts.forEach(alert => { remove( selectedList, item => item._id === alert._id // eslint-disable-line ); }); this.setState({ selectedAlerts: selectedList, selectedPages: pages, }); }; /** * @function * @name handleOnDeselectAlert * @description Handle deselect a single alert action * * @param {object} alert alert to be removed from selected alerts * @returns {undefined} * * @version 0.1.0 * @since 0.1.0 */ handleOnDeselectAlert = alert => { const { selectedAlerts } = this.state; const selectedList = [...selectedAlerts]; remove( selectedList, item => item._id === alert._id // eslint-disable-line ); this.setState({ selectedAlerts: selectedList }); }; render() { const { alerts, loading, page, total, onEdit, onFilter, onShare, } = this.props; const { selectedAlerts, selectedPages } = this.state; // const sortedAlerts = sortByUpdatedAt(sortByExpiredAt(alerts)); const selectedAlertsCount = intersectionBy(selectedAlerts, alerts, '_id') .length; return ( <> {/* toolbar */} <Toolbar itemName="Alert" page={page} total={total} selectedItemsCount={selectedAlertsCount} exportUrl={getAlertsExportUrl({ filter: { _id: map(selectedAlerts, '_id') }, })} onFilter={onFilter} onPaginate={nextPage => { paginateAlerts(nextPage); }} onRefresh={() => refreshAlerts( () => { notifySuccess('Alerts refreshed successfully'); }, () => { notifyError( 'An Error occurred while refreshing Alerts please contact system administrator' ); } ) } /> {/* end toolbar */} {/* alert list header */} <ListHeader headerLayout={headerLayout} onSelectAll={this.handleSelectAll} onDeselectAll={this.handleDeselectAll} isBulkSelected={selectedPages.includes(page)} /> {/* end alert list header */} {/* alerts list */} <List loading={loading} dataSource={alerts} renderItem={alert => { return ( <AlertListItem key={alert._id} // eslint-disable-line abbreviation={alert.source.toUpperCase().charAt(0)} urgency={alert.urgency} area={alert.area} certainty={alert.certainty} event={alert.event} headline={alert.headline} description={alert.description} source={alert.source} color={alert.color} reportedAt={alert.reportedAt} expiredAt={alert.expiredAt} expectedAt={alert.expectedAt} severity={alert.severity} onShare={() => { onShare(alert); }} isSelected={ // eslint-disable-next-line map(selectedAlerts, item => item._id).includes(alert._id) } onSelectItem={() => { this.handleOnSelectAlert(alert); }} onDeselectItem={() => { this.handleOnDeselectAlert(alert); }} onEdit={() => onEdit(alert)} onArchive={() => deleteAlert( alert._id, // eslint-disable-line () => { notifySuccess('Alert was archived successfully'); }, () => { notifyError( 'An Error occurred while archiving Alert please alert system administrator' ); } ) } /> ); }} /> {/* end alerts list */} </> ); } }
JavaScript
class ProductImagesModel extends BaseModel { fetch() { return new Promise((resolve, reject) => { let basket = this.__config.basket; let productIds = basket.product_items.map(function(productItem){ return productItem.product_id; }); const prodUrl = `${process.env.OCAPI_HOST}${process.env.OCAPI_PATH}/products/(${productIds.toString()})?client_id=${process.env.OCAPI_CLIENT_ID}&expand=images,variations,prices&all_images=true`; Promise.all([ rp.get({ uri: prodUrl, json: true }) ]) .then(([products]) => { var externalProduct = products.data.find((item) => { return item.id === 'external-product'; }); if (externalProduct) { let extProdUrl = 'http://headless-external-service.herokuapp.com/externalProduct'; rp.get({ uri: extProdUrl, json: true }) .then((extProduct) => { Object.keys(extProduct).forEach(function(key){ externalProduct[key] = extProduct[key]; }); basket.product_items.forEach(function(productItem) { products.data.forEach(function(returnedProd){ if (productItem.product_id === returnedProd.id) { productItem.variation_values = returnedProd.variation_values; productItem.image_groups = returnedProd.image_groups; } }) }) resolve({ basket }); }) } else { basket.product_items.forEach(function(productItem) { products.data.forEach(function(returnedProd){ if (productItem.product_id === returnedProd.id) { productItem.variation_values = returnedProd.variation_values; productItem.image_groups = returnedProd.image_groups; } }) }) resolve({ basket }); } }) .catch((err) => { reject(err); }); }); } }
JavaScript
class ServiceProvider extends OSLCResource { constructor(uri, kb) { // Parse the RDF source into an internal representation for future use super(uri, kb) var _self = this } /* * Get the queryBase URL for an OSLC QueryCapability with the given oslc:resourceType * * @param {Symbol} a symbol for the desired oslc:resourceType * @returns {string} the queryBase URL used to query resources of that type */ queryBase(resourceType) { let resourceTypeSym = (typeof resourceType === 'string')? this.kb.sym(resourceType): resourceType; let services = this.kb.each(this.id, OSLC('service')); for (let service of services) { var queryCapabilities = this.kb.each(service, OSLC('queryCapability')); for (let queryCapability of queryCapabilities) { if (this.kb.statementsMatching(queryCapability, OSLC('resourceType'), resourceTypeSym).length) { return this.kb.the(queryCapability, OSLC('queryBase')).value } } } return null } /* * Get the creation URL for an OSLC CreationFactory with the given oslc:resourceType * * @param {Symbol | string} a symbol for, or the name of the desired oslc:resourceType * @returns {string} the creation URL used to create resources of that type */ creationFactory(resourceType) { var services = this.kb.each(this.id, OSLC('service')) for (var service in services) { var creationFactories = this.kb.each(services[service], OSLC('creationFactory')); // TODO: for now, find an RTC creation factory for only oslc:resourceType=oslc:ChangeRequest for (var creationFactory in creationFactories) { if (typeof(resourceType) === 'string') { var types = this.kb.each(creationFactories[creationFactory], OSLC('resourceType')) for (var aType in types) { if (types[aType].uri.endsWith(resourceType)) return this.kb.the(creationFactories[creationFactory], OSLC('creation')).uri } } else if (this.kb.statementsMatching(creationFactories[creationFactory], OSLC('resourceType'), resourceType).length === 1) { return this.kb.the(creationFactories[creationFactory], OSLC('creation')).uri } } } return null } }
JavaScript
class ViewHelpers { constructor({ options } = {}) { let opts = options || (window && window.REDUX_STATE && window.REDUX_STATE.paths) opts = opts || { rootPath: '/admin', } // when ViewHelpers are used on the frontend, paths are taken from global Redux State this.options = opts } /** * To each related path adds rootPath passed by the user, as well as a query string * @param {String[]} paths list of parts of the url * @return {String} path */ urlBuilder(paths) { const { rootPath } = this.options return `${rootPath}/${paths.join('/')}` } /** * Returns login URL * @return {String} */ loginUrl() { return this.options.loginPath } /** * Returns logout URL * @return {String} */ logoutUrl() { return this.options.logoutPath } listUrl({ resourceId }) { console.warn(` Deprecation: this function will be removed in the next versions. Please use resourceActionUrl({ resourceId, actionName: 'list'}) instead`) return this.resourceActionUrl({ resourceId, actionName: 'list' }) } /** * Returns URL for the dashboard * @return {String} */ dashboardUrl() { return this.options.rootPath } resourceActionUrl({ resourceId, actionName }) { return this.urlBuilder(['resources', resourceId, 'actions', actionName]) } recordActionUrl({ resourceId, recordId, actionName }) { return this.urlBuilder(['resources', resourceId, 'records', recordId, actionName]) } /** * Returns absolute path to a given asset * @param {String} asset * @return {String} */ assetPath(asset) { return this.urlBuilder(['frontend', 'assets', asset]) } }
JavaScript
class BooksApp extends Component { constructor(props) { super(props); // Set the initial state this.state = { booksList: [], }; // Bindings to 'this' this.fetchAllBooks = this.fetchAllBooks.bind(this); this.renderBookSearch = this.renderBookSearch.bind(this); this.renderMyReads = this.renderMyReads.bind(this); } componentDidMount() { // Fetch all of the books on the initial mounting this.fetchAllBooks(); } /** * Make a fetch request to get all of the books for the given user (me in this case) * @return {Promise} */ fetchAllBooks() { getAllBooks() .then(res => { // This is the final booksList coming back from the API fetch call. const booksList = res.books ? res.books : []; // After successfully fetching the 'booksList', update the component's state with booksList this.setState({ booksList, }); }) .catch(() => { throw new UndefinedBooksListException(); }); return null; } /** * Render the book search route * @return {JSX} */ renderBookSearch() { const { booksList, } = this.state; const { closeSearchURL, searchPlaceholder, } = this.props; return ( <BookSearch closeSearchURL={closeSearchURL} originalBooksList={booksList} placeholder={searchPlaceholder} fetchAllBooks={this.fetchAllBooks} /> ); } /** * Render the my reads route * @return {JSX} */ renderMyReads() { const { booksList, } = this.state; return ( <MyReads booksList={booksList} onShelfChange={this.fetchAllBooks} /> ); } render() { return ( <BrowserRouter basename="/"> <div className="app"> <Route exact path="/" render={this.renderMyReads} /> <Route path="/search" render={this.renderBookSearch} /> <Route path="/book/:bookId" component={BookDetails} /> </div> </BrowserRouter> ); } }
JavaScript
class StorageMock { setItem(key, value) { this[key] = value; } getItem(key) { return this[key]; } }
JavaScript
class Deployment extends UtilityClass { /** * {array<string>} Array of absolute filesystem paths to the asset directory * trees, in priority order (earliest directory "overrides" later ones when * two or more contain the same-named file). All files under these directories * are expected to be servable to clients; that is, there should be no * server-private files under them. */ static get ASSET_DIRS() { return use.Deployment.ASSET_DIRS; } /** * Performs any setup needed prior to running either a server per se or one * of the server actions (such as running a unit test). This gets called * _after_ the very lowest layer of the system is set up (e.g. the Babel * runtime) and _after_ the logging system is ready, and _before_ everything * else. * * @param {@bayou/top-server/Action} action The action that is about to be * run. */ static async aboutToRun(action) { await use.Deployment.aboutToRun(action); } /** * Determines the location of the "var" (variable / mutable data) directory, * returning an absolute path to it. (This is where, for example, log files * are stored.) The directory need not exist; the system will take care of * creating it as needed. * * The `baseDir` argument is provided for use by configurations (such as * commonly used during development) which want to keep code and data * together. It's expected that in many production environments, though, the * `baseDir` argument will be ignored, instead returning an unrelated * filesystem path. (For example, many deployment environments want to make * their code directories read-only.) * * @param {string} baseDir The base product directory. This is the root * directory under which the code for the product lives. * @returns {string} Absolute filesystem path to the "var" directory to use. */ static findVarDirectory(baseDir) { return use.Deployment.findVarDirectory(baseDir); } /** * Checks to see if this server is running in a "development" environment, * returning an indication of the fact. A development environment is notable * in that it notices when source files change (and acts accordingly), has * `/debug` endpoints enabled, and may be less secure in other ways as a * tradeoff for higher internal visibility, that is, higher debugability. * * @returns {boolean} `true` if this server is running in a development * environment, or `false` if not. */ static isRunningInDevelopment() { return use.Deployment.isRunningInDevelopment(); } /** * Gets an object whose instance methods are to be provided via the API as * part of the root authority. The methods are provided in addition to what is * provided by default by {@link app-setup.RootAccess}. If no additional * methods are required by this configuration, this method should return * `null`. * * @returns {object|null} Object with additional methods to be provided as * part of root access, or `null` if there are none. */ static rootAccess() { return use.Deployment.rootAccess(); } /** * Gets a short server-identifying string, which is expected to be unique * per machine (or machine-like-thing). This is specifically used to produce * a hash per machine, which can be used for bucketing and the like. * * @returns {string} Server ID string. */ static serverId() { return use.Deployment.serverId(); } /** * Gets arbitrary server-identifying information, which gets returned to * clients via {@link MetaHandler#serverInfo}. * * @returns {object} Ad-hoc information about the server. */ static serverInfo() { return use.Deployment.serverInfo(); } /** * Checks to see if this server should serve code assets (most notably client * JavaScript bundles). It is typical (but not necessary) for this to be * `true` in development environments and `false` in production environments. * * @returns {boolean} `true` if this server should serve code assets, or * `false` if not. */ static shouldServeClientCode() { return use.Deployment.shouldServeClientCode(); } }
JavaScript
class CustomQueryBuilder extends QueryBuilder { constructor(modelClass) { super(modelClass) if (modelClass.defaultSchema) { this.withSchema(modelClass.defaultSchema) } } softDelete(id) { if (id) { return this.patch({ status: 3 }).findById(id) } } async isValid(data) { let validity = await this.findOne({ ...data, status: 1 }) return !!validity } upsert(model) { if (model.id) { return this.update(model).where('id', model.id) } else { return this.insert(model) } } }
JavaScript
class Segment { /** * Creates a new `Segment` instance. * @param {Rac} rac - Instance to use for drawing and creating other objects * @param {Rac.Ray} ray - A `Ray` the segment will be based of * @param {number} length - The length of the segment */ constructor(rac, ray, length) { // TODO: different approach to error throwing? // assert || throw new Error(err.missingParameters) // or // checker(msg => { throw Rac.Exception.failedAssert(msg)); // .exists(rac) // .isType(Rac.Ray, ray) // .isNumber(length) utils.assertExists(rac, ray, length); utils.assertType(Rac.Ray, ray); utils.assertNumber(length); /** * Instance of `Rac` used for drawing and passed along to any created * object. * * @type {Rac} */ this.rac = rac; /** * The `Ray` the segment is based of. * @type {Rac.Ray} */ this.ray = ray; /** * The length of the segment. * @type {number} */ this.length = length; } /** * Returns a string representation intended for human consumption. * * @param {number} [digits] - The number of digits to print after the * decimal point, when ommited all digits are printed * @returns {string} */ toString(digits = null) { const xStr = utils.cutDigits(this.ray.start.x, digits); const yStr = utils.cutDigits(this.ray.start.y, digits); const turnStr = utils.cutDigits(this.ray.angle.turn, digits); const lengthStr = utils.cutDigits(this.length, digits); return `Segment((${xStr},${yStr}) a:${turnStr} l:${lengthStr})`; } /** * Returns `true` when `ray` and `length` in both segments are equal. * * When `otherSegment` is any class other that `Rac.Segment`, returns `false`. * * Segments' `length` are compared using `{@link Rac#equals}`. * * @param {Rac.Segment} otherSegment - A `Segment` to compare * @returns {boolean} * @see Rac.Ray#equals * @see Rac#equals */ equals(otherSegment) { return otherSegment instanceof Segment && this.ray.equals(otherSegment.ray) && this.rac.equals(this.length, otherSegment.length); } /** * Returns the `[angle]{@link Rac.Ray#angle}` of the segment's `ray`. * @returns {Rac.Angle} */ angle() { return this.ray.angle; } /** * Returns the `[start]{@link Rac.Ray#start}` of the segment's `ray`. * @returns {Rac.Point} */ startPoint() { return this.ray.start; } /** * Returns a new `Point` where the segment ends. * @returns {Rac.Point} */ endPoint() { return this.ray.pointAtDistance(this.length); } /** * Returns a new `Segment` with angle set to `newAngle`. * * All other properties are copied from `this`. * * @param {Rac.Angle|number} newAngle - The angle for the new `Segment` * @returns {Rac.Segment} */ withAngle(newAngle) { newAngle = Rac.Angle.from(this.rac, newAngle); const newRay = new Rac.Ray(this.rac, this.ray.start, newAngle); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with `ray` set to `newRay`. * * All other properties are copied from `this`. * * @param {Rac.Ray} newRay - The ray for the new `Segment` * @returns {Rac.Segment} */ withRay(newRay) { return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with start point set to `newStart`. * * All other properties are copied from `this`. * * @param {Rac.Point} newStartPoint - The start point for the new * `Segment` * @returns {Rac.Segment} */ withStartPoint(newStartPoint) { const newRay = this.ray.withStart(newStartPoint); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with `length` set to `newLength`. * * All other properties are copied from `this`. * * @param {number} newLength - The length for the new `Segment` * @returns {Rac.Segment} */ withLength(newLength) { return new Segment(this.rac, this.ray, newLength); } /** * Returns a new `Segment` with `length` added to `this.length`. * * All other properties are copied from `this`. * * @param {number} length - The length to add * @returns {Rac.Segment} */ withLengthAdd(length) { return new Segment(this.rac, this.ray, this.length + length); } /** * Returns a new `Segment` with `length` set to `this.length * ratio`. * * All other properties are copied from `this`. * * @param {number} ratio - The factor to multiply `length` by * @returns {Rac.Segment} */ withLengthRatio(ratio) { return new Segment(this.rac, this.ray, this.length * ratio); } /** * Returns a new `Segment` with `angle` added to `this.angle()`. * * All other properties are copied from `this`. * * @param {Rac.Angle|number} angle - The angle to add * @returns {Rac.Segment} */ withAngleAdd(angle) { const newRay = this.ray.withAngleAdd(angle); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with `angle` set to * `this.ray.{@link Rac.Angle#shift angle.shift}(angle, clockwise)`. * * All other properties are copied from `this`. * * @param {Rac.Angle|number} angle - The angle to be shifted by * @param {boolean} [clockwise=true] - The orientation of the shift * @returns {Rac.Segment} */ withAngleShift(angle, clockwise = true) { const newRay = this.ray.withAngleShift(angle, clockwise); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with the start point moved in the inverse * direction of the segment's ray by the given `distance`. The resulting * `Segment` will have the same `endPoint()` and `angle()` as `this`. * * Using a positive `distance` results in a longer segment, using a * negative `distance` results in a shorter one. * * @param {number} distance - The distance to move the start point by * @returns {Rac.Segment} */ withStartExtension(distance) { const newRay = this.ray.translateToDistance(-distance); return new Segment(this.rac, newRay, this.length + distance); } /** * Returns a new `Segment` with `distance` added to `this.length`, which * results in `endPoint()` for the resulting `Segment` moving in the * direction of the segment's ray by the given `distance`. * * All other properties are copied from `this`. * * Using a positive `distance` results in a longer segment, using a * negative `distance` results in a shorter one. * * This method performs the same operation as * `[withLengthAdd]{@link Rac.Segment#withLengthAdd}`. * * @param {number} distance - The distance to add to `length` * @returns {Rac.Segment} */ withEndExtension(distance) { return this.withLengthAdd(distance); } /** * Returns a new `Segment` pointing towards the * [perpendicular angle]{@link Rac.Angle#perpendicular} of * `this.angle()` in the `clockwise` orientation. * * The resulting `Segment` will have the same `startPoint()` and `length` * as `this`. * * @param {boolean} [clockwise=true] - The orientation of the perpendicular * @returns {Rac.Segment} * @see Rac.Angle#perpendicular */ perpendicular(clockwise = true) { const newRay = this.ray.perpendicular(clockwise); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with its start point set at * `[this.endPoint()]{@link Rac.Segment#endPoint}`, * angle set to `this.angle().[inverse()]{@link Rac.Angle#inverse}`, and * same length as `this`. * * @returns {Rac.Segment} * @see Rac.Angle#inverse */ reverse() { const end = this.endPoint(); const inverseRay = new Rac.Ray(this.rac, end, this.ray.angle.inverse()); return new Segment(this.rac, inverseRay, this.length); } /** * Returns a new `Segment` with the start point moved towards `angle` by * the given `distance`. All other properties are copied from `this`. * * @param {Rac.Angle|number} angle - An `Angle` to move the start point towards * @param {number} distance - The distance to move the start point by * @returns {Rac.Segment} */ translateToAngle(angle, distance) { const newRay = this.ray.translateToAngle(angle, distance); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with the start point moved along the segment's * ray by the given `length`. All other properties are copied from `this`. * * When `length` is negative, `start` is moved in the inverse direction of * `angle`. * * @param {number} length - The length to move the start point by * @returns {Rac.Segment} */ translateToLength(length) { const newRay = this.ray.translateToDistance(length); return new Segment(this.rac, newRay, this.length); } /** * Returns a new `Segment` with the start point moved the given `distance` * towards the perpendicular angle to `this.angle()` in the `clockwise` * orientaton. All other properties are copied from `this`. * * @param {number} distance - The distance to move the start point by * @param {boolean} [clockwise=true] - The orientation of the perpendicular * @returns {Rac.Segment} */ translatePerpendicular(distance, clockwise = true) { const newRay = this.ray.translatePerpendicular(distance, clockwise); return new Segment(this.rac, newRay, this.length); } /** * Returns the given `value` clamped to [startInset, length-endInset]. * * When `startInset` is greater that `length-endInset` the range for the * clamp becomes imposible to fulfill. In this case the returned value * will be the centered between the range limits and still clampled to * `[0, length]`. * * @param {number} value - A value to clamp * @param {number} [startInset=0] - The inset for the lower limit of the * clamping range * @param {endInset} [endInset=0] - The inset for the higher limit of the * clamping range * @returns {number} */ clampToLength(value, startInset = 0, endInset = 0) { const endLimit = this.length - endInset; if (startInset >= endLimit) { // imposible range, return middle point const rangeMiddle = (startInset - endLimit) / 2; const middle = startInset - rangeMiddle; // Still clamp to the segment itself let clamped = middle; clamped = Math.min(clamped, this.length); clamped = Math.max(clamped, 0); return clamped; } let clamped = value; clamped = Math.min(clamped, this.length - endInset); clamped = Math.max(clamped, startInset); return clamped; } /** * Returns a new `Point` in the segment's ray at the given `length` from * `this.startPoint()`. When `length` is negative, the new `Point` is * calculated in the inverse direction of `this.angle()`. * * @param {number} length - The distance from `this.startPoint()` * @returns {Rac.Point} * @see Rac.Ray#pointAtDistance */ pointAtLength(length) { return this.ray.pointAtDistance(length); } /** * Returns a new `Point` in the segment's ray at a distance of * `this.length * ratio` from `this.startPoint()`. When `ratio` is * negative, the new `Point` is calculated in the inverse direction of * `this.angle()`. * * @param {number} ratio - The factor to multiply `length` by * @returns {Rac.Point} * @see Rac.Ray#pointAtDistance */ pointAtLengthRatio(ratio) { return this.ray.pointAtDistance(this.length * ratio); } /** * Returns a new `Point` at the middle point the segment. * @returns {Rac.Point} */ pointAtBisector() { return this.ray.pointAtDistance(this.length/2); } /** * Returns a new `Segment` starting at `newStartPoint` and ending at * `this.endPoint()`. * * When `newStartPoint` and `this.endPoint()` are considered * [equal]{@link Rac.Point#equals}, the new `Segment` will use * `this.angle()`. * * @param {Rac.Point} newStartPoint - The start point of the new `Segment` * @returns {Rac.Segment} * @see Rac.Point#equals */ moveStartPoint(newStartPoint) { const endPoint = this.endPoint(); return newStartPoint.segmentToPoint(endPoint, this.ray.angle); } /** * Returns a new `Segment` starting at `this.startPoint()` and ending at * `newEndPoint`. * * When `this.startPoint()` and `newEndPoint` are considered * [equal]{@link Rac.Point#equals}, the new `Segment` will use * `this.angle()`. * * @param {Rac.Point} newEndPoint - The end point of the new `Segment` * @returns {Rac.Segment} * @see Rac.Point#equals */ moveEndPoint(newEndPoint) { return this.ray.segmentToPoint(newEndPoint); } /** * Returns a new `Segment` from the starting point to the segment's middle * point. * * @returns {Rac.Segment} * @see Rac.Segment#pointAtBisector */ segmentToBisector() { return new Segment(this.rac, this.ray, this.length/2); } /** * Returns a new `Segment` from the segment's middle point towards the * perpendicular angle in the `clockwise` orientation. * * The new `Segment` will have the given `length`, or when ommited or * `null` will use `this.length` instead. * * @param {?number} [length=null] - The length of the new `Segment`, or * `null` to use `this.length` * @param {boolean} [clockwise=true] - The orientation of the perpendicular * @returns {Rac.Segment} * @see Rac.Segment#pointAtBisector * @see Rac.Angle#perpendicular */ segmentBisector(length = null, clockwise = true) { const newStart = this.pointAtBisector(); const newAngle = this.ray.angle.perpendicular(clockwise); const newRay = new Rac.Ray(this.rac, newStart, newAngle); const newLength = length === null ? this.length : length; return new Segment(this.rac, newRay, newLength); } /** * Returns a new `Segment` starting from `endPoint()` with the given * `length` and the same angle as `this`. * * @param {number} length - The length of the next `Segment` * @returns {Rac.Segment} */ nextSegmentWithLength(length) { const newStart = this.endPoint(); const newRay = this.ray.withStart(newStart); return new Segment(this.rac, newRay, length); } /** * Returns a new `Segment` starting from `endPoint()` and up to the given * `nextEndPoint`. * * When `endPoint()` and `nextEndPoint` are considered * [equal]{@link Rac.Point#equals}, the new `Segment` will use * `this.angle()`. * * @param {Rac.Point} nextEndPoint - The end point of the next `Segment` * @returns {Rac.Segment} * @see Rac.Point#equals */ nextSegmentToPoint(nextEndPoint) { const newStart = this.endPoint(); return newStart.segmentToPoint(nextEndPoint, this.ray.angle); } /** * Returns a new `Segment` starting from `endPoint()` towards `angle` * with the given `length`. * * The new `Segment` will have the given `length`, or when ommited or * `null` will use `this.length` instead. * * @param {Rac.Angle|number} angle - The angle of the new `Segment` * @param {?number} [length=null] - The length of the new `Segment`, or * `null` to use `this.length` * @returns {Rac.Segment} */ nextSegmentToAngle(angle, length = null) { angle = Rac.Angle.from(this.rac, angle); const newLength = length === null ? this.length : length; const newStart = this.endPoint(); const newRay = new Rac.Ray(this.rac, newStart, angle); return new Segment(this.rac, newRay, newLength); } /** * Returns a new `Segment` starting from `endPoint()` towards the given * `angleDistance` from `this.angle().inverse()` in the `clockwise` * orientation. * * The new `Segment` will have the given `length`, or when ommited or * `null` will use `this.length` instead. * * Notice that the `angleDistance` is applied to the inverse of the * segment's angle. E.g. with an `angleDistance` of `0` the resulting * `Segment` will be directly over and pointing in the inverse angle of * `this`. As the `angleDistance` increases the two segments separate with * the pivot at `endPoint()`. * * @param {Rac.Angle|number} angleDistance - An angle distance to apply to * the segment's angle inverse * @param {boolean} [clockwise=true] - The orientation of the angle shift * from `endPoint()` * @param {?number} [length=null] - The length of the new `Segment`, or * `null` to use `this.length` * @returns {Rac.Segment} * @see Rac.Angle#inverse */ nextSegmentToAngleDistance(angleDistance, clockwise = true, length = null) { angleDistance = this.rac.Angle.from(angleDistance); const newLength = length === null ? this.length : length; const newRay = this.ray .translateToDistance(this.length) .inverse() .withAngleShift(angleDistance, clockwise); return new Segment(this.rac, newRay, newLength); } /** * Returns a new `Segment` starting from `endPoint()` towards the * `[perpendicular angle]{@link Rac.Angle#perpendicular}` of * `this.angle().inverse()` in the `clockwise` orientation. * * The new `Segment` will have the given `length`, or when ommited or * `null` will use `this.length` instead. * * Notice that the perpendicular is calculated from the inverse of the * segment's angle. E.g. with `clockwise` as `true`, the resulting * `Segment` will be pointing towards `this.angle().perpendicular(false)`. * * @param {boolean} [clockwise=true] - The orientation of the * perpendicular angle from `endPoint()` * @param {?number} [length=null] - The length of the new `Segment`, or * `null` to use `this.length` * @returns {Rac.Segment} * @see Rac.Angle#perpendicular */ nextSegmentPerpendicular(clockwise = true, length = null) { const newLength = length === null ? this.length : length; const newRay = this.ray .translateToDistance(this.length) .perpendicular(!clockwise); return new Segment(this.rac, newRay, newLength); } /** * Returns a new `Segment` starting from `endPoint()` which corresponds * to the leg of a right triangle where `this` is the other cathetus and * the hypotenuse is of length `hypotenuse`. * * The new `Segment` will point towards the perpendicular angle of * `[this.angle().[inverse()]{@link Rac.Angle#inverse}` in the `clockwise` * orientation. * * When `hypotenuse` is smaller that the segment's `length`, returns * `null` since no right triangle is possible. * * @param {number} hypotenuse - The length of the hypotenuse side of the * right triangle formed with `this` and the new `Segment` * @param {boolean} [clockwise=true] - The orientation of the * perpendicular angle from `endPoint()` * @returns {Rac.Segment} * @see Rac.Angle#inverse */ nextSegmentLegWithHyp(hypotenuse, clockwise = true) { if (hypotenuse < this.length) { return null; } // cos = ady / hyp const radians = Math.acos(this.length / hypotenuse); // tan = ops / adj // tan * adj = ops const ops = Math.tan(radians) * this.length; return this.nextSegmentPerpendicular(clockwise, ops); } /** * Returns a new `Arc` based on this segment, with the given `endAngle` * and `clockwise` orientation. * * The returned `Arc` will use this segment's start as `center`, its angle * as `start`, and its length as `radius`. * * When `endAngle` is ommited or `null`, the segment's angle is used * instead resulting in a complete-circle arc. * * @param {?Rac.Angle} [endAngle=null] - An `Angle` to use as end for the * new `Arc`, or `null` to use `this.angle()` * @param {boolean} [clockwise=true] - The orientation of the new `Arc` * @returns {Rac.Arc} */ arc(endAngle = null, clockwise = true) { endAngle = endAngle === null ? this.ray.angle : Rac.Angle.from(this.rac, endAngle); return new Rac.Arc(this.rac, this.ray.start, this.length, this.ray.angle, endAngle, clockwise); } /** * Returns a new `Arc` based on this segment, with the arc's end at * `angleDistance` from the segment's angle in the `clockwise` * orientation. * * The returned `Arc` will use this segment's start as `center`, its angle * as `start`, and its length as `radius`. * * @param {Rac.Angle|number} angleDistance - The angle distance from the * segment's start to the new `Arc` end * @param {boolean} [clockwise=true] - The orientation of the new `Arc` * @returns {Rac.Arc} */ arcWithAngleDistance(angleDistance, clockwise = true) { angleDistance = this.rac.Angle.from(angleDistance); const stargAngle = this.ray.angle; const endAngle = stargAngle.shift(angleDistance, clockwise); return new Rac.Arc(this.rac, this.ray.start, this.length, stargAngle, endAngle, clockwise); } // TODO: uncomment once beziers are tested again // bezierCentralAnchor(distance, clockwise = true) { // let bisector = this.segmentBisector(distance, clockwise); // return new Rac.Bezier(this.rac, // this.start, bisector.end, // bisector.end, this.end); // } } // Segment
JavaScript
class ProtocolFramer extends Transform { constructor() { super({ objectMode: true }); } genenerateCheckSum(data) { // start value is 173 let sum = 173; for (const b of data) { sum += b; } // return least significant byte return sum & 0xFF; } _transform(chunk, encoding, callback) { const commandHandler = commands.byName(chunk.name); if (!commandHandler) return callback(new Error('Unknown Comfoair command')); const command = Buffer.from(commandHandler.command); const reducer = (accumulator, currentValue) => { const matchingParam = chunk.params[currentValue.name]; const currentDataFragment = currentValue.writer(matchingParam); return accumulator.concat(currentDataFragment); }; const data = Buffer.from(commandHandler.arg.reduce(reducer, [])); const dataLength = Buffer.from([data.length]); const msg = Buffer.concat([command, dataLength, data]); const checksum = Buffer.from([this.genenerateCheckSum(msg)]); // double 0x07 in data section to meet protocol specs const escapedData = bufferReplace(data, sequences.singleSeven, sequences.doubleSeven); // send message to comfoair const req = Buffer.concat([sequences.start, command, dataLength, escapedData, checksum, sequences.end]); this.push(req); callback(); } _flush(callback) { callback(); } }
JavaScript
class Button extends Component { constructor(options = {}) { super(new TButton(options)); privateProperties.set(this, { _defaultSelector: 'c__button', _callback: options.callback, }); } set disabled(val) { this.state = { ...this.state, disabled: val }; !val ? this.el.removeAttribute('disabled') : this.el.setAttribute('disabled', true); } set label(val) { this.state = { ...this.state, label: val }; this.el.innerText = val; } setCallback() { const { el } = this; const { _callback } = privateProperties.get(this); el.onclick = (evt) => { evt.preventDefault(); _callback(evt.target); }; } render() { const { _defaultSelector } = privateProperties.get(this); const { label, type, cssClass, disabled } = this.state; const otherClass = cssClass ? `${_defaultSelector}${cssClass}` : ''; this.el = this.template( 'button', { class: `${_defaultSelector} ${otherClass}`, 'data-label': label, type, }, label ); if (disabled) { this.el.setAttribute('disabled', true); } this.setCallback(); return this.el; } }
JavaScript
class MetaTagsContext extends Component { static childContextTypes = { extract: PropTypes.func } getChildContext() { return {extract: this.props.extract}; } render() { return Children.only(this.props.children); } }
JavaScript
class NoFocusTestWalker extends Lint.RuleWalker { visitCallExpression(node) { const functionName = node.expression.getText(); // create a failure at the current position if call is banned if (bannedFunctions.indexOf(functionName) !== -1) { this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING(functionName))); } // call the base version of this visitor to actually parse this node super.visitCallExpression(node); } }
JavaScript
class VentClientSubscription { constructor(client, name) { this.client = client; this._name = name; this._id = Random.id(); } get id() { return VentConstants.getPrefix(this._id, this._name); } /** * Subscribes to Meteor * * @param args * @returns {*} */ subscribe(...args) { const self = this; const handler = this.client.connection.subscribe( this._name, this._id, ...args ); const oldStop = handler.stop; Object.assign(handler, { listen(eventHandler) { if (!_.isFunction(eventHandler)) { throw new Meteor.Error( 'invalid-argument', 'You should pass a function to listen()' ); } self._eventHandler = eventHandler; }, stop() { self.client.remove(self); return oldStop.call(handler); }, }); return handler; } /** * Watches the incomming events */ handle(event) { if (this._eventHandler) { this._eventHandler(event); } } }
JavaScript
class KeyerPaddleNoneProcessor extends AudioWorkletProcessor { constructor() { super(); this.port.onmessage = (e) => this.onmessage(e); this.port.onmessageerror = (e) => this.onmessageerror(e); this.mode = 'B'; this.zeroes = new Float32Array(128); } onmessage(e) { // console.log(`KeyerPaddleNoneProcessor message ${e}`); const [message, ...data] = e.data; switch (message) { case 'timing': [ this.perSample, this.perRawDit, this.perDit, this.perDah, this.perIes, this.perIls, this.perIws ] = data; break; case 'mode': [this.mode] = data; break; default: console.log(`KeyerPaddleNoneProcessor message? ${e.data}`); break; } } onmessageerror(e) { console.log(`KeyerPaddleNoneProcessor message error ${e.data}`); this.messageError = e } process (inputs, outputs) { const output = outputs[0][0]; const input0 = inputs[0][0] || this.zeroes; const input1 = inputs[1][0] || this.zeroes; for (let i = 0; i < output.length; i += 1) { output[i] = KeyerPaddleNoneProcessor.clock(input0[i] !== 0, input1[i] !== 0, this.perSample); } return true; } static clock(dit, dah /* , tick */) { return dit || dah ? 1 : 0; } }
JavaScript
class BudgetOverview extends Component { constructor(props) { super(props); this.state = { budget: [], perPageLimit: 3, currentPage: 0, }; this.paginationRef = React.createRef(); } componentDidMount() { this.props.dispatch(budgetActions.getBugetOverview()); } componentDidUpdate(prevProps, prevState) { const { budget, perPageLimit, currentPage } = this.state; if ( this.props.budget_overview_status !== prevProps.budget_overview_status && this.props.budget_overview_status === status.SUCCESS ) { if ( this.props.budget_overview_data && this.props.budget_overview_data.length > 0 ) { this.setState({ budget: this.props.budget_overview_data }); let newData = this.props.budget_overview_data; let indexOfLastData = Math.ceil(newData.length / perPageLimit); this.paginationRef.current.setOptions({ totalPages: indexOfLastData, perPageLimit, totalRecords: newData.length, }); } } } onChangeCurrentPage = (currentPage) => { this.setState({ currentPage, }); }; displayData = () => { const { budget, currentPage, perPageLimit } = this.state; let retData = []; for (let i = 0; i < budget.length; i++) { if ( i >= currentPage * perPageLimit && i <= currentPage * perPageLimit + (perPageLimit - 1) ) { let row = budget[i]; retData.push( <div className='allocate-box' key={row[i]}> <div className='d-block allocate-heading'> <div className='row justify-content-between align-items-center'> <div className='col-md-9'> <div className='d-flex justify-content-start align-items-center'> <h4>{row.Department}</h4> <div className='d-flex justify-content-center align-items-center graph-circle'> <CircularProgressbar value={row.UsedBudgetPercentage} text={`${row.UsedBudgetPercentage}%`} strokeWidth={15} styles={buildStyles({ strokeLinecap: "butt", trailColor: "#f0f0f0", pathColor: "#6418c3", textColor: "#202020", })} /> </div> </div> </div> <div className='col-md-3'> <div className='d-flex justify-content-end align-items-center'> <a href='' className='primary-link' onClick={() => { this.props.history.push( `/postlogin/budgetoverview/${row.BudgetId}` ); }}> View Details </a> </div> </div> </div> </div> <div className='d-block allocate-progress'> <div className='d-block impacted'> $ {row.UsedBudget} Impacted on $ {row.TotalBudget} </div> <div class='progress'> <div class='progress-bar used' role='progressbar' style={{ width: `${row.UsedBudgetPercentage}%` }} aria-valuenow={row.UsedBudgetPercentage} aria-valuemin='0' aria-valuemax='100'></div> <div class='progress-bar commited' role='progressbar' style={{ width: `${row.CommitedBudgetPercentage}%` }} aria-valuenow={row.CommitedBudgetPercentage} aria-valuemin='75' aria-valuemax='100'></div> </div> </div> <div className='d-flex justify-content-center align-items-center allocate-progress-prices'> <div className='price used'> <h5>Used</h5> <p>${row.UsedBudget}</p> </div> <div className='price commited'> <h5>Commited</h5> <p>${row.CommitedBudget}</p> </div> <div className='price avaliable'> <h5>Avaliable</h5> <p>${row.AvaliableBudget}</p> </div> </div> </div> ); } } return retData; }; render() { const { budget } = this.state; return ( <div className='main-content'> <div className='budget-section'> <div className='budget-head-section'> <div className='row justify-content-center align-items-center'> <div className='col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12'> <div className='heading'> <h3>Budget Overview</h3> <span>Synectiks Budget FY 2021</span> </div> </div> <div className='col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12'> <div className='calender float-left float-md-right mt-3 mt-md-0 '> <DateFormat className='d-block' /> </div> </div> </div> </div> <div className='budget-content-section'> <div className='d-flex justify-content-end align-items-center'> <Button variant='contained' className='primary-btn allocate-btn' onClick={() => this.props.history.push(`/postlogin/budgetallocation`) }> Budget Allocate </Button> </div> {this.displayData()} </div> </div> <Pagination ref={this.paginationRef} changeCurrentPage={this.onChangeCurrentPage} /> </div> ); } }
JavaScript
class Buffer { /** * @param {number} width * @param {number} height */ constructor(width, height) { this.width = width; this.height = height; this.chars = new Uint32Array(width * height); this.foreground = new Uint32Array(width * height); this.background = new Uint32Array(width * height); this.layers = new Uint32Array(width * height); } /** * Set the value of a cell in this buffer. If the layer is lower than * the cell that is already drawn at this position, then it will be * ignored. * * @param {number} x The x position of the cell * @param {number} y The y position of the cell * @param {number | string} char The character code (or literal character to draw) * @param {number} fg The foreground color (in numeric RGBA format) * @param {number} [bg] The background color (in numeric RGBA format) * @param {number} [layer] The numeric layer */ put(x, y, char, fg, bg, layer = 0) { let index = x + y * this.width; let code = typeof char === "string" ? char.charCodeAt(0) : char; if (x >= 0 && y >= 0 && x < this.width && y < this.height) { if (layer >= this.layers[index]) { this.layers[index] = layer; if (fg != null) { this.foreground[index] = fg; } if (code != null) { this.chars[index] = code; } if (bg != null) { this.background[index] = bg; } } } } /** * Copy the contents of one buffer into another at a specific * coordinate. * * See: https://en.wiktionary.org/wiki/blit * * @param {Buffer} buffer * @param {number} [x] * @param {number} [y] * @param {number} [w] * @param {number} [h] */ blit(buffer, x = 0, y = 0, w = buffer.width, h = buffer.height, layer = 0) { for (let i = 0; i < w; i++) { for (let j = 0; j < h; j++) { let index = i + j * buffer.width; this.put( x + i, y + j, buffer.chars[index], buffer.foreground[index], buffer.background[index], buffer.layers[index] + layer, ); } } } /** * Reset the state of this buffer. */ clear() { this.chars.fill(0); this.foreground.fill(0); this.background.fill(0); this.layers.fill(0); } }
JavaScript
class RemindInThreeSeconds extends TestCase { /** * Executes the test case * @return {Promise} nothing (in case of failure - an exception will be thrown) */ async execute() { super.execute(); const discordClient = this.processor.discordClient; this.assertNotNull(discordClient); const user = discordClient.user; this.assertNotNull(user); const guild = discordClient.guilds.cache.get(this.processor.prefsManager.test_discord_guild_id); this.assertNotNull(guild); const channel = guild.channels.cache.get(this.processor.prefsManager.test_discord_text_channel_1_id); this.assertNotNull(channel); channel.send('!permitremind <@!' + user.id + '>'); let receivedMessage = await this.getReply(channel); this.assertNotNull(receivedMessage); this.assertEquals(receivedMessage.content, 'Successfully added the permission.'); channel.send('!reminders'); let receivedMessages = await this.getAllReplies(channel); this.assertNotNull(receivedMessages); let totalText = ''; for (const message of receivedMessages) { this.assertNotNull(message.content); totalText += message.content; } const remindersArrayStartLength = totalText.split('\n').length; channel.send('!remind in 3s e2e test'); receivedMessage = await this.getReply(channel); this.assertNotNull(receivedMessage); this.assertEquals(receivedMessage.content, 'Successfully added and scheduled a reminder.'); receivedMessage = await this.getReply(channel, 3000); this.assertNotNull(receivedMessage); this.assertEquals(receivedMessage.content, 'e2e test'); channel.send('!reminders'); receivedMessages = await this.getAllReplies(channel); this.assertNotNull(receivedMessages); totalText = ''; for (const message of receivedMessages) { this.assertNotNull(message.content); totalText += message.content; } const remindersArrayEndLength = totalText.split('\n').length; channel.send('!denyremind <@!' + user.id + '>'); receivedMessage = await this.getReply(channel); this.assertNotNull(receivedMessage); this.assertEquals(receivedMessage.content, 'Successfully removed 1 permission(s).'); this.assertEquals(remindersArrayStartLength, remindersArrayEndLength); } }
JavaScript
class BookBundle extends React.Component { render() { return ( <> <EcwidEmbed /> </> ); } }
JavaScript
class Payments { constructor(client) { this.client = client this.basePath = '/payments' } /** * Initiate payment * * @param {*} body object containing {debitAccountNumber, creditAccountNumber, kid, amount, currency} etc. */ async initiatePayment(body) { try { return await this.client.do .post(`${this.basePath}`, {}, body) .then(obj => obj.json()) } catch (err) { throw err } } /** * Delete payment * * @param {String} accountNumber * @param {String} paymentId */ async deletePayment(accountNumber, paymentId) { try { return await this.client.do .delete(`${this.basePath}/${accountNumber}/pending-payments/${paymentId}`) .then(obj => obj.json()) } catch (err) { throw err } } /** * Update existing payment * * @param {String} accountNumber * @param {String} paymentId * @param {Object} body of request: { status, debitAccountNumber, amount, requestedExecutionDate } */ async updateExistingPayment(accountNumber, paymentId, body) { try { return await this.client.do .patch(`${this.basePath}/${accountNumber}/pending-payments/${paymentId}`, {}, body) .then(obj => obj.json()) } catch (err) { throw err } } /** * Get due payments for an account * * @param {String} accountNumber */ async getDuePayments(accountNumber) { try { return await this.client.do .get(`${this.basePath}/${accountNumber}/due`) .then(obj => obj.json()) } catch (err) { throw err } } /** * Get a due payment for an account * * @param {String} accountNumber * @param {String} paymentId */ async getDuePayment(accountNumber, paymentId) { try { return await this.client.do .get(`${this.basePath}/${accountNumber}/due/${paymentId}`) .then(obj => obj.json()) } catch (err) { throw err } } }
JavaScript
class ChaptersButton extends TextTrackButton { constructor(player, options, ready) { super(player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ buildCSSClass() { return `vjs-chapters-button ${super.buildCSSClass()}`; } update(event) { if (!this.track_ || (event && (event.type === 'addtrack' || event.type === 'removetrack'))) { this.setTrack(this.findChaptersTrack()); } super.update(); } setTrack(track) { if (this.track_ === track) { return; } if (!this.updateHandler_) { this.updateHandler_ = this.update.bind(this); } // here this.track_ refers to the old track instance if (this.track_) { const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (remoteTextTrackEl) { remoteTextTrackEl.removeEventListener('load', this.updateHandler_); } this.track_ = null; } this.track_ = track; // here this.track_ refers to the new track instance if (this.track_) { this.track_.mode = 'hidden'; const remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_); if (remoteTextTrackEl) { remoteTextTrackEl.addEventListener('load', this.updateHandler_); } } } findChaptersTrack() { const tracks = this.player_.textTracks() || []; for (let i = tracks.length - 1; i >= 0; i--) { // We will always choose the last track as our chaptersTrack const track = tracks[i]; if (track.kind === this.kind_) { return track; } } } getMenuCaption() { if (this.track_ && this.track_.label) { return this.track_.label; } return this.localize(toTitleCase(this.kind_)); } /** * Create menu from chapter track * * @return {Menu} Menu of chapter buttons * @method createMenu */ createMenu() { this.options_.title = this.getMenuCaption(); return super.createMenu(); } /** * Create a menu item for each chapter cue * * @return {Array} Array of menu items * @method createItems */ createItems() { const items = []; if (!this.track_) { return items; } const cues = this.track_.cues; if (!cues) { return items; } for (let i = 0, l = cues.length; i < l; i++) { const cue = cues[i]; const mi = new ChaptersTrackMenuItem(this.player_, { track: this.track_, cue }); items.push(mi); } return items; } }
JavaScript
class DestinationResourceSpecification { /** * Constructs a new <code>DestinationResourceSpecification</code>. * The information required to create a destination resource. Applications should use one resource type (sqs or eventBridge) per destination. * @alias module:client/models/DestinationResourceSpecification * @class */ constructor() { } /** * Constructs a <code>DestinationResourceSpecification</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:client/models/DestinationResourceSpecification} obj Optional instance to populate. * @return {module:client/models/DestinationResourceSpecification} The populated <code>DestinationResourceSpecification</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new DestinationResourceSpecification(); if (data.hasOwnProperty('sqs')) { obj['sqs'] = SqsResource.constructFromObject(data['sqs']); } if (data.hasOwnProperty('eventBridge')) { obj['eventBridge'] = EventBridgeResourceSpecification.constructFromObject(data['eventBridge']); } } return obj; } /** * @member {module:client/models/SqsResource} sqs */ 'sqs' = undefined; /** * @member {module:client/models/EventBridgeResourceSpecification} eventBridge */ 'eventBridge' = undefined; }
JavaScript
class DraftAreaContainer extends React.Component { constructor(props, context) { super(props, context); this.initValue(); } async initValue() { const input = await this.context.pymSessionStorage.getItem(this.getPath()); if (input && this.props.onInputChange) { let parsed = ''; // Older version saved a normal string, catch those and ignore them. try { parsed = JSON.parse(input); } catch (_e) {} if (typeof parsed === 'object') { this.props.onInputChange(parsed); } } } getPath = () => { return `${STORAGE_PATH}_${this.props.id}`; }; componentWillReceiveProps(nextProps) { if (this.props.input !== nextProps.input) { if (nextProps.input) { this.context.pymSessionStorage.setItem( this.getPath(), JSON.stringify(nextProps.input) ); } else { this.context.pymSessionStorage.removeItem(this.getPath()); } } } render() { return ( <DraftArea root={this.props.root} comment={this.props.comment} input={this.props.input} id={this.props.id} onInputChange={this.props.onInputChange} disabled={this.props.disabled} charCountEnable={this.props.charCountEnable} maxCharCount={this.props.maxCharCount} registerHook={this.props.registerHook} unregisterHook={this.props.unregisterHook} isReply={this.props.isReply} isEdit={this.props.isEdit} /> ); } }
JavaScript
class FirstPage extends Component { render() { return ( // Wrap in a React.Fragment because there needs to be some kind of wrapper - won't add anything to DOM <React.Fragment> <Content type='title'> Sample Title </Content> <Link to= { `/sample/1`}> <Content> Link 1 </Content> </Link> <Link to= { `/sample/2`}> <Content> Link 2 </Content> </Link> </React.Fragment> ); } }
JavaScript
class IconSeparator extends PureComponent { static propTypes = { /** * An optional style to apply. */ style: PropTypes.object, /** * An optional className to apply. */ className: PropTypes.string, /** * An optional style to apply to the label. */ labelStyle: PropTypes.object, /** * An optional className to apply to the label. */ labelClassName: PropTypes.string, /** * The label to display. */ label: PropTypes.node.isRequired, /** * The icon to display. */ children: PropTypes.node.isRequired, /** * Boolean if the icon should appear before or after the text */ iconBefore: PropTypes.bool, /** * The component to be rendered as. */ component: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, PropTypes.object, ]).isRequired, }; static defaultProps = { component: 'div', }; render() { const { className, labelStyle, labelClassName, component, label, iconBefore, children, ...props } = this.props; let text; if (isValidElement(label)) { const labelProps = Children.only(label).props; text = cloneElement(label, { className: cn('md-icon-text', labelClassName, labelProps.className), style: { ...labelStyle, ...labelProps.style }, }); } else { text = <span style={labelStyle} className={cn('md-icon-text', labelClassName)}>{label}</span>; } const Component = component; return ( <Component {...props} className={cn('md-icon-separator', className)}> {iconBefore && children} {text} {!iconBefore && children} </Component> ); } }
JavaScript
class Controller { /** * Constructor. * @param {!angular.Scope} $scope * @param {!angular.JQLite} $element * @param {!angular.$compile} $compile * @ngInject */ constructor($scope, $element, $compile) { if ('result' in $scope) { var result = $scope['result'].getResult(); this['url'] = result.getUrl(); this['title'] = TuiEditor.getUnformatedText(result.getTitle()); } } /** * Get the title with correct action icon * * @return {string} * @export */ getViewIcon() { var file = this.isFileDownloadLink(); var icon = file ? '<i class="fa fa-download px-2" title="Download Report"></i>' : ''; var actionIcon = '<a href="' + this['url'] + '" target="' + this['url'] + '">' + icon + '</a>'; return actionIcon; } /** * To linkify title or not * * @return {string} * @export */ getTitle() { var file = this.isFileDownloadLink(); var linkTitle = '<a href="' + this['url'] + '" target="' + this['url'] + '" title="' + this['url'] + '">' + this['title'] + '</a>'; return file ? this['title'] : linkTitle; } /** * Is the link to an external site * * @return {boolean} * @export */ isFileDownloadLink() { var fileDownloadUrl = /** @type {string} */ (Settings.getInstance().get('tools.fileDownloadUrl')); return !!this['url'] && this['url'].includes(fileDownloadUrl); } }
JavaScript
class OrgChartGraphSearch extends GraphSearch { /** * Returns whether the given node is a match when searching for the given text. * This method searches the matching string to the labels and the tags of the nodes. * @param {INode} node The node to be examined * @param {string} text The text to be queried * @return {boolean} True if the node matches the text, false otherwise */ matches(node, text) { const lowercaseText = text.toLowerCase() // the icon property does not have to be matched if ( node.tag && Object.getOwnPropertyNames(node.tag).some( prop => prop !== 'icon' && node.tag[prop] && node.tag[prop] .toString() .toLowerCase() .indexOf(lowercaseText) !== -1 ) ) { return true } return node.labels.some(label => label.text.toLowerCase().indexOf(lowercaseText) !== -1) } }
JavaScript
class ScriptFunctionCreator extends FunctionCreatorBase_1.FunctionCreatorBase { constructor(functionAppPath, template, language) { super(functionAppPath, template); this._language = language; } promptForSettings(ui, functionName) { return __awaiter(this, void 0, void 0, function* () { if (!functionName) { const defaultFunctionName = yield fsUtil.getUniqueFsPath(this._functionAppPath, this._template.defaultFunctionName); this._functionName = yield ui.showInputBox({ placeHolder: localize_1.localize('azFunc.funcNamePlaceholder', 'Function name'), prompt: localize_1.localize('azFunc.funcNamePrompt', 'Provide a function name'), validateInput: (s) => this.validateTemplateName(s), value: defaultFunctionName || this._template.defaultFunctionName }); } else { this._functionName = functionName; } }); } createFunction(userSettings) { return __awaiter(this, void 0, void 0, function* () { const functionPath = path.join(this._functionAppPath, this._functionName); yield fse.ensureDir(functionPath); yield Promise.all(Object.keys(this._template.templateFiles).map((fileName) => __awaiter(this, void 0, void 0, function* () { yield fse.writeFile(path.join(functionPath, fileName), this._template.templateFiles[fileName]); }))); for (const key of Object.keys(userSettings)) { this._template.functionConfig.inBinding[key] = userSettings[key]; } yield fsUtil.writeFormattedJson(path.join(functionPath, 'function.json'), this._template.functionConfig.functionJson); const mainFileName = getScriptFileNameFromLanguage(this._language); if (mainFileName) { return path.join(functionPath, mainFileName); } else { return undefined; } }); } validateTemplateName(name) { if (!name) { return localize_1.localize('azFunc.emptyTemplateNameError', 'The template name cannot be empty.'); } else if (fse.existsSync(path.join(this._functionAppPath, name))) { return localize_1.localize('azFunc.existingFolderError', 'A folder with the name \'{0}\' already exists.', name); } else if (!this._functionNameRegex.test(name)) { return localize_1.localize('azFunc.functionNameInvalidError', 'Function name must start with a letter and can contain letters, digits, \'_\' and \'-\''); } else { return undefined; } } }
JavaScript
class ConfigFacade { static async getConfig() { let config = await ApiRequestFactory .createApiRequest("http") .makeGetRequest('jsonplaceholder.typicode.com/posts/1'); config = ConfigFormatConvert.convert(config); config = ConfigCheck.configCheck(config); console.log(config); } }
JavaScript
class BisWebHistogram { constructor(numbins=64,origin=0.0,scale=1.0) { this.numbins=Math.floor(util.range(numbins,2,1024)); this.max=this.numbins-1.000; this.bins=new Uint32Array(this.numbins); this.scale=scale; this.origin=origin; this.zero(); } zero() { for (let i=0;i<this.numbins;i++) this.bins[i]=0; this.numsamples=0; } getnumsamples() { return this.numsamples; } /** Computes mean and stdev * @returns{Array} - [ mean, stdev ] */ computeStats() { let sum=0,sum2=0; let numscalars=0; for (let i=0; i<this.numbins; i++) { let w=this.bins[i]; let v=this.origin+this.scale*i; sum += w*v; sum2 += (w*v*v); numscalars += w; } if (numscalars<0.01) numscalars=0.01; let mean = sum/(numscalars); let sigma = sum2/(numscalars)-mean*mean; if (sigma<0.00001) sigma=0.00001; return [ mean,sigma ]; } /** Computes Entropy of histogram * returns {number} - entropy value */ entropy() { let out=0.0; for (let i=0;i<this.numbins;i++) { let tmp=this.bins[i]; if (tmp > 0) out += tmp * Math.log(tmp); } return (- out / this.numsamples + Math.log(this.numsamples)); } fill(arr,reset=true) { // If reset, do reset if (reset) { this.zero(); } for (let i=0;i<arr.length;i++) { let v=Math.round( (arr[i]-this.origin)/this.scale); if (v>=0 && v<this.numbins) this.bins[v]+=1; } this.numsamples=0; for (let i=0;i<this.numbins;i++) { this.numsamples+=this.bins[i]; } } }
JavaScript
class GodsMap extends Map { constructor(options) { super(options); this.reset(); } reset() { this._switches = {}; super.reset(); } addObject(obj) { super.addObject(obj); // console.log('addObject', obj.type); // add switch to the list if (obj.type === 'switch') { this._switches[obj.id] = obj; } } getSwitchAboveMaster() { var switchSprite = null, master = this.masterObject, masterHitBox = master.getHitBox(), hitBox = null, masterCenterPos = master.x + (master.getCurrentWidth() / 2), box = { x: master.x, y: master.y, x2: master.x + masterHitBox.x2, y2: master.y + masterHitBox.y2 }, id; for (id in this._switches) { switchSprite = this._switches[id]; hitBox = switchSprite.getHitBox(); if ((switchSprite.x + hitBox.x2) >= masterCenterPos && switchSprite.x <= masterCenterPos) { if ((switchSprite.y + hitBox.y2) >= (master.y - 5) && switchSprite.y <= (box.y2 + 5)) { break; } } else { switchSprite = null; } } return switchSprite; } }
JavaScript
class Car { constructor(name, year) { this.name = name; this.year = year; } }
JavaScript
class Car { constructor(brand) { this.carname = brand; } get cnam() { return this.carname; } set cnam(x) { this.carname = x; } }
JavaScript
class Car { constructor(brand) { this.carname = brand; } }
JavaScript
class DomHandler { /** * Constructor. * * @param {string} rootNodeId - id from parent grid * @param {string} selectedRootNodeId - id from parent selected grid */ constructor(rootNodeId, selectedRootNodeId) { this.rootNode = document.getElementById(rootNodeId); this.selectedRootNode = document.getElementById(selectedRootNodeId); this.items = []; // current grid items (may be a little Virtual DOM, but as list) this.selected = {}; // selected items this.index = {}; // for eases item access by it's id this.isEmpty = true; // empty element flag this.incrementalId = 0; } /** * Triggers grid re-render. */ render() { let fragment = document.createDocumentFragment(); for (let item of this.items) fragment.appendChild(item); // appends empty li to end for aspect ratio fix fragment.appendChild(this._createItem(true)); this.rootNode.textContent = ""; // clears grid content this.rootNode.appendChild(fragment); } /** * Triggers selected grid re-render. */ renderSelected() { if (this.isEmpty) this.clear(); let fragment = document.createDocumentFragment(); for (let item of Object.values(this.selected)) fragment.appendChild(item); // appends empty li to end for aspect ratio fix !this.isEmpty && fragment.appendChild(this._createItem(true)); this.selectedRootNode.textContent = ""; // clears grid content this.selectedRootNode.appendChild(fragment); } /** * Adds 'n' random items to grid. * * @param {number} count */ add(count) { while (count-- > 0) { const item = this._createItem(); this.index = { ...this.index, [item.id]: item }; this.items.push(item); } } /** * Removes selected all items from grid. */ clear() { this.selected = { _: this._noItemsBanner() }; this.isEmpty = true; } /** * Toggles item selection state. * * @param {number} id item id */ _select(id) { const { [id]: item, ...rest } = this.selected; if (item) { this.selected = rest; this.index[id].classList.remove("selected"); if (Object.keys(this.selected).length === 0) this.isEmpty = true; } else { if (this.isEmpty) this.selected = {}; this.selected[id] = this.index[id].cloneNode(true); this.selected[id].id = `${id}-selected`; this.selected[id].classList.remove("hoverable"); this.index[id].classList.add("selected"); this.isEmpty = false; } this.renderSelected(); } /** * Creates a new HTMLElement (li) for grid. * * @param {boolean} empty - whether li must be empty * * @returns {HTMLLIElement} */ _createItem(empty) { let item = document.createElement("li"); if (!empty) { const [width, height] = randomResolution(); item.className = "item card depth-2 hoverable cursor"; item.id = ++this.incrementalId; item.onclick = () => this._select(item.id); let img = document.createElement("img"); img.className = "card-image"; img.src = `https://picsum.photos/${width}/${height}`; item.appendChild(img); } return item; } /** * Creates default HTMLElement (li) * for grid when no elements are rendered. * * @returns {HTMLLIElement} */ _noItemsBanner() { let item = document.createElement("li"); item.className = "item card empty"; let text = document.createElement("h1"); text.textContent = "No photos selected"; item.appendChild(text); return item; } }
JavaScript
class DeathFeed extends Feature { callbacks_ = null; disabledPlayers_ = null; recentDeaths_ = null; constructor() { super(); // Set of players for whom the death feed is disabled. this.disabledPlayers_ = new WeakSet(); // Array of the most recent additions to the death feed. Will be limited in size to the // value of kDeathFeedVisibleMessageCount. Used to restore the death feeds for players. this.recentDeaths_ = []; this.callbacks_ = new ScopedCallbacks(); this.callbacks_.addEventListener( 'playerresolveddeath', DeathFeed.prototype.onPlayerDeath.bind(this)); this.callbacks_.addEventListener( 'playerdisconnect', DeathFeed.prototype.onPlayerDisconnect.bind(this)); } // Returns an array with the most recent deaths. get recentDeaths() { return this.recentDeaths_; } // Disables the death feed for |player|. Five fake deaths will be send to their client to clear // the current state of the death screen on their screens, wiping it clean. disableForPlayer(player) { this.disabledPlayers_.add(player); for (let index = 0; index < kDeathFeedVisibleMessageCount; ++index) this.sendDeathMessage(player, kUnassignedPlayerId, Player.kInvalidId, 0); } // Enables the death feed for |player|. The five most recent deaths will be send to their client // so that it accurately resembles the current state of the world again. enableForPlayer(player) { this.disabledPlayers_.delete(player); for (const { killee, killer, reason } of this.recentDeaths_) this.sendDeathMessage(player, killee, killer, reason); } // Called when a player dies or gets killed. Will cause an update to the death feed for all // players, except those for whom the death feed has been disabled. The source of this event is // the Pawn part of Las Venturas Playground, as the circumstances of the death may have to be // resolved prior to being presented to players. onPlayerDeath(event) { this.recentDeaths_.unshift({ killee: event.playerid, killer: event.killerid, reason: event.reason }); this.recentDeaths_ = this.recentDeaths_.slice(0, kDeathFeedVisibleMessageCount); // TODO: This needs to live in a better place. { const player = server.playerManager.getById(event.playerid); if (player && player.isSelectingObject()) player.cancelEdit(); } for (const recipient of server.playerManager) { if (recipient.isNonPlayerCharacter()) continue; // don't waste cpu cycles on NPCs if (this.disabledPlayers_.has(recipient)) continue; // they've opted out of death messages this.sendDeathMessage(recipient, event.playerid, event.killerid, event.reason); } } // Utility function to send a death message to |player|. sendDeathMessage(player, killee, killer, reason) { pawnInvoke('SendDeathMessageToPlayer', 'iiii', player.id, killer, killee, reason); } // Called when a player disconnects from the server. Re-enables the death feed for the player in // case it was previously disabled. (So that it's not disabled for future players.) onPlayerDisconnect(event) { const player = server.playerManager.getById(event.playerid); if (player) this.disabledPlayers_.delete(player); } dispose() { this.disabledPlayers_ = null; this.callbacks_.dispose(); this.callbacks_ = null; } }
JavaScript
class Size { /** * Creates instances of {@link Size} from the dimensions read from the specified <code>image</code>. * * <code>image</code> can either be a <code>Buffer</code> containing image data or the path of an image file. If * <code>image</code> contains multiple images (e.g. ICO), the returned array will contain a {@link Size} for each * image contained within. * * @param {Buffer|string} image - the image whose dimensions are to be captured in the returned {@link Size} instances * @return {Promise<Size[]>} A <code>Promise</code> for the asynchronous image parsing and file reading that is * resolved with a {@link Size} instance for each image contained within <code>image</code>. * @public */ static async fromImage(image) { const { height, images, width } = await sizeOf(image); const sizes = []; if (images) { for (const dimensions of images) { sizes.push(new Size(dimensions.width, dimensions.height)); } } else { sizes.push(new Size(width, height)); } return sizes; } /** * Parses the specified <code>size</code> value into a {@link Size} instance. * * <code>size</code> can either be a string representation of {@link Size} or a number representing both width and * height dimensions. If <code>size</code> is a string, it can contain either just a single number, which will be used * as both width and height dimensions, or two numbers separated by an "x", which will be used as the width and height * dimensions repsectively. * * An error will occur if <code>size</code> is a negative number or <code>NaN</code>, or it's a malformed string, or * it's a string or number. * * @param {number|string} size - the size value to be parsed * @return {Size} A {@link Size} parsed from <code>size</code>. * @throws {Error} If <code>size</code> is invalid or malformed. * @public */ static parse(size) { let height; let match; let width; switch (typeof size) { case 'number': if (Number.isNaN(size) || size < 0) { throw new Error(`"sizes" configuration must contain only valid positive numbers: ${size}`); } width = size; height = size; break; case 'string': match = size.match(rSize); if (!match) { throw new Error(`"sizes" configuration must contain width and optionally height: ${size}`); } width = parseInt(match[1], 10); height = match[3] ? parseInt(match[3], 10) : width; break; default: throw new Error(`"sizes" configuration can only contain numbers and strings: ${size} (${typeof size})`); } return new Size(width, height); } /** * Returns a string representation of the specified <code>size</code>. * * <code>null</code> will be returned if <code>size</code> is <code>null</code>. * * @param {?Size} size - the {@link Size} whose string representation is to be returned (may be <code>null</code>) * @return {?string} The string representation of <code>size</code> or <code>null</code> if <code>size</code> is * <code>null</code>. * @public */ static stringify(size) { return size ? size.toString() : null; } /** * Creates an instance of {@link Size} with the <code>width</code> and <code>height</code> provided. * * {@link Size.parse} is typically used to create instances during the parsing of a {@link Config}. * * @param {number} width - the width to be used * @param {number} height - the height to be used * @public */ constructor(width, height) { this[_width] = width; this[_height] = height; } /** * @override */ toString() { return `${this.width}x${this.height}`; } /** * Returns the height of this {@link Size}. * * @return {number} The height. * @public */ get height() { return this[_height]; } /** * Returns the width of this {@link Size}. * * @return {number} The width. * @public */ get width() { return this[_width]; } }
JavaScript
class XRFaceMesh extends XRMesh { constructor(transform, geometry, blendShapeArray, uid=null, timestamp=0) { super(transform, geometry, uid, timestamp) this._blendShapes = {} this._blendShapesChanged = true this._updateBlendShapes(blendShapeArray) } get changed () { return super.changed || this._blendShapesChanged } clearChanged() { super.clearChanged() this._blendShapesChanged = false; } _updateBlendShapes(blendShapeArray) { for (let i = 0; i < blendShapeNames.length; i++) { let j = blendShapeNames[i] var a0 = this._blendShapes[j] var b0 = blendShapeArray[i] if (Math.abs(a0 - b0) > glMatrix.EPSILON) { this._blendShapesChanged = true this._blendShapes[j] = b0 } } } updateFaceData(transform, geometry, blendShapeArray, timestamp) { super.updateModelMatrix(transform, timestamp) // updates to the face mesh only have "vertices" set in geometry. // add vertexCount back if (typeof geometry.vertexCount === 'undefined') { geometry.vertexCount = geometry.vertices.length / (XRMesh.useGeomArrays() ? 3 : 1) } this._updateGeometry(geometry) this._updateBlendShapes(blendShapeArray) } get blendShapes() { return this._blendShapes } }
JavaScript
class ProfileHeader extends React.Component{ render(){ return( <div className="Profile__header"> <img className="Profile__logo"src={confLogo} alt="logo AcademiaGeek"></img> </div> ); } }
JavaScript
class FormatterHTML { /** * See {@link Formatter} * @param doc * @param metadata * @returns {string} */ start (doc, metadata) { return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>${metadata['Title'] ? metadata['Title'] : 'pdf-gold-digger - pdf to html'}</title> </head> <body> `; } /** * Formats {@link TextObject} to xml object * @param {TextObject} textObject * @returns {object} */ formatTextObject (textObject) { let txtObjOut = `<div>\n`; const lines = textObject.getData(); lines.sort((a, b) => { if (a.y > b.y) return -1; if (a.y < b.y) return 1; return 0; }); lines.forEach(textLine => { txtObjOut += this.formatTextLine(textLine); }); txtObjOut += '</div>\n'; return txtObjOut; } /** * Format image object * @param {ImageObject} imageObject */ formatImageObject (imageObject) { return `<img class="pdf-dig-img" width="${imageObject.width}px" height="${imageObject.height}px" src="img/${imageObject.name}"/>\n`; } /** * Formats {@link TextLine} to xml object * @param {TextLine} textLine * @returns {object} */ formatTextLine (textLine) { let txtLineOut = `<p class="pdfdig-text-line">`; textLine.getText().forEach(textFont => { txtLineOut += this.formatTextFont(textFont); }); txtLineOut += '</p>\n'; return txtLineOut; } /** * Formats {@link TextFont} to xml object * @param {TextFont} textFont * @returns {object} */ formatTextFont (textFont) { const font = textFont.font; return `<span class="pdfdig-text-font" style="font-family: ${font.family}; font-size:${font.size}pt; font-style:${font.style}; font-weight:${font.weight};"> ${textFont.getText()} </span>`; } /** * See {@link Formatter} * @param page * @param data * @param last * @returns {string} */ format (page, data, last) { let out = '<div class="pdfdig-pdf-object">\n'; data.forEach(pdfObject => { if (pdfObject instanceof Model.TextObject) { out += this.formatTextObject(pdfObject); } else if (pdfObject instanceof Model.ImageObject) { out += this.formatImageObject(pdfObject); } else { console.warn(`Not recognised object ${pdfObject}`); } }); out += '</div>'; return out; } /** * See {@link Formatter} * @param {array} fontData */ formatFont (fontData) { return ''; } /** * See {@link Formatter} * @returns {string} */ end () { return `</body> </html>`; } }
JavaScript
class View extends Component { state = { roles: "member", rate: 0, active: true, stepsEnabled: true, initialStep: 0, steps: [ { intro: "Welcome to the Slackr dashboard! From here managers have access to all essentials and team members can view the stand up reports that their managers have created." }, { element: ".one", intro: "Here you can see all the reports. Managers can edit and delete existing reports. To select a specific report click on the respond button." }, { element: ".two", intro: "This displays the percentage of completed reports." }, { intro: "To add people to your team click the my team button on the left." }, { intro: "To view more in depth statistics about the well being of your team and reports filled out by day click on the stats button on the left." }, { intro: "Managers can use the + button on the side bar to create their first survey!" } ] }; componentDidMount() { this.getData(); } // refactor into async await for readability and promise.all for performance getData = async () => { try { const roles = jwt_decode(localStorage.getItem("token")).roles; const endpoint = `${baseURL}/users/byuser`; // make api calls at the same time const [userResponse, rateResponse] = await Promise.all([ await axiosWithAuth().get(endpoint), await axiosWithAuth().get(`${baseURL}/reports/submissionRate`) ]); const rate = rateResponse.data.historicalSubmissionRate / 100; this.setState({ active: userResponse.data.user.active, rate, roles }); } catch (err) { console.log(err.response); } }; render() { const { stepsEnabled, steps, initialStep } = this.state; return this.state.active ? ( <div className="dashboard-view"> {localStorage.getItem("doneTour") === "yeah!" ? null : ( <Steps className="step" enabled={stepsEnabled} steps={steps} initialStep={initialStep} onExit={this.onExit} /> )} <div className="view"> <Dashboard className="usersDash" role={this.state.roles} /> <div className="one"> <ReportsDash className="reportsDash" role={this.state.roles} {...this.props} /> </div> </div> <div className="sidebar"> <div className="two"> <CircleProgress title="Today's Surveys" percentComplete={this.state.rate} /> </div> {/* <PollCalendar /> */} </div> </div> ) : ( <Card style={{ textAlign: "center" }}> Looks like your account has been deactivated. If you believe this is an error, please contact your manager. </Card> ); } onExit = () => { this.setState(() => ({ stepsEnabled: false })); localStorage.setItem("doneTour", "yeah!"); }; }
JavaScript
class InactiveVoiceStreamJob extends Job { /** * The jobs constructor, this will check if the cache * already exists, if it doesn't it will create * it by calling the run method. */ constructor() { super(); this.run(); } /** * This method determines when the job should be execcuted. * * @override * @param {RecurrenceRule} rule A node-schedule CRON recurrence rule instance * @return {mixed} */ runCondition(rule) { return '*/30 * * * *'; } /** * The jobs main logic method, this method is executed * whenever the {@link Job#runCondition} method returns true. * * @override */ run() { return app.database.getBlacklist().then(users => { let feature = app.bot.features.blacklist; feature.blacklist = users; }).catch(err => app.logger.error(err)); } }
JavaScript
class HaxCeContext extends LitElement { /** * LitElement constructable styles enhancement */ static get styles() { return [ css` :host *[hidden] { display: none; } :host { display: block; height: 36px; } hax-context-item { margin: 0; height: 36px; } :host(.hax-context-pin-top) hax-toolbar { position: fixed; top: 64px; opacity: 0.9; } :host(.hax-context-pin-bottom) hax-toolbar { position: fixed; bottom: 0; opacity: 0.9; } :host(.hax-context-pin-top) hax-toolbar:hover, :host(.hax-context-pin-bottom) hax-toolbar:hover { opacity: 1; } ` ]; } constructor() { super(); this.ceSize = 100; this.haxProperties = {}; import("@lrnwebcomponents/hax-body/lib/hax-context-item.js"); import("@lrnwebcomponents/hax-body/lib/hax-toolbar.js"); } render() { return html` <hax-toolbar id="toolbar" size="${this.ceSize}" @size-changed="${this.ceSizeChanged}" > <slot slot="primary"></slot> <hax-context-item slot="primary" icon="icons:settings" label="Settings" event-name="hax-manager-configure" .hidden="${!this.__hasSettingsForm}" ></hax-context-item> <hax-context-item slot="primary" icon="icons:view-quilt" label="${this.__parentName}" event-name="hax-manager-configure-container" .hidden="${!this.__hasParentSettingsForm}" ></hax-context-item> </hax-toolbar> `; } static get tag() { return "hax-ce-context"; } static get properties() { return { /** * ce size. */ ceSize: { type: Number, attribute: "ce-size" }, /** * Selected value to match ce direction currently. */ haxProperties: { type: Object, attribute: "hax-properties" }, __hasSettingsForm: { type: Boolean }, __hasParentSettingsForm: { type: Boolean }, __parentName: { type: String } }; } updated(changedProperties) { changedProperties.forEach((oldValue, propName) => { if (propName == "haxProperties") { this.shadowRoot.querySelector("#toolbar").haxProperties = this[ propName ]; this._haxPropertiesChanged(this[propName], oldValue); } if (propName == "ceSize") { this._ceSizeChanged(this[propName], oldValue); } }); } ceSizeChanged(e) { this.ceSize = e.detail; } /** * Set haxProperties. */ setHaxProperties(props) { // be aggressive w/ reset this.haxProperties = props; } /** * ce size changed. */ _ceSizeChanged(newValue, oldValue) { if ( typeof newValue !== typeof undefined && typeof oldValue !== typeof undefined ) { this.dispatchEvent( new CustomEvent("hax-context-item-selected", { bubbles: true, cancelable: true, composed: true, detail: { eventName: "hax-size-change", value: newValue } }) ); } } /** * HAX properties changed, update buttons available. */ _haxPropertiesChanged(newValue, oldValue) { if ( typeof oldValue !== typeof undefined && typeof newValue.settings !== typeof undefined ) { // clear current slot for the tag while (this.firstChild !== null) { this.removeChild(this.firstChild); } let settings = newValue.settings.quick; let configure = newValue.settings.configure; let advanced = newValue.settings.advanced; // support things that could technically have no configuration // or advanced form but have quick settings // This doesn't make a ton of sense but it is possible if ( (configure.length || advanced.length) && newValue.element.tagName !== "HR" ) { this.__hasSettingsForm = true; } else { this.__hasSettingsForm = false; } this.__hasParentSettingsForm = false; // test for parent being different from child if ( window.HaxStore.instance.activeContainerNode !== window.HaxStore.instance.activeNode && window.HaxStore.instance.activeContainerNode !== null ) { this.__hasParentSettingsForm = true; switch (window.HaxStore.instance.activeContainerNode.tagName) { case "P": case "UL": case "OL": case "DIV": this.__parentName = "Text block settings"; break; case "GRID-PLATE": this.__parentName = "Layout settings"; break; default: this.__parentName = window.HaxStore.instance.activeContainerNode.tagName .replace("-", " ") .toLowerCase(); +" settings"; break; } } var item; // @todo kick stuff into the local dom as options for (var i = 0; i < settings.length; i++) { let setting = settings[i]; // create a new context item for the quick item = document.createElement("hax-context-item"); item.eventName = "hax-edit-property"; item.label = setting.title; item.options = setting.options; item.icon = setting.icon; item.inputMethod = setting.inputMethod; item.required = setting.required; item.options = setting.options; item.validation = setting.validation; item.validationType = setting.validationType; item.description = setting.description; // property or slot if it doesn't exist if (typeof setting.property !== typeof undefined) { item.propertyToBind = setting.property; } else if (typeof setting.attribute !== typeof undefined) { item.propertyToBind = setting.attribute; } else { item.slotToBind = setting.slot; } this.appendChild(item); } } } }
JavaScript
class TextureContainerEditor extends ContainerEditor { _renderNode($$, node) { if (!node) throw new Error("'node' is mandatory") let props = { node } let el let ComponentClass = this.getComponent(node.type, true) if (node.isText()) { if (ComponentClass) { el = $$(ComponentClass, props) } else { el = $$(this.getComponent('text-node'), props) } } else { if (ComponentClass) { if (ComponentClass.prototype._isCustomNodeComponent || ComponentClass.prototype._isIsolatedNodeComponent) { el = $$(ComponentClass, props) } else { el = $$(IsolatedNodeComponent, props) } } else { el = $$(this.getComponent('unsupported'), props) } } el.ref(node.id) return el } }
JavaScript
class TerminologyProvider { constructor(terminologyCollection, conceptCollection) { this.terminologyCollection = terminologyCollection this.conceptCollection = conceptCollection } /** * Return a Promise with an array of vocabularies. */ getVocabularies(req, res) { let query = req.query let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 let mongoQuery = {} if (query.uri) { mongoQuery = { $or: query.uri.split("|").map(uri => ({ uri })) } } let cursor = this.terminologyCollection.find(mongoQuery) return cursor.count().then(total => { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total }) return cursor.skip(offset).limit(limit).toArray() }) } /** * Return a Promise with an array of concept data. */ getDetails(req, res) { let query = req.query let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 if (!query.uri) { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total: 0 }) return Promise.resolve([]) } let mongoQuery = { $or: query.uri.split("|").map(uri => ({ uri })) } // Return results for both concepts and terminologies let cursor1 = this.conceptCollection.find(mongoQuery) let cursor2 = this.terminologyCollection.find(mongoQuery) return Promise.all([cursor1.count(), cursor2.count()]).then(totals => { let total = totals.reduce((t, c) => t + c) // Add headers util.setPaginationHeaders({ req, res, limit, offset, total }) return Promise.all([cursor1.skip(offset).limit(limit).toArray(), cursor2.skip(offset).limit(limit).toArray()]) }).then(results => { results = _.union(...results) return results }) } /** * Return a Promise with an array of concept data. */ getTop(req, res) { let query = req.query let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 let criteria if (query.uri) { criteria = { "topConceptOf.uri": query.uri } } else { // Search for all top concepts in all vocabularies criteria = { topConceptOf: { $exists: true } } } let cursor = this.conceptCollection.find(criteria) return cursor.count().then(total => { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total }) return cursor.skip(offset).limit(limit).toArray() }) } /** * Return a Promise with an array of concepts. */ getConcepts(req, res) { let query = req.query let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 let criteria = {} if (query.uri) { criteria = { "inScheme.uri": query.uri } } let cursor = this.conceptCollection.find(criteria) return cursor.count().then(total => { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total }) return cursor.skip(offset).limit(limit).toArray() }) } /** * Return a Promise with an array of concept data. */ getNarrower(req, res) { let query = req.query if (!query.uri) { return Promise.resolve([]) } let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 let uri = query.uri return this._getNarrower(uri).then(results => { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total: results.length }) return results.slice(offset, offset+limit) }) } // Internal function for getNarrower _getNarrower(uri) { return this.conceptCollection.find({ broader: { $elemMatch: { uri: uri } } }).toArray() } /** * Return a Promise with an array of concept data. */ getAncestors(req, res) { let query = req.query if (!query.uri) { return Promise.resolve([]) } let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 let uri = query.uri // First retrieve the concept object from database return this.conceptCollection.find({ uri: uri }) .toArray() .then(result => { if (!result.length) { return Promise.resolve(null) } let concept = result[0] if (concept.broader && concept.broader.length) { // Load next parent let parentUri = concept.broader[0].uri // Temporary fix for self-referencing broader parentUri = parentUri == uri ? (concept.broader[1] && concept.broader[1].uri) : parentUri if (!parentUri) { return Promise.resolve(null) } return this._getAncestors(parentUri).then(ancestors => { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total: ancestors.length }) return ancestors.slice(offset, offset+limit) }) } else { return Promise.resolve(null) } }).then(results => { if (results == null) { results = [] // Add headers util.setPaginationHeaders({ req, res, limit, offset, total: 0 }) } return results }) } // Internal function for getAncestors _getAncestors(uri) { return this.conceptCollection.find({ uri: uri }) .toArray() .then(result => { if (!result.length) { // URI not found in database return Promise.resolve([]) } let concept = result[0] if (concept.broader && concept.broader.length) { // Load next parent let parentUri = concept.broader[0].uri // Temporary fix for self-referencing broader parentUri = parentUri == uri ? (concept.broader[1] && concept.broader[1].uri) : parentUri if (!parentUri) { return Promise.resolve([concept]) } return this._getAncestors(parentUri).then(results => { return results.concat([concept]) }) } else { return Promise.resolve([concept]) } }) } /** * Return a Promise with suggestions, either in OpenSearch Suggest Format or JSKOS (?format=jskos). */ getSuggestions(req, res) { let query = req.query let search = query.search || "" let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 let format = query.format || "" return this.searchConcept(search, query.voc).then(results => { if (format.toLowerCase() == "jskos") { // Return in JSKOS format return results.slice(offset, offset+limit) } // Transform to OpenSearch Suggest Format let labels = [] let descriptions = [] let uris = [] let currentOffset = offset for (let result of results) { // Skip if offset is not reached if (currentOffset) { currentOffset -= 1 continue } // Skip if limit is reached if (labels.length >= limit) { break } let prefLabel = result.prefLabel ? (result.prefLabel.de || result.prefLabel.en || "") : "" labels.push(result.notation[0] + " " + prefLabel) // + " (" + result.priority + ")") descriptions.push("") uris.push(result.uri) } // Add headers util.setPaginationHeaders({ req, res, limit, offset, total: results.length }) return [ search, labels, descriptions, uris ] }).catch(error => { console.log("Error in getSuggestion:", error) return [] }) } /** * Return a Promise with an array of suggestions in JSKOS format. */ search(req, res) { let query = req.query let search = query.query || query.search || "" let limit = parseInt(query.limit) || 100 let offset = parseInt(query.offset) || 0 return this.searchConcept(search, query.voc).then(results => { // Add headers util.setPaginationHeaders({ req, res, limit, offset, total: results.length }) return results.slice(offset, offset+limit) }).catch(error => { console.log(error) return [] }) } searchConcept(search, voc) { // Don't try to search for an empty query if (!search.length) { return Promise.resolve([]) } let query, queryOr = [{ _id: search }] // let projectAndSort = {} if (search.length > 2) { // Use text search for queries longer than two characters queryOr.push({ $text: { $search: "\"" + search + "\"" } }) // Projekt and sort on text score // projectAndSort = { score: { $meta: "textScore" } } } if (search.length <= 2) { // Search for notations specifically for one or two characters queryOr.push({ _keywordsNotation: { $regex: "^" + search.toUpperCase() } }) } if (search.length > 1) { // Search _keywordsLabels // TODO: Rethink this approach. queryOr.push({ "_keywordsLabels": { $regex: "^" + search.toUpperCase() }}) } // Also search for exact matches with the URI (in field _id) query = { $or: queryOr } // Filter by scheme uri if (voc) { query = { $and: [query, { "inScheme.uri": voc } ] } } return this.conceptCollection.find(query) // .project(projectAndSort) // FIXME: Either test more and include, or remove completely // .sort(projectAndSort) // .limit(20000) .toArray() .then(results => { let _search = search.toUpperCase() // Prioritize results for (let result of results) { let priority = 100 if (result.notation && result.notation.length > 0) { let _notation = result.notation[0].toUpperCase() // Shorter notation equals higher priority priority -= _notation.length // Notation equals search means highest priority if (_search == _notation) { priority += 1000 } // Notation starts with serach means higher priority if (_notation.startsWith(_search)) { priority += 150 } } // prefLabel/altLabel equals search means very higher priority for (let [labelType, factor] of [["prefLabel", 2.0], ["altLabel", 1.0], ["creator.prefLabel", 0.8], ["definition", 0.7]]) { let labels = [] // Collect all labels for (let label of Object.values(_.get(result, labelType, {}))) { if (Array.isArray(label)) { labels = labels.concat(label) } else { labels.push(label) } } let matchCount = 0 let priorityDiff = 0 for (let label of labels) { let _label try { _label = label.toUpperCase() } catch(error) { console.log(label, error) continue } if (_search == _label) { priorityDiff += 100 matchCount += 1 } else if (_label.startsWith(_search)) { priorityDiff += 50 matchCount += 1 } else if (_label.indexOf(_search) > 0) { priorityDiff += 15 matchCount += 1 } } matchCount = Math.pow(matchCount, 2) || 1 priority += priorityDiff * (factor / matchCount) } result.priority = priority } // Sort results first by priority, then by notation results = results.sort((a, b) => { if (a.priority != b.priority) { return b.priority - a.priority } if (a.notation && a.notation.length && b.notation && b.notation.length) { if (b.notation[0] > a.notation[0]) { return -1 } else { return 1 } } else { return 0 } }) return results }).catch(error => { console.log("Error in searchConcept:", error) return [] }) } }
JavaScript
class ActionsOverview extends Component { constructor(props) { super(props); this.state = { severity: [], total: 0, category: [] }; } componentDidMount() { const response = { total: 9, severity: { info: 0, warn: 2, error: 3, critical: 4 }, category: { availability: 7, security: 2, stability: 4, performance: 10 } }; this.setState({ severity: [response.severity.info, response.severity.warn, response.severity.error, response.severity.critical] }); this.setState({ category: [response.category.availability, response.category.security, response.category.stability, response.category.performance] }); this.setState({ total: response.total }); } render() { let SummaryChartItems = []; for (let i = this.state.severity.length - 1; i >= 0; i--) { SummaryChartItems.push( <ConditionalLink key={i} condition={ this.state.severity[i] } wrap={children => <Link to= { `/actions/${sevNames[i].toLowerCase()}` }> {children} </Link> }> <SummaryChartItem name={ sevNames[i] } numIssues={ this.state.severity[i] } totalIssues={ this.state.total }/> </ConditionalLink> ); } let donutValues = []; let renderDonut = []; // Returns NaN while wating for data to load if (this.state.category[1]) { for (let i = 0; i <= this.state.category.length - 1; i++) { donutValues.push([typeNames[i], this.state.category[i]]); } renderDonut.push( <Donut key='advisor-donut' values={donutValues} totalLabel='issues' identifier='advisor-donut' withLegend/> ); } return ( <React.Fragment> <PageHeader> <PageHeaderTitle title='Actions'/> </PageHeader> <Section type='content'> <Grid gutter='md'> <GridItem span={4}> <Card> <CardHeader>Category Summary</CardHeader> <CardBody> { renderDonut } </CardBody> </Card> </GridItem> <GridItem span={4}> <Card> <CardHeader>Risk Summary</CardHeader> <CardBody> <SummaryChart> { SummaryChartItems } </SummaryChart> </CardBody> </Card> </GridItem> </Grid> </Section> </React.Fragment> ); } }
JavaScript
class CustomDocument extends next_document__WEBPACK_IMPORTED_MODULE_1__.default { static async getInitialProps(ctx) { return await next_document__WEBPACK_IMPORTED_MODULE_1__.default.getInitialProps(ctx); } render() { const { locale } = this.props.__NEXT_DATA__; if (false) {} return ( /*#__PURE__*/ // <Html dir={getDirection(locale)}> (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)(next_document__WEBPACK_IMPORTED_MODULE_1__.Html, { lang: "vi", children: [/*#__PURE__*/react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx(next_document__WEBPACK_IMPORTED_MODULE_1__.Head, {}), /*#__PURE__*/(0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("body", { children: [/*#__PURE__*/react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx(next_document__WEBPACK_IMPORTED_MODULE_1__.Main, {}), /*#__PURE__*/react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx(next_document__WEBPACK_IMPORTED_MODULE_1__.NextScript, {})] })] }) ); } }
JavaScript
class DirectoryElement { constructor(name, childDefinitions, parent, browser) { this.name = name; this.parent = parent; this.browser = browser; if(typeof(parent.id) === 'string' && parent.id.length > 0) this.id = parent.id + '/' + this.name; else this.id = this.name; this.selected = false; this.children = {}; if(childDefinitions !== undefined && typeof(childDefinitions) === 'object') { let childKeys = Object.keys(childDefinitions); for(var k=0; k<childKeys.length; k++) { let child = new DirectoryElement(childKeys[k], childDefinitions[childKeys[k]], this, this.browser); this.children[child.id] = child; } } this._setup_markup(); browser.registerElement(this); } _setup_markup() { let self = this; this.markup = $('<div class="file-directory-entry" id="'+this.id+'"></div>'); this.nameDiv = $('<div class="file-directory-entry-name">' + this.name + '</div>'); this.nameDiv.on('click', function() { self._entry_clicked(); }); if(Object.keys(this.children).length > 0) { this.childDiv = $('<div class="file-directory-entry-children"></div>'); for(var childKey in this.children) { this.childDiv.append(this.children[childKey].markup); } // add collapsible button let collapsible = $('<div class="file-directory-entry-collapsible">&#9654;</div>'); //TODO: symbol collapsible.on('click', function() { let rotationFactor = (self.childDiv.is(':visible') ? 0 : 90); self.childDiv.slideToggle(); $(this).css({ 'transform': 'rotate(' + rotationFactor + 'deg)'}) .css({ 'WebkitTransform': 'rotate(' + rotationFactor + 'deg)'}) .css({ '-moz-transform': 'rotate(' + rotationFactor + 'deg)'}); }); this.markup.append(collapsible); this.markup.append(this.nameDiv); this.markup.append(this.childDiv); } else { this.markup.append(this.nameDiv); } } _entry_clicked() { this.setSelected(!this.selected); this.browser.entrySelected(this, this.selected); } childSelected(selected) { if(selected) { // highlight this entry in a dim color this.nameDiv.addClass('file-directory-highlighted-weak'); this.nameDiv.removeClass('file-directory-highlighted'); this.selected = false; } else { this.nameDiv.removeClass('file-directory-highlighted-weak'); } this.parent.childSelected(selected); } setSelected(selected) { this.selected = selected; if(this.selected) { this.nameDiv.addClass('file-directory-highlighted'); } else { this.nameDiv.removeClass('file-directory-highlighted'); } this.parent.childSelected(this.selected); } }
JavaScript
class Element{ constructor(tag, attributes){ let element = document.createElement(tag); this.element = element; if(attributes) this.attribute(attributes); return this; } attribute(attributes, value){ if(typeof attributes == "string") this.attribute({attributes: value}); else { for(let attr in attributes){ if(['html', 'text'].includes(attr)){ if(attr == 'html') this.element.innerHTML = attributes[attr]; else this.element.innerText = attributes[attr]; } else this.element.setAttribute(attr, attributes[attr]); } } return this; } event(...args){ if( args.length == 2 && typeof args[0] == "string" && typeof args[1] == "function" ) this.element.addEventListener(args[0], args[1]); else for(let i = 0; i < args.length; i ++){ const arg = args[i]; if( !Array.isArray(arg) || typeof arg[1] != "function" || typeof arg[0] != "string" ) throw new Error('Cannot process given argument at position ' + (i + 1)); this.element.addEventListener(arg[0], arg[1]); } return this; } childs(...childs){ if(!Array.isArray(childs)) childs = Array(childs); for(let child of childs){ if(child instanceof Element || child.constructor.name == 'Progress'){ this.element.appendChild(child.element); } else this.element.appendChild(child); } return this; } }
JavaScript
class Postgres extends events.EventEmitter { /** * Get a function that takes chunks of stdin data, aggregates it, and passes * it in complete lines, one by one, to a given {@link Postgres~callback}. * @argument {Postgres~callback} callback * @return {Function} */ static getTextLineAggregator(callback) { let buffer = ''; return (data) => { const fragments = data.toString().split(regExp.newline); const lines = fragments.slice(0, fragments.length - 1); // If there was an unended line in the previous dump, complete it by // the first section. lines[0] = buffer + lines[0]; // If there is an unended line in this dump, store it to be completed by // the next. This assumes there will be a terminating newline character // at some point. Generally, this is a safe assumption. buffer = fragments[fragments.length - 1]; for (let line of lines) { callback(line); } }; } /** * Populate a given {@link Postgres~Config} with values from a * given {@link Postgres~Config}. * @protected * @argument {Postgres~Config} source * @argument {Postgres~Config} target * @return {Postgres~Config} */ static parseConfig(source, target) { if (target == null) { target = Object.create(null); } if (typeof source === 'string') { target.datadir = source; return target; } if (source == null || typeof source !== 'object') { return target; } if (source.bin != null) { target.bin = source.bin; } if (source.shutdown != null) { target.shutdown = source.shutdown; } if (source.conf != null) { target.conf = source.conf; return target; } if (source.datadir != null) { target.datadir = source.datadir; } if (source.port != null) { target.port = source.port; } return target; } /** * Parse process flags for PostgreSQL from a given {@link Postgres~Config}. * @protected * @argument {Postgres~Config} config * @return {Array.<String>} */ static parseFlags(config) { if (config.conf != null) { return ['-c', `config_file=${config.conf}`]; } const flags = []; if (config.datadir != null) { flags.push('-D', config.datadir); } if (config.port != null) { flags.push('-p', config.port); } return flags; } /** * Parse Redis server output for terminal messages. * @protected * @argument {String} string * @return {Object} */ static parseData(string) { const matches = regExp.terminalMessage.exec(string); if (matches === null) { return null; } const result = { err: null, key: matches .pop() .replace(regExp.nonAlpha, '') .toLowerCase() }; switch (result.key) { case 'readytoaccept': break; case 'alreadyinuse': result.err = new Error('Address already in use'); result.err.code = -1; break; case 'denied': result.err = new Error('Permission denied'); result.err.code = -2; break; case 'postgres': case 'fatal': { const matches = regExp.errorMessage.exec(string); result.err = new Error( matches === null ? string : matches.pop() ); result.err.code = -3; break; } } return result; } /** * Start a given {@linkcode server}. * @protected * @fires Postgres#stdout * @fires Postgres#opening * @fires Postgres#open * @fires Postgres#closing * @fires Postgres#close * @argument {Postgres} server * @return {Promise} */ static open(server) { if (server.isOpening) { return server.openPromise; } server.isOpening = true; server.isClosing = false; server.openPromise = server.promiseQueue.add(() => { if (server.isClosing || server.isRunning) { server.isOpening = false; return Promise.resolve(null); } return new Promise((resolve, reject) => { /** * A listener for the current server process' stdout that resolves or * rejects the current {@link Promise} when done. * @see Postgres.getTextLineAggregator * @see Postgres.parseData * @argument {Buffer} buffer * @return {undefined} */ const dataListener = Postgres.getTextLineAggregator((string) => { const result = Postgres.parseData(string); if (result === null) { return; } server.process.stdout.removeListener('data', dataListener); server.process.stderr.removeListener('data', dataListener); server.isOpening = false; if (result.err === null) { server.isRunning = true; server.emit('open'); resolve(null); } else { server.isClosing = true; server.emit('closing'); server.process.once('close', () => reject(result.err)); } }); /** * A listener to close the server when the current process exits. * @return {undefined} */ const exitListener = () => { // istanbul ignore next server.close(); }; /** * Get a text line aggregator that emits a given {@linkcode event} * for the current server. * @see Postgres.getTextLineAggregator * @argument {String} event * @return {Function} */ const getDataPropagator = (event) => Postgres.getTextLineAggregator((line) => server.emit(event, line)); server.emit('opening'); const flags = Postgres.parseFlags(server.config); flags.push('-c', `unix_socket_directories=${__dirname}`); server.process = childprocess.spawn(server.config.bin, flags); server.process.stderr.on('data', dataListener); server.process.stderr.on('data', getDataPropagator('stdout')); server.process.stdout.on('data', dataListener); server.process.stdout.on('data', getDataPropagator('stdout')); server.process.on('close', () => { server.process = null; server.isRunning = false; server.isClosing = false; process.removeListener('exit', exitListener); server.emit('close'); }); process.on('exit', exitListener); }); }); return server.openPromise; } /** * Stop a given {@linkcode server}. * @protected * @fires Postgres#closing * @argument {Postgres} server * @return {Promise} */ static close(server) { if (server.isClosing) { return server.closePromise; } server.isClosing = true; server.isOpening = false; server.closePromise = server.promiseQueue.add(() => { if (server.isOpening || !server.isRunning) { server.isClosing = false; return Promise.resolve(null); } return new Promise((resolve) => { server.emit('closing'); server.process.once('close', () => resolve(null)); let signal = server.config.shutdown; switch (server.config.shutdown) { case 'smart': signal = 'SIGTERM'; break; case 'fast': signal = 'SIGINT'; break; case 'immediate': signal = 'SIGQUIT'; break; } server.process.kill(signal); }); }); return server.closePromise; } /** * Construct a new {@link Postgres}. * @argument {(Number|String|Postgres~Config)} [configOrDataDir] * A number or string that is a port or an object for configuration. */ constructor(configOrDataDir) { super(); /** * Configuration options. * @protected * @type {Postgres~Config} */ this.config = Postgres.parseConfig(configOrDataDir, { bin: 'postgres', conf: null, port: 5432, datadir: null, shutdown: 'fast' }); /** * The current process. * @protected * @type {ChildProcess} */ this.process = null; /** * The last {@link Promise} returned by {@link Postgres#open}. * @protected * @type {Promise} */ this.openPromise = Promise.resolve(null); /** * The last {@link Promise} returned by {@link Postgres#close}. * @protected * @type {Promise} */ this.closePromise = Promise.resolve(null); /** * A serial queue of open and close promises. * @protected * @type {PromiseQueue} */ this.promiseQueue = new PromiseQueue(1); /** * Determine if the instance is closing a PostgreSQL server; {@linkcode true} * while a process is being, or about to be, killed until the * contained PostgreSQL server either closes or errs. * @readonly * @type {Boolean} */ this.isClosing = false; /** * Determine if the instance is starting a PostgreSQL server; {@linkcode true} * while a process is spawning, or about tobe spawned, until the * contained PostgreSQL server either starts or errs. * @readonly * @type {Boolean} */ this.isRunning = false; /** * Determine if the instance is running a PostgreSQL server; {@linkcode true} * once a process has spawned and the contained PostgreSQL server is ready * to service requests. * @readonly * @type {Boolean} */ this.isOpening = false; } /** * Open the server. * @argument {Postgres~callback} [callback] * @return {Promise} */ open(callback) { const promise = Postgres.open(this); return typeof callback === 'function' ? promise .then((v) => callback(null, v)) .catch((e) => callback(e, null)) : promise; } /** * Close the server. * @argument {Postgres~callback} [callback] * @return {Promise} */ close(callback) { const promise = Postgres.close(this); return typeof callback === 'function' ? promise .then((v) => callback(null, v)) .catch((e) => callback(e, null)) : promise; } }
JavaScript
class Currency { /** * Creates a new Currency instance. * * @param {Number|String|BigNumber|Currency} value */ constructor(value) { let pasc = value; if (pasc instanceof Currency) { this[P_VALUE] = pasc.value; return; } if (BN.isBN(pasc)) { this[P_VALUE] = pasc; return; } pasc = pasc.toString(); pasc = pasc.split(',').join(''); // remove commas // now split the '.' const ten = new BN(10); const base = ten.pow(new BN(4)); // Is it negative? let negative = (pasc.substring(0, 1) === '-'); if (negative) { pasc = pasc.substring(1); } if (pasc === '.') { throw new Error( `Invalid value ${pasc} cannot be converted to` + ' base unit with 4 decimals.'); } // Split it into a whole and fractional part let comps = pasc.split('.'); if (comps.length > 2) { throw new Error('Too many decimal points'); } let whole = comps[0], fraction = comps[1]; if (!whole) { whole = '0'; } if (!fraction) { fraction = '0'; } if (fraction.length > 4) { throw new Error('Too many decimal places'); } while (fraction.length < 4) { fraction += '0'; } whole = new BN(whole); fraction = new BN(fraction); let molina = (whole.mul(base)).add(fraction); if (negative) { molina = molina.neg(); } this[P_VALUE] = new BN(molina.toString(10), 10); } static fromMolina(molina) { return new Currency( new BN(molina.toString()) ); } /** * Gets the BigNumber instance. * * @returns {BigNumber} */ get value() { return this[P_VALUE]; } /** * Gets the pascal value as a string. * * @returns {string} */ toString() { return toFixed(this[P_VALUE]); } /** * Gets a value indicating that the current value has more decimals than * allowed. */ isVague() { return this.toStringOpt(5) !== this.toStringOpt(4); } /** * Gets an optimized pascal value with less zeros as possible. * * @returns {string} */ toStringOpt(decimals = 4) { return toFixed(this[P_VALUE]) .replace(new RegExp('[0]+$'), '') .replace(new RegExp('[\.]+$'), ''); } /** * Gets the pascal value as a string. * * @returns {Number} */ toMolina() { return this[P_VALUE].toString(); } /** * Adds the given value to the current value and returns a **new** * value. * * @param {Number|String|BigNumber|Currency} addValue * @returns {Currency} */ add(addValue) { return new Currency( this.value.add(new Currency(addValue).value), ); } /** * Adds the given value to the current value and returns a **new** * value. * * @param {Number|String|BigNumber|Currency} addValue * @returns {Currency} */ mul(val) { return Currency.fromMolina( this.value.mul(new BN(val)) ); } /** * Subtracts the given value from the current value and returns a * **new** value. * * @param {Currency} subValue * @returns {Currency} */ sub(subValue) { return new Currency( this.value.sub(new Currency(subValue).value) ); } /** * Gets a positive variant of the value. If the value is already * positive, the current instance will be returned, else a new * instance. * * @returns {Currency} */ toPositive() { if (this[P_VALUE].isNeg() === true) { return new Currency( this[P_VALUE].neg(), ); } return this; } /** * Gets a value indicating whether the given value is equal to the current * value. * * @param {Number|String|BigNumber|Currency} value * @returns {boolean} */ eq(value) { return this[P_VALUE].eq(new Currency(value).value); } /** * Gets a value indicating whether the given value is greater than the current * value. * * @param {Number|String|BigNumber|Currency} value * @returns {boolean} */ gt(value) { return this[P_VALUE].gt(new Currency(value).value); } /** * Gets a value indicating whether the given value is lower than the current * value. * * @param {Number|String|BigNumber|Currency} value * @returns {boolean} */ lt(value) { return this[P_VALUE].lt(new Currency(value).value); } /** * Gets a value indicating whether the given value is lower or equal to the * current value. * * @param {Number|String|BigNumber|Currency} value * @returns {boolean} */ lteq(value) { return this[P_VALUE].lte(new Currency(value).value); } /** * Gets a value indicating whether the given value is greater or equal to the * current value. * * @param {Number|String|BigNumber|Currency} value * @returns {boolean} */ gteq(value) { return this[P_VALUE].gte(new Currency(value).value); } get bn() { return this[P_VALUE]; } /** * Gets the serialized version of this instance. * * @returns {Object} */ serialize() { return { pascal: this.toStringOpt(), molina: this.toMolina() }; } }
JavaScript
class ProductsService { constructor() { this.products = [] this.generate() } generate() { const limit = 100 for (let i = 0; i < limit; i++) { this.products.push({ id: faker.datatype.uuid(), name: faker.commerce.productName(), price: parseInt(faker.commerce.price(), 10), image: faker.image.imageUrl(), isBlocked: faker.datatype.boolean() }) } } async create(data) { const newProduct = { id: faker.datatype.uuid(), ...data } this.products.push(newProduct) return newProduct } async find() { const users = await User.findAll() // const rta = await client.query("SELECT * FROM tasks") // const products = this.products // if(!products.length) throw boom.notFound('Product not found') return users } async findOne(id) { const product = this.products.find(item => item.id === id) if (!product) throw boom.notFound('Product not found') if (!product.isBlocked) throw boom.conflict('Product is blocked') return product } async update(id, changes) { const index = this.products.findIndex(item => item.id === id) if (index === -1) throw boom.notFound('Product not found') const newProduct = Object.assign(this.products[index], changes) this.products[index] = newProduct return this.products[index] } async delete(id) { const index = this.products.findIndex(item => item.id === id) if (index === -1) throw boom.notFound('Product not found') await this.products.splice(index, 1) return id } }
JavaScript
class NpmOutdated { /** * init the package */ constructor() { /** * all possible options * @type {Object} */ this.config = configJson; /** * map of created npm handler * @type {Object} */ this.npmHandlers = {}; } /** * activate npmHandler for each project in atom */ activate() { this.disposables = new CompositeDisposable(); this.disposables.add( atom.config.observe('npm-outdated', (value) => { this.settings = value; lodash.forEach(this.npmHandlers, (npmHandler) => npmHandler.updateSettings(this.settings)); }) ); this.handleProjectPaths(atom.project.getPaths()); this.disposables.add(atom.project.onDidChangePaths((projectPaths) => this.handleProjectPaths(projectPaths))); this.disposables.add( atom.commands.add('atom-workspace', 'npm-outdated', () => this.checkNpmHandlers() ) ); this.disposables.add( atom.commands.add('atom-workspace', 'npm-outdated:disable', () => this.disposeNpmHandlers() ) ); this.disposables.add( atom.commands.add('atom-workspace', 'npm-outdated:enable', () => this.handleProjectPaths(atom.project.getPaths()) ) ); } /** * iterate the list of project paths and attach watcher to new project paths * @param {array} projectPaths array of project paths */ handleProjectPaths(projectPaths) { lodash.forEach(projectPaths, projectPath => { if (!this.npmHandlers[projectPath]) { const npmHandler = this.createWatcher(projectPath); if (npmHandler) { this.npmHandlers[projectPath] = npmHandler; } } lodash.pull(this.prevProjectPaths, projectPath); }); lodash.forEach(this.prevProjectPaths, projectPath => { const npmHandler = this.npmHandlers[projectPath]; if (npmHandler) { npmHandler.dispose(); delete this.npmHandlers[projectPath]; } }); this.prevProjectPaths = projectPaths; } /** * search for package.json in project path and attach file watcher * @param {string} projectPath project path * @returns {npmHandler} create handler for file */ createWatcher(projectPath) { const packagePath = path.join(projectPath, 'package.json'); if (fs.existsSync(packagePath)) { return new npmHandler(packagePath, this.settings); } return null; } /** * check all npm handlers */ checkNpmHandlers() { lodash.forEach(this.npmHandlers, (npmHandler) => npmHandler.check()); } /** * dispose npm handlers */ disposeNpmHandlers() { lodash.forEach(this.npmHandlers, (npmHandler) => npmHandler.dispose()); this.npmHandlers = {}; } /** * deactivate all file watcher */ deactivate() { this.disposeNpmHandlers(); this.disposables.clear(); } }
JavaScript
class Cloud { /** * @param {Vector2} offsetFromParent * @param {Property.<Vector2>} parentPositionProperty */ constructor( offsetFromParent, parentPositionProperty ) { // @public {NumberProperty} - existence strength, which basically translates to opacity, of the cloud this.existenceStrengthProperty = new NumberProperty( 1, { range: new Range( 0, 1 ) } ); // @public (read-only) {number} - offset position for this cloud this.offsetFromParent = offsetFromParent; // @private {number} - used to calculate this cloud's position this.parentPositionProperty = parentPositionProperty; // @private {Shape|null} - the ellipse that defines the shape of this cloud. only null until the parent position // is linked this.cloudEllipse = null; this.parentPositionProperty.link( parentPosition => { const center = parentPosition.plus( this.offsetFromParent ); this.cloudEllipse = Shape.ellipse( center.x, center.y, WIDTH / 2, HEIGHT / 2, 0, 0, 0, false ); } ); } /** * return ellipse with size of this cloud * @returns {Shape.ellipse} - ellipse with axes sized to width and height of cloud * @public */ getCloudAbsorptionReflectionShape() { return this.cloudEllipse; } /** * @returns {Vector2} Center position of cloud * @public */ getCenterPosition() { return this.parentPositionProperty.get().plus( this.offsetFromParent ); } }
JavaScript
class IncomingRoomKeyRequestCancellation { constructor(event) { const content = event.getContent(); this.userId = event.getSender(); this.deviceId = content.requesting_device_id; this.requestId = content.request_id; } }
JavaScript
class Controllers { // 已经确认由于 NodeBB 的 Express 的原因, 会导致中间件已经书写头, 造成错误, 故暂时移除此处的重写 renderAdminPage(req, res) { /* 请确保你的路由地址能和模板路径能够对应。 例如, 如果你的站点地址为: myforum.com/some/complex/route/ 你的模板地址应该为: templates/some/complex/route.tpl 并且你应该这样来渲染它: res.render('some/complex/route'); */ res.render('admin/plugins/dipperinAdmin', {}) /* 使用回调方式中的 next(err, data) 方法。 传递数据: return '数据' 传递错误: throw new Error('错误') */ } /* load () { // 转换所有内部方法为回调方式 const methods = Object.getOwnPropertyNames(Object.getPrototypeOf(this)) _.pull(methods, 'constructor', 'load') // _.pull(methods, 'prototype', 'length', 'name', 'load') const target = {} for (let method of methods) { target[method] = callbackify(this[method]) } return target } */ renderDipperin(req, res) { const data = {} data.uid = req.uid data.loggedIn = req.loggedIn data.route = req.route console.log('dipperin:', data) res.render('account/plugins/dipperin', data) } }
JavaScript
class DSA_Laravel extends DSA_Base { /** * @inheritdoc */ constructor(settings = {}) { settings.inputId = settings.inputId || 'dsa_laravel_search_input'; settings.searchUrl = settings.searchUrl || 'https://bh4d9od16a-dsn.algolia.net/1/indexes/laravel/query?x-algolia-agent=Algolia%20for%20JavaScript%20(4.6.0)%3B%20Browser%20(lite)&x-algolia-api-key=7dc4fe97e150304d1bf34f5043f178c4&x-algolia-application-id=BH4D9OD16A'; settings.docsVersion = settings.docsVersion || 'master'; super(settings); } /** * @inheritdoc */ search(searchQuery) { let searchData = { 'query': encodeURIComponent(searchQuery), 'hitsPerPage': 5, 'facetFilters': ['version:' + this.docsVersion] }; this.sendPost(this.searchUrl, JSON.stringify(searchData)); } /** * @inheritdoc */ getResultItemsHtml(data) { var self = this; if (!data.hits || !data.hits.length) { return ( '<a href="' + self.getFallbackSearchLink('Laravel ' + self._searchInput.value) + '" class="' + self.resultsItemClass + ' ' + self.noResultsItemClass + '" target="_blank">' + self.noResultsMessage + '&nbsp;' + '<span class="dsa-search-result-accent">' + self.falbackSearchMessage +'</span>' + '</a>' ); } var resultItems = ''; for (let i in data.hits) { let url = data.hits[i].url; let content = data.hits[i]._highlightResult?.content; let matchData = data.hits[i]._highlightResult?.hierarchy_camel?.[0] || data.hits[i]._highlightResult?.hierarchy; if (!matchData) { continue; } resultItems += '<a href="' + url + '" class="' + self.resultsItemClass + '" target="_blank">'; if (matchData.lvl0) { resultItems += '<div class="dsa-search-result-title">' + matchData.lvl0.value + '</div>'; } resultItems += '<div class="dsa-search-result-item-sub-section">'; if (matchData.lvl1) { resultItems += '<div class="dsa-search-result-h2"><span class="dsa-search-result-accent">#</span>&nbsp;' + matchData.lvl1.value + '</div>'; } if (matchData.lvl2) { resultItems += '<div class="dsa-search-result-h2">&nbsp;&gt;&nbsp;' + matchData.lvl2.value + '</div>'; } if (matchData.lvl3) { resultItems += '<div class="dsa-search-result-h2">&nbsp;&gt;&nbsp;' + matchData.lvl3.value + '</div>'; } resultItems += '</div>'; if (content) { resultItems += '<div class="dsa-search-result-item-content">' + content.value + '</div>'; } resultItems += '</a>'; } return resultItems; } }
JavaScript
class DependencyAnalyser { constructor(options) { this.options = options; this.countService = new countService_1.CountService(this); // read package.json this.packageJson = JSON.parse(fs.readFileSync(path.join(options.rootDir, "package.json"), "utf-8")); // get all files to scan const allFiles = this.getAllFiles(options.scanDir); this.allFiles = allFiles.filesArray; this.filesObject = allFiles.filesObject; } get allFiles() { return this._allFiles; } set allFiles(value) { this._allFiles = value; } get filesObject() { return this._filesObject; } set filesObject(value) { this._filesObject = value; } get importScannerMap() { return this._importScannerMap; } set importScannerMap(value) { this._importScannerMap = value; } get countService() { return this._countService; } set countService(value) { this._countService = value; } get options() { return this._options; } set options(value) { this._options = value; } get packageJson() { return this._packageJson; } set packageJson(value) { this._packageJson = value; } /** * Scans the given given directory path and returns an object * with all filtered Files as array and as an object tree. * @param scanDir Path to a File or Directory to be scanned */ getAllFiles(scanDir) { const options = this.options; const filesArray = []; let filesObject; if (fs.existsSync(scanDir)) { const lstatSync = fs.lstatSync(scanDir); if (lstatSync.isDirectory()) { filesObject = getAllFilesRek(scanDir); } else if (lstatSync.isFile()) { if (options.fileExtensionFilter.some(value => path.parse(scanDir).ext === value)) { const _filesObject = {}; _filesObject[scanDir] = null; return { "filesArray": [scanDir], "filesObject": _filesObject }; } else { throw new Error("The given file is not a .ts File: " + scanDir); } } else { throw new Error("Scan path is not a file nor a directory: " + scanDir); } } return { "filesArray": filesArray, "filesObject": filesObject }; function getAllFilesRek(directory) { const directoryItems = fs.readdirSync(directory); const filesObj = {}; if (options.exclude.some(value => directory.match(value))) return null; directoryItems.forEach(value => { const fileName = path.join(directory, value); const lstatSync = fs.lstatSync(fileName); if (lstatSync.isDirectory()) { const children = getAllFilesRek(fileName); filesObj[fileName] = children ? { children: children } : {}; } else if (lstatSync.isFile()) { if (options.fileExtensionFilter.some(fileExtension => path.parse(fileName).ext === fileExtension)) { filesObj[fileName] = null; filesArray.push(fileName); } } }); return filesObj; } } /** * Scans all found files with ImportScanner */ scanAllFiles() { this.importScannerMap = new Map(); if (this.allFiles.length === 0) { throw new Error("No files to scan found."); } this.allFiles.forEach(fileName => { const sourceFile = ts.createSourceFile(fileName, // fileName fs.readFileSync(fileName, 'utf8'), // sourceText ts.ScriptTarget.Latest); const importScanner = new importService_1.ImportScanner(this, fileName, sourceFile); this.importScannerMap.set(fileName, importScanner); }); } /** * @link OutputGenerator#generateHTML */ generateOutput() { this.countService.outputGenerator.generateHTML(); } }
JavaScript
class PDP11 extends PDP11Ops { /** * PDP11(idMachine, idDevice, config) * * The PDP11 class supports the following config properties: * * model: a number (eg, 1170) that should match one of the PDP11.MODEL_* values * addrReset: reset address (default is 0) * * After looking over the timings of PDP-11/70 instructions, nearly all of them appear * to be multiples of 150ns. So that's what we'll consider a cycle. How many 150ns are * in one second? Approximately 6666667. So by way of comparison to other PCjs machines, * that makes the PDP-11 (or at least the PDP-11/70) look like a 6.67Mhz machine. * * I've started with the PDP-11/70, since that's what Paul Nankervis started with. When * I go back and add support for earlier PDP-11 models (primarily by neutering functions * that didn't exist), I will no doubt have to tweak some instruction cycle counts, too. * * Examples of operations that take 1 extra cycle (150ns): single and double operand byte * instructions with an odd address (except MOV/MTPI/MTPD/JMP/JRS), ADD/SUB/BIC/BIS/MOVB/CMP/BIT * instructions with src of R1-R7 and dst of R6-R7, RORB/ASRB with an odd address, and each * shift of ASH/ASHC. As you can see, the rules are not simple. * * We're not simulating cache hardware, but our timings should be optimistic and assume 100% * cache hits; for cache hits, each read cycle is 300ns. As for write cycles, they are always * 750ns. My initial take on DEC's timings is that they are including the write time as part * of the total EF (execute/fetch) time. So, for instructions that write to memory, it looks * like we'll normally need to add 5 cycles (750/150) to the instruction's base time, but * we'll need to keep an eye out for exceptions. * * @this {PDP11} * @param {string} idMachine * @param {string} idDevice * @param {Config} [config] */ constructor(idMachine, idDevice, config) { super(idMachine, idDevice, config); this.model = +this.config['model'] || PDP11.MODEL_1170; this.addrReset = +this.config['addrReset'] || 0; /* * Get access to the Bus device and create an IOPage block for it. We assume that the bus * has been defined with an 8K blockSize and an 8-bit dataWidth, because our buses are defined * in terms of their MINIMUM data size, not their maximum. All read/write operations must be * some multiple of that minimum (usually 1, 2, or 4), hence the readData()/writeData(), * readPair()/writePair(), and readQuad()/writeQuad() bus interfaces. */ this.bus = /** @type {Bus} */ (this.findDeviceByClass("Bus")); this.bus.setFaultHandler(this.fault.bind(this)); this.blockIOPage = /** @type {IOPage} */ (this.findDeviceByClass("IOPage")); this.panel = /** @type {Device} */ (this.findDeviceByClass("Panel", false)); /* * We also need some IOPage bookkeeping variables, such as the current IOPage address * and the previous block (if any) at that address. */ this.addrIOPage = 0; this.blockIOPagePrev = null; /* * Get access to the Input device, so we can call setFocus() as needed. */ this.input = /** @type {Input} */ (this.findDeviceByClass("Input", false)); /* * Initialize processor operation to match the requested model. * * offRegSrc is a bias added to the register index calculated in readSrcWord() and readSrcByte(), * and by default has no effect on the register index, UNLESS this is a PDP-11/20, in which case the * bias is changed to 8 and we return one of the negative values you see above. Those negative values * act as signals to writeDstWord() and writeDstByte(), effectively delaying evaluation of the register * until then. */ this.offRegSrc = 0; this.maskRegSrcByte = 0xff; if (this.model <= PDP11.MODEL_1120) { this.opDecode = PDP11.op1120.bind(this); this.checkStackLimit = this.checkStackLimit1120; this.offRegSrc = 8; this.maskRegSrcByte = -1; this.pswUsed = ~(PDP11.PSW.UNUSED | PDP11.PSW.REGSET | PDP11.PSW.PMODE | PDP11.PSW.CMODE) & 0xffff; this.pswRegSet = 0; } else { this.opDecode = PDP11.op1140.bind(this); this.checkStackLimit = this.checkStackLimit1140; /* * The alternate register set (REGSET) doesn't exist on the 11/20 or 11/40; it's available on the 11/45 and 11/70. * Ditto for separate I/D spaces, SUPER mode, and the instructions MFPD, MTPD, and SPL. */ this.pswUsed = ~(PDP11.PSW.UNUSED | (this.model <= PDP11.MODEL_1140? PDP11.PSW.REGSET : 0)) & 0xffff; this.pswRegSet = (this.model > PDP11.MODEL_1140? PDP11.PSW.REGSET : 0); } this.nDisableTraps = 0; this.trapVector = this.trapReason = 0; /** @type {IRQ|null} */ this.irqNext = null; // the head of the active IRQ list, in priority order /** @type {Array.<IRQ>} */ this.aIRQs = []; // list of all IRQs, active or not (to be used for auto-configuration) this.srcMode = this.srcReg = 0; this.dstMode = this.dstReg = this.dstAddr = 0; this.nReadBreaks = this.nWriteBreaks = 0; /* * We can now initialize the CPU. */ this.initCPU(); } /** * execute(nCycles) * * Called from startClock() to execute a series of instructions. * * Executes the specified "burst" of instructions. This code exists outside of the startClock() function * to ensure that its try/catch exception handler doesn't interfere with the optimization of this tight loop. * * @this {PDP11} * @param {number} nCycles */ execute(nCycles) { } /** * initCPU() * * Initializes the CPU's state. * * @this {PDP11} */ initCPU() { /* * TODO: Verify the initial state of all PDP-11 flags and registers (are they well-documented?) */ let f = 0xffff; this.flagC = 0x10000; // PSW C bit this.flagV = 0x8000; // PSW V bit this.flagZ = f; // PSW Z bit (TODO: Why do we clear instead of set Z, like other flags?) this.flagN = 0x8000; // PSW N bit this.regPSW = 0x000f; // PSW other bits (TODO: What's the point of setting the flag bits here, too?) this.regsGen = [ // General R0-R7 0, 0, 0, 0, 0, 0, 0, this.addrReset, -1, -2, -3, -4, -5, -6, -7, -8 ]; this.regsAlt = [ // Alternate R0-R5 0, 0, 0, 0, 0, 0 ]; this.regsAltStack = [ // Alternate R6 stack pointers (KERNEL, SUPER, UNUSED, USER) 0, 0, 0, 0 ]; this.regsPAR = [ // memory management PAR registers by mode [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // KERNEL (8 KIPAR regs followed by 8 KDPAR regs) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // SUPER (8 SIPDR regs followed by 8 SDPDR regs) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // mode 2 (not used) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // USER (8 UIPDR regs followed by 8 UDPDR regs) ]; this.regsPDR = [ // memory management PDR registers by mode [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // KERNEL (8 KIPDR regs followed by 8 KDPDR regs) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], // SUPER (8 SIPDR regs followed by 8 SDPDR regs) [f, f, f, f, f, f, f, f, f, f, f, f, f, f, f, f], // mode 2 (not used) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // USER (8 UIPDR regs followed by 8 UDPDR regs) ]; this.regsUNIMap = [ // 32 UNIBUS map registers 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; this.regsControl = [ // various control registers (177740-177756) we don't really care about 0, 0, 0, 0, 0, 0, 0, 0 ]; this.pswMode = 0; // current memory management mode (see PDP11.MODE.KERNEL | SUPER | UNUSED | USER) this.pswTrap = -1; this.regMBR = 0; /* * opFlags contains various conditions that stepCPU() needs to be aware of. */ this.opFlags = 0; /* * srcMode and srcReg are set by SRCMODE decodes, and dstMode and dstReg are set for DSTMODE decodes, * indicating to the opcode handlers the mode(s) and register(s) used as part of the current opcode, so * that they can calculate the correct number of cycles. dstAddr is set for byte operations that also * need to know the effective address for their cycle calculation. */ this.srcMode = this.srcReg = 0; this.dstMode = this.dstReg = this.dstAddr = 0; this.initMMU(); for (let i = 0; i <= 7; i++) { this.defineRegister("R"+i, () => this.regsGen[i], (value) => this.regsGen[i] = value & 0xffff); } this.defineRegisterAlias("R6", "SP"); this.defineRegisterAlias("R7", Debugger.REGISTER.PC); this.defineRegister("CF", () => (this.getCF()? 1 : 0), (value) => {value? this.setCF() : this.clearCF()}); this.defineRegister("NF", () => (this.getNF()? 1 : 0), (value) => {value? this.setNF() : this.clearNF()}); this.defineRegister("VF", () => (this.getVF()? 1 : 0), (value) => {value? this.setVF() : this.clearVF()}); this.defineRegister("ZF", () => (this.getZF()? 1 : 0), (value) => {value? this.setZF() : this.clearZF()}); this.defineRegister("PS", () => this.getPSW(), (value) => this.setPSW(value)); this.defineRegister("PI", () => this.getPIR(), (value) => this.setPIR(value)); this.defineRegister("ER", () => this.regErr); this.defineRegister("SL", () => this.getSLR(), (value) => this.setSLR(value)); this.defineRegister("M0", () => this.getMMR0(), (value) => this.setMMR0(value)); this.defineRegister("M1", () => this.getMMR1()); this.defineRegister("M2", () => this.getMMR2()); this.defineRegister("M3", () => this.getMMR3(), (value) => this.setMMR3(value)); // if (this.panel) { // this.defineRegister("AR", () => this.panel.getAR(), (value) => this.panel.setAR(value)); // this.defineRegister("DR", () => this.panel.getDR(), (value) => this.panel.setDR(value)); // this.defineRegister("SR", () => this.panel.getSR(), (value) => this.panel.setSR(value)); // } } /** * initMMU() * * Reset all registers required as part of a RESET instruction. * * TODO: Do we ever need to automatically clear regErr, or is it cleared manually? * * @this {PDP11} */ initMMU() { this.regMMR0 = 0; // 177572 this.regMMR1 = 0; // 177574 this.regMMR2 = 0; // 177576 this.regMMR3 = 0; // 172516 this.regErr = 0; // 177766 this.regPIR = 0; // 177772 this.regSLR = 0xff; // 177774 this.mmuEnable = 0; // MMU enabled for PDP11.ACCESS.READ or PDP11.ACCESS.WRITE this.mmuLastMode = 0; this.mmuLastPage = 0; this.mmuMask = 0x3ffff; this.mapMMR3 = [4,2,0,1]; // map from mode to MMR3 I/D bit /* * This is queried and displayed by the Panel when it's not displaying its own ADDRESS register * (which takes precedence when, for example, you've manually halted the CPU and are independently * examining the contents of other addresses). * * We initialize it to whatever the current PC is, because according to @paulnank's pdp11.js: "Reset * displays next instruction address" and initMMU() is called on a RESET. */ this.addrLast = this.regsGen[7]; /* * This stores the PC in the lower 16 bits, and any auto-incs or auto-decs from the last opcode in the * upper 16 bits; the lower 16 bits are used to update MMR2, and the upper 16 bits are used to update MMR1. * The upper bits are automatically zeroed at the start of every operation when the PC is copied to opLast. */ this.opLast = 0; this.resetIRQs(); this.setMemoryAccess(); this.addrInvalid = this.bus.getMemoryLimit(Memory.TYPE.READWRITE); } /** * onUpdate(fTransition) * * Enumerate all bindings and update their values. * * Called by Time's update() function whenever 1) its YIELDS_PER_UPDATE threshold is reached * (default is twice per second), 2) a step() operation has just finished (ie, the device is being * single-stepped), and 3) a start() or stop() transition has occurred. * * @this {PDP11} * @param {boolean} [fTransition] */ onUpdate(fTransition) { // TODO: Decide what bindings we want to support, and update them as appropriate. } /** * getMMR0() * * NOTE: It's OK to bypass this function if you're only interested in bits that always stored directly in MMR0. * * 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 MMR0 * nonr leng read trap unus unus ena mnt cmp -mode- i/d --page-- enable * * @this {PDP11} * @returns {number} */ getMMR0() { let data = this.regMMR0; if (!(data & PDP11.MMR0.ABORT)) { data = (data & ~(PDP11.MMR0.UNUSED | PDP11.MMR0.PAGE | PDP11.MMR0.MODE)) | (this.mmuLastMode << 5) | (this.mmuLastPage << 1); } return data; } /** * setMMR0() * * @this {PDP11} * @param {number} newMMR0 */ setMMR0(newMMR0) { newMMR0 &= ~PDP11.MMR0.UNUSED; if (this.regMMR0 != newMMR0) { if (newMMR0 & PDP11.MMR0.ABORT) { /* * If updates to MMR0[1-7], MMR1, and MMR2 are being shut off (ie, MMR0.ABORT bits are transitioning * from clear to set), then do one final sync with their real-time counterparts in opLast. */ if (!(this.regMMR0 & PDP11.MMR0.ABORT)) { this.regMMR1 = (this.opLast >> 16) & 0xffff; this.regMMR2 = this.opLast & 0xffff; } } /* * NOTE: We are not protecting the read-only state of the COMPLETED bit here; that's handled by writeMMR0(). */ this.regMMR0 = newMMR0; this.mmuLastMode = (newMMR0 & PDP11.MMR0.MODE) >> PDP11.MMR0.SHIFT.MODE; this.mmuLastPage = (newMMR0 & PDP11.MMR0.PAGE) >> PDP11.MMR0.SHIFT.PAGE; let mmuEnable = 0; if (newMMR0 & (PDP11.MMR0.ENABLED | PDP11.MMR0.MAINT)) { mmuEnable = PDP11.ACCESS.WRITE; if (newMMR0 & PDP11.MMR0.ENABLED) mmuEnable |= PDP11.ACCESS.READ; } if (this.mmuEnable != mmuEnable) { this.mmuEnable = mmuEnable; this.setMemoryAccess(); } } } /** * getMMR1() * * @this {PDP11} * @returns {number} */ getMMR1() { /* * If updates to MMR1 have not been shut off (ie, MMR0.ABORT bits are clear), then we are allowed * to sync MMR1 with its real-time counterpart in opLast. * * UPDATE: Apparently, I was mistaken that this register would only be updated when the MMR0 ENABLED * bit was set. * * if ((this.regMMR0 & (PDP11.MMR0.ABORT | PDP11.MMR0.ENABLED)) == PDP11.MMR0.ENABLED) */ if (!(this.regMMR0 & PDP11.MMR0.ABORT)) { this.regMMR1 = (this.opLast >> 16) & 0xffff; } let result = this.regMMR1; if (result & 0xff00) { result = ((result << 8) | (result >> 8)) & 0xffff; } return result; } /** * getMMR2() * * @this {PDP11} * @returns {number} */ getMMR2() { /* * If updates to MMR2 have not been shut off (ie, MMR0.ABORT bits are clear), then we are allowed * to sync MMR2 with its real-time counterpart in opLast. * * UPDATE: Apparently, I was mistaken that this register would only be updated when the MMR0 ENABLED * bit was set. * * if ((this.regMMR0 & (PDP11.MMR0.ABORT | PDP11.MMR0.ENABLED)) == PDP11.MMR0.ENABLED) */ if (!(this.regMMR0 & PDP11.MMR0.ABORT)) { this.regMMR2 = this.opLast & 0xffff; } return this.regMMR2; } /** * getMMR3() * * @this {PDP11} * @returns {number} */ getMMR3() { return this.regMMR3; } /** * setMMR3() * * @this {PDP11} * @param {number} newMMR3 */ setMMR3(newMMR3) { /* * Don't allow non-11/70 models to use 22-bit addressing or the UNIBUS map. */ if (this.model < PDP11.MODEL_1170) { newMMR3 &= ~(PDP11.MMR3.MMU_22BIT | PDP11.MMR3.UNIBUS_MAP); } if (this.regMMR3 != newMMR3) { this.regMMR3 = newMMR3; this.mmuMask = (newMMR3 & PDP11.MMR3.MMU_22BIT)? PDP11.MASK_22BIT : PDP11.MASK_18BIT; this.setMemoryAccess(); } } /** * setReset(addr, fStart, bUnit, addrStack) * * @this {PDP11} * @param {number} addr * @param {boolean} [fStart] (true if a "startable" image was just loaded, false if not) * @param {number} [bUnit] (boot unit #) * @param {number} [addrStack] */ setReset(addr, fStart, bUnit, addrStack) { this.addrReset = addr; this.setPC(addr); this.setPSW(0); this.resetCPU(); if (fStart) { this.regsGen[0] = bUnit || 0; for (let i = 1; i <= 5; i++) this.regsGen[i] = 0; this.regsGen[6] = addrStack || 0o2000; // if (!this.flags.powered) { // this.flags.autoStart = true; // } // else if (!this.flags.running) { // this.startCPU(); // } } else { // if (this.dbg && this.flags.powered) { // /* // * TODO: Review the decision to always stop the CPU if the Debugger is loaded. Note that // * when stopCPU() stops a running CPU, the Debugger gets notified, so no need to notify it again. // * // * TODO: There are more serious problems to deal with if another component is slamming a new PC down // * the CPU's throat (presumably while also dropping some new code into RAM) while the CPU is running; // * we should probably force a complete reset, but for now, it's up to the user to hit the reset button // * themselves. // */ // if (!this.stopCPU() && !this.cmp.flags.reset) { // this.dbg.updateStatus(); // this.cmp.updateDisplays(-1); // } // } // else if (fStart === false) { // this.stopCPU(); // } } // if (!this.isRunning() && this.panel) this.panel.stop(); } /** * getMMUState() * * Returns bit 0 set if 22-bit, bit 1 set if 18-bit, or bit 2 set if 16-bit; used by the Panel component. * * @this {PDP11} * @returns {number} */ getMMUState() { return this.mmuEnable? ((this.regMMR3 & PDP11.MMR3.MMU_22BIT)? 1 : 2) : 4; } /** * resetCPU() * * @this {PDP11} */ resetCPU() { // TODO: Make sure all devices get reset notifications, and the IOPage address is reset. this.initMMU(); } /** * setMemoryAccess() * * Define handlers and DSPACE setting appropriate for the current MMU mode, in order to eliminate * unnecessary calls to mapVirtualToPhysical(). * * @this {PDP11} */ setMemoryAccess() { if (this.blockIOPagePrev) { this.bus.setBlock(this.addrIOPage, this.blockIOPagePrev); } if (!this.mmuEnable) { this.addrDSpace = 0; this.addrIOPage = PDP11.IOPAGE_16BIT; this.getAddr = this.getPhysicalAddrByMode; this.readWord = this.readWordFromPhysical; this.writeWord = this.writeWordToPhysical; } else { this.addrDSpace = PDP11.ACCESS.DSPACE; this.addrIOPage = (this.regMMR3 & PDP11.MMR3.MMU_22BIT)? PDP11.IOPAGE_22BIT : PDP11.IOPAGE_18BIT; this.getAddr = this.getVirtualAddrByMode; this.readWord = this.nReadBreaks? this.readWordFromVirtualChecked : this.readWordFromVirtual; this.writeWord = this.nWriteBreaks? this.writeWordToVirtualChecked : this.writeWordToVirtual; } this.blockIOPagePrev = this.bus.setBlock(this.addrIOPage, this.blockIOPage); } /** * loadState(stateCPU) * * If any saved values don't match (possibly overridden), abandon the given state and return false. * * @this {PDP11} * @param {Array} stateCPU * @returns {boolean} */ loadState(stateCPU) { if (!stateCPU || !stateCPU.length) { this.println("invalid saved state"); return false; } let idDevice = stateCPU.shift(); let version = stateCPU.shift(); if (idDevice != this.idDevice || (version|0) !== (+PDP11.VERSION|0)) { this.printf("CPU state mismatch (%s %3.2f)\n", idDevice, version); return false; } try { this.regsGen = stateCPU.shift(); this.regsAlt = stateCPU.shift(); this.regsAltStack = stateCPU.shift(); this.regsPAR = stateCPU.shift(); this.regsPDR = stateCPU.shift(); this.regsUNIMap = stateCPU.shift(); this.regsControl = stateCPU.shift(); this.regErr = stateCPU.shift(); this.regMBR = stateCPU.shift(); this.regPIR = stateCPU.shift(); this.regSLR = stateCPU.shift(); this.mmuLastMode = stateCPU.shift(); this.mmuLastPage = stateCPU.shift(); this.addrLast = stateCPU.shift(); this.opFlags = stateCPU.shift(); this.opLast = stateCPU.shift(); this.pswTrap = stateCPU.shift(); this.trapReason = stateCPU.shift(); this.trapVector = stateCPU.shift(); this.addrReset = stateCPU.shift(); this.setPSW(stateCPU.shift()); this.setMMR0(stateCPU.shift()); this.regMMR1 = stateCPU.shift(); this.regMMR2 = stateCPU.shift(); this.setMMR3(stateCPU.shift()); this.restoreIRQs(stateCPU.shift()); // this.restoreTimers(stateCPU.shift()); } catch(err) { this.println("CPU state error: " + err.message); return false; } return true; } /** * saveState(stateCPU) * * @this {PDP11} * @param {Array} stateCPU */ saveState(stateCPU) { stateCPU.push(this.idDevice); stateCPU.push(+PDP11.VERSION); stateCPU.push(this.regsGen); stateCPU.push(this.regsAlt); stateCPU.push(this.regsAltStack); stateCPU.push(this.regsPAR); stateCPU.push(this.regsPDR); stateCPU.push(this.regsUNIMap); stateCPU.push(this.regsControl); stateCPU.push(this.regErr); stateCPU.push(this.regMBR); stateCPU.push(this.regPIR); stateCPU.push(this.regSLR); stateCPU.push(this.mmuLastMode); stateCPU.push(this.mmuLastPage); stateCPU.push(this.addrLast); stateCPU.push(this.opFlags); stateCPU.push(this.opLast); stateCPU.push(this.pswTrap); stateCPU.push(this.trapReason); stateCPU.push(this.trapVector); stateCPU.push(this.addrReset); stateCPU.push(this.getPSW()); stateCPU.push(this.getMMR0()); stateCPU.push(this.getMMR1()); stateCPU.push(this.getMMR2()); stateCPU.push(this.getMMR3()); stateCPU.push(this.saveIRQs()); // stateCPU.push(this.saveTimers()); } /** * clearCF() * * @this {PDP11} */ clearCF() { this.flagC = 0; } /** * getCF() * * @this {PDP11} * @returns {number} 0 or PDP11.PSW.CF */ getCF() { return (this.flagC & 0x10000)? PDP11.PSW.CF: 0; } /** * setCF() * * @this {PDP11} */ setCF() { this.flagC = 0x10000; } /** * clearVF() * * @this {PDP11} */ clearVF() { this.flagV = 0; } /** * getVF() * * @this {PDP11} * @returns {number} 0 or PDP11.PSW.VF */ getVF() { return (this.flagV & 0x8000)? PDP11.PSW.VF: 0; } /** * setVF() * * @this {PDP11} */ setVF() { this.flagV = 0x8000; } /** * clearZF() * * @this {PDP11} */ clearZF() { this.flagZ = 1; } /** * getZF() * * @this {PDP11} * @returns {number} 0 or PDP11.PSW.ZF */ getZF() { return (this.flagZ & 0xffff)? 0 : PDP11.PSW.ZF; } /** * setZF() * * @this {PDP11} */ setZF() { this.flagZ = 0; } /** * clearNF() * * @this {PDP11} */ clearNF() { this.flagN = 0; } /** * getNF() * * @this {PDP11} * @returns {number} 0 or PDP11.PSW.NF */ getNF() { return (this.flagN & 0x8000)? PDP11.PSW.NF : 0; } /** * setNF() * * @this {PDP11} */ setNF() { this.flagN = 0x8000; } /** * getOpcode() * * @this {PDP11} * @returns {number} */ getOpcode() { let pc = this.opLast = this.regsGen[PDP11.REG.PC]; /* * If PC is unaligned, a BUS trap will be generated, and because it will generate an * exception, the next line (the equivalent of advancePC(2)) will not be executed, ensuring that * original unaligned PC will be pushed onto the stack by trap(). */ let opcode = this.readWord(pc); this.regsGen[PDP11.REG.PC] = (pc + 2) & 0xffff; return opcode; } /** * advancePC(off) * * NOTE: This function is nothing more than a convenience, and we fully expect it to be inlined at runtime. * * @this {PDP11} * @param {number} off * @returns {number} (original PC) */ advancePC(off) { let pc = this.regsGen[PDP11.REG.PC]; this.regsGen[PDP11.REG.PC] = (pc + off) & 0xffff; return pc; } /** * branch(opcode) * * @this {PDP11} * @param {number} opcode * @param {boolean|number} condition */ branch(opcode, condition) { if (condition) { let off = ((opcode << 24) >> 23); if (PDP11.DEBUG && this.dbg && off == -2) { this.dbg.stopCPU("branch to self"); } this.setPC(this.getPC() + off); this.nStepCycles -= 2; } this.nStepCycles -= (2 + 1); } /** * getPC() * * NOTE: This function is nothing more than a convenience, and we fully expect it to be inlined at runtime. * * @this {PDP11} * @returns {number} */ getPC() { return this.regsGen[PDP11.REG.PC]; } /** * getLastAddr() * * @this {PDP11} * @returns {number} */ getLastAddr() { return this.addrLast; } /** * getLastPC() * * @this {PDP11} * @returns {number} */ getLastPC() { return this.opLast & 0xffff; } /** * setPC() * * NOTE: Unlike other PCjs emulators, such as PCx86, where all PC updates MUST go through the setPC() * function, this function is nothing more than a convenience, because in the PDP-11, the PC can be loaded * like any other general register. We fully expect this function to be inlined at runtime. * * @this {PDP11} * @param {number} addr */ setPC(addr) { this.regsGen[PDP11.REG.PC] = addr & 0xffff; } /** * getSP() * * NOTE: This function is nothing more than a convenience, and we fully expect it to be inlined at runtime. * * @this {PDP11} * @returns {number} */ getSP() { return this.regsGen[PDP11.REG.SP]; } /** * setSP() * * NOTE: Unlike other PCjs emulators, such as PCx86, where all SP updates MUST go through the setSP() * function, this function is nothing more than a convenience, because in the PDP-11, the PC can be loaded * like any other general register. We fully expect this function to be inlined at runtime. * * @this {PDP11} * @param {number} addr */ setSP(addr) { this.regsGen[PDP11.REG.SP] = addr & 0xffff; } /** * addIRQ(vector, priority, message) * * @this {PDP11} * @param {number} vector (-1 for floating vector) * @param {number} priority * @param {number} [message] * @returns {IRQ} */ addIRQ(vector, priority, message) { let irq = {vector: vector, priority: priority, message: message || 0, name: PDP11.VECTORS[vector], next: null}; this.aIRQs.push(irq); return irq; } /** * insertIRQ(irq) * * @this {PDP11} * @param {IRQ} irq */ insertIRQ(irq) { if (irq != this.irqNext) { let irqPrev = this.irqNext; if (!irqPrev || irqPrev.priority <= irq.priority) { irq.next = irqPrev; this.irqNext = irq; } else { do { let irqNext = irqPrev.next; if (!irqNext || irqNext.priority <= irq.priority) { irq.next = irqNext; irqPrev.next = irq; break; } irqPrev = irqNext; } while (irqPrev); } } /* * See the writeXCSR() function for an explanation of why signalling an IRQ hardware interrupt * should be done using IRQ_DELAY rather than setting IRQ directly. */ this.opFlags |= PDP11.OPFLAG.IRQ_DELAY; } /** * removeIRQ(irq) * * @this {PDP11} * @param {IRQ} irq */ removeIRQ(irq) { let irqPrev = this.irqNext; if (irqPrev == irq) { this.irqNext = irq.next; } else { while (irqPrev) { let irqNext = irqPrev.next; if (irqNext == irq) { irqPrev.next = irqNext.next; break; } irqPrev = irqNext; } } /* * We could also set irq.next to null now, but strictly speaking, that shouldn't be necessary. * * Last but not least, if there's still an IRQ on the active IRQ list, we need to make sure IRQ_DELAY * is still set. */ if (this.irqNext) { this.opFlags |= PDP11.OPFLAG.IRQ_DELAY; } } /** * setIRQ(irq) * * @this {PDP11} * @param {IRQ|null} irq */ setIRQ(irq) { if (irq) { this.insertIRQ(irq); this.printf(PDP11.MESSAGE.INT + irq.message, "setIRQ(vector=%o,priority=%d)\n", irq.vector, irq.priority + ")"); } } /** * clearIRQ(irq) * * @this {PDP11} * @param {IRQ|null} irq */ clearIRQ(irq) { if (irq) { this.removeIRQ(irq); this.printf(PDP11.MESSAGE.INT + irq.message, "clearIRQ(vector=%o,priority=%d)\n", irq.vector, irq.priority + ")"); } } /** * findIRQ(vector) * * @this {PDP11} * @param {number} vector * @returns {IRQ|null} */ findIRQ(vector) { for (let i = 0; i < this.aIRQs.length; i++) { let irq = this.aIRQs[i]; if (irq.vector === vector) return irq; } return null; } /** * checkIRQs(priority) * * @this {PDP11} * @param {number} priority * @returns {IRQ|null} */ checkIRQs(priority) { return (this.irqNext && this.irqNext.priority > priority)? this.irqNext : null; } /** * resetIRQs(priority) * * @this {PDP11} */ resetIRQs() { this.irqNext = null; } /** * saveIRQs() * * @this {PDP11} * @returns {Array.<number>} */ saveIRQs() { let aIRQVectors = []; let irq = this.irqNext; while (irq) { aIRQVectors.push(irq.vector); irq = irq.next; } return aIRQVectors; } /** * restoreIRQs(aIRQVectors) * * @this {PDP11} * @param {Array.<number>} aIRQVectors */ restoreIRQs(aIRQVectors) { for (let i = aIRQVectors.length - 1; i >= 0; i--) { let irq = this.findIRQ(aIRQVectors[i]); this.assert(irq != null); if (irq) { irq.next = this.irqNext; this.irqNext = irq; } } } /** * checkInterrupts() * * @this {PDP11} * @returns {boolean} true if an interrupt was dispatched, false if not */ checkInterrupts() { let fInterrupt = false; if (this.opFlags & PDP11.OPFLAG.IRQ) { let vector = PDP11.TRAP.PIRQ; let priority = (this.regPIR & PDP11.PSW.PRI) >> PDP11.PSW.SHIFT.PRI; let irq = this.checkIRQs(priority); if (irq) { vector = irq.vector; priority = irq.priority; } if (this.dispatchInterrupt(vector, priority)) { if (irq) this.removeIRQ(irq); fInterrupt = true; } if (!this.irqNext && !this.regPIR) { this.opFlags &= ~PDP11.OPFLAG.IRQ; } } else if (this.opFlags & PDP11.OPFLAG.IRQ_DELAY) { /* * We know that IRQ (bit 2) is clear, so since IRQ_DELAY (bit 0) is set, incrementing opFlags * will eventually transform IRQ_DELAY into IRQ, without affecting any other (higher) bits. */ this.opFlags++; } return fInterrupt; } /** * dispatchInterrupt(vector, priority) * * TODO: The process of dispatching an interrupt MUST cost some cycles; either trap() needs to assess * that cost, or we do. * * @this {PDP11} * @param {number} vector * @param {number} priority * @returns {boolean} (true if dispatched, false if not) */ dispatchInterrupt(vector, priority) { let priorityCPU = (this.regPSW & PDP11.PSW.PRI) >> PDP11.PSW.SHIFT.PRI; if (priority > priorityCPU) { if (this.opFlags & PDP11.OPFLAG.WAIT) { this.advancePC(2); this.opFlags &= ~PDP11.OPFLAG.WAIT; } this.trap(vector, 0, PDP11.REASON.INTERRUPT); return true; } return false; } /** * checkTraps() * * NOTE: The following code processes these "deferred" traps in priority order. Unfortunately, that * order seems to have changed since the 11/20. For reference, here's the priority list for the 11/20: * * 1. Bus Errors * 2. Instruction Traps * 3. Trace Trap * 4. Stack Overflow Trap * 5. Power Failure Trap * * and for the 11/70: * * 1. HALT (Instruction, Switch, or Command) * 2. MMU Faults * 3. Parity Errors * 4. Bus Errors (including stack overflow traps?) * 5. Floating Point Traps * 6. TRAP Instruction * 7. TRACE Trap * 8. OVFL Trap * 9. Power Fail Trap * 10. Console Bus Request (Front Panel Operation) * 11. PIR 7, BR 7, PIR 6, BR 6, PIR 5, BR 5, PIR 4, BR 4, PIR 3, BR 3, PIR 2, PIR 1 * 12. WAIT Loop * * TODO: Determine 1) if the 11/20 Handbook was wrong, or 2) if the 11/70 really has different priorities. * * Also, as the PDP-11/20 Handbook (1971), p.100, notes: * * If a bus error is caused by the trap process handling instruction traps, trace traps, stack overflow * traps, or a previous bus error, the processor is halted. * * If a stack overflow is caused by the trap process in handling bus errors, instruction traps, or trace traps, * the process is completed and then the stack overflow trap is sprung. * * TODO: Based on the above notes, we should probably be halting the CPU when a bus error occurs during a trap. * * @this {PDP11} * @returns {boolean} (true if dispatched, false if not) */ checkTraps() { if (this.opFlags & PDP11.OPFLAG.TRAP_MMU) { this.trap(PDP11.TRAP.MMU, PDP11.OPFLAG.TRAP_MMU, PDP11.REASON.FAULT); return true; } if (this.opFlags & PDP11.OPFLAG.TRAP_SP) { this.trap(PDP11.TRAP.BUS, PDP11.OPFLAG.TRAP_SP, PDP11.REASON.YELLOW); return true; } if (this.opFlags & PDP11.OPFLAG.TRAP_TF) { this.trap(PDP11.TRAP.BPT, PDP11.OPFLAG.TRAP_TF, PDP11.REASON.TRACE); return true; } return false; } /** * isWaiting() * * @this {PDP11} * @returns {boolean} (true if OPFLAG.WAIT is set, false otherwise) */ isWaiting() { return !!(this.opFlags & PDP11.OPFLAG.WAIT); } /** * getPSW() * * @this {PDP11} * @returns {number} */ getPSW() { let mask = PDP11.PSW.CMODE | PDP11.PSW.PMODE | PDP11.PSW.REGSET | PDP11.PSW.PRI | PDP11.PSW.TF; return this.regPSW = (this.regPSW & mask) | this.getNF() | this.getZF() | this.getVF() | this.getCF(); } /** * setPSW(newPSW) * * This updates the CPU Processor Status Word. The PSW should generally be written through * this routine so that changes can be tracked properly, for example the correct register set, * the current memory management mode, etc. An exception is SPL which writes the priority directly. * Note that that N, Z, V, and C flags are actually stored separately for performance reasons. * * PSW 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 * CMODE PMODE RS -------- PRIORITY T N Z V C * * @this {PDP11} * @param {number} newPSW */ setPSW(newPSW) { newPSW &= this.pswUsed; this.flagN = newPSW << 12; this.flagZ = (~newPSW) & 4; this.flagV = newPSW << 14; this.flagC = newPSW << 16; if ((newPSW ^ this.regPSW) & this.pswRegSet) { /* * Swap register sets */ for (let i = this.regsAlt.length; --i >= 0;) { let tmp = this.regsGen[i]; this.regsGen[i] = this.regsAlt[i]; this.regsAlt[i] = tmp; } } this.pswMode = (newPSW >> PDP11.PSW.SHIFT.CMODE) & PDP11.MODE.MASK; let oldMode = (this.regPSW >> PDP11.PSW.SHIFT.CMODE) & PDP11.MODE.MASK; if (this.pswMode != oldMode) { /* * Swap stack pointers */ this.regsAltStack[oldMode] = this.regsGen[6]; this.regsGen[6] = this.regsAltStack[this.pswMode]; } this.regPSW = newPSW; /* * Trigger a call to checkInterrupts(), just in case. If there's an active IRQ, then setting * OPFLAG.IRQ is a no-brainer, but even if not, we set IRQ_DELAY in case the priority was lowered * enough to permit a programmed interrupt (via regPIR). */ this.opFlags &= ~PDP11.OPFLAG.IRQ; this.opFlags |= (this.irqNext? PDP11.OPFLAG.IRQ : PDP11.OPFLAG.IRQ_DELAY); } /** * getSLR() * * @this {PDP11} * @returns {number} */ getSLR() { return this.regSLR & 0xff00; } /** * setSLR(newSL) * * @this {PDP11} * @param {number} newSLR */ setSLR(newSLR) { this.regSLR = newSLR | 0xff; } /** * getPIR() * * @this {PDP11} * @returns {number} */ getPIR() { return this.regPIR; } /** * setPIR(newPIR) * * @this {PDP11} * @param {number} newPIR */ setPIR(newPIR) { newPIR &= PDP11.PIR.BITS; if (newPIR) { let bits = newPIR >> PDP11.PIR.SHIFT.BITS; do { newPIR += PDP11.PIR.PIA_INC; } while ((bits >>= 1)); this.opFlags |= PDP11.OPFLAG.IRQ_DELAY; } this.regPIR = newPIR; } /** * updateNZVFlags(result) * * NOTE: Only N and Z are updated based on the result; V is zeroed, C is unchanged. * * @this {PDP11} * @param {number} result */ updateNZVFlags(result) { this.flagN = this.flagZ = result; this.flagV = 0; } /** * updateNZVCFlags(result) * * NOTE: Only N and Z are updated based on the result; both V and C are simply zeroed. * * @this {PDP11} * @param {number} result */ updateNZVCFlags(result) { this.flagN = this.flagZ = result; this.flagV = this.flagC = 0; } /** * updateAllFlags(result, overflow) * * NOTE: The V flag is simply zeroed, unless a specific value is provided (eg, by NEG). * * @this {PDP11} * @param {number} result * @param {number} [overflow] */ updateAllFlags(result, overflow) { this.flagN = this.flagZ = this.flagC = result; this.flagV = overflow || 0; } /** * updateAddFlags(result, src, dst) * * @this {PDP11} * @param {number} result (dst + src) * @param {number} src * @param {number} dst */ updateAddFlags(result, src, dst) { this.flagN = this.flagZ = this.flagC = result; this.flagV = (src ^ result) & (dst ^ result); } /** * updateDecFlags(result, dst) * * NOTE: We could have used updateSubFlags() if not for the fact that the C flag must be preserved. * * @this {PDP11} * @param {number} result (dst - src, where src is an implied 1) * @param {number} dst */ updateDecFlags(result, dst) { this.flagN = this.flagZ = result; /* * Because src is always 1 (with a zero sign bit), it can be optimized out of this calculation. */ this.flagV = (/* src ^ */ dst) & (dst ^ result); } /** * updateIncFlags(result, dst) * * NOTE: We could have used updateAddFlags() if not for the fact that the C flag must be preserved. * * @this {PDP11} * @param {number} result (dst + src, where src is an implied 1) * @param {number} dst */ updateIncFlags(result, dst) { this.flagN = this.flagZ = result; /* * Because src is always 1 (with a zero sign bit), it can be optimized out of this calculation. */ this.flagV = (/* src ^ */ result) & (dst ^ result); } /** * updateMulFlags(result) * * @this {PDP11} * @param {number} result */ updateMulFlags(result) { this.flagN = result >> 16; this.flagZ = this.flagN | result; this.flagV = 0; this.flagC = (result < -32768 || result > 32767)? 0x10000 : 0; } /** * updateShiftFlags(result) * * @this {PDP11} * @param {number} result */ updateShiftFlags(result) { this.flagN = this.flagZ = this.flagC = result; this.flagV = this.flagN ^ (this.flagC >> 1); } /** * updateSubFlags(result, src, dst) * * NOTE: CMP operations calculate (src - dst) rather than (dst - src), so when they call updateSubFlags(), * they must reverse the order of the src and dst parameters. * * @this {PDP11} * @param {number} result (dst - src) * @param {number} src * @param {number} dst */ updateSubFlags(result, src, dst) { this.flagN = this.flagZ = this.flagC = result; this.flagV = (src ^ dst) & (dst ^ result); } /** * fault(addr, reason) * * @this {PDP11} * @param {number} addr * @param {number} [reason] */ fault(addr, reason) { if (reason <= 3) this.cpu.regErr |= PDP11.CPUERR.TIMEOUT; this.trap(PDP11.TRAP.BUS, 0, addr); } /** * trap(vector, flag, reason) * * trap() handles all the trap/abort functions. It reads the trap vector from kernel * D space, changes mode to reflect the new PSW and PC, and then pushes the old PSW and * PC onto the new mode stack. * * @this {PDP11} * @param {number} vector * @param {number} flag * @param {number} [reason] (for diagnostic purposes only) */ trap(vector, flag, reason) { this.printf(PDP11.MESSAGE.TRAP, "trap to vector %o (%o: %s)\n", vector, reason, reason < 0? PDP11.REASONS[-reason] : "BUS ERROR"); if (this.nDisableTraps) return; if (this.pswTrap < 0) { this.pswTrap = this.getPSW(); } else if (!this.pswMode) { reason = PDP11.REASON.RED; // double-fault (nested trap) forces a RED condition } if (reason == PDP11.REASON.RED) { if (this.opFlags & PDP11.OPFLAG.TRAP_RED) { reason = PDP11.REASON.PANIC; } this.opFlags |= PDP11.OPFLAG.TRAP_RED; /* * The next two lines used to be deferred until after the setPSW() below, but * I'm not seeing any dependencies on these registers, so I'm consolidating the code. */ this.regErr |= PDP11.CPUERR.RED; this.regsGen[6] = vector = 4; } if (reason != PDP11.REASON.PANIC) { /* * NOTE: Pre-setting the auto-dec values for MMR1 to 0xF6F6 is a work-around for an "EKBEE1" * diagnostic (PC 056710), which tests what happens when a misaligned read triggers a BUS trap, * and that trap then triggers an MMU trap during the first pushWord() below. * * One would think it would be fine to zero those bits by setting opLast to vector alone, * and then letting each of the pushWord() calls below shift their own 0xF6 auto-dec value into * opLast. When the first pushWord() triggers an MMU trap, we obviously won't get to the second * pushWord(), yet the diagnostic expects TWO auto-decs to be recorded. I'm puzzled why the * hardware apparently indicates TWO auto-decs, if SP wasn't actually decremented twice, but who * am I to judge. */ this.opLast = vector | 0xf6f60000; /* * Read from kernel D space */ this.pswMode = 0; let newPC = this.readWord(vector | this.addrDSpace); let newPSW = this.readWord(((vector + 2) & 0xffff) | this.addrDSpace); /* * Set new PSW with previous mode */ this.setPSW((newPSW & ~PDP11.PSW.PMODE) | ((this.pswTrap >> 2) & PDP11.PSW.PMODE)); this.pushWord(this.pswTrap); this.pushWord(this.regsGen[7]); this.setPC(newPC); } /* * TODO: Determine the appropriate number of cycles for traps; all I've done for now is move the * cycle charge from opTrap() to here, and reduced the amount the other opcode handlers that call * trap() charge by a corresponding amount (5). */ this.nStepCycles -= (4 + 1); /* * DEC's "TRAP TEST" (MAINDEC-11-D0NA-PB) triggers a RESERVED trap with an invalid opcode and the * stack deliberately set too low, and expects the stack overflow trap to be "sprung" immediately * afterward, so we only want to "lose interest" in the TRAP flag(s) that were set on entry, not ALL * of them. * * this.opFlags &= ~PDP11.OPFLAG.TRAP_MASK; // lose interest in traps after an abort * * Well, OK, we're also supposed to "lose interest" in the TF flag, too; otherwise, DEC tests fail. * * Finally, setPSW() likes to always set IRQ, to force a check of hardware interrupts prior to * the next instruction, just in case the PSW priority was lowered. However, there are "TRAP TEST" * tests like this one: * * 005640: 012706 007700 MOV #7700,SP * 005644: 012767 000340 172124 MOV #340,177776 * 005652: 012767 000100 171704 MOV #100,177564 * 005660: 012767 005712 172146 MOV #5712,000034 ; set TRAP vector (its PSW is already zero) * 005666: 012767 005714 172170 MOV #5714,000064 ; set hardware interrupt vector (its PSW is already zero) * 005674: 012767 005716 172116 MOV #5716,000020 ; set IOT vector * 005702: 012767 000340 172112 MOV #340,000022 ; set IOT PSW * 005710: 104400 TRAP 000 * 005712: 000004 IOT * 005714: 000000 HALT * * where, after "TRAP 000" has executed, a hardware interrupt will be acknowledged, and instead of * executing the IOT, we'll execute the HALT and fail the test. We avoid that by relying on the same * trick that the SPL instruction uses: setting IRQ_DELAY instead of IRQ, which effectively delays * IRQ detection for one instruction, which is just long enough to allow the diagnostic to pass. */ this.opFlags &= ~(flag | PDP11.OPFLAG.TRAP_TF | PDP11.OPFLAG.IRQ_MASK); this.opFlags |= PDP11.OPFLAG.IRQ_DELAY | PDP11.OPFLAG.TRAP_LAST; this.pswTrap = -1; // reset flag that we have a trap within a trap /* * These next properties (in conjunction with setting PDP11.OPFLAG.TRAP_LAST) are purely an aid for the Debugger; * see getTrapStatus(). */ this.trapReason = reason; this.trapVector = vector; if (reason == PDP11.REASON.PANIC) { this.time.stop(); } if (reason >= PDP11.REASON.RED) throw vector; } /** * trapReturn() * * @this {PDP11} */ trapReturn() { /* * This code used to defer updating regsGen[6] (SP) until after BOTH words had been popped, which seems * safer, but if we're going to do pushes in trap(), then I see no reason to avoid doing pops in trapReturn(). */ let addr = this.popWord(); let newPSW = this.popWord(); if (this.regPSW & PDP11.PSW.CMODE) { /* * Keep SPL and allow lower only for modes and register set. * * TODO: Review, because it seems a bit odd to only CLEAR the PRI bits in the new PSW, and then to OR in * CMODE, PMODE, and REGSET bits from the current PSW. */ newPSW = (newPSW & ~PDP11.PSW.PRI) | (this.regPSW & (PDP11.PSW.PRI | PDP11.PSW.REGSET | PDP11.PSW.PMODE | PDP11.PSW.CMODE)); } this.setPC(addr); this.setPSW(newPSW); this.opFlags &= ~PDP11.OPFLAG.TRAP_TF; } /** * getTrapStatus() * * @this {PDP11} * @returns {number} */ getTrapStatus() { return (this.opFlags & PDP11.OPFLAG.TRAP_LAST)? (this.trapVector | this.trapReason << 8) : 0; } /** * mapUnibus(addr) * * Used to convert 18-bit addresses to 22-bit addresses. Since mapUnibus() only looks at the low 18 bits of addr, * there's no need to mask addr first. Note that if bits 13-17 are all set, then the 18-bit address points to the * top 8Kb of its 256Kb range, and mapUnibus() will return addr unchanged, since it should already be pointing to * the top 8Kb of the 4Mb 22-bit range. * * Also, when bits 18-21 of addr are ALL set (which callers check using addr >= BusPDP11.UNIBUS_22BIT aka 0x3C0000), * then we have a 22-bit address pointing to the top 256Kb range, so if the UNIBUS relocation map is enabled, we again * pass the lower 18 bits of that address through the map. * * From the PDP-11/70 Handbook: * * On the 11/44 and 11/70, there are a total of 31 mapping registers for address relocation. Each register is * composed of a double 16-bit PDP-11 word (in consecutive locations) that holds the 22-bit base address. These * registers have UNIBUS addresses in the range 770200 to 770372. * * If the UNIBUS map relocation is not enabled, an incoming 18-bit UNIBUS address has 4 leading zeroes added for * referencing a 22-bit physical address. The lower 18 bits are the same. No relocation is performed. * * If UNIBUS map relocation is enabled, the five high order bits of the UNIBUS address are used to select one of the * 31 mapping registers. The low-order 13 bits of the incoming address are used as an offset from the base address * contained in the 22-bit mapping register. To form the physical address, the 13 low-order bits of the UNIBUS * address are added to 22 bits of the selected mapping register to produce the 22-bit physical address. The lowest * order bit of all mapping registers is always a zero, since relocation is always on word boundaries. * * Sadly, because these mappings occur at a word-granular level, we can't implement the mappings by simply shuffling * the underlying block around in the Bus component; it would be much more efficient if we could. That's how we move * the IOPage in response to addressing changes. * * @this {PDP11} * @param {number} addr * @returns {number} */ mapUnibus(addr) { let idx = (addr >> 13) & 0x1F; if (idx < 31) { if (this.regMMR3 & PDP11.MMR3.UNIBUS_MAP) { /* * The UNIBUS map relocation is enabled */ addr = (this.regsUNIMap[idx] + (addr & 0x1FFF)) & PDP11.MASK_22BIT; /* * TODO: Review this assertion. * * this.assert(addr < BusPDP11.UNIBUS_22BIT || addr >= BusPDP11.IOPAGE_22BIT); */ } else { /* * Since UNIBUS map relocation is NOT enabled, then as explained above: * * If the UNIBUS map relocation is not enabled, an incoming 18-bit UNIBUS address has 4 leading zeroes added for * referencing a 22-bit physical address. The lower 18 bits are the same. No relocation is performed. */ addr &= ~PDP11.UNIBUS_22BIT; } } return addr; } /** * getAddrInfo(addr, fPhysical) * * @this {PDP11} * @param {number} addr * @param {boolean} [fPhysical] * @returns {Array} */ getAddrInfo(addr, fPhysical) { let a = []; let addrPhysical; if (fPhysical) { addrPhysical = this.mapUnibus(addr); let idx = (addr >> 13) & 0x1F; a.push(addrPhysical); a.push(idx); if (this.regMMR3 & PDP11.MMR3.UNIBUS_MAP) { a.push(this.regsUNIMap[idx]); a.push(addr & 0x1FFF); } } else if (!this.mmuEnable) { addrPhysical = addr & 0xffff; if (addrPhysical >= PDP11.IOPAGE_16BIT) addrPhysical |= this.addrIOPage; a.push(addrPhysical); } else { let mode = this.pswMode << 1; let page = addr >> 13; if (page > 7) mode |= 1; if (!(this.regMMR3 & this.mapMMR3[this.pswMode])) page &= 7; let pdr = this.regsPDR[this.pswMode][page]; let off = addr & 0x1fff; let paf = (this.regsPAR[this.pswMode][page] << 6); addrPhysical = (paf + off) & this.mmuMask; if (addrPhysical >= PDP11.UNIBUS_22BIT) addrPhysical = this.mapUnibus(addrPhysical); a.push(addrPhysical); // a[0] a.push(off); // a[1] a.push(mode); // a[2] (0=KI, 1=KD, 2=SI, 3=SD, 4=??, 5=??, 6=UI, 7=UD) a.push(page & 7); // a[3] a.push(paf); // a[4] a.push(this.mmuMask); // a[5] } return a; } /** * mapVirtualToPhysical(addrVirtual, access) * * mapVirtualToPhysical() does memory management. It converts a 17-bit I/D virtual address to a * 22-bit physical address. A real PDP 11/70 memory management unit can be enabled separately for * read and write for diagnostic purposes. This is handled here by having an enable mask (mmuEnable) * which is tested against the operation access mask (access). If there is no match, then the virtual * address is simply mapped as a 16 bit physical address with the upper page going to the IO address * space. Significant access mask values used are PDP11.ACCESS.READ and PDP11.ACCESS.WRITE. * * When doing mapping, pswMode is used to decide what address space is to be used (0 = kernel, * 1 = supervisor, 2 = illegal, 3 = user). Normally, pswMode is set by the setPSW() function, but * there are exceptions for instructions which move data between address spaces (MFPD, MFPI, MTPD, * and MTPI) and trap(). These will modify pswMode outside of setPSW() and then restore it again if * all worked. If however something happens to cause a trap then no restore is done as setPSW() * will have been invoked as part of the trap, which will resynchronize pswMode. * * A PDP-11/70 is different from other PDP-11s in that the highest 18 bit space (017000000 & above) * maps directly to UNIBUS space - including low memory. This doesn't appear to be particularly useful * as it restricts maximum system memory - although it does appear to allow software testing of the * UNIBUS map. This feature also appears to confuse some OSes which test consecutive memory locations * to find maximum memory -- and on a full memory system find themselves accessing low memory again at * high addresses. * * Construction of a Physical Address * ---------------------------------- * * Virtual Addr (VA) 12 11 10 9 8 7 6 5 4 3 2 1 0 * + Page Addr Field (PAF) 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 * ----------------------------------------------------------------- * = Physical Addr (PA) 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 * * The Page Address Field (PAF) comes from a Page Address Register (PAR) that is selected by Virtual * Address (VA) bits 15-13. You can see from the above alignments that the VA contributes to the low * 13 bits, providing an 8Kb range. * * VA bits 0-5 pass directly through to the PA; those are also called the DIB (Displacement in Block) bits. * VA bits 6-12 are added to the low 7 bits of the PAF and are also called the BN (Block Number) bits. * * You can also think of the entire PAF as a block number, where each block is 64 bytes. This is consistent * with the LSIZE register at 177760, which is supposed to contain the block number of the last 64-byte block * of memory installed. * * Note that if a PAR is initialized to zero, successively adding 0200 (0x80) to the PAR will advance the * base physical address to the next 8Kb page. * * @this {PDP11} * @param {number} addrVirtual * @param {number} access * @returns {number} */ mapVirtualToPhysical(addrVirtual, access) { let page, pdr, addr; /* * This can happen when the MAINT bit of MMR0 is set but not the ENABLED bit. */ if (!(access & this.mmuEnable)) { addr = addrVirtual & 0xffff; if (addr >= PDP11.IOPAGE_16BIT) addr |= this.addrIOPage; return addr; } page = addrVirtual >> 13; if (!(this.regMMR3 & this.mapMMR3[this.pswMode])) page &= 7; pdr = this.regsPDR[this.pswMode][page]; addr = ((this.regsPAR[this.pswMode][page] << 6) + (addrVirtual & 0x1fff)) & this.mmuMask; if (addr >= PDP11.UNIBUS_22BIT) addr = this.mapUnibus(addr); if (this.nDisableTraps) return addr; /* * TEST #122 ("KT BEND") in the "EKBEE1" diagnostic (PC 076060) triggers a NOMEMORY error using * this instruction: * * 076170: 005037 140100 CLR @#140100 * * It also triggers an ODDADDR error using this instruction: * * 076356: 005037 140001 CLR @#140001 * * @paulnank: So it turns out that the memory management unit that does odd address and non-existent * memory trapping: who knew? :-) I thought these would have been handled at access time. * * @jeffpar: We're assuming, at least, that the MMU does its "NEXM" (NOMEMORY) non-existent memory test * very simplistically, by range-checking the address against something like the memory SIZE registers, * because otherwise the MMU would have to wait for a bus time-out: something so prohibitively expensive * that the MMU could not afford to do it. I rely on addrInvalid, which is derived from the same Bus * getMemoryLimit() service that the SIZE registers (177760--177762) use to derive their value. */ if (addr >= this.addrInvalid && addr < this.addrIOPage) { this.regErr |= PDP11.CPUERR.NOMEMORY; this.trap(PDP11.TRAP.BUS, 0, addr); } else if ((addr & 0x1) && !(access & PDP11.ACCESS.BYTE)) { this.regErr |= PDP11.CPUERR.ODDADDR; this.trap(PDP11.TRAP.BUS, 0, addr); } let newMMR0 = 0; switch (pdr & PDP11.PDR.ACF.MASK) { case PDP11.PDR.ACF.RO1: // 0x1: read-only, abort on write attempt, memory management trap on read (11/70 only) newMMR0 = PDP11.MMR0.TRAP_MMU; /* falls through */ case PDP11.PDR.ACF.RO: // 0x2: read-only, abort on write attempt pdr |= PDP11.PDR.ACCESSED; if (access & PDP11.ACCESS.WRITE) { newMMR0 = PDP11.MMR0.ABORT_RO; } break; case PDP11.PDR.ACF.RW1: // 0x4: read/write, memory management trap upon completion of a read or write newMMR0 = PDP11.MMR0.TRAP_MMU; /* falls through */ case PDP11.PDR.ACF.RW2: // 0x5: read/write, memory management trap upon completion of a write (11/70 only) if (access & PDP11.ACCESS.WRITE) { newMMR0 = PDP11.MMR0.TRAP_MMU; } /* falls through */ case PDP11.PDR.ACF.RW: // 0x6: read/write, no system trap/abort action pdr |= ((access & PDP11.ACCESS.WRITE) ? (PDP11.PDR.ACCESSED | PDP11.PDR.MODIFIED) : PDP11.PDR.ACCESSED); break; default: // 0x0 (non-resident, abort all accesses) or 0x3 or 0x7 (unused, abort all accesses) newMMR0 = PDP11.MMR0.ABORT_NR; break; } if ((pdr & (PDP11.PDR.PLF | PDP11.PDR.ED)) != PDP11.PDR.PLF) { // skip checking most common case (hopefully) /* * The Page Descriptor Register (PDR) Page Length Field (PLF) is a 7-bit block number, where a block * is 64 bytes. Since the bit 0 of the block number is located at bit 8 of the PDR, we shift the PDR * right 2 bits and then clear the bottom 6 bits by masking it with 0x1FC0. */ if (pdr & PDP11.PDR.ED) { if (pdr & PDP11.PDR.PLF) { if ((addrVirtual & 0x1FC0) < ((pdr >> 2) & 0x1FC0)) { newMMR0 |= PDP11.MMR0.ABORT_PL; } } } else { if ((addrVirtual & 0x1FC0) > ((pdr >> 2) & 0x1FC0)) { newMMR0 |= PDP11.MMR0.ABORT_PL; } } } /* * Aborts and traps: log FIRST trap and MOST RECENT abort */ this.regsPDR[this.pswMode][page] = pdr; if (addr != ((PDP11.IOPAGE_22BIT | PDP11.UNIBUS.MMR0) & this.mmuMask) || this.pswMode) { this.mmuLastMode = this.pswMode; this.mmuLastPage = page; } if (newMMR0) { if (newMMR0 & PDP11.MMR0.ABORT) { if (this.pswTrap >= 0) { newMMR0 |= PDP11.MMR0.COMPLETED; } if (!(this.regMMR0 & PDP11.MMR0.ABORT)) { newMMR0 |= (this.regMMR0 & PDP11.MMR0.TRAP_MMU) | (this.mmuLastMode << 5) | (this.mmuLastPage << 1); this.assert(!(newMMR0 & ~PDP11.MMR0.UPDATE)); this.setMMR0((this.regMMR0 & ~PDP11.MMR0.UPDATE) | (newMMR0 & PDP11.MMR0.UPDATE)); } /* * NOTE: In unusual circumstances, if regMMR0 already indicated an ABORT condition above, * we run the risk of infinitely looping; eg, we call trap(), which calls mapVirtualToPhysical() * on the trap vector, which faults again, etc. * * TODO: Determine what a real PDP-11 does in that situation; in our case, trap() deals with it * by checking an internal OPFLAG (TRAP_RED) and turning the next trap into a PANIC, triggering an * immediate HALT. */ this.trap(PDP11.TRAP.MMU, PDP11.OPFLAG.TRAP_MMU, PDP11.REASON.ABORT); } if (!(this.regMMR0 & (PDP11.MMR0.ABORT | PDP11.MMR0.TRAP_MMU))) { /* * TODO: Review the code below, because the address range seems over-inclusive. */ if (addr < ((PDP11.IOPAGE_22BIT | PDP11.UNIBUS.SIPDR0) & this.mmuMask) || addr > ((PDP11.IOPAGE_22BIT | PDP11.UNIBUS.UDPAR7 | 0x1) & this.mmuMask)) { this.regMMR0 |= PDP11.MMR0.TRAP_MMU; if (this.regMMR0 & PDP11.MMR0.MMU_TRAPS) this.opFlags |= PDP11.OPFLAG.TRAP_MMU; } } } return addr; } /** * popWord() * * @this {PDP11} * @returns {number} */ popWord() { let result = this.readWord(this.regsGen[6] | this.addrDSpace); this.regsGen[6] = (this.regsGen[6] + 2) & 0xffff; return result; } /** * pushWord(data) * * @this {PDP11} * @param {number} data */ pushWord(data) { let addrVirtual = (this.regsGen[6] - 2) & 0xffff; this.regsGen[6] = addrVirtual; // BSD needs SP updated before any fault :-( this.opLast = (this.opLast & 0xffff) | ((this.opLast & ~0xffff) << 8) | (0x00f6 << 16); if (!(this.opFlags & PDP11.OPFLAG.TRAP_RED)) this.checkStackLimit(PDP11.ACCESS.WRITE_WORD, -2, addrVirtual); this.writeWord(addrVirtual, data); } /** * getAddrByMode(mode, reg, access) * * getAddrByMode() maps a six bit operand to a 17 bit I/D virtual address space. * * Instruction operands are six bits in length - three bits for the mode and three * for the register. The 17th I/D bit in the resulting virtual address represents * whether the reference is to Instruction space or Data space - which depends on * combination of the mode and whether the register is the Program Counter (R7). * * The eight modes are:- * 0 R no valid virtual address * 1 (R) operand from I/D depending if R = 7 * 2 (R)+ operand from I/D depending if R = 7 * 3 @(R)+ address from I/D depending if R = 7 and operand from D space * 4 -(R) operand from I/D depending if R = 7 * 5 @-(R) address from I/D depending if R = 7 and operand from D space * 6 x(R) x from I space but operand from D space * 7 @x(R) x from I space but address and operand from D space * * Also need to keep MMR1 updated as this stores which registers have been * incremented and decremented so that the OS can reset and restart an instruction * if a page fault occurs. * * Stack Overflow Traps * -------------------- * On the PDP-11/20, stack overflow traps occur when an address below 400 is referenced * by SP in either mode 4 (auto-decrement) or 5 (auto-decrement deferred). The instruction * is allowed to complete before the trap is issued. NOTE: This information comes * directly from the PDP-11/20 Handbook (1971), but the 11/20 diagnostics apparently only * test mode 4, not mode 5, because when I later removed stack limit checks for mode 5 on * the 11/70, none of the 11/20 tests complained. * * TODO: Find some independent confirmation as to whether ANY PDP-11 models check for * stack overflow on mode 5 (auto-decrement deferred); if they do, then further tweaks to * checkStackLimit functions may be required. * * On the PDP-11/70, the stack limit register (177774) allows a variable boundary for the * kernel stack. * * @this {PDP11} * @param {number} mode * @param {number} reg * @param {number} access * @returns {number} */ getAddrByMode(mode, reg, access) { let addrVirtual, step; let addrDSpace = (access & PDP11.ACCESS.VIRT)? 0 : this.addrDSpace; /* * Modes that need to auto-increment or auto-decrement will break, in order to perform * the update; others will return an address immediately. */ switch (mode) { /* * Mode 0: Registers don't have a virtual address, so trap. * * NOTE: Most instruction code paths never call getAddrByMode() when the mode is zero; * JMP and JSR instructions are exceptions, but that's OK, because those are documented as * ILLEGAL instructions which produce a BUS trap (as opposed to UNDEFINED instructions * that cause a RESERVED trap). */ case 0: this.trap(PDP11.TRAP.BUS, 0, PDP11.REASON.ILLEGAL); return 0; /* * Mode 1: (R) */ case 1: if (reg == 6) this.checkStackLimit(access, 0, this.regsGen[6]); this.nStepCycles -= (2 + 1); return (reg == 7? this.regsGen[reg] : (this.regsGen[reg] | addrDSpace)); /* * Mode 2: (R)+ */ case 2: step = 2; addrVirtual = this.regsGen[reg]; if (reg == 6) this.checkStackLimit(access, step, addrVirtual); if (reg != 7) { addrVirtual |= addrDSpace; if (reg < 6 && (access & PDP11.ACCESS.BYTE)) step = 1; } this.nStepCycles -= (2 + 1); break; /* * Mode 3: @(R)+ */ case 3: step = 2; addrVirtual = this.regsGen[reg]; if (reg != 7) addrVirtual |= addrDSpace; addrVirtual = this.readWord(addrVirtual); addrVirtual |= addrDSpace; this.nStepCycles -= (5 + 2); break; /* * Mode 4: -(R) */ case 4: step = -2; if (reg < 6 && (access & PDP11.ACCESS.BYTE)) step = -1; addrVirtual = (this.regsGen[reg] + step) & 0xffff; if (reg == 6) this.checkStackLimit(access, step, addrVirtual); if (reg != 7) addrVirtual |= addrDSpace; this.nStepCycles -= (3 + 1); break; /* * Mode 5: @-(R) */ case 5: step = -2; addrVirtual = (this.regsGen[reg] - 2) & 0xffff; if (reg != 7) addrVirtual |= addrDSpace; addrVirtual = this.readWord(addrVirtual) | addrDSpace; this.nStepCycles -= (6 + 2); break; /* * Mode 6: d(R) */ case 6: addrVirtual = this.readWord(this.advancePC(2)); addrVirtual = (addrVirtual + this.regsGen[reg]) & 0xffff; if (reg == 6) this.checkStackLimit(access, 0, addrVirtual); this.nStepCycles -= (4 + 2); return addrVirtual | addrDSpace; /* * Mode 7: @d(R) */ case 7: addrVirtual = this.readWord(this.advancePC(2)); addrVirtual = (addrVirtual + this.regsGen[reg]) & 0xffff; addrVirtual = this.readWord(addrVirtual | this.addrDSpace); this.nStepCycles -= (7 + 3); return addrVirtual | addrDSpace; } this.regsGen[reg] = (this.regsGen[reg] + step) & 0xffff; this.opLast = (this.opLast & 0xffff) | ((this.opLast & ~0xffff) << 8) | ((((step << 3) & 0xf8) | reg) << 16); return addrVirtual; } /** * checkStackLimit1120(access, step, addr) * * @this {PDP11} * @param {number} access * @param {number} step * @param {number} addr */ checkStackLimit1120(access, step, addr) { /* * NOTE: DEC's "TRAP TEST" (MAINDEC-11-D0NA-PB) expects "TST -(SP)" to trap when SP is 150, * so we ignore the access parameter. Also, strangely, it does NOT expect this instruction * to trap: * * R0=006302 R1=000000 R2=000000 R3=000000 R4=000000 R5=000776 * SP=000000 PC=006346 PS=000344 IR=000000 SL=000377 T0 N0 Z1 V0 C0 * 006346: 112667 171426 MOVB (SP)+,000000 * * so if the step parameter is positive, we let it go. */ if (!this.pswMode && step <= 0 && addr <= this.regSLR) { /* * On older machines (eg, the PDP-11/20), there is no "YELLOW" and "RED" distinction, and the * instruction is always allowed to complete, so the trap must always be issued in this fashion. */ this.opFlags |= PDP11.OPFLAG.TRAP_SP; } } /** * checkStackLimit1140(access, step, addr) * * @this {PDP11} * @param {number} access * @param {number} step * @param {number} addr */ checkStackLimit1140(access, step, addr) { if (!this.pswMode) { /* * NOTE: The 11/70 CPU Instruction Exerciser does NOT expect reads to trigger a stack overflow, * so we check the access parameter. * * Moreover, TEST 40 of diagnostic EKBBF0 executes this instruction: * * R0=177777 R1=032435 R2=152110 R3=000024 R4=153352 R5=001164 * SP=177776 PC=020632 PS=000350 IR=000000 SL=000377 T0 N1 Z0 V0 C0 * 020632: 005016 CLR @SP ;cycles=7 * * expecting a RED stack overflow trap. Yes, using *any* addresses in the IOPage for the stack isn't * a good idea, but who said it was illegal? For now, we're going to restrict overflows to the highest * address tested by the diagnostic (0xFFFE, aka the PSW), by making that address negative. */ if (addr >= 0xFFFE) addr |= ~0xFFFF; if ((access & PDP11.ACCESS.WRITE) && addr <= this.regSLR) { /* * regSLR can never fall below 0xFF, so this subtraction can never go negative, so this comparison * is always safe. */ if (addr <= this.regSLR - 32) { this.trap(PDP11.TRAP.BUS, 0, PDP11.REASON.RED); } else { this.regErr |= PDP11.CPUERR.YELLOW; this.opFlags |= PDP11.OPFLAG.TRAP_SP; } } } } /** * readByteSafe(addr) * * This interface is expressly for the Debugger, to access virtual memory without faulting. * * @this {PDP11} * @param {number} addr * @returns {number} */ readByteSafe(addr) { this.nDisableTraps++; let b = this.bus.readData(this.mapVirtualToPhysical(addr, PDP11.ACCESS.READ_BYTE)); this.nDisableTraps--; return b; } /** * readWordSafe(addr) * * This interface is expressly for the Debugger, to access virtual memory without faulting. * * @this {PDP11} * @param {number} addr * @returns {number} */ readWordSafe(addr) { this.nDisableTraps++; let w = this.bus.readPair(this.mapVirtualToPhysical(addr, PDP11.ACCESS.READ_WORD)); this.nDisableTraps--; return w; } /** * writeByteSafe(addr, data) * * This interface is expressly for the Debugger, to access virtual memory without faulting. * * @this {PDP11} * @param {number} addr * @param {number} data */ writeByteSafe(addr, data) { this.nDisableTraps++; this.bus.writeData(this.mapVirtualToPhysical(addr, PDP11.ACCESS.WRITE_BYTE), data); this.nDisableTraps--; } /** * writeWordSafe(addr, data) * * This interface is expressly for the Debugger, to access virtual memory without faulting. * * @this {PDP11} * @param {number} addr * @param {number} data */ writeWordSafe(addr, data) { this.nDisableTraps++; this.bus.writePair(this.mapVirtualToPhysical(addr, PDP11.ACCESS.WRITE_WORD), data); this.nDisableTraps--; } /** * addMemBreak(addr, fWrite) * * @this {PDP11} * @param {number} addr * @param {boolean} fWrite is true for a memory write breakpoint, false for a memory read breakpoint */ addMemBreak(addr, fWrite) { let nBreaks = fWrite? this.nWriteBreaks++ : this.nReadBreaks++; this.assert(nBreaks >= 0); if (!nBreaks) this.setMemoryAccess(); } /** * removeMemBreak(addr, fWrite) * * @this {PDP11} * @param {number} addr * @param {boolean} fWrite is true for a memory write breakpoint, false for a memory read breakpoint */ removeMemBreak(addr, fWrite) { let nBreaks = fWrite? --this.nWriteBreaks : --this.nReadBreaks; this.assert(nBreaks >= 0); if (!nBreaks) this.setMemoryAccess(); } /** * getPhysicalAddrByMode(mode, reg, access) * * This is a handler set up by setMemoryAccess(). All calls should go through getAddr(). * * @this {PDP11} * @param {number} mode * @param {number} reg * @param {number} access * @returns {number} */ getPhysicalAddrByMode(mode, reg, access) { return this.getAddrByMode(mode, reg, access); } /** * getVirtualAddrByMode(mode, reg, access) * * This is a handler set up by setMemoryAccess(). All calls should go through getAddr(). * * @this {PDP11} * @param {number} mode * @param {number} reg * @param {number} access * @returns {number} */ getVirtualAddrByMode(mode, reg, access) { return this.mapVirtualToPhysical(this.getAddrByMode(mode, reg, access), access); } /** * readWordFromPhysical(addr) * * This is a handler set up by setMemoryAccess(). All calls should go through readWord(). * * @this {PDP11} * @param {number} addr * @returns {number} */ readWordFromPhysical(addr) { return this.bus.readPair(this.addrLast = addr); } /** * readWordFromVirtual(addrVirtual) * * This is a handler set up by setMemoryAccess(). All calls should go through readWord(). * * @this {PDP11} * @param {number} addrVirtual (input address is 17 bit (I&D)) * @returns {number} */ readWordFromVirtual(addrVirtual) { return this.bus.readPair(this.addrLast = this.mapVirtualToPhysical(addrVirtual, PDP11.ACCESS.READ_WORD)); } /** * readWordFromVirtualChecked(addrVirtual) * * This is a handler set up by setMemoryAccess(). All calls should go through readWord(). * * @this {PDP11} * @param {number} addrVirtual (input address is 17 bit (I&D)) * @returns {number} */ readWordFromVirtualChecked(addrVirtual) { if (this.dbg) { this.dbg.checkVirtualRead(addrVirtual, 2); } return this.readWordFromVirtual(addrVirtual); } /** * writeWordToPhysical(addr, data) * * This is a handler set up by setMemoryAccess(). All calls should go through writeWord(). * * @this {PDP11} * @param {number} addr * @param {number} data */ writeWordToPhysical(addr, data) { this.bus.writePair(this.addrLast = addr, data); } /** * writeWordToVirtual(addrVirtual, data) * * This is a handler set up by setMemoryAccess(). All calls should go through writeWord(). * * @this {PDP11} * @param {number} addrVirtual (input address is 17 bit (I&D)) * @param {number} data */ writeWordToVirtual(addrVirtual, data) { this.bus.writePair(this.addrLast = this.mapVirtualToPhysical(addrVirtual, PDP11.ACCESS.WRITE_WORD), data); } /** * writeWordToVirtualChecked(addrVirtual, data) * * This is a handler set up by setMemoryAccess(). All calls should go through writeWord(). * * @this {PDP11} * @param {number} addrVirtual (input address is 17 bit (I&D)) * @param {number} data */ writeWordToVirtualChecked(addrVirtual, data) { if (this.dbg) { this.dbg.checkVirtualWrite(addrVirtual, 2); } this.writeWordToVirtual(addrVirtual, data); } /** * readWordFromPrevSpace(opcode, access) * * @this {PDP11} * @param {number} opcode * @param {number} access (really just PDP11.ACCESS.DSPACE or PDP11.ACCESS.ISPACE) * @returns {number} */ readWordFromPrevSpace(opcode, access) { let data; let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { if (reg != 6 || ((this.regPSW >> 2) & PDP11.PSW.PMODE) === (this.regPSW & PDP11.PSW.PMODE)) { data = this.regsGen[reg]; } else { data = this.regsAltStack[(this.regPSW >> 12) & 3]; } } else { let addr = this.getAddrByMode(mode, reg, PDP11.ACCESS.READ_WORD); if (!(access & PDP11.ACCESS.DSPACE)) { if ((this.regPSW & 0xf000) !== 0xf000) addr &= 0xffff; } this.pswMode = (this.regPSW >> 12) & 3; data = this.readWord(addr | (access & this.addrDSpace)); this.pswMode = (this.regPSW >> 14) & 3; } return data; } /** * writeWordToPrevSpace(opcode, access, data) * * @this {PDP11} * @param {number} opcode * @param {number} access (really just PDP11.ACCESS.DSPACE or PDP11.ACCESS.ISPACE) * @param {number} data */ writeWordToPrevSpace(opcode, access, data) { this.opLast = (this.opLast & 0xffff) | (0x0016 << 16); let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { if (reg != 6 || ((this.regPSW >> 2) & PDP11.PSW.PMODE) === (this.regPSW & PDP11.PSW.PMODE)) { this.regsGen[reg] = data; } else { this.regsAltStack[(this.regPSW >> 12) & 3] = data; } } else { let addr = this.getAddrByMode(mode, reg, PDP11.ACCESS.WRITE_WORD); if (!(access & PDP11.ACCESS.DSPACE)) addr &= 0xffff; /* * TODO: Consider replacing the following code with writeWord(), by adding optional pswMode * parameters for each of the discrete mapVirtualToPhysical() and writePair() operations, because * as it stands, this is the only remaining call to mapVirtualToPhysical() outside of our * setMemoryAccess() handlers. */ this.pswMode = (this.regPSW >> 12) & 3; addr = this.mapVirtualToPhysical(addr | (access & PDP11.ACCESS.DSPACE), PDP11.ACCESS.WRITE); this.pswMode = (this.regPSW >> 14) & 3; this.bus.writePair(addr, data); } } /** * readSrcByte(opcode) * * WARNING: If the SRC operand is a register, offRegSrc ensures we return a negative register number * rather than the register value, because on the PDP-11/20, the final value of the register must be * resolved AFTER the DST operand has been decoded and any pre-decrement or post-increment operations * affecting the SRC register have been completed. See readSrcWord() for more details. * * @this {PDP11} * @param {number} opcode * @returns {number} */ readSrcByte(opcode) { let result; opcode >>= PDP11.SRCMODE.SHIFT; let reg = this.srcReg = opcode & PDP11.OPREG.MASK; let mode = this.srcMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { result = this.regsGen[reg + this.offRegSrc] & this.maskRegSrcByte; } else { result = this.bus.readData(this.getAddr(mode, reg, PDP11.ACCESS.READ_BYTE)); } return result; } /** * readSrcWord(opcode) * * WARNING: If the SRC operand is a register, offRegSrc ensures we return a negative register number * rather than the register value, because on the PDP-11/20, the final value of the register must be * resolved AFTER the DST operand has been decoded and any pre-decrement or post-increment operations * affecting the SRC register have been completed. * * Here's an example from DEC's "TRAP TEST" (MAINDEC-11-D0NA-PB): * * 007200: 012700 006340 MOV #6340,R0 * 007204: 010020 MOV R0,(R0)+ * 007206: 026727 177126 006342 CMP 006340,#6342 * 007214: 001401 BEQ 007220 * 007216: 000000 HALT * * If this function returned the value of R0 for the SRC operand of "MOV R0,(R0)+", then the operation * would write 6340 to the destination, rather than 6342. * * Most callers don't need to worry about this, because if they pass the result from readSrcWord() directly * to writeDstWord() or updateDstWord(), those functions will take care of converting any negative register * number back into the current register value. The exceptions are opcodes that don't modify the DST operand * (BIT, BITB, CMP, and CMPB); those opcode handlers must deal with negative register numbers themselves. * * @this {PDP11} * @param {number} opcode * @returns {number} */ readSrcWord(opcode) { let result; opcode >>= PDP11.SRCMODE.SHIFT; let reg = this.srcReg = opcode & PDP11.OPREG.MASK; let mode = this.srcMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { result = this.regsGen[reg + this.offRegSrc]; } else { result = this.bus.readPair(this.getAddr(mode, reg, PDP11.ACCESS.READ_WORD)); } return result; } /** * readDstAddr(opcode) * * @this {PDP11} * @param {number} opcode * @returns {number} */ readDstAddr(opcode) { let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; return this.getAddrByMode(mode, reg, PDP11.ACCESS.VIRT); } /** * readDstByte(opcode) * * @this {PDP11} * @param {number} opcode * @returns {number} */ readDstByte(opcode) { let result; let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { result = this.regsGen[reg] & 0xff; } else { result = this.bus.readData(this.getAddr(mode, reg, PDP11.ACCESS.READ_BYTE)); } return result; } /** * readDstWord(opcode) * * @this {PDP11} * @param {number} opcode * @returns {number} */ readDstWord(opcode) { let result; let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { result = this.regsGen[reg]; } else { result = this.bus.readPair(this.getAddr(mode, reg, PDP11.ACCESS.READ_WORD)); } return result; } /** * updateDstByte(opcode, data, fnOp) * * Used whenever the DST operand (as described by opcode) needs to be read before writing. * * @this {PDP11} * @param {number} opcode * @param {number} data * @param {function(number,number)} fnOp */ updateDstByte(opcode, data, fnOp) { let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { let dst = this.regsGen[reg]; data = (data < 0? (this.regsGen[-data-1] & 0xff) : data); this.regsGen[reg] = (dst & 0xff00) | fnOp.call(this, data, dst & 0xff); } else { let addr = this.dstAddr = this.getAddr(mode, reg, PDP11.ACCESS.UPDATE_BYTE); data = (data < 0? (this.regsGen[-data-1] & 0xff) : data); this.bus.writeData(addr, fnOp.call(this, data, this.bus.readData(addr))); if (addr & 1) this.nStepCycles--; } } /** * updateDstWord(opcode, data, fnOp) * * Used whenever the DST operand (as described by opcode) needs to be read before writing. * * @this {PDP11} * @param {number} opcode * @param {number} data * @param {function(number,number)} fnOp */ updateDstWord(opcode, data, fnOp) { let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; this.assert(data < 0 && data >= -8 || !(data & ~0xffff)); if (!mode) { this.regsGen[reg] = fnOp.call(this, data < 0? this.regsGen[-data-1] : data, this.regsGen[reg]); } else { let addr = this.getAddr(mode, reg, PDP11.ACCESS.UPDATE_WORD); this.bus.writePair(addr, fnOp.call(this, data < 0? this.regsGen[-data-1] : data, this.bus.readPair(addr))); } } /** * writeDstByte(opcode, data, writeFlags, fnFlags) * * Used whenever the DST operand (as described by opcode) does NOT need to be read before writing. * * @this {PDP11} * @param {number} opcode * @param {number} data * @param {number} writeFlags (WRITE.BYTE aka 0xff, or WRITE.SBYTE aka 0xffff) * @param {function(number)} fnFlags */ writeDstByte(opcode, data, writeFlags, fnFlags) { this.assert(writeFlags); let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; if (!mode) { if (!data) { /* * Potentially worthless optimization (but it looks good on "paper"). */ this.regsGen[reg] &= ~writeFlags; } else { /* * Potentially worthwhile optimization: skipping the sign-extending data shifts * if writeFlags is WRITE.BYTE (but that requires an extra test and separate code paths). */ data = (data < 0? (this.regsGen[-data-1] & 0xff): data); this.regsGen[reg] = (this.regsGen[reg] & ~writeFlags) | (((data << 24) >> 24) & writeFlags); } fnFlags.call(this, data << 8); } else { let addr = this.getAddr(mode, reg, PDP11.ACCESS.WRITE_BYTE); fnFlags.call(this, (data = data < 0? (this.regsGen[-data-1] & 0xff) : data) << 8); this.bus.writeData(addr, data); if (addr & 1) this.nStepCycles--; } } /** * writeDstWord(opcode, data, fnFlags) * * Used whenever the DST operand (as described by opcode) does NOT need to be read before writing. * * @this {PDP11} * @param {number} opcode * @param {number} data * @param {function(number)} fnFlags */ writeDstWord(opcode, data, fnFlags) { let reg = this.dstReg = opcode & PDP11.OPREG.MASK; let mode = this.dstMode = (opcode & PDP11.OPMODE.MASK) >> PDP11.OPMODE.SHIFT; this.assert(data < 0 && data >= -8 || !(data & ~0xffff)); if (!mode) { this.regsGen[reg] = (data = data < 0? this.regsGen[-data-1] : data); fnFlags.call(this, data); } else { let addr = this.getAddr(mode, reg, PDP11.ACCESS.WRITE_WORD); fnFlags.call(this, (data = data < 0? this.regsGen[-data-1] : data)); this.bus.writePair(addr, data); } } /** * toInstruction(addr, opcode) * * Returns a string representation of the specified instruction. * * @this {PDP11} * @param {number} addr * @param {number|undefined} [opcode] * @returns {string} */ toInstruction(addr, opcode) { return this.dbg && this.dbg.dumpInstruction(addr, 1) || ""; } /** * toString() * * Returns a string representation of the current CPU state. * * @this {PDP11} * @returns {string} */ toString() { let s = ""; if (this.dbg) { let regs = [ "R0", "R1", "R2", "R3", "R4", "R5", "", "SP", "PC", "PS", "PI", "SL", "NF", "ZF", "VF", "CF", "", "M0", "M1", "M2", "M3", "ER", "", "SR", "AR", "DR" ]; for (let i = 0; i < regs.length; i++) { let reg = regs[i]; if (!reg) { s += '\n'; continue; } let bits = 16; if (reg[1] == 'F') bits = 1; let value = this.getRegister(reg); /* * We must call the Debugger's sprintf() instead of our own in order to use its custom formatters (eg, %n). */ if (value != undefined) s += this.dbg.sprintf("%s=%*n ", reg, bits, value); } } return s; } }
JavaScript
class Catalog_Search_Items extends Catalog_Request { _display_name = "Catalog_Search_Items"; _last_verified_square_api_version = "2021-07-21"; _help = this.display_name + ": " + man; constructor() { super(); this._method = "post"; this._endpoint = "/search-catalog-items"; this._body = { cursor: undefined, limit: 100, sort_order: undefined, //str "ASC" or "DESC" text_filter: undefined, //str product_types: undefined, // ["REGULAR", "APPOINTMENTS_SERVICE"] stock_levels: undefined, // ["OUT", "LOW"] category_ids: undefined, // [ ids ] enabled_location_ids: undefined, // [ ids ] custom_attribute_filters: undefined, //[ {}, {}] max 10 }; } // GETTERS get sort_order() { return this._body.sort_order; } get text_filter() { return this._body.text_filter; } get product_types() { return this._body.product_types; } get stock_levels() { return this._body.stock_levels; } get category_ids() { return this._body.category_ids; } get enabled_location_ids() { return this._body.enabled_location_ids; } get custom_attribute_filters() { return this._body.custom_attribute_filters; } // SETTERS set sort_order(sort) { if (sort !== "ASC" && sort !== "DESC") { throw new Error('sort_order only accepts "ASC" or "DESC"'); } this._body.sort_order = sort; } set text_filter(str) { this._body.text_filter = str; } set product_types(type) { if (type !== "REGULAR" && type !== "APPOINTMENTS_SERVICE") { throw new Error( 'product_types only accepts "APPOINTMENTS_SERVICE" or "REGULAR"' ); } arrayify(this._body, "product_types", this._display_name); this._body.product_types = type; } set stock_levels(level) { if (level !== "OUT" && level !== "LOW") { throw new Error('stock_levels only accepts "OUT" and "LOW"'); } arrayify(this._body, "stock_levels", this._display_name); // prevent more than two - no point since duplicates are prevented and there are only two options // disallow duplicates if ( this._body.stock_levels.length === 1 && this.stock_levels[0] === level ) { throw new Error(`stock levels already contain ${level}`); } this._body.stock_levels.push(level); } set category_ids(id) { arrayify(this._body, "category_ids", this._display_name); this._body.category_ids.push(id); } set enabled_location_ids(id) { arrayify(this._body, "enabled_location_ids", this._display_name); this._body.enabled_location_ids.push(id); } set custom_attribute_filters(obj) { arrayify(this._body, "custom_attribute_filters", this._display_name); if (this._body.custom_attribute_filters.length >= 10) { throw new Error( "custom_attribute_filters can contain a maximum of 10 filters." ); } this._body.custom_attribute_filters.push(obj); } set attribute_filter(obj) { this._attribute_filter = obj; } set category_array_concat(arr) { let caller = "category_array_concat"; let name = this._display_name; arrayify(this._body, "category_ids", name, caller); // check that arr is an array [NI - no limit specified] and that the existing array does not exceed allowable length if (shazam_is_array(arr, name, caller)) { let joined_array = this._body.category_ids.concat(arr); // If we ever find a limit, check it here. See Order_Search for example. this._body.category_ids = joined_array; } } set enabled_location_array_concat(arr) { let name = this._display_name; let caller = "enabled_location_array_concat"; arrayify(this._body, "enabled_location_ids", name, caller); // check that arr is an array [NI - no limit specified] and that the existing array does not exceed allowable length if (shazam_is_array(arr, name, caller)) { let joined_array = this._body.enabled_location_ids.concat(arr); // If we ever find a limit, check it here. See Order_Search for example. this._body.enabled_location_ids = joined_array; } } set custom_attribute_filter_array_concat(arr) { let caller = "custom_attribute_filter_array_concat"; let name = this._display_name; arrayify(this._body, "custom_attribute_filters", name, caller); // check that arr is an array [NI - no limit specified] and that the existing array does not exceed allowable length if (shazam_is_array(arr, name, caller)) { let joined_array = this._body.custom_attribute_filters.concat(arr); // If we ever find a limit, check it here. See Order_Search for example. this._body.custom_attribute_filters = joined_array; } } // PRIVATE METHODS /** * {@link https://developer.squareup.com/reference/square/enums/SortOrder | Link To Square Docs}<br> *<br>{@link Catalog_Search_Items.make| Back to make()}<br> * #enum_sort_order<br> * Enumerated methods set specific values from a limited set of allowable values defined by Square. * For each value, a sub-method will exist that is the lowercase version of that value. There may also * exist abbreviated aliases. * * Enumerated methods are usually called by other functions and set the value on the object on which * the calling function operates. * @typedef {function} Catalog_Search_Items.enum_sort_order * @private * @abstract * @memberOf Catalog_Search_Items * @property asc() sets value to "ASC" * @property desc() sets value to "DESC" * @property up() alias of `asc` * @property down() alias of `desc` * @example * If you were allowed to choose from the set ["GOOD", "BAD", "UGLY"] in order to set the * value of `clint` on the object 'western' * * vyMar.make_western().clint.().good() => const spaghetti = {western : {clint: "GOOD"}} * */ #enum_sort_order(calling_this) { return { self: this, asc: function () { this.self.sort_order = "ASC"; return calling_this; }, desc: function () { this.self.sort_order = "DESC"; return calling_this; }, up: function () { return this.asc(); }, down: function () { return this.desc(); }, }; } /** * {@link https://developer.squareup.com/reference/square/enums/CatalogItemProductType | Link To Square Docs}<br> * <br>{@link Catalog_Search_Items.make| Back to make()}<br> * #enum_product_type<br> * Enumerated methods set specific values from a limited set of allowable values defined by Square. * For each value, a sub-method will exist that is the lowercase version of that value. There may also * exist abbreviated aliases. * * Enumerated methods are usually called by other functions and set the value on the object on which * the calling function operates. * @typedef {function} Catalog_Search_Items.enum_product_type * @private * @abstract * @memberOf Catalog_Search_Items * @property regular() sets value to "REGULAR" * @property appointments_service() sets value to "APPOINTMENTS_SERVICE" * @property appt() alias of `appointments_service` * @example * If you were allowed to choose from the set ["GOOD", "BAD", "UGLY"] in order to set the * value of `clint` on the object 'western' * * vyMar.make_western().clint.().good() => const spaghetti = {western : {clint: "GOOD"}} * */ #enum_product_type(calling_this) { return { self: this, regular: function () { this.self.product_types = "REGULAR"; return calling_this; }, appointments_service: function () { this.self.product_types = "APPOINTMENTS_SERVICE"; return calling_this; }, appt: function () { return this.appointments_service(); }, }; } /** * {@link https://developer.squareup.com/reference/square/enums/SearchCatalogItemsRequestStockLevel | Link To Square Docs}<br> * <br>{@link Catalog_Search_Items.make| Back to make()}<br> * #enum_stock_levels * stock_levels is an ARRAY. It can take multiple values. * * Enumerated methods set specific values from a limited set of allowable values defined by Square. * For each value, a sub-method will exist that is the lowercase version of that value. There may also * exist abbreviated aliases. * * Enumerated methods are usually called by other functions and set the value on the object on which * the calling function operates. * @typedef {function} Catalog_Search_Items.enum_stock_levels * @private * @abstract * @memberOf Catalog_Search_Items * @property low() adds value to array: "LOW" * @property out() adds value to array: "OUT" * @property any() adds both values to array: "LOW", "OUT" * @example * If you were allowed to choose from the set ["GOOD", "BAD", "UGLY"] in order to set the * value of `clint` on the object 'western' * * vyMar.make_western().clint.().good() => const spaghetti = {western : {clint: "GOOD"}} * */ #enum_stock_levels(calling_this) { return { self: this, low: function () { this.self.stock_levels = "LOW"; return calling_this; }, out: function () { this.self.stock_levels = "OUT"; return calling_this; }, any: function () { this.self.stock_levels = "LOW"; this.self.stock_levels = "OUT"; return calling_this; }, }; } // MAKE METHODS /** * make() method of Catalog_Search_Items * Make sure to have the Square Docs open in front of you. * Sub-Method names are exactly the same as the property names listed * in the Square docs. There may be additional methods and/or shortened aliases of other methods. * * You should read the generated docs as: * method_name(arg) {type} description of arg * * @typedef {function} Catalog_Search_Items.make * @method * @public * @memberOf Catalog_Search_Items * @property sort_order() {Enumerated} - calls {@link Catalog_Search_Items.enum_sort_order|`#enum_sort_order`} * @property stock_levels() {Enumerated} -- calls {@link Catalog_Search_Items.enum_stock_levels|`#enum_stock_levels`} * @property text_filter(id) {string<id>} - * @property product_types() {Enumerated} -- calls {@link Catalog_Search_Items.enum_product_type|`#enum_product_type`} * @property category_ids(id) {string<id>} - * @property enabled_location_ids(id) {string<id>} - * @property custom_attribute_filters(obj) {object} - Takes a **complete** custom attribute filter object. * @property (obj) {object} * @property sort() alias of `sort_order` * @property product() alias of `product_types` * @property stock() alias of `stock_levels` * @property text() alias of `text_filter` * @property custom() alias of `custom_attribute_filters` * @property category() alias of `category_ids` * @property location() alias of `enabled_location_ids` * @property concat_categories(arr) {array<id>} - adds the contents of an array of category ids * @property concat_enabled_locations(arr) {array<id>} - adds the contents of an array of location ids * @property concat_custom_attribute_filters(arr) {array<fardel>} - adds the contents of an array of custom attribute filter objects * @example * You must use parentheses with every call to make and with every sub-method. If you have to make a lot * of calls from different lines, it will reduce your tying and improve readability to set make() to a * variable. * * let make = myVar.make(); * make.gizmo() * make.gremlin() * //is the same as * myVar.make().gizmo().gremlin() * */ make() { return { self: this, sort_order: function () { return this.self.#enum_sort_order(this); }, stock_levels: function () { return this.self.#enum_stock_levels(this); }, text_filter: function (str) { this.self.text_filter = str; return this; }, product_types: function () { return this.self.#enum_product_type(this); }, category_ids: function (id) { this.self.category_ids = id; return this; }, enabled_location_ids: function (id) { this.self.enabled_location_ids = id; return this; }, custom_attribute_filters: function (obj) { this.self.custom_attribute_filters = obj; return this; }, sort: function () { return this.sort_order(); }, product() { return this.product_types(); }, stock() { return this.stock_levels(); }, text(str) { return this.text_filter(str); }, custom(obj) { return this.custom_attribute_filters(obj); }, category(id) { return this.category_ids(id); }, location(id) { return this.enabled_location_ids(id); }, concat_categories: function (arr) { this.self.category_array_concat = arr; return this; }, concat_enabled_locations: function (arr) { this.self.enabled_location_array_concat = arr; return this; }, concat_custom_attribute_filters: function (arr) { this.self.custom_attribute_filter_array_concat = arr; return this; }, }; } /** * {@link https://developer.squareup.com/reference/square/objects/CustomAttributeFilter | Square Docs}<br> * make_custom_attribute_filter() method of Catalog_Search_Items * Make sure to have the Square Docs open in front of you. * Sub-Method names are exactly the same as the property names listed * in the Square docs. There may be additional methods and/or shortened aliases of other methods. * * You should read the generated docs as: * method_name(arg) {type} description of arg * @typedef {function} Catalog_Search_Items.make_custom_attribute_filter * @method * @public * @memberOf Catalog_Search_Items * @property custom_attribute_definition_id(id) {string<id>} - * @property key(id) {string<id>} - * @property string_filter(id) {string<id>} - * @property number_filter(num1,num2) {number|number} * @property selection_uids_filter(id) {string<id>} - * @property bool_filter(bool) {boolean} * @property view() - Returns the custom_attribute_filter under construction * @property add() - Adds the custom_attribute_filter to the array - Must be called last. * @example * This behaves similarly to a normal `make` function except that you must call `.add()` as the last * step. You must call the function for each object you want to build. * * */ make_custom_attribute_filter() { let filter = { custom_attribute_definition_id: undefined, key: undefined, string_filter: undefined, number_filter: undefined, selection_uids_filter: [], bool_filter: undefined, }; return { self: this, custom_attribute_definition_id: function (id) { filter.custom_attribute_definition_id = id; return this; }, key: function (str) { filter.key = str; return this; }, string_filter: function (str) { filter.string_filter = str; return this; }, number_filter: function (num1, num2 = 0) { // set min and max, if they are same, set them to same let min = num1 >= num2 ? num2 : num1; let max = num1 <= num2 ? num2 : num1; filter.number_filter = { min, max }; return this; }, selection_uids_filter: function (str) { filter.selection_uids_filter.push(str); return this; }, bool_filter: function (bool) { if (typeof bool !== "boolean") { throw new Error( generate_error_message( "custom attribute filter bool_filter", "boolean", bool ) ); } filter.bool_filter = bool; return this; }, view: function () { return filter; }, add: function () { this.self.custom_attribute_filters = clone_object(filter); }, }; } }
JavaScript
class EventStoreConfigCtrl { /** @ngInject */ constructor($scope) { this.scope = $scope; this.current.jsonData = this.current.jsonData || {}; this.current.jsonData.url = this.current.jsonData.url || "http://localhost:3020"; this.current.jsonData.user = this.current.jsonData.user || "admin"; this.current.jsonData.password = this.current.jsonData.password || "password"; this.current.jsonData.selectedDatabase = this.current.jsonData.selectedDatabase || 0; this.current.jsonData.databases = this.current.jsonData.databases || { name: 'Select a Database', value: 0 }; this.current.jsonData.securityToken = this.current.jsonData.securityToken || null; this.current.jsonData.headerConfig = this.current.jsonData.headerConfig || { headers: { 'cache-control': 'no-cache', 'content-type': 'application/json' } }; } /** * Retrieve the Bearer Token to be used for all further requests with the server */ _retrieveBearerToken() { var username = this.current.jsonData.user; var password = this.current.jsonData.password; var url = this.current.jsonData.url var stringToEncode = username + ":" + password var auth = "Basic " + window.btoa(stringToEncode); console.log('Getting the Platform Bearer Token') console.log('====================================================') console.log(url + '/com/ibm/event/api/v1/init/user') var data = { username: username, password: password }; var outerScope = this; axios({ method: 'post', url: url + '/com/ibm/event/api/v1/init/user', data: data }) .then(function (response) { var token = response.data.token console.log('Token successfully retrieved:') console.log('====================================================') console.log(token) console.log('====================================================') console.log('') outerScope.current.jsonData.securityToken = 'bearer ' + token outerScope.current.jsonData.headerConfig.headers['Authorization'] = outerScope.current.jsonData.securityToken outerScope._getDatabasesList() }) .catch(function (error) { console.log(error); }); } /** * If the address is http, add a sample token to remain compatible */ _assignBearerToken() { var outerScope = this; outerScope.current.jsonData.securityToken = 'bearer token' outerScope.current.jsonData.headerConfig.headers['Authorization'] = outerScope.current.jsonData.securityToken outerScope._getDatabasesList() } /** * Get and populate the database list */ _getDatabasesList () { var outerScope = this; axios({ url: this.current.jsonData.url + '/com/ibm/event/api/v1/oltp/databases', method: 'get', headers: this.current.jsonData.headerConfig.headers }) .then(function (response) { outerScope.current.jsonData.databases = []; var database; var count = 0; var s = outerScope; /** * Wrap in scope, in order to make sure ng-options is properly updated, since the Array is directly populated. */ outerScope.scope.$apply(function() { for (database in response.data.data) { var db = response.data.data[database]; s.current.jsonData.databases.push ({name: db.name, value: count}); s.current.jsonData.selectedDatabase = count; count++; } }); }) .catch(function (error) { console.log(error); }); } /** * Retrieve the list of Databases currently managed by the store */ populateDatabases() { if (_.startsWith(this.current.jsonData.url, 'https')) { this._retrieveBearerToken(); } else { this._assignBearerToken(); } } }
JavaScript
class AssessCategory { /** * @param {string} id * @param {string} heading * @param {AssessArticle[]} articles */ constructor(id, heading, articles) { this.id = id; this.heading = heading; this.articles = articles; } }
JavaScript
class AssessArticle { /** * @param {string} id * @param {string} heading * @param {AssessArticleLink[]} links */ constructor(id, heading, links) { this.id = id; this.heading = heading; this.links = links; } }
JavaScript
class AssessArticleLink { /** * * @param {string} title * @param {string} href */ constructor(title, href) { this.title = title; this.href = href; } }
JavaScript
class Body_S { constructor(x, y) { this.comp = new Array(); this.pos = new Vector_S(x, y); this.m = 0; this.inv_m = 0; this.inertia = 0; this.inv_inertia = 0; this.elasticity = 1; this.friction = 0; this.angFriction = 0; this.maxSpeed = 0; this.color = ""; this.layer = 0; this.up = false; this.down = false; this.left = false; this.right = false; this.action = false; this.vel = new Vector_S(0, 0); this.acc = new Vector_S(0, 0); this.keyForce = 1; this.angKeyForce = 0.1; this.angle = 0; this.angVel = 0; this.player = false; this.collides = true; BODIES_S.push(this); } render() { for (let i in this.comp) { this.comp[i].draw(this.color); } } reposition() { this.acc = this.acc.unit().mult(this.keyForce); this.vel = this.vel.add(this.acc); this.vel = this.vel.mult(1 - this.friction); if (this.vel.mag() > this.maxSpeed && this.maxSpeed !== 0) { this.vel = this.vel.unit().mult(this.maxSpeed); } //this.angVel *= (1-this.angFriction); this.angVel = this.angVel * (1 - this.angFriction); } keyControl() { } remove() { if (BODIES_S.indexOf(this) !== -1) { BODIES_S.splice(BODIES_S.indexOf(this), 1); } } setMass(m) { this.m = m; if (this.m === 0) { this.inv_m = 0; } else { this.inv_m = 1 / this.m; } } setCollide(value) { this.collides = value; } }
JavaScript
class CollData_S { constructor(o1, o2, normal, pen, cp) { this.o1 = o1; this.o2 = o2; this.normal = normal; this.pen = pen; this.cp = cp; } penRes() { if (this.o1.inv_m + this.o2.inv_m == 0) return; let penResolution = this.normal.mult(this.pen / (this.o1.inv_m + this.o2.inv_m)); this.o1.pos = this.o1.pos.add(penResolution.mult(this.o1.inv_m)); this.o2.pos = this.o2.pos.add(penResolution.mult(-this.o2.inv_m)); } collRes() { //1. Closing velocity let collArm1 = this.cp.subtr(this.o1.comp[0].pos); let rotVel1 = new Vector_S(-this.o1.angVel * collArm1.y, this.o1.angVel * collArm1.x); let closVel1 = this.o1.vel.add(rotVel1); let collArm2 = this.cp.subtr(this.o2.comp[0].pos); let rotVel2 = new Vector_S(-this.o2.angVel * collArm2.y, this.o2.angVel * collArm2.x); let closVel2 = this.o2.vel.add(rotVel2); //2. Impulse augmentation let impAug1 = Vector_S.cross(collArm1, this.normal); impAug1 = impAug1 * this.o1.inv_inertia * impAug1; let impAug2 = Vector_S.cross(collArm2, this.normal); impAug2 = impAug2 * this.o2.inv_inertia * impAug2; let relVel = closVel1.subtr(closVel2); let sepVel = Vector_S.dot(relVel, this.normal); let new_sepVel = -sepVel * Math.min(this.o1.elasticity, this.o2.elasticity); let vsep_diff = new_sepVel - sepVel; let impulseDenom = this.o1.inv_m + this.o2.inv_m + impAug1 + impAug2; let impulse = (impulseDenom > 0) ? vsep_diff / (this.o1.inv_m + this.o2.inv_m + impAug1 + impAug2) : 0; let impulseVec = this.normal.mult(impulse); //3. Changing the velocities this.o1.vel = this.o1.vel.add(impulseVec.mult(this.o1.inv_m)); this.o2.vel = this.o2.vel.add(impulseVec.mult(-this.o2.inv_m)); this.o1.angVel += this.o1.inv_inertia * Vector_S.cross(collArm1, impulseVec); this.o2.angVel -= this.o2.inv_inertia * Vector_S.cross(collArm2, impulseVec); } }
JavaScript
class BomItem { /** * Constructs a new instance of a BOM line item * * This method cleans up the manufacturer part number, manufacturer name and * the reference designators. Cleaning ensures the removal any additional * spaces in the fields, and fixing the character cases. * * It also auto-initializes the number of occurences to 1. * * @param {String} MPN The manufacturer part number * @param {String} Manufacturer The name of the manufacturer * @param {String} ReferenceDesignators Comma-separated reference designators */ constructor ({ MPN, Manufacturer, ReferenceDesignators }) { this.MPN = MPN.toUpperCase() .split(/\s*/) .filter(char => !!char) .join('') this.Manufacturer = Manufacturer.toLowerCase() .split(/\s+/) .filter(word => !!word) .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' ') this.ReferenceDesignators = new Set(ReferenceDesignators.toUpperCase() .split(/\s*/) .filter(char => !!char) .join('') .split(',')) this.NumOccurrences = 1 // seal the object to prevent any additional fields from being added Object.seal(this) } /** * Returns a unique identifier for the BOM item * * This is currently a concatenation of the manufacturer name and the part * number. This identifier is used to differentiate between similar part * numbers for different manufacturers. * * @returns {String} */ get id () { return `${this.Manufacturer}:${this.MPN}` } /** * Returns the JSON representation of the BOM line item instane * @returns {Object} */ toJSON () { const { MPN, Manufacturer, ReferenceDesignators, NumOccurrences } = this return { MPN, Manufacturer, ReferenceDesignators: Array.from(ReferenceDesignators), NumOccurrences } } }
JavaScript
class Header extends Component{ renderNav(auth){ if(auth && auth.isAuthenticated){ return( <ul id="nav-mobile" className="right hide-on-med-and-down "> <li><Link to="/page/one">Agrregation</Link></li> <li><Link to="/page/two">Geo</Link></li> <li><button id="logout-button" className="waves-effect waves-light btn-flat" onClick={this.props.logoutUser}>Logout</button></li> </ul> ); } return(<Fragment></Fragment>) } render(){ return( <div className="navbar-fixed"> <nav className="header-nav"> <div className="nav-wrapper"> <Link to="/home" className="main-logo brand-logo">Kiva</Link> {this.renderNav(this.props.auth)} </div> </nav> </div> ); } }
JavaScript
class Aligner extends _processor.default { constructor(arg1, options) { super(arg1, options); if (arg1 instanceof Aligner) { var other = arg1; this._fieldSpec = other._fieldSpec; this._window = other._window; this._method = other._method; this._limit = other._limit; } else if ((0, _pipeline.isPipeline)(arg1)) { var { fieldSpec, window, method = "hold", limit = null } = options; this._fieldSpec = fieldSpec; this._window = window; this._method = method; this._limit = limit; } else { throw new Error("Unknown arg to Aligner constructor", arg1); } // // Internal members // this._previous = null; // work out field specs if (_underscore.default.isString(this._fieldSpec)) { this._fieldSpec = [this._fieldSpec]; } // check input of method if (!_underscore.default.contains(["linear", "hold"], this._method)) { throw new Error("Unknown method '".concat(this._method, "' passed to Aligner")); } // check limit if (this._limit && !Number.isInteger(this._limit)) { throw new Error("Limit passed to Aligner is not an integer"); } } clone() { return new Aligner(this); } /** * Test to see if an event is perfectly aligned. Used on first event. */ isAligned(event) { var bound = _index.default.getIndexString(this._window, event.timestamp()); return this.getBoundaryTime(bound) === event.timestamp().getTime(); } /** * Returns a list of indexes of window boundaries if the current * event and the previous event do not lie in the same window. If * they are in the same window, return an empty list. */ getBoundaries(event) { var prevIndex = _index.default.getIndexString(this._window, this._previous.timestamp()); var currentIndex = _index.default.getIndexString(this._window, event.timestamp()); if (prevIndex !== currentIndex) { var range = new _timerange.default(this._previous.timestamp(), event.timestamp()); return _index.default.getIndexStringList(this._window, range).slice(1); } else { return []; } } /** * We are dealing in UTC only with the Index because the events * all have internal timestamps in UTC and that's what we're * aligning. Let the user display in local time if that's * what they want. */ getBoundaryTime(boundaryIndex) { var index = new _index.default(boundaryIndex); return index.begin().getTime(); } /** * Generate a new event on the requested boundary and carry over the * value from the previous event. * * A variation just sets the values to null, this is used when the * limit is hit. */ interpolateHold(boundary) { var setNone = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var d = new _immutable.default.Map(); var t = this.getBoundaryTime(boundary); this._fieldSpec.forEach(path => { var fieldPath = _util.default.fieldPathToArray(path); if (!setNone) { d = d.setIn(fieldPath, this._previous.get(fieldPath)); } else { d = d.setIn(fieldPath, null); } }); return new _timeevent.default(t, d); } /** * Generate a linear differential between two counter values that lie * on either side of a window boundary. */ interpolateLinear(boundary, event) { var d = new _immutable.default.Map(); var previousTime = this._previous.timestamp().getTime(); var boundaryTime = this.getBoundaryTime(boundary); var currentTime = event.timestamp().getTime(); // This ratio will be the same for all values being processed var f = (boundaryTime - previousTime) / (currentTime - previousTime); this._fieldSpec.forEach(path => { var fieldPath = _util.default.fieldPathToArray(path); // // Generate the delta beteen the values and // bulletproof against non-numeric or bad paths // var previousVal = this._previous.get(fieldPath); var currentVal = event.get(fieldPath); var interpolatedVal = null; if (!_underscore.default.isNumber(previousVal) || !_underscore.default.isNumber(currentVal)) { console.warn("Path ".concat(fieldPath, " contains a non-numeric value or does not exist")); } else { interpolatedVal = previousVal + f * (currentVal - previousVal); } d = d.setIn(fieldPath, interpolatedVal); }); return new _timeevent.default(boundaryTime, d); } /** * Perform the fill operation on the event and emit. */ addEvent(event) { if (event instanceof _timerangeevent.default || event instanceof _indexedevent.default) { throw new Error("TimeRangeEvent and IndexedEvent series can not be aligned."); } if (this.hasObservers()) { if (!this._previous) { this._previous = event; if (this.isAligned(event)) { this.emit(event); } return; } var boundaries = this.getBoundaries(event); // // If the returned list is not empty, interpolate an event // on each of the boundaries and emit them // var count = boundaries.length; boundaries.forEach(boundary => { var outputEvent; if (this._limit && count > this._limit) { outputEvent = this.interpolateHold(boundary, true); } else { if (this._method === "linear") { outputEvent = this.interpolateLinear(boundary, event); } else { outputEvent = this.interpolateHold(boundary); } } this.emit(outputEvent); }); // // The current event now becomes the previous event // this._previous = event; } } }
JavaScript
class Home extends Component{ static propTypes = { userToken: PropTypes.string, user: PropTypes.string, isAuth: PropTypes.bool.isRequired }; static defaultProps = { userToken: "", user: "" }; /** * @propsUsed {this.props.userToken, this.props.user * @return {JSX} - The Pantry and Recipes components seperated in controlled panels */ render(){ let content = null; if(this.props.isAuth){ content = ( <div className="content-wrap"> <Tabs selected={0}> <Pane label="Pantry"><Pantry userToken={this.props.userToken} user={this.props.user}/></Pane> <Pane label="Recipes"><Recipes userToken={this.props.userToken}/></Pane> </Tabs> </div> ); } return content; } }
JavaScript
class BshbHandler { /** * Create a new handler * * @param bshb * adapter main class * @param boschSmartHomeBridge * bshb */ constructor(bshb, boschSmartHomeBridge) { this.bshb = bshb; this.boschSmartHomeBridge = boschSmartHomeBridge; this.long_timeout = 5000; this.chain = Promise.resolve(); } /** * Get bshb client */ getBshcClient() { return this.boschSmartHomeBridge.getBshcClient(); } }