How to use timeQuery method in Best

Best JavaScript code snippet using best

PerformQuery.js

Source:PerformQuery.js Github

copy

Full Screen

1import React, { useState, useEffect } from 'react';2import * as $ from 'jquery';3import { getDataFromServer } from '../../../services/services';4import moment from 'moment';5import { DatePicker } from 'antd';6import 'antd/dist/antd.css';7import { useDispatch, useSelector } from 'react-redux';8import {9 hadleSearch,10 setloadingButton,11 loadGraphic,12 setSamples,13 setTotalResponseData,14 getUrl,15 setActualPage16}17from '../../../actions';18import LoadingButton from '@mui/lab/LoadingButton';19import {Stack, MenuItem, FormControl, Select } from '@mui/material';20import PlayCircleFilledWhiteIcon from '@mui/icons-material/PlayCircleFilledWhite';21import ArrowRightIcon from '@mui/icons-material/ArrowRight';22import ArrowLeftIcon from '@mui/icons-material/ArrowLeft';23// import StopCircleIcon from '@mui/icons-material/StopCircle';24import DownloadEmailData from './DownloadData/DownloadEmailData';25// import AdvancedOptions from './AdvancedOptions';26import SaveQuery from './StroreQuerys/SaveQuery';27import ViewHandleQuery from './StroreQuerys/handleQuerys/ViewHandleQuery';28import PopUpMessage from '../../handleErrors/PopUpMessage';29import buildUrl from './buildUrl'30/*31 * Hide Component and monitor list32 */33const hideAndShowSection = () => {34 $('.perform-query-section').toggleClass('hide-sections')35 $('.arrow-showPerfomSection').toggleClass('hide-sections')36}37function PerformQuery(props) {38 const dispatch = useDispatch()39 const [msg, handleMessage] = PopUpMessage()40 const monitor = useSelector(state => state.monitor)41 const loadWhileGetData = useSelector(state => state.loadingButton)42 const pagination = useSelector(state => state.pagination)43 const editing = useSelector(state => state.editingQuery)44 const [loadingSearch, setLoadingSearch] = useState(false)45 const [beginDateInput, setBeginDateInput] = useState("")46 const [endDateInput, setEndDateInput] = useState("")47 48 const [timeQuery, setTimeQuery] = useState({49 beginDate: "",50 endDate: "",51 sampling: 052 })53 /*54 * Show Error55 */56 const showErrorMessage = (mesage) => {57 handleMessage({ 58 message: mesage, 59 type: 'error',60 persist: true,61 preventDuplicate: false62 })63 }64 /*65 * handle warning message66 */67 const showWarningMeggage = (message) => {68 handleMessage({ 69 message: message, 70 type: 'warning', 71 persist: false,72 preventDuplicate: false73 })74 }75 76 /*77 * 'loadWhileGetData' will be set to true when the data has arrived, and then the buttons will be active again78 */79 useEffect(() => {80 if (loadWhileGetData) {81 setLoadingSearch(false);82 }83 }, [loadWhileGetData])84 /*85 * set a sampling if specified86 */87 useEffect(() => {88 setTimeQuery(prevState =>({89 ...prevState,90 sampling: (editing?.active && editing?.sampling) ? editing.sampling : 091 }))92 }, [editing])93 /*94 * Get Samples From Server95 */96 const getSamplesFromServer = () => {97 const url = buildUrl(monitor, timeQuery, pagination) // construct url98 dispatch(getUrl(url)) // refactor => eliminar99 100 Promise.resolve( getDataFromServer(url) )101 .then(res => { 102 const totalArraysRecive = res.samples.length103 const totalRecords = res.reportInfo.totalSamples104 const totalPerPage = props.urliDisplayLength105 dispatch(setSamples(res, timeQuery.sampling))106 dispatch(setTotalResponseData(totalArraysRecive, totalRecords, totalPerPage))107 console.log("\n \108 MonitorsMagnitude Data was recibe successfully!! \n \109 Sampling Period Choosen: " + timeQuery.sampling + " microsegundos \n \110 Arrays Recived: " + totalArraysRecive + " \n \111 total Records: " + totalRecords + " \n \112 ----------------------------------------------------------------"113 )114 })115 .catch(error => {116 const error_message = (error.response?.data) ? error.response.data.toString() : "Unsupported error";117 const error_status = (error.response?.status) ? error.response.status : "Unknown"118 showErrorMessage('Error: ' + error_message + " - Code " + error_status)119 console.error(error)120 })121 .finally(() => {122 dispatch(setloadingButton(true))123 dispatch(loadGraphic(false))124 })125 }126 /*127 * handle search inputs onchange128 */129 const onChange = (date, value, dateFieldName) => {130 try {131 setTimeQuery(prevState => ({132 ...prevState,133 [dateFieldName]: value134 }))135 if(dateFieldName === "beginDate") // antDesign input string format date136 setBeginDateInput(date) 137 else if(dateFieldName === "endDate")138 setEndDateInput(date)139 } catch (error) {140 showErrorMessage(error)141 }142 }143 144 /*145 * Convert Date to unix146 */147 const convertToUnix = (date) => {148 let format = date.split(" ") // split date an time149 format = format[0].split(/[-/]/).reverse().join('/') + " " + format[1] // change format to YYYY/MM/DD150 return new Date(format).getTime()151 }152 /*153 * dispatch acction if submit was correct154 */155 const dispatchActionsOnSubmit = () => {156 const perform = true; // initial state use to check searched monitors selected comparation157 dispatch(setActualPage(false, 0, 0)) // reset pagination if it is already display158 const searchedMonitors = monitor.map(e => e["id"]) // save the monitors id's that where choosen for the search159 dispatch(hadleSearch(perform, timeQuery.beginDate, timeQuery.endDate, timeQuery.sampling, searchedMonitors))160 dispatch(setloadingButton(false))161 dispatch(loadGraphic(true))162 }163 /*164 * Check Dates and sampling inputs before submit165 */166 const checkOnSubmit = (button_click) => {167 // convert to unix 168 // we use this to get a better control over the correct validation of the dates169 const unixBeginDate = convertToUnix(timeQuery["beginDate"])170 const unixEndDate = convertToUnix(timeQuery["endDate"])171 // handle all errors from the date inputs172 if (timeQuery.beginDate === '' || timeQuery.endDate === ''){173 showWarningMeggage('The Date Fields cannot be empty')174 return false175 }176 else if (unixBeginDate > unixEndDate){177 showWarningMeggage('The begin Date cannot be greater than end Date')178 return false179 }180 else if (timeQuery.beginDate === timeQuery.endDate){181 showWarningMeggage('The begin and end Date cannot be the same')182 return false183 }184 else if (monitor[0] === undefined){185 showWarningMeggage('There are no monitors selected')186 return false187 }188 else{189 if(button_click !== "download"){ // refactor llamar buildUrl desde download190 setLoadingSearch(true)191 dispatchActionsOnSubmit()192 getSamplesFromServer()193 }194 else{195 return buildUrl(monitor, timeQuery, pagination, true)196 }197 return true198 }199 }200 return(201 <>202 <div className="arrowShowHide arrow-showPerfomSection hide-sections"><ArrowLeftIcon onClick={() => { hideAndShowSection() }} className="arrow-rightSection" /></div>203 <div className="perform-query-section">204 <div className="sample-header-perform-query">205 <Stack direction="column" spacing={1}>206 <Stack className="stack-row-components-title-buttons" direction="row">207 <p className="components-item-title">Perform Queries</p>208 <ArrowRightIcon onClick={() => { hideAndShowSection() }} className="hide_icon_componentList"/>209 </Stack>210 <div className="perform-query-date-time-picker">211 <DatePicker212 id="beginDate"213 showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}214 format="DD/MM/YYYY HH:mm:ss"215 placeholder="Start Date"216 value={beginDateInput}217 onChange={(date, dateString) => {onChange(date, dateString, "beginDate")}}218 />219 <DatePicker220 id="endDate"221 showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}222 format="DD/MM/YYYY HH:mm:ss"223 placeholder="End Date"224 value={endDateInput}225 onChange={(date, dateString) => {onChange(date, dateString, "endDate")}}226 />227 </div>228 <FormControl sx={{ m: 1, minWidth: 120 }}>229 <Select230 className="select-sampling-perform-query"231 value={timeQuery.sampling}232 onChange={(e) => {onChange(null, e.target.value, "sampling")}}233 displayEmpty234 inputProps={{ 'aria-label': 'Without label' }}235 >236 <MenuItem disabled value="">237 <em className="default-select-sampling">Sampling</em>238 </MenuItem>239 <MenuItem value={0}>Default</MenuItem>240 <MenuItem value={100000}>100 milliseconds</MenuItem>241 <MenuItem value={200000}>200 milliseconds</MenuItem>242 <MenuItem value={500000}>500 milliseconds</MenuItem>243 <MenuItem value={1000000}>1 second</MenuItem>244 <MenuItem value={2000000}>2 seconds</MenuItem>245 <MenuItem value={5000000}>5 seconds</MenuItem>246 <MenuItem value={10000000}>10 seconds</MenuItem>247 <MenuItem value={60000000}>1 minute</MenuItem>248 <MenuItem value={120000000}>2 minutes</MenuItem>249 <MenuItem value={300000000}>5 minutes</MenuItem>250 <MenuItem value={600000000}>10 minutes</MenuItem>251 <MenuItem value={3600000000}>1 hour</MenuItem>252 <MenuItem value={7200000000}>2 hours</MenuItem>253 </Select>254 </FormControl>255 </Stack>256 </div>257 <div className="perform-query-buttons-box">258 <Stack spacing={1}>259 { // Advance options component260 // <AdvancedOptions />261 }262 <div className="flex-row">263 <LoadingButton264 onClick={() => {265 checkOnSubmit('display');266 }}267 loading={loadingSearch}268 loadingPosition="start"269 className="perfrom-query-button-search"270 variant="contained"271 startIcon={<PlayCircleFilledWhiteIcon/>}272 >273 Search & Display274 </LoadingButton>275 </div>276 { // Only_Download data component // TODO: change file name277 <DownloadEmailData278 service ={props.serviceIP}279 checkOnSubmit={checkOnSubmit}280 />281 }282 </Stack>283 </div>284 <div className="store-query-section">285 <div className="sample-header-store-query">286 <Stack direction="column" spacing={1}>287 Store Queries288 <SaveQuery 289 convertToUnix={convertToUnix}290 timeQuery={timeQuery}291 editing={editing}292 />293 {294 (editing?.active) ? "" :295 <ViewHandleQuery 296 editing={editing}297 />298 }299 </Stack>300 </div>301 </div>302 </div>303 </>304 );305}...

