Exemplo n.º 1
0
def node_rider_request(sys, args):
    # State changes
    rider_id = len(sys.rider_start_locations)
    rider_location = gen_location()
    sys.rider_start_locations.append(rider_location)
    sys.rider_end_locations.append(gen_end_rider(sys, rider_location))
    sys.rider_start_times.append(sys.cur_time)
    sys.rider_pickup_times.append(-1)
    sys.rider_end_times.append(-1)

    # Schedule events
    new_event_time = sys.cur_time + inter_rnd()
    new_event = event.event("Rider Request",
                            new_event_time,
                            node_rider_request,
                            priority=5)
    eventlist_tuple = (new_event_time, new_event)
    heapq.heappush(sys.eventlist, eventlist_tuple)

    new_event_time = sys.cur_time
    new_event = event.event("Update Driver Location",
                            new_event_time,
                            node_update_driver_locations,
                            args={
                                'rider_id': rider_id,
                                'rider_location': rider_location
                            },
                            priority=1)
    eventlist_tuple = (new_event_time, new_event)
    heapq.heappush(sys.eventlist, eventlist_tuple)
Exemplo n.º 2
0
    def __init__(self):
        self.account = ''
        self.parrent_id = ''
        self.order_id = ''
        self.operation = operation_type.none
        self.symbol = ''
        self.side = side_type.none
        self.quantity = 0
        self.order_price = ''
        self.contra = ''
        self.channel_of_execution = channel.CSFB
        self.tif = ''
        self.type = ''
        self.display = display_mode.lit
        self.stop_limit_price = ''
        self.reserve_size = ''
        self.cancel_replace_id = ''
        self.ticket_id = ''
        self.algo_fields = ''
        self.security_type = ''
        self.security_id = ''
        self.is_submitted = False
        self.cancel_submitted = False

        self.on_partial = event()
        self.on_acknowledge = event()
        self.on_completed = event()
        self.on_canceled = event()
Exemplo n.º 3
0
def node_rider_request(sys, args):
    # State changes
    rider_id = len(sys.rider_start_locations)
    rider_location = gen_location()
    sys.rider_start_locations.append(rider_location)
    sys.rider_end_locations.append(gen_end_rider(sys, rider_location))
    dist = distance(rider_location, sys.rider_end_locations[-1])
    sys.rider_start_times.append(sys.cur_time)
    sys.rider_pickup_times.append(-1)
    sys.rider_end_times.append(-1)

    # Schedule events
    new_event_time = sys.cur_time + inter_rnd()
    new_event = event.event("Rider Request", new_event_time,
                            node_rider_request)
    eventlist_tuple = (new_event_time, new_event)
    heapq.heappush(sys.eventlist, eventlist_tuple)

    new_event_time = sys.cur_time
    new_event = event.event("Available Driver",
                            new_event_time,
                            node_available_driver,
                            args={
                                'rider_id': rider_id,
                                'rider_location': rider_location
                            })
    eventlist_tuple = (new_event_time, new_event)
    heapq.heappush(sys.eventlist, eventlist_tuple)
Exemplo n.º 4
0
 def __init__(self,
              agent_util_func,
              generator_func,
              c,
              n,
              iterations,
              alpha=None):
     self._iterations = iterations
     self._candidates = list(range(c))
     #generate preference orderings
     self._ballots = generator_func(self._candidates, n, alpha)
     self._generator = generator_func
     self._util = agent_util_func
     self._alpha = alpha
     #get condorcet winner
     self._cond_winner = evaluation.get_condorcet_winner(
         self._candidates, self._ballots)
     #determine if there is a condorcet winner
     if self._cond_winner == None:
         self._isCond = False
     else:
         self._isCond = True
     self._c = c
     self._n = n
     self._learning = event(agent.LearningAgent, agent_util_func,
                            self._ballots, self._candidates)
     self._bestresponse = event(agent.BestResponseAgent, agent_util_func,
                                self._ballots, self._candidates)
     self._bayes = event(agent.LearningBayesianAgent, agent_util_func,
                         self._ballots, self._candidates)
     self._learnbr = event(agent.LearningBestResponseAgent, agent_util_func,
                           self._ballots, self._candidates)
     self._prag = event(agent.PragmatistAgent, agent_util_func,
                        self._ballots, self._candidates)
Exemplo n.º 5
0
 def accept(self):
     if not self.accept_channel:
         self.accept_channel = stackless.channel()
         event.event(self.handle_accept,
                     handle=self.sock,
                     evtype=event.EV_READ | event.EV_PERSIST).add()
     return self.accept_channel.receive()
Exemplo n.º 6
0
    def run(self):
        self._run = True
        logmod.set_current_application(self)
        log.info('Starting eventful application')
        for s in self._services:
            s.bind_and_listen()
            event.event(eventbase.event_read_bound_socket,
                        handle=s.sock,
                        evtype=event.EV_READ | event.EV_PERSIST,
                        arg=s).add()

        self.setup_wake_pipe()

        def checkpoint():
            if not self._run:
                raise SystemExit

        timers.call_every(1.0, checkpoint)

        self.setup()
        while self._run:
            try:
                event.dispatch()
            except SystemExit:
                log.warn("-- SystemExit raised.. exiting main loop --")
                break
            except KeyboardInterrupt:
                log.warn("-- KeyboardInterrupt raised.. exiting main loop --")
                break
            except Exception, e:
                log.error("-- Unhandled Exception in main loop --")
                log.error(traceback.format_exc())
