Ejemplo n.º 1
0
def init_step_random_balanced(evidence, encoder, predictions, seq_len,
                              observ_len, token_len, max_episode_steps):
    if np.random.rand() < 0.2:
        nodes = [x for x in PreOrderIter(evidence['tree']) if not x.dummy]
    else:
        nodes = [
            x for x in PreOrderIter(evidence['tree'])
            if not x.dummy and not hasattr(x, 'sidx')
        ]
    node = random.choice(nodes)

    if node.is_root:
        step = 0
    else:
        min_step = node.depth + get_node_dist(node.parent)[0]
        max_step = max_episode_steps - 1  # minus 1 because counting from 0
        if min_step >= max_step:
            step = max_step
        else:
            step = np.random.randint(min_step, max_step)

    preds = predictions if to_add_prediction(node) else None
    info = get_node_observ_props(node, step, evidence, encoder, seq_len,
                                 observ_len, token_len, preds)
    (observ_w, observ_c, props, ans_w, ans_c, ans_p) = info

    return node, observ_w, observ_c, props, ans_w, ans_c, ans_p, step
Ejemplo n.º 2
0
def annotate_dep_tree(
    tree, whitelist: [str], ignored_packages: [str]
) -> Tuple[AnyNode, Set[str]]:
    """
  An idea of this function is to go through elements from the bottom -> up and
  mark subtree_problem if any of the children has a license_problem or a subtree_problem
  :param tree:
  :param whitelist:
  :param ignored_packages:
  :return: list of licenses not found in a whitelist
  """

    for node in PreOrderIter(tree):
        node.license_normalized = normalize_license_expression(node.license)

    licenses_not_found = set()
    for node in PreOrderIter(tree):
        node.license_problem = (
            not is_license_ok(node.license_normalized, whitelist)
            and node.name not in ignored_packages
        )
        if node.license_problem and node.license:
            licenses_not_found.add(str(node.license_normalized))

    for node in list(LevelOrderIter(tree))[::-1]:
        node.subtree_problem = (
            False
            if node.is_leaf
            else any(
                map(lambda x: x.subtree_problem or x.license_problem, node.children)
            )
        )

    return tree, licenses_not_found
Ejemplo n.º 3
0
def main():
    args = parse_args()

    with open(args.file1, "r") as f:
        data = json.load(f)
        root1 = importer.import_(data['symbols'])

    with open(args.file2, "r") as f:
        data = json.load(f)
        root2 = importer.import_(data['symbols'])

    for node in PreOrderIter(root1):
        # pylint: disable=undefined-loop-variable
        n = find(root2, lambda node2: node2.identifier == node.identifier)
        if n:
            if n.size != node.size:
                diff = n.size - node.size
                if diff == 0:
                    continue
                if not n.children or not n.parent:
                    if diff < 0:
                        print(f"{n.identifier} -> {Fore.GREEN}{diff}{Fore.RESET}")
                    else:
                        print(f"{n.identifier} -> {Fore.RED}+{diff}{Fore.RESET}")

        else:
            if not node.children:
                print(f"{node.identifier} ({Fore.GREEN}-{node.size}{Fore.RESET}) disappeared.")

    for node in PreOrderIter(root2):
        n = find(root1, lambda node2: node2.identifier == node.identifier)
        if not n:
            if not node.children and node.size != 0:
                print(f"{node.identifier} ({Fore.RED}+{node.size}{Fore.RESET}) is new.")
Ejemplo n.º 4
0
def ascending_connected_random_orderings(g, root,
                                         n):  # TODO: Increase performance
    '''
    Pseudo randomly reorders a list of clusters based on their connectivity in g.
    Starts with a random DFS until reaching the lowest level. Then adds clusters based on their connectivity.
    '''

    random.seed(config.SEED)

    node_to_leaf = OrderedDict()  # map from node to leaf
    for leaf in root.leaves:
        node_to_leaf[leaf.node_id] = leaf

    # the count represents how many edges reach this cluster.
    # will be updated throughout the tree
    ret = list()

    for i in range(n):
        for node in PreOrderIter(root):
            node.count = 0

        current_leaf = node_to_leaf[peripheral_node(
            g, nk.graphtools.randomNode(g))]

        increment_edge_count(current_leaf)

        ret.append([
            node.node_id for node in rec_reorder_clusters_with_common_parent(
                g, root, node_to_leaf)
        ])

    for node in PreOrderIter(root):
        del node.count

    return ret
