id
stringlengths
23
25
content
stringlengths
1.16k
88k
max_stars_repo_path
stringlengths
12
48
codereval_python_data_1
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, di...
neo4j/_codec/hydration/v1/temporal.py
codereval_python_data_2
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...
neo4j/_codec/hydration/v1/temporal.py
codereval_python_data_3
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 ...
neo4j/_codec/hydration/v1/temporal.py
codereval_python_data_4
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 ...
neo4j/_codec/hydration/v1/spatial.py
codereval_python_data_5
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) # Copyright (c) "Neo4j" # Neo4j Sweden AB [https://neo4j.com] # # This file is part of Neo4j. # # Licensed under t...
neo4j/_data.py
codereval_python_data_6
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 version is supported. If no protocol version is provided, all available versions will be returned. :param protoco...
neo4j/_sync/io/_bolt.py
codereval_python_data_7
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_people_tx(tx): result = tx.run("MATCH (a:Person) RETURN count(a) AS...
neo4j/work/query.py
codereval_python_data_8
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): ...
neo4j/_data.py
codereval_python_data_9
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 :rtype: list def values(self, *keys): """ Return the values of ...
neo4j/_data.py
codereval_python_data_10
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 of bounds will trigger an :exc:`IndexError`. :param keys: indexes or k...
neo4j/_data.py
codereval_python_data_11
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] + ...
neo4j/_codec/packstream/v1/__init__.py
codereval_python_data_12
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) :param dehydration_hooks: Hooks to dehydrate types (dict from type (class) to dehydration function). Dehydration functions receive the value a...
neo4j/_async/io/_bolt3.py
codereval_python_data_13
Appends a BEGIN message to the output queue. :param mode: access mode for routing - "READ" or "WRITE" (default) :param bookmarks: iterable of bookmark values after which this transaction should begin :param metadata: custom metadata dictionary to attach to the transaction :param timeout: timeout for transaction execut...
neo4j/_async/io/_bolt3.py
codereval_python_data_14
>>> 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 >>> round_half_to_even(4.5) 4 >>> round_half_to_even(4.7) 5 :param n: :return: def...
neo4j/time/_arithmetic.py
codereval_python_data_15
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...
neo4j/_spatial/__init__.py
codereval_python_data_16
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 f...
neo4j/_meta.py
codereval_python_data_17
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. Th...
pre_commit/languages/r.py
codereval_python_data_18
A simplified implementation of xargs. color: Make a pty if on a platform that supports it target_concurrency: Target number of partitions to run concurrently def xargs( cmd: tuple[str, ...], varargs: Sequence[str], *, color: bool = False, target_concurrency: int = 1, _m...
pre_commit/xargs.py
codereval_python_data_19
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 from __future__ import annotations import multiproces...
pre_commit/languages/helpers.py
codereval_python_data_20
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('.')) from __future__ import annotations import contextlib import errno import functools import importlib.resources import os.path import shutil import stat im...
pre_commit/util.py
codereval_python_data_21
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/issue855...
pre_commit/parse_shebang.py
codereval_python_data_22
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, **...
cachetools/decorators.py
codereval_python_data_23
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 s...
cachetools/func.py
codereval_python_data_24
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) ...
cachetools/func.py
codereval_python_data_25
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) ...
cachetools/func.py
codereval_python_data_26
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...
cachetools/func.py
codereval_python_data_27
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 ...
cachetools/fifo.py
codereval_python_data_28
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 from collections.abc import MutableMapping class _DefaultSize(object): ...
cachetools/cache.py
codereval_python_data_29
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 from collections.abc import MutableMapping class _DefaultSize(object): __slots__ = () def __getitem__(self, _): ...
cachetools/cache.py
codereval_python_data_30
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 ...
cachetools/decorators.py
codereval_python_data_31
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 level (default 5) :type max_path_level: int :return The exception readable string :rtype str @classmethod def extostr(cls, e...
pysolbase/SolBase.py
codereval_python_data_32
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 buffer to write. :type text_buffer: str :param encoding: The encoding to use. :type encoding: str :param overwrite: If true, file is overwritten. :type ove...
pysolbase/FileUtility.py
codereval_python_data_33
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: Encoding to use. :type encoding: str :return: A text buffer or None in case of error. :rtype str @staticmethod ...
pysolbase/FileUtility.py
codereval_python_data_34
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...
pysolbase/FileUtility.py
codereval_python_data_35
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.getL...
pysolbase/SolBase.py
codereval_python_data_36
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 ############################################################################## # # Copyri...
src/zope/interface/tests/test_declarations.py
codereval_python_data_37
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: >>> _mergeOrderings([ ... ['x', 'y', 'z'], ... ['q', 'z'], ... [1, 3, 5],...
src/zope/interface/ro.py
codereval_python_data_38
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.interface...
src/zope/interface/declarations.py
codereval_python_data_39
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: ...
src/zope/interface/advice.py
codereval_python_data_40
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 sel...
src/zope/interface/interface.py
codereval_python_data_41
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__: ...
src/zope/interface/interface.py
codereval_python_data_42
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 Declari...
src/zope/interface/declarations.py
codereval_python_data_43
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 ...
src/zope/interface/_compat.py
codereval_python_data_44
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 optimizati...
src/zope/interface/_compat.py
codereval_python_data_45
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" ##############################################################################...
src/zope/interface/_compat.py
codereval_python_data_46
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`. """ ...
src/zope/interface/_compat.py
codereval_python_data_47
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 *ini...
lena/structures/histogram.py
codereval_python_data_48
.. 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 the output (new line is added automatically). Since a graph can be multidimensional, for ea...
lena/structures/graph.py
codereval_python_data_49
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: e...
lena/structures/graph.py
codereval_python_data_50
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 "x", "y" and "z" (this corresponds to first three coordinates, if they are present),...
lena/structures/graph.py
codereval_python_data_51
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 inte...
lena/structures/hist_functions.py
codereval_python_data_52
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 ...
lena/core/check_sequence_type.py
codereval_python_data_53
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) """Check whether a sequence can be conver...
lena/core/check_sequence_type.py
codereval_python_data_54
Object contains executable method 'run'. def is_run_el(obj): """Object contains executable method 'run'.""" return hasattr(obj, "run") and callable(obj.run) """Check whether a sequence can be converted to a Lena Sequence.""" # otherwise import errors arise # from . import source def is_fill_compute_el(obj)...
lena/core/check_sequence_type.py
codereval_python_data_55
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)) """Check whether ...
lena/core/check_sequence_type.py
codereval_python_data_56
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 difference. See :func:`intersection` for more details. *d1* and ...
lena/context/functions.py
codereval_python_data_57
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(coo...
lena/structures/histogram.py
codereval_python_data_58
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 regular expression. The error contains as message the list...
krake/krake/data/core.py
codereval_python_data_59
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 th...
krake/krake/data/core.py
codereval_python_data_60
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: ...
krake/krake/data/core.py
codereval_python_data_61
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:...
krake/krake/data/core.py
codereval_python_data_62
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`` or ``manifest_list``. Args: manifest_dict (dict): Partial Kubernetes resources first...
krake/krake/controller/kubernetes/hooks.py
codereval_python_data_63
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: last_applied_manifest (list): partial ``last_applied_manifest`` being updated observer_schema (list): partial `...
krake/krake/controller/kubernetes/hooks.py
codereval_python_data_64
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: last_applied_manifest (dict): partial ``last_applied_manifest`` being updated observer_schema (dict): partial `...
krake/krake/controller/kubernetes/hooks.py
codereval_python_data_65
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 default observer schema def generate_default_observer_schema(app):...
krake/krake/controller/kubernetes/hooks.py
codereval_python_data_66
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 query. *params* (:class:`~collections.abc.Mapping` or :class:`~collections.abc.Sequence`) contains the set of in-style parameters. It maps each parameter (:class:`str` or :class:...
sqlparams/__init__.py
codereval_python_data_67
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 query. *many_params* (:class:`~collections.abc.Iterable`) contains each set of in-style parameters (*params*). - *params* (:class:`~collections.abc.Mapping` or :class:`~co...
sqlparams/__init__.py
codereval_python_data_68
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: ...
ocfl/validator.py
codereval_python_data_69
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] """OCFL Validation Logger. ...
ocfl/validation_logger.py
codereval_python_data_70
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) """OCFL Validator. Philosophy of this code is to keep it separate from the ...
ocfl/validator.py
codereval_python_data_71
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 """Base class for Dispositor objects.""" import os import ...
ocfl/dispositor.py
codereval_python_data_72
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 based on the version given in self.spec_version. def validate(self, inventory, extract_spec_versi...
ocfl/inventory_validator.py
codereval_python_data_73
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) ...
ocfl/inventory_validator.py
codereval_python_data_74
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 consistency. def validate_as_prior_version(self, prior): """Check that p...
ocfl/inventory_validator.py
codereval_python_data_75
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 described. def get_logical_path_map(inventory, version): ""...
ocfl/inventory_validator.py
codereval_python_data_76
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 o...
ocfl/inventory_validator.py
codereval_python_data_77
Return the files in `path` def files_list(path): """ Return the files in `path` """ return os.listdir(path) import os import logging import re import shutil import tempfile from zipfile import ZipFile, ZIP_DEFLATED logger = logging.getLogger(__name__) def is_folder(source): return os.path.is...
packtools/file_utils.py
codereval_python_data_78
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 Returns ------- dict key: name of the XML files value: Package def _group_files_by_xml_file...
packtools/sps/models/packages.py
codereval_python_data_79
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 ------- bool True - file belongs to the package def match_file_by_prefix(prefix, file_p...
packtools/sps/models/packages.py
codereval_python_data_80
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 ------- list files paths which basename files matches to prefix def select_filenames_by_prefix(prefi...
packtools/sps/models/packages.py
codereval_python_data_81
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...
packtools/sps/models/packages.py
codereval_python_data_82
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 filename : str filename file_folder : str file folder Returns ---...
packtools/sps/models/packages.py
codereval_python_data_83
{ "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) import logging import os ...
packtools/sps/models/packages.py
codereval_python_data_84
"{ "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-gf0...
packtools/sps/models/packages.py
codereval_python_data_85
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 dic...
packtools/sps/models/packages.py
codereval_python_data_86
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-0889-tinf-33-0421/2318-0889-tinf-33-e200071.xml', '2318-0889-tinf-33-0421/2318...
packtools/file_utils.py
codereval_python_data_87
Convert text that defaults to 'w:st="' to '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 ite...
packtools/sps/utils/xml_utils.py
codereval_python_data_88
Returns the first match in the pubdate_xpaths list 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 import logging import re ...
packtools/sps/utils/xml_utils.py
codereval_python_data_89
Extract the possible values of number and suppl from the contents of issue. 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, ...
packtools/sps/models/front_articlemeta_issue.py
codereval_python_data_90
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}>" ...
boolean/boolean.py
codereval_python_data_91
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 absorption:: A & (~A | B) = A & B, A | (~A & B) = A | B def absorb(self, args): ...
boolean/boolean.py
codereval_python_data_92
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. ...
krake/krake/controller/kubernetes/hooks.py
codereval_python_data_93
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_port (int): the port for the database. Returns: dict: the created configuration. def b...
krake/tests/conftest.py
codereval_python_data_94
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 datetime is ambiguous and in a "fold" state (e.g. if it's the first occurrence...
dateutil/tz/_common.py
codereval_python_data_95
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.relativedelta.relativedelta` object. def normalized(self): """ Return ...
dateutil/relativedelta.py
codereval_python_data_96
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 ...
dateutil/tz/_common.py
codereval_python_data_97
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/bbfreez...
src/prestoplot/_version.py
codereval_python_data_98
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, "...
src/prestoplot/_version.py
codereval_python_data_99
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 "+" # This file helps to compute a version number in source trees obtained from # git-archive...
src/prestoplot/_version.py
codereval_python_data_100
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 i...
src/prestoplot/_version.py