Exemplo n.º 7
0
def deteched():
    event().write("1")
    os.system("aplay {0}".format("resources/ding.wav"))
    while True:
        tu=event().read()
        if tu=="0":
            return False
        time.sleep(0.2)
Exemplo n.º 8
0
def ReadAtMost(fd, size):
    while True:
        try:
            return os.read(fd, size)
        except OSError, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup, handle=fd, evtype=event.EV_READ, arg=stackless.current).add()
            stackless.schedule_remove()
Exemplo n.º 9
0
def Accept(sock):
    while True:
        try:
            return sock.accept()
        except socket.error, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup, handle=sock.fileno(), evtype=event.EV_READ, arg=stackless.current).add()
            stackless.schedule_remove()
Exemplo n.º 10
0
 def __init__(self, host, port, conn_handler):
     self.host = host
     self.port = port
     self.conn_handler = conn_handler
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.setblocking(0)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADD, 1)
     sock.bind((host, port))
     sock.listen(socket.SOMAXCONN)
     event.event(self.handle_accept, handle=sock, evtype=event.EV_READ|event.EV_PERSIST).add()
Exemplo n.º 11
0
 def __init__(self, host, port, sock, conn_handler):
     self.host = host
     self.port = port
     self.conn_handler = conn_handler
     if event:
         event.event(self.handle_accept, handle=sock,
                     evtype=event.EV_READ|event.EV_PERSIST).add()
     else: # asyncore
         asyncore.dispatcher.__init__(self, sock=sock)
         self.accepting = True
Exemplo n.º 12
0
    def test_read(self):
        def __read_cb(ev, fd, evtype, pipe):
            buf = os.read(fd, 1024)
            assert buf == 'hi niels', 'read event failed'

        print 'test_read'
        pipe = os.pipe()
        event.event(__read_cb, handle=pipe[0], evtype=event.EV_READ).add()
        os.write(pipe[1], 'hi niels')
        event.dispatch()
Exemplo n.º 13
0
def ReadAtMost(fd, size):
  while True:
    try:
      return os.read(fd, size)
    except OSError, e:
      if e.errno != errno.EAGAIN:
        raise
      event.event(HandleWakeup, handle=fd, evtype=event.EV_READ,
                  arg=greenlet.getcurrent()).add()
      ScheduleRemove()
Exemplo n.º 14
0
 def test_read(self):
     def __read_cb(ev, fd, evtype, pipe):
         buf = os.read(fd, 1024)
         assert buf == 'hi niels', 'read event failed'
     print 'test_read'
     pipe = os.pipe()
     event.event(__read_cb, handle=pipe[0],
                 evtype=event.EV_READ).add()
     os.write(pipe[1], 'hi niels')
     event.dispatch()
Exemplo n.º 15
0
def Accept(sock):
  while True:
    try:
      return sock.accept()
    except socket.error, e:
      if e.args[0] != errno.EAGAIN:
        raise
      event.event(HandleWakeup, handle=sock.fileno(), evtype=event.EV_READ,
                  arg=greenlet.getcurrent()).add()
      ScheduleRemove()
Exemplo n.º 16
0
 def test_signal(self):
     def __signal_cb(ev, sig, evtype, arg):
         if evtype == event.EV_SIGNAL:
             ev.delete()
         elif evtype == event.EV_TIMEOUT:
             os.kill(os.getpid(), signal.SIGUSR1)
     print 'test_signal'
     event.event(__signal_cb, handle=signal.SIGUSR1,
                 evtype=event.EV_SIGNAL).add()
     event.event(__signal_cb).add(2)
     event.dispatch()
Exemplo n.º 17
0
 def __init__(self, host, port, sock, conn_handler):
     self.host = host
     self.port = port
     self.conn_handler = conn_handler
     if event:
         event.event(self.handle_accept,
                     handle=sock,
                     evtype=event.EV_READ | event.EV_PERSIST).add()
     else:  # asyncore
         asyncore.dispatcher.__init__(self, sock=sock)
         self.accepting = True
Exemplo n.º 18
0
    def setup_wake_pipe(self):
        '''Establish a pipe that can be used to wake up the main
		loop.
		'''
        thread.start_new_thread(lambda: None, ())
        self._wake_i, self._wake_o = os.pipe()
        set_nonblocking(self._wake_i)
        set_nonblocking(self._wake_o)
        event.event(self.wake_routine,
                    handle=self._wake_i,
                    evtype=event.EV_READ | event.EV_PERSIST).add()
