Example #1
0
def readInitialization(file):
    fid = open(file, "r")
    data = fid.read()
    dataSplit = data.split()
    for i in [0, 2, 4]:
        with Switch(dataSplit[i]) as case:
            if case('Station:'):
                Station = dataSplit[i + 1]
                with Switch(Station) as station:
                    if station('Asian'):
                        delayTime = 0
                    if station('American'):
                        delayTime = 1
                    if station('Persian'):
                        delayTime = 2
                    if station('Italian'):
                        delayTime = 3
                    if station('Latin'):
                        delayTime = 4
#print "Station: ", Station
            if case('ipaddr:'):
                ipaddr = dataSplit[i + 1]
#print "ipaddr: ", ipaddr
            if case('port:'):
                port = int(dataSplit[i + 1])

#print "port: ", port

    return [Station, ipaddr, port, delayTime]
Example #2
0
 def test_get_switch(self):
     """get by id first the use the name for testing get by name"""
     pw_db = Ponicwatch_db("sqlite3")
     switch1 = Switch(pw_db, id=1)
     self.assertEqual(switch1["switch_id"], 1)
     print("[{}] has the id: {}".format(switch1, switch1["switch_id"]))
     name = switch1["name"]
     switch1 = Switch(pw_db, name=name)
     self.assertEqual(switch1["switch_id"], 1)
def test(duration=0
         ):  # Runs oscillator, counts interrupts, responds to switches
    if duration:
        print("Test interrupt on pin X8 for {:3d} seconds".format(duration))
    objSched = Sched()  # Requires jumper between pins X7 and X8
    objSched.add_thread(oscillator(1))  # 1Hz
    objSched.add_thread(irqtest_thread())
    Switch(objSched, 'X5', open_func=x5print,
           open_func_args=("Red", ))  # X5 triggers on open
    Switch(objSched, 'X6', x6print, ("Yellow", ))  # X6 triggers on close
    if duration:
        objSched.add_thread(stop(duration, objSched))
    objSched.run()
