Example #1
0
    def test_add_publish_channel_with_new_client_id(self):
        expected_publish_channels = {
            1: [{
                'routing_key': 'foo.routing.key',
                'channel_id': 2,
                'transform_id': 3
            }]
        }

        router_instance = router.Router()
        router_instance.transforms[3] = Mock()
        router_instance.add_publish_channel(1, 'foo.routing.key', 2, 3)

        self.assertEqual(router_instance.publish_channels,
                         expected_publish_channels)
Example #2
0
    def test_it_should_handle_a_publish_packet_with_unknown_client_id(self):
        publish_packet_id = 4
        client_id = 99
        channel_id = random.randint(1, 255)
        payload = bytes([channel_id]) + bytes([1, 2, 3, 4])

        router_instance = router.Router()

        with self.assertLogs(router.LOGGER) as log_messages:
            yield from router_instance.handle_packet(client_id,
                                                     publish_packet_id,
                                                     payload)

        log_messages = log_messages.output
        self.assertIn(
            'WARNING:router:Client 99 tried to publish, but has no channels set up',
            log_messages)
Example #3
0
def create_data_model():
    """Stores the data for the problem."""
    fn = 'instances/my2.txt'
    r = router.Router(fn)
    stops = r.get_stops()
    students = r.get_students()
    maxwalk = r.get_maxwalk()
    capacity = r.get_capacity()
    student_near_stops = r.get_student_near_stops()
    data = {}
    data['distance_matrix'] = r.adj_matrix(r.gen_adj())
    #need to change this
    data['demands'] = [0, 6, 4, 3, 3, 3, 3, 2, 0]
    data['vehicle_capacities'] = [capacity]
    data['num_vehicles'] = 1
    data['depot'] = 0
    return data
Example #4
0
def main():
    data_file = None
    template_loader = TemplateEngine(
        searchpath='/home/ubuntu/Desktop/devclub/Architecture2/templates')
    route_strings = []

    with open('routes.conf', 'r') as file:
        for line in file:
            route_strings.append(line[:-1])

    my_router = router.Router(route_strings)
    route = my_router.route_for_uri('/')
    template = None

    if route:
        template = template_loader.get_template(route.template)

    with open('index.html', 'w') as file:
        file.write(template.render(my_string='News!', my_list=news_list))

    route = my_router.route_for_uri('/news/')
    template = None

    if route:
        template = template_loader.get_template(route.template)

    with open('news.html', 'w') as file:
        file.write(template.render(my_string='News!', my_list=news_list))

    route = my_router.route_for_uri('/news/sport/')

    if route:
        template = template_loader.get_template(route.template)

    with open('news-sport.html', 'w') as file:
        file.write(template.render(my_string='News-Sport!',
                                   my_list=sport_list))

    route = my_router.route_for_uri('/news/sport/football/')

    if route:
        template = template_loader.get_template(route.template)

    with open('news-sport-football.html', 'w') as file:
        file.write(template.render(data_article=dict_article))
Example #5
0
    def test_it_should_handle_a_publish_packet_with_unknown_channel_id(self):
        publish_packet_id = 4
        client_id = 99
        channel_id = 100
        payload = bytes([channel_id]) + bytes([1, 2, 3, 4])

        router_instance = router.Router()
        router_instance.publish_channels = {client_id: []}

        with self.assertLogs(router.LOGGER) as log_messages:
            yield from router_instance.handle_packet(client_id,
                                                     publish_packet_id,
                                                     payload)

        log_messages = log_messages.output
        self.assertIn(
            'WARNING:router:Client 99 tried to publish message with unknown channel 100',
            log_messages)
Example #6
0
    def test_it_should_handle_a_publish_channel_packet(self):
        subscription_packet_id = 2
        expected_channel_id = random.randint(1, 255)
        expected_transform_id = random.randint(1, 255)
        expected_routing_key = 'test:routing:key'
        payload = bytes([expected_channel_id, expected_transform_id]) + bytes(
            expected_routing_key, encoding='ascii')
        expected_client_id = random.randint(1, 255)
        router_instance = router.Router()
        router_instance.add_publish_channel = Mock()

        yield from router_instance.handle_packet(expected_client_id,
                                                 subscription_packet_id,
                                                 payload)

        router_instance.add_publish_channel.assert_called_once_with(
            expected_client_id, expected_routing_key, expected_channel_id,
            expected_transform_id)
