How to use interval method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

time.models.ts

Source:time.models.ts Github

copy

Full Screen

1///2/// Copyright © 2016-2022 The Thingsboard Authors3///4/// Licensed under the Apache License, Version 2.0 (the "License");5/// you may not use this file except in compliance with the License.6/// You may obtain a copy of the License at7///8/// http://www.apache.org/licenses/LICENSE-2.09///10/// Unless required by applicable law or agreed to in writing, software11/// distributed under the License is distributed on an "AS IS" BASIS,12/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13/// See the License for the specific language governing permissions and14/// limitations under the License.15///16import { TimeService } from '@core/services/time.service';17import { deepClone, isDefined, isNumeric, isUndefined } from '@app/core/utils';18import * as moment_ from 'moment';19import * as momentTz from 'moment-timezone';20const moment = moment_;21export const SECOND = 1000;22export const MINUTE = 60 * SECOND;23export const HOUR = 60 * MINUTE;24export const DAY = 24 * HOUR;25export const WEEK = 7 * DAY;26export const YEAR = DAY * 365;27export type ComparisonDuration = moment_.unitOfTime.DurationConstructor | 'previousInterval' | 'customInterval';28export enum TimewindowType {29 REALTIME,30 HISTORY31}32export enum RealtimeWindowType {33 LAST_INTERVAL,34 INTERVAL35}36export enum HistoryWindowType {37 LAST_INTERVAL,38 FIXED,39 INTERVAL40}41export interface IntervalWindow {42 interval?: number;43 timewindowMs?: number;44 quickInterval?: QuickTimeInterval;45}46export interface RealtimeWindow extends IntervalWindow{47 realtimeType?: RealtimeWindowType;48}49export interface FixedWindow {50 startTimeMs: number;51 endTimeMs: number;52}53export interface HistoryWindow extends IntervalWindow {54 historyType?: HistoryWindowType;55 fixedTimewindow?: FixedWindow;56}57export enum AggregationType {58 MIN = 'MIN',59 MAX = 'MAX',60 AVG = 'AVG',61 SUM = 'SUM',62 COUNT = 'COUNT',63 NONE = 'NONE'64}65export const aggregationTranslations = new Map<AggregationType, string>(66 [67 [AggregationType.MIN, 'aggregation.min'],68 [AggregationType.MAX, 'aggregation.max'],69 [AggregationType.AVG, 'aggregation.avg'],70 [AggregationType.SUM, 'aggregation.sum'],71 [AggregationType.COUNT, 'aggregation.count'],72 [AggregationType.NONE, 'aggregation.none'],73 ]74);75export interface Aggregation {76 interval?: number;77 type: AggregationType;78 limit: number;79}80export interface Timewindow {81 displayValue?: string;82 displayTimezoneAbbr?: string;83 hideInterval?: boolean;84 hideAggregation?: boolean;85 hideAggInterval?: boolean;86 hideTimezone?: boolean;87 selectedTab?: TimewindowType;88 realtime?: RealtimeWindow;89 history?: HistoryWindow;90 aggregation?: Aggregation;91 timezone?: string;92}93export interface SubscriptionAggregation extends Aggregation {94 interval?: number;95 timeWindow?: number;96 stateData?: boolean;97}98export interface SubscriptionTimewindow {99 startTs?: number;100 quickInterval?: QuickTimeInterval;101 timezone?: string;102 tsOffset?: number;103 realtimeWindowMs?: number;104 fixedWindow?: FixedWindow;105 aggregation?: SubscriptionAggregation;106 timeForComparison?: ComparisonDuration;107}108export interface WidgetTimewindow {109 minTime?: number;110 maxTime?: number;111 interval?: number;112 timezone?: string;113 stDiff?: number;114}115export enum QuickTimeInterval {116 YESTERDAY = 'YESTERDAY',117 DAY_BEFORE_YESTERDAY = 'DAY_BEFORE_YESTERDAY',118 THIS_DAY_LAST_WEEK = 'THIS_DAY_LAST_WEEK',119 PREVIOUS_WEEK = 'PREVIOUS_WEEK',120 PREVIOUS_WEEK_ISO = 'PREVIOUS_WEEK_ISO',121 PREVIOUS_MONTH = 'PREVIOUS_MONTH',122 PREVIOUS_YEAR = 'PREVIOUS_YEAR',123 CURRENT_HOUR = 'CURRENT_HOUR',124 CURRENT_DAY = 'CURRENT_DAY',125 CURRENT_DAY_SO_FAR = 'CURRENT_DAY_SO_FAR',126 CURRENT_WEEK = 'CURRENT_WEEK',127 CURRENT_WEEK_ISO = 'CURRENT_WEEK_ISO',128 CURRENT_WEEK_SO_FAR = 'CURRENT_WEEK_SO_FAR',129 CURRENT_WEEK_ISO_SO_FAR = 'CURRENT_WEEK_ISO_SO_FAR',130 CURRENT_MONTH = 'CURRENT_MONTH',131 CURRENT_MONTH_SO_FAR = 'CURRENT_MONTH_SO_FAR',132 CURRENT_YEAR = 'CURRENT_YEAR',133 CURRENT_YEAR_SO_FAR = 'CURRENT_YEAR_SO_FAR'134}135export const QuickTimeIntervalTranslationMap = new Map<QuickTimeInterval, string>([136 [QuickTimeInterval.YESTERDAY, 'timeinterval.predefined.yesterday'],137 [QuickTimeInterval.DAY_BEFORE_YESTERDAY, 'timeinterval.predefined.day-before-yesterday'],138 [QuickTimeInterval.THIS_DAY_LAST_WEEK, 'timeinterval.predefined.this-day-last-week'],139 [QuickTimeInterval.PREVIOUS_WEEK, 'timeinterval.predefined.previous-week'],140 [QuickTimeInterval.PREVIOUS_WEEK_ISO, 'timeinterval.predefined.previous-week-iso'],141 [QuickTimeInterval.PREVIOUS_MONTH, 'timeinterval.predefined.previous-month'],142 [QuickTimeInterval.PREVIOUS_YEAR, 'timeinterval.predefined.previous-year'],143 [QuickTimeInterval.CURRENT_HOUR, 'timeinterval.predefined.current-hour'],144 [QuickTimeInterval.CURRENT_DAY, 'timeinterval.predefined.current-day'],145 [QuickTimeInterval.CURRENT_DAY_SO_FAR, 'timeinterval.predefined.current-day-so-far'],146 [QuickTimeInterval.CURRENT_WEEK, 'timeinterval.predefined.current-week'],147 [QuickTimeInterval.CURRENT_WEEK_ISO, 'timeinterval.predefined.current-week-iso'],148 [QuickTimeInterval.CURRENT_WEEK_SO_FAR, 'timeinterval.predefined.current-week-so-far'],149 [QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR, 'timeinterval.predefined.current-week-iso-so-far'],150 [QuickTimeInterval.CURRENT_MONTH, 'timeinterval.predefined.current-month'],151 [QuickTimeInterval.CURRENT_MONTH_SO_FAR, 'timeinterval.predefined.current-month-so-far'],152 [QuickTimeInterval.CURRENT_YEAR, 'timeinterval.predefined.current-year'],153 [QuickTimeInterval.CURRENT_YEAR_SO_FAR, 'timeinterval.predefined.current-year-so-far']154]);155export function historyInterval(timewindowMs: number): Timewindow {156 return {157 selectedTab: TimewindowType.HISTORY,158 history: {159 historyType: HistoryWindowType.LAST_INTERVAL,160 timewindowMs161 }162 };163}164export function defaultTimewindow(timeService: TimeService): Timewindow {165 const currentTime = moment().valueOf();166 return {167 displayValue: '',168 hideInterval: false,169 hideAggregation: false,170 hideAggInterval: false,171 hideTimezone: false,172 selectedTab: TimewindowType.REALTIME,173 realtime: {174 realtimeType: RealtimeWindowType.LAST_INTERVAL,175 interval: SECOND,176 timewindowMs: MINUTE,177 quickInterval: QuickTimeInterval.CURRENT_DAY178 },179 history: {180 historyType: HistoryWindowType.LAST_INTERVAL,181 interval: SECOND,182 timewindowMs: MINUTE,183 fixedTimewindow: {184 startTimeMs: currentTime - DAY,185 endTimeMs: currentTime186 },187 quickInterval: QuickTimeInterval.CURRENT_DAY188 },189 aggregation: {190 type: AggregationType.AVG,191 limit: Math.floor(timeService.getMaxDatapointsLimit() / 2)192 }193 };194}195function getTimewindowType(timewindow: Timewindow): TimewindowType {196 if (isUndefined(timewindow.selectedTab)) {197 return isDefined(timewindow.realtime) ? TimewindowType.REALTIME : TimewindowType.HISTORY;198 } else {199 return timewindow.selectedTab;200 }201}202export function initModelFromDefaultTimewindow(value: Timewindow, timeService: TimeService): Timewindow {203 const model = defaultTimewindow(timeService);204 if (value) {205 model.hideInterval = value.hideInterval;206 model.hideAggregation = value.hideAggregation;207 model.hideAggInterval = value.hideAggInterval;208 model.hideTimezone = value.hideTimezone;209 model.selectedTab = getTimewindowType(value);210 if (model.selectedTab === TimewindowType.REALTIME) {211 if (isDefined(value.realtime.interval)) {212 model.realtime.interval = value.realtime.interval;213 }214 if (isUndefined(value.realtime.realtimeType)) {215 if (isDefined(value.realtime.quickInterval)) {216 model.realtime.realtimeType = RealtimeWindowType.INTERVAL;217 } else {218 model.realtime.realtimeType = RealtimeWindowType.LAST_INTERVAL;219 }220 } else {221 model.realtime.realtimeType = value.realtime.realtimeType;222 }223 if (model.realtime.realtimeType === RealtimeWindowType.INTERVAL) {224 model.realtime.quickInterval = value.realtime.quickInterval;225 } else {226 model.realtime.timewindowMs = value.realtime.timewindowMs;227 }228 } else {229 if (isDefined(value.history.interval)) {230 model.history.interval = value.history.interval;231 }232 if (isUndefined(value.history.historyType)) {233 if (isDefined(value.history.timewindowMs)) {234 model.history.historyType = HistoryWindowType.LAST_INTERVAL;235 } else if (isDefined(value.history.quickInterval)) {236 model.history.historyType = HistoryWindowType.INTERVAL;237 } else {238 model.history.historyType = HistoryWindowType.FIXED;239 }240 } else {241 model.history.historyType = value.history.historyType;242 }243 if (model.history.historyType === HistoryWindowType.LAST_INTERVAL) {244 model.history.timewindowMs = value.history.timewindowMs;245 } else if (model.history.historyType === HistoryWindowType.INTERVAL) {246 model.history.quickInterval = value.history.quickInterval;247 } else {248 model.history.fixedTimewindow.startTimeMs = value.history.fixedTimewindow.startTimeMs;249 model.history.fixedTimewindow.endTimeMs = value.history.fixedTimewindow.endTimeMs;250 }251 }252 if (value.aggregation) {253 if (value.aggregation.type) {254 model.aggregation.type = value.aggregation.type;255 }256 model.aggregation.limit = value.aggregation.limit || Math.floor(timeService.getMaxDatapointsLimit() / 2);257 }258 model.timezone = value.timezone;259 }260 return model;261}262export function toHistoryTimewindow(timewindow: Timewindow, startTimeMs: number, endTimeMs: number,263 interval: number, timeService: TimeService): Timewindow {264 if (timewindow.history) {265 interval = isDefined(interval) ? interval : timewindow.history.interval;266 } else if (timewindow.realtime) {267 interval = timewindow.realtime.interval;268 } else {269 interval = 0;270 }271 let aggType: AggregationType;272 let limit: number;273 if (timewindow.aggregation) {274 aggType = timewindow.aggregation.type || AggregationType.AVG;275 limit = timewindow.aggregation.limit || timeService.getMaxDatapointsLimit();276 } else {277 aggType = AggregationType.AVG;278 limit = timeService.getMaxDatapointsLimit();279 }280 return {281 hideInterval: timewindow.hideInterval || false,282 hideAggregation: timewindow.hideAggregation || false,283 hideAggInterval: timewindow.hideAggInterval || false,284 hideTimezone: timewindow.hideTimezone || false,285 selectedTab: TimewindowType.HISTORY,286 history: {287 historyType: HistoryWindowType.FIXED,288 fixedTimewindow: {289 startTimeMs,290 endTimeMs291 },292 interval: timeService.boundIntervalToTimewindow(endTimeMs - startTimeMs, interval, AggregationType.AVG)293 },294 aggregation: {295 type: aggType,296 limit297 },298 timezone: timewindow.timezone299 };300}301export function timewindowTypeChanged(newTimewindow: Timewindow, oldTimewindow: Timewindow): boolean {302 if (!newTimewindow || !oldTimewindow) {303 return false;304 }305 const newType = getTimewindowType(newTimewindow);306 const oldType = getTimewindowType(oldTimewindow);307 return newType !== oldType;308}309export function calculateTsOffset(timezone?: string): number {310 if (timezone) {311 const tz = getTimezone(timezone);312 const localOffset = moment().utcOffset();313 return (tz.utcOffset() - localOffset) * 60 * 1000;314 } else {315 return 0;316 }317}318export function isHistoryTypeTimewindow(timewindow: Timewindow): boolean {319 return getTimewindowType(timewindow) === TimewindowType.HISTORY;320}321export function createSubscriptionTimewindow(timewindow: Timewindow, stDiff: number, stateData: boolean,322 timeService: TimeService): SubscriptionTimewindow {323 const subscriptionTimewindow: SubscriptionTimewindow = {324 fixedWindow: null,325 realtimeWindowMs: null,326 aggregation: {327 interval: SECOND,328 limit: timeService.getMaxDatapointsLimit(),329 type: AggregationType.AVG330 },331 timezone: timewindow.timezone,332 tsOffset: calculateTsOffset(timewindow.timezone)333 };334 let aggTimewindow;335 if (stateData) {336 subscriptionTimewindow.aggregation.type = AggregationType.NONE;337 subscriptionTimewindow.aggregation.stateData = true;338 }339 if (isDefined(timewindow.aggregation) && !stateData) {340 subscriptionTimewindow.aggregation = {341 type: timewindow.aggregation.type || AggregationType.AVG,342 limit: timewindow.aggregation.limit || timeService.getMaxDatapointsLimit()343 };344 }345 const selectedTab = getTimewindowType(timewindow);346 if (selectedTab === TimewindowType.REALTIME) {347 let realtimeType = timewindow.realtime.realtimeType;348 if (isUndefined(realtimeType)) {349 if (isDefined(timewindow.realtime.quickInterval)) {350 realtimeType = RealtimeWindowType.INTERVAL;351 } else {352 realtimeType = RealtimeWindowType.LAST_INTERVAL;353 }354 }355 if (realtimeType === RealtimeWindowType.INTERVAL) {356 subscriptionTimewindow.realtimeWindowMs =357 getSubscriptionRealtimeWindowFromTimeInterval(timewindow.realtime.quickInterval, timewindow.timezone);358 subscriptionTimewindow.quickInterval = timewindow.realtime.quickInterval;359 const currentDate = getCurrentTime(timewindow.timezone);360 subscriptionTimewindow.startTs = calculateIntervalStartTime(timewindow.realtime.quickInterval, currentDate).valueOf();361 } else {362 subscriptionTimewindow.realtimeWindowMs = timewindow.realtime.timewindowMs;363 const currentDate = getCurrentTime(timewindow.timezone);364 subscriptionTimewindow.startTs = currentDate.valueOf() + stDiff - subscriptionTimewindow.realtimeWindowMs;365 }366 subscriptionTimewindow.aggregation.interval =367 timeService.boundIntervalToTimewindow(subscriptionTimewindow.realtimeWindowMs, timewindow.realtime.interval,368 subscriptionTimewindow.aggregation.type);369 aggTimewindow = subscriptionTimewindow.realtimeWindowMs;370 if (realtimeType !== RealtimeWindowType.INTERVAL) {371 const startDiff = subscriptionTimewindow.startTs % subscriptionTimewindow.aggregation.interval;372 if (startDiff) {373 subscriptionTimewindow.startTs -= startDiff;374 aggTimewindow += subscriptionTimewindow.aggregation.interval;375 }376 }377 } else {378 let historyType = timewindow.history.historyType;379 if (isUndefined(historyType)) {380 if (isDefined(timewindow.history.timewindowMs)) {381 historyType = HistoryWindowType.LAST_INTERVAL;382 } else if (isDefined(timewindow.history.quickInterval)) {383 historyType = HistoryWindowType.INTERVAL;384 } else {385 historyType = HistoryWindowType.FIXED;386 }387 }388 if (historyType === HistoryWindowType.LAST_INTERVAL) {389 const currentDate = getCurrentTime(timewindow.timezone);390 const currentTime = currentDate.valueOf();391 subscriptionTimewindow.fixedWindow = {392 startTimeMs: currentTime - timewindow.history.timewindowMs,393 endTimeMs: currentTime394 };395 aggTimewindow = timewindow.history.timewindowMs;396 } else if (historyType === HistoryWindowType.INTERVAL) {397 const startEndTime = calculateIntervalStartEndTime(timewindow.history.quickInterval, timewindow.timezone);398 subscriptionTimewindow.fixedWindow = {399 startTimeMs: startEndTime[0],400 endTimeMs: startEndTime[1]401 };402 aggTimewindow = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;403 subscriptionTimewindow.quickInterval = timewindow.history.quickInterval;404 } else {405 subscriptionTimewindow.fixedWindow = {406 startTimeMs: timewindow.history.fixedTimewindow.startTimeMs - subscriptionTimewindow.tsOffset,407 endTimeMs: timewindow.history.fixedTimewindow.endTimeMs - subscriptionTimewindow.tsOffset408 };409 aggTimewindow = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;410 }411 subscriptionTimewindow.startTs = subscriptionTimewindow.fixedWindow.startTimeMs;412 subscriptionTimewindow.aggregation.interval =413 timeService.boundIntervalToTimewindow(aggTimewindow, timewindow.history.interval, subscriptionTimewindow.aggregation.type);414 }415 const aggregation = subscriptionTimewindow.aggregation;416 aggregation.timeWindow = aggTimewindow;417 if (aggregation.type !== AggregationType.NONE) {418 aggregation.limit = Math.ceil(aggTimewindow / subscriptionTimewindow.aggregation.interval);419 }420 return subscriptionTimewindow;421}422function getSubscriptionRealtimeWindowFromTimeInterval(interval: QuickTimeInterval, tz?: string): number {423 let currentDate;424 switch (interval) {425 case QuickTimeInterval.CURRENT_HOUR:426 return HOUR;427 case QuickTimeInterval.CURRENT_DAY:428 case QuickTimeInterval.CURRENT_DAY_SO_FAR:429 return DAY;430 case QuickTimeInterval.CURRENT_WEEK:431 case QuickTimeInterval.CURRENT_WEEK_ISO:432 case QuickTimeInterval.CURRENT_WEEK_SO_FAR:433 case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:434 return WEEK;435 case QuickTimeInterval.CURRENT_MONTH:436 case QuickTimeInterval.CURRENT_MONTH_SO_FAR:437 currentDate = getCurrentTime(tz);438 return currentDate.endOf('month').diff(currentDate.clone().startOf('month'));439 case QuickTimeInterval.CURRENT_YEAR:440 case QuickTimeInterval.CURRENT_YEAR_SO_FAR:441 currentDate = getCurrentTime(tz);442 return currentDate.endOf('year').diff(currentDate.clone().startOf('year'));443 }444}445export function calculateIntervalStartEndTime(interval: QuickTimeInterval, tz?: string): [number, number] {446 const startEndTs: [number, number] = [0, 0];447 const currentDate = getCurrentTime(tz);448 const startDate = calculateIntervalStartTime(interval, currentDate);449 startEndTs[0] = startDate.valueOf();450 const endDate = calculateIntervalEndTime(interval, startDate, tz);451 startEndTs[1] = endDate.valueOf();452 return startEndTs;453}454export function calculateIntervalStartTime(interval: QuickTimeInterval, currentDate: moment_.Moment): moment_.Moment {455 switch (interval) {456 case QuickTimeInterval.YESTERDAY:457 currentDate.subtract(1, 'days');458 return currentDate.startOf('day');459 case QuickTimeInterval.DAY_BEFORE_YESTERDAY:460 currentDate.subtract(2, 'days');461 return currentDate.startOf('day');462 case QuickTimeInterval.THIS_DAY_LAST_WEEK:463 currentDate.subtract(1, 'weeks');464 return currentDate.startOf('day');465 case QuickTimeInterval.PREVIOUS_WEEK:466 currentDate.subtract(1, 'weeks');467 return currentDate.startOf('week');468 case QuickTimeInterval.PREVIOUS_WEEK_ISO:469 currentDate.subtract(1, 'weeks');470 return currentDate.startOf('isoWeek');471 case QuickTimeInterval.PREVIOUS_MONTH:472 currentDate.subtract(1, 'months');473 return currentDate.startOf('month');474 case QuickTimeInterval.PREVIOUS_YEAR:475 currentDate.subtract(1, 'years');476 return currentDate.startOf('year');477 case QuickTimeInterval.CURRENT_HOUR:478 return currentDate.startOf('hour');479 case QuickTimeInterval.CURRENT_DAY:480 case QuickTimeInterval.CURRENT_DAY_SO_FAR:481 return currentDate.startOf('day');482 case QuickTimeInterval.CURRENT_WEEK:483 case QuickTimeInterval.CURRENT_WEEK_SO_FAR:484 return currentDate.startOf('week');485 case QuickTimeInterval.CURRENT_WEEK_ISO:486 case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:487 return currentDate.startOf('isoWeek');488 case QuickTimeInterval.CURRENT_MONTH:489 case QuickTimeInterval.CURRENT_MONTH_SO_FAR:490 return currentDate.startOf('month');491 case QuickTimeInterval.CURRENT_YEAR:492 case QuickTimeInterval.CURRENT_YEAR_SO_FAR:493 return currentDate.startOf('year');494 }495}496export function calculateIntervalEndTime(interval: QuickTimeInterval, startDate: moment_.Moment, tz?: string): number {497 switch (interval) {498 case QuickTimeInterval.YESTERDAY:499 case QuickTimeInterval.DAY_BEFORE_YESTERDAY:500 case QuickTimeInterval.THIS_DAY_LAST_WEEK:501 case QuickTimeInterval.CURRENT_DAY:502 return startDate.add(1, 'day').valueOf();503 case QuickTimeInterval.PREVIOUS_WEEK:504 case QuickTimeInterval.PREVIOUS_WEEK_ISO:505 case QuickTimeInterval.CURRENT_WEEK:506 case QuickTimeInterval.CURRENT_WEEK_ISO:507 return startDate.add(1, 'week').valueOf();508 case QuickTimeInterval.PREVIOUS_MONTH:509 case QuickTimeInterval.CURRENT_MONTH:510 return startDate.add(1, 'month').valueOf();511 case QuickTimeInterval.PREVIOUS_YEAR:512 case QuickTimeInterval.CURRENT_YEAR:513 return startDate.add(1, 'year').valueOf();514 case QuickTimeInterval.CURRENT_HOUR:515 return startDate.add(1, 'hour').valueOf();516 case QuickTimeInterval.CURRENT_DAY_SO_FAR:517 case QuickTimeInterval.CURRENT_WEEK_SO_FAR:518 case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:519 case QuickTimeInterval.CURRENT_MONTH_SO_FAR:520 case QuickTimeInterval.CURRENT_YEAR_SO_FAR:521 return getCurrentTime(tz).valueOf();522 }523}524export function quickTimeIntervalPeriod(interval: QuickTimeInterval): number {525 switch (interval) {526 case QuickTimeInterval.CURRENT_HOUR:527 return HOUR;528 case QuickTimeInterval.YESTERDAY:529 case QuickTimeInterval.DAY_BEFORE_YESTERDAY:530 case QuickTimeInterval.THIS_DAY_LAST_WEEK:531 case QuickTimeInterval.CURRENT_DAY:532 case QuickTimeInterval.CURRENT_DAY_SO_FAR:533 return DAY;534 case QuickTimeInterval.PREVIOUS_WEEK:535 case QuickTimeInterval.PREVIOUS_WEEK_ISO:536 case QuickTimeInterval.CURRENT_WEEK:537 case QuickTimeInterval.CURRENT_WEEK_ISO:538 case QuickTimeInterval.CURRENT_WEEK_SO_FAR:539 case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:540 return WEEK;541 case QuickTimeInterval.PREVIOUS_MONTH:542 case QuickTimeInterval.CURRENT_MONTH:543 case QuickTimeInterval.CURRENT_MONTH_SO_FAR:544 return DAY * 30;545 case QuickTimeInterval.PREVIOUS_YEAR:546 case QuickTimeInterval.CURRENT_YEAR:547 case QuickTimeInterval.CURRENT_YEAR_SO_FAR:548 return YEAR;549 }550}551export function calculateIntervalComparisonStartTime(interval: QuickTimeInterval,552 startDate: moment_.Moment): moment_.Moment {553 switch (interval) {554 case QuickTimeInterval.YESTERDAY:555 case QuickTimeInterval.DAY_BEFORE_YESTERDAY:556 case QuickTimeInterval.CURRENT_DAY:557 case QuickTimeInterval.CURRENT_DAY_SO_FAR:558 startDate.subtract(1, 'days');559 return startDate.startOf('day');560 case QuickTimeInterval.THIS_DAY_LAST_WEEK:561 startDate.subtract(1, 'weeks');562 return startDate.startOf('day');563 case QuickTimeInterval.PREVIOUS_WEEK:564 case QuickTimeInterval.CURRENT_WEEK:565 case QuickTimeInterval.CURRENT_WEEK_SO_FAR:566 startDate.subtract(1, 'weeks');567 return startDate.startOf('week');568 case QuickTimeInterval.PREVIOUS_WEEK_ISO:569 case QuickTimeInterval.CURRENT_WEEK_ISO:570 case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:571 startDate.subtract(1, 'weeks');572 return startDate.startOf('isoWeek');573 case QuickTimeInterval.PREVIOUS_MONTH:574 case QuickTimeInterval.CURRENT_MONTH:575 case QuickTimeInterval.CURRENT_MONTH_SO_FAR:576 startDate.subtract(1, 'months');577 return startDate.startOf('month');578 case QuickTimeInterval.PREVIOUS_YEAR:579 case QuickTimeInterval.CURRENT_YEAR:580 case QuickTimeInterval.CURRENT_YEAR_SO_FAR:581 startDate.subtract(1, 'years');582 return startDate.startOf('year');583 case QuickTimeInterval.CURRENT_HOUR:584 startDate.subtract(1, 'hour');585 return startDate.startOf('hour');586 }587}588export function calculateIntervalComparisonEndTime(interval: QuickTimeInterval,589 comparisonStartDate: moment_.Moment,590 endDate: moment_.Moment): number {591 switch (interval) {592 case QuickTimeInterval.CURRENT_DAY_SO_FAR:593 return endDate.subtract(1, 'days').valueOf();594 case QuickTimeInterval.CURRENT_WEEK_SO_FAR:595 case QuickTimeInterval.CURRENT_WEEK_ISO_SO_FAR:596 return endDate.subtract(1, 'week').valueOf();597 case QuickTimeInterval.CURRENT_MONTH_SO_FAR:598 return endDate.subtract(1, 'month').valueOf();599 case QuickTimeInterval.CURRENT_YEAR_SO_FAR:600 return endDate.subtract(1, 'year').valueOf();601 default:602 return calculateIntervalEndTime(interval, comparisonStartDate);603 }604}605export function createTimewindowForComparison(subscriptionTimewindow: SubscriptionTimewindow,606 timeUnit: ComparisonDuration, customIntervalValue: number): SubscriptionTimewindow {607 const timewindowForComparison: SubscriptionTimewindow = {608 fixedWindow: null,609 realtimeWindowMs: null,610 aggregation: subscriptionTimewindow.aggregation,611 tsOffset: subscriptionTimewindow.tsOffset612 };613 if (subscriptionTimewindow.fixedWindow) {614 let startTimeMs;615 let endTimeMs;616 if (timeUnit === 'previousInterval') {617 if (subscriptionTimewindow.quickInterval) {618 const startDate = moment(subscriptionTimewindow.fixedWindow.startTimeMs);619 const endDate = moment(subscriptionTimewindow.fixedWindow.endTimeMs);620 if (subscriptionTimewindow.timezone) {621 startDate.tz(subscriptionTimewindow.timezone);622 endDate.tz(subscriptionTimewindow.timezone);623 }624 const comparisonStartDate = calculateIntervalComparisonStartTime(subscriptionTimewindow.quickInterval, startDate);625 startTimeMs = comparisonStartDate.valueOf();626 endTimeMs = calculateIntervalComparisonEndTime(subscriptionTimewindow.quickInterval, comparisonStartDate, endDate);627 } else {628 const timeInterval = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;629 endTimeMs = subscriptionTimewindow.fixedWindow.startTimeMs;630 startTimeMs = endTimeMs - timeInterval;631 }632 } else if (timeUnit === 'customInterval') {633 if (isNumeric(customIntervalValue) && isFinite(customIntervalValue) && customIntervalValue > 0) {634 const timeInterval = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;635 endTimeMs = subscriptionTimewindow.fixedWindow.endTimeMs - Math.round(customIntervalValue);636 startTimeMs = endTimeMs - timeInterval;637 } else {638 endTimeMs = subscriptionTimewindow.fixedWindow.endTimeMs;639 startTimeMs = subscriptionTimewindow.fixedWindow.startTimeMs;640 }641 } else {642 const timeInterval = subscriptionTimewindow.fixedWindow.endTimeMs - subscriptionTimewindow.fixedWindow.startTimeMs;643 endTimeMs = moment(subscriptionTimewindow.fixedWindow.endTimeMs).subtract(1, timeUnit).valueOf();644 startTimeMs = endTimeMs - timeInterval;645 }646 timewindowForComparison.startTs = startTimeMs;647 timewindowForComparison.fixedWindow = {648 startTimeMs: timewindowForComparison.startTs,649 endTimeMs650 };651 }652 return timewindowForComparison;653}654export function cloneSelectedTimewindow(timewindow: Timewindow): Timewindow {655 const cloned: Timewindow = {};656 cloned.hideInterval = timewindow.hideInterval || false;657 cloned.hideAggregation = timewindow.hideAggregation || false;658 cloned.hideAggInterval = timewindow.hideAggInterval || false;659 cloned.hideTimezone = timewindow.hideTimezone || false;660 if (isDefined(timewindow.selectedTab)) {661 cloned.selectedTab = timewindow.selectedTab;662 if (timewindow.selectedTab === TimewindowType.REALTIME) {663 cloned.realtime = deepClone(timewindow.realtime);664 } else if (timewindow.selectedTab === TimewindowType.HISTORY) {665 cloned.history = deepClone(timewindow.history);666 }667 }668 cloned.aggregation = deepClone(timewindow.aggregation);669 cloned.timezone = timewindow.timezone;670 return cloned;671}672export interface TimeInterval {673 name: string;674 translateParams: {[key: string]: any};675 value: number;676}677export const defaultTimeIntervals = new Array<TimeInterval>(678 {679 name: 'timeinterval.seconds-interval',680 translateParams: {seconds: 1},681 value: SECOND682 },683 {684 name: 'timeinterval.seconds-interval',685 translateParams: {seconds: 5},686 value: 5 * SECOND687 },688 {689 name: 'timeinterval.seconds-interval',690 translateParams: {seconds: 10},691 value: 10 * SECOND692 },693 {694 name: 'timeinterval.seconds-interval',695 translateParams: {seconds: 15},696 value: 15 * SECOND697 },698 {699 name: 'timeinterval.seconds-interval',700 translateParams: {seconds: 30},701 value: 30 * SECOND702 },703 {704 name: 'timeinterval.minutes-interval',705 translateParams: {minutes: 1},706 value: MINUTE707 },708 {709 name: 'timeinterval.minutes-interval',710 translateParams: {minutes: 2},711 value: 2 * MINUTE712 },713 {714 name: 'timeinterval.minutes-interval',715 translateParams: {minutes: 5},716 value: 5 * MINUTE717 },718 {719 name: 'timeinterval.minutes-interval',720 translateParams: {minutes: 10},721 value: 10 * MINUTE722 },723 {724 name: 'timeinterval.minutes-interval',725 translateParams: {minutes: 15},726 value: 15 * MINUTE727 },728 {729 name: 'timeinterval.minutes-interval',730 translateParams: {minutes: 30},731 value: 30 * MINUTE732 },733 {734 name: 'timeinterval.hours-interval',735 translateParams: {hours: 1},736 value: HOUR737 },738 {739 name: 'timeinterval.hours-interval',740 translateParams: {hours: 2},741 value: 2 * HOUR742 },743 {744 name: 'timeinterval.hours-interval',745 translateParams: {hours: 5},746 value: 5 * HOUR747 },748 {749 name: 'timeinterval.hours-interval',750 translateParams: {hours: 10},751 value: 10 * HOUR752 },753 {754 name: 'timeinterval.hours-interval',755 translateParams: {hours: 12},756 value: 12 * HOUR757 },758 {759 name: 'timeinterval.days-interval',760 translateParams: {days: 1},761 value: DAY762 },763 {764 name: 'timeinterval.days-interval',765 translateParams: {days: 7},766 value: 7 * DAY767 },768 {769 name: 'timeinterval.days-interval',770 translateParams: {days: 30},771 value: 30 * DAY772 }773);774export enum TimeUnit {775 SECONDS = 'SECONDS',776 MINUTES = 'MINUTES',777 HOURS = 'HOURS',778 DAYS = 'DAYS'779}780export enum TimeUnitMilli {781 MILLISECONDS = 'MILLISECONDS'782}783export type FullTimeUnit = TimeUnit | TimeUnitMilli;784export const timeUnitTranslationMap = new Map<FullTimeUnit, string>(785 [786 [TimeUnitMilli.MILLISECONDS, 'timeunit.milliseconds'],787 [TimeUnit.SECONDS, 'timeunit.seconds'],788 [TimeUnit.MINUTES, 'timeunit.minutes'],789 [TimeUnit.HOURS, 'timeunit.hours'],790 [TimeUnit.DAYS, 'timeunit.days']791 ]792);793export interface TimezoneInfo {794 id: string;795 name: string;796 offset: string;797 nOffset: number;798 abbr: string;799}800let timezones: TimezoneInfo[] = null;801let defaultTimezone: string = null;802export function getTimezones(): TimezoneInfo[] {803 if (!timezones) {804 timezones = momentTz.tz.names().map((zoneName) => {805 const tz = momentTz.tz(zoneName);806 return {807 id: zoneName,808 name: zoneName.replace(/_/g, ' '),809 offset: `UTC${tz.format('Z')}`,810 nOffset: tz.utcOffset(),811 abbr: tz.zoneAbbr()812 };813 });814 }815 return timezones;816}817export function getTimezoneInfo(timezoneId: string, defaultTimezoneId?: string, userTimezoneByDefault?: boolean): TimezoneInfo {818 const timezoneList = getTimezones();819 let foundTimezone = timezoneId ? timezoneList.find(timezoneInfo => timezoneInfo.id === timezoneId) : null;820 if (!foundTimezone) {821 if (userTimezoneByDefault) {822 const userTimezone = getDefaultTimezone();823 foundTimezone = timezoneList.find(timezoneInfo => timezoneInfo.id === userTimezone);824 } else if (defaultTimezoneId) {825 foundTimezone = timezoneList.find(timezoneInfo => timezoneInfo.id === defaultTimezoneId);826 }827 }828 return foundTimezone;829}830export function getDefaultTimezoneInfo(): TimezoneInfo {831 const userTimezone = getDefaultTimezone();832 return getTimezoneInfo(userTimezone);833}834export function getDefaultTimezone(): string {835 if (!defaultTimezone) {836 defaultTimezone = momentTz.tz.guess();837 }838 return defaultTimezone;839}840export function getCurrentTime(tz?: string): moment_.Moment {841 if (tz) {842 return moment().tz(tz);843 } else {844 return moment();845 }846}847export function getTime(ts: number, tz?: string): moment_.Moment {848 if (tz) {849 return moment(ts).tz(tz);850 } else {851 return moment(ts);852 }853}854export function getTimezone(tz: string): moment_.Moment {855 return moment.tz(tz);856}857export function getCurrentTimeForComparison(timeForComparison: moment_.unitOfTime.DurationConstructor, tz?: string): moment_.Moment {858 return getCurrentTime(tz).subtract(1, timeForComparison);...

