_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q19700
SummonerApiV4.by_account
train
def by_account(self, region, encrypted_account_id): """ Get a summoner by account ID. :param string region: The region to execute this request on :param string encrypted_account_id: The account ID. :returns: SummonerDTO: represents a summoner """ url, query = SummonerApiV4Urls.by_account( region=region, encrypted_account_id=encrypted_account_id ) return self._raw_request(self.by_account.__name__, region, url, query)
python
{ "resource": "" }
q19701
SummonerApiV4.by_name
train
def by_name(self, region, summoner_name): """ Get a summoner by summoner name :param string region: The region to execute this request on :param string summoner_name: Summoner Name :returns: SummonerDTO: represents a summoner """ url, query = SummonerApiV4Urls.by_name( region=region, summoner_name=summoner_name ) return self._raw_request(self.by_name.__name__, region, url, query)
python
{ "resource": "" }
q19702
SummonerApiV4.by_puuid
train
def by_puuid(self, region, encrypted_puuid): """ Get a summoner by PUUID. :param string region: The region to execute this request on :param string encrypted_puuid: PUUID :returns: SummonerDTO: represents a summoner """ url, query = SummonerApiV4Urls.by_puuid( region=region, encrypted_puuid=encrypted_puuid ) return self._raw_request(self.by_puuid.__name__, region, url, query)
python
{ "resource": "" }
q19703
SummonerApiV4.by_id
train
def by_id(self, region, encrypted_summoner_id): """ Get a summoner by summoner ID. :param string region: The region to execute this request on :param string encrypted_summoner_id: Summoner ID :returns: SummonerDTO: represents a summoner """ url, query = SummonerApiV4Urls.by_id( region=region, encrypted_summoner_id=encrypted_summoner_id ) return self._raw_request(self.by_id.__name__, region, url, query)
python
{ "resource": "" }
q19704
SpectatorApiV4.featured_games
train
def featured_games(self, region): """ Get list of featured games. :param string region: The region to execute this request on :returns: FeaturedGames """ url, query = SpectatorApiV4Urls.featured_games(region=region) return self._raw_request(self.featured_games.__name__, region, url, query)
python
{ "resource": "" }
q19705
ThirdPartyCodeApiV4.by_summoner
train
def by_summoner(self, region, encrypted_summoner_id): """ FOR KR SUMMONERS, A 404 WILL ALWAYS BE RETURNED. Valid codes must be no longer than 256 characters and only use valid characters: 0-9, a-z, A-Z, and - :param string region: the region to execute this request on :param string encrypted_summoner_id: Summoner ID :returns: string """ url, query = ThirdPartyCodeApiV4Urls.by_summoner( region=region, encrypted_summoner_id=encrypted_summoner_id ) return self._raw_request(self.by_summoner.__name__, region, url, query)
python
{ "resource": "" }
q19706
NamedEndpoint._raw_request
train
def _raw_request(self, method_name, region, url, query_params): """ Sends a request through the BaseApi instance provided, injecting the provided endpoint_name into the method call, so the caller doesn't have to. :param string method_name: The name of the calling method :param string region: The region to execute this request on :param string url: The full URL to the method being requested. :param dict query_params: Query parameters to be provided in the HTTP request """ return self._base_api.raw_request( self._endpoint_name, method_name, region, url, query_params )
python
{ "resource": "" }
q19707
LeagueApiV4.challenger_by_queue
train
def challenger_by_queue(self, region, queue): """ Get the challenger league for a given queue. :param string region: the region to execute this request on :param string queue: the queue to get the challenger players for :returns: LeagueListDTO """ url, query = LeagueApiV4Urls.challenger_by_queue(region=region, queue=queue) return self._raw_request(self.challenger_by_queue.__name__, region, url, query)
python
{ "resource": "" }
q19708
LeagueApiV4.masters_by_queue
train
def masters_by_queue(self, region, queue): """ Get the master league for a given queue. :param string region: the region to execute this request on :param string queue: the queue to get the master players for :returns: LeagueListDTO """ url, query = LeagueApiV4Urls.master_by_queue(region=region, queue=queue) return self._raw_request(self.masters_by_queue.__name__, region, url, query)
python
{ "resource": "" }
q19709
LeagueApiV4.by_id
train
def by_id(self, region, league_id): """ Get league with given ID, including inactive entries :param string region: the region to execute this request on :param string league_id: the league ID to query :returns: LeagueListDTO """ url, query = LeagueApiV4Urls.by_id(region=region, league_id=league_id) return self._raw_request(self.by_id.__name__, region, url, query)
python
{ "resource": "" }
q19710
LeagueApiV4.entries
train
def entries(self, region, queue, tier, division): """ Get all the league entries :param string region: the region to execute this request on :param string queue: the queue to query, i.e. RANKED_SOLO_5x5 :param string tier: the tier to query, i.e. DIAMOND :param string division: the division to query, i.e. III :returns: Set[LeagueEntryDTO] """ url, query = LeagueApiV4Urls.entries( region=region, queue=queue, tier=tier, division=division ) return self._raw_request(self.entries.__name__, region, url, query)
python
{ "resource": "" }
q19711
ChampionApiV3.rotations
train
def rotations(self, region): """ Returns champion rotations, including free-to-play and low-level free-to-play rotations. :returns: ChampionInfo """ url, query = ChampionApiV3Urls.rotations(region=region) return self._raw_request(self.rotations.__name__, region, url, query)
python
{ "resource": "" }
q19712
Response.get_body
train
def get_body(self): '''Get the response Body :returns Body: A Body object containing the response. ''' if self._body is None: resp = self._dispatcher._dispatch(self.request) self._body = self._create_body(resp) return self._body
python
{ "resource": "" }
q19713
Response.cancel
train
def cancel(self): '''Cancel any request.''' if self._body: self._body._cancel = True else: self._cancel = True
python
{ "resource": "" }
q19714
Body.last_modified
train
def last_modified(self): '''Read the last-modified header as a datetime, if present.''' lm = self.response.headers.get('last-modified', None) return datetime.strptime(lm, '%a, %d %b %Y %H:%M:%S GMT') if lm \ else None
python
{ "resource": "" }
q19715
Paged.iter
train
def iter(self, pages=None): '''Get an iterator of pages. :param int pages: optional limit to number of pages :return: iter of this and subsequent pages ''' i = self._pages() if pages is not None: i = itertools.islice(i, pages) return i
python
{ "resource": "" }
q19716
Paged.json_encode
train
def json_encode(self, out, limit=None, sort_keys=False, indent=None): '''Encode the results of this paged response as JSON writing to the provided file-like `out` object. This function will iteratively read as many pages as present, streaming the contents out as JSON. :param file-like out: an object with a `write` function :param int limit: optional maximum number of items to write :param bool sort_keys: if True, output keys sorted, default is False :param bool indent: if True, indent output, default is False ''' stream = self._json_stream(limit) enc = json.JSONEncoder(indent=indent, sort_keys=sort_keys) for chunk in enc.iterencode(stream): out.write(u'%s' % chunk)
python
{ "resource": "" }
q19717
Paged.items_iter
train
def items_iter(self, limit): '''Get an iterator of the 'items' in each page. Instead of a feature collection from each page, the iterator yields the features. :param int limit: The number of 'items' to limit to. :return: iter of items in page ''' pages = (page.get() for page in self._pages()) items = itertools.chain.from_iterable( (p[self.ITEM_KEY] for p in pages) ) if limit is not None: items = itertools.islice(items, limit) return items
python
{ "resource": "" }
q19718
create
train
def create(client, mosaic=False, **kw): '''Create a Downloader with the provided client. :param mosaic bool: If True, the Downloader will fetch mosaic quads. :returns: :py:Class:`planet.api.downloader.Downloader` ''' if mosaic: return _MosaicDownloader(client, **kw) else: return _Downloader(client, **kw)
python
{ "resource": "" }
q19719
quick_search
train
def quick_search(limit, pretty, sort, **kw): '''Execute a quick search.''' req = search_req_from_opts(**kw) cl = clientv1() page_size = min(limit, 250) echo_json_response(call_and_wrap( cl.quick_search, req, page_size=page_size, sort=sort ), pretty, limit)
python
{ "resource": "" }
q19720
create_search
train
def create_search(pretty, **kw): '''Create a saved search''' req = search_req_from_opts(**kw) cl = clientv1() echo_json_response(call_and_wrap(cl.create_search, req), pretty)
python
{ "resource": "" }
q19721
saved_search
train
def saved_search(search_id, sort, pretty, limit): '''Execute a saved search''' sid = read(search_id) cl = clientv1() page_size = min(limit, 250) echo_json_response(call_and_wrap( cl.saved_search, sid, page_size=page_size, sort=sort ), limit=limit, pretty=pretty)
python
{ "resource": "" }
q19722
download
train
def download(asset_type, dest, limit, sort, search_id, dry_run, activate_only, quiet, **kw): '''Activate and download''' cl = clientv1() page_size = min(limit or 250, 250) asset_type = list(chain.from_iterable(asset_type)) # even though we're using functionality from click.Path, this was needed # to detect inability to write on Windows in a read-only vagrant mount... # @todo check/report upstream if not activate_only and not check_writable(dest): raise click.ClickException( 'download destination "%s" is not writable' % dest) if search_id: if dry_run: raise click.ClickException( 'dry-run not supported with saved search') if any(kw[s] for s in kw): raise click.ClickException( 'search options not supported with saved search') search, search_arg = cl.saved_search, search_id else: # any requested asset-types should be used as permission filters kw['asset_type'] = [AssetTypePerm.to_permissions(asset_type)] req = search_req_from_opts(**kw) if dry_run: req['interval'] = 'year' stats = cl.stats(req).get() item_cnt = sum([b['count'] for b in stats['buckets']]) asset_cnt = item_cnt * len(asset_type) click.echo( 'would download approximately %d assets from %s items' % (asset_cnt, item_cnt) ) return else: search, search_arg = cl.quick_search, req dl = downloader.create(cl) output = downloader_output(dl, disable_ansi=quiet) # delay initial item search until downloader output initialized output.start() try: items = search(search_arg, page_size=page_size, sort=sort) except Exception as ex: output.cancel() click_exception(ex) func = dl.activate if activate_only else dl.download args = [items.items_iter(limit), asset_type] if not activate_only: args.append(dest) # invoke the function within an interrupt handler that will shut everything # down properly handle_interrupt(dl.shutdown, func, *args)
python
{ "resource": "" }
q19723
search_mosaics
train
def search_mosaics(name, bbox, rbox, limit, pretty): '''Get quad IDs and information for a mosaic''' bbox = bbox or rbox cl = clientv1() mosaic, = cl.get_mosaic_by_name(name).items_iter(1) response = call_and_wrap(cl.get_quads, mosaic, bbox) echo_json_response(response, pretty, limit)
python
{ "resource": "" }
q19724
mosaic_info
train
def mosaic_info(name, pretty): '''Get information for a specific mosaic''' cl = clientv1() echo_json_response(call_and_wrap(cl.get_mosaic_by_name, name), pretty)
python
{ "resource": "" }
q19725
quad_info
train
def quad_info(name, quad, pretty): '''Get information for a specific mosaic quad''' cl = clientv1() mosaic, = cl.get_mosaic_by_name(name).items_iter(1) echo_json_response(call_and_wrap(cl.get_quad_by_id, mosaic, quad), pretty)
python
{ "resource": "" }
q19726
quad_contributions
train
def quad_contributions(name, quad, pretty): '''Get contributing scenes for a mosaic quad''' cl = clientv1() mosaic, = cl.get_mosaic_by_name(name).items_iter(1) quad = cl.get_quad_by_id(mosaic, quad).get() response = call_and_wrap(cl.get_quad_contributions, quad) echo_json_response(response, pretty)
python
{ "resource": "" }
q19727
download_quads
train
def download_quads(name, bbox, rbox, quiet, dest, limit): '''Download quads from a mosaic''' bbox = bbox or rbox cl = clientv1() dl = downloader.create(cl, mosaic=True) output = downloader_output(dl, disable_ansi=quiet) output.start() try: mosaic, = cl.get_mosaic_by_name(name).items_iter(1) items = cl.get_quads(mosaic, bbox).items_iter(limit) except Exception as ex: output.cancel() click_exception(ex) # invoke the function within an interrupt handler that will shut everything # down properly handle_interrupt(dl.shutdown, dl.download, items, [], dest)
python
{ "resource": "" }
q19728
configure_logging
train
def configure_logging(verbosity): '''configure logging via verbosity level of between 0 and 2 corresponding to log levels warning, info and debug respectfully.''' log_level = max(logging.DEBUG, logging.WARNING - logging.DEBUG*verbosity) logging.basicConfig( stream=sys.stderr, level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) urllib3_logger = logging.getLogger( 'requests.packages.urllib3') urllib3_logger.setLevel(log_level) # if debug level set then its nice to see the headers of the request if log_level == logging.DEBUG: try: import http.client as http_client except ImportError: # Python 2 import httplib as http_client http_client.HTTPConnection.debuglevel = 1
python
{ "resource": "" }
q19729
cli
train
def cli(context, verbose, api_key, base_url, workers): '''Planet API Client''' configure_logging(verbose) client_params.clear() client_params['api_key'] = api_key client_params['workers'] = workers if base_url: client_params['base_url'] = base_url
python
{ "resource": "" }
q19730
help
train
def help(context, command): '''Get command help''' if command: cmd = cli.commands.get(command, None) if cmd: context.info_name = command click.echo(cmd.get_help(context)) else: raise click.ClickException('no command: %s' % command) else: click.echo(cli.get_help(context))
python
{ "resource": "" }
q19731
geometry_from_json
train
def geometry_from_json(obj): '''try to find a geometry in the provided JSON object''' obj_type = obj.get('type', None) if not obj_type: return None if obj_type == 'FeatureCollection': features = obj.get('features', []) if len(features): obj = obj['features'][0] obj_type = obj.get('type', None) else: return None if obj_type == 'Feature': geom = obj['geometry'] else: geom = obj # @todo we're just assuming it's a geometry at this point if 'coordinates' in geom: return geom
python
{ "resource": "" }
q19732
check_status
train
def check_status(response): '''check the status of the response and if needed raise an APIException''' status = response.status_code if status < 300: return exception = { 400: exceptions.BadQuery, 401: exceptions.InvalidAPIKey, 403: exceptions.NoPermission, 404: exceptions.MissingResource, 429: exceptions.TooManyRequests, 500: exceptions.ServerError }.get(status, None) # differentiate between over quota and rate-limiting if status == 429 and 'quota' in response.text.lower(): exception = exceptions.OverQuota if exception: raise exception(response.text) raise exceptions.APIException('%s: %s' % (status, response.text))
python
{ "resource": "" }
q19733
get_filename
train
def get_filename(response): """Derive a filename from the given response. >>> import requests >>> from planet.api import utils >>> response = requests.Response() >>> response.headers = { ... 'date': 'Thu, 14 Feb 2019 16:13:26 GMT', ... 'last-modified': 'Wed, 22 Nov 2017 17:22:31 GMT', ... 'accept-ranges': 'bytes', ... 'content-type': 'image/tiff', ... 'content-length': '57350256', ... 'content-disposition': 'attachment; filename="open_california.tif"' ... } >>> response.url = 'https://planet.com/path/to/example.tif?foo=f6f1' >>> print(utils.get_filename(response)) open_california.tif >>> del response >>> response = requests.Response() >>> response.headers = { ... 'date': 'Thu, 14 Feb 2019 16:13:26 GMT', ... 'last-modified': 'Wed, 22 Nov 2017 17:22:31 GMT', ... 'accept-ranges': 'bytes', ... 'content-type': 'image/tiff', ... 'content-length': '57350256' ... } >>> response.url = 'https://planet.com/path/to/example.tif?foo=f6f1' >>> print(utils.get_filename(response)) example.tif >>> del response >>> response = requests.Response() >>> response.headers = { ... 'date': 'Thu, 14 Feb 2019 16:13:26 GMT', ... 'last-modified': 'Wed, 22 Nov 2017 17:22:31 GMT', ... 'accept-ranges': 'bytes', ... 'content-type': 'image/tiff', ... 'content-length': '57350256' ... } >>> response.url = 'https://planet.com/path/to/oops/' >>> print(utils.get_filename(response)) #doctest:+SKIP planet-bFL6pwki.tif >>> :param response: An HTTP response. :type response: :py:class:`requests.Response` :returns: a filename (i.e. ``basename``) :rtype: str """ name = (get_filename_from_headers(response.headers) or get_filename_from_url(response.url) or get_random_filename(response.headers.get('content-type'))) return name
python
{ "resource": "" }
q19734
get_filename_from_headers
train
def get_filename_from_headers(headers): """Get a filename from the Content-Disposition header, if available. >>> from planet.api import utils >>> headers = { ... 'date': 'Thu, 14 Feb 2019 16:13:26 GMT', ... 'last-modified': 'Wed, 22 Nov 2017 17:22:31 GMT', ... 'accept-ranges': 'bytes', ... 'content-type': 'image/tiff', ... 'content-length': '57350256', ... 'content-disposition': 'attachment; filename="open_california.tif"' ... } >>> name = utils.get_filename_from_headers(headers) >>> print(name) open_california.tif >>> >>> headers.pop('content-disposition', None) 'attachment; filename="open_california.tif"' >>> name = utils.get_filename_from_headers(headers) >>> print(name) None >>> :param headers dict: a ``dict`` of response headers :returns: a filename (i.e. ``basename``) :rtype: str or None """ cd = headers.get('content-disposition', '') match = re.search('filename="?([^"]+)"?', cd) return match.group(1) if match else None
python
{ "resource": "" }
q19735
get_filename_from_url
train
def get_filename_from_url(url): """Get a filename from a URL. >>> from planet.api import utils >>> urls = [ ... 'https://planet.com/', ... 'https://planet.com/path/to/', ... 'https://planet.com/path/to/example.tif', ... 'https://planet.com/path/to/example.tif?foo=f6f1&bar=baz', ... 'https://planet.com/path/to/example.tif?foo=f6f1&bar=baz#quux' ... ] >>> for url in urls: ... print('{} -> {}'.format(url, utils.get_filename_from_url(url))) ... https://planet.com/ -> None https://planet.com/path/to/ -> None https://planet.com/path/to/example.tif -> example.tif https://planet.com/path/to/example.tif?foo=f6f1&bar=baz -> example.tif https://planet.com/path/to/example.tif?foo=f6f1&bar=baz#quux -> example.tif >>> :returns: a filename (i.e. ``basename``) :rtype: str or None """ path = urlparse(url).path name = path[path.rfind('/')+1:] return name or None
python
{ "resource": "" }
q19736
get_random_filename
train
def get_random_filename(content_type=None): """Get a pseudo-random, Planet-looking filename. >>> from planet.api import utils >>> print(utils.get_random_filename()) #doctest:+SKIP planet-61FPnh7K >>> print(utils.get_random_filename('image/tiff')) #doctest:+SKIP planet-V8ELYxy5.tif >>> :returns: a filename (i.e. ``basename``) :rtype: str """ extension = mimetypes.guess_extension(content_type or '') or '' characters = string.ascii_letters + '0123456789' letters = ''.join(random.sample(characters, 8)) name = 'planet-{}{}'.format(letters, extension) return name
python
{ "resource": "" }
q19737
write_to_file
train
def write_to_file(directory=None, callback=None, overwrite=True): '''Create a callback handler for asynchronous Body handling. If provided, the callback will be invoked as described in :py:meth:`planet.api.models.Body.write`. In addition, if the download is skipped because the destination exists, the callback will be invoked with ``callback(skip=body)``. The name of the file written to will be determined from the Body.name property. :param directory str: The optional directory to write to. :param callback func: An optional callback to receive notification of write progress. :param overwrite bool: Overwrite any existing files. Defaults to True. ''' def writer(body): file = os.path.join(directory or '.', body.name) if overwrite or not os.path.exists(file): body.write(file, callback) else: if callback: callback(skip=body) body.response.close() return writer
python
{ "resource": "" }
q19738
probably_wkt
train
def probably_wkt(text): '''Quick check to determine if the provided text looks like WKT''' valid = False valid_types = set([ 'POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION', ]) matched = re.match(r'(\w+)\s*\([^)]+\)', text.strip()) if matched: valid = matched.group(1).upper() in valid_types return valid
python
{ "resource": "" }
q19739
probably_geojson
train
def probably_geojson(input): '''A quick check to see if this input looks like GeoJSON. If not a dict JSON-like object, attempt to parse input as JSON. If the resulting object has a type property that looks like GeoJSON, return that object or None''' valid = False if not isinstance(input, dict): try: input = json.loads(input) except ValueError: return None typename = input.get('type', None) supported_types = set([ 'Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon', 'GeometryCollection', 'Feature', 'FeatureCollection' ]) valid = typename in supported_types return input if valid else None
python
{ "resource": "" }
q19740
ClientV1.quick_search
train
def quick_search(self, request, **kw): '''Execute a quick search with the specified request. :param request: see :ref:`api-search-request` :param **kw: See Options below :returns: :py:class:`planet.api.models.Items` :raises planet.api.exceptions.APIException: On API error. :Options: * page_size (int): Size of response pages * sort (string): Sorting order in the form `field (asc|desc)` ''' body = json.dumps(request) params = self._params(kw) return self.dispatcher.response(models.Request( self._url('data/v1/quick-search'), self.auth, params=params, body_type=models.Items, data=body, method='POST')).get_body()
python
{ "resource": "" }
q19741
ClientV1.saved_search
train
def saved_search(self, sid, **kw): '''Execute a saved search by search id. :param sid string: The id of the search :returns: :py:class:`planet.api.models.Items` :raises planet.api.exceptions.APIException: On API error. :Options: * page_size (int): Size of response pages * sort (string): Sorting order in the form `field (asc|desc)` ''' path = 'data/v1/searches/%s/results' % sid params = self._params(kw) return self._get(self._url(path), body_type=models.Items, params=params).get_body()
python
{ "resource": "" }
q19742
ClientV1.get_searches
train
def get_searches(self, quick=False, saved=True): '''Get searches listing. :param quick bool: Include quick searches (default False) :param quick saved: Include saved searches (default True) :returns: :py:class:`planet.api.models.Searches` :raises planet.api.exceptions.APIException: On API error. ''' params = {} if saved and not quick: params['search_type'] = 'saved' elif quick: params['search_type'] = 'quick' return self._get(self._url('data/v1/searches/'), body_type=models.Searches, params=params).get_body()
python
{ "resource": "" }
q19743
ClientV1.stats
train
def stats(self, request): '''Get stats for the provided request. :param request dict: A search request that also contains the 'interval' property. :returns: :py:class:`planet.api.models.JSON` :raises planet.api.exceptions.APIException: On API error. ''' # work-around for API bug request = _patch_stats_request(request) body = json.dumps(request) return self.dispatcher.response(models.Request( self._url('data/v1/stats'), self.auth, body_type=models.JSON, data=body, method='POST')).get_body()
python
{ "resource": "" }
q19744
ClientV1.activate
train
def activate(self, asset): '''Request activation of the specified asset representation. Asset representations are obtained from :py:meth:`get_assets`. :param request dict: An asset representation from the API. :returns: :py:class:`planet.api.models.Body` with no response content :raises planet.api.exceptions.APIException: On API error. ''' activate_url = asset['_links']['activate'] return self._get(activate_url, body_type=models.Body).get_body()
python
{ "resource": "" }
q19745
ClientV1.download
train
def download(self, asset, callback=None): '''Download the specified asset. If provided, the callback will be invoked asynchronously. Otherwise it is up to the caller to handle the response Body. :param asset dict: An asset representation from the API :param callback: An optional function to aysnchronsously handle the download. See :py:func:`planet.api.write_to_file` :returns: :py:Class:`planet.api.models.Response` containing a :py:Class:`planet.api.models.Body` of the asset. :raises planet.api.exceptions.APIException: On API error. ''' download_url = asset['location'] return self._get(download_url, models.Body, callback=callback)
python
{ "resource": "" }
q19746
ClientV1.get_item
train
def get_item(self, item_type, id): '''Get the an item response for the given item_type and id :param item_type str: A valid item-type :param id str: The id of the item :returns: :py:Class:`planet.api.models.JSON` :raises planet.api.exceptions.APIException: On API error. ''' url = 'data/v1/item-types/%s/items/%s' % (item_type, id) return self._get(url).get_body()
python
{ "resource": "" }
q19747
ClientV1.get_assets_by_id
train
def get_assets_by_id(self, item_type, id): '''Get an item's asset response for the given item_type and id :param item_type str: A valid item-type :param id str: The id of the item :returns: :py:Class:`planet.api.models.JSON` :raises planet.api.exceptions.APIException: On API error. ''' url = 'data/v1/item-types/%s/items/%s/assets' % (item_type, id) return self._get(url).get_body()
python
{ "resource": "" }
q19748
ClientV1.get_mosaics
train
def get_mosaics(self): '''Get information for all mosaics accessible by the current user. :returns: :py:Class:`planet.api.models.Mosaics` ''' url = self._url('basemaps/v1/mosaics') return self._get(url, models.Mosaics).get_body()
python
{ "resource": "" }
q19749
ClientV1.get_mosaic_by_name
train
def get_mosaic_by_name(self, name): '''Get the API representation of a mosaic by name. :param name str: The name of the mosaic :returns: :py:Class:`planet.api.models.Mosaics` :raises planet.api.exceptions.APIException: On API error. ''' params = {'name__is': name} url = self._url('basemaps/v1/mosaics') return self._get(url, models.Mosaics, params=params).get_body()
python
{ "resource": "" }
q19750
ClientV1.get_quads
train
def get_quads(self, mosaic, bbox=None): '''Search for quads from a mosaic that are inside the specified bounding box. Will yield all quads if no bounding box is specified. :param mosaic dict: A mosaic representation from the API :param bbox tuple: A lon_min, lat_min, lon_max, lat_max area to search :returns: :py:Class:`planet.api.models.MosaicQuads` :raises planet.api.exceptions.APIException: On API error. ''' if bbox is None: # Some bboxes can slightly exceed backend min/max latitude bounds xmin, ymin, xmax, ymax = mosaic['bbox'] bbox = (max(-180, xmin), max(-85, ymin), min(180, xmax), min(85, ymax)) url = mosaic['_links']['quads'] url = url.format(lx=bbox[0], ly=bbox[1], ux=bbox[2], uy=bbox[3]) return self._get(url, models.MosaicQuads).get_body()
python
{ "resource": "" }
q19751
ClientV1.get_quad_by_id
train
def get_quad_by_id(self, mosaic, quad_id): '''Get a quad response for a specific mosaic and quad. :param mosaic dict: A mosaic representation from the API :param quad_id str: A quad id (typically <xcoord>-<ycoord>) :returns: :py:Class:`planet.api.models.JSON` :raises planet.api.exceptions.APIException: On API error. ''' path = 'basemaps/v1/mosaics/{}/quads/{}'.format(mosaic['id'], quad_id) return self._get(self._url(path)).get_body()
python
{ "resource": "" }
q19752
ClientV1.download_quad
train
def download_quad(self, quad, callback=None): '''Download the specified mosaic quad. If provided, the callback will be invoked asynchronously. Otherwise it is up to the caller to handle the response Body. :param asset dict: A mosaic quad representation from the API :param callback: An optional function to aysnchronsously handle the download. See :py:func:`planet.api.write_to_file` :returns: :py:Class:`planet.api.models.Response` containing a :py:Class:`planet.api.models.Body` of the asset. :raises planet.api.exceptions.APIException: On API error. ''' download_url = quad['_links']['download'] return self._get(download_url, models.Body, callback=callback)
python
{ "resource": "" }
q19753
and_filter_from_opts
train
def and_filter_from_opts(opts): '''build an AND filter from the provided opts dict as passed to a command from the filter_options decorator. Assumes all dict values are lists of filter dict constructs.''' return filters.and_filter(*list(chain.from_iterable([ o for o in opts.values() if o] )))
python
{ "resource": "" }
q19754
read
train
def read(value, split=False): '''Get the value of an option interpreting as a file implicitly or explicitly and falling back to the value if not explicitly specified. If the value is '@name', then a file must exist with name and the returned value will be the contents of that file. If the value is '@-' or '-', then stdin will be read and returned as the value. Finally, if a file exists with the provided value, that file will be read. Otherwise, the value will be returned. ''' v = str(value) retval = value if v[0] == '@' or v == '-': fname = '-' if v == '-' else v[1:] try: with click.open_file(fname) as fp: if not fp.isatty(): retval = fp.read() else: retval = None # @todo better to leave as IOError and let caller handle it # to better report in context of call (e.g. the option/type) except IOError as ioe: # if explicit and problems, raise if v[0] == '@': raise click.ClickException(str(ioe)) elif path.exists(v) and path.isfile(v): with click.open_file(v) as fp: retval = fp.read() if retval and split and type(retval) != tuple: retval = _split(retval.strip()) return retval
python
{ "resource": "" }
q19755
build_search_request
train
def build_search_request(filter_like, item_types, name=None, interval=None): '''Build a data-api search request body for the specified item_types. If 'filter_like' is a request, item_types will be merged and, if name or interval is provided, will replace any existing values. :param dict filter_like: a filter or request with a filter :param sequence(str) item_types: item-types to specify in the request :param str name: optional name :param str interval: optional interval [year, month, week, day] ''' filter_spec = filter_like.get('filter', filter_like) all_items = list(set(filter_like.get('item_types', [])).union(item_types)) name = filter_like.get('name', name) interval = filter_like.get('interval', interval) req = {'item_types': all_items, 'filter': filter_spec} if name: req['name'] = name if interval: req['interval'] = interval return req
python
{ "resource": "" }
q19756
date_range
train
def date_range(field_name, **kwargs): '''Build a DateRangeFilter. Predicate arguments accept a value str that in ISO-8601 format or a value that has a `isoformat` callable that returns an ISO-8601 str. :raises: ValueError if predicate value does not parse >>> date_range('acquired', gt='2017') == \ {'config': {'gt': '2017-01-01T00:00:00Z'}, \ 'field_name': 'acquired', 'type': 'DateRangeFilter'} True ''' for k, v in kwargs.items(): dt = v if not hasattr(v, 'isoformat'): dt = strp_lenient(str(v)) if dt is None: raise ValueError("unable to use provided time: " + str(v)) kwargs[k] = dt.isoformat() + 'Z' return _filter('DateRangeFilter', config=kwargs, field_name=field_name)
python
{ "resource": "" }
q19757
Vrfs.get
train
def get(self, value): """Returns the VRF configuration as a resource dict. Args: value (string): The vrf name to retrieve from the running configuration. Returns: A Python dict object containing the VRF attributes as key/value pairs. """ config = self.get_block('vrf definition %s' % value) if not config: return None response = dict(vrf_name=value) response.update(self._parse_rd(config)) response.update(self._parse_description(config)) config = self.get_block('no ip routing vrf %s' % value) if config: response['ipv4_routing'] = False else: response['ipv4_routing'] = True config = self.get_block('no ipv6 unicast-routing vrf %s' % value) if config: response['ipv6_routing'] = False else: response['ipv6_routing'] = True return response
python
{ "resource": "" }
q19758
Vrfs._parse_rd
train
def _parse_rd(self, config): """ _parse_rd scans the provided configuration block and extracts the vrf rd. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration Returns: dict: resource dict attribute """ match = RD_RE.search(config) if match: value = match.group('value') else: value = match return dict(rd=value)
python
{ "resource": "" }
q19759
Vrfs._parse_description
train
def _parse_description(self, config): """ _parse_description scans the provided configuration block and extracts the vrf description value. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration Returns: dict: resource dict attribute """ value = DESCRIPTION_RE.search(config).group('value') return dict(description=value)
python
{ "resource": "" }
q19760
Vrfs.getall
train
def getall(self): """Returns a dict object of all VRFs in the running-config Returns: A dict object of VRF attributes """ vrfs_re = re.compile(r'(?<=^vrf definition\s)(\w+)', re.M) response = dict() for vrf in vrfs_re.findall(self.config): response[vrf] = self.get(vrf) return response
python
{ "resource": "" }
q19761
Vrfs.create
train
def create(self, vrf_name, rd=None): """ Creates a new VRF resource Note: A valid RD has the following format admin_ID:local_assignment. The admin_ID can be an AS number or globally assigned IPv4 address. The local_assignment can be an integer between 0-65,535 if the admin_ID is an IPv4 address and can be between 0-4,294,967,295 if the admin_ID is an AS number. If the admin_ID is an AS number the local_assignment could also be in the form of an IPv4 address. Args: vrf_name (str): The VRF name to create rd (str): The value to configure the vrf rd Returns: True if create was successful otherwise False """ commands = ['vrf definition %s' % vrf_name] if rd: commands.append('rd %s' % rd) return self.configure(commands)
python
{ "resource": "" }
q19762
Vrfs.configure_vrf
train
def configure_vrf(self, vrf_name, commands): """ Configures the specified VRF using commands Args: vrf_name (str): The VRF name to configure commands: The list of commands to configure Returns: True if the commands completed successfully """ commands = make_iterable(commands) commands.insert(0, 'vrf definition %s' % vrf_name) return self.configure(commands)
python
{ "resource": "" }
q19763
Vrfs.set_description
train
def set_description(self, vrf_name, description=None, default=False, disable=False): """ Configures the VRF description Args: vrf_name (str): The VRF name to configure description(str): The string to set the vrf description to default (bool): Configures the vrf description to its default value disable (bool): Negates the vrf description Returns: True if the operation was successful otherwise False """ cmds = self.command_builder('description', value=description, default=default, disable=disable) return self.configure_vrf(vrf_name, cmds)
python
{ "resource": "" }
q19764
Vrfs.set_ipv4_routing
train
def set_ipv4_routing(self, vrf_name, default=False, disable=False): """ Configures ipv4 routing for the vrf Args: vrf_name (str): The VRF name to configure default (bool): Configures ipv4 routing for the vrf value to default if this value is true disable (bool): Negates the ipv4 routing for the vrf if set to true Returns: True if the operation was successful otherwise False """ cmd = 'ip routing vrf %s' % vrf_name if default: cmd = 'default %s' % cmd elif disable: cmd = 'no %s' % cmd cmd = make_iterable(cmd) return self.configure(cmd)
python
{ "resource": "" }
q19765
Vrfs.set_interface
train
def set_interface(self, vrf_name, interface, default=False, disable=False): """ Adds a VRF to an interface Notes: Requires interface to be in routed mode. Must apply ip address after VRF has been applied. This feature can also be accessed through the interfaces api. Args: vrf_name (str): The VRF name to configure interface (str): The interface to add the VRF too default (bool): Set interface VRF forwarding to default disable (bool): Negate interface VRF forwarding Returns: True if the operation was successful otherwise False """ cmds = ['interface %s' % interface] cmds.append(self.command_builder('vrf forwarding', value=vrf_name, default=default, disable=disable)) return self.configure(cmds)
python
{ "resource": "" }
q19766
Vrrp.get
train
def get(self, name): """Get the vrrp configurations for a single node interface Args: name (string): The name of the interface for which vrrp configurations will be retrieved. Returns: A dictionary containing the vrrp configurations on the interface. Returns None if no vrrp configurations are defined or if the interface is not configured. """ # Validate the interface and vrid are specified interface = name if not interface: raise ValueError("Vrrp.get(): interface must contain a value.") # Get the config for the interface. Return None if the # interface is not defined config = self.get_block('interface %s' % interface) if config is None: return config # Find all occurrences of vrids in this interface and make # a set of the unique vrid numbers match = set(re.findall(r'^\s+(?:no |)vrrp (\d+)', config, re.M)) if not match: return None # Initialize the result dict result = dict() for vrid in match: subd = dict() # Parse the vrrp configuration for the vrid(s) in the list subd.update(self._parse_delay_reload(config, vrid)) subd.update(self._parse_description(config, vrid)) subd.update(self._parse_enable(config, vrid)) subd.update(self._parse_ip_version(config, vrid)) subd.update(self._parse_mac_addr_adv_interval(config, vrid)) subd.update(self._parse_preempt(config, vrid)) subd.update(self._parse_preempt_delay_min(config, vrid)) subd.update(self._parse_preempt_delay_reload(config, vrid)) subd.update(self._parse_primary_ip(config, vrid)) subd.update(self._parse_priority(config, vrid)) subd.update(self._parse_secondary_ip(config, vrid)) subd.update(self._parse_timers_advertise(config, vrid)) subd.update(self._parse_track(config, vrid)) subd.update(self._parse_bfd_ip(config, vrid)) result.update({int(vrid): subd}) # If result dict is empty, return None, otherwise return result return result if result else None
python
{ "resource": "" }
q19767
Vrrp.getall
train
def getall(self): """Get the vrrp configurations for all interfaces on a node Returns: A dictionary containing the vrrp configurations on the node, keyed by interface. """ vrrps = dict() # Find the available interfaces interfaces = re.findall(r'^interface\s(\S+)', self.config, re.M) # Get the vrrps defined for each interface for interface in interfaces: vrrp = self.get(interface) # Only add those interfaces that have vrrps defined if vrrp: vrrps.update({interface: vrrp}) return vrrps
python
{ "resource": "" }
q19768
Vrrp.create
train
def create(self, interface, vrid, **kwargs): """Creates a vrrp instance from an interface Note: This method will attempt to create a vrrp in the node's operational config. If the vrrp already exists on the interface, then this method will set the properties of the existing vrrp to those that have been passed in, if possible. Args: interface (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be created. kwargs (dict): A dictionary specifying the properties to be applied to the new vrrp instance. See library documentation for available keys and values. Returns: True if the vrrp could be created otherwise False (see Node) """ if 'enable' not in kwargs: kwargs['enable'] = False return self._vrrp_set(interface, vrid, **kwargs)
python
{ "resource": "" }
q19769
Vrrp.delete
train
def delete(self, interface, vrid): """Deletes a vrrp instance from an interface Note: This method will attempt to delete the vrrp from the node's operational config. If the vrrp does not exist on the interface then this method will not perform any changes but still return True Args: interface (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be deleted. Returns: True if the vrrp could be deleted otherwise False (see Node) """ vrrp_str = "no vrrp %d" % vrid return self.configure_interface(interface, vrrp_str)
python
{ "resource": "" }
q19770
Vrrp.default
train
def default(self, interface, vrid): """Defaults a vrrp instance from an interface Note: This method will attempt to default the vrrp on the node's operational config. Default results in the deletion of the specified vrrp . If the vrrp does not exist on the interface then this method will not perform any changes but still return True Args: interface (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be defaulted. Returns: True if the vrrp could be defaulted otherwise False (see Node) """ vrrp_str = "default vrrp %d" % vrid return self.configure_interface(interface, vrrp_str)
python
{ "resource": "" }
q19771
Vrrp.set_enable
train
def set_enable(self, name, vrid, value=False, run=True): """Set the enable property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (boolean): True to enable the vrrp, False to disable. run (boolean): True to execute the command, False to return a string with the formatted command. Returns: If run is True, returns True if the command executed successfully, error if failure If run is False, returns the formatted command string which can be passed to the node """ if value is False: cmd = "vrrp %d shutdown" % vrid elif value is True: cmd = "no vrrp %d shutdown" % vrid else: raise ValueError("vrrp property 'enable' must be " "True or False") # Run the command if requested if run: result = self.configure_interface(name, cmd) # And verify the command succeeded if result is False: return self.error return result # Otherwise return the formatted command return cmd
python
{ "resource": "" }
q19772
Vrrp.set_secondary_ips
train
def set_secondary_ips(self, name, vrid, secondary_ips, run=True): """Configure the secondary_ip property of the vrrp Notes: set_secondary_ips takes a list of secondary ip addresses which are to be set on the virtal router. An empty list will remove any existing secondary ip addresses from the vrrp. A list containing addresses will configure the virtual router with only the addresses specified in the list - any existing addresses not included in the list will be removed. Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. secondary_ips (list): A list of secondary ip addresses to be assigned to the virtual router. run (boolean): Set to True to execute the command, False to return a string with the formatted command. Returns: If run is True, returns True if the command executed successfully, error if failure. If run is False, returns the formatted command string which can be passed to the node """ cmds = [] # Get the current set of tracks defined for the vrrp curr_sec_ips = [] vrrps = self.get(name) if vrrps and vrid in vrrps: curr_sec_ips = vrrps[vrid]['secondary_ip'] # Validate the list of ip addresses for sec_ip in secondary_ips: if type(sec_ip) is not str or \ not re.match(r'^\d+\.\d+\.\d+\.\d+$', sec_ip): raise ValueError("vrrp property 'secondary_ip' must be a list " "of properly formatted ip address strings") intersection = list(set(curr_sec_ips) & set(secondary_ips)) # Delete the intersection from both lists to determine which # addresses need to be added or removed from the vrrp remove = list(set(curr_sec_ips) - set(intersection)) add = list(set(secondary_ips) - set(intersection)) # Build the commands to add and remove the secondary ip addresses for sec_ip in remove: cmds.append("no vrrp %d ip %s secondary" % (vrid, sec_ip)) for sec_ip in add: cmds.append("vrrp %d ip %s secondary" % (vrid, sec_ip)) cmds = sorted(cmds) # Run the command if requested if run: result = self.configure_interface(name, cmds) # And verify the command succeeded if result is False: return self.error return result # Otherwise return the formatted command return cmds
python
{ "resource": "" }
q19773
Vrrp.set_mac_addr_adv_interval
train
def set_mac_addr_adv_interval(self, name, vrid, value=None, disable=False, default=False, run=True): """Set the mac_addr_adv_interval property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (integer): mac-address advertisement-interval value to assign to the vrrp. disable (boolean): Unset mac-address advertisement-interval if True. default (boolean): Set mac-address advertisement-interval to default if True. run (boolean): Set to True to execute the command, False to return a string with the formatted command. Returns: If run is True, returns True if the command executed successfully, error if failure. If run is False, returns the formatted command string which can be passed to the node """ if not default and not disable: if not int(value) or int(value) < 1 or int(value) > 3600: raise ValueError("vrrp property 'mac_addr_adv_interval' must " "be in the range 1-3600") cmd = self.command_builder('vrrp %d mac-address advertisement-interval' % vrid, value=value, default=default, disable=disable) # Run the command if requested if run: result = self.configure_interface(name, cmd) # And verify the command succeeded if result is False: return self.error return result # Otherwise return the formatted command return cmd
python
{ "resource": "" }
q19774
Vrrp.set_bfd_ip
train
def set_bfd_ip(self, name, vrid, value=None, disable=False, default=False, run=True): """Set the bfd_ip property of the vrrp Args: name (string): The interface to configure. vrid (integer): The vrid number for the vrrp to be managed. value (string): The bfd ip address to be set. disable (boolean): Unset bfd ip if True. default (boolean): Set bfd ip to default if True. run (boolean): Set to True to execute the command, False to return a string with the formatted command. Returns: If run is True, returns True if the command executed successfully, error if failure. If run is False, returns the formatted command string which can be passed to the node """ if not default and not disable: if not re.match(r'^\d+\.\d+\.\d+\.\d+$', str(value)): raise ValueError("vrrp property 'bfd_ip' must be " "a properly formatted IP address") cmd = self.command_builder('vrrp %d bfd ip' % vrid, value=value, default=default, disable=disable) # Run the command if requested if run: result = self.configure_interface(name, cmd) # And verify the command succeeded if result is False: return self.error return result # Otherwise return the formatted command return cmd
python
{ "resource": "" }
q19775
Vrrp.vrconf_format
train
def vrconf_format(self, vrconfig): """Formats a vrrp configuration dictionary to match the information as presented from the get and getall methods. vrrp configuration dictionaries passed to the create method may contain data for setting properties which results in a default value on the node. In these instances, the data for setting or changing the property is replaced with the value that would be returned from the get and getall methods. Intended for validating updated vrrp configurations. """ fixed = dict(vrconfig) # primary_ip: default, no, None results in address of 0.0.0.0 if fixed['primary_ip'] in ('no', 'default', None): fixed['primary_ip'] = '0.0.0.0' # priority: default, no, None results in priority of 100 if fixed['priority'] in ('no', 'default', None): fixed['priority'] = 100 # description: default, no, None results in None if fixed['description'] in ('no', 'default', None): fixed['description'] = None # secondary_ip: list should be exactly what is required, # just sort it for easier comparison if 'secondary_ip' in fixed: fixed['secondary_ip'] = sorted(fixed['secondary_ip']) # ip_version: default, no, None results in value of 2 if fixed['ip_version'] in ('no', 'default', None): fixed['ip_version'] = 2 # timers_advertise: default, no, None results in value of 1 if fixed['timers_advertise'] in ('no', 'default', None): fixed['timers_advertise'] = 1 # mac_address_advertisement_interaval: # default, no, None results in value of 30 if fixed['mac_addr_adv_interval'] in \ ('no', 'default', None): fixed['mac_addr_adv_interval'] = 30 # preempt: default, no results in value of False if fixed['preempt'] in ('no', 'default'): fixed['preempt'] = False # preempt_delay_min: default, no, None results in value of 0 if fixed['preempt_delay_min'] in ('no', 'default', None): fixed['preempt_delay_min'] = 0 # preempt_delay_reload: default, no, None results in value of 0 if fixed['preempt_delay_reload'] in ('no', 'default', None): fixed['preempt_delay_reload'] = 0 # delay_reload: default, no, None results in value of 0 if fixed['delay_reload'] in ('no', 'default', None): fixed['delay_reload'] = 0 # track: list should be exactly what is required, # just sort it for easier comparison if 'track' in fixed: fixed['track'] = \ sorted(fixed['track'], key=lambda k: (k['name'], k['action'])) # bfd_ip: default, no, None results in '' if fixed['bfd_ip'] in ('no', 'default', None): fixed['bfd_ip'] = '' return fixed
python
{ "resource": "" }
q19776
prefixlen_to_mask
train
def prefixlen_to_mask(prefixlen): """Converts a prefix length to a dotted decimal subnet mask Args: prefixlen (str): The prefix length value to convert Returns: str: The subt mask as a dotted decimal string """ prefixlen = prefixlen or '32' addr = '0.0.0.0/%s' % prefixlen return str(netaddr.IPNetwork(addr).netmask)
python
{ "resource": "" }
q19777
Acls.getall
train
def getall(self): """Returns all ACLs in a dict object. Returns: A Python dictionary object containing all ACL configuration indexed by ACL name:: { "<ACL1 name>": {...}, "<ACL2 name>": {...} } """ acl_re = re.compile(r'^ip access-list (?:(standard) )?(.+)$', re.M) response = {'standard': {}, 'extended': {}} for acl_type, name in acl_re.findall(self.config): acl = self.get(name) if acl_type and acl_type == 'standard': response['standard'][name] = acl else: response['extended'][name] = acl return response
python
{ "resource": "" }
q19778
Mlag.get
train
def get(self): """Returns the Mlag configuration as a resource dict Returns: dict: A dict ojbect containing the Mlag resource attributes. """ resource = dict() resource.update(self._parse_config()) resource.update(self._parse_interfaces()) return resource
python
{ "resource": "" }
q19779
Mlag._parse_config
train
def _parse_config(self): """Parses the mlag global configuration Returns: dict: A dict object that is intended to be merged into the resource dict """ config = self.get_block('mlag configuration') cfg = dict() cfg.update(self._parse_domain_id(config)) cfg.update(self._parse_local_interface(config)) cfg.update(self._parse_peer_address(config)) cfg.update(self._parse_peer_link(config)) cfg.update(self._parse_shutdown(config)) return dict(config=cfg)
python
{ "resource": "" }
q19780
Mlag._parse_domain_id
train
def _parse_domain_id(self, config): """Scans the config block and parses the domain-id value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict """ match = re.search(r'domain-id (.+)$', config) value = match.group(1) if match else None return dict(domain_id=value)
python
{ "resource": "" }
q19781
Mlag._parse_local_interface
train
def _parse_local_interface(self, config): """Scans the config block and parses the local-interface value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict """ match = re.search(r'local-interface (\w+)', config) value = match.group(1) if match else None return dict(local_interface=value)
python
{ "resource": "" }
q19782
Mlag._parse_peer_address
train
def _parse_peer_address(self, config): """Scans the config block and parses the peer-address value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict """ match = re.search(r'peer-address ([^\s]+)', config) value = match.group(1) if match else None return dict(peer_address=value)
python
{ "resource": "" }
q19783
Mlag._parse_peer_link
train
def _parse_peer_link(self, config): """Scans the config block and parses the peer-link value Args: config (str): The config block to scan Returns: dict: A dict object that is intended to be merged into the resource dict """ match = re.search(r'peer-link (\S+)', config) value = match.group(1) if match else None return dict(peer_link=value)
python
{ "resource": "" }
q19784
Mlag._parse_interfaces
train
def _parse_interfaces(self): """Scans the global config and returns the configured interfaces Returns: dict: A dict object that is intended to be merged into the resource dict. """ interfaces = dict() names = re.findall(r'^interface (Po.+)$', self.config, re.M) for name in names: config = self.get_block('interface %s' % name) match = re.search(r'mlag (\d+)', config) if match: interfaces[name] = dict(mlag_id=match.group(1)) return dict(interfaces=interfaces)
python
{ "resource": "" }
q19785
Mlag.set_domain_id
train
def set_domain_id(self, value=None, default=False, disable=False): """Configures the mlag domain-id value Args: value (str): The value to configure the domain-id default (bool): Configures the domain-id using the default keyword disable (bool): Negates the domain-id using the no keyword Returns: bool: Returns True if the commands complete successfully """ return self._configure_mlag('domain-id', value, default, disable)
python
{ "resource": "" }
q19786
Mlag.set_local_interface
train
def set_local_interface(self, value=None, default=False, disable=False): """Configures the mlag local-interface value Args: value (str): The value to configure the local-interface default (bool): Configures the local-interface using the default keyword disable (bool): Negates the local-interface using the no keyword Returns: bool: Returns True if the commands complete successfully """ return self._configure_mlag('local-interface', value, default, disable)
python
{ "resource": "" }
q19787
Mlag.set_peer_address
train
def set_peer_address(self, value=None, default=False, disable=False): """Configures the mlag peer-address value Args: value (str): The value to configure the peer-address default (bool): Configures the peer-address using the default keyword disable (bool): Negates the peer-address using the no keyword Returns: bool: Returns True if the commands complete successfully """ return self._configure_mlag('peer-address', value, default, disable)
python
{ "resource": "" }
q19788
Mlag.set_peer_link
train
def set_peer_link(self, value=None, default=False, disable=False): """Configures the mlag peer-link value Args: value (str): The value to configure the peer-link default (bool): Configures the peer-link using the default keyword disable (bool): Negates the peer-link using the no keyword Returns: bool: Returns True if the commands complete successfully """ return self._configure_mlag('peer-link', value, default, disable)
python
{ "resource": "" }
q19789
Mlag.set_shutdown
train
def set_shutdown(self, default=False, disable=True): """Configures the mlag shutdown value Default setting for set_shutdown is disable=True, meaning 'no shutdown'. Setting both default and disable to False will effectively enable shutdown. Args: default (bool): Configures the shutdown using the default keyword disable (bool): Negates shutdown using the no keyword Returns: bool: Returns True if the commands complete successfully """ return self._configure_mlag('shutdown', True, default, disable)
python
{ "resource": "" }
q19790
Mlag.set_mlag_id
train
def set_mlag_id(self, name, value=None, default=False, disable=False): """Configures the interface mlag value for the specified interface Args: name (str): The interface to configure. Valid values for the name arg include Port-Channel* value (str): The mlag identifier to cofigure on the interface default (bool): Configures the interface mlag value using the default keyword disable (bool): Negates the interface mlag value using the no keyword Returns: bool: Returns True if the commands complete successfully """ cmd = self.command_builder('mlag', value=value, default=default, disable=disable) return self.configure_interface(name, cmd)
python
{ "resource": "" }
q19791
Bgp.get
train
def get(self): """Returns the bgp routing configuration as a dict object """ config = self.get_block('^router bgp .*') if not config: return None response = dict() response.update(self._parse_bgp_as(config)) response.update(self._parse_router_id(config)) response.update(self._parse_max_paths(config)) response.update(self._parse_shutdown(config)) response.update(self._parse_networks(config)) response['neighbors'] = self.neighbors.getall() return response
python
{ "resource": "" }
q19792
Ospf.get
train
def get(self, vrf=None): """Returns the OSPF routing configuration Args: vrf (str): VRF name to return OSPF routing config for Returns: dict: keys: router_id (int): OSPF router-id vrf (str): VRF of the OSPF process networks (dict): All networks that are advertised in OSPF ospf_process_id (int): OSPF proc id redistribution (dict): All protocols that are configured to be redistributed in OSPF shutdown (bool): Gives the current shutdown off the process """ match = '^router ospf .*' if vrf: match += ' vrf %s' % vrf config = self.get_block(match) if not config: return None response = dict() response.update(self._parse_router_id(config)) response.update(self._parse_vrf(config)) response.update(self._parse_networks(config)) response.update(self._parse_ospf_process_id(config)) response.update(self._parse_redistribution(config)) response.update(self._parse_shutdown(config)) return response
python
{ "resource": "" }
q19793
Ospf._parse_ospf_process_id
train
def _parse_ospf_process_id(self, config): """Parses config file for the OSPF proc ID Args: config(str): Running configuration Returns: dict: key: ospf_process_id (int) """ match = re.search(r'^router ospf (\d+)', config) return dict(ospf_process_id=int(match.group(1)))
python
{ "resource": "" }
q19794
Ospf._parse_vrf
train
def _parse_vrf(self, config): """Parses config file for the OSPF vrf name Args: config(str): Running configuration Returns: dict: key: ospf_vrf (str) """ match = re.search(r'^router ospf \d+ vrf (\w+)', config) if match: return dict(vrf=match.group(1)) return dict(vrf='default')
python
{ "resource": "" }
q19795
Ospf._parse_networks
train
def _parse_networks(self, config): """Parses config file for the networks advertised by the OSPF process Args: config(str): Running configuration Returns: list: dict: keys: network (str) netmask (str) area (str) """ networks = list() regexp = r'network (.+)/(\d+) area (\d+\.\d+\.\d+\.\d+)' matches = re.findall(regexp, config) for (network, netmask, area) in matches: networks.append(dict(network=network, netmask=netmask, area=area)) return dict(networks=networks)
python
{ "resource": "" }
q19796
Ospf._parse_redistribution
train
def _parse_redistribution(self, config): """Parses config file for the OSPF router ID Args: config (str): Running configuration Returns: list: dict: keys: protocol (str) route-map (optional) (str) """ redistributions = list() regexp = r'redistribute .*' matches = re.findall(regexp, config) for line in matches: ospf_redist = line.split() if len(ospf_redist) == 2: # simple redist: eg 'redistribute bgp' protocol = ospf_redist[1] redistributions.append(dict(protocol=protocol)) if len(ospf_redist) == 4: # complex redist eg 'redistribute bgp route-map NYSE-RP-MAP' protocol = ospf_redist[1] route_map_name = ospf_redist[3] redistributions.append(dict(protocol=protocol, route_map=route_map_name)) return dict(redistributions=redistributions)
python
{ "resource": "" }
q19797
Ospf.delete
train
def delete(self): """Removes the entire ospf process from the running configuration Args: None Returns: bool: True if the command completed succssfully """ config = self.get() if not config: return True command = 'no router ospf {}'.format(config['ospf_process_id']) return self.configure(command)
python
{ "resource": "" }
q19798
Ospf.create
train
def create(self, ospf_process_id, vrf=None): """Creates a OSPF process in the specified VRF or the default VRF. Args: ospf_process_id (str): The OSPF process Id value vrf (str): The VRF to apply this OSPF process to Returns: bool: True if the command completed successfully Exception: ValueError: If the ospf_process_id passed in less than 0 or greater than 65536 """ value = int(ospf_process_id) if not 0 < value < 65536: raise ValueError('ospf as must be between 1 and 65535') command = 'router ospf {}'.format(ospf_process_id) if vrf: command += ' vrf %s' % vrf return self.configure(command)
python
{ "resource": "" }
q19799
Ospf.configure_ospf
train
def configure_ospf(self, cmd): """Allows for a list of OSPF subcommands to be configured" Args: cmd: (list or str): Subcommand to be entered Returns: bool: True if all the commands completed successfully """ config = self.get() cmds = ['router ospf {}'.format(config['ospf_process_id'])] cmds.extend(make_iterable(cmd)) return super(Ospf, self).configure(cmds)
python
{ "resource": "" }