def __init__(self): self.launch_local_server(ip, port) self.buf = "" self.connect_to_server(ip, port) Node.__init__(self, self.socket) network.serverproxy = self out("proxy connected.")
def remove_rooms(self, coordinates): if isinstance(coordinates, tuple): x = coordinates[0] y = coordinates[1] try: self.floor_matrix[x][y] except IndexError: print("Coordinate", (x,y), "does not exist on this floor. There is nothing to remove.") return Node.remove_children(self, self.floor_matrix[x][y]) self.floor_matrix[x][y].coordinate = None self.floor_matrix[x][y] = False elif type(coordinates) == list: for c in range(0, len(coordinates)): x = coordinates[c][0] y = coordinates[c][1] try: self.floor_matrix[x][y] except IndexError: print("Coordinate", (x,y), "does not exist on this floor. There is nothing to remove.") continue Node.remove_children(self, self.floor_matrix[x][y]) self.floor_matrix[x][y].coordinate = None self.floor_matrix[x][y] = False
def add(self, item): temp = Node(item) # temp is a Node instance temp.set_next(self.head) if self.tail == None: self.tail == temp self.head = temp
def parseSystemList(self): systemslist = [] while self.currentToken.type in ('IDENTIFIER'): identifier = self.parseIdentifier() #EXTENSION of UPPAAL language: instantiation on system line #e.g. system Template(0), Template(1); if self.currentToken.type == 'LPAREN': # Process(5, true) # ^ inst = self.parseTemplateInstantiation(identifier) else: # Process params = [] inst = Node("TemplateInstantiation", params, identifier, ident=identifier, parameters=params) inst.priority = self.prioritycounter if self.currentToken.type == 'COMMA': self.accept('COMMA') elif self.currentToken.type == 'LESS': self.accept('LESS') self.prioritycounter += 1 systemslist.append( inst ) if self.currentToken.type == 'SEMI': self.accept('SEMI') break return systemslist
class FilterGroupNodeWrapper: def __init__(self, name, filters=OrderedDict()): self.name = name self.node = Node("ros_vision", "filter_chain_node.py", name) self.reset_params() self.node.run() create_filter_srv_name = '/%s/create_filter' % name rospy.wait_for_service(create_filter_srv_name) self.create_filter = rospy.ServiceProxy(create_filter_srv_name, CreateFilter) i = 0 for filter_name in filters.keys(): i += 1 if 'type' in filters[filter_name].keys(): filter_type = filters[filter_name]['type'] del filters[filter_name]['type'] for parameter_name in filters[filter_name].keys(): rosparam.set_param('/%s/%s/%s' % (name, filter_name, parameter_name), str(filters[filter_name][parameter_name])) self.create_filter(filter_name, filter_type, i) def reset_params(self): for p in rosparam.list_params(self.name): rosparam.delete_param(p) def kill(self): self.node.kill()
def parseExtern(self): self.accept('EXTERN') #has the form "extern somelib.somelib.ClassName" identnode = self.parseIdentifierComplex() n = Node('NodeExtern', [], identnode) #parse out the actual class name classnamenode = identnode while len(classnamenode.children) == 1 and \ classnamenode.children[0].type == 'Identifier': classnamenode = classnamenode.children[0] ident = classnamenode.leaf #do we have constructor parameters? if self.currentToken.type == 'EQUALS': self.accept('EQUALS') constructor_call_expr = self.parseExpression() assert len(constructor_call_expr.children) == 1 assert constructor_call_expr.children[0].type == 'FunctionCall' constructor_call = constructor_call_expr.children[0] n.children = [constructor_call] self.typedefDict[ident] = n self.externList += [ident] self.accept('SEMI') return n
def reduced_error_pruning(root,training_set,validation_set): ''' take the a node, training set, and validation set and returns the improved node. You can implement this as you choose, but the goal is to remove some nodes such that doing so improves validation accuracy. ''' if root.label != None or not validation_set: return root else: baseacc = validation_accuracy(root,validation_set) #treebest = root # To prune the tree, remove the subtree and assign # it a leaf node whose value is the most common # classification of examples associated with that node. newtree = Node() newtree.label = mode(validation_set) if validation_accuracy(newtree,validation_set) > baseacc: return newtree if root.is_nominal: # if the tree split according to nominal new = split_on_nominal(validation_set, root.decision_attribute) i = 0 for key in root.children: validation_set = new[i] root.children[key] = reduced_error_pruning(root.children[key],training_set,validation_set) i = i + 1 else: # if the tree split according to numeric new = split_on_numerical(validation_set, root.decision_attribute, root.splitting_value) validation0 = new[0] validation1 = new[1] root.children[0] = reduced_error_pruning(root.children[0],training_set,validation0) root.children[1] = reduced_error_pruning(root.children[1],training_set,validation1) return root
def test_init(self): startdata = 100 root = Node(startdata) self.assertEqual(root.getheight(), 0) self.assertEqual(root.getdata(), startdata) self.assertIsNone(root.getleft()) self.assertIsNone(root.getright())
def _get_link_details(entity, link_name): """"Lookup the (edge_class, left_edge_id, right_edge_id, node_class) for the given entity and link_name. param entity: The current entity Node subclass :param str link_name: The association proxy name edge_class: The Edge subclass the association is proxied through left_edge_id: The edge.{src,dst}_id right_edge_id: The edge.{dst,src}_id (opposit of left_edge_id) node_class: The target node the association_proxy points to """ # Look for the link_name in OUTBOUND edges from the current # entity for edge in Edge._get_edges_with_src(entity.__name__): if edge.__src_dst_assoc__ == link_name: return (edge, edge.src_id, edge.dst_id, Node.get_subclass_named(edge.__dst_class__)) # Look for the link_name in INBOUND edges from the current # entity for edge in Edge._get_edges_with_dst(entity.__name__): if edge.__dst_src_assoc__ == link_name: return (edge, edge.dst_id, edge.src_id, Node.get_subclass_named(edge.__src_class__)) raise AttributeError( "type object '{}' has no attribute '{}'" .format(entity.__name__, link_name))
def test_new_right_and_left(self): root = Node() root.set_root() right = root.new_right() left = root.new_left() self.assertEqual(right.sibling, left) self.assertEqual(left.sibling, right)
def test_parse_tree_manual(self): root = Node() current = root current.set_root() self.assertEqual(root, current) current = root.new_left() introspection = current current = introspection.new_left() current = current.parent self.assertEqual(introspection, current) current.token = '!' self.assertEqual('!', introspection.token) current.left = None self.assertIsNone(introspection.left) current = current.new_right() a = current current.token = 'a' self.assertEqual('a', a.token) current = current.parent self.assertEqual(introspection, current) current = current.parent self.assertEqual(current, root) current.token = ':' self.assertEqual(':', root.token) current = current.new_right() F = current current.token = 'F' self.assertEqual('F', F.token) current = current.parent self.assertEqual(root, current) current = current.parent self.assertEqual(root, current)
def __init__(self, start, end): Node.__init__(self) self.start = start self.end = end self.outter = False self.inverse = None logger.info("the edge has been created")
def test_sibling(self): right = Node() left = Node() right.sibling = left left.sibling = right self.assertEqual(right, left.sibling) self.assertEqual(left, right.sibling)
def __init__(self, site, log_path, output_split_logs = False): assert site is not None assert isinstance(site, str) assert log_path is not None assert isinstance(log_path, str) self._initialized = False self._nodes = None nodelogs = _split_node_data(log_path, output_split_logs) nodes = {} for nodeid, log in nodelogs.items(): print " * Loading data for node nr. %d ..." % nodeid assert not (nodeid in nodes.keys()) node = Node(site, nodeid, log) if node.initialized(): nodes[nodeid] = node else: print "warning: discarding data on node nr. %d since it failed to parse its log\n" % nodeid self._nodes = nodes self._initialized = True
def test_node(self): node1 = Node(addr1, id1, 'version') node2 = Node(addr2, id2) node1b = Node(addr1, None) node1ip = Node(('127.0.0.2', 1111), id1) node1port = Node(addr2, id1) node1id = Node(addr1, id2) eq_(str(node1), '<node: %r %r (version)>' % (addr1, id1)) #<node: ('127.0.0.1', 1111) 0x1313131313131313131313131313131313131313> eq_(node1.id, id1) assert node1.id != id2 assert node1.addr == addr1 eq_(node1.ip, addr1[0]) assert node1.addr != addr2 assert node1 == node1 assert node1 != node1b node1b.id = id1 assert node1 == node1b assert node1 != node2 assert node1 != node1ip assert node1 != node1port assert node1 != node1id
def add_here(self, new_item): """Adds an item to the list, between previous and current. @author Jeffrey Dowdle @since 31 Aug 2013 @param new_item: item to be added @post new_item will be added to the list, between previous and current. previous will point the newly added item. @complexity Best/Worst: O(1) """ new_node = Node(new_item, None) if self.linked_list.is_empty(): self.linked_list.head = new_node self.previous = new_node self.current = None else: if self.previous is None: new_node.link = self.linked_list.head self.linked_list.head = new_node self.previous = new_node elif self.current is None: self.previous.link = new_node self.previous = new_node else: self.previous.link = new_node new_node.link = self.current self.previous = new_node
def __init__(self, name, lic=None, file=None): if file is None: self.name = name self.ntc = Netica() self.env = self.ntc.newenv(lic) self.ntc.initenv(self.env) self.net = self.ntc.newnet(name, self.env) self.nodes = [] else: self.name = name self.ntc = Netica() self.env = self.ntc.newenv(lic) self.ntc.initenv(self.env) self.net = self.ntc.opennet(self.env, file) nodelist_p = self.ntc.getnetnodes(self.net) numnode = self.ntc.lengthnodelist(nodelist_p) self.nodes = [] for i in range(numnode): nodei_p = self.ntc.nthnode(nodelist_p, i) nodename = self.ntc.getnodename(nodei_p) statename = 'init'; statenames = []; istate = 0 while statename!='error': statename = self.ntc.getnodestatename(nodei_p, istate) statenames.append(statename) istate += 1 statenames = statenames[:-1] # default: no parents and continuous: therefore not the original nodes nodei = Node(nodename, parents=[], rvname='continuous') nodei.set_node_ptr(nodei_p) nodei.set_node_state_name(statenames) self.nodes.append(nodei)
def __init__(self, matrix, x, y, identity): Node.__init__(self, matrix, x, y, identity) self.name = 'Nexus' self.images['operational'] = self.images['node_operational'] self.images['damaged'] = self.images['node_damaged'] self.images['failed'] = self.images['node_failed'] self.image = self.images['operational'] self.rect = self.image.get_rect(center=(int(self.x),int(self.y))) self.radius = (self.image.get_width()//2) self.sound = {} self.sound['bootup'] = load_sound('powerup.wav') self.sound['bootup'].set_volume(0.3) self.matrix.node_update(self) self.initiation = False self.initiate = False self.init_count = 3 self.aware = False self.data_type = ['noncorrupt','corrupt'] self.data_process = 0 self.data_corruption = 0 self.data_integration = 0 self.data_integration_top = 0 self.integrity_high_color = engine.Color(80,100,220) self.integrity_low_color = engine.Color(180,50,50) self.integrity_loss = -0.001 self.integrity = 1.0 self.count = 10
def add(self, item): """ Add item to list """ temp = Node(item) temp.set_next(self.head) self.head = temp
def __init__(self): Node.__init__(self, -1) self.nodes = {} self.connections = {} self.index = 0 self.tnodes = {} self.doprop = True
def test_node(self): node1 = Node(addr1, id1) node2 = Node(addr2, id2) node1b = Node(addr1, None) node1ip = Node(('127.0.0.2', 1111), id1) node1port = Node(addr2, id1) node1id = Node(addr1, id2) assert str(node1) == '<node: %r %r>' % (addr1, id1) #<node: ('127.0.0.1', 1111) 0x1313131313131313131313131313131313131313> assert node1.id == id1 assert node1.id != id2 assert node1.addr == addr1 assert node1.addr != addr2 assert node1 == node1 assert node1 != node1b node1b.id = id1 assert node1 == node1b assert node1 != node2 assert node1 != node1ip assert node1 != node1port assert node1 != node1id
def randomNode(): node = Node() node.x = random.randint(10, 500) node.y = random.randint(10, 300) node.color = "black" graph.add(node) return node
class Queue(): def __init__(self): self.size = 0 self.head = None self.tail = None def push(self, value): if self.size == 0: self.size = self.size + 1 self.head = Node(value) else: node = Node(value) if not self.tail: self.tail = node self.tail.change_previous_node(self.head) self.head.change_next_node(self.tail) else: self.tail.change_next_node(node) node.change_previous_node(self.node) self.tail = node self.size = self.size + 1 def pop(self): element_to_pop = self.head self.head = self.head.get_next_node() self.size = self.size - 1 return element_to_pop def get_size(self): return self.size def peek(self): return self.head.get_value()
def create_cct(data, flag): entry = "lttng_ust_cyg_profile:func_entry" exit = "lttng_ust_cyg_profile:func_exit" tree = Node("root",[]) pointer = tree for each in data: if entry in each: if (flag): print ("cria no") begin = (each.find("addr")) begin += 7 end = begin + 7 name = (each[begin:end]) print (name) print () if("perf_thread_page_fault" in each): print ("page faults") if(pointer.get_label() == name): if (flag): print("already there") pointer.increment() else: aux = Node(name, []) pointer.add_child(aux) aux.set_parent(pointer) pointer = aux if exit in each: if(flag): print ("fecha no") pointer = pointer.get_parent() return tree
def add_node(self, node=None, pos=None, ori=None, commRange=None): """ Add node to network. Attributes: `node` -- node to add, default: new node is created `pos` -- position (x,y), default: random free position in environment `ori` -- orientation from 0 to 2*pi, default: random orientation """ if (not node): node = Node(commRange=commRange) assert(isinstance(node, Node)) if not node.network: node.network = self else: logger.warning('Node is already in another network, can\'t add.') return None pos = pos if pos is not None else self.find_random_pos(n=100) ori = ori if ori is not None else rand() * 2 * pi ori = ori % (2 * pi) if (self._environment.is_space(pos)): Graph.add_node(self, node) self.pos[node] = array(pos) self.ori[node] = ori self.labels[node] = str(node.id) logger.debug('Node %d is placed on position %s.' % (node.id, pos)) self.recalculate_edges([node]) else: logger.error('Given position is not free space.') return node
def test_ping(): node = Node('127.0.0.1:20000') reactor.listenTCP(20000, node) print node testMessage = Msg(0, 32812248528126350900072321242296281633, 10009, 293268701940054034179163628332357508988, 20000, -1, -1, True, {}, 0) node.send(testMessage, (32812248528126350900072321242296281633, 10009)) node.send(testMessage, (32812248528126350900072321242296281633, 10009))
def insert(self, s): node = self.seen[ord(s)] if node is None: spawn = Node(symbol=s, weight=1) internal = Node(symbol='', weight=1, parent=self.NYT.parent, left=self.NYT, right=spawn) spawn.parent = internal self.NYT.parent = internal if internal.parent is not None: internal.parent.left = internal else: self.root = internal self.nodes.insert(0, internal) self.nodes.insert(0, spawn) self.seen[ord(s)] = spawn node = internal.parent while node is not None: largest = self.find_largest_node(node.weight) if (node is not largest and node is not largest.parent and largest is not node.parent): self.swap_node(node, largest) node.weight = node.weight + 1 node = node.parent
def p_call(p): '''call : ID id_call LPAR par_call RPAR par_call2 | ID id_call LPAR par_call params RPAR par_call2 ''' global pila_Oz global cont global param_cont global temp_cont global mem_temp global list_temp #Check for ")" item = pila_Oz.pop() if item == ")": #Take elements out of stack until no params while item != "(": item = pila_Oz.pop() if item != "(": param = "param" + str(param_cont) #IF ID if isinstance(item, str): var = variableFetch(item) if isinstance(var, Node): op1 = var.mem #IF TMP elif isinstance(item, Node): op1 = item.name #IF CTE else: cte_memoryAssign(item) item = cte_list[item] op1 = item #PARAMS cuadruplo_temp = Cuadruplo() cuadruplo_temp.set_cont(cont) cuadruplo_temp.set_operator("param") cuadruplo_temp.set_operand1(op1) cuadruplo_temp.set_result(param) cuadruplos_list.append(cuadruplo_temp) cont += 1 param_cont += 1 #POPS name subname = pila_Oz.pop() #GO SUB createCuad("goSub", subname, None, None) #TEMPORAL output func = functionFetch(subname) if func.ret: temp = Node() tname = subname temp.name = tname temp.mem = mem_temp temp.value = func.ret.value list_temp.append(temp) pila_Oz.append(temp) temp_cont += 1 mem_temp += 1 param_cont = 0
def mockLaunch(name, ami='ami-3d4ff254', instance_type='t1.micro', key_name='amazon2', zone='us-east-1d', security_group='quicklaunch-1', job=None): """ Simulate a node launch for dev purposes """ i = { 'name': name, 'key_name': key_name, 'public_dns_name': u'ec2-107-21-159-143.compute-1.amazonaws.com', 'ip_address': u'107.21.159.143', 'private_dns_name': u'ip-10-29-6-45.ec2.internal', 'id': u'i-e2a5559d', 'image_id': ami, 'placement': zone, 'dns_name': u'ec2-107-21-159-143.compute-1.amazonaws.com', 'instance_type': instance_type, 'private_ip_address': u'10.29.6.45', 'user':user, 'jobs':job } n = Node(i['name'], i['id'], i['image_id'], i['key_name'], i['placement'], i['instance_type'], i['dns_name'], i['private_dns_name'], i['ip_address'], i['private_ip_address'], i['user'], job) pprint.pprint(n.to_dict()) addNode(n)
def __init__(self, cluster): # A lot of things are wrong in that method. It assumes that the ip # 127.0.0.<nbnode> is free and use standard ports without asking. # It should problably be fixed, but will be good enough for now. addr = '127.0.0.%d' % (len(cluster.nodes) + 1) self.path = tempfile.mkdtemp(prefix='bulkloader-') Node.__init__(self, 'bulkloader', cluster, False, (addr, 9160), (addr, 7000), str(9042), 2000, None)
def decisionTree(self, instances, attributes, target_class, top_edge=None): """ Função recursiva que cria uma árvore de decisão com base no conjunto 'instances' """ node = Node() node.top_edge = top_edge if len(instances) == 0: return node if self.haveSameClass(instances, target_class): # Se todos os exemplos do conjunto possuem a mesma classificação, # retorna node como um nó folha rotulado com a classe # Pega a classe da primeira instância. Tanto faz, pois todos têm a mesma classe. node.value = instances[0][target_class] return node if len(attributes) == 0: # Se L é vazia, retorna node como um nó folha com a classe mais # frequente no conjunto de instancias value = self.getMostFrequentClass(instances, target_class) node.value = value return node else: # Seleciona m atributos aleatórios e escolhe o melhor m = int(math.sqrt(len(attributes))) random_attributes = self.getRandomAttributes(attributes, m) attribute, info_gain = self.getBestAttribute(random_attributes, instances) node.value = attribute node.info_gain = info_gain attributes.remove(attribute) if self.attributes_types[attribute] == 'n': # atributo numerico values_sum = 0 for instance in instances: values_sum = values_sum + float(instance[attribute]) avg_value = values_sum / len(instances) subset_A, subset_B = self.getSubsetsForNumericAttribute(attribute, avg_value, instances) subset_A_attribute_value = '<= ' + str(avg_value) subset_B_attribute_value = '> ' + str(avg_value) node.children.append(self.decisionTree(subset_A, attributes[:], target_class, subset_A_attribute_value)) node.children.append(self.decisionTree(subset_B, attributes[:], target_class, subset_B_attribute_value)) else: # Para cada valor V distinto do atributo em questão, considerando os exemplos da lista de instancias: distinct_attribute_values = self.getDistinctValuesForAttribute(attribute, instances) for attribute_value in distinct_attribute_values: subset = self.getSubsetWithAttributeValue(attribute, attribute_value, instances) if len(subset) == 0: # Se esse subset for vazio, retorna node como nó folha rotulado # com a classe mais frequente no conjunto node.value = self.getMostFrequentClass(instances, target_class) return node else: node.children.append(self.decisionTree(subset, attributes[:], target_class, attribute_value)) return node
def __init__(self): self.current_node = Node(None, None) self.__size = 0
def create_node(self, tag=None, identifier=None, parent=None, data=None): """Create a child node for given @parent node.""" node = Node(tag=tag, identifier=identifier, data=data) self.add_node(node, parent) return node
def _add(self, value): self.length += 1 node = Node(value) if self.tail: self.tail.pointer = node self.tail = node
def _addFirst(self, value): self.length = 1 node = Node(value) self.head = node self.tail = node
from node import Node from graph import Graph list = [] z1 = Node("z1", [], [], 16) z2 = Node("z2", [], [], 20) z3 = Node("z3", [], [], 4) z4 = Node("z4", [], [], 3) z5 = Node("z5", [], [], 15) z6 = Node("z6", [], [], 14) z7 = Node("z7", [], [], 17) z8 = Node("z8", [], [], 6) z9 = Node("z9", [], [], 6) z10 = Node("z10", [], [], 4) z11 = Node("z11", [], [], 10) z12 = Node("z12", [], [], 8) z13 = Node("z13", [], [], 9) z14 = Node("z14", [], [], 7) z15 = Node("z15", [], [], 10) z16 = Node("z16", [], [], 9) z17 = Node("z17", [], [], 10) z18 = Node("z18", [], [], 8) z19 = Node("z19", [], [], 2) z20 = Node("z20", [], [], 3) z21 = Node("z21", [], [], 6) z22 = Node("z22", [], [], 5) z23 = Node("z23", [], [], 4) z24 = Node("z24", [], [], 11) z25 = Node("z25", [], [], 12) z26 = Node("z26", [], [], 9) z27 = Node("z27", [], [], 10)
from node import Node from linkedlist import LinkedList if __name__ == "__main__": node1 = Node(4, 4) node2 = Node(5, 2) node6 = Node(2, 5) linkedlist = LinkedList() print "%d words in linked list" % len(linkedlist) linkedlist.push(node1) linkedlist.push(node2) linkedlist.push(node6) print "%d values in linked list" % len(linkedlist) """ print 'num buckets: ', len(hashmap._buckets) print 'num empty buckets: ', hashmap.get_num_empty_buckets() print 'longest bucket: ', hashmap.get_longest_bucket() print 'shortest bucket: ', hashmap.get_shortest_bucket() print 'val in long bucket `weever`: ', hashmap.get('weever') print 'change_len: ', hashmap.change_len print 'repr: ', repr(hashmap) """
def push_front(self, value): new_front = Node(value, self.front) self.front = new_front self.size += 1
def push(self, item): """Inserts item at top of the stack.""" self._items = Node(item, self._items) self._size += 1
def add(self, item): # Add an item to the beginning of the list temp = Node(item) temp.set_next(self.head) self.head = temp
def search(self, b): # Initial unassigned variables unas_vrbls = [] for j in range(b.size_y): for i in range(b.size_x): if b.hints[i][j] == -1: variable = Unassigned_Variable((i, j), b, self.heuristic) unas_vrbls.append(variable) # Create the root node root = Node([], unas_vrbls, None) # Initial frontier # Frontier: stack frontier = [root] while len(frontier): # Expand the deepest (most recent) unexpanded node cur_node = frontier.pop() # Return assigned variables when solution is found # or skip this node if not consistent consistency = cur_node.consistency_check(b) if consistency == 0 and len(cur_node.unas_vrbls) == 0: return cur_node.asgn_vrbls elif consistency < 0 or len(cur_node.unas_vrbls) == 0: continue # Forward checking (Optional) if self.fc: if cur_node.last_sltd_vrbl is not None: if cur_node.forward_checking( b, cur_node.last_sltd_vrbl.position) != 0: continue # Heuristics (Optional) sort_count = len(cur_node.unas_vrbls) # MRV if self.mrv: sort_count = cur_node.mrv(sort_count) # Degree heuristic or Space heuristic if self.heuristic == 'degree': sort_count = cur_node.degree_hrs(b, cur_node.last_sltd_vrbl, sort_count) elif self.heuristic == 'space': sort_count = cur_node.space_hrs(b, cur_node.last_sltd_vrbl, sort_count) # LCV if self.lcv: cur_node.lcv(b) # Choose the selected variable to expand sltd_vrbl = cur_node.unas_vrbls.pop() for value in sltd_vrbl.domain: # Create child node and append to parent child_asgn_vrbls = copy.deepcopy(cur_node.asgn_vrbls) child_asgn_vrbls.append( Assigned_Variable(sltd_vrbl.position, value)) child_unas_vrbls = copy.deepcopy(cur_node.unas_vrbls) child = Node(child_asgn_vrbls, child_unas_vrbls, sltd_vrbl) cur_node.add_child(child) # Set frontier frontier.append(child) # Return empty list if no solution is found return []
def generate_node(node_options): return Node(**node_options)
def read_tree_string(instr): root = None index = 0 nextchar = instr[index] start = True keepgoing = True curnode = None while keepgoing == True: if nextchar == "(": if start == True: root = Node() curnode = root start = False else: newnode = Node() curnode.add_child(newnode) curnode = newnode elif nextchar == "[": note = "" index += 1 nextchar = instr[index] while True: if nextchar == "]": break index += 1 note += nextchar nextchar = instr[index] curnode.note = note elif nextchar == ',': curnode = curnode.parent elif nextchar == ")": curnode = curnode.parent index += 1 nextchar = instr[index] name = "" while True: if nextchar == ',' or nextchar == ')' or nextchar == ':' \ or nextchar == ';' or nextchar == '[': break name += nextchar index += 1 nextchar = instr[index] curnode.label = name index -= 1 elif nextchar == ';': keepgoing = False break elif nextchar == ":": index += 1 nextchar = instr[index] brlen = "" while True: if nextchar == ',' or nextchar == ')' or nextchar == ':' \ or nextchar == ';' or nextchar == '[': break brlen += nextchar index += 1 nextchar = instr[index] curnode.length = float(brlen) index -= 1 elif nextchar == ' ': index += 1 nextchar = instr[index] else: # this is an external named node newnode = Node() curnode.add_child(newnode) curnode = newnode curnode.istip = True name = "" while True: if nextchar == ',' or nextchar == ')' or nextchar == ':' \ or nextchar == ';' or nextchar == '[': break name += nextchar index += 1 nextchar = instr[index] curnode.label = name index -= 1 if index < len(instr) - 1: index += 1 nextchar = instr[index] return root
# dummy.py # This creates a fake node # hosting a random chain from aiohttp import web from wallet import Wallet from node import Node app = web.Application() # Change this soon to a # stored wallet node_creator = Wallet() node = Node(node_creator.address) async def chain(request): return web.Response(text=node.getChain(), content_type="application/json") app.router.add_get("/chain", chain) web.run_app(app, host="127.0.0.1", port=8080) print("RUNNING DUMMY NODE")
from import_list import import_list from node import Node from os import system my_list = import_list() node = Node(my_list) my_list = node.tri() print(my_list) system('pause')
def create_node(self, node_name, key_name=None, os_version=None, docker_version=None, wait_for_ready=True): os_version = os_version or self.OS_VERSION docker_version = docker_version or self.DOCKER_VERSION if self.DOCKER_INSTALLED.lower() == 'false': image, ssh_user = self._select_ami(os_version) else: image, ssh_user = self._select_private_ami(os_version, docker_version) if key_name: # if cert private key if key_name.endswith('.pem'): ssh_private_key_name = key_name ssh_private_key = self.get_ssh_key(key_name) ssh_private_key_path = self.get_ssh_key_path(key_name) else: # get private key ssh_private_key_name = key_name.replace('.pub', '') ssh_private_key = self.get_ssh_key(ssh_private_key_name) ssh_private_key_path = self.get_ssh_key_path( ssh_private_key_name) else: key_name = AWS_SSH_KEY_NAME.replace('.pem', '') ssh_private_key_name = key_name ssh_private_key = self.master_ssh_key ssh_private_key_path = self.master_ssh_key_path args = { "ImageId": image, "InstanceType": AWS_INSTANCE_TYPE, "MinCount": 1, "MaxCount": 1, "TagSpecifications": [{ 'ResourceType': 'instance', 'Tags': [{ 'Key': 'Name', 'Value': node_name }, { 'Key': 'CICD', 'Value': AWS_CICD_INSTANCE_TAG }] }], "KeyName": key_name, "NetworkInterfaces": [{ 'DeviceIndex': 0, 'AssociatePublicIpAddress': True, 'Groups': AWS_SECURITY_GROUPS }], "Placement": { 'AvailabilityZone': AWS_REGION_AZ }, "BlockDeviceMappings": [{ "DeviceName": "/dev/sda1", "Ebs": { "VolumeSize": 50 } }] } if (len(AWS_IAM_PROFILE) > 0): args["IamInstanceProfile"] = {'Name': AWS_IAM_PROFILE} instance = self._client.run_instances(**args) node = Node(provider_node_id=instance['Instances'][0]['InstanceId'], state=instance['Instances'][0]['State']['Name'], ssh_user=ssh_user, ssh_key_name=ssh_private_key_name, ssh_key_path=ssh_private_key_path, ssh_key=ssh_private_key, os_version=os_version, docker_version=docker_version) # mark for clean up at the end self.created_node.append(node.provider_node_id) if wait_for_ready: node = self.wait_for_node_state(node) node.ready_node() return node
def test_initial_state(self): print("test0\n") view = [addr1, addr2, addr3, addr4] shard = Node(router, addr1, view, repl_factor) print(shard) self.assertTrue(shard != None)
def readInput(input_file): """ Read input parameters from a file. It is assumed that the input file contains key-value pairs in the form "key value" on separate lines. If a keyword containing the string 'geometry' is encountered, the corresponding geometries are read in the form (example for methane dissociation): geometry ( 0 1 C -0.03144385 0.03144654 0.00041162 H 0.32521058 -0.97736346 0.00041162 H 0.32522899 0.53584473 0.87406313 H 0.32522899 0.53584473 -0.87323988 H -1.10144385 0.03145972 0.00041162 **** C -0.36061854 -0.43406458 0.80670792 H 0.14377652 -1.32573293 0.49781771 H 0.14379613 0.27926689 1.42446520 H 0.56523315 0.87525286 -1.46111753 H -1.36941886 -0.25571437 0.49781777 ) If '#' is found in a line, the rest of the line will be ignored. A dictionary containing all input parameters and their values is returned. """ # Allowed keywords keys = ('reac_smiles', 'nbreak', 'nform', 'dh_cutoff', 'forcefield', 'name', 'nsteps', 'nnode', 'lsf', 'tol', 'gtol', 'nlstnodes', 'qprog', 'theory', 'theory_low') # Read all data from file with open(input_file, 'r') as f: input_data = f.read().splitlines() # Create dictionary input_dict = {} # Extract remaining keywords and values for line in input_data: if line != '' and not line.strip().startswith('#'): key = line.split()[0].lower() if key not in keys: continue if line.split()[1] == '=': input_dict[key] = line.split()[2] else: input_dict[key] = line.split()[1] # Read geometry block read = False geometry = [] sep_loc = -1 for line in input_data: if line.strip().startswith(')'): break if read and not line.strip().startswith('#') and line != '': geometry.append(line) if line.strip().startswith('*'): sep_loc = len(geometry) - 1 elif 'geometry' in line: read = True if geometry: if sep_loc == -1: raise Exception('Incorrect geometry specification') # Extract multiplicity, atoms, and geometries multiplicity = geometry[0].split()[1] reactant = geometry[1:sep_loc] reac_atoms = [line.split()[0] for line in reactant] reac_geo = [[float(coord) for coord in line.split()[1:4]] for line in reactant] product = geometry[sep_loc + 1:] prod_atoms = [line.split()[0] for line in product] prod_geo = [[float(coord) for coord in line.split()[1:4]] for line in product] # Create nodes reac_node = Node(reac_geo, reac_atoms, multiplicity) prod_node = Node(prod_geo, prod_atoms, multiplicity) # Add to dictionary input_dict['reactant'] = reac_node input_dict['product'] = prod_node # Check if valid method was specified and default to FSM try: method = input_dict['method'].lower() except KeyError: input_dict['method'] = 'fsm' except AttributeError: raise Exception('Invalid method') else: if method != 'gsm' and method != 'fsm': raise Exception('Invalid method: {}'.format(method)) return input_dict
def as_subdomain(self) -> list[Node]: return gzip('/*') + log() + [ Node(f'file_server /* browse', [Node(f'root {self.path}'), Node(f'hide .*')]) ] + hidden()
def __init__(self): self.cabeca = None self.cauda = None def len(self): tamanho = 0 if self.cabeca is not None: tamanho += 1 atual = self.cabeca while atual is not self.cauda: tamanho += 1 atual = atual.next return tamanho node1 = Node(2) node2 = Node(5) node3 = Node('Bryan') node4 = Node(3.14) node1.next = node2 node1.prev = node4 node2.next = node3 node2.prev = node1 node3.next = node4 node3.prev = node2 node4.next = node1 lista = ListaCircular() lista.cabeca = node1 lista.cauda = node4 print(lista.len())
from node import Node if len(sys.argv) < 3: sys.stderr.write("Usage: [node Id] [neighbour1 Id] [neighbour2 Id] ...\n") sys.exit(1) if sys.argv[1] == '0': sys.stderr.write("Warning: [node Id] could not be an integer but 0\n") sys.exit(1) if sys.argv[1] in sys.argv[2:]: sys.stderr.write("Warning: [node Id] could not be in neighbours list\n") sys.exit(1) est_racine = raw_input("ce noeud est-il la racine? O/N : ") holder = False node_id = int(sys.argv[1]) voisins = [] for i in sys.argv[2:]: voisins.append(int(i)) while (est_racine != 'o' and est_racine != 'O' and est_racine != 'n' and est_racine != 'N'): est_racine = input( "ce noeud est-il la racine? Repondez par O(oui) ou N(non): ") if est_racine == 'o' or est_racine == 'O': holder = True Node(node_id, voisins, holder)
if __name__ == '__main__': # Get data from the json file json_file = sys.argv[1] node_id, port, node_list = get_server_info(json_file) # Server Address udp_host = socket.gethostbyname(socket.gethostname()) # Host IP udp_port = port # Specified port to connect server_address = (udp_host, udp_port) # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(server_address) server = Node(node_id, server_address, 'FOLLOWER', node_list, sock) server.update_state() print(server) server.socket.setblocking(False) while True: try: # Receive response data, address = sock.recvfrom(4096) message = Message.deserialize(data.decode()) print(message) # It's time to send a heartbeat message server.heartbeat_timeout_due()
raise ValueError() return res = top.data lres = 0 rres = 0 if top.left != None: lres = max_bst(top.left) if top.right != None: rres = max_bst(top.right) if lres > res: res = lres if rres > res: res = rres return res root = Node(1) root.left = Node(5) root.right = Node(2) root.left.left = Node(-6) root.left.right = Node(11) root.right.left = Node(0) root.right.right = Node(8) minV = min_bst(root) maxV = max_bst(root) print "Minimalna wartosc w drzewie: " + str(minV) print "Maksymalna wartosc w drzewie: " + str(maxV)
def nextSubgraph(self): token = self.buffer.peek() word_pos = token.word + "_" + token.pos lemma_pos = token.lemma + "_" + token.pos #TRICK FOR SEMICOLONS if token.word == ";": if self.semicol_gen_and: return Subgraph([],[]) else: self.semicol_gen_and = True return Subgraph([Node(token, self.variables.nextVar(), "and", False)],[]) #HOOKS if self.hooks and token.ne != "O" and (token.ne == "ORGANIZATION" and word_pos in Resources.phrasetable) == False: ret = hooks.run(token, token.word, token.ne, self.variables) if ret != False: return Subgraph(ret[0],ret[1]) #ISI LISTS # if token.word in Resources.verbalization_list: # return Resources.verbalization_list[token.word].get(token, self.variables) # if token.lemma in Resources.verbalization_list: # return Resources.verbalization_list[token.lemma].get(token, self.variables) #PHRASETABLE if word_pos in Resources.phrasetable: return Resources.phrasetable[word_pos].get(token, self.variables) if lemma_pos in Resources.phrasetable: return Resources.phrasetable[lemma_pos].get(token, self.variables) #UNKNOWN TOKENS (variables or constants) if token.ne == "O": #var v = self.variables.nextVar() label = "" if token.pos.startswith("V"): label = token.lemma.replace('"','') if label == "": label = "emptyconcept" label += "-01" if label == "": label = token.lemma if label == "": label = token.word if label.count('"') % 2 != 0: label = "".join(label.rsplit('"', 1)) if label.count("'") % 2 != 0: label = "".join(label.rsplit("'", 1)) label = label.replace('""','"') if "_" in label or "\\" in label or ":" in label or "/" in label or "(" in label or ")" in label: label = "genericconcept" if label == "": label = "emptyconcept" if label.startswith("@"): label = label[1:] label = label.lower() return Subgraph([Node(token, v, label, False)],[]) #UNKNKOWN CONSTANTS nodes = [] token.word = re.sub("[-\/\\\/\(\)]","_",token.word) for t in token.word.split("_"): if t.replace(".","").isdigit() and t != '""': nodes.append(Node(token, t, token.ne, True)) elif t != "": nodes.append(Node(token, '"' + t + '"', token.ne, True)) return Subgraph(nodes,[])
def insert(self, string): node = self.root for char in string + "$": if char not in node.children: node.children[char] = Node(char) node = node.children[char]
def ExpandNodeDFS(fringe, node): # this is the tricky bit # CASE 1: one chicken in boat # check which side boat is on if (node.data[2] == 1): #boat is on left side tmp = list(node.data) if (tmp[0] >= 1): # check that there are chickens to move tmp[0] -= 1 tmp[3] += 1 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 0 tmp[5] = 1 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) else: #boat is on right side tmp = list(node.data) if (tmp[3] >= 1): # check that there are chickens to move tmp[3] -= 1 tmp[0] += 1 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 1 tmp[5] = 0 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) # CASE 2: two chickens in boat # check which side boat is on if (node.data[2] == 1): #boat is on left side tmp = list(node.data) if (tmp[0] >= 2): # check that there are chickens to move tmp[0] -= 2 tmp[3] += 2 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 0 tmp[5] = 1 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) else: #boat is on right side tmp = list(node.data) if (tmp[3] >= 2): # check that there are chickens to move tmp[3] -= 2 tmp[0] += 2 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 1 tmp[5] = 0 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) # CASE 3: one wolf in boat # check which side boat is on if (node.data[2] == 1): #boat is on left side tmp = list(node.data) if (tmp[1] >= 1): # check that there are wolves to move tmp[1] -= 1 tmp[4] += 1 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 0 tmp[5] = 1 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) else: #boat is on right side tmp = list(node.data) if (tmp[4] >= 1): # check that there are wolves to move tmp[4] -= 1 tmp[1] += 1 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 1 tmp[5] = 0 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) # CASE 4: one wolf one chicken # check which side boat is on if (node.data[2] == 1): #boat is on left side tmp = list(node.data) if (tmp[0] >= 1 and tmp[1] >= 1): # check that there are wolves and chickens to move tmp[0] -= 1 tmp[3] += 1 tmp[1] -= 1 tmp[4] += 1 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 0 tmp[5] = 1 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) else: #boat is on right side tmp = list(node.data) if (tmp[3] >= 1 and tmp[4] >= 1): # check that there are wolves and chickens to move tmp[4] -= 1 tmp[1] += 1 tmp[3] -= 1 tmp[0] += 1 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 1 tmp[5] = 0 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) # CASE 5: two wolves in boat # check which side boat is on if (node.data[2] == 1): #boat is on left side tmp = list(node.data) if (tmp[1] >= 2): # check that there are wolves to move tmp[1] -= 2 tmp[4] += 2 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 0 tmp[5] = 1 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node) else: #boat is on right side tmp = list(node.data) if (tmp[4] >= 2): # check that there are wolves to move tmp[4] -= 2 tmp[1] += 2 # check wolf condition if (tmp[0] == 0 and tmp[3] >= tmp[4]) or ( tmp[3] == 0 and tmp[0] >= tmp[1]) or (tmp[0] >= tmp[1] and tmp[3] >= tmp[4]): # all good, create node # switch boat tmp[2] = 1 tmp[5] = 0 # create node and add to bottom of fringe new_node = Node(tmp, node, None) fringe.put(new_node) # add new node to current node's children node.AddChild(new_node)
def generateGrid(self): for i in range(0, self.width, 30): for j in range(0, self.height, 30): self.nodeList[str(i)+' '+str(j)] = Node(i, j) self.connectNeighbours() return self
def __init__(self): self.root = Node("") self.show_list = [] self.solution = []
def dibbs(start: np.ndarray, goal: np.ndarray, forward_heuristic, reverse_heuristic): forward_fbar = defaultdict(lambda: math.inf) backward_fbar = defaultdict(lambda: math.inf) start_node = Node(None, start, None, None, 0, forward_heuristic, reverse_heuristic) goal_node = Node(None, goal, None, None, 0, reverse_heuristic, forward_heuristic) forward_fbar[start_node] = start_node.f_bar forward_fbar_min = 0 backward_fbar[goal_node] = goal_node.f_bar backward_fbar_min = 0 forward_frontier = [start_node] forward_set = {start_node: (start_node, 1)} backward_frontier = [goal_node] backward_set = {goal_node: (goal_node, 1)} upper_bound = math.inf explore_forward = False best_node = None count = 0 f_combined = -math.inf b_combined = -math.inf best_f_fbar = -math.inf best_b_fbar = -math.inf f_cost = -math.inf b_cost = -math.inf while upper_bound > (forward_fbar_min + backward_fbar_min) / 2: if explore_forward: upper_bound, best_node, count = expand(forward_frontier, forward_set, backward_set, forward_heuristic, reverse_heuristic, upper_bound, best_node, count) forward_fbar_min = forward_frontier[0].f_bar if forward_frontier[0].cost > f_cost: f_cost = forward_frontier[0].cost print("Forward cost: ", f_cost) if forward_fbar_min > best_f_fbar: best_f_fbar = forward_fbar_min print("Forward fbar:", best_f_fbar) if forward_frontier[0].combined > f_combined: f_combined = forward_frontier[0].combined print("Forward combined: ", f_combined) else: upper_bound, best_node, count = expand(backward_frontier, backward_set, forward_set, reverse_heuristic, forward_heuristic, upper_bound, best_node, count) backward_fbar_min = backward_frontier[0].f_bar if backward_frontier[0].cost > b_cost: b_cost = backward_frontier[0].cost print("Backward cost: ", b_cost) if backward_fbar_min > best_b_fbar: best_b_fbar = backward_fbar_min print("Backward fbar:", best_b_fbar) if backward_frontier[0].combined > b_combined: b_combined = backward_frontier[0].combined print("Backward combined: ", b_combined) explore_forward = forward_fbar_min < backward_fbar_min #explore_forward = len(forward_frontier) < len(backward_frontier) #explore_forward = forward_frontier[-1].cost < backward_frontier[-1].cost path = best_node.get_path() reverse_path = best_node.reverse_parent.get_path() best_start_state = None for x in best_node: best_start_state = x.state if np.array_equal(best_start_state, start): path, reverse_path = reverse_path, path path = [(face, ro.inverse_rotation(rotation)) for face, rotation in path] path.extend(reversed(reverse_path)) faces = [] rotations = [] for face, rotation in path: if face is not None: faces.append(face) rotations.append(rotation) return faces, rotations, count
from node import Node from singly_list import SinglyList from print_list import print_list from remove import remove list = SinglyList() list.add_head(Node("b")) list.add_head(Node("c")) list.add_head(Node("a")) list.add_head(Node("d")) list.add_head(Node("e")) list.add_head(Node("f")) list_head = list.head remove(list_head, "a") print_list(list_head)