Full Screen

Full Screen

time_buckets.js

Source:time_buckets.js Github

copy

Full Screen

1import _ from 'lodash';2import moment from 'moment';3import { parseInterval } from 'ui/utils/parse_interval';4import { TimeBucketsCalcAutoIntervalProvider } from 'ui/time_buckets/calc_auto_interval';5import { TimeBucketsCalcEsIntervalProvider } from 'ui/time_buckets/calc_es_interval';6import { RegistryFieldFormatsProvider } from 'ui/registry/field_formats';7export function TimeBucketsProvider(Private, timefilter, config) {8 const calcAuto = Private(TimeBucketsCalcAutoIntervalProvider);9 const calcEsInterval = Private(TimeBucketsCalcEsIntervalProvider);10 const fieldFormats = Private(RegistryFieldFormatsProvider);11 const getConfig = (...args) => config.get(...args);12 function isValidMoment(m) {13 return m && ('isValid' in m) && m.isValid();14 }15 /**16 * Helper class for wrapping the concept of an "Interval",17 * which describes a timespan that will seperate moments.18 *19 * @param {state} object - one of ""20 * @param {[type]} display [description]21 */22 function TimeBuckets() {23 return TimeBuckets.__cached__(this);24 }25 /****26 * PUBLIC API27 ****/28 /**29 * Set the bounds that these buckets are expected to cover.30 * This is required to support interval "auto" as well31 * as interval scaling.32 *33 * @param {object} input - an object with properties min and max,34 * representing the edges for the time span35 * we should cover36 *37 * @returns {undefined}38 */39 TimeBuckets.prototype.setBounds = function (input) {40 if (!input) return this.clearBounds();41 let bounds;42 if (_.isPlainObject(input)) {43 // accept the response from timefilter.getActiveBounds()44 bounds = [input.min, input.max];45 } else {46 bounds = Array.isArray(input) ? input : [];47 }48 const moments = _(bounds)49 .map(_.ary(moment, 1))50 .sortBy(Number);51 const valid = moments.size() === 2 && moments.every(isValidMoment);52 if (!valid) {53 this.clearBounds();54 throw new Error('invalid bounds set: ' + input);55 }56 this._lb = moments.shift();57 this._ub = moments.pop();58 if (this.getDuration().asSeconds() < 0) {59 throw new TypeError('Intervals must be positive');60 }61 };62 /**63 * Clear the stored bounds64 *65 * @return {undefined}66 */67 TimeBuckets.prototype.clearBounds = function () {68 this._lb = this._ub = null;69 };70 /**71 * Check to see if we have received bounds yet72 *73 * @return {Boolean}74 */75 TimeBuckets.prototype.hasBounds = function () {76 return isValidMoment(this._ub) && isValidMoment(this._lb);77 };78 /**79 * Return the current bounds, if we have any.80 *81 * THIS DOES NOT CLONE THE BOUNDS, so editing them82 * may have unexpected side-effects. Always83 * call bounds.min.clone() before editing84 *85 * @return {object|undefined} - If bounds are not defined, this86 * returns undefined, else it returns the bounds87 * for these buckets. This object has two props,88 * min and max. Each property will be a moment()89 * object90 *91 */92 TimeBuckets.prototype.getBounds = function () {93 if (!this.hasBounds()) return;94 return {95 min: this._lb,96 max: this._ub97 };98 };99 /**100 * Get a moment duration object representing101 * the distance between the bounds, if the bounds102 * are set.103 *104 * @return {moment.duration|undefined}105 */106 TimeBuckets.prototype.getDuration = function () {107 if (!this.hasBounds()) return;108 return moment.duration(this._ub - this._lb, 'ms');109 };110 /**111 * Update the interval at which buckets should be112 * generated.113 *114 * Input can be one of the following:115 * - Any object from src/ui/agg_types/buckets/_interval_options.js116 * - "auto"117 * - Pass a valid moment unit118 * - a moment.duration object.119 *120 * @param {object|string|moment.duration} input - see desc121 */122 TimeBuckets.prototype.setInterval = function (input) {123 let interval = input;124 // selection object -> val125 if (_.isObject(input)) {126 interval = input.val;127 }128 if (!interval || interval === 'auto') {129 this._i = 'auto';130 return;131 }132 if (_.isString(interval)) {133 input = interval;134 interval = parseInterval(interval);135 if (+interval === 0) {136 interval = null;137 }138 }139 // if the value wasn't converted to a duration, and isn't140 // already a duration, we have a problem141 if (!moment.isDuration(interval)) {142 throw new TypeError('"' + input + '" is not a valid interval.');143 }144 this._i = interval;145 };146 /**147 * Get the interval for the buckets. If the148 * number of buckets created by the interval set149 * is larger than config:histogram:maxBars then the150 * interval will be scaled up. If the number of buckets151 * created is less than one, the interval is scaled back.152 *153 * The interval object returned is a moment.duration154 * object that has been decorated with the following155 * properties.156 *157 * interval.description: a text description of the interval.158 * designed to be used list "field per {{ desc }}".159 * - "minute"160 * - "10 days"161 * - "3 years"162 *163 * interval.expr: the elasticsearch expression that creates this164 * interval. If the interval does not properly form an elasticsearch165 * expression it will be forced into one.166 *167 * interval.scaled: the interval was adjusted to168 * accomidate the maxBars setting.169 *170 * interval.scale: the numer that y-values should be171 * multiplied by172 *173 * interval.scaleDescription: a description that reflects174 * the values which will be produced by using the175 * interval.scale.176 *177 *178 * @return {[type]} [description]179 */180 TimeBuckets.prototype.getInterval = function () {181 const self = this;182 const duration = self.getDuration();183 return decorateInterval(maybeScaleInterval(readInterval()));184 // either pull the interval from state or calculate the auto-interval185 function readInterval() {186 const interval = self._i;187 if (moment.isDuration(interval)) return interval;188 return calcAuto.near(config.get('histogram:barTarget'), duration);189 }190 // check to see if the interval should be scaled, and scale it if so191 function maybeScaleInterval(interval) {192 if (!self.hasBounds()) return interval;193 const maxLength = config.get('histogram:maxBars');194 const approxLen = duration / interval;195 let scaled;196 if (approxLen > maxLength) {197 scaled = calcAuto.lessThan(maxLength, duration);198 } else {199 return interval;200 }201 if (+scaled === +interval) return interval;202 decorateInterval(interval);203 return _.assign(scaled, {204 preScaled: interval,205 scale: interval / scaled,206 scaled: true207 });208 }209 // append some TimeBuckets specific props to the interval210 function decorateInterval(interval) {211 const esInterval = calcEsInterval(interval);212 interval.esValue = esInterval.value;213 interval.esUnit = esInterval.unit;214 interval.expression = esInterval.expression;215 interval.overflow = duration > interval ? moment.duration(interval - duration) : false;216 const prettyUnits = moment.normalizeUnits(esInterval.unit);217 if (esInterval.value === 1) {218 interval.description = prettyUnits;219 } else {220 interval.description = esInterval.value + ' ' + prettyUnits + 's';221 }222 return interval;223 }224 };225 /**226 * Get a date format string that will represent dates that227 * progress at our interval.228 *229 * Since our interval can be as small as 1ms, the default230 * date format is usually way too much. with `dateFormat:scaled`231 * users can modify how dates are formatted within series232 * produced by TimeBuckets233 *234 * @return {string}235 */236 TimeBuckets.prototype.getScaledDateFormat = function () {237 const interval = this.getInterval();238 const rules = config.get('dateFormat:scaled');239 for (let i = rules.length - 1; i >= 0; i--) {240 const rule = rules[i];241 if (!rule[0] || interval >= moment.duration(rule[0])) {242 return rule[1];243 }244 }245 return config.get('dateFormat');246 };247 TimeBuckets.prototype.getScaledDateFormatter = function () {248 const DateFieldFormat = fieldFormats.getType('date');249 return new DateFieldFormat({250 pattern: this.getScaledDateFormat()251 }, getConfig);252 };253 TimeBuckets.__cached__ = function (self) {254 let cache = {};255 const sameMoment = same(moment.isMoment);256 const sameDuration = same(moment.isDuration);257 const desc = {258 __cached__: {259 value: self260 },261 };262 const breakers = {263 setBounds: 'bounds',264 clearBounds: 'bounds',265 setInterval: 'interval'266 };267 const resources = {268 bounds: {269 setup: function () {270 return [self._lb, self._ub];271 },272 changes: function (prev) {273 return !sameMoment(prev[0], self._lb) || !sameMoment(prev[1], self._ub);274 }275 },276 interval: {277 setup: function () {278 return self._i;279 },280 changes: function (prev) {281 return !sameDuration(prev, this._i);282 }283 }284 };285 function cachedGetter(prop) {286 return {287 value: function cachedGetter() {288 if (cache.hasOwnProperty(prop)) {289 return cache[prop];290 }291 return cache[prop] = self[prop]();292 }293 };294 }295 function cacheBreaker(prop) {296 const resource = resources[breakers[prop]];297 const setup = resource.setup;298 const changes = resource.changes;299 const fn = self[prop];300 return {301 value: function cacheBreaker() {302 const prev = setup.call(self);303 const ret = fn.apply(self, arguments);304 if (changes.call(self, prev)) {305 cache = {};306 }307 return ret;308 }309 };310 }311 function same(checkType) {312 return function (a, b) {313 if (a === b) return true;314 if (checkType(a) === checkType(b)) return +a === +b;315 return false;316 };317 }318 _.forOwn(TimeBuckets.prototype, function (fn, prop) {319 if (prop[0] === '_') return;320 if (breakers.hasOwnProperty(prop)) {321 desc[prop] = cacheBreaker(prop);322 } else {323 desc[prop] = cachedGetter(prop);324 }325 });326 return Object.create(self, desc);327 };328 return TimeBuckets;...

Full Screen

Full Screen

interval.ts

Source:interval.ts Github

copy

Full Screen

1import { NoteIndex } from "./note";2import { Tone, toneOps } from "./tone";3export type MajorIntervals = "M2" | "M3" | "M6" | "M7";4export type MinorIntervals = "m2" | "m3" | "m6" | "m7";5export type PerfectIntervals = "p4" | "p5";6export type DiminishedIntervals = "d5" | "d7";7export type AugmentedIntervals = "A4" | "A5";8export type SimpleInterval =9 | MajorIntervals10 | MinorIntervals11 | PerfectIntervals12 | DiminishedIntervals13 | AugmentedIntervals14 | "U";15export type NonUnitaryInterval = Exclude<SimpleInterval, "U">;16export type PositiveDelta = `+${SimpleInterval}`;17export type NegativeDelta = `-${SimpleInterval}`;18export type IntervalDelta = PositiveDelta | NegativeDelta;19export function isPositive(delta: IntervalDelta): delta is PositiveDelta {20 return delta[0] === "+";21}22export function isNegative(delta: IntervalDelta): delta is NegativeDelta {23 return delta[0] === "-";24}25// Octaves + Interval26export type CompoundInterval = [number, SimpleInterval];27export function compoundInterval(octaves: number, interval: SimpleInterval): CompoundInterval {28 return [octaves, interval];29}30export type Interval = SimpleInterval | CompoundInterval;31export function isSimpleInterval(interval: Interval): interval is SimpleInterval {32 return !Array.isArray(interval);33}34export function isCompoundInterval(interval: Interval): interval is CompoundInterval {35 return !isSimpleInterval(interval);36}37export function compoundIntervalWidth(interval: CompoundInterval): number {38 return 12 * interval[0] + intervalWidth(interval[1]);39}40export function widthToCompoundInterval(n: number): CompoundInterval[] {41 const octaves = Math.trunc(n / 12);42 const rest = n - octaves;43 return widthToInterval(rest as any).map((w) => compoundInterval(octaves, w));44}45export function intervalWidth(interval: SimpleInterval): NoteIndex {46 switch (interval) {47 case "U":48 return 0;49 case "m2":50 return 1;51 case "M2":52 return 2;53 case "m3":54 return 3;55 case "M3":56 return 4;57 case "p4":58 return 5;59 case "d5":60 case "A4":61 return 6;62 case "p5":63 return 7;64 case "m6":65 case "A5":66 return 8;67 case "M6":68 case "d7":69 return 9;70 case "m7":71 return 10;72 case "M7":73 return 11;74 default:75 throw new Error("Unknown interval " + interval);76 }77}78export function widthToInterval(interval: NoteIndex): SimpleInterval[] {79 switch (interval) {80 case 0:81 return ["U"];82 case 1:83 return ["m2"];84 case 2:85 return ["M2"];86 case 3:87 return ["m3"];88 case 4:89 return ["M3"];90 case 5:91 return ["p4"];92 case 6:93 return ["d5", "A4"];94 case 7:95 return ["p5"];96 case 8:97 return ["m6", "A5"];98 case 9:99 return ["M6", "d7"];100 case 10:101 return ["m7"];102 case 11:103 return ["M7"];104 default:105 throw new Error("Unknown interval " + interval);106 }107}108export function invertSimpleInterval(interval: SimpleInterval): SimpleInterval[] {109 return widthToInterval((12 - intervalWidth(interval)) as NoteIndex);110}111export const intervalOps = {112 add(a: Interval, b: Interval): Interval[] {113 return this.fromWidth(this.width(a) + this.width(b));114 },115 offset(a: Interval, semitones: number) {116 return this.fromWidth(this.width(a) + semitones);117 },118 width(a: Interval): number {119 if (isCompoundInterval(a)) {120 return compoundIntervalWidth(a);121 } else {122 return intervalWidth(a);123 }124 },125 fromWidth(a: number): Interval[] {126 return widthToCompoundInterval(a);127 },128 octaves(a: Interval): number {129 return Math.trunc(this.width(a) / 12);130 },131 coerce(a: Interval): SimpleInterval {132 return isSimpleInterval(a) ? a : a[1];133 },134 coerceDelta(a: IntervalDelta): SimpleInterval {135 return a.slice(1) as SimpleInterval;136 },137 deltaWidth(a: IntervalDelta): number {138 const direction: "+" | "-" = a[0] as any;139 const interval = a.slice(1) as SimpleInterval;140 return direction === "-" ? -this.width(interval) : this.width(interval);141 },142 up(a: SimpleInterval): IntervalDelta {143 return `+${a}`;144 },145 down(a: SimpleInterval): IntervalDelta {146 return `-${a}`;147 },148 withDelta(a: Interval, b: IntervalDelta) {149 return this.offset(a, this.deltaWidth(b));150 },151 applyDelta(a: Tone, b: IntervalDelta) {152 if (isNegative(b)) {153 return toneOps.subtract(a, -this.deltaWidth(b));154 } else {155 return toneOps.offset(a, this.deltaWidth(b));156 }157 },158 coerceDown(b: IntervalDelta): IntervalDelta {159 return `-${this.coerceDelta(b)}`;160 },161 coerceUp(b: IntervalDelta): IntervalDelta {162 return `+${this.coerceDelta(b)}`;163 },164 invertDelta(b: IntervalDelta): IntervalDelta {165 const inverted = invertSimpleInterval(this.coerceDelta(b))[0];166 const iv: IntervalDelta = `${b[0]}${inverted}` as any;167 return this.deltaWidth(b) > 0 ? this.coerceDown(iv) : this.coerceUp(iv);168 },...

Full Screen

Full Screen

IntervalManager.js

Source:IntervalManager.js Github

copy

Full Screen

1import {CONFIG} from "../../config/config";2var ballInterval;3var ballIntervalTime;4var symbolInterval;5var playerResponseTimeout;6var playerResponseTime;7var ballCB;8var symbolCB;9var playerResponseCB;10export default class IntervalManager {11 constructor(ballC, symbolC, playerResponseC) {12 ballIntervalTime = CONFIG.ball.defaultSpeed;13 playerResponseTime = CONFIG.space.playerResponseTime;14 ballCB = ballC;15 symbolCB = symbolC;16 playerResponseCB = playerResponseC;17 }18 createBallInterval() {19 clearInterval(ballInterval);20 ballInterval = setInterval(() => ballCB(), ballIntervalTime);21 }22 createSymbolInterval() {23 let time = this.randomNumber(3000, 6000)24 clearInterval(symbolInterval);25 symbolInterval = setInterval(() => symbolCB(), time)26 }27 createPlayerResponseTimeout()28 {29 playerResponseTimeout = setTimeout(() => playerResponseCB(), playerResponseTime)30 }31 reset() {32 clearInterval(ballInterval);33 clearInterval(symbolInterval);34 clearTimeout(playerResponseTimeout);35 ballIntervalTime = CONFIG.ball.defaultSpeed;36 playerResponseTime = CONFIG.space.playerResponseTime;37 }38 clearPlayerResponseTimeout()39 {40 clearTimeout(playerResponseTimeout);41 }42 slowDownButtonPressed() {43 ballIntervalTime += CONFIG.slowDownButton.slowDownBy44 this.createBallInterval()45 }46 randomNumber(min, max) {47 return Math.random() * (max - min) + min;48 }49 setBallIntervalTime(time) {50 ballIntervalTime = time;51 }52 getBallIntervalTime() {53 return ballIntervalTime;54 }55 resetBallIntervalSpeed() {56 ballIntervalTime = CONFIG.ball.defaultSpeed;57 }58 increaseBallIntervalSpeed() {59 if (ballIntervalTime > CONFIG.ball.maxSpeedInMilliseconds)60 ballIntervalTime -= CONFIG.ball.speedDecreaseInMilliseconds;61 this.createBallInterval();62 }63 decreaseBallIntervalSpeed() {64 if (ballIntervalTime < 1600)65 ballIntervalTime += CONFIG.ball.speedIncreaseInMilliseconds66 this.createBallInterval();67 }68 pauseIntervals()69 {70 clearInterval(ballInterval);71 clearInterval(symbolInterval);72 }73 continueIntervals()74 {75 this.createBallInterval();76 this.createSymbolInterval();77 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var devicefarmer = require('devicefarmer-stf');2stf.getDevices(function(err, devices) {3 console.log(devices);4});5stf.getDevices(function(err, devices) {6 console.log(devices);7 stf.use(devices[0].serial, function(err, device) {8 console.log('Using device ' + device.serial);9 stf.interval(device.serial, 1000, function(err, device) {10 console.log('Interval device ' + device.serial);11 stf.release(device.serial, function(err, device) {12 console.log('Released device ' + device.serial);13 });14 });15 });16});17var devicefarmer = require('devicefarmer-stf');18stf.getDevices(function(err, devices) {19 console.log(devices);20});21stf.getDevices(function(err, devices) {22 console.log(devices);23 stf.use(devices[0].serial, function(err, device) {24 console.log('Using device ' + device.serial);25 stf.interval(device.serial, 1000, function(err, device) {26 console.log('Interval device ' + device.serial);27 stf.release(device.serial, function(err, device) {28 console.log('Released device ' + device.serial);29 });30 });31 });32});

Full Screen

Using AI Code Generation

copy

Full Screen

1var DeviceFarmer = require('devicefarmer-stf-client');2var client = new DeviceFarmer.Client();3client.on('connect', function() {4 console.log('connected');5 client.interval(5000);6});7client.on('interval', function() {8 console.log('interval');9});10client.on('disconnect', function() {11 console.log('disconnected');12});13client.on('reconnect', function() {14 console.log('reconnect');15});16client.on('error', function() {17 console.log('error');18});19var DeviceFarmer = require('devicefarmer-stf-client');20var client = new DeviceFarmer.Client();21client.on('connect', function() {22 console.log('connected');23 client.interval(5000);24});25client.on('interval', function() {26 console.log('interval');27});28client.on('disconnect', function() {29 console.log('disconnected');30});31client.on('reconnect', function() {32 console.log('reconnect');33});34client.on('error', function() {35 console.log('error');36});37var DeviceFarmer = require('devicefarmer-stf-client');38var client = new DeviceFarmer.Client();39client.on('connect', function() {40 console.log('connected');41 client.interval(5000);42});43client.on('interval', function() {44 console.log('interval');45});46client.on('disconnect', function() {47 console.log('disconnected');48});49client.on('reconnect', function() {50 console.log('reconnect');51});52client.on('error', function() {53 console.log('error');54});55var DeviceFarmer = require('devicefarmer-stf-client');56var client = new DeviceFarmer.Client();57client.on('connect', function() {58 console.log('connected');59 client.interval(5000);60});61client.on('interval', function() {62 console.log('interval');63});64client.on('disconnect', function() {65 console.log('disconnected');66});67client.on('reconnect', function() {68 console.log('reconnect');69});70client.on('error

Full Screen

Using AI Code Generation

copy

Full Screen

1setInterval(function() {2 console.log('Repeating');3}, 1000);4setTimeout(function() {5 console.log('Repeating');6}, 1000);

Full Screen

Using AI Code Generation

copy

Full Screen

1var interval = require('interval');2var adb = require('adbkit');3var client = adb.createClient();4var device = client.listDevices().then(function(devices) {5 return devices[0];6}).catch(function(err) {7 console.error('Something went wrong:', err.stack);8 process.exit(1);9});10var deviceID = device.then(function(device) {11 return device.id;12}).catch(function(err) {13 console.error('Something went wrong:', err.stack);14 process.exit(1);15});16var deviceStatus = device.then(function(device) {17 return device.status;18}).catch(function(err) {19 console.error('Something went wrong:', err.stack);20 process.exit(1);21});22var deviceModel = device.then(function(device) {23 return device.model;24}).catch(function(err) {25 console.error('Something went wrong:', err.stack);26 process.exit(1);27});28var deviceType = device.then(function(device) {29 return device.type;30}).catch(function(err) {31 console.error('Something went wrong:', err.stack);32 process.exit(1);33});34var deviceProduct = device.then(function(device) {35 return device.product;36}).catch(function(err) {37 console.error('Something went wrong:', err.stack);38 process.exit(1);39});40var deviceManufacturer = device.then(function(device) {41 return device.manufacturer;42}).catch(function(err) {43 console.error('Something went wrong:', err.stack);44 process.exit(1);45});46var deviceScreen = device.then(function(device) {47 return device.screen;48}).catch(function(err) {49 console.error('Something went wrong:', err.stack);50 process.exit(1);51});52var deviceAbi = device.then(function(device) {53 return device.abi;54}).catch(function(err) {55 console.error('Something went wrong:', err.stack);56 process.exit(1);57});58var deviceSdk = device.then(function(device) {59 return device.sdk;60}).catch(function(err) {61 console.error('Something went wrong:', err.stack);62 process.exit(1);63});64var deviceVersion = device.then(function(device) {65 return device.version;66}).catch(function(err) {67 console.error('Something went wrong:', err.stack);68 process.exit(1);69});70var deviceIsOnline = device.then(function(device) {71 return device.isOnline;

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run devicefarmer-stf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful