Imports *vpn_path* to qualifying VRF tables.

        Import RTs of VRF table is matched with RTs from *vpn4_path* and if we
        have any common RTs we import the path into VRF.
358490
def import_single_vpn_path_to_all_vrfs(self, vpn_path, path_rts=None):
        
        LOG.debug('Importing path %s to qualifying VRFs', vpn_path)

        # If this path has no RTs we are done.
        if not path_rts:
            LOG.info('Encountered a path with no RTs: %s', vpn_path)
            return

        # We match path RTs with all VRFs that are interested in them.
        interested_tables = set()

        # Get route family of VRF to when this VPN Path can be imported to
        if vpn_path.route_family == RF_IPv4_VPN:
            route_family = RF_IPv4_UC
        elif vpn_path.route_family == RF_IPv6_VPN:
            route_family = RF_IPv6_UC
        elif vpn_path.route_family == RF_L2_EVPN:
            route_family = RF_L2_EVPN
        elif vpn_path.route_family == RF_VPNv4_FLOWSPEC:
            route_family = RF_IPv4_FLOWSPEC
        elif vpn_path.route_family == RF_VPNv6_FLOWSPEC:
            route_family = RF_IPv6_FLOWSPEC
        elif vpn_path.route_family == RF_L2VPN_FLOWSPEC:
            route_family = RF_L2VPN_FLOWSPEC
        else:
            raise ValueError('Unsupported route family for VRF: %s' %
                             vpn_path.route_family)

        for rt in path_rts:
            rt_rf_id = rt + ':' + str(route_family)
            vrf_rt_tables = self._tables_for_rt.get(rt_rf_id)
            if vrf_rt_tables:
                interested_tables.update(vrf_rt_tables)

        if interested_tables:
            # We iterate over all VRF tables that are interested in the RT
            # of the given path and import this path into them.
            route_dist = vpn_path.nlri.route_dist
            for vrf_table in interested_tables:
                if (vpn_path.source is not None or
                        route_dist != vrf_table.vrf_conf.route_dist):
                    update_vrf_dest = vrf_table.import_vpn_path(vpn_path)
                    # Queue the destination for further processing.
                    if update_vrf_dest is not None:
                        self._signal_bus.\
                            dest_changed(update_vrf_dest)
        else:
            # If we do not have any VRF with import RT that match with path RT
            LOG.debug('No VRF table found that imports RTs: %s', path_rts)
1055978
private Collection<Import> doImport(String url, Import previous) {
		try {
			if (url.startsWith("/")) {
				// absolute imports are searched in /WEB-INF/scss
				return resolveImport(Paths.get("/WEB-INF/scss").resolve(url));
			}

			// find in import paths
			final List<Path> importPaths = new LinkedList<>();

			// (a) relative to the previous import file
			final String previousPath = previous.getAbsoluteUri().getPath();
			final Path previousParentPath = Paths.get(previousPath).getParent();
			importPaths.add(previousParentPath);

			// (b) within /WEB-INF/assets/foundation
			importPaths.add(Paths.get("/WEB-INF/assets/foundation"));

			// (c) within /WEB-INF/assets/motion-ui
			importPaths.add(Paths.get("/WEB-INF/assets/motion-ui"));

			for (Path importPath : importPaths) {
				Path target = importPath.resolve(url);

				Collection<Import> imports = resolveImport(target);
				if (null != imports) {
					return imports;
				}
			}

			// file not found
			throw new FileNotFoundException(url);
		} catch (URISyntaxException | IOException e) {
			throw new RuntimeException(e);
		}
	}
835457
def setup_client_server_paths(paths):
    ''''''

    global norm_file_to_client
    global norm_file_to_server
    global _last_client_server_paths_set
    global _next_source_reference

    _last_client_server_paths_set = paths[:]

    _source_reference_to_server_filename.clear()
    _client_filename_in_utf8_to_source_reference.clear()
    _next_source_reference = partial(next, itertools.count(1))

    # Work on the client and server slashes.
    python_sep = '\\' if IS_WINDOWS else '/'
    eclipse_sep = '\\' if _ide_os == 'WINDOWS' else '/'

    norm_filename_to_server_container = {}
    norm_filename_to_client_container = {}
    initial_paths = list(paths)
    paths_from_eclipse_to_python = initial_paths[:]

    # Apply normcase to the existing paths to follow the os preferences.

    for i, (path0, path1) in enumerate(paths_from_eclipse_to_python[:]):
        if IS_PY2:
            if isinstance(path0, unicode):  # noqa
                path0 = path0.encode(sys.getfilesystemencoding())
            if isinstance(path1, unicode):  # noqa
                path1 = path1.encode(sys.getfilesystemencoding())

        path0 = _fix_path(path0, eclipse_sep)
        path1 = _fix_path(path1, python_sep)
        initial_paths[i] = (path0, path1)

        paths_from_eclipse_to_python[i] = (_normcase_from_client(path0), normcase(path1))

    if not paths_from_eclipse_to_python:
        # no translation step needed (just inline the calls)
        norm_file_to_client = _original_file_to_client
        norm_file_to_server = _original_file_to_server
        return

    # only setup translation functions if absolutely needed!
    def _norm_file_to_server(filename, cache=norm_filename_to_server_container):
        # Eclipse will send the passed filename to be translated to the python process
        # So, this would be 'NormFileFromEclipseToPython'
        try:
            return cache[filename]
        except KeyError:
            if eclipse_sep != python_sep:
                # Make sure that the separators are what we expect from the IDE.
                filename = filename.replace(python_sep, eclipse_sep)

            # used to translate a path from the client to the debug server
            translated = filename
            translated_normalized = _normcase_from_client(filename)
            for eclipse_prefix, server_prefix in paths_from_eclipse_to_python:
                if translated_normalized.startswith(eclipse_prefix):
                    found_translation = True
                    if DEBUG_CLIENT_SERVER_TRANSLATION:
                        sys.stderr.write('pydev debugger: replacing to server: %s\n' % (filename,))
                    translated = server_prefix + filename[len(eclipse_prefix):]
                    if DEBUG_CLIENT_SERVER_TRANSLATION:
                        sys.stderr.write('pydev debugger: sent to server: %s\n' % (translated,))
                    break
            else:
                found_translation = False

            # Note that when going to the server, we do the replace first and only later do the norm file.
            if eclipse_sep != python_sep:
                translated = translated.replace(eclipse_sep, python_sep)

            if found_translation:
                translated = _NormFile(translated)
            else:
                if not os.path.exists(translated):
                    if not translated.startswith('<'):
                        # This is a configuration error, so, write it always so
                        # that the user can fix it.
                        error_once('pydev debugger: unable to find translation for: "%s" in [%s] (please revise your path mappings).\n' %
                            (filename, ', '.join(['"%s"' % (x[0],) for x in paths_from_eclipse_to_python])))
                else:
                    # It's possible that we had some round trip (say, we sent /usr/lib and received
                    # it back, so, having no translation is ok too).
                    translated = _NormFile(translated)

            cache[filename] = translated
            return translated

    def _norm_file_to_client(filename, cache=norm_filename_to_client_container):
        # The result of this method will be passed to eclipse
        # So, this would be 'NormFileFromPythonToEclipse'
        try:
            return cache[filename]
        except KeyError:
            # used to translate a path from the debug server to the client
            translated = _NormFile(filename)

            # After getting the real path, let's get it with the path with
            # the real case and then obtain a new normalized copy, just in case
            # the path is different now.
            translated_proper_case = get_path_with_real_case(translated)
            translated = _NormFile(translated_proper_case)

            path_mapping_applied = False

            if IS_WINDOWS:
                if translated.lower() != translated_proper_case.lower():
                    translated_proper_case = translated
                    if DEBUG_CLIENT_SERVER_TRANSLATION:
                        sys.stderr.write(
                            'pydev debugger: _NormFile changed path (from: %s to %s)\n' % (
                                translated_proper_case, translated))

            for i, (eclipse_prefix, python_prefix) in enumerate(paths_from_eclipse_to_python):
                if translated.startswith(python_prefix):
                    if DEBUG_CLIENT_SERVER_TRANSLATION:
                        sys.stderr.write('pydev debugger: replacing to client: %s\n' % (translated,))

                    # Note: use the non-normalized version.
                    eclipse_prefix = initial_paths[i][0]
                    translated = eclipse_prefix + translated_proper_case[len(python_prefix):]
                    if DEBUG_CLIENT_SERVER_TRANSLATION:
                        sys.stderr.write('pydev debugger: sent to client: %s\n' % (translated,))
                    path_mapping_applied = True
                    break
            else:
                if DEBUG_CLIENT_SERVER_TRANSLATION:
                    sys.stderr.write('pydev debugger: to client: unable to find matching prefix for: %s in %s\n' % \
                        (translated, [x[1] for x in paths_from_eclipse_to_python]))
                    translated = translated_proper_case

            if eclipse_sep != python_sep:
                translated = translated.replace(python_sep, eclipse_sep)

            translated = _path_to_expected_str(translated)

            # The resulting path is not in the python process, so, we cannot do a _NormFile here,
            # only at the beginning of this method.
            cache[filename] = translated

            if translated not in _client_filename_in_utf8_to_source_reference:
                if path_mapping_applied:
                    source_reference = 0
                else:
                    source_reference = _next_source_reference()
                _client_filename_in_utf8_to_source_reference[translated] = source_reference
                _source_reference_to_server_filename[source_reference] = filename

            return translated

    norm_file_to_server = _norm_file_to_server
    norm_file_to_client = _norm_file_to_client
