def updateInfo(self): cnt = 0 fields = [ "", "", "", "", "", "", "", "", "" ] # [numbers,names,timelens,providers,bouquets,recnames,tuner,remaining,snrvalue] for (key, value) in self.reclist.items(): r = int(math.floor(value[7][0] - Time())) cnt += 1 if cnt > 1: for x in range(len(fields)): fields[x] += '\n\n' fields[0] += value[0] and str(value[0]) or '' fields[1] += "%s" % (value[1]) fields[2] += self.getTimeStr(Time() - value[2]) if fields[3] != ("Unknown") or fields[3] != _("N/A"): fields[3] += _("Provider: %s") % (value[3]) else: fields[3] += "%s" % (value[3]) if value[4] != '': fields[4] += _("Bouquet: %s") % (value[4]) else: fields[4] += "%s" % (value[4]) fields[5] += "%s" % (value[5]) if value[6] == 'Stream': fields[6] += _('Stream') else: fields[6] += _("Tuner: %s") % (value[6]) fields[7] += _("+%d min / %s") % (r / 60, value[7][1]) fields[8] += self.getSignalQuality(value[8]) cnt = 0 for x in self.labels: self[x].setText(fields[cnt]) cnt += 1 if self.shown: self.updateTimer.start(1000, True)
def __init__(self, log='console', log_length=5): self.time = Time() self.time_i = self.get_time() self.dtime = [] self.number = 0 self.log = None self.log_list = None self.log_num = 0 self.log_scroll = True self.set_log(log, log_length)
def __init__(self, id): self._id = id self._sound = None self._active = False self._pause = False self._loops = 0 self._volume = 1.0 self._lvolume = 1.0 self._rvolume = 1.0 self._mixer._register_channel(self) self._time = Time() self._nonimplemented_methods()
def Wait(Self, Args): # Seconds in sec. Seconds = Args[0] from time import time as Time # Get timing information. End = Time() + Seconds # Wait for the time to be up. LaunchExited = False while End > Time(): if Self.Button("DOWN"): LaunchExited = True break # Return a boolean for whether or not the the launch was ended by the user. return LaunchExited
def checkWakeup(self): for timer in NavigationInstance.instance.RecordTimer.timer_list: if timer.justplay: continue ret = None if 0 < timer.begin - Time() <= 60*5: if timer.afterEvent == AFTEREVENT.STANDBY: ret = 1 elif timer.afterEvent == AFTEREVENT.DEEPSTANDBY: ret = 2 elif timer.afterEvent == AFTEREVENT.AUTO: ret = 3 else: ret = 4 if ret != None and config.plugins.RecInfobar.after_event.value == "0": if ret == 3: if Standby.inStandby is None: Notifications.AddNotification(Standby.Standby) else: self.checkStandby() elif ret != None and ret != 4 and config.plugins.RecInfobar.after_event.value == "5": if ret == 3: if Standby.inStandby is None: Notifications.AddNotification(Standby.Standby) else: self.checkStandby() elif ret == 1 and config.plugins.RecInfobar.after_event.value == "1": self.checkStandby() elif ret == 2 and (config.plugins.RecInfobar.after_event.value == "2" or config.plugins.RecInfobar.after_event.value == "4"): self.checkStandby() elif ret == 3 and (config.plugins.RecInfobar.after_event.value == "3" or config.plugins.RecInfobar.after_event.value == "4"): if Standby.inStandby is None: Notifications.AddNotification(Standby.Standby)
def loading(master_frame, time): # hide all widgets in the frame: for child in master_frame.winfo_children(): child.grid_remove() loading_lbl = master_frame.winfo_children()[0] # the first child is loading label image. loading_lbl.grid(row=0, column=0, padx=115, pady=(50, 196)) # show the loading. tic = Time() def animate(i): loading_lbl.configure(image=loading_lbl.images[i]) # set the image with next frame. i = 0 if i > 6 else i + 1 # reset and add up i (index). looping over the frames. # remove the loading after 'second's: toc = Time() elapsed_time = toc - tic if elapsed_time < time: loading_lbl.after(100, animate, i) # loop animation. else: for child in master_frame.winfo_children(): child.grid() # todo: what padding? loading_lbl.grid_forget() # hide the loading image. i = random.randint(0, 7) # make the starting frame different each time. animate(i)
def __init__(self,parent): self.parent = parent self.model=GeneratorXY() self.view=View(parent,self.model) self.menuFrame=Frame(parent) self.lissajouTimaFrame=Frame(parent) self.lissajouTopLevel = None self.lissajou = None self.model.attach(self.view) self.time = Time(self.lissajouTimaFrame,self.model,self.view) self.lissajouButton = Button(self.lissajouTimaFrame, text = "XY Curve", command=lambda:self.createLissajou(self.model),pady = 18) self.controlY=Controller(parent,self.view,None,self.model.getSignalY(),self.model) self.controlX=Controller(parent,self.view,None,self.model.getSignalX(),self.model) self.menubar=MenuBar(parent,self.menuFrame,self.model,self.controlX,self.controlY,self.view) self.parent.protocol('WM_DELETE_WINDOW', lambda:self.menubar.exit()) self.save = self.menubar.getSave() self.parent.bind('<Control-o>', lambda x:self.save.load()) self.parent.bind('<Control-s>', lambda x:self.save.saving()) self.parent.bind('<Control-q>', lambda x:self.menubar.exit()) self.parent.bind('<Control-d>', lambda x:self.save.savingAs()) self.parent.bind('<Control-b>', lambda x:self.view.setColor("bg")) self.parent.bind('<Control-g>', lambda x:self.view.setColor("grid")) self.parent.bind('<Control-x>', lambda x:self.view.setColor(self.model.getSignalX())) self.parent.bind('<Control-y>', lambda x:self.view.setColor(self.model.getSignalY())) self.parent.bind('<Control-a>', lambda x:self.menubar.about()) self.parent.bind('<Control-l>', lambda x:self.createLissajou(self.model))
def example(): from time import sleep from select import epoll from select import EPOLLIN from random import randint from time import time as Time sched = Timer(clock_id=CLOCK_MONOTONIC, flags=TFD_NONBLOCK | TFD_CLOEXEC) # if not use every, the timer will notify noce, and block forever. sched.after(3, 0).every(3, 0) sched.update(absolute=False) efd = epoll() efd.register(sched.fileno(), EPOLLIN) start = Time() while True: log(start, "enter poll") evs = efd.poll(-1, 10) log(start, "leave poll") for fileno, ev in evs: assert fileno == sched.fileno() if ev & EPOLLIN: r = sched.readev() log(start, "read {} from {}".format(r, fileno)) wk = randint(0, 3) log(start, "goto work {}".format(wk)) sleep(wk) log(start, "work done") print("---------------------------------------------")
def print_temperature(sensor): tm = Time(True) high = False while True: temp = sensor.read() tm.now() print "[python]: Temperature: %f at %s" % (temp, tm.to_string()) if high: avr.port_and(avr.portb, 0x7F) high = False else: avr.port_or(avr.portb, 0x80) high = True sys.wait(1000)
def timerEntryOnStateChange(self, timer): if config.plugins.RecInfobar.set_position.value and not self.SetPosition: self.SetPosition = False self.zap_ref = None timeout = int(timer.begin - Time()) if timeout > 1: self.SetPosition = True if timer.justplay: if Standby.inStandby is None: try: curservice = self.session.nav.getCurrentlyPlayingServiceOrGroup() except: curservice = self.session.nav.getCurrentlyPlayingServiceReference() if curservice is None or timer.service_ref.ref != curservice: self.zap_ref = timer.service_ref.ref else: self.zap_ref = timer.service_ref.ref self.zap_timer = eTimer() self.zap_timer.callback.append(self.GozapPosition) self.zap_timer.start(19000, True) if config.plugins.RecInfobar.always_zap.value == "1" and Standby.inStandby is None: self.no_decode = False timeout = int(timer.begin - Time()) if timeout > 1: self.no_decode = True if config.plugins.RecInfobar.always_zap.value == "2" and Standby.inStandby is None: self.rec_ref = None timeout = int(timer.begin - Time()) if timeout > 1 and not config.misc.rectimerstate.value: if not timer.justplay: try: curservice = self.session.nav.getCurrentlyPlayingServiceOrGroup() except: curservice = self.session.nav.getCurrentlyPlayingServiceReference() if curservice is None or timer.service_ref.ref != curservice: config.misc.rectimerstate.value = True config.misc.rectimerstate.save() self.rec_ref = timer.service_ref.ref name = timer.service_ref.getServiceName() prov = self.getServiceProvider(timer.service_ref.ref) rec_name = timer.name begintime = ((timer.end - timer.begin) / 60) begintimestr = strftime("%H:%M ", localtime(timer.begin)) begintimeendstr = strftime("%H:%M ", localtime(timer.end)) default = (config.plugins.RecInfobar.default_zap.value == "yes") self.session.openWithCallback(self.callbackYesNo, MessageBox, _("Recording starts!\n") + _("duration: %s ... ") % (begintimestr) + "%s " % (begintimeendstr) + _(" (%d mins)\n") % (begintime) + _("channel: %s prov: %s\n %s\n") % (name, prov, rec_name) + "\n" + _("Switch to a recordable channel?"), MessageBox.TYPE_YESNO, timeout = timeout, default = default)
async def inner_wrapper(ctx, *args): start = Time() await func(ctx, *args) print( f'COMMAND "{func.__name__}": {round(Time() - start, 2)}\n\t{args}' )
def project_curve(self, context, event): self.strokes.clear() self.start_time = Time() size = self.ups.size if self.ups.use_unified_size else self.brush.size for p in self.bez_screen_point: hit, pos, normal, index, obj, matrix = raycast_2d_3d(context, p) if hit: stroke = self.strokes.add() stroke.is_start = False stroke.mouse = p stroke.time = Time() - self.start_time stroke.size = size stroke.pressure = event.pressure stroke.location = pos if self.bez_first_time_project: self.do_stroke(context) else: self.redo_stroke(context)
def __Repeat__(self): # This Method Executes The Given Task Repeatedly. # Explanation : # The Method Uses 'Estimated_Sleep_Time' and 'After_Task_Sleep_Time', # To Calculate The Needed Sleep Time, In Order To Prevent Task Drifting. # Task Drifting : # Is When A Task Takes Longer Then Estimated To Execute, And The # Following Tasks, Executig With An Unwanted Delay. # Estimated_Sleep_Time : # Is The Time The User Rquested To Wait, Between Task Executions. # After_Task_Sleep_Time : # Is The Time Left To Sleep, After The Task Was Executed. # Pre-Calculations : Estimated_Sleep_Time = Time() + self.Interval try: # Trying To Execute The Given Task. while not self.__Stop_Flag__: # Continue Executing, If The Stop Flag Is False. self.Task(*self.Args, **self.KWArgs) # Executing The Task. After_Task_Sleep_Time = max( 0, Estimated_Sleep_Time - Time()) # Preventing Task Drifting. Sleep(After_Task_Sleep_Time) # Calculating The New Sleep Time. Estimated_Sleep_Time += self.Interval # Updating The 'Estimated_Sleep_Time'. except Exception as Error: # Catching The Error. print(f'An Error Has Occurred While Executing The Task :\n{Error}')
def __init__(self, size, buffered): Surface.__init__(self, size) MouseWheelHandler.__init__(self, True) if isinstance(buffered, bool): self._bufferedimage = buffered else: self._bufferedimage = True try: if self.impl.canvasContext: self._isCanvas = True except: self._isCanvas = False self._bufferedimage = False if self._bufferedimage: self.surface = Surface(size) else: self.surface = self self.resize(size[0], size[1]) self.images = {} self.image_list = [] self.function = None self.time_wait = 0 self.time = Time() self.event = pyjsdl.event self.addMouseListener(self) self.addMouseWheelListener(self) self.addKeyboardListener(self) self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP| Event.ONMOUSEMOVE | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP) self.modKey = pyjsdl.event.modKey self.specialKey = pyjsdl.event.specialKey self._rect_list = [] self._rect_list.append(Rect(0,0,0,0)) self._rect_len = 1 self._rect_num = 0 self._rect_temp = Rect(0,0,0,0) _animationFrame = self._initAnimationFrame() if _animationFrame: self.time_hold_min = 0 else: self.time_hold_min = 1 self.time_hold = self.time_hold_min
def __init__(self): """ Initializes the Brief extension and the extensions it calls """ # Regular expression to match extension containing 'brief' and 'me' matchExpression = "^(?=\\b.*brief\\b)(?=\\b.*me\\b)" # Key words that Felix must compile into the language model keys = ["BRIEF", "ME"] # Extension with lower precedence gets executed in a tie precedence = 2 super(Brief, self).__init__(matchExpression, keys, precedence) # Import extensions that will be called in the brief self.extensions = [Time(), Weather(), News()]
def animate(i): loading_lbl.configure(image=loading_lbl.images[i]) # set the image with next frame. i = 0 if i > 6 else i + 1 # reset and add up i (index). looping over the frames. # remove the loading after 'second's: toc = Time() elapsed_time = toc - tic if elapsed_time < time: loading_lbl.after(100, animate, i) # loop animation. else: for child in master_frame.winfo_children(): child.grid() # todo: what padding? loading_lbl.grid_forget() # hide the loading image.
def stats_scraper(btag: str, page: bytes, per_10: bool = False) -> Tuple[str, str, str, str, list]: '''return tuple(embed_description : str, rank_url : str, top_5_graph : str, all_classes_graph : str, top_5_stats : list)''' start = Time() soup_start = Time() soup = Soup(page, 'lxml') soup_finish = round(Time() - soup_start, 2) if soup.h1.text == 'Profile Not Found': return 'not found' if soup.p.text == 'Private Profile': return 'private' career = soup.find('div', attrs = {'id': 'competitive', 'data-js': 'career-category'}) top_5, all_classes, top_5_IDs = all_graphs(career) embed_desc, rank_url = embed_desc_and_img(btag, soup, career) if per_10: per_10 = stats_tables({hero: stats_per_10_mins(career, top_5_IDs[hero]) for hero in top_5_IDs}) print(f'time: {round(Time() - start, 2)}\nsoup time: {soup_finish}') return (embed_desc, rank_url, top_5, all_classes, per_10)
def change_timer_when_polling(): """ 测试已经在 polling 的 timerfd, 又修改了另一个时间,是否会按照最新的生效 测试结果:会按照最新的生效,提前或者延后都会生效 """ from time import sleep from select import epoll from select import EPOLLIN from random import randint from time import time as Time sched = Timer(clock_id=CLOCK_MONOTONIC, flags=TFD_NONBLOCK | TFD_CLOEXEC) sched.after(3, 0).every(3, 0) sched.update(absolute=False) timer_to_change = Timer(clock_id=CLOCK_MONOTONIC, flags=TFD_NONBLOCK | TFD_CLOEXEC) timer_to_change.after(5, 0).every(0, 0) timer_to_change.update(absolute=False) efd = epoll() efd.register(sched.fileno(), EPOLLIN) efd.register(timer_to_change.fileno(), EPOLLIN) start = Time() change_count = 0 while True: log(start, "enter poll") evs = efd.poll(-1, 10) log(start, "leave poll") for fileno, ev in evs: if fileno == sched.fileno(): if ev & EPOLLIN: r = sched.readev() log(start, "read {} from {}".format(r, fileno)) if change_count == 0: change_count += 1 log(start, "change timer_to_change") timer_to_change.after(1, 0).every(0, 0) timer_to_change.update(absolute=False) if fileno == timer_to_change.fileno(): if ev & EPOLLIN: r = timer_to_change.readev() log(start, "timer_to_change read {} from {}".format(r, fileno)) print("---------------------------------------------")
def add_stroke(self, context, event): hit_point = self.get_hit_point(context) if not hit_point: return #print("add stroke") stroke = self.strokes.add() stroke.is_start = False stroke.mouse = self.mouse_pos stroke.time = Time() - self.start_time stroke.size = self.ups.size if self.ups.use_unified_size else self.brush.size stroke.pressure = event.pressure stroke.location = hit_point self.space_points.append(hit_point) self.screen_points.append(self.mouse_pos)
def project_cursor(self, context, event): self.strokes.clear() #size = self.ups.size if self.ups.use_unified_size else self.brush.size #size = size / len(self.cursor_points) size = 5 for i, p in enumerate(self.cursor_points): hit, pos, normal, index, obj, matrix = raycast_2d_3d(context, p) if hit: stroke = self.strokes.add() stroke.is_start = False stroke.mouse = p stroke.time = Time() - self.start_time stroke.size = self.cursor_points_size[i] stroke.pressure = event.pressure stroke.location = pos self.do_Stroke_no_undo_push()
def __init__(self, size, buffered): Surface.__init__(self, size) MouseWheelHandler.__init__(self, True) if isinstance(buffered, bool): self._bufferedimage = buffered else: self._bufferedimage = True try: if self.impl.canvasContext: self._isCanvas = True except: self._isCanvas = False self._bufferedimage = False if self._bufferedimage: self.surface = Surface(size) else: self.surface = self self.resize(size[0], size[1]) self.images = {} self.image_list = [] self.function = None self.time_wait = 0 self.time = Time() self.event = pyjsdl.event self.addMouseListener(self) self.addMouseWheelListener(self) self.addKeyboardListener(self) self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP| Event.ONMOUSEMOVE | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP) self.modKey = pyjsdl.event.modKey self.specialKey = pyjsdl.event.specialKey self._rect_list = [] self._rect_list.append(Rect(0,0,0,0)) self._rect_len = 1 self._rect_num = 0 self._rect_temp = Rect(0,0,0,0) _animationFrame = self._initAnimationFrame() if _animationFrame: self.time_hold_min = 0 else: self.time_hold_min = 1 self.time_hold = self.time_hold_min self.initialized = False
class Channel: """ **pyjsdl.mixer.Channel** * Channel.play * Channel.stop * Channel.pause * Channel.unpause * Channel.set_volume * Channel.get_volume * Channel.get_busy * Channel.get_sound """ _mixer = None def __init__(self, id): self._id = id self._sound = None self._active = False self._pause = False self._loops = 0 self._volume = 1.0 self._lvolume = 1.0 self._rvolume = 1.0 self._mixer._register_channel(self) self._time = Time() self._nonimplemented_methods() def _set_sound(self, sound): if self._sound: self._sound._channel = None self._sound = sound def _play(self): self._volume = 1.0 self._lvolume = 1.0 self._rvolume = 1.0 self._active = True self._sound._sound_object.play() self._time.timeout(self._sound._sound_object.getDuration()*1000, self) def _play_repeat(self, loops): if loops > 0: self._loops = loops else: self._loops = -1 self._play() def play(self, sound, loops=0, maxtime=0, fade_ms=0): """ Play sound on channel. Argument sound to play and loops is number of repeats or -1 for continuous. """ if self._sound: self.stop() self._set_sound(sound) if not loops: self._play() else: self._play_repeat(loops) return None def run(self): if not self._loops: self._active = False else: if self._loops > 0: self._loops -= 1 self._play() def stop(self): """ Stop sound on channel. """ if self._sound: self._sound._sound_object.pause() self._sound._sound_object.setCurrentTime(0) self._pause = False self._loops = 0 self._active = False return None def pause(self): """ Pause sound on channel. """ if self._sound: if not self._pause: self._sound._sound_object.pause() self._pause = True return None def unpause(self): """ Unpause sound on channel. """ if self._sound: if self._pause: self._sound._sound_object.play() self._pause = False return None def set_volume(self, volume): """ Set channel volume of sound playing. """ if volume < 0.0: volume = 0.0 elif volume > 1.0: volume = 1.0 self._volume = volume if self._sound: self._sound._sound_object.setVolume(self._volume * self._sound._sound_object._volume) else: self._volume = 1.0 return None def get_volume(self): """ Get channel volume for current sound. """ return self._volume def get_busy(self): """ Check if channel is processing sound. """ return self._active def get_sound(self): """ Get sound open by channel. """ return self._sound def _nonimplemented_methods(self): """ Non-implemented methods. """ self.fadeout = lambda *arg: None self.queue = lambda *arg: None self.get_queue = lambda *arg: None self.set_endevent = lambda *arg: None self.get_endevent = lambda *arg: 0
from draw import Draw from event import Event from key import Key from mouse import Mouse from transform import Transform from surfarray import Surfarray from color import Color from mixer import Mixer from time import Time import util import mask import font import sprite from locals import * time = Time() display = Display() image = Image() draw = Draw() transform = Transform() surfarray = Surfarray() mixer = Mixer() event = Event() mouse = Mouse() key = Key() init = lambda: None def quit(): canvas = display.get_canvas()
# Creating and manipulating object of class time from time import Time time1 = Time() print("The attributes of time1 are: ") print("time1.hour:", time1.hour) print("time1.minute:", time1.minute) print("time1.second:", time1.second) print("Calling method print_military:", time1.print_military()) print("Calling method print_standard:", time1.print_standard()) print("Charging time1's hour atrribute... ") time1.hour = 25 print("Calling method print_military after alteration:", time1.print_military(), end="")
import numpy as np import ctypes as ct import sfa_interface as sfa import matplotlib.pyplot as plt import os from time import time as Time time_start = Time() nn = 15 #nc=10是勉强的,nc=8是不行的 E1, E2, w, nc = 0.08, 0.046, 0.057, nn #定义基频光电场:S方向 def Efs_field_sin2(t): duration = 2. * nc * np.pi / w result = np.zeros(len(t)) idx = np.nonzero((t >= -duration / 2) & (t <= duration / 2)) result[idx] = E1 * np.sin(w * (t[idx] - duration / 2) / (2. * nc))**2 * np.cos(w * t[idx]) return result #定义倍频光电场矢势,倍频光是圆偏场 def Eds_field_sin2(t, DT): duration = 2. * nc * np.pi / w result = np.zeros(len(t)) idx = np.nonzero((t >= -duration / 2 + DT * 41.34) & (t <= duration / 2 + DT * 41.34)) result[idx] = E2 * np.sin(w * (t[idx] - duration / 2 - DT * 41.34) / (2. * nc))**2 * np.cos(2 * w *
class Canvas(Surface, MouseWheelHandler): def __init__(self, size, buffered): Surface.__init__(self, size) MouseWheelHandler.__init__(self, True) if isinstance(buffered, bool): self._bufferedimage = buffered else: self._bufferedimage = True try: if self.impl.canvasContext: self._isCanvas = True except: self._isCanvas = False self._bufferedimage = False if self._bufferedimage: self.surface = Surface(size) else: self.surface = self self.resize(size[0], size[1]) self.images = {} self.image_list = [] self.function = None self.time_wait = 0 self.time = Time() self.event = pyjsdl.event self.addMouseListener(self) self.addMouseWheelListener(self) self.addKeyboardListener(self) self.sinkEvents(Event.ONMOUSEDOWN | Event.ONMOUSEUP| Event.ONMOUSEMOVE | Event.ONMOUSEOUT | Event.ONMOUSEWHEEL | Event.ONKEYDOWN | Event.ONKEYPRESS | Event.ONKEYUP) self.modKey = pyjsdl.event.modKey self.specialKey = pyjsdl.event.specialKey self._rect_list = [] self._rect_list.append(Rect(0,0,0,0)) self._rect_len = 1 self._rect_num = 0 self._rect_temp = Rect(0,0,0,0) _animationFrame = self._initAnimationFrame() if _animationFrame: self.time_hold_min = 0 else: self.time_hold_min = 1 self.time_hold = self.time_hold_min def _initAnimationFrame(self): JS(""" $wnd['requestAnimationFrame'] = $wnd['requestAnimationFrame'] || $wnd['mozRequestAnimationFrame'] || $wnd['webkitRequestAnimationFrame'] || $wnd['oRequestAnimationFrame']; """) if JS("""$wnd['requestAnimationFrame'] != undefined"""): _animationFrame = True else: JS("""$wnd['requestAnimationFrame'] = function(cb){cb()};""") _animationFrame = False return _animationFrame def onMouseMove(self, sender, x, y): event = DOM.eventGetCurrentEvent() event.pos = (x, y) self.event.mouseMove['x'], self.event.mouseMove['y'] = x, y self.event._updateQueue(event) def onMouseDown(self, sender, x, y): event = DOM.eventGetCurrentEvent() event.pos = (x, y) self.event.mousePress[event.button] = True self.event._updateQueue(event) def onMouseUp(self, sender, x, y): event = DOM.eventGetCurrentEvent() event.pos = (x, y) self.event.mousePress[event.button] = False self.event._updateQueue(event) def onMouseLeave(self, sender): self.event.mousePress[0], self.event.mousePress[1], self.event.mousePress[2] = False, False, False self.event.mouseMove['x'], self.event.mouseMove['y'] = -1, -1 self.event.mouseMoveRel['x'], self.event.mouseMoveRel['y'] = None, None for keycode in self.modKey: if self.event.keyPress[keycode]: self.event.keyPress[keycode] = False def onMouseWheel(self, sender, velocity): event = DOM.eventGetCurrentEvent() if event.type == 'mousewheel': #TODO: update for changes in mousewheel implementation if hasattr(event, 'wheelDeltaX'): self.onMouseWheel = self._onMouseWheel self._onMouseWheel(sender, velocity) else: self.onMouseWheel = self._onMouseWheelY DOM.eventGetMouseWheelVelocityY = eventGetMouseWheelVelocityY self._onMouseWheelY(sender, eventGetMouseWheelVelocityY(event)) else: #DOMMouseScroll self.onMouseWheel = self._onMouseScroll self._onMouseScroll(sender, velocity) def _onMouseWheel(self, sender, velocity): event = DOM.eventGetCurrentEvent() if not event.wheelDeltaX: if velocity < 0: button = 4 events = velocity / -3 else: button = 5 events = velocity / 3 else: if velocity < 0: button = 6 events = velocity / -3 else: button = 7 events = velocity / 3 event.btn = button event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y']) for evt in range(events): self.event._updateQueue(event) def _onMouseWheelY(self, sender, velocity): event = DOM.eventGetCurrentEvent() if velocity < 0: button = 4 events = velocity / -3 else: button = 5 events = velocity / 3 event.btn = button event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y']) for evt in range(events): self.event._updateQueue(event) def _onMouseScroll(self, sender, velocity): event = DOM.eventGetCurrentEvent() if velocity > 1 or velocity < -1: if velocity < 0: button = 4 else: button = 5 else: if velocity < 0: button = 6 else: button = 7 event.btn = button event.pos = (self.event.mouseMove['x'], self.event.mouseMove['y']) self.event._updateQueue(event) def onKeyDown(self, sender, keycode, modifiers): if keycode in self.modKey: event = DOM.eventGetCurrentEvent() self.event.keyPress[keycode] = True self.event._updateQueue(event) DOM.eventPreventDefault(event) elif keycode in self.specialKey: event = DOM.eventGetCurrentEvent() self.event._updateQueue(event) DOM.eventPreventDefault(event) def onKeyPress(self, sender, keycode, modifiers): event = DOM.eventGetCurrentEvent() if not (event.keyCode and event.keyCode in self.specialKey): self.event._updateQueue(event) DOM.eventPreventDefault(event) def onKeyUp(self, sender, keycode, modifiers): event = DOM.eventGetCurrentEvent() if keycode in self.modKey: self.event.keyPress[keycode] = False self.event._updateQueue(event) def resize(self, width, height): Surface.resize(self, width, height) self.surface.resize(width, height) try: self.surface._display.textbox.resize() except (TypeError, AttributeError): #pyjs-O:TypeError/-S:AttributeError pass try: self.surface._display.textarea.resize() except (TypeError, AttributeError): #pyjs-O:TypeError/-S:AttributeError pass def set_function(self, function): self.function = function def load_images(self, images): if images: image_list = [] for image in images: if isinstance(image, str): image_list.append(image) self.image_list.append(image) else: name = image[0] if isinstance(image[1], str): data = image[1] else: data = base64.b64encode(image[1].getvalue()) if not data.startswith('data:'): ext = name.strip().split('.')[-1] data = "data:%s;base64,%s" %(ext, data) #data:[<mediatype>][;base64],<data> image_list.append(data) self.image_list.append(name) loadImages(image_list, self) else: self.start() def set_timeout(self, change): self.time_hold += change if self.time_hold < self.time_hold_min: self.time_hold = self.time_hold_min def start(self): self.run = self._run self.time.timeout(self.time_hold, self) def stop(self): self.time_wait = 0 self.run = lambda: None def onImagesLoaded(self, images): for i, image in enumerate(self.image_list): self.images[image] = images[i] self.start() def set_timeWait(self, time): if time: self.time_wait = time self.run = lambda: None else: if self.time_wait: self.time_wait = 0 self.run = self._run self.run() def _get_rect(self): if self._rect_num < self._rect_len: return self._rect_list[self._rect_num] else: self._rect_list.append(Rect(0,0,0,0)) self._rect_len += 1 return self._rect_list[self._rect_num] def _run(self): self.function() JS("""$wnd['requestAnimationFrame'](@{{paint}});""") def rerun(self): if not self.time_hold: self.run() else: self.time.timeout(self.time_hold, self)
class Oscilloscope(object) : def __init__(self,parent): self.parent = parent self.model=GeneratorXY() self.view=View(parent,self.model) self.menuFrame=Frame(parent) self.lissajouTimaFrame=Frame(parent) self.lissajouTopLevel = None self.lissajou = None self.model.attach(self.view) self.time = Time(self.lissajouTimaFrame,self.model,self.view) self.lissajouButton = Button(self.lissajouTimaFrame, text = "XY Curve", command=lambda:self.createLissajou(self.model),pady = 18) self.controlY=Controller(parent,self.view,None,self.model.getSignalY(),self.model) self.controlX=Controller(parent,self.view,None,self.model.getSignalX(),self.model) self.menubar=MenuBar(parent,self.menuFrame,self.model,self.controlX,self.controlY,self.view) self.parent.protocol('WM_DELETE_WINDOW', lambda:self.menubar.exit()) self.save = self.menubar.getSave() self.parent.bind('<Control-o>', lambda x:self.save.load()) self.parent.bind('<Control-s>', lambda x:self.save.saving()) self.parent.bind('<Control-q>', lambda x:self.menubar.exit()) self.parent.bind('<Control-d>', lambda x:self.save.savingAs()) self.parent.bind('<Control-b>', lambda x:self.view.setColor("bg")) self.parent.bind('<Control-g>', lambda x:self.view.setColor("grid")) self.parent.bind('<Control-x>', lambda x:self.view.setColor(self.model.getSignalX())) self.parent.bind('<Control-y>', lambda x:self.view.setColor(self.model.getSignalY())) self.parent.bind('<Control-a>', lambda x:self.menubar.about()) self.parent.bind('<Control-l>', lambda x:self.createLissajou(self.model)) def test(self) : save = self.menubar.getSave() save.load() def createLissajou(self,model) : if self.lissajou == None: self.lissajouTopLevel = Toplevel(self.parent) self.lissajouTopLevel.protocol('WM_DELETE_WINDOW', lambda:self.deleteLissajou()) self.lissajouTopLevel.wm_attributes("-topmost", True) self.lissajouTopLevel.title("XY Curve") self.lissajou = Lissajou (self.lissajouTopLevel,self.model) self.model.attach(self.lissajou) self.controlX.setLissajou(self.lissajou) self.controlY.setLissajou(self.lissajou) self.lissajou.packing() def deleteLissajou(self): self.lissajou = None self.controlX.setLissajou(self.lissajou) self.controlY.setLissajou(self.lissajou) self.lissajouTopLevel.destroy() def packing(self) : self.menuFrame.pack(fill='x',side='top') self.menubar.packing() self.view.packing() self.lissajouTimaFrame.pack(fill='x') self.lissajouButton.pack(side="right") self.time.packing() self.controlX.packing() self.controlY.packing()
SATELLITE_URL = "http://%s/rpc/api" % SATELLITE_HOST SATELLITE_LOGIN = parser.get("rhof", "rhns_user") SATELLITE_PASSWORD = parser.get("rhof", "rhns_password") # the statusfile to store temporary status information of scheduled actions # Note: To make parallel scheduling possible we add as a suffix to the filename # defined below the releaseid or if not set the date-time of the action (YYMMDDHHMM) global statusfile statusfile = "/var/tmp/schedule_status" # define some variables systemlist = [] success_ops = 0 failed_ops = 0 failed_systems = [] date8601 = DateTime(Time()) needed = 'provisioning_entitled' ############################################################################################### # # SCRIPT OPTIONS # ############################################################################################### scriptparser.add_option( "-u", "--user", dest="scriptuser", default="root", help="Username to run the remote script. Default: root") scriptparser.add_option( "-g",
class Timer(object): """ Simple profiling timer. Output log can be directed to 'console' or to 'textarea'. If output is to textarea, may specify log length. """ def __init__(self, log='console', log_length=5): self.time = Time() self.time_i = self.get_time() self.dtime = [] self.number = 0 self.log = None self.log_list = None self.log_num = 0 self.log_scroll = True self.set_log(log, log_length) def get_time(self): """ Get current time. """ return self.time.time() def set_time(self): """ Set current time. """ self.time_i = self.get_time() def lap_time(self, time_i=None, time_f=None, number=100, print_result=True): """ Time lapsed since previous set_time. Optional arguments time_i and time_f, number of calls to average, and print_results to output result. """ if time_i is None: time_i = self.time_i if time_f is None: time_f = self.get_time() self.dtime.append(time_f-time_i) self.number += 1 if self.number >= number: t_ave = ( sum(self.dtime)/number ) self.dtime = [] self.number = 0 if print_result: if self.log_type == 'console': self.log_num += 1 entry = "Time %d: %s" % (self.log_num, t_ave) print(entry) else: self.log_num += 1 entry = "Time %d: %s" % (self.log_num, t_ave) self.print_log(entry) return t_ave def set_log(self, log, log_length=5): """ Set log output. Argument log can be 'console' or 'textarea'. """ if log in ('console','textarea'): self.log_type = log if log == 'textarea': if not self.log: size = env.canvas.surface.width-5, 102 self.log = env.canvas.surface._display.Textarea(size) self.log.setReadonly(True) self.log.addMouseListener(self) self.onMouseUp = lambda sender,x,y: None self.onMouseMove = lambda sender,x,y: None self.onMouseEnter = lambda sender: None self.log_list = ['' for i in range(log_length)] self.log.toggle(True) else: if self.log: self.log.toggle(False) self.log_list = [] def onMouseDown(self, sender, x, y): self.log_scroll = False def onMouseLeave(self, sender): self.log_scroll = True def print_log(self, text): """ Print text to output. """ if self.log_type == 'console': print(text) else: self.log_list.pop(0) self.log_list.append(text+'\n') text = ''.join(self.log_list) self.log.setText(text) if self.log_scroll: self.log.setCursorPos(len(text))
#!/usr/bin/env python # This imports just the class definition Time from the module time.py. # See also time-driver1.py from time import Time start = Time(9, 45, 00) start.print_time() end = start.increment(1337) end.print_time() print 'Is end after start?', print end.is_after(start) print 'Using __str__' print start, end start = Time(9, 45) duration = Time(1, 35) print start + duration print start + 1337 print 1337 + start print 'Example of polymorphism' t1 = Time(7, 43) t2 = Time(7, 41) t3 = Time(7, 37) total = sum([t1, t2, t3]) print total
def Run(self): """Run the model one time Use the Chronos instance and list of StreamNodes to cycle through each timestep and spacestep, calling the appropriate StreamNode functions to calculate heat and hydraulics.""" msg = "Starting Simulation: {0}".format(IniParams["name"]) logger.info(msg) print_console(msg) # Current time of the Chronos clock (i.e. this timestep) time = Chronos.TheTime # Stop time for Chronos stop = Chronos.stop # Start time for Chronos, model start, not flush/spin start. start = Chronos.start # flush in seconds flush = start - (IniParams["flushdays"] * 86400) # Number of timesteps is based on the division of the timesteps # into the hour. In other words 1 day with a 1 minute dt is # 1440 timesteps, while a 3 minute dt is only 480 timesteps. # Thus, we define the timesteps by dividing dt (now in seconds) # by 3600 timesteps = (stop - flush) / IniParams["dt"] # Counter iterator for counting current timesteps passed cnt = count() # Volume of water flowing out of mouth (for simple mass balance) out = 0 # Current computer time- for estimating total model runtime time1 = Time() # Localize run_type for a bit more speed ################################################################ # So, it's simple and stupid. We basically just cycle through the # time until we get to the model stop time, and each cycle, we # call a method that cycles through the StreamNodes, and # calculates them in order. A smarter way would be to thread # this so we can start calculating the second timestep (using # another CPU or core) while the first one is still unfinished. while time <= stop: year, month, day, hour, minute, second, JD, offset, JDC = Chronos.TimeTuple( ) # zero hour+minute+second means first timestep of new day if not (hour + minute + second): # zero out the daily flux sum at this point. for nd in self.reachlist: nd.F_DailySum = [0] * 5 nd.Solar_Blocked = {} # Number of radial sample directions for i in range(IniParams["trans_count"]): # A spot for each land cover sample nd.Solar_Blocked[i] = [ 0 ] * IniParams["transsample_count"] nd.Solar_Blocked["diffuse"] = 0 # Back to every timestep level of the loop. Here we wrap the call to # run_all() in a try block to catch the exceptions thrown. try: # Note that all of the run methods have to have # the same signature #if time == 1056951360.0: # print_console(msg="error timestep") self.run_all(time, hour, minute, second, JD, JDC) # Shit, there's a problem except: msg = "Error at model km {0} at {1}, model time {2} {3}".format( nd.km, Chronos.PrettyTime(), Chronos.TheTime, traceback.format_exc()) logging.error(msg) print_console(msg) # Then just die raise SystemExit # If minute and second are both zero, we are at the top of # the hour. if (minute == 0 and second == 0): ts = cnt.next() # Number of actual timesteps per tick # Number of timesteps in one hour hr = 60 / (IniParams["dt"] / 60) # This writes a line to the status bar. msg = "Timesteps:" logger.info('{0} {1} {2}'.format(msg, (ts) * hr, timesteps)) print_console(msg, True, (ts) * hr, timesteps) # Call the Output class to update the textfiles. We call # this every hour and store the data, then we write to # file every day. Limiting disk access saves us # considerable time. self.Output(time, hour) # ---- # Uncomment to output every timestep and # comment section above #ts = cnt.next() #msg = "Timesteps:" #logger.info('{0} {1} {2}'.format(msg, ts, timesteps)) #print_console("Timesteps:", True, ts, timesteps) #self.Output(time, hour, minute, second) # ---- # We've made it through the entire stream without an error, # so we update our mass balance # by adding the discharge of the mouth... out += self.reachlist[-1].Q # and tell Chronos that we're moving time forward. time = Chronos(tick=True) # So, here we are at the end of a model run. First we # calculate how long all of this took total_time = (Time() - time1) / 60 # Calculate the mass balance inflow balances = [x.Q_mass for x in self.reachlist] total_inflow = sum(balances) # Calculate how long the model took to run each timestep for # each spacestep. This is how long (on average) it took to # calculate a single StreamNode's information one time. # Ideally, for performance and impatience reasons, we want this # to be somewhere around or less than 1 microsecond. microseconds = (total_time / timesteps / len(self.reachlist)) * 1e6 message = "Simulation Complete" message += "\n\nFinished in {0:0.1f} minutes ".format(total_time) message += "(spent {0:0.3f} microseconds ".format(microseconds) message += "in each stream node).\n" message += "Water Balance: {0:0.3f}/{1:0.3f}\n".format( total_inflow, out) message += "Simulation: {0}\n".format(IniParams["name"]) message += "Outputs: {0}\n\n".format(IniParams["outputdir"]) logger.info(message) print_console(message)
def modal(self, context, event): if event.type == 'ESC': if event.value == 'PRESS': self.finish() return {'FINISHED'} elif self.area != context.area: self.finish() return {'FINISHED'} if self.change_tool(event.ascii): return {'RUNNING_MODAL'} # TODO: Filter if it's not a brush self.brush = context.tool_settings.sculpt.brush self.ups = context.tool_settings.unified_paint_settings self.mouse_pos = Vector((event.mouse_region_x, event.mouse_region_y)) self.area.tag_redraw() if self.stroke_finished: if self.op_mode == 'BRISTLE': # Está usando el cursor. if self.cursor_drawing or (event.shift and event.type in {'LEFTMOUSE', 'PEN'}): if event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'RELEASE': self.cursor_drawing = False return {'RUNNING_MODAL'} # Moving cursor points. (using threshold) d_diff_mouse = distance_between(self.prev_cursor_pos, self.mouse_pos) if d_diff_mouse > 4: dir_mouse = direction_normalized( self.cursor_origin, self.mouse_pos) dir_angle = angle_from_vector(dir_mouse) prev_dir_angle = angle_from_vector(self.prev_dir_mouse) diff_angle = radians(dir_angle - prev_dir_angle) # Transpose and rotate points. offset = self.mouse_pos - self.prev_cursor_pos d_drag_mouse = distance_between( self.cursor_origin, self.mouse_pos) dir_drag_mouse = direction_normalized( self.cursor_origin, self.mouse_pos) for i in range(0, len(self.cursor_points)): self.cursor_points[ i] = rotate_point_around_another( self.cursor_origin, diff_angle, self.cursor_points[i]) + offset #self.update_bezier_drag_point() self.cursor_origin = self.mouse_pos # Project points. self.prev_cursor_pos = self.mouse_pos self.prev_dir_mouse = dir_mouse self.project_cursor(context, event) # Se hace click. elif event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'PRESS': # Se hace sobre el origen del cursor ? if distance_between(self.cursor_origin, self.mouse_pos) < 14: self.cursor_drawing = True self.start_time = Time() else: self.cursor_points.append(self.mouse_pos) self.cursor_points_size.append(1 + random.randrange(0, 9)) return {'RUNNING_MODAL'} elif event.ctrl and event.value == 'PRESS': self.cursor_origin = self.mouse_pos else: self.cursor_active = distance_between( self.cursor_origin, self.mouse_pos) < 14 return {'PASS_THROUGH'} elif self.op_mode == 'CURVE': if self.dragging_bezier_paint: if event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'RELEASE': self.dragging_bezier_paint = False return {'RUNNING_MODAL'} # MOVE CURVE BRUSH. d_diff_mouse = distance_between(self.prev_drag_pos, self.mouse_pos) if d_diff_mouse > 20: dir_mouse = direction_normalized( self.curve_drag_point, self.mouse_pos) # 1ST METHOD: #v_AC = direction_normalized(self.bezier_points[0], self.bezier_points[2]) #normal = perpendicular_vector2(v_AC) #v1 = mathutils_vector_to_numpy_array(normal) #v2 = mathutils_vector_to_numpy_array(dir_mouse) #diff_angle = angle_between_vectors(v1, v2) #print("1:", diff_angle) # 2ND METHOD: dir_angle = angle_from_vector(dir_mouse) prev_dir_angle = angle_from_vector(self.prev_dir_mouse) diff_angle = radians(dir_angle - prev_dir_angle) #print("2:", diff_angle) # TRANSPOSE AND ROTATE POINTS. offset = self.mouse_pos - self.prev_drag_pos d_drag_mouse = distance_between( self.curve_drag_point, self.mouse_pos) dir_drag_mouse = direction_normalized( self.curve_drag_point, self.mouse_pos) for i in range(0, len(self.bezier_points)): #dist = distance_between(p, self.mouse_pos) #dir = direction_normalized(p, self.mouse_pos) #p = rotate_point_around_another(self.curve_drag_point, angle, p) + dir * dist + dir_drag_mouse * d_drag_mouse self.bezier_points[i] = rotate_point_around_another( self.curve_drag_point, diff_angle, self.bezier_points[i] ) + offset #dir_drag_mouse * d_drag_mouse #+ dir_mouse * d_diff_mouse self.update_bezier_drag_point() # UPDATE and PROJECT. self.update_bezier_curve_points(context, event) self.prev_drag_pos = self.mouse_pos self.prev_dir_mouse = dir_mouse self.project_curve(context, event) elif self.dragging_bezier: if event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'RELEASE': self.dragging_bezier = False return {'RUNNING_MODAL'} else: self.bezier_points[ self. active_point_index] = self.active_point = self.mouse_pos self.update_bezier_curve_points(context, event) self.update_bezier_drag_point() #self.bez_length = self.quadratic_bezier_length(self.bezier_points) elif self.active_point or self.curve_drag_point_active: if event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'PRESS': if self.curve_drag_point_active: print("Active Drag Point") self.dragging_bezier_paint = True else: self.dragging_bezier = True self.prev_drag_pos = self.mouse_pos return {'RUNNING_MODAL'} else: self.update_bezier_drag_point() elif self.using_tool: if event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'RELEASE': self.using_tool = False return {'RUNNING_MODAL'} self.apply_tool(context, event) elif self.dragging_ui: if event.type in {'LEFTMOUSE', 'PEN' } and event.value == 'RELEASE': self.dragging_ui = False return {'RUNNING_MODAL'} self.move_ui() elif event.type in {'LEFTMOUSE', 'PEN'} and event.value == 'PRESS': # Change tool by clicking. if isinstance(self.hover_tool, StrokeTool): if self.hover_tool == StrokeTool.NONE: #print("MOVE UI") self.dragging_ui = True self.move_ui_offset[0] = self.mouse_pos[0] - self.x self.move_ui_offset[1] = self.mouse_pos[1] - self.y else: self.active_tool = self.hover_tool return {'RUNNING_MODAL'} # Check if there's a valid active point. {MOVE, ROPE...} Modes that need a point. elif self.active_tool in {StrokeTool.Move, StrokeTool.Rope}: if self.active_point_index == -1 or not self.active_point: return {'PASS_THROUGH'} if self.active_tool == StrokeTool.Rope: self.num_points = len(self.screen_points) # Modes that are only one-click action. (no drag and so) elif self.active_tool == StrokeTool.Extrude: self.extrude(context, event) return {'RUNNING_MODAL'} self.prev_drag_pos = self.mouse_pos self.using_tool = True return {'RUNNING_MODAL'} elif event.type == 'I' and event.value == 'PRESS': self.inverted = not self.inverted self.redo_stroke(context) return {'RUNNING_MODAL'} return {'PASS_THROUGH'} # START RELEASE elif self.start: if event.type in { 'PEN', 'LEFTMOUSE' } and event.value == 'RELEASE': # event.type not in {'PEN', 'RIGHTMOUSE', 'MOUSEMOVE'} or # RELEASE CURVE DRAW if self.op_mode == 'CURVE': dist = distance_between(self.bezier_points[0], self.mouse_pos) dir = direction_normalized(self.bezier_points[0], self.mouse_pos) mid_point = self.bezier_points[0] + dir * (dist / 2.0) self.bezier_points.append(mid_point) self.bezier_points.append(self.mouse_pos) self.update_bezier_curve_points(context, event) #self.bez_length = self.quadratic_bezier_length(self.bezier_points) else: self.do_stroke(context) self.start_trick(context) self.stroke_finished = True return {'RUNNING_MODAL'} elif self.op_mode == 'DEFAULT' and distance_between( self.mouse_pos, self.point_pos) > 20: self.point_pos = self.mouse_pos self.add_stroke(context, event) return {'PASS_THROUGH'} elif self.op_mode == 'BRISTLE': self.cursor_origin = self.mouse_pos # update origin point return {'PASS_THROUGH'} # START PRESS elif event.type in {'PEN', 'LEFTMOUSE' } and event.value == 'PRESS': # and event.alt: hit_point = self.get_hit_point(context) if not hit_point: return {'PASS_THROUGH'} #print("start stroke") self.start = True self.start_time = Time() self.point_pos = self.mouse_pos if self.op_mode == 'DEFAULT': stroke = self.strokes.add() stroke.is_start = True stroke.mouse = self.mouse_pos stroke.time = 0 stroke.size = self.brush.size stroke.pressure = event.pressure stroke.location = hit_point self.space_points.append(hit_point) self.screen_points.append(self.mouse_pos) elif self.op_mode == 'BRISTLE': self.cursor_origin = self.prev_cursor_pos = self.mouse_pos else: self.bezier_points.append(self.mouse_pos) return {'RUNNING_MODAL'} return {'PASS_THROUGH'}
def log_validator(args): today = dt.today().date() if args.testnet: service = validator_testnet_service genesis = genesis_testnet else: service = validator_service genesis = genesis_mainnet tg = dt.fromtimestamp(genesis) j = journal.Reader() j.log_level(journal.LOG_INFO) j.add_match(_SYSTEMD_UNIT=service) if args.subcommand == "schedule": j.add_match(MESSAGE="Proposal schedule") j.add_match(MESSAGE="Attestation schedule") j.seek_tail() i = 0 print("Duty Pubkey Slot Epoch") while i < args.rows: msg = j.get_previous() if not msg: i += 1 continue slot = int(msg['SLOT']) if args.epoch and slot > args.epoch * 32: continue if msg['MESSAGE'] == "Attestation schedule": duty = "Attestation" pubkeys = [k for k in msg['PUBKEYS'][1:-1].split()] else: duty = "Proposal" pubkeys = [ msg['PUBKEY'], ] for key in pubkeys: print("{:<20} {} {:<8} {:>6}".format(duty, key, slot, slot // 32)) i += 1 if args.subcommand == "proposals": j.add_match(MESSAGE="Submitted new block") j.seek_tail() print( " Date Slot Pubkey Root Atts Deps Graffiti" ) j.seek_tail() i = 0 while i < args.rows: msg = j.get_previous() if not msg: i += 1 continue slot = int(msg['SLOT']) if args.epoch and slot > args.epoch * 32: continue root = msg['BLOCKROOT'] pubkey = msg['PUBKEY'] atts = msg['NUMATTESTATIONS'] deps = msg['NUMDEPOSITS'] #graffiti_temp = base64.b64decode(msg["GRAFFITI"]) graffiti = msg['GRAFFITI'] # graffiti = graffiti_temp.decode('utf8').replace("\00", " ") datetime = msg['_SOURCE_REALTIME_TIMESTAMP'] if datetime.date() >= today: time = datetime.strftime("%H:%M:%S") else: time = datetime.strftime("%D") print( "{} {:>7} {} {} {:>2} {:>2} {}".format( time, slot, pubkey, root, atts, deps, graffiti)) i += 1 if args.subcommand == "attestations": j.add_match(MESSAGE="Submitted new attestations") j.seek_tail() print( " time source target slot index agr committee sourceroot targetroot beaconroot{ts}" .format(ts=" delay" if args.timestamp else "")) i = 0 while i < args.rows: msg = j.get_previous() if not msg: i += 1 continue slot = int(msg['SLOT']) if args.epoch and slot > args.epoch * 32: continue aggidx = [int(m) for m in msg["AGGREGATORINDICES"][1:-1].split()] attidx = [int(m) for m in msg["ATTESTERINDICES"][1:-1].split()] source = int(msg['SOURCEEPOCH']) target = int(msg['TARGETEPOCH']) commitee = int(msg['COMMITTEEINDEX']) targetroot = msg['TARGETROOT'] sourceroot = msg['SOURCEROOT'] beaconroot = msg['BEACONBLOCKROOT'] datetime = msg['_SOURCE_REALTIME_TIMESTAMP'] if args.timestamp: delta = datetime - tg delay = delta.total_seconds() - 12 * slot if datetime.date() >= today: time = datetime.strftime("%H:%M:%S") else: time = datetime.strftime("%D") for idx in attidx: print( "{} {:>8} {:>8} {:>9} {:>8} {agr} {:>8} {} {} {}{ts}" .format(time, source, target, slot, idx, commitee, sourceroot, targetroot, beaconroot, agr='✓' if idx in aggidx else ' ', ts=" {:.4f}".format(delay) if args.timestamp else "")) i += 1 if args.subcommand == "performance": j.add_match(MESSAGE="Previous epoch voting summary") j.seek_tail() print( " time pubkey epoch source target head inc. dist. Balance Chg." ) i = 0 last_epoch = args.epoch while i < args.rows: msg = j.get_previous() if not msg: i += 1 continue epoch = int(msg['EPOCH']) if args.epoch and epoch > args.epoch: continue if last_epoch and epoch < last_epoch - 1: for lostepoch in range(last_epoch - epoch - 1): i += 1 print( "{} {} {:>8} {:^5} {:^5} {:^5} {:>5}".format( time, pubkey, last_epoch - lostepoch - 1, "⨯", "⨯", "⨯", "miss")) inclusion = int(msg['INCLUSIONDISTANCE']) if msg['CORRECTLYVOTEDSOURCE'] == "true": source = "✓" else: source = "⨯" if msg['CORRECTLYVOTEDTARGET'] == "true": target = "✓" else: target = "⨯" if msg['CORRECTLYVOTEDHEAD'] == "true": head = "✓" else: head = "⨯" pubkey = msg['PUBKEY'] oldbal = float(msg['OLDBALANCE']) newbal = float(msg['NEWBALANCE']) balchg = int((newbal - oldbal) * 10**9) datetime = msg['_SOURCE_REALTIME_TIMESTAMP'] if datetime.date() >= today: time = datetime.strftime("%H:%M:%S") else: time = datetime.strftime("%D") if inclusion < 33: print( "{} {} {:>8} {:^5} {:^5} {:^5} {:>5} {:>9}" .format(time, pubkey, epoch, source, target, head, inclusion, balchg)) else: print( "{} {} {:>8} {:^5} {:^5} {:^5} {:>5} {:>9}" .format(time, pubkey, epoch, source, target, head, "miss", balchg)) last_epoch = epoch i += 1 if args.subcommand == "status": print("Validator summary since last launch:\n") resp = read_status(service) for key in resp: print('{:<10}: {}'.format(key, resp[key])) j.add_match(MESSAGE="Vote summary since launch") j.seek_tail() msg = j.get_previous() if not msg: return source = msg['CORRECTLYVOTEDSOURCEPCT'] target = msg['CORRECTLYVOTEDTARGETPCT'] head = msg['CORRECTLYVOTEDHEADPCT'] inclusion = msg['AVERAGEINCLUSIONDISTANCE'] attinclusion = msg['ATTESTATIONSINCLUSIONPCT'] epochs = msg['NUMBEROFEPOCHS'] print("\n") print("Average Inclusion Distance : {}".format(inclusion)) print("Correctly Voted Source : {}".format(source)) print("Correctly Voted Target : {}".format(target)) print("Correctly Voted Head : {}".format(head)) print("Attestations Inclusion : {}".format(attinclusion)) print("\n") print("Number of Epochs running : {}".format(epochs)) j.flush_matches() j.add_match(_SYSTEMD_UNIT=service) j.add_match(MESSAGE="Previous epoch voting summary") bals_now = balances(j) td = Time() - 3600 bals_hour = balances(j, td) td = td - 82800 bals_day = balances(j, td) td = td - 86400 * 6 bals_week = balances(j, td) hourly = {pubkey: (bal - bals_hour.get(pubkey,32)) * 8760 / bals_hour.get(pubkey,32)\ for pubkey, bal in bals_now.items() } daily = {pubkey: (bal - bals_day.get(pubkey,32)) * 365 / bals_day.get(pubkey,32)\ for pubkey, bal in bals_now.items() } weekly = {pubkey: (bal - bals_week.get(pubkey,32)) * 365 / 7 / bals_week.get(pubkey,32)\ for pubkey, bal in bals_now.items() } time_fraction = 31536000 / (Time() - genesis) print( "\n Public Key Balance Hourly Daily Weekly" ) for pubkey, bal in bals_now.items(): print("{:<20}{:>.9f} {:6.2%} {:6.2%} {:6.2%}".format( pubkey, bal, hourly[pubkey], daily[pubkey], weekly[pubkey])) total = sum([val for (key, val) in bals_now.items()]) total_hour = sum([ int((bal - bals_hour.get(pubkey, 32)) * 1000000000) for pubkey, bal in bals_now.items() ]) total_day = sum([ bal - bals_day.get(pubkey, 32) for pubkey, bal in bals_now.items() ]) total_week = sum([ bal - bals_week.get(pubkey, 32) for pubkey, bal in bals_now.items() ]) print("{:<20}{:>.9f} {:>} {:>.4f} {:>.4f}".format( "Totals", total, total_hour, total_day, total_week))
def gotRecordEvent(self, service, event): if event in (iRecordableService.evEnd, iRecordableService.evStart): key = service.__deref__() if event == iRecordableService.evStart: for timer in self.session.nav.RecordTimer.timer_list: if timer.record_service and timer.record_service.__deref__( ) == key: try: curservice = self.session.nav.getCurrentlyPlayingServiceOrGroup( ) except: curservice = self.session.nav.getCurrentlyPlayingServiceReference( ) if config.plugins.RecInfobar.set_position.value and self.SetPosition and Standby.inStandby is None and ( curservice is None or timer.service_ref.ref == curservice): if timer.service_ref.ref != eServiceReference( config.tv.lastservice.value): self.setZapPosition(timer.service_ref.ref, SetCurTimer=True) self.SetPosition = False name = timer.service_ref.getServiceName() begin = timer.begin if (Time() - begin) >= 60: begin = Time() end = timer.end if end <= begin: end += 3600 * 24 beginstr = strftime("%H:%M", localtime(begin)) endstr = strftime("%H:%M", localtime(end)) duration = ((end - begin) / 60) remaining = (end, _("%s...%s (%d mins)") % (beginstr, endstr, duration)) num, bqname = self.getServiceNumber( timer.service_ref.ref) prov = self.getServiceProvider(timer.service_ref.ref) recname = timer.name tunnum, tunname = self.getTunerName( timer.record_service) if "%3a//" in timer.service_ref.ref.toString().lower(): tunname = 'Stream' self.reclist[service] = [ num, name, begin, prov, bqname, recname, tunname, remaining, timer.record_service ] if config.plugins.RecInfobar.always_zap.value == "1" and self.no_decode == True and Standby.inStandby is None: self.no_decode = False try: curservice = self.session.nav.getCurrentlyPlayingServiceOrGroup( ) except: curservice = self.session.nav.getCurrentlyPlayingServiceReference( ) if curservice is None or timer.service_ref.ref != curservice: if config.plugins.RecInfobar.set_position.value and self.SetPosition: self.setZapPosition(timer.service_ref.ref) self.SetPosition = False self.session.nav.playService( timer.service_ref.ref) if config.plugins.RecInfobar.always_message.value is True: if config.usage.show_message_when_recording_starts.value: self.session.open( MessageBox, _("Switched to the recording service !\n" ) + _("channel: %s prov: %s\n") % (name, prov), MessageBox.TYPE_INFO, timeout=2) else: self.session.open( MessageBox, _("Switched to the recording service !\n" ) + _("channel: %s prov: %s\n %s\n") % (name, prov, recname), MessageBox.TYPE_INFO, timeout=5) if config.plugins.RecInfobar.rec_indicator.value: if self.RecIndicator is None: self.RecIndicator = self.session.instantiateDialog( RecIndicator) if self.RecIndicator is not None: self.RecIndicator.show() else: self.RecIndicator.show() elif event == iRecordableService.evEnd: for (k, val) in self.reclist.items(): if k.__deref__() == key: del self.reclist[k] break if len(self.reclist) == 0: if self.RecIndicator is not None: self.RecIndicator.hide() self.reSize()
draw.rect(gameDisplay, (255, 223, 0), Rect(x, y, blockwidth, blockheight)) def collisiondetector(ball, blockx, blocky, blockwidth): ballbottom = ball.y + 10 if ballbottom >= blocky and ball.x >= blockx and ball.x <= blockx + blockwidth: ball.y_speed = -ball.y_speed if ball.x >= x_size - 20 or ball.x <= 10: ball.x_speed = -ball.x_speed if ball.y - 10 <= 0: ball.y_speed = -ball.y_speed ball = Ball(randint(x_size / 5, 0.8 * (x_size)), randint(y_size / 5, 0.8 * y_size), 3, 3) InitTime = Time() while not gameExit: for i in event.get(): print(i) if i.type == QUIT: gameExit = True if i.type == KEYDOWN: if i.unicode == 'q': gameExit = True if i.key == 275: x_change += 5 if i.key == 276: x_change -= 5 if i.type == KEYUP: if i.key == 275 or i.key == 276: x_change = 0
def Game(): PieceValueMap = setupTileReadingValues(BoardDelimitationBox) ComputerSide = None while ComputerSide == None: if not TestMode: takeScreenshot() while not validadeBoard(): sleep(1) continue initial = ReadScreen(PieceValueMap) if initial[0] == 'r' and initial[7] == 'r': ComputerSide = 0 elif initial[0] == 'R' and initial[7] == 'R': ComputerSide = 1 else: sleep(2) print( "Computer playing as %s." % Colors[ComputerSide] ) Board = chess.Board() WaitingEngineMove = False EngineThinkingStartTime = Time() print("board reader online.") RunningEngine.newGame() RunningEngine.send("load any") lastPieceCount = 32 RunningEngine.send('new') if not ComputerSide: RunningEngine.send('white') RunningEngine.send('go') WaitingEngineMove = True else: RunningEngine.send('black') game = True #print(">%s" % RunningEngine.MachineName) while game: MOVES, pieceCount = detectScreenBoardMovement(Board, PieceValueMap, ComputerSide) if CheckForNewGameImage(PIL.Image.open(PathToPresentBoardScreenshot)): # Check winner; MachineWins = [ detectSubImage(NameTag, PathToPresentBoardScreenshot)\ for NameTag in PathToNameTag ] if True in MachineWins: print("MACHINE WINS %s" % RunningEngine.MachineName) else: print("MACHINE LOSES") MacFile = "../lampreia-engine/machines/halloffame/%s" % RunningEngine.MachineName print("Removing > %s <" % MacFile) os.remove(MacFile) if AutoNewGameMode: mouseClick(NewGameBox, BrowserAbsolutePosition) sleep(3) print("\nScreen to new game detected!") #if tryNewGame(Board, PieceValueMap, ComputerSide): return else: RunningEngine.destroy() exit() V = validadeBoard() if not V: print("invalid screenshot.") continue if pieceCount > lastPieceCount or pieceCount < lastPieceCount-2: print( "invalid piece count. (%i against %i)" % (pieceCount,lastPieceCount) ) continue if MOVES: #print("&" * 12) # moves saved as 'screen coordinates' print(MOVES) if len(MOVES) > 3: # bail and don't process if screenshot proves to be invalid. # maybe website is waiting response for new game? check. # try to start new game, and reboot. print("Bizarre board conformation!") castlingExclusion = {'h8f8': 'e8g8', 'a8c8': 'e8b8', 'a8d8': 'e8c8', 'h1f1': 'e1g1', 'a1c1': 'e1b1', 'a1d1': 'e1c1'} for M in MOVES: if M[0] in AllPieces[1-ComputerSide]: #filter castling: if M[3] in castlingExclusion.keys(): if castlingExclusion[M[3]] in [ m[3] for m in MOVES]: continue print("Move detected: %s" % showmove(M)) if chess.Move.from_uci(M[3]) in list(Board.generate_legal_moves()): Board.push(chess.Move.from_uci(M[3])) RunningEngine.appendToComm(str(Board)+'\n') RunningEngine.send(M[3]) WaitingEngineMove = True print("\nWaiting engine movement...\n") lastPieceCount = pieceCount EngineThinkingStartTime = Time() else: print("ILLEGAL MOVE! %s" % M[3]) RunningEngine.send("dump") print("Ignoring...") else: print("Redoing movement %s." % M[3]) takeScreenshot() if validadeBoard(): makeMovementFromContrastingBoard(M[3], ComputerSide, True) else: continue else: print("|" * 12) while WaitingEngineMove: sleep(0.3) print("\r... %.1fs" % (Time() - EngineThinkingStartTime), end=" ") enginemove, score = RunningEngine.readMove(Verbose=False) if enginemove: if enginemove == 'Checkmate': break EngineThinkingTime = Time() - EngineThinkingStartTime print("\rEngine says %s ! :%is %s" % (enginemove, EngineThinkingTime, score) ) Board.push(chess.Move.from_uci(enginemove)) RunningEngine.send("show") RunningEngine.appendToComm(str(Board)) WaitingEngineMove = False if not MovingModeEnabled: break PromoteMove = True if 'q' in enginemove else False takeScreenshot() if validadeBoard(): makeMovementFromContrastingBoard(enginemove, ComputerSide, PromoteMove=PromoteMove) sleep(0.2)
class Channel: """ **pyjsdl.mixer.Channel** * Channel.play * Channel.stop * Channel.pause * Channel.unpause * Channel.set_volume * Channel.get_volume * Channel.get_busy * Channel.get_sound """ _mixer = None def __init__(self, id): self._id = id self._sound = None self._active = False self._pause = False self._loops = 0 self._volume = 1.0 self._lvolume = 1.0 self._rvolume = 1.0 self._mixer._register_channel(self) self._time = Time() self._nonimplemented_methods() def _set_sound(self, sound): if self._sound: self._sound._channel = None self._sound = sound def _play(self): self._volume = 1.0 self._lvolume = 1.0 self._rvolume = 1.0 self._active = True self._sound._sound_object.play() self._time.timeout(self._sound._sound_object.getDuration() * 1000, self) def _play_repeat(self, loops): if loops > 0: self._loops = loops else: self._loops = -1 self._play() def play(self, sound, loops=0, maxtime=0, fade_ms=0): """ Play sound on channel. Argument sound to play and loops is number of repeats or -1 for continuous. """ if self._sound: self.stop() self._set_sound(sound) if not loops: self._play() else: self._play_repeat(loops) return None def run(self): if not self._loops: self._active = False else: if self._loops > 0: self._loops -= 1 self._play() def stop(self): """ Stop sound on channel. """ if self._sound: self._sound._sound_object.pause() self._sound._sound_object.setCurrentTime(0) self._pause = False self._loops = 0 self._active = False return None def pause(self): """ Pause sound on channel. """ if self._sound: if not self._pause: self._sound._sound_object.pause() self._pause = True return None def unpause(self): """ Unpause sound on channel. """ if self._sound: if self._pause: self._sound._sound_object.play() self._pause = False return None def set_volume(self, volume): """ Set channel volume of sound playing. """ if volume < 0.0: volume = 0.0 elif volume > 1.0: volume = 1.0 self._volume = volume if self._sound: self._sound._sound_object.setVolume( self._volume * self._sound._sound_object._volume) else: self._volume = 1.0 return None def get_volume(self): """ Get channel volume for current sound. """ return self._volume def get_busy(self): """ Check if channel is processing sound. """ return self._active def get_sound(self): """ Get sound open by channel. """ return self._sound def _nonimplemented_methods(self): """ Non-implemented methods. """ self.fadeout = lambda *arg: None self.queue = lambda *arg: None self.get_queue = lambda *arg: None self.set_endevent = lambda *arg: None self.get_endevent = lambda *arg: 0