Exemplo n.º 19
0
    def set_config(self, conf):
        self._readlimit = conf["readlimit"]
        if self._readlimit > 0:
            self._readlimitnext = self._readlimit
            self._evrlimit = event(self._evs, self._tms, self._sock)
            self._evrlimit.add_timer(1000, self._timeouthandler)

        self._writelimit = conf["writelimit"]
        if self._writelimit > 0:
            self._writelimitnext = self._writelimit
            self._evwlimit = event(self._evs, self._tms, self._sock)
            self._evwlimit.add_timer(1000, self._timeouthandler)
Exemplo n.º 20
0
def Accept(sock):
    while True:
        try:
            return sock.accept()
        except socket.error, e:
            if e.args[0] != errno.EAGAIN:
                raise
            event.event(HandleWakeup,
                        handle=sock.fileno(),
                        evtype=event.EV_READ,
                        arg=greenlet.getcurrent()).add()
            ScheduleRemove()
Exemplo n.º 21
0
def ReadAtMost(fd, size):
    while True:
        try:
            return os.read(fd, size)
        except OSError, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup,
                        handle=fd,
                        evtype=event.EV_READ,
                        arg=greenlet.getcurrent()).add()
            ScheduleRemove()
Exemplo n.º 22
0
    def set_config(self, conf):
        self._readlimit = conf["readlimit"]
        if self._readlimit > 0:
            self._readlimitnext = self._readlimit
            self._evrlimit = event(self._evs, self._tms, self._sock)
            self._evrlimit.add_timer(1000, self._timeouthandler)

        self._writelimit = conf["writelimit"]
        if self._writelimit > 0:
            self._writelimitnext = self._writelimit
            self._evwlimit = event(self._evs, self._tms, self._sock)
            self._evwlimit.add_timer(1000, self._timeouthandler)
Exemplo n.º 23
0
def ReadAtMost(fd, size):
    while True:
        try:
            return os.read(fd, size)
        except OSError, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup,
                        handle=fd,
                        evtype=event.EV_READ,
                        arg=stackless.current).add()
            stackless.schedule_remove()
Exemplo n.º 24
0
def test_event():
    # 配置事件监听者
    Dispatcher.listen = {
        'tests.test_event.SaveEvent': ['tests.test_event.Listen1'],
    }

    # 事件的触发
    event(SaveEvent(12))
    assert num == 13

    event(SaveEvent(1))
    assert num == 14
Exemplo n.º 25
0
def Accept(sock):
    while True:
        try:
            return sock.accept()
        except socket.error, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup,
                        handle=sock.fileno(),
                        evtype=event.EV_READ,
                        arg=stackless.current).add()
            stackless.schedule_remove()
Exemplo n.º 26
0
    def test_signal(self):
        def __signal_cb(ev, sig, evtype, arg):
            if evtype == event.EV_SIGNAL:
                ev.delete()
            elif evtype == event.EV_TIMEOUT:
                os.kill(os.getpid(), signal.SIGUSR1)

        print 'test_signal'
        event.event(__signal_cb, handle=signal.SIGUSR1,
                    evtype=event.EV_SIGNAL).add()
        event.event(__signal_cb).add(2)
        event.dispatch()
Exemplo n.º 27
0
def Write(fd, data):
    while True:
        try:
            got = os.write(fd, data)
            if got == len(data):
                return
            if got:
                data = data[got:]  # TODO(pts): Do with less copy
        except OSError, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup, handle=fd, evtype=event.EV_WRITE, arg=stackless.current).add()
            stackless.schedule_remove()
Exemplo n.º 28
0
def createScenario(Echeancier, loiExpo, dureeTrans, k, unSurLambda, packetOfMachine):
    # Temps global
    Temps = 0

    # loiExpo : tableu des valeurs aléatoires suivent la loi exponentiel de paramètre lambda
    for i in loiExpo:
        # Récupérer les machines occupées à l'instant T
        machinesNotDispo = MajMachinesOccupees(Echeancier, dureeTrans, Temps)

        # Si tous les machines sont occupées on avance le temps global jusqu'il y aura au moins une machine libre
        while len(machinesNotDispo) == 10:
            Temps += np.random.exponential(unSurLambda, 1)[0]
            machinesNotDispo = MajMachinesOccupees(Echeancier, dureeTrans, Temps)

        # Récupérer les machines disponibles
        machineDispo = []
        for m in range(10):
            if m not in machinesNotDispo:
                machineDispo.append(m)

        # Choisir d'une facon uniforme la prochaine machine qui va transmettre un paquet parmi les machines disponibles
        machine = machineDispo[np.random.randint(0, len(machineDispo), 1)[0]]

        # Ajouter évènement à l'échéancier
        ptr = event(Temps, machine, packetOfMachine[machine])
        Echeancier.append(ptr)

        # Ajouter les copies du paquets à l'échéancier
        T_copis = 0
        for j in range(k - 1):
            T_copis += dureeTrans

            # trouver un instant avec un interval inter paquets qui suit la loi exponentiel de paramètre 1/(k * lambda)
            randInterval = np.random.exponential(unSurLambda / k, 1)[0]

            # Avancer le temps
            T_copis += randInterval

            # Ajouter la copie à l'écheancier
            ptr = event(Temps + T_copis, machine, packetOfMachine[machine])
            Echeancier.append(ptr)

            machinesNotDispo.clear()

        # MAJ du nombre de paquets transmis par la machine i
        packetOfMachine[machine] += 1

        # Avancer le temps global
        Temps += i

        machinesNotDispo.clear()