565957
def _python_rpath(self):
        """"""
        # Windows virtualenv installation installs pip to the [Ss]cripts
        # folder. Here's a simple check to support:
        if sys.platform == 'win32':
            return os.path.join('Scripts', 'python.exe')
        return os.path.join('bin', 'python')
772637
def get_network_instances(self, name=""):
        """"""

        output = self._show_vrf()
        vrfs = {}
        all_vrf_interfaces = {}
        for vrf in output:
            if (
                vrf.get("route_distinguisher", "") == "<not set>"
                or vrf.get("route_distinguisher", "") == "None"
            ):
                vrf["route_distinguisher"] = ""
            else:
                vrf["route_distinguisher"] = py23_compat.text_type(
                    vrf["route_distinguisher"]
                )
            interfaces = {}
            for interface_raw in vrf.get("interfaces", []):
                interface = interface_raw.split(",")
                for line in interface:
                    if line.strip() != "":
                        interfaces[py23_compat.text_type(line.strip())] = {}
                        all_vrf_interfaces[py23_compat.text_type(line.strip())] = {}

            vrfs[py23_compat.text_type(vrf["name"])] = {
                "name": py23_compat.text_type(vrf["name"]),
                "type": "L3VRF",
                "state": {"route_distinguisher": vrf["route_distinguisher"]},
                "interfaces": {"interface": interfaces},
            }
        all_interfaces = self.get_interfaces_ip().keys()
        vrfs["default"] = {
            "name": "default",
            "type": "DEFAULT_INSTANCE",
            "state": {"route_distinguisher": ""},
            "interfaces": {
                "interface": {
                    k: {} for k in all_interfaces if k not in all_vrf_interfaces.keys()
                }
            },
        }

        if name:
            if name in vrfs:
                return {py23_compat.text_type(name): vrfs[name]}
            return {}
        else:
            return vrfs
999938
function getImportAbsolutePath(url, prev, includedFilesMap, includedPaths = []) {
  // Ensure that both @import 'file' and @import 'file.scss' is mapped correctly
  let extension = path.posix.extname(prev);
  if(path.posix.extname(url) !== extension) {
    url += extension;
  }

  const absolutePath = findImportedPath(url, prev, includedFilesMap, includedPaths);

  if(!absolutePath) {
    throw new Error(`Can not determine imported file for url '${url}' imported in ${prev}`);
  }

  return absolutePath;
}
162056
def universal_import(imports, imp_from=None, target=""):
    """"""
    importmap = []  # [((imp | old_imp, imp, version_check), imp_as), ...]
    for imps in imports:
        if len(imps) == 1:
            imp, imp_as = imps[0], imps[0]
        else:
            imp, imp_as = imps
        if imp_from is not None:
            imp = imp_from + "./" + imp  # marker for from ... import ...
        old_imp = None
        path = imp.split(".")
        for i in reversed(range(1, len(path) + 1)):
            base, exts = ".".join(path[:i]), path[i:]
            clean_base = base.replace("/", "")
            if clean_base in py3_to_py2_stdlib:
                old_imp, version_check = py3_to_py2_stdlib[clean_base]
                if exts:
                    old_imp += "."
                    if "/" in base and "/" not in old_imp:
                        old_imp += "/"  # marker for from ... import ...
                    old_imp += ".".join(exts)
                break
        if old_imp is None:
            paths = (imp,)
        elif not target:  # universal compatibility
            paths = (old_imp, imp, version_check)
        elif get_target_info_len2(target) >= version_check:  # if lowest is above, we can safely use new
            paths = (imp,)
        elif target.startswith("2"):  # "2" and "27" can safely use old
            paths = (old_imp,)
        elif get_target_info(target) < version_check:  # "3" should be compatible with all 3+
            paths = (old_imp, imp, version_check)
        else:  # "35" and above can safely use new
            paths = (imp,)
        importmap.append((paths, imp_as))

    stmts = []
    for paths, imp_as in importmap:
        if len(paths) == 1:
            more_stmts = single_import(paths[0], imp_as)
            stmts.extend(more_stmts)
        else:
            first, second, version_check = paths
            stmts.append("if _coconut_sys.version_info < " + str(version_check) + ":")
            first_stmts = single_import(first, imp_as)
            first_stmts[0] = openindent + first_stmts[0]
            first_stmts[-1] += closeindent
            stmts.extend(first_stmts)
            stmts.append("else:")
            second_stmts = single_import(second, imp_as)
            second_stmts[0] = openindent + second_stmts[0]
            second_stmts[-1] += closeindent
            stmts.extend(second_stmts)
    return "\n".join(stmts)
1229010
def send_velocity_world_setpoint(self, vx, vy, vz, yawrate):
        
        pk = CRTPPacket()
        pk.port = CRTPPort.COMMANDER_GENERIC
        pk.data = struct.pack('<Bffff', TYPE_VELOCITY_WORLD,
                              vx, vy, vz, yawrate)
        self._cf.send_packet(pk)
777146
def complete_vrf(arg):
    

    search_string = ''
    if arg is not None:
        search_string = '^%s' % arg

    res = VRF.search({
        'operator': 'regex_match',
        'val1': 'rt',
        'val2':  search_string
        }, { 'max_result': 100000 } )

    ret = []

    for v in res['result']:
        ret.append(v.rt)
    if re.match(search_string, 'none'):
        ret.append('none')

    return ret
748211
def OpenPathWithStub(path, stub):
   
   from six.moves import http_client
   if not hasattr(stub, 'scheme'):
      raise vmodl.fault.NotSupported()
   elif stub.scheme == http_client.HTTPConnection:
      protocol = 'http'
   elif stub.scheme == http_client.HTTPSConnection:
      protocol = 'https'
   else:
      raise vmodl.fault.NotSupported()
   hostPort = stub.host
   url = '%s://%s%s' % (protocol, hostPort, path)
   headers = {}
   if stub.cookie:
      headers["Cookie"] = stub.cookie
   return requests.get(url, headers=headers, verify=False)
476486
def import_by_path(dotted_path, error_prefix=''):
    
    try:
        module_path, class_name = dotted_path.rsplit('.', 1)
    except ValueError:
        raise ImproperlyConfigured("%s%s doesn't look like a module path" % (
            error_prefix, dotted_path))
    try:
        module = import_module(module_path)
    except ImportError as e:
        raise ImproperlyConfigured('%sError importing module %s: "%s"' % (
            error_prefix, module_path, e))
    try:
        attr = getattr(module, class_name)
    except AttributeError:
        raise ImproperlyConfigured(
            '%sModule "%s" does not define a "%s" attribute/class' % (
                error_prefix, module_path, class_name
            )
        )
    return attr
