예제 #1
0
def read():
    is_init = 0
    es = []
    for line in sys.stdin:
        if line == "0 END\n":
            break;
        if line[0] == '#' or line.isspace():
            continue;
        if is_init == False:
            np, na, tmax = map((lambda x: int(x)), line.split())
            is_init = True
            continue;
        t, action, aux1, aux2 = line.split()
        t = int(t)
        if action == "PROPOSE":
            # Recall: Proposers have positive int labels
            # and Acceptors have negative int labels.
            e = event.Event(t, [], [], int(aux1), int(aux2))
        elif action == "FAIL":
            if aux1 == "PROPOSER":
                e = event.Event(t, [int(aux2)], [], None, None)
            else:
                e = event.Event(t, [-int(aux2)], [], None, None)
        elif action == "RECOVER":
            if aux1 == "PROPOSER":
                e = event.Event(t, [], [int(aux2)], None, None)
            else:
                e = event.Event(t, [], [-int(aux2)], None, None)
        else:
            raise ValueError("my_read_in: Invalid Action")
        es.append(e)
        fs = event.shrink(es)
    return (np, na, tmax, fs)
예제 #2
0
    def change_content_expiry_time(self, content, time_cur):
        """
        mengubah content expiry time, misalnya saat upload content yang akan expire waktu content sedang diupload
        """
        content_id = content[0]
        time_lama = self.cache_entries[content_id][3]

        #hitung durasi dan time_baru
        #contoh: {0: [0, 5.0775931306168065, 499.0, 3600.0]}
        durasi = (content[2] * 8) / (self.dn_bw / 1000.0)
        time_baru = time_cur + durasi
        #print '--->', time_cur, content[0], content[1], content[2], self.dn_bw, durasi, time_baru, time_lama
        if time_baru > time_lama:
            new_expire_event = event.Event(event.REMOVE_CONTENT, time_baru,
                                           self, self.remove_content_extend,
                                           [content[0]])
            old_expire_event = event.Event(event.REMOVE_CONTENT, time_lama,
                                           self, self.remove_content,
                                           [content[0]])
            #print 'change',  new_expire_event, old_expire_event
            #update cache entries dng time baru.
            self.cache_entries[content_id][3] = time_baru
            return [new_expire_event, old_expire_event]
        else:
            return None, None
예제 #3
0
 def check_colls(self, saucer, sim_time):
     # Esta funcion retorna evento
     for i in self.p:
         '''
          Retorna tiempo de colision disco-disco con el disco que estamos
          analizando vs todos los demas que se encuentran en el sistema
         '''
         tiempo_colision = saucer.disk_coll(i)
         # Revisamos que la suma de tiempos tenga sentido para crear el evento
         if (self.t + tiempo_colision) <= sim_time:
             nuevo_evento = ev.Event(self.t + tiempo_colision, saucer, i)
             # Agregamos el evento a la cola
             pq.heappush(self.pq, nuevo_evento)
     '''
     Ahora tenemos que verificar el tiempo de colision de particula con
     las paredes del contenededor
     '''
     t1 = saucer.vert_wall_coll()
     t2 = saucer.horz_wall_coll()
     if (self.t + t1) <= sim_time:
         nuevo_evento = ev.Event(self.t + t1, saucer, None)
         pq.heappush(self.pq, nuevo_evento)
     if (self.t + t2) <= sim_time:
         nuevo_evento = ev.Event(self.t + t2, None, saucer)
         pq.heappush(self.pq, nuevo_evento)
예제 #4
0
    def test_constructor_with_event_list(self):
        e1 = e.Event(1)
        e2 = e.Event(1)
        e_list = [e1, e2]

        rec = er.EventRecord(e_list)
        assert rec.get_event_list() == [e1, e2]