Ejemplo n.º 5
0
def visualize_tree_dot(tree, mode, node_to_class, node_to_classes, filename):

    tree = deepcopy(tree)
    if mode == 'ids':
        pass
    elif isinstance(mode, dict):
        for node in PreOrderIter(tree):
            if not node.is_leaf:
                node.name = mode.get(node_to_class[node.name], 'root') + '_' + \
                    str(node.name)
            else:
                node.name = mode.get(node_to_classes[node.name][0], 'root') + '_' + \
                    str(node.name)

    elif mode == 'classes':
        for node in PreOrderIter(tree):
            node.name = ''.join([
                str(node_to_class.get(node.name, 'root')),
                ':',
                str(node_to_classes[node.name]).replace(' ', ''),
                '\n',
            ])
    else:
        raise ValueError(f'No mode named {mode}')

    DotExporter(tree).to_picture(filename)
    return filename
Ejemplo n.º 6
0
 def cuttingVarNodes(self, tree=Node):
     nodeName = ["VAR", "FACTOR", "NOT_FACTOR", "UNARY_EXPRESSION"]
     for name in nodeName:
         for node in PreOrderIter(tree):
             if node.name == name and len(node.children) == 1:
                 n = node.children[0]
                 self.cutting(n, node)
                 if self.treeHasElement(name):
                     self.cuttingVarNodes(self.syntax_tree)
                 else:
                     break
     nodeName = ["VAR_LIST", "INDEX_STMT", "VAR_INDEX_STMT"]
     for node in PreOrderIter(tree):
         if node.name in nodeName:
             for n in node.children:
                 parent = node.parent
                 n.parent = parent
             node.parent = None
             if self.treeHasElement(node.name):
                 self.cuttingVarNodes(self.syntax_tree)
             else:
                 break
     nodeName = ["OPEN_BRACKET", "CLOSE_BRACKET", "NOT"]
     for node in PreOrderIter(tree):
         if node.name in nodeName:
             node.parent = None
         elif (node.name == "MINUS"
               and (node.parent.name == "NEGATIVE_VAR"
                    or node.parent.name == "NEGATIVE_NUMBER")):
             node.parent = None
Ejemplo n.º 7
0
    def cuttingCallFunctionNodes(self, tree=Node):
        nodeName = ["ARGUMENT_STATEMENT_STMT", "CALL_FUNCTION_STMT"]
        for name in nodeName:
            for node in PreOrderIter(tree):
                if node.name == name and len(node.children) == 1:
                    n = node.children[0]
                    self.cutting(n, node)
                    if self.treeHasElement(name):
                        self.cuttingCallFunctionNodes(self.syntax_tree)
                    else:
                        break

        for node in PreOrderIter(tree):
            if node.name == "ARGUMENT_LIST_STMT":
                parent = node.parent
                for n in node.children:
                    n.parent = parent
                node.parent = None
                if self.treeHasElement("ARGUMENT_LIST_STMT"):
                    self.cuttingCallFunctionNodes(self.syntax_tree)
                else:
                    break
        for node in PreOrderIter(tree):
            if "CALL_FUNCTION" in node.name:
                node.name = "CALL_FUNCTION"
Ejemplo n.º 8
0
    def fix_indents(self, selected_node_A, selected_node_B):
        # if selected_node_A.name.rsplit(')')[1].rsplit('_id')[0] != 'expr_e':
        #     diff = selected_node_A.code.count('\t') - selected_node_B.code.count('\t')
        # else:
        #     diff = selected_node_A.code.split('else:\n')[1].count('\t') - selected_node_B.code.split('else:\n')[1].count('\t')
        diff = selected_node_A.indent - selected_node_B.indent
        n_tab = '\t'*diff
        for node in PreOrderIter(selected_node_A): #-\t
            if node.name.rsplit(')')[1].rsplit('_id')[0] == 'expr_e':
                node.indent-=diff
                node.code = ('else:\n').join(node.code.split(n_tab+'else:\n'+n_tab)) # divide in ['\n\t\t, \t\t\t] and then join with else:\n
            elif node.label=='expr':
                if node.code!='':# or node.name.rsplit(')')[1].rsplit('_id')[0] != 'expr_b':
                    node.code = node.code[:-diff]
                    node.indent-=diff
                else:
                    node.indent-=diff
                # elif node.name.rsplit(')')[1].rsplit('_id')[0] == 'expr_b':
                #     node.indent-=diff
                # elif node.code=='' :
                #     node.indent-=diff

        for node in PreOrderIter(selected_node_B): #+\t
            if node.name.rsplit(')')[1].rsplit('_id')[0] == 'expr_e':
                node.indent+=diff
                node.code=(n_tab+'else:\n'+n_tab).join(node.code.split('else:\n'))
            elif node.label=='expr':
                if node.code!='':# or node.name.rsplit(')')[1].rsplit('_id')[0] != 'expr_b':
                    node.code += n_tab
                    node.indent+=diff
                else:
                    node.indent+=diff
