Beispiel #1
0
 def test_when_set_packet_id_should_store_id(self):
     # Given
     event = Event("    A", 1, 2, 3, 4, 5)
     # When
     event.set_packet_id(11)
     # Then
     self.assertEqual(event.get_packet_id(), 11)
Beispiel #2
0
 def setUp(self):
     species = []
     self.volume = 1000
     for species_name, state in Event.registered_species:
         fraction = 1 / len(Event.registered_species)
         species.append((species_name, state, fraction * self.volume))
     self.event = Event(species)
Beispiel #3
0
 def test_when_get_event_should_return_all_events_of_same_type(self):
     # Given
     e = Event("LOGAA", 1, 2, 3, 4, 5)
     e_2 = Event("LOGAA", 1, 2, 3, 4, 5)
     e_3 = Event("LOGAB", 1, 2, 3, 4, 5)
     c = Channel("c", [e], 12)
     # When
     c.add_events([e_2, e_3])
     # Then
     exp = c.get_event("A")
     self.assertEqual(exp, [e, e_2])
Beispiel #4
0
 def test_when_get_existed_event_count_should_return_log_count(self):
     # Given
     e1 = Event("LOGAA", 2, 1, 1, 1, 1)
     e2 = Event("LOGAB", 3, 1, 1, 1, 1)
     p = Packet("receiver", "    sender", [e1, e2])
     # When
     event_a_log_count = p.get_event_count("A")
     event_b_log_count = p.get_event_count("B")
     # Then
     self.assertEqual(event_a_log_count, 2)
     self.assertEqual(event_b_log_count, 3)
Beispiel #5
0
    def test_a_listener_is_notified_when_an_event_is_raised(self):
        called = False

        def listener():
            nonlocal called
            called = True

        event = Event()
        event.connect(listener)
        event.fire()
        self.assertTrue(called)
Beispiel #6
0
 def test_when_get_dict_should_return_event_dict(self):
     # Given
     event = Event("    A", 1, 2, 3, 4, 5)
     # When
     event_dict = event.get_dict()
     # Then
     expect_dict = {
         "type": "A",
         "log_count": 1,
         "passed_time": 2,
         "min": 3,
         "max": 4,
         "avg": 5,
     }
     self.assertEqual(expect_dict, event_dict)
Beispiel #7
0
    def test_ignore_unknown_event_types(self):
        # given
        event = Event({
            'api_app_id': 'api_app_id',
            'authed_users': ['U75KAHN4T'],
            "event": {
                "type": "reaction_added",
                "user": "******",
                "item": {
                    "type": "message",
                    "channel": "C76NQ1WQP",
                    "ts": "1506283080.000045"
                },
                "reaction": "neutral_face",
                "item_user": "******",
                "event_ts": "1506283351.000047"
            },
            'event_id': 'event_id',
            'event_time': 1506187774,
            'team_id': 'team_id',
            'token': 'token',
            'type': 'event_callback'
        })
        # when
        self.bot.handle_event(event)

        # then
        self.slack_client.post_message.assert_not_called()
def retrieve_event(response):
    '''Given an Event from an Eventbrite API response, create an Event object'''
    format_id = response["format"]["id"] if response[
        "format"] is not None else None
    price = 0
    if "ticket_availability" in response:
        if "minimum_ticket_price" in response[
                "ticket_availability"] and response["ticket_availability"][
                    "minimum_ticket_price"] is not None:
            price = float(response["ticket_availability"]
                          ["minimum_ticket_price"]["major_value"])
    return Event(
        event_id=f"EVENTBRITE-{response['url']}",
        url=response["url"],
        start_time=datetime.strptime(response["start"]["utc"],
                                     "%Y-%m-%dT%H:%M:%SZ").timestamp(),
        end_time=datetime.strptime(response["end"]["utc"],
                                   "%Y-%m-%dT%H:%M:%SZ").timestamp(),
        latitude=float(response["venue"]["latitude"])
        if response["venue"] is not None else "",
        longitude=float(response["venue"]["longitude"])
        if response["venue"] is not None else "",
        name=response["name"]["text"],
        organiser=response["organizer"]["name"],
        price=price,
        is_online=response["online_event"] or is_online(response),
        summary=response["summary"],
        description_html=response["description"]["html"],
        tags=get_tags(response["category_id"], format_id),
        image=response["logo"]["original"]["url"]
        if response.get("logo") is not None else "")