942406
def _get_bgp_route_attr(self, destination, vrf, next_hop, ip_version=4):
        

        CMD_SHIBNV = 'show ip bgp neighbors vrf {vrf} | include "is {neigh}"'

        search_re_dict = {
            "aspath": {
                "re": r"AS-Path: ([\d\(\)]([\d\(\) ])*)",
                "group": 1,
                "default": "",
            },
            "bgpnh": {
                "re": r"[^|\\n][ ]{4}(" + IP_ADDR_REGEX + r")",
                "group": 1,
                "default": "",
            },
            "bgpfrom": {
                "re": r"from (" + IP_ADDR_REGEX + r")",
                "group": 1,
                "default": "",
            },
            "bgpcomm": {
                "re": r"  Community: ([\w\d\-\: ]+)",
                "group": 1,
                "default": "",
            },
            "bgplp": {"re": r"localpref (\d+)", "group": 1, "default": ""},
            # external, internal, redist
            "bgpie": {"re": r"^: (\w+),", "group": 1, "default": ""},
            "vrfimp": {
                "re": r"Imported from [\S]+ \(VRF (\S+)\)",
                "group": 1,
                "default": "",
            },
        }

        bgp_attr = {}
        # get BGP AS number
        outbgp = self._send_command('show bgp process | include "BGP Protocol Tag"')
        matchbgpattr = RE_BGP_PROTO_TAG.match(outbgp)
        if not matchbgpattr:
            return bgp_attr
        bgpas = matchbgpattr.group(1)
        if ip_version == 4:
            bgpcmd = "show ip bgp vrf {vrf} {destination}".format(
                vrf=vrf, destination=destination
            )
            outbgp = self._send_command(bgpcmd)
            outbgpsec = outbgp.split("Path type")

            # this should not happen (zero BGP paths)...
            if len(outbgpsec) == 1:
                return bgp_attr

            # process all bgp paths
            for bgppath in outbgpsec[1:]:
                if "is best path" not in bgppath:
                    # only best path is added to protocol attributes
                    continue
                # find BGP attributes
                for key in search_re_dict:
                    matchre = re.search(search_re_dict[key]["re"], bgppath)
                    if matchre:
                        groupnr = int(search_re_dict[key]["group"])
                        search_re_dict[key]["result"] = matchre.group(groupnr)
                    else:
                        search_re_dict[key]["result"] = search_re_dict[key]["default"]
                bgpnh = search_re_dict["bgpnh"]["result"]

                # if route is not leaked next hops have to match
                if (
                    not (search_re_dict["bgpie"]["result"] in ["redist", "local"])
                ) and (bgpnh != next_hop):
                    # this is not the right route
                    continue
                # find remote AS nr. of this neighbor
                bgpcmd = CMD_SHIBNV.format(vrf=vrf, neigh=bgpnh)
                outbgpnei = self._send_command(bgpcmd)
                matchbgpras = RE_BGP_REMOTE_AS.search(outbgpnei)
                if matchbgpras:
                    bgpras = matchbgpras.group(1)
                else:
                    # next-hop is not known in this vrf, route leaked from
                    #  other vrf or from vpnv4 table?
                    # get remote AS nr. from as-path if it is ebgp neighbor
                    # if locally sourced remote AS if undefined
                    bgpie = search_re_dict["bgpie"]["result"]
                    if bgpie == "external":
                        bgpras = bgpie.split(" ")[0].replace("(", "")
                    elif bgpie == "internal":
                        bgpras = bgpas
                    else:  # redist, local
                        bgpras = ""
                # community
                bothcomm = []
                extcomm = []
                stdcomm = search_re_dict["bgpcomm"]["result"].split()
                commsplit = bgppath.split("Extcommunity:")
                if len(commsplit) == 2:
                    for line in commsplit[1].split("\n")[1:]:
                        #          RT:65004:22
                        matchcommun = RE_BGP_COMMUN.match(line)
                        if matchcommun:
                            extcomm.append(matchcommun.group(1))
                        else:
                            # we've reached end of the extended community section
                            break
                bothcomm = stdcomm + extcomm
                bgp_attr = {
                    "as_path": search_re_dict["aspath"]["result"].strip(),
                    "remote_address": search_re_dict["bgpfrom"]["result"],
                    "local_preference": int(search_re_dict["bgplp"]["result"]),
                    "communities": bothcomm,
                    "local_as": helpers.as_number(bgpas),
                }
                if bgpras:
                    bgp_attr["remote_as"] = helpers.as_number(bgpras)
                else:
                    bgp_attr["remote_as"] = 0  # 0? , locally sourced
        return bgp_attr