Example #7
0
    def test_handle_message(self):
        transform_id_0 = random.randint(0, 255)
        transform_id_1 = random.randint(0, 255)
        channel_id_0 = random.randint(0, 255)
        channel_id_1 = random.randint(0, 255)
        message = Mock()
        message.routing_key = 'some.routing.key'
        message.json.return_value = 'JSON'

        router_instance = router.Router()
        router_instance.send_packet = Mock()
        router_instance.transforms[transform_id_0] = Mock()
        router_instance.transforms[
            transform_id_0].to_packet.return_value = bytes([1, 2, 3])
        router_instance.transforms[transform_id_1] = Mock()
        router_instance.transforms[
            transform_id_1].to_packet.return_value = bytes([4, 5, 6])
        router_instance.subscription_channels['some.routing.key'] = [{
            'client_id':
            0,
            'channel_id':
            channel_id_0,
            'transform_id':
            transform_id_0
        }, {
            'client_id':
            1,
            'channel_id':
            channel_id_1,
            'transform_id':
            transform_id_1
        }]

        router_instance.handle_message(message)
        router_instance.transforms[
            transform_id_0].to_packet.assert_called_once_with('JSON')
        router_instance.transforms[
            transform_id_1].to_packet.assert_called_once_with('JSON')
        self.assertEqual(router_instance.send_packet.call_count, 2)
        router_instance.send_packet.assert_any_call(
            0, 4, bytes([channel_id_0, 1, 2, 3]))
        router_instance.send_packet.assert_any_call(
            1, 4, bytes([channel_id_1, 4, 5, 6]))
    def __init__(self, trip_time=6, extra_time = 2, battery_cap=100, average_mpkwh = 3, startLocation = ['-111.8338','41.7370'], 
        endLocation=['-109.5498','38.5733'], charger_radius=5, route_from_file=False, 
        chargers_from_file=False):
        """
        Create a new environment. Takes the expected trip time, a buffer of time, the capacity of the battery, 
        the mpkwh for the vehicle, the start location, the end location, and the radius to search for chargers 
        along the route. It also includes flags for loading a route and nearest chargers from a file instead
        of sending requests to the OSRM api and database. If these flags are true, the route and nearest charger
        files must be of the same route. 
        """

        print('Creating new environment')
        self.charger_database = db.ChargerDatabase()
        self.route_machine = router.Router()
        self.expected_time = trip_time * 4
        self.T = (trip_time + extra_time) * 4
        self.B = battery_cap
        self.average_mpkhw = average_mpkwh
        self.final_chargers = []

        if route_from_file:
            #Get a route from a file. 
            self.route_data = self.route_machine.get_route_from_file()
        else:
            #Get a route using the api call.
            self.route_data = self.route_machine.get_route(startLocation, endLocation)

        print('route points: ', len(self.route_data['route']))
        print('intersections: ',len(self.route_data['intersections']))
        if chargers_from_file:
            self.nearest_chargers = self.route_machine.get_nearest_chargers_from_file()
        else:
            self.nearest_chargers = self.route_machine.get_nearest_chargers(self.route_data)

        print('Number of chargers along route: ', len(self.nearest_chargers))

        print('Building route model')
        start_point = self.route_data['route'][0]
        end_point = self.route_data['route'][-1]
        self.route = self.build_route(start_point, end_point)
        self.states = self.compute_states()
        self.actions = [NavigationAction.driving, NavigationAction.charging]
Example #9
0
    def test_add_subscription_channel_with_new_routing_key(self):
        expected_subscription_channels = {
            'foo.routing.key': [{
                'client_id': 1,
                'channel_id': 2,
                'transform_id': 3
            }]
        }

        router_instance = router.Router()
        router_instance.transforms[3] = Mock()
        router_instance.queue = Mock()
        router_instance.exchange = Mock()
        yield from router_instance.add_subscription_channel(
            1, 'foo.routing.key', 2, 3)

        self.assertEqual(router_instance.subscription_channels,
                         expected_subscription_channels)
        router_instance.queue.bind.assert_called_once_with(
            router_instance.exchange, 'foo.routing.key')
Example #10
0
def main(args=sys.argv[1:]):
    args = parse_args(args)

    db = database.create(args.reset)

    routes = router.Router(db)

    app = web.Application()
    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader(router.TEMPLATE_DIR))

    app.router.add_get('/', routes.get_dashboard)
    app.router.add_get('/query', routes.get_query)
    app.router.add_post('/log', routes.post_json)
    app.router.add_get('/export', routes.get_export)
    app.router.add_get('/tags', routes.get_tags)

    web.run_app(app, host=args.host, port=args.port)

    print("Closing database...", end="")
    db.close()
    print("closed.")