Beispiel #9
0
    def _sjf_queue_process(self):
        """start a process with shortest job first scheduling"""
        if not self.process_queue.empty():
            # Do we need to preempt a process?
            if self.running_process:
                process = self.running_process
                remain = process.get_remaining()
                next_process = self.process_queue.queue[0][1]
                if next_process.run_time - next_process.used < remain:
                    logging.debug("%s: offloading process: %s",
                                  self.current_time, process)
                    self.put_process(process)
                    self._start_process()
            else:
                self._start_process()

        # Check if we need to queue a completion event
        if self.running_process:
            remain = self.running_process.get_remaining()
            estimate = self.current_time.shift(seconds=remain)
            if not self.event_queue.empty():
                next_time = self.event_queue.queue[0].created_at
                if not estimate < next_time:
                    return

            self.event_queue.put(
                Event(created_at=estimate, event_type=EVENT_TYPES['COMPLETE']))
Beispiel #10
0
    def get_events(self):
        """
        See EventSource.get_events
        """

        entries_class = "eventBox"
        date_class = "date"
        location_class = "venue"

        entries = self.html.find_all(name=Tags.DIV.value,
                                     attrs={Attrs.CLASS: entries_class})

        for entry in entries:
            event = Event(title=entry.find(Tags.H3.value).contents[0].text,
                          date=self._convert_date(
                              entry.find(name=Tags.H4.value,
                                         attrs={
                                             Attrs.CLASS: date_class
                                         }).contents[0]),
                          link="https://www.nienvironmentlink.org/" +
                          entry.find(name=Tags.A.value).get(Attrs.HREF),
                          scope=EventScope.NATIONAL,
                          location=entry.find(name=Tags.H4.value,
                                              attrs={
                                                  Attrs.CLASS: location_class
                                              }).contents[0])
            self.events.append(event)

        return self.events
Beispiel #11
0
 def _rr_queue_process(self):
     """start a process with round robin scheduling"""
     if not self.running_process and not self.process_queue.empty():
         self._start_process()
         remain = self.running_process.get_remaining()
         if remain < self.config['quantum']:
             logging.debug('scheduling RR completion: %s',
                           self.running_process)
             self.event_queue.put(
                 Event(created_at=self.current_time.shift(seconds=remain),
                       event_type=EVENT_TYPES['COMPLETE']))
         else:
             self.event_queue.put(
                 Event(created_at=self.current_time.shift(
                     seconds=self.config['quantum']),
                       event_type=EVENT_TYPES['SWITCH']))
Beispiel #12
0
def normalise_response(response, category_id):
    start_time = int(response["time"])
    duration = int(response["duration"]
                   ) if "duration" in response else THREE_HOURS_IN_SECONDS
    tags = get_activity_tags(response, category_id)
    image = ""
    if "photo_url" in response:
        image = re.sub("global", "highres", response["photo_url"])
    return Event(
        event_id=f"MEETUP-{response['event_url']}",
        url=response['event_url'],
        start_time=start_time / 1000,
        end_time=(start_time + duration) / 1000,
        latitude=float(response["venue"]["lat"])
        if "venue" in response else "",
        longitude=float(response["venue"]["lon"])
        if "venue" in response else "",
        name=response["name"].strip(),
        organiser=response["group"]["name"],
        price=float(response["fee"]["amount"]) if "fee" in response else 0,
        is_online=is_event_online(response),
        summary="",
        description_html=response["description"]
        if "description" in response else "",
        tags=tags,
        image=image)
Beispiel #13
0
    def check_for_event(self):
        """
        check_for_event
        Analyzes sensor data, and creates a new Event object if necessary

        Event "one" Conditions:
        - humidity must have been increasing for specified period of time
        - humidity value must exceed humidity threshold
        - an event must not have been fired within specified time.

        Event "changed" conditions
        - humidity less than the "dry" humidity threshold.
        - humidity must have been decreasing for specified period of time.
        - must have been long enough since last event was fired.
        """
        if self.sensor_data.length() < MIN_DATA_POINTS:
            return

        last_data = self.sensor_data.peek()
        current_humidity = last_data.humidity
        average_humidity = self.sensor_data.get_average_humidity()
        percent_diff_from_average = (
            abs(current_humidity - average_humidity) /
            ((current_humidity + average_humidity) / 2)) * 100  # pylint: disable=C0301
        long_enough_since_last_event = self.events.time_since_last_dirty_event(
        ) > MIN_TIME_BETWEEN_EVENTS  # pylint: disable=C0301

        if long_enough_since_last_event and current_humidity > HUMIDITY_THRESHOLD and current_humidity > average_humidity and percent_diff_from_average > MIN_PERCENT_DIFFERENCE:  # pylint: disable=C0301
            event = Event()
            self.events.push(event)
            self.bluetooth_server.send_event_notification(event)
