def supetransition(self): rm2 = [] for link in self.links: if "#" in link.tag: if link.destination.isFinal(): link.origin.final = True if link.origin.isInitial(): link.destination.initial = True result = False for lk in self.links: if link != lk and lk.destination == link.origin: anotherLink = self.isLink(lk.origin, link.destination) if anotherLink[0]: anotherLink[1].add(lk) else: nlk = Link(lk.origin, link.destination, lk.tag[0]) for t in lk.tag[1:]: nlk.addTag(t) self.links.append(nlk) result = True if result: link.delTag("#") if len(link.tag) == 0: rm2.append(link) for l in rm2: self.links.remove(l) self.syncState()
def merge_sorted_link(link1, link2): """ 合并两个有序的链表(默认从小到大) :param link1: 原始有序链表1 :param link2: 原始有序链表2 :return: Link, 合并后的有序链表 """ link_merged = Link() p1 = link1.get_first_node() p2 = link2.get_first_node() while p1 or p2: if not p1: link_merged.cat_with_node(p2) break elif not p2: link_merged.cat_with_node(p1) break else: if p1.data >= p2.data: link_merged.append(p2.data) p2 = link2.get_next_node(p2) else: link_merged.append(p1.data) p1 = link1.get_next_node(p1) return link_merged
def __init__(self, root, month, year): self.root = root self.month = month self.year = year self.daysList = ['Δε','Τρ','Τε','Πε','Πα','Σα','Κυ'] #φτιάχνω λίστα με τους αριθμούς των ημερών self.numOfDays = self.getNumOfDays(self.month) self.numbers = Link.Link(int) for i in range(self.numOfDays): self.numbers.add(i+1) self.numbers.setDefault(time.localtime()[2]) #φτιάχνω λίστα με τις μέρες self.days = Link.Link(str) for i in range(7): self.days.add(self.daysList[i]) self.days.setDefault(self.daysList[time.localtime()[6]]) #αρχικοποιώ ημέρα for i in range(time.localtime()[2]): self.days.setPrevious() self.firstDay = self.days.getData() #φτιάχνω τον πίνακα self.days.setDefault(self.firstDay) self.numbers.setDefault(1) self.table = self.makeTable()
def createLinks(self): #print 'Creating Links' for fname in self.ListOfFiles: idx = fname.find('link') dst_id= fname[(idx+4):-4].split('-')[1] data = open(fname,'rb').read() data = data.replace('\n', '') data = data.split(' ') #convert from string to int for idx, v in enumerate(data): if v != '': data[idx] = int(v) else: data.remove('') #create a link object link = Link(int(dst_id), data) link.ChannelIds = self.ChannelIds #add a link object to the list of links self.ListOfLinks.append(link) self.ListOfLinks.sort() self.NoLinks = len(self.ListOfLinks)
def l3_recvfrom(node, message): # decode payload data = json.loads(message) # get destination nid from payload dest_nid = data['destination_nid'] # get last nid from payload last_nid = data['last_nid'] # reset last nid data['last_nid'] = node.GetNID() # set variable for segment segment = data['payload'] # if it is for this node, pass it up to layer 4 if str(dest_nid) == str(node.GetNID()): Transport.l4_recvfrom(segment) # if its not for this node, send it back down to layer 2 else: ttl = data['ttl'] new_ttl = (ttl - 1) data['ttl'] = new_ttl if (data['ttl'] > 0): datagram = json.dumps(data) Link.l2_sendto(node, last_nid, dest_nid, datagram) else: pass # April 28, 2016
def l3_sendto(node, dest_nid, segment): # get list of all links from link table and find link for this node links = node.GetLinks() link1 = links[0] # set hostname, port this node hostname = link1[1] port = link1[2] # set sequence number (fix later) sequence_number = 1 # set sequence total (fix later) sequence_total = 1 # set ttl (fix later) ttl = 10 # set length of data segment data_length = len(segment) # get port table for this node and set values for destination target PortTable = node.GetPortTable() for link in PortTable: info = PortTable[link] if info[0] == dest_nid: dest_hostname = info[1] dest_port = info[2] # set last nid value (for routing) last_nid = node.GetNID() # build datagram datagram = {} datagram['source_hostname'] = node.GetHostName() datagram['source_nid'] = node.GetNID() datagram['source_port'] = node.GetPort() datagram['destination_hostname'] = dest_hostname datagram['destination_nid'] = dest_nid datagram['destination_port'] = dest_port datagram['sequence_number'] = 1 datagram['total_sequence_numbers'] = 1 datagram['ttl'] = 15 datagram['mtu'] = 1000 datagram['length'] = data_length datagram['payload'] = segment datagram['last_nid'] = node.GetNID() # encode payload payload = json.dumps(datagram) # pass to link layer for sending Link.l2_sendto(node, last_nid, payload)
def update_router_time(self): self.check_neighbors_aliveness() if (time_elapsed - self.current_time) >= 10: for neighbor in self.neighbors: if Link.get_link_by_routers(self, neighbor) is not None: liveness_packet = Packet( self.id, neighbor.id, 'liveness_packet', Link.get_link_by_routers(self, neighbor)) Link.get_link_by_routers(self, neighbor).transfer_packet( self, neighbor, liveness_packet) self.current_time = time_elapsed
def render_data(self, context, row): # Create a StatsLink. Note that we could leave it up to the StatsLink # to look up the title, but that would end up creating an SQL query # for each row in the table- not good when we're trying to view a page # with 1000 projects without making our server explode. target = Stats.Target.StatsTarget(row[self.pathIndex]) return Link.StatsLink(target, text=self._findTitle(row))
def render_rows(self, context): return [ Link.MessageLink(self.target, self.messageId, extraSegments = ('xml',), text = 'Unformatted XML', ), ]
def crawl(self, origin): """ Crawls to URL and returns a unique, sanitized list of all links associated with this site. """ res = requests.get(origin.url) page = html.fromstring(res.content) # build unique set of Links with hrefs links = set() for href in page.xpath('//a/@href'): if href.startswith('http'): link = Link(url=href) else: link = Link(base=origin.root, path=href) links.add(link) return list(links)
def set_garbler(L, C): print "L = ", L print "C = ", C if int(L) > 100: os.system('clear') print "Failure: Loss = " + str(L) + "% bad argument" raw_input("press enter to continue...") elif int(C) > 100: os.system('clear') print "Failure: Corruption = " + str(C) + "% bad argument" raw_input("press enter to continue...") else: Link.garbler(L, C) os.system('clear')
def addLink(self): tA = self.linkA tB = self.linkB if tA == -1 or tB == -1: print "ERROR: a link end not assigned" if tA != tB and not self.hasLink(tA, tB): self.links.append( Link(self, self.getThought(tA), self.getThought(tB), importance=self.linkImportance)) #print "Creating a link!" # set circle colour back to white TA = self.getThought(tA) TA.canvas.itemconfig(TA.smallCircleIndex, fill=g.toHex(self.cs.smallCircle)) # reset link assignments self.resetLinkData() self.lowerLinks()
def build_web(self, start_url): """ Starts at the given URL and builds a web that is levels deep using BFS. Uses helper function crawl, to visit, connect, and mark sites. """ self.links = [Link(url=start_url)] Q = [0] for _ in range(self.levels): level = [] for link_id in Q: origin = self.links[link_id] links = self.crawl(origin) # list[Link] for link in links: conn = self.web.get(link_id, []) if link in self.links: i = self.links.index(link) self.web[link_id] = conn + [i] continue i = len(self.links) self.links.append(link) self.web[link_id] = conn + [i] level.append(i) Q = level self.save_links('links.json') self.save_web('web.json') return
def check_neighbors_aliveness(self): self.set_neighbors_last_time() for neighbor in self.neighbors: if (time_elapsed - self.neighbors_last_time[neighbor]) >= 30: if Link.get_link_by_routers(self, neighbor) is not None: # Link.remove_link(self, neighbor) # self.LSDB.remove_edge(self, neighbor) # self.neighbors.remove(neighbor) # update_packet = Packet(self.id, neighbor.id, 'update', None) # self.setup_connection(update_packet) Link.remove_link(self, neighbor) self.LSDB.remove_edge(self, neighbor) self.LSDB.add_edge(self, neighbor, weight=10000) update_packet = Packet(self.id, self.id, 'update', None) self.setup_connection(update_packet)
def get_missing_links(self): chains = self.get_chains() list_tuples = Link.create_link_tuples_from_chains(chains) missing_links = [] for list_tuple in list_tuples: missing_links.append(Link.Link(self.get_cell_with_value(list_tuple[0]), self.get_cell_with_value(list_tuple[-1]))) return missing_links
def addLink(self, manager): if self.index == -1: raise AssertionError("Index not found in command string") url = self.getStringArgument("link") topic = manager.get(self.index - 1) newLink = Link.Link() newLink.url = url topic.links.append(newLink) print("Added link number " + str(len(topic.links)))
def render_extraHeaders(self, context): # Add a <link> tag pointing at our RSS feed. Some RSS # aggregators can use this to automatically detect feeds. return tag( 'link', rel='alternate', type='application/rss+xml', title='RSS', href=Link.RSSLink(self.target).getURL(context), )
def initProgram(): linksTxt = "txtFiles/links.txt" demandsTxt = "txtFiles/demands.txt" links = [] demands = [] variables = [] with open(linksTxt, "r") as f: line = f.readline() while(line): txtParsed = line.strip().split(" ") link = Link(txtParsed[0], txtParsed[1], txtParsed[2]) links.append(link) line = f.readline() with open(demandsTxt, "r") as f: line = f.readline() while(line): txtParsed = line.strip().split(" ") demand = Demand(txtParsed[0], txtParsed[1], txtParsed[2]) demands.append(demand) line = f.readline() for link in links: for demand in demands: firstElementOfDemand = demand.firstElement lastElementOfDemand = demand.lastElement if (link.lastElement != demand.firstElement and link.firstElement != demand.lastElement): variable = Variable(link, demand) variables.append(variable) outputFile = "output.lp" temp = [] with open(outputFile, "w+") as f: for demand in demands: print("DEMAND: " + str(demand)) variablesByDemand = getVariablesByDemand(variables, demand) string = "" for variableDemand in variablesByDemand: if variableDemand.link.firstElement == demand.firstElement: print(variableDemand) # string += str(variableDemand) + " + " variableDemand.demand.getVolume() for variableDemand in variablesByDemand: if variableDemand.link.lastElement == demand.lastElement: print(variableDemand) intermediateVariables = getIntermediateVariables(variables, demand) print("INTERMEDIATES") for element in intermediateVariables: print("POSITIVE") for y in element[0]: print(y) print("NEGATIVE") for k in element[1]: print(k)
def render_rows(self, context): parsed = [] for id, xml in self.target.messages.getLatest(self.limit): m = Message.Message(xml) m.hyperlink = Link.MessageLink(self.target, id, text="#") parsed.append(m) if parsed: return self.renderMessages(context, parsed) else: return []
def updateLink(self, active_id, id, object_id, name, node1, node2, direction, capacity, distance): temp_link = lk.Link(id, object_id, name, node1, node2, direction, capacity, distance) active_link = self.getLinkById(active_id) if (temp_link.getAllProperties() == active_link.getAllProperties()): pass else: active_link.updateLink(id, object_id, name, node1, node2, direction, capacity, distance)
def __init__(self): self.InputLayerWidth = 18 #self.HiddenLayerWidth = 10 #self.OutputLayerWidth = 2 self.HiddenLayerWidth = 21 self.OutputLayerWidth = 24 self.NumInputToHiddenLinks = 18 * 21 #18 * 10 self.NumHiddenToHiddenLinks = 21 * 21 #10 * 10 self.NumHiddenToOutputLinks = 21 * 24 #10 * 2 self.InputLayer = [] for i in range(0, self.InputLayerWidth): self.InputLayer.append(Node()) self.InputLayer[0].CurrentActivation = Decimal(0) self.HiddenLayer1 = [] self.HiddenLayer2 = [] self.HiddenLayer3 = [] for i in range(0, self.HiddenLayerWidth): self.HiddenLayer1.append(Node()) self.HiddenLayer2.append(Node()) self.HiddenLayer3.append(Node()) self.OutputLayer = [] for i in range(0, self.OutputLayerWidth): self.OutputLayer.append(Node()) self.InputToHidden1Links = [] for i in range(0, self.NumInputToHiddenLinks): self.InputToHidden1Links.append(Link()) self.Hidden1ToHidden2Links = [] self.Hidden2ToHidden3Links = [] for i in range(0, self.NumHiddenToHiddenLinks): self.Hidden1ToHidden2Links.append(Link()) self.Hidden2ToHidden3Links.append(Link()) self.Hidden3ToOutputLinks = [] for i in range(0, self.NumHiddenToOutputLinks): self.Hidden3ToOutputLinks.append(Link())
def parse_topology(generate_json): """"generate JSON file for visualization if generate_json == True""" tree = ET.parse("abilene-TM" + os.sep + "topo" + os.sep + "Abilene-Topo-10-04-2004.xml") root = tree.getroot() topology = root.find("topology") node_list = [] link_list = [] graph = Graph(node_list, link_list) if generate_json: f = open("data.json", "w") output = {"nodes":{}, "links":[]} for node in topology.iter("node"): new_node = Node(node.attrib["id"]) node_list.append(new_node) if generate_json: location = node.find("location") new_node.set_location(float(location.attrib["latitude"]), float(location.attrib["longitude"])) output["nodes"][new_node.node_id] =\ (float(location.attrib["latitude"]), float(location.attrib["longitude"])) for link in topology.iter("link"): link_id = link.attrib["id"] link_from = graph.find_node(link.find("from").attrib["node"]) link_to = graph.find_node(link.find("to").attrib["node"]) bw = int(link.find("bw").text) new_link = Link(link_id, link_from, link_to, bw) link_list.append(new_link) if generate_json: output["links"].append(\ ((link_from.lat, link_from.lng), (link_to.lat, link_to.lng))) igp = root.find("igp").find("links") for link in igp.iter("link"): link_id = link.attrib["id"] link_obj = graph.find_link_by_id(link_id) if link_obj != None: link_obj.metric = float(link.find("static").find("metric").text) if generate_json: json.dump(output, f) f.close() return graph
def push(self, url): """ Spawns a new thread based on url and starts it. """ link = _Link.classify(url) if isinstance(link, _Link.ThreadLink): self.start(ThreadPool.ThreadWorker(link, self)) elif isinstance(link, _Link.BoardLink): self.start(ThreadPool.BoardWorker(link, self)) elif isinstance(link, _Link.ImageLink): self.start(ThreadPool.ImageWorker(link, self))
def dealLink(ID): while True: print """ 1.list links 2.delete a link 3.add a link 0.quit""" L = LI.getLink(ID) command = raw_input("please input the number(0~3):") if command == "0": break if command == "1": l = len(L) for j in range(0, l, 1): print "%d:" % j + L[j][2] if command == "2": number = int(raw_input("input the ID you want to delete:")) LI.deleteLink(L[number][0]) if command == "3": link = raw_input("please input the link you want add:") LI.addLink(ID, link) return 0
def link_up(N): # global variables global node # search links list for attributes links = node.GetLinks() link1 = links[0] link2 = links[1] status1 = node.GetUpFlagL1() status2 = node.GetUpFlagL2() # clear screen os.system('clear') # find the right link and set flag if int(N) == link1[0]: if status1 == True: print "Failure: link to node-" + N + " is already up" raw_input("press enter to continue...") else: Link.inhibit('u1') print "Success: link to node-" + N + " is up" raw_input("press enter to continue...") # find the right link and set flag elif int(N) == link2[0]: if status2 == True: print "Failure: link to node-" + N + " is already up" raw_input("press enter to continue...") else: Link.inhibit('u2') print "Success: link to node-" + N + " is up" raw_input("press enter to continue...") # if no link, print error message else: print "Failure: link to node-" + N + " does not exist" raw_input("press enter to continue...")
def config(self, path): data = json.load(open(path, mode='r')) for c in data: chain = KineChain(self.root) for l in c: name = l['name'] pos = l['pos'] theta = l['theta'] lb = l['lb'] ub = l['ub'] link = Link(name, pos, theta, lb, ub) chain.add_link(link) self.chains.append(chain)
def __init__(self, root): self.root = root months = ['Ιανουάριος','Φεβρουάριος','Μάρτιος','Απρίλιος','Μάιος','Ιουνίος', 'Ιούλιος','Αύγουστος','Σεπτέμβριος','Οκτώβριος','Νοέμβριος','Δεκέμβριος'] self.year = time.localtime()[0] #φτιάχνω λίστα με τους μήνες self.months = Link.Link(str) for i in range(12): self.months.add(months[i]) self.months.setDefault(months[time.localtime()[1]-1]) #φτιάχνω το frame για τους μήνες self.monthsFrame = tk.Frame(self.root) self.monthsFrame.pack(expand = False,side = 'top',anchor = 'n') self.month = tk.StringVar() self.month.set(self.months.getData() + ' ' + str(self.year)) self.left = tk.Button(self.monthsFrame, text = '<', bg = 'lightgreen', command = self.back) self.left.pack(fill = 'both',side = 'left') self.right = tk.Button(self.monthsFrame, text = '>', bg = 'lightgreen', command = self.next) self.right.pack(fill = 'both',side = 'right') self.label = tk.Label(self.monthsFrame,textvariable = self.month, font = 'Arial 10',width = 45, height = 2, bg = 'lightblue') self.label.pack(fill = 'both',side = 'bottom') #φτιάχνω λίστα με τους αριθμούς των μηνών numbers = [1,2,3,4,5,6,7,8,9,10,11,12] self.numbers = Link.Link(int) for i in range(12): self.numbers.add(numbers[i]) self.numbers.setDefault(time.localtime()[1]) #φτιάχνω το frame για τον πίνακα self.tableFrame = tk.Frame(self.root) self.tableFrame.pack(expand = True,side = 'top',anchor = 'n') self.table = Table(self.tableFrame,self.numbers.getData(),self.year)
def __init__(self, url, html=""): self.url = url self.link = Link(self.url) self.response_code = 0 if html == "": self.html_page = False self.download_sec = 0.0 self.html = "" self.download() else: self.html_page = True self.download_sec = 0.0 self.html = html if self.html_page: self.extracted_links = self.__extract_links()
def loadFromFile(self, filename, jok=False): """loadFromFile permet de charger un Automate à partir d'un fichier Elle chargera le fichier indiqué dans filename. jok permet de specifier l'utilisation de e-transition Parameters ---------- filename : String chemin d'acces au fichier jok : boolean indique l'utilisation de e-transition Returns ------- None """ try: file = open(filename, "r") except: print("Cannot open the file, abort") return False lines = file.readlines() for i in range(0, len(lines)): lines[i] = lines[i].rstrip() file.close() self.alphabet = [e for e in lines[0]] if jok: self.alphabet.append("#") self.nbState = int(lines[1]) self.initial = [int(e) for e in lines[2].split()] self.final = [int(e) for e in lines[3].split()] self.states = [State(i, self.alphabet) for i in range(0, self.nbState)] self.current = self.states[self.initial[0]] self.initStateStatus() for i in range(4, len(lines)): line = lines[i].split() origin = self.states[int(line[0])] destination = self.states[int(line[1])] link = self.isLink(origin, destination) if not (line[2] == '#' and origin.id == destination.id): if not link[0]: self.links.append(Link(origin, destination, line[2])) else: link[1].addTag(line[2]) origin.nbLink += 1 origin.addLink(line[2], destination) if origin != destination: destination.nbLink += 1
def updatebyMoore(self, list): """"updatebyMoore permet de mettre à jour un automate avec un tableau issue de l'algorithme de moore Parameters ---------- list : [] liste issue de la fonction minMoore Returns ------- None """ list = self.minusOne2D(list) newState = [] for i in range(len(list)): if list[i][0] not in newState: newState.append(list[i][0]) nbnewState = len(newState) states = [State(e, self.alphabet) for e in newState] finals = [] inits = [] for i in range(nbnewState): isFinal = True isInit = True for j in range(self.nbState): if list[j][0] == i: if not self.states[j].isFinal(): isFinal = False if not self.states[j].isInitial(): isInit = False if isFinal: finals.append(i) if isInit: inits.append(i) links = [] for i in range(len(states)): for j in range(1, len(self.alphabet) + 1): origin = states[list[i][0]] dest = states[list[i][j]] link = self.isLink(origin, dest, links, True) if not link[0]: links.append(Link(states[list[i][0]], states[list[i][j]], self.alphabet[j - 1])) else: link[1].addTag(self.alphabet[j - 1]) origin.nbLink += 1 if origin != dest: dest.nbLink += 1 origin.addLink(self.alphabet[j - 1], dest) self.initMachine(nbnewState, inits, finals, states, links)
def _addlinks(self, category, cat): ''' Parse and add all links to a category @param category: a collection of XML Elements @param cat: the Category to add the collections to ''' for link in category.findall("links/link"): linkid = link.get("id") if linkid == None: logging.warn("Category " + cat.term + " - invalid link") continue logging.info("Category " + cat.term + " link " + linkid) try: cat.addlink(Link.Link(linkid)) except: logging.error("Category " + cat.term + " Problem processing link " + linkid) logging.error(sys.exc_info())
def get_index_page(self, filter=None): file_names = self.file_reader.get_files_list(self.pages_dir) file_names.sort() labels = [ self.file_name_to_link_label(file_name) for file_name in file_names ] targets = [ self.file_name_to_link_target(file_name) for file_name in file_names ] links = [ Link.Link(labels[ind], targets[ind]) for ind in range(len(file_names)) ] return render_template('index.j2', links=links)
def read_network(filename): with open('Euro16/' + filename) as f: lines = f.readlines() nodes = int(lines[0]) links = int(lines[1]) network = [] l = [] x = 0 for line in lines[2:]: network.append([int(x) for x in line.split('\t')]) for i in range(2, len(lines)): n = lines[i].split('\t') for j in range(len(n)): if int(n[j]) != 0: l.append(Link.Link(x, j, int(n[j]), cores_num)) x += 1 return nodes, links, network, l
def get_links_to_the_companies(uri, page): list_of_companies = [] site = uri hdr = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' } req = requests.get(site, headers=hdr) print(req) soup = bs4.BeautifulSoup(req.text, 'html.parser') # listoflinks = soup.select("a href", class_='tekst_tytul_miejsce') listoftitles = soup.findAll('a', class_='wizLnk') for item in listoftitles: value = item.attrs['href'] new_value = value.replace("'", "") print(value) list_of_companies.append(new_value) for company in list_of_companies: v = Link.Firma(company, page)
def __init__(self, connections, terminals, inhibN,threshold1, tau1, timeStep,dinc): global threshold,tau # record the firing time of the neuron self.fireTime = list() self.psp = list() threshold = threshold1 tau = tau1 # create the number of connections the current neuron has with the previous layer self.synapses = np.empty((connections), dtype=object) if inhibN > 0: self.type = -1 else: self.type = 1 # initialise each link as a connection element with different weights and delays for s in range(connections): self.synapses[s] = Link(terminals, connections,threshold, tau,timeStep,dinc)
def __extract_links(self): try: log = structlog.get_logger() log.info("__extracting_links", base_url=self.url) links = [] soup = BeautifulSoup(self.html, "html.parser") anchors = soup.find_all('a') count = 0 for href in anchors: count = count + 1 url = href.get("href") log.info("got_href", url=url) if url is None: # Link has no href and is placeholder for future frontend processing continue try: link = Link(url, self.url, href.text) formatted_url = link.url_qualified log.info("got_link", formatted_url=formatted_url) if url is not None: if link.url_qualified != "": link_location = "" if link.is_external_link: link_location = "external" else: link_location = "relative" links.append(link) except Exception as e: exception_name = type(e).__name__ log.exception("formatting_url_exception", exception_name=exception_name, formatted_url=formatted_url) traceback.print_exc() continue except Exception as e: exception_name = type(e).__name__ log.exception("basic_extract_url_exception", exception_name=exception_name) traceback.print_exc() return links
def addJSONLinksByUser(data, userId): #FIXME: change insertion algorithm for sql queries that inserting data #as zip, json or ... #curTime = time.time() query = {"linksQuery":StringHolder("INSERT INTO link (id, user_id, url, url_hash, title, description, type_name, modified_at) VALUES\n"), "updateLinkSubQuery":{"id":StringHolder(""), "title":StringHolder(""), "description":StringHolder(""), "type_name":StringHolder(""), "modified_at":StringHolder("")}, "tagsQuery":StringHolder("INSERT INTO tag (id, user_id, name) VALUES\n"), "mapsQuery":StringHolder("INSERT INTO link_tag_map (tag_id, link_id) VALUES\n"), "mdQuery":StringHolder("INSERT INTO meta_data (link_id, l_key, value) VALUES\n")} tags = [] savedTags = tagQM.getTagNames(userId) savedLinks = linkQM.getLinkUrlsAndIds(userId) parseData(userId, data, tags, query, savedLinks, savedTags) #print "calculating time: " + str(utils.timeDifference(curTime)) + " ms" #curTime = time.time() conn = db.connect() cursor = conn.cursor() if not query["linksQuery"].value.endswith("VALUES\n"): cursor.execute(query["linksQuery"].value[:-2]) if not query["mdQuery"].value.endswith("VALUES\n"): cursor.execute(query["mdQuery"].value[:-2]) if not query["tagsQuery"].value.endswith("VALUES\n"): cursor.execute(query["tagsQuery"].value[:-2]) #FIXME : check if link refer to another tag if not query["mapsQuery"].value.endswith("VALUES\n"): cursor.execute(query["mapsQuery"].value[:-2]) if query["updateLinkSubQuery"]["id"].value != "": cursor.execute(buildUpdateQuery(query["updateLinkSubQuery"])) conn.commit() cursor.close() #print "database request time: " + str(utils.timeDifference(curTime)) + " ms" return
def main (argv): # global variables global node #check for proper input if len(sys.argv) != 3: PrintUsage() # good input, start program else: run = 1 # initialize node object in physical layer node = Physical.InitializeTopology(sys.argv[1], sys.argv[2]) # wait for node to propagate time.sleep(2) #start listen threads Link.start_listener(node) # begin loop while(run == 1): # clear screen os.system('clear') # print menu menu() # prompt for input message = raw_input("Enter your selection: ") # start new service if (message == '1'): P = raw_input("Enter the maximum number of connections this service point will accept: ") start_service(P) # stop service if (message == '2'): S = raw_input("Enter the Service ID of the node you wish to stop service with: ") stop_service(S) # list service points if (message == '3'): list_service_points() # connect to node x if (message == '4'): Y = raw_input("Enter the node you would like to connect to: ") S = raw_input("Enter the SID of the node: ") #connect(Y, S) thread.start_new_thread(connect, (Y,S)) # close connection with node x if (message == '5'): C = raw_input("Enter the CID of the connection you would like to close: ") close(C) # download from node x if (message == '6'): C = raw_input("Enter the CID of the peer from whom you would like to download: ") F = raw_input("Enter the name of the file you would like to download: ") thread.start_new_thread(download, (C,F)) # set garbler probability if (message == '7'): L = raw_input("Set the probability of packet loss (1-100): ") C = raw_input("Set the probability of packet corruption (1-100): ") set_garbler(L, C) # display next hop data if (message == '8'): route_table(node) # down link to node x if (message == '9'): N = raw_input("Enter the node with whom you would like to down a link: ") link_down(N) # up link to node x if (message == '10'): N = raw_input("Enter the node with whom you would like to up a link: ") link_up(N) # for testing, send simple text message if (message == "11"): dest_nid = raw_input("Enter NID of target: ") text = raw_input("Enter Text Message: ") string = {} string['code'] = '10' string['message'] = text data = json.dumps(string) Transport.l4_sendto(node, dest_nid, data) # for testing node at physical layer if (message == "12"): node.PrintStatus() # exit program if (message == '13') or (message == 'Exit') or (message == 'exit'): run = 0
import Link as l import time import sys FILENAME = "test" ID = sys.argv[1] count = 0 while True: time.sleep(0.5) print("tick") msgout = u"test:" + ID + str(count) print("out:" + msgout) l.write(msgout) count += 1 time.sleep(0.1) msgin = l.read() msgin = msgin.strip() print("in:" + msgin) # END
def main (argv): #check for proper input if len(sys.argv) != 3: PrintUsage() # good input, start program else: run = 1 # initialize node object in physical layer node = Physical.InitializeTopology(sys.argv[1], sys.argv[2]) #start listen threads Link.start_listener(node) # begin loop while(run == 1): # clear screen os.system('clear') # prompt for input message = raw_input("Enter A Command, or 'menu' to see all options: ") # for testing node at physical layer if (message == "PrintStatus"): node.PrintStatus() # for testing, send simple text message if (message == "send message"): dest_nid = raw_input("Enter NID of target: ") data = raw_input("Enter Message: ") Transport.l4_sendto(node, dest_nid, data) # print menu to screen if (message == "MENU") or (message == "Menu") or (message == "menu"): menu() # start new service if (message == '1'): P = raw_input("Enter the maximum number of connections this service point will accept: ") start_service(P) # stop service if (message == '2'): S = raw_input("Enter the Service ID of the node you wish to stop service with: ") stop_service(S) # connect to node x if (message == '3'): Y = raw_input("Enter the node you would like to connect to: ") S = raw_input("Enter the SID of the node: ") W = raw_input("Enter a value between 1-5 to set the window for packets in flight") connect(Y, S, W) # close connection with node x if (message == '4'): C = raw_input("Enter the CID of the connection you would like to close: ") close(C) # download from node x if (message == '5'): C = raw_input("Enter the CID of the peer from whom you would like to download: ") F = raw_input("Enter the name of the file you would like to download") download(C, F) # set garbler probability if (message == '6'): L = raw_input("Set the probability of packet loss (1-100): ") C = raw_input("Set the probability of packet corruption (1-100): ") set_garbler(L, C) # display next hop data if (message == '7'): route_table(node) # down link to node x if (message == '8'): N = raw_input("Enter the node with whom you would like to down a link: ") link_down(node, N) # up link to node x if (message == '9'): N = raw_input("Enter the node with whom you would like to up a link: ") link_up(node, N) # exit program if (message == 'Exit') or (message == 'Exit') or (message == 'exit'): run = 0
def setup_nodes(g, size, pcount): #make nodes nodes = [setup_node(i) for i in range(size)] for pnode in random.sample(nodes, pcount): pnode.paware=True #foreach node for node in g: #foreach neighbor for neighbor in g[node].keys(): #add a link to the neighbor linkweight = g[node][neighbor]['weight'] if linkweight == 0: cap = 4 delay = 20 elif linkweight == 1: cap = 20 delay = 10 elif linkweight ==2: cap = 100 delay = 5 elif linkweight == 3: cap = 1000 delay = 5 else: cap = 2000 delay = 2 link = Link(name=("Link"+str(node)+"-"+str(neighbor)), capacity=cap) #need to vary link capacity, but don't worry yet #map node IPs to link pointers labelstr = str(node) +"."+ str(neighbor) revlabelstr = str(neighbor) +"."+ str(node) link.setup(nodes[neighbor], delay) #set propdelay and destination if(not revlabelstr in linktable): #Only set up the link if it doesn't already exist in reverse nodes[node].add_link(link) #hook link on to parent #add link in cbgp cbgpcommands.append("net add link " + str(nodes[node].prefix[1]) +" "+str(nodes[neighbor].prefix[1])) linktable[labelstr] = link #add static route in cbgp cbgpcommands.append("net node " +str(nodes[node].prefix[1]) + " route add --oif="+str(nodes[neighbor].prefix[1]) + " "+str(nodes[neighbor].prefix[1])+"/32 1") #set up peering cbgpcommands.append("bgp router " + str(nodes[node].prefix[1]) + "\n add peer " + str(neighbor) + " " + str(nodes[neighbor].prefix[1])+ "\n peer " + str(nodes[neighbor].prefix[1])+" up \n exit") cbgpcommands.append("sim run") for source in nodes: for destination in nodes: if source==destination: continue cbgpcommands.append("bgp router "+str(source.prefix[1])+" debug dp " + str(destination.prefix)) cbgpcommands.append("sim run") cbgpcommands.append("sim clear") p = subprocess.Popen(["cbgp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cbgp_stdout = p.communicate(input="\n".join(cbgpcommands))[0] #sys.stderr.write(cbgp_stdout) cbgp_stdout = cbgp_stdout.splitlines() p.stdin.close() p.stdout.close() srcid = -1 dstid = -1 grab_flag = False allroutes = [] state = 0 for line in cbgp_stdout: #print state, linee if route_header_re.match(line): m = route_header_re.match(line) state = 1 srcid = m.group(1) dstid = m.group(2) #set srcid, dstid from regex elif state==1 and line == "[ Current Best route: ]": state = 2 elif state == 2 and route_re.match(line): r = route_re.match(line) nexthopid = r.group(1) hoplength = len(r.group(2).split()) l = linktable[str(srcid)+"."+str(nexthopid)] bestroute = Route(IPNetwork("10.0."+str(dstid)+".0/24"), l, hoplength) allroutes.append(bestroute) state = 3 elif state >= 3 and (line == "[ Shortest AS-PATH ]" or line == "[ Eligible routes: ]"): state = 4 elif state == 4 and route_re.match(line): r = route_re.match(line) nexthopid = r.group(1) hoplength = len(r.group(2).split()) l = linktable[str(srcid)+"."+str(nexthopid)] rt = Route(IPNetwork("10.0."+str(dstid)+".0/24"), l, hoplength) allroutes.append(rt) elif state ==4 or (line == "[ Best route ]" and state!=0): state = 0 nodes[int(srcid)].rib.extend(set(allroutes)) allroutes = [] srcid = -1 dstid = -1 for node in nodes: for i in range(size): if i == nodes.index(node): continue l = filter(lambda x: str(x.prefix)==("10.0."+str(i)+".0/24"), node.rib) if len(l) == 0: print "Missing route from ", node.prefix, "to 10.0."+str(i)+".0/24" print node.prefix, "RIB:", node.rib return nodes
def run(self): initialize() # The input parameters: # # NODES[][] is a 2-way array with NODES[i] being the list [ID, isSource,isDest,isRouter,isMonitored,sourceID,destID,numbits,starttime] if the node is a source # or destination, and [ID,0,0,1] otherwise if it is a router. # # TOPOLOGY[][][] is a 3-way array with TOPOLOGY[i][j] being the list [isMonitored, rate, propTime, bufferCapacity] for the link between nodes i and j, # and [-1] if one does not exist. # # Everything is on the scale of bits and milliseconds. # # Common test cases are the following: # Test Case 1: # NODES = [[0,1,0,0,1,0,1,160000000,0], [1,0,1,0,1,0,1],[2,0,0,1],[3,0,0,1],[4,0,0,1],[5,0,0,1]] # TOPOLOGY = [ [[-1],[-1],[0,10000,10,64],[-1],[-1],[-1]], # [[-1],[-1],[-1],[-1],[-1],[0,10000,10,64]], # [[0, 10000, 10, 64],[-1],[-1],[1, 10000, 10, 64],[1, 10000, 10, 64],[-1]], # [[-1],[-1],[1, 10000, 10, 64],[-1],[-1],[0, 10000, 10, 64]], # [[-1],[-1],[1, 10000, 10, 64],[-1],[-1],[0, 10000, 10, 64]], # [[-1],[0, 10000, 10, 64],[-1],[0, 10000, 10, 64],[0, 10000, 10, 64],[-1]] ] # # Test Case 2: # NODES = [[0,1,0,0,1,0,1,160000000,0],[1,0,1,0,1,0,1],[2,0,0,0,1],[3,0,0,1],[4,0,0,1],[5,0,0,1],[6,1,0,0,1,6,7,100000000,2000],[7,0,1,0,1,6,7],[8,1,0,0,1,8,9,100000000,13000],[9,0,1,0,1,8,9]] # TOPOLOGY = [ [[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1],[-1],[-1]], # [[-1],[-1],[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1]], # [[0,20000,10,128],[-1],[-1],[1,10000,10,128],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1]], # [[-1],[-1],[1,10000,10,128],[-1],[1,10000,10,128],[-1],[-1],[0,20000,10,128],[-1],[-1]], # [[-1],[-1],[-1],[1,10000,10,128],[-1],[1,10000,10,128],[-1],[-1],[0,20000,10,128],[-1]], # [[-1],[0,20000,10,128],[-1],[-1],[1,10000,10,128],[-1],[-1],[-1],[-1],[0,20000,10,128]], # [[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1],[-1],[-1]], # [[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1],[-1]], # [[-1],[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1]], # [[-1],[-1],[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1]] ] if self.globs.TEST_CASE == 1: NODES = [[0,1,0,0,1,0,1,160000000,0], [1,0,1,0,1,0,1],[2,0,0,1],[3,0,0,1],[4,0,0,1],[5,0,0,1]] TOPOLOGY = [ [[-1],[-1],[0,10000,10,64],[-1],[-1],[-1]], [[-1],[-1],[-1],[-1],[-1],[0,10000,10,64]], [[0, 10000, 10, 64],[-1],[-1],[1, 10000, 10, 64],[1, 10000, 10, 64],[-1]], [[-1],[-1],[1, 10000, 10, 64],[-1],[-1],[0, 10000, 10, 64]], [[-1],[-1],[1, 10000, 10, 64],[-1],[-1],[0, 10000, 10, 64]], [[-1],[0, 10000, 10, 64],[-1],[0, 10000, 10, 64],[0, 10000, 10, 64],[-1]] ] self.globs.NODES = NODES self.globs.TOPOLOGY = TOPOLOGY elif self.globs.TEST_CASE == 2: NODES = [[0,1,0,0,1,0,1,160000000,0],[1,0,1,0,1,0,1],[2,0,0,1],[3,0,0,1],[4,0,0,1],[5,0,0,1],[6,1,0,0,1,6,7,100000000,2000],[7,0,1,0,1,6,7],[8,1,0,0,1,8,9,100000000,13000],[9,0,1,0,1,8,9]] TOPOLOGY = [ [[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1],[-1],[-1]], [[-1],[-1],[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1]], [[0,20000,10,128],[-1],[-1],[1,10000,10,128],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1]], [[-1],[-1],[1,10000,10,128],[-1],[1,10000,10,128],[-1],[-1],[0,20000,10,128],[-1],[-1]], [[-1],[-1],[-1],[1,10000,10,128],[-1],[1,10000,10,128],[-1],[-1],[0,20000,10,128],[-1]], [[-1],[0,20000,10,128],[-1],[-1],[1,10000,10,128],[-1],[-1],[-1],[-1],[0,20000,10,128]], [[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1],[-1],[-1]], [[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1],[-1]], [[-1],[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1],[-1]], [[-1],[-1],[-1],[-1],[-1],[0,20000,10,128],[-1],[-1],[-1],[-1]] ] self.globs.NODES = NODES self.globs.TOPOLOGY = TOPOLOGY else: NODES = self.globs.NODES TOPOLOGY = self.globs.TOPOLOGY # Global Arrays of the Network Objects. Devices includes all the Sources, Destinations, and Routers, and links includes all the link objects. devices = [] links = [] # Global Arrays containing the Monitors that observe the relevant data throughputs = [] sendRates = [] windowSizes = [] packetDelays = [] bufferOccs = [] droppedPackets = [] linkFlowRates = [] # Global values for determining when the simulation is over self.globs.numFlows = 0 self.globs.flowsDone = 0 # Output is written to files with names such as outputName+"throughputs(n).png" outputName = 'TestCase' + str(self.globs.TEST_CASE) if self.globs.DYNAMIC_ROUTING: outputName += 'Dynamic' outputName += self.globs.CONGESTION_CONTROL_ALGORITHM # For each device in the nodes, instantiate the appropriate device with its monitors for i in range(len(NODES)): # If the device is a source ... if NODES[i][1]: self.globs.numFlows += 1 # Create the monitors sendRateMonitor = Monitor(name = 'Send Rate of Source ' + str(NODES[i][0])) windowSizeMonitor = Monitor(name = 'Window Size of Source '+str(NODES[i][0])) # Create the object, add it to the list of devices, and activate it source = Source(NODES[i][0], NODES[i][6], NODES[i][7], NODES[i][8], sendRateMonitor, windowSizeMonitor, self.globs) devices.append(source) activate(source, source.run()) # If this node should be monitored, add its monitors to the arrays if NODES[i][4]: sendRates.append(sendRateMonitor) windowSizes.append(windowSizeMonitor) # If the device is a destination ... elif NODES[i][2]: # Create the Monitors thru = Monitor(name = 'Throughput to Destination ' + str(i)) pDelay = Monitor(name = 'Packet Delays of Destination ' + str(i)) # Create the object, add it to the list of devices, and activate it dest = Destination(NODES[i][0], NODES[i][5], thru, pDelay, self.globs) devices.append(dest) activate(dest, dest.run()) # If this node should be monitored, add its monitors to the arrays if NODES[i][4]: packetDelays.append(pDelay) throughputs.append(thru) # If the device is a router ... elif NODES[i][3]: # Create the object, add it to the list of devices, and activate it router = Router(NODES[i][0],TOPOLOGY, self.globs) devices.append(router) activate(router, router.run()) # Otherwise the input is incorrect ... else: print("Incorrect Input: One of the nodes is not a source, destination, or router.") assert(False) # For each link in the topology, instantiate the appropriate link with its monitors for i in range(len(TOPOLOGY)): for j in range(len(TOPOLOGY[i])): # If there is a link between node i and node j (i.e. TOPOLOGY[i][j] isn't [-1]) ... if len(TOPOLOGY[i][j]) > 1: # Create the monitors buffOcc = Monitor(name = 'Buffer Occupancies of the Link From ' + str(i) + ' to ' + str(j)) dropPacket = Monitor(name = 'Dropped Packets of the Link From ' + str(i) + ' to ' + str(j)) flowRate = Monitor(name = 'Link Flow Rate of the Link From ' + str(i) + ' to ' + str(j)) # Create the object, add it to the list of links, and activate it link = Link(TOPOLOGY[i][j][1], devices[i], devices[j], TOPOLOGY[i][j][2], TOPOLOGY[i][j][3], buffOcc, dropPacket, flowRate) links.append(link) activate(link, link.run()) # Tell device i that it is connected to this link object devices[i].addLink(link) # If this link should be monitored, add its monitors to the arrays if TOPOLOGY[i][j][0]: linkFlowRates.append(flowRate) bufferOccs.append(buffOcc) droppedPackets.append(dropPacket) # The Main Simulation! simulate(until = 50000) # Plot and save all the appropriate measurements. Output files are named outputName+data+(n).png. print 'producing graphs...' # Window Sizes n = 0 for m in windowSizes: plt.plot(m.tseries(), m.yseries()) plt.title(m.name) plt.xlabel("Time (ms)") plt.ylabel("Window Size (Packets)") plt.savefig(outputName+"windowSizes" + str(n) + ".png") plt.clf() n += 1 # Throughputs n = 0 for m in throughputs: L = len(m.yseries()) deltay = [a-b for a,b in zip(m.yseries()[2*self.globs.AVERAGE_INTERVAL:L],m.yseries()[0:L-2*self.globs.AVERAGE_INTERVAL])] deltax = [a-b for a,b in zip(m.tseries()[2*self.globs.AVERAGE_INTERVAL:L],m.tseries()[0:L-2*self.globs.AVERAGE_INTERVAL])] thru = [float(a)/b for a,b in zip(deltay,deltax)] times = m.tseries()[self.globs.AVERAGE_INTERVAL:L-self.globs.AVERAGE_INTERVAL] intervals = [a-b for a,b in zip(times[1:len(times)],times[0:len(times)-1])] timeavThru = [a*b for a,b in zip(thru[0:len(thru)-1],intervals)] print("The Average of " + m.name + " is " + str(sum(timeavThru) / float(sum(intervals)))) plt.plot(m.tseries()[self.globs.AVERAGE_INTERVAL:L-self.globs.AVERAGE_INTERVAL], thru) plt.title(m.name) plt.xlabel("Time (ms)") plt.ylabel("Throughput (bpms)") plt.savefig(outputName+"throughput" + str(n) + ".png") plt.clf() n += 1 # Send Rates n = 0 for m in sendRates: plt.plot(m.tseries(), m.yseries()) plt.title(m.name) plt.xlabel("Time (ms)") plt.ylabel("Send Rate (bpms)") plt.savefig(outputName+"sendRate" + str(n) + ".png") plt.clf() n += 1 # Packet Delays n = 0 for m in packetDelays: L = len(m.yseries()) delay = [(a-b)/float(self.globs.AVERAGE_INTERVAL) for a,b in zip(m.yseries()[2*self.globs.AVERAGE_INTERVAL:L],m.yseries()[0:L-2*self.globs.AVERAGE_INTERVAL])] times = m.tseries()[self.globs.AVERAGE_INTERVAL:L-self.globs.AVERAGE_INTERVAL] intervals = [a-b for a,b in zip(times[1:len(times)],times[0:len(times)-1])] timeavDelay = [a*b for a,b in zip(delay[0:len(delay)-1],intervals)] print("Average of "+ m.name + " is " + str(sum(timeavDelay)/float(sum(intervals)))) plt.plot(m.tseries()[self.globs.AVERAGE_INTERVAL:L-self.globs.AVERAGE_INTERVAL], delay) plt.title(m.name) plt.xlabel("Packet Delay (ms)") plt.ylabel("Time (ms)") plt.savefig(outputName+"packetDelay" + str(n) + ".png") plt.clf() n += 1 # Buffer Occupancies n = 0 for m in bufferOccs: print("Average of "+ m.name + " is " + str(m.timeAverage())) print("Variance of "+m.name + " is " + str(m.timeVariance())) plt.plot(m.tseries(), m.yseries()) plt.title(m.name) plt.xlabel("Time (ms)") plt.ylabel("Buffer Occupancy (Packets)") plt.savefig(outputName+"bufferOccupancies" + str(n) + ".png") plt.clf() n += 1 # Dropped Packets n = 0 for m in droppedPackets: print("Average of "+m.name + " is " + str(m.timeAverage())) plt.plot(m.tseries(), m.yseries()) plt.title(m.name) plt.xlabel("Time (ms)") plt.ylabel("Packets") plt.savefig(outputName+"droppedPackets" + str(n) + ".png") plt.clf() n += 1 # Link Flow Rates n = 0 for m in linkFlowRates: plt.plot(m.tseries(), m.yseries()) plt.title(m.name) plt.xlabel("Time (ms)") plt.ylabel("Link Flow (bpms)") plt.savefig(outputName+"linkSendRate" + str(n) + ".png") plt.clf() n += 1 print("done")
__author__ = 'bwright' import Numbrix import Link # Test calls on Link chains = [range(1, 31), range(37, 38), range(48, 82)] links = Link.create_link_tuples_from_chains(chains) print links chains = [range(5, 31), range(37, 38), range(48, 81)] links = Link.create_link_tuples_from_chains(chains) print links NUM_ROWS = 9 CELL_DIMENSION = 60 game_1 = [13, 15, 17, 21, 25, 9, 27, 37, 51, 81, 55, 79, 75, 69, 61, 59] game_2 = [61, 71, 81, 1, 5, 59, 7, 57, 13, 53, 29, 51, 45, 41, 39, 37] nov_30_2013_beginner = [5, 6, 7, 8, 9, 24, 25, 30, 31,
def next_hop(node, last_nid): # include global variables global link1_flag, link2_flag link1_flag = Link.routing_flag1() link2_flag = Link.routing_flag2() links = node.GetLinks() tabl = node.linkTable #print "in routing", last_nid; for k in tabl.keys(): if (k==int(last_nid)): metrix1 = 1 tn1 = int(node.nid) tn2 = links[0][0] while tn2!=k: for key, value in tabl.items(): if key==tn2: if len(filter(bool, value))==1: metrix1 = 100 break else: if value[0]==tn1: tn1 = tn2 tn2 = value[1] metrix1 += 1 else: tn1 = tn2 tn2 = value[0] metrix1 += 1 break if metrix1>10: break metrix2 = 1 tn1 = int(node.nid) tn2 = links[1][0] while tn2!=k: for key, value in tabl.items(): if key==tn2: if len(filter(bool, value))==1: metrix2 = 100 break else: if value[0]==tn1: tn1 = tn2 tn2 = value[1] metrix2 += 1 else: tn1 = tn2 tn2 = value[0] metrix2 += 1 break if metrix2>10: break if metrix2>metrix1: metrix = metrix1 nh = links[0][0] if metrix2<metrix1: metrix = metrix2 nh = links[1][0] if metrix2==metrix1: metrix = metrix1 nh = max(int(links[0][0]), int(links[1][0])) if node.upL1==False and node.upL2==False: metrix = "inf" nh = "not reachable" if node.upL1==False and node.upL2==True: metrix = metrix2 nh = links[1][0] if node.upL1==True and node.upL2==False: metrix = metrix1 nh = links[0][0] return nh
def route_table(node): # include global variables global link1_flag, link2_flag # Flags to check link status of the current node link1_flag = Link.routing_flag1() link2_flag = Link.routing_flag2() links = node.GetLinks() # Links of the current node tabl = node.linkTable # Link table of the topology print "Destination NID Cost/Metrix Next Hop\n" for k in tabl.keys(): # Traverse through the Link Table # If the node is not the current node if (k!=int(node.nid)): # Since there are maximum two links per node, only two possible routes to the destination # exists. This portion of the code calculates the costs and next hop values for both of these # routes, one by one metrix1 = 1 tn1 = int(node.nid) # Source (current) NID tn2 = links[0][0] # One of the connected nodes' NID while tn2!=k: for key, value in tabl.items(): if key==tn2: # If end of path occurs if len(filter(bool, value))==1: metrix1 = 100 break # Else, continue traversing, by updating values of tn1 and tn2 else: if value[0]==tn1: tn1 = tn2 tn2 = value[1] metrix1 += 1 else: tn1 = tn2 tn2 = value[0] metrix1 += 1 break if metrix1>10: break metrix2 = 1 tn1 = int(node.nid) # Source (current) NID tn2 = links[1][0] # Other connected nodes' NID while tn2!=k: for key, value in tabl.items(): if key==tn2: # If end of path occurs if len(filter(bool, value))==1: metrix2 = 100 break # Else, continue traversing, by updating values of tn1 and tn2 else: if value[0]==tn1: tn1 = tn2 tn2 = value[1] metrix2 += 1 else: tn1 = tn2 tn2 = value[0] metrix2 += 1 break if metrix2>10: break if metrix2>metrix1: metrix = metrix1 nhop = links[0][0] if metrix2<metrix1: metrix = metrix2 nhop = links[1][0] if metrix2==metrix1: metrix = metrix1 nhop = max(int(links[0][0]), int(links[1][0])) if node.upL1==False and node.upL2==False: metrix = "inf" nhop = "not reachable" if node.upL1==False and node.upL2==True: metrix = metrix2 nhop = links[1][0] if node.upL1==True and node.upL2==False: metrix = metrix1 nhop = links[0][0] print '{0:^14}{1:^21}{2:^3}\n'.format(k, metrix, nhop) # print state of flags (for testing) print "Link 1 flag is ", link1_flag print "Link 2 flag is ", link2_flag raw_input("press enter to continue...")