예제 #5
0
	def test_init_and_basic_simulation (self):
		e = event_simulator.Event_Simulator({"h1":host.Host("h1",["l1"]),\
			"h2":host.Host("h2",["l1"]),\
			"f1":flow.Data_Source("f1", "h1", "h2", 20, 1)})
		
		self.assertEqual(e.get_current_time(), 0.0)
		self.assertFalse(e.are_flows_done())
		
		self.assertEqual(e.get_element("h1").get_id(), "h1")
		self.assertEqual(e.get_element("h2").get_id(), "h2")
		self.assertEqual(e.get_element("f1").get_id(), "f1")

		e.request_event(event.Event().set_completion_time(1.0))
		e.request_event(event.Event().set_completion_time(2.0))
		e.request_event(event.Event().set_completion_time(0.5))
		e.request_event(event.Event().set_completion_time(1.5))
		e.request_event(event.Event().set_completion_time(0.2))
		
		''' Now event heap should be ordered 0.2, 0.5, 1, 1.5, 2 '''
		
		e.run_next_event()
		self.assertEqual(e.get_current_time(), 0.2)
		e.run_next_event()
		self.assertEqual(e.get_current_time(), 0.5)
		e.run_next_event()
		self.assertEqual(e.get_current_time(), 1.0)				
		e.run_next_event()
		self.assertEqual(e.get_current_time(), 1.5)
		e.run_next_event()
		self.assertEqual(e.get_current_time(), 2.0)
예제 #6
0
    def request_to_peer(self, content_id, other, time_cur):
        """
        request ke peer lain (other)
        """
        #ambil content ke peer, hasilnya content
        content = other.get_content(content_id, time_cur)

        #ekstrak nilai panjang file
        #print content
        #contoh: {0: [0, 5.0775931306168065, 499.0, 3600.0]}
        durasi_up = (content[2] * 8) / (self.up_bw / 1000.0)

        #event utk upload done
        upload_done_event = event.Event(event.UPLOAD_DONE,
                                        time_cur + durasi_up, other,
                                        other.upload_done,
                                        [content_id, other.id, 'BUSY'])
        #print 'hhh', content
        new_remove_content_event, old_remove_content_event = other.change_content_expiry_time(
            content, time_cur)

        #hitung durasi
        #time_duration = (content[1]*8)/(other.up_bw/1000.0)
        durasi_down = (content[2] * 8) / (self.dn_bw / 1000.0)
        # tandai bahwa cache entry akan di-isi content sebenarnya
        self.cache_entries[content_id] = 1

        # bikin cache_content event:
        cache_event = event.Event(
            event.CACHE_CONTENT, time_cur + durasi_down, self,
            self.cache_content, [content_id, content, time_cur + durasi_down])

        #kembalikan event
        return [cache_event, upload_done_event,
                new_remove_content_event], [old_remove_content_event]
예제 #7
0
def makeEventList(y, label, delta=2):
    '''
    Consider y as a pandas series, returns a list of Events corresponding to
    the requested label (int), works for both smoothed and expected series
    Delta corresponds to the series frequency (in our basic case with random
    index, we consider this value to be equal to 2)
    '''
    listOfPosLabel = y[y == label]
    if len(listOfPosLabel) == 0:
        return []
    deltaBetweenPosLabel = listOfPosLabel.index[1:] - listOfPosLabel.index[:-1]
    deltaBetweenPosLabel.insert(0, datetime.timedelta(0))
    endOfEvents = np.where(
        deltaBetweenPosLabel > datetime.timedelta(minutes=delta))[0]
    indexBegin = 0
    eventList = []
    for i in endOfEvents:
        end = i
        eventList.append(
            evt.Event(listOfPosLabel.index[indexBegin],
                      listOfPosLabel.index[end]))
        indexBegin = i + 1
    eventList.append(
        evt.Event(listOfPosLabel.index[indexBegin], listOfPosLabel.index[-1]))
    return eventList
예제 #8
0
    def test_group_balancing(self):
        """
    --------------------------------------------------------------------------
    This is the test function you want to execute!!!!
    --------------------------------------------------------------------------
    """
        events = [
            e.Event(30, "max", ["nicolas", "max", "sandrina"]),
            e.Event(20, "max", ["nicolas", "max", "sandrina"]),
            e.Event(50, "max", ["nicolas", "max", "sandrina", "annika"]),
            e.Event(30, "nicolas", ["nicolas", "max", "annika"]),
            e.Event(60.50, "nicolas", ["nicolas", "max", "sandrina"]),
        ]

        transactions = [t.Transaction(2.0, "nicolas", "max")]

        # Add events
        for event in events:
            self.group.add_event(event)
            self.group.print_account_data()
            self.assertTrue(self.group.check_balance())
            print()

        for transaction in transactions:
            self.group.do_transaction(transaction)
            self.group.print_account_data()
            self.assertTrue(self.group.check_balance())
            print()

        # Calculate transactions needed to balance accounts
        self.group.calculate_balancing()

        return self.group