Exemplo n.º 29
0
def packet_generation(
        STA_list, location, speed, sp_type,
        arg):  #generate packe according to the alarm spreading model
    # speed should be in unit of m/s
    import math, random
    assert sp_type == "All" or sp_type == "Exp" or sp_type == "Sq"
    packet_generation_events = []
    counter = 0
    x = location[0]
    y = location[1]
    for each in STA_list:  #calculate the packet arrival time
        #print(each.AID)
        distance = math.sqrt((each.x - x)**2 + (each.y - y)**2)

        if sp_type == "All":
            new_event = event.event("packet arrival",
                                    start_time=(distance / speed * 10**6))
            new_event.register_STA(each)
            packet_generation_events.append(new_event)
            counter += 1
            # timer.register_event(new_event)

        if sp_type == "Exp":
            a = arg
            probability = math.exp(-a * distance)
            if random.random() <= probability:
                new_event = event.event("packet arrival",
                                        start_time=(distance / speed * 10**6))
                new_event.register_STA(each)
                packet_generation_events.append(new_event)
                counter += 1
                # timer.register_event(new_event)

        if sp_type == "Sq":
            d_max = arg
            if distance < d_max:
                probability = math.sqrt(d_max**2 - distance**2)
            else:
                probability = 0
            if random.random() <= probability:
                new_event = event.event("packet arrival",
                                        start_time=(distance / speed * 10**6))
                new_event.register_STA(each)
                packet_generation_events.append(new_event)
                counter += 1
    print("packet amount=" + str(counter))

    import time
    # time.sleep(1)
    return packet_generation_events, counter
Exemplo n.º 30
0
def initialize(fptr):
    otopo = topo.Topology(fptr)  # create topo object #
    otm = tmc.get_TMgen(fptr, otopo.L)  # create traffic matrix (TM) object #
    # We just created the structure of TM
    # instantiated with all 0's traffic volumes.
    # Now we fill these or read from file
    # (depends on 'TMgenerate' in the config file).

    otm.generate(otopo.L)  # generate the TM #
    print("TM after generation:", otm.tm)
    oflowgen = flow.flowgen(fptr, otm.tm)  # create flow generator object #
    oevent = event.event(fptr, otopo, otm)  # create event simulator object #

    sim_dur = int(gen.get_param(fptr, "SIM_DUR"))  # duration of simulation #
    oevent.insert(oflowgen.next(otm.tm))  # insert first event #

    #loadev = {"type":"load-surge","time":1000,"surgetype":"random","num":5}
    #oevent.insert(loadev)

    while True:
        currev = oevent.pop()  # pop event from queue #
        if currev["time"] > sim_dur:  # time #
            break
        oevent.handler(currev, otopo, otm)  # handle current event #
        if currev[
                "type"] == "flow-arr":  # if event is flow arrival, inseert next -
            oevent.insert(oflowgen.next(otm.tm))  # - arrival in event queue
Exemplo n.º 31
0
def get_on_lib_event():
    ulr_manager = urllib3.PoolManager()
    site = "https://ontarioliberal.ca/events/"
    page = ulr_manager.request('GET', site)
    soup = BeautifulSoup(page.data, "html.parser")

    block_list = soup.find_all(
        class_="cell large-4 medium-6 events-listing-single")

    #basic information
    province = "Ontario"
    party = "Liberal"
    id = 0
    event_list = []

    for block in block_list:
        title = block.h2.string
        date = block.find("p", class_="entry-date").string
        link = block.a["href"]
        detail_page = ulr_manager.request('GET', link)
        detail_soup = BeautifulSoup(detail_page.data, "html.parser")
        location = detail_soup.find("p", class_="location").span.string
        event_list.append(
            evnt.event(province, id, location, title, party, link, date))
        id += 1
        print("%s Liberal event found" % id)

    return event_list
Exemplo n.º 32
0
def get_on_pc_event():
    url_manager = urlib.PoolManager()
    site = "https://www.ontariopc.ca/events"
    main_site = url_manager.request('GET',site)

    soup = BeautifulSoup(main_site.data,"html.parser")
    event_block = soup.find_all("div",class_="event")

    #baisc information 
    party = "PC"
    province = "Ontario"
    id = 0
    event_list = []
    for event in event_block:
        link = site+event.find("a",class_="event__register")["href"]
        date = event.find("div",class_="event__date--month").string.lstrip().rstrip()+ " " + event.find("div",class_="event__date--day").string.lstrip().rstrip()
        location = event.find("div",class_="event__venue").string
        if location == None:#sometime it is not in the div tag directly but in a tag
            location = event.find("div",class_="event__venue").a.string
        location = location.lstrip().rstrip()
        title = event.find("h4",class_="event__headline").string
        event_list.append(evnt.event(province,id,location,title,party,link,date))
        id += 1
        print("%s PC event found"%id)

    return event_list
