Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
24
24
input
stringlengths
69
2.76k
output
stringlengths
97
21.1k
62e60f43d76274f8a4026e28
def hydrate_time(nanoseconds, tz=None): """ Hydrator for `Time` and `LocalTime` values. :param nanoseconds: :param tz: :return: Time """
def hydrate_time(nanoseconds, tz=None): """ Hydrator for `Time` and `LocalTime` values. :param nanoseconds: :param tz: :return: Time """ from pytz import FixedOffset seconds, nanoseconds = map(int, divmod(nanoseconds, 1000000000)) minutes, seconds = map(int, divmod(seconds, 60)) hou...
62e60f3bd76274f8a4026e10
def dehydrate_timedelta(value): """ Dehydrator for `timedelta` values. :param value: :type value: timedelta :return: """
def dehydrate_timedelta(value): """ Dehydrator for `timedelta` values. :param value: :type value: timedelta :return: """ months = 0 days = value.days seconds = value.seconds nanoseconds = 1000 * value.microseconds return Structure(b"E", months, days, seconds, nanoseconds)
62e60f37d76274f8a4026dfd
def dehydrate_time(value): """ Dehydrator for `time` values. :param value: :type value: Time :return: """
def dehydrate_time(value): """ Dehydrator for `time` values. :param value: :type value: Time :return: """ if isinstance(value, Time): nanoseconds = value.ticks elif isinstance(value, time): nanoseconds = (3600000000000 * value.hour + 60000000000 * value.minute + ...
62e60f33d76274f8a4026de9
def dehydrate_point(value): """ Dehydrator for Point data. :param value: :type value: Point :return: """
def dehydrate_point(value): """ Dehydrator for Point data. :param value: :type value: Point :return: """ dim = len(value) if dim == 2: return Structure(b"X", value.srid, *value) elif dim == 3: return Structure(b"Y", value.srid, *value) else: raise ValueError(...
62e60ed4d76274f8a4026da0
def keys(self): """ Return the keys of the record. :return: list of key names """
def keys(self): """ Return the keys of the record. :return: list of key names """ return list(self.__keys)
62e60ecfd76274f8a4026d6a
@classmethod def protocol_handlers(cls, protocol_version=None): """ Return a dictionary of available Bolt protocol handlers, keyed by version tuple. If an explicit protocol version is provided, the dictionary will contain either zero or one items, depending on whether that versio...
@classmethod def protocol_handlers(cls, protocol_version=None): """ Return a dictionary of available Bolt protocol handlers, keyed by version tuple. If an explicit protocol version is provided, the dictionary will contain either zero or one items, depending on whether that versio...
62e60e49d76274f8a4026d25
def unit_of_work(metadata=None, timeout=None): """This function is a decorator for transaction functions that allows extra control over how the transaction is carried out. For example, a timeout may be applied:: from neo4j import unit_of_work @unit_of_work(timeout=100) def count_peopl...
def unit_of_work(metadata=None, timeout=None): """This function is a decorator for transaction functions that allows extra control over how the transaction is carried out. For example, a timeout may be applied:: from neo4j import unit_of_work @unit_of_work(timeout=100) def count_peopl...
62e60e05d76274f8a4026cfd
def index(self, key): """ Return the index of the given item. :param key: a key :return: index :rtype: int """
def index(self, key): """ Return the index of the given item. :param key: a key :return: index :rtype: int """ if isinstance(key, int): if 0 <= key < len(self.__keys): return key raise IndexError(key) elif isinstance(ke...
62e60da4d76274f8a4026cf1
def values(self, *keys): """ Return the values of the record, optionally filtering to include only certain values by index or key. :param keys: indexes or keys of the items to include; if none are provided, all values will be included :return: list of values ...
def values(self, *keys): """ Return the values of the record, optionally filtering to include only certain values by index or key. :param keys: indexes or keys of the items to include; if none are provided, all values will be included :return: list of values ...
62e60b10d76274f8a4026ccd
def data(self, *keys): """ Return the keys and values of this record as a dictionary, optionally including only certain values by index or key. Keys provided in the items that are not in the record will be inserted with a value of :const:`None`; indexes provided that are out ...
def data(self, *keys): """ Return the keys and values of this record as a dictionary, optionally including only certain values by index or key. Keys provided in the items that are not in the record will be inserted with a value of :const:`None`; indexes provided that are out ...
62e6087bd76274f8a4026bfa
def pop_u16(self): """ Remove the last two bytes of data, returning them as a big-endian 16-bit unsigned integer. """
def pop_u16(self): """ Remove the last two bytes of data, returning them as a big-endian 16-bit unsigned integer. """ if self.used >= 2: value = 0x100 * self.data[self.used - 2] + self.data[self.used - 1] self.used -= 2 return value else: ...
62e6087ad76274f8a4026bf2
def discard(self, n=-1, qid=-1, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a DISCARD message to the output queue. :param n: number of records to discard, default = -1 (ALL) :param qid: query ID to discard for, default = -1 (last query) ...
def discard(self, n=-1, qid=-1, dehydration_hooks=None, hydration_hooks=None, **handlers): # Just ignore n and qid, it is not supported in the Bolt 3 Protocol. log.debug("[#%04X] C: DISCARD_ALL", self.local_port) self._append(b"\x2F", (), Response(self, ...
62e60879d76274f8a4026bec
def begin(self, mode=None, bookmarks=None, metadata=None, timeout=None, db=None, imp_user=None, dehydration_hooks=None, hydration_hooks=None, **handlers): """ Appends a BEGIN message to the output queue. :param mode: access mode for routing - "READ" or "WRITE" (d...
def begin(self, mode=None, bookmarks=None, metadata=None, timeout=None, db=None, imp_user=None, dehydration_hooks=None, hydration_hooks=None, **handlers): if db is not None: raise ConfigurationError( "Database name parameter for selecting database is n...
62e60723d76274f8a4026b75
def round_half_to_even(n): """ >>> round_half_to_even(3) 3 >>> round_half_to_even(3.2) 3 >>> round_half_to_even(3.5) 4 >>> round_half_to_even(3.7) 4 >>> round_half_to_even(4) 4 >>> round_half_to_even(4.2) 4 >>> ...
def round_half_to_even(n): """ >>> round_half_to_even(3) 3 >>> round_half_to_even(3.2) 3 >>> round_half_to_even(3.5) 4 >>> round_half_to_even(3.7) 4 >>> round_half_to_even(4) 4 >>> round_half_to_even(4.2) 4 >>> ...
62e60707d76274f8a4026b69
def point_type(name, fields, srid_map): """ Dynamically create a Point subclass. """
def point_type(name, fields, srid_map): """ Dynamically create a Point subclass. """ def srid(self): try: return srid_map[len(self)] except KeyError: return None attributes = {"srid": property(srid)} for index, subclass_field in enumerate(fields): ...
62e5dc9ed76274f8a4026b5b
def deprecated(message): """ Decorator for deprecating functions and methods. :: @deprecated("'foo' has been deprecated in favour of 'bar'") def foo(x): pass """
def deprecated(message): """ Decorator for deprecating functions and methods. :: @deprecated("'foo' has been deprecated in favour of 'bar'") def foo(x): pass """ def decorator(f): if asyncio.iscoroutinefunction(f): @wraps(f) async def inner(...
62e4fc3c85ea98643089041e
def _inline_r_setup(code: str) -> str: """ Some behaviour of R cannot be configured via env variables, but can only be configured via R options once R has started. These are set here. """
def _inline_r_setup(code: str) -> str: """ Some behaviour of R cannot be configured via env variables, but can only be configured via R options once R has started. These are set here. """ with_option = f"""\ options(install.packages.compile.from.source = "never") {code} """ return wi...
62e4fbda85ea986430890405
def xargs( cmd: tuple[str, ...], varargs: Sequence[str], *, color: bool = False, target_concurrency: int = 1, _max_length: int = _get_platform_max_length(), **kwargs: Any, ) -> tuple[int, bytes]: """A simplified implementation of xargs. color: Make a pty ...
def xargs( cmd: tuple[str, ...], varargs: Sequence[str], *, color: bool = False, target_concurrency: int = 1, _max_length: int = _get_platform_max_length(), **kwargs: Any, ) -> tuple[int, bytes]: """A simplified implementation of xargs. color: Make a pty ...
62e4fbda85ea986430890403
def _shuffled(seq: Sequence[str]) -> list[str]: """Deterministically shuffle"""
def _shuffled(seq: Sequence[str]) -> list[str]: """Deterministically shuffle""" fixed_random = random.Random() fixed_random.seed(FIXED_RANDOM_SEED, version=1) seq = list(seq) fixed_random.shuffle(seq) return seq
62e4fb6585ea98643089032b
def parse_version(s: str) -> tuple[int, ...]: """poor man's version comparison"""
def parse_version(s: str) -> tuple[int, ...]: """poor man's version comparison""" return tuple(int(p) for p in s.split('.'))
62e4fb4d85ea9864308902e7
def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]: """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """
def normalize_cmd(cmd: tuple[str, ...]) -> tuple[str, ...]: """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(...
62b8d27a48ba5a41d1c3f4c6
def cached(cache, key=hashkey, lock=None): """Decorator to wrap a function with a memoizing callable that saves results in a cache. """
def cached(cache, key=hashkey, lock=None): """Decorator to wrap a function with a memoizing callable that saves results in a cache. """ def decorator(func): if cache is None: def wrapper(*args, **kwargs): return func(*args, **kwargs) elif lock is None: ...
62b8d24048ba5a41d1c3f49f
def ttl_cache(maxsize=128, ttl=600, timer=time.monotonic, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Recently Used (LRU) algorithm with a per-item time-to-live (TTL) value. """
def ttl_cache(maxsize=128, ttl=600, timer=time.monotonic, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Recently Used (LRU) algorithm with a per-item time-to-live (TTL) value. """ if maxsize is None: return _cache(...
62b8d23b48ba5a41d1c3f49a
def mru_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Most Recently Used (MRU) algorithm. """
def mru_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Most Recently Used (MRU) algorithm. """ if maxsize is None: return _cache(_UnboundCache(), typed) elif callable(maxsize): return _cache...
62b8d23948ba5a41d1c3f498
def lru_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Recently Used (LRU) algorithm. """
def lru_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Recently Used (LRU) algorithm. """ if maxsize is None: return _cache(_UnboundCache(), typed) elif callable(maxsize): return _cac...
62b8d23748ba5a41d1c3f496
def lfu_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm. """
def lfu_cache(maxsize=128, typed=False): """Decorator to wrap a function with a memoizing callable that saves up to `maxsize` results based on a Least Frequently Used (LFU) algorithm. """ if maxsize is None: return _cache(_UnboundCache(), typed) elif callable(maxsize): return _c...
62b8d22f48ba5a41d1c3f488
def popitem(self): """Remove and return the `(key, value)` pair first inserted."""
def popitem(self): """Remove and return the `(key, value)` pair first inserted.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from None else: return (key, self.pop(key))
62b8d22a48ba5a41d1c3f47e
def setdefault(self, key, default=None): """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
def setdefault(self, key, default=None): if key in self: value = self[key] else: self[key] = value = default return value
62b8d22948ba5a41d1c3f47c
def get(self, key, default=None): """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
def get(self, key, default=None): if key in self: return self[key] else: return default
62b8d22548ba5a41d1c3f472
def cachedmethod(cache, key=hashkey, lock=None): """Decorator to wrap a class or instance method with a memoizing callable that saves results in a cache. """
def cachedmethod(cache, key=hashkey, lock=None): """Decorator to wrap a class or instance method with a memoizing callable that saves results in a cache. """ def decorator(method): if lock is None: def wrapper(self, *args, **kwargs): c = cache(self) i...
62b8c517e0d34b282c18122e
@classmethod def extostr(cls, e, max_level=30, max_path_level=5): """ Format an exception. :param e: Any exception instance. :type e: Exception :param max_level: Maximum call stack level (default 30) :type max_level: int :param max_path_level: Maximum path...
@classmethod def extostr(cls, e, max_level=30, max_path_level=5): """ Format an exception. :param e: Any exception instance. :type e: Exception :param max_level: Maximum call stack level (default 30) :type max_level: int :param max_path_level: Maximum path...
62b8bbbfe0d34b282c181210
@staticmethod def append_text_to_file(file_name, text_buffer, encoding, overwrite=False): """ Write to the specified filename, the provided binary buffer Create the file if required. :param file_name: File name. :type file_name: str :param text_buffer: Text buffe...
@staticmethod def append_text_to_file(file_name, text_buffer, encoding, overwrite=False): """ Write to the specified filename, the provided binary buffer Create the file if required. :param file_name: File name. :type file_name: str :param text_buffer: Text buffe...
62b8bbbfe0d34b282c18120f
@staticmethod def file_to_textbuffer(file_name, encoding): """ Load a file toward a text buffer (UTF-8), using the specify encoding while reading. CAUTION : This will read the whole file IN MEMORY. :param file_name: File name. :type file_name: str :param encoding:...
@staticmethod def file_to_textbuffer(file_name, encoding): """ Load a file toward a text buffer (UTF-8), using the specify encoding while reading. CAUTION : This will read the whole file IN MEMORY. :param file_name: File name. :type file_name: str :param encoding:...
62b8bbbce0d34b282c18120d
@staticmethod def is_file_exist(file_name): """ Check if file name exist. :param file_name: File name. :type file_name: str :return: Return true (exist), false (do not exist, or invalid file name) :rtype bool """
@staticmethod def is_file_exist(file_name): """ Check if file name exist. :param file_name: File name. :type file_name: str :return: Return true (exist), false (do not exist, or invalid file name) :rtype bool """ # Check if file_name is No...
62b8b99de0d34b282c1811f8
@classmethod def _reset_logging(cls): """ Reset """
@classmethod def _reset_logging(cls): """ Reset """ # Found no way to fully reset the logging stuff while running # We reset root and all loggers to INFO, and kick handlers # Initialize root = logging.getLogger() root.setLevel(logging.getLevelNam...
62b8b59feb7e40a82d2d1291
def _getTargetClass(self): """ Define this to return the implementation in use, without the 'Py' or 'Fallback' suffix. """
def _getTargetClass(self): from zope.interface.declarations import getObjectSpecification return getObjectSpecification
62b8b590eb7e40a82d2d1275
def _legacy_mergeOrderings(orderings): """Merge multiple orderings so that within-ordering order is preserved Orderings are constrained in such a way that if an object appears in two or more orderings, then the suffix that begins with the object must be in both orderings. For example: >>> _me...
def _legacy_mergeOrderings(orderings): """Merge multiple orderings so that within-ordering order is preserved Orderings are constrained in such a way that if an object appears in two or more orderings, then the suffix that begins with the object must be in both orderings. For example: >>> _me...
62b8b58deb7e40a82d2d1269
def directlyProvidedBy(object): # pylint:disable=redefined-builtin """Return the interfaces directly provided by the given object The value returned is an `~zope.interface.interfaces.IDeclaration`. """
def directlyProvidedBy(object): # pylint:disable=redefined-builtin """Return the interfaces directly provided by the given object The value returned is an `~zope.interface.interfaces.IDeclaration`. """ provides = getattr(object, "__provides__", None) if ( provides is None # no spec ...
62b8b559eb7e40a82d2d11f8
def minimalBases(classes): """Reduce a list of base classes to its ordered minimum equivalent"""
def minimalBases(classes): """Reduce a list of base classes to its ordered minimum equivalent""" if not __python3: # pragma: no cover classes = [c for c in classes if c is not ClassType] candidates = [] for m in classes: for n in classes: if issubclass(n,m) and m is not n: ...
62b8b4b9eb7e40a82d2d1134
def namesAndDescriptions(self, all=False): # pylint:disable=redefined-builtin """Return attribute names and descriptions defined by interface."""
def namesAndDescriptions(self, all=False): # pylint:disable=redefined-builtin """Return attribute names and descriptions defined by interface.""" if not all: return self.__attrs.items() r = {} for base in self.__bases__[::-1]: r.update(dict(base.namesAndDescr...
62b8b416eb7e40a82d2d1129
def names(self, all=False): # pylint:disable=redefined-builtin """Return the attribute names defined by the interface."""
def names(self, all=False): # pylint:disable=redefined-builtin """Return the attribute names defined by the interface.""" if not all: return self.__attrs.keys() r = self.__attrs.copy() for base in self.__bases__: r.update(dict.fromkeys(base.names(all))) ...
62b8b3d6eb7e40a82d2d111c
def _normalizeargs(sequence, output=None): """Normalize declaration arguments Normalization arguments might contain Declarions, tuples, or single interfaces. Anything but individial interfaces or implements specs will be expanded. """
def _normalizeargs(sequence, output=None): """Normalize declaration arguments Normalization arguments might contain Declarions, tuples, or single interfaces. Anything but individial interfaces or implements specs will be expanded. """ if output is None: output = [] cls = sequence....
62b8b3d5eb7e40a82d2d1110
def _c_optimizations_available(): """ Return the C optimization module, if available, otherwise a false value. If the optimizations are required but not available, this raises the ImportError. This does not say whether they should be used or not. """
def _c_optimizations_available(): """ Return the C optimization module, if available, otherwise a false value. If the optimizations are required but not available, this raises the ImportError. This does not say whether they should be used or not. """ catch = () if _c_optimizations_requ...
62b8b3d4eb7e40a82d2d110f
def _should_attempt_c_optimizations(): """ Return a true value if we should attempt to use the C optimizations. This takes into account whether we're on PyPy and the value of the ``PURE_PYTHON`` environment variable, as defined in `_use_c_impl`. """
def _should_attempt_c_optimizations(): """ Return a true value if we should attempt to use the C optimizations. This takes into account whether we're on PyPy and the value of the ``PURE_PYTHON`` environment variable, as defined in `_use_c_impl`. """ is_pypy = hasattr(sys, 'pypy_version_info') ...
62b8b3d4eb7e40a82d2d110e
def _c_optimizations_ignored(): """ The opposite of `_c_optimizations_required`. """
def _c_optimizations_ignored(): """ The opposite of `_c_optimizations_required`. """ pure_env = os.environ.get('PURE_PYTHON') return pure_env is not None and pure_env != "0"
62b8b3d4eb7e40a82d2d110d
def _c_optimizations_required(): """ Return a true value if the C optimizations are required. This uses the ``PURE_PYTHON`` variable as documented in `_use_c_impl`. """
def _c_optimizations_required(): """ Return a true value if the C optimizations are required. This uses the ``PURE_PYTHON`` variable as documented in `_use_c_impl`. """ pure_env = os.environ.get('PURE_PYTHON') require_c = pure_env == "0" return require_c
62b87b989a0c4fa8b80b35ee
def reset(self): """Reset the histogram. Current context is reset to an empty dict. Bins are reinitialized with the *initial_value* or with *make_bins()* (depending on the initialization). """
def reset(self): """Reset the histogram. Current context is reset to an empty dict. Bins are reinitialized with the *initial_value* or with *make_bins()* (depending on the initialization). """ if self._make_bins is not None: self.bins = self._make_bins() ...
62b87b859a0c4fa8b80b35d7
def to_csv(self, separator=",", header=None): """.. deprecated:: 0.5 in Lena 0.5 to_csv is not used. Iterables are converted to tables. Convert graph's points to CSV. *separator* delimits values, the default is comma. *header*, if not ``None``, is the first string of...
def to_csv(self, separator=",", header=None): """.. deprecated:: 0.5 in Lena 0.5 to_csv is not used. Iterables are converted to tables. Convert graph's points to CSV. *separator* delimits values, the default is comma. *header*, if not ``None``, is the first string of...
62b87b839a0c4fa8b80b35cb
def _get_err_indices(self, coord_name): """Get error indices corresponding to a coordinate."""
def _get_err_indices(self, coord_name): """Get error indices corresponding to a coordinate.""" err_indices = [] dim = self.dim for ind, err in enumerate(self._parsed_error_names): if err[1] == coord_name: err_indices.append(ind+dim) return err_indi...
62b87b7e9a0c4fa8b80b35bc
def _update_context(self, context): """Update *context* with the properties of this graph. *context.error* is appended with indices of errors. Example subcontext for a graph with fields "E,t,error_E_low": {"error": {"x_low": {"index": 2}}}. Note that error names are called "...
def _update_context(self, context): """Update *context* with the properties of this graph. *context.error* is appended with indices of errors. Example subcontext for a graph with fields "E,t,error_E_low": {"error": {"x_low": {"index": 2}}}. Note that error names are called "...
62b87b4f9a0c4fa8b80b3580
def integral(bins, edges): """Compute integral (scale for a histogram). *bins* contain values, and *edges* form the mesh for the integration. Their format is defined in :class:`.histogram` description. """
def integral(bins, edges): """Compute integral (scale for a histogram). *bins* contain values, and *edges* form the mesh for the integration. Their format is defined in :class:`.histogram` description. """ total = 0 for ind, bin_content in iter_bins(bins): bin_lengths = [ ...
62b87b199a0c4fa8b80b354e
def is_fill_request_seq(seq): """Test whether *seq* can be converted to a FillRequestSeq. True only if it is a FillRequest element or contains at least one such, and it is not a Source sequence. """
def is_fill_request_seq(seq): """Test whether *seq* can be converted to a FillRequestSeq. True only if it is a FillRequest element or contains at least one such, and it is not a Source sequence. """ if is_source(seq): return False is_fcseq = False if hasattr(seq, "__iter__"): ...
62b87b099a0c4fa8b80b3538
def is_fill_request_el(obj): """Object contains executable methods 'fill' and 'request'."""
def is_fill_request_el(obj): """Object contains executable methods 'fill' and 'request'.""" return hasattr(obj, "fill") and hasattr(obj, "request") \ and callable(obj.fill) and callable(obj.request)
62b87af99a0c4fa8b80b3524
def is_run_el(obj): """Object contains executable method 'run'."""
def is_run_el(obj): """Object contains executable method 'run'.""" return hasattr(obj, "run") and callable(obj.run)
62b87af69a0c4fa8b80b351a
def is_fill_compute_el(obj): """Object contains executable methods 'fill' and 'compute'."""
def is_fill_compute_el(obj): """Object contains executable methods 'fill' and 'compute'.""" return (hasattr(obj, "fill") and hasattr(obj, "compute") and callable(obj.fill) and callable(obj.compute))
62b87af19a0c4fa8b80b34f7
def difference(d1, d2, level=-1): """Return a dictionary with items from *d1* not contained in *d2*. *level* sets the maximum depth of recursion. For infinite recursion, set that to -1. For level 1, if a key is present both in *d1* and *d2* but has different values, it is included into the differen...
def difference(d1, d2, level=-1): """Return a dictionary with items from *d1* not contained in *d2*. *level* sets the maximum depth of recursion. For infinite recursion, set that to -1. For level 1, if a key is present both in *d1* and *d2* but has different values, it is included into the differen...
62b87af09a0c4fa8b80b34f1
def fill(self, coord, weight=1): """Fill histogram at *coord* with the given *weight*. Coordinates outside the histogram edges are ignored. """
def fill(self, coord, weight=1): """Fill histogram at *coord* with the given *weight*. Coordinates outside the histogram edges are ignored. """ indices = hf.get_bin_on_value(coord, self.edges) subarr = self.bins for ind in indices[:-1]: # underflow ...
62b86aa3b4d922cb0e688d36
def _validate_labels(labels): """Check that keys and values in the given labels match against their corresponding regular expressions. Args: labels (dict): the different labels to validate. Raises: ValidationError: if any of the keys and labels does not match their respective ...
def _validate_labels(labels): """Check that keys and values in the given labels match against their corresponding regular expressions. Args: labels (dict): the different labels to validate. Raises: ValidationError: if any of the keys and labels does not match their respective ...
62b86a9eb4d922cb0e688d25
def _get_resource_name_regex(): """Build or return the regular expressions that are used to validate the name of the Krake resources. Returns: (re.Pattern): the compiled regular expressions, to validate the resource name. """
def _get_resource_name_regex(): """Build or return the regular expressions that are used to validate the name of the Krake resources. Returns: (re.Pattern): the compiled regular expressions, to validate the resource name. """ global _resource_name_regex, _resource_name_pattern ...
62b86a4fb4d922cb0e688cf8
def validate_value(value): """Validate the given value against the corresponding regular expression. Args: value: the string to validate Raises: ValidationError: if the given value is not conform to the regular expression. """
def validate_value(value): """Validate the given value against the corresponding regular expression. Args: value: the string to validate Raises: ValidationError: if the given value is not conform to the regular expression. """ _, value_regex = _get_labels_regex() if not value_r...
62b86a4fb4d922cb0e688cf7
def validate_key(key): """Validate the given key against the corresponding regular expression. Args: key: the string to validate Raises: ValidationError: if the given key is not conform to the regular expression. """
def validate_key(key): """Validate the given key against the corresponding regular expression. Args: key: the string to validate Raises: ValidationError: if the given key is not conform to the regular expression. """ key_regex, _ = _get_labels_regex() if not key_regex.fullmatch...
62b86a01b4d922cb0e688ccc
def generate_default_observer_schema_dict(manifest_dict, first_level=False): """Together with :func:``generate_default_observer_schema_list``, this function is called recursively to generate part of a default ``observer_schema`` from part of a Kubernetes resource, defined respectively by ``manifest_dict`` o...
def generate_default_observer_schema_dict(manifest_dict, first_level=False): """Together with :func:``generate_default_observer_schema_list``, this function is called recursively to generate part of a default ``observer_schema`` from part of a Kubernetes resource, defined respectively by ``manifest_dict`` o...
62b869ebb4d922cb0e688cc6
def update_last_applied_manifest_list_from_resp( last_applied_manifest, observer_schema, response ): """Together with :func:``update_last_applied_manifest_dict_from_resp``, this function is called recursively to update a partial ``last_applied_manifest`` from a partial Kubernetes response Args: ...
def update_last_applied_manifest_list_from_resp( last_applied_manifest, observer_schema, response ): """Together with :func:``update_last_applied_manifest_dict_from_resp``, this function is called recursively to update a partial ``last_applied_manifest`` from a partial Kubernetes response Args: ...
62b869eab4d922cb0e688cc5
def update_last_applied_manifest_dict_from_resp( last_applied_manifest, observer_schema, response ): """Together with :func:``update_last_applied_manifest_list_from_resp``, this function is called recursively to update a partial ``last_applied_manifest`` from a partial Kubernetes response Args: ...
def update_last_applied_manifest_dict_from_resp( last_applied_manifest, observer_schema, response ): """Together with :func:``update_last_applied_manifest_list_from_resp``, this function is called recursively to update a partial ``last_applied_manifest`` from a partial Kubernetes response Args: ...
62b869eab4d922cb0e688cbf
def generate_default_observer_schema(app): """Generate the default observer schema for each Kubernetes resource present in ``spec.manifest`` for which a custom observer schema hasn't been specified. Args: app (krake.data.kubernetes.Application): The application for which to generate a d...
def generate_default_observer_schema(app): """Generate the default observer schema for each Kubernetes resource present in ``spec.manifest`` for which a custom observer schema hasn't been specified. Args: app (krake.data.kubernetes.Application): The application for which to generate a d...
62b43427903eeb48555d3ea5
def format( self, sql: AnyStr, params: Union[Dict[Union[str, int], Any], Sequence[Any]], ) -> Tuple[AnyStr, Union[Dict[Union[str, int], Any], Sequence[Any]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:class:`str` or :class:`bytes`) is the SQL ...
def format( self, sql: AnyStr, params: Union[Dict[Union[str, int], Any], Sequence[Any]], ) -> Tuple[AnyStr, Union[Dict[Union[str, int], Any], Sequence[Any]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:class:`str` or :class:`bytes`) is the SQL ...
62b43428903eeb48555d3eaa
def formatmany( self, sql: AnyStr, many_params: Union[Iterable[Dict[Union[str, int], Any]], Iterable[Sequence[Any]]], ) -> Tuple[AnyStr, Union[List[Dict[Union[str, int], Any]], List[Sequence[Any]]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:c...
def formatmany( self, sql: AnyStr, many_params: Union[Iterable[Dict[Union[str, int], Any]], Iterable[Sequence[Any]]], ) -> Tuple[AnyStr, Union[List[Dict[Union[str, int], Any]], List[Sequence[Any]]]]: """ Convert the SQL query to use the out-style parameters instead of the in-style parameters. *sql* (:c...
62b45df05108cfac7f2109ce
def validate(self, path): """Validate OCFL object at path or pyfs root. Returns True if valid (warnings permitted), False otherwise. """
def validate(self, path): """Validate OCFL object at path or pyfs root. Returns True if valid (warnings permitted), False otherwise. """ self.initialize() try: if isinstance(path, str): self.obj_fs = open_fs(path) else: ...
62b45df15108cfac7f2109dc
def status_str(self, prefix=''): """Return string of validator status, with optional prefix."""
def status_str(self, prefix=''): """Return string of validator status, with optional prefix.""" s = '' for message in sorted(self.messages): s += prefix + message + '\n' return s[:-1]
62b45df15108cfac7f2109dd
def status_str(self, prefix=''): """Return string representation of validation log, with optional prefix."""
def status_str(self, prefix=''): """Return string representation of validation log, with optional prefix.""" return self.log.status_str(prefix=prefix)
62b45e135108cfac7f2109f4
def is_valid(self, identifier): # pylint: disable=unused-argument """Return True if identifier is valid, always True in this base implementation."""
def is_valid(self, identifier): # pylint: disable=unused-argument """Return True if identifier is valid, always True in this base implementation.""" return True
62b45e145108cfac7f210a07
def validate(self, inventory, extract_spec_version=False): """Validate a given inventory. If extract_spec_version is True then will look at the type value to determine the specification version. In the case that there is no type value or it isn't valid, then other tests will be base...
def validate(self, inventory, extract_spec_version=False): """Validate a given inventory. If extract_spec_version is True then will look at the type value to determine the specification version. In the case that there is no type value or it isn't valid, then other tests will be base...
62b45e145108cfac7f210a09
def check_digests_present_and_used(self, manifest_files, digests_used): """Check all digests in manifest that are needed are present and used."""
def check_digests_present_and_used(self, manifest_files, digests_used): """Check all digests in manifest that are needed are present and used.""" in_manifest = set(manifest_files.values()) in_state = set(digests_used) not_in_manifest = in_state.difference(in_manifest) if len(...
62b45e165108cfac7f210a16
def validate_as_prior_version(self, prior): """Check that prior is a valid prior version of the current inventory object. The input variable prior is also expected to be an InventoryValidator object and both self and prior inventories are assumed to have been checked for internal co...
def validate_as_prior_version(self, prior): """Check that prior is a valid prior version of the current inventory object. The input variable prior is also expected to be an InventoryValidator object and both self and prior inventories are assumed to have been checked for internal co...
62b45e165108cfac7f210a17
def get_logical_path_map(inventory, version): """Get a map of logical paths in state to files on disk for version in inventory. Returns a dictionary: logical_path_in_state -> set(content_files) The set of content_files may includes references to duplicate files in later versions than the version being...
def get_logical_path_map(inventory, version): """Get a map of logical paths in state to files on disk for version in inventory. Returns a dictionary: logical_path_in_state -> set(content_files) The set of content_files may includes references to duplicate files in later versions than the version being...
62b45e175108cfac7f210a19
def validate_fixity(self, fixity, manifest_files): """Validate fixity block in inventory. Check the structure of the fixity block and makes sure that only files listed in the manifest are referenced. """
def validate_fixity(self, fixity, manifest_files): """Validate fixity block in inventory. Check the structure of the fixity block and makes sure that only files listed in the manifest are referenced. """ if not isinstance(fixity, dict): # The value of fixity must...
62b463153879012d19481498
def files_list(path): """ Return the files in `path` """
def files_list(path): """ Return the files in `path` """ return os.listdir(path)
62b463153879012d1948149a
def _group_files_by_xml_filename(source, xmls, files): """ Group files by their XML basename Groups files by their XML basename and returns data in dict format. Parameters ---------- xml_filename : str XML filenames files : list list of files in the folder or zipfile R...
def _group_files_by_xml_filename(source, xmls, files): """ Group files by their XML basename Groups files by their XML basename and returns data in dict format. Parameters ---------- xml_filename : str XML filenames files : list list of files in the folder or zipfile R...
62b463153879012d1948149b
def match_file_by_prefix(prefix, file_path): """ Identify if a `file_path` belongs to a document package by a given `prefix` Retorna `True` para documentos pertencentes a um pacote. Parameters ---------- prefix : str Filename prefix file_path : str File path Returns ...
def match_file_by_prefix(prefix, file_path): """ Identify if a `file_path` belongs to a document package by a given `prefix` Retorna `True` para documentos pertencentes a um pacote. Parameters ---------- prefix : str Filename prefix file_path : str File path Returns ...
62b463153879012d1948149c
def select_filenames_by_prefix(prefix, files): """ Get files which belongs to a document package. Retorna os arquivos da lista `files` cujos nomes iniciam com `prefix` Parameters ---------- prefix : str Filename prefix files : str list Files paths Returns ------- ...
def select_filenames_by_prefix(prefix, files): """ Get files which belongs to a document package. Retorna os arquivos da lista `files` cujos nomes iniciam com `prefix` Parameters ---------- prefix : str Filename prefix files : str list Files paths Returns ------- ...
62b463153879012d1948149d
def _explore_folder(folder): """ Get packages' data from folder Groups files by their XML basename and returns data in dict format. Parameters ---------- folder : str Folder of the package Returns ------- dict """
def _explore_folder(folder): """ Get packages' data from folder Groups files by their XML basename and returns data in dict format. Parameters ---------- folder : str Folder of the package Returns ------- dict """ if file_utils.is_folder(folder): data = _gro...
62b463153879012d1948149f
def _eval_file(prefix, file_path): """ Identifica o tipo de arquivo do pacote: `asset` ou `rendition`. Identifica o tipo de arquivo do pacote e atualiza `packages` com o tipo e o endereço do arquivo em análise. Parameters ---------- prefix : str nome do arquivo XML sem extensão ...
def _eval_file(prefix, file_path): """ Identifica o tipo de arquivo do pacote: `asset` ou `rendition`. Identifica o tipo de arquivo do pacote e atualiza `packages` com o tipo e o endereço do arquivo em análise. Parameters ---------- prefix : str nome do arquivo XML sem extensão ...
62b463153879012d194814a1
def add_rendition(self, lang, file_path): """ { "original": "artigo02.pdf", "en": "artigo02-en.pdf", } """
def add_rendition(self, lang, file_path): """ { "original": "artigo02.pdf", "en": "artigo02-en.pdf", } """ self._renditions[lang] = self.file_path(file_path)
62b463163879012d194814a2
def add_asset(self, basename, file_path): """ "{ "artigo02-gf03.tiff": "/path/artigo02-gf03.tiff", "artigo02-gf03.jpg": "/path/artigo02-gf03.jpg", "artigo02-gf03.png": "/path/artigo02-gf03.png", } """
def add_asset(self, basename, file_path): """ "{ "artigo02-gf03.tiff": "/path/artigo02-gf03.tiff", "artigo02-gf03.jpg": "/path/artigo02-gf03.jpg", "artigo02-gf03.png": "/path/artigo02-gf03.png", } """ self._assets[basename] = self.file_path...
62b463163879012d194814a4
def _explore_zipfile(zip_path): """ Get packages' data from zip_path Groups files by their XML basename and returns data in dict format. Parameters ---------- zip_path : str zip file path Returns ------- dict """
def _explore_zipfile(zip_path): """ Get packages' data from zip_path Groups files by their XML basename and returns data in dict format. Parameters ---------- zip_path : str zip file path Returns ------- dict """ if file_utils.is_zipfile(zip_path): with ZipF...
62b463163879012d194814a6
def files_list_from_zipfile(zip_path): """ Return the files in `zip_path` Example: ``` [ '2318-0889-tinf-33-0421/2318-0889-tinf-33-e200069.pdf', '2318-0889-tinf-33-0421/2318-0889-tinf-33-e200069.xml', '2318-0889-tinf-33-0421/2318-0889-tinf-33-e200071.pdf', '2318-088...
def files_list_from_zipfile(zip_path): """ Return the files in `zip_path` Example: ``` [ '2318-0889-tinf-33-0421/2318-0889-tinf-33-e200069.pdf', '2318-0889-tinf-33-0421/2318-0889-tinf-33-e200069.xml', '2318-0889-tinf-33-0421/2318-0889-tinf-33-e200071.pdf', '2318-088...
62b4631b3879012d194814dd
def fix_namespace_prefix_w(content): """ Convert os textos cujo padrão é `w:st="` em `w-st="` """
def fix_namespace_prefix_w(content): """ Convert os textos cujo padrão é `w:st="` em `w-st="` """ pattern = r"\bw:[a-z]{1,}=\"" found_items = re.findall(pattern, content) logger.debug("Found %i namespace prefix w", len(found_items)) for item in set(found_items): new_namespace = item....
62b463283879012d1948153d
def match_pubdate(node, pubdate_xpaths): """ Retorna o primeiro match da lista de pubdate_xpaths """
def match_pubdate(node, pubdate_xpaths): """ Retorna o primeiro match da lista de pubdate_xpaths """ for xpath in pubdate_xpaths: pubdate = node.find(xpath) if pubdate is not None: return pubdate
62b463303879012d19481579
def _extract_number_and_supplment_from_issue_element(issue): """ Extrai do conteúdo de <issue>xxxx</issue>, os valores number e suppl. Valores possíveis 5 (suppl), 5 Suppl, 5 Suppl 1, 5 spe, 5 suppl, 5 suppl 1, 5 suppl. 1, 25 Suppl 1, 2-5 suppl 1, 2spe, Spe, Supl. 1, Suppl, Suppl 12, s2, spe, sp...
def _extract_number_and_supplment_from_issue_element(issue): """ Extrai do conteúdo de <issue>xxxx</issue>, os valores number e suppl. Valores possíveis 5 (suppl), 5 Suppl, 5 Suppl 1, 5 spe, 5 suppl, 5 suppl 1, 5 suppl. 1, 25 Suppl 1, 2-5 suppl 1, 2spe, Spe, Supl. 1, Suppl, Suppl 12, s2, spe, sp...
62b46740d2f69a53b466171a
def pretty(self, indent=0, debug=False): """ Return a pretty formatted representation of self. """
def pretty(self, indent=0, debug=False): """ Return a pretty formatted representation of self. """ debug_details = "" if debug: debug_details += f"<isliteral={self.isliteral!r}, iscanonical={self.iscanonical!r}>" obj = f"'{self.obj}'" if isinstance(self.o...
62b46746d2f69a53b4661722
def absorb(self, args): """ Given an `args` sequence of expressions, return a new list of expression applying absorption and negative absorption. See https://en.wikipedia.org/wiki/Absorption_law Absorption:: A & (A | B) = A, A | (A & B) = A Negative ab...
def absorb(self, args): """ Given an `args` sequence of expressions, return a new list of expression applying absorption and negative absorption. See https://en.wikipedia.org/wiki/Absorption_law Absorption:: A & (A | B) = A, A | (A & B) = A Negative ab...
62b86707b4d922cb0e688c2a
def on(self, hook): """Decorator function to add a new handler to the registry. Args: hook (HookType): Hook attribute for which to register the handler. Returns: callable: Decorator for registering listeners for the specified hook. """
def on(self, hook): """Decorator function to add a new handler to the registry. Args: hook (HookType): Hook attribute for which to register the handler. Returns: callable: Decorator for registering listeners for the specified hook. """ ...
62b86729b4d922cb0e688c2f
def base_config(user, etcd_host="localhost", etcd_port=2379): """Creates a configuration with some simple parameters, which have a default value that can be set. Args: user (str): the name of the user for the static authentication etcd_host (str): the host for the database. etcd_por...
def base_config(user, etcd_host="localhost", etcd_port=2379): """Creates a configuration with some simple parameters, which have a default value that can be set. Args: user (str): the name of the user for the static authentication etcd_host (str): the host for the database. etcd_por...
62b8a4a4755ee91dce50a3d2
def _fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the ...
def _fromutc(self, dt): """ Given a timezone-aware datetime in a given timezone, calculates a timezone-aware datetime in a new timezone. Since this is the one time that we *know* we have an unambiguous datetime object, we take this opportunity to determine whether the ...
62b8982f755ee91dce50a241
def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=+1, hours=+14) :return: Returns a :class:`dateutil.relat...
def normalized(self): """ Return a version of this object represented entirely using integer values for the relative attributes. >>> relativedelta(days=1.5, hours=2).normalized() relativedelta(days=+1, hours=+14) :return: Returns a :class:`dateutil.relat...
62b89640755ee91dce50a114
def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """
def tzname_in_python2(namefunc): """Change unicode output into bytestrings in Python 2 tzname() API changed in Python 3. It used to return bytes, but was changed to unicode strings """ if PY2: @wraps(namefunc) def adjust_encoding(*args, **kwargs): name = namefunc(*args, ...
62b87d24d292efb640a55670
def get_versions(): """Get version information or return default if unable to do so."""
def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which #...
62b87d24d292efb640a5566f
def render(pieces, style): """Render the given version pieces into the requested style."""
def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return { "version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None, ...
62b87d24d292efb640a5566d
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a ."""
def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+"
62b87d23d292efb640a5566b
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s)."""
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo =...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
47