def dump_tree(root_node): for pre, _, node in RenderTree(root_node, style=AsciiStyle()): print("%s%s" % (pre, (str(node.name.id) + "-" + str(node.name.status)))) pass
def print_tree(tree): for pre, fill, node in RenderTree(tree, style=AsciiStyle()): print("{0}{1} [{2}]".format(pre, node.label, node.module)) if node.params != '': kwargs = split_params(node.params) for k,v in kwargs.items(): print("{0}{1}: {2}".format(fill, k, v)) print("{0}".format(fill))
def highlight_node(name, node, color='red'): for pre, fill, node in RenderTree(node, style=AsciiStyle()): if name in node.name: start = node.name.find(name) end = start + len(name) print pre + node.name[:start] + bcolors.RED + node.name[start:end] + bcolors.ENDC + node.name[end:] else: print("%s%s" % (pre, node.name))
def __init__(self, train_data, train_target): """put the data in the model""" self._train_data = train_data self._train_target = train_target self._target_feature = train_target.to_frame().columns[0] classes = [] self._tree = self._make_ID3_tree(self._train_data, self._train_target, None, "root") print RenderTree(self._tree, style=AsciiStyle())
def startt(): start.destroy() print("SON OF MANARCHY") print("type 'help' for help\n") print(RenderTree(wake_up, style=AsciiStyle()).by_attr()) user.node = suspicious.name # print(wake_up.statement) # print(all_items, all_characters) prompt_command()
def pretty_ast(ast: Node) -> str: """Create a nice string representation of an AST. Parameters ---------- ast: Node Tree to be pretty printed. Returns ------- pretty_tree: str Prettified tree ready to print. """ try: ast.full_name return RenderTree(ast, style=AsciiStyle()).by_attr('full_name') except AttributeError: return RenderTree(ast, style=AsciiStyle()).by_attr('name')
def tree(self, sents, lang='en', engine='stanza'): """ $ python -m sagas.nlu.anal tree 'Nosotros estamos en la escuela.' es stanza :param sents: :param lang: :param engine: :return: """ tree_root = build_anal_tree(sents, lang, engine) print( RenderTree(tree_root, style=AsciiStyle()).by_attr( lambda n: f"{n.dependency_relation}: {n.text} ({n.upos.lower()})"))
def print_tree_tab_structure(self, notes=""): """A debugging function for logging state of the tree tabs""" with open("qutebrowser_treetab.log", 'a') as f: f.write("%s" % notes) cur_tab = self.tabBar()._current_tab() for pre, _, node in RenderTree(self.tree_root, style=AsciiStyle()): name = node.name.tab_id if node.name else 'ROOT' curr = '*' if cur_tab and cur_tab.node == node else '' f.write("%s%s%s\n" % (pre, name, curr)) f.write("\n")
def render_tree(tree_root, max_depth, tree_ascii=False): style = AsciiStyle() if tree_ascii else ContStyle() output = [] for child in tree_root.children: lines = [] for fill, _, node in RenderTree(child, style=style): if max_depth and node.depth > max_depth: continue lines.append(u"{}{} ({}{})".format( fill, node.pip_string, node.version, ", cyclic" if hasattr(node, "cyclic") else "", )) output += lines return "\n".join(output)
def print_bookmark_tree(root: Node): ''' Print a nested bookmark tree from a root tree `Node`, folders first bookmark with urls second. ''' for pre, _, node in RenderTree(root, style=AsciiStyle()): if node.node_type == Folder: required = ('folder_name', ) args = [getattr(node, key) for key in required] args[0] = f'[F] {node.id}\t{args[0]}' elif node.node_type == Bookmark: required = ('title', 'url') args = [getattr(node, key) for key in required] args[0] = f'[B] {node.id}\t{args[0]}' print(f'{pre}{" ".join(args)}')
def main(logger_, cache_dir, start_month, output_dir, refresh=True): global logger logger = logger_ ensure_directory(cache_dir) mbox_paths = mboxes_download(cache_dir, start_month, refresh) root, lookup, releases = mboxes_process(mbox_paths) discussions = discussions_find(root, lookup, releases) discussions = discussions_reduce(discussions) export = discussions_export(lookup, releases, discussions) ensure_directory(output_dir) with open(path.join(output_dir, 'mail.yaml'), 'w') as outfile: yaml.safe_dump(export, outfile) if logger.isEnabledFor(logging.DEBUG): from anytree import RenderTree, AsciiStyle print(RenderTree(root, style=AsciiStyle()).by_attr()) discussion_print(export)
def draw(self, translate=False): """ >>> from sagas.nlu.anal import build_anal_tree, Doc, AnalNode >>> f=build_anal_tree('Η σαλάτα μου έχει τομάτα.', 'el', 'stanza') >>> f.draw(True) :param translate: :return: """ def additional(n): addons = [str(n.index), n.lemma] if n.upos == 'VERB': if n.personal_pronoun_repr: addons.append(n.personal_pronoun_repr) if n.dependency_relation != 'punct': if translate: from sagas.nlu.translator import get_contrast addons.append(get_contrast(n.text, n.lang)) return '; '.join(addons) print( RenderTree(self, style=AsciiStyle()).by_attr( lambda n: f"{n.dependency_relation}: {n.text} " f"({additional(n)}, {n.upos.lower()})"))
def create_tree(lines_str): lines = lines_str.split("\n") previous_sign_index = 0 parent_node = Node(lines[0]) reference_node = parent_node for i in range(1, len(lines)): line = lines[i] level = 0 if sign1 in line: sign1_index = line.index(sign1) + 3 level = (sign1_index - previous_sign_index) / eachLevelDistance previous_sign_index = sign1_index line = line[sign1_index:len(line)] elif sign2 in line: sign2_index = line.index(sign2) + 3 level = (sign2_index - previous_sign_index) / eachLevelDistance previous_sign_index = sign2_index line = line[sign2_index:len(line)] reference_node = add_to_tree(reference_node, line, level) logging.debug("----DependencyTree-----\n" + RenderTree(parent_node, style=AsciiStyle()).by_attr()) return parent_node
def digest_verb(sents, lang, engine='stanza'): f = build_anal_tree(sents, lang, engine) words = findall_by_attr(f, name='upos', value='VERB') if words: print(sents, len(words)) rs = [] for w in words: rs.append(proc_verb_subs(w)) def proc_text(t): if lang in ('ko'): return get_contrast(t, lang) return t succ = any(rs) cl = 'blue' if succ else 'white' tc.emp( cl, RenderTree(f, style=AsciiStyle()).by_attr( lambda n: f"{n.dependency_relation}: {proc_text(n.text)} {n.upos}")) return succ return False
def main(): print() aux = argv[1].split(".") if aux[-1] != "tpp": raise IOError("Not a .tpp file!") data = open(argv[1]) source_file = data.read() parser.parse(source_file) try: if root and root.children != (): print("\n-------------OK--------------") print("Generating Syntax Tree Graph...") DotExporter(root).to_picture(argv[1] + ".ast.png") UniqueDotExporter(root).to_picture(argv[1] + ".unique.ast.png") DotExporter(root).to_dotfile(argv[1] + ".ast.dot") UniqueDotExporter(root).to_dotfile(argv[1] + ".unique.ast.dot") print(RenderTree(root, style=AsciiStyle()).by_attr()) print("Graph was generated.\nOutput file: " + argv[1] + ".ast.png") DotExporter( root, graph="graph", nodenamefunc=MyNode.nodenamefunc, nodeattrfunc=lambda node: "label=%s" % (node.type), edgeattrfunc=MyNode.edgeattrfunc, edgetypefunc=MyNode.edgetypefunc, ).to_picture(argv[1] + ".ast2.png") DotExporter(root, nodenamefunc=lambda node: node.label).to_picture( argv[1] + ".ast3.png" ) except NameError: print("Não foi possível gerar a árvore sintática.") print("\n\n")
def main(): groupObj = PairingGroup('SS512') cpabe = IDABE.IDABE(groupObj) gpfile = "global.param" cpabe.setupGP(gpfile) ta_conf = cpabe.read_attr_dict("TAs.config") print("TA configurations: ", ta_conf) TAset = ta_conf['TAs'] ta_msk_filenames = ta_conf['TAmsk'] ta_pk_filenames = ta_conf['TApubs'] # org tree structure root = Node("org1") org2 = Node("org2", parent=root) org3 = Node("org3", parent=root) org4 = Node("org4", parent=root) org5 = Node("org5", parent=org2) org6 = Node("org6", parent=org2) print("Organization Tree Structure\n") print(Fore.BLUE + RenderTree(root, style=AsciiStyle()).by_attr()) print(Style.RESET_ALL) # each TA first generate their own public key and msk key for ta in TAset: cpabe.ta_setup_tree(ta_pk_filenames[ta], ta_msk_filenames[ta], root) # this simulates how multiple TAs generate the fe for i in range(1, len(TAset)): ta_first = "ta" + str(i) ta_second = "ta" + str(i + 1) cpabe.federated_setup1(ta_pk_filenames[ta_first], ta_pk_filenames[ta_second], ta_msk_filenames[ta_second], root) command = "cp {} {}".format(ta_pk_filenames[TAset[-1]], "pk.param") print("command is ", command) os.system(command)
def print_tree(self): """Prints table as it is stored in tree. Relevant for rowspan/colspan only""" if self.table_tree: for pre, _, node in RenderTree(self.table_tree, style=AsciiStyle()): print(pre, node.name, node.position, node.obj)
while True: if current_node.is_root and len(current_node.children) > 0: current_node = current_node.children[0] else: if current_node.is_leaf: return current_node elif len(current_node.children) > 0: current_node = current_node.children[0] if __name__ == '__main__': l = [0, 1, 2, 99.0, 118.0, 200.315, 75, 64, 22] print(find_max_cpu_util(l)) # Example of a Binary Search Tree root = Node(99.0) root_rc = Node(99.5, parent=root) root_lc = Node(1, parent=root) rrc_rc = Node(100, parent=root_rc) rrc_rc_rc = Node(101, parent=rrc_rc) print(RenderTree(root, style=AsciiStyle()).by_attr()) print(find_max_cpu_util_tree(root))
def __repr__(self): return str(RenderTree(self.root, style=AsciiStyle()))
orbiterNode = find_by_attr(ERRANDS, orbiter) if orbiterNode is not None: orbiterNode.parent = centerNode else: orbiterNode = Node(orbiter, parent=centerNode) return COM def verifymap(orbitmap): """Verifies an orbitmap, returns the checksum >>> verifymap(readmap("COM)B\\nB)C\\nC)D\\nD)E\\nE)F\\nB)G\\nG)H\\nD)I\\nE)J\\nJ)K\\nK)L")) 42 """ count = 0 orbiters = findall(orbitmap, filter_=lambda node: node.name != "COM") for orbiter in orbiters: count += orbiter.depth return count if __name__ == "__main__": with open("data") as data: orbitmap = data.readlines() orbitmap = readmap(orbitmap) print(RenderTree(orbitmap, style=AsciiStyle()).by_attr()) checksum = verifymap(orbitmap) print("Checksum is: %d" % checksum)
def render_beautify_tree(tree, ofd): tree = beautify_tree(tree) for pre, _, node in RenderTree(tree, style=AsciiStyle()): print_writeofd("%s%s" % (pre, node.name), ofd)
def ascii_art(self): print(RenderTree(self.root, style=AsciiStyle()))
def renderTreeToFile(filename, tree): f = open(filename + "_out.txt", "w") for pre, _, node in RenderTree(tree, style=AsciiStyle()): f.write("%s%s\r" % (pre, node.name))
def render_tree(self): """Print tree structure.""" print(RenderTree(self.root, style=AsciiStyle()).by_attr()) return self
def prune_taxtree(): for node in PreOrderIter(taxtree, filter_=lambda n: rankmap.get(n.name) == 'genus' and len(n.children) > 0): node.children = [] # for node in PreOrderIter(taxtree, # filter_=lambda n: len(n.children) == 0 # and rankmap.get(n.name) != 'genus'): fill_rankmap() prune_taxtree() t = RenderTree(taxtree, style=AsciiStyle()).by_attr() hdl = open('taxtree.txt', 'w') hdl.write(t + '\n') print('Writing taxid db') count = -1 m = {} tfile = open('trainset_db_taxid.txt', 'w') rankmap['Root'] = 'rootrank' for node in PreOrderIter(taxtree): count = count + 1 m[node.name] = count if count == 0: parentno = -1 else: parentno = m.get(node.parent.name)
# reference: https://stackoverflow.com/questions/2358045/how-can-i-implement-a-tree-in-python # http://pydoc.net/anytree/2.4.3/anytree.node.nodemixin/ # reference: https://anytree.readthedocs.io/en/latest/ from anytree import Node, RenderTree, Walker from anytree import Node, RenderTree, AsciiStyle layer1 = Node(44) layer2_1 = Node(6, parent=layer1) layer2_2 = Node(9, parent=layer1) layer3_1 = Node(34, parent=layer2_2) layer3_2 = Node(5, parent=layer2_1) layer3_3 = Node(4, parent=layer2_1) print('\nShowing the entire tree:') for pre, fill, node in RenderTree(layer1): print("%s%s" % (pre, node.name)) print('\n') w = Walker() print('\nWalking the tree, layers3_2, and layers3_3:') print(w.walk(layer3_2, layer3_3)) print('\n') print('Showing the tree AsciiStyle:') print(RenderTree(layer1, style=AsciiStyle())) print('\n') # reference: https://anytree.readthedocs.io/en/latest/
beliefsTree.append(AxiomNode('belief'+str(nCandidate), beliefLeaf, parent = beliefsTree[nParents], axiom = candLeaf)) # retreiving the branch containing the explanation explanation = [i.name for i in list(beliefsTree[-1].path)] # for the path fram leaf to root break else: nCandidate += 1 candNode = [] beliefNode = [] for candidate in candidatePair: candNode.append(candidate[1]) if candidate[0]: beliefNode.append(candidate[0][0]) beliefsTree.append(AxiomNode('belief'+str(nCandidate), beliefNode, parent = beliefsTree[nParents], axiom = candNode)) extendedBeliefs.append(beliefNode) if stop: break beliefs = extendedBeliefs if not beliefs: stop = 1 nParents += 1 print (RenderTree(beliefsTree[0], style=AsciiStyle()).by_attr()) for beliefs in beliefsTree: print beliefs.name+' : ' print beliefs.belief print beliefs.axiom
def print_tree(structures_tree, root_node_idx=0): from anytree import RenderTree, AsciiStyle root_node = structures_tree[root_node_idx] print(RenderTree(root_node, style=AsciiStyle()))
else: error() check_point(FACTOR[1], followset=FACTOR[0], patron_follow=ID_NUM) return temp # PROGRAMA PRINCIPAL actualizar_token() raiz = programa() if not os.path.exists(directorio_sintactico): os.makedirs(directorio_sintactico) with open(directorio_sintactico + os.path.sep + ARBOL_TXT, "w") as archivo_arbol: archivo_arbol.write(str(RenderTree(raiz, style=AsciiStyle()))) if os.name == 'posix': RenderTreeGraph(raiz, nodeattrfunc=lambda node: "shape = box").to_picture( directorio_sintactico + os.path.sep + ARBOL_PNG) elif os.name == 'nt': RenderTreeGraph(raiz, nodeattrfunc=lambda node: "shape = box").to_dotfile( directorio_sintactico + os.path.sep + ARBOL_DOT) comando = "dot " + directorio_sintactico + os.path.sep + ARBOL_DOT + " -T png -o " + directorio_sintactico + os.path.sep + ARBOL_PNG startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW subprocess.call(comando, startupinfo=startupinfo) with open(directorio_sintactico + os.path.sep + "errores_sintacticos.txt", "w") as archivo_errores_sintacticos: for error in errores:
def draw_tree(self, tree): for prefix, _, node in RenderTree(tree, style=AsciiStyle()): print("%s%s" % (prefix.replace('+', '`'), node.name))