740484
def vpath(self, new_vpath):
        """"""
        _, line_number = self._find_vpath()
        new_vpath = self.write_pattern.format(new_vpath)
        self.writeline(new_vpath, line_number)
670107
def dir_import_table(self):
        
        import_header = list(self.optional_data_directories)[1]
        import_offset = self.resolve_rva(import_header.VirtualAddress)

        i = 0
        while True:
            offset = import_offset + i*Import_DirectoryTable.get_size()
            idt = Import_DirectoryTable(self.stream, offset, self)

            if idt.is_empty():
                break
            else:
                yield idt

            i += 1
704801
def on_remove_vrf_conf(self, evt):
        
        vrf_conf = evt.value
        # Detach VrfConf change listener.
        vrf_conf.remove_listener(VrfConf.VRF_CHG_EVT, self.on_chg_vrf_conf)

        self._table_manager.remove_vrf_by_vrf_conf(vrf_conf)

        # Update local RT NLRIs
        self._rt_manager.update_local_rt_nlris()

        self._signal_bus.vrf_removed(vrf_conf.route_dist)

        # Remove AttributeMaps under the removed vrf
        rd = vrf_conf.route_dist
        rf = vrf_conf.route_family
        peers = self._peer_manager.iterpeers
        for peer in peers:
            key = ':'.join([rd, rf])
            peer.attribute_maps.pop(key, None)
1263328
def clone_rtcpath_update_rt_as(path, new_rt_as):
    
    assert path and new_rt_as
    if not path or path.route_family != RF_RTC_UC:
        raise ValueError('Expected RT_NLRI path')
    old_nlri = path.nlri
    new_rt_nlri = RouteTargetMembershipNLRI(new_rt_as, old_nlri.route_target)
    return RtcPath(path.source, new_rt_nlri, path.source_version_num,
                   pattrs=path.pathattr_map, nexthop=path.nexthop,
                   is_withdraw=path.is_withdraw)
851068
def grow_pool(arg, opts, shell_opts):
    
    if not pool:
        print("No pool with name '%s' found." % arg, file=sys.stderr)
        sys.exit(1)

    if not 'add' in opts:
        print("Please supply a prefix to add to pool '%s'" % pool.name, file=sys.stderr)
        sys.exit(1)

    # Figure out VRF.
    # If pool already has a member prefix, implied_vrf will be set. Look for new
    # prefix to add in the same vrf as implied_vrf.
    # If pool has no members, then use get_vrf() to get vrf to search in for
    # prefix to add.
    if pool.vrf is not None:
        v = pool.vrf
    else:
        v = get_vrf(opts.get('vrf_rt'), abort=True)

    q = { 'prefix': opts['add'] }
    if v.rt != 'all':
        q['vrf_rt'] = v.rt

    res = Prefix.list(q)

    if len(res) == 0:
        print("No prefix found matching %s in %s." % (opts['add'], vrf_format(v)), file=sys.stderr)
        sys.exit(1)
    elif res[0].pool:
        if res[0].pool == pool:
            print("Prefix %s in %s is already assigned to that pool." % (opts['add'], vrf_format(v)), file=sys.stderr)
        else:
            print("Prefix %s in %s is already assigned to a different pool ('%s')." % (opts['add'], vrf_format(v), res[0].pool.name), file=sys.stderr)
        sys.exit(1)

    res[0].pool = pool
    res[0].save()
    print("Prefix %s in %s added to pool '%s'." % (res[0].prefix, vrf_format(v), pool.name))