Exemplo n.º 33
0
    def register_xmlrpc_agent(self):
        self.SESS_LOCK.acquire()

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', globals()['XMLRPC_PORT']))  # add host_name specific later
        s.listen(4)

        self.sockets[s.fileno()] = {
            'sock': s,
            'special': 'XMLRPC'
        }  # Register socket

        self.leventobjs[s.fileno()] = event.event(
            self.libevent_read_callback,
            handle=s,
            evtype=event.EV_TIMEOUT | event.EV_READ
            | event.EV_PERSIST)  # Register callback agent
        if self.leventobjs[s.fileno()] is not None:
            self.leventobjs[s.fileno()].add()  # Add agent to the queue.

        self.SESS_LOCK.release()
        if globals()['cmd_options'].enable_debug is True:
            print "XMLRPC has been registered to port %i" % globals(
            )['XMLRPC_PORT']
        return True
Exemplo n.º 34
0
def node_available_driver(sys, args):
    rider_id = args["rider_id"]
    rider_location = args["rider_location"]
    if have_free_driver(sys):
        # State changes
        min_driver_id = None
        min_distance = None
        for driver_id, driver_loc in enumerate(sys.driver_current_locations):
            curr_distance = distance(rider_location, driver_loc)
            if sys.driver_is_free[driver_id] and \
                    (min_distance is None
                     or curr_distance < min_distance):
                min_driver_id = driver_id
                min_distance = curr_distance
        sys.driver_is_free[min_driver_id] = False

        # Schedule events
        new_event_time = sys.cur_time + min_distance / sys.speed
        # FIXME: Not sure if this is supposed to be higher or lower priority
        new_event = event.event("Driver Response",
                                new_event_time,
                                node_driver_response,
                                args={
                                    'rider_id': rider_id,
                                    'driver_id': min_driver_id
                                },
                                priority=4)
        eventlist_tuple = (new_event_time, new_event)
        heapq.heappush(sys.eventlist, eventlist_tuple)
    else:
        sys.rider_queue.append(rider_id)
Exemplo n.º 35
0
def Write(fd, data):
    while True:
        try:
            got = os.write(fd, data)
            if got == len(data):
                return
            if got:
                data = data[got:]  # TODO(pts): Do with less copy
        except OSError, e:
            if e.errno != errno.EAGAIN:
                raise
            event.event(HandleWakeup,
                        handle=fd,
                        evtype=event.EV_WRITE,
                        arg=greenlet.getcurrent()).add()
            ScheduleRemove()
Exemplo n.º 36
0
def node_available_driver(sys, args):
    # State changes
    rider_id = args["rider_id"]
    rider_location = args["rider_location"]
    free_driver = have_free_driver(sys)
    min_driver_id = None
    min_distance = None
    if free_driver:
        for driver_id, driver_loc in enumerate(sys.driver_current_locations):
            curr_distance = distance(rider_location, driver_loc)
            if sys.driver_is_free[driver_id] and \
                (min_distance is None
                 or curr_distance < min_distance):
                min_driver_id = driver_id
                min_distance = curr_distance
        sys.driver_is_free[min_driver_id] = False
    else:
        sys.rider_queue.append(rider_id)

    # Schedule events
    if free_driver:
        new_event_time = sys.cur_time + min_distance / sys.speed
        new_event = event.event("Driver Response",
                                new_event_time,
                                node_driver_response,
                                args={
                                    'rider_id': rider_id,
                                    'driver_id': min_driver_id
                                },
                                priority=3)
        eventlist_tuple = (new_event_time, new_event)
        heapq.heappush(sys.eventlist, eventlist_tuple)
Exemplo n.º 37
0
 def schedule_call_local(self, seconds, cb, *args, **kwargs):
     current = greenlet.getcurrent()
     if current is self.greenlet:
         return self.schedule_call_global(seconds, cb, *args, **kwargs)
     event_impl = event.event(_scheduled_call_local, (cb, args, kwargs, current))
     wrapper = event_wrapper(event_impl, seconds=seconds)
     self.events_to_add.append(wrapper)
     return wrapper
Exemplo n.º 38
0
def main(argv):
    # initialize libevent
    event.init()

    # set the SIGINT handler
    event.signal(signal.SIGINT, _sigint)

    # create an incoming (listen) socket, and bind
    listen_sock = socket.socket()
    listen_sock.setblocking(0)
    listen_sock.bind(("localhost", listen_port))

    # start listening, set event
    listen_sock.listen(20)
    event.event(listen_read, None, event.EV_READ | event.EV_PERSIST, listen_sock).add()

    # start event loop
    event.dispatch()
Exemplo n.º 39
0
 def test_timeout(self):
     def __timeout_cb(ev, handle, evtype, ts):
         now = time.time()
         assert int(now - ts['start']) == ts['secs'], 'timeout failed'
     print 'test_timeout'
     ts = { 'start':time.time(), 'secs':5 }
     ev = event.event(__timeout_cb, arg=ts)
     ev.add(ts['secs'])
     event.dispatch()
