repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
click-contrib/click-configfile
tasks/_vendor/pathlib.py
PurePath.with_name
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])
python
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])
[ "def", "with_name", "(", "self", ",", "name", ")", ":", "if", "not", "self", ".", "name", ":", "raise", "ValueError", "(", "\"%r has an empty name\"", "%", "(", "self", ",", ")", ")", "return", "self", ".", "_from_parsed_parts", "(", "self", ".", "_drv",...
Return a new path with the file name changed.
[ "Return", "a", "new", "path", "with", "the", "file", "name", "changed", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L773-L778
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
PurePath.with_suffix
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("Invalid suffix %r" % (suffix)) suffix = parts[0] if not suffix.startswith('.'): raise ValueError("Invalid suffix %r" % (suffix)) name = self.name if not name: raise ValueError("%r has an empty name" % (self,)) old_suffix = self.suffix if not old_suffix: name = name + suffix else: name = name[:-len(old_suffix)] + suffix return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
python
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("Invalid suffix %r" % (suffix)) suffix = parts[0] if not suffix.startswith('.'): raise ValueError("Invalid suffix %r" % (suffix)) name = self.name if not name: raise ValueError("%r has an empty name" % (self,)) old_suffix = self.suffix if not old_suffix: name = name + suffix else: name = name[:-len(old_suffix)] + suffix return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name])
[ "def", "with_suffix", "(", "self", ",", "suffix", ")", ":", "# XXX if suffix is None, should the current suffix be removed?", "drv", ",", "root", ",", "parts", "=", "self", ".", "_flavour", ".", "parse_parts", "(", "(", "suffix", ",", ")", ")", "if", "drv", "o...
Return a new path with the file suffix changed (or added, if none).
[ "Return", "a", "new", "path", "with", "the", "file", "suffix", "changed", "(", "or", "added", "if", "none", ")", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L780-L798
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path._raw_open
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)
python
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)
[ "def", "_raw_open", "(", "self", ",", "flags", ",", "mode", "=", "0o777", ")", ":", "return", "self", ".", "_accessor", ".", "open", "(", "self", ",", "flags", ",", "mode", ")" ]
Open the file pointed by this path and return a file descriptor, as os.open() does.
[ "Open", "the", "file", "pointed", "by", "this", "path", "and", "return", "a", "file", "descriptor", "as", "os", ".", "open", "()", "does", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L962-L967
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.iterdir
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 continue yield self._make_child_relpath(name)
python
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 continue yield self._make_child_relpath(name)
[ "def", "iterdir", "(", "self", ")", ":", "for", "name", "in", "self", ".", "_accessor", ".", "listdir", "(", "self", ")", ":", "if", "name", "in", "(", "'.'", ",", "'..'", ")", ":", "# Yielding a path object for these makes little sense", "continue", "yield"...
Iterate over the files in this directory. Does not yield any result for the special paths '.' and '..'.
[ "Iterate", "over", "the", "files", "in", "this", "directory", ".", "Does", "not", "yield", "any", "result", "for", "the", "special", "paths", ".", "and", "..", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L978-L986
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.absolute
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! if self.is_absolute(): return self # FIXME this must defer to the specific flavour (and, under Windows, # use nt._getfullpathname()) obj = self._from_parts([os.getcwd()] + self._parts, init=False) obj._init(template=self) return obj
python
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! if self.is_absolute(): return self # FIXME this must defer to the specific flavour (and, under Windows, # use nt._getfullpathname()) obj = self._from_parts([os.getcwd()] + self._parts, init=False) obj._init(template=self) return obj
[ "def", "absolute", "(", "self", ")", ":", "# XXX untested yet!", "if", "self", ".", "is_absolute", "(", ")", ":", "return", "self", "# FIXME this must defer to the specific flavour (and, under Windows,", "# use nt._getfullpathname())", "obj", "=", "self", ".", "_from_part...
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.
[ "Return", "an", "absolute", "version", "of", "this", "path", ".", "This", "function", "works", "even", "if", "the", "path", "doesn", "t", "point", "to", "anything", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1012-L1026
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.resolve
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 consistency, raise an error if # the path doesn't exist or is forbidden self.stat() s = str(self.absolute()) # Now we have no symlinks in the path, it's safe to normalize it. normed = self._flavour.pathmod.normpath(s) obj = self._from_parts((normed,), init=False) obj._init(template=self) return obj
python
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 consistency, raise an error if # the path doesn't exist or is forbidden self.stat() s = str(self.absolute()) # Now we have no symlinks in the path, it's safe to normalize it. normed = self._flavour.pathmod.normpath(s) obj = self._from_parts((normed,), init=False) obj._init(template=self) return obj
[ "def", "resolve", "(", "self", ")", ":", "s", "=", "self", ".", "_flavour", ".", "resolve", "(", "self", ")", "if", "s", "is", "None", ":", "# No symlink resolution => for consistency, raise an error if", "# the path doesn't exist or is forbidden", "self", ".", "sta...
Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).
[ "Make", "the", "path", "absolute", "resolving", "all", "symlinks", "on", "the", "way", "and", "also", "normalizing", "it", "(", "for", "example", "turning", "slashes", "into", "backslashes", "under", "Windows", ")", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1028-L1044
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.open
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, buffering, encoding, errors, newline, opener=self._opener) else: return io.open(str(self), mode, buffering, encoding, errors, newline)
python
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, buffering, encoding, errors, newline, opener=self._opener) else: return io.open(str(self), mode, buffering, encoding, errors, newline)
[ "def", "open", "(", "self", ",", "mode", "=", "'r'", ",", "buffering", "=", "-", "1", ",", "encoding", "=", "None", ",", "errors", "=", "None", ",", "newline", "=", "None", ")", ":", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "3", "...
Open the file pointed by this path and return a file object, as the built-in open() function does.
[ "Open", "the", "file", "pointed", "by", "this", "path", "and", "return", "a", "file", "object", "as", "the", "built", "-", "in", "open", "()", "function", "does", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1067-L1077
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.replace
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 later") self._accessor.replace(self, target)
python
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 later") self._accessor.replace(self, target)
[ "def", "replace", "(", "self", ",", "target", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "3", ")", ":", "raise", "NotImplementedError", "(", "\"replace() is only available \"", "\"with Python 3.3 and later\"", ")", "self", ".", "_accessor", ...
Rename this path to the given path, clobbering the existing destination if it exists.
[ "Rename", "this", "path", "to", "the", "given", "path", "clobbering", "the", "existing", "destination", "if", "it", "exists", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1152-L1160
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.symlink_to
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)
python
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)
[ "def", "symlink_to", "(", "self", ",", "target", ",", "target_is_directory", "=", "False", ")", ":", "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.
[ "Make", "this", "path", "a", "symlink", "pointing", "to", "the", "given", "path", ".", "Note", "the", "order", "of", "arguments", "(", "self", "target", ")", "is", "the", "reverse", "of", "os", ".", "symlink", "s", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1162-L1167
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.is_symlink
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
python
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
[ "def", "is_symlink", "(", "self", ")", ":", "try", ":", "return", "S_ISLNK", "(", "self", ".", "lstat", "(", ")", ".", "st_mode", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "ENOENT", ":", "raise", "# Path doesn't exist", ...
Whether this path is a symbolic link.
[ "Whether", "this", "path", "is", "a", "symbolic", "link", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1210-L1220
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.is_block_device
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 https://bitbucket.org/pitrou/pathlib/issue/12/) return False
python
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 https://bitbucket.org/pitrou/pathlib/issue/12/) return False
[ "def", "is_block_device", "(", "self", ")", ":", "try", ":", "return", "S_ISBLK", "(", "self", ".", "stat", "(", ")", ".", "st_mode", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "ENOENT", ":", "raise", "# Path doesn't exist...
Whether this path is a block device.
[ "Whether", "this", "path", "is", "a", "block", "device", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1222-L1233
train
click-contrib/click-configfile
tasks/_vendor/pathlib.py
Path.is_char_device
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 https://bitbucket.org/pitrou/pathlib/issue/12/) return False
python
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 https://bitbucket.org/pitrou/pathlib/issue/12/) return False
[ "def", "is_char_device", "(", "self", ")", ":", "try", ":", "return", "S_ISCHR", "(", "self", ".", "stat", "(", ")", ".", "st_mode", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "ENOENT", ":", "raise", "# Path doesn't exist ...
Whether this path is a character device.
[ "Whether", "this", "path", "is", "a", "character", "device", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/pathlib.py#L1235-L1246
train
creare-com/pydem
pydem/reader/my_types.py
grid_coords_from_corners
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, -(upper_left_corner.lon - lower_right_corner.lon) / float(size[1]), 0, upper_left_corner.lat, 0, -(upper_left_corner.lat - lower_right_corner.lat) / float(size[0])]) return GridCoordinates(geotransform=geotransform, wkt=upper_left_corner.wkt, y_size=size[0], x_size=size[1])
python
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, -(upper_left_corner.lon - lower_right_corner.lon) / float(size[1]), 0, upper_left_corner.lat, 0, -(upper_left_corner.lat - lower_right_corner.lat) / float(size[0])]) return GridCoordinates(geotransform=geotransform, wkt=upper_left_corner.wkt, y_size=size[0], x_size=size[1])
[ "def", "grid_coords_from_corners", "(", "upper_left_corner", ",", "lower_right_corner", ",", "size", ")", ":", "assert", "upper_left_corner", ".", "wkt", "==", "lower_right_corner", ".", "wkt", "geotransform", "=", "np", ".", "array", "(", "[", "upper_left_corner", ...
Points are the outer edges of the UL and LR pixels. Size is rows, columns. GC projection type is taken from Points.
[ "Points", "are", "the", "outer", "edges", "of", "the", "UL", "and", "LR", "pixels", ".", "Size", "is", "rows", "columns", ".", "GC", "projection", "type", "is", "taken", "from", "Points", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L150-L159
train
creare-com/pydem
pydem/reader/my_types.py
GridCoordinates.intersects
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. ax1, ay1, ax2, ay2 = self.ULC.lon, self.ULC.lat, self.LRC.lon, self.LRC.lat bx1, by1, bx2, by2 = ogc.ULC.lon, ogc.ULC.lat, ogc.LRC.lon, ogc.LRC.lat if ((ax1 <= bx2) and (ax2 >= bx1) and (ay1 >= by2) and (ay2 <= by1)): return True else: return False
python
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. ax1, ay1, ax2, ay2 = self.ULC.lon, self.ULC.lat, self.LRC.lon, self.LRC.lat bx1, by1, bx2, by2 = ogc.ULC.lon, ogc.ULC.lat, ogc.LRC.lon, ogc.LRC.lat if ((ax1 <= bx2) and (ax2 >= bx1) and (ay1 >= by2) and (ay2 <= by1)): return True else: return False
[ "def", "intersects", "(", "self", ",", "other_grid_coordinates", ")", ":", "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.
[ "returns", "True", "if", "the", "GC", "s", "overlap", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L191-L201
train
creare-com/pydem
pydem/reader/my_types.py
GridCoordinates.unique_str
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()'. The string should be filename-safe (no \/:*?"<>|). ..note::Because of length/readability restrictions, this fxn ignores wkt. Example output: "-180.000_0.250_0.000_90.000_0.000_-0.251_512_612_2013-05-21_12_32_52.945000" """ unique_str = "_".join(["%.3f" % f for f in self.geotransform] + ["%d" % d for d in self.x_size, self.y_size] ) if self.date is not None: unique_str += '_' + str(self.date) if self.time is not None: unique_str += '_' + str(self.time) return unique_str.replace(':', '_')
python
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()'. The string should be filename-safe (no \/:*?"<>|). ..note::Because of length/readability restrictions, this fxn ignores wkt. Example output: "-180.000_0.250_0.000_90.000_0.000_-0.251_512_612_2013-05-21_12_32_52.945000" """ unique_str = "_".join(["%.3f" % f for f in self.geotransform] + ["%d" % d for d in self.x_size, self.y_size] ) if self.date is not None: unique_str += '_' + str(self.date) if self.time is not None: unique_str += '_' + str(self.time) return unique_str.replace(':', '_')
[ "def", "unique_str", "(", "self", ")", ":", "unique_str", "=", "\"_\"", ".", "join", "(", "[", "\"%.3f\"", "%", "f", "for", "f", "in", "self", ".", "geotransform", "]", "+", "[", "\"%d\"", "%", "d", "for", "d", "in", "self", ".", "x_size", ",", "...
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-safe (no \/:*?"<>|). ..note::Because of length/readability restrictions, this fxn ignores wkt. Example output: "-180.000_0.250_0.000_90.000_0.000_-0.251_512_612_2013-05-21_12_32_52.945000"
[ "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", ".", "un...
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L205-L227
train
creare-com/pydem
pydem/reader/my_types.py
GridCoordinates._get_x_axis
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] + self.geotransform[1] * x_centers + self.geotransform[2] * y_centers)
python
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] + self.geotransform[1] * x_centers + self.geotransform[2] * y_centers)
[ "def", "_get_x_axis", "(", "self", ")", ":", "# 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",...
See http://www.gdal.org/gdal_datamodel.html for details.
[ "See", "http", ":", "//", "www", ".", "gdal", ".", "org", "/", "gdal_datamodel", ".", "html", "for", "details", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L244-L251
train
creare-com/pydem
pydem/reader/my_types.py
GridCoordinates._get_y_axis
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] + self.geotransform[4] * x_centers + self.geotransform[5] * y_centers)
python
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] + self.geotransform[4] * x_centers + self.geotransform[5] * y_centers)
[ "def", "_get_y_axis", "(", "self", ")", ":", "# 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",...
See http://www.gdal.org/gdal_datamodel.html for details.
[ "See", "http", ":", "//", "www", ".", "gdal", ".", "org", "/", "gdal_datamodel", ".", "html", "for", "details", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L254-L261
train
creare-com/pydem
pydem/reader/my_types.py
GridCoordinates.raster_to_projection_coords
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]]) arr = np.inner(gt, h_px_py) return arr[2], arr[1]
python
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]]) arr = np.inner(gt, h_px_py) return arr[2], arr[1]
[ "def", "raster_to_projection_coords", "(", "self", ",", "pixel_x", ",", "pixel_y", ")", ":", "h_px_py", "=", "np", ".", "array", "(", "[", "1", ",", "pixel_x", ",", "pixel_y", "]", ")", "gt", "=", "np", ".", "array", "(", "[", "[", "1", ",", "0", ...
Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for details.
[ "Use", "pixel", "centers", "when", "appropriate", ".", "See", "documentation", "for", "the", "GDAL", "function", "GetGeoTransform", "for", "details", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L265-L271
train
creare-com/pydem
pydem/reader/my_types.py
GridCoordinates.projection_to_raster_coords
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(tg, r_px_py)[1:]
python
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(tg, r_px_py)[1:]
[ "def", "projection_to_raster_coords", "(", "self", ",", "lat", ",", "lon", ")", ":", "r_px_py", "=", "np", ".", "array", "(", "[", "1", ",", "lon", ",", "lat", "]", ")", "tg", "=", "inv", "(", "np", ".", "array", "(", "[", "[", "1", ",", "0", ...
Returns pixel centers. See documentation for the GDAL function GetGeoTransform for details.
[ "Returns", "pixel", "centers", ".", "See", "documentation", "for", "the", "GDAL", "function", "GetGeoTransform", "for", "details", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L273-L278
train
creare-com/pydem
pydem/reader/my_types.py
AbstractDataLayer.reproject_to_grid_coordinates
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() rb = source_dataset.GetRasterBand(1) rb.SetNoDataValue(NO_DATA_VALUE) rb.WriteArray(np.ma.filled(self.raster_data, NO_DATA_VALUE)) gdal.ReprojectImage(source_dataset, dest_dataset, source_dataset.GetProjection(), dest_dataset.GetProjection(), interp) dest_layer = self.clone_traits() dest_layer.grid_coordinates = grid_coordinates rb = dest_dataset.GetRasterBand(1) dest_layer.raster_data = np.ma.masked_values(rb.ReadAsArray(), NO_DATA_VALUE) return dest_layer
python
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() rb = source_dataset.GetRasterBand(1) rb.SetNoDataValue(NO_DATA_VALUE) rb.WriteArray(np.ma.filled(self.raster_data, NO_DATA_VALUE)) gdal.ReprojectImage(source_dataset, dest_dataset, source_dataset.GetProjection(), dest_dataset.GetProjection(), interp) dest_layer = self.clone_traits() dest_layer.grid_coordinates = grid_coordinates rb = dest_dataset.GetRasterBand(1) dest_layer.raster_data = np.ma.masked_values(rb.ReadAsArray(), NO_DATA_VALUE) return dest_layer
[ "def", "reproject_to_grid_coordinates", "(", "self", ",", "grid_coordinates", ",", "interp", "=", "gdalconst", ".", "GRA_NearestNeighbour", ")", ":", "source_dataset", "=", "self", ".", "grid_coordinates", ".", "_as_gdal_dataset", "(", ")", "dest_dataset", "=", "gri...
Reprojects data in this layer to match that in the GridCoordinates object.
[ "Reprojects", "data", "in", "this", "layer", "to", "match", "that", "in", "the", "GridCoordinates", "object", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L351-L368
train
creare-com/pydem
pydem/reader/my_types.py
AbstractDataLayer.inpaint
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)
python
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)
[ "def", "inpaint", "(", "self", ")", ":", "import", "inpaint", "filled", "=", "inpaint", ".", "replace_nans", "(", "np", ".", "ma", ".", "filled", "(", "self", ".", "raster_data", ",", "np", ".", "NAN", ")", ".", "astype", "(", "np", ".", "float32", ...
Replace masked-out elements in an array using an iterative image inpainting algorithm.
[ "Replace", "masked", "-", "out", "elements", "in", "an", "array", "using", "an", "iterative", "image", "inpainting", "algorithm", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L379-L384
train
creare-com/pydem
pydem/reader/my_types.py
AbstractRasterDataLayer.interp_value
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 self.raster_data[round(py), round(px)] else: # from scipy.interpolate import interp2d # f_interp = interp2d(self.grid_coordinates.x_axis, self.grid_coordinates.y_axis, self.raster_data, bounds_error=True) # return f_interp(lon, lat)[0] from scipy.ndimage import map_coordinates ret = map_coordinates(self.raster_data, [[py], [px]], order=1) # linear interp return ret[0]
python
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 self.raster_data[round(py), round(px)] else: # from scipy.interpolate import interp2d # f_interp = interp2d(self.grid_coordinates.x_axis, self.grid_coordinates.y_axis, self.raster_data, bounds_error=True) # return f_interp(lon, lat)[0] from scipy.ndimage import map_coordinates ret = map_coordinates(self.raster_data, [[py], [px]], order=1) # linear interp return ret[0]
[ "def", "interp_value", "(", "self", ",", "lat", ",", "lon", ",", "indexed", "=", "False", ")", ":", "(", "px", ",", "py", ")", "=", "self", ".", "grid_coordinates", ".", "projection_to_raster_coords", "(", "lat", ",", "lon", ")", "if", "indexed", ":", ...
Lookup a pixel value in the raster data, performing linear interpolation if necessary. Indexed ==> nearest neighbor (*fast*).
[ "Lookup", "a", "pixel", "value", "in", "the", "raster", "data", "performing", "linear", "interpolation", "if", "necessary", ".", "Indexed", "==", ">", "nearest", "neighbor", "(", "*", "fast", "*", ")", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/my_types.py#L445-L457
train
thefab/tornadis
tornadis/pool.py
ClientPool.get_connected_client
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 connection problem) """ if self.__sem is not None: yield self.__sem.acquire() client = None newly_created, client = self._get_client_from_pool_or_make_it() if newly_created: res = yield client.connect() if not res: LOG.warning("can't connect to %s", client.title) raise tornado.gen.Return( ClientError("can't connect to %s" % client.title)) raise tornado.gen.Return(client)
python
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 connection problem) """ if self.__sem is not None: yield self.__sem.acquire() client = None newly_created, client = self._get_client_from_pool_or_make_it() if newly_created: res = yield client.connect() if not res: LOG.warning("can't connect to %s", client.title) raise tornado.gen.Return( ClientError("can't connect to %s" % client.title)) raise tornado.gen.Return(client)
[ "def", "get_connected_client", "(", "self", ")", ":", "if", "self", ".", "__sem", "is", "not", "None", ":", "yield", "self", ".", "__sem", ".", "acquire", "(", ")", "client", "=", "None", "newly_created", ",", "client", "=", "self", ".", "_get_client_fro...
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)
[ "Gets", "a", "connected", "Client", "object", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L75-L95
train
thefab/tornadis
tornadis/pool.py
ClientPool.get_client_nowait
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: if self.__sem._value == 0: return None self.__sem.acquire() _, client = self._get_client_from_pool_or_make_it() return client
python
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: if self.__sem._value == 0: return None self.__sem.acquire() _, client = self._get_client_from_pool_or_make_it() return client
[ "def", "get_client_nowait", "(", "self", ")", ":", "if", "self", ".", "__sem", "is", "not", "None", ":", "if", "self", ".", "__sem", ".", "_value", "==", "0", ":", "return", "None", "self", ".", "__sem", ".", "acquire", "(", ")", "_", ",", "client"...
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).
[ "Gets", "a", "Client", "object", "(", "not", "necessary", "connected", ")", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L97-L110
train
thefab/tornadis
tornadis/pool.py
ClientPool.connected_client
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 # it will be automatically released to the pool thanks to # the "with" keyword reply = yield client.call("PING") """ future = self.get_connected_client() cb = functools.partial(self._connected_client_release_cb, future) return ContextManagerFuture(future, cb)
python
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 # it will be automatically released to the pool thanks to # the "with" keyword reply = yield client.call("PING") """ future = self.get_connected_client() cb = functools.partial(self._connected_client_release_cb, future) return ContextManagerFuture(future, cb)
[ "def", "connected_client", "(", "self", ")", ":", "future", "=", "self", ".", "get_connected_client", "(", ")", "cb", "=", "functools", ".", "partial", "(", "self", ".", "_connected_client_release_cb", ",", "future", ")", "return", "ContextManagerFuture", "(", ...
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 automatically released to the pool thanks to # the "with" keyword reply = yield client.call("PING")
[ "Returns", "a", "ContextManagerFuture", "to", "be", "yielded", "in", "a", "with", "statement", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L132-L147
train
thefab/tornadis
tornadis/pool.py
ClientPool.release_client
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') self.__pool.append(client) elif client.is_connected(): LOG.debug('Client is expired and connected. Disconnecting') client.disconnect() if self.__sem is not None: self.__sem.release()
python
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') self.__pool.append(client) elif client.is_connected(): LOG.debug('Client is expired and connected. Disconnecting') client.disconnect() if self.__sem is not None: self.__sem.release()
[ "def", "release_client", "(", "self", ",", "client", ")", ":", "if", "isinstance", "(", "client", ",", "Client", ")", ":", "if", "not", "self", ".", "_is_expired_client", "(", "client", ")", ":", "LOG", ".", "debug", "(", "'Client is not expired. Adding back...
Releases a client object to the pool. Args: client: Client object.
[ "Releases", "a", "client", "object", "to", "the", "pool", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L153-L167
train
thefab/tornadis
tornadis/pool.py
ClientPool.destroy
def destroy(self): """Disconnects all pooled client objects.""" while True: try: client = self.__pool.popleft() if isinstance(client, Client): client.disconnect() except IndexError: break
python
def destroy(self): """Disconnects all pooled client objects.""" while True: try: client = self.__pool.popleft() if isinstance(client, Client): client.disconnect() except IndexError: break
[ "def", "destroy", "(", "self", ")", ":", "while", "True", ":", "try", ":", "client", "=", "self", ".", "__pool", ".", "popleft", "(", ")", "if", "isinstance", "(", "client", ",", "Client", ")", ":", "client", ".", "disconnect", "(", ")", "except", ...
Disconnects all pooled client objects.
[ "Disconnects", "all", "pooled", "client", "objects", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L169-L177
train
thefab/tornadis
tornadis/pool.py
ClientPool.preconnect
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_size == -1 """ if size == -1 and self.max_size == -1: raise ClientError("size=-1 not allowed with pool max_size=-1") limit = min(size, self.max_size) if size != -1 else self.max_size clients = yield [self.get_connected_client() for _ in range(0, limit)] for client in clients: self.release_client(client)
python
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_size == -1 """ if size == -1 and self.max_size == -1: raise ClientError("size=-1 not allowed with pool max_size=-1") limit = min(size, self.max_size) if size != -1 else self.max_size clients = yield [self.get_connected_client() for _ in range(0, limit)] for client in clients: self.release_client(client)
[ "def", "preconnect", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "-", "1", "and", "self", ".", "max_size", "==", "-", "1", ":", "raise", "ClientError", "(", "\"size=-1 not allowed with pool max_size=-1\"", ")", "limit", "=", "m...
(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
[ "(", "pre", ")", "Connects", "some", "or", "all", "redis", "clients", "inside", "the", "pool", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pool.py#L180-L195
train
click-contrib/click-configfile
tasks/_setup.py
setup_path
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_VENDOR_DIR) in sys.path: # -- SETUP ALREADY DONE: # return pass use_vendor_bundles = os.environ.get("INVOKE_TASKS_USE_VENDOR_BUNDLES", "no") if need_vendor_bundles(invoke_minversion): use_vendor_bundles = "yes" if use_vendor_bundles == "yes": syspath_insert(0, os.path.abspath(TASKS_VENDOR_DIR)) if setup_path_for_bundle(INVOKE_BUNDLE, pos=1): import invoke bundle_path = os.path.relpath(INVOKE_BUNDLE, os.getcwd()) print("USING: %s (version: %s)" % (bundle_path, invoke.__version__)) else: # -- BEST-EFFORT: May rescue something syspath_append(os.path.abspath(TASKS_VENDOR_DIR)) setup_path_for_bundle(INVOKE_BUNDLE, pos=len(sys.path)) if DEBUG_SYSPATH: for index, p in enumerate(sys.path): print(" %d. %s" % (index, p))
python
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_VENDOR_DIR) in sys.path: # -- SETUP ALREADY DONE: # return pass use_vendor_bundles = os.environ.get("INVOKE_TASKS_USE_VENDOR_BUNDLES", "no") if need_vendor_bundles(invoke_minversion): use_vendor_bundles = "yes" if use_vendor_bundles == "yes": syspath_insert(0, os.path.abspath(TASKS_VENDOR_DIR)) if setup_path_for_bundle(INVOKE_BUNDLE, pos=1): import invoke bundle_path = os.path.relpath(INVOKE_BUNDLE, os.getcwd()) print("USING: %s (version: %s)" % (bundle_path, invoke.__version__)) else: # -- BEST-EFFORT: May rescue something syspath_append(os.path.abspath(TASKS_VENDOR_DIR)) setup_path_for_bundle(INVOKE_BUNDLE, pos=len(sys.path)) if DEBUG_SYSPATH: for index, p in enumerate(sys.path): print(" %d. %s" % (index, p))
[ "def", "setup_path", "(", "invoke_minversion", "=", "None", ")", ":", "# print(\"INVOKE.tasks: setup_path\")", "if", "not", "os", ".", "path", ".", "isdir", "(", "TASKS_VENDOR_DIR", ")", ":", "print", "(", "\"SKIP: TASKS_VENDOR_DIR=%s is missing\"", "%", "TASKS_VENDOR...
Setup python search and add ``TASKS_VENDOR_DIR`` (if available).
[ "Setup", "python", "search", "and", "add", "TASKS_VENDOR_DIR", "(", "if", "available", ")", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_setup.py#L30-L58
train
click-contrib/click-configfile
tasks/_setup.py
require_invoke_minversion
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: VersionRequirementError=SystemExit if requirement fails. """ # -- REQUIRES: sys.path is setup and contains invoke try: import invoke invoke_version = invoke.__version__ except ImportError: invoke_version = "__NOT_INSTALLED" if invoke_version < min_version: message = "REQUIRE: invoke.version >= %s (but was: %s)" % \ (min_version, invoke_version) message += "\nUSE: pip install invoke>=%s" % min_version raise VersionRequirementError(message) INVOKE_VERSION = os.environ.get("INVOKE_VERSION", None) if verbose and not INVOKE_VERSION: os.environ["INVOKE_VERSION"] = invoke_version print("USING: invoke.version=%s" % invoke_version)
python
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: VersionRequirementError=SystemExit if requirement fails. """ # -- REQUIRES: sys.path is setup and contains invoke try: import invoke invoke_version = invoke.__version__ except ImportError: invoke_version = "__NOT_INSTALLED" if invoke_version < min_version: message = "REQUIRE: invoke.version >= %s (but was: %s)" % \ (min_version, invoke_version) message += "\nUSE: pip install invoke>=%s" % min_version raise VersionRequirementError(message) INVOKE_VERSION = os.environ.get("INVOKE_VERSION", None) if verbose and not INVOKE_VERSION: os.environ["INVOKE_VERSION"] = invoke_version print("USING: invoke.version=%s" % invoke_version)
[ "def", "require_invoke_minversion", "(", "min_version", ",", "verbose", "=", "False", ")", ":", "# -- REQUIRES: sys.path is setup and contains invoke", "try", ":", "import", "invoke", "invoke_version", "=", "invoke", ".", "__version__", "except", "ImportError", ":", "in...
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.
[ "Ensures", "that", ":", "mod", ":", "invoke", "has", "at", "the", "least", "the", ":", "param", ":", "min_version", ".", "Otherwise" ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_setup.py#L61-L85
train
click-contrib/click-configfile
click_configfile.py
matches_section
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 @matches_section(["bar", "baz.*"]) class BarAndBazSchema(SectionSchema): pass .. sourcecode:: ini # -- FILE: *.ini [foo] # USE: FooSchema ... [bar] # USE: BarAndBazSchema ... [baz.alice] # USE: BarAndBazSchema ... """ section_names = section_name if isinstance(section_name, six.string_types): section_names = [section_name] elif not isinstance(section_name, (list, tuple)): raise ValueError("%r (expected: string, strings)" % section_name) def decorator(cls): class_section_names = getattr(cls, "section_names", None) if class_section_names is None: cls.section_names = list(section_names) else: # -- BETTER SUPPORT: For multiple decorators # @matches_section("foo") # @matches_section("bar.*") # class Example(SectionSchema): # pass # assert Example.section_names == ["foo", "bar.*"] approved = [name for name in section_names if name not in cls.section_names] cls.section_names = approved + cls.section_names return cls return decorator
python
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 @matches_section(["bar", "baz.*"]) class BarAndBazSchema(SectionSchema): pass .. sourcecode:: ini # -- FILE: *.ini [foo] # USE: FooSchema ... [bar] # USE: BarAndBazSchema ... [baz.alice] # USE: BarAndBazSchema ... """ section_names = section_name if isinstance(section_name, six.string_types): section_names = [section_name] elif not isinstance(section_name, (list, tuple)): raise ValueError("%r (expected: string, strings)" % section_name) def decorator(cls): class_section_names = getattr(cls, "section_names", None) if class_section_names is None: cls.section_names = list(section_names) else: # -- BETTER SUPPORT: For multiple decorators # @matches_section("foo") # @matches_section("bar.*") # class Example(SectionSchema): # pass # assert Example.section_names == ["foo", "bar.*"] approved = [name for name in section_names if name not in cls.section_names] cls.section_names = approved + cls.section_names return cls return decorator
[ "def", "matches_section", "(", "section_name", ")", ":", "section_names", "=", "section_name", "if", "isinstance", "(", "section_name", ",", "six", ".", "string_types", ")", ":", "section_names", "=", "[", "section_name", "]", "elif", "not", "isinstance", "(", ...
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.*"]) class BarAndBazSchema(SectionSchema): pass .. sourcecode:: ini # -- FILE: *.ini [foo] # USE: FooSchema ... [bar] # USE: BarAndBazSchema ... [baz.alice] # USE: BarAndBazSchema ...
[ "Decorator", "for", "SectionSchema", "classes", "to", "define", "the", "mapping", "between", "a", "config", "section", "schema", "class", "and", "one", "or", "more", "config", "sections", "with", "matching", "name", "(", "s", ")", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L30-L78
train
click-contrib/click-configfile
click_configfile.py
assign_param_names
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 ConfigSectionSchema.alice.name == "alice" assert ConfigSectionSchema.bob.name == "bob" .. sourcecode:: # -- NESTED ASSIGN: Covers also nested SectionSchema subclasses. @assign_param_names class ConfigSectionSchema(object): class Foo(SectionSchema): alice = Param(type=str) bob = Param(type=str) assert ConfigSectionSchema.Foo.alice.name == "alice" assert ConfigSectionSchema.Foo.bob.name == "bob" """ if param_class is None: param_class = Param def decorate_class(cls): for name, value in select_params_from_section_schema(cls, param_class, deep=True): # -- ANNOTATE PARAM: By assigning its name if not value.name: value.name = name return cls # -- DECORATOR LOGIC: if cls is None: # -- CASE: @assign_param_names # -- CASE: @assign_param_names(...) return decorate_class else: # -- CASE: @assign_param_names class X: ... # -- CASE: assign_param_names(my_class) # -- CASE: my_class = assign_param_names(my_class) return decorate_class(cls)
python
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 ConfigSectionSchema.alice.name == "alice" assert ConfigSectionSchema.bob.name == "bob" .. sourcecode:: # -- NESTED ASSIGN: Covers also nested SectionSchema subclasses. @assign_param_names class ConfigSectionSchema(object): class Foo(SectionSchema): alice = Param(type=str) bob = Param(type=str) assert ConfigSectionSchema.Foo.alice.name == "alice" assert ConfigSectionSchema.Foo.bob.name == "bob" """ if param_class is None: param_class = Param def decorate_class(cls): for name, value in select_params_from_section_schema(cls, param_class, deep=True): # -- ANNOTATE PARAM: By assigning its name if not value.name: value.name = name return cls # -- DECORATOR LOGIC: if cls is None: # -- CASE: @assign_param_names # -- CASE: @assign_param_names(...) return decorate_class else: # -- CASE: @assign_param_names class X: ... # -- CASE: assign_param_names(my_class) # -- CASE: my_class = assign_param_names(my_class) return decorate_class(cls)
[ "def", "assign_param_names", "(", "cls", "=", "None", ",", "param_class", "=", "None", ")", ":", "if", "param_class", "is", "None", ":", "param_class", "=", "Param", "def", "decorate_class", "(", "cls", ")", ":", "for", "name", ",", "value", "in", "selec...
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 ConfigSectionSchema.bob.name == "bob" .. sourcecode:: # -- NESTED ASSIGN: Covers also nested SectionSchema subclasses. @assign_param_names class ConfigSectionSchema(object): class Foo(SectionSchema): alice = Param(type=str) bob = Param(type=str) assert ConfigSectionSchema.Foo.alice.name == "alice" assert ConfigSectionSchema.Foo.bob.name == "bob"
[ "Class", "decorator", "to", "assign", "parameter", "name", "to", "instances", "of", ":", "class", ":", "Param", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L81-L126
train
click-contrib/click-configfile
click_configfile.py
select_params_from_section_schema
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=invalid-name for name, value in inspect.getmembers(section_schema): if name.startswith("__") or value is None: continue # pragma: no cover elif inspect.isclass(value) and deep: # -- CASE: class => SELF-CALL (recursively). # pylint: disable= bad-continuation cls = value for name, value in select_params_from_section_schema(cls, param_class=param_class, deep=True): yield (name, value) elif isinstance(value, param_class): yield (name, value)
python
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=invalid-name for name, value in inspect.getmembers(section_schema): if name.startswith("__") or value is None: continue # pragma: no cover elif inspect.isclass(value) and deep: # -- CASE: class => SELF-CALL (recursively). # pylint: disable= bad-continuation cls = value for name, value in select_params_from_section_schema(cls, param_class=param_class, deep=True): yield (name, value) elif isinstance(value, param_class): yield (name, value)
[ "def", "select_params_from_section_schema", "(", "section_schema", ",", "param_class", "=", "Param", ",", "deep", "=", "False", ")", ":", "# pylint: disable=invalid-name", "for", "name", ",", "value", "in", "inspect", ".", "getmembers", "(", "section_schema", ")", ...
Selects the parameters of a config section schema. :param section_schema: Configuration file section schema to use. :return: Generator of params
[ "Selects", "the", "parameters", "of", "a", "config", "section", "schema", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L203-L222
train
click-contrib/click-configfile
click_configfile.py
parse_config_section
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_section class ConfigSectionSchema(object): class Foo(SectionSchema): name = Param(type=str) flag = Param(type=bool) numbers = Param(type=int, multiple=True) filenames = Param(type=click.Path(), multiple=True) parser = configparser.ConfigParser() parser.read(["foo.ini"]) config_section = parser["foo"] data = parse_config_section(config_section, ConfigSectionSchema.Foo) # -- FAILS WITH: click.BadParameter if conversion errors occur. .. sourcecode:: ini # -- FILE: foo.ini [foo] name = Alice flag = yes # true, false, yes, no (case-insensitive) numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt :param config_section: Config section to parse :param section_schema: Schema/description of config section (w/ Param). :return: Retrieved data, values converted to described types. :raises: click.BadParameter, if conversion error occurs. """ storage = {} for name, param in select_params_from_section_schema(section_schema): value = config_section.get(name, None) if value is None: if param.default is None: continue value = param.default else: value = param.parse(value) # -- DIAGNOSTICS: # print(" %s = %s" % (name, repr(value))) storage[name] = value return storage
python
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_section class ConfigSectionSchema(object): class Foo(SectionSchema): name = Param(type=str) flag = Param(type=bool) numbers = Param(type=int, multiple=True) filenames = Param(type=click.Path(), multiple=True) parser = configparser.ConfigParser() parser.read(["foo.ini"]) config_section = parser["foo"] data = parse_config_section(config_section, ConfigSectionSchema.Foo) # -- FAILS WITH: click.BadParameter if conversion errors occur. .. sourcecode:: ini # -- FILE: foo.ini [foo] name = Alice flag = yes # true, false, yes, no (case-insensitive) numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt :param config_section: Config section to parse :param section_schema: Schema/description of config section (w/ Param). :return: Retrieved data, values converted to described types. :raises: click.BadParameter, if conversion error occurs. """ storage = {} for name, param in select_params_from_section_schema(section_schema): value = config_section.get(name, None) if value is None: if param.default is None: continue value = param.default else: value = param.parse(value) # -- DIAGNOSTICS: # print(" %s = %s" % (name, repr(value))) storage[name] = value return storage
[ "def", "parse_config_section", "(", "config_section", ",", "section_schema", ")", ":", "storage", "=", "{", "}", "for", "name", ",", "param", "in", "select_params_from_section_schema", "(", "section_schema", ")", ":", "value", "=", "config_section", ".", "get", ...
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): class Foo(SectionSchema): name = Param(type=str) flag = Param(type=bool) numbers = Param(type=int, multiple=True) filenames = Param(type=click.Path(), multiple=True) parser = configparser.ConfigParser() parser.read(["foo.ini"]) config_section = parser["foo"] data = parse_config_section(config_section, ConfigSectionSchema.Foo) # -- FAILS WITH: click.BadParameter if conversion errors occur. .. sourcecode:: ini # -- FILE: foo.ini [foo] name = Alice flag = yes # true, false, yes, no (case-insensitive) numbers = 1 4 9 16 25 filenames = foo/xxx.txt bar/baz/zzz.txt :param config_section: Config section to parse :param section_schema: Schema/description of config section (w/ Param). :return: Retrieved data, values converted to described types. :raises: click.BadParameter, if conversion error occurs.
[ "Parse", "a", "config", "file", "section", "(", "INI", "file", ")", "by", "using", "its", "schema", "/", "description", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L225-L274
train
click-contrib/click-configfile
click_configfile.py
generate_configfile_names
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): for config_basename in reversed(config_files): config_fname = os.path.join(config_path, config_basename) if os.path.isfile(config_fname): yield config_fname :param config_files: List of config file basenames. :param config_searchpath: List of directories to look for config files. :return: List of available configuration file names (as generator) """ if config_searchpath is None: config_searchpath = ["."] for config_path in reversed(config_searchpath): for config_basename in reversed(config_files): config_fname = os.path.join(config_path, config_basename) if os.path.isfile(config_fname): # MAYBE: yield os.path.normpath(config_fname) yield config_fname
python
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): for config_basename in reversed(config_files): config_fname = os.path.join(config_path, config_basename) if os.path.isfile(config_fname): yield config_fname :param config_files: List of config file basenames. :param config_searchpath: List of directories to look for config files. :return: List of available configuration file names (as generator) """ if config_searchpath is None: config_searchpath = ["."] for config_path in reversed(config_searchpath): for config_basename in reversed(config_files): config_fname = os.path.join(config_path, config_basename) if os.path.isfile(config_fname): # MAYBE: yield os.path.normpath(config_fname) yield config_fname
[ "def", "generate_configfile_names", "(", "config_files", ",", "config_searchpath", "=", "None", ")", ":", "if", "config_searchpath", "is", "None", ":", "config_searchpath", "=", "[", "\".\"", "]", "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): config_fname = os.path.join(config_path, config_basename) if os.path.isfile(config_fname): yield config_fname :param config_files: List of config file basenames. :param config_searchpath: List of directories to look for config files. :return: List of available configuration file names (as generator)
[ "Generates", "all", "configuration", "file", "name", "combinations", "to", "read", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L280-L305
train
click-contrib/click-configfile
click_configfile.py
select_config_sections
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 strings). :param desired_section_patterns: :return: List of selected section names or empty list (as generator). """ for section_name in configfile_sections: for desired_section_pattern in desired_section_patterns: if fnmatch(section_name, desired_section_pattern): yield section_name
python
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 strings). :param desired_section_patterns: :return: List of selected section names or empty list (as generator). """ for section_name in configfile_sections: for desired_section_pattern in desired_section_patterns: if fnmatch(section_name, desired_section_pattern): yield section_name
[ "def", "select_config_sections", "(", "configfile_sections", ",", "desired_section_patterns", ")", ":", "for", "section_name", "in", "configfile_sections", ":", "for", "desired_section_pattern", "in", "desired_section_patterns", ":", "if", "fnmatch", "(", "section_name", ...
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 names or empty list (as generator).
[ "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", ")", ...
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L308-L320
train
click-contrib/click-configfile
click_configfile.py
SectionSchema.matches_section
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. :return: Fals, if this schema does not match the config section. """ if supported_section_names is None: supported_section_names = getattr(cls, "section_names", None) # pylint: disable=invalid-name for supported_section_name_or_pattern in supported_section_names: if fnmatch(section_name, supported_section_name_or_pattern): return True # -- OTHERWISE: return False
python
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. :return: Fals, if this schema does not match the config section. """ if supported_section_names is None: supported_section_names = getattr(cls, "section_names", None) # pylint: disable=invalid-name for supported_section_name_or_pattern in supported_section_names: if fnmatch(section_name, supported_section_name_or_pattern): return True # -- OTHERWISE: return False
[ "def", "matches_section", "(", "cls", ",", "section_name", ",", "supported_section_names", "=", "None", ")", ":", "if", "supported_section_names", "is", "None", ":", "supported_section_names", "=", "getattr", "(", "cls", ",", "\"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. :return: Fals, if this schema does not match the config section.
[ "Indicates", "if", "this", "schema", "can", "be", "used", "for", "a", "config", "section", "by", "using", "the", "section", "name", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L137-L153
train
click-contrib/click-configfile
click_configfile.py
ConfigFileReader.collect_config_sections_from_schemas
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 DerivedClass). :param config_section_schemas: List of config section schema classes. :return: List of config section names or name patterns (as string). """ if config_section_schemas is None: config_section_schemas = cls.config_section_schemas collected = [] for schema in config_section_schemas: collected.extend(schema.section_names) # -- MAYBE BETTER: # for name in schema.section_names: # if name not in collected: # collected.append(name) return collected
python
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 DerivedClass). :param config_section_schemas: List of config section schema classes. :return: List of config section names or name patterns (as string). """ if config_section_schemas is None: config_section_schemas = cls.config_section_schemas collected = [] for schema in config_section_schemas: collected.extend(schema.section_names) # -- MAYBE BETTER: # for name in schema.section_names: # if name not in collected: # collected.append(name) return collected
[ "def", "collect_config_sections_from_schemas", "(", "cls", ",", "config_section_schemas", "=", "None", ")", ":", "# pylint: disable=invalid-name", "if", "config_section_schemas", "is", "None", ":", "config_section_schemas", "=", "cls", ".", "config_section_schemas", "collec...
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 config section names or name patterns (as string).
[ "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", "i...
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L405-L424
train
click-contrib/click-configfile
click_configfile.py
ConfigFileReader.process_config_section
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(_PERSONS={})) schema = cls.select_config_schema_for(config_section.name) if not schema: message = "No schema found for: section=%s" raise LookupError(message % config_section.name) # -- PARSE AND STORE CONFIG SECTION: section_storage = cls.select_storage_for(config_section.name, storage) section_data = parse_config_section(config_section, schema) section_storage.update(section_data)
python
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(_PERSONS={})) schema = cls.select_config_schema_for(config_section.name) if not schema: message = "No schema found for: section=%s" raise LookupError(message % config_section.name) # -- PARSE AND STORE CONFIG SECTION: section_storage = cls.select_storage_for(config_section.name, storage) section_data = parse_config_section(config_section, schema) section_storage.update(section_data)
[ "def", "process_config_section", "(", "cls", ",", "config_section", ",", "storage", ")", ":", "# -- CONCEPT:", "# if not storage:", "# # -- INIT DATA: With default parts.", "# storage.update(dict(_PERSONS={}))", "schema", "=", "cls", ".", "select_config_schema_for", "("...
Process the config section and store the extracted data in the param:`storage` (as outgoing param).
[ "Process", "the", "config", "section", "and", "store", "the", "extracted", "data", "in", "the", "param", ":", "storage", "(", "as", "outgoing", "param", ")", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L429-L446
train
click-contrib/click-configfile
click_configfile.py
ConfigFileReader.select_config_schema_for
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-loop, redefined-outer-name for section_schema in cls.config_section_schemas: schema_matches = getattr(section_schema, "matches_section", None) if schema_matches is None: # -- OTHER SCHEMA CLASS: Reuse SectionSchema functionality. schema_matches = lambda name: SectionSchema.matches_section( name, section_schema.section_names) if schema_matches(section_name): return section_schema return None
python
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-loop, redefined-outer-name for section_schema in cls.config_section_schemas: schema_matches = getattr(section_schema, "matches_section", None) if schema_matches is None: # -- OTHER SCHEMA CLASS: Reuse SectionSchema functionality. schema_matches = lambda name: SectionSchema.matches_section( name, section_schema.section_names) if schema_matches(section_name): return section_schema return None
[ "def", "select_config_schema_for", "(", "cls", ",", "section_name", ")", ":", "# pylint: disable=cell-var-from-loop, redefined-outer-name", "for", "section_schema", "in", "cls", ".", "config_section_schemas", ":", "schema_matches", "=", "getattr", "(", "section_schema", ","...
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).
[ "Select", "the", "config", "schema", "that", "matches", "the", "config", "section", "(", "by", "name", ")", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L449-L465
train
click-contrib/click-configfile
click_configfile.py
ConfigFileReader.select_storage_for
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: Data storage to use. :return: :param:`storage` or a part of it (as section storage). """ section_storage = storage storage_name = cls.get_storage_name_for(section_name) if storage_name: section_storage = storage.get(storage_name, None) if section_storage is None: section_storage = storage[storage_name] = dict() return section_storage
python
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: Data storage to use. :return: :param:`storage` or a part of it (as section storage). """ section_storage = storage storage_name = cls.get_storage_name_for(section_name) if storage_name: section_storage = storage.get(storage_name, None) if section_storage is None: section_storage = storage[storage_name] = dict() return section_storage
[ "def", "select_storage_for", "(", "cls", ",", "section_name", ",", "storage", ")", ":", "section_storage", "=", "storage", "storage_name", "=", "cls", ".", "get_storage_name_for", "(", "section_name", ")", "if", "storage_name", ":", "section_storage", "=", "storag...
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 a part of it (as section storage).
[ "Selects", "the", "data", "storage", "for", "a", "config", "section", "within", "the", ":", "param", ":", "storage", ".", "The", "primary", "config", "section", "is", "normally", "merged", "into", "the", ":", "param", ":", "storage", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/click_configfile.py#L484-L499
train
click-contrib/click-configfile
tasks/clean.py
clean
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. extra_directories = ctx.clean.extra_directories or [] extra_files = ctx.clean.extra_files or [] if extra_directories: directories.extend(extra_directories) if extra_files: files.extend(extra_files) # -- PERFORM CLEANUP: execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=dry_run) cleanup_dirs(directories, dry_run=dry_run) cleanup_files(files, dry_run=dry_run)
python
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. extra_directories = ctx.clean.extra_directories or [] extra_files = ctx.clean.extra_files or [] if extra_directories: directories.extend(extra_directories) if extra_files: files.extend(extra_files) # -- PERFORM CLEANUP: execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=dry_run) cleanup_dirs(directories, dry_run=dry_run) cleanup_files(files, dry_run=dry_run)
[ "def", "clean", "(", "ctx", ",", "dry_run", "=", "False", ")", ":", "# -- VARIATION-POINT 1: Allow user to override in configuration-file", "directories", "=", "ctx", ".", "clean", ".", "directories", "files", "=", "ctx", ".", "clean", ".", "files", "# -- VARIATION-...
Cleanup temporary dirs/files to regain a clean state.
[ "Cleanup", "temporary", "dirs", "/", "files", "to", "regain", "a", "clean", "state", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/clean.py#L65-L82
train
click-contrib/click-configfile
tasks/clean.py
clean_all
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 [], dry_run=dry_run) cleanup_files(ctx.clean_all.extra_files or [], dry_run=dry_run) execute_cleanup_tasks(ctx, cleanup_all_tasks, dry_run=dry_run) clean(ctx, dry_run=dry_run)
python
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 [], dry_run=dry_run) cleanup_files(ctx.clean_all.extra_files or [], dry_run=dry_run) execute_cleanup_tasks(ctx, cleanup_all_tasks, dry_run=dry_run) clean(ctx, dry_run=dry_run)
[ "def", "clean_all", "(", "ctx", ",", "dry_run", "=", "False", ")", ":", "cleanup_dirs", "(", "ctx", ".", "clean_all", ".", "directories", "or", "[", "]", ",", "dry_run", "=", "dry_run", ")", "cleanup_dirs", "(", "ctx", ".", "clean_all", ".", "extra_direc...
Clean up everything, even the precious stuff. NOTE: clean task is executed first.
[ "Clean", "up", "everything", "even", "the", "precious", "stuff", ".", "NOTE", ":", "clean", "task", "is", "executed", "first", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/clean.py#L86-L95
train
click-contrib/click-configfile
tasks/clean.py
clean_python
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", "**/*.pyo", "**/*$py.class"], dry_run=dry_run)
python
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", "**/*.pyo", "**/*$py.class"], dry_run=dry_run)
[ "def", "clean_python", "(", "ctx", ",", "dry_run", "=", "False", ")", ":", "# MAYBE NOT: \"**/__pycache__\"", "cleanup_dirs", "(", "[", "\"build\"", ",", "\"dist\"", ",", "\"*.egg-info\"", ",", "\"**/__pycache__\"", "]", ",", "dry_run", "=", "dry_run", ")", "if"...
Cleanup python related files/dirs: *.pyc, *.pyo, ...
[ "Cleanup", "python", "related", "files", "/", "dirs", ":", "*", ".", "pyc", "*", ".", "pyo", "..." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/clean.py#L99-L106
train
click-contrib/click-configfile
tasks/clean.py
cleanup_files
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 directory (default=".") """ current_dir = Path(workdir) python_basedir = Path(Path(sys.executable).dirname()).joinpath("..").abspath() error_message = None error_count = 0 for file_pattern in patterns: for file_ in path_glob(file_pattern, current_dir): if file_.abspath().startswith(python_basedir): # -- PROTECT CURRENTLY USED VIRTUAL ENVIRONMENT: continue if dry_run: print("REMOVE: %s (dry-run)" % file_) else: print("REMOVE: %s" % file_) try: file_.remove_p() except os.error as e: message = "%s: %s" % (e.__class__.__name__, e) print(message + " basedir: "+ python_basedir) error_count += 1 if not error_message: error_message = message if False and error_message: class CleanupError(RuntimeError): pass raise CleanupError(error_message)
python
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 directory (default=".") """ current_dir = Path(workdir) python_basedir = Path(Path(sys.executable).dirname()).joinpath("..").abspath() error_message = None error_count = 0 for file_pattern in patterns: for file_ in path_glob(file_pattern, current_dir): if file_.abspath().startswith(python_basedir): # -- PROTECT CURRENTLY USED VIRTUAL ENVIRONMENT: continue if dry_run: print("REMOVE: %s (dry-run)" % file_) else: print("REMOVE: %s" % file_) try: file_.remove_p() except os.error as e: message = "%s: %s" % (e.__class__.__name__, e) print(message + " basedir: "+ python_basedir) error_count += 1 if not error_message: error_message = message if False and error_message: class CleanupError(RuntimeError): pass raise CleanupError(error_message)
[ "def", "cleanup_files", "(", "patterns", ",", "dry_run", "=", "False", ",", "workdir", "=", "\".\"", ")", ":", "current_dir", "=", "Path", "(", "workdir", ")", "python_basedir", "=", "Path", "(", "Path", "(", "sys", ".", "executable", ")", ".", "dirname"...
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=".")
[ "Remove", "files", "or", "files", "selected", "by", "file", "patterns", ".", "Skips", "removal", "if", "file", "does", "not", "exist", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/clean.py#L157-L189
train
click-contrib/click-configfile
tasks/clean.py
path_glob
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_dir: current_dir = pathlib.Path.cwd() elif not isinstance(current_dir, pathlib.Path): # -- CASE: string, path.Path (string-like) current_dir = pathlib.Path(str(current_dir)) for p in current_dir.glob(pattern): yield Path(str(p))
python
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_dir: current_dir = pathlib.Path.cwd() elif not isinstance(current_dir, pathlib.Path): # -- CASE: string, path.Path (string-like) current_dir = pathlib.Path(str(current_dir)) for p in current_dir.glob(pattern): yield Path(str(p))
[ "def", "path_glob", "(", "pattern", ",", "current_dir", "=", "None", ")", ":", "if", "not", "current_dir", ":", "current_dir", "=", "pathlib", ".", "Path", ".", "cwd", "(", ")", "elif", "not", "isinstance", "(", "current_dir", ",", "pathlib", ".", "Path"...
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).
[ "Use", "pathlib", "for", "ant", "-", "like", "patterns", "like", ":", "**", "/", "*", ".", "py" ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/clean.py#L191-L205
train
thefab/tornadis
tornadis/pipeline.py
Pipeline.stack_call
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() >>> pipeline.stack_call("HSET", "key", "field", "value") >>> pipeline.stack_call("PING") >>> pipeline.stack_call("INCR", "key2") """ self.pipelined_args.append(args) self.number_of_stacked_calls = self.number_of_stacked_calls + 1
python
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() >>> pipeline.stack_call("HSET", "key", "field", "value") >>> pipeline.stack_call("PING") >>> pipeline.stack_call("INCR", "key2") """ self.pipelined_args.append(args) self.number_of_stacked_calls = self.number_of_stacked_calls + 1
[ "def", "stack_call", "(", "self", ",", "*", "args", ")", ":", "self", ".", "pipelined_args", ".", "append", "(", "args", ")", "self", ".", "number_of_stacked_calls", "=", "self", ".", "number_of_stacked_calls", "+", "1" ]
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", "value") >>> pipeline.stack_call("PING") >>> pipeline.stack_call("INCR", "key2")
[ "Stacks", "a", "redis", "command", "inside", "the", "object", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/pipeline.py#L31-L46
train
thefab/tornadis
tornadis/connection.py
Connection.connect
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.unix_domain_socket is None: self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.tcp_nodelay: self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) else: if not os.path.exists(self.unix_domain_socket): LOG.warning("can't connect to %s, file does not exist", self.unix_domain_socket) raise tornado.gen.Return(False) self.__socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.__socket.setblocking(0) self.__periodic_callback.start() try: LOG.debug("connecting to %s...", self._redis_server()) self._state.set_connecting() if self.unix_domain_socket is None: self.__socket.connect((self.host, self.port)) else: self.__socket.connect(self.unix_domain_socket) except socket.error as e: if (errno_from_exception(e) not in _ERRNO_INPROGRESS and errno_from_exception(e) not in _ERRNO_WOULDBLOCK): self.disconnect() LOG.warning("can't connect to %s", self._redis_server()) raise tornado.gen.Return(False) self.__socket_fileno = self.__socket.fileno() self._register_or_update_event_handler() yield self._state.get_changed_state_future() if not self.is_connected(): LOG.warning("can't connect to %s", self._redis_server()) raise tornado.gen.Return(False) else: LOG.debug("connected to %s", self._redis_server()) self.__socket_fileno = self.__socket.fileno() self._state.set_connected() self._register_or_update_event_handler() raise tornado.gen.Return(True)
python
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.unix_domain_socket is None: self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.tcp_nodelay: self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) else: if not os.path.exists(self.unix_domain_socket): LOG.warning("can't connect to %s, file does not exist", self.unix_domain_socket) raise tornado.gen.Return(False) self.__socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.__socket.setblocking(0) self.__periodic_callback.start() try: LOG.debug("connecting to %s...", self._redis_server()) self._state.set_connecting() if self.unix_domain_socket is None: self.__socket.connect((self.host, self.port)) else: self.__socket.connect(self.unix_domain_socket) except socket.error as e: if (errno_from_exception(e) not in _ERRNO_INPROGRESS and errno_from_exception(e) not in _ERRNO_WOULDBLOCK): self.disconnect() LOG.warning("can't connect to %s", self._redis_server()) raise tornado.gen.Return(False) self.__socket_fileno = self.__socket.fileno() self._register_or_update_event_handler() yield self._state.get_changed_state_future() if not self.is_connected(): LOG.warning("can't connect to %s", self._redis_server()) raise tornado.gen.Return(False) else: LOG.debug("connected to %s", self._redis_server()) self.__socket_fileno = self.__socket.fileno() self._state.set_connected() self._register_or_update_event_handler() raise tornado.gen.Return(True)
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "is_connected", "(", ")", "or", "self", ".", "is_connecting", "(", ")", ":", "raise", "tornado", ".", "gen", ".", "Return", "(", "True", ")", "if", "self", ".", "unix_domain_socket", "is", "...
Connects the object to the host:port. Returns: Future: a Future object with True as result if the connection process was ok.
[ "Connects", "the", "object", "to", "the", "host", ":", "port", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/connection.py#L127-L173
train
thefab/tornadis
tornadis/connection.py
Connection.disconnect
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...", self._redis_server()) self.__periodic_callback.stop() try: self._ioloop.remove_handler(self.__socket_fileno) self._listened_events = 0 except Exception: pass self.__socket_fileno = -1 try: self.__socket.close() except Exception: pass self._state.set_disconnected() self._close_callback() LOG.debug("disconnected from %s", self._redis_server())
python
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...", self._redis_server()) self.__periodic_callback.stop() try: self._ioloop.remove_handler(self.__socket_fileno) self._listened_events = 0 except Exception: pass self.__socket_fileno = -1 try: self.__socket.close() except Exception: pass self._state.set_disconnected() self._close_callback() LOG.debug("disconnected from %s", self._redis_server())
[ "def", "disconnect", "(", "self", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", "and", "not", "self", ".", "is_connecting", "(", ")", ":", "return", "LOG", ".", "debug", "(", "\"disconnecting from %s...\"", ",", "self", ".", "_redis_server"...
Disconnects the object. Safe method (no exception, even if it's already disconnected or if there are some connection errors).
[ "Disconnects", "the", "object", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/connection.py#L208-L230
train
thefab/tornadis
tornadis/connection.py
Connection.write
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 one (without copying). Args: data (str or WriteBuffer): string (or WriteBuffer) to write to the host:port. """ if isinstance(data, WriteBuffer): self._write_buffer.append(data) else: if len(data) > 0: self._write_buffer.append(data) if self.aggressive_write: self._handle_write() if self._write_buffer._total_length > 0: self._register_or_update_event_handler(write=True)
python
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 one (without copying). Args: data (str or WriteBuffer): string (or WriteBuffer) to write to the host:port. """ if isinstance(data, WriteBuffer): self._write_buffer.append(data) else: if len(data) > 0: self._write_buffer.append(data) if self.aggressive_write: self._handle_write() if self._write_buffer._total_length > 0: self._register_or_update_event_handler(write=True)
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "WriteBuffer", ")", ":", "self", ".", "_write_buffer", ".", "append", "(", "data", ")", "else", ":", "if", "len", "(", "data", ")", ">", "0", ":", "self", "...
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). Args: data (str or WriteBuffer): string (or WriteBuffer) to write to the host:port.
[ "Buffers", "some", "data", "to", "be", "sent", "to", "the", "host", ":", "port", "in", "a", "non", "blocking", "way", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/connection.py#L302-L323
train
click-contrib/click-configfile
tasks/_vendor/path.py
surrogate_escape
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
python
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
[ "def", "surrogate_escape", "(", "error", ")", ":", "chars", "=", "error", ".", "object", "[", "error", ".", "start", ":", "error", ".", "end", "]", "assert", "len", "(", "chars", ")", "==", "1", "val", "=", "ord", "(", "chars", ")", "val", "+=", ...
Simulate the Python 3 ``surrogateescape`` handler, but for Python 2 only.
[ "Simulate", "the", "Python", "3", "surrogateescape", "handler", "but", "for", "Python", "2", "only", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L83-L91
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path._always_unicode
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')
python
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')
[ "def", "_always_unicode", "(", "cls", ",", "path", ")", ":", "if", "PY3", "or", "isinstance", "(", "path", ",", "text_type", ")", ":", "return", "path", "return", "path", ".", "decode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ",", "'surrogate...
Ensure the path as retrieved from a Python API, such as :func:`os.listdir`, is a proper Unicode string.
[ "Ensure", "the", "path", "as", "retrieved", "from", "a", "Python", "API", "such", "as", ":", "func", ":", "os", ".", "listdir", "is", "a", "proper", "Unicode", "string", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L221-L228
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.namebase
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.splitext(self.name) return base
python
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.splitext(self.name) return base
[ "def", "namebase", "(", "self", ")", ":", "base", ",", "ext", "=", "self", ".", "module", ".", "splitext", "(", "self", ".", "name", ")", "return", "base" ]
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'``.
[ "The", "same", "as", ":", "meth", ":", "name", "but", "with", "one", "file", "extension", "stripped", "off", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L336-L345
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.listdir
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 lists items whose names match the given pattern. .. seealso:: :meth:`files`, :meth:`dirs` """ if pattern is None: pattern = '*' return [ self / child for child in map(self._always_unicode, os.listdir(self)) if self._next_class(child).fnmatch(pattern) ]
python
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 lists items whose names match the given pattern. .. seealso:: :meth:`files`, :meth:`dirs` """ if pattern is None: pattern = '*' return [ self / child for child in map(self._always_unicode, os.listdir(self)) if self._next_class(child).fnmatch(pattern) ]
[ "def", "listdir", "(", "self", ",", "pattern", "=", "None", ")", ":", "if", "pattern", "is", "None", ":", "pattern", "=", "'*'", "return", "[", "self", "/", "child", "for", "child", "in", "map", "(", "self", ".", "_always_unicode", ",", "os", ".", ...
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 given pattern. .. seealso:: :meth:`files`, :meth:`dirs`
[ "D", ".", "listdir", "()", "-", ">", "List", "of", "items", "in", "this", "directory", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L522-L541
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.dirs
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 directories whose names match the given pattern. For example, ``d.dirs('build-*')``. """ return [p for p in self.listdir(pattern) if p.isdir()]
python
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 directories whose names match the given pattern. For example, ``d.dirs('build-*')``. """ return [p for p in self.listdir(pattern) if p.isdir()]
[ "def", "dirs", "(", "self", ",", "pattern", "=", "None", ")", ":", "return", "[", "p", "for", "p", "in", "self", ".", "listdir", "(", "pattern", ")", "if", "p", ".", "isdir", "(", ")", "]" ]
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. For example, ``d.dirs('build-*')``.
[ "D", ".", "dirs", "()", "-", ">", "List", "of", "this", "directory", "s", "subdirectories", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L543-L554
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.files
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 given pattern. For example, ``d.files('*.pyc')``. """ return [p for p in self.listdir(pattern) if p.isfile()]
python
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 given pattern. For example, ``d.files('*.pyc')``. """ return [p for p in self.listdir(pattern) if p.isfile()]
[ "def", "files", "(", "self", ",", "pattern", "=", "None", ")", ":", "return", "[", "p", "for", "p", "in", "self", ".", "listdir", "(", "pattern", ")", "if", "p", ".", "isfile", "(", ")", "]" ]
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('*.pyc')``.
[ "D", ".", "files", "()", "-", ">", "List", "of", "the", "files", "in", "this", "directory", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L556-L567
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.walkdirs
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 with names ending in ``'test'``. The `errors=` keyword argument controls behavior when an error occurs. The default is ``'strict'``, which causes an exception. The other allowed values are ``'warn'`` (which reports the error via :func:`warnings.warn()`), and ``'ignore'``. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: dirs = self.dirs() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in dirs: if pattern is None or child.fnmatch(pattern): yield child for subsubdir in child.walkdirs(pattern, errors): yield subsubdir
python
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 with names ending in ``'test'``. The `errors=` keyword argument controls behavior when an error occurs. The default is ``'strict'``, which causes an exception. The other allowed values are ``'warn'`` (which reports the error via :func:`warnings.warn()`), and ``'ignore'``. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: dirs = self.dirs() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in dirs: if pattern is None or child.fnmatch(pattern): yield child for subsubdir in child.walkdirs(pattern, errors): yield subsubdir
[ "def", "walkdirs", "(", "self", ",", "pattern", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "errors", "not", "in", "(", "'strict'", ",", "'warn'", ",", "'ignore'", ")", ":", "raise", "ValueError", "(", "\"invalid errors parameter\"", ")", ...
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 argument controls behavior when an error occurs. The default is ``'strict'``, which causes an exception. The other allowed values are ``'warn'`` (which reports the error via :func:`warnings.warn()`), and ``'ignore'``.
[ "D", ".", "walkdirs", "()", "-", ">", "iterator", "over", "subdirs", "recursively", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L624-L658
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.walkfiles
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`` extension. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: try: isfile = child.isfile() isdir = not isfile and child.isdir() except: if errors == 'ignore': continue elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) continue else: raise if isfile: if pattern is None or child.fnmatch(pattern): yield child elif isdir: for f in child.walkfiles(pattern, errors): yield f
python
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`` extension. """ if errors not in ('strict', 'warn', 'ignore'): raise ValueError("invalid errors parameter") try: childList = self.listdir() except Exception: if errors == 'ignore': return elif errors == 'warn': warnings.warn( "Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) return else: raise for child in childList: try: isfile = child.isfile() isdir = not isfile and child.isdir() except: if errors == 'ignore': continue elif errors == 'warn': warnings.warn( "Unable to access '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning) continue else: raise if isfile: if pattern is None or child.fnmatch(pattern): yield child elif isdir: for f in child.walkfiles(pattern, errors): yield f
[ "def", "walkfiles", "(", "self", ",", "pattern", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "if", "errors", "not", "in", "(", "'strict'", ",", "'warn'", ",", "'ignore'", ")", ":", "raise", "ValueError", "(", "\"invalid errors parameter\"", ")",...
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.
[ "D", ".", "walkfiles", "()", "-", ">", "iterator", "over", "files", "in", "D", "recursively", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L660-L706
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.open
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(self, *args, **kwargs)
python
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(self, *args, **kwargs)
[ "def", "open", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "io_error_compat", "(", ")", ":", "return", "io", ".", "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.
[ "Open", "this", "file", "and", "return", "a", "corresponding", ":", "class", ":", "file", "object", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L743-L750
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.write_text
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 differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See below. Parameters: `text` - str/unicode - The text to be written. `encoding` - str - The Unicode encoding that will be used. This is ignored if `text` isn't a Unicode string. `errors` - str - How to handle Unicode encoding errors. Default is ``'strict'``. See ``help(unicode.encode)`` for the options. This is ignored if `text` isn't a Unicode string. `linesep` - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is :data:`os.linesep`. You can also specify ``None`` to leave all newlines as they are in `text`. `append` - keyword argument - bool - Specifies what to do if the file already exists (``True``: append to the end of it; ``False``: overwrite it.) The default is ``False``. --- Newline handling. ``write_text()`` converts all standard end-of-line sequences (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default end-of-line sequence (see :data:`os.linesep`; on Windows, for example, the end-of-line marker is ``'\r\n'``). If you don't like your platform's default, you can override it using the `linesep=` keyword argument. If you specifically want ``write_text()`` to preserve the newlines as-is, use ``linesep=None``. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``. (This is slightly different from when you open a file for writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')`` in Python.) --- Unicode If `text` isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The `encoding` and `errors` arguments are not used and must be omitted. If `text` is Unicode, it is first converted to :func:`bytes` using the specified `encoding` (or the default encoding if `encoding` isn't specified). The `errors` argument applies only to this conversion. """ if isinstance(text, text_type): if linesep is not None: text = U_NEWLINE.sub(linesep, text) text = text.encode(encoding or sys.getdefaultencoding(), errors) else: assert encoding is None text = NEWLINE.sub(linesep, text) self.write_bytes(text, append=append)
python
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 differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See below. Parameters: `text` - str/unicode - The text to be written. `encoding` - str - The Unicode encoding that will be used. This is ignored if `text` isn't a Unicode string. `errors` - str - How to handle Unicode encoding errors. Default is ``'strict'``. See ``help(unicode.encode)`` for the options. This is ignored if `text` isn't a Unicode string. `linesep` - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is :data:`os.linesep`. You can also specify ``None`` to leave all newlines as they are in `text`. `append` - keyword argument - bool - Specifies what to do if the file already exists (``True``: append to the end of it; ``False``: overwrite it.) The default is ``False``. --- Newline handling. ``write_text()`` converts all standard end-of-line sequences (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default end-of-line sequence (see :data:`os.linesep`; on Windows, for example, the end-of-line marker is ``'\r\n'``). If you don't like your platform's default, you can override it using the `linesep=` keyword argument. If you specifically want ``write_text()`` to preserve the newlines as-is, use ``linesep=None``. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``. (This is slightly different from when you open a file for writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')`` in Python.) --- Unicode If `text` isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The `encoding` and `errors` arguments are not used and must be omitted. If `text` is Unicode, it is first converted to :func:`bytes` using the specified `encoding` (or the default encoding if `encoding` isn't specified). The `errors` argument applies only to this conversion. """ if isinstance(text, text_type): if linesep is not None: text = U_NEWLINE.sub(linesep, text) text = text.encode(encoding or sys.getdefaultencoding(), errors) else: assert encoding is None text = NEWLINE.sub(linesep, text) self.write_bytes(text, append=append)
[ "def", "write_text", "(", "self", ",", "text", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "linesep", "=", "os", ".", "linesep", ",", "append", "=", "False", ")", ":", "if", "isinstance", "(", "text", ",", "text_type", ")", ":"...
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 below. Parameters: `text` - str/unicode - The text to be written. `encoding` - str - The Unicode encoding that will be used. This is ignored if `text` isn't a Unicode string. `errors` - str - How to handle Unicode encoding errors. Default is ``'strict'``. See ``help(unicode.encode)`` for the options. This is ignored if `text` isn't a Unicode string. `linesep` - keyword argument - str/unicode - The sequence of characters to be used to mark end-of-line. The default is :data:`os.linesep`. You can also specify ``None`` to leave all newlines as they are in `text`. `append` - keyword argument - bool - Specifies what to do if the file already exists (``True``: append to the end of it; ``False``: overwrite it.) The default is ``False``. --- Newline handling. ``write_text()`` converts all standard end-of-line sequences (``'\n'``, ``'\r'``, and ``'\r\n'``) to your platform's default end-of-line sequence (see :data:`os.linesep`; on Windows, for example, the end-of-line marker is ``'\r\n'``). If you don't like your platform's default, you can override it using the `linesep=` keyword argument. If you specifically want ``write_text()`` to preserve the newlines as-is, use ``linesep=None``. This applies to Unicode text the same as to 8-bit text, except there are three additional standard Unicode end-of-line sequences: ``u'\x85'``, ``u'\r\x85'``, and ``u'\u2028'``. (This is slightly different from when you open a file for writing with ``fopen(filename, "w")`` in C or ``open(filename, 'w')`` in Python.) --- Unicode If `text` isn't Unicode, then apart from newline handling, the bytes are written verbatim to the file. The `encoding` and `errors` arguments are not used and must be omitted. If `text` is Unicode, it is first converted to :func:`bytes` using the specified `encoding` (or the default encoding if `encoding` isn't specified). The `errors` argument applies only to this conversion.
[ "r", "Write", "the", "given", "text", "to", "this", "file", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L799-L871
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.write_lines
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. See `linesep` below. `lines` - A list of strings. `encoding` - A Unicode encoding to use. This applies only if `lines` contains any Unicode strings. `errors` - How to handle errors in Unicode encoding. This also applies only to Unicode strings. linesep - The desired line-ending. This line-ending is applied to every line. If a line already has any standard line ending (``'\r'``, ``'\n'``, ``'\r\n'``, ``u'\x85'``, ``u'\r\x85'``, ``u'\u2028'``), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent (``'\r\n'`` on Windows, ``'\n'`` on Unix, etc.). Specify ``None`` to write the lines as-is, like :meth:`file.writelines`. Use the keyword argument ``append=True`` to append lines to the file. The default is to overwrite the file. .. warning :: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the `encoding=` parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later. """ with self.open('ab' if append else 'wb') as f: for l in lines: isUnicode = isinstance(l, text_type) if linesep is not None: pattern = U_NL_END if isUnicode else NL_END l = pattern.sub('', l) + linesep if isUnicode: l = l.encode(encoding or sys.getdefaultencoding(), errors) f.write(l)
python
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. See `linesep` below. `lines` - A list of strings. `encoding` - A Unicode encoding to use. This applies only if `lines` contains any Unicode strings. `errors` - How to handle errors in Unicode encoding. This also applies only to Unicode strings. linesep - The desired line-ending. This line-ending is applied to every line. If a line already has any standard line ending (``'\r'``, ``'\n'``, ``'\r\n'``, ``u'\x85'``, ``u'\r\x85'``, ``u'\u2028'``), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent (``'\r\n'`` on Windows, ``'\n'`` on Unix, etc.). Specify ``None`` to write the lines as-is, like :meth:`file.writelines`. Use the keyword argument ``append=True`` to append lines to the file. The default is to overwrite the file. .. warning :: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the `encoding=` parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later. """ with self.open('ab' if append else 'wb') as f: for l in lines: isUnicode = isinstance(l, text_type) if linesep is not None: pattern = U_NL_END if isUnicode else NL_END l = pattern.sub('', l) + linesep if isUnicode: l = l.encode(encoding or sys.getdefaultencoding(), errors) f.write(l)
[ "def", "write_lines", "(", "self", ",", "lines", ",", "encoding", "=", "None", ",", "errors", "=", "'strict'", ",", "linesep", "=", "os", ".", "linesep", ",", "append", "=", "False", ")", ":", "with", "self", ".", "open", "(", "'ab'", "if", "append",...
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 applies only if `lines` contains any Unicode strings. `errors` - How to handle errors in Unicode encoding. This also applies only to Unicode strings. linesep - The desired line-ending. This line-ending is applied to every line. If a line already has any standard line ending (``'\r'``, ``'\n'``, ``'\r\n'``, ``u'\x85'``, ``u'\r\x85'``, ``u'\u2028'``), that will be stripped off and this will be used instead. The default is os.linesep, which is platform-dependent (``'\r\n'`` on Windows, ``'\n'`` on Unix, etc.). Specify ``None`` to write the lines as-is, like :meth:`file.writelines`. Use the keyword argument ``append=True`` to append lines to the file. The default is to overwrite the file. .. warning :: When you use this with Unicode data, if the encoding of the existing data in the file is different from the encoding you specify with the `encoding=` parameter, the result is mixed-encoding data, which can really confuse someone trying to read the file later.
[ "r", "Write", "the", "given", "lines", "of", "text", "to", "this", "file", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L898-L944
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.mkdir_p
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 self
python
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 self
[ "def", "mkdir_p", "(", "self", ",", "mode", "=", "0o777", ")", ":", "try", ":", "self", ".", "mkdir", "(", "mode", ")", "except", "OSError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "e", ".", "errno", "!=", "...
Like :meth:`mkdir`, but does not raise an exception if the directory already exists.
[ "Like", ":", "meth", ":", "mkdir", "but", "does", "not", "raise", "an", "exception", "if", "the", "directory", "already", "exists", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1203-L1212
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.makedirs_p
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 return self
python
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 return self
[ "def", "makedirs_p", "(", "self", ",", "mode", "=", "0o777", ")", ":", "try", ":", "self", ".", "makedirs", "(", "mode", ")", "except", "OSError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "e", ".", "errno", "!=...
Like :meth:`makedirs`, but does not raise an exception if the directory already exists.
[ "Like", ":", "meth", ":", "makedirs", "but", "does", "not", "raise", "an", "exception", "if", "the", "directory", "already", "exists", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1219-L1228
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.rmdir_p
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: raise return self
python
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: raise return self
[ "def", "rmdir_p", "(", "self", ")", ":", "try", ":", "self", ".", "rmdir", "(", ")", "except", "OSError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "e", ".", "errno", "!=", "errno", ".", "ENOTEMPTY", "and", "e",...
Like :meth:`rmdir`, but does not raise an exception if the directory is not empty or does not exist.
[ "Like", ":", "meth", ":", "rmdir", "but", "does", "not", "raise", "an", "exception", "if", "the", "directory", "is", "not", "empty", "or", "does", "not", "exist", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1235-L1244
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.removedirs_p
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.EEXIST: raise return self
python
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.EEXIST: raise return self
[ "def", "removedirs_p", "(", "self", ")", ":", "try", ":", "self", ".", "removedirs", "(", ")", "except", "OSError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "e", ".", "errno", "!=", "errno", ".", "ENOTEMPTY", "an...
Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist.
[ "Like", ":", "meth", ":", "removedirs", "but", "does", "not", "raise", "an", "exception", "if", "the", "directory", "is", "not", "empty", "or", "does", "not", "exist", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1251-L1260
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.remove_p
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
python
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
[ "def", "remove_p", "(", "self", ")", ":", "try", ":", "self", ".", "unlink", "(", ")", "except", "OSError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise"...
Like :meth:`remove`, but does not raise an exception if the file does not exist.
[ "Like", ":", "meth", ":", "remove", "but", "does", "not", "raise", "an", "exception", "if", "the", "file", "does", "not", "exist", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1278-L1287
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.rmtree_p
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
python
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
[ "def", "rmtree_p", "(", "self", ")", ":", "try", ":", "self", ".", "rmtree", "(", ")", "except", "OSError", ":", "_", ",", "e", ",", "_", "=", "sys", ".", "exc_info", "(", ")", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise"...
Like :meth:`rmtree`, but does not raise an exception if the directory does not exist.
[ "Like", ":", "meth", ":", "rmtree", "but", "does", "not", "raise", "an", "exception", "if", "the", "directory", "does", "not", "exist", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1357-L1366
train
click-contrib/click-configfile
tasks/_vendor/path.py
Path.merge_tree
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 newer than `dst`. Note that the technique employed stages the files in a temporary directory first, so this function is not suitable for merging trees with large files, especially if the temporary directory is not capable of storing a copy of the entire source tree. """ update = kwargs.pop('update', False) with tempdir() as _temp_dir: # first copy the tree to a stage directory to support # the parameters and behavior of copytree. stage = _temp_dir / str(hash(self)) self.copytree(stage, symlinks, *args, **kwargs) # now copy everything from the stage directory using # the semantics of dir_util.copy_tree dir_util.copy_tree(stage, dst, preserve_symlinks=symlinks, update=update)
python
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 newer than `dst`. Note that the technique employed stages the files in a temporary directory first, so this function is not suitable for merging trees with large files, especially if the temporary directory is not capable of storing a copy of the entire source tree. """ update = kwargs.pop('update', False) with tempdir() as _temp_dir: # first copy the tree to a stage directory to support # the parameters and behavior of copytree. stage = _temp_dir / str(hash(self)) self.copytree(stage, symlinks, *args, **kwargs) # now copy everything from the stage directory using # the semantics of dir_util.copy_tree dir_util.copy_tree(stage, dst, preserve_symlinks=symlinks, update=update)
[ "def", "merge_tree", "(", "self", ",", "dst", ",", "symlinks", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "update", "=", "kwargs", ".", "pop", "(", "'update'", ",", "False", ")", "with", "tempdir", "(", ")", "as", "_temp_dir...
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 temporary directory first, so this function is not suitable for merging trees with large files, especially if the temporary directory is not capable of storing a copy of the entire source tree.
[ "Copy", "entire", "contents", "of", "self", "to", "dst", "overwriting", "existing", "contents", "in", "dst", "with", "those", "in", "self", "." ]
a616204cb9944125fd5051556f27a7ccef611e22
https://github.com/click-contrib/click-configfile/blob/a616204cb9944125fd5051556f27a7ccef611e22/tasks/_vendor/path.py#L1374-L1397
train
creare-com/pydem
pydem/reader/gdal_reader.py
GdalReader.__gdal_dataset_default
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_name, self.file_types)) dataset = gdal.OpenShared(self.file_name, gdalconst.GA_ReadOnly) if dataset is None: raise ValueError('Dataset %s did not load properly.' % self.file_name) # Sanity checks. assert dataset.RasterCount > 0 # Seems okay... return dataset
python
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_name, self.file_types)) dataset = gdal.OpenShared(self.file_name, gdalconst.GA_ReadOnly) if dataset is None: raise ValueError('Dataset %s did not load properly.' % self.file_name) # Sanity checks. assert dataset.RasterCount > 0 # Seems okay... return dataset
[ "def", "__gdal_dataset_default", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "file_name", ")", ":", "return", "None", "if", "os", ".", "path", ".", "splitext", "(", "self", ".", "file_name", ")", "[", "1", ...
DiskReader implementation.
[ "DiskReader", "implementation", "." ]
c2fc8d84cfb411df84f71a6dec9edc4b544f710a
https://github.com/creare-com/pydem/blob/c2fc8d84cfb411df84f71a6dec9edc4b544f710a/pydem/reader/gdal_reader.py#L100-L116
train
thefab/tornadis
tornadis/client.py
Client.connect
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. """ if self.is_connected(): raise tornado.gen.Return(True) cb1 = self._read_callback cb2 = self._close_callback self.__callback_queue = collections.deque() self._reply_list = [] self.__reader = hiredis.Reader(replyError=ClientError) kwargs = self.connection_kwargs self.__connection = Connection(cb1, cb2, **kwargs) connection_status = yield self.__connection.connect() if connection_status is not True: # nothing left to do here, return raise tornado.gen.Return(False) if self.password is not None: authentication_status = yield self._call('AUTH', self.password) if authentication_status != b'OK': # incorrect password, return back the result LOG.warning("impossible to connect: bad password") self.__connection.disconnect() raise tornado.gen.Return(False) if self.db != 0: db_status = yield self._call('SELECT', self.db) if db_status != b'OK': LOG.warning("can't select db %s", self.db) raise tornado.gen.Return(False) raise tornado.gen.Return(True)
python
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. """ if self.is_connected(): raise tornado.gen.Return(True) cb1 = self._read_callback cb2 = self._close_callback self.__callback_queue = collections.deque() self._reply_list = [] self.__reader = hiredis.Reader(replyError=ClientError) kwargs = self.connection_kwargs self.__connection = Connection(cb1, cb2, **kwargs) connection_status = yield self.__connection.connect() if connection_status is not True: # nothing left to do here, return raise tornado.gen.Return(False) if self.password is not None: authentication_status = yield self._call('AUTH', self.password) if authentication_status != b'OK': # incorrect password, return back the result LOG.warning("impossible to connect: bad password") self.__connection.disconnect() raise tornado.gen.Return(False) if self.db != 0: db_status = yield self._call('SELECT', self.db) if db_status != b'OK': LOG.warning("can't select db %s", self.db) raise tornado.gen.Return(False) raise tornado.gen.Return(True)
[ "def", "connect", "(", "self", ")", ":", "if", "self", ".", "is_connected", "(", ")", ":", "raise", "tornado", ".", "gen", ".", "Return", "(", "True", ")", "cb1", "=", "self", ".", "_read_callback", "cb2", "=", "self", ".", "_close_callback", "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", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/client.py#L84-L118
train
thefab/tornadis
tornadis/client.py
Client._close_callback
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.__callback_queue.popleft() callback(ConnectionError("closed connection")) except IndexError: break if self.subscribed: # pubsub clients self._reply_list.append(ConnectionError("closed connection")) self._condition.notify_all()
python
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.__callback_queue.popleft() callback(ConnectionError("closed connection")) except IndexError: break if self.subscribed: # pubsub clients self._reply_list.append(ConnectionError("closed connection")) self._condition.notify_all()
[ "def", "_close_callback", "(", "self", ")", ":", "while", "True", ":", "try", ":", "callback", "=", "self", ".", "__callback_queue", ".", "popleft", "(", ")", "callback", "(", "ConnectionError", "(", "\"closed connection\"", ")", ")", "except", "IndexError", ...
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.
[ "Callback", "called", "when", "redis", "closed", "the", "connection", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/client.py#L130-L145
train
thefab/tornadis
tornadis/client.py
Client._read_callback
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. """ try: if data is not None: self.__reader.feed(data) while True: reply = self.__reader.gets() if reply is not False: try: callback = self.__callback_queue.popleft() # normal client (1 reply = 1 callback) callback(reply) except IndexError: # pubsub clients self._reply_list.append(reply) self._condition.notify_all() else: break except hiredis.ProtocolError: # something nasty occured (corrupt stream => no way to recover) LOG.warning("corrupted stream => disconnect") self.disconnect()
python
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. """ try: if data is not None: self.__reader.feed(data) while True: reply = self.__reader.gets() if reply is not False: try: callback = self.__callback_queue.popleft() # normal client (1 reply = 1 callback) callback(reply) except IndexError: # pubsub clients self._reply_list.append(reply) self._condition.notify_all() else: break except hiredis.ProtocolError: # something nasty occured (corrupt stream => no way to recover) LOG.warning("corrupted stream => disconnect") self.disconnect()
[ "def", "_read_callback", "(", "self", ",", "data", "=", "None", ")", ":", "try", ":", "if", "data", "is", "not", "None", ":", "self", ".", "__reader", ".", "feed", "(", "data", ")", "while", "True", ":", "reply", "=", "self", ".", "__reader", ".", ...
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", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/client.py#L147-L175
train
thefab/tornadis
tornadis/client.py
Client.call
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). Returns: a Future with the decoded redis reply as result (when available) or a ConnectionError object in case of connection error. Raises: ClientError: your Pipeline object is empty. Examples: >>> @tornado.gen.coroutine def foobar(): client = Client() result = yield client.call("HSET", "key", "field", "val") """ if not self.is_connected(): if self.autoconnect: # We use this method only when we are not contected # to void performance penaly due to gen.coroutine decorator return self._call_with_autoconnect(*args, **kwargs) else: error = ConnectionError("you are not connected and " "autoconnect=False") return tornado.gen.maybe_future(error) return self._call(*args, **kwargs)
python
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). Returns: a Future with the decoded redis reply as result (when available) or a ConnectionError object in case of connection error. Raises: ClientError: your Pipeline object is empty. Examples: >>> @tornado.gen.coroutine def foobar(): client = Client() result = yield client.call("HSET", "key", "field", "val") """ if not self.is_connected(): if self.autoconnect: # We use this method only when we are not contected # to void performance penaly due to gen.coroutine decorator return self._call_with_autoconnect(*args, **kwargs) else: error = ConnectionError("you are not connected and " "autoconnect=False") return tornado.gen.maybe_future(error) return self._call(*args, **kwargs)
[ "def", "call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "if", "self", ".", "autoconnect", ":", "# We use this method only when we are not contected", "# to void performance penaly ...
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 redis reply as result (when available) or a ConnectionError object in case of connection error. Raises: ClientError: your Pipeline object is empty. Examples: >>> @tornado.gen.coroutine def foobar(): client = Client() result = yield client.call("HSET", "key", "field", "val")
[ "Calls", "a", "redis", "command", "and", "returns", "a", "Future", "of", "the", "reply", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/client.py#L177-L208
train
thefab/tornadis
tornadis/client.py
Client.async_call
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 not set, the reply is silently discarded. In case of errors, the callback is called with a TornadisException object as argument. Args: *args: full redis command as variable length argument list or a Pipeline object (as a single argument). **kwargs: options as keyword parameters. Examples: >>> def cb(result): pass >>> client.async_call("HSET", "key", "field", "val", callback=cb) """ def after_autoconnect_callback(future): if self.is_connected(): self._call(*args, **kwargs) else: # FIXME pass if 'callback' not in kwargs: kwargs['callback'] = discard_reply_cb if not self.is_connected(): if self.autoconnect: connect_future = self.connect() cb = after_autoconnect_callback self.__connection._ioloop.add_future(connect_future, cb) else: error = ConnectionError("you are not connected and " "autoconnect=False") kwargs['callback'](error) else: self._call(*args, **kwargs)
python
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 not set, the reply is silently discarded. In case of errors, the callback is called with a TornadisException object as argument. Args: *args: full redis command as variable length argument list or a Pipeline object (as a single argument). **kwargs: options as keyword parameters. Examples: >>> def cb(result): pass >>> client.async_call("HSET", "key", "field", "val", callback=cb) """ def after_autoconnect_callback(future): if self.is_connected(): self._call(*args, **kwargs) else: # FIXME pass if 'callback' not in kwargs: kwargs['callback'] = discard_reply_cb if not self.is_connected(): if self.autoconnect: connect_future = self.connect() cb = after_autoconnect_callback self.__connection._ioloop.add_future(connect_future, cb) else: error = ConnectionError("you are not connected and " "autoconnect=False") kwargs['callback'](error) else: self._call(*args, **kwargs)
[ "def", "async_call", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "after_autoconnect_callback", "(", "future", ")", ":", "if", "self", ".", "is_connected", "(", ")", ":", "self", ".", "_call", "(", "*", "args", ",", "*", ...
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 case of errors, the callback is called with a TornadisException object as argument. Args: *args: full redis command as variable length argument list or a Pipeline object (as a single argument). **kwargs: options as keyword parameters. Examples: >>> def cb(result): pass >>> client.async_call("HSET", "key", "field", "val", callback=cb)
[ "Calls", "a", "redis", "command", "waits", "for", "the", "reply", "and", "call", "a", "callback", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/client.py#L218-L259
train
thefab/tornadis
tornadis/utils.py
format_args_in_redis_protocol
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). More informations about the protocol: http://redis.io/topics/protocol Args: *args: full redis command as variable length argument list Returns: binary string (arguments in redis protocol) Examples: >>> format_args_in_redis_protocol("HSET", "key", "field", "value") '*4\r\n$4\r\nHSET\r\n$3\r\nkey\r\n$5\r\nfield\r\n$5\r\nvalue\r\n' """ buf = WriteBuffer() l = "*%d\r\n" % len(args) # noqa: E741 if six.PY2: buf.append(l) else: # pragma: no cover buf.append(l.encode('utf-8')) for arg in args: if isinstance(arg, six.text_type): # it's a unicode string in Python2 or a standard (unicode) # string in Python3, let's encode it in utf-8 to get raw bytes arg = arg.encode('utf-8') elif isinstance(arg, six.string_types): # it's a basestring in Python2 => nothing to do pass elif isinstance(arg, six.binary_type): # pragma: no cover # it's a raw bytes string in Python3 => nothing to do pass elif isinstance(arg, six.integer_types): tmp = "%d" % arg if six.PY2: arg = tmp else: # pragma: no cover arg = tmp.encode('utf-8') elif isinstance(arg, WriteBuffer): # it's a WriteBuffer object => nothing to do pass else: raise Exception("don't know what to do with %s" % type(arg)) l = "$%d\r\n" % len(arg) # noqa: E741 if six.PY2: buf.append(l) else: # pragma: no cover buf.append(l.encode('utf-8')) buf.append(arg) buf.append(b"\r\n") return buf
python
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). More informations about the protocol: http://redis.io/topics/protocol Args: *args: full redis command as variable length argument list Returns: binary string (arguments in redis protocol) Examples: >>> format_args_in_redis_protocol("HSET", "key", "field", "value") '*4\r\n$4\r\nHSET\r\n$3\r\nkey\r\n$5\r\nfield\r\n$5\r\nvalue\r\n' """ buf = WriteBuffer() l = "*%d\r\n" % len(args) # noqa: E741 if six.PY2: buf.append(l) else: # pragma: no cover buf.append(l.encode('utf-8')) for arg in args: if isinstance(arg, six.text_type): # it's a unicode string in Python2 or a standard (unicode) # string in Python3, let's encode it in utf-8 to get raw bytes arg = arg.encode('utf-8') elif isinstance(arg, six.string_types): # it's a basestring in Python2 => nothing to do pass elif isinstance(arg, six.binary_type): # pragma: no cover # it's a raw bytes string in Python3 => nothing to do pass elif isinstance(arg, six.integer_types): tmp = "%d" % arg if six.PY2: arg = tmp else: # pragma: no cover arg = tmp.encode('utf-8') elif isinstance(arg, WriteBuffer): # it's a WriteBuffer object => nothing to do pass else: raise Exception("don't know what to do with %s" % type(arg)) l = "$%d\r\n" % len(arg) # noqa: E741 if six.PY2: buf.append(l) else: # pragma: no cover buf.append(l.encode('utf-8')) buf.append(arg) buf.append(b"\r\n") return buf
[ "def", "format_args_in_redis_protocol", "(", "*", "args", ")", ":", "buf", "=", "WriteBuffer", "(", ")", "l", "=", "\"*%d\\r\\n\"", "%", "len", "(", "args", ")", "# noqa: E741", "if", "six", ".", "PY2", ":", "buf", ".", "append", "(", "l", ")", "else",...
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://redis.io/topics/protocol Args: *args: full redis command as variable length argument list Returns: binary string (arguments in redis protocol) Examples: >>> format_args_in_redis_protocol("HSET", "key", "field", "value") '*4\r\n$4\r\nHSET\r\n$3\r\nkey\r\n$5\r\nfield\r\n$5\r\nvalue\r\n'
[ "Formats", "arguments", "into", "redis", "protocol", "..." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/utils.py#L14-L70
train
thefab/tornadis
tornadis/utils.py
ContextManagerFuture._done_callback
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 object """ if wrapped.exception(): self.set_exception(wrapped.exception()) else: self.set_result(wrapped.result())
python
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 object """ if wrapped.exception(): self.set_exception(wrapped.exception()) else: self.set_result(wrapped.result())
[ "def", "_done_callback", "(", "self", ",", "wrapped", ")", ":", "if", "wrapped", ".", "exception", "(", ")", ":", "self", ".", "set_exception", "(", "wrapped", ".", "exception", "(", ")", ")", "else", ":", "self", ".", "set_result", "(", "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 object
[ "Internal", "done", "callback", "to", "set", "the", "result", "of", "the", "object", "." ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/utils.py#L108-L120
train
thefab/tornadis
tornadis/utils.py
ContextManagerFuture.result
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. @contextlib.contextmanager def f(): try: yield self._wrapped.result() finally: self._exit_callback() return f()
python
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. @contextlib.contextmanager def f(): try: yield self._wrapped.result() finally: self._exit_callback() return f()
[ "def", "result", "(", "self", ")", ":", "if", "self", ".", "exception", "(", ")", ":", "raise", "self", ".", "exception", "(", ")", "# Otherwise return a context manager that cleans up after the block.", "@", "contextlib", ".", "contextmanager", "def", "f", "(", ...
The result method which returns a context manager Returns: ContextManager: The corresponding context manager
[ "The", "result", "method", "which", "returns", "a", "context", "manager" ]
f9dc883e46eb5971b62eab38346319757e5f900f
https://github.com/thefab/tornadis/blob/f9dc883e46eb5971b62eab38346319757e5f900f/tornadis/utils.py#L122-L138
train
enricobacis/lyricwikia
lyricwikia/lyricwikia.py
create_url
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)))
python
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)))
[ "def", "create_url", "(", "artist", ",", "song", ")", ":", "return", "(", "__BASE_URL__", "+", "'/wiki/{artist}:{song}'", ".", "format", "(", "artist", "=", "urlize", "(", "artist", ")", ",", "song", "=", "urlize", "(", "song", ")", ")", ")" ]
Create the URL in the LyricWikia format
[ "Create", "the", "URL", "in", "the", "LyricWikia", "format" ]
bc6caa7f745f1d54adf3ba1a72df76d593164cfa
https://github.com/enricobacis/lyricwikia/blob/bc6caa7f745f1d54adf3ba1a72df76d593164cfa/lyricwikia/lyricwikia.py#L20-L24
train
enricobacis/lyricwikia
lyricwikia/lyricwikia.py
get_lyrics
def get_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve the lyrics of the song and return the first one in case multiple versions are available.""" return get_all_lyrics(artist, song, linesep, timeout)[0]
python
def get_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve the lyrics of the song and return the first one in case multiple versions are available.""" return get_all_lyrics(artist, song, linesep, timeout)[0]
[ "def", "get_lyrics", "(", "artist", ",", "song", ",", "linesep", "=", "'\\n'", ",", "timeout", "=", "None", ")", ":", "return", "get_all_lyrics", "(", "artist", ",", "song", ",", "linesep", ",", "timeout", ")", "[", "0", "]" ]
Retrieve the lyrics of the song and return the first one in case multiple versions are available.
[ "Retrieve", "the", "lyrics", "of", "the", "song", "and", "return", "the", "first", "one", "in", "case", "multiple", "versions", "are", "available", "." ]
bc6caa7f745f1d54adf3ba1a72df76d593164cfa
https://github.com/enricobacis/lyricwikia/blob/bc6caa7f745f1d54adf3ba1a72df76d593164cfa/lyricwikia/lyricwikia.py#L27-L30
train
enricobacis/lyricwikia
lyricwikia/lyricwikia.py
get_all_lyrics
def get_all_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve a list of all the lyrics versions of a song.""" url = create_url(artist, song) response = _requests.get(url, timeout=timeout) soup = _BeautifulSoup(response.content, "html.parser") lyricboxes = soup.findAll('div', {'class': 'lyricbox'}) if not lyricboxes: raise LyricsNotFound('Cannot download lyrics') for lyricbox in lyricboxes: for br in lyricbox.findAll('br'): br.replace_with(linesep) return [lyricbox.text.strip() for lyricbox in lyricboxes]
python
def get_all_lyrics(artist, song, linesep='\n', timeout=None): """Retrieve a list of all the lyrics versions of a song.""" url = create_url(artist, song) response = _requests.get(url, timeout=timeout) soup = _BeautifulSoup(response.content, "html.parser") lyricboxes = soup.findAll('div', {'class': 'lyricbox'}) if not lyricboxes: raise LyricsNotFound('Cannot download lyrics') for lyricbox in lyricboxes: for br in lyricbox.findAll('br'): br.replace_with(linesep) return [lyricbox.text.strip() for lyricbox in lyricboxes]
[ "def", "get_all_lyrics", "(", "artist", ",", "song", ",", "linesep", "=", "'\\n'", ",", "timeout", "=", "None", ")", ":", "url", "=", "create_url", "(", "artist", ",", "song", ")", "response", "=", "_requests", ".", "get", "(", "url", ",", "timeout", ...
Retrieve a list of all the lyrics versions of a song.
[ "Retrieve", "a", "list", "of", "all", "the", "lyrics", "versions", "of", "a", "song", "." ]
bc6caa7f745f1d54adf3ba1a72df76d593164cfa
https://github.com/enricobacis/lyricwikia/blob/bc6caa7f745f1d54adf3ba1a72df76d593164cfa/lyricwikia/lyricwikia.py#L33-L47
train
melizalab/arf
arf.py
open_file
def open_file(name, mode=None, driver=None, libver=None, userblock_size=None, **kwargs): """Open an ARF file, creating as necessary. Use this instead of h5py.File to ensure that root-level attributes and group creation property lists are set correctly. """ import sys import os from h5py import h5p from h5py._hl import files try: # If the byte string doesn't match the default # encoding, just pass it on as-is. Note Unicode # objects can always be encoded. name = name.encode(sys.getfilesystemencoding()) except (UnicodeError, LookupError): pass exists = os.path.exists(name) try: fcpl = h5p.create(h5p.FILE_CREATE) fcpl.set_link_creation_order( h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) except AttributeError: # older version of h5py fp = files.File(name, mode=mode, driver=driver, libver=libver, **kwargs) else: fapl = files.make_fapl(driver, libver, **kwargs) fp = files.File(files.make_fid(name, mode, userblock_size, fapl, fcpl)) if not exists and fp.mode == 'r+': set_attributes(fp, arf_library='python', arf_library_version=__version__, arf_version=spec_version) return fp
python
def open_file(name, mode=None, driver=None, libver=None, userblock_size=None, **kwargs): """Open an ARF file, creating as necessary. Use this instead of h5py.File to ensure that root-level attributes and group creation property lists are set correctly. """ import sys import os from h5py import h5p from h5py._hl import files try: # If the byte string doesn't match the default # encoding, just pass it on as-is. Note Unicode # objects can always be encoded. name = name.encode(sys.getfilesystemencoding()) except (UnicodeError, LookupError): pass exists = os.path.exists(name) try: fcpl = h5p.create(h5p.FILE_CREATE) fcpl.set_link_creation_order( h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) except AttributeError: # older version of h5py fp = files.File(name, mode=mode, driver=driver, libver=libver, **kwargs) else: fapl = files.make_fapl(driver, libver, **kwargs) fp = files.File(files.make_fid(name, mode, userblock_size, fapl, fcpl)) if not exists and fp.mode == 'r+': set_attributes(fp, arf_library='python', arf_library_version=__version__, arf_version=spec_version) return fp
[ "def", "open_file", "(", "name", ",", "mode", "=", "None", ",", "driver", "=", "None", ",", "libver", "=", "None", ",", "userblock_size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "import", "sys", "import", "os", "from", "h5py", "import", "h5p"...
Open an ARF file, creating as necessary. Use this instead of h5py.File to ensure that root-level attributes and group creation property lists are set correctly.
[ "Open", "an", "ARF", "file", "creating", "as", "necessary", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L42-L79
train
melizalab/arf
arf.py
create_entry
def create_entry(group, name, timestamp, **attributes): """Create a new ARF entry under group, setting required attributes. An entry is an abstract collection of data which all refer to the same time frame. Data can include physiological recordings, sound recordings, and derived data such as spike times and labels. See add_data() for information on how data are stored. name -- the name of the new entry. any valid python string. timestamp -- timestamp of entry (datetime object, or seconds since January 1, 1970). Can be an integer, a float, or a tuple of integers (seconds, microsceconds) Additional keyword arguments are set as attributes on created entry. Returns: newly created entry object """ # create group using low-level interface to store creation order from h5py import h5p, h5g, _hl try: gcpl = h5p.create(h5p.GROUP_CREATE) gcpl.set_link_creation_order( h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) except AttributeError: grp = group.create_group(name) else: name, lcpl = group._e(name, lcpl=True) grp = _hl.group.Group(h5g.create(group.id, name, lcpl=lcpl, gcpl=gcpl)) set_uuid(grp, attributes.pop("uuid", None)) set_attributes(grp, timestamp=convert_timestamp(timestamp), **attributes) return grp
python
def create_entry(group, name, timestamp, **attributes): """Create a new ARF entry under group, setting required attributes. An entry is an abstract collection of data which all refer to the same time frame. Data can include physiological recordings, sound recordings, and derived data such as spike times and labels. See add_data() for information on how data are stored. name -- the name of the new entry. any valid python string. timestamp -- timestamp of entry (datetime object, or seconds since January 1, 1970). Can be an integer, a float, or a tuple of integers (seconds, microsceconds) Additional keyword arguments are set as attributes on created entry. Returns: newly created entry object """ # create group using low-level interface to store creation order from h5py import h5p, h5g, _hl try: gcpl = h5p.create(h5p.GROUP_CREATE) gcpl.set_link_creation_order( h5p.CRT_ORDER_TRACKED | h5p.CRT_ORDER_INDEXED) except AttributeError: grp = group.create_group(name) else: name, lcpl = group._e(name, lcpl=True) grp = _hl.group.Group(h5g.create(group.id, name, lcpl=lcpl, gcpl=gcpl)) set_uuid(grp, attributes.pop("uuid", None)) set_attributes(grp, timestamp=convert_timestamp(timestamp), **attributes) return grp
[ "def", "create_entry", "(", "group", ",", "name", ",", "timestamp", ",", "*", "*", "attributes", ")", ":", "# create group using low-level interface to store creation order", "from", "h5py", "import", "h5p", ",", "h5g", ",", "_hl", "try", ":", "gcpl", "=", "h5p"...
Create a new ARF entry under group, setting required attributes. An entry is an abstract collection of data which all refer to the same time frame. Data can include physiological recordings, sound recordings, and derived data such as spike times and labels. See add_data() for information on how data are stored. name -- the name of the new entry. any valid python string. timestamp -- timestamp of entry (datetime object, or seconds since January 1, 1970). Can be an integer, a float, or a tuple of integers (seconds, microsceconds) Additional keyword arguments are set as attributes on created entry. Returns: newly created entry object
[ "Create", "a", "new", "ARF", "entry", "under", "group", "setting", "required", "attributes", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L82-L116
train
melizalab/arf
arf.py
create_dataset
def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED, chunks=True, maxshape=None, compression=None, **attributes): """Create an ARF dataset under group, setting required attributes Required arguments: name -- the name of dataset in which to store the data data -- the data to store Data can be of the following types: * sampled data: an N-D numerical array of measurements * "simple" event data: a 1-D array of times * "complex" event data: a 1-D array of records, with field 'start' required Optional arguments: datatype -- a code defining the nature of the data in the channel units -- channel units (optional for sampled data, otherwise required) sampling_rate -- required for sampled data and event data with units=='samples' Arguments passed to h5py: maxshape -- make the node resizable up to this shape. Use None for axes that need to be unlimited. chunks -- specify the chunk size. The optimal chunk size depends on the intended use of the data. For single-channel sampled data the auto-chunking (True) is probably best. compression -- compression strategy. Can be 'gzip', 'szip', 'lzf' or an integer in range(10) specifying gzip(N). Only gzip is really portable. Additional arguments are set as attributes on the created dataset Returns the created dataset """ from numpy import asarray srate = attributes.get('sampling_rate', None) # check data validity before doing anything if not hasattr(data, 'dtype'): data = asarray(data) if data.dtype.kind in ('S', 'O', 'U'): raise ValueError( "data must be in array with numeric or compound type") if data.dtype.kind == 'V': if 'start' not in data.dtype.names: raise ValueError("complex event data requires 'start' field") if not isinstance(units, (list, tuple)): raise ValueError("complex event data requires sequence of units") if not len(units) == len(data.dtype.names): raise ValueError("number of units doesn't match number of fields") if units == '': if srate is None or not srate > 0: raise ValueError( "unitless data assumed time series and requires sampling_rate attribute") elif units == 'samples': if srate is None or not srate > 0: raise ValueError( "data with units of 'samples' requires sampling_rate attribute") # NB: can't really catch case where sampled data has units but doesn't # have sampling_rate attribute dset = group.create_dataset( name, data=data, maxshape=maxshape, chunks=chunks, compression=compression) set_attributes(dset, units=units, datatype=datatype, **attributes) return dset
python
def create_dataset(group, name, data, units='', datatype=DataTypes.UNDEFINED, chunks=True, maxshape=None, compression=None, **attributes): """Create an ARF dataset under group, setting required attributes Required arguments: name -- the name of dataset in which to store the data data -- the data to store Data can be of the following types: * sampled data: an N-D numerical array of measurements * "simple" event data: a 1-D array of times * "complex" event data: a 1-D array of records, with field 'start' required Optional arguments: datatype -- a code defining the nature of the data in the channel units -- channel units (optional for sampled data, otherwise required) sampling_rate -- required for sampled data and event data with units=='samples' Arguments passed to h5py: maxshape -- make the node resizable up to this shape. Use None for axes that need to be unlimited. chunks -- specify the chunk size. The optimal chunk size depends on the intended use of the data. For single-channel sampled data the auto-chunking (True) is probably best. compression -- compression strategy. Can be 'gzip', 'szip', 'lzf' or an integer in range(10) specifying gzip(N). Only gzip is really portable. Additional arguments are set as attributes on the created dataset Returns the created dataset """ from numpy import asarray srate = attributes.get('sampling_rate', None) # check data validity before doing anything if not hasattr(data, 'dtype'): data = asarray(data) if data.dtype.kind in ('S', 'O', 'U'): raise ValueError( "data must be in array with numeric or compound type") if data.dtype.kind == 'V': if 'start' not in data.dtype.names: raise ValueError("complex event data requires 'start' field") if not isinstance(units, (list, tuple)): raise ValueError("complex event data requires sequence of units") if not len(units) == len(data.dtype.names): raise ValueError("number of units doesn't match number of fields") if units == '': if srate is None or not srate > 0: raise ValueError( "unitless data assumed time series and requires sampling_rate attribute") elif units == 'samples': if srate is None or not srate > 0: raise ValueError( "data with units of 'samples' requires sampling_rate attribute") # NB: can't really catch case where sampled data has units but doesn't # have sampling_rate attribute dset = group.create_dataset( name, data=data, maxshape=maxshape, chunks=chunks, compression=compression) set_attributes(dset, units=units, datatype=datatype, **attributes) return dset
[ "def", "create_dataset", "(", "group", ",", "name", ",", "data", ",", "units", "=", "''", ",", "datatype", "=", "DataTypes", ".", "UNDEFINED", ",", "chunks", "=", "True", ",", "maxshape", "=", "None", ",", "compression", "=", "None", ",", "*", "*", "...
Create an ARF dataset under group, setting required attributes Required arguments: name -- the name of dataset in which to store the data data -- the data to store Data can be of the following types: * sampled data: an N-D numerical array of measurements * "simple" event data: a 1-D array of times * "complex" event data: a 1-D array of records, with field 'start' required Optional arguments: datatype -- a code defining the nature of the data in the channel units -- channel units (optional for sampled data, otherwise required) sampling_rate -- required for sampled data and event data with units=='samples' Arguments passed to h5py: maxshape -- make the node resizable up to this shape. Use None for axes that need to be unlimited. chunks -- specify the chunk size. The optimal chunk size depends on the intended use of the data. For single-channel sampled data the auto-chunking (True) is probably best. compression -- compression strategy. Can be 'gzip', 'szip', 'lzf' or an integer in range(10) specifying gzip(N). Only gzip is really portable. Additional arguments are set as attributes on the created dataset Returns the created dataset
[ "Create", "an", "ARF", "dataset", "under", "group", "setting", "required", "attributes" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L119-L181
train
melizalab/arf
arf.py
create_table
def create_table(group, name, dtype, **attributes): """Create a new array dataset under group with compound datatype and maxshape=(None,)""" dset = group.create_dataset( name, shape=(0,), dtype=dtype, maxshape=(None,)) set_attributes(dset, **attributes) return dset
python
def create_table(group, name, dtype, **attributes): """Create a new array dataset under group with compound datatype and maxshape=(None,)""" dset = group.create_dataset( name, shape=(0,), dtype=dtype, maxshape=(None,)) set_attributes(dset, **attributes) return dset
[ "def", "create_table", "(", "group", ",", "name", ",", "dtype", ",", "*", "*", "attributes", ")", ":", "dset", "=", "group", ".", "create_dataset", "(", "name", ",", "shape", "=", "(", "0", ",", ")", ",", "dtype", "=", "dtype", ",", "maxshape", "="...
Create a new array dataset under group with compound datatype and maxshape=(None,)
[ "Create", "a", "new", "array", "dataset", "under", "group", "with", "compound", "datatype", "and", "maxshape", "=", "(", "None", ")" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L184-L189
train
melizalab/arf
arf.py
append_data
def append_data(dset, data): """Append data to dset along axis 0. Data must be a single element or a 1D array of the same type as the dataset (including compound datatypes).""" N = data.shape[0] if hasattr(data, 'shape') else 1 if N == 0: return oldlen = dset.shape[0] newlen = oldlen + N dset.resize(newlen, axis=0) dset[oldlen:] = data
python
def append_data(dset, data): """Append data to dset along axis 0. Data must be a single element or a 1D array of the same type as the dataset (including compound datatypes).""" N = data.shape[0] if hasattr(data, 'shape') else 1 if N == 0: return oldlen = dset.shape[0] newlen = oldlen + N dset.resize(newlen, axis=0) dset[oldlen:] = data
[ "def", "append_data", "(", "dset", ",", "data", ")", ":", "N", "=", "data", ".", "shape", "[", "0", "]", "if", "hasattr", "(", "data", ",", "'shape'", ")", "else", "1", "if", "N", "==", "0", ":", "return", "oldlen", "=", "dset", ".", "shape", "...
Append data to dset along axis 0. Data must be a single element or a 1D array of the same type as the dataset (including compound datatypes).
[ "Append", "data", "to", "dset", "along", "axis", "0", ".", "Data", "must", "be", "a", "single", "element", "or", "a", "1D", "array", "of", "the", "same", "type", "as", "the", "dataset", "(", "including", "compound", "datatypes", ")", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L192-L201
train
melizalab/arf
arf.py
check_file_version
def check_file_version(file): """Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWarning for (potentially) forwards-incompatible files, and UserWarning for files that may not have been created by an ARF library. Returns the version for the file """ from distutils.version import StrictVersion as Version try: ver = file.attrs.get('arf_version', None) if ver is None: ver = file.attrs['arf_library_version'] except KeyError: raise UserWarning( "Unable to determine ARF version for {0.filename};" "created by another program?".format(file)) try: # if the attribute is stored as a string, it's ascii-encoded ver = ver.decode("ascii") except (LookupError, AttributeError): pass # should be backwards compatible after 1.1 file_version = Version(ver) if file_version < Version('1.1'): raise DeprecationWarning( "ARF library {} may have trouble reading file " "version {} (< 1.1)".format(version, file_version)) elif file_version >= Version('3.0'): raise FutureWarning( "ARF library {} may be incompatible with file " "version {} (>= 3.0)".format(version, file_version)) return file_version
python
def check_file_version(file): """Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWarning for (potentially) forwards-incompatible files, and UserWarning for files that may not have been created by an ARF library. Returns the version for the file """ from distutils.version import StrictVersion as Version try: ver = file.attrs.get('arf_version', None) if ver is None: ver = file.attrs['arf_library_version'] except KeyError: raise UserWarning( "Unable to determine ARF version for {0.filename};" "created by another program?".format(file)) try: # if the attribute is stored as a string, it's ascii-encoded ver = ver.decode("ascii") except (LookupError, AttributeError): pass # should be backwards compatible after 1.1 file_version = Version(ver) if file_version < Version('1.1'): raise DeprecationWarning( "ARF library {} may have trouble reading file " "version {} (< 1.1)".format(version, file_version)) elif file_version >= Version('3.0'): raise FutureWarning( "ARF library {} may be incompatible with file " "version {} (>= 3.0)".format(version, file_version)) return file_version
[ "def", "check_file_version", "(", "file", ")", ":", "from", "distutils", ".", "version", "import", "StrictVersion", "as", "Version", "try", ":", "ver", "=", "file", ".", "attrs", ".", "get", "(", "'arf_version'", ",", "None", ")", "if", "ver", "is", "Non...
Check the ARF version attribute of file for compatibility. Raises DeprecationWarning for backwards-incompatible files, FutureWarning for (potentially) forwards-incompatible files, and UserWarning for files that may not have been created by an ARF library. Returns the version for the file
[ "Check", "the", "ARF", "version", "attribute", "of", "file", "for", "compatibility", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L204-L238
train
melizalab/arf
arf.py
set_attributes
def set_attributes(node, overwrite=True, **attributes): """Set multiple attributes on node. If overwrite is False, and the attribute already exists, does nothing. If the value for a key is None, the attribute is deleted. """ aset = node.attrs for k, v in attributes.items(): if not overwrite and k in aset: pass elif v is None: if k in aset: del aset[k] else: aset[k] = v
python
def set_attributes(node, overwrite=True, **attributes): """Set multiple attributes on node. If overwrite is False, and the attribute already exists, does nothing. If the value for a key is None, the attribute is deleted. """ aset = node.attrs for k, v in attributes.items(): if not overwrite and k in aset: pass elif v is None: if k in aset: del aset[k] else: aset[k] = v
[ "def", "set_attributes", "(", "node", ",", "overwrite", "=", "True", ",", "*", "*", "attributes", ")", ":", "aset", "=", "node", ".", "attrs", "for", "k", ",", "v", "in", "attributes", ".", "items", "(", ")", ":", "if", "not", "overwrite", "and", "...
Set multiple attributes on node. If overwrite is False, and the attribute already exists, does nothing. If the value for a key is None, the attribute is deleted.
[ "Set", "multiple", "attributes", "on", "node", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L241-L256
train
melizalab/arf
arf.py
keys_by_creation
def keys_by_creation(group): """Returns a sequence of links in group in order of creation. Raises an error if the group was not set to track creation order. """ from h5py import h5 out = [] try: group._id.links.iterate( out.append, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER_INC) except (AttributeError, RuntimeError): # pre 2.2 shim def f(name): if name.find(b'/', 1) == -1: out.append(name) group._id.links.visit( f, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER_INC) return map(group._d, out)
python
def keys_by_creation(group): """Returns a sequence of links in group in order of creation. Raises an error if the group was not set to track creation order. """ from h5py import h5 out = [] try: group._id.links.iterate( out.append, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER_INC) except (AttributeError, RuntimeError): # pre 2.2 shim def f(name): if name.find(b'/', 1) == -1: out.append(name) group._id.links.visit( f, idx_type=h5.INDEX_CRT_ORDER, order=h5.ITER_INC) return map(group._d, out)
[ "def", "keys_by_creation", "(", "group", ")", ":", "from", "h5py", "import", "h5", "out", "=", "[", "]", "try", ":", "group", ".", "_id", ".", "links", ".", "iterate", "(", "out", ".", "append", ",", "idx_type", "=", "h5", ".", "INDEX_CRT_ORDER", ","...
Returns a sequence of links in group in order of creation. Raises an error if the group was not set to track creation order.
[ "Returns", "a", "sequence", "of", "links", "in", "group", "in", "order", "of", "creation", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L259-L277
train
melizalab/arf
arf.py
convert_timestamp
def convert_timestamp(obj): """Make an ARF timestamp from an object. Argument can be a datetime.datetime object, a time.struct_time, an integer, a float, or a tuple of integers. The returned value is a numpy array with the integer number of seconds since the Epoch and any additional microseconds. Note that because floating point values are approximate, the conversion between float and integer tuple may not be reversible. """ import numbers from datetime import datetime from time import mktime, struct_time from numpy import zeros out = zeros(2, dtype='int64') if isinstance(obj, datetime): out[0] = mktime(obj.timetuple()) out[1] = obj.microsecond elif isinstance(obj, struct_time): out[0] = mktime(obj) elif isinstance(obj, numbers.Integral): out[0] = obj elif isinstance(obj, numbers.Real): out[0] = obj out[1] = (obj - out[0]) * 1e6 else: try: out[:2] = obj[:2] except: raise TypeError("unable to convert %s to timestamp" % obj) return out
python
def convert_timestamp(obj): """Make an ARF timestamp from an object. Argument can be a datetime.datetime object, a time.struct_time, an integer, a float, or a tuple of integers. The returned value is a numpy array with the integer number of seconds since the Epoch and any additional microseconds. Note that because floating point values are approximate, the conversion between float and integer tuple may not be reversible. """ import numbers from datetime import datetime from time import mktime, struct_time from numpy import zeros out = zeros(2, dtype='int64') if isinstance(obj, datetime): out[0] = mktime(obj.timetuple()) out[1] = obj.microsecond elif isinstance(obj, struct_time): out[0] = mktime(obj) elif isinstance(obj, numbers.Integral): out[0] = obj elif isinstance(obj, numbers.Real): out[0] = obj out[1] = (obj - out[0]) * 1e6 else: try: out[:2] = obj[:2] except: raise TypeError("unable to convert %s to timestamp" % obj) return out
[ "def", "convert_timestamp", "(", "obj", ")", ":", "import", "numbers", "from", "datetime", "import", "datetime", "from", "time", "import", "mktime", ",", "struct_time", "from", "numpy", "import", "zeros", "out", "=", "zeros", "(", "2", ",", "dtype", "=", "...
Make an ARF timestamp from an object. Argument can be a datetime.datetime object, a time.struct_time, an integer, a float, or a tuple of integers. The returned value is a numpy array with the integer number of seconds since the Epoch and any additional microseconds. Note that because floating point values are approximate, the conversion between float and integer tuple may not be reversible.
[ "Make", "an", "ARF", "timestamp", "from", "an", "object", "." ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L280-L313
train
melizalab/arf
arf.py
timestamp_to_datetime
def timestamp_to_datetime(timestamp): """Convert an ARF timestamp to a datetime.datetime object (naive local time)""" from datetime import datetime, timedelta obj = datetime.fromtimestamp(timestamp[0]) return obj + timedelta(microseconds=int(timestamp[1]))
python
def timestamp_to_datetime(timestamp): """Convert an ARF timestamp to a datetime.datetime object (naive local time)""" from datetime import datetime, timedelta obj = datetime.fromtimestamp(timestamp[0]) return obj + timedelta(microseconds=int(timestamp[1]))
[ "def", "timestamp_to_datetime", "(", "timestamp", ")", ":", "from", "datetime", "import", "datetime", ",", "timedelta", "obj", "=", "datetime", ".", "fromtimestamp", "(", "timestamp", "[", "0", "]", ")", "return", "obj", "+", "timedelta", "(", "microseconds", ...
Convert an ARF timestamp to a datetime.datetime object (naive local time)
[ "Convert", "an", "ARF", "timestamp", "to", "a", "datetime", ".", "datetime", "object", "(", "naive", "local", "time", ")" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L316-L320
train
melizalab/arf
arf.py
set_uuid
def set_uuid(obj, uuid=None): """Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype """ from uuid import uuid4, UUID if uuid is None: uuid = uuid4() elif isinstance(uuid, bytes): if len(uuid) == 16: uuid = UUID(bytes=uuid) else: uuid = UUID(hex=uuid) if "uuid" in obj.attrs: del obj.attrs["uuid"] obj.attrs.create("uuid", str(uuid).encode('ascii'), dtype="|S36")
python
def set_uuid(obj, uuid=None): """Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype """ from uuid import uuid4, UUID if uuid is None: uuid = uuid4() elif isinstance(uuid, bytes): if len(uuid) == 16: uuid = UUID(bytes=uuid) else: uuid = UUID(hex=uuid) if "uuid" in obj.attrs: del obj.attrs["uuid"] obj.attrs.create("uuid", str(uuid).encode('ascii'), dtype="|S36")
[ "def", "set_uuid", "(", "obj", ",", "uuid", "=", "None", ")", ":", "from", "uuid", "import", "uuid4", ",", "UUID", "if", "uuid", "is", "None", ":", "uuid", "=", "uuid4", "(", ")", "elif", "isinstance", "(", "uuid", ",", "bytes", ")", ":", "if", "...
Set the uuid attribute of an HDF5 object. Use this method to ensure correct dtype
[ "Set", "the", "uuid", "attribute", "of", "an", "HDF5", "object", ".", "Use", "this", "method", "to", "ensure", "correct", "dtype" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L328-L341
train
melizalab/arf
arf.py
get_uuid
def get_uuid(obj): """Return the uuid for obj, or null uuid if none is set""" # TODO: deprecate null uuid ret val from uuid import UUID try: uuid = obj.attrs['uuid'] except KeyError: return UUID(int=0) # convert to unicode for python 3 try: uuid = uuid.decode('ascii') except (LookupError, AttributeError): pass return UUID(uuid)
python
def get_uuid(obj): """Return the uuid for obj, or null uuid if none is set""" # TODO: deprecate null uuid ret val from uuid import UUID try: uuid = obj.attrs['uuid'] except KeyError: return UUID(int=0) # convert to unicode for python 3 try: uuid = uuid.decode('ascii') except (LookupError, AttributeError): pass return UUID(uuid)
[ "def", "get_uuid", "(", "obj", ")", ":", "# TODO: deprecate null uuid ret val", "from", "uuid", "import", "UUID", "try", ":", "uuid", "=", "obj", ".", "attrs", "[", "'uuid'", "]", "except", "KeyError", ":", "return", "UUID", "(", "int", "=", "0", ")", "#...
Return the uuid for obj, or null uuid if none is set
[ "Return", "the", "uuid", "for", "obj", "or", "null", "uuid", "if", "none", "is", "set" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L344-L357
train
melizalab/arf
arf.py
count_children
def count_children(obj, type=None): """Return the number of children of obj, optionally restricting by class""" if type is None: return len(obj) else: # there doesn't appear to be any hdf5 function for getting this # information without inspecting each child, which makes this somewhat # slow return sum(1 for x in obj if obj.get(x, getclass=True) is type)
python
def count_children(obj, type=None): """Return the number of children of obj, optionally restricting by class""" if type is None: return len(obj) else: # there doesn't appear to be any hdf5 function for getting this # information without inspecting each child, which makes this somewhat # slow return sum(1 for x in obj if obj.get(x, getclass=True) is type)
[ "def", "count_children", "(", "obj", ",", "type", "=", "None", ")", ":", "if", "type", "is", "None", ":", "return", "len", "(", "obj", ")", "else", ":", "# there doesn't appear to be any hdf5 function for getting this", "# information without inspecting each child, whic...
Return the number of children of obj, optionally restricting by class
[ "Return", "the", "number", "of", "children", "of", "obj", "optionally", "restricting", "by", "class" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L360-L368
train
melizalab/arf
arf.py
DataTypes._todict
def _todict(cls): """ generate a dict keyed by value """ return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_'))
python
def _todict(cls): """ generate a dict keyed by value """ return dict((getattr(cls, attr), attr) for attr in dir(cls) if not attr.startswith('_'))
[ "def", "_todict", "(", "cls", ")", ":", "return", "dict", "(", "(", "getattr", "(", "cls", ",", "attr", ")", ",", "attr", ")", "for", "attr", "in", "dir", "(", "cls", ")", "if", "not", "attr", ".", "startswith", "(", "'_'", ")", ")" ]
generate a dict keyed by value
[ "generate", "a", "dict", "keyed", "by", "value" ]
71746d9edbe7993a783d4acaf84b9631f3230283
https://github.com/melizalab/arf/blob/71746d9edbe7993a783d4acaf84b9631f3230283/arf.py#L32-L34
train
singularityhub/singularity-python
singularity/views/utils.py
get_template
def get_template(template_name,fields=None): '''get_template will return a template in the template folder, with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"} ''' template = None if not template_name.endswith('.html'): template_name = "%s.html" %(template_name) here = "%s/cli/app/templates" %(get_installdir()) template_path = "%s/%s" %(here,template_name) if os.path.exists(template_path): template = ''.join(read_file(template_path)) if fields is not None: for tag,sub in fields.items(): template = template.replace(tag,sub) return template
python
def get_template(template_name,fields=None): '''get_template will return a template in the template folder, with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"} ''' template = None if not template_name.endswith('.html'): template_name = "%s.html" %(template_name) here = "%s/cli/app/templates" %(get_installdir()) template_path = "%s/%s" %(here,template_name) if os.path.exists(template_path): template = ''.join(read_file(template_path)) if fields is not None: for tag,sub in fields.items(): template = template.replace(tag,sub) return template
[ "def", "get_template", "(", "template_name", ",", "fields", "=", "None", ")", ":", "template", "=", "None", "if", "not", "template_name", ".", "endswith", "(", "'.html'", ")", ":", "template_name", "=", "\"%s.html\"", "%", "(", "template_name", ")", "here", ...
get_template will return a template in the template folder, with some substitutions (eg, {'{{ graph | safe }}':"fill this in!"}
[ "get_template", "will", "return", "a", "template", "in", "the", "template", "folder", "with", "some", "substitutions", "(", "eg", "{", "{{", "graph", "|", "safe", "}}", ":", "fill", "this", "in!", "}" ]
498c3433724b332f7493fec632d8daf479f47b82
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/views/utils.py#L32-L46
train
singularityhub/singularity-python
singularity/analysis/compare.py
container_similarity_vector
def container_similarity_vector(container1=None,packages_set=None,by=None): '''container similarity_vector is similar to compare_packages, but intended to compare a container object (singularity image or singularity hub container) to a list of packages. If packages_set is not provided, the default used is 'docker-os'. This can be changed to 'docker-library', or if the user wants a custom list, should define custom_set. :param container1: singularity image or singularity hub container. :param packages_set: a name of a package set, provided are docker-os and docker-library :by: metrics to compare by (files.txt and or folders.txt) ''' if by == None: by = ['files.txt'] if not isinstance(by,list): by = [by] if not isinstance(packages_set,list): packages_set = [packages_set] comparisons = dict() for b in by: bot.debug("Starting comparisons for %s" %b) df = pandas.DataFrame(columns=packages_set) for package2 in packages_set: sim = calculate_similarity(container1=container1, image_package2=package2, by=b)[b] name1 = os.path.basename(package2).replace('.img.zip','') bot.debug("container vs. %s: %s" %(name1,sim)) df.loc["container",package2] = sim df.columns = [os.path.basename(x).replace('.img.zip','') for x in df.columns.tolist()] comparisons[b] = df return comparisons
python
def container_similarity_vector(container1=None,packages_set=None,by=None): '''container similarity_vector is similar to compare_packages, but intended to compare a container object (singularity image or singularity hub container) to a list of packages. If packages_set is not provided, the default used is 'docker-os'. This can be changed to 'docker-library', or if the user wants a custom list, should define custom_set. :param container1: singularity image or singularity hub container. :param packages_set: a name of a package set, provided are docker-os and docker-library :by: metrics to compare by (files.txt and or folders.txt) ''' if by == None: by = ['files.txt'] if not isinstance(by,list): by = [by] if not isinstance(packages_set,list): packages_set = [packages_set] comparisons = dict() for b in by: bot.debug("Starting comparisons for %s" %b) df = pandas.DataFrame(columns=packages_set) for package2 in packages_set: sim = calculate_similarity(container1=container1, image_package2=package2, by=b)[b] name1 = os.path.basename(package2).replace('.img.zip','') bot.debug("container vs. %s: %s" %(name1,sim)) df.loc["container",package2] = sim df.columns = [os.path.basename(x).replace('.img.zip','') for x in df.columns.tolist()] comparisons[b] = df return comparisons
[ "def", "container_similarity_vector", "(", "container1", "=", "None", ",", "packages_set", "=", "None", ",", "by", "=", "None", ")", ":", "if", "by", "==", "None", ":", "by", "=", "[", "'files.txt'", "]", "if", "not", "isinstance", "(", "by", ",", "lis...
container similarity_vector is similar to compare_packages, but intended to compare a container object (singularity image or singularity hub container) to a list of packages. If packages_set is not provided, the default used is 'docker-os'. This can be changed to 'docker-library', or if the user wants a custom list, should define custom_set. :param container1: singularity image or singularity hub container. :param packages_set: a name of a package set, provided are docker-os and docker-library :by: metrics to compare by (files.txt and or folders.txt)
[ "container", "similarity_vector", "is", "similar", "to", "compare_packages", "but", "intended", "to", "compare", "a", "container", "object", "(", "singularity", "image", "or", "singularity", "hub", "container", ")", "to", "a", "list", "of", "packages", ".", "If"...
498c3433724b332f7493fec632d8daf479f47b82
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/compare.py#L41-L75
train
singularityhub/singularity-python
singularity/analysis/compare.py
compare_singularity_images
def compare_singularity_images(image_paths1, image_paths2=None): '''compare_singularity_images is a wrapper for compare_containers to compare singularity containers. If image_paths2 is not defined, pairwise comparison is done with image_paths1 ''' repeat = False if image_paths2 is None: image_paths2 = image_paths1 repeat = True if not isinstance(image_paths1,list): image_paths1 = [image_paths1] if not isinstance(image_paths2,list): image_paths2 = [image_paths2] dfs = pandas.DataFrame(index=image_paths1,columns=image_paths2) comparisons_done = [] for image1 in image_paths1: fileobj1,tar1 = get_image_tar(image1) members1 = [x.name for x in tar1] for image2 in image_paths2: comparison_id = [image1,image2] comparison_id.sort() comparison_id = "".join(comparison_id) if comparison_id not in comparisons_done: if image1 == image2: sim = 1.0 else: fileobj2,tar2 = get_image_tar(image2) members2 = [x.name for x in tar2] c = compare_lists(members1, members2) sim = information_coefficient(c['total1'],c['total2'],c['intersect']) delete_image_tar(fileobj2, tar2) dfs.loc[image1,image2] = sim if repeat: dfs.loc[image2,image1] = sim comparisons_done.append(comparison_id) delete_image_tar(fileobj1, tar1) return dfs
python
def compare_singularity_images(image_paths1, image_paths2=None): '''compare_singularity_images is a wrapper for compare_containers to compare singularity containers. If image_paths2 is not defined, pairwise comparison is done with image_paths1 ''' repeat = False if image_paths2 is None: image_paths2 = image_paths1 repeat = True if not isinstance(image_paths1,list): image_paths1 = [image_paths1] if not isinstance(image_paths2,list): image_paths2 = [image_paths2] dfs = pandas.DataFrame(index=image_paths1,columns=image_paths2) comparisons_done = [] for image1 in image_paths1: fileobj1,tar1 = get_image_tar(image1) members1 = [x.name for x in tar1] for image2 in image_paths2: comparison_id = [image1,image2] comparison_id.sort() comparison_id = "".join(comparison_id) if comparison_id not in comparisons_done: if image1 == image2: sim = 1.0 else: fileobj2,tar2 = get_image_tar(image2) members2 = [x.name for x in tar2] c = compare_lists(members1, members2) sim = information_coefficient(c['total1'],c['total2'],c['intersect']) delete_image_tar(fileobj2, tar2) dfs.loc[image1,image2] = sim if repeat: dfs.loc[image2,image1] = sim comparisons_done.append(comparison_id) delete_image_tar(fileobj1, tar1) return dfs
[ "def", "compare_singularity_images", "(", "image_paths1", ",", "image_paths2", "=", "None", ")", ":", "repeat", "=", "False", "if", "image_paths2", "is", "None", ":", "image_paths2", "=", "image_paths1", "repeat", "=", "True", "if", "not", "isinstance", "(", "...
compare_singularity_images is a wrapper for compare_containers to compare singularity containers. If image_paths2 is not defined, pairwise comparison is done with image_paths1
[ "compare_singularity_images", "is", "a", "wrapper", "for", "compare_containers", "to", "compare", "singularity", "containers", ".", "If", "image_paths2", "is", "not", "defined", "pairwise", "comparison", "is", "done", "with", "image_paths1" ]
498c3433724b332f7493fec632d8daf479f47b82
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/compare.py#L78-L120
train
singularityhub/singularity-python
singularity/analysis/compare.py
compare_containers
def compare_containers(container1=None, container2=None): '''compare_containers will generate a data structure with common and unique files to two images. If environmental variable SINGULARITY_HUB is set, will use container database objects. :param container1: first container for comparison :param container2: second container for comparison if either not defined must include default compares just files ''' # Get files and folders for each container1_guts = get_container_contents(split_delim="\n", container=container1)['all'] container2_guts = get_container_contents(split_delim="\n", container=container2)['all'] # Do the comparison for each metric return compare_lists(container1_guts, container2_guts)
python
def compare_containers(container1=None, container2=None): '''compare_containers will generate a data structure with common and unique files to two images. If environmental variable SINGULARITY_HUB is set, will use container database objects. :param container1: first container for comparison :param container2: second container for comparison if either not defined must include default compares just files ''' # Get files and folders for each container1_guts = get_container_contents(split_delim="\n", container=container1)['all'] container2_guts = get_container_contents(split_delim="\n", container=container2)['all'] # Do the comparison for each metric return compare_lists(container1_guts, container2_guts)
[ "def", "compare_containers", "(", "container1", "=", "None", ",", "container2", "=", "None", ")", ":", "# Get files and folders for each", "container1_guts", "=", "get_container_contents", "(", "split_delim", "=", "\"\\n\"", ",", "container", "=", "container1", ")", ...
compare_containers will generate a data structure with common and unique files to two images. If environmental variable SINGULARITY_HUB is set, will use container database objects. :param container1: first container for comparison :param container2: second container for comparison if either not defined must include default compares just files
[ "compare_containers", "will", "generate", "a", "data", "structure", "with", "common", "and", "unique", "files", "to", "two", "images", ".", "If", "environmental", "variable", "SINGULARITY_HUB", "is", "set", "will", "use", "container", "database", "objects", ".", ...
498c3433724b332f7493fec632d8daf479f47b82
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/compare.py#L123-L140
train
singularityhub/singularity-python
singularity/analysis/compare.py
compare_lists
def compare_lists(list1,list2): '''compare lists is the lowest level that drives compare_containers and compare_packages. It returns a comparison object (dict) with the unique, total, and intersecting things between two lists :param list1: the list for container1 :param list2: the list for container2 ''' intersect = list(set(list1).intersection(list2)) unique1 = list(set(list1).difference(list2)) unique2 = list(set(list2).difference(list1)) # Return data structure comparison = {"intersect":intersect, "unique1": unique1, "unique2": unique2, "total1": len(list1), "total2": len(list2)} return comparison
python
def compare_lists(list1,list2): '''compare lists is the lowest level that drives compare_containers and compare_packages. It returns a comparison object (dict) with the unique, total, and intersecting things between two lists :param list1: the list for container1 :param list2: the list for container2 ''' intersect = list(set(list1).intersection(list2)) unique1 = list(set(list1).difference(list2)) unique2 = list(set(list2).difference(list1)) # Return data structure comparison = {"intersect":intersect, "unique1": unique1, "unique2": unique2, "total1": len(list1), "total2": len(list2)} return comparison
[ "def", "compare_lists", "(", "list1", ",", "list2", ")", ":", "intersect", "=", "list", "(", "set", "(", "list1", ")", ".", "intersection", "(", "list2", ")", ")", "unique1", "=", "list", "(", "set", "(", "list1", ")", ".", "difference", "(", "list2"...
compare lists is the lowest level that drives compare_containers and compare_packages. It returns a comparison object (dict) with the unique, total, and intersecting things between two lists :param list1: the list for container1 :param list2: the list for container2
[ "compare", "lists", "is", "the", "lowest", "level", "that", "drives", "compare_containers", "and", "compare_packages", ".", "It", "returns", "a", "comparison", "object", "(", "dict", ")", "with", "the", "unique", "total", "and", "intersecting", "things", "betwee...
498c3433724b332f7493fec632d8daf479f47b82
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/compare.py#L143-L160
train
singularityhub/singularity-python
singularity/analysis/compare.py
calculate_similarity
def calculate_similarity(container1=None, container2=None, comparison=None, metric=None): '''calculate_similarity will calculate similarity of two containers by files content, default will calculate 2.0*len(intersect) / total package1 + total package2 Parameters ========== container1: container 1 container2: container 2 must be defined or metric a function to take a total1, total2, and intersect count (we can make this more general if / when more are added) valid are currently files.txt or folders.txt comparison: the comparison result object for the tree. If provided, will skip over function to obtain it. ''' if metric is None: metric = information_coefficient if comparison == None: comparison = compare_containers(container1=container1, container2=container2) return metric(total1=comparison['total1'], total2=comparison['total2'], intersect=comparison["intersect"])
python
def calculate_similarity(container1=None, container2=None, comparison=None, metric=None): '''calculate_similarity will calculate similarity of two containers by files content, default will calculate 2.0*len(intersect) / total package1 + total package2 Parameters ========== container1: container 1 container2: container 2 must be defined or metric a function to take a total1, total2, and intersect count (we can make this more general if / when more are added) valid are currently files.txt or folders.txt comparison: the comparison result object for the tree. If provided, will skip over function to obtain it. ''' if metric is None: metric = information_coefficient if comparison == None: comparison = compare_containers(container1=container1, container2=container2) return metric(total1=comparison['total1'], total2=comparison['total2'], intersect=comparison["intersect"])
[ "def", "calculate_similarity", "(", "container1", "=", "None", ",", "container2", "=", "None", ",", "comparison", "=", "None", ",", "metric", "=", "None", ")", ":", "if", "metric", "is", "None", ":", "metric", "=", "information_coefficient", "if", "compariso...
calculate_similarity will calculate similarity of two containers by files content, default will calculate 2.0*len(intersect) / total package1 + total package2 Parameters ========== container1: container 1 container2: container 2 must be defined or metric a function to take a total1, total2, and intersect count (we can make this more general if / when more are added) valid are currently files.txt or folders.txt comparison: the comparison result object for the tree. If provided, will skip over function to obtain it.
[ "calculate_similarity", "will", "calculate", "similarity", "of", "two", "containers", "by", "files", "content", "default", "will", "calculate", "2", ".", "0", "*", "len", "(", "intersect", ")", "/", "total", "package1", "+", "total", "package2" ]
498c3433724b332f7493fec632d8daf479f47b82
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/analysis/compare.py#L163-L193
train