Beispiel #14
0
 def _fcfs_queue_process(self):
     """start a process with first come first served scheduling"""
     if not self.running_process and not self.process_queue.empty():
         self._start_process()
         # Queue completion event
         create = self.current_time.shift(
             seconds=self.running_process.run_time)
         self.event_queue.put(
             Event(created_at=create, event_type=EVENT_TYPES['COMPLETE']))
def event_from_json(json_string):
    json_object = json.loads(json_string)
    __validate_json_object(json_object)
    return Event(
        event_id=json_object[EVENT_ID],
        timestamp=json_object[TIMESTAMP],
        event_type=json_object[EVENT_TYPE],
        details=json_object[DETAILS],
    )
Beispiel #16
0
    def create_event(self, activate_at: Arrow, p_id: int) -> Event:
        """Create a new process"""
        process = Process(process_id=p_id,
                          run_time=rand_exp_float(self.config['burst_lambda']),
                          created_at=activate_at)

        return Event(created_at=activate_at,
                     event_type=EVENT_TYPES['NEW'],
                     process=process)
Beispiel #17
0
 def test_when_update_map_with_new_channels_should_return_true_for_update_map(
         self):
     # Given
     event = Event("    " + PACKET_PUSHED, 1, 1, 1, 1, 1)
     p = Packet("A", "    B", [event])
     # When
     self.cm.add_packet(p)
     update_map = self.cm.should_update_map()
     # Then
     self.assertTrue(update_map)
Beispiel #18
0
 def test_when_add_packet_with_pushed_events_should_store_sender_n_receiver(
         self):
     # Given
     event = Event("    " + PACKET_PUSHED, 1, 1, 1, 1, 1)
     p = Packet("A", "    B", [event])
     # When
     self.cm.add_packet(p)
     # Then
     channels = [c.get_name() for c in self.cm.get_channels()]
     self.assertEqual(channels, ['A', 'B'])
Beispiel #19
0
    def __get_channel(values):
        events = []
        for (event_type, count) in values:
            for i in range(0, count):
                e = Event("LOGA" + event_type, 1, 1, 1, 1, 1)
                events.append(e)

        channel = Channel("channel", events, 11)

        return channel
def event_from_json_object(json_object):
    __validate_json_object(json_object)
    if json_object[EVENT_TYPE] == 'error_event' and SESSION_ID not in json_object:
        return Event(
            event_id = json_object[EVENT_ID],
            timestamp = __date_checker(json_object[TIMESTAMP]),
            event_type = json_object[EVENT_TYPE],
            originating_service = json_object[ORIGINATING_SERVICE],
            session_id = '',
            details = json_object[DETAILS],
        )
    return Event(
        event_id = json_object[EVENT_ID],
        timestamp= __date_checker(json_object[TIMESTAMP]),
        event_type = json_object[EVENT_TYPE],
        originating_service = json_object[ORIGINATING_SERVICE],
        session_id = json_object[SESSION_ID],
        details = json_object[DETAILS],
    )
Beispiel #21
0
 def clear_event(self, e_id):
     """
     clear_event
     Removes event from cache
     """
     # Find & remove the existing event if it exists.
     self.events.remove_event(e_id)
     # Generate the 'change' event, and pass to client.
     new_event = Event(EventType.changed)
     self.events.push(new_event)
     self.bluetooth_server.send_event_notification(new_event)
Beispiel #22
0
 def test_when_add_packet_with_pushed_events_should_create_channels_map(
         self):
     # Given
     event = Event("    " + PACKET_PUSHED, 1, 1, 1, 1, 1)
     p = Packet("A", "    B", [event])
     # When
     self.cm.add_packet(p)
     channels, channels_map = self.cm.get_channels_map()
     # Then
     self.assertEqual(channels, ['A', 'B'])
     self.assertEqual(channels_map, [(1, 0)])