Exemplo n.º 40
0
 def __init__(self, sock, addr):
     self._sock = sock
     self.addr = addr
     self._to_be_sent = "" # write buffer
     
     self._sock.setblocking(False)
     
     self._read_ev = event.event(self._handle_read, handle=self._sock, evtype=event.EV_READ|event.EV_PERSIST)
     self._read_ev.add()
Exemplo n.º 41
0
 def __init__(self, host, port, conn_handler):
     self.host = host
     self.port = port
     self.conn_handler = conn_handler
     if event:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         sock.setblocking(0)
         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         sock.bind((host, port))
         sock.listen(socket.SOMAXCONN)
         event.event(self.handle_accept, handle=sock,
                     evtype=event.EV_READ|event.EV_PERSIST).add()
     else: # asyncore
         asyncore.dispatcher.__init__(self)
         self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
         self.set_reuse_addr()
         self.bind((host, port))
         self.listen(socket.SOMAXCONN) # TODO: set SO_SNDBUF, SO_RCVBUF
Exemplo n.º 42
0
    def test_timeout(self):
        def __timeout_cb(ev, handle, evtype, ts):
            now = time.time()
            assert int(now - ts['start']) == ts['secs'], 'timeout failed'

        print 'test_timeout'
        ts = {'start': time.time(), 'secs': 5}
        ev = event.event(__timeout_cb, arg=ts)
        ev.add(ts['secs'])
        event.dispatch()
Exemplo n.º 43
0
def node_init(sys, args):
    # State changes
    for i in range(sys.num_drivers):
        sys.driver_current_locations.append(gen_location())
        sys.driver_is_free.append(True)

    # Schedule events
    new_event_time = sys.cur_time
    new_event = event.event("Rider Request", new_event_time,
                            node_rider_request)
    eventlist_tuple = (new_event_time, new_event)
    heapq.heappush(sys.eventlist, eventlist_tuple)
Exemplo n.º 44
0
 def _initserver(self):
     try:
         self._sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
         self._sock.setblocking(self._blocking)
         self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, self._reuseaddr)
         self._sock.bind((self._host, self._port))
         self._sock.listen(self._backlog)
         self._ev = event(self._evs, self._tms, self._sock)
         self._ev.add_read(self._accepthandler)
     except socket.error, e:
         sys.stdout.write("Error occur when initserver: %s\n" % e)
         raise e
Exemplo n.º 45
0
def initialization(t,src,n):
	argv = {}
	argv['time'] = t
	argv['actType'] = 'sendMac'
	argv['src'] = src
	argv['des'] = n - 1
	argv['pacSize'] = 60
	argv['pacData'] = src
	argv['pacType'] = 'data'
	argv['pacAckReq'] = True
	e = event(argv)
	return e
Exemplo n.º 46
0
 def _on_worker_connect(self, sock):
     new_sock, new_addr = sock.accept()
     new_sock.setblocking(False)
     
     self._worker_read_ev = event.event(self._on_worker_complete, handle=new_sock, evtype=event.EV_READ|event.EV_PERSIST)
     self._worker_read_ev.add()
     
     #read_ev = event.read(new_sock, self._on_worker_complete, new_sock)
     #read_ev.add()
     
     # close the listening server socket since there's only 1 worker
     sock.close()
Exemplo n.º 47
0
    def register_xmlrpc_agent(self):
        self.SESS_LOCK.acquire()

        s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('', globals()['XMLRPC_PORT'])) #add host_name specific later
        s.listen(1)

        self.sockets[s.fileno()] = {'sock':s,'special':'XMLRPC'} #Register socket

        self.leventobjs[s.fileno()]= event.event(self.libevent_read_callback, handle = s, evtype = event.EV_TIMEOUT | event.EV_READ | event.EV_PERSIST) #Register callback agent
        if self.leventobjs[s.fileno()] != None:
            self.leventobjs[s.fileno()].add() #Add agent to the queue.

        self.SESS_LOCK.release()
        print("XMLRPC has been registered to port %i"%globals()['XMLRPC_PORT'])
        return True
