예제 #1
0
    def __init__(self, name, logger):
        super(ChatService, self).__init__()

        self._name = name
        self._logger = logger

        self._connected = Event("connected")
        self._messageReceived = Event("messageReceived")
예제 #2
0
    def __init__(self, chatService, chatServer):
        super(ChatChannel, self).__init__()

        self._chatService = chatService
        self._chatServer = chatServer

        self._messageReceived = Event("messageReceived")
예제 #3
0
    def __init__(self):
        super(TerminalEmulatedProcess, self).__init__()

        self._terminated = Event("terminated")
        self._screenUpdated = Event("screenUpdated")

        self._logger = None

        self._terminalEmulator = TerminalEmulator()
        self._terminalEmulator.resize(80, 24)

        self.masterPty = None
        self.slavePty = None
        self.process = None

        self.outputThread = None
예제 #4
0
    def test_connects_directly(self, sleep):
        connector = Mock()
        data_transport = DataTransport(connector)
        data_transport.send = Mock()
        data_transport.deliver_event(Event("test"))

        connector.connect.assert_called_once()
        assert sleep.call_count == 0
예제 #5
0
    def run(self, city):
        self.household.humans.add(self)
        while True:
            if self.name == 1:
                # to check the source of randomness
                if self.last_state != self.state:
                    print(self.env.timestamp, self.state)
                    self.last_state = self.state

            if self.is_infectious and self.has_logged_symptoms is False:
                Event.log_symptom_start(self, self.env.timestamp, True)
                self.has_logged_symptoms = True

            if self.is_infectious and self.env.timestamp - self.infection_timestamp > datetime.timedelta(
                    days=TEST_DAYS):
                Event.log_test(self, self.env.timestamp, True)
                assert self.has_logged_symptoms is True

            if self.is_infectious and self.env.timestamp - self.infection_timestamp >= datetime.timedelta(
                    days=AVG_RECOVERY_DAYS):
                # self.recovered_timestamp = self.env.timestamp
                self.recovered_timestamp = datetime.datetime.max
                self.update_r(self.env.timestamp - self.infection_timestamp)
                self.infection_timestamp = None
                yield self.env.timeout(np.inf)
                # yield self.env.process(self.at(self.grave, np.inf))

            # Mobility
            hour = self.env.hour_of_day()
            if not WORK_FROM_HOME and not self.env.is_weekend(
            ) and hour == self.work_start_hour:
                yield self.env.process(self.excursion(city, "work"))

            elif hour == self.shopping_hours and self.env.day_of_week(
            ) == self.shopping_days:
                yield self.env.process(self.excursion(city, "shopping"))

            elif hour == self.exercise_hours and self.env.day_of_week(
            ) == self.exercise_days:
                yield self.env.process(self.excursion(city, "exercise"))

            elif self.rng.random() < 0.05 and self.env.is_weekend():
                yield self.env.process(self.excursion(city, "leisure"))

            yield self.env.process(self.at(self.household, 60))
예제 #6
0
    def test_connects_after_retries(self, sleep):
        data_transport = DataTransport(
            FailsAfterNTimes(2, with_exception=ConnectionError))
        data_transport.send = Mock()
        data_transport.deliver_event(Event("test"))

        data_transport.send.assert_called_once_with("decoded test")

        assert (sleep.call_count == DataTransport._RETRY_TIMES -
                1), sleep.call_count
예제 #7
0
    def at(self, location, duration):
        if self.name == 1:
            # print(self, self.env.timestamp.strftime("%b %d, %H %M"), self.location)
            # print(self.env.timestamp.strftime("%b %d, %H %M"), self.location._name, "-->", location._name, duration)
            pass

        self.location = location
        location.humans.add(self)
        self.leaving_time = duration + self.env.now
        self.start_time = self.env.now

        # Report all the encounters
        for h in location.humans:
            if h == self or self.location.location_type == 'household':
                continue

            distance = self.rng.randint(50, 1000)
            t_near = min(self.leaving_time, h.leaving_time) - max(
                self.start_time, h.start_time)
            is_exposed = False
            if h.is_infectious and distance <= 200 and t_near * TICK_MINUTE > 2:
                if self.is_susceptible:
                    is_exposed = True
                    h.n_infectious_contacts += 1
                    Event.log_exposed(self, self.env.timestamp)

            if self.is_susceptible and is_exposed:
                self.infection_timestamp = self.env.timestamp

            Event.log_encounter(
                self,
                h,
                location=location,
                duration=t_near,
                distance=distance,
                # cm  #TODO: prop to Area and inv. prop to capacity
                time=self.env.timestamp,
                # latent={"infected":self.is_exposed}
            )

        yield self.env.timeout(duration / TICK_MINUTE)
        location.humans.remove(self)