Beispiel #23
0
def parseVenueToEvent(venue, category):
    time = ""
    start_time = 0
    end_time = 0
    url = ""
    description = ""
    # The four square API only has a price tier, so the price will remain an arbitrary value.
    price = 0
    # The price_tier values are in the range (1-4) where '1' is for the pocket friendly places and '4' is for the most expensive places.
    price_tier = 0
    is_online = False
    rating = 0
    image = ""
    id = f"FOURSQUARE-{venue['id']}"

    premium_details = get_event_details(venue["id"])
    if premium_details is not None:
        venue = premium_details

    if 'hours' in venue:
        time = venue['hours']['timeframes'][0]['open'][0]
        start_time = get_time(time['start'])
        end_time = get_time(time['end'])
        line = str(time[0]['open'][0]['renderedTime'])
        line = line.split("–")
        start_time = time_to_unix_time(line[0])
        end_time = time_to_unix_time(line[1])
    if 'url' in venue:
        url = venue['url']
    if 'description' in venue:
        description = venue['description']
    if 'price' in venue:
        price_tier = venue['price']['tier']
    if 'photos' in venue:
        if 'groups' in venue['photos'] and len(venue['photos']['groups']) != 0:
            group = venue['photos']['groups'][0]
            if 'items' in group:
                item = group['items'][0]
                image = item['prefix'] + str(item['width']) + 'x' + str(
                    item['height']) + item['suffix']
    if 'rating' in venue:
        rating = venue['rating']

    event_obj = Event(id, url, start_time, end_time,
                      float(venue['location']['lat']),
                      float(venue['location']['lng']), venue['name'], "",
                      price, is_online, description, "",
                      CATEGORIES_TAGS.get(CATEGORIES.get(category)),
                      price_tier, rating, image)

    return event_obj
def parseInfoToEvent(info, classification):
    start_time = 0.0
    end_time = 0.0

    url = ""
    summary = ""
    organiser = ""
    tags = CLASSIFICATIONS.get(classification)
    latitude = 0.0
    longitude = 0.0
    is_online = True
    rating = 0
    price = 0
    # The ticket master API only has a price, so the price_tier will remain an arbitrary value.
    price_tier = 0
    image = ""

    if info['dates']['status']['code'] == 'cancelled':
        is_online = False
    if 'dates' in info:
        if 'start' in info['dates']:
            if 'dateTime' in info['dates']['start']:
                dt = datetime.datetime.strptime(
                    info['dates']['start']['dateTime'], '%Y-%m-%dT%H:%M:%SZ')
                start_time = dt.timestamp()
                end_time = (dt + datetime.timedelta(hours=4)).timestamp()

    if 'location' in info['_embedded']['venues'][0]:
        latitude = float(
            info['_embedded']['venues'][0]['location']['latitude'])
        longitude = float(
            info['_embedded']['venues'][0]['location']['longitude'])
    if 'info' in info:
        summary = info['info']
    if 'promoter' in info:
        organiser = info['promoter']['name']
    if 'url' in info:
        url = info['url']
    if 'images' in info:
        if 'url' in info['images'][0]:
            image = info['images'][0]['url']
    if 'priceRanges' in info:
        price = info['priceRanges'][0]['min']

    event_info = Event(info['id'], url, start_time, end_time, latitude,
                       longitude, info['name'], organiser, price, is_online,
                       summary, "", tags, price_tier, rating, image)

    return event_info
    def test_check_if_message_is_private(self):
        # given
        event = Event({
            'api_app_id': 'api_app_id',
            'authed_users': ['U75KAHN4T'],
            'event': {
                'channel': 'D75RLTNNR',
                'event_ts': '1506187774.000063',
                'text': 'direct message on pric',
                'ts': '1506187774.000063',
                'type': 'message',
                'user': '******'
            },
            'event_id': 'event_id',
            'event_time': 1506187774,
            'team_id': 'team_id',
            'token': 'token',
            'type': 'event_callback'
        })
        # when
        is_private_message = event.is_private_message()

        # then
        self.assertTrue(is_private_message)