예제 #9
0
    def __received_Beacon__(self, beacon):
        # This function is called when the sensor received a Beacon frame from AP
        self.next_RAW_slot = None
        self.next_open_access = 0
        for each_RAW in beacon.RAWs:  # check whether the STA is in a certain RAW
            if ((each_RAW.paged_only and self in each_RAW.paged_STAs)
                    or (not each_RAW.paged_only and self in each_RAW.STAs)
                ):  # find the corresonding slot in this RAW for the sensor
                for each_slot in each_RAW.slot_list:
                    if self in each_slot.STAs:
                        self.next_RAW_slot = each_slot
                        break

        self.next_open_access = max(x.end_time for x in beacon.RAWs)
        self.status = "Sleep"
        if self.next_RAW_slot != None:  # wake up at certain time for this RAW
            new_event = event.Event("Wakeup for RAW",
                                    self.next_RAW_slot.start_time)
            new_event.register_device(self)
            self.timer.register_event(new_event)
            return True
        else:  # wake up while the channel is open for access
            new_event = event.Event("Wakeup during open access",
                                    self.next_open_access)
            new_event.register_device(self)
            self.timer.register_event(new_event)
            return False
예제 #10
0
 def wakeup_in_RAW(self):
     # This function is called when the sensor wakesup in a RAW
     # The first backoff timer need to be freezed and the second backoff timer with RAW_CWmin RAW_CWmax
     # Output:
     #	True--the sensor has something to report
     #	False--the sensor has nothing to report
     # print("wake up at "+str(self.timer.current_time))
     import random
     if not self.queue:  # if there is no packet buffering here
         return False
     assert self.next_RAW_slot.start_time == self.timer.current_time, "wake up in a wrong RAW"
     if self.next_RAW_slot.raw_type == "General":
         self.access_mode = "General Raw"
     elif self.next_RAW_slot.raw_type == "Trigger":
         self.access_mode = "Trigger Raw"
     # print(self.access_mode)
     self.status = "Listen"
     # use the new backoff timer value
     self.CWmin, self.CWmax = self.RAW_CWmin, self.RAW_CWmax
     self.freezed_backoff_timer = self.backoff_timer
     self.freezed_backoff_stage = self.backoff_stage
     self.backoff_timer = random.randint(0, self.CWmin - 1)
     self.backoff_stage = self.CWmin
     if self.channel_state == "Idle":  # start backoff after DIFS
         new_event = event.Event("IFS expire",
                                 self.timer.DIFS + self.timer.current_time)
         new_event.register_device(self)
         self.timer.register_event(new_event)
         self.IFS_expire_event = new_event
     new_event = event.Event("Endup RAW",
                             self.next_RAW_slot.end_time)  # end this RAW
     new_event.register_device(self)
     self.timer.register_event(new_event)
     return True
예제 #11
0
    def init_collision_time(self):
        """
        Initialise next collision time calculations for the first timestep.
        Calculate all possible ball pairs and their respective impending
        collision time.
        Collision times are recorded as an event.Event object.
        All collision events are added into a priority queue for high 
        efficiency selection of next event.
        The priority queue is a binary heap implemented using heapdict.heapdict
        The root node of this priority queue will always be the next immediate 
        event (it has the smallest time value).
        """
        # Calculating all collisions between balls
        for pair in self._pairs:  # All possible ball pair combinations
            ball_A = self._ball[pair[0]]
            ball_B = self._ball[pair[1]]
            dt = ball_A.time_to_collision(ball_B)
            if dt != np.inf:  # Selecting only valid solutions
                self._pq[ev.Event(
                    (pair[0], pair[1], ball_A._count, ball_B._count,
                     dt))] = dt  # Adding event to priority queue

        # Calculating collisions between balls and container
        for i, ball in enumerate(self._ball):
            dt = ball.time_to_collision(self._container)
            if dt != np.inf:
                self._pq[ev.Event((i, self._N_ball, ball._count, -1, dt))] = dt
예제 #12
0
 def __init__(self):
     "Create a new Bitcoin client class."
     self.setup_config()
     self.setup_rpc()
     self.on_transaction = event.Event()
     self.on_block = event.Event()
     self.setup_polling()
