def __init__(self, vista): self.app = vista self.cronometro = Cronometro() #self.app.btnIniciar['command'] = self.iniciar self.app.btnIniciar['command'] = self.interruptor self.app.btnReiniciar['command'] = self.reiniciar self.app.root.mainloop()
def __init__(self): self.ventana = tk.Tk() self.ventana.geometry('500x200') self.ventana.resizable(0, 0) self.ventana.title('Cronometro') self.ventana.config(background='#72a922') self.cronometro_label = tk.Label(text="", font=('Tahoma', 44), fg='#ffffff', bg='#1f2f3f', pady=10, padx=10) self.cronometro_label.place(x=20, y=30) self.cronometro = Cronometro() self.activo = True self.frame = Frame(self.ventana) self.cronometro_label.configure(text=self.cronometro.mostrarTiempo()) self.btnIniciar = Button(self.frame, fg='blue', text='Iniciar', command=self.actualizar) self.btnIniciar.grid(row=1, column=1) self.btnParar = Button(self.frame, fg='blue', text='Parar', command=self.parar) self.btnParar.grid(row=1, column=2) btnReiniciar = Button(self.frame, fg='blue', text='Reiniciar', command=self.reiniciar) btnReiniciar.grid(row=1, column=3) self.frame.pack(side=tk.BOTTOM) self.ventana.mainloop()
class Controlador(): def __init__(self, vista): self.app = vista self.cronometro = Cronometro() #self.app.btnIniciar['command'] = self.iniciar self.app.btnIniciar['command'] = self.interruptor self.app.btnReiniciar['command'] = self.reiniciar self.app.root.mainloop() #Metodo donde se reinicio el cronometro def reiniciar(self): self.cronometro.corriendo = False self.app.actualizarTiempo(self.cronometro.reiniciar()) #Metodo para parar el cronometro def interruptor(self): if self.cronometro.corriendo: self.cronometro.corriendo = False self.app.btnIniciar.config(fg='blue', text='Iniciar') else: self.cronometro.corriendo = True self.app.btnIniciar.config(fg='red', text='Parar') self.iniciar() #Metodo para iniciar el cronometro def iniciar(self): self.app.actualizarTiempo(self.cronometro.iniciar()) self.app.root.after(100, self.iniciar)
def __init__(self, host): self.__host = host self.__ping = Ping() self.__novoQuadro = None self.__quadroRecebido = False self.__quadroTempoVital = 4 # Time in seconds self.__quadroTTL = 64 # ttl linux defaul self.__cronometro = Cronometro() #self.__timer = [0,0] useless self.__enviados = 0 self.__recebidos = 0
def __init__(self): super().__init__() self.title = 'Placar para gincanas' self.top = 0 self.left = 0 self.width = 1366 self.height = 768 self.valorPlacarA = 0 self.valorPlacarB = 0 self.initWindow() self.cronoWindow = Cronometro()
class VentanaCronometro(): def __init__(self): self.ventana = tk.Tk() self.ventana.geometry('500x200') self.ventana.resizable(0, 0) self.ventana.title('Cronometro') self.ventana.config(background='#72a922') self.cronometro_label = tk.Label(text="", font=('Tahoma', 44), fg='#ffffff', bg='#1f2f3f', pady=10, padx=10) self.cronometro_label.place(x=20, y=30) self.cronometro = Cronometro() self.activo = True self.frame = Frame(self.ventana) self.cronometro_label.configure(text=self.cronometro.mostrarTiempo()) self.btnIniciar = Button(self.frame, fg='blue', text='Iniciar', command=self.actualizar) self.btnIniciar.grid(row=1, column=1) self.btnParar = Button(self.frame, fg='blue', text='Parar', command=self.parar) self.btnParar.grid(row=1, column=2) btnReiniciar = Button(self.frame, fg='blue', text='Reiniciar', command=self.reiniciar) btnReiniciar.grid(row=1, column=3) self.frame.pack(side=tk.BOTTOM) self.ventana.mainloop() def actualizar(self): global proceso self.cronometro.iniciar() self.cronometro_label.configure(text=self.cronometro.mostrarTiempo()) proceso = self.ventana.after(1, self.actualizar) self.btnIniciar.grid_forget() def parar(self): global proceso self.cronometro.detener() self.ventana.after_cancel(proceso) if self.activo: self.btnParar.configure(text='Reanudar') self.activo = False else: self.btnParar.configure(text='Parar') self.activo = True proceso = self.ventana.after(1, self.actualizar) def reiniciar(self): global proceso self.cronometro.reiniciar() self.ventana.after_cancel(proceso) self.cronometro_label.configure(text=self.cronometro.mostrarTiempo()) self.btnIniciar.grid(row=1, column=1) self.frame.pack(side=tk.BOTTOM)
def insertion_sort(array): for i in range(len(array)): current_value = array[i] current_position = i while (current_position > 0 and array[current_position - 1] > current_value): array[current_position] = array[current_position - 1] current_position = current_position - 1 array[current_position] = current_value return array for algorithm in (insertion_sort, selection_sort): algorithm_name = algorithm.__name__ for input in (10_000, 100_000, 1_000_000): sorted_numbers = list(range(input)) reversed_sorted_numbers = list(reversed(sorted_numbers)) random_numbers = sorted_numbers[:] # copia os ordenados shuffle(random_numbers) # embaralha eles with Cronometro(f"{algorithm_name} com entrada" + f"ordenada de {input} números"): algorithm(sorted_numbers) with Cronometro(f"{algorithm_name} com entrada" + f"inversamente ordenada de {input} números"): algorithm(reversed_sorted_numbers) with Cronometro(f"{algorithm_name} com entrada" + f"aleatória de {input} números"): algorithm(random_numbers) print("*" * 50)
class ventana: window = None Chat = None Cronometro = None Focus = False Evento = None Cliente = None Game = None heigth = 0 width = 0 posX_chat = 0 posY_chat = 0 heigth_C = 0.0 width_C = 0.0 heigth_V = 0.0 width_V = 0.0 # colores blanco = sf.Color(250, 250, 250) negro = sf.Color(0, 0, 0) def __init__(self,cliente): self.heigth = 680 self.width = 1024 self.heigth_C = 680.0 self.width_C = 1024.0 self.heigth_V = float(self.heigth) self.width_V = float(self.width) XMLP = XMLParser() XMLP.setMapaFile("mapFile") XMLP.setPlayersFile("playersFile") self.Game = XMLP.reconstruirGame(cliente.nick) self.Game.mapa.escalaX = 680.0/520.0 self.Game.mapa.escalaY = 680.0/520.0 self.Game.PosicionarPlayer(680,680) self.Cliente = cliente self.Cliente.setWindow(self) self.posX_chat = (780.0/self.width_V)*self.width self.posY_chat = (350.0 /self.heigth_V)*self.heigth self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "BOMBERMAN") self.Evento = sf.Event() self.window.SetFramerateLimit(60) self.CrearChat() self.CrearCronometro() def CrearChat(self): self.Chat = chat(self.posX_chat + 5, self.posY_chat,self.width,self.heigth) self.Chat.SetCliente(self.Cliente) self.Cliente.setChat(self.Chat) def CrearCronometro(self): self.Cronometro = Cronometro(0,0) self.Cronometro.setTime(self.Game.tiempo) self.Cronometro.setRectangule(self.posX_chat + 10,100,44,44) def VerificarFocus(self,x,y): if x >= self.posX_chat and x <= self.posX_chat + (240.0/self.width_V)* self.width_C : if y >= self.posY_chat and y <= self.posY_chat + (330.0/self.heigth_V)*self.heigth_C: return True if not x >= self.posX_chat and x <= self.posX_chat + (240.0/self.width_V)* self.width_C : if not y >= self.posY_chat and y <= self.posY_chat + (330.0/self.heigth_V)*self.heigth_C: return False def SubirText(self,x,y): if x >= self.posX_chat and x <= self.posX_chat + (240.0/self.width_V)* (self.width_C/2): if y >= self.posY_chat+((330.0/self.heigth_V)*self.heigth_C) - 60 and y <= self.posY_chat+(330.0/self.heigth_V)*self.heigth_C-30: return True def BajarText(self,x,y): if x >= self.posX_chat +(240.0/self.width_V)* (self.width_C/2)+10 and x <= self.posX_chat + (240.0/self.width_V)* self.width_C: if y >= self.posY_chat+((330.0/self.heigth_V)*self.heigth_C) - 60 and y <= self.posY_chat+(330.0/self.heigth_V)*self.heigth_C-30: return True def Send(self,x,y): if x >= self.posX_chat +(240.0/self.width_V)*self.width_C - 30 and x <= self.posX_chat + (240.0/self.width_V)* self.width_C: if y >= self.posY_chat+((330.0/self.heigth_V)*self.heigth_C) - 40 and y <= self.posY_chat+(330.0/self.heigth_V)*self.heigth_C: return True def MoverPlayer(self, direction, nick): self.Game.SetDirection(nick, direction) def DetenerPlayer(self, direction, nick, x, y): self.Game.SetDirection(nick, direction) self.Game.PosicionarPlayer2(nick, x, y) def PonerBomba(self, nick): self.Game.PonerBomba(nick, self.Cliente, False) def Run(self): self.Game.mapa.reproducirMusica() self.Cronometro.start() input = self.window.GetInput() self.Game.Update(self.window.GetFrameTime()) quit = False nick = self.Cliente.nick Statics.SetClient(self.Cliente) while not quit: x = input.GetMouseX() y = input.GetMouseY() frameTime = self.window.GetFrameTime() self.Game.Update(frameTime) if self.window.GetEvent(self.Evento): if self.Evento.Type == sf.Event.Resized: self.heigth_V = float(self.Evento.Size.Height) self.width_V = float(self.Evento.Size.Width) self.posX = (780.0/self.width_V)*self.width self.posY = (373.0/self.heigth_V)*self.heigth if self.Evento.Type == sf.Event.KeyPressed: if not self.Focus: evento = self.Evento if evento.Key.Code == sf.Key.Left: self.Game.MoverPlayer(nick, "Izquierda", frameTime) self.Cliente.__send__("MOVEPLAYER:Izquierda") if evento.Key.Code == sf.Key.Right: self.Game.MoverPlayer(nick, "Derecha", frameTime) self.Cliente.__send__("MOVEPLAYER:Derecha") if evento.Key.Code == sf.Key.Up: self.Game.MoverPlayer(nick, "Arriba", frameTime) self.Cliente.__send__("MOVEPLAYER:Arriba") if evento.Key.Code == sf.Key.Down: self.Game.MoverPlayer(nick, "Abajo", frameTime) self.Cliente.__send__("MOVEPLAYER:Abajo") if evento.Key.Code == sf.Key.Space: self.Game.PonerBomba(nick, self.Cliente, True) if self.Evento.Type == sf.Event.KeyReleased: if not self.Focus: evento = self.Evento if evento.Key.Code == sf.Key.Left or evento.Key.Code == sf.Key.Right or evento.Key.Code == sf.Key.Up or evento.Key.Code == sf.Key.Down: pla = self.Game.PlayerPosition(nick) self.Cliente.__send__("STOPPLAYER:"+nick+","+str(int(pla[0]))+","+str(int(pla[1]))) #self.Cliente.__send__("STOPPLAYER:"+nick) self.Game.MoverPlayer(nick,"None",frameTime) if self.Evento.Type == sf.Event.Closed: quit = True if self.Evento.Type == sf.Event.MouseButtonPressed: self.Focus = self.VerificarFocus(x,y) if(self.Focus): if(self.SubirText(x,y)): self.Chat.SubirTexto() if(self.BajarText(x,y)): self.Chat.BajarTexto() if(self.Send(x,y)): self.Chat.Send() if self.Evento.Type == sf.Event.TextEntered: if self.Focus: self.Chat.Update(self.Evento) self.window.Clear(self.negro) self.Chat.Draw(self.window) self.Game.Draw(self.window.GetFrameTime(),self.window) self.Cronometro.Draw(self.window) self.window.Display() self.Cliente.stop() self.window.Close()
class ventana: window = None Chat = None Cronometro = None Focus = False Evento = None Cliente = None Game = None FondoCronometro = None peligro = False parche = None heigth = 0 width = 0 posX_chat = 0 posY_chat = 0 heigth_C = 0.0 width_C = 0.0 heigth_V = 0.0 width_V = 0.0 # colores blanco = sf.Color(250, 250, 250) negro = sf.Color(0, 0, 0) DIRECTORIO = "bgs/" def __init__(self,cliente): self.heigth = 680 self.width = 1024 self.heigth_C = 680.0 self.width_C = 1024.0 self.heigth_V = float(self.heigth) self.width_V = float(self.width) XMLP = XMLParser() XMLP.setMapaFile("mapFile") XMLP.setPlayersFile("playersFile") self.Game = XMLP.reconstruirGame(cliente.nick) self.Game.mapa.escalaX = 680.0/520.0 self.Game.mapa.escalaY = 680.0/520.0 self.Game.PosicionarPlayer(680,680) self.Cliente = cliente self.Cliente.setWindow(self) self.posX_chat = (780.0/self.width_V)*self.width self.posY_chat = (300.0 /self.heigth_V)*self.heigth self.window = sf.RenderWindow(sf.VideoMode(self.width, self.heigth), "BOMBERMAN") self.Evento = sf.Event() self.window.SetFramerateLimit(60) self.CrearChat() self.CrearCronometro() self.FondoCrono("Clock1") self.parche() def CrearChat(self): self.Chat = chat(self.posX_chat + 5, self.posY_chat,self.width,self.heigth) self.Chat.SetCliente(self.Cliente) self.Cliente.setChat(self.Chat) def parche(self): image = sf.Image() image.LoadFromFile(self.DIRECTORIO+"bomberman.png") self.parche = sf.Sprite(image) self.parche.SetCenter(0, 0) self.parche.Resize((240.0/1024.0)*self.width,46) self.parche.SetPosition(self.posX_chat+5,0) def FondoCrono(self,nombre): image = sf.Image() image.LoadFromFile(self.DIRECTORIO+nombre+".png") if self.FondoCronometro == None: self.FondoCronometro = sf.Sprite(image) else: self.FondoCronometro.SetImage(image) self.FondoCronometro.Resize((240.0/1024.0)*self.width,255) self.FondoCronometro.SetCenter(0, 0) self.FondoCronometro.SetPosition(self.posX_chat+5,46) def CrearCronometro(self): self.Cronometro = Cronometro(0,0) self.Cronometro.setTime(self.Game.tiempo) self.Cronometro.setRectangule(880,210,44,44) def VerificarFocus(self,x,y): if x >= self.posX_chat and x <= self.posX_chat + (240.0/self.width_V)* self.width_C : if y >= self.posY_chat and y <= self.posY_chat + (380.0/self.heigth_V)*self.heigth_C: return True if not x >= self.posX_chat and x <= self.posX_chat + (240.0/self.width_V)* self.width_C : if not y >= self.posY_chat and y <= self.posY_chat + (380.0/self.heigth_V)*self.heigth_C: return False def SubirText(self,x,y): if x >= self.posX_chat and x <= self.posX_chat + (240.0/self.width_V)* (self.width_C/2): if y >= self.posY_chat+((380.0/self.heigth_V)*self.heigth_C) - 60 and y <= self.posY_chat+(380.0/self.heigth_V)*self.heigth_C-30: return True def BajarText(self,x,y): if x >= self.posX_chat +(240.0/self.width_V)* (self.width_C/2)+10 and x <= self.posX_chat + (240.0/self.width_V)* self.width_C: if y >= self.posY_chat+((380.0/self.heigth_V)*self.heigth_C) - 60 and y <= self.posY_chat+(380.0/self.heigth_V)*self.heigth_C-30: return True def Send(self,x,y): if x >= self.posX_chat +(240.0/self.width_V)*self.width_C - 30 and x <= self.posX_chat + (240.0/self.width_V)* self.width_C: if y >= self.posY_chat+((380.0/self.heigth_V)*self.heigth_C) - 40 and y <= self.posY_chat+(380.0/self.heigth_V)*self.heigth_C: return True def MoverPlayer(self, direction, nick): self.Game.SetDirection(nick, direction) def Game_Over(self): GameOverLogic.game = self.Game g_over = GameOverLogic(self.Cliente.nick) sumary = g_over.Summary() self.window.Close() if(g_over.winner): g = GameOver("Victory",sumary) g.Update() elif(g_over.empate): g = GameOver("Draw",sumary) g.Update() else: g = GameOver("Defeat",sumary) g.Update() def DetenerPlayer(self, direction, nick, x, y): self.Game.SetDirection(nick, direction) self.Game.PosicionarPlayer2(nick, x, y) def PonerBomba(self, nick): self.Game.PonerBomba(nick, self.Cliente, False) def matarA(self, nick): self.Game.MatarA(nick) def Run(self): self.Game.mapa.reproducirMusica() self.Cronometro.start() input = self.window.GetInput() self.Game.cliente = self.Cliente self.Game.Update(self.window.GetFrameTime()) quit = False nick = self.Cliente.nick notShown = True keyPressed = False while not quit: if self.Cronometro.timeout and notShown: notShown = False self.Game_Over() x = input.GetMouseX() y = input.GetMouseY() frameTime = self.window.GetFrameTime() self.Game.Update(frameTime) if self.window.GetEvent(self.Evento): if self.Evento.Type == sf.Event.Resized: self.heigth_V = float(self.Evento.Size.Height) self.width_V = float(self.Evento.Size.Width) self.posX = (780.0/self.width_V)*self.width self.posY = (373.0/self.heigth_V)*self.heigth if self.Evento.Type == sf.Event.JoyButtonPressed: evento = self.Evento num = evento.JoyButton.Button + 1 if not keyPressed: keyPressed = True if num == 1: self.Game.MoverPlayer(nick, "Izquierda", frameTime) self.Cliente.__send__("MOVEPLAYER:Izquierda") elif num == 2: self.Game.MoverPlayer(nick, "Abajo", frameTime) self.Cliente.__send__("MOVEPLAYER:Abajo") elif num == 3: self.Game.MoverPlayer(nick, "Derecha", frameTime) self.Cliente.__send__("MOVEPLAYER:Derecha") elif num == 4: self.Game.MoverPlayer(nick, "Arriba", frameTime) self.Cliente.__send__("MOVEPLAYER:Arriba") elif num == 5: self.Game.PonerBomba(nick, self.Cliente, True) if self.Evento.Type == sf.Event.KeyPressed: if not self.Focus: if not keyPressed: keyPressed = True evento = self.Evento if evento.Key.Code == sf.Key.Left: self.Game.MoverPlayer(nick, "Izquierda", frameTime) self.Cliente.__send__("MOVEPLAYER:Izquierda") if evento.Key.Code == sf.Key.Right: self.Game.MoverPlayer(nick, "Derecha", frameTime) self.Cliente.__send__("MOVEPLAYER:Derecha") if evento.Key.Code == sf.Key.Up: self.Game.MoverPlayer(nick, "Arriba", frameTime) self.Cliente.__send__("MOVEPLAYER:Arriba") if evento.Key.Code == sf.Key.Down: self.Game.MoverPlayer(nick, "Abajo", frameTime) self.Cliente.__send__("MOVEPLAYER:Abajo") if evento.Key.Code == sf.Key.Space: self.Game.PonerBomba(nick, self.Cliente, True) if self.Evento.Type == sf.Event.KeyReleased: if not self.Focus: evento = self.Evento keyPressed = False if evento.Key.Code == sf.Key.Left or evento.Key.Code == sf.Key.Right or evento.Key.Code == sf.Key.Up or evento.Key.Code == sf.Key.Down: pla = self.Game.PlayerPosition(nick) self.Cliente.__send__("STOPPLAYER:"+nick+","+str(int(pla[0]))+","+str(int(pla[1]))) #self.Cliente.__send__("STOPPLAYER:"+nick) self.Game.MoverPlayer(nick,"None",frameTime) if self.Evento.Type == sf.Event.JoyButtonReleased: evento = self.Evento num = evento.JoyButton.Button + 1 if num in [1,2,3,4]: keyPressed = False pla = self.Game.PlayerPosition(nick) self.Cliente.__send__("STOPPLAYER:"+nick+","+str(int(pla[0]))+","+str(int(pla[1]))) #self.Cliente.__send__("STOPPLAYER:"+nick) self.Game.MoverPlayer(nick,"None",frameTime) if self.Evento.Type == sf.Event.Closed: quit = True if self.Evento.Type == sf.Event.MouseButtonPressed: self.Focus = self.VerificarFocus(x,y) if(self.Focus): if(self.SubirText(x,y)): self.Chat.SubirTexto() if(self.BajarText(x,y)): self.Chat.BajarTexto() if(self.Send(x,y)): self.Chat.Send() if self.Evento.Type == sf.Event.TextEntered: if self.Focus: self.Chat.Update(self.Evento) if(self.peligro == False): if(self.Cronometro.mins == 0): if(self.Cronometro.segs < 15): self.FondoCrono("Clock2") self.peligro = True self.window.Clear(self.negro) self.window.Draw(self.FondoCronometro) self.window.Draw(self.parche) self.Chat.Draw(self.window) self.Game.Draw(self.window.GetFrameTime(),self.window) self.Cronometro.Draw(self.window) self.window.Display() self.Cliente.stop() self.window.Close()
array[current_position] = current_value return array # algorithms execution for algorithm in (insertion_sort, selection_sort): algorithm_name = algorithm.__name__ for input in (10_000, 100_000, 1_000_000): sorted_numbers = list(range(input)) reversed_sorted_numbers = list(reversed(sorted_numbers)) random_numbers = sorted_numbers[:] # copia dos ordenados shuffle(random_numbers) # embaralha eles with Cronometro( f"{algorithm_name} com entrada ordenada de {input} números"): algorithm(sorted_numbers) with Cronometro( f"{algorithm_name} com entrada inversamente ordenada de {input} números" ): algorithm(reversed_sorted_numbers) with Cronometro( f"{algorithm_name} com entrada aleatória de {input} números"): algorithm(random_numbers) print("*" * 50)
class ICMP(): "@param host: ICMP Host" def __init__(self, host): self.__host = host self.__ping = Ping() self.__novoQuadro = None self.__quadroRecebido = False self.__quadroTempoVital = 4 # Time in seconds self.__quadroTTL = 64 # ttl linux defaul self.__cronometro = Cronometro() #self.__timer = [0,0] useless self.__enviados = 0 self.__recebidos = 0 "@param ipDest: Destination Ping IP" def iniciaPing(self,ipDest): self.__ping.setipResposta(ipDest) self.__ping.setipOrigin(self.__host.getIP()) self.__quadroRecebido = False self.__cronometro.zerar() self.__cronometro.iniciar() self.__enviados += 1 # Sending ping frame if (self.__host.enviarQuadro(self.enviaICMP(ipDest)) == False): if (self.__enviados > 0): self.__enviados -= 1 else: self.__enviados = 0 self.__ping.setTempo(self.__cronometro.parar()) self.__ping.setMessage('connect: Network is unreachable') #return False # Timeout without answer elif (self.__quadroRecebido == False): self.__ping.setTempo(self.__cronometro.parar()) # Artificial delay time.sleep(self.__quadroTempoVital) self.__ping.setMessage('Timeout without answer') "@param ipDest: ICMP frame IP origin to be created" def respostaPing(self, ipOrigem, ttl): # Check delivery time delivery_time=self.__cronometro.parar() self.__ping.setTempo(delivery_time) self.__quadroRecebido = True # If the frame was delivered in time and ttl more than 0 if delivery_time < self.__quadroTempoVital and ttl > 0: # Add to ping queue self.__recebidos += 1 self.__ping.setTTL(ttl) self.__ping.setFilaPing() # If the frame was delivered in time and ttl less or igual 0 elif delivery_time < self.__quadroTempoVital and ttl <= 0: # Destination Host Unreachable self.__ping.setMessage('Destination Host Unreachable') # If the frame was delivered with time's up elif delivery_time > self.__quadroTempoVital: # Received with time's up self.__ping.setMessage('Time\'s up!') else: self.__ping.setMessage('Erro check network connection') "@param ipDest: Destination ICMP frame IP to be create" def enviaICMP(self, ipDest): # Make ICMP packet pacote_ICMP = Pacote(self.__host.getIP(),self.__ping.getTamanho()) pacote_ICMP.setIPDestino(ipDest) PacPing = PacotePing("request",0) # PING frame TTL PacPing.setTtl(self.__quadroTTL) pacote_ICMP.setDados(PacPing) # Make ICMP frame Quadro_ICMP = self.__host.constroiQuadro(self.__ping.getTamanho(), "000000000000", pacote_ICMP) Quadro_ICMP.setTipo(2) # Return ICMP frame ready return Quadro_ICMP "@param ipDest: Origin frame IP received from Host" "@param macDest: Origin frame MAC received from Host" def respondeICMP(self, ipDest, macDest, ttl): # Make ICMP answer packet pacote_ICMP = Pacote(self.__host.getIP(),self.__ping.getTamanho()) pacote_ICMP.setIPDestino(ipDest) # Make ping answer packet PacPing = PacotePing("reply",8) PacPing.setTtl(ttl) pacote_ICMP.setDados(PacPing) # Make ICMP frame Quadro_ICMP = self.__host.constroiQuadro(self.__ping.getTamanho(), "000000000000", pacote_ICMP) Quadro_ICMP.setDestino(macDest) Quadro_ICMP.setTipo(2) # Return ICMP frame set return Quadro_ICMP def resetStatistics(self): # Restart queue, list and variables self.__ping.setIcmpSeq() self.__ping.zerarFilaPing() self.__enviados = 0 self.__recebidos = 0 # Rebuild the ping fuction # store all data in pingTabela and use it until new ping request def estatisticas(self): statisticsTable = [] pingTabela = self.__ping.getFilaPing() # Lost, sent and received perdidos = self.__enviados - self.__recebidos try: porcentagem = 100*perdidos/self.__enviados except (ZeroDivisionError): porcentagem = 0 statisticsTable.append("--- "+self.__ping.getipResposta()+" ping statistics ---") statisticsTable.append((str(self.__enviados))+" packets transmitted, "+(str(self.__recebidos))+" received, "+(str(porcentagem))+"% packet loss") maior = pingTabela[0][4] menor = pingTabela[0][4] for ptime in pingTabela: if ptime[4] > maior: maior = ptime[4] if ptime[4] < menor: menor = ptime[4] try: media = (maior + menor)/2 except (ZeroDivisionError): media = 0 #except (TypeError): statisticsTable.append("rtt min/avg/max = "+"%1.*f" % (3, menor)+"/"+"%1.*f" % (3, media)+"/"+"%1.*f" % (3, maior)+" ms") self.resetStatistics() perdidos = 0 media = 0 return statisticsTable def getPingResult (self): pingTabela = self.__ping.getFilaPing()[len(self.__ping.getFilaPing())-1] try: pingTabela[3].isalpha() return (str(pingTabela[0]))+' bytes from '+pingTabela[1]+' ('+pingTabela[1]+'): icmp_seq='+(str(pingTabela[2]))+' '+pingTabela[3] except(AttributeError): return (str(pingTabela[0]))+' bytes from '+pingTabela[1]+' ('+pingTabela[1]+'): icmp_seq='+(str(pingTabela[2]))+' ttl='+(str(pingTabela[3]))+' time='+"%1.*f" % (3, pingTabela[4])+' ms'
from Cronometro import Cronometro with Cronometro("algoritmo"): animais = [ "zebra", "macaco", "elefante", "arara", "javali", "cabra", 'boy', 'bode' ] animais.sort() print(animais)
class ICMP(): "@param host: ICMP Host" def __init__(self, host): self.__host = host self.__ping = Ping() self.__novoQuadro = None self.__quadroRecebido = False self.__quadroTempoVital = 4 # Time in seconds self.__quadroTTL = 64 # ttl linux defaul self.__cronometro = Cronometro() #self.__timer = [0,0] useless self.__enviados = 0 self.__recebidos = 0 "@param ipDest: Destination Ping IP" def iniciaPing(self, ipDest): self.__ping.setipResposta(ipDest) self.__ping.setipOrigin(self.__host.getIP()) self.__quadroRecebido = False self.__cronometro.zerar() self.__cronometro.iniciar() self.__enviados += 1 # Sending ping frame if (self.__host.enviarQuadro(self.enviaICMP(ipDest)) == False): if (self.__enviados > 0): self.__enviados -= 1 else: self.__enviados = 0 self.__ping.setTempo(self.__cronometro.parar()) self.__ping.setMessage('connect: Network is unreachable') #return False # Timeout without answer elif (self.__quadroRecebido == False): self.__ping.setTempo(self.__cronometro.parar()) # Artificial delay time.sleep(self.__quadroTempoVital) self.__ping.setMessage('Timeout without answer') "@param ipDest: ICMP frame IP origin to be created" def respostaPing(self, ipOrigem, ttl): # Check delivery time delivery_time = self.__cronometro.parar() self.__ping.setTempo(delivery_time) self.__quadroRecebido = True # If the frame was delivered in time and ttl more than 0 if delivery_time < self.__quadroTempoVital and ttl > 0: # Add to ping queue self.__recebidos += 1 self.__ping.setTTL(ttl) self.__ping.setFilaPing() # If the frame was delivered in time and ttl less or igual 0 elif delivery_time < self.__quadroTempoVital and ttl <= 0: # Destination Host Unreachable self.__ping.setMessage('Destination Host Unreachable') # If the frame was delivered with time's up elif delivery_time > self.__quadroTempoVital: # Received with time's up self.__ping.setMessage('Time\'s up!') else: self.__ping.setMessage('Erro check network connection') "@param ipDest: Destination ICMP frame IP to be create" def enviaICMP(self, ipDest): # Make ICMP packet pacote_ICMP = Pacote(self.__host.getIP(), self.__ping.getTamanho()) pacote_ICMP.setIPDestino(ipDest) PacPing = PacotePing("request", 0) # PING frame TTL PacPing.setTtl(self.__quadroTTL) pacote_ICMP.setDados(PacPing) # Make ICMP frame Quadro_ICMP = self.__host.constroiQuadro(self.__ping.getTamanho(), "000000000000", pacote_ICMP) Quadro_ICMP.setTipo(2) # Return ICMP frame ready return Quadro_ICMP "@param ipDest: Origin frame IP received from Host" "@param macDest: Origin frame MAC received from Host" def respondeICMP(self, ipDest, macDest, ttl): # Make ICMP answer packet pacote_ICMP = Pacote(self.__host.getIP(), self.__ping.getTamanho()) pacote_ICMP.setIPDestino(ipDest) # Make ping answer packet PacPing = PacotePing("reply", 8) PacPing.setTtl(ttl) pacote_ICMP.setDados(PacPing) # Make ICMP frame Quadro_ICMP = self.__host.constroiQuadro(self.__ping.getTamanho(), "000000000000", pacote_ICMP) Quadro_ICMP.setDestino(macDest) Quadro_ICMP.setTipo(2) # Return ICMP frame set return Quadro_ICMP def resetStatistics(self): # Restart queue, list and variables self.__ping.setIcmpSeq() self.__ping.zerarFilaPing() self.__enviados = 0 self.__recebidos = 0 # Rebuild the ping fuction # store all data in pingTabela and use it until new ping request def estatisticas(self): statisticsTable = [] pingTabela = self.__ping.getFilaPing() # Lost, sent and received perdidos = self.__enviados - self.__recebidos try: porcentagem = 100 * perdidos / self.__enviados except (ZeroDivisionError): porcentagem = 0 statisticsTable.append("--- " + self.__ping.getipResposta() + " ping statistics ---") statisticsTable.append((str(self.__enviados)) + " packets transmitted, " + (str(self.__recebidos)) + " received, " + (str(porcentagem)) + "% packet loss") maior = pingTabela[0][4] menor = pingTabela[0][4] for ptime in pingTabela: if ptime[4] > maior: maior = ptime[4] if ptime[4] < menor: menor = ptime[4] try: media = (maior + menor) / 2 except (ZeroDivisionError): media = 0 #except (TypeError): statisticsTable.append("rtt min/avg/max = " + "%1.*f" % (3, menor) + "/" + "%1.*f" % (3, media) + "/" + "%1.*f" % (3, maior) + " ms") self.resetStatistics() perdidos = 0 media = 0 return statisticsTable def getPingResult(self): pingTabela = self.__ping.getFilaPing()[len(self.__ping.getFilaPing()) - 1] try: pingTabela[3].isalpha() return (str(pingTabela[0])) + ' bytes from ' + pingTabela[ 1] + ' (' + pingTabela[1] + '): icmp_seq=' + (str( pingTabela[2])) + ' ' + pingTabela[3] except (AttributeError): return (str(pingTabela[0])) + ' bytes from ' + pingTabela[ 1] + ' (' + pingTabela[1] + '): icmp_seq=' + (str( pingTabela[2])) + ' ttl=' + (str( pingTabela[3])) + ' time=' + "%1.*f" % ( 3, pingTabela[4]) + ' ms'
def main(): ########################## # CONFIG ########################## seeds = [11,7,13,19,5189,600,1000,1500,1500,1500, 1000] size = [50,100,250,500,1000,1500,2000,2500,3000,3500,7000] epcohs = [] ########################## ########################## ########################## # RUN THE EXPERIMENTS ########################## # Throw the experiments for exp in range(5): print(f">>>> EXPERIMENTO: {exp + 1} <<<<") results = [] for i,seed in enumerate(seeds): np.random.seed(seed) vetor = gera_seq_aleatoria(size[i]) cron = Cronometro() cron.Iniciar() conta_somas(vetor) cron.Parar() results.append(cron.Exibir()) print(f"Tempo gasto com {size[i]} elementos foi {cron} segundos") del vetor del cron epcohs.append(results) print() ########################## ########################## ########################## # PLOT THE RESULTS ########################## # Generate the scatter X and Y scatter_x = size * len(epcohs) scatter_y = np.concatenate(epcohs) # Create a polinomial function of 1 dimension fit_fn = np.poly1d(np.polyfit(scatter_x,scatter_y,1)) plt.title("Resultados") # PLOT: Linear Regression line, = plt.plot(scatter_x, fit_fn(scatter_x), '--', c="#0c29d0") line.set_dashes([10,5,10,5]) # PLOT: Poly Regression plt.plot(size, np.mean(epcohs, axis=0), c="#ff5900", label="Regressão Poly") # PLOT: STM plt.fill_between(size, np.min(epcohs, axis=0), np.max(epcohs, axis=0), alpha=.3, facecolor="#ff5900", label="Desvio") # PLOT: Scatter plt.scatter(scatter_x, scatter_y, c="#0c29d0", label="Tempos") plt.legend(['Tendência', 'Regressão Polinomial', 'Desvio', 'Tempos']) plt.show()
def CrearCronometro(self): self.Cronometro = Cronometro(0,0) self.Cronometro.setTime(self.Game.tiempo) self.Cronometro.setRectangule(880,210,44,44)
class Placar(QMainWindow): def __init__(self): super().__init__() self.title = 'Placar para gincanas' self.top = 0 self.left = 0 self.width = 1366 self.height = 768 self.valorPlacarA = 0 self.valorPlacarB = 0 self.initWindow() self.cronoWindow = Cronometro() def initWindow(self): #espaço em branco espaco = QWidget() espaco.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) #Titulo do programa self.labelTituloJanela = QLabel(' PLACAR GINCANA', self) self.labelTituloJanela.setGeometry(450, 10, 430, 100) self.labelTituloJanela.setStyleSheet( 'QLabel {font: 45px; color: white; font: bold; background-color: #19B5FE; border-radius: 10px}' ) #Seção dos LCDS self.lcdPlacar1 = QLCDNumber(self) self.lcdPlacar2 = QLCDNumber(self) self.lcdPlacar1.setGeometry(50, 120, 300, 250) self.lcdPlacar2.setGeometry(940, 120, 300, 250) self.lcdPlacar1.setStyleSheet( 'QLCDNumber {background-color: #000000; color: red; font: bold}') self.lcdPlacar1.setSegmentStyle(2) # QLCDNumber::SegmentStyle self.lcdPlacar2.setStyleSheet( 'QLCDNumber {background-color: #000000; color: red; font: bold}') self.lcdPlacar2.setSegmentStyle(2) #Label dos nomes dos grupos self.labelGrupA = QLabel('Grupo A', self) self.labelGrupB = QLabel('Grupo B', self) self.labelGrupA.setGeometry(125, 20, 200, 100) self.labelGrupA.setStyleSheet('QLabel {font: 40px; font: bold;}') self.labelGrupB.setStyleSheet('QLabel {font: 40px; font: bold}') self.labelGrupB.setGeometry(1010, 20, 200, 100) #Label do cronometro self.labelCrono = QLabel(' 00:00 ', self) self.labelCrono.setGeometry(130, 490, 170, 100) self.labelCrono.setStyleSheet( 'QLabel {background-color: #336E7B; color: white; font: 50px; border: None; border-radius: 20px}' ) #Label contendo a imagem central do programa self.imagemLabel = QLabel(self) pixmap = QPixmap('imagens/competir.png') self.imagemLabel.setPixmap(pixmap) self.imagemLabel.setGeometry(490, 120, 330, 348) #Botões de pontuar os grupos self.bntGrupA = QPushButton('Pontuar Grupo A', self) self.bntGrupB = QPushButton('Pontuar Grupo B', self) self.bntGrupA.setGeometry(370, 520, 200, 60) self.bntGrupB.setGeometry(690, 520, 200, 60) self.bntGrupA.setStyleSheet( 'QPushButton {font: 23px; font: bold; background-color: #0AEB7E}') self.bntGrupB.setStyleSheet( 'QPushButton {font: 23px; font: bold; background-color: #0AEB7E}') #Spin para definir a pontução (Está entre os dois botões) self.spinBox = QSpinBox(self) self.spinBox.setMaximum(100) self.spinBox.setGeometry(592, 520, 90, 60) self.spinBox.setStyleSheet('QSpinBox {font: 50px}') #Actions Buttons pontuação self.bntGrupA.clicked.connect(lambda: self.setValorLcd(1)) self.bntGrupB.clicked.connect(lambda: self.setValorLcd(2)) #Seção do cronômetro self.labelCronometro = QLabel('Cronometro', self) #self.labelCronometro.setIcon(QtGui.QIcon('crono')) self.labelCronometro.setStyleSheet( 'QLabel {font: 25px; color: black; font: bold; background-color: #ECF0F1;}' ) self.labelCronometro.setGeometry(145, 440, 150, 50) self.bntIniciarCrono = QPushButton('INICIAR', self) self.bntIniciarCrono.setGeometry(130, 590, 185, 50) self.bntIniciarCrono.setStyleSheet( 'QPushButton {font: 20px; color: black; font: bold; background-color: #ECF0F1; border-radius: 10px}' ) self.bntIniciarCrono.setIcon(QtGui.QIcon('imagens/play')) self.bntIniciarCrono.setCheckable(True) self.bntIniciarCrono.clicked.connect(self.threadCrono) #Botão configurar cronometro self.bntConfingCronometro = QPushButton('Configurar', self) self.bntConfingCronometro.setGeometry(180, 650, 100, 50) self.bntConfingCronometro.setStyleSheet( 'QPushButton {font: 18px; color: black; font: bold; background-color: #ECF0F1; border-radius: 10px}' ) self.bntConfingCronometro.clicked.connect(self.configCronometro) #Seção Sortear Número self.labelSorteio = QLabel('Sortear Número', self) self.labelSorteio.setStyleSheet( 'QLabel {font: 25px; color: black; font: bold; background-color: #ECF0F1;}' ) self.labelSorteio.setGeometry(970, 450, 200, 50) self.labelAte = QLabel('ATÉ', self) self.labelAte.setStyleSheet( 'QLabel {font: 25px; color: black; font: bold; background-color: #ECF0F1;}' ) self.labelAte.setGeometry(1040, 520, 50, 50) self.spinBoxNumb1 = QSpinBox(self) self.spinBoxNumb2 = QSpinBox(self) self.spinBoxNumb1.setGeometry(940, 520, 90, 50) self.spinBoxNumb2.setGeometry(1100, 520, 90, 50) self.spinBoxNumb1.setStyleSheet('QSpinBox {font: 50px}') self.spinBoxNumb2.setStyleSheet('QSpinBox {font: 50px}') self.bntSortear = QPushButton('Sortear', self) self.bntSortear.setGeometry(1020, 590, 90, 50) self.bntSortear.setStyleSheet( 'QPushButton {font: 25px; color: black; font: bold; background-color: #F9690E; border-radius: 10px}' ) self.bntSortear.clicked.connect(self.sortearNumero) #Seção da janela principal self.setWindowTitle(self.title) self.setGeometry(self.top, self.left, self.width, self.height) self.setWindowIcon(QtGui.QIcon("user.png")) self.show() def setValorLcd(self, n): if (n == 1): self.lcdPlacar1.display(self.spinBox.value()) self.valorPlacarA = self.spinBox.value() if (n == 2): self.lcdPlacar2.display(self.spinBox.value()) self.valorPlacarB = self.spinBox.value() def placarColor(valorPlacarA, valorPlacarB): if (valorPlacarA > valorPlacarB): self.lcdPlacar1.setStyleSheet( 'QLCDNumber {background-color: #3FC380; color: white; font: bold}' ) if (valorPlacarB > valorPlacarA): self.lcdPlacar2.setStyleSheet( 'QLCDNumber {background-color: #3FC380; color: white; font: bold}' ) if (valorPlacarA < valorPlacarB): self.lcdPlacar1.setStyleSheet( 'QLCDNumber {background-color: #F22613; color: white; font: bold}' ) if (valorPlacarB < valorPlacarA): self.lcdPlacar2.setStyleSheet( 'QLCDNumber {background-color: #F22613; color: white; font: bold}' ) if (valorPlacarA == valorPlacarB): self.lcdPlacar1.setStyleSheet( 'QLCDNumber {background-color: #22A7F0; color: white; font: bold}' ) self.lcdPlacar2.setStyleSheet( 'QLCDNumber {background-color: #22A7F0; color: white; font: bold}' ) placarColor(self.valorPlacarA, self.valorPlacarB) def bntIniciarCronoState(self): i = 0 if (self.bntIniciarCrono.isChecked()): i += 1 return i return i def threadCrono(self): global stop stop = 0 bntCronoStatus = self.bntIniciarCronoState() if (bntCronoStatus == 1): self.t = threading.Thread(target=self.iniciarCrono) self.bntIniciarCrono.setText('PARAR') self.t.start() if (bntCronoStatus == 0): self.bntIniciarCrono.setText('Iniciar novamente') stop = -1 def iniciarCrono(self): self.seg = self.cronoWindow.getValueSpinSeg() self.min = self.cronoWindow.getValueSpinMin() self.count = 0 self.i = self.seg + (self.min * 60) while (self.i != 0): self.min = self.count / 60 self.seg = self.count % 60 + 1 time.sleep(1) self.labelCrono.setText('%02d:%02d' % (self.min, self.seg)) self.count += 1 self.i -= 1 if stop == -1: self.bntIniciarCrono.setText('Iniciar novamente') self.i = 0 def sortearNumero(self): try: a = self.spinBoxNumb1.value() b = self.spinBoxNumb2.value() self.resultado = randint(a, b) self.msgResultado = QMessageBox() self.msgResultado.setStyleSheet( 'QMessageBox, QMessageBox QLabel {font: 35px; color: white; background-color:#34495E}' ) self.msgResultado.information( self.msgResultado, 'INFORMAÇÃO ', 'Número sorteado: \n-->{:>7} <--'.format( self.resultado)) except ValueError: self.warningValue = QMessageBox() self.warningValue.setStyleSheet( 'QMessageBox, QMessageBox QLabel {font: bold; color: white; font: 25px; background-color: #D91E18;}' ) self.warningValue.warning( self.warningValue, 'Aviso', 'Entrada incorreta! \n 1 até 0 é inválido') def configCronometro(self): print('Inciando cronometro') self.cronoWindow = Cronometro() self.cronoWindow.show()
def merge(left, right, merged): left_cursor, right_cursor = 0, 0 while left_cursor < len(left) and right_cursor < len(right): if left[left_cursor] <= right[right_cursor]: merged[left_cursor + right_cursor] = left[left_cursor] left_cursor += 1 else: merged[left_cursor + right_cursor] = right[right_cursor] right_cursor += 1 for left_cursor in range(left_cursor, len(left)): merged[left_cursor + right_cursor] = left[left_cursor] for right_cursor in range(right_cursor, len(right)): merged[left_cursor + right_cursor] = right[right_cursor] return merged for algorithm in (bubble_sort, merge_sort): algorithm_name = algorithm.__name__ numbers = list(range(10_000)) shuffle(numbers) with Cronometro(algorithm_name): algorithm(numbers)
def configCronometro(self): print('Inciando cronometro') self.cronoWindow = Cronometro() self.cronoWindow.show()
def CrearCronometro(self): self.Cronometro = Cronometro(0,0) self.Cronometro.setTime(self.Game.tiempo) self.Cronometro.setRectangule(self.posX_chat + 10,100,44,44)