id
stringlengths
23
25
content
stringlengths
1.16k
88k
max_stars_repo_path
stringlengths
12
48
codereval_python_data_101
Create, populate and return the VersioneerConfig() object. def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "pep440" cfg.tag_...
src/prestoplot/_version.py
codereval_python_data_102
Create decorator to mark a method as the handler of a VCS. def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} ...
src/prestoplot/_version.py
codereval_python_data_103
Validate storage root hierarchy. Returns: num_objects - number of objects checked good_objects - number of objects checked that were found to be valid def validate_hierarchy(self, validate_objects=True, check_digests=True, show_warnings=False): """Validate storage root hierarchy. Returns:...
ocfl/store.py
codereval_python_data_104
Create and initialize a new OCFL storage root. def initialize(self): """Create and initialize a new OCFL storage root.""" (parent, root_dir) = fs.path.split(self.root) parent_fs = open_fs(parent) if parent_fs.exists(root_dir): raise StoreException("OCFL storage root %s a...
ocfl/store.py
codereval_python_data_105
Next version identifier following existing pattern. Must deal with both zero-prefixed and non-zero prefixed versions. def next_version(version): """Next version identifier following existing pattern. Must deal with both zero-prefixed and non-zero prefixed versions. """ m = re.match(r'''v((\d)\d*)$'''...
ocfl/object_utils.py
codereval_python_data_106
Each version SHOULD have an inventory up to that point. Also keep a record of any content digests different from those in the root inventory so that we can also check them when validating the content. version_dirs is an array of version directory names and is assumed to be in version sequence (1, 2, 3...). def v...
ocfl/validator.py
codereval_python_data_107
Return a string indicating the type of thing at the given path. Return values: 'root' - looks like an OCFL Storage Root 'object' - looks like an OCFL Object 'file' - a file, might be an inventory other string explains error description Looks only at "0=*" Namaste files to determine the directory type....
ocfl/object_utils.py
codereval_python_data_108
Amend the Bugzilla params def amend_bzparams(self, params, bug_ids): """Amend the Bugzilla params""" if not self.all_include_fields(): if "include_fields" in params: fields = params["include_fields"] if isinstance(fields, list): if "id...
auto_nag/bzcleaner.py
codereval_python_data_109
Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colli...
borgmatic/config/load.py
codereval_python_data_110
Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. def parse_arguments(*arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. ''...
borgmatic/commands/generate_config.py
codereval_python_data_111
Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in ac...
borgmatic/commands/completion.py
codereval_python_data_112
Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the ar...
borgmatic/commands/arguments.py
codereval_python_data_113
Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subpar...
borgmatic/commands/arguments.py
codereval_python_data_114
Build a top-level parser and its subparsers and return them as a tuple. def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(ex...
borgmatic/commands/arguments.py
codereval_python_data_115
Given a nested borgmatic configuration data structure as a list of tuples in the form of: ( ruamel.yaml.nodes.ScalarNode as a key, ruamel.yaml.nodes.MappingNode or other Node as a value, ), ... deep merge any node values corresponding to duplicate keys and return the result. If there are colli...
borgmatic/config/load.py
codereval_python_data_116
Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. def parse_arguments(*arguments): ''' Given command-line arguments with which this script was invoked, parse the arguments and return them as an ArgumentParser instance. ''...
borgmatic/commands/generate_config.py
codereval_python_data_117
Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in ac...
borgmatic/commands/completion.py
codereval_python_data_118
Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. def bash_completion(): ''' Return a bash completion script for the borgmatic command. Produce this by introspecting borgmatic's command-line argument parsers. ''' top_...
borgmatic/commands/completion.py
codereval_python_data_119
Given command-line arguments with which this script was invoked, parse the arguments and return them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance. def parse_arguments(*unparsed_arguments): ''' Given command-line arguments with which this script was invoked, parse the ar...
borgmatic/commands/arguments.py
codereval_python_data_120
Given a sequence of arguments and a dict from subparser name to argparse.ArgumentParser instance, give each requested action's subparser a shot at parsing all arguments. This allows common arguments like "--repository" to be shared across multiple subparsers. Return the result as a tuple of (a dict mapping from subpar...
borgmatic/commands/arguments.py
codereval_python_data_121
Build a top-level parser and its subparsers and return them as a tuple. def make_parsers(): ''' Build a top-level parser and its subparsers and return them as a tuple. ''' config_paths = collect.get_default_config_paths(expand_home=True) unexpanded_config_paths = collect.get_default_config_paths(ex...
borgmatic/commands/arguments.py
codereval_python_data_122
Returns WAPI response page by page Args: response (list): WAPI response. max_results (int): Maximum number of objects to be returned in one page. Returns: Generator object with WAPI response split page by page. def paging(response, max_results): """Returns WAPI response page by page Args: ...
infoblox_client/utils.py
codereval_python_data_123
Convert human readable file size to bytes. Resulting value is an approximation as input value is in most case rounded. Args: size: A string representing a human readable file size (eg: '500K') Returns: A decimal representation of file size Examples:: >>> size_to_bytes("500") 500 ...
swh/lister/arch/lister.py
codereval_python_data_124
Combine values of the dictionaries supplied by iterable dicts. >>> _dictsum([{'a': 1, 'b': 2}, {'a': 5, 'b': 0}]) {'a': 6, 'b': 2} def _dictsum(dicts): """ Combine values of the dictionaries supplied by iterable dicts. >>> _dictsum([{'a': 1, 'b': 2}, {'a': 5, 'b': 0}]) {'a': 6, 'b': 2} """ it...
contrib/planb-swiftsync.py
codereval_python_data_125
Replace any custom string URL items with values in args def _replace_url_args(url, url_args): """Replace any custom string URL items with values in args""" if url_args: for key, value in url_args.items(): url = url.replace(f"{key}/", f"{value}/") return url #!/usr/bin/env python """ c...
pyseed/apibase.py
codereval_python_data_126
Check if a string represents a None value. def is_none_string(val: any) -> bool: """Check if a string represents a None value.""" if not isinstance(val, str): return False return val.lower() == 'none' # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this ...
cinder/api/api_utils.py
codereval_python_data_127
Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. def parser_flags(parser): ''' Given an argparse.ArgumentParser instance, return its argument flags in a space-separated string. ''' return ' '.join(option for action in parser._actions for option in ac...
borgmatic/commands/completion.py
codereval_python_data_128
Check if a file or directory has already been processed. To prevent recursion, expand the path name to an absolution path call this function with a set that will store all the entries and the entry to test. If the entry is already in the set, report the issue and return ``True``. Otherwise, add the entry to the set an...
makeprojects/util.py
codereval_python_data_129
return 3 points for each vertex of the polygon. This will include the vertex and the 2 points on both sides of the vertex:: polygon with vertices ABCD Will return DAB, ABC, BCD, CDA -> returns 3tuples #A B C D -> of vertices def vertex3tuple(vertices): """return 3 points for each vertex of the polygon. ...
eppy/geometry/surface.py
codereval_python_data_130
Convert a number to a string, using the given alphabet. The output has the most significant digit first. def int_to_string(number: int, alphabet: List[str], padding: Optional[int] = None) -> str: """ Convert a number to a string, using the given alphabet. The output has the most significant digit first. ...
shortuuid/main.py
codereval_python_data_131
Replace value from flows to given register number 'register_value' key in dictionary will be replaced by register number given by 'register_number' :param flow_params: Dictionary containing defined flows :param register_number: The number of register where value will be stored :param register_value: Key to be replace...
neutron_lib/agent/common/utils.py
codereval_python_data_132
Replaces all values of '.' to arg from the given string def replace_dots(value, arg): """Replaces all values of '.' to arg from the given string""" return value.replace(".", arg) # Copyright (C) 2022 The Sipwise Team - http://sipwise.com # # This program is free software: you can redistribute it and/or modif...
release_dashboard/templatetags/rd_extras.py
codereval_python_data_133
Return all subclasses of a class, recursively def subclasses(cls): """Return all subclasses of a class, recursively""" children = cls.__subclasses__() return set(children).union( set(grandchild for child in children for grandchild in subclasses(child)) ) # coding: utf-8 # Copyright 2014-2020...
rows/utils/__init__.py
codereval_python_data_134
Convert a string to a number, using the given alphabet. The input is assumed to have the most significant digit first. def string_to_int(string: str, alphabet: List[str]) -> int: """ Convert a string to a number, using the given alphabet. The input is assumed to have the most significant digit first. ...
shortuuid/main.py
codereval_python_data_135
Given an url and a destination path, retrieve and extract .tar.gz archive which contains 'desc' file for each package. Each .tar.gz archive corresponds to an Arch Linux repo ('core', 'extra', 'community'). Args: url: url of the .tar.gz archive to download destination_path: the path on disk where to extract arc...
swh/lister/arch/lister.py
codereval_python_data_136
Checks if the os is macOS :return: True is macOS :rtype: bool import os def os_is_mac(): """ Checks if the os is macOS :return: True is macOS :rtype: bool """ return platform.system() == "Darwin" import platform import sys import os from pathlib import Path from cloudmesh.common.util import...
cloudmesh/common/systeminfo.py
codereval_python_data_137
Convert *.cpp keys to regex keys Given a dict where the keys are all filenames with wildcards, convert only the keys into equivalent regexes and leave the values intact. Example: rules = { '*.cpp': {'a': 'arf', 'b': 'bark', 'c': 'coo'}, '*.h': {'h': 'help'} } regex_keys = regex_dict(rules) A...
makeprojects/util.py
codereval_python_data_138
Remove quote from the given name. import re def unquote(name): """Remove quote from the given name.""" assert isinstance(name, bytes) # This function just gives back the original text if it can decode it def unquoted_char(match): """For each ;000 return the corresponding byte.""" if le...
rdiffweb/core/librdiff.py
codereval_python_data_139
Multi-platform variant of shlex.split() for command-line splitting. For use with subprocess, for argv injection etc. Using fast REGEX. platform: 'this' = auto from current platform; 1 = POSIX; 0 = Windows/CMD (other values reserved) import re def split(s, platform='this'): """Multi-p...
cloudmesh/common/shlex.py
codereval_python_data_140
Given an existing archive_path, uncompress it. Returns a file repo url which can be used as origin url. This does not deal with the case where the archive passed along does not exist. import subprocess def prepare_repository_from_archive( archive_path: str, filename: Optional[str] = None, tmp_path: Union[...
swh/lister/arch/tests/__init__.py
codereval_python_data_141
Use the git command to obtain the file names, turn it into a list, sort the list for only ignored files, return those files as a single string with each filename separated by a comma. import subprocess def addignored(ignored): ''' Use the git command to obtain the file names, turn it into a list, sort the list for...
src/flashbake/plugins/ignored.py
codereval_python_data_142
Check if the filename is a type that this module supports Args: filename: Filename to match Returns: False if not a match, True if supported import os def match(filename): """ Check if the filename is a type that this module supports Args: filename: Filename to match Returns: ...
docopt/__init__.py
codereval_python_data_143
Given a frequency string with a number and a unit of time, return a corresponding datetime.timedelta instance or None if the frequency is None or "always". For instance, given "3 weeks", return datetime.timedelta(weeks=3) Raise ValueError if the given frequency cannot be parsed. import datetime def parse_frequency(f...
borgmatic/borg/check.py
codereval_python_data_144
Checks if the host is the localhost :param host: The hostname or ip :return: True if the host is the localhost import socket def is_local(host): """ Checks if the host is the localhost :param host: The hostname or ip :return: True if the host is the localhost """ return host in ["127.0.0.1", ...
cloudmesh/common/util.py
codereval_python_data_145
Given a sequence of path fragments or patterns as passed to `--find`, transform all path fragments into glob patterns. Pass through existing patterns untouched. For example, given find_paths of: ['foo.txt', 'pp:root/somedir'] ... transform that into: ['sh:**/*foo.txt*/**', 'pp:root/somedir'] import re def make...
borgmatic/borg/list.py
codereval_python_data_146
returns True if you run in a Windows gitbash :return: True if gitbash import os def is_gitbash(): """ returns True if you run in a Windows gitbash :return: True if gitbash """ try: exepath = os.environ['EXEPATH'] return "Git" in exepath except: return False import su...
cloudmesh/common/util.py
codereval_python_data_147
Given a target config filename and rendered config YAML, write it out to file. Create any containing directories as needed. But if the file already exists and overwrite is False, abort before writing anything. import os def write_configuration(config_filename, rendered_config, mode=0o600, overwrite=False): ''' ...
borgmatic/config/generate.py
codereval_python_data_148
converts a script to one line command. THis is useful to run a single ssh command and pass a one line script. :param script: :return: import textwrap def oneline(script, seperator=" && "): """ converts a script to one line command. THis is useful to run a single ssh command and pass a one line script. ...
cloudmesh/common/Shell.py
codereval_python_data_149
Run a function in a sub-process. Parameters ---------- func : function The function to be run. It must be in a module that is importable. *args : str Any additional command line arguments to be passed in the first argument to ``subprocess.run``. extra_env : dict[str, str] Any additional environment va...
lib/matplotlib/testing/__init__.py
codereval_python_data_150
Get the value from environment given a matcher containing a name and an optional default value. If the variable is not defined in environment and no default value is provided, an Error is raised. import os def _resolve_string(matcher): ''' Get the value from environment given a matcher containing a name and an...
borgmatic/config/override.py
codereval_python_data_151
Parse an image href into composite parts. :param image_href: href of an image :returns: a tuple of the form (image_id, netloc, use_ssl) :raises ValueError: import urllib def _parse_image_ref(image_href: str) -> Tuple[str, str, bool]: """Parse an image href into composite parts. :param image_href: href of an ...
cinder/image/glance.py
codereval_python_data_152
Iterate over a string list and remove trailing os seperator characters. Each string is tested if its length is greater than one and if the last character is the pathname seperator. If so, the pathname seperator character is removed. Args: input_list: list of strings Returns: Processed list of strings Raises...
makeprojects/util.py
codereval_python_data_153
This method converts the given string to regex pattern import re def get_pattern(pattern, strip=True): """ This method converts the given string to regex pattern """ if type(pattern) == re.Pattern: return pattern if strip and type(pattern) == str: pattern = pattern.strip() ret...
shconfparser/search.py
codereval_python_data_154
Call the given command(s). import subprocess 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 windo...
makeprojects/core.py
codereval_python_data_155
Test if IPv4 address or not import ipaddress def is_ipv4(target): """ Test if IPv4 address or not """ try: chk = ipaddress.IPv4Address(target) return True except ipaddress.AddressValueError: return False """ Gopad OpenAPI API definition for Gopad # noqa: E501 ...
gopad/rest.py
codereval_python_data_156
Find the roots in some sort of transitive hierarchy. find_roots(graph, rdflib.RDFS.subClassOf) will return a set of all roots of the sub-class hierarchy Assumes triple of the form (child, prop, parent), i.e. the direction of RDFS.subClassOf or SKOS.broader import rdflib def find_roots( graph: "Graph", prop: "URI...
rdflib/util.py
codereval_python_data_157
Dump to a py2-unicode or py3-string import yaml def _dump_string(obj, dumper=None): """Dump to a py2-unicode or py3-string""" if PY3: return yaml.dump(obj, Dumper=dumper) else: return yaml.dump(obj, Dumper=dumper, encoding=None) from __future__ import absolute_import, division, print_func...
tests/unit/mock/yaml_helper.py
codereval_python_data_158
General purpose application logger. Useful mainly for debugging import os,logging def build_app_logger(name='app', logfile='app.log', debug=True): """ General purpose application logger. Useful mainly for debugging """ # level = logging.DEBUG if settings.DEBUG else logging.INFO level = logging.INFO...
apphelpers/loggers.py
codereval_python_data_159
Function to create an array with shape and dtype. Parameters ---------- shape : tuple shape of the array to create dtype : `numpy.dtype` data-type of the array to create import numpy as np def make_array(shape, dtype=np.dtype("float32")): """ Function to create an array with shape and dtype. Para...
radiospectra/spectrogram.py
codereval_python_data_160
Gaussian centered around 0.2 with a sigma of 0.1. import numpy as np def gaussian(x): """ Gaussian centered around 0.2 with a sigma of 0.1. """ mu = 0.2 sigma = 0.1 return np.exp(-(x-mu)**2/sigma**2) import random import numpy as np from concert.tests import assert_almost_equal, TestCase, slo...
concert/tests/unit/devices/test_monochromator.py
codereval_python_data_161
Given a sequence of configuration filenames, load and validate each configuration file. Return the results as a tuple of: dict of configuration filename to corresponding parsed configuration, and sequence of logging.LogRecord instances containing any parse errors. import logging def load_configurations(config_filename...
borgmatic/commands/borgmatic.py
codereval_python_data_162
This function returns the bytes object corresponding to ``obj`` in case it is a string using UTF-8. import numpy def force_string(obj): """ This function returns the bytes object corresponding to ``obj`` in case it is a string using UTF-8. """ if isinstance(obj,numpy.bytes_)==True or isinstance(o...
o2sclpy/utils.py
codereval_python_data_163
Create a time from ticks (nanoseconds since midnight). :param ticks: nanoseconds since midnight :type ticks: int :param tz: optional timezone :type tz: datetime.tzinfo :rtype: Time :raises ValueError: if ticks is out of bounds (0 <= ticks < 86400000000000) @classmethod def from_ticks(cls, ticks, tz=None...
neo4j/time/__init__.py
codereval_python_data_164
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/_async/io/_bolt.py
codereval_python_data_165
Create a Bookmarks object from a list of raw bookmark string values. You should not need to use this method unless you want to deserialize bookmarks. :param values: ASCII string values (raw bookmarks) :type values: Iterable[str] @classmethod def from_raw_values(cls, values): """Create a Bookmarks obj...
neo4j/api.py
codereval_python_data_166
Return a (sequence, type) pair. Sequence is derived from *seq* (or is *seq*, if that is of a sequence type). def _get_seq_with_type(seq, bufsize=None): """Return a (sequence, type) pair. Sequence is derived from *seq* (or is *seq*, if that is of a sequence type). """ seq_type = "" if isinstance...
lena/core/split.py
codereval_python_data_167
Compute or set scale (integral of the histogram). If *other* is ``None``, return scale of this histogram. If its scale was not computed before, it is computed and stored for subsequent use (unless explicitly asked to *recompute*). Note that after changing (filling) the histogram one must explicitly recompute the scale...
lena/structures/histogram.py
codereval_python_data_168
Get or set the scale of the graph. If *other* is ``None``, return the scale of this graph. If a numeric *other* is provided, rescale to that value. If the graph has unknown or zero scale, rescaling that will raise :exc:`~.LenaValueError`. To get meaningful results, graph's fields are used. Only the last coordinate i...
lena/structures/graph.py
codereval_python_data_169
Convert a :class:`.histogram` to a :class:`.graph`. *make_value* is a function to set the value of a graph's point. By default it is bin content. *make_value* accepts a single value (bin content) without context. This option could be used to create graph's error bars. For example, to create a graph with errors from a...
lena/structures/hist_functions.py
codereval_python_data_170
Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interf...
src/zope/interface/verify.py
codereval_python_data_171
Verify that *candidate* might correctly provide *iface*. This involves: - Making sure the candidate claims that it provides the interface using ``iface.providedBy`` (unless *tentative* is `True`, in which case this step is skipped). This means that the candidate's class declares that it `implements <zope.interf...
src/zope/interface/verify.py
codereval_python_data_172
Verify that the *candidate* might correctly provide *iface*. def verifyClass(iface, candidate, tentative=False): """ Verify that the *candidate* might correctly provide *iface*. """ return _verify(iface, candidate, tentative, vtype='c') ################################################################...
src/zope/interface/verify.py
codereval_python_data_173
Determine metaclass from 1+ bases and optional explicit __metaclass__ def determineMetaclass(bases, explicit_mc=None): """Determine metaclass from 1+ bases and optional explicit __metaclass__""" meta = [getattr(b,'__class__',type(b)) for b in bases] if explicit_mc is not None: # The explicit meta...
src/zope/interface/advice.py
codereval_python_data_174
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. def pop(self, key, default=__marker): if key in self: value = self[key] del self[key] elif default is self.__marker: ...
cachetools/cache.py
codereval_python_data_175
Remove and return the `(key, value)` pair least frequently used. def popitem(self): """Remove and return the `(key, value)` pair least frequently used.""" try: (key, _), = self.__counter.most_common(1) except ValueError: raise KeyError('%s is empty' % type(self).__na...
cachetools/lfu.py
codereval_python_data_176
Remove and return the `(key, value)` pair least recently used. def popitem(self): """Remove and return the `(key, value)` pair least recently used.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from N...
cachetools/lru.py
codereval_python_data_177
Remove and return the `(key, value)` pair most recently used. def popitem(self): """Remove and return the `(key, value)` pair most recently used.""" try: key = next(iter(self.__order)) except StopIteration: raise KeyError('%s is empty' % type(self).__name__) from Non...
cachetools/mru.py
codereval_python_data_178
Remove and return a random `(key, value)` pair. def popitem(self): """Remove and return a random `(key, value)` pair.""" try: key = self.__choice(list(self)) except IndexError: raise KeyError('%s is empty' % type(self).__name__) from None else: re...
cachetools/rr.py
codereval_python_data_179
Create the in-style parameter regular expression. Returns the in-style parameter regular expression (:class:`re.Pattern`). def _create_in_regex(self) -> Pattern: """ Create the in-style parameter regular expression. Returns the in-style parameter regular expression (:class:`re.Pattern`). """ regex_parts =...
sqlparams/__init__.py
codereval_python_data_180
Create the parameter style converter. Returns the parameter style converter (:class:`._converting._Converter`). def _create_converter(self) -> _converting._Converter: """ Create the parameter style converter. Returns the parameter style converter (:class:`._converting._Converter`). """ assert self._in_reg...
sqlparams/__init__.py
codereval_python_data_181
Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. An ISO-8601 datetime string consists of a date portion, followed optionally by a time portion - the date and time portions are separated by a single character separator, which is ``T`` in the official standard. Incomplete date formats (such as ``YYYY...
dateutil/parser/isoparser.py
codereval_python_data_182
Parse the date/time string into a :class:`datetime.datetime` object. :param timestr: Any date/time string using the supported formats. :param default: The default datetime object, if this is a datetime object and not ``None``, elements specified in ``timestr`` replace elements in the default object. ...
dateutil/parser/_parser.py
codereval_python_data_183
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_184
Sets the ``tzinfo`` parameter on naive datetimes only This is useful for example when you are provided a datetime that may have either an implicit or explicit time zone, such as when parsing a time zone string. .. doctest:: >>> from dateutil.tz import tzoffset >>> from dateutil.parser import parse >>> fr...
dateutil/utils.py
codereval_python_data_185
Set the bytes used to delimit slice points. Args: before: Split file before these delimiters. after: Split file after these delimiters. def set_cut_chars(self, before: bytes, after: bytes) -> None: """Set the bytes used to delimit slice points. Args: before: Split file before ...
src/lithium/testcases.py
codereval_python_data_186
Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a legacy payload. def identify_request(request: RequestType): """Try to identify whether this is a Diaspora request. Try first public message. Then private message. The check if this is a ...
federation/protocols/diaspora/protocol.py
codereval_python_data_187
Try to identify whether this is a Matrix request def identify_request(request: RequestType) -> bool: """ Try to identify whether this is a Matrix request """ # noinspection PyBroadException try: data = json.loads(decode_if_bytes(request.body)) if "events" in data: return...
federation/protocols/matrix/protocol.py
codereval_python_data_188
Format a datetime in the way that D* nodes expect. def format_dt(dt): """ Format a datetime in the way that D* nodes expect. """ return ensure_timezone(dt).astimezone(tzutc()).strftime( '%Y-%m-%dT%H:%M:%SZ' ) from dateutil.tz import tzlocal, tzutc from lxml import etree def ensure_timez...
federation/entities/diaspora/utils.py
codereval_python_data_189
Find tags in text. Tries to ignore tags inside code blocks. Optionally, if passed a "replacer", will also replace the tag word with the result of the replacer function called with the tag word. Returns a set of tags and the original or replaced text. def find_tags(text: str, replacer: callable = None) -> Tuple[Set,...
federation/utils/text.py
codereval_python_data_190
Process links in text, adding some attributes and linkifying textual links. def process_text_links(text): """Process links in text, adding some attributes and linkifying textual links.""" link_callbacks = [callbacks.nofollow, callbacks.target_blank] def link_attributes(attrs, new=False): """Run st...
federation/utils/text.py
codereval_python_data_191
Fetch the HEAD of the remote url to determine the content type. def fetch_content_type(url: str) -> Optional[str]: """ Fetch the HEAD of the remote url to determine the content type. """ try: response = requests.head(url, headers={'user-agent': USER_AGENT}, timeout=10) except RequestExcepti...
federation/utils/network.py
codereval_python_data_192
Test a word whether it could be accepted as a tag. def test_tag(tag: str) -> bool: """Test a word whether it could be accepted as a tag.""" if not tag: return False for char in ILLEGAL_TAG_CHARS: if char in tag: return False return True import re from typing import Set, Tu...
federation/utils/text.py
codereval_python_data_193
Turn the children of node <xml> into a dict, keyed by tag name. This is only a shallow conversation - child nodes are not recursively processed. def xml_children_as_dict(node): """Turn the children of node <xml> into a dict, keyed by tag name. This is only a shallow conversation - child nodes are not recursi...
federation/entities/diaspora/mappers.py
codereval_python_data_194
Ensure that sender and entity handles match. Basically we've already verified the sender is who they say when receiving the payload. However, the sender might be trying to set another author in the payload itself, since Diaspora has the sender in both the payload headers AND the object. We must ensure they're the same...
federation/entities/diaspora/mappers.py
codereval_python_data_195
Generate a NodeInfo .well-known document. See spec: http://nodeinfo.diaspora.software :arg url: The full base url with protocol, ie https://example.com :arg document_path: Custom NodeInfo document path if supplied (optional) :returns: dict def get_nodeinfo_well_known_document(url, document_path=None): """Generat...
federation/hostmeta/generators.py
codereval_python_data_196
Verify the signed XML elements to have confidence that the claimed author did actually generate this message. def verify_relayable_signature(public_key, doc, signature): """ Verify the signed XML elements to have confidence that the claimed author did actually generate this message. """ sig_hash = ...
federation/protocols/diaspora/signatures.py
codereval_python_data_197
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github.io/diaspora_federation/discovery/webfinger.html def parse_diaspora_webfinger(document: str) -> Dict: """ Parse Diaspora webfinger which is either in JSON format (new) or XRD (old). https://diaspora.github....
federation/utils/diaspora.py
codereval_python_data_198
Try to retrieve an RFC7033 webfinger document. Does not raise if it fails. def try_retrieve_webfinger_document(handle: str) -> Optional[str]: """ Try to retrieve an RFC7033 webfinger document. Does not raise if it fails. """ try: host = handle.split("@")[1] except AttributeError: lo...
federation/utils/network.py
codereval_python_data_199
Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict def retrieve_and_parse_diaspora_webfinger(handle): """ Retrieve a and parse a remote Diaspora webfinger document. :arg handle: Remote handle to retrieve :returns: dict """ document...
federation/utils/diaspora.py
codereval_python_data_200
Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance def retrieve_diaspora_host_meta(host): """ Retrieve a remote Diaspora host-meta document. :arg host: Host to retrieve from :returns: ``XRD`` instance """ document, code, exception = fetc...
federation/utils/diaspora.py