当前位置: 首页>>代码示例>>Python>>正文


Python DiGraph.neighbors方法代码示例

本文整理汇总了Python中networkx.DiGraph.neighbors方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.neighbors方法的具体用法?Python DiGraph.neighbors怎么用?Python DiGraph.neighbors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在networkx.DiGraph的用法示例。


在下文中一共展示了DiGraph.neighbors方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: LSDB

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import neighbors [as 别名]
class LSDB(object):
    def __init__(self):
        self.private_address_network = ip_network(CFG.get(DEFAULTSECT,
                                                  'private_net'))
        try:
            with open(CFG.get(DEFAULTSECT, 'private_ips'), 'r') as f:
                self.private_address_binding = json.load(f)
                self.router_private_address = {}
                for subnets in self.private_address_binding.itervalues():
                    for rid, ip in subnets.iteritems():
                        try:
                            iplist = self.router_private_address[rid]
                        except KeyError:
                            iplist = self.router_private_address[rid] = []
                        iplist.append(ip)
        except Exception as e:
            log.error('Incorrect private IP addresses binding file')
            log.error(str(e))
            self.private_address_binding = {}
            self.router_private_address = {}
        self.last_line = ''
        self.transaction = None
        self.graph = DiGraph()
        self.routers = {}  # router-id : lsa
        self.networks = {}  # DR IP : lsa
        self.ext_networks = {}  # (router-id, dest) : lsa
        self.controllers = defaultdict(list)  # controller nr : ip_list
        self.listener = {}
        self.keep_running = True
        self.queue = Queue()
        self.processing_thread = Thread(target=self.process_lsa,
                                        name="lsa_processing_thread")
        self.processing_thread.start()

    def get_leader(self):
        return min(self.controllers.iterkeys())

    def stop(self):
        for l in self.listener.values():
            l.session.stop()
        self.keep_running = False
        self.queue.put('')

    def lsdb(self, lsa):
        if lsa.TYPE == RouterLSA.TYPE:
            return self.routers
        elif lsa.TYPE == NetworkLSA.TYPE:
            return self.networks
        elif lsa.TYPE == ASExtLSA.TYPE:
            return self.ext_networks

    def register_change_listener(self, listener):
        try:
            del self.listener[listener]
            log.info('Shapeshifter disconnected.')
        except KeyError:
            log.info('Shapeshifter connected.')
            l = ProxyCloner(ShapeshifterProxy, listener)
            self.listener[listener] = l
            l.boostrap_graph(graph=[(u, v, d.get('metric', -1))
                                    for u, v, d in self.graph.edges(data=True)])

    @staticmethod
    def extract_lsa_properties(lsa_part):
        d = {}
        for prop in lsa_part.split(SEP_INTER_FIELD):
            if not prop:
                continue
            key, val = prop.split(SEP_INTRA_FIELD)
            d[key] = val
        return d

    def commit_change(self, line):
        # Check that this is not a duplicate of a previous update ...
        if self.last_line == line:
            return
        self.queue.put(line)

    def forwarding_address_of(self, src, dst):
        """
        Return the forwarding address for a src, dst pair. If src is specified, return
        the private 'link-local' address of the src-dst link, otherwise return a 'public'
        IP belonging to dst
        :param src: the source node of the link towards the FA, possibly null
        :param dst: the node owning the forwarding address
        :return: forwarding address (str) or None if no compatible address was found
        """
        try:
            return self.graph[src][dst]['dst_address'] if src \
                else self.graph[dst][self.graph.neighbors(dst)[0]]['src_address']
        except KeyError:
            log.debug('%s-%s not found in graph', src, dst)
            return None

    def remove_lsa(self, lsa):
        lsdb = self.lsdb(lsa)
        try:
            del lsdb[lsa.key()]
        except KeyError:
            pass
#.........这里部分代码省略.........
开发者ID:jaepark,项目名称:FibbingNode,代码行数:103,代码来源:lsdb.py