Example #11
0
    def decorator(cls):
        import service
        if not issubclass(cls, service.ServiceController):
            raise exceptions.NeedToBeController(service=str(cls))

        cls.service_name = service_name
        for method_name in dir(cls):
            method = getattr(cls, method_name)

            # if method is handler then register it in dispatcher
            if hasattr(method, "_method_name") \
                and hasattr(method, "_service_name") \
                    and hasattr(method, "_method_type"):

                # register service in router to define message controller
                # class
                router.Router().register(method._service_name, cls)
                ep = entry_point.EntryPoint(method._service_name,
                                            method._method_name)
                cls.get_dispatcher().register(ep, method._method_type,
                                              method_name)

        return cls
Example #12
0
def parse_routers(f, l_map):
    routers = []
    r_map = {}
    r_links = []

    num_routers = int(next_line(f))

    for i in xrange(num_routers):
        addr = next_line(f)

        num_links = int(next_line(f))

        for j in xrange(num_links):
            link_id = next_line(f)
            
            r_links.append(link_id)

        router_id = next_line(f)

        # Construct router and update router map and list
        r = router_class.Router(router_id, r_links)
        r_map[router_id] = r
        routers.append(r)

        # Update the ends of the links connected to each router
        for l_id in r_links:
            mapped_link = l_map[l_id]
            mapped_link.add_end(r)

        # Reset r_links after each iteration
        r_links = []

    # Set the map for the router class
    router_class.Router.r_map = r_map

    return (routers, r_map)
Example #13
0
import config

config.SERVER_MOTD = util.create_textbox_data(b'''
    Welcome to Glitchland!
    
    The event has ended.
    The game can be played.
    
    However, leaderboard scores
    will not be updated.
''')

if len(config.SERVER_MOTD) > 120:
    raise RuntimeError("motd too long [was %i bytes]" % len(config.SERVER_MOTD))

rt = router.Router()