Beispiel #26
0
 def test_when_init_should_store_fields(self):
     # Given
     event = Event("    A", 1, 2, 3, 4, 5)
     # When
     e_type = event.get_type()
     e_log_count = event.get_log_count()
     e_passed_time = event.get_passed_time()
     e_min_val = event.get_min()
     e_max_val = event.get_max()
     e_avg_val = event.get_avg()
     # Then
     self.assertEqual(e_type, "A")
     self.assertEqual(e_log_count, 1)
     self.assertEqual(e_passed_time, 2)
     self.assertEqual(e_min_val, 3)
     self.assertEqual(e_max_val, 4)
     self.assertEqual(e_avg_val, 5)
 def add_event(self, user_id, summary, location, description,
               start_datetime, end_datetime, timezone, attendee_studio,
               attendee_user):
     """ Add Event to DB """
     if self.find_event(description) is None:
         event = Event(user_id=user_id,
                       summary=summary,
                       location=location,
                       description=description,
                       start_datetime=start_datetime,
                       end_datetime=end_datetime,
                       timezone=timezone,
                       attendee_studio=attendee_studio,
                       attendee_user=attendee_user)
         self.database.add_event(event)
     print('Event added to DB @ Start time: ' + event.start_datetime)
Beispiel #28
0
 def test_when_set_id_for_events_should_stores_in_events(self):
     # Given
     e1 = Event("LOGAA", 1, 1, 1, 1, 1)
     e2 = Event("LOGAB", 1, 1, 1, 1, 1)
     p = Packet("receiver", "    sender", [e1, e2])
     # When
     p.set_id(11)
     p.set_id_for_events()
     # Then
     self.assertEqual(e1.get_packet_id(), 11)
     self.assertEqual(e2.get_packet_id(), 11)
Beispiel #29
0
    def __get_event(self, pos):
        """instantiating an event type

        Args:
            pos: The current position in the packet to start parsing from

        Returns:
            An event and the position where the process finished
        """

        event_type, pos = self.__get_keyword(pos)
        log_count, pos = self.__get_int_val(pos)
        time_passed, pos = self.__get_int_val(pos)
        min_val, pos = self.__get_float_val(pos)
        max_val, pos = self.__get_float_val(pos)
        avg_val, pos = self.__get_float_val(pos)

        return Event(event_type, log_count, time_passed, min_val, max_val,
                     avg_val), pos
Beispiel #30
0
def test_comparisson():
    event1 = Event(event_type=EventType.CHEGADA_1, name='event1')
    event2 = Event(event_type=EventType.CHEGADA_2, name='event2')
    event3 = Event(event_type=EventType.FIM_DE_SERVICO, name='event3')
    event5 = Event(event_type=EventType.CHEGADA_2, name='event5')
    event4 = Event(event_type=EventType.FIM_DE_SERVICO, name='event4')
    event6 = Event(event_type=EventType.CHEGADA_1, name='event6')

    events = [event1, event2, event3, event4, event5, event6]

    expected_sorted_events = [event6, event1, event2, event5, event3, event4]
    sorted_events = sorted(events)

    assert sorted_events == expected_sorted_events
    def get_events(self):
        """
        See EventSource.get_events
        """

        main_data_spec = "search-results"
        entries_class = "eds-media-card-content__content__principal"
        date_class = "eds-text-bs--fixed eds-text-color--grey-600 eds-l-mar-top-1"
        title_class = "eds-is-hidden-accessible"
        link_class = "eds-media-card-content__action-link"
        location_class = "card-text--truncated__one"

        entries = self.html.find(name=Tags.MAIN.value,
                                 attrs={
                                     Attrs.DATA_SPEC: main_data_spec
                                 }).find(name=Tags.DIV.value).find_all(
                                     name=Tags.DIV.value,
                                     attrs={Attrs.CLASS: entries_class})

        for entry in entries:
            location_div = entry.find(name=Tags.DIV.value,
                                      attrs={Attrs.CLASS: location_class})
            event = Event(title=entry.find(name=Tags.DIV.value,
                                           attrs={
                                               Attrs.CLASS: title_class
                                           }).contents[0],
                          date=self._convert_date(
                              entry.find(name=Tags.DIV.value,
                                         attrs={
                                             Attrs.CLASS: date_class
                                         }).contents[0]),
                          link=entry.find(name=Tags.A.value,
                                          attrs={
                                              Attrs.CLASS: link_class
                                          }).get(Attrs.HREF),
                          scope=EventScope.NATIONAL,
                          location=location_div.contents[0]
                          if location_div is not None else None)

            self.events.append(event)

        return self.events