Exemplo n.º 48
0
    def registersession(self, s, mode, type_guid, server_guid, server_host=None, server_port=None, options=None):
        self.SESS_LOCK.acquire()

        if mode == 0:
            self.routes[type_guid][server_guid]['clients'] += [s]
        elif mode == 1 or mode == 3:
            if type_guid in self.routes.keys() is False:
                self.routes[type_guid] = {}
            if mode == 1:
                self.routes[type_guid]['bind'] = s
                self.routes[type_guid]['data'] = {}
            if server_guid in self.routes[type_guid].keys() is False:
                self.routes[type_guid].update({server_guid: {'clients': [],
                                                             'info': {'port': server_port,
                                                                      'host': server_host},
                                                             'data': {},
                                                             'channels': []}})
            else:
                self.routes[type_guid][server_guid]['info'] = {'port': server_port, 'host': server_host, 'bind': s}
                self.routes[type_guid][server_guid]['data'] = {}
            if isinstance(options, type({})):
                for x, y in options.iteritems():
                    self.routes[type_guid][server_guid]['info'][x] = y

            if mode == 3:
                self.SESS_LOCK.release()
                if globals()['cmd_options'].enable_debug is True:
                    print "registered secondary as type %s" % str(mode)
                return s
            else:
                self.types_by_port[str(s.getsockname()[1])] = type_guid

        elif mode == 2:
            self.routes[type_guid][server_guid]['channels'] += [s]

        self.sockets[s.fileno()] = {'sock': s, 'tguid': type_guid, 'sguid': server_guid}  # Register socket

        self.leventobjs[s.fileno()] = event.event(self.libevent_read_callback, handle=s, evtype=event.EV_TIMEOUT | event.EV_READ | event.EV_PERSIST)  # Register callback agent
        if self.leventobjs[s.fileno()] is not None:
            self.leventobjs[s.fileno()].add()  # Add agent to the queue.
        self.SESS_LOCK.release()
        if globals()['cmd_options'].enable_debug is True:
            print "registered socket %s as type %s" % (s.fileno(), str(mode))
        return s
Exemplo n.º 49
0
    def __init__(self, sock, srvconf, evs, tms):
        self._evs = evs
        self._tms = tms
        self._sock = sock

        self._blocking = 0
        if srvconf.has_key("blocking"):
            self._blocking = srvconf["blocking"]

        self._recvbuf = 8092
        if srvconf.has_key("recvbuf"):
            self._recvbuf = srvconf["recvbuf"]

        self._sendbuf = 8092
        if srvconf.has_key("sendbuf"):
            self._sendbuf = srvconf["sendbuf"]

        self._linger = pack("ii", 0, 0)
        if srvconf.has_key("linger"):
            self._linger = pack("ii", srvconf["linger"][0], srvconf["linger"][1])

        self._sock.setblocking(self._blocking)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self._recvbuf)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self._sendbuf)

        self._readbuffer = ""
        self._writebuffer = ""
        self._readlimit = -1
        self._readlimitnext = -1
        self._evrlimit = None
        self._writelimit = -1
        self._writelimitnext = -1
        self._evwlimit = None
        self._setrtimeout = 0
        self._setwtimeout = 0
        self._closed = 0
        self._ev = event(evs, tms, self._sock)
        self._ev.add_read(self._readhandler)

        self._recvmsghandler = None
        self._brokenhandler = None
Exemplo n.º 50
0
 def registersession(self,s):
     self.SESS_LOCK.acquire()
     if isinstance(s,Session):
         if s._registered:
             self.SESS_LOCK.release()
             if self._DEBUG.active: raise "Twice session Registration!"
             else: return
         s._registered=1
     reg_method = ''
     self.sockets[s.fileno()]=s
     if select_enabled:
         reg_method = 'select'
         self.sockpoll.register(s,1 | 2 | 8)
     elif 'event' in globals().keys():
         reg_method = 'libevent'
         self.leventobjs[s.fileno()]= event.event(self.libevent_read_callback, handle = s, evtype = event.EV_TIMEOUT | event.EV_READ | event.EV_PERSIST)
         if self.leventobjs[s.fileno()] != None:
             self.leventobjs[s.fileno()].add()
     if isinstance(self._socker,Socker_client):
         socker_notice = "->[SOCKER(TM)]"
     else:
         socker_notice = ''
     self.DEBUG('server',self._l(SERVER_NODE_REGISTERED)%{'fileno':s.fileno(),'raw':s,'method':reg_method,'socker_notice':socker_notice})
     self.SESS_LOCK.release()
Exemplo n.º 51
0
 def __init__(self, addr=('', 8080), connection_handler=BaseConnectionHandler):
     self.addr, self.port = addr
     self._sock = io.server_socket(self.addr, self.port)
     self._connection_handler = connection_handler
     listen_ev = event.event(self._accept_connection, handle=self._sock, evtype=event.EV_READ | event.EV_PERSIST)
     listen_ev.add()
Exemplo n.º 52
0
station2_x = np.empty((5,4), dtype = float)
station2_y = np.empty((5,4), dtype = float)
station2_z = np.empty((5,4), dtype = float)
station3_strings = []

#Gets the location for every antenna
#loops through strings
for i in range(5):
	#loops through antennas
	for j in range(4):
		station2_x[i][j] = station.get_string_coordinates(2,i+1, j)[0]
		station2_y[i][j] = station.get_string_coordinates(2,i+1, j)[1]
		station2_z[i][j] = station.get_string_coordinates(2,i+1, j)[2]

#Event object
e = event()
#While loop finds optimal event
#vp, dv, oca, d = e.create_vertex()
#Comment out to find complete random event

while True:
	vp, dv, oca, d = e.create_vertex()
	s = 0.0
	for i in range(4):
		for j in range(4):
			s += oca[i][j]
	s = s/16.0
	if s > 55.5 and s < 56.5:
		break
	else:
		pass	