Ejemplo n.º 9
0
    def _cmp_local2old(self, local):
        """Compare the current local tree to the last seen one.

        """
        deleted_nodes = {"documents": [], "folders": []}

        oldtree = self._load_sync_state_local(local)
        curtree = localtree.LocalTree(local)
        curtree.rebuild_tree()
        if oldtree is not None:
            # Iterate over all nodes in the old tree first
            for oldnode in PreOrderIter(oldtree.tree):
                node = curtree.get_node_by_path(oldnode.relpath)
                if node is not None:
                    self._check_node(oldnode, node)
                    # print(f"Name: {node.name}: {node.sync_state}")
                else:
                    # print("NOT FOUND")
                    if oldnode.entry_type == "document":
                        deleted_nodes["documents"].append(oldnode.relpath)
                    else:
                        deleted_nodes["folders"].append(oldnode.relpath)
            # Iterate over all nodes in the new tree now to find new items
            for node in PreOrderIter(curtree.tree):
                if node.sync_state is None:
                    # Node not yet checked means it was not present in the old tree.
                    node.sync_state = "new"
                    # print(f"Name: {node.name}: {node.sync_state}")
        else:
            print(
                "WARNING: No old remote state found. Maybe this is an initial sync?"
            )
        print(deleted_nodes)
        return deleted_nodes, curtree
Ejemplo n.º 10
0
def parse_file(json_file):

    with open(json_file, "r") as fp:
        contents = json.load(fp)
        root = importer.import_(contents['symbols'])

    zr = find(root, lambda node: node.name == 'ZEPHYR_BASE')
    ws = find(root, lambda node: node.name == 'WORKSPACE')

    data = {}
    if zr and ws:
        trees = [zr, ws]
    else:
        trees = [root]

    for node in PreOrderIter(root, maxlevel=2):
        if node.name not in ['WORKSPACE', 'ZEPHYR_BASE']:
            if node.name in ['Root', 'Symbols']:
                data['all'] = node.size
            else:
                data[node.name] = node.size

    for t in trees:
        root = t.name
        for node in PreOrderIter(t, maxlevel=2):
            if node.name == root:
                continue
            comp = node.name
            if comp in ['Root', 'Symbols']:
                data['all'] = node.size
            else:
                data[comp] = node.size

    return data
Ejemplo n.º 11
0
def cutExpressionElements(tree):
    for node in PreOrderIter(tree):
        if name(node) == 'expressao' and len(node.children) > 0 and name(
                node.children[0]) == 'expressao_logica':
            for n in PreOrderIter(node):
                if name(n) == 'expressao_aditiva':
                    n.parent = node
                    node.children[0].parent = None
Ejemplo n.º 12
0
    def test_expand(self):
        # expand one node
        node = self.tree.root.children[3].children[4]
        n_nodes_before_expand = len(list(PreOrderIter(self.tree.root)))
        self.tree.expand(node)
        n_nodes_after_expand = len(list(PreOrderIter(self.tree.root)))

        self.assertEqual(n_nodes_before_expand+1, n_nodes_after_expand)
