Beispiel #1
0
    def run(self):
        while self._running:

            events = pygame.event.get()

            timestamp = time.monotonic_ns()

            for event in events:

                if event.type == pygame.JOYAXISMOTION and event.joy == self.index:
                    axis = event.axis
                    self.set_trait('timestamp', timestamp)
                    self.axes[axis].set_trait('value', _clamp(event.value))
                elif event.type == pygame.JOYBUTTONDOWN and event.joy == self.index:
                    button = event.button
                    self.set_trait('timestamp', timestamp)
                    self.buttons[button].set_trait('value', 1.0)
                    self.buttons[button].set_trait('pressed', True)
                elif event.type == pygame.JOYBUTTONUP and event.joy == self.index:
                    button = event.button
                    self.set_trait('timestamp', timestamp)
                    self.buttons[button].set_trait('value', 0.0)
                    self.buttons[button].set_trait('pressed', False)

            time.sleep(0.01)
Beispiel #2
0
    def elapsed(self) -> int:
        """Return integer which show how many ms has passed since start of time limit.

            Returns:
                int
        """
        return (time.monotonic_ns() - self.start) // 1000000
    def step(self):
        # Update each wheel for one time step
        if self.state == RUNNING:
            # Slowly lose speed when running, but go at least speed 64
            self.vel = max(self.vel * 9 // 10, 64)
            if time.monotonic_ns() > self.stop_time:
                self.state = BRAKING
        elif self.state == BRAKING:
            # More quickly lose speed when braking, down to speed 7
            self.vel = max(self.vel * 85 // 100, 7)

        # Advance the wheel according to the velocity, and wrap it around
        # after 7680 positions
        self.pos = (self.pos + self.vel) % 7680

        # Compute the rounded Y coordinate
        yy = round(self.pos / 16)
        # Compute the offset of the tile (tiles are 24 pixels tall)
        yyy = yy % 24
        # Find out which tile is the top tile
        off = yy // 24

        # If we're braking and a tile is close to midscreen,
        # then stop and make sure that tile is exactly centered
        if self.state == BRAKING and self.vel == 7 and yyy < 4:
            self.pos = off * 24 * 16
            self.vel = 0
            self.state = STOPPED

        # Move the displayed tiles to the correct height and make sure the
        # correct tiles are displayed.
        self.y = yyy - 20
        for i in range(3):
            self[i] = self.order[(19 - i + off) % 20]
Beispiel #4
0
    async def lookup(self, k: T) -> U:
        if self._shutting_down:
            raise ValueError('Cache is shutting down.')

        if k in self._expiry_time:
            assert k in self._cache
            if self._expiry_time[k] <= time.monotonic_ns():
                self._remove(k)

        if k in self._cache:
            CACHE_HITS.labels(cache_name=self.cache_name).inc()
            return self._cache[k]

        CACHE_MISSES.labels(cache_name=self.cache_name).inc()
        if k in self._futures:
            return await self._futures[k]

        self._futures[k] = asyncio.create_task(self.load(k))
        try:
            v = await prom_async_time(
                CACHE_LOAD_LATENCY.labels(cache_name=self.cache_name),
                self._futures[k])
        finally:
            del self._futures[k]

        self._put(k, v)

        if self._over_capacity():
            CACHE_EVICTIONS.labels(cache_name=self.cache_name).inc()
            self._evict_oldest()

        return v
Beispiel #5
0
def stopwatch_stop(bytes_uploaded):
    elapsed_ms = (monotonic_ns() - stopwatch_ns) // 1000000
    transfer_rate_MBps = 0
    if elapsed_ms > 0:
        transfer_rate_kBps = bytes_uploaded // elapsed_ms
    print("%d bytes uploaded in %d ms (%d kB/s)" %
          (bytes_uploaded, elapsed_ms, transfer_rate_kBps))
Beispiel #6
0
    def _timestep(self, target_dt_ns: int):
        ti = time.monotonic_ns()

        def no_samples_to_send(failure: Failure):
            failure.trap(NoSensorUpdate)
            # no sensor data to send, ignore
            return

        def send_step_results(sensor_samples: Mapping[str, PhyPropType]):
            # TODO: log!
            self._control.put_sensor_values(sensor_samples)

        def reschedule_step_callback(*args, **kwargs):
            dt = nanos2seconds(target_dt_ns - (time.monotonic_ns() - ti))
            if dt >= 0:
                self._reactor.callLater(dt, self._timestep, target_dt_ns)
            else:
                warnings.warn(
                    'Emulation step took longer than allotted time slot!',
                    EmulationWarning)
                self._reactor.callLater(0, self._timestep, target_dt_ns)

        # instead of using the default deferToThread method
        # this way we can pass the reactor and don't have to trust the
        # function to use the default one.
        threads.deferToThreadPool(self._reactor,
                                  self._reactor.getThreadPool(),
                                  self._emu_step) \
            .addCallback(send_step_results) \
            .addErrback(no_samples_to_send) \
            .addCallback(reschedule_step_callback)
Beispiel #7
0
def printTransportStats():
    global tapePosition
    global tapeInches
    global transportState
    global transportTime
    global msStartTime

    stateList = ["TRANSPORT_STATE_OFF",\
                "TRANSPORT_STATE_FWD_SLOW",\
                "TRANSPORT_STATE_FWD_FAST",\
                "TRANSPORT_STATE_RWD_SLOW",\
                "TRANSPORT_STATE_RWD_FAST",\
                "TRANSPORT_STATE_SLOW_2HOLE"]

    ms = int(time.monotonic_ns() / 1000000) - msStartTime

    print("\n%s" % stateList[transportState] + ", t=%d" % ms +
          "ms, tach=%d" % header.tachometer)

    print("   Tape position=%d" % tapePosition + " counts, %d" % tapeInches +
          " inches")
    print("   Status reg=0x%02x " % header.statusRegister +
          " Control reg=0x%02x " % header.controlRegister)

    return
Beispiel #8
0
def deltatime_point():
  """ Take a point in time.
  Returns:
    Opaque point-in-time
  """
  point = time.monotonic_ns()
  return (point + 5 * 10 ** 8) // 10 ** 9
Beispiel #9
0
    def sync(self):
        if time.monotonic_ns() / 1e9 - self._last_update_device_time > 1800:
            self._update_device()

        headers = {
            "mc_token": self.token,
            "mc_secret": self.secret,
        }
        if self.debug:
            print(self._data_url)
            print(headers)
            print(self._outgoing_message_queue)

        try:
            result = self.requests.put(
                self._data_url,
                headers = headers,
                json = self._outgoing_message_queue,
                timeout = 5,
            )
            if self.debug:
                print(result.status_code, result.content)

            if result.status_code != 200:
                print("[freedomrobotics] sync error: " + str(result.status_code) + ": " + result.content)
                return False
            else:
                self._outgoing_message_queue = []
        except Exception as e:
            sys.print_exception(e)
            raise Exception("[freedomrobotics] sync error")
            return False

        return True
 def run_trial(self):
     for _ in range(self.nTrials):
         if not self.concentrate:
             self.concentrate = True
             if not self.quiet:
                 print("Concentrate")
         else:
             self.concentrate = False
             if not self.quiet:
                 print("Relax")
         t1 = time.monotonic_ns()
         for i in range(self.nSamples):
             self.get_sample(i)
         t2 = time.monotonic_ns()
         elapsed = floor(t2 - t1)
         self.time_delta.append(elapsed)
Beispiel #11
0
 def key_exchange_handler(self, path: str, query: dict, data: dict) -> None:
     """Handles a key exchange.
 Accepts the AC's random and time and pass its own.
 Note that a key encryption component is the lanip_key, mapped to the
 lanip_key_id provided by the AC. This secret part is provided by HiSense
 server. Fortunately the lanip_key_id (and lanip_key) are static for a given
 AC.
 """
     try:
         key = data['key_exchange']
         if key['ver'] != 1 or key['proto'] != 1 or key.get('sec'):
             raise KeyError()
         _config.lan_config.random_1 = key['random_1']
         _config.lan_config.time_1 = key['time_1']
     except KeyError:
         logging.error('Invalid key exchange: %r', data)
         self.do_HEAD(400)
         return
     if key['key_id'] != _config.lan_config.lanip_key_id:
         logging.error(
             'The key_id has been replaced!!\nOld ID was %d; new ID is %d.',
             _config.lan_config.lanip_key_id, key['key_id'])
         self.do_HEAD(404)
         return
     _config.lan_config.random_2 = ''.join(
         random.choices(string.ascii_letters + string.digits, k=16))
     _config.lan_config.time_2 = time.monotonic_ns() % 2**40
     _config.update()
     self.do_HEAD()
     self._write_json({
         "random_2": _config.lan_config.random_2,
         "time_2": _config.lan_config.time_2
     })
Beispiel #12
0
def begin(
    Ts
):  # Sampling functionality is initialized with begin() to keep consistent with Arduino API
    Settings.Tsampling = Ts * 1000  # Convert sampling time to _nano_seconds
    Settings.t_last = time.monotonic_ns(
    )  # Initialize "last" sample as current monotonic time.
    Settings.t_next = Settings.t_last + Settings.Tsampling  # Initialize next sample. The next sampling time is the current time + sampling
Beispiel #13
0
    def __init__(self, update_freq_hz: int):
        super(State, self).__init__()
        # self.__sensor_vars: Dict[str, SensorVariable] = {}
        # self.__actuator_vars: Dict[str, ActuatorVariable] = {}

        self._freq = update_freq_hz
        self._ti = time.monotonic_ns()
Beispiel #14
0
def get(pid):
    if not isinstance(pid, str):
        return False

    ret = None
    ms_s = str(time.monotonic_ns())[:-6]
    lock = filelock.FileLock('tmp/.pend_lock', timeout=5)
    try:
        with lock:
            if not os.path.exists('tmp/.pend'):
                return False
            with open('tmp/.pend', 'r') as file:
                pl_ori = json.loads(file.read())
            since = max(int(ms_s) - gconf['comment']['timeout'] * 1000, 0)
            pl = dict(
                filter(lambda elem: int(elem[0][:-6]) >= since,
                       pl_ori.items()))
            if pid in pl:
                ret = pl[pid]
                del pl[pid]
            if len(pl_ori) != len(pl):
                with open('tmp/.pend', 'w') as file:
                    file.write(
                        json.dumps(pl,
                                   indent=2,
                                   ensure_ascii=False,
                                   sort_keys=False))
        return ret

    except filelock.Timeout:
        return None
Beispiel #15
0
 def _auto_advance(self):
     if not self._advance_interval:
         return
     now = monotonic_ns()
     if now - self._last_advance > self._advance_interval:
         self._last_advance = now
         self.next()
Beispiel #16
0
 def resume(self):
     """
     Resumes the animation.
     """
     self._next_update = monotonic_ns() + self._time_left_at_pause
     self._time_left_at_pause = 0
     self._paused = False
Beispiel #17
0
 def wait_for(self, timeout):
     """
     Returns true if when the pin transitions from low to high.
     Assumes some other process will reset the pin to low.
     :param timeout: time to wait for the interrupt in milliseconds
     :return: True if the interrupt happened. False if it timed out.
     """
     ready = False
     # Dividing sleep time by 300 instead of 30 double CPU load but cuts
     # IMU timestamp variation from about 20% to less than 1%
     sleep_time = (timeout / 1000.0) / 30
     stop_time = time.monotonic_ns() + (timeout * 1000000.0)
     while not ready and time.monotonic_ns() < stop_time:
         ready = GPIO.input(self.gpio_pin)
         time.sleep(sleep_time)
     return ready
Beispiel #18
0
    def poll_controls(self):
        k = self.win.getch()
        if k > 0:
            self._handle_key(k)
        if self.hardware is not None:
            self.hardware.poll_controls()
            if self.enclast > 0 and (time.monotonic_ns() - self.enclast) > 1000000000:
                self.encsw = '--'
                self.dirty = True
                self.enclast = 0
            for ctrl in self.hardware.analog_controls:
                if ctrl.value != ctrl.last_read:
                    ctrl.value = ctrl.last_read
                    self.dirty = True

        if alsa_available and self.audiocard is not None:
            l,data = self.audio_in.read()
            if l > 0:
                npd = np.frombuffer(data, dtype=np.int16)
                d_left = npd[0::2]
                d_right = npd[1::2]
                # Ideally look for peak to peak but ...
                self.lpeak = np.amax(d_left)
                self.rpeak = np.amax(d_right)
                if not self.dirty:
                    func, data = self.lines[self.vu_left]
                    func(self.vu_left, data)
                    func, data = self.lines[self.vu_right]
                    func(self.vu_right, data)

        if self.dirty:
            self.dirty = False
            self.refresh()
Beispiel #19
0
def print_frame_time():
    global last_time
    current_time = time.monotonic_ns()
    delta_time = current_time - last_time
    print(delta_time/1000000)
    last_time = current_time
    return print_frame_time
Beispiel #20
0
 def transfer_start_callback(self, *_: Any) -> None:
     """Callback for each chunked (down|up)loads.
     Called first to set the end time of the current (down|up)loaded chunk.
     """
     action = Action.get_current_action()
     if action:  # mypy fix ...
         action.chunk_transfer_end_time_ns = monotonic_ns()
Beispiel #21
0
    def declare_savepoint(self, name: str):
        if self.is_implicit():
            raise errors.TransactionError(
                'savepoints can only be used in transaction blocks')

        sp_id = time.monotonic_ns()

        # Save the savepoint state so that we can rollback to it.
        self._stack.append(
            TransactionState(
                id=sp_id,
                name=name,
                schema=self.get_schema(),
                modaliases=self.get_modaliases(),
                config=self.get_session_config()))

        # The top of the stack is the "current" state.
        self._stack.append(
            TransactionState(
                id=sp_id,
                name=None,
                schema=self.get_schema(),
                modaliases=self.get_modaliases(),
                config=self.get_session_config()))

        copy = self.copy()
        self._constate._savepoints_log[sp_id] = copy

        return sp_id
Beispiel #22
0
 def __enter__(self) -> None:
     self._nesting_level = len(_clusters)
     if self._with_time:
         self._monotonic_ns = time.monotonic_ns()
     if is_unsuppressed_level(self._level):
         self.inform_title()
     _clusters.append(self)
Beispiel #23
0
    def loop(self):
        global monotonic_ns

        now = monotonic_ns()
        assert isinstance(now, int), f"now={repr(now)}"

        # get previous data
        was_touched = self._was_touched
        last_coord = self._last_coord

        # get current data
        self._coord = coord = self.poll_coord()
        self._is_touched = is_touched = coord is not None

        if is_touched and not was_touched:
            # print(f"[down] coord={coord}, last_coord={last_coord}")
            self._touch_down()
        elif not is_touched and was_touched:
            # print(f"[ up ] coord={coord}, last_coord={last_coord}")
            self._touch_up()
        elif is_touched:
            # print(f"[cont] coord={coord}, last_coord={last_coord}")
            self._continue_touch()
        elif not is_touched and not was_touched:
            pass
        else:
            assert False, "unreachable"

        self._last_coord = coord
        self._was_touched = is_touched
Beispiel #24
0
    def __init__(self, constate,
                 schema: s_schema.Schema,
                 modaliases: immutables.Map,
                 config: immutables.Map, *,
                 implicit=True):

        self._constate = constate

        self._id = time.monotonic_ns()

        self._implicit = implicit

        self._stack = []

        # Save the very first state -- we can use it to rollback
        # the transaction completely.
        self._stack.append(
            TransactionState(
                id=self._id,
                name=None,
                schema=schema,
                modaliases=modaliases,
                config=config))

        # The top of the stack is the "current" state.
        self._stack.append(
            TransactionState(
                id=self._id,
                name=None,
                schema=schema,
                modaliases=modaliases,
                config=config))
Beispiel #25
0
def mobile_classify(options):
	print("MOBIL CLASS")
	pic_source = base64.b64decode(options['pic'])
	
	model=str(options["model"])
	
	#create a client to make requests to ml api
	http = urllib3.PoolManager()
	bytesIO = BytesIO()
	bytesIO.write(pic_source)
	bytesIO.seek(0)
	s3 = boto3.resource("s3")
	bucket_name = "machine-learning2019"

	now = str(time.monotonic_ns())
	pic_path = "{}.dir/unannotated_images/{}.jpeg".format(model, now)
	
	#upload the file that was passed to the S3 bucket
	s3 = boto3.resource("s3")
	bucket_name = "machine-learning2019"
	s3.meta.client.upload_fileobj(bytesIO, bucket_name, pic_path)
	#s3.meta.client.upload_file(pic_source, bucket_name, pic_path)
	print("MOBILE CLASS UPLAODED IMAGE TO S3")
	#TODO replace with actual request
	r = http.request('GET', 'ec2-3-18-109-238.us-east-2.compute.amazonaws.com:3000/predict?modelName={}&imageURL={}'.format(model, pic_path))
	#resp stores the classifier prediction
	resp = json.loads(r.data.decode('utf-8'))
	return constants.respond(statusCode="200", res=resp)
Beispiel #26
0
    def _check_zoom_in(self):
        """Check if recent data warrants zooming in on y axis scale based on checking
           minimum and maximum times which are recorded in approximate 1 second buckets.
           Returns two element tuple with (min, max) or empty tuple for no zoom required.
           Caution is required with min == max."""
        start_idx = len(self._data_start_ns) - self.ZOOM_IN_TIME
        if start_idx < 0:
            return ()

        now_ns = time.monotonic_ns()
        if now_ns < self._plot_lastzoom_ns + self.ZOOM_IN_CHECK_TIME_NS:
            return ()

        recent_min = min(self._data_mins[start_idx:])
        recent_max = max(self._data_maxs[start_idx:])
        recent_range = recent_max - recent_min
        headroom = recent_range * self.ZOOM_HEADROOM

        # No zoom if the range of data is near the plot range
        if (self._plot_min > recent_min - headroom
                and self._plot_max < recent_max + headroom):
            return ()

        new_plot_min = max(recent_min - headroom, self._abs_min)
        new_plot_max = min(recent_max + headroom, self._abs_max)
        return (new_plot_min, new_plot_max)
Beispiel #27
0
def classify(options):
	#options:
	#	picture:(str) a picture to classify. path to file
	#	model: (str) the model to classify with
	#TODO assert these are proper types
	pic_source = str(options["pic"])
	model=str(options["model"])
	
	#create a client to make requests to ml api
	http = urllib3.PoolManager()
	bytesIO = BytesIO()
	bytesIO.write(http.request("GET", pic_source).data)
	bytesIO.seek(0)
	s3 = boto3.resource("s3")
	bucket_name = "machine-learning2019"

	now = str(time.monotonic_ns())
	pic_path = "{}.dir/unannotated_images/{}.jpeg".format(model, now)
	
	#upload the file that was passed to the S3 bucket
	s3 = boto3.resource("s3")
	bucket_name = "machine-learning2019"
	s3.meta.client.upload_fileobj(bytesIO, bucket_name, pic_path)
	#s3.meta.client.upload_file(pic_source, bucket_name, pic_path)
	
	#TODO replace with actual request
	r = http.request('GET', 'ec2-3-18-109-238.us-east-2.compute.amazonaws.com:3000/predict?modelName={}&imageURL={}'.format(model, pic_path))
	#resp stores the classifier prediction
	resp = json.loads(r.data.decode('utf-8'))
	return constants.respond(statusCode="200", res=resp)
Beispiel #28
0
def verify(ms_s, code):
    if not isinstance(ms_s, str) or not isinstance(code, str):
        return False
    ret = False
    lock = filelock.FileLock('tmp/.captcha_lock', timeout=5)
    try:
        with lock:
            if not os.path.exists('tmp/.captcha'):
                return False

            with open('tmp/.captcha', 'r') as file:
                cl_ori = json.loads(file.read())

            now_s = str(time.monotonic_ns())[:-6]
            since = max(int(now_s) - gconf['captcha']['timeout'] * 1000, 0)
            cl = dict(
                filter(lambda elem: int(elem[0]) >= since, cl_ori.items()))
            if ms_s in cl:
                if cl[ms_s] == code:
                    ret = True
                del cl[ms_s]
            if len(cl) != len(cl_ori):
                with open('tmp/.captcha', 'w') as file:
                    file.write(
                        json.dumps(cl,
                                   indent=2,
                                   ensure_ascii=False,
                                   sort_keys=False))
        return ret

    except filelock.Timeout:
        print(f'verify captcha failed: filelock.Timeout', file=sys.stderr)
        return None
Beispiel #29
0
def get():
    ms_s = str(time.monotonic_ns())[:-6]
    code = ''.join(
        random.choice('02345689') for i in range(gconf['captcha']['length']))

    ic = ImageCaptcha()
    img = ic.generate(code, 'jpeg').read()

    dat = {'id': ms_s, 'img': base64.b64encode(img).decode('ascii')}

    lock = filelock.FileLock('tmp/.captcha_lock', timeout=5)

    try:
        with lock:
            if os.path.exists('tmp/.captcha'):
                with open('tmp/.captcha', 'r') as file:
                    cl = json.loads(file.read())
            else:
                cl = {}
            since = max(int(ms_s) - gconf['captcha']['timeout'] * 1000, 0)
            cl = dict(filter(lambda elem: int(elem[0]) >= since, cl.items()))
            cl[ms_s] = code
            with open('tmp/.captcha', 'w') as file:
                file.write(
                    json.dumps(cl,
                               indent=2,
                               ensure_ascii=False,
                               sort_keys=False))

    except filelock.Timeout:
        print(f'create captcha failed: filelock.Timeout', file=sys.stderr)
        return None
    return dat
Beispiel #30
0
def measure(maze):
    sm = 0
    for i in range(ITERATE):
        print(i)
        start_time = time.monotonic_ns()
        a = (random.randint(0, ROW - 1), random.randint(0, ROW - 1))
        b = (random.randint(0, ROW - 1), random.randint(0, ROW - 1))
        while maze[a[0]][a[1]] == 1 or maze[b[0]][b[1]] == 1:
            a = (random.randint(0, ROW - 1), random.randint(0, ROW - 1))
            b = (random.randint(0, ROW - 1), random.randint(0, ROW - 1))
        print(a, b, maze[a[0]][a[1]], maze[b[0]][b[1]])
        astar(maze, a, b)
        end_time = time.monotonic_ns()
        sm += end_time - start_time
    sm = sm / ITERATE
    return sm
Beispiel #31
0
    def test_time_ns_type(self):
        def check_ns(sec, ns):
            self.assertIsInstance(ns, int)

            sec_ns = int(sec * 1e9)
            # tolerate a difference of 50 ms
            self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))

        check_ns(time.time(),
                 time.time_ns())
        check_ns(time.monotonic(),
                 time.monotonic_ns())
        check_ns(time.perf_counter(),
                 time.perf_counter_ns())
        check_ns(time.process_time(),
                 time.process_time_ns())

        if hasattr(time, 'clock_gettime'):
            check_ns(time.clock_gettime(time.CLOCK_REALTIME),
                     time.clock_gettime_ns(time.CLOCK_REALTIME))