示例2: __init__

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import neighbors [as 别名]
class Codebase:
    def __init__(self):
        self.counter = 0
        self._revisions = []
        with open(path.join(path.dirname(__file__), '..', 'App.java')) as java_file:
            parser = Parser()
            tree = parser.parse_file(java_file)
            initial_classes = tree.type_declarations
        self._inheritance_graph = DiGraph()
        self._method_call_graph = DiGraph()

        for c in initial_classes:
            self._inheritance_graph.add_node(c.name, {'class': c})
            for m in c.body:
                if isinstance(m, MethodDeclaration):
                    self._method_call_graph.add_node(m.name,
                                                  {'method': m,
                                                   'class_name': c.name,
                                                   'fitness': random()
                                                   })

    def get_class_name(self, method_name):
        return self._method_call_graph.node[method_name]['class_name']

    def size_of(self, method_name):
        return len(self._method_call_graph.node[method_name]['method'].body)

    def number_of_methods(self):
        return len(self._method_call_graph)

    def number_of_classes(self):
        return len(self._inheritance_graph)

    def has_method(self, method_name):
        return self._method_call_graph.has_node(method_name)

    def choose_random_method(self):
        """
        Choose a random method, weighted by its size
        :return: the method name
        """
        return sample([(method_name, len(data['method'].body) + 1)
                       for method_name, data in self._method_call_graph.nodes_iter(True)])

    def choose_random_class(self):
        """
        Choose a random class, weighted by its size
        :return: the class name
        """
        return sample([(class_name, len(data['class'].body) + 1)
                       for class_name, data in self._inheritance_graph.nodes_iter(data=True)])

    def least_fit_methods(self, n=1):
        """
        :return: the name of the method with smallest fitness value
        """
        return nsmallest(n, self._method_call_graph,
                         key=lambda method_name: self._method_call_graph.node[method_name]['fitness'])

    def choose_random_neighbor(self, method_name):
        neighbors = self._method_call_graph.neighbors(method_name)
        num_neighbors = len(neighbors)
        if num_neighbors > 0:
            return neighbors[floor(random() * num_neighbors)]
        else:
            return None

    def caller_names(self, method_name):
        """
        :param method_name:
        :return: caller method names iterator
        """
        return self._method_call_graph.predecessors_iter(method_name)

    def method_invocations(self, method_name):
        """
        Generator for MethodInvocation instances of method_name
        :param method_name:
        :return:
        """
        for caller_name in self._method_call_graph.predecessors_iter(method_name):
            caller = self._method_call_graph.node[caller_name]['method']
            for stmt in caller.body:
                if Codebase.is_invocation(stmt, method_name):
                    yield stmt.expression

    def create_method(self, class_name):
        """
        The created methods are static methods for now
        """
        klass = self._inheritance_graph.node[class_name]['class']
        method = MethodDeclaration(
            'method' + str(self.counter),
            body=[], modifiers=['static'])
        self.counter += 1
        klass.body.append(method)
        method_info = {'method': method, 'class_name': class_name, 'fitness': random()}
        self._method_call_graph.add_node(method.name, method_info)
        return 1, method.name

#.........这里部分代码省略.........
开发者ID:linzhp,项目名称:Codevo3,代码行数:103,代码来源:codebase.py

示例3: GroupGraph

# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import neighbors [as 别名]

#.........这里部分代码省略.........
            return sorted(self._disabled_groups.values(), key=lambda g: g.name)

    def get_groups(self, audited=False, directly_audited=False):
        # type: (bool, bool) -> List[Group]
        """Get the list of groups as Group instances sorted by group name.

        Arg(s):
            audited (bool): true to get only audited groups
            directly_audited (bool): true to get only directly audited
                groups (implies `audited` is true)
        """
        if directly_audited:
            audited = True
        with self.lock:
            groups = sorted(self._groups.values(), key=lambda g: g.name)
            if audited:

                def is_directly_audited(group):
                    # type: (Group) -> bool
                    for grant in self._group_grants[group.name]:
                        if self._permissions[grant.permission].audited:
                            return True
                    return False

                directly_audited_groups = list(filter(is_directly_audited, groups))
                if directly_audited:
                    return directly_audited_groups
                queue = [("Group", group.name) for group in directly_audited_groups]
                audited_group_nodes = set()  # type: Set[Node]
                while len(queue):
                    g = queue.pop()
                    if g not in audited_group_nodes:
                        audited_group_nodes.add(g)
                        for nhbr in self._graph.neighbors(g):  # Members of g.
                            if nhbr[0] == "Group":
                                queue.append(nhbr)
                groups = sorted(
                    [self._groups[group[1]] for group in audited_group_nodes], key=lambda g: g.name
                )
        return groups

    def get_group_details(self, groupname, show_permission=None, expose_aliases=True):
        # type: (str, Optional[str], bool) -> Dict[str, Any]
        """ Get users and permissions that belong to a group. Raise NoSuchGroup
        for missing groups. """

        with self.lock:
            data = {
                "group": {"name": groupname},
                "users": {},
                "groups": {},
                "subgroups": {},
                "permissions": [],
            }  # type: Dict[str, Any]
            if groupname in self._group_service_accounts:
                data["service_accounts"] = self._group_service_accounts[groupname]
            if groupname in self._groups and self._groups[groupname].email_address:
                data["group"]["contacts"] = {"email": self._groups[groupname].email_address}

            # This is calculated based on all the permissions that apply to this group. Since this
            # is a graph walk, we calculate it here when we're getting this data.
            group_audited = False

            group = ("Group", groupname)
            if not self._graph.has_node(group):
                raise NoSuchGroup("Group %s is either missing or disabled." % groupname)
开发者ID:dropbox,项目名称:grouper,代码行数:70,代码来源:graph.py


注:本文中的networkx.DiGraph.neighbors方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。