예제 #8
0
    def test_connection_error(self, sleep):
        data_transport = DataTransport(
            Mock(connect=Mock(side_effect=ConnectionError)))

        self.assertRaisesRegex(
            ConnectionError,
            "Couldn't connect after \d+ times",
            data_transport.deliver_event,
            Event("connection error"),
        )
        assert sleep.call_count == DataTransport._RETRY_TIMES
 def deliver_event(self, event: Event):
     try:
         self.connect()
         data = event.decode()
         self.send(data)
     except ConnectionError as e:
         logger.info("connection error detected: %s", e)
         raise
     except ValueError as e:
         logger.error("%r contains incorrect data: %s", event, e)
         raise
예제 #10
0
    def __init__(self):
        super(ChatBot, self).__init__()

        self._connected = Event("connected")
        self._messageReceived = Event("messageReceived")

        self.config = None

        self._running = False
        self._eventLoop = None

        self.logger = MulticastLogger()
        self.logger.add(ConsoleLogger())
        self.channelLoggers = []

        self.plugins = {}
        self._commandSystem = CommandSystem(self.logger)

        self.chatServiceFactories = {}
        self.chatServiceFactories["Discord"] = DiscordChatService
        self.chatServiceFactories["Slack"] = SlackChatService

        self._chatServices = {}
예제 #11
0
    def __init__(self,
                 size=Config.PyGR_SIZE,
                 deviceID=0,
                 position='tl',
                 verbose=False):
        self.size = size
        self.deviceID = deviceID
        self.capture = Capture(deviceID=self.deviceID)
        self.position = position
        self.event = Event(Event.NONE)
        self.image = None

        self.verbose = verbose
        print(self.verbose)
        self.roi = _get_roi(size=self.size, ratio=0.65, position=position)

        self.thread = threading.Thread(target=self._showloop)
예제 #12
0
def grdetect(array, verbose=False):
    event = Event(Event.NONE)

    copy = array.copy()

    array = _remove_background(array)  # 移除背景, add by wnavy
    '''
    gray       = Util.to_grayscale(array) # 转化为灰度图像
    blur       = cv2.GaussianBlur(gray, ksize = _DEFAULT_GAUSSIAN_BLUR_KERNEL, sigmaX = 0) # 高斯滤波
    _, thresh  = cv2.threshold(blur, 0, 255, _DEFAULT_THRESHOLD_TYPE) # 图像二值化
    '''
    thresh = _bodyskin_detetc(array)

    if verbose:
        cv2.imshow('pygr.HoverPad.roi.threshold', thresh)

    contours = _get_contours(thresh.copy())
    largecont = max(contours, key=lambda contour: cv2.contourArea(contour))

    if verbose:
        roi = cv2.boundingRect(largecont)
        copy = Util.mount_roi(copy, roi, color=_COLOR_RED)

    convexHull = cv2.convexHull(largecont)

    if verbose:
        _draw_contours(copy, contours, -1, _COLOR_RED, 0)
        _draw_contours(copy, [largecont], 0, _COLOR_GREEN, 0)
        _draw_contours(copy, [convexHull], 0, _COLOR_GREEN, 0)

    hull = cv2.convexHull(largecont, returnPoints=False)
    defects = cv2.convexityDefects(largecont, hull)

    if defects is not None:
        copy, ndefects = _get_defects_count(copy,
                                            largecont,
                                            defects,
                                            verbose=verbose)
        if ndefects == 0:
            copy, tip = _get_tip_position(copy, largecont, verbose=verbose)

            event.setTip(tip)
            # TODO: check for a single finger.
            # event.setType(Event.ROCK)
            event.setType(Event.ZERO)
        elif ndefects == 1:
            # TODO: check for an Event.LIZARD
            # event.setType(Event.SCISSOR)
            event.setType(Event.TWO)
        elif ndefects == 2:
            # event.setType(Event.SPOCK)
            event.setType(Event.THREE)
        elif ndefects == 3:
            event.setType(Event.FOUR)
        elif ndefects == 4:
            # event.setType(Event.PAPER)
            event.setType(Event.FIVE)
    if verbose:
        cv2.imshow('pygr.HoverPad.roi', copy)

    if verbose:
        return copy, event
    else:
        return event
예제 #13
0
 def send(self, event: Event):
     try:
         return self.connection.send(event.decode())
     except ValueError as e:
         logger.error("%r contains incorrect data: %s", event, e)
         raise