Full Screen

Full Screen

es_model.js

Source:es_model.js Github

copy

Full Screen

1'use strict';2// Loading required libraries and config file3const es = require('elasticsearch');4const uuidv4 = require('uuid/v4');5const config = require('../../config/config.json');6var winston = require('winston');7var deepcopy = require("deepcopy");8var logger = winston.createLogger({9 transports: [10 new (winston.transports.Console)({ 'timestamp': true, level: 'error' })11 ],12 exitOnError: false13});14// Connection to elasticsearch15const esClient = new es.Client({16 host: [17 {18 host: config.garage.backend.esHost,19 port: config.garage.backend.esPort20 }21 ]22});23/** Checks if index exists */24const checkIndexExists = (indexName) => {25 return new Promise(function (resolve, reject) {26 esClient.indices.exists({ index: indexName }).then(response=> {27 resolve(response)28 }).catch(error=>{29 reject(error);30 });31 });32}33/** Queries the Event Index and returns the results */34const getEvents = (query,isSearch) => {35 return new Promise(function (resolve, reject) {36 let indexName = config.garage.backend.esEventsIndex;37 checkIndexExists(indexName).then(indexExist=>{38 if(indexExist){39 let queryObject={40 index: indexName,41 q: query,42 sort: '@timestamp:desc',43 _sourceInclude: [44 'object.vehicle.license', '@timestamp',45 'place.entrance.level','place.parkingSpot.level', 'place.aisle.level',46 'event.type',47 'videoPath'48 ]49 };50 if(isSearch){51 queryObject['size']=config.garage.backend.anomalyEventQuerySize;52 }else{53 queryObject['size']=config.garage.backend.eventApiQueryResultSize;54 }55 esClient.search(queryObject).then(results => {56 results = results.hits.hits;57 resolve(results);58 }).catch(error => {59 reject(error)60 });61 }else{62 resolve([]);63 logger.info('[ALERT!] Index not yet created');64 }65 }).catch(error => {66 reject(error)67 });68 });69}70/** Queries the Anomaly Index and returns the results */71const getAnomaly = (query) => {72 return new Promise(function (resolve, reject) {73 let indexName = config.garage.backend.esAnomalyIndex;74 checkIndexExists(indexName).then(indexExist=>{75 if(indexExist){76 esClient.search({77 index: indexName,78 size: config.garage.backend.anomalyEventQuerySize,79 q: query,80 sort: '@timestamp:desc',81 _sourceInclude: [82 'object.vehicle.license', '@timestamp',83 'place.entrance.level', 'place.parkingSpot.level', 'place.aisle.level',84 'analyticsModule.description',85 'entryVideo', 'exitVideo', 'endTimestamp'86 ]87 }).then(results => {88 results = results.hits.hits;89 resolve(results);90 }).catch(error => {91 reject(error)92 });93 }else{94 resolve([]);95 logger.info('[ALERT!] Index not yet created');96 }97 }).catch(error => {98 reject(error)99 });100 });101}102/** Queries the Event Index and returns the results */103const getEventsDeprecated = (query) => {104 return new Promise(function (resolve, reject) {105 let indexName = config.garage.backend.esEventsIndex;106 checkIndexExists(indexName).then(indexExist=>{107 if(indexExist){108 esClient.search({109 index: indexName,110 size: config.garage.backend.anomalyEventQuerySize,111 q: query,112 sort: '@timestamp:desc',113 _sourceInclude: [114 'object.vehicle.license', '@timestamp',115 'place.entrance.level','place.parkingSpot.level', 'place.aisle.level',116 'event.type',117 'videoPath'118 ]119 }).then(results => {120 results = results.hits.hits;121 resolve(results);122 }).catch(error => {123 reject(error)124 });125 }else{126 resolve([]);127 logger.info('[ALERT!] Index not yet created');128 }129 }).catch(error => {130 reject(error)131 }); 132 });133}134/** Used to obtain the start and end index of search tokens in a complex search query string */135function getTokenAttributes(token,tokenAttributes){136 let newTokenAttributes=deepcopy(tokenAttributes);137 let extractedToken=token.substring(tokenAttributes.start,tokenAttributes.end)138 if (extractedToken.startsWith('(')||extractedToken.startsWith('!')){139 newTokenAttributes.start+=1;140 }else if(extractedToken.endsWith(')')){141 newTokenAttributes.end-=1;142 }143 if(tokenAttributes.start===newTokenAttributes.start && tokenAttributes.end===newTokenAttributes.end){144 return tokenAttributes;145 }else{146 return getTokenAttributes(token,newTokenAttributes);147 }148}149/** Formats the search query */150function formatSearchQuery(q,timeQuery){151 if(q==null){152 return(timeQuery);153 }154 let luceneOperatorSet=new Set(["||","&&","!","OR","AND","NOT"]);155 let tokenList=q.split(" ");156 for(let i=0;i<tokenList.length;i++){157 let token=tokenList[i];158 if(!luceneOperatorSet.has(token)){159 tokenList[i]=token;160 let tokenAttributes={start:0,end:token.length};161 tokenAttributes=getTokenAttributes(token,tokenAttributes);162 let finalExtractedToken=token.substring(tokenAttributes.start,tokenAttributes.end);163 tokenList[i]=token.substring(0,tokenAttributes.start)+'"'+finalExtractedToken+'"'+token.substring(tokenAttributes.end);164 } 165 }166 let formattedQuery=tokenList.join(" ");167 q='('+formattedQuery+') AND '+timeQuery;168 return q;169}170/** The result is compressed so that a variety of events can be obtained for various detected objects. 171 * Moving events for a particular license plate is compressed based on the value mentioned for eventCompressionSize key in the config file. 172*/173function getCompressedResult(results){174 let compressedResult=new Array();175 let resultDictionary={};176 for (let result of results){177 if(result._source.event.type!=="moving"){178 compressedResult.push(result);179 }else{180 let key = result._source.object.vehicle.license === "" ? uuidv4() : result._source.object.vehicle.license;181 if (resultDictionary.hasOwnProperty(key.toString())) {182 resultDictionary[key].push(result);183 }else{184 resultDictionary[key]=new Array();185 resultDictionary[key].push(result);186 }187 }188 }189 let keys=Object.getOwnPropertyNames(resultDictionary);190 for(let key of keys){191 let resultList=resultDictionary[key];192 resultList.sort(function(x, y){193 return y._source['@timestamp'] - x._source['@timestamp'];194 });195 let slicedResultList=resultList.slice(0,config.garage.backend.eventCompressionSize);196 for (let result of slicedResultList) {197 compressedResult.push(result);198 }199 }200 compressedResult.sort(function(x, y){201 return y._source['@timestamp'] - x._source['@timestamp'];202 });203 return compressedResult;204}205module.exports={206 /** Formats the query before getting the events from elasticsearch and compresses the result before sending to client*/207 searchEvents:function(req,res,next){208 let q=req.query['q'];209 let timeQuery=req.query['timeQuery'];210 let isSearch=(req.query['isSearch']=== 'true');211 q=formatSearchQuery(q,timeQuery);212 getEvents(q,isSearch).then((response) => {213 if(isSearch){214 res.send(response);215 }else{216 let compressedResult=getCompressedResult(response);217 res.send(compressedResult.slice(0,config.garage.backend.anomalyEventQuerySize));218 }219 }).catch(error=>{220 console.log(error)221 });222 },223 /** Formats the query and gets the anomalies from elasticsearch */224 searchAnomaly:function(req,res,next){225 let q=req.query['q'];226 let timeQuery=req.query['timeQuery'];227 q=formatSearchQuery(q,timeQuery);228 getAnomaly(q).then((response) => {229 res.send(response);230 }).catch(error=>{231 console.log(error)232 });233 },234 /** Formats the query and gets the events from elasticsearch (Deprecated)*/235 searchEventsDeprecated:function(req,res,next){236 let q=req.query['q'];237 let timeQuery=req.query['timeQuery'];238 q=formatSearchQuery(q,timeQuery);239 getEventsDeprecated(q).then((response) => {240 res.send(response);241 }).catch(error=>{242 console.log(error)243 });244 }...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import React from 'react'2import { useQuery } from 'react-query'3import axios from 'axios'4export default function Posts() {5 const timeQuery = useQuery(6 'posts',7 async () => {8 return axios.get('/api/time').then(res => res.data)9 },10 {11 refetchInterval: 1000,12 refetchIntervalInBackground: true,13 }14 )15 return (16 <div>17 <h1>Server Time {timeQuery.isFetching ? '...' : null}</h1>18 <div>19 {timeQuery.isLoading20 ? 'Loading time...'21 : new Date(timeQuery.data.time).toLocaleString()}22 </div>23 </div>24 )...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestBuy = require('./bestbuy.js');2var bb = new BestBuy();3bb.timeQuery(function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});

Full Screen

Using AI Code Generation

copy

Full Screen

1const BestBuyApi = require('./bestbuyapi');2const bestbuy = new BestBuyApi();3bestbuy.timeQuery().then((data) => {4 console.log(data);5});6timeQuery() {7 return new Promise((resolve, reject) => {8 if(err) {9 reject(err);10 } else {11 resolve(body);12 }13 });14 });15}

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestBuy = require('./bestbuy.js');2var bestbuy = new BestBuy();3bestbuy.timeQuery('playstation', function(err, res) {4 if (err) {5 console.log('Error: ' + err);6 } else {7 console.log(res);8 }9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestTime = require('./bestTime');2var bestTime = new BestTime();3var time = bestTime.timeQuery('2015-05-01 12:00:00', '2015-05-01 12:00:00', '2015-05-01 12:00:00', '2015-05-01 12:00:00');4console.log(time);5var BestTime = function() {};6BestTime.prototype.timeQuery = function() {7 return '12:00:00';8};9module.exports = BestTime;10var BestTime = function() {};11BestTime.prototype.timeQuery = function() {12 return '12:00:00';13};14module.exports = BestTime.prototype.timeQuery;

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 Best 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