HEADERS_CORS = [
    ('Access-Control-Allow-Origin', '*'),
    ('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
]
HEADERS_HTML = [
    ('Content-Type', 'text/html')
]
HEADERS_TEXT = [
    ('Content-Type', 'text/plain')
]
HEADERS_JSON = [
    ('Content-Type', 'application/json')
]
Example #14
0
import router

router1 = router.Router('Cisco', 'IOSv', 'R1')
router2 = router.Router('Cisco', '3745', 'R2')
router3 = router.Router('Juniper', 'MX5', 'R3')

router1.add_interface("S0/0")
router2.add_interface("S0/1")
router1.add_interface("S0/2")
router2.add_interface("S0/2")
router3.add_interface("S0/0")
router3.add_interface("S0/2")

router1.add_interface_ip("S0/0", "1.1.1.1")
router2.add_interface_ip("S0/1", "2.2.2.2")
router1.add_interface_ip("S0/2", "3.3.3.3")
router2.add_interface_ip("S0/2", "4.4.4.4")
router3.add_interface_ip("S0/0", "5.5.5.5")
router3.add_interface_ip("S0/2", "6.6.6.6")

router1.connect("S0/0", router2, "S0/1")
router1.connect("S0/2", router3, "S0/2")
router3.connect("S0/0", router2, "S0/2")

router1.show()
router1.show_interface()
router1.show_neighbor()

router2.show()
router2.show_interface()
router2.show_neighbor()
Example #15
0
 def _get_router(self):
     return router.Router()
Example #16
0
def main():
    app = QtGui.QApplication(sys.argv)
    os.chdir(os.path.dirname(__file__))
    ui = uic.loadUi('simulator.ui')
    ui.setWindowIcon(QtGui.QIcon('icon.png'))

    def log(msg):
        ui.messages.appendPlainText('%s    %s' % (time.ctime().split()[3], msg))

    # Override default functions
    router.mktimer = mktimer
    router.log = log

    configfile = QtGui.QFileDialog.getOpenFileName(ui, 'Open router configuration file', '', '*.cfg')
    if not configfile:
        if len(sys.argv) != 2:
            sys.exit(1)
        configfile = sys.argv[1]
    cfg = ConfigParser.SafeConfigParser()
    try:
        cfg.read(str(configfile))
    except ConfigParser.MissingSectionHeaderError:
        QtGui.QMessageBox.warning(ui, 'OSPF-Sim', 'Invalid router configuration file!')
        sys.exit(app.quit())

    hostname = cfg.get('Local', 'hostname')
    ui.setWindowTitle('OSPF-Sim: %s' % (hostname, ))
    r = router.Router(hostname)

    # Create and configure Router interfaces
    ifaces = [i for i in cfg.sections() if i.startswith('Local:')]
    ui.interfaces.setRowCount(len(ifaces))
    for iface in ifaces:
        # Create
        name = iface.split(':')[1]
        bandwidth = cfg.get(iface, 'bandwidth')
        port = int(cfg.get(iface, 'port'))
        try:
            r.iface_create(name, bandwidth, port)
        except socket.error:
            QtGui.QMessageBox.information(ui, 'OSPF-Sim', 'An instance of %s is already running.' % (hostname, ))
            sys.exit(app.quit())
        # Configure
        address = cfg.get(iface, 'address')
        netmask = cfg.get(iface, 'netmask')
        link = cfg.get(iface, 'link')
        host = cfg.get(link, 'host')
        port = int(cfg.get(link, 'port'))
        r.iface_config(name, address, netmask, host, port)
        bandwidth = int(bandwidth)
        if bandwidth < 1000:
            bandwidth = '%d bps' % (bandwidth, )
        elif bandwidth < 1000000:
            bandwidth = '%.1f kbps' % (bandwidth / 1000.0, )
        elif bandwidth < 1000000000:
            bandwidth = '%.1f Mbps' % (bandwidth / 1000000.0, )
        else:
            bandwidth = '%.1f Gbps' % (bandwidth / 1000000000.0, )
        cols = [name, address, netmask, bandwidth, link]
        for val in cols:
            item = QtGui.QTableWidgetItem(val)
            ui.interfaces.setItem(ifaces.index(iface), cols.index(val), item)
    # Sort entries according to interface name
    ui.interfaces.sortItems(0, QtCore.Qt.AscendingOrder)

    def refresh_ui():
        # Routing Table
        rows = len(r._table)
        if ui.routingTable.rowCount() != rows:
            ui.routingTable.setRowCount(rows)
        for i in xrange(rows):
            col_count = 0
            metric = '%.2f' % (r._table[i].metric, )
            for col in ('dest', 'gateway', 'netmask', 'metric', 'iface'):
                val = (metric if col == 'metric' else getattr(r._table[i], col))
                item = QtGui.QTableWidgetItem(val)
                ui.routingTable.setItem(i, col_count, item)
                col_count += 1
        # Sort entries according to Destination
        ui.routingTable.sortItems(0, QtCore.Qt.DescendingOrder)
        # Link State Database
        rows = sum([len(n.networks) for n in r._lsdb.values()])
        if ui.linkStateDb.rowCount() != rows:
            ui.linkStateDb.setRowCount(rows)
        row_count = 0
        for lsa in r._lsdb.values():
            for network, data in lsa.networks.iteritems():
                cost = '%.2f' % (data[1], )
                col_count = 0
                for val in (lsa.adv_router, lsa.seq_no, lsa.age, network, cost):
                    item = QtGui.QTableWidgetItem(str(val))
                    ui.linkStateDb.setItem(row_count, col_count, item)
                    col_count += 1
                row_count += 1
        # Sort entries according to Router ID
        ui.linkStateDb.sortItems(0, QtCore.Qt.AscendingOrder)
    # Create timers
    ui_timer = QtCore.QTimer()
    router_timer = QtCore.QTimer()
    # Setup signal-slot connections
    QtCore.QObject.connect(app, QtCore.SIGNAL('lastWindowClosed()'), r.stop)
    QtCore.QObject.connect(ui_timer, QtCore.SIGNAL('timeout()'), refresh_ui)
    QtCore.QObject.connect(router_timer, QtCore.SIGNAL('timeout()'), router.poll)
    # Start timers
    ui_timer.start(1000)
    router_timer.start(500)
    # Start router and show UI
    r.start()
    ui.show()
    # Setup signal handlers
    signal.signal(signal.SIGTERM, lambda s, f: ui.close())
    signal.signal(signal.SIGINT, lambda s, f: ui.close())
    # Start event loop
    sys.exit(app.exec_())
Example #17
0
#CODE USAGE for SERVER
import router
import time

print '############################'
print 'ROUTER SIDE STARTED'
print '############################'
print '\n'
r = router.Router('Router', ('localhost', 6789, 'localhost', 6666), ('localhost', 9876, 'localhost', 9999))
time.sleep(2)

r.connect()
time.sleep(1)

Example #18
0
def parse_log_file(fn, log_index, comn):
    """
    Given a file name, return an array of Routers that hold the parsed lines.
    Lines that don't parse are identified on stderr and then discarded.
    :param fn: file name
    :param log_index: router id 0 for 'A', 1 for 'B', ...
    :param comn: common data
    :return: list of Routers
    """
    instance = 0
    lineno = 0
    search_for_in_progress = True
    rtrs = []
    rtr = None
    key1 = "SERVER (trace) ["  # AMQP traffic
    key2 = "SERVER (info) Container Name:"  # Normal 'router is starting' restart discovery line
    key3 = "ROUTER_LS (info)"  # a log line placed in separate pool of lines
    keys = [key1, key3]
    key4 = "ROUTER (info) Version:"  # router version line
    key5 = "ROUTER (info) Router started in "  # router mode
    with open(fn, 'r') as infile:
        for line in infile:
            if search_for_in_progress:
                # What if the log file has no record of the router starting?
                # This is an in_progress router and it is a pre-existing router instance
                # and not one found by restart discovery.
                # Any key or AMQP line indicates a router in-progress
                if any(s in line
                       for s in keys) or ("[" in line and "]" in line):
                    assert rtr is None
                    rtr = router.Router(fn, log_index, instance)
                    rtrs.append(rtr)
                    search_for_in_progress = False
                    rtr.restart_rec = router.RestartRecord(
                        rtr, line, lineno + 1)
            lineno += 1
            if key2 in line:
                # This line closes the current router, if any, and opens a new one
                if rtr is not None:
                    instance += 1
                rtr = router.Router(fn, log_index, instance)
                rtrs.append(rtr)
                rtr.restart_rec = router.RestartRecord(rtr, line, lineno)
                search_for_in_progress = False
                rtr.container_name = line[(line.find(key2) +
                                           len(key2)):].strip().split()[0]
            elif key3 in line:
                pl = None
                try:
                    pl = ParsedLogLine(log_index, instance, lineno, line, comn,
                                       rtr)
                except ValueError as ve:
                    pass
                except Exception as e:
                    # t, v, tb = sys.exc_info()
                    if hasattr(e, 'message'):
                        sys.stderr.write(
                            "Failed to parse file '%s', line %d : %s. Analysis continuing...\n"
                            % (fn, lineno, e.message))
                    else:
                        sys.stderr.write(
                            "Failed to parse file '%s', line %d : %s. Analysis continuing...\n"
                            % (fn, lineno, e))
                if pl is not None:
                    if pl.data.is_router_ls:
                        rtr.router_ls.append(pl)
            elif key4 in line:
                rtr.version = line[(line.find(key4) +
                                    len(key4)):].strip().split()[0]
            elif key5 in line:
                rtr.mode = line[(line.find(key5) +
                                 len(key5)):].strip().split()[0].lower()
            elif "[" in line and "]" in line:
                try:
                    if lineno == 130:
                        pass
                    do_this = True if not hasattr(
                        comn.args,
                        'skip_all_data') else not comn.args.skip_all_data
                    if not do_this:
                        # not indexing data. maybe do this line anyway
                        do_this = not any(s in line for s in [
                            ' @transfer', ' @disposition', ' @flow',
                            'EMPTY FRAME'
                        ])
                    if do_this:
                        pl = ParsedLogLine(log_index, instance, lineno, line,
                                           comn, rtr)
                        if pl is not None:
                            rtr.lines.append(pl)
                    else:
                        comn.data_skipped += 1
                except ValueError as ve:
                    pass
                except Exception as e:
                    # t, v, tb = sys.exc_info()
                    if hasattr(e, 'message'):
                        sys.stderr.write(
                            "Failed to parse file '%s', line %d : %s. Analysis continuing...\n"
                            % (fn, lineno, e.message))
                    else:
                        sys.stderr.write(
                            "Failed to parse file '%s', line %d : %s. Analysis continuing...\n"
                            % (fn, lineno, e))
                    # raise t, v, tb
            else:
                # ignore this log line
                pass
    return rtrs
Example #19
0
    def process_input():
        label = Label(outputs, text='Your Output Will appear here')
        label.grid(row=0, column=0)
        widgets.append(label)

        # create router
        if r.get() == 0:
            for l in widgets:
                l.destroy()

            router = str(e1.get())
            router_obj = rt.Router(router, g)
            ROUTERS.append(router_obj)
            label = Label(outputs, justify='left',
                          text='Successfully added router with name {}'.format(router_obj.name))
            label.grid(row=0, column=0)
            widgets.append(label)

        # create edge
        if r.get() == 1:
            for l in widgets:
                l.destroy()

            router_a = str(e1.get())
            router_b = str(e2.get())
            cost = int(e3.get())
            g.add_router(router_a, router_b, cost)
            label = Label(outputs, justify='left',
                          text="added connection between {} <--> {} with cost {}".format(router_a, router_b, cost))
            label.grid(row=0, column=0)
            widgets.append(label)

        # get path
        if r.get() == 2:
            for l in widgets:
                l.destroy()

            start = str(e1.get())
            dst = str(e2.get())
            if start in [router.name for router in ROUTERS]:
                for router in ROUTERS:
                    if router.name == start:
                        start = router

                start, finish, path, cost = router.get_path(dst)
                label = Label(outputs, justify="left", text="start: {}\nFinish: {}\nPath: {}\nCost: {}".format(
                    start, finish, "-->".join(path), cost))

            else:
                label = Label(outputs, justify='left',
                              text="Router object for {} does not exist create one and try again".format(start))

            label.grid(row=0, column=0)
            widgets.append(label)

        # delete router
        if r.get() == 3:
            for l in widgets:
                l.destroy()
            router_a = str(e1.get())
            if router_a in g.router_list:
                g.remove_router(router_a)
                label = Label(outputs, justify='left',
                              text="deleted router {}".format(router_a))
            else:
                label = Label(
                    outputs, justify="left", text="No router with identity {} found!".format(router_a))

            label.grid(row=0, column=0)
            widgets.append(label)

        # routing table
        if r.get() == 4:
            for l in widgets:
                l.destroy()

            start = str(e1.get())
            if start in [router.name for router in ROUTERS]:
                print("True")
                t = Text(outputs, height=(len(g.router_list) - 1),
                         width=50, bg="lightgrey")
                t.grid(row=0, column=0, sticky="nsew")

                for router in ROUTERS:
                    if router.name == start:
                        start = router

                path, cost, info = router.print_routing_table()
                head = "{:<8}{:<8} {:<10} {:<10} {:<10}\n".format(
                    "pos", "from", "to", "cost", "path")
                t.insert(END, head)
                row_i = 1
                col_i = 0
                for k, v in info.items():
                    From, to, cost, path = v
                    t.insert(END, "{:<8}{:<8} {:<10} {:<10} {:<10}\n".format(
                        k, From, to, cost, path))

                widgets.append(t)
                t.config(state=DISABLED)

            else:
                label = Label(outputs, justify='left',
                              text="Router object for {} does not exist create one and try again".format(start))

                label.grid(row=0, column=0)
            widgets.append(label)
Example #20
0
def process(fn, maxiter, maxtries, tm=None):
    print('Router init for', fn)
    print('time constraint: {0}\nmax iterations={1}\nmax tries for better result={2}'.format(tm, maxiter, maxtries))
    t0 = time.clock()
    router = r.Router(fn)
    stops = router.get_stops()
    students = router.get_students()
    maxwalk = router.get_maxwalk()
    capacity = router.get_capacity()
    print('Time: {0:.6f}s'.format(time.clock()-t0))

    minvalue = float('+Inf')
    tries = 0
    min_path_list = None
    min_students_dict = None
    it = 0
    twhile = time.clock()
    while True:
        if tm is not None:
            if (time.clock()-twhile) > tm*60:
                print('time limit reached: {0}  ({1}m)'.format(time.clock()-twhile, tm))
                break
        it+=1
        sys.stdout.write(str(it)+'\r')
        sys.stdout.flush()
        tries+=1
        # print('Local search', it, end=' ')
        # t0 = time.clock()
        global_path_list, global_students_dict = None, None
        while global_path_list is None or global_students_dict is None:
            global_path_list, global_students_dict = router.route_local_search()
        # print('{0:.5f}s'.format(time.clock()-t0))
        dist = router.get_distance()
        if dist < minvalue:
            print(dist)
            minvalue = dist
            min_path_list=global_path_list
            min_students_dict=global_students_dict
            tries=0
        if maxtries and tries>maxtries:
            print('tries {0}, it: {1}'.format(maxtries, it))
            break

        if maxiter and it>maxiter:
            break

    if tm is None:
        print('time elapsed: {0:.2f}s'.format(time.clock()-twhile))

    if tm is None:
        outfname = 'res-un-'+(fn.split('/')[1]).split('.')[0]+'.txt'
    else:
        outfname = 'res-'+str(tm)+'m-'+(fn.split('/')[1]).split('.')[0]+'.txt'

    with open('results/results.txt', mode='a', encoding='utf-8') as f:
        f.write('{6} {4} dist={3} iter={5}time_constraint={0} maxiter={1} maxtries={2}\n'.format(
            tm, maxiter, maxtries, dist, outfname, it, datetime.datetime.now().strftime("%Y-%m-%d %H:%M")))

    global_path_list = min_path_list
    global_students_dict = min_students_dict

    print(outfname)
    with open('results/'+outfname, mode='wt', encoding='utf-8') as f:
        for path in global_path_list:
            f.write(' '.join(str(elem) for elem in path)+'\n')
        f.write('\n')
        for k, v in global_students_dict.items():
            f.write('{0} {1}\n'.format(k, v))
    return [global_path_list, global_students_dict]
Example #21
0
#!/usr/bin/env python3

import router
import time

if __name__ == '__main__':
    fn = 'instances/sbr3.txt'

    print('Router init', end=' ')
    t0 = time.perf_counter()
    router = router.Router()
    stops = router.get_stops()
    students = router.get_students()
    maxwalk = router.get_maxwalk()
    capacity = router.get_capacity()
    print('{0:.5f}s'.format(time.perf_counter() - t0))
    print()

    nf = 0
    print('loop')
    it = 1000
    for i in range(it):
        print('{0}/{1} ({2}%)'.format(i, it, 100 * (i / it)))
        t0 = time.perf_counter()
        global_path_list, global_students_dict = router.route_local_search()
        if global_path_list is None and global_students_dict is None:
            nf += 1
    print('not feasible solutions: {0}/{1} ({2}%)'.format(
        nf, it, 100 * (nf / it)))
Example #22
0
 def run(self):
     route = router.Router()
     route.run()
Example #23
0
import sys
import router

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Usage: python start_router.py config_filename')
        sys.exit(1)

    config_filename = sys.argv[1]
    print('config file name: ' + config_filename)
    r = None
    try:
        r = router.Router(config_filename)
        r.start()
    finally:
        if r: r.stop()
Example #24
0
import wsgiref.validate
import router as router_module

from utils import parse_http_x_www_form_urlencoded_post_data, \
    get_first_element, parse_http_get_data, parse_http_headers, \
    parse_http_content_type, parse_http_uri

DEBUG = True
STATIC_URL = '/static/'
STATIC_ROOT = 'data/'

router = router_module.Router()

data_messages = [
    b'Name: user<br>Message: hi!',
    b'Name: user<br>Message: hi!',
]


@wsgiref.validate.validator
def application(environ, start_response):
    # https://www.python.org/dev/peps/pep-3333/#environ-variables
    REQUEST_METHOD = environ['REQUEST_METHOD']
    CONTENT_TYPE, CONTENT_TYPE_KWARGS = parse_http_content_type(environ)
    SERVER_PROTOCOL = environ['SERVER_PROTOCOL']
    HEADERS = parse_http_headers(environ)
    URI_PATH = environ['PATH_INFO']
    URI_QUERY = environ['QUERY_STRING']
    URI = parse_http_uri(environ)
    POST = parse_http_x_www_form_urlencoded_post_data(environ)
    GET = parse_http_get_data(environ)
Example #25
0
    subnet1 = manager_subnet.create("10.2.1.0/24")
    subnet2 = manager_subnet.create("10.2.2.0/24")
    subnet3 = manager_subnet.create("10.2.3.0/24")
    subnet4 = manager_subnet.create("10.2.4.0/24")
    subnet5 = manager_subnet.create("10.3.1.0/24")
    subnet6 = manager_subnet.create("10.3.2.0/24")

    print(asys.ask(subnet1, "name"))
    print(asys.ask(subnet2, "name"))
    print(asys.ask(subnet3, "name"))
    print(asys.ask(subnet4, "name"))
    print(asys.ask(subnet5, "name"))
    print(asys.ask(subnet6, "name"))

    RA = router.Router("RouterA", asys, manager_subnet)
    RA.iface_create("eth0", 1000)
    RA.iface_config("eth0", "10.2.1.1", "255.255.255.0")
    RA.iface_create("eth1", 10)
    RA.iface_config("eth1", "10.2.2.1", "255.255.255.0")
    RA.iface_create("eth2", 1000)
    RA.iface_config("eth2", "10.3.1.1", "255.255.255.0")

    RB = router.Router("RouterB", asys, manager_subnet)
    RB.iface_create("eth0", 1000)
    RB.iface_config("eth0", "10.2.3.1", "255.255.255.0")
    RB.iface_create("eth1", 1000)
    RB.iface_config("eth1", "10.2.2.254", "255.255.255.0")
    RB.iface_create("eth2", 1000)
    RB.iface_config("eth2", "10.3.2.1", "255.255.255.0")
Example #26
0
#!/usr/bin/env python3

import router
import time

if __name__ == '__main__':
    fn = 'instances/sbr3.txt'

    print('Router init', end=' ')
    t0 = time.clock()
    router = router.Router(fn)
    stops = router.get_stops()
    students = router.get_students()
    maxwalk = router.get_maxwalk()
    capacity = router.get_capacity()
    print('{0:.5f}s'.format(time.clock() - t0))
    print()

    nf = 0
    print('loop')
    it = 1000
    for i in range(it):
        print('{0}/{1} ({2}%)'.format(i, it, 100 * (i / it)))
        t0 = time.clock()
        global_path_list, global_students_dict = router.route_local_search()
        if global_path_list == None and global_students_dict == None:
            nf += 1
    print('not feasible solutions: {0}/{1} ({2}%)'.format(
        nf, it, 100 * (nf / it)))
Example #27
0
from jinja2 import (Environment, FileSystemLoader, Template)

import router
import templateEngine

news_list = ['Sport', 'Politic', 'Live', 'World', 'Economics']
sport_list = ['Football', 'Tenis', 'Hoky', 'Basketball', 'Cars']

route_strings = []
with open('routes.conf', 'r') as file:
    for line in file:
        route_strings.append(line[:-1])

template_loader = templateEngine.TemplateEngine(
    searchpath='/usr/share/uwsgi/www/mySite/get')
my_router = router.Router(route_strings)


def do_GET(environ, environ_values):
    template = None
    url = (environ_values['PATH_INFO'])
    route = my_router.route_for_uri(url)

    if route:
        template = template_loader.get_template(route.uri + route.template)

    response_body = template.render(my_string='News!', my_list=news_list)

    return response_body.encode('utf-8')

Example #28
0
import router
from utils import Utils
from hack import Hack

utils = Utils()
a = router.Router(256, utils.keygenFromWord("Blank"))
print(a.encrypt("Plaintext"))
print(a.decrypt(a.encrypt("Plaintext")))
with open("beemovie.txt") as f:
    content = f.readlines()

content = [x.strip() for x in content]
while "" in content:
    content.remove("")
hackIt = Hack(3, 5, 256, "s")
for i in range(300):
    print("iter ", i)
    for c in content:
        hackIt.getPacket(a.encrypt(c))
print(hackIt.solveWEP())
Example #29
0
	def __init__(self):
		super(VrpEnv, self).__init__()
		self.minvalue = float('+Inf')
		self.min_path_list = None
		self.min_students_dict = None
		self.instance_file = 'instances/my2.txt'
		self.router = router.Router(self.instance_file)
		self.stops = self.router.get_stops()
		self.students = self.router.get_students()
		self.maxwalk = self.router.get_maxwalk()
		self.capacity = self.router.get_capacity()
		self.router.generate_student_near_stops()
		self.student_near_stops = self.router.student_near_stops
		self.router.generate_stop_near_students()
		self.stop_near_students=self.router.stop_near_students
		#print(self.router.stop_near_students)
		self.router.generate_stop_near_stops()
		self.stop_near_stops=self.router.stop_near_stops
		# Define action and observation space
		# They must be gym.spaces objects
		# Example when using discrete actions:
		self.action_space = spaces.Discrete(3)  
		# N to D
		# D to N
		# N to N
		# Example for using image as input:
		#print("SELF.STOPS", self.stops)
		self.no_of_stops=len(self.stops)
		
		self.demand= self.router.get_demand() 
		self.reward = -1000
	
		self.local_stops = self.stops
		self.gloabl_stops = self.stops
		
		self.global_path_list = []
        #self.total_local_distance = 0
	
		# choosing a random node to start with
		self.current_point = random.randint(1,self.no_of_stops-1)
		self.local_path_list = [ self.current_point ]
		# initiliazing the observation dataframe
		self.column_names = ["stop_id", "stop_x", "stop_y","maxwalk","demand","capacity", "visited", "current_point"]
		self.obs_columns = ["demand","capacity", "visited", "current_point"]
		self.info_columns = ["stop_id", "stop_x", "stop_y","maxwalk"]
		self.observation = pd.DataFrame(columns = self.column_names)
		self.observation['stop_id']=list(self.stops.keys())
		self.observation['stop_x']=[self.stops.get(x)[0] for x in self.stops]
		self.observation['stop_y']=[self.stops.get(x)[1] for x in self.stops] 
		self.observation['maxwalk']=[self.maxwalk] *self.no_of_stops  
		self.observation['demand'] = self.demand                                        
		self.observation['capacity']=[self.capacity] *self.no_of_stops 
		self.observation['visited'] = [0]* self.no_of_stops
		self.observation['current_point'] = [self.current_point] * self.no_of_stops 
		# 0: not visited, 1: visited; if the capacity < demand at that node, then keep as not visited
			
		# depot. coordinates = (0,0)
		self.done = False

		self.observation_space = spaces.Box(low=-100, high=100, shape=(self.no_of_stops,4), dtype=np.uint8)
		# stock market: self.observation_space = spaces.Box(low=0, high=1, shape=(6, 6), dtype=np.float16)
	    
		self.action_space = spaces.Discrete(3)
Example #30
0
import router
import api
import interfaces

router_object = router.Router()

import pickle

# Skill-specific required packages
import numpy as np
#import pyrealsense2 as rs
import cv2
import imutils
import base64


# Skill-specific helper functions
def adjust_gamma(image, gamma=1.0):
    invGamma = 1.0 / gamma
    table = np.array([((i / 255.0)**invGamma) * 255
                      for i in np.arange(0, 256)]).astype("uint8")
    return cv2.LUT(image, table)


def base64_to_image(uri):
    encoded_data = uri.split(',')[1]
    nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    return img