sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def find_best_candidate(self, elev_source_files=None): """ Heuristically determines which tile should be recalculated based on updated edge information. Presently does not check if that tile is locked, which could lead to a parallel thread closing while one thread continues to pr...
Heuristically determines which tile should be recalculated based on updated edge information. Presently does not check if that tile is locked, which could lead to a parallel thread closing while one thread continues to process tiles.
entailment
def process_twi(self, index=None, do_edges=False, skip_uca_twi=False): """ Processes the TWI, along with any dependencies (like the slope and UCA) Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, ...
Processes the TWI, along with any dependencies (like the slope and UCA) Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of the files as listed in self.el...
entailment
def process(self, index=None): """ This will completely process a directory of elevation tiles (as supplied in the constructor). Both phases of the calculation, the single tile and edge resolution phases are run. Parameters ----------- index : int/slice (optional...
This will completely process a directory of elevation tiles (as supplied in the constructor). Both phases of the calculation, the single tile and edge resolution phases are run. Parameters ----------- index : int/slice (optional) Default None - processes all tiles in...
entailment
def calculate_twi(self, esfile, save_path, use_cache=True, do_edges=False, skip_uca_twi=False): """ Calculates twi for supplied elevation file Parameters ----------- esfile : str Path to elevation file to be processed save_path: str ...
Calculates twi for supplied elevation file Parameters ----------- esfile : str Path to elevation file to be processed save_path: str Root path to location where TWI will be saved. TWI will be saved in a subdirectory 'twi'. use_cache : bool (op...
entailment
def process_command(self, command, save_name='custom', index=None): """ Processes the hillshading Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of ...
Processes the hillshading Parameters ----------- index : int/slice (optional) Default: None - process all tiles in source directory. Otherwise, will only process the index/indices of the files as listed in self.elev_source_files
entailment
def rename_files(files, name=None): """ Given a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM package. This assumes a .tif extension. Parameters ----------- files : list A list of strings of the paths to the elevat...
Given a list of file paths for elevation files, this function will rename those files to the format required by the pyDEM package. This assumes a .tif extension. Parameters ----------- files : list A list of strings of the paths to the elevation files that will be renamed name ...
entailment
def parse_fn(fn): """ This parses the file name and returns the coordinates of the tile Parameters ----------- fn : str Filename of a GEOTIFF Returns -------- coords = [LLC.lat, LLC.lon, URC.lat, URC.lon] """ try: parts = os.path.splitext(os.path.split(fn)[-1])[0].r...
This parses the file name and returns the coordinates of the tile Parameters ----------- fn : str Filename of a GEOTIFF Returns -------- coords = [LLC.lat, LLC.lon, URC.lat, URC.lon]
entailment
def get_fn(elev, name=None): """ Determines the standard filename for a given GeoTIFF Layer. Parameters ----------- elev : GdalReader.raster_layer A raster layer from the GdalReader object. name : str (optional) An optional suffix to the filename. Returns ------- fn ...
Determines the standard filename for a given GeoTIFF Layer. Parameters ----------- elev : GdalReader.raster_layer A raster layer from the GdalReader object. name : str (optional) An optional suffix to the filename. Returns ------- fn : str The standard <filename>_<na...
entailment
def get_fn_from_coords(coords, name=None): """ Given a set of coordinates, returns the standard filename. Parameters ----------- coords : list [LLC.lat, LLC.lon, URC.lat, URC.lon] name : str (optional) An optional suffix to the filename. Returns ------- fn : str ...
Given a set of coordinates, returns the standard filename. Parameters ----------- coords : list [LLC.lat, LLC.lon, URC.lat, URC.lon] name : str (optional) An optional suffix to the filename. Returns ------- fn : str The standard <filename>_<name>.tif with suffix (if...
entailment
def mk_dx_dy_from_geotif_layer(geotif): """ Extracts the change in x and y coordinates from the geotiff file. Presently only supports WGS-84 files. """ ELLIPSOID_MAP = {'WGS84': 'WGS-84'} ellipsoid = ELLIPSOID_MAP[geotif.grid_coordinates.wkt] d = distance(ellipsoid=ellipsoid) dx = geotif...
Extracts the change in x and y coordinates from the geotiff file. Presently only supports WGS-84 files.
entailment
def mk_geotiff_obj(raster, fn, bands=1, gdal_data_type=gdal.GDT_Float32, lat=[46, 45], lon=[-73, -72]): """ Creates a new geotiff file objects using the WGS84 coordinate system, saves it to disk, and returns a handle to the python file object and driver Parameters ------------ ...
Creates a new geotiff file objects using the WGS84 coordinate system, saves it to disk, and returns a handle to the python file object and driver Parameters ------------ raster : array Numpy array of the raster data to be added to the object fn : str Name of the geotiff file ban...
entailment
def sortrows(a, i=0, index_out=False, recurse=True): """ Sorts array "a" by columns i Parameters ------------ a : np.ndarray array to be sorted i : int (optional) column to be sorted by, taken as 0 by default index_out : bool (optional) return the index I such that a(I) ...
Sorts array "a" by columns i Parameters ------------ a : np.ndarray array to be sorted i : int (optional) column to be sorted by, taken as 0 by default index_out : bool (optional) return the index I such that a(I) = sortrows(a,i). Default = False recurse : bool (optional...
entailment
def get_adjacent_index(I, shape, size): """ Find indices 2d-adjacent to those in I. Helper function for get_border*. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region shape : tuple(int, int) region shape size : int region size (technical...
Find indices 2d-adjacent to those in I. Helper function for get_border*. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region shape : tuple(int, int) region shape size : int region size (technically computable from shape) Returns ------- ...
entailment
def get_border_index(I, shape, size): """ Get flattened indices for the border of the region I. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region. size : int region size (technically computable from shape argument) shape : tuple(int, int) ...
Get flattened indices for the border of the region I. Parameters ---------- I : np.ndarray(dtype=int) indices in the flattened region. size : int region size (technically computable from shape argument) shape : tuple(int, int) region shape Returns ------- J : np...
entailment
def get_border_mask(region): """ Get border of the region as a boolean array mask. Parameters ---------- region : np.ndarray(shape=(m, n), dtype=bool) mask of the region Returns ------- border : np.ndarray(shape=(m, n), dtype=bool) mask of the region border (not includi...
Get border of the region as a boolean array mask. Parameters ---------- region : np.ndarray(shape=(m, n), dtype=bool) mask of the region Returns ------- border : np.ndarray(shape=(m, n), dtype=bool) mask of the region border (not including region)
entailment
def get_distance(region, src): """ Compute within-region distances from the src pixels. Parameters ---------- region : np.ndarray(shape=(m, n), dtype=bool) mask of the region src : np.ndarray(shape=(m, n), dtype=bool) mask of the source pixels to compute distances from. Ret...
Compute within-region distances from the src pixels. Parameters ---------- region : np.ndarray(shape=(m, n), dtype=bool) mask of the region src : np.ndarray(shape=(m, n), dtype=bool) mask of the source pixels to compute distances from. Returns ------- d : np.ndarray(shape=(...
entailment
def grow_slice(slc, size): """ Grow a slice object by 1 in each direction without overreaching the list. Parameters ---------- slc: slice slice object to grow size: int list length Returns ------- slc: slice extended slice """ return slice(max(0, s...
Grow a slice object by 1 in each direction without overreaching the list. Parameters ---------- slc: slice slice object to grow size: int list length Returns ------- slc: slice extended slice
entailment
def is_edge(obj, shape): """ Check if a 2d object is on the edge of the array. Parameters ---------- obj : tuple(slice, slice) Pair of slices (e.g. from scipy.ndimage.measurements.find_objects) shape : tuple(int, int) Array shape. Returns ------- b : boolean ...
Check if a 2d object is on the edge of the array. Parameters ---------- obj : tuple(slice, slice) Pair of slices (e.g. from scipy.ndimage.measurements.find_objects) shape : tuple(int, int) Array shape. Returns ------- b : boolean True if the object touches any edge ...
entailment
def find_centroid(region): """ Finds an approximate centroid for a region that is within the region. Parameters ---------- region : np.ndarray(shape=(m, n), dtype='bool') mask of the region. Returns ------- i, j : tuple(int, int) 2d index within the region nearest t...
Finds an approximate centroid for a region that is within the region. Parameters ---------- region : np.ndarray(shape=(m, n), dtype='bool') mask of the region. Returns ------- i, j : tuple(int, int) 2d index within the region nearest the center of mass.
entailment
def clear(self): """Resets the object at its initial (empty) state.""" self._deque.clear() self._total_length = 0 self._has_view = False
Resets the object at its initial (empty) state.
entailment
def _tobytes(self): """Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object. """ if not self._has_view: # fast path optimization if len(self._deque) == 0: return b"" elif len(self._dequ...
Serializes the write buffer into a single string (bytes). Returns: a string (bytes) object.
entailment
def pop_chunk(self, chunk_max_size): """Pops a chunk of the given max size. Optimized to avoid too much string copies. Args: chunk_max_size (int): max size of the returned chunk. Returns: string (bytes) with a size <= chunk_max_size. """ if self...
Pops a chunk of the given max size. Optimized to avoid too much string copies. Args: chunk_max_size (int): max size of the returned chunk. Returns: string (bytes) with a size <= chunk_max_size.
entailment
def with_name(self, name): """Return a new path with the file name changed.""" if not self.name: raise ValueError("%r has an empty name" % (self,)) return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
Return a new path with the file name changed.
entailment
def with_suffix(self, suffix): """Return a new path with the file suffix changed (or added, if none).""" # XXX if suffix is None, should the current suffix be removed? drv, root, parts = self._flavour.parse_parts((suffix,)) if drv or root or len(parts) != 1: raise ValueError(...
Return a new path with the file suffix changed (or added, if none).
entailment
def _raw_open(self, flags, mode=0o777): """ Open the file pointed by this path and return a file descriptor, as os.open() does. """ return self._accessor.open(self, flags, mode)
Open the file pointed by this path and return a file descriptor, as os.open() does.
entailment
def iterdir(self): """Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'. """ for name in self._accessor.listdir(self): if name in ('.', '..'): # Yielding a path object for these makes little sense ...
Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'.
entailment
def absolute(self): """Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. all '.' and '..' will be kept along. Use resolve() to get the canonical path to a file. """ # XXX untested yet!...
Return an absolute version of this path. This function works even if the path doesn't point to anything. No normalization is done, i.e. all '.' and '..' will be kept along. Use resolve() to get the canonical path to a file.
entailment
def resolve(self): """ Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows). """ s = self._flavour.resolve(self) if s is None: # No symlink resolution => for cons...
Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).
entailment
def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None): """ Open the file pointed by this path and return a file object, as the built-in open() function does. """ if sys.version_info >= (3, 3): return io.open(str(self), mode, buf...
Open the file pointed by this path and return a file object, as the built-in open() function does.
entailment
def replace(self, target): """ Rename this path to the given path, clobbering the existing destination if it exists. """ if sys.version_info < (3, 3): raise NotImplementedError("replace() is only available " "with Python 3.3 and l...
Rename this path to the given path, clobbering the existing destination if it exists.
entailment
def symlink_to(self, target, target_is_directory=False): """ Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's. """ self._accessor.symlink(target, self, target_is_directory)
Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink's.
entailment
def is_symlink(self): """ Whether this path is a symbolic link. """ try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist return False
Whether this path is a symbolic link.
entailment
def is_block_device(self): """ Whether this path is a block device. """ try: return S_ISBLK(self.stat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist or is a broken symlink # (see htt...
Whether this path is a block device.
entailment
def is_char_device(self): """ Whether this path is a character device. """ try: return S_ISCHR(self.stat().st_mode) except OSError as e: if e.errno != ENOENT: raise # Path doesn't exist or is a broken symlink # (see ...
Whether this path is a character device.
entailment
def grid_coords_from_corners(upper_left_corner, lower_right_corner, size): ''' Points are the outer edges of the UL and LR pixels. Size is rows, columns. GC projection type is taken from Points. ''' assert upper_left_corner.wkt == lower_right_corner.wkt geotransform = np.array([upper_left_corner.lon, -(...
Points are the outer edges of the UL and LR pixels. Size is rows, columns. GC projection type is taken from Points.
entailment
def intersects(self, other_grid_coordinates): """ returns True if the GC's overlap. """ ogc = other_grid_coordinates # alias # for explanation: http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other # Note the flipped y-coord in this coord system. ...
returns True if the GC's overlap.
entailment
def unique_str(self): """ A string that (ideally) uniquely represents this GC object. This helps with naming files for caching. 'Unique' is defined as 'If GC1 != GC2, then GC1.unique_str() != GC2.unique_str()'; conversely, 'If GC1 == GC2, then GC1.unique_str() == GC2.unique_str()'. ...
A string that (ideally) uniquely represents this GC object. This helps with naming files for caching. 'Unique' is defined as 'If GC1 != GC2, then GC1.unique_str() != GC2.unique_str()'; conversely, 'If GC1 == GC2, then GC1.unique_str() == GC2.unique_str()'. The string should be filename-...
entailment
def _get_x_axis(self): """See http://www.gdal.org/gdal_datamodel.html for details.""" # 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5). x_centers = np.linspace(.5, self.x_size - .5, self.x_size) y_centers = x_centers * 0 return (self.geotransform[0...
See http://www.gdal.org/gdal_datamodel.html for details.
entailment
def _get_y_axis(self): """See http://www.gdal.org/gdal_datamodel.html for details.""" # 0,0 is top/left top top/left pixel. Actual x/y coord of that pixel are (.5,.5). y_centers = np.linspace(.5, self.y_size - .5, self.y_size) x_centers = y_centers * 0 return (self.geotransform[3...
See http://www.gdal.org/gdal_datamodel.html for details.
entailment
def raster_to_projection_coords(self, pixel_x, pixel_y): """ Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for details. """ h_px_py = np.array([1, pixel_x, pixel_y]) gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]) ...
Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for details.
entailment
def projection_to_raster_coords(self, lat, lon): """ Returns pixel centers. See documentation for the GDAL function GetGeoTransform for details. """ r_px_py = np.array([1, lon, lat]) tg = inv(np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]])) return np.inner(t...
Returns pixel centers. See documentation for the GDAL function GetGeoTransform for details.
entailment
def reproject_to_grid_coordinates(self, grid_coordinates, interp=gdalconst.GRA_NearestNeighbour): """ Reprojects data in this layer to match that in the GridCoordinates object. """ source_dataset = self.grid_coordinates._as_gdal_dataset() dest_dataset = grid_coordinates._as_gdal_dataset(...
Reprojects data in this layer to match that in the GridCoordinates object.
entailment
def inpaint(self): """ Replace masked-out elements in an array using an iterative image inpainting algorithm. """ import inpaint filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2) self.raster_data = np.ma.masked_invalid(filled)
Replace masked-out elements in an array using an iterative image inpainting algorithm.
entailment
def interp_value(self, lat, lon, indexed=False): """ Lookup a pixel value in the raster data, performing linear interpolation if necessary. Indexed ==> nearest neighbor (*fast*). """ (px, py) = self.grid_coordinates.projection_to_raster_coords(lat, lon) if indexed: return sel...
Lookup a pixel value in the raster data, performing linear interpolation if necessary. Indexed ==> nearest neighbor (*fast*).
entailment
def get_connected_client(self): """Gets a connected Client object. If max_size is reached, this method will block until a new client object is available. Returns: A Future object with connected Client instance as a result (or ClientError if there was a conne...
Gets a connected Client object. If max_size is reached, this method will block until a new client object is available. Returns: A Future object with connected Client instance as a result (or ClientError if there was a connection problem)
entailment
def get_client_nowait(self): """Gets a Client object (not necessary connected). If max_size is reached, this method will return None (and won't block). Returns: A Client instance (not necessary connected) as result (or None). """ if self.__sem is not None: ...
Gets a Client object (not necessary connected). If max_size is reached, this method will return None (and won't block). Returns: A Client instance (not necessary connected) as result (or None).
entailment
def connected_client(self): """Returns a ContextManagerFuture to be yielded in a with statement. Returns: A ContextManagerFuture object. Examples: >>> with (yield pool.connected_client()) as client: # client is a connected tornadis.Client instance ...
Returns a ContextManagerFuture to be yielded in a with statement. Returns: A ContextManagerFuture object. Examples: >>> with (yield pool.connected_client()) as client: # client is a connected tornadis.Client instance # it will be automati...
entailment
def release_client(self, client): """Releases a client object to the pool. Args: client: Client object. """ if isinstance(client, Client): if not self._is_expired_client(client): LOG.debug('Client is not expired. Adding back to pool') ...
Releases a client object to the pool. Args: client: Client object.
entailment
def destroy(self): """Disconnects all pooled client objects.""" while True: try: client = self.__pool.popleft() if isinstance(client, Client): client.disconnect() except IndexError: break
Disconnects all pooled client objects.
entailment
def preconnect(self, size=-1): """(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_si...
(pre)Connects some or all redis clients inside the pool. Args: size (int): number of redis clients to build and to connect (-1 means all clients if pool max_size > -1) Raises: ClientError: when size == -1 and pool max_size == -1
entailment
def setup_path(invoke_minversion=None): """Setup python search and add ``TASKS_VENDOR_DIR`` (if available).""" # print("INVOKE.tasks: setup_path") if not os.path.isdir(TASKS_VENDOR_DIR): print("SKIP: TASKS_VENDOR_DIR=%s is missing" % TASKS_VENDOR_DIR) return elif os.path.abspath(TASKS_VE...
Setup python search and add ``TASKS_VENDOR_DIR`` (if available).
entailment
def require_invoke_minversion(min_version, verbose=False): """Ensures that :mod:`invoke` has at the least the :param:`min_version`. Otherwise, :param min_version: Minimal acceptable invoke version (as string). :param verbose: Indicates if invoke.version should be shown. :raises: VersionRequirem...
Ensures that :mod:`invoke` has at the least the :param:`min_version`. Otherwise, :param min_version: Minimal acceptable invoke version (as string). :param verbose: Indicates if invoke.version should be shown. :raises: VersionRequirementError=SystemExit if requirement fails.
entailment
def matches_section(section_name): """Decorator for SectionSchema classes to define the mapping between a config section schema class and one or more config sections with matching name(s). .. sourcecode:: @matches_section("foo") class FooSchema(SectionSchema): pass ...
Decorator for SectionSchema classes to define the mapping between a config section schema class and one or more config sections with matching name(s). .. sourcecode:: @matches_section("foo") class FooSchema(SectionSchema): pass @matches_section(["bar", "baz.*"]) ...
entailment
def assign_param_names(cls=None, param_class=None): """Class decorator to assign parameter name to instances of :class:`Param`. .. sourcecode:: @assign_param_names class ConfigSectionSchema(object): alice = Param(type=str) bob = Param(type=str) assert ConfigS...
Class decorator to assign parameter name to instances of :class:`Param`. .. sourcecode:: @assign_param_names class ConfigSectionSchema(object): alice = Param(type=str) bob = Param(type=str) assert ConfigSectionSchema.alice.name == "alice" assert ConfigSec...
entailment
def select_params_from_section_schema(section_schema, param_class=Param, deep=False): """Selects the parameters of a config section schema. :param section_schema: Configuration file section schema to use. :return: Generator of params """ # pylint: disable=inva...
Selects the parameters of a config section schema. :param section_schema: Configuration file section schema to use. :return: Generator of params
entailment
def parse_config_section(config_section, section_schema): """Parse a config file section (INI file) by using its schema/description. .. sourcecode:: import configparser # -- NOTE: Use backport for Python2 import click from click_configfile import SectionSchema, Param, parse_config_...
Parse a config file section (INI file) by using its schema/description. .. sourcecode:: import configparser # -- NOTE: Use backport for Python2 import click from click_configfile import SectionSchema, Param, parse_config_section class ConfigSectionSchema(object): c...
entailment
def generate_configfile_names(config_files, config_searchpath=None): """Generates all configuration file name combinations to read. .. sourcecode:: # -- ALGORITHM: # First basenames/directories are prefered and override other files. for config_path in reversed(config_searchpath): ...
Generates all configuration file name combinations to read. .. sourcecode:: # -- ALGORITHM: # First basenames/directories are prefered and override other files. for config_path in reversed(config_searchpath): for config_basename in reversed(config_files): con...
entailment
def select_config_sections(configfile_sections, desired_section_patterns): """Select a subset of the sections in a configuration file by using a list of section names of list of section name patters (supporting :mod:`fnmatch` wildcards). :param configfile_sections: List of config section names (as stri...
Select a subset of the sections in a configuration file by using a list of section names of list of section name patters (supporting :mod:`fnmatch` wildcards). :param configfile_sections: List of config section names (as strings). :param desired_section_patterns: :return: List of selected section n...
entailment
def matches_section(cls, section_name, supported_section_names=None): """Indicates if this schema can be used for a config section by using the section name. :param section_name: Config section name to check. :return: True, if this schema can be applied to the config section. ...
Indicates if this schema can be used for a config section by using the section name. :param section_name: Config section name to check. :return: True, if this schema can be applied to the config section. :return: Fals, if this schema does not match the config section.
entailment
def collect_config_sections_from_schemas(cls, config_section_schemas=None): # pylint: disable=invalid-name """Derive support config section names from config section schemas. If no :param:`config_section_schemas` are provided, the schemas from this class are used (normally defined in the...
Derive support config section names from config section schemas. If no :param:`config_section_schemas` are provided, the schemas from this class are used (normally defined in the DerivedClass). :param config_section_schemas: List of config section schema classes. :return: List of confi...
entailment
def process_config_section(cls, config_section, storage): """Process the config section and store the extracted data in the param:`storage` (as outgoing param). """ # -- CONCEPT: # if not storage: # # -- INIT DATA: With default parts. # storage.update(dict...
Process the config section and store the extracted data in the param:`storage` (as outgoing param).
entailment
def select_config_schema_for(cls, section_name): """Select the config schema that matches the config section (by name). :param section_name: Config section name (as key). :return: Config section schmema to use (subclass of: SectionSchema). """ # pylint: disable=cell-var-from-...
Select the config schema that matches the config section (by name). :param section_name: Config section name (as key). :return: Config section schmema to use (subclass of: SectionSchema).
entailment
def select_storage_for(cls, section_name, storage): """Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: ...
Selects the data storage for a config section within the :param:`storage`. The primary config section is normally merged into the :param:`storage`. :param section_name: Config section (name) to process. :param storage: Data storage to use. :return: :param:`storage` or...
entailment
def clean(ctx, dry_run=False): """Cleanup temporary dirs/files to regain a clean state.""" # -- VARIATION-POINT 1: Allow user to override in configuration-file directories = ctx.clean.directories files = ctx.clean.files # -- VARIATION-POINT 2: Allow user to add more files/dirs to be removed. ex...
Cleanup temporary dirs/files to regain a clean state.
entailment
def clean_all(ctx, dry_run=False): """Clean up everything, even the precious stuff. NOTE: clean task is executed first. """ cleanup_dirs(ctx.clean_all.directories or [], dry_run=dry_run) cleanup_dirs(ctx.clean_all.extra_directories or [], dry_run=dry_run) cleanup_files(ctx.clean_all.files or [],...
Clean up everything, even the precious stuff. NOTE: clean task is executed first.
entailment
def clean_python(ctx, dry_run=False): """Cleanup python related files/dirs: *.pyc, *.pyo, ...""" # MAYBE NOT: "**/__pycache__" cleanup_dirs(["build", "dist", "*.egg-info", "**/__pycache__"], dry_run=dry_run) if not dry_run: ctx.run("py.cleanup") cleanup_files(["**/*.pyc", "*...
Cleanup python related files/dirs: *.pyc, *.pyo, ...
entailment
def cleanup_files(patterns, dry_run=False, workdir="."): """Remove files or files selected by file patterns. Skips removal if file does not exist. :param patterns: File patterns, like "**/*.pyc" (as list). :param dry_run: Dry-run mode indicator (as bool). :param workdir: Current work dir...
Remove files or files selected by file patterns. Skips removal if file does not exist. :param patterns: File patterns, like "**/*.pyc" (as list). :param dry_run: Dry-run mode indicator (as bool). :param workdir: Current work directory (default=".")
entailment
def path_glob(pattern, current_dir=None): """Use pathlib for ant-like patterns, like: "**/*.py" :param pattern: File/directory pattern to use (as string). :param current_dir: Current working directory (as Path, pathlib.Path, str) :return Resolved Path (as path.Path). """ if not current_di...
Use pathlib for ant-like patterns, like: "**/*.py" :param pattern: File/directory pattern to use (as string). :param current_dir: Current working directory (as Path, pathlib.Path, str) :return Resolved Path (as path.Path).
entailment
def stack_call(self, *args): """Stacks a redis command inside the object. The syntax is the same than the call() method a Client class. Args: *args: full redis command as variable length argument list. Examples: >>> pipeline = Pipeline() >>> pipelin...
Stacks a redis command inside the object. The syntax is the same than the call() method a Client class. Args: *args: full redis command as variable length argument list. Examples: >>> pipeline = Pipeline() >>> pipeline.stack_call("HSET", "key", "field", "va...
entailment
def connect(self): """Connects the object to the host:port. Returns: Future: a Future object with True as result if the connection process was ok. """ if self.is_connected() or self.is_connecting(): raise tornado.gen.Return(True) if self.u...
Connects the object to the host:port. Returns: Future: a Future object with True as result if the connection process was ok.
entailment
def disconnect(self): """Disconnects the object. Safe method (no exception, even if it's already disconnected or if there are some connection errors). """ if not self.is_connected() and not self.is_connecting(): return LOG.debug("disconnecting from %s...", se...
Disconnects the object. Safe method (no exception, even if it's already disconnected or if there are some connection errors).
entailment
def write(self, data): """Buffers some data to be sent to the host:port in a non blocking way. So the data is always buffered and not sent on the socket in a synchronous way. You can give a WriteBuffer as parameter. The internal Connection WriteBuffer will be extended with this...
Buffers some data to be sent to the host:port in a non blocking way. So the data is always buffered and not sent on the socket in a synchronous way. You can give a WriteBuffer as parameter. The internal Connection WriteBuffer will be extended with this one (without copying). A...
entailment
def surrogate_escape(error): """ Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only. """ chars = error.object[error.start:error.end] assert len(chars) == 1 val = ord(chars) val += 0xdc00 return __builtin__.unichr(val), error.end
Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only.
entailment
def _always_unicode(cls, path): """ Ensure the path as retrieved from a Python API, such as :func:`os.listdir`, is a proper Unicode string. """ if PY3 or isinstance(path, text_type): return path return path.decode(sys.getfilesystemencoding(), 'surrogateescape'...
Ensure the path as retrieved from a Python API, such as :func:`os.listdir`, is a proper Unicode string.
entailment
def namebase(self): """ The same as :meth:`name`, but with one file extension stripped off. For example, ``Path('/home/guido/python.tar.gz').name == 'python.tar.gz'``, but ``Path('/home/guido/python.tar.gz').namebase == 'python.tar'``. """ base, ext = self.module...
The same as :meth:`name`, but with one file extension stripped off. For example, ``Path('/home/guido/python.tar.gz').name == 'python.tar.gz'``, but ``Path('/home/guido/python.tar.gz').namebase == 'python.tar'``.
entailment
def listdir(self, pattern=None): """ D.listdir() -> List of items in this directory. Use :meth:`files` or :meth:`dirs` instead if you want a listing of just files or just subdirectories. The elements of the list are Path objects. With the optional `pattern` argument, this only...
D.listdir() -> List of items in this directory. Use :meth:`files` or :meth:`dirs` instead if you want a listing of just files or just subdirectories. The elements of the list are Path objects. With the optional `pattern` argument, this only lists items whose names match the gi...
entailment
def dirs(self, pattern=None): """ D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). With the optional `pattern` argument, this only lists directo...
D.dirs() -> List of this directory's subdirectories. The elements of the list are Path objects. This does not walk recursively into subdirectories (but see :meth:`walkdirs`). With the optional `pattern` argument, this only lists directories whose names match the given pattern. ...
entailment
def files(self, pattern=None): """ D.files() -> List of the files in this directory. The elements of the list are Path objects. This does not walk into subdirectories (see :meth:`walkfiles`). With the optional `pattern` argument, this only lists files whose names match the give...
D.files() -> List of the files in this directory. The elements of the list are Path objects. This does not walk into subdirectories (see :meth:`walkfiles`). With the optional `pattern` argument, this only lists files whose names match the given pattern. For example, ``d.files(...
entailment
def walkdirs(self, pattern=None, errors='strict'): """ D.walkdirs() -> iterator over subdirs, recursively. With the optional `pattern` argument, this yields only directories whose names match the given pattern. For example, ``mydir.walkdirs('*test')`` yields only directories wi...
D.walkdirs() -> iterator over subdirs, recursively. With the optional `pattern` argument, this yields only directories whose names match the given pattern. For example, ``mydir.walkdirs('*test')`` yields only directories with names ending in ``'test'``. The `errors=` keyword a...
entailment
def walkfiles(self, pattern=None, errors='strict'): """ D.walkfiles() -> iterator over files in D, recursively. The optional argument `pattern` limits the results to files with names that match the pattern. For example, ``mydir.walkfiles('*.tmp')`` yields only files with the ``.tmp`` ...
D.walkfiles() -> iterator over files in D, recursively. The optional argument `pattern` limits the results to files with names that match the pattern. For example, ``mydir.walkfiles('*.tmp')`` yields only files with the ``.tmp`` extension.
entailment
def open(self, *args, **kwargs): """ Open this file and return a corresponding :class:`file` object. Keyword arguments work as in :func:`io.open`. If the file cannot be opened, an :class:`~exceptions.OSError` is raised. """ with io_error_compat(): return io.open(sel...
Open this file and return a corresponding :class:`file` object. Keyword arguments work as in :func:`io.open`. If the file cannot be opened, an :class:`~exceptions.OSError` is raised.
entailment
def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two diff...
r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See be...
entailment
def write_lines(self, lines, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. ...
r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. See `linesep` below. `lines` - A list of strings. `encoding` - A Unicode encoding to use. This ap...
entailment
def mkdir_p(self, mode=0o777): """ Like :meth:`mkdir`, but does not raise an exception if the directory already exists. """ try: self.mkdir(mode) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.EEXIST: raise return ...
Like :meth:`mkdir`, but does not raise an exception if the directory already exists.
entailment
def makedirs_p(self, mode=0o777): """ Like :meth:`makedirs`, but does not raise an exception if the directory already exists. """ try: self.makedirs(mode) except OSError: _, e, _ = sys.exc_info() if e.errno != errno.EEXIST: raise ...
Like :meth:`makedirs`, but does not raise an exception if the directory already exists.
entailment
def rmdir_p(self): """ Like :meth:`rmdir`, but does not raise an exception if the directory is not empty or does not exist. """ try: self.rmdir() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST: ...
Like :meth:`rmdir`, but does not raise an exception if the directory is not empty or does not exist.
entailment
def removedirs_p(self): """ Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist. """ try: self.removedirs() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOTEMPTY and e.errno != errno...
Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist.
entailment
def remove_p(self): """ Like :meth:`remove`, but does not raise an exception if the file does not exist. """ try: self.unlink() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self
Like :meth:`remove`, but does not raise an exception if the file does not exist.
entailment
def rmtree_p(self): """ Like :meth:`rmtree`, but does not raise an exception if the directory does not exist. """ try: self.rmtree() except OSError: _, e, _ = sys.exc_info() if e.errno != errno.ENOENT: raise return self
Like :meth:`rmtree`, but does not raise an exception if the directory does not exist.
entailment
def merge_tree(self, dst, symlinks=False, *args, **kwargs): """ Copy entire contents of self to dst, overwriting existing contents in dst with those in self. If the additional keyword `update` is True, each `src` will only be copied if `dst` does not exist, or `src` is n...
Copy entire contents of self to dst, overwriting existing contents in dst with those in self. If the additional keyword `update` is True, each `src` will only be copied if `dst` does not exist, or `src` is newer than `dst`. Note that the technique employed stages the files in a...
entailment
def __gdal_dataset_default(self): """DiskReader implementation.""" if not os.path.exists(self.file_name): return None if os.path.splitext(self.file_name)[1].lower() not in self.file_types: raise RuntimeError('Filename %s does not have extension type %s.' % (self.file_nam...
DiskReader implementation.
entailment
def connect(self): """Connects the client object to redis. It's safe to use this method even if you are already connected. Note: this method is useless with autoconnect mode (default). Returns: a Future object with True as result if the connection was ok. """ ...
Connects the client object to redis. It's safe to use this method even if you are already connected. Note: this method is useless with autoconnect mode (default). Returns: a Future object with True as result if the connection was ok.
entailment
def _close_callback(self): """Callback called when redis closed the connection. The callback queue is emptied and we call each callback found with None or with an exception object to wake up blocked client. """ while True: try: callback = self.__callb...
Callback called when redis closed the connection. The callback queue is emptied and we call each callback found with None or with an exception object to wake up blocked client.
entailment
def _read_callback(self, data=None): """Callback called when some data are read on the socket. The buffer is given to the hiredis parser. If a reply is complete, we put the decoded reply to on the reply queue. Args: data (str): string (buffer) read on the socket. ""...
Callback called when some data are read on the socket. The buffer is given to the hiredis parser. If a reply is complete, we put the decoded reply to on the reply queue. Args: data (str): string (buffer) read on the socket.
entailment
def call(self, *args, **kwargs): """Calls a redis command and returns a Future of the reply. Args: *args: full redis command as variable length argument list or a Pipeline object (as a single argument). **kwargs: internal private options (do not use). Re...
Calls a redis command and returns a Future of the reply. Args: *args: full redis command as variable length argument list or a Pipeline object (as a single argument). **kwargs: internal private options (do not use). Returns: a Future with the decoded...
entailment
def async_call(self, *args, **kwargs): """Calls a redis command, waits for the reply and call a callback. Following options are available (not part of the redis command itself): - callback Function called (with the result as argument) when the result is available. If no...
Calls a redis command, waits for the reply and call a callback. Following options are available (not part of the redis command itself): - callback Function called (with the result as argument) when the result is available. If not set, the reply is silently discarded. In ...
entailment
def format_args_in_redis_protocol(*args): """Formats arguments into redis protocol... This function makes and returns a string/buffer corresponding to given arguments formated with the redis protocol. integer, text, string or binary types are automatically converted (using utf8 if necessary). ...
Formats arguments into redis protocol... This function makes and returns a string/buffer corresponding to given arguments formated with the redis protocol. integer, text, string or binary types are automatically converted (using utf8 if necessary). More informations about the protocol: http://red...
entailment
def _done_callback(self, wrapped): """Internal "done callback" to set the result of the object. The result of the object if forced by the wrapped future. So this internal callback must be called when the wrapped future is ready. Args: wrapped (Future): the wrapped Future ob...
Internal "done callback" to set the result of the object. The result of the object if forced by the wrapped future. So this internal callback must be called when the wrapped future is ready. Args: wrapped (Future): the wrapped Future object
entailment
def result(self): """The result method which returns a context manager Returns: ContextManager: The corresponding context manager """ if self.exception(): raise self.exception() # Otherwise return a context manager that cleans up after the block. ...
The result method which returns a context manager Returns: ContextManager: The corresponding context manager
entailment
def create_url(artist, song): """Create the URL in the LyricWikia format""" return (__BASE_URL__ + '/wiki/{artist}:{song}'.format(artist=urlize(artist), song=urlize(song)))
Create the URL in the LyricWikia format
entailment