_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q257300 | cancel | validation | def cancel(batch_fn, cancel_fn, ops):
"""Cancel operations.
Args:
batch_fn: API-specific batch function.
cancel_fn: API-specific cancel function.
ops: A list of operations to cancel.
Returns:
A list of operations canceled and a list of error messages.
"""
# Canceling many operations one-by-... | python | {
"resource": ""
} |
q257301 | retry_api_check | validation | def retry_api_check(exception):
"""Return True if we should retry. False otherwise.
Args:
exception: An exception to test for transience.
Returns:
True if we should retry. False otherwise.
"""
if isinstance(exception, apiclient.errors.HttpError):
if exception.resp.status in TRANSIENT_HTTP_ERROR_... | python | {
"resource": ""
} |
q257302 | retry_auth_check | validation | def retry_auth_check(exception):
"""Specific check for auth error codes.
Return True if we should retry.
False otherwise.
Args:
exception: An exception to test for transience.
Returns:
True if we should retry. False otherwise.
"""
if isinstance(exception, apiclient.errors.HttpError):
if exc... | python | {
"resource": ""
} |
q257303 | setup_service | validation | def setup_service(api_name, api_version, credentials=None):
"""Configures genomics API client.
Args:
api_name: Name of the Google API (for example: "genomics")
api_version: Version of the API (for example: "v2alpha1")
credentials: Credentials to be used for the gcloud API calls.
Returns:
A confi... | python | {
"resource": ""
} |
q257304 | Api.execute | validation | def execute(api):
"""Executes operation.
Args:
api: The base API object
Returns:
A response body object
"""
try:
return api.execute()
except Exception as exception:
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
_print_error('%s: Exception %s: %s' % (now, ... | python | {
"resource": ""
} |
q257305 | _eval_arg_type | validation | def _eval_arg_type(arg_type, T=Any, arg=None, sig=None):
"""Returns a type from a snippit of python source. Should normally be
something just like 'str' or 'Object'.
arg_type the source to be evaluated
T the default type
arg context... | python | {
"resource": ""
} |
q257306 | jsonify_status_code | validation | def jsonify_status_code(status_code, *args, **kw):
"""Returns a jsonified response with the specified HTTP status code.
The positional and keyword arguments are passed directly to the
:func:`flask.jsonify` function which creates the response.
"""
is_batch = kw.pop('is_batch', False)
if is_batch... | python | {
"resource": ""
} |
q257307 | ServiceProxy.send_payload | validation | def send_payload(self, params):
"""Performs the actual sending action and returns the result
"""
data = json.dumps({
'jsonrpc': self.version,
'method': self.service_name,
'params': params,
'id': text_type(uuid.uuid4())
})
data_binar... | python | {
"resource": ""
} |
q257308 | Error.json_rpc_format | validation | def json_rpc_format(self):
"""Return the Exception data in a format for JSON-RPC
"""
error = {
'name': text_type(self.__class__.__name__),
'code': self.code,
'message': '{0}'.format(text_type(self.message)),
'data': self.data
}
if... | python | {
"resource": ""
} |
q257309 | Config.from_file | validation | def from_file(cls, file):
"""Try loading given config file.
:param str file: full path to the config file to load
"""
if not os.path.exists(file):
raise ValueError("Config file not found.")
try:
config_parser = configparser.ConfigParser()
con... | python | {
"resource": ""
} |
q257310 | Config.discover | validation | def discover(cls):
"""Make a guess about the config file location an try loading it."""
file = os.path.join(Config.config_dir, Config.config_name)
return cls.from_file(file) | python | {
"resource": ""
} |
q257311 | Config.create_config | validation | def create_config(cls, cfgfile, nick, twtfile, twturl, disclose_identity, add_news):
"""Create a new config file at the default location.
:param str cfgfile: path to the config file
:param str nick: nickname to use for own tweets
:param str twtfile: path to the local twtxt file
... | python | {
"resource": ""
} |
q257312 | Config.write_config | validation | def write_config(self):
"""Writes `self.cfg` to `self.config_file`."""
with open(self.config_file, "w") as config_file:
self.cfg.write(config_file) | python | {
"resource": ""
} |
q257313 | validate_config_key | validation | def validate_config_key(ctx, param, value):
"""Validate a configuration key according to `section.item`."""
if not value:
return value
try:
section, item = value.split(".", 1)
except ValueError:
raise click.BadArgumentUsage("Given key does not contain a section name.")
else:... | python | {
"resource": ""
} |
q257314 | expand_mentions | validation | def expand_mentions(text, embed_names=True):
"""Searches the given text for mentions and expands them.
For example:
"@source.nick" will be expanded to "@<source.nick source.url>".
"""
if embed_names:
mention_format = "@<{name} {url}>"
else:
mention_format = "@<{url}>"
def h... | python | {
"resource": ""
} |
q257315 | make_aware | validation | def make_aware(dt):
"""Appends tzinfo and assumes UTC, if datetime object has no tzinfo already."""
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc) | python | {
"resource": ""
} |
q257316 | Cache.from_file | validation | def from_file(cls, file, *args, **kwargs):
"""Try loading given cache file."""
try:
cache = shelve.open(file)
return cls(file, cache, *args, **kwargs)
except OSError as e:
logger.debug("Loading {0} failed".format(file))
raise e | python | {
"resource": ""
} |
q257317 | Cache.discover | validation | def discover(cls, *args, **kwargs):
"""Make a guess about the cache file location an try loading it."""
file = os.path.join(Cache.cache_dir, Cache.cache_name)
return cls.from_file(file, *args, **kwargs) | python | {
"resource": ""
} |
q257318 | Cache.is_cached | validation | def is_cached(self, url):
"""Checks if specified URL is cached."""
try:
return True if url in self.cache else False
except TypeError:
return False | python | {
"resource": ""
} |
q257319 | Cache.add_tweets | validation | def add_tweets(self, url, last_modified, tweets):
"""Adds new tweets to the cache."""
try:
self.cache[url] = {"last_modified": last_modified, "tweets": tweets}
self.mark_updated()
return True
except TypeError:
return False | python | {
"resource": ""
} |
q257320 | Cache.get_tweets | validation | def get_tweets(self, url, limit=None):
"""Retrieves tweets from the cache."""
try:
tweets = self.cache[url]["tweets"]
self.mark_updated()
return sorted(tweets, reverse=True)[:limit]
except KeyError:
return [] | python | {
"resource": ""
} |
q257321 | Cache.remove_tweets | validation | def remove_tweets(self, url):
"""Tries to remove cached tweets."""
try:
del self.cache[url]
self.mark_updated()
return True
except KeyError:
return False | python | {
"resource": ""
} |
q257322 | timeline | validation | def timeline(ctx, pager, limit, twtfile, sorting, timeout, porcelain, source, cache, force_update):
"""Retrieve your personal timeline."""
if source:
source_obj = ctx.obj["conf"].get_source_by_nick(source)
if not source_obj:
logger.debug("Not following {0}, trying as URL".format(sour... | python | {
"resource": ""
} |
q257323 | config | validation | def config(ctx, key, value, remove, edit):
"""Get or set config item."""
conf = ctx.obj["conf"]
if not edit and not key:
raise click.BadArgumentUsage("You have to specify either a key or use --edit.")
if edit:
return click.edit(filename=conf.config_file)
if remove:
try:
... | python | {
"resource": ""
} |
q257324 | Tweet.relative_datetime | validation | def relative_datetime(self):
"""Return human-readable relative time string."""
now = datetime.now(timezone.utc)
tense = "from now" if self.created_at > now else "ago"
return "{0} {1}".format(humanize.naturaldelta(now - self.created_at), tense) | python | {
"resource": ""
} |
q257325 | save | validation | def save(url, *args, **kwargs):
""" Parse the options, set defaults and then fire up PhantomJS. """
device = heimdallDevice(kwargs.get('device', None))
kwargs['width'] = kwargs.get('width', None) or device.width
kwargs['height'] = kwargs.get('height', None) or device.height
kwargs['user_agent'] = ... | python | {
"resource": ""
} |
q257326 | screenshot | validation | def screenshot(url, *args, **kwargs):
""" Call PhantomJS with the specified flags and options. """
phantomscript = os.path.join(os.path.dirname(__file__),
'take_screenshot.js')
directory = kwargs.get('save_dir', '/tmp')
image_name = kwargs.get('image_name', None) or _i... | python | {
"resource": ""
} |
q257327 | _image_name_from_url | validation | def _image_name_from_url(url):
""" Create a nice image name from the url. """
find = r'https?://|[^\w]'
replace = '_'
return re.sub(find, replace, url).strip('_') | python | {
"resource": ""
} |
q257328 | worker | validation | def worker(f):
"""
Decorator. Abortable worker. If wrapped task will be cancelled by
dispatcher, decorator will send ftp codes of successful interrupt.
::
>>> @worker
... async def worker(self, connection, rest):
... ...
"""
@functools.wraps(f)
async def wrappe... | python | {
"resource": ""
} |
q257329 | User.get_permissions | validation | def get_permissions(self, path):
"""
Return nearest parent permission for `path`.
:param path: path which permission you want to know
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:rtype: :py:class:`aioftp.Permission`
"""
path = pathlib.PurePo... | python | {
"resource": ""
} |
q257330 | AvailableConnections.release | validation | def release(self):
"""
Release, incrementing the internal counter by one.
"""
if self.value is not None:
self.value += 1
if self.value > self.maximum_value:
raise ValueError("Too many releases") | python | {
"resource": ""
} |
q257331 | register_memory | validation | def register_memory():
"""Register an approximation of memory used by FTP server process
and all of its children.
"""
# XXX How to get a reliable representation of memory being used is
# not clear. (rss - shared) seems kind of ok but we might also use
# the private working set via get_memory_map... | python | {
"resource": ""
} |
q257332 | connect | validation | def connect():
"""Connect to FTP server, login and return an ftplib.FTP instance."""
ftp_class = ftplib.FTP if not SSL else ftplib.FTP_TLS
ftp = ftp_class(timeout=TIMEOUT)
ftp.connect(HOST, PORT)
ftp.login(USER, PASSWORD)
if SSL:
ftp.prot_p() # secure data connection
return ftp | python | {
"resource": ""
} |
q257333 | bytes_per_second | validation | def bytes_per_second(ftp, retr=True):
"""Return the number of bytes transmitted in 1 second."""
tot_bytes = 0
if retr:
def request_file():
ftp.voidcmd('TYPE I')
conn = ftp.transfercmd("retr " + TESTFN)
return conn
with contextlib.closing(request_file()) a... | python | {
"resource": ""
} |
q257334 | async_enterable | validation | def async_enterable(f):
"""
Decorator. Bring coroutine result up, so it can be used as async context
::
>>> async def foo():
...
... ...
... return AsyncContextInstance(...)
...
... ctx = await foo()
... async with ctx:
...
..... | python | {
"resource": ""
} |
q257335 | setlocale | validation | def setlocale(name):
"""
Context manager with threading lock for set locale on enter, and set it
back to original state on exit.
::
>>> with setlocale("C"):
... ...
"""
with LOCALE_LOCK:
old_locale = locale.setlocale(locale.LC_ALL)
try:
yield loc... | python | {
"resource": ""
} |
q257336 | Throttle.append | validation | def append(self, data, start):
"""
Count `data` for throttle
:param data: bytes of data for count
:type data: :py:class:`bytes`
:param start: start of read/write time from
:py:meth:`asyncio.BaseEventLoop.time`
:type start: :py:class:`float`
"""
... | python | {
"resource": ""
} |
q257337 | Throttle.limit | validation | def limit(self, value):
"""
Set throttle limit
:param value: bytes per second
:type value: :py:class:`int` or :py:class:`None`
"""
self._limit = value
self._start = None
self._sum = 0 | python | {
"resource": ""
} |
q257338 | StreamThrottle.clone | validation | def clone(self):
"""
Clone throttles without memory
"""
return StreamThrottle(
read=self.read.clone(),
write=self.write.clone()
) | python | {
"resource": ""
} |
q257339 | ThrottleStreamIO.append | validation | def append(self, name, data, start):
"""
Update timeout for all throttles
:param name: name of throttle to append to ("read" or "write")
:type name: :py:class:`str`
:param data: bytes of data for count
:type data: :py:class:`bytes`
:param start: start of read/w... | python | {
"resource": ""
} |
q257340 | BaseClient.check_codes | validation | def check_codes(self, expected_codes, received_code, info):
"""
Checks if any of expected matches received.
:param expected_codes: tuple of expected codes
:type expected_codes: :py:class:`tuple`
:param received_code: received code for matching
:type received_code: :py:c... | python | {
"resource": ""
} |
q257341 | BaseClient.parse_directory_response | validation | def parse_directory_response(s):
"""
Parsing directory server response.
:param s: response line
:type s: :py:class:`str`
:rtype: :py:class:`pathlib.PurePosixPath`
"""
seq_quotes = 0
start = False
directory = ""
for ch in s:
if... | python | {
"resource": ""
} |
q257342 | BaseClient.parse_list_line_windows | validation | def parse_list_line_windows(self, b):
"""
Parsing Microsoft Windows `dir` output
:param b: response line
:type b: :py:class:`bytes` or :py:class:`str`
:return: (path, info)
:rtype: (:py:class:`pathlib.PurePosixPath`, :py:class:`dict`)
"""
line = b.decode... | python | {
"resource": ""
} |
q257343 | Client.upload_stream | validation | def upload_stream(self, destination, *, offset=0):
"""
Create stream for write data to `destination` file.
:param destination: destination path of file on server side
:type destination: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:param offset: byte offset for stream s... | python | {
"resource": ""
} |
q257344 | jenks_breaks | validation | def jenks_breaks(values, nb_class):
"""
Compute jenks natural breaks on a sequence of `values`, given `nb_class`,
the number of desired class.
Parameters
----------
values : array-like
The Iterable sequence of numbers (integer/float) to be used.
nb_class : int
The desired nu... | python | {
"resource": ""
} |
q257345 | Gdk3PixbufWrapper.grab | validation | def grab(self, bbox=None):
"""Grabs an image directly to a buffer.
:param bbox: Optional tuple or list containing (x1, y1, x2, y2) coordinates
of sub-region to capture.
:return: PIL RGB image
:raises: ValueError, if image data does not have 3 channels (RGB), each with 8
... | python | {
"resource": ""
} |
q257346 | grab | validation | def grab(bbox=None, childprocess=None, backend=None):
"""Copy the contents of the screen to PIL image memory.
:param bbox: optional bounding box (x1,y1,x2,y2)
:param childprocess: pyscreenshot can cause an error,
if it is used on more different virtual displays
and back-end is not i... | python | {
"resource": ""
} |
q257347 | backend_version | validation | def backend_version(backend, childprocess=None):
"""Back-end version.
:param backend: back-end (examples:scrot, wx,..)
:param childprocess: see :py:func:`grab`
:return: version as string
"""
if childprocess is None:
childprocess = childprocess_default_value()
if not childprocess:
... | python | {
"resource": ""
} |
q257348 | open | validation | def open(
config, mode="continue", zoom=None, bounds=None, single_input_file=None,
with_cache=False, debug=False
):
"""
Open a Mapchete process.
Parameters
----------
config : MapcheteConfig object, config dict or path to mapchete file
Mapchete process configuration
mode : strin... | python | {
"resource": ""
} |
q257349 | _get_zoom_level | validation | def _get_zoom_level(zoom, process):
"""Determine zoom levels."""
if zoom is None:
return reversed(process.config.zoom_levels)
if isinstance(zoom, int):
return [zoom]
elif len(zoom) == 2:
return reversed(range(min(zoom), max(zoom)+1))
elif len(zoom) == 1:
return zoom | python | {
"resource": ""
} |
q257350 | _process_worker | validation | def _process_worker(process, process_tile):
"""Worker function running the process."""
logger.debug((process_tile.id, "running on %s" % current_process().name))
# skip execution if overwrite is disabled and tile exists
if (
process.config.mode == "continue" and
process.config.output.til... | python | {
"resource": ""
} |
q257351 | Mapchete.get_process_tiles | validation | def get_process_tiles(self, zoom=None):
"""
Yield process tiles.
Tiles intersecting with the input data bounding boxes as well as
process bounds, if provided, are considered process tiles. This is to
avoid iterating through empty tiles.
Parameters
----------
... | python | {
"resource": ""
} |
q257352 | Mapchete.batch_process | validation | def batch_process(
self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1
):
"""
Process a large batch of tiles.
Parameters
----------
process : MapcheteProcess
process to be run
zoom : list or int
either single zoom level or l... | python | {
"resource": ""
} |
q257353 | Mapchete.batch_processor | validation | def batch_processor(
self, zoom=None, tile=None, multi=cpu_count(), max_chunksize=1
):
"""
Process a large batch of tiles and yield report messages per tile.
Parameters
----------
zoom : list or int
either single zoom level or list of minimum and maximum ... | python | {
"resource": ""
} |
q257354 | Mapchete.execute | validation | def execute(self, process_tile, raise_nodata=False):
"""
Run the Mapchete process.
Execute, write and return data.
Parameters
----------
process_tile : Tile or tile index tuple
Member of the process tile pyramid (not necessarily the output
pyrami... | python | {
"resource": ""
} |
q257355 | Mapchete.read | validation | def read(self, output_tile):
"""
Read from written process output.
Parameters
----------
output_tile : BufferedTile or tile index tuple
Member of the output tile pyramid (not necessarily the process
pyramid, if output has a different metatiling setting)
... | python | {
"resource": ""
} |
q257356 | Mapchete.write | validation | def write(self, process_tile, data):
"""
Write data into output format.
Parameters
----------
process_tile : BufferedTile or tile index tuple
process tile
data : NumPy array or features
data to be written
"""
if isinstance(process_... | python | {
"resource": ""
} |
q257357 | Mapchete.get_raw_output | validation | def get_raw_output(self, tile, _baselevel_readonly=False):
"""
Get output raw data.
This function won't work with multiprocessing, as it uses the
``threading.Lock()`` class.
Parameters
----------
tile : tuple, Tile or BufferedTile
If a tile index is ... | python | {
"resource": ""
} |
q257358 | Mapchete._extract | validation | def _extract(self, in_tile=None, in_data=None, out_tile=None):
"""Extract data from tile."""
return self.config.output.extract_subset(
input_data_tiles=[(in_tile, in_data)],
out_tile=out_tile
) | python | {
"resource": ""
} |
q257359 | MapcheteProcess.read | validation | def read(self, **kwargs):
"""
Read existing output data from a previous run.
Returns
-------
process output : NumPy array (raster) or feature iterator (vector)
"""
if self.tile.pixelbuffer > self.config.output.pixelbuffer:
output_tiles = list(self.con... | python | {
"resource": ""
} |
q257360 | MapcheteProcess.open | validation | def open(self, input_id, **kwargs):
"""
Open input data.
Parameters
----------
input_id : string
input identifier from configuration file or file path
kwargs : driver specific parameters (e.g. resampling)
Returns
-------
tiled input d... | python | {
"resource": ""
} |
q257361 | MapcheteProcess.hillshade | validation | def hillshade(
self, elevation, azimuth=315.0, altitude=45.0, z=1.0, scale=1.0
):
"""
Calculate hillshading from elevation data.
Parameters
----------
elevation : array
input elevation data
azimuth : float
horizontal angle of light sou... | python | {
"resource": ""
} |
q257362 | MapcheteProcess.contours | validation | def contours(
self, elevation, interval=100, field='elev', base=0
):
"""
Extract contour lines from elevation data.
Parameters
----------
elevation : array
input elevation data
interval : integer
elevation value interval when drawing c... | python | {
"resource": ""
} |
q257363 | MapcheteProcess.clip | validation | def clip(
self, array, geometries, inverted=False, clip_buffer=0
):
"""
Clip array by geometry.
Parameters
----------
array : array
raster data to be clipped
geometries : iterable
geometries used to clip source array
inverted :... | python | {
"resource": ""
} |
q257364 | clip_array_with_vector | validation | def clip_array_with_vector(
array, array_affine, geometries, inverted=False, clip_buffer=0
):
"""
Clip input array with a vector list.
Parameters
----------
array : array
input raster data
array_affine : Affine
Affine object describing the raster's geolocation
geometries... | python | {
"resource": ""
} |
q257365 | pyramid | validation | def pyramid(
input_raster,
output_dir,
pyramid_type=None,
output_format=None,
resampling_method=None,
scale_method=None,
zoom=None,
bounds=None,
overwrite=False,
debug=False
):
"""Create tile pyramid out of input raster."""
bounds = bounds if bounds else None
options ... | python | {
"resource": ""
} |
q257366 | raster2pyramid | validation | def raster2pyramid(input_file, output_dir, options):
"""Create a tile pyramid out of an input raster dataset."""
pyramid_type = options["pyramid_type"]
scale_method = options["scale_method"]
output_format = options["output_format"]
resampling = options["resampling"]
zoom = options["zoom"]
bo... | python | {
"resource": ""
} |
q257367 | _get_zoom | validation | def _get_zoom(zoom, input_raster, pyramid_type):
"""Determine minimum and maximum zoomlevel."""
if not zoom:
minzoom = 1
maxzoom = get_best_zoom_level(input_raster, pyramid_type)
elif len(zoom) == 1:
minzoom = zoom[0]
maxzoom = zoom[0]
elif len(zoom) == 2:
if zoom... | python | {
"resource": ""
} |
q257368 | validate_values | validation | def validate_values(config, values):
"""
Validate whether value is found in config and has the right type.
Parameters
----------
config : dict
configuration dictionary
values : list
list of (str, type) tuples of values and value types expected in config
Returns
-------
... | python | {
"resource": ""
} |
q257369 | get_hash | validation | def get_hash(x):
"""Return hash of x."""
if isinstance(x, str):
return hash(x)
elif isinstance(x, dict):
return hash(yaml.dump(x)) | python | {
"resource": ""
} |
q257370 | get_zoom_levels | validation | def get_zoom_levels(process_zoom_levels=None, init_zoom_levels=None):
"""Validate and return zoom levels."""
process_zoom_levels = _validate_zooms(process_zoom_levels)
if init_zoom_levels is None:
return process_zoom_levels
else:
init_zoom_levels = _validate_zooms(init_zoom_levels)
... | python | {
"resource": ""
} |
q257371 | snap_bounds | validation | def snap_bounds(bounds=None, pyramid=None, zoom=None):
"""
Snaps bounds to tiles boundaries of specific zoom level.
Parameters
----------
bounds : bounds to be snapped
pyramid : TilePyramid
zoom : int
Returns
-------
Bounds(left, bottom, right, top)
"""
if not isinstanc... | python | {
"resource": ""
} |
q257372 | clip_bounds | validation | def clip_bounds(bounds=None, clip=None):
"""
Clips bounds by clip.
Parameters
----------
bounds : bounds to be clipped
clip : clip bounds
Returns
-------
Bounds(left, bottom, right, top)
"""
bounds = Bounds(*bounds)
clip = Bounds(*clip)
return Bounds(
max(bo... | python | {
"resource": ""
} |
q257373 | _validate_zooms | validation | def _validate_zooms(zooms):
"""
Return a list of zoom levels.
Following inputs are converted:
- int --> [int]
- dict{min, max} --> range(min, max + 1)
- [int] --> [int]
- [int, int] --> range(smaller int, bigger int + 1)
"""
if isinstance(zooms, dict):
if any([a not in zooms... | python | {
"resource": ""
} |
q257374 | _raw_at_zoom | validation | def _raw_at_zoom(config, zooms):
"""Return parameter dictionary per zoom level."""
params_per_zoom = {}
for zoom in zooms:
params = {}
for name, element in config.items():
if name not in _RESERVED_PARAMETERS:
out_element = _element_at_zoom(name, element, zoom)
... | python | {
"resource": ""
} |
q257375 | _element_at_zoom | validation | def _element_at_zoom(name, element, zoom):
"""
Return the element filtered by zoom level.
- An input integer or float gets returned as is.
- An input string is checked whether it starts with "zoom". Then, the
provided zoom level gets parsed and compared with the actual zoom
... | python | {
"resource": ""
} |
q257376 | _filter_by_zoom | validation | def _filter_by_zoom(element=None, conf_string=None, zoom=None):
"""Return element only if zoom condition matches with config string."""
for op_str, op_func in [
# order of operators is important:
# prematurely return in cases of "<=" or ">=", otherwise
# _strip_zoom() cannot parse config... | python | {
"resource": ""
} |
q257377 | _strip_zoom | validation | def _strip_zoom(input_string, strip_string):
"""Return zoom level as integer or throw error."""
try:
return int(input_string.strip(strip_string))
except Exception as e:
raise MapcheteConfigError("zoom level could not be determined: %s" % e) | python | {
"resource": ""
} |
q257378 | _flatten_tree | validation | def _flatten_tree(tree, old_path=None):
"""Flatten dict tree into dictionary where keys are paths of old dict."""
flat_tree = []
for key, value in tree.items():
new_path = "/".join([old_path, key]) if old_path else key
if isinstance(value, dict) and "format" not in value:
flat_tr... | python | {
"resource": ""
} |
q257379 | _unflatten_tree | validation | def _unflatten_tree(flat):
"""Reverse tree flattening."""
tree = {}
for key, value in flat.items():
path = key.split("/")
# we are at the end of a branch
if len(path) == 1:
tree[key] = value
# there are more branches
else:
# create new dict
... | python | {
"resource": ""
} |
q257380 | MapcheteConfig.bounds | validation | def bounds(self):
"""Process bounds as defined in the configuration."""
if self._raw["bounds"] is None:
return self.process_pyramid.bounds
else:
return Bounds(*_validate_bounds(self._raw["bounds"])) | python | {
"resource": ""
} |
q257381 | MapcheteConfig.init_bounds | validation | def init_bounds(self):
"""
Process bounds this process is currently initialized with.
This gets triggered by using the ``init_bounds`` kwarg. If not set, it will
be equal to self.bounds.
"""
if self._raw["init_bounds"] is None:
return self.bounds
else... | python | {
"resource": ""
} |
q257382 | MapcheteConfig.effective_bounds | validation | def effective_bounds(self):
"""
Effective process bounds required to initialize inputs.
Process bounds sometimes have to be larger, because all intersecting process
tiles have to be covered as well.
"""
return snap_bounds(
bounds=clip_bounds(bounds=self.init_... | python | {
"resource": ""
} |
q257383 | MapcheteConfig.output | validation | def output(self):
"""Output object of driver."""
output_params = dict(
self._raw["output"],
grid=self.output_pyramid.grid,
pixelbuffer=self.output_pyramid.pixelbuffer,
metatiling=self.output_pyramid.metatiling
)
if "path" in output_params:
... | python | {
"resource": ""
} |
q257384 | MapcheteConfig.input | validation | def input(self):
"""
Input items used for process stored in a dictionary.
Keys are the hashes of the input parameters, values the respective
InputData classes.
"""
# the delimiters are used by some input drivers
delimiters = dict(
zoom=self.init_zoom_... | python | {
"resource": ""
} |
q257385 | MapcheteConfig.baselevels | validation | def baselevels(self):
"""
Optional baselevels configuration.
baselevels:
min: <zoom>
max: <zoom>
lower: <resampling method>
higher: <resampling method>
"""
if "baselevels" not in self._raw:
return {}
baselevels ... | python | {
"resource": ""
} |
q257386 | MapcheteConfig.params_at_zoom | validation | def params_at_zoom(self, zoom):
"""
Return configuration parameters snapshot for zoom as dictionary.
Parameters
----------
zoom : int
zoom level
Returns
-------
configuration snapshot : dictionary
zoom level dependent process configur... | python | {
"resource": ""
} |
q257387 | MapcheteConfig.area_at_zoom | validation | def area_at_zoom(self, zoom=None):
"""
Return process bounding box for zoom level.
Parameters
----------
zoom : int or None
if None, the union of all zoom level areas is returned
Returns
-------
process area : shapely geometry
"""
... | python | {
"resource": ""
} |
q257388 | MapcheteConfig.bounds_at_zoom | validation | def bounds_at_zoom(self, zoom=None):
"""
Return process bounds for zoom level.
Parameters
----------
zoom : integer or list
Returns
-------
process bounds : tuple
left, bottom, right, top
"""
return () if self.area_at_zoom(zoo... | python | {
"resource": ""
} |
q257389 | zoom_index_gen | validation | def zoom_index_gen(
mp=None,
out_dir=None,
zoom=None,
geojson=False,
gpkg=False,
shapefile=False,
txt=False,
vrt=False,
fieldname="location",
basepath=None,
for_gdal=True,
threading=False,
):
"""
Generate indexes for given zoom level.
Parameters
---------... | python | {
"resource": ""
} |
q257390 | InputData.profile | validation | def profile(self):
"""Return raster metadata."""
with rasterio.open(self.path, "r") as src:
return deepcopy(src.meta) | python | {
"resource": ""
} |
q257391 | execute | validation | def execute(mp):
"""
Example process for testing.
Inputs:
-------
file1
raster file
Parameters:
-----------
Output:
-------
np.ndarray
"""
# Reading and writing data works like this:
with mp.open("file1", resampling="bilinear") as raster_file:
if ra... | python | {
"resource": ""
} |
q257392 | OutputData.is_valid_with_config | validation | def is_valid_with_config(self, config):
"""
Check if output format is valid with other process parameters.
Parameters
----------
config : dictionary
output configuration parameters
Returns
-------
is_valid : bool
"""
validate_... | python | {
"resource": ""
} |
q257393 | InputTile.read | validation | def read(self, validity_check=True, no_neighbors=False, **kwargs):
"""
Read data from process output.
Parameters
----------
validity_check : bool
run geometry validity check (default: True)
no_neighbors : bool
don't include neighbor tiles if there... | python | {
"resource": ""
} |
q257394 | available_output_formats | validation | def available_output_formats():
"""
Return all available output formats.
Returns
-------
formats : list
all available output formats
"""
output_formats = []
for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):
driver_ = v.load()
if hasattr(driver_, "MET... | python | {
"resource": ""
} |
q257395 | available_input_formats | validation | def available_input_formats():
"""
Return all available input formats.
Returns
-------
formats : list
all available input formats
"""
input_formats = []
for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):
logger.debug("driver found: %s", v)
driver_ = v... | python | {
"resource": ""
} |
q257396 | load_output_writer | validation | def load_output_writer(output_params, readonly=False):
"""
Return output class of driver.
Returns
-------
output : ``OutputData``
output writer object
"""
if not isinstance(output_params, dict):
raise TypeError("output_params must be a dictionary")
driver_name = output_p... | python | {
"resource": ""
} |
q257397 | load_input_reader | validation | def load_input_reader(input_params, readonly=False):
"""
Return input class of driver.
Returns
-------
input_params : ``InputData``
input parameters
"""
logger.debug("find input reader with params %s", input_params)
if not isinstance(input_params, dict):
raise TypeError(... | python | {
"resource": ""
} |
q257398 | driver_from_file | validation | def driver_from_file(input_file):
"""
Guess driver from file extension.
Returns
-------
driver : string
driver name
"""
file_ext = os.path.splitext(input_file)[1].split(".")[1]
if file_ext not in _file_ext_to_driver():
raise MapcheteDriverError(
"no driver co... | python | {
"resource": ""
} |
q257399 | write_output_metadata | validation | def write_output_metadata(output_params):
"""Dump output JSON and verify parameters if output metadata exist."""
if "path" in output_params:
metadata_path = os.path.join(output_params["path"], "metadata.json")
logger.debug("check for output %s", metadata_path)
try:
existing_p... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.