Best Python code snippet using gabbi_python
hmi.js
Source:hmi.js  
1import { observable, action, computed } from 'mobx';2import _ from 'lodash';3import WS from 'store/websocket';4import UTTERANCE from 'store/utterance';5import RENDERER from 'renderer';6const TELEOP_MODE = Object.freeze({7  CAR: 'Car Teleop',8  CONSOLE: 'Console Teleop',9});10export default class HMI {11  modes = [];12  @observable currentMode = 'none';13  vehicles = [];14  @observable currentVehicle = 'none';15  defaultVehicleSize = {16    height: 1.48,17    width: 2.11,18    length: 4.933,19  };20  vehicleParam = {21    frontEdgeToCenter: 3.89,22    backEdgeToCenter: 1.043,23    leftEdgeToCenter: 1.055,24    rightEdgeToCenter: 1.055,25    height: 1.48,26    width: 2.11,27    length: 4.933,28    steerRatio: 16,29    wheelBase: 2.8448,30  };31  maps = [];32  @observable currentMap = 'none';33  @observable moduleStatus = observable.map();34  @observable componentStatus = observable.map();35  @observable otherComponentStatus = observable.map();36  @observable enableStartAuto = false;37  @observable dockerImage = 'unknown';38  @observable isCoDriver = false;39  @observable isMute = false;40  @observable isPreprocess = false;41  displayName = {};42  utmZoneId = 10;43  @observable isVehicleCalibrationMode = false;44  @observable isSensorCalibrationMode = false;45  @observable dataCollectionUpdateStatus = observable.map();46  @observable dataCollectionProgress = observable.map();47  @observable lidars = observable.map();48  @observable camera = {};49  @observable mainSensor = 'none';50  @observable updateConfiguration = false;51  @observable preprocessStarted = false;52  @observable preprocessFinished = false;53  @observable unexpectedAborted = false;54  @observable preprocessStatus = 'UNKNOWN'; // Under normal situation55  @observable logString = '';56  @observable preprocessProgress = 0;57  @observable preprocessMonitorItemTimeStamp = null;58  @observable counter = 0;59  @action toggleCoDriverFlag() {60    this.isCoDriver = !this.isCoDriver;61  }62  @action toggleMuteFlag() {63    this.isMute = !this.isMute;64    UTTERANCE.setMute(this.isMute);65  }66  @action updateStatus(newStatus) {67    if (newStatus.dockerImage) {68      this.dockerImage = newStatus.dockerImage;69    }70    if (newStatus.utmZoneId) {71      this.utmZoneId = newStatus.utmZoneId;72    }73    if (newStatus.modes) {74      this.modes = newStatus.modes.sort();75    }76    if (newStatus.currentMode) {77      this.isVehicleCalibrationMode = newStatus.currentMode78        .toLowerCase()79        .includes('vehicle calibration');80      this.isSensorCalibrationMode = newStatus.currentMode81        .toLowerCase()82        .includes('sensor calibration');83      if (this.currentMode !== newStatus.currentMode) {84        this.resetDataCollectionProgress();85        this.resetSensorCalibrationConfiguration();86        this.resetPreprocessProgress();87        this.currentMode = newStatus.currentMode;88        if (this.isSensorCalibrationMode) {89          this.updateConfiguration = true;90        }91      }92    }93    if (newStatus.maps) {94      this.maps = newStatus.maps.sort();95    }96    if (newStatus.currentMap) {97      this.currentMap = newStatus.currentMap;98    }99    if (newStatus.vehicles) {100      this.vehicles = newStatus.vehicles.sort();101    }102    if (newStatus.currentVehicle) {103      if (104        this.isVehicleCalibrationMode &&105        this.currentVehicle !== newStatus.currentVehicle106      ) {107        this.resetDataCollectionProgress();108        this.resetPreprocessProgress();109      }110      if (111        this.isSensorCalibrationMode &&112        this.currentVehicle !== newStatus.currentVehicle113      ) {114        this.updateConfiguration = true;115        this.resetSensorCalibrationConfiguration();116        this.resetPreprocessProgress();117      }118      this.currentVehicle = newStatus.currentVehicle;119    }120    if (newStatus.modules) {121      const newKeyList = JSON.stringify(Object.keys(newStatus.modules).sort());122      const curKeyList = JSON.stringify(this.moduleStatus.keys().sort());123      if (newKeyList !== curKeyList) {124        this.moduleStatus.clear();125      }126      for (const key in newStatus.modules) {127        this.moduleStatus.set(key, newStatus.modules[key]);128      }129    }130    if (newStatus.monitoredComponents) {131      const newKeyList = JSON.stringify(132        Object.keys(newStatus.monitoredComponents).sort(),133      );134      const curKeyList = JSON.stringify(this.componentStatus.keys().sort());135      if (newKeyList !== curKeyList) {136        this.componentStatus.clear();137      }138      for (const key in newStatus.monitoredComponents) {139        this.componentStatus.set(key, newStatus.monitoredComponents[key]);140      }141      if (142        this.startMonitorRecorderProcess &&143        !this.allMonitoredComponentSuccess144      ) {145        this.toggleModule(this.preConditionModule);146      }147    }148    if (newStatus.otherComponents) {149      const newKeyList = JSON.stringify(150        Object.keys(newStatus.otherComponents).sort(),151      );152      const curKeyList = JSON.stringify(153        this.otherComponentStatus.keys().sort(),154      );155      if (newKeyList !== curKeyList) {156        this.otherComponentStatus.clear();157      }158      for (const key in newStatus.otherComponents) {159        this.otherComponentStatus.set(key, newStatus.otherComponents[key]);160      }161    }162    if (this.preprocessStarted && !this.preprocessIsRunning) {163      this.counter += 1; // use counter to delay time164      if (this.counter > 1) {165        if (!this.preprocessFinished) {166          this.unexpectedAborted = true;167        }168        this.counter = 0;169        this.preprocessStarted = false;170      }171    }172    if (typeof newStatus.passengerMsg === 'string') {173      UTTERANCE.speakRepeatedly(newStatus.passengerMsg);174    }175  }176  @action update(world) {177    this.enableStartAuto = world.engageAdvice === 'READY_TO_ENGAGE';178  }179  updateVehicleParam(vehicleParam) {180    this.vehicleParam = vehicleParam;181    RENDERER.adc.resizeCarScale(182      this.vehicleParam.length / this.defaultVehicleSize.length,183      this.vehicleParam.width / this.defaultVehicleSize.width,184      this.vehicleParam.height / this.defaultVehicleSize.height,185    );186  }187  @action toggleModule(id) {188    this.moduleStatus.set(id, !this.moduleStatus.get(id));189    const command = this.moduleStatus.get(id) ? 'START_MODULE' : 'STOP_MODULE';190    WS.executeModuleCommand(id, command);191  }192  @computed get inNavigationMode() {193    return this.currentMode === 'Navigation';194  }195  @computed get inCarTeleopMode() {196    return this.currentMode === TELEOP_MODE.CAR;197  }198  @computed get inConsoleTeleopMode() {199    return this.currentMode === TELEOP_MODE.CONSOLE;200  }201  @computed get inTeleopMode() {202    return Object.values(TELEOP_MODE).includes(this.currentMode);203  }204  @computed get inCameraLidarSensorCalibrationMode() {205    return this.currentMode === 'Camera-Lidar Sensor Calibration';206  }207  @computed get isCalibrationMode() {208    return this.isSensorCalibrationMode || this.isVehicleCalibrationMode;209  }210  @computed get shouldDisplayNavigationMap() {211    return this.inNavigationMode || this.inTeleopMode;212  }213  @computed get allMonitoredComponentSuccess() {214    return (215      this.isCalibrationMode &&216      _.every(this.componentStatus.keys(), (key) => {217        return key === 'Recorder' || _.get(this.componentStatus.get(key), 'status') === 'OK';218      })219    );220  }221  @computed get preConditionModule() {222    return this.isCalibrationMode ? 'Recorder' : 'none';223  }224  @computed get startMonitorRecorderProcess() {225    return this.isSensorCalibrationMode && this.moduleStatus.get('Recorder');226  }227  @computed get canStartDataCollectionPreprocess() {228    return (229      this.isVehicleCalibrationMode &&230      _.some(231        this.dataCollectionProgress.get('Go Straight').values(),232        (x) => x > 0,233      )234    );235  }236  @computed get preprocessIsRunning() {237    return (238      this.isCalibrationMode &&239      this.otherComponentStatus &&240      _.get(this.otherComponentStatus.get('Preprocess'), 'status') === 'OK'241    );242  }243  @computed get startUpdateDataCollectionProgress() {244    return this.isVehicleCalibrationMode && this.moduleStatus.get('Recorder');245  }246  @action resetDataCollectionProgress() {247    this.dataCollectionUpdateStatus.clear();248    this.dataCollectionProgress.clear();249  }250  @action resetSensorCalibrationConfiguration() {251    this.lidars.clear();252    this.camera = {};253  }254  @action resetPreprocessProgress() {255    this.preprocessStarted = false;256    this.preprocessFinished = false;257    this.unexpectedAborted = false;258    this.preprocessStatus = 'UNKNOWN';259    this.logString = '';260    this.preprocessProgress = 0;261    this.preprocessMonitorItemTimeStamp = null;262  }263  @action updateDataCollectionProgress(data) {264    Object.keys(data)265      .sort()266      .forEach((scenarioName) => {267        if (!this.dataCollectionProgress.has(scenarioName)) {268          this.dataCollectionProgress.set(scenarioName, observable.map());269          this.dataCollectionUpdateStatus.set(scenarioName, observable.map());270        }271        const categoryProgress = this.dataCollectionProgress.get(scenarioName);272        const categoryStatus = this.dataCollectionUpdateStatus.get(273          scenarioName,274        );275        const scenario = data[scenarioName];276        Object.keys(scenario)277          .sort()278          .forEach((categoryName) => {279            const isUpdated =280              categoryProgress.get(categoryName) !== scenario[categoryName];281            categoryProgress.set(categoryName, scenario[categoryName]);282            categoryStatus.set(categoryName, isUpdated);283          });284      });285  }286  @action updatePreprocessProgress(data) {287    if (this.updateConfiguration) {288      if (data.lidarConfig) {289        data.lidarConfig.map((lidar) => {290          this.lidars.set(lidar.sensorName, lidar.translation);291        });292      }293      if (data.cameraConfig) {294        this.camera = data.cameraConfig;295      }296      this.mainSensor = data.mainSensor;297      this.updateConfiguration = false;298    }299    if (data.progress) {300      this.preprocessMonitorItemTimeStamp = new Date().getTime();301      if (this.unexpectedAborted) {302        this.preprocessStatus = 'FAIL';303        this.logString =304          'The preprocessing process has been aborted unexpectedly, please check nohup.out for reasons or try again.';305      } else {306        this.preprocessProgress = _.get(data, 'progress.percentage');307        this.logString = _.get(data, 'progress.logString');308        this.preprocessStatus = _.get(data, 'progress.status');309        if (['SUCCESS', 'FAIL'].includes(this.preprocessStatus)) {310          this.preprocessFinished = true;311        } else {312          this.preprocessFinished = false;313        }314      }315    }316  }317  // name:{x y z}318  @action changeTranslation(name, index, val, isLidar) {319    isLidar320      ? _.set(this.lidars.get(name), index, val)321      : _.set(this.camera, `translation.${index}`, val);322  }323  @action changeIntrinsic(name, index, val) {324    _.set(this.camera, `${name}[${index}]`, val);325  }326  rotate2DPoint({ x, y }, rotationInRad) {327    return {328      x: x * Math.cos(rotationInRad) - y * Math.sin(rotationInRad),329      y: x * Math.sin(rotationInRad) + y * Math.cos(rotationInRad),330    };331  }332  calculateCarPolygonPoints(positionX, positionY, headingInRad) {333    const config = this.vehicleParam;334    const polygonPoints = [335      { y: -config.leftEdgeToCenter, x: config.frontEdgeToCenter },336      { y: config.rightEdgeToCenter, x: config.frontEdgeToCenter },337      { y: config.rightEdgeToCenter, x: -config.backEdgeToCenter },338      { y: -config.leftEdgeToCenter, x: -config.backEdgeToCenter },339      { y: -config.leftEdgeToCenter, x: config.frontEdgeToCenter },340    ];341    polygonPoints.forEach((point) => {342      const newPoint = this.rotate2DPoint(point, headingInRad);343      point.x = positionX + newPoint.x;344      point.y = positionY + newPoint.y;345    });346    return polygonPoints;347  }...angular-moment.js
Source:angular-moment.js  
1/* angular-moment.js / v0.7.1 / (c) 2013, 2014 Uri Shaked / MIT Licence */2/* global define */3(function () {4	'use strict';5	function angularMoment(angular, moment) {6		/**7		 * @ngdoc overview8		 * @name angularMoment9		 *10		 * @description11		 * angularMoment module provides moment.js functionality for angular.js apps.12		 */13		return angular.module('angularMoment', [])14		/**15		 * @ngdoc object16		 * @name angularMoment.config:angularMomentConfig17		 *18		 * @description19		 * Common configuration of the angularMoment module20		 */21			.constant('angularMomentConfig', {22				/**23				 * @ngdoc property24				 * @name angularMoment.config.angularMomentConfig#preprocess25				 * @propertyOf angularMoment.config:angularMomentConfig26				 * @returns {string} The default preprocessor to apply27				 *28				 * @description29				 * Defines a default preprocessor to apply (e.g. 'unix', 'etc', ...). The default value is null,30				 * i.e. no preprocessor will be applied.31				 */32				preprocess: null, // e.g. 'unix', 'utc', ...33				/**34				 * @ngdoc property35				 * @name angularMoment.config.angularMomentConfig#timezone36				 * @propertyOf angularMoment.config:angularMomentConfig37				 * @returns {string} The default timezone38				 *39				 * @description40				 * The default timezone (e.g. 'Europe/London'). Empty string by default (does not apply41				 * any timezone shift).42				 */43				timezone: ''44			})45		/**46		 * @ngdoc object47		 * @name angularMoment.object:moment48		 *49		 * @description50		 * moment global (as provided by the moment.js library)51		 */52			.constant('moment', moment)53		/**54		 * @ngdoc object55		 * @name angularMoment.config:amTimeAgoConfig56		 * @module angularMoment57		 *58		 * @description59		 * configuration specific to the amTimeAgo directive60		 */61			.constant('amTimeAgoConfig', {62				/**63				 * @ngdoc property64				 * @name angularMoment.config.amTimeAgoConfig#withoutSuffix65				 * @propertyOf angularMoment.config:amTimeAgoConfig66				 * @returns {boolean} Whether to include a suffix in am-time-ago directive67				 *68				 * @description69				 * Defaults to false.70				 */71				withoutSuffix: false72			})73		/**74		 * @ngdoc directive75		 * @name angularMoment.directive:amTimeAgo76		 * @module angularMoment77		 *78		 * @restrict A79		 */80			.directive('amTimeAgo', ['$window', 'moment', 'amMoment', 'amTimeAgoConfig', 'angularMomentConfig', function ($window, moment, amMoment, amTimeAgoConfig, angularMomentConfig) {81				return function (scope, element, attr) {82					var activeTimeout = null;83					var currentValue;84					var currentFormat;85					var withoutSuffix = amTimeAgoConfig.withoutSuffix;86					var preprocess = angularMomentConfig.preprocess;87					function cancelTimer() {88						if (activeTimeout) {89							$window.clearTimeout(activeTimeout);90							activeTimeout = null;91						}92					}93					function updateTime(momentInstance) {94						element.text(momentInstance.fromNow(withoutSuffix));95						var howOld = moment().diff(momentInstance, 'minute');96						var secondsUntilUpdate = 3600;97						if (howOld < 1) {98							secondsUntilUpdate = 1;99						} else if (howOld < 60) {100							secondsUntilUpdate = 30;101						} else if (howOld < 180) {102							secondsUntilUpdate = 300;103						}104						activeTimeout = $window.setTimeout(function () {105							updateTime(momentInstance);106						}, secondsUntilUpdate * 1000);107					}108					function updateMoment() {109						cancelTimer();110						if (currentValue) {111							updateTime(amMoment.preprocessDate(currentValue, preprocess, currentFormat));112						}113					}114					scope.$watch(attr.amTimeAgo, function (value) {115						if ((typeof value === 'undefined') || (value === null) || (value === '')) {116							cancelTimer();117							if (currentValue) {118								element.text('');119								currentValue = null;120							}121							return;122						}123						currentValue = value;124						updateMoment();125					});126					if (angular.isDefined(attr.amWithoutSuffix)) {127						scope.$watch(attr.amWithoutSuffix, function (value) {128							if (typeof value === 'boolean') {129								withoutSuffix = value;130								updateMoment();131							} else {132								withoutSuffix = amTimeAgoConfig.withoutSuffix;133							}134						});135					}136					attr.$observe('amFormat', function (format) {137						currentFormat = format;138						updateMoment();139					});140					attr.$observe('amPreprocess', function (newValue) {141						preprocess = newValue;142						updateMoment();143					});144					scope.$on('$destroy', function () {145						cancelTimer();146					});147					scope.$on('amMoment:languageChange', function () {148						updateMoment();149					});150				};151			}])152		/**153		 * @ngdoc service154		 * @name angularMoment.service.amMoment155		 * @module angularMoment156		 */157			.service('amMoment', ['moment', '$rootScope', '$log', 'angularMomentConfig', function (moment, $rootScope, $log, angularMomentConfig) {158				/**159				 * @ngdoc property160				 * @name angularMoment:amMoment#preprocessors161				 * @module angularMoment162				 *163				 * @description164				 * Defines the preprocessors for the preprocessDate method. By default, the following preprocessors165				 * are defined: utc, unix.166				 */167				this.preprocessors = {168					utc: moment.utc,169					unix: moment.unix170				};171				/**172				 * @ngdoc function173				 * @name angularMoment.service.amMoment#changeLanguage174				 * @methodOf angularMoment.service.amMoment175				 *176				 * @description177				 * Changes the language for moment.js and updates all the am-time-ago directive instances178				 * with the new language.179				 *180				 * @param {string} lang 2-letter language code (e.g. en, es, ru, etc.)181				 */182				this.changeLanguage = function (lang) {183					var result = moment.lang(lang);184					if (angular.isDefined(lang)) {185						$rootScope.$broadcast('amMoment:languageChange');186					}187					return result;188				};189				/**190				 * @ngdoc function191				 * @name angularMoment.service.amMoment#preprocessDate192				 * @methodOf angularMoment.service.amMoment193				 *194				 * @description195				 * Preprocess a given value and convert it into a Moment instance appropriate for use in the196				 * am-time-ago directive and the filters.197				 *198				 * @param {*} value The value to be preprocessed199				 * @param {string} preprocess The name of the preprocessor the apply (e.g. utc, unix)200				 * @param {string=} format Specifies how to parse the value (see {@link http://momentjs.com/docs/#/parsing/string-format/})201				 * @return {Moment} A value that can be parsed by the moment library202				 */203				this.preprocessDate = function (value, preprocess, format) {204					if (angular.isUndefined(preprocess)) {205						preprocess = angularMomentConfig.preprocess;206					}207					if (this.preprocessors[preprocess]) {208						return this.preprocessors[preprocess](value, format);209					}210					if (preprocess) {211						$log.warn('angular-moment: Ignoring unsupported value for preprocess: ' + preprocess);212					}213					if (!isNaN(parseFloat(value)) && isFinite(value)) {214						// Milliseconds since the epoch215						return moment(parseInt(value, 10));216					}217					// else just returns the value as-is.218					return moment(value, format);219				};220				/**221				 * @ngdoc function222				 * @name angularMoment.service.amMoment#applyTimezone223				 * @methodOf angularMoment.service.amMoment224				 *225				 * @description226				 * Apply a timezone onto a given moment object - if moment-timezone.js is included227				 * Otherwise, it'll not apply any timezone shift.228				 *229				 * @param {Moment} aMoment a moment() instance to apply the timezone shift to230				 * @returns {Moment} The given moment with the timezone shift applied231				 */232				this.applyTimezone = function (aMoment) {233					var timezone = angularMomentConfig.timezone;234					if (aMoment && timezone) {235						if (aMoment.tz) {236							aMoment = aMoment.tz(timezone);237						} else {238							$log.warn('angular-moment: timezone specified but moment.tz() is undefined. Did you forget to include moment-timezone.js?');239						}240					}241					return aMoment;242				};243			}])244		/**245		 * @ngdoc filter246		 * @name angularMoment.filter:amCalendar247		 * @module angularMoment248		 */249			.filter('amCalendar', ['moment', 'amMoment', function (moment, amMoment) {250				return function (value, preprocess) {251					if (typeof value === 'undefined' || value === null) {252						return '';253					}254					value = amMoment.preprocessDate(value, preprocess);255					var date = moment(value);256					if (!date.isValid()) {257						return '';258					}259					return amMoment.applyTimezone(date).calendar();260				};261			}])262		/**263		 * @ngdoc filter264		 * @name angularMoment.filter:amDateFormat265		 * @module angularMoment266		 * @function267		 */268			.filter('amDateFormat', ['moment', 'amMoment', function (moment, amMoment) {269				return function (value, format, preprocess) {270					if (typeof value === 'undefined' || value === null) {271						return '';272					}273					value = amMoment.preprocessDate(value, preprocess);274					var date = moment(value);275					if (!date.isValid()) {276						return '';277					}278					return amMoment.applyTimezone(date).format(format);279				};280			}])281		/**282		 * @ngdoc filter283		 * @name angularMoment.filter:amDurationFormat284		 * @module angularMoment285		 * @function286		 */287			.filter('amDurationFormat', ['moment', function (moment) {288				return function (value, format, suffix) {289					if (typeof value === 'undefined' || value === null) {290						return '';291					}292					return moment.duration(value, format).humanize(suffix);293				};294			}]);295	}296	if (typeof define === 'function' && define.amd) {297		define('angular-moment', ['angular', 'moment'], angularMoment);298	} else {299		angularMoment(angular, window.moment);300	}...docPreprocessor.js
Source:docPreprocessor.js  
1'use strict';2var isString = require('./helpers').isString;3var isNumber = require('./helpers').isNumber;4var isBoolean = require('./helpers').isBoolean;5var isArray = require('./helpers').isArray;6var isUndefined = require('./helpers').isUndefined;7var fontStringify = require('./helpers').fontStringify;8function DocPreprocessor() {9}10DocPreprocessor.prototype.preprocessDocument = function (docStructure) {11	this.parentNode = null;12	this.tocs = [];13	this.nodeReferences = [];14	return this.preprocessNode(docStructure);15};16DocPreprocessor.prototype.preprocessNode = function (node) {17	// expand shortcuts and casting values18	if (isArray(node)) {19		node = { stack: node };20	} else if (isString(node)) {21		node = { text: node };22	} else if (isNumber(node) || isBoolean(node)) {23		node = { text: node.toString() };24	} else if (node === undefined || node === null) {25		node = { text: '' };26	} else if (Object.keys(node).length === 0) { // empty object27		node = { text: '' };28	} else if ('text' in node && (node.text === undefined || node.text === null)) {29		node.text = '';30	}31	if (node.columns) {32		return this.preprocessColumns(node);33	} else if (node.stack) {34		return this.preprocessVerticalContainer(node);35	} else if (node.ul) {36		return this.preprocessList(node);37	} else if (node.ol) {38		return this.preprocessList(node);39	} else if (node.table) {40		return this.preprocessTable(node);41	} else if (node.text !== undefined) {42		return this.preprocessText(node);43	} else if (node.toc) {44		return this.preprocessToc(node);45	} else if (node.image) {46		return this.preprocessImage(node);47	} else if (node.svg) {48		return this.preprocessSVG(node);49	} else if (node.canvas) {50		return this.preprocessCanvas(node);51	} else if (node.qr) {52		return this.preprocessQr(node);53	} else if (node.pageReference || node.textReference) {54		return this.preprocessText(node);55	} else {56		throw 'Unrecognized document structure: ' + JSON.stringify(node, fontStringify);57	}58};59DocPreprocessor.prototype.preprocessColumns = function (node) {60	var columns = node.columns;61	for (var i = 0, l = columns.length; i < l; i++) {62		columns[i] = this.preprocessNode(columns[i]);63	}64	return node;65};66DocPreprocessor.prototype.preprocessVerticalContainer = function (node) {67	var items = node.stack;68	for (var i = 0, l = items.length; i < l; i++) {69		items[i] = this.preprocessNode(items[i]);70	}71	return node;72};73DocPreprocessor.prototype.preprocessList = function (node) {74	var items = node.ul || node.ol;75	for (var i = 0, l = items.length; i < l; i++) {76		items[i] = this.preprocessNode(items[i]);77	}78	return node;79};80DocPreprocessor.prototype.preprocessTable = function (node) {81	var col, row, cols, rows;82	for (col = 0, cols = node.table.body[0].length; col < cols; col++) {83		for (row = 0, rows = node.table.body.length; row < rows; row++) {84			var rowData = node.table.body[row];85			var data = rowData[col];86			if (data !== undefined) {87				if (data === null) { // transform to object88					data = '';89				}90				if (!data._span) {91					rowData[col] = this.preprocessNode(data);92				}93			}94		}95	}96	return node;97};98DocPreprocessor.prototype.preprocessText = function (node) {99	if (node.tocItem) {100		if (!isArray(node.tocItem)) {101			node.tocItem = [node.tocItem];102		}103		for (var i = 0, l = node.tocItem.length; i < l; i++) {104			if (!isString(node.tocItem[i])) {105				node.tocItem[i] = '_default_';106			}107			var tocItemId = node.tocItem[i];108			if (!this.tocs[tocItemId]) {109				this.tocs[tocItemId] = { toc: { _items: [], _pseudo: true } };110			}111			if (!node.id) {112				node.id = 'toc-' + tocItemId + '-' + this.tocs[tocItemId].toc._items.length;113			}114			var tocItemRef = {115				_nodeRef: this._getNodeForNodeRef(node),116				_textNodeRef: node117			};118			this.tocs[tocItemId].toc._items.push(tocItemRef);119		}120	}121	if (node.id) {122		if (this.nodeReferences[node.id]) {123			if (!this.nodeReferences[node.id]._pseudo) {124				throw "Node id '" + node.id + "' already exists";125			}126			this.nodeReferences[node.id]._nodeRef = this._getNodeForNodeRef(node);127			this.nodeReferences[node.id]._textNodeRef = node;128			this.nodeReferences[node.id]._pseudo = false;129		} else {130			this.nodeReferences[node.id] = {131				_nodeRef: this._getNodeForNodeRef(node),132				_textNodeRef: node133			};134		}135	}136	if (node.pageReference) {137		if (!this.nodeReferences[node.pageReference]) {138			this.nodeReferences[node.pageReference] = {139				_nodeRef: {},140				_textNodeRef: {},141				_pseudo: true142			};143		}144		node.text = '00000';145		node.linkToDestination = node.pageReference;146		node._pageRef = this.nodeReferences[node.pageReference];147	}148	if (node.textReference) {149		if (!this.nodeReferences[node.textReference]) {150			this.nodeReferences[node.textReference] = { _nodeRef: {}, _pseudo: true };151		}152		node.text = '';153		node.linkToDestination = node.textReference;154		node._textRef = this.nodeReferences[node.textReference];155	}156	if (node.text && node.text.text) {157		node.text = [this.preprocessNode(node.text)];158	} else if (isArray(node.text)) {159		var isSetParentNode = false;160		if (this.parentNode === null) {161			this.parentNode = node;162			isSetParentNode = true;163		}164		for (var i = 0, l = node.text.length; i < l; i++) {165			node.text[i] = this.preprocessNode(node.text[i]);166		}167		if (isSetParentNode) {168			this.parentNode = null;169		}170	}171	return node;172};173DocPreprocessor.prototype.preprocessToc = function (node) {174	if (!node.toc.id) {175		node.toc.id = '_default_';176	}177	node.toc.title = node.toc.title ? this.preprocessNode(node.toc.title) : null;178	node.toc._items = [];179	if (this.tocs[node.toc.id]) {180		if (!this.tocs[node.toc.id].toc._pseudo) {181			throw "TOC '" + node.toc.id + "' already exists";182		}183		node.toc._items = this.tocs[node.toc.id].toc._items;184	}185	this.tocs[node.toc.id] = node;186	return node;187};188DocPreprocessor.prototype.preprocessImage = function (node) {189	if (!isUndefined(node.image.type) && !isUndefined(node.image.data) && (node.image.type === 'Buffer') && isArray(node.image.data)) {190		node.image = Buffer.from(node.image.data);191	}192	return node;193};194DocPreprocessor.prototype.preprocessSVG = function (node) {195	return node;196};197DocPreprocessor.prototype.preprocessCanvas = function (node) {198	return node;199};200DocPreprocessor.prototype.preprocessQr = function (node) {201	return node;202};203DocPreprocessor.prototype._getNodeForNodeRef = function (node) {204	if (this.parentNode) {205		return this.parentNode;206	}207	return node;208}...tts_background_test.js
Source:tts_background_test.js  
...13SYNC_TEST_F('ChromeVoxTtsBackgroundTest', 'Preprocess', function() {14  const tts = new TtsBackground(false);15  const preprocess = tts.preprocess.bind(tts);16  // Punctuation.17  assertEquals('dot', preprocess('.'));18  assertEquals('x.', preprocess('x.'));19  assertEquals('.x', preprocess('.x'));20  assertEquals('space', preprocess(' '));21  assertEquals('', preprocess('  '));22  assertEquals('A', preprocess('a'));23  assertEquals('A', preprocess('A'));24  assertEquals('a.', preprocess('a.'));25  assertEquals('.a', preprocess('.a'));26  // Only summarize punctuation if there are three or more occurrences without27  // a space in between.28  assertEquals('10 equal signs', preprocess('=========='));29  assertEquals('bullet bullet bullet', preprocess('\u2022 \u2022\u2022'));30  assertEquals('3 bullets', preprocess('\u2022\u2022\u2022'));31  assertEquals('C plus plus', preprocess('C++'));32  assertEquals('C 3 plus signs', preprocess('C+++'));33  // There are some punctuation marks that we do not verbalize because they34  // result in an overly verbose experience (periods, commas, dashes, etc.).35  // This set of punctuation marks is defined in the |some_punctuation| regular36  // expression in TtsBackground.37  assertEquals('C--', preprocess('C--'));38  assertEquals('Hello world.', preprocess('Hello world.'));39  assertEquals('new line', preprocess('\n'));40  assertEquals('return', preprocess('\r'));41});42TEST_F('ChromeVoxTtsBackgroundTest', 'UpdateVoice', function() {43  const tts = new TtsBackground(false);44  const voices = [45    {lang: 'zh-CN', voiceName: 'Chinese'},46    {lang: 'zh-TW', voiceName: 'Chinese (Taiwan)'},47    {lang: 'es', voiceName: 'Spanish'},48    {lang: 'en-US', voiceName: 'U.S. English'}49  ];50  chrome.tts.getVoices = function(callback) {51    callback(voices);52  };53  // Asks this test to process the next task immediately.54  const flushNextTask = function() {55    const task = tasks.shift();56    if (!task) {57      return;58    }59    if (task.setup) {60      task.setup();61    }62    tts.updateVoice_(task.testVoice, this.newCallback(function(actualVoice) {63      assertEquals(task.expectedVoice, actualVoice);64      flushNextTask();65    }));66  }.bind(this);67  assertTrue(!tts.currentVoice);68  const tasks = [69    {testVoice: '', expectedVoice: constants.SYSTEM_VOICE},70    {71      setup() {72        voices[3].lang = 'en';73      },74      testVoice: 'U.S. English',75      expectedVoice: 'U.S. English'76    },77    {78      setup() {79        voices[3].lang = 'fr-FR';80        voices[3].voiceName = 'French';81      },82      testVoice: '',83      expectedVoice: constants.SYSTEM_VOICE84    },85    {testVoice: 'French', expectedVoice: 'French'},86    {testVoice: 'NotFound', expectedVoice: constants.SYSTEM_VOICE},87  ];88  flushNextTask();89});90// This test only works if Google tts is installed. Run it locally.91TEST_F(92    'ChromeVoxTtsBackgroundTest', 'DISABLED_EmptyStringCallsCallbacks',93    function() {94      const tts = new TtsBackground(false);95      let startCalls = 0, endCalls = 0;96      assertCallsCallbacks = function(text, speakCalls) {97        tts.speak(text, QueueMode.QUEUE, {98          startCallback() {99            ++startCalls;100          },101          endCallback: this.newCallback(function() {102            ++endCalls;103            assertEquals(speakCalls, endCalls);104            assertEquals(endCalls, startCalls);105          })106        });107      }.bind(this);108      assertCallsCallbacks('', 1);109      assertCallsCallbacks('  ', 2);110      assertCallsCallbacks(' \u00a0 ', 3);111    });112SYNC_TEST_F(113    'ChromeVoxTtsBackgroundTest', 'CapitalizeSingleLettersAfterNumbers',114    function() {115      const tts = new TtsBackground(false);116      const preprocess = tts.preprocess.bind(tts);117      // Capitalize single letters if they appear directly after a number.118      assertEquals(119          'Click to join the 5G network',120          preprocess('Click to join the 5g network'));121      assertEquals(122          'I ran a 100M sprint in 10 S',123          preprocess('I ran a 100m sprint in 10 s'));124      // Do not capitalize the letter "a".125      assertEquals(126          'Please do the shopping at 3 a thing came up at work',127          preprocess('Please do the shopping at 3 a thing came up at work'));128    });129SYNC_TEST_F('ChromeVoxTtsBackgroundTest', 'AnnounceCapitalLetters', function() {130  const tts = new TtsBackground(false);131  const preprocess = tts.preprocess.bind(tts);132  assertEquals('A', preprocess('A'));133  // Only announce capital for solo capital letters.134  localStorage['capitalStrategy'] = 'announceCapitals';135  assertEquals('Cap A', preprocess('A'));136  assertEquals('Cap Z', preprocess('Z'));137  // Do not announce capital for the following inputs.138  assertEquals('BB', preprocess('BB'));139  assertEquals('A.', preprocess('A.'));140});141SYNC_TEST_F('ChromeVoxTtsBackgroundTest', 'NumberReadingStyle', function() {142  const tts = new TtsBackground();143  let lastSpokenTextString = '';144  tts.speakUsingQueue_ = function(utterance, _) {145    lastSpokenTextString = utterance.textString;146  };147  // Check the default preference.148  assertEquals('asWords', localStorage['numberReadingStyle']);149  tts.speak('100');150  assertEquals('100', lastSpokenTextString);151  tts.speak('An unanswered call lasts for 30 seconds.');152  assertEquals(153      'An unanswered call lasts for 30 seconds.', lastSpokenTextString);...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