예제 #13
0
def main():
	#Constructor test
	wu1 = imp.Wuubern(3,0)
	wu2 = imp.Wuubern(3,1)
	wu1.printAll()
	wu2.printAll()

	#insert event at wu1
	wu1.insert(e.Event("res_pend", 1, 0))
	wu1.printAll()

	#insert 2 events at wu2
	wu2.insert(e.Event("res_pend", 1, 1))
	wu2.insert(e.Event("res_conf", 2, 1))
	wu2.printAll()

	#send of message from wu2 to wu1
	np, oMC = wu2.send(wu1.mID)
	wu1.receive(oMC, wu2.mID, np)

	print("HERE")
	wu1.printAll()
	wu2.printAll()

	wu3 = imp.Wuubern(3,2)
	np, oMC = wu1.send(wu3.mID)
	wu3.receive(oMC, wu1.mID, np)
	wu3.printAll()

	ev = e.Event("res_pend", 1, 0)
	print("EHERE")

	print(ev)
    def createTestEvents(self):
        """ Create a list of test event definitions

        In this method 30 events are defined to be checked against the video material.
        These are based on the Event class and are defined based on screenshots of GUI
        states. The examples below are all for Android 8 Oreo in FullHD resolution using
        screenshots from a Google Pixel 2.
        """
        #1 keyboard opened
        e1 = event.Event('keyboard opened', True)
        e1.addFixedPosition('events/keyboard_small.jpg', (0, 1168, 1080, 1640),
                            False, True)  # small
        e1.addFixedPosition('events/keyboard_capital.jpg',
                            (0, 1168, 1080, 1640), False, True)  # capitals
        self.addEvent(e1)

        #2 SMS chat opened, with Person X
        e2 = event.Event('SMS chat opened')
        e2.addFixedPosition('events/messages_chat.jpg', (40, 65, 100, 205),
                            False, True)  # go back arrow left
        e2.addFixedPosition('events/messages_chat.jpg', (860, 65, 1080, 205),
                            False, True)  # icons on the right in header
        e2.addsearchForText((180, 85, 750, 158), '', False)
        self.addEvent(e2)

        #3 SMS message/chatlist opened
        e3 = event.Event('SMS message/chatlist opened')
        e3.addFixedPosition('events/messages.jpg', (0, 65, 1080, 205), False,
                            True)
        e3.addFixedPosition('events/messages.jpg', (919, 1640, 1015, 1730),
                            False, True)
        self.addEvent(e3)
        """
예제 #15
0
 def update_receiving_power(self, packets_in_air):
     #This function is called when the power level in the channel has been changed
     #The channel status will be changed by judging whether the power level reaches the minimum interference power
     #Input:
     #	packets_in_air: the list of packets that are transmitting in the air
     #Output:
     #	True--channel status is changed from idle/busy to busy/idle
     #	False--channel status is not changed
     status_changed = super().update_receiving_power(packets_in_air)
     if self.packet_can_receive == None or (
             self.packet_can_receive in packets_in_air
     ):  # the current can receive packet is still transmitting, or none of the frames can be received
         if self.channel_state == "Busy" and self.status == "Listen":
             print("detecting process 1")
             if self.detector.channel_busy() and self.mode == "Open access":
                 new_event = event.Event("Alarm detected",
                                         self.timer.current_time)
                 new_event.register_device(self)
                 self.timer.register_event(new_event)
                 self.mode = "Alarm resolution--clear the channel"
         elif self.channel_state == "Idle" and self.status == "Listen":
             if self.detector.channel_idle() and self.mode == "Open access":
                 new_event = event.Event("Alarm detected",
                                         self.timer.current_time)
                 new_event.register_device(self)
                 self.timer.register_event(new_event)
                 self.mode = "Alarm resolution--clear the channel"
     if self.mode == "Alarm resolution--Polling phase" and self.current_slot != None:
         if self.current_slot.status == "Idle" and self.channel_state == "Busy":  # change the slot status to collision (may becomes Received)
             self.current_slot.status = "Collision"
     return status_changed
예제 #16
0
파일: jets.py 프로젝트: gautiernguyen/EDR
def read_csv(filename,
             index_col=0,
             header=None,
             dateFormat="%Y/%m/%d %H:%M",
             sep=','):
    '''
    Consider a  list of events as csv file ( with at least begin and end)
    and return a list of jets
    '''
    df = pd.read_csv(filename, index_col=index_col, header=header, sep=sep)
    df['begin'] = pd.to_datetime(df['begin'], format=dateFormat)
    df['end'] = pd.to_datetime(df['end'], format=dateFormat)
    df['Xing_begin'] = pd.to_datetime(df['Xing_begin'], format=dateFormat)
    df['Xing_end'] = pd.to_datetime(df['Xing_end'], format=dateFormat)
    df['Msh_begin'] = pd.to_datetime(df['Msh_begin'], format=dateFormat)
    df['Msh_end'] = pd.to_datetime(df['Msh_end'], format=dateFormat)

    jetList = [
        Jet(evt.Event(df['begin'][i], df['end'][i]))
        for i in range(0, len(df))
    ]
    for i, elt in enumerate(jetList):
        elt.clock_angle = df['clock_angle'][i]
        elt.tilt = df['tilt'][i]
        elt.velocity = pd.Series(index=['Vx', 'Vy', 'Vz'],
                                 data=[df['Vx'][i], df['Vy'][i], df['Vz'][i]])
        elt.pos = pd.Series(index=['X', 'Y', 'Z'],
                            data=[df['X'][i], df['Y'][i], df['Z'][i]])
        elt.crossing = evt.Event(df['Xing_begin'][i], df['Xing_end'][i])
        elt.ideal_msh = evt.Event(df['Msh_begin'][i], df['Msh_end'][i])
        elt.proba = df['proba'][i]
    return jetList
예제 #17
0
        def __init__(self):
                self.base_event = event.Event()
                self.current_event = event.Event()
                self.base_event.load_from_file('event-details.txt')
                self.threshold = 0

                days_file = open("days.txt", "r")
                self.days_of_week_list = days_file.read().splitlines()
                days_file.close()
                full_months_file = open("full-month.txt", "r")
                self.full_months = full_months_file.read().splitlines()
                full_months_file.close()
                abbrev_months_file = open("abbrev-month.txt", "r")
                self.abbrev_months = abbrev_months_file.read().splitlines()
                abbrev_months_file.close()
                disaster_list_file = open("disaster-list.txt", "r")
                self.disaster_list = disaster_list_file.read().splitlines()
                disaster_list_file.close()
                countries_file = open("countries.txt", "r")
                self.country_list = countries_file.read().splitlines()
                countries_file.close()
                state_list_file = open("us-states.txt", "r")
                self.state_list = state_list_file.read().splitlines()
                state_list_file.close()

                self.sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')

                # reset last-run-trees.txt
                f = open(last_run_file, 'w')
                f.close()
예제 #18
0
    def request_to_cdn(self, content_id, time_cur):
        """
        request ke CDN
        CDN reply dengan content atau redirect ke peer lain
        buat event untuk cache content dari CDN jika CDN reply dengan content
        buat event untuk request_to_peer jika CDN redirect ke peer lain
        """

        # cek cache entries dulu utk mencegah kasus peer yng sama me-request content id yng sama
        #
        # jika cache_entries[content_id] sudah ada return []
        if self.cache_entries.has_key(content_id):
            return [], []

        other_reply = self.cdn.get_content(self.id, content_id, time_cur)
        if other_reply[0]:
            content = other_reply[0]

            #pada prinsipnya cache_event ini adalah mendownload kemudian menyimpan
            #cache_content event, download duration, actor, actor action, action parameters
            # tandai bahwa cache entry akan di-isi content sebenarnya
            self.cache_entries[content_id] = 1
            #contoh: {0: [0, 5.0775931306168065, 499.0, 3600.0]}
            durasi = content[2] * 8 / (self.dn_bw / 1000.0)
            cache_event = event.Event(event.CACHE_CONTENT, time_cur + durasi,
                                      self, self.cache_content,
                                      [content_id, content, time_cur + durasi])

            return [cache_event], []

        else:
            request_to_peer_event = event.Event(
                event.REQUEST, time_cur, self, self.request_to_peer,
                [content_id, other_reply[1], time_cur])
            return [request_to_peer_event], []
예제 #19
0
    def collision_time(self):
        """
        Calculates next collision times of the balls that underwent collisions.
        """
        collided_ball = set()
        for event in self._events:  # Events of next collisions
            for collided in event.pair():
                collided_ball.add(collided)

        # Adds collision events to priority queue
        for element in collided_ball:
            if element != self._N_ball:
                # Calculating collisions with container
                dt = self._ball[element].time_to_collision(self._container)
                if dt != np.inf:
                    self._pq[ev.Event((
                        element,
                        self._N_ball,
                        self._ball[element]._count,
                        -1,
                        dt + self._global_time,
                    ))] = (dt + self._global_time)

                # Calculating collisions with other balls
                for j in range(self._N_ball):
                    if j != element:
                        # Ensure smaller index comes first
                        if j < element:
                            ball_A = self._ball[j]
                            ball_B = self._ball[element]
                            index_A = j
                            index_B = element
                        else:
                            ball_A = self._ball[element]
                            ball_B = self._ball[j]
                            index_A = element
                            index_B = j
                        dt = ball_A.time_to_collision(ball_B)
                        if dt != np.inf:
                            self._pq[ev.Event((
                                index_A,
                                index_B,
                                self._ball[index_A]._count,
                                self._ball[index_B]._count,
                                dt + self._global_time,
                            ))] = (dt + self._global_time)

            # If container underwent collision
            else:
                for j in range(self._N_ball):
                    dt = self._ball[j].time_to_collision(self._container)
                    if dt != np.inf:
                        self._pq[ev.Event((
                            j,
                            self._N_ball,
                            self._ball[j]._count,
                            -1,
                            dt + self._global_time,
                        ))] = (dt + self._global_time)
예제 #20
0
    def process_data(self):
        str_arg = ''
        command = None

        _debug_("Data received: %s" % str(self.data), 2)
        str_cmd = self.data[:4]
        if str_cmd in ('VOL-', 'VOL+', 'VOLM', 'MAIN', 'STAT'):
            command = self.cmds.get(str_cmd, '')
            if command:
                _debug_('Event Translation: "%s" -> "%s"' % (str_cmd, command))
                if str_cmd in ('VOL-', 'VOL+'):
                    self.rc.post_event(
                        em.Event(command, arg=self.mixer_default_step))
                else:
                    self.rc.post_event(em.Event(command))

        elif str_cmd == 'TEXT':
            str_arg = self.data[4:]
            for letter in str_arg:
                command = self.rc.key_event_mapper(letter)
                if command:
                    _debug_('Event with arg Translation: "%s" -> "%s %s"' %
                            (self.data, command, letter))
                    self.rc.post_event(command)

        elif str_cmd == 'MSND':
            self.menu_client_waiting = True

        elif str_cmd == 'MITM':
            str_arg = self.data[4:]
            try:
                pos = int(str_arg)

                menu = self.menuw.menustack[-1]
                max = len(menu.choices)
                if pos < max:
                    menu.selected = menu.choices[pos]
                    self.rc.post_event(em.MENU_SELECT)
                else:
                    _debug_('Menu index too high!: %s (max=%s)' %
                            (pos, max - 1))

            except ValueError:
                _debug_('Menu index sent: %s' % str_arg)
                pass

        else:
            command = self.rc.key_event_mapper(self.cmds.get(self.data, ''))
            if command:
                _debug_('Event Translation: "%s" -> "%s"' %
                        (self.data, command))
                self.rc.post_event(command)

        if command and self.osd_message:
            _debug_('OSD Event: "%s"' % (command))
            rc.post_event(
                em.Event(em.OSD_MESSAGE, arg=_('BT event %s' % command)))

        self.data = ''
예제 #21
0
def get_ideal_interval(event,
                       model_region,
                       data,
                       label=1,
                       method='smart',
                       feature_to_look='V',
                       windowsize=12):
    pred = pd.Series(
        index=data[event.begin:event.end].resample('1T').mean().dropna().index,
        data=medfilt(
            model_region.predict(
                data[event.begin:event.end].resample('1T').mean().dropna()),
            3))
    mshs = pp.makeEventList(pred, label, 1.5)
    largest_msh = mshs[np.argmax([x.duration for x in mshs])]
    if feature_to_look == 'V':
        ftl = np.sqrt(data.Vx**2 + data.Vy**2 + data.Vz**2)
    if feature_to_look == 'Vl':
        Vlmn = mva.MVA(data[['Bx', 'By',
                             'Bz']].values).vec2lmn(data[['Vx', 'Vy',
                                                          'Vz']].values)
        Vlmn = pd.DataFrame(index=data.index,
                            data=Vlmn,
                            columns=['Vn', 'Vm', 'Vl'])
        ftl = Vlmn.Vl
    if method == 'smart':
        stab = ftl[largest_msh.begin:largest_msh.end].rolling(
            windowsize, center=True, min_periods=windowsize).std()
        cluster = KMeans(n_clusters=2)
        clustered = pd.Series(index=stab.dropna().index,
                              data=cluster.fit_predict(
                                  stab.dropna().values.reshape(-1, 1)))
        label = np.argmin(cluster.cluster_centers_)
        potential_ideals = pp.makeEventList(clustered, label, 10 / 60)
        ideal_msh = potential_ideals[np.argmax(
            [x.duration for x in potential_ideals])]
        most_stab = ftl[ideal_msh.begin:ideal_msh.end].rolling(
            int(ideal_msh.duration.total_seconds() / 10),
            center=True).std().idxmin()
        ideal_msh = evt.Event(most_stab - ideal_msh.duration / 4,
                              most_stab + ideal_msh.duration / 4)
        return ideal_msh
    if method == 'center':
        return evt.Event(
            largest_msh.begin + 0.5 *
            (largest_msh.duration - datetime.timedelta(minutes=duration)),
            largest_msh.begin + 0.5 *
            (largest_msh.duration + datetime.timedelta(minutes=duration)))
    if method == 'stable':
        V = np.sqrt(data.Vx**2 + data.Vy**2 + data.Vz**2)
        stab = V[largest_msh.begin:largest_msh.end]
        begin = stab.rolling(int(duration * 12),
                             center=True,
                             min_periods=int(duration * 12)).std().idxmin()
        return evt.Event(begin - 0.5 * datetime.timedelta(minutes=duration),
                         begin + 0.5 * datetime.timedelta(minutes=duration))
예제 #22
0
 def __init__(self, ip, port, buffersize=10000):
     self.on_connected = event.Event()
     self.on_connection_lost = event.Event()
     self.on_response = event.Event()
     self.ip = ip
     self.port = port
     self.buffersize = buffersize
     self.sslcontext = ssl.SSLContext(cert_reqs=ssl.CERT_OPTIONAL)
     self.mainsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.connected = False
예제 #23
0
 def shuntItemInCart(self, item):
     ''' Move an image item into or out of the shopping cart
     '''
     if self.cart != [] and item in self.cart:
         self.cart.remove(item)
         rc.post_event(
             em.Event(em.OSD_MESSAGE, arg=_('Removed Item from Cart')))
     else:
         self.cart.append(item)
         rc.post_event(em.Event(em.OSD_MESSAGE,
                                arg=_('Added Item to Cart')))
def main():
    try:
        source = urllib.request.urlopen(
            config.timetableURL).read()  # Requests HTML page
    except urllib.error.HTTPError as e:
        print("Unable to open timetable Website, aborting!")
        print('Error code: ', e.code)
        exit(2)
    except urllib.error.URLError as e:
        print(
            "There's an error with the timetable like that's been given to me")
        print("Go into config/config.json and fix the `timetableURL` please")
        print('Error code: ', e.reason)
        exit(3)
    soup = bs.BeautifulSoup(source,
                            'lxml')  # loads into BS with the data type of lxml
    print('Crunching through EVision Timetable')
    table = soup.find_all(
        'table',
        {"class": "spreadsheet"})  # finds all the tables in HTML with day data
    for day in range(5):  # For each day table
        # find the entries with info on classes
        dayData = table[day]
        activities = dayData.find_all('tr')
        # for each class/activity we get the data on it
        for activity in range(
                1, len(activities)
        ):  # We ignore the first entry as it's a header used by the website.
            items = activities[activity]
            td = items.find_all('td')
            # This checks if the user is taking the module
            for pos, module in enumerate(config.modulesTaken):
                if module in td[0].text:
                    colour = config.colourID[pos]
                    weeks = td[6].text  # Obtains the weeks the class is on for
                    # Checks if entry is for multiple weeks
                    if '-' in weeks:
                        weeks = weeks.split('-')
                        # If event is for multiple weeks we make an event object for one
                        for week in range(int(weeks[0]), int(weeks[1]) + 1):
                            # Creates object
                            instance = event.Event(module, td[2].text,
                                                   td[8].text, td[7].text,
                                                   colour)
                            instance.addDate(week, day, td[3].text, td[4].text)
                            objectArray.append(instance)  # Add object to list

                    else:
                        # If the event doesn't, creates object
                        instance = event.Event(module, td[2].text, td[8].text,
                                               td[7].text, colour)
                        instance.addDate(int(weeks), day, td[3].text,
                                         td[4].text)
                        objectArray.append(instance)  # add to list
예제 #25
0
def get_component(name, ent):  # maybe move this to init py file
    if name == 'zombie':
        z = undead.Zombie(ent)
        ent.add_component(z)
        ent.send_event(event.Event('start-up'))
        return ent
        #return undead.Zombie(entity)
    elif name == 'skeleton':
        s = undead.Skeleton(ent)
        ent.add_component(s)
        ent.send_event(event.Event('start-up'))
        return ent
예제 #26
0
 def __init__(self, robot, alarmDist=0, debug=None):
     threading.Thread.__init__(self)
     self.R = robot
     self.debug = debug
     self.alarmDist = alarmDist
     self.USDist = 0
     self.rearBumper = 0
     self.frontBumper = 0
     self.rearBumper_pressed = event.Event()
     self.USSensor_tooNear = event.Event()
     self.frontBumper_pressed = event.Event()
     self.running = threading.Event()
예제 #27
0
def test_event():
    e1 = event.Event("s1", "e1", ref_date, ref_date + timedelta(minutes=15),
                     "ended")
    e2 = event.Event("s2", "e2", ref_date + timedelta(20),
                     ref_date + timedelta(40), "ended")
    e3 = event.Event("s2", "e3", ref_date + timedelta(40),
                     ref_date + timedelta(100), "ended")

    l = event.EventList()
    l.add(e1)
    l.add(e3)
    l.add(e2)
    l.write()
예제 #28
0
    def __init__(self) -> None:
        self.client_sockets: List[socket] = []
        self.connection_threads: List[Thread] = []
        self.running: bool = True

        self.server_socket: socket = socket(AF_INET, SOCK_STREAM)
        self.server_socket.bind((server_bind_addr, port))
        self.server_socket.listen(socket_listen_queue_cap)

        self.event_client_connected: event.Event = event.Event()
        self.event_full_connections: event.Event = event.Event()
        self.event_received_message: event.Event = event.Event()
        self.event_client_disconnected: event.Event = event.Event()
예제 #29
0
 def polling_round_end(self):
     # This function is called when polling round ends
     self.current_slot = None
     RAW_slots = []
     for each_RAW in self.polling_round.RAWs:
         for each_slot in each_RAW.slot_list:
             RAW_slots.append(each_slot)
     print([x.status for x in RAW_slots])
     next_STAs_to_check, next_STAs_to_collect, next_blocks_to_check = self.polling_round.polling_round_analyse(
     )
     if not (next_STAs_to_collect or next_STAs_to_check
             or next_blocks_to_check):
         # sys.stdout=open('test.txt','a')
         print("Polling Phase finished ")
         print(self.status)
         print(self.channel_state)
         self.mode = "Open access"
         self.detector.reset()
         self.detector.turn_on()
         for each_block in self.block_list.blocks:
             each_block.STA_received = []
         self.block_list.STA_received = []
         return
     self.polling_round = restricted_access_window.PollingRound(
         self.timer, self.max_data_size, self, self.STA_list)
     self.polling_round.set_polling_target(next_STAs_to_check,
                                           next_STAs_to_collect,
                                           next_blocks_to_check)
     self.queue = self.polling_round.generate_beacon(
         self.timer.current_time,  #+self.timer.SIFS,
         self.channel_state,
         self.max_data_size)
     statistics_collection.collector.register_beacons(
         self.timer.current_time, self.queue[-1])
     self.transmit_packet(self.queue[0])
     for each_RAW in self.polling_round.RAWs:
         for each_slot in each_RAW.slot_list:  # register when the RAW slot start event
             new_event = event.Event("Raw slot start", each_slot.start_time)
             new_event.register_device(self)
             self.timer.register_event(new_event)
     new_event = event.Event("Polling round end",
                             self.polling_round.end_time
                             )  # register when the polling round will end
     new_event.register_device(self)
     self.timer.register_event(new_event)
     # time.sleep(5)
     print(
         "\n##############################next polling round##########################################"
     )
예제 #30
0
 def __init__(self, barGroup, slippageModel, commissionModel):
     self.__orderId = 0
     self.__orderDeque = {}
     for instr in barGroup.keys():
         self.__orderDeque[instr] = deque()
     self.__barGroup = barGroup
     self.__slippage = slippageModel
     self.__commission = commissionModel
     self.__barGroup.updateEvent.subscribe(self.__onMktData)
     
     self._hist = bar.HistBars()
     
     self._tradeEvent = event.Event()
     self._orderInsertEvent = event.Event()
     self._mktDataEvent = event.Event()