Best JavaScript code snippet using stryker-parent
Instrument.js
Source:Instrument.js
1/* *2 *3 * (c) 2009-2019 Ãystein Moseng4 *5 * Instrument class for sonification module.6 *7 * License: www.highcharts.com/license8 *9 * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!10 *11 * */12'use strict';13import H from '../../parts/Globals.js';14import U from '../../parts/Utilities.js';15var pick = U.pick;16/**17 * A set of options for the Instrument class.18 *19 * @requires module:modules/sonification20 *21 * @interface Highcharts.InstrumentOptionsObject22 */ /**23* The type of instrument. Currently only `oscillator` is supported. Defaults24* to `oscillator`.25* @name Highcharts.InstrumentOptionsObject#type26* @type {string|undefined}27*/ /**28* The unique ID of the instrument. Generated if not supplied.29* @name Highcharts.InstrumentOptionsObject#id30* @type {string|undefined}31*/ /**32* When using functions to determine frequency or other parameters during33* playback, this options specifies how often to call the callback functions.34* Number given in milliseconds. Defaults to 20.35* @name Highcharts.InstrumentOptionsObject#playCallbackInterval36* @type {number|undefined}37*/ /**38* A list of allowed frequencies for this instrument. If trying to play a39* frequency not on this list, the closest frequency will be used. Set to `null`40* to allow all frequencies to be used. Defaults to `null`.41* @name Highcharts.InstrumentOptionsObject#allowedFrequencies42* @type {Array<number>|undefined}43*/ /**44* Options specific to oscillator instruments.45* @name Highcharts.InstrumentOptionsObject#oscillator46* @type {Highcharts.OscillatorOptionsObject|undefined}47*/48/**49 * Options for playing an instrument.50 *51 * @requires module:modules/sonification52 *53 * @interface Highcharts.InstrumentPlayOptionsObject54 */ /**55* The frequency of the note to play. Can be a fixed number, or a function. The56* function receives one argument: the relative time of the note playing (057* being the start, and 1 being the end of the note). It should return the58* frequency number for each point in time. The poll interval of this function59* is specified by the Instrument.playCallbackInterval option.60* @name Highcharts.InstrumentPlayOptionsObject#frequency61* @type {number|Function}62*/ /**63* The duration of the note in milliseconds.64* @name Highcharts.InstrumentPlayOptionsObject#duration65* @type {number}66*/ /**67* The minimum frequency to allow. If the instrument has a set of allowed68* frequencies, the closest frequency is used by default. Use this option to69* stop too low frequencies from being used.70* @name Highcharts.InstrumentPlayOptionsObject#minFrequency71* @type {number|undefined}72*/ /**73* The maximum frequency to allow. If the instrument has a set of allowed74* frequencies, the closest frequency is used by default. Use this option to75* stop too high frequencies from being used.76* @name Highcharts.InstrumentPlayOptionsObject#maxFrequency77* @type {number|undefined}78*/ /**79* The volume of the instrument. Can be a fixed number between 0 and 1, or a80* function. The function receives one argument: the relative time of the note81* playing (0 being the start, and 1 being the end of the note). It should82* return the volume for each point in time. The poll interval of this function83* is specified by the Instrument.playCallbackInterval option. Defaults to 1.84* @name Highcharts.InstrumentPlayOptionsObject#volume85* @type {number|Function|undefined}86*/ /**87* The panning of the instrument. Can be a fixed number between -1 and 1, or a88* function. The function receives one argument: the relative time of the note89* playing (0 being the start, and 1 being the end of the note). It should90* return the panning value for each point in time. The poll interval of this91* function is specified by the Instrument.playCallbackInterval option.92* Defaults to 0.93* @name Highcharts.InstrumentPlayOptionsObject#pan94* @type {number|Function|undefined}95*/ /**96* Callback function to be called when the play is completed.97* @name Highcharts.InstrumentPlayOptionsObject#onEnd98* @type {Function|undefined}99*/100/**101 * @requires module:modules/sonification102 *103 * @interface Highcharts.OscillatorOptionsObject104 */ /**105* The waveform shape to use for oscillator instruments. Defaults to `sine`.106* @name Highcharts.OscillatorOptionsObject#waveformShape107* @type {string|undefined}108*/109// Default options for Instrument constructor110var defaultOptions = {111 type: 'oscillator',112 playCallbackInterval: 20,113 oscillator: {114 waveformShape: 'sine'115 }116};117/* eslint-disable no-invalid-this, valid-jsdoc */118/**119 * The Instrument class. Instrument objects represent an instrument capable of120 * playing a certain pitch for a specified duration.121 *122 * @sample highcharts/sonification/instrument/123 * Using Instruments directly124 * @sample highcharts/sonification/instrument-advanced/125 * Using callbacks for instrument parameters126 *127 * @requires module:modules/sonification128 *129 * @class130 * @name Highcharts.Instrument131 *132 * @param {Highcharts.InstrumentOptionsObject} options133 * Options for the instrument instance.134 */135function Instrument(options) {136 this.init(options);137}138Instrument.prototype.init = function (options) {139 if (!this.initAudioContext()) {140 H.error(29);141 return;142 }143 this.options = H.merge(defaultOptions, options);144 this.id = this.options.id = options && options.id || H.uniqueKey();145 // Init the audio nodes146 var ctx = H.audioContext;147 this.gainNode = ctx.createGain();148 this.setGain(0);149 this.panNode = ctx.createStereoPanner && ctx.createStereoPanner();150 if (this.panNode) {151 this.setPan(0);152 this.gainNode.connect(this.panNode);153 this.panNode.connect(ctx.destination);154 }155 else {156 this.gainNode.connect(ctx.destination);157 }158 // Oscillator initialization159 if (this.options.type === 'oscillator') {160 this.initOscillator(this.options.oscillator);161 }162 // Init timer list163 this.playCallbackTimers = [];164};165/**166 * Return a copy of an instrument. Only one instrument instance can play at a167 * time, so use this to get a new copy of the instrument that can play alongside168 * it. The new instrument copy will receive a new ID unless one is supplied in169 * options.170 *171 * @function Highcharts.Instrument#copy172 *173 * @param {Highcharts.InstrumentOptionsObject} [options]174 * Options to merge in for the copy.175 *176 * @return {Highcharts.Instrument}177 * A new Instrument instance with the same options.178 */179Instrument.prototype.copy = function (options) {180 return new Instrument(H.merge(this.options, { id: null }, options));181};182/**183 * Init the audio context, if we do not have one.184 * @private185 * @return {boolean} True if successful, false if not.186 */187Instrument.prototype.initAudioContext = function () {188 var Context = H.win.AudioContext || H.win.webkitAudioContext, hasOldContext = !!H.audioContext;189 if (Context) {190 H.audioContext = H.audioContext || new Context();191 if (!hasOldContext &&192 H.audioContext &&193 H.audioContext.state === 'running') {194 H.audioContext.suspend(); // Pause until we need it195 }196 return !!(H.audioContext &&197 H.audioContext.createOscillator &&198 H.audioContext.createGain);199 }200 return false;201};202/**203 * Init an oscillator instrument.204 * @private205 * @param {Highcharts.OscillatorOptionsObject} oscillatorOptions206 * The oscillator options passed to Highcharts.Instrument#init.207 * @return {void}208 */209Instrument.prototype.initOscillator = function (options) {210 var ctx = H.audioContext;211 this.oscillator = ctx.createOscillator();212 this.oscillator.type = options.waveformShape;213 this.oscillator.connect(this.gainNode);214 this.oscillatorStarted = false;215};216/**217 * Set pan position.218 * @private219 * @param {number} panValue220 * The pan position to set for the instrument.221 * @return {void}222 */223Instrument.prototype.setPan = function (panValue) {224 if (this.panNode) {225 this.panNode.pan.setValueAtTime(panValue, H.audioContext.currentTime);226 }227};228/**229 * Set gain level. A maximum of 1.2 is allowed before we emit a warning. The230 * actual volume is not set above this level regardless of input.231 * @private232 * @param {number} gainValue233 * The gain level to set for the instrument.234 * @param {number} [rampTime=0]235 * Gradually change the gain level, time given in milliseconds.236 * @return {void}237 */238Instrument.prototype.setGain = function (gainValue, rampTime) {239 if (this.gainNode) {240 if (gainValue > 1.2) {241 console.warn(// eslint-disable-line242 'Highcharts sonification warning: ' +243 'Volume of instrument set too high.');244 gainValue = 1.2;245 }246 if (rampTime) {247 this.gainNode.gain.setValueAtTime(this.gainNode.gain.value, H.audioContext.currentTime);248 this.gainNode.gain.linearRampToValueAtTime(gainValue, H.audioContext.currentTime + rampTime / 1000);249 }250 else {251 this.gainNode.gain.setValueAtTime(gainValue, H.audioContext.currentTime);252 }253 }254};255/**256 * Cancel ongoing gain ramps.257 * @private258 * @return {void}259 */260Instrument.prototype.cancelGainRamp = function () {261 if (this.gainNode) {262 this.gainNode.gain.cancelScheduledValues(0);263 }264};265/**266 * Get the closest valid frequency for this instrument.267 * @private268 * @param {number} frequency - The target frequency.269 * @param {number} [min] - Minimum frequency to return.270 * @param {number} [max] - Maximum frequency to return.271 * @return {number} The closest valid frequency to the input frequency.272 */273Instrument.prototype.getValidFrequency = function (frequency, min, max) {274 var validFrequencies = this.options.allowedFrequencies, maximum = pick(max, Infinity), minimum = pick(min, -Infinity);275 return !validFrequencies || !validFrequencies.length ?276 // No valid frequencies for this instrument, return the target277 frequency :278 // Use the valid frequencies and return the closest match279 validFrequencies.reduce(function (acc, cur) {280 // Find the closest allowed value281 return Math.abs(cur - frequency) < Math.abs(acc - frequency) &&282 cur < maximum && cur > minimum ?283 cur : acc;284 }, Infinity);285};286/**287 * Clear existing play callback timers.288 * @private289 * @return {void}290 */291Instrument.prototype.clearPlayCallbackTimers = function () {292 this.playCallbackTimers.forEach(function (timer) {293 clearInterval(timer);294 });295 this.playCallbackTimers = [];296};297/**298 * Set the current frequency being played by the instrument. The closest valid299 * frequency between the frequency limits is used.300 * @param {number} frequency301 * The frequency to set.302 * @param {Highcharts.Dictionary<number>} [frequencyLimits]303 * Object with maxFrequency and minFrequency304 * @return {void}305 */306Instrument.prototype.setFrequency = function (frequency, frequencyLimits) {307 var limits = frequencyLimits || {}, validFrequency = this.getValidFrequency(frequency, limits.min, limits.max);308 if (this.options.type === 'oscillator') {309 this.oscillatorPlay(validFrequency);310 }311};312/**313 * Play oscillator instrument.314 * @private315 * @param {number} frequency - The frequency to play.316 */317Instrument.prototype.oscillatorPlay = function (frequency) {318 if (!this.oscillatorStarted) {319 this.oscillator.start();320 this.oscillatorStarted = true;321 }322 this.oscillator.frequency.setValueAtTime(frequency, H.audioContext.currentTime);323};324/**325 * Prepare instrument before playing. Resumes the audio context and starts the326 * oscillator.327 * @private328 */329Instrument.prototype.preparePlay = function () {330 this.setGain(0.001);331 if (H.audioContext.state === 'suspended') {332 H.audioContext.resume();333 }334 if (this.oscillator && !this.oscillatorStarted) {335 this.oscillator.start();336 this.oscillatorStarted = true;337 }338};339/**340 * Play the instrument according to options.341 *342 * @sample highcharts/sonification/instrument/343 * Using Instruments directly344 * @sample highcharts/sonification/instrument-advanced/345 * Using callbacks for instrument parameters346 *347 * @function Highcharts.Instrument#play348 *349 * @param {Highcharts.InstrumentPlayOptionsObject} options350 * Options for the playback of the instrument.351 *352 * @return {void}353 */354Instrument.prototype.play = function (options) {355 var instrument = this, duration = options.duration || 0, 356 // Set a value, or if it is a function, set it continously as a timer.357 // Pass in the value/function to set, the setter function, and any358 // additional data to pass through to the setter function.359 setOrStartTimer = function (value, setter, setterData) {360 var target = options.duration, currentDurationIx = 0, callbackInterval = instrument.options.playCallbackInterval;361 if (typeof value === 'function') {362 var timer = setInterval(function () {363 currentDurationIx++;364 var curTime = (currentDurationIx * callbackInterval / target);365 if (curTime >= 1) {366 instrument[setter](value(1), setterData);367 clearInterval(timer);368 }369 else {370 instrument[setter](value(curTime), setterData);371 }372 }, callbackInterval);373 instrument.playCallbackTimers.push(timer);374 }375 else {376 instrument[setter](value, setterData);377 }378 };379 if (!instrument.id) {380 // No audio support - do nothing381 return;382 }383 // If the AudioContext is suspended we have to resume it before playing384 if (H.audioContext.state === 'suspended' ||385 this.oscillator && !this.oscillatorStarted) {386 instrument.preparePlay();387 // Try again in 10ms388 setTimeout(function () {389 instrument.play(options);390 }, 10);391 return;392 }393 // Clear any existing play timers394 if (instrument.playCallbackTimers.length) {395 instrument.clearPlayCallbackTimers();396 }397 // Clear any gain ramps398 instrument.cancelGainRamp();399 // Clear stop oscillator timer400 if (instrument.stopOscillatorTimeout) {401 clearTimeout(instrument.stopOscillatorTimeout);402 delete instrument.stopOscillatorTimeout;403 }404 // If a note is playing right now, clear the stop timeout, and call the405 // callback.406 if (instrument.stopTimeout) {407 clearTimeout(instrument.stopTimeout);408 delete instrument.stopTimeout;409 if (instrument.stopCallback) {410 // We have a callback for the play we are interrupting. We do not411 // allow this callback to start a new play, because that leads to412 // chaos. We pass in 'cancelled' to indicate that this note did not413 // finish, but still stopped.414 instrument._play = instrument.play;415 instrument.play = function () { };416 instrument.stopCallback('cancelled');417 instrument.play = instrument._play;418 }419 }420 // Stop the note without fadeOut if the duration is too short to hear the421 // note otherwise.422 var immediate = duration < H.sonification.fadeOutDuration + 20;423 // Stop the instrument after the duration of the note424 instrument.stopCallback = options.onEnd;425 var onStop = function () {426 delete instrument.stopTimeout;427 instrument.stop(immediate);428 };429 if (duration) {430 instrument.stopTimeout = setTimeout(onStop, immediate ? duration :431 duration - H.sonification.fadeOutDuration);432 // Play the note433 setOrStartTimer(options.frequency, 'setFrequency', {434 minFrequency: options.minFrequency,435 maxFrequency: options.maxFrequency436 });437 // Set the volume and panning438 setOrStartTimer(pick(options.volume, 1), 'setGain', 4); // Slight ramp439 setOrStartTimer(pick(options.pan, 0), 'setPan');440 }441 else {442 // No note duration, so just stop immediately443 onStop();444 }445};446/**447 * Mute an instrument that is playing. If the instrument is not currently448 * playing, this function does nothing.449 *450 * @function Highcharts.Instrument#mute451 */452Instrument.prototype.mute = function () {453 this.setGain(0.0001, H.sonification.fadeOutDuration * 0.8);454};455/**456 * Stop the instrument playing.457 *458 * @function Highcharts.Instrument#stop459 *460 * @param {boolean} immediately461 * Whether to do the stop immediately or fade out.462 *463 * @param {Function} [onStopped]464 * Callback function to be called when the stop is completed.465 *466 * @param {*} [callbackData]467 * Data to send to the onEnd callback functions.468 *469 * @return {void}470 */471Instrument.prototype.stop = function (immediately, onStopped, callbackData) {472 var instr = this, reset = function () {473 // Remove timeout reference474 if (instr.stopOscillatorTimeout) {475 delete instr.stopOscillatorTimeout;476 }477 // The oscillator may have stopped in the meantime here, so allow478 // this function to fail if so.479 try {480 instr.oscillator.stop();481 }482 catch (e) {483 // silent error484 }485 instr.oscillator.disconnect(instr.gainNode);486 // We need a new oscillator in order to restart it487 instr.initOscillator(instr.options.oscillator);488 // Done stopping, call the callback from the stop489 if (onStopped) {490 onStopped(callbackData);491 }492 // Call the callback for the play we finished493 if (instr.stopCallback) {494 instr.stopCallback(callbackData);495 }496 };497 // Clear any existing timers498 if (instr.playCallbackTimers.length) {499 instr.clearPlayCallbackTimers();500 }501 if (instr.stopTimeout) {502 clearTimeout(instr.stopTimeout);503 }504 if (immediately) {505 instr.setGain(0);506 reset();507 }508 else {509 instr.mute();510 // Stop the oscillator after the mute fade-out has finished511 instr.stopOscillatorTimeout =512 setTimeout(reset, H.sonification.fadeOutDuration + 100);513 }514};...
pointSonify.js
Source:pointSonify.js
1/* *2 *3 * (c) 2009-2019 Ãystein Moseng4 *5 * Code for sonifying single points.6 *7 * License: www.highcharts.com/license8 *9 * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!10 *11 * */12'use strict';13import H from '../../parts/Globals.js';14import U from '../../parts/Utilities.js';15var pick = U.pick;16/**17 * Define the parameter mapping for an instrument.18 *19 * @requires module:modules/sonification20 *21 * @interface Highcharts.PointInstrumentMappingObject22 */ /**23* Define the volume of the instrument. This can be a string with a data24* property name, e.g. `'y'`, in which case this data property is used to define25* the volume relative to the `y`-values of the other points. A higher `y` value26* would then result in a higher volume. This option can also be a fixed number27* or a function. If it is a function, this function is called in regular28* intervals while the note is playing. It receives three arguments: The point,29* the dataExtremes, and the current relative time - where 0 is the beginning of30* the note and 1 is the end. The function should return the volume of the note31* as a number between 0 and 1.32* @name Highcharts.PointInstrumentMappingObject#volume33* @type {string|number|Function}34*/ /**35* Define the duration of the notes for this instrument. This can be a string36* with a data property name, e.g. `'y'`, in which case this data property is37* used to define the duration relative to the `y`-values of the other points. A38* higher `y` value would then result in a longer duration. This option can also39* be a fixed number or a function. If it is a function, this function is called40* once before the note starts playing, and should return the duration in41* milliseconds. It receives two arguments: The point, and the dataExtremes.42* @name Highcharts.PointInstrumentMappingObject#duration43* @type {string|number|Function}44*/ /**45* Define the panning of the instrument. This can be a string with a data46* property name, e.g. `'x'`, in which case this data property is used to define47* the panning relative to the `x`-values of the other points. A higher `x`48* value would then result in a higher panning value (panned further to the49* right). This option can also be a fixed number or a function. If it is a50* function, this function is called in regular intervals while the note is51* playing. It receives three arguments: The point, the dataExtremes, and the52* current relative time - where 0 is the beginning of the note and 1 is the53* end. The function should return the panning of the note as a number between54* -1 and 1.55* @name Highcharts.PointInstrumentMappingObject#pan56* @type {string|number|Function|undefined}57*/ /**58* Define the frequency of the instrument. This can be a string with a data59* property name, e.g. `'y'`, in which case this data property is used to define60* the frequency relative to the `y`-values of the other points. A higher `y`61* value would then result in a higher frequency. This option can also be a62* fixed number or a function. If it is a function, this function is called in63* regular intervals while the note is playing. It receives three arguments:64* The point, the dataExtremes, and the current relative time - where 0 is the65* beginning of the note and 1 is the end. The function should return the66* frequency of the note as a number (in Hz).67* @name Highcharts.PointInstrumentMappingObject#frequency68* @type {string|number|Function}69*/70/**71 * @requires module:modules/sonification72 *73 * @interface Highcharts.PointInstrumentOptionsObject74 */ /**75* The minimum duration for a note when using a data property for duration. Can76* be overridden by using either a fixed number or a function for77* instrumentMapping.duration. Defaults to 20.78* @name Highcharts.PointInstrumentOptionsObject#minDuration79* @type {number|undefined}80*/ /**81* The maximum duration for a note when using a data property for duration. Can82* be overridden by using either a fixed number or a function for83* instrumentMapping.duration. Defaults to 2000.84* @name Highcharts.PointInstrumentOptionsObject#maxDuration85* @type {number|undefined}86*/ /**87* The minimum pan value for a note when using a data property for panning. Can88* be overridden by using either a fixed number or a function for89* instrumentMapping.pan. Defaults to -1 (fully left).90* @name Highcharts.PointInstrumentOptionsObject#minPan91* @type {number|undefined}92*/ /**93* The maximum pan value for a note when using a data property for panning. Can94* be overridden by using either a fixed number or a function for95* instrumentMapping.pan. Defaults to 1 (fully right).96* @name Highcharts.PointInstrumentOptionsObject#maxPan97* @type {number|undefined}98*/ /**99* The minimum volume for a note when using a data property for volume. Can be100* overridden by using either a fixed number or a function for101* instrumentMapping.volume. Defaults to 0.1.102* @name Highcharts.PointInstrumentOptionsObject#minVolume103* @type {number|undefined}104*/ /**105* The maximum volume for a note when using a data property for volume. Can be106* overridden by using either a fixed number or a function for107* instrumentMapping.volume. Defaults to 1.108* @name Highcharts.PointInstrumentOptionsObject#maxVolume109* @type {number|undefined}110*/ /**111* The minimum frequency for a note when using a data property for frequency.112* Can be overridden by using either a fixed number or a function for113* instrumentMapping.frequency. Defaults to 220.114* @name Highcharts.PointInstrumentOptionsObject#minFrequency115* @type {number|undefined}116*/ /**117* The maximum frequency for a note when using a data property for frequency.118* Can be overridden by using either a fixed number or a function for119* instrumentMapping.frequency. Defaults to 2200.120* @name Highcharts.PointInstrumentOptionsObject#maxFrequency121* @type {number|undefined}122*/123/**124 * An instrument definition for a point, specifying the instrument to play and125 * how to play it.126 *127 * @interface Highcharts.PointInstrumentObject128 */ /**129* An Instrument instance or the name of the instrument in the130* Highcharts.sonification.instruments map.131* @name Highcharts.PointInstrumentObject#instrument132* @type {Highcharts.Instrument|string}133*/ /**134* Mapping of instrument parameters for this instrument.135* @name Highcharts.PointInstrumentObject#instrumentMapping136* @type {Highcharts.PointInstrumentMappingObject}137*/ /**138* Options for this instrument.139* @name Highcharts.PointInstrumentObject#instrumentOptions140* @type {Highcharts.PointInstrumentOptionsObject|undefined}141*/ /**142* Callback to call when the instrument has stopped playing.143* @name Highcharts.PointInstrumentObject#onEnd144* @type {Function|undefined}145*/146/**147 * Options for sonifying a point.148 * @interface Highcharts.PointSonifyOptionsObject149 */ /**150* The instrument definitions for this point.151* @name Highcharts.PointSonifyOptionsObject#instruments152* @type {Array<Highcharts.PointInstrumentObject>}153*/ /**154* Optionally provide the minimum/maximum values for the points. If this is not155* supplied, it is calculated from the points in the chart on demand. This156* option is supplied in the following format, as a map of point data properties157* to objects with min/max values:158* ```js159* dataExtremes: {160* y: {161* min: 0,162* max: 100163* },164* z: {165* min: -10,166* max: 10167* }168* // Properties used and not provided are calculated on demand169* }170* ```171* @name Highcharts.PointSonifyOptionsObject#dataExtremes172* @type {object|undefined}173*/ /**174* Callback called when the sonification has finished.175* @name Highcharts.PointSonifyOptionsObject#onEnd176* @type {Function|undefined}177*/178import utilities from './utilities.js';179// Defaults for the instrument options180// NOTE: Also change defaults in Highcharts.PointInstrumentOptionsObject if181// making changes here.182var defaultInstrumentOptions = {183 minDuration: 20,184 maxDuration: 2000,185 minVolume: 0.1,186 maxVolume: 1,187 minPan: -1,188 maxPan: 1,189 minFrequency: 220,190 maxFrequency: 2200191};192/* eslint-disable no-invalid-this, valid-jsdoc */193/**194 * Sonify a single point.195 *196 * @sample highcharts/sonification/point-basic/197 * Click on points to sonify198 * @sample highcharts/sonification/point-advanced/199 * Sonify bubbles200 *201 * @requires module:modules/sonification202 *203 * @function Highcharts.Point#sonify204 *205 * @param {Highcharts.PointSonifyOptionsObject} options206 * Options for the sonification of the point.207 *208 * @return {void}209 */210function pointSonify(options) {211 var point = this, chart = point.series.chart, dataExtremes = options.dataExtremes || {}, 212 // Get the value to pass to instrument.play from the mapping value213 // passed in.214 getMappingValue = function (value, makeFunction, allowedExtremes) {215 // Function. Return new function if we try to use callback,216 // otherwise call it now and return result.217 if (typeof value === 'function') {218 return makeFunction ?219 function (time) {220 return value(point, dataExtremes, time);221 } :222 value(point, dataExtremes);223 }224 // String, this is a data prop.225 if (typeof value === 'string') {226 // Find data extremes if we don't have them227 dataExtremes[value] = dataExtremes[value] ||228 utilities.calculateDataExtremes(point.series.chart, value);229 // Find the value230 return utilities.virtualAxisTranslate(pick(point[value], point.options[value]), dataExtremes[value], allowedExtremes);231 }232 // Fixed number or something else weird, just use that233 return value;234 };235 // Register playing point on chart236 chart.sonification.currentlyPlayingPoint = point;237 // Keep track of instruments playing238 point.sonification = point.sonification || {};239 point.sonification.instrumentsPlaying =240 point.sonification.instrumentsPlaying || {};241 // Register signal handler for the point242 var signalHandler = point.sonification.signalHandler =243 point.sonification.signalHandler ||244 new utilities.SignalHandler(['onEnd']);245 signalHandler.clearSignalCallbacks();246 signalHandler.registerSignalCallbacks({ onEnd: options.onEnd });247 // If we have a null point or invisible point, just return248 if (point.isNull || !point.visible || !point.series.visible) {249 signalHandler.emitSignal('onEnd');250 return;251 }252 // Go through instruments and play them253 options.instruments.forEach(function (instrumentDefinition) {254 var instrument = typeof instrumentDefinition.instrument === 'string' ?255 H.sonification.instruments[instrumentDefinition.instrument] :256 instrumentDefinition.instrument, mapping = instrumentDefinition.instrumentMapping || {}, extremes = H.merge(defaultInstrumentOptions, instrumentDefinition.instrumentOptions), id = instrument.id, onEnd = function (cancelled) {257 // Instrument on end258 if (instrumentDefinition.onEnd) {259 instrumentDefinition.onEnd.apply(this, arguments);260 }261 // Remove currently playing point reference on chart262 if (chart.sonification &&263 chart.sonification.currentlyPlayingPoint) {264 delete chart.sonification.currentlyPlayingPoint;265 }266 // Remove reference from instruments playing267 if (point.sonification && point.sonification.instrumentsPlaying) {268 delete point.sonification.instrumentsPlaying[id];269 // This was the last instrument?270 if (!Object.keys(point.sonification.instrumentsPlaying).length) {271 signalHandler.emitSignal('onEnd', cancelled);272 }273 }274 };275 // Play the note on the instrument276 if (instrument && instrument.play) {277 point.sonification.instrumentsPlaying[instrument.id] =278 instrument;279 instrument.play({280 frequency: getMappingValue(mapping.frequency, true, { min: extremes.minFrequency, max: extremes.maxFrequency }),281 duration: getMappingValue(mapping.duration, false, { min: extremes.minDuration, max: extremes.maxDuration }),282 pan: getMappingValue(mapping.pan, true, { min: extremes.minPan, max: extremes.maxPan }),283 volume: getMappingValue(mapping.volume, true, { min: extremes.minVolume, max: extremes.maxVolume }),284 onEnd: onEnd,285 minFrequency: extremes.minFrequency,286 maxFrequency: extremes.maxFrequency287 });288 }289 else {290 H.error(30);291 }292 });293}294/**295 * Cancel sonification of a point. Calls onEnd functions.296 *297 * @requires module:modules/sonification298 *299 * @function Highcharts.Point#cancelSonify300 *301 * @param {boolean} [fadeOut=false]302 * Whether or not to fade out as we stop. If false, the points are303 * cancelled synchronously.304 *305 * @return {void}306 */307function pointCancelSonify(fadeOut) {308 var playing = this.sonification && this.sonification.instrumentsPlaying, instrIds = playing && Object.keys(playing);309 if (instrIds && instrIds.length) {310 instrIds.forEach(function (instr) {311 playing[instr].stop(!fadeOut, null, 'cancelled');312 });313 this.sonification.instrumentsPlaying = {};314 this.sonification.signalHandler.emitSignal('onEnd', 'cancelled');315 }316}317var pointSonifyFunctions = {318 pointSonify: pointSonify,319 pointCancelSonify: pointCancelSonify320};...
InstrumentScope.js
Source:InstrumentScope.js
1var InstrumentScopeSecurityAltIDGrp = require('../components/InstrumentScopeSecurityAltIDGrp');2var InstrumentScopeSymbol = require('../fields/InstrumentScopeSymbol');3var InstrumentScopeSymbolSfx = require('../fields/InstrumentScopeSymbolSfx');4var InstrumentScopeSecurityID = require('../fields/InstrumentScopeSecurityID');5var InstrumentScopeSecurityIDSource = require('../fields/InstrumentScopeSecurityIDSource');6var InstrumentScopeProduct = require('../fields/InstrumentScopeProduct');7var InstrumentScopeProductComplex = require('../fields/InstrumentScopeProductComplex');8var InstrumentScopeSecurityGroup = require('../fields/InstrumentScopeSecurityGroup');9var InstrumentScopeCFICode = require('../fields/InstrumentScopeCFICode');10var InstrumentScopeSecurityType = require('../fields/InstrumentScopeSecurityType');11var InstrumentScopeSecuritySubType = require('../fields/InstrumentScopeSecuritySubType');12var InstrumentScopeMaturityMonthYear = require('../fields/InstrumentScopeMaturityMonthYear');13var InstrumentScopeMaturityTime = require('../fields/InstrumentScopeMaturityTime');14var InstrumentScopeRestructuringType = require('../fields/InstrumentScopeRestructuringType');15var InstrumentScopeSeniority = require('../fields/InstrumentScopeSeniority');16var InstrumentScopePutOrCall = require('../fields/InstrumentScopePutOrCall');17var InstrumentScopeFlexibleIndicator = require('../fields/InstrumentScopeFlexibleIndicator');18var InstrumentScopeCouponRate = require('../fields/InstrumentScopeCouponRate');19var InstrumentScopeSecurityExchange = require('../fields/InstrumentScopeSecurityExchange');20var InstrumentScopeSecurityDesc = require('../fields/InstrumentScopeSecurityDesc');21var InstrumentScopeEncodedSecurityDescLen = require('../fields/InstrumentScopeEncodedSecurityDescLen');22var InstrumentScopeEncodedSecurityDesc = require('../fields/InstrumentScopeEncodedSecurityDesc');23var InstrumentScopeSettlType = require('../fields/InstrumentScopeSettlType');24function InstrumentScope (instrumentScope) {25 this.message = instrumentScope;26}27/* component */28InstrumentScope.prototype.instrumentScopeSecurityAltIdgrp = function () {29 return this.message.groups[InstrumentScopeSecurityAltIDGrp.Tag]30 .map(function (instrumentScopeSecurityAltIdgrp) {31 return new InstrumentScopeSecurityAltIDGrp(instrumentScopeSecurityAltIdgrp);32 });33};34/* field */35InstrumentScope.prototype.instrumentScopeSymbol = function () {36 return new InstrumentScopeSymbol(this.message.tags[InstrumentScopeSymbol.Tag]);37};38/* field */39InstrumentScope.prototype.instrumentScopeSymbolSfx = function () {40 return new InstrumentScopeSymbolSfx(this.message.tags[InstrumentScopeSymbolSfx.Tag]);41};42/* field */43InstrumentScope.prototype.instrumentScopeSecurityId = function () {44 return new InstrumentScopeSecurityID(this.message.tags[InstrumentScopeSecurityID.Tag]);45};46/* field */47InstrumentScope.prototype.instrumentScopeSecurityIdsource = function () {48 return new InstrumentScopeSecurityIDSource(this.message.tags[InstrumentScopeSecurityIDSource.Tag]);49};50/* field */51InstrumentScope.prototype.instrumentScopeProduct = function () {52 return new InstrumentScopeProduct(this.message.tags[InstrumentScopeProduct.Tag]);53};54/* field */55InstrumentScope.prototype.instrumentScopeProductComplex = function () {56 return new InstrumentScopeProductComplex(this.message.tags[InstrumentScopeProductComplex.Tag]);57};58/* field */59InstrumentScope.prototype.instrumentScopeSecurityGroup = function () {60 return new InstrumentScopeSecurityGroup(this.message.tags[InstrumentScopeSecurityGroup.Tag]);61};62/* field */63InstrumentScope.prototype.instrumentScopeCficode = function () {64 return new InstrumentScopeCFICode(this.message.tags[InstrumentScopeCFICode.Tag]);65};66/* field */67InstrumentScope.prototype.instrumentScopeSecurityType = function () {68 return new InstrumentScopeSecurityType(this.message.tags[InstrumentScopeSecurityType.Tag]);69};70/* field */71InstrumentScope.prototype.instrumentScopeSecuritySubType = function () {72 return new InstrumentScopeSecuritySubType(this.message.tags[InstrumentScopeSecuritySubType.Tag]);73};74/* field */75InstrumentScope.prototype.instrumentScopeMaturityMonthYear = function () {76 return new InstrumentScopeMaturityMonthYear(this.message.tags[InstrumentScopeMaturityMonthYear.Tag]);77};78/* field */79InstrumentScope.prototype.instrumentScopeMaturityTime = function () {80 return new InstrumentScopeMaturityTime(this.message.tags[InstrumentScopeMaturityTime.Tag]);81};82/* field */83InstrumentScope.prototype.instrumentScopeRestructuringType = function () {84 return new InstrumentScopeRestructuringType(this.message.tags[InstrumentScopeRestructuringType.Tag]);85};86/* field */87InstrumentScope.prototype.instrumentScopeSeniority = function () {88 return new InstrumentScopeSeniority(this.message.tags[InstrumentScopeSeniority.Tag]);89};90/* field */91InstrumentScope.prototype.instrumentScopePutOrCall = function () {92 return new InstrumentScopePutOrCall(this.message.tags[InstrumentScopePutOrCall.Tag]);93};94/* field */95InstrumentScope.prototype.instrumentScopeFlexibleIndicator = function () {96 return new InstrumentScopeFlexibleIndicator(this.message.tags[InstrumentScopeFlexibleIndicator.Tag]);97};98/* field */99InstrumentScope.prototype.instrumentScopeCouponRate = function () {100 return new InstrumentScopeCouponRate(this.message.tags[InstrumentScopeCouponRate.Tag]);101};102/* field */103InstrumentScope.prototype.instrumentScopeSecurityExchange = function () {104 return new InstrumentScopeSecurityExchange(this.message.tags[InstrumentScopeSecurityExchange.Tag]);105};106/* field */107InstrumentScope.prototype.instrumentScopeSecurityDesc = function () {108 return new InstrumentScopeSecurityDesc(this.message.tags[InstrumentScopeSecurityDesc.Tag]);109};110/* field */111InstrumentScope.prototype.instrumentScopeEncodedSecurityDescLen = function () {112 return new InstrumentScopeEncodedSecurityDescLen(this.message.tags[InstrumentScopeEncodedSecurityDescLen.Tag]);113};114/* field */115InstrumentScope.prototype.instrumentScopeEncodedSecurityDesc = function () {116 return new InstrumentScopeEncodedSecurityDesc(this.message.tags[InstrumentScopeEncodedSecurityDesc.Tag]);117};118/* field */119InstrumentScope.prototype.instrumentScopeSettlType = function () {120 return new InstrumentScopeSettlType(this.message.tags[InstrumentScopeSettlType.Tag]);121};122InstrumentScope.Tag = '1536';...
instrumentSelect.js
Source:instrumentSelect.js
1/* global AlphaPoint, localStorage, document */2import React from 'react';3import uuidV4 from 'uuid/v4';4import {5 formatNumberToLocale6} from './helper';7class InstrumentSelect extends React.Component {8 constructor() {9 super();10 this.state = {11 instruments: [],12 instrumentTicks: {},13 selectedInstrument: null,14 };15 }16 componentDidUpdate(prevProps, prevState){17 if(this.state.instruments.length > 0 && this.state.instruments.length !== prevState.instruments.length){18 this.setState({...this.state, selectedInstrument: this.state.instruments.find(ins => ins.Symbol == 'ETHBTC').InstrumentId || 1})19 }20 }21 componentDidMount() {22 this.instruments = AlphaPoint.instruments23 .filter(instruments => instruments.length)24 .take(1)25 .subscribe((instruments) => {26 this.setState({ instruments }, () => this.selectInstrument(instruments.find(ins => ins.Symbol == 'ETHBTC').InstrumentId || 1));27 });28 if (AlphaPoint.config.instrumentSelectTicker) {29 this.tickers = AlphaPoint.instruments.subscribe(productPairs => {30 productPairs.forEach(pair => AlphaPoint.subscribeLvl1(pair.InstrumentId));31 });32 this.level1 = AlphaPoint.Level1.subscribe(instrumentTicks => {33 this.setState({ instrumentTicks });34 });35 this.products = AlphaPoint.products.filter(data => data.length).subscribe(prods => {36 const decimalPlaces = {};37 prods.forEach(product => {38 decimalPlaces[product.Product] = product.DecimalPlaces;39 });40 this.setState({ decimalPlaces });41 });42 }43 // this.instrumentCheck = AlphaPoint.instrumentChange.subscribe(i => this.setState({ selectedInstrument: i }));44 }45 componentWillUnmount() {46 this.instruments.dispose();47 if (AlphaPoint.config.instrumentSelectTicker) {48 this.level1.dispose();49 this.tickers.dispose();50 this.products.dispose();51 }52 this.instrumentCheck.dispose();53 }54 selectInstrument = (instrumentId) => {55 const selectedInstrument = +instrumentId;56 const instrument = this.state.instruments.find((inst) => inst.InstrumentId === selectedInstrument);57 localStorage.setItem('SessionInstrumentId', selectedInstrument);58 document.APAPI.Session.SelectedInstrumentId = selectedInstrument;59 localStorage.setItem('SessionPair', instrument.Symbol);60 AlphaPoint.setProductPair(instrument.Symbol);61 AlphaPoint.instrumentChange.onNext(selectedInstrument);62 if (this.state.selectedInstrument) {63 this.unsubscribeInstrument(this.state.selectedInstrument);64 }65 this.subscribeInstrument(selectedInstrument);66 this.setState({ selectedInstrument });67 };68 subscribeInstrument = (InstrumentId) => {69 AlphaPoint.subscribeTrades(InstrumentId, 100);70 AlphaPoint.subscribeLvl2(InstrumentId);71 };72 unsubscribeInstrument = (InstrumentId) => {73 AlphaPoint.unsubscribeTradesCall(InstrumentId);74 AlphaPoint.unsubscribeLvl2(InstrumentId);75 };76 render() {77 const instrumentTicks = this.state.instrumentTicks;78 const instrument = this.state.instruments.find(ins => ins.InstrumentId == this.state.selectedInstrument);79 const decimalPlaces = this.state.decimalPlaces;80 const instrumentsList = this.state.instruments81 .filter((inst) => (inst.InstrumentId !== (instrument && instrument.InstrumentId)) && inst.Symbol === 'ETHBTC')82 .map((inst) => (83 <li key={uuidV4()} className={`instrument-${inst.Symbol}`}84 onClick={(e) => {85 e.preventDefault();86 this.selectInstrument(inst.InstrumentId);87 }}88 >89 <a90 className={AlphaPoint.config.instrumentSelectTicker && "instrument-symbol"}91 >{AlphaPoint.config.reversePairs ? (inst.Product2Symbol + inst.Product1Symbol) : inst.Symbol}</a>92 { AlphaPoint.config.instrumentSelectTicker &&93 <div className="instrument-row--detail">94 <div className="instrument-row__detail-price" data-value={ instrumentTicks[inst.InstrumentId] && formatNumberToLocale(instrumentTicks[inst.InstrumentId].LastTradedPx, decimalPlaces[inst.Product2Symbol]) }>95 </div>96 <div className="instrument-row__detail-change" data-value={ instrumentTicks[inst.InstrumentId] && formatNumberToLocale(instrumentTicks[inst.InstrumentId].Rolling24HrPxChange, decimalPlaces[inst.Product2Symbol] || AlphaPoint.config.decimalPlaces) }>97 </div>98 <div className="instrument-row__detail-volume" data-value={ instrumentTicks[inst.InstrumentId] && formatNumberToLocale(instrumentTicks[inst.InstrumentId].Rolling24HrVolume, decimalPlaces[inst.Product2Symbol] || AlphaPoint.config.decimalPlaces) }>99 </div>100 </div>101 }102 </li>103 ));104 const dropdownStyle = AlphaPoint.config.instrumentSelectTicker ? { minWidth: "400px", right: 'unset' } : { right: 'unset' };105 return (106 <div className="dropdown instrument-dropdown">107 <button id="instrument-select" className="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">108 <img src="img/ethereum.svg"/>109 {instrument && instrument.Symbol}110 {instrumentsList.length ? <span className="caret" style={{ marginLeft: '8px' }} /> : null}111 </button>112 {instrumentsList.length ?113 <ul className="dropdown-menu" style={dropdownStyle} aria-labelledby="dropdownMenu2">114 { AlphaPoint.config.instrumentSelectTicker &&115 <li key={uuidV4()} className="instrument-header">116 <div>{AlphaPoint.translation('INSTRUMENT_SELECT.INSTRUMENT') || 'Pair'}</div>117 <div>{AlphaPoint.translation('INSTRUMENT_SELECT.LAST_PRICE') || 'Price'}</div>118 <div>{AlphaPoint.translation('INSTRUMENT_SELECT.T24_HOUR_CHANGE') || '24hr Chg'}</div>119 <div>{AlphaPoint.translation('INSTRUMENT_SELECT.VOLUME') || 'Volume'}</div>120 </li>121 }122 {instrumentsList}123 </ul> : null}124 </div>125 );126 }127}...
instrument.ts
Source:instrument.ts
1import { Action, ActionCreator } from 'redux';2import { InstrumentEnum } from '../../../models/base';3import { ID } from '../../../models/types';4// instrument action after refactoring5export const INSTRUMENT_CREATE = 'INSTRUMENT_CREATE';6export type INSTRUMENT_CREATE = typeof INSTRUMENT_CREATE;7export interface ICreateInstrumentAction extends Action<INSTRUMENT_CREATE> {8 type: INSTRUMENT_CREATE;9 payload: InstrumentEnum;10}11export const createInstrumentAction: ActionCreator<ICreateInstrumentAction> = (instrument: InstrumentEnum) => ({12 type: INSTRUMENT_CREATE,13 payload: instrument,14});15export const INSTRUMENT_PLAY_START = 'INSTRUMENT_PLAY_START';16export type INSTRUMENT_PLAY_START = typeof INSTRUMENT_PLAY_START;17export interface IStartPlayInstrumentAction extends Action<INSTRUMENT_PLAY_START> {18 type: INSTRUMENT_PLAY_START;19 payload: ID;20}21export const startPlayInstrumentAction: ActionCreator<IStartPlayInstrumentAction> = (id: ID) => ({22 type: INSTRUMENT_PLAY_START,23 payload: id,24});25export const INSTRUMENT_PLAY_STOP = 'INSTRUMENT_PLAY_STOP';26export type INSTRUMENT_PLAY_STOP = typeof INSTRUMENT_PLAY_STOP;27export interface IStopPlayInstrumentAction extends Action<INSTRUMENT_PLAY_STOP> {28 type: INSTRUMENT_PLAY_STOP;29 payload: ID;30}31export const stopPlayInstrumentAction: ActionCreator<IStopPlayInstrumentAction> = (id: ID) => ({32 type: INSTRUMENT_PLAY_STOP,33 payload: id,34});35export type InstrumentAction =36 IStartPlayInstrumentAction |37 IStopPlayInstrumentAction |...
Using AI Code Generation
1const { instrument } = require('stryker-parent');2const fs = require('fs');3const path = require('path');4const code = fs.readFileSync(path.resolve(__dirname, 'src', 'index.js'), 'utf8');5const instrumentedCode = instrument(code, 'src/index.js');6fs.writeFileSync(path.resolve(__dirname, 'instrumented.js'), instrumentedCode);
Using AI Code Generation
1var stryker = require('stryker-parent').instrument;2var stryker = require('stryker-parent').instrument;3var stryker = require('stryker-parent').instrument;4var stryker = require('stryker-parent').instrument;5var stryker = require('stryker-parent').instrument;6var stryker = require('stryker-parent').instrument;7var stryker = require('stryker-parent').instrument;8var stryker = require('stryker-parent').instrument;9var stryker = require('stryker-parent').instrument;10var stryker = require('stryker-parent').instrument;11var stryker = require('stryker-parent').instrument;12var stryker = require('stryker-parent').instrument;13var stryker = require('stryker-parent').instrument;14var stryker = require('stryker-parent').instrument;15var stryker = require('stryker-parent').instrument;16var stryker = require('stryker-parent').instrument;17var stryker = require('stryker-parent').instrument;18var stryker = require('stryker-parent').instrument;
Using AI Code Generation
1const stryker = require('stryker-parent');2stryker.instrument('path/to/file.js');3const stryker = require('stryker-parent');4stryker.instrument('path/to/file.js');5const stryker = require('stryker-parent');6stryker.instrument('path/to/file.js');7const stryker = require('stryker-parent');8stryker.instrument('path/to/file.js');9const stryker = require('stryker-parent');10stryker.instrument('path/to/file.js');11const stryker = require('stryker-parent');12stryker.instrument('path/to/file.js');13const stryker = require('stryker-parent');14stryker.instrument('path/to/file.js');15const stryker = require('stryker-parent');16stryker.instrument('path/to/file.js');17const stryker = require('stryker-parent');18stryker.instrument('path/to/file.js');19const stryker = require('stryker-parent');20stryker.instrument('path/to/file.js');21const stryker = require('stryker-parent');22stryker.instrument('path/to/file.js');23const stryker = require('stryker-parent');24stryker.instrument('path/to/file.js');25const stryker = require('stryker-parent');26stryker.instrument('path/to/file.js');
Using AI Code Generation
1var stryker = require('stryker-parent');2stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {3 console.log(instrumentedFile);4});5var stryker = require('stryker-parent');6stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {7 console.log(instrumentedFile);8});9var stryker = require('stryker-parent');10stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {11 console.log(instrumentedFile);12});13var stryker = require('stryker-parent');14stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {15 console.log(instrumentedFile);16});17var stryker = require('stryker-parent');18stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {19 console.log(instrumentedFile);20});21var stryker = require('stryker-parent');22stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {23 console.log(instrumentedFile);24});25var stryker = require('stryker-parent');26stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {27 console.log(instrumentedFile);28});29var stryker = require('stryker-parent');30stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {31 console.log(instrumentedFile);32});33var stryker = require('stryker-parent');34stryker.instrument('test.js', 'test.js', function (error, instrumentedFile) {35 console.log(in
Using AI Code Generation
1const { instrument } = require('stryker-parent');2const foo = 1;3const bar = 2;4const instrumented = instrument('test.js', 'var foo = 1; var bar = 2;');5console.log(instrumented);6var foo = 1; var bar = 2;7### instrument(fileName, code, options)8* `plugins` (optional) An array of plugins that will be loaded by Stryker. See [Stryker plugins](
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!!