Ejemplo n.º 13
0
    def _dump_hdf5(self, path, mode='a', state=True, **kwargs):  #pylint: disable=too-many-branches
        """Save data into HDF5 file.

        Parameters
        ----------
        path : str
            Path to output file.
        mode : str
            Mode to open file.
            'w': write, a new file is created (an existing file with
            the same name would be deleted).
            'a': append, an existing file is opened for reading and writing,
            and if the file does not exist it is created.
            Default to 'a'.
        state : bool
            Dump compoments's state.

        Returns
        -------
        comp : Wells
            Wells unchanged.
        """
        _ = kwargs
        with h5py.File(path, mode) as f:
            wells = f[self.class_name] if self.class_name in f else f.create_group(self.class_name)
            if state:
                for k, v in self.state.as_dict().items():
                    wells.attrs[k] = v
            for node in PreOrderIter(self.root):
                if node.is_root:
                    continue
                node_path = node.fullname
                if node.name == 'data':
                    raise ValueError("Name 'data' is not allowed for nodes.")
                grp = wells[node_path] if node_path in wells else wells.create_group(node_path)
                grp.attrs['is_group'] = node.is_group
                if 'data' not in grp:
                    grp_data = wells.create_group(node_path + '/data')
                else:
                    grp_data = grp['data']
                for att, data in node.items():
                    if isinstance(data, pd.DataFrame):
                        continue
                    if att in grp_data:
                        del grp_data[att]
                    grp_data.create_dataset(att, data=data)

        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            for node in PreOrderIter(self.root):
                if node.is_root:
                    continue
                for att, data in node.items():
                    if isinstance(data, pd.DataFrame):
                        data.to_hdf(path, key='/'.join([self.class_name, node.fullname,
                                                        'data', att]), mode='a')
        return self
Ejemplo n.º 14
0
def equal_tree_structure(built_tree, expected_tree):
    print("testing if equal trees")
    print(RenderTree(built_tree))
    print(RenderTree(expected_tree))

    comparable_built_tree = list(map(get_comparable_node_info, PreOrderIter(built_tree)))
    comparable_expected_tree = list(map(get_comparable_node_info, PreOrderIter(expected_tree)))

    return comparable_built_tree == comparable_expected_tree
Ejemplo n.º 15
0
    def _dump_ascii(self, path, attr, mode='w', **kwargs):
        """Save data into text file.

        Parameters
        ----------
        path : str
            Path to output file.
        attr : str
            Attribute to dump into file.
        mode : str
            Mode to open file.
            'w': write, a new file is created (an existing file with
            the same name would be deleted).
            'a': append, an existing file is opened for reading and writing,
            and if the file does not exist it is created.
            Default to 'w'.

        Returns
        -------
        comp : Wells
            Wells unchanged.
        """
        with open(path, mode) as f:
            if attr.upper() == 'WELLTRACK':
                for node in self:
                    if 'WELLTRACK' in node and 'COMPDAT' not in node:
                        f.write('WELLTRACK\t{}\n'.format(node.name))
                        for line in node.welltrack:
                            f.write(' '.join(line.astype(str)) + '\n')
            elif attr.upper() == 'PERF':
                write_perf(f, self, DEFAULTS)
            elif attr.upper() == 'GROUP':
                for node in PreOrderIter(self.root):
                    if node.is_root:
                        continue
                    if node.is_group and not node.is_leaf and not node.children[0].is_group:
                        f.write(' '.join(['GROUP', node.name] +
                                         [child.name for child in node.children]) + '\n')
                f.write('/\n')
            elif attr.upper() == 'GRUPTREE':
                f.write('GRUPTREE\n')
                for node in PreOrderIter(self.root):
                    if node.is_root:
                        continue
                    if node.is_group and node.parent.is_group:
                        p_name = '1*' if node.parent.is_root else node.parent.name
                        f.write(' '.join([node.name, p_name, '/\n']))
                f.write('/\n')
            elif attr.upper() == 'EVENTS':
                write_events(f, self, VALUE_CONTROL)
            elif attr.upper() == 'SCHEDULE':
                write_schedule(f, self, **kwargs)
            elif attr.upper() == 'WELSPECS':
                write_welspecs(f, self)
            else:
                raise NotImplementedError("Dump for {} is not implemented.".format(attr.upper()))
Ejemplo n.º 16
0
def getNamesChildren(item):  # used for ~ (something)
    name1 = ''.join(
        reversed([
            node.name
            for node in PreOrderIter(item.tree.children[0].children[1])
        ]))
    name2 = ''.join(
        reversed([
            node.name
            for node in PreOrderIter(item.tree.children[0].children[0])
        ]))
    return name1, name2
