def run(self): time = QTime() hora = time.currentTime().toString() #self.startTelaDeLog.emit(hora + " - Inicializaçao do Sistema") while True: hora = time.currentTime().toString() self.horario.emit(hora)
def factor(self,N): startTime = currentTime() possibleA = largeNumber(squareRoot(N)) condition = True iteration = 0 while condition: x = largeNumber(squareRoot(possibleA**2 - N)) possibleP = possibleA - x possibleQ = possibleA + x #Debug print("---") print("Iteration:",iteration) print("possibleA:",str(possibleA)) print("x:",x) print("possibleP:",str(possibleP)) print("possibleQ:",str(possibleQ)) print("Match:",str(largeNumber(possibleP*possibleQ)),"out of",N," --- Approximately",( largeNumber(largeNumber(possibleP*possibleQ)/N) )*100,"%") print("---") if possibleP*possibleQ == N: endTime = currentTime() condition = False return self.assign(possibleP,possibleQ,possibleA,x,startTime,endTime) else: possibleA += 1 iteration += 1
def run(self, pipeline=None): #bring into local scope and save most recently used pipeline if pipeline == None: pipeline = self.pipeline self.pipeline = pipeline if pipeline is not None else self.pipeline pipelineName = pipeline.path.split("/")[-1] else: raise ValueError("A pipeline must be given") print("Loading dataset") ins = pipeline.dataset.map(lambda first, second: first) targets = pipeline.dataset.map(lambda first, second: second) ins = np.array(list(ins.as_numpy_iterator())) targets = np.array(list(targets.as_numpy_iterator())) for model in self.models: model = self.models[model] print(f"Running {model.name}...") timeStart = currentTime() modelOut = model.process(pipeline) inferenceTime = currentTime() - timeStart modelResults = {"outs": modelOut} modelSummary = {} if pipeline.numEntries is not None: modelSummary[ "Inference time"] = f"{inferenceTime/pipeline.numEntries} s/entry" else: modelSummary["Inference time"] = f"{inferenceTime} s" print("Done.") for metric in self.metrics: metric = self.metrics[metric] print(f"Evaluating {model.name}-{metric.name}...") mean, stdDev, full = metric.call(modelOut, targets) modelSummary[metric.name] = f"{mean}+/-{stdDev}" modelResults[metric.name] = full self.results[model.name] = modelSummary self.data[model.name] = modelResults baselineSummary = {"Inference time": "N/A"} baselineResults = {} for metric in self.metrics: metric = self.metrics[metric] if metric.baseline: print(f"Running baseline metric: {metric.name}") mean, stdDev, full = metric.call(ins, targets) baselineSummary[metric.name] = f"{mean} +/- {stdDev}" baselineResults[metric.name] = full else: baselineSummary[metric.name] = "N/A" baselineResults[metric.name] = None self.results[f"dataset--{pipelineName}"] = baselineSummary self.data[f"dataset--{pipelineName}"] = baselineResults del pipeline, ins, targets return self.results
def run(self): print('start main game calculation thread') self.__updateTimeStamp() while True: self.deltaTime = self.__calculateDeltaTime() self.__updateGame(self.deltaTime) self.__updateTimeStamp() if currentTime() - self.lastSent >= BROADCAST_DELAY: self.__broadcastGameData() self.lastSent = currentTime()
def timeit(func, iter=1000, *args, **kwargs): """ timeit(func, iter = 1000 *args, **kwargs) -> elapsed time calls func iter times with args and kwargs, returns time elapsed """ from time import time as currentTime r = range(iter) t = currentTime() for i in r: func(*args, **kwargs) return currentTime() - t
def timeit(func, iter = 1000, *args, **kwargs): """ timeit(func, iter = 1000 *args, **kwargs) -> elapsed time calls func iter times with args and kwargs, returns time elapsed """ from time import time as currentTime r = range(iter) t = currentTime() for i in r: func(*args, **kwargs) return currentTime() - t
def _calculateAllCorr(numComplete, against, totalToAnalyze, stocks, fp, maxShift, minShift, shiftFactor): printMessage('Calculating Correlations') for i, tick in enumerate(stocks.columns): start = currentTime() tickResults = pd.DataFrame() tickData = stocks[tick].shift(minShift) for day in range(minShift, maxShift + 1): tickData = tickData.shift(shiftFactor) tickResults[day] = against.corrwith(tickData) print(i + 1 + numComplete, 'out of', totalToAnalyze, currentTime() - start) saveProgress(fp, tickResults, tick)
def get(self, key): (val, exptime) = self._data[key] if exptime and currentTime() > exptime: del self._data[key] raise KeyError(key) else: return val
def updateGameState(gameData): allReady = True allFinished = True someFinished = False for player in gameData.playerDataList: state = player.getPlayerState() if state is not PLAYERSTATE.READY: allReady = False if state is not PLAYERSTATE.FINISHED: allFinished = False if state is PLAYERSTATE.FINISHED: someFinished = True # assuming this method won't be called while gameState is READY if allReady and currentTime() - gameData.launchTime < LAUNCH_TIME: updatedState = GAMESTATE.LAUNCHING elif allFinished: updatedState = GAMESTATE.ALL_FINISHED elif someFinished: updatedState = GAMESTATE.FIRST_FINISHED else: updatedState = GAMESTATE.PLAYING_NO_WINNER gameData.gameState = updatedState
def __init__(self): # Explaining super is out of the scope of this article # So please google it if you're not familar with it # Simple reason why we use it here is that it allows us to # access variables, methods etc in the design.py file self.t1 = None super(self.__class__, self).__init__() self.setupUi(self) # This is defined in design.py file automatically # It sets up layout and widgets that are defined # When the button is pressed self.btnAddContact.clicked.connect( self.openWebToAddContact) # Execute browse_folder function self.btnHistory.clicked.connect(self.openHistory) self.btnStart.clicked.connect(self.runScriptStart) self.btnStop.clicked.connect(self.btn_stop) self.btnContactList.clicked.connect(self.open_contact) #update date and current time from os. time = QTime() date = QDate() current_t = time.currentTime() current_d = date.currentDate() self.timeEdit.setTime(current_t) self.dateEdit.setDate(current_d)
def action(self, complete): if complete.type() == "NOTICE" and complete.fullMessage().split( )[0] == "TIME": time = ' '.join(complete.message().split())[:-1] channel = self.getChannel(complete.user()) return [ "PRIVMSG " + channel + " :" + complete.user() + "'s local time is: " + time ] elif complete.type() == "NOTICE" and complete.fullMessage().split( )[0] == "\001VERSION": time = ' '.join(complete.message().split())[:-1] channel = self.getChannel(complete.user()) return [ "PRIVMSG " + channel + " :" + complete.user() + "'s version is: " + time ] elif complete.type() == "NOTICE" and complete.fullMessage().split( )[0] == "\001FINGER": time = ' '.join(complete.message().split())[:-1] channel = self.getChannel(complete.user()) return [ "PRIVMSG " + channel + " :" + complete.user() + "'s finger is: " + time ] elif complete.type() == "NOTICE" and complete.fullMessage().split( )[0] == "\001PING": now = currentTime() then = float(complete.message()[:-1]) channel = self.getChannel(complete.user()) return [ "PRIVMSG " + channel + " :Received %s's pong in %s seconds." % (complete.user(), (now - then)) ] return [""]
def log(logLevel, logInfo): colourCodes = ["green", "yellow", "red", "cyan"] # Colour codes for different error levels logLevels = ["[Info] ", "[Warning] ", "[Error] ", "[Debug] "] # Labels for different log levels timeStamp = "["+currentTime("%H:%M:%S")+"] " # Timestamp of current time if enableDebugging == False and logLevel == 3: return else: click.echo(click.style(logLevels[logLevel], fg=colourCodes[logLevel])+click.style(timeStamp, fg="blue")+logInfo) # Display error level of log event, current time and log descriptiom
def update_info(self) : if self.SN == None : self.SN = self.get_serial_number() if not self.optical : self.optical = array('h') self.optical.extend([0] * NUMBER_OF_SAMPLES) if not self.latency : self.latency = array('h') self.latency.extend([0] * NUMBER_OF_SAMPLES) oldTimeStamp = currentTime() #self.load() # Borramos el dato actual. self.optical[int(tm % NUMBER_OF_SAMPLES)] = 0 self.latency[int(tm % NUMBER_OF_SAMPLES)] = 0 try : newRxPower = self.get_optical_info()["RxPower"] newTimeStamp = currentTime() # Borro los posibles "huecos" que se puedan producir por una latencia alta. raise Exception("last=%i new=%i" % (self.lastTime, newTimeStamp)) if self.lastTime and int(newTimeStamp) != int(self.lastTime+1) : self._clearRangeData(self.lastTime+1, newTimeStamp) self.lastTime = newTimeStamp indice = int(self.lastTime % NUMBER_OF_SAMPLES) # Guardo los datos float convertidos a un entero pero multiplicado por 256 para no perder muchos decimales try: self.latency[indice] = int((newTimeStamp-oldTimeStamp) * 256) except OverflowError: self.latency[indice] = int(32768 if newTimeStamp-oldTimeStamp > 0 else -32768) try: self.optical[indice] = int(newRxPower * 256) except OverflowError: self.optical[indice] = int(32768 if newRxPower > 0 else -32768) print "%i: %fdb %fseg." % (self.lastTime, float(self.optical[indice]) / 256.0, float(self.latency[indice])/256.0) except : newTimeStamp = currentTime() if self.lastTime and int(self.lastTime+1) != int(newTimeStamp) : self._clearRangeData( self.lastTime+1, newTimeStamp ) raise
def onStateChanged(self): """Действие при активации чекбокса""" now = datetime.datetime.now() date_1 = now.strftime("%d.%m.%Y") date_ne_pars = now.strftime("%H:%M:%S") chbk = self.sender() print(chbk.parent()) ix = self.table_widget.indexAt(chbk.pos()) print(ix.row(), ix.column() + 1, chbk.isChecked()) if chbk.isChecked(): time = QtCore.QTime() print(time.currentTime()) type(time.currentTime()) self.table_widget.setItem(ix.row(), ix.column() - 1, QTableWidgetItem(date_ne_pars)) chbk.setDisabled(True) else: self.table_widget.setItem(ix.row(), ix.column() - 1, QTableWidgetItem('Не выполнилось'))
def action(self, complete): if complete.type()=="NOTICE" and complete.fullMessage().split()[0]=="TIME": time=' '.join(complete.message().split())[:-1] channel=self.getChannel(complete.user()) return ["PRIVMSG "+channel+" :"+complete.user()+"'s local time is: "+time] elif complete.type()=="NOTICE" and complete.fullMessage().split()[0]=="\001VERSION": time=' '.join(complete.message().split())[:-1] channel=self.getChannel(complete.user()) return ["PRIVMSG "+channel+" :"+complete.user()+"'s version is: "+time] elif complete.type()=="NOTICE" and complete.fullMessage().split()[0]=="\001FINGER": time=' '.join(complete.message().split())[:-1] channel=self.getChannel(complete.user()) return ["PRIVMSG "+channel+" :"+complete.user()+"'s finger is: "+time] elif complete.type()=="NOTICE" and complete.fullMessage().split()[0]=="\001PING": now=currentTime() then=float(complete.message()[:-1]) channel=self.getChannel(complete.user()) return ["PRIVMSG "+channel+" :Received %s's pong in %s seconds."%(complete.user(), (now-then))] return [""]
def _update_instrument_order(self): '''Updates calculated_instrument_order, missing_instruments and surplus_instruments based on canonical_instrument_order and the connected instruments. ''' instrument_order = self.settings['instrument_order'] detected_instruments = self.visualizer_state['connections'].keys() calculated_instruments = [i for i in instrument_order if i in detected_instruments] surplus_instruments = [i for i in detected_instruments if i not in instrument_order] missing_instruments = [i for i in instrument_order if i not in detected_instruments] self.internal_settings['calculated_instrument_order'] = calculated_instruments self.internal_settings['missing_instruments'] = missing_instruments self.internal_settings['surplus_instruments'] = surplus_instruments if surplus_instruments: t = currentTime() if t - self.viz_last_warning_message_time > 10: self.log('Warning, the following instruments are missing from the visualization order: {}'.format(surplus_instruments)); self.viz_last_warning_message_time = t
def setData(self, data): self._refreshTime = currentTime() self._cacheStore.set(self._cacheItemID, data, self._expiryTime)
def hasExpired(self): return self._expiryTime and currentTime() > self._expiryTime
import sys from PyQt5.QtWidgets import * import time from PyQt5.QtCore import * import os import pyqrcode from PyQt5.QtGui import * from PIL import Image wd=os.getcwd() os.chdir(wd+"\\") #find local time/system time time=QTime() current_t = time.currentTime() str_current_t=str(current_t) a="Successfully signed into " #generate qr code function def qr_gen(string): qr_code=pyqrcode.create(string) qr_code_img=qr_code.png(wd+"\\code.png") return qr_code_img class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize(591, 287)
def __init__(self, gameData, connectionList): super().__init__(name="GameCalculationThread") self.gameData = gameData self.connectionList = connectionList self.lastSent = currentTime()
def SetupEmbeddedWorld(worldname): global WORLDSERVER global MANHOLE DATABASE = "sqlite:///%s/%s/data/worlds/singleplayer/%s/world.db" % ( os.getcwd(), GAMEROOT, worldname) SetDBConnection(DATABASE, True) #destroy the new player user, and recreate try: user = User.byName("NewPlayer") user.destroySelf() except: pass CreatePlayer() IDESetup() #--- Application from twisted.spread import pb from twisted.internet import reactor from twisted.cred.credentials import UsernamePassword from mud.server.app import Server WORLDSERVER = server = Server(3013) server.startServices() #kickstart the heart world = World.byName("TheWorld") #TODO, single player backups #world.dbFile = os.getcwd()+"/minions.of.mirth/data/worlds/singleplayer/"+worldname+"/world.db" try: v = int(TGEGetGlobal("$pref::gameplay::difficulty")) except: v = 0 TGESetGlobal("$pref::gameplay::difficulty", 0) try: respawn = float(TGEGetGlobal("$pref::gameplay::monsterrespawn")) except: TGESetGlobal("$pref::gameplay::monsterrespawn", 0.0) respawn = 0.0 try: SPpopulators = int(TGEGetGlobal("$pref::gameplay::SPpopulators")) except: SPpopulators = 0 TGESetGlobal("$pref::gameplay::SPpopulators", 0) if v == 1: CoreSettings.DIFFICULTY = 0 elif v == 2: CoreSettings.DIFFICULTY = 2 else: CoreSettings.DIFFICULTY = 1 CoreSettings.RESPAWNTIME = respawn CoreSettings.SPPOPULATORS = SPpopulators CoreSettings.SINGLEPLAYER = True world.launchTime = currentTime() world.singlePlayer = True world.startup() world.transactionTick() world.tick()
def __calculateDeltaTime(self): return currentTime() - self.previousTimeStamp
def hasExpired(self): return (self._expiryTime and currentTime() > self._expiryTime)
def changeMade(self): self.lastUpdate = currentTime()
def addNewPrice(self, price): priceData = {"Price": price, "Time": currentTime()} self.prices.append(priceData)
def start(self): print('game is started') if self.gameState is GAMESTATE.READY: self.gameState = GAMESTATE.LAUNCHING self.launchTime = currentTime()
def __init__(self): self.lastUpdate = currentTime() self.products = []
def current_time(self): time = QtCore.QTime() curent_t = time.currentTime() return curent_t
def SetupEmbeddedWorld(worldname): global WORLDSERVER global MANHOLE DATABASE = "sqlite:///%s/%s/data/worlds/singleplayer/%s/world.db"%(os.getcwd(),GAMEROOT,worldname) SetDBConnection(DATABASE,True) #destroy the new player user, and recreate try: user = User.byName("NewPlayer") user.destroySelf() except: pass CreatePlayer() IDESetup() #--- Application from twisted.spread import pb from twisted.internet import reactor from twisted.cred.credentials import UsernamePassword from mud.server.app import Server WORLDSERVER = server = Server(3013) server.startServices() #kickstart the heart world = World.byName("TheWorld") #TODO, single player backups #world.dbFile = os.getcwd()+"/minions.of.mirth/data/worlds/singleplayer/"+worldname+"/world.db" try: v = int(TGEGetGlobal("$pref::gameplay::difficulty")) except: v = 0 TGESetGlobal("$pref::gameplay::difficulty",0) try: respawn = float(TGEGetGlobal("$pref::gameplay::monsterrespawn")) except: TGESetGlobal("$pref::gameplay::monsterrespawn",0.0) respawn = 0.0 try: SPpopulators = int(TGEGetGlobal("$pref::gameplay::SPpopulators")) except: SPpopulators = 0 TGESetGlobal("$pref::gameplay::SPpopulators",0) if v == 1: CoreSettings.DIFFICULTY = 0 elif v == 2: CoreSettings.DIFFICULTY = 2 else: CoreSettings.DIFFICULTY = 1 CoreSettings.RESPAWNTIME = respawn CoreSettings.SPPOPULATORS = SPpopulators CoreSettings.SINGLEPLAYER = True world.launchTime = currentTime() world.singlePlayer = True world.startup() world.transactionTick() world.tick()
raise def getPrintableData(self) : i = 0 rtn = [None] * NUMBER_OF_SAMPLES while i < NUMBER_OF_SAMPLES : fecha = (int(self.lastTime) - NUMBER_OF_SAMPLES) + i indice = fecha % NUMBER_OF_SAMPLES latencia = self.latency[indice] potencia = self.optical[indice] rtn[i] = [fecha, potencia, latencia] i += 1 return rtn if __name__ == '__main__': import sys ontInfo = ONTInfo("10.50.219.95", "root", "admin", 10023) ontInfo.connect() ontInfo.load() tm = 0 i = 0 while i < 65 : while tm == int(currentTime()) : pass tm = int(currentTime()) ontInfo.update_info() i+=1 print ontInfo
def __updateTimeStamp(self): self.previousTimeStamp = currentTime()
#k[0] = setPeriodicForcingValues(t, nrOfGrainSizes, [20000*yr2sec, 60000*yr2sec], [1*3.2e-4, 0.5*3.2e-4] , [1*3.2e-4, 1*3.2e-4], 0) #k[1] = setPeriodicForcingValues(t, nrOfGrainSizes, [20000*yr2sec, 60000*yr2sec], [2*3.2e-4, 1*3.2e-4] , [2*3.2e-4, 2*3.2e-4], 0) subsidenceRate = setPeriodicForcingValues(t, nrOfGrainSizes, tmax, 2e-5, 3e-7) #subsidenceRate = 2e-6 #k[0]= 4*3.2e-4 # Gravel diffusivity (m2/s) Attention: will be overwritten in setBoudnaryCondtitionValues if declared there! #k[1]= 5*3.2e-4 # Sand diffusivity (m2/s) Attention: will be overwritten in setBoudnaryCondtitionValues if declared there! return q0, k, subsidenceRate ## ## ## ## ## ## ## ## ## ## ## ## End of modifiable part ## ## ## ## ## ## ## ## ## ## ## ## startTime = currentTime() transportDensity = 2700 ## Density of newly deposited material. This variable was added with the foresight of the addition of compaction. Since compaction is not in the model, transportDensity can practically be any positive value and serves only as a measure of how well filled the nodes are. The model will crash if the variable is removed or unassigned. nrOfGrainSizes = 2 ## While this number is not hard-coded, the model is not tested for other amounts of grain sizes and the plotting of the data is tuned to two grain sizes. It is therefore not to be modified unless it is ones goal to modify the code to allow for this. ## Initialize: k = list(range(nrOfGrainSizes)) q0 = list(range(nrOfGrainSizes)) totalSedInputThroughTime0 = list(range(nrOfGrainSizes)) totalSedInputThroughTime1 = list(range(nrOfGrainSizes)) inputFractions = list(range(nrOfGrainSizes)) totalHeight = list(range(imax + 1)) newHeight = list(range(imax + 1)) x = list(range(imax + 1)) sedContentInActiveLayer = np.zeros(shape=(2, imax + 1))