def test_remaining_time(context): # Haven't created any timers yet time_to_next_expire = timer.TIMER_SCHEDULER.trigger_all_expired_timers() assert time_to_next_expire is None # Timer1: periodic interval 0.8 sec timer1 = timer.Timer(interval=0.8, expire_function=context.timer1_expired) # Timer2: one-shot interval 0.8 sec _timer2 = timer.Timer(interval=0.8, expire_function=context.timer2_expired, periodic=False) time.sleep(2.0) # Now is 2.0 time_to_next_expire = timer.TIMER_SCHEDULER.trigger_all_expired_timers() assert context.timer1_expired_count == 2 # Expired at 0.8 and 1.6. Next expiry at 2.4 assert context.timer2_expired_count == 1 # Expired at 0.8. No next expiry. assert time_to_next_expire == pytest.approx(0.4, abs=0.1) time.sleep(0.5) # Now is 2.5 context.clear_counters() time_to_next_expire = timer.TIMER_SCHEDULER.trigger_all_expired_timers() assert context.timer1_expired_count == 1 # Expired at 2.4. Next expiry at 3.2. assert context.timer2_expired_count == 0 # Not running. assert time_to_next_expire == pytest.approx(0.7, abs=0.1) # Stop timer1. At this point no timer is running, so there no time_to_next_expire. timer1.stop() time_to_next_expire = timer.TIMER_SCHEDULER.trigger_all_expired_timers() assert time_to_next_expire is None time.sleep(1.0) context.clear_counters() time_to_next_expire = timer.TIMER_SCHEDULER.trigger_all_expired_timers() assert time_to_next_expire is None assert context.timer1_expired_count == 0 # Not running assert context.timer2_expired_count == 0 # Not running
def testTimer(self): with timer.Timer('Timer test') as t: time.sleep(0.1) with timer.Timer('Timer test', True) as t: time.sleep(0.1) with timer.Timer('Timer test') as t: time.sleep(0.1)
def run(self): self._lie_send_handler = udp_send_handler.UdpSendHandler( interface_name=self.name, remote_address=self._tx_lie_ipv4_mcast_address, port=self._tx_lie_port, local_address=self._ipv4_address, multicast_loopback=self._node.engine.multicast_loopback) # TODO: Use source address (_, source_port) = self._lie_send_handler.source_address_and_port() self._lie_udp_source_port = source_port self._lie_receive_handler = udp_receive_handler.UdpReceiveHandler( remote_address=self._rx_lie_ipv4_mcast_address, port=self._rx_lie_port, receive_function=self.receive_lie_message, local_address=self._ipv4_address) self._flood_receive_handler = None self._flood_send_handler = None self._one_second_timer = timer.Timer( 1.0, lambda: self.fsm.push_event(self.Event.TIMER_TICK)) self._service_queues_timer = timer.Timer( interval=self.SERVICE_QUEUES_INTERVAL, expire_function=self.service_queues, periodic=True, start=False)
def __init__(self, type='default'): self.mouse = ika.Input.mouse self.x = int(self.mouse.x.Position()) self.y = int(self.mouse.y.Position()) self.type = type global pointers self.pointer = pointers[self.type] #used internally only self.leftPressed = False self.rightPressed = False self.middlePressed = False self.timer = timer.Timer(10) self.doubleTimer = timer.Timer(40) #will be used (indirectly) by others to determine state of mouse self.leftClicked = False self.leftDoubleClicked = False self.leftHeld = False self.leftReleased = False self.rightClicked = False self.rightDoubleClicked = False self.rightHeld = False self.rightReleased = False self.middleClicked = False self.middleDoubleClicked = False self.middleHeld = False self.middleReleased = False
def InitializeTimers(self): # Timers self.render_period = 1./60 self.render_timer = timer.Timer(self.render_period) self.game_period = 1./240 self.game_timer = timer.Timer(self.game_period)
def plot_hr_many(filenames): load_CUDA() ecgs = [(filename, read_ISHNE(filename)) for filename in filenames] result = [] wall = 0.0 for filename, ecg in ecgs: with timer.Timer() as compression_time: compressed_leads = compress_leads(*ecg.leads) print "Compression:", compression_time wall += compression_time.interval with timer.Timer() as compute: y, x = get_hr(compressed_leads, ecg.sampling_rate / 4) result.append(( x, y, filename, )) wall += compute.interval print "Total:", wall, "seconds" for x, y, filename in result: plt.plot(x, y, label=filename) plt.legend() plt.title("ECG - RR") plt.xlabel("Hours") plt.ylabel("Heartrate (BPM)") plt.show()
def test_oneshot(context): # Timer1: interval 0.8 sec (expires 1x in 2.0 sec), started in constructor # Rely on default values for start parameter _timer1 = timer.Timer(interval=0.8, expire_function=context.timer1_expired, periodic=False) # Timer2: interval 2.2 sec (expires 0x in 2.0 sec), started outside constructor timer2 = timer.Timer(interval=2.2, expire_function=context.timer1_expired, periodic=False, start=False) timer2.start() # Timer3: interval 2.5 sec (expires 0x in 2.0 sec), never started _timer3 = timer.Timer(interval=2.5, expire_function=context.timer3_expired, periodic=False, start=False) # Timer4: interval 0.8 sec (same as timer1, expires 1x in 2.0 sec), started outside constructor timer4 = timer.Timer(interval=0.8, expire_function=context.timer4_expired, periodic=False, start=False) timer4.start() # Timer5: interval 1.4 sec (expires 1x in 2.0 sec), not started _timer5 = timer.Timer(interval=1.4, expire_function=context.timer5_expired, periodic=False, start=False) time.sleep(2.0) timer.TIMER_SCHEDULER.trigger_all_expired_timers() assert context.timer1_expired_count == 1 assert context.timer2_expired_count == 0 assert context.timer3_expired_count == 0 assert context.timer4_expired_count == 1 assert context.timer5_expired_count == 0
def fishtank(): logger = log.RotatingFile("/var/log/picontroller/logs") sensorAir = temp_sensor.TempSensor.new(name="Room",sensor="/sys/bus/w1/devices/28-0014117fb1ff/w1_slave") sensorTank = temp_sensor.TempSensor.new(name="Tank", sensor="/sys/bus/w1/devices/28-00000676eb5f/w1_slave") pinList = [11, 13, 15, 16] r0 = relay.Relay(pin=pinList[0],name="Relay1") r1 = relay.Relay(pin=pinList[1],name="Relay2") r0.init() r1.init() t0 = timer.Timer('Light1') t0.set(timer.S3,timer.S3,timer.S3,timer.S3,timer.S3,timer.S5,timer.S5) t1 = timer.Timer('Light2') t1.set(timer.S4,timer.S4,timer.S4,timer.S4,timer.S4,timer.S6,timer.S6) webserver.temps.append(sensorAir) webserver.temps.append(sensorTank) webserver.relays.append(r0) webserver.relays.append(r1) webserver.timers.append(t0) webserver.timers.append(t1) webserver.start_server() now = 0 while True: while time.time() < now: time.sleep(1) now = time.time()+60 sensorAir.tick() sensorTank.tick() if t0.on(): r0.turn_relay_on() else: r0.turn_relay_off() if t1.on(): r1.turn_relay_on() else: r1.turn_relay_off() timestamp = datetime.datetime.utcnow().isoformat('T')+"000Z" l = "time:{t}\troom:{r}\ttank:{w}\tlight0:{r0}\tline1:{r1}".format(t=timestamp, r=sensorAir.current_value, w=sensorTank.current_value, r0=r0.current_state, r1=r1.current_state) logger.log(l)
def run(params, eq, timeout, ploc, wd): path = ploc.findProgram("woorpjeSMT") if not path: raise "WoorpjeSMT Not in Path" tempd = tempfile.mkdtemp() smtfile = os.path.join(tempd, "out.smt") time = timer.Timer() myerror = "" SMTSolverCalls = 0 try: smtmodel = os.path.join(wd, "smtmodel.smt") time = timer.Timer() #out = subprocess.check_output ([path, '--smtmodel',smtmodel,'--smttimeout', '15','--solver','4']+params+[eq],timeout=timeout) p = subprocess.run([ path, '--smtmodel', smtmodel, '--solver', '4', '--smttimeout', '15' ] + params + [eq], stdout=subprocess.PIPE, encoding='ascii', universal_newlines=True, timeout=timeout) time.stop() output = p.stdout.splitlines() for l in output: if l.startswith("SMTCalls:"): SMTSolverCalls = [int(x) for x in l.split(" ") if x.isdigit()][0] if p.returncode == 0: with open(smtmodel) as f: #model = f.read() model = "" for l in f: #model += "".join(l.split("_")) model += l.replace("(define-fun _", "(define-fun ", 1).replace("_()", "()", 1) + "\n" return utils.Result(True, time.getTime(), False, SMTSolverCalls, "\n".join(output), model) elif p.returncode == 10 or p.returncode == 20: return utils.Result(None, time.getTime(), False, SMTSolverCalls, "\n".join(output)) elif p.returncode == 1: return utils.Result(False, time.getTime(), False, SMTSolverCalls, "\n".join(output)) else: return utils.Result(None, time.getTime(), False, SMTSolverCalls, "\n".join(output)) except Exception as e: time.stop() return utils.Result(None, timeout, True, SMTSolverCalls, str(e))
def _test_callbacks(self, cb, args=None, kwargs=None): if args and kwargs: t = timer.Timer(self.duration, cb, *args, **kwargs) elif args: t = timer.Timer(self.duration, cb, *args) else: t = timer.Timer(self.duration, cb) t.start() time.sleep(0.01) self.assertEqual(t.elapsed, self.duration) self.assertFalse(t.running) self.assertTrue(t.expired)
def CLAW_DRIVE(): """ Controls the claw motor The fuctions acts as a togggle When the claw is closed it applies continious power to the motor """ tickTimer = timer.Timer() tickTimer_max = 1.3 # Seconds tickTimer.start() buttonTimer = timer.Timer() buttonTimer_max = 1.3 # Seconds buttonTimer.start() clawIsOpen = False while True: # print 'TELEOP CLAW' # CLAW MOTORS if joystick.b8down() and buttonTimer.elapsed_time() > buttonTimer_max: if not clawIsOpen: clawIsOpen = True # RESET TICK TIMER tickTimer.start_lap() elif clawIsOpen: clawIsOpen = False # RESET TICK TIMER tickTimer.start_lap() # RESET BUTTON TIMER buttonTimer.start_lap() if tickTimer.elapsed_time() < tickTimer_max: if not clawIsOpen: # IF CLAW IS CLOSED OPEN IT _claw.run(CLAW_OPEN_POWER) elif clawIsOpen: # IF CLAW IS OPEN CLOSE IT _claw.run(CLAW_CLOSE_POWER) # CONTINIOUS POWER TO CLOSE THE CLAW else: if clawIsOpen: # IF CLAW IS OPEN PROVIDE CONTANT POWER TO THE MOTOR _claw.run(CLAW_CONSTANT_CLOSE_POWER) else: # TURNS OFF CLAW IF IT'S OPEN _claw.off()
def __init__(self, size=10, frameRate=40, hflip=False, vflip=False): """A wrapper class for the Raspberry Pi camera using the picamera python library. The size parameter sets the camera resolution to size * (64, 48).""" self.active = False try: if type(size) is not int: raise TypeError("Size must be an integer") elif 1 <= size and size <= 51: self.size = size self.hRes = size * 64 self.vRes = size * 48 else: raise ValueError("Size must be in range 1 to 51") except TypeError or ValueError: raise self.picam = PiCamera() self.picam.resolution = (self.hRes, self.vRes) self.picam.framerate = frameRate self.picam.hflip = hflip self.picam.vflip = vflip time.sleep(1) self.stream = PiCameraCircularIO(self.picam, seconds=1) self.frameRateTimer = timer.Timer() self.frameRateFilter = filters.Filter1D(maxSize=21) self.start()
def add_timers(timer1, timer2): """Returns: A new Timer object representing the sum of the times in timer1 and timer2. Does not alter timer1 or timer2. Example: if timer1 represents 1 hr 59 min and timer2 represents 1 hr 2 min, then the **new** returned Timer represents 3 hr 1 min. Preconditions: timer1 is a Timer object timer2 is a Timer object""" # PLACEHOLDER: REPLACE WITH YOUR IMPLEMENTATION. # HINT1: The main challenge is to figure out what to do if the minutes # add up to more than 60. It's useful to use the remainder # operator `%`; for example, 61 % 60 is 1. And it's useful # to remember the `//` operator; for example, 61 // 1 is 1. # HINT2: The class Timer is defined in module `timer`, which we've # imported above. So, to create a new Timer, you need a # call like timer.Timer(..., ...) # HINT3: You can use if/then/elif/else statements if you want. hoursum=timer1.hours+timer2.hours minsum=timer1.minutes+timer2.minutes if minsum >59 : hoursum=hoursum+1 minsum=minsum %60 t=timer.Timer(hoursum,minsum) return t
def plot_hr_pipelined(ecg_filenames): manager = multiprocessing.Manager() compress_queue = manager.Queue() compute_queue = manager.Queue() compress_pool = multiprocessing.Pool(processes=8) compute_process = multiprocessing.Process(target=compute, args=( compress_queue, compute_queue, )) plot_process = multiprocessing.Process(target=plot, args=(compute_queue, )) compute_process.start() plot_process.start() ecgs = [(filename, read_ISHNE(filename)) for filename in ecg_filenames] with timer.Timer() as wall: for filename, ecg in ecgs: compress_pool.apply_async(compress, args=( ecg.leads, ecg.sampling_rate, filename, compress_queue, )) # Prevent more work from being put to the pool compress_pool.close() # # Wait for the pool to finish compress_pool.join() # Send the done message compress_queue.put(True) compute_process.join() # Total seems to include about 200ms of overhead print "Total:", wall plot_process.join()
def start_server(internal=False): if internal: server = Server(("localhost", 1486), ThreadedTCPRequestHandler) else: import os import re localips = ignore_127_ips( socket.gethostbyname_ex(socket.gethostname())[2]) if os.name == 'posix' and len(localips) == 0: from subprocess import Popen, PIPE p = Popen(["ifconfig"], stdin=PIPE, stdout=PIPE, stderr=PIPE) ifconfig, stderr = p.communicate("".encode()) localips = ignore_127_ips( re.compile('addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'). findall(ifconfig)) if len(localips) == 0: print("No suitable ip addresses found, using 127.0.0.1") localips = ["127.0.0.1"] localip = localips[0] server = Server((localip, 1486), ThreadedTCPRequestHandler) G.SERVER = server server_thread = threading.Thread(target=server.serve_forever) server_thread.start() threading.Thread(target=server.world.content_update, name="world_server.content_update").start() # start server timer G.main_timer = timer.Timer(G.TIMER_INTERVAL, name="G.main_timer") G.main_timer.start() return server, server_thread
def __init__(self): # Initialize hardware self.left_wheels = vex.Motor(10) self.right_wheels = vex.Motor(1) self.lline_track = vex.LineTracker(2) self.rline_track = vex.LineTracker(1) self.serial = vex.Serial(1, 9600) self.serial.write("begin") # Default power self.TOTAL_POWER = 60 # State can be one of [forward, on_tape, off_tape] self.state = "forward" self.lon_tape = False self.ron_tape = False # Keep track of coordinates self.square = Vector(0, 0) self.lcd_print(self.square) # Going to the right self.direction = Vector(1, 0) # Class timer object self.timer = timer.Timer()
def __init__ (self): self.user = USERID self.password = PASSWORD self.timer = timer.Timer() self.started = False self.paused = False self.total_blocks = 0 self.break_blocks = 0 self.total_time = 0 self.break_time = 0 self.productive_time = 0 self.items = [] self.tasks = [] self.curr_task_num = None self.curr_task = None self.task_blocks = 0 self.task_break_blocks = 0 self.task_time = 0 self.task_break_time = 0 self.goal_hrs = 0 self.goal_blocks = 0 self.hour_track = 0 self.store = Storage() self.sync_status = None self.sync_status_time = None self.today = datetime.now(timezone('EST')).strftime("%a %d %b")
def test_update(self): field = f.Field('tests/lvl1.txt') field.hero.energizer = True field.hero.timer = t.Timer(0) field.hero.update(field) self.assertFalse(field.hero.energizer) self.assertIsNone(field.hero.timer)
def __init__(self, ID, x, y, width, height, active_frames, change_rgb_value=False, rgb=(10, 10, 10, 0)): """Initialise a sprite. ID is a string. active_framea is a list of tuples containing animations e.g [(animation_name, [loaded_images], int_animation_speed)]""" self.ID = ID self.x = x self.y = y self.width = width self.height = height self.active_frames = active_frames self.all_frames = {} self.all_frame_speed = {} self.all_timers = timer.Timer() if change_rgb_value: self.change_sprite_rgb_value(rgb) for t in self.active_frames: self.all_frames[t[0]] = t[1] self.all_frame_speed[t[0]] = t[2] self.current_frame = 0 self.current_animation = self.active_frames[0][0] self.all_timers.add_ID('time_till_next_frame', 0)
def restart(self, delay): self.__pending = PendingRequest.RESTART self.__timer = timer.Timer() self.__delay = delay for l in self.__listeners: l.shutdown(delay, restart=True)
def halt(self, delay): self.__pending = PendingRequest.HALT self.__timer = timer.Timer() self.__delay = delay for l in self.__listeners: l.shutdown(delay, restart=False)
def gen_windows2(array): try: with timer.Timer() as t: x = range(0, array.shape[1]) y = range(0, array.shape[2]) myfunc = lambda a: a.flatten() aList = [myfunc(array[i, :, :]) for i in range(0, array.shape[0])] full_index = pd.MultiIndex.from_product([x, y], names=['i', 'j']) i = 0 x = False y = False windows = pd.DataFrame({i: aList[0]}, index=full_index) for i in range(1, len(aList)): print('gen_windows: ', i, ' of ', len(aList)) temp = pd.DataFrame({i: aList[i]}, index=full_index) windows = windows.merge(temp, left_index=True, right_index=True, how='left') temp = False windows.index.names = ['i', 'j'] aList = False array = False finally: print('gen_windows2 request took %.03f sec.' % t.interval) return windows
def __init__(self): x, y = 0, 0 width = 50 height = 50 display_layer = 4 is_active = False orb_animation = [ universal_var.misc_images['explosion_1'], universal_var.misc_images['explosion_2'], universal_var.misc_images['explosion_3'], universal_var.misc_images['explosion_4'], universal_var.misc_images['explosion_5'], universal_var.misc_images['blank'] ] orb_sprite = Sprite(universal_var.main_sprite, x, y, width, height, [('orb', orb_animation, 20)]) super().__init__('Death_orb', x, y, [orb_sprite], None, is_active, width, height, display_layer) self.spawned = False self.vel = 0 self.all_timers = timer.Timer() self.all_timers.add_ID('start_time', 0) Death_orb.add_to_class_lst(self, Death_orb.all_orbs_lst, self.ID) Death_orb.all_orbs_stack.push(self)
def get(self, http, locator): # http is an httplib2.Http object. # locator is a KeepLocator object. url = self.root + str(locator) _logger.debug("Request: GET %s", url) try: with timer.Timer() as t: result = http.request(url.encode('utf-8'), 'GET', headers=self.get_headers) except self.HTTP_ERRORS as e: _logger.debug("Request fail: GET %s => %s: %s", url, type(e), str(e)) self.last_result = e else: self.last_result = result self.success_flag = retry.check_http_response_success(result) content = result[1] _logger.info("%s response: %s bytes in %s msec (%.3f MiB/sec)", self.last_status(), len(content), t.msecs, (len(content) / (1024.0 * 1024)) / t.secs) if self.success_flag: resp_md5 = hashlib.md5(content).hexdigest() if resp_md5 == locator.md5sum: return content _logger.warning("Checksum fail: md5(%s) = %s", url, resp_md5) return None
def nodalSum2(val,elems,tol): """Compute the nodal sum of values defined on elements. val : (nelems,nplex,nval) values at points of elements. elems : (nelems,nplex) nodal ids of points of elements. work : a work space (unused) The return value is a tuple of two arrays: res: cnt On return each value is replaced with the sum of values at that node. """ print("!!!!nodalSum2!!!!") val[:] = normalize(val) import timer from pyformex.lib import misc t = timer.Timer() nodes = unique(elems) t.reset() [ averageDirectionsOneNode(val,where(elems==i),tol) for i in nodes ] ## for i in nodes: ## wi = where(elems==i) ## k = val[wi] ## #averageDirection(k,tol) ## misc.averageDirection(k,tol) ## val[wi] = k print("TIME %s \n" % t.seconds())
def __init__(self): object.__init__(self) # Handedness ('r' or 'l') self._handedness = "r" # Normalized up direction self._up = vec3(0, 0, 1) # Unit (1 unit = unitscale [Unit]) self._unit = "m" # Unit scale self._unitscale = 1.0 # Global options self._globals = {} self.items = [] # self.items_by_name = {} self._worldroot = _core.WorldObject("WorldRoot") self._timer = timer.Timer(auto_insert=False) # Key: ID Value:Joystick object self._joysticks = {} self.clear()
def start(self): """ Starts the server. """ # set up the input ports self.input_ports = list( map(create_input_socket, self.config.input_ports)) # start the periodic timer self.periodic_timer = timer.Timer( self.config.periodic_update, self.process_periodic_update) self.periodic_timer.start() self.periodic_timer.trigger() # only block for a second at a time blocking_time = 0.1 loop_time = time.time() while self.input_ports: readable, _writable, exceptional = select.select( self.input_ports, [], self.input_ports, blocking_time) # increment the age dt = time.time() - loop_time self.rt.increment_age(dt) # redisplay the screen self.print_display() # update the timer, may call process_periodic_update self.periodic_timer.update() # may call process_triggered_updates self.rt.update(self.process_triggered_updates) # display the information log print("") print("Information Log:") for line in self.loglines: print(" ", line) # iterate through all sockets that have data waiting on them for sock in readable: data, addr = sock.recvfrom(4096) resp = self.process_incoming_data(addr, data) if resp is not None: sock.sendto(resp, addr) # removes a socket from the input list if it raised an error for sock in exceptional: if sock in self.input_ports: self.input_ports.remove(sock) sock.close() raise Exception("A socket raised an error") # update the loop time loop_time = time.time()
def get_input_data(bands, year, sites, get_predictor_data_only=False): data_by_site = dict() try: with timer.Timer() as t: for site in sites: print(site) type = db.data_context_dict[site] data = pd.DataFrame() if (type == 'supplementary_class'): print('Getting fixed class data') data = get_fixed_bands(bands, site, type) else: island = db.data_context_dict[site] all_class = image_cache.get_class_by_concession_name(site) #box = shapefilehelp.get_bounding_box_polygon(db.shapefiles[site]) if not get_predictor_data_only: #THIS IS TRAINING DATA year = str(int( db.get_concession_assessment_year(site))) x = get_concession_bands(bands, year, all_class, site) y = get_classes(all_class.data, 'clas') data = combine_input_landcover(x, y) elif get_predictor_data_only: data = get_concession_bands(bands, year, all_class, site) data_by_site[site] = data all_class = False x = False y = False finally: print('get_input_data Request took %.03f sec.' % t.interval) return data_by_site
def __init__(self, transformComponent: TransformComponent, rigidbodyComponent: RigidbodyComponent, colliderComponent: ColliderComponent, weaponComponent: WeaponComponent, healthComponent: HealthComponent, sightComponent: SightComponent, actionComponent: ActionComponent, mapComponent: MapComponent, shootDelay, seeDelay, hitReaction, aimOffset, canPickUpObjects, canTakeCover): super().__init__(transformComponent, rigidbodyComponent, colliderComponent, weaponComponent, healthComponent, sightComponent, actionComponent, mapComponent) self.shootDelay = shootDelay self.seeDelay = seeDelay self.aimOffset = aimOffset self.hitReaction = hitReaction self.canPickUpObjects = canPickUpObjects self.canTakeCover = canTakeCover self.timer = timer.Timer() self.graph = Graph(self.map) self.agent = movement.Agent(self) self.fsm = decisionMaking.FSM(self) self.lastSeenBotEntity = None self.lastKnownPosition = None self.lastKnownDirection = None
def test_timer_as_instance_error_when_stop_a_non_running_timer(): timer.Timer.timers = {} my_timer = timer.Timer(name='test_timer', logger=logger.info, silent=False) with pytest.raises(timer.TimerError) as exc: my_timer.stop() assert isinstance(exc.type, type(timer.TimerError))