Ejemplo n.º 17
0
    def test_backpropagate1(self):
        # select a node from which backpropagation start
        node_name = '0_3_4_1'
        node = findall(self.tree.root, filter_=lambda n: n.name == node_name)[0]
        total_plays_before = sum([n.n_plays for n in PreOrderIter(self.tree.root)])

        # perform backpropagation
        self.tree.backpropagate(node, n_plays=100, n_wins=10, n_ties=0)
        total_plays_after = sum([n.n_plays for n in PreOrderIter(self.tree.root)])
        total_wins_after = sum([n.n_wins for n in PreOrderIter(self.tree.root)])

        self.assertEquals(total_plays_after-total_plays_before, 4*100)
        self.assertGreater(total_wins_after, 1)
Ejemplo n.º 18
0
def color_origin_tree(new_swc_tree, swc_tree):
    new_swc_list = [node for node in PreOrderIter(new_swc_tree.root())]
    id_node_map = {}

    for node in PreOrderIter(swc_tree.root()):
        id_node_map[node.get_id()] = node

    for node in new_swc_list:
        if node._type == 3:
            o_node = id_node_map[node.get_id()]
            while o_node.get_id() != node.parent.get_id():
                o_node._type = 3
                o_node = o_node.parent
Ejemplo n.º 19
0
def findVar(tree):
    st = {}
    variaveis = []

    for node in PreOrderIter(tree):
        node_name = name(node)

        if node_name == 'declaracao_variaveis':
            for n in PreOrderIter(node):
                if name(n) == 'tipo':
                    st['tipo'] = name(n.children[0])

                    if 'declaracao_funcao' not in str(n.ancestors):
                        st['escopo'] = 'global'
                    else:
                        st['escopo'] = 'local'
                elif name(n) == 'lista_variaveis':
                    dados = {}
                    st['info'] = []

                    for e in PreOrderIter(n):
                        if len(n.children) >= 1:
                            if name(e) == 'var':
                                dados['lexema'] = name(e.children[0])   
                                for i in PreOrderIter(e):
                                    if name(i.parent) == 'fator' and i.children[0].is_leaf:
                                        linha = getLine(dados['lexema'])
                                        
                                        if name(i) != 'numero' or '.' in name(i.children[0]):
                                            showErrors(linha, 'err', dados['lexema']+'['+name(i.children[0])+']', 13)
                                            exit(0)

                                        dados['categoria'] = 'vetor'
                                        dados['dimensao'] = name(i.children[0])
                                            
                                    elif name(i.parent) == 'var':
                                        dados['categoria'] = 'variavel'
                                
                                st['info'].append(dados)
                                dados = {}
                        else:
                            dados['lexema'] = name(e)
                            dados['categoria'] = 'variavel'

                            st['info'] = dados
                            dados = {}

            variaveis.append(st)
            st = {}

    return variaveis