Exemplo n.º 53
0
 def schedule_call_global(self, seconds, cb, *args, **kwargs):
     event_impl = event.event(_scheduled_call, (cb, args, kwargs))
     wrapper = event_wrapper(event_impl, seconds=seconds)
     self.events_to_add.append(wrapper)
     return wrapper
Exemplo n.º 54
0
    response = ('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n'
                '<a href="/%d">continue with %d</a>\n' %
                (next_num, next_num))
  Write(csfd, response)
  cs.close()  # No need for event_del, nothing listening (?).

  # TODO(pts): In a finally: block for all greenlets.
  #assert greenlet.getcurrent() is runnable_greenlets.popleft()
  runnable_greenlets.popleft()
  greenlet.getcurrent().parent = runnable_greenlets[0]

def SignalHandler(ev, sig, evtype, arg):
  SendExceptionAndRun(main_greenlet, (KeyboardInterrupt,))

if __name__ == '__main__':
  event.event(SignalHandler, handle=signal.SIGINT,
              evtype=event.EV_SIGNAL|event.EV_PERSIST).add()
  main_loop_greenlet = greenlet.greenlet(MainLoop)
  runnable_greenlets.appendleft(main_loop_greenlet)
  main_loop_greenlet.switch()

  ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  SetFdBlocking(ss, False)
  ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  # TODO(pts): Use ss._sock.
  ss.bind(('127.0.0.1', 8080))
  ss.listen(128)
  print >>sys.stderr, 'info: listening on: %r' % (
      ss.getsockname(),)
  while True:
    cs, csaddr = Accept(ss)
    handler_greenlet = greenlet.greenlet(Handler)
Exemplo n.º 55
0
 def setUp(self):
     self.e = event.event()
     self.__dummycount = 0
     self.__dummyargs = []
     self.__dummykw = {}
Exemplo n.º 56
0
 def accept(self):
     if not self.accept_channel:
         self.accept_channel = stackless.channel()
         event.event(self.handle_accept, handle=self.sock,
                     evtype=event.EV_READ | event.EV_PERSIST).add()
     return self.accept_channel.receive()
Exemplo n.º 57
0
 def init(self):
     self.__events = event.event()
     for evtclass in self.__events__:
         evtname = evtclass.__name__
         self.__events.create_event(evtname)
Exemplo n.º 58
0
    def __init__(self, graphics, level, players, inputqueue, options):

        self.graphics = graphics
        self.inputqueue = inputqueue
        graphics.load(level.objectsUsed)
        # initialize events
        events = event.events()
        events.token = event.event("token")  # arguments: none
        events.timeout = event.event("timeout")  # arguments: gamestate, object that timed out
        events.collision = event.event("collision")  # arguments: gamestate, object1, object2
        events.playerkilled = event.event("playerkilled")  # arguments: gamestate, bomberman, explosion
        events.playerspawned = event.event("playerspawned")  # arguments: bomberman
        events.bombexplode = event.event("bombexplode")  # arguments: bombcoordinate, bombrange
        events.poweruppickup = event.event("poweruppickup")  # arguments: bombcoordinate, bombrange

        events.eMouseEvent = event.event("eMouseEvent")

        # emits as data: the message as a string, player_id as an integer.
        events.eChtMessage = event.event("eChtMessage")

        # these all emit as data: player_id as an integer.
        events.eAcceForwOn = event.event("eAcceForwOn")
        events.eAcceBackOn = event.event("eAcceBackOn")
        events.eStepLeftOn = event.event("eStepLeftOn")
        events.eStepRghtOn = event.event("eStepRghtOn")
        events.eDropBombOn = event.event("eDropBombOn")
        events.ePowerup1On = event.event("ePowerup1On")
        events.ePowerup2On = event.event("ePowerup2On")
        events.ePowerup3On = event.event("ePowerup3On")
        events.eMinimapTOn = event.event("eMinimapTOn")

        events.eAcceForwOff = event.event("eAcceForwOff")
        events.eAcceBackOff = event.event("eAcceBackOff")
        events.eStepLeftOff = event.event("eStepLeftOff")
        events.eStepRghtOff = event.event("eStepRghtOff")
        events.eDropBombOff = event.event("eDropBombOff")
        events.ePowerup1Off = event.event("ePowerup1Off")
        events.ePowerup2Off = event.event("ePowerup2Off")
        events.ePowerup3Off = event.event("ePowerup3Off")
        events.eMinimapTOff = event.event("eMinimapTOff")

        events.eNeatQuit = event.event("eNeatQuit")

        events.token.register(engine.play)

        time = options.get("time", 120)  # TODO: tijd (timeleft in dit geval dacht ik) goed regelen

        level.createLevel(self, players)
        level.loadScripts(events)
        self.graphics.initEvents(events)

        self.gamestate = gamestate.gamestate(self, level, players, events, 10, time)  # TODO: framerate fixen
        graphics.buildLists(self.gamestate)

        self.inputqueuehandler = testqhandlers.QReaderEventWriter(inputqueue, self.gamestate)