Example #4
0
def main():  # Programa principal
    # Routers
    RINT = Router('RINT', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RoExt = Router('RoExt', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RBor1 = Router('RBor1', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RBor2 = Router('RBor2', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)

    #Switches
    SW1 = Switch('SW1', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SW2 = Switch('SW2', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SW3 = Switch('SW3', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SwExt = Switch('SwExt', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)

    print(SW1.interfaces)
Example #5
0
def main():
    pi = pigpio.pi()
    srv = Servo(pi)
    swi = Switch(pi, srv)
    door = Door(pi)

    try:
        while True:
            logger.debug("waiting id card")
            # ここでカード読み込み
            if database.confirm("ここに番号"), "ここにIDm"):
                srv.open_lock()
                slack.send_slack("ここになまえ")
                time.sleep(10)
                while door.door_status() == door.OPEN:
                    time.sleep(0.5)
                srv.close_lock()
            else:
                led.red_led_on()
                print("Can't confirm.")
                time.sleep(3)
                led.red_led_off()
    except:
        pi.stop()
        r.close()
        main()
Example #6
0
def main():
    global relay_pin

    client = MQTTClient(CLIENT_ID, SERVER)
    client.set_callback(new_msg)

    try:
        client.connect()
    except OSError:
        print("MQTT Broker seems down")
        print("Resetting after 20 seconds")
        time.sleep(20)
        machine.reset()

    client.subscribe(COMMAND_TOPIC)

    # Publish as available once connected
    client.publish(AVAILABILITY_TOPIC, "online", retain=True)

    switch_pin = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
    reed_switch = Switch(switch_pin)

    # Initialize state of garage door after booting up
    if switch_pin.value():
        client.publish(STATE_TOPIC, "open", retain=True)
    else:
        client.publish(STATE_TOPIC, "closed", retain=True)

    relay_pin = machine.Pin(4, machine.Pin.OUT, 0)

    try:
        while True:

            reed_switch_new_value = False

            # Disable interrupts for a short time to read shared variable
            irq_state = machine.disable_irq()
            if reed_switch.new_value_available:
                reed_switch_value = reed_switch.value
                reed_switch_new_value = True
                reed_switch.new_value_available = False
            machine.enable_irq(irq_state)

            # If the reed switch had a new value, publish the new state
            if reed_switch_new_value:
                if reed_switch_value:
                    client.publish(STATE_TOPIC, "open")
                else:
                    client.publish(STATE_TOPIC, "closed")

            # Process any MQTT messages
            if client.check_msg():
                client.wait_msg()

            time.sleep_ms(500)

    finally:
        client.publish(AVAILABILITY_TOPIC, "offline", retain=False)
        client.disconnect()
        machine.reset()
Example #7
0
def start_car():
    ## 启动小车
    a = Switch('switch002', 'host_remote')
    a.execute('on')  ## 启动小车
    print("\033[1;31;47mStart the car\033[0m")
    time.sleep(3)
    a.execute('off')  ## 关闭小车
 def menupresidente(self):
     layout_presidente = [
         [sg.Text("Menu Presidente")],
         [
             sg.ReadButton("Cadastrar Presidente"),
             sg.ReadButton("Listar Presidentes")
         ],
         [
             sg.ReadButton("Excluir Presidente"),
             sg.ReadButton("Editar Presidente")
         ],
     ]
     window = sg.Window("Gerenciar presidente",
                        default_button_element_size=(15, 1),
                        auto_size_buttons=False,
                        grab_anywhere=False).Layout(layout_presidente)
     botao, valor = window.Read()
     with Switch(valor) as case:
         if case('Criar'):
             self.cadastrar_presidente()
         if case('Editar'):
             self.cadastrar_presidente()
         if case('Excluir'):
             self.cadastrar_presidente()
         if case('Listar'):
             self.cadastrar_presidente()
    def cadastrar_presidente(self):
        layout_criar = [[sg.Text("Cadastrar aluno")],
                        [
                            sg.Text('Nome', size=(15, 1)),
                            sg.InputText('', key='nome', size=(15, 1))
                        ],
                        [
                            sg.Text('Matricula', size=(15, 1)),
                            sg.InputText('', key='matricula', size=(15, 1))
                        ],
                        [
                            sg.Text('CPF', size=(15, 1)),
                            sg.InputText('', key='cpf', size=(15, 1))
                        ],
                        [
                            sg.Text('Senha', size=(15, 1)),
                            sg.InputText('', key='senha', size=(15, 1))
                        ],
                        [sg.ReadButton("Cadastrar"),
                         sg.ReadButton("Voltar")]]
        window = sg.Window("Gerenciar Aluno").Layout(layout_criar)
        event, valor = window.Read()
        with Switch(valor) as case:
            if case('Cadastrar'):
                nome = valor['nome']
                matricula = valor['matricula']
                cpf = valor['cpf']
                senha = valor['senha']
                self.__ctrlPresidente.inclui_presidente(
                    self.__ctrlPresidente, nome, matricula, cpf, senha)

            if case('Voltar'):
                TelaPresidente.menupresidente(self)
Example #10
0
    def menu_aluno(self):
        layout_aluno = [[sg.Text("Menu Aluno")],
                        [
                            sg.ReadButton("Criar", key='Criar'),
                            sg.ReadButton("Listar", key='Listar')
                        ],
                        [
                            sg.ReadButton("Editar", key='Editar'),
                            sg.ReadButton("Excluir", key='Excluir')
                        ],
                        [
                            sg.Text("    "),
                            sg.ReadButton("Voltar", key='Voltar')
                        ]]
        window = sg.Window("Gerenciar Aluno").Layout(layout_aluno)
        event, valor = window.Read()
        with Switch(valor) as case:
            if case('Criar'):
                self.cadastrar_aluno()

            if case('Editar'):
                self.cadastrar_aluno()
            if case('Excluir'):
                self.cadastrar_aluno()
            if case('Listar'):
                self.cadastrar_aluno()
Example #11
0
def getLastTotal(Station):
    conn = sqlite3.connect(
        "/var/www/html/PeopleTracker-C4C/HTML/mainDatabase.db")
    curs = conn.cursor()
    with Switch(Station) as case:
        if case('Asian'):
            curs.execute("SELECT * FROM Asian")
            data = curs.fetchall()
        if case('American'):
            curs.execute("SELECT * FROM American")
            data = curs.fetchall()
        if case('Persian'):
            curs.execute("SELECT * FROM Persian")
            data = curs.fetchall()
        if case('Italian'):
            curs.execute("SELECT * FROM Italian"),
            data = curs.fetchall()
        if case('Latin'):
            curs.execute("SELECT * FROM Latin")
            data = curs.fetchall()

    print "about to get data"
    L = len(data)
    print "length: ", L
    Total = data[L - 1]
    print "Station: ", Station
    print "Total,: ", Total[2]
    return Total[2]
Example #12
0
def postProcessing(sPhraseSpec, node_dict):
  #verifica punct in caso di interrogative
    questionMarksList = list(filter(lambda elem:
                                    elem.get_dependency() == 'punct' and elem.get_original_token() == '?', node_dict.values()))
    if (len(questionMarksList) > 0):
        sPhraseSpec.setFeature(Feature.INTERROGATIVE_TYPE,
                               InterrogativeType.YES_NO)
        print(str(len(questionMarksList)))
  #POST PROCESSING IN CASO IN CUI IL SOGGETTO NON SIA STATO ESPLICITATO
    if sPhraseSpec.getSubject() == None:
      #sPhraseSpec.setFeature(LexicalFeature.EXPLETIVE_SUBJECT, True)
      verbalPhrase = sPhraseSpec.getVerbPhrase()
      allFeatures = verbalPhrase.getAllFeatures()
      with Switch(str(verbalPhrase.getFeature(Feature.PERSON))) as case:
        if case('FIRST'):
           sPhraseSpec.setSubject('I') if str(verbalPhrase.getFeature(
               Feature.NUMBER)) == 'SINGULAR' else sPhraseSpec.setSubject('we')
        if case('SECOND'):
          str(verbalPhrase.getFeature(LexicalFeature.GENDER))
        if case('THIRD'):
            if str(verbalPhrase.getFeature(Feature.NUMBER)) != 'SINGULAR':
              sPhraseSpec.setSubject('they')
            else:  # TODO verificare genere
              if verbalPhrase.getFeature(LexicalFeature.GENDER)==None:
               sPhraseSpec.setSubject('it')
              else:
               sPhraseSpec.setSubject('he')
    return sPhraseSpec
Example #13
0
def main():
    try:
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((HOST, PORT))
    except OSError as e:
        print(e)
        exit(1)

    jobs = load_file(sys.argv[1])
    run_all_jobs(jobs)

    while True:
        server.listen()
        conn, _ = server.accept()
        req = read(conn).split(' ')
        switch = Switch()
        switch.add_case(lambda: req[0] == 'getpid', lambda: get_pid(conn))
        switch.add_case(lambda: req[0] == 'stop',
                        lambda: stop_proccess(jobs, req[1]))
        switch.add_case(lambda: req[0] == 'start',
                        lambda: start_proccess(jobs, req[1]))
        switch.add_case(lambda: req[0] == 'signal',
                        lambda: send_signal(jobs, req[1]))
        switch.add_case(lambda: req[0] == 'status', lambda: status(jobs))
        switch.add_case(lambda: req[0] == 'close', lambda: exit(0))
        switch.switch()
        conn.close()
    def entrar(self):
        login_principal = [[sg.Text("Controle de Acesso ao CASIN")],
                           [
                               sg.Text('Matricula'),
                               sg.InputText(size=(15, 1),
                                            do_not_clear=True,
                                            justification='left',
                                            key='matricula')
                           ],
                           [
                               sg.Text('Matricula'),
                               sg.InputText(size=(15, 1),
                                            do_not_clear=True,
                                            justification='left',
                                            key='senha')
                           ], [sg.ReadButton('Entrar'),
                               sg.ReadButton('Sair')]]
        login = sg.Window("Controle de Acesso",
                          default_button_element_size=(5, 2),
                          auto_size_buttons=False,
                          grab_anywhere=False).Layout(login_principal)
        event, valor = login.Read()
        with Switch(valor) as case:
            if case('Entrar'):
                matricula = valor['matricula']
                senha = valor['senha']
                CtrlPrincipal.login(self.__ctrl_principal, matricula, senha)

            if case('Sair'):
                CtrlPrincipal.finalizar(self.__ctrl_principal)
def invoke_command_on(input):
    for case in Switch(get_command_from_input(input)):
        if case(QUIT):
            quit()
            break
        if case(PERF):
            break
        if case(QUIT_WITHOUT_SAVE):
            break
        if case(KICK):
            break
        if case(HELP):
            break
        if case(BAN):
            print(
                "This will execute a kick ban. It will then be broadcast to the entire server."
            )
            break
        if case(STATUS):
            print(
                "This will cause the console to print out a partial list of connected clients along with their ping, ip"
            )
            break
        if case(TIME):
            time()
            break
        if case(COMMANDS):
            commands()
            break
        if case():  # default, could also just omit condition or 'if True'
            print(
                "Command not found. For information on the commands, type commands"
            )
Example #16
0
    def __init__(self, post: RedditPostContents, post_type: str) -> None:
        self.type = post_type
        with Switch(self.type) as case:
            if case("post"):
                self.credit_string = "Post by:"
            if case("meme"):
                self.credit_string = "Meme by:"
        super().__init__(
            colour=discord.Color.orange(),
            title=post.title,
            image=post.image,
            source=post.subreddit,
            author=post.author,
            author_icon=post.author_avatar,
            link=post.link,
            footer_author_url=post.author_avatar,
            footer_string=
            f"Posted on: {post.subreddit}\n{self.credit_string} {post.author}",
        )

        self.object_embed_session.insert_field_at(
            20,
            name="Link to post",
            value=f"[Go to post]({self.link})",
            inline=True,
        )
Example #17
0
    def _handle_ConnectionUp(self, event):

        sw = self.switches.get(event.dpid)
        sw_str = dpidToStr(event.dpid)
        log.info("Saw switch com up: %s", sw_str)
        name_str = self.t.id_gen(dpid=event.dpid).name_str()

        if name_str not in self.t.switches():
            log.warn("Ignoring unknown switch %s" % sw_str)
            return

        if sw is None:
            log.info("Added fresh switch %s" % sw_str)
            sw = Switch()
            self.switches[event.dpid] = sw
            sw.connect(event.connection)

        else:
            log.info("Odd - already saw switch %s come up" % sw_str)
            sw.connect(event.connection)
        sw.connection.send(of.ofp_set_config(miss_send_len=MISS_SEND_LEN))

        if len(self.switches) == len(self.t.switches()):
            log.info("Woo! All switches up")
            self.all_switches_up = True

            self._save_paths()
            # log.info("self.routeTable : %s" % self.routeTable)

            start = time()
            self._install_paths()
            log.info("use %s seconds to install paths" % (time() - start))

            # the pre_install_paths should have been installed
            log.info("Woo! All paths ok")
Example #18
0
    def create_switches(self):
        '''
        Create switches with definition in the config file
        '''

        switches = []
        for name in self.config.sections():
            if name != "COMMON":
                sid = name

                other_options = dict(self.config.items(sid, vars))

                if self.config.has_option(name, "active"):
                    del other_options["active"]
                    if not self.config[name].getboolean("active"):
                        continue

                if not self.config.has_option(name, "timeout"):
                    raise Exception("switch doesn't have timeout set")

                del other_options["timeout"]
                timeout = int(self.config[name]["timeout"])

                to_file = True
                if self.config.has_option(name, "to_file"):
                    del other_options["to_file"]
                    to_file = self.config[name].getboolean("to_file")

                sw = Switch(sid, timeout, to_file, **other_options)
                switches.append(sw)

                if len(switches) > self.num_switches:
                    break

        return switches
Example #19
0
    def __init__(self, env, period):
        super(STFQ_tb, self).__init__(env, period)

        self.sched_alg = "STFQ"
        self.sched_tree_shape = {0: []}
        self.switch = Switch(self.env, self.period, self.sw_ready_out_pipe, self.sw_pkt_in_pipe, self.sw_pkt_out_pipe, self.start_dequeue_pipe, self.sched_tree_shape, self.sched_alg)

        # start dequeueing immediately
        self.start_dequeue_pipe.put(1)

        # create flows
        rates = [10, 13, 20, 25]
        num_flows = len(rates)
        base_sport = 0
        self.generators = []
        self.pkt_gen_pipes = []
        for i in range(num_flows):
            pipe = simpy.Store(env)
            rate = rates[i] # Gbps
            pkt = Ether()/IP()/TCP(sport=base_sport+i)/('\x00'*10)
            meta = StdMetadata(len(pkt), 0b00000001, 0b00000100, [0], 0, sched_meta=STFQMeta())
            pkt_gen = PktGenerator(env, period, pipe, rate, pkt, meta, cycle_limit=5000)
            self.generators.append(pkt_gen)
            self.pkt_gen_pipes.append(pipe)

        self.egress_link_rate = 10 # Gbps

        self.arbiter = Arbiter(env, period, self.pkt_gen_pipes, self.sw_pkt_in_pipe)
        self.receiver = PktReceiver(env, period, self.sw_pkt_out_pipe, self.sw_ready_out_pipe, self.egress_link_rate)

        self.env.process(self.wait_complete()) 
Example #20
0
def index():
    status_class = Status()
    switch_class = Switch()
    timer_class = Timer()

    # heroku側からparamsの受け取り
    params = request.json
    kadenId = params['kadenId']
    manipulateId = params['manipulateId']
    timerDatetime = params['timerDatetime']

    #ステータス管理処理
    if int(manipulateId) == 0:
        result = status_class.checkStatus(kadenId)
        result = {
            "result": result
        }

    #ONOFF処理
    elif int(manipulateId) in [1, 2]:
        onOffData = params
        result = switch_class.Switching(onOffData) #kadenID manipulateIdを渡す
        result = {
            "result": result
        }

    #タイマー処理
    elif int(manipulateId) in [3, 4]:
        timer_class = Timer()      
        result = timer_class.timerSetting(params) #kadenId manipulateId,timerDatetimeを渡す
        result = {
            "result": result
        }

    return json.dumps(result, ensure_ascii=False)
    def parse_sel_switches(self, sel_switches):
        for each_id, switch in sel_switches.iteritems():
            # prepare the switch id
            switch_id = "s" + str(each_id)

            sw = self.get_node_object(switch_id)
            # Check to see if a switch with this id already exists in the graph,
            # if so grab it, otherwise create it
            if not sw:
                sw = Switch(switch_id, self)
                self.graph.add_node(switch_id, node_type="switch", sw=sw)
                self.switch_ids.append(switch_id)
            # Parse out the information about all the ports in the switch
            switch_ports = {}
            for port in switch["ports"]:
                switch_ports[port["portId"]] = Port(sw, port_json=port)

            sw.ports = switch_ports

            # Parse group table if one is available
            if "groups" in sel_switches[each_id]:
                sw.group_table = GroupTable(sw,
                                            sel_switches[each_id]["groups"])

            # Parse all the flow tables and sort them by table_id in the list
            switch_flow_tables = []
            for table_id in sel_switches[each_id]["flow_tables"]:
                switch_flow_tables.append(
                    FlowTable(sw, table_id,
                              sel_switches[each_id]["flow_tables"][table_id]))

            sw.flow_tables = sorted(switch_flow_tables,
                                    key=lambda flow_table: flow_table.table_id)
    def switch_feature_handler(self, event):
        dpid = event.msg.datapath_id
        try:
            switch = self.dpid_to_switch[dpid]
        except KeyError:
            self.dpid_to_switch[dpid] = Switch(event.msg.datapath)
            switch = self.dpid_to_switch[dpid]

        for port_no, port in event.msg.ports.iteritems():
            if port_no not in switch.ports:
                p = Port(port=port, dp=event.msg.datapath)
                switch.ports[port_no] = p

            p = switch.ports[port_no]

            if port_no == ofproto_v1_0.OFPP_LOCAL:
                switch.name = port.name.rstrip('\x00')
            else:
                # port.curr is a number of 32 bits, only used 12 bits in ovs
                # represents current features of the port.
                # LOCAL port doesn't have a cost value
                curr = port.curr & 0x7f  # get last 7 bits
                p.cost = 64 / curr
                print 'cost:', p.cost

        switch.update_from_config(self.switch_cfg)
        self.routing_algo.topology_last_update = time.time()
Example #23
0
    def arithmetic_phase(self, operation, node):
        """
        Arithmetic phase

        """
        for case in Switch(operation):
            if case('AND'):
                self.output[:, node] = np.bitwise_and(self.input1[:, node], self.input2[:, node])
                break
            if case('OR'):
                self.output[:, node] = np.bitwise_or(self.input1[:, node], self.input2[:, node])
                break
            if case('XOR'):
                self.output[:, node] = np.bitwise_xor(self.input1[:, node], self.input2[:, node])
                break
            if case('NOR'):
                self.output[:, node] = np.bitwise_nor(self.input1[:, node])  # Single operand instruction
                break
            if case('ADD'):
                self.output[:, node] = np.add(self.input1[:, node], self.input2[:, node])
                break
            if case('SUB'):
                self.output[:, node] = np.subtract(self.input1[:, node], self.input2[:, node])
                break
            if case('MULT'):
                self.output[:, node] = np.multiply(self.input1[:, node], self.input2[:, node])
                break
            if case():  # Default
                print("Error! Undefined instruction ", operation)
                exit()
Example #24
0
def create(name:str, url : str, farbe1:str, farbe2: str):
  if farbe1.lowcase() == farbe2.lowcase():
   print("err")
  with Switch(farbe1) as case:
    if case.match(r'rot|Rot'):
      farbe1 = 255,0,0
    if case.match(r'grün|Grün'):
      farbe1 = 124,252,0
Example #25
0
def generateThreeLayer(k):
	# initialize essential parameters 
	num_ports_per_switch = k	# number of ports per switch
	num_pod = k					# number of pods
	num_servers = int(k/2)			# number of hosts under a ToR switch 
	num_tor = int(k/2)				# number of ToR switches in a pod 
	num_agg = int(k/2)				# number of aggregation switches in a pod 
	num_core = int((k**2)/4)			# number of core switches 
	total_servers = int((k**3)/4)	# number of total servers 

	# initialize component generation 
	num_racks = num_pod * num_tor
	list_of_racks = []
	cpu_cores = 16
	for i in range(num_racks):
		rack = Rack(str(i))
		for j in range(num_servers):
			server = Server(i*(num_servers)+j,"server"+str(i)+"-"+str(j), cpu_cores)
			rack.accumulate(server)
		list_of_racks.append(rack)

	list_of_tors = []
	for i in range(num_tor * num_pod):
		tor = Switch("ToR"+str(i), "ToR", k)
		list_of_tors.append(tor)

	list_of_agg= []
	for i in range(num_agg * num_pod):
		agg = Switch("Agg"+ str(i), "Agg", k)
		list_of_agg.append(agg)

	list_of_core = []
	for i in range(num_core):
		core = Switch("Core"+str(i), "Core", k)
		list_of_core.append(core)

	list_of_links = []
	num_links = int(3 * (k**3) / 4)
	capacity = 1024 	# Mbits
	delay = 1			# ms
	for i in range(num_links):
		link = Link("link"+str(i), capacity, delay)
		list_of_links.append(link)

	return list_of_racks, list_of_tors, list_of_agg, list_of_core, list_of_links
Example #26
0
    def __init__(self, args, config, logger):

        api_call = Connector(config, logger)
        sw_api_call = ConnSwitch(config, logger)
        ap_api_call = AccessPoint(config, logger)

        sw = Switch()
        sw.ipv4_address = args.address
        self.upgrade_code(api_call, sw_api_call, ap_api_call, sw, logger)
Example #27
0
 def drawGpuSwitch(self, MainWindow):
     MainWindow.GpuSwitch = Switch(thumb_radius=8,
                                   track_radius=10,
                                   show_text=False)
     MainWindow.horizontalLayout.addWidget(MainWindow.GpuSwitch)
     MainWindow.GpuSwitch.setEnabled(torch.cuda.is_available())
     MainWindow.use_cuda = False
     MainWindow.GpuSwitch.setToolTip("<h4>CUDA installed: {}</h4>".format(
         torch.cuda.is_available()))
Example #28
0
def switch(val):
    ret = []
    with Switch(val) as case:
        if case(1, fall_through=True):
            ret.append(1)
        if case(2):
            ret.append(2)
        if case.call(lambda v: 2 < v < 4):
            ret.append(3)
Example #29
0
def test_exception():
    with pytest.raises(SyntaxError):
        with Switch(2) as case:
            if case(1):
                assert False
            if case.default:
                assert True
            if case(2):
                assert False
Example #30
0
    def parse_ryu_switches(self):

        ryu_switches = None

        with open(self.network_configuration.conf_path + "ryu_switches.json",
                  "r") as in_file:
            ryu_switches = json.loads(in_file.read())

        #  Go through each node and grab the ryu_switches and the corresponding hosts associated with the switch
        for dpid in ryu_switches:

            #  prepare a switch id
            switch_id = "s" + str(dpid)

            # Check to see if a switch with this id already exists in the graph,
            # if so grab it, otherwise create it
            sw = self.get_node_object(switch_id)
            if not sw:
                sw = Switch(switch_id, self)
                self.graph.add_node(switch_id, node_type="switch", sw=sw)
                self.switch_ids.append(switch_id)

            # Parse out the information about all the ports in the switch
            switch_ports = {}
            for port in ryu_switches[dpid]["ports"]:
                if port["port_no"] == 4294967294:
                    continue

                if port["port_no"] == "LOCAL":
                    continue

                switch_ports[int(port["port_no"])] = Port(sw, port_json=port)

            if (not ryu_switches[dpid]["ports"]):
                #import pdb; pdb.set_trace()
                ovs_sw = self.network_configuration.mininet_obj.get(switch_id)
                for intf in ovs_sw.intfList():
                    if intf.name != 'lo':
                        new_port_obj = Port(sw, None, intf)
                        switch_ports[new_port_obj.port_number] = new_port_obj

            sw.ports = switch_ports

            # Parse group table if one is available
            if "groups" in ryu_switches[dpid]:
                sw.group_table = GroupTable(sw, ryu_switches[dpid]["groups"])

            # Parse all the flow tables and sort them by table_id in the list
            switch_flow_tables = []
            for table_id in ryu_switches[dpid]["flow_tables"]:
                switch_flow_tables.append(
                    FlowTable(sw, table_id,
                              ryu_switches[dpid]["flow_tables"][table_id]))
                sw.flow_tables = sorted(
                    switch_flow_tables,
                    key=lambda flow_table: flow_table.table_id)