Ejemplo n.º 20
0
 def hasIndexError(self):
     hasError = False
     for node in PreOrderIter(self.syntax_tree):
         if node.name == "INDEX":
             for i in PreOrderIter(node):
                 if hasattr(i, 'data_type') and hasattr(i, 'line'):
                     if i.data_type == "flutuante":
                         print("===== ERROR =====\n",
                               "In line ",
                               i.line,
                               ", index cannot be flutuante",
                               sep="")
                         hasError = True
     return hasError
    def displayTree(self):
        tree = self.configDialog.dataTree
        samples = PreOrderIter(self.config, maxlevel=2)
        next(samples)  #skip root
        for sample in samples:
            s = QtWidgets.QTreeWidgetItem(tree)
            s.setText(0, sample.name)
            s.setFlags(s.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
            if sample.selected:
                s.setCheckState(0, Qt.Checked)

            s.setData(0, Qt.UserRole,
                      sample)  #Set the tree node data to QT Node
            params = PreOrderIter(sample, maxlevel=2)
            next(params)  #skip sample
            for param in params:
                p = QtWidgets.QTreeWidgetItem(s)
                p.setFlags(p.flags() | Qt.ItemIsTristate
                           | Qt.ItemIsUserCheckable)
                p.setText(0, param.name)

                if param.selected:
                    p.setCheckState(0, Qt.Checked)
                if param.hasComplex:
                    if param.complex:
                        p.setText(1, "Re/Im")
                    else:
                        p.setText(1, "Mag")

                    p.setData(1, Qt.UserRole,
                              param)  #Set the tree node data to QT Node

                p.setData(0, Qt.UserRole,
                          param)  #Set the tree node data to QT Node

                series = PreOrderIter(param, maxlevel=2)
                next(series)  #skip param
                for ser in series:
                    l = QtWidgets.QTreeWidgetItem(p)
                    l.setFlags(l.flags() | Qt.ItemIsUserCheckable)
                    l.setText(0, ser.name)
                    if ser.selected:
                        l.setCheckState(0, Qt.Checked)
                    l.setData(0, Qt.UserRole,
                              ser)  #Set the tree node data to QT Node

        tree.itemClicked.connect(self.updateConfig)
        tree.itemChanged.connect(self.updateConfig)

        tree.show()
Ejemplo n.º 22
0
def get_pathful_dict(heading_content_dict, tree_of_headings):
    key_list = [k for k in heading_content_dict.keys()]
    printable = set(string.printable)
    list_of_node_names = [node.name for node in PreOrderIter(tree_of_headings)]
    list_of_nodes = [node for node in PreOrderIter(tree_of_headings)]
    list_of_contents = []
    pathful_dict = {}
    for node in PreOrderIter(tree_of_headings):
        if node.name <> 'ROOT':
            list_of_contents.append(heading_content_dict[node.name])
    for val in range(0, len(list_of_contents)):
        pathful_dict[compute_ancestry(
            list_of_nodes[val + 1])] = list_of_contents[val]
    return pathful_dict
Ejemplo n.º 23
0
 def test_save_load(self):
     self._create_and_split_space()
     self.space.save(self.TEMP_FILENAME)
     loaded_space = ParameterSpace.from_file(self.TEMP_FILENAME)
     self.assertEqual(self.space.__class__, loaded_space.__class__)
     # compare attributes as name, score, label, etc. for all nodes
     self.assertTrue(
         all(
             all(
                 getattr(orig_node, attr) == getattr(loaded_node, attr)
                 for attr in self.space.COMPARE_ATTRS)
             for orig_node, loaded_node in zip(PreOrderIter(self.space),
                                               PreOrderIter(loaded_space))))
     os.remove(self.TEMP_FILENAME + PKL_EXT)
Ejemplo n.º 24
0
    def cuttingLeafs(self, tree=Node):
        nodeName = [
            "RETURN", "OPEN_PARENTHESES", "CLOSE_PARENTHESES", "TYPE", "COMMA",
            "TWO_DOTS", "END", "WRITE", "READ", "UNTIL", "FOR"
        ]
        for node in PreOrderIter(tree):
            if node.name in nodeName:
                node.parent = None

        for node in PreOrderIter(tree):
            if "WRITE" in node.name:
                node.name = "WRITE"
            elif "READ" in node.name:
                node.name = "READ"
Ejemplo n.º 25
0
 def cuttingRepeatNodes(self, tree=Node):
     nodeName = ["REPEAT_STMT", "SIMPLE_STATEMENT"]
     for name in nodeName:
         for node in PreOrderIter(self.syntax_tree):
             if node.name == name and len(node.children) == 1:
                 n = node.children[0]
                 self.cutting(n, node)
                 if self.treeHasElement(name):
                     self.cuttingRepeatNodes(self.syntax_tree)
                 else:
                     break
     for node in PreOrderIter(tree):
         if "REPEAT" in node.name:
             node.name = "REPEAT"
Ejemplo n.º 26
0
 def annotateExpressionTypes(self, exprNode=Node):
     for node in PreOrderIter(exprNode):
         if node.name == "CALL_FUNCTION_STMT":
             func_name = node.children[0].children[0].lexeme
             for symbol in self.SymbolTable:
                 if symbol[0] == "func_declare" and func_name == symbol[2]:
                     exprNode.data_type = symbol[1]
                     return
     for node in PreOrderIter(exprNode):
         if hasattr(node, 'data_type'):
             if node.data_type == "flutuante":
                 exprNode.data_type = "flutuante"
                 break
             elif node.data_type == "inteiro":
                 exprNode.data_type = "inteiro"
Ejemplo n.º 27
0
    def check(self):
        check_yarn()
        check_node()

        with open(self.package_json_path) as package_json_file:
            package_json = json.load(package_json_file)
            project_name = package_json.get("name", "project_name")

        if not self.silent:
            print(get_initiated_text(ProjectType.YARN, project_name, self.directory))

        with yaspin(text="Analysing dependencies ...") if not self.silent else nullcontext():
            package_map = parse_yarn_lock(get_yarn_lock_json(self.directory))
            flat_tree = get_flat_tree(
                get_yarn_list_json(self.directory).get("data", {}).get("trees", []),
                package_map,
            )
            dep_tree = get_dependency_tree(flat_tree, package_json, package_map)

            flat_dependencies = [(get_name(s), v) for s, v in package_map.items()]
            license_map = fetch_npm_licenses(flat_dependencies)

            for node in PreOrderIter(dep_tree):
                node.license = license_map.get(f"{node.name}@{node.version}", None)

        return dep_tree
Ejemplo n.º 28
0
def sync_part_tree_on_update(ele_model, seq_model, root_node):
    """Update node names to track element labels. """
    ele_dict = {e.label: e for e in ele_model.elements}
    for node in PreOrderIter(root_node):
        name = node.name
        if name[0] == 'i':
            idx = seq_model.ifcs.index(node.id)
            node.name = f'i{idx}'
        elif name[0] == 'g':
            gap, z_dir = node.id
            idx = seq_model.gaps.index(gap)
            z_dir = seq_model.z_dir[idx]
            node.id = (gap, z_dir)
            node.name = f'g{idx}'
        elif name[0] == 'p':
            p_name = node.parent.name
            e = ele_dict[p_name]
            idx = int(name[1:])-1 if len(name) > 1 else 0
            node.id = e.interface_list()[idx].profile
        elif name[:2] == 'tl':
            p_name = node.parent.name
            e = ele_dict[p_name]
            node.id = e.intrfc
            idx = seq_model.ifcs.index(node.id)
            node.name = f'tl{idx}'
        elif name[0] == 't':
            p_name = node.parent.name
            e = ele_dict[p_name]
            idx = int(name[1:])-1 if len(name) > 1 else 0
            node.id = e.gap_list()[idx]
        elif name == 'root':
            pass
        else:
            if hasattr(node.id, 'label'):
                node.name = node.id.label
Ejemplo n.º 29
0
def sync_part_tree_on_restore(ele_model, seq_model, root_node):
    ele_dict = {e.label: e for e in ele_model.elements}
    for node in PreOrderIter(root_node):
        name = node.name
        if name in ele_dict:
            node.id = ele_dict[name]
        elif name[0] == 'i':
            idx = int(name[1:])
            node.id = seq_model.ifcs[idx]
        elif name[0] == 'g':
            idx = int(name[1:])
            node.id = (seq_model.gaps[idx], seq_model.z_dir[idx])
        elif name[0] == 'p':
            p_name = node.parent.name
            e = ele_dict[p_name]
            try:
                idx = int(name[1:]) - 1
            except ValueError:
                idx = 0
            node.id = e.interface_list()[idx].profile
        elif name[:2] == 'tl':
            p_name = node.parent.name
            e = ele_dict[p_name]
            node.id = e.intrfc
        elif name[0] == 't':
            p_name = node.parent.name
            e = ele_dict[p_name]
            idx = int(name[1:])-1 if len(name) > 1 else 0
            node.id = e.gap_list()[idx]
        elif name[:1] == 'di':
            p_name = node.parent.name
            e = ele_dict[p_name]
            node.id = e.ref_ifc
Ejemplo n.º 30
0
    def check(self):
        project_name = get_project_name(get_project_pom_xml(self.directory))

        if not self.silent:
            print("===========")
            print(
                f"Initiated License.sh check for Maven project {project_name} located at {self.directory}"
            )
            print("===========")

        with (yaspin(
                text="Getting dependency tree... (First run might take a while)"
        ) if not self.silent else nullcontext()) as sp:
            xml_tree = get_dependency_tree_xml(self.directory, self.debug)

        with (yaspin(text="Analysing dependencies ...")
              if not self.silent else nullcontext()) as sp:
            dep_tree = parse_dependency_xml(xml_tree)
            license_map = parse_licenses_xml(
                get_license_xml_file(self.directory, self.debug))

        for node in PreOrderIter(dep_tree):
            node.license = license_map.get(f"{node.name}@{node.version}", "")

        return dep_tree, license_map