id stringlengths 24 24 | input stringlengths 69 2.76k | output stringlengths 97 21.1k |
|---|---|---|
62b87d23d292efb640a55668 | def get_config():
"""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_prefix = ""
cfg.parentdir_prefix = "None"
cfg.versio... |
62b87d23d292efb640a55667 | def register_vcs_handler(vcs, method): # decorator
"""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] = {}
HANDLERS[vcs][method] = f
return f
return dec... |
62b45e945108cfac7f210a4a | def validate_hierarchy(self, validate_objects=True, check_digests=True, show_warnings=False):
"""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:
num_objects - number of objects checked
good_objects - number of objects checked that were found to be valid
"""
num_obj... |
62b45e515108cfac7f210a3c | def initialize(self):
"""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 already exists, aborting!" % (self.root))
... |
62b45e2eb89c9fd354170232 | def next_version(version):
"""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*)$''', version)
if not m:
raise ObjectException("Bad version '%s'" % version)
next_n = int(m.group(1)) + 1
... |
62b45e23e0d4551b0392c90a | def validate_version_inventories(self, version_dirs):
"""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... | def validate_version_inventories(self, version_dirs):
"""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... |
62b45e21e0d4551b0392c8ed | def find_path_type(path):
"""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 onl... | def find_path_type(path):
"""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 onl... |
62b45b396decaeff903e1001 | def amend_bzparams(self, params, bug_ids):
"""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" not in fields:
... |
62b4567ed7d32e5b55cc83d9 | def deep_merge_nodes(nodes):
'''
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 correspondin... | def deep_merge_nodes(nodes):
'''
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 correspondin... |
62b4567ad7d32e5b55cc83af | def parse_arguments(*arguments):
'''
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.
'''
parser = ArgumentParser(description='Generate a sample borgmatic YAML configuration file.')
parser.add_argument(
'-... |
62b45679d7d32e5b55cc83a9 | def parser_flags(parser):
'''
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 action.option_strings)
|
62b45665d7d32e5b55cc8365 | def parse_arguments(*unparsed_arguments):
'''
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 arguments and return
them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance.
'''
top_level_parser, subparsers = make_parsers()
arguments, ... |
62b45665d7d32e5b55cc8364 | def parse_subparser_arguments(unparsed_arguments, subparsers):
'''
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 acros... | def parse_subparser_arguments(unparsed_arguments, subparsers):
'''
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 acros... |
62b45665d7d32e5b55cc8363 | def make_parsers():
'''
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(expand_home=False)
global_parser = ArgumentParser(add_help=False)
... |
62b438ba66fea644fe22cca2 | def deep_merge_nodes(nodes):
'''
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 correspondin... | def deep_merge_nodes(nodes):
'''
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 correspondin... |
62b438b666fea644fe22cc78 | def parse_arguments(*arguments):
'''
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.
'''
parser = ArgumentParser(description='Generate a sample borgmatic YAML configuration file.')
parser.add_argument(
'-... |
62b438b666fea644fe22cc72 | def parser_flags(parser):
'''
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 action.option_strings)
|
62b438b566fea644fe22cc70 | def bash_completion():
'''
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_level_parser, subparsers = arguments.make_parsers()
global_flags = parser_flags(top_level_parser)
actions = ' '.join(subparse... |
62b438a266fea644fe22cc2e | def parse_arguments(*unparsed_arguments):
'''
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 arguments and return
them as a dict mapping from subparser name (or "global") to an argparse.Namespace instance.
'''
top_level_parser, subparsers = make_parsers()
arguments, ... |
62b438a266fea644fe22cc2d | def parse_subparser_arguments(unparsed_arguments, subparsers):
'''
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 acros... | def parse_subparser_arguments(unparsed_arguments, subparsers):
'''
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 acros... |
62b438a266fea644fe22cc2c | def make_parsers():
'''
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(expand_home=False)
global_parser = ArgumentParser(add_help=False)
... |
62ece4982e6aefcf4aabbd5f | def paging(response, max_results):
"""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:
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.
"""
i = 0
while i < le... |
62ece4982e6aefcf4aabbd60 | def size_to_bytes(size: str) -> int:
"""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
... | def size_to_bytes(size: str) -> int:
"""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
... |
62ece4982e6aefcf4aabbd61 | 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}
"""
| 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 = iter(dicts)
first = next(it).copy()
for d in it:
for k, v in d.items():
first[k] += v
return first... |
62ece4982e6aefcf4aabbd62 | def _replace_url_args(url, url_args):
"""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
|
62ece4982e6aefcf4aabbd63 | def is_none_string(val: any) -> bool:
"""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'
|
62ece4982e6aefcf4aabbd65 | def parser_flags(parser):
'''
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 action.option_strings)
|
62ece4982e6aefcf4aabbd66 | def was_processed(processed, path_name, verbose):
"""
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, re... | def was_processed(processed, path_name, verbose):
"""
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, re... |
62ece4982e6aefcf4aabbd67 | def vertex3tuple(vertices):
"""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. 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
"""
asver... |
62ece4982e6aefcf4aabbd68 | 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.
"""
| 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.
"""
output = ""
alpha_len = len(alphabet)
while number:
number, digit = divmod(numb... |
62ece4982e6aefcf4aabbd69 | def _replace_register(flow_params, register_number, register_value):
"""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... | def _replace_register(flow_params, register_number, register_value):
"""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... |
62ece4982e6aefcf4aabbd6a | def replace_dots(value, arg):
"""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)
|
62ece4982e6aefcf4aabbd6b | def subclasses(cls):
"""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))
)
|
62ece4982e6aefcf4aabbd6d | 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.
"""
| 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.
"""
number = 0
alpha_len = len(alphabet)
for char in string:
number = number * alpha_len + alphabet.... |
62ece4982e6aefcf4aabbd6f | import requests
def get_repo_archive(url: str, destination_path: Path) -> Path:
"""
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:
... | import requests
def get_repo_archive(url: str, destination_path: Path) -> Path:
"""
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:
... |
62ece4982e6aefcf4aabbd70 | import os
def os_is_mac():
"""
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"
|
62ece4982e6aefcf4aabbd71 | import re
def regex_dict(item):
"""
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'},
... | import re
def regex_dict(item):
"""
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'},
... |
62ece4982e6aefcf4aabbd72 | import re
def unquote(name):
"""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 len(match.group()) != 4:
... |
62ece4982e6aefcf4aabbd73 | import re
def split(s, platform='this'):
"""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 value... | import re
def split(s, platform='this'):
"""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 value... |
62ece4982e6aefcf4aabbd74 | import subprocess
def prepare_repository_from_archive(
archive_path: str,
filename: Optional[str] = None,
tmp_path: Union[PosixPath, str] = "/tmp",
) -> str:
"""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 ca... | import subprocess
def prepare_repository_from_archive(
archive_path: str,
filename: Optional[str] = None,
tmp_path: Union[PosixPath, str] = "/tmp",
) -> str:
"""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 ca... |
62ece4982e6aefcf4aabbd75 | import subprocess
def addignored(ignored):
''' 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 only ignored files, return those files as a single string with each filename separated by a comma.'''
fldr=subprocess.run(["git", "-C", ignored, "status", "-s", "--ignored"], captu... |
62ece4982e6aefcf4aabbd76 | import os
def match(filename):
"""
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:
False if not a match, True if supported
"""
base_name = os.path.basename(filename)
base_name_lower = base_name.lower()
return base_nam... |
62ece4982e6aefcf4aabbd77 | import datetime
def parse_frequency(frequency):
'''
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 ... | import datetime
def parse_frequency(frequency):
'''
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 ... |
62ece4992e6aefcf4aabbd78 | 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
"""
| 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",
"localhost",
socket.gethostname(),
# just in case soc... |
62ece4992e6aefcf4aabbd79 | import re
def make_find_paths(find_paths):
'''
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... | import re
def make_find_paths(find_paths):
'''
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... |
62ece4992e6aefcf4aabbd7a | import os
def is_gitbash():
"""
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
|
62ece4992e6aefcf4aabbd7b | import os
def write_configuration(config_filename, rendered_config, mode=0o600, overwrite=False):
'''
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 an... | import os
def write_configuration(config_filename, rendered_config, mode=0o600, overwrite=False):
'''
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 an... |
62ece4992e6aefcf4aabbd7c | 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.
: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.
:param script:
:return:
"""
return seperator.join(textwrap.dedent(script).strip().splitlines())
|
62ece4992e6aefcf4aabbd7d | import subprocess
def subprocess_run_helper(func, *args, timeout, extra_env=None):
"""
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 ... | import subprocess
def subprocess_run_helper(func, *args, timeout, extra_env=None):
"""
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 ... |
62ece4992e6aefcf4aabbd7e | import os
def _resolve_string(matcher):
'''
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 optional default value.
If the variable is not defined in environment and no default value is provided, an Error is raised.
'''
name, default = matcher.group("name"), matcher.group("de... |
62ece4992e6aefcf4aabbd7f | 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 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 image
:returns: a tuple of the form (image_id, netloc, use_ssl)
:raises ValueError:
"""
url = urllib.parse.urlparse(image_href)
netloc = ... |
62ece4992e6aefcf4aabbd80 | import os
def remove_ending_os_sep(input_list):
"""
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:
... | import os
def remove_ending_os_sep(input_list):
"""
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:
... |
62ece4992e6aefcf4aabbd82 | import re
def get_pattern(pattern, strip=True):
"""
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()
return re.compile(pattern)
|
62ece4992e6aefcf4aabbd83 | import subprocess
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):
"""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 window if pythonw.exe is used
... |
62ece4992e6aefcf4aabbd84 | import ipaddress
def is_ipv4(target):
""" 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
|
62ece4992e6aefcf4aabbd85 | import rdflib
def find_roots(
graph: "Graph", prop: "URIRef", roots: Optional[Set["Node"]] = None
) -> Set["Node"]:
"""
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... | import rdflib
def find_roots(
graph: "Graph", prop: "URIRef", roots: Optional[Set["Node"]] = None
) -> Set["Node"]:
"""
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... |
62ece4992e6aefcf4aabbd86 | import yaml
def _dump_string(obj, dumper=None):
"""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)
|
62ece4992e6aefcf4aabbd87 | import os,logging
def build_app_logger(name='app', logfile='app.log', debug=True):
"""
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
logdir = './logs' # TODO: move this to settings
if... |
62ece4992e6aefcf4aabbd88 | import numpy as np
def make_array(shape, dtype=np.dtype("float32")):
"""
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.
Parameters
----------
shape : tuple
shape of the array to create
dtype : `numpy.dtype`
data-type of the array to create
"""
return np.zeros(shape, d... |
62ece4992e6aefcf4aabbd89 | import numpy as np
def gaussian(x):
"""
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)
|
62ece4992e6aefcf4aabbd8a | import logging
def load_configurations(config_filenames, overrides=None, resolve_env=True):
'''
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 ... | import logging
def load_configurations(config_filenames, overrides=None, resolve_env=True):
'''
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 ... |
62ece4992e6aefcf4aabbd8b | import numpy
def force_string(obj):
"""
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(obj,bytes)==True:
return obj.decode('utf-8')
return obj
|
62e60723d76274f8a4026b76 | @classmethod
def from_ticks(cls, ticks, tz=None):
"""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:... | @classmethod
def from_ticks(cls, ticks, tz=None):
"""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:... |
62e60873d76274f8a4026bd8 | @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... |
62e60e3bd76274f8a4026d1a | @classmethod
def from_raw_values(cls, values):
"""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: Itera... | @classmethod
def from_raw_values(cls, values):
"""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: Itera... |
62b87b199a0c4fa8b80b354c | 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).
"""
| 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(seq, source.Source):
seq_type = "source"
elif isinstance(seq, fill_compute_seq.FillComputeSeq):
... |
62b87b4f9a0c4fa8b80b3581 | def scale(self, other=None, recompute=False):
"""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 *recomput... | def scale(self, other=None, recompute=False):
"""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 *recomput... |
62b87b519a0c4fa8b80b3583 | def scale(self, other=None):
"""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`.
... | def scale(self, other=None):
"""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`.
... |
62b87b869a0c4fa8b80b35e1 | def hist_to_graph(hist, make_value=None, get_coordinate="left",
field_names=("x", "y"), scale=None):
"""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... | def hist_to_graph(hist, make_value=None, get_coordinate="left",
field_names=("x", "y"), scale=None):
"""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... |
62b8b4baeb7e40a82d2d1136 | def _verify(iface, candidate, tentative=False, vtype=None):
"""
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 ski... | def _verify(iface, candidate, tentative=False, vtype=None):
"""
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 ski... |
62b8b4baeb7e40a82d2d1137 | def verifyObject(iface, candidate, tentative=False):
"""
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... | def verifyObject(iface, candidate, tentative=False):
return _verify(iface, candidate, tentative, vtype='o')
|
62b8b4c1eb7e40a82d2d1139 | def verifyClass(iface, candidate, tentative=False):
"""
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')
|
62b8b559eb7e40a82d2d11f6 | def determineMetaclass(bases, explicit_mc=None):
"""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 metaclass needs to be verified for compatibility
# as well, and all... |
62b8d22a48ba5a41d1c3f47d | def pop(self, key, default=__marker):
"""
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:
raise KeyError(key)
else:
value = default
return value
|
62b8d23748ba5a41d1c3f497 | def popitem(self):
"""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).__name__) from None
else:
return (key, self.pop(ke... |
62b8d23a48ba5a41d1c3f499 | def popitem(self):
"""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 None
else:
return (key, self.pop(key))
|
62b8d23c48ba5a41d1c3f49b | def popitem(self):
"""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 None
else:
return (key, self.pop(key))
|
62b8d23e48ba5a41d1c3f49e | def popitem(self):
"""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:
return (key, self.pop(key))
|
62b43425903eeb48555d3ea1 | def _create_in_regex(self) -> Pattern:
"""
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 = []
if self._in_obj.escape_char != "%" and self._out_obj.escape_char == "%":
regex_parts.append("(?P<out_percent>%)")
... |
62b43426903eeb48555d3ea2 | def _create_converter(self) -> _converting._Converter:
"""
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_regex is not None, self._in_regex
assert self._out_obj is not None, self._out_obj
# Determine converter class.
... |
62b8966c755ee91dce50a154 | @_takes_ascii
def isoparse(self, dt_str):
"""
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 charact... | @_takes_ascii
def isoparse(self, dt_str):
"""
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 charact... |
62b896de755ee91dce50a183 | def parse(self, timestr, default=None,
ignoretz=False, tzinfos=None, **kwargs):
"""
Parse the date/time string into a :class:`datetime.datetime` object.
:param timestr:
Any date/time string using the supported formats.
:param default:
The defau... | def parse(self, timestr, default=None,
ignoretz=False, tzinfos=None, **kwargs):
"""
Parse the date/time string into a :class:`datetime.datetime` object.
:param timestr:
Any date/time string using the supported formats.
:param default:
The defau... |
62b8a4a4755ee91dce50a3d3 | @_validate_fromutc_inputs
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... | @_validate_fromutc_inputs
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... |
62b8a7b2755ee91dce50a4a7 | def default_tzinfo(dt, tzinfo):
"""
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 impo... | def default_tzinfo(dt, tzinfo):
"""
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 impo... |
6305f9991d275c6667163c50 | def set_cut_chars(self, before: bytes, after: bytes) -> None:
"""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 these delimiters.
after: Split file after these delimiters.
"""
self._cutter = re.compile(
b"["
... |
6306292052e177c0ba469f09 | 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 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 legacy payload.
"""
# Private encrypted JSON payload
try:
data = json.loads(decode_if_bytes(request.body))
if "en... |
6306292152e177c0ba469f0d | def identify_request(request: RequestType) -> bool:
"""
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 True
except Exception:
pass
retur... |
6306292252e177c0ba469f11 | def format_dt(dt):
"""
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'
)
|
6306292352e177c0ba469f1d | def find_tags(text: str, replacer: callable = None) -> Tuple[Set, str]:
"""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 th... | def find_tags(text: str, replacer: callable = None) -> Tuple[Set, str]:
"""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 th... |
6306292352e177c0ba469f1e | def process_text_links(text):
"""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 standard callbacks except for internal links."""
href_key = (None, "hre... |
6306292652e177c0ba469f34 | def fetch_content_type(url: str) -> Optional[str]:
"""
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 RequestException as ex:
logger.warning("fetch_content_type - %s when fe... |
6306292a52e177c0ba469f41 | def test_tag(tag: str) -> bool:
"""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
|
6306298b52e177c0ba469fdc | 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 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 recursively processed.
"""
return dict((e.tag, e.text) for e in node)
|
6306299052e177c0ba469fe8 | def check_sender_and_entity_handle_match(sender_handle, entity_handle):
"""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... | def check_sender_and_entity_handle_match(sender_handle, entity_handle):
"""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... |
630629b952e177c0ba46a043 | def get_nodeinfo_well_known_document(url, document_path=None):
"""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)
:return... | def get_nodeinfo_well_known_document(url, document_path=None):
"""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)
:return... |
630629d052e177c0ba46a0a1 | 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.
"""
| 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 = _create_signature_hash(doc)
cipher = PKCS1_v1_5.new(RSA.importKey(public_key))
return cipher.verify(sig... |
630629e052e177c0ba46a0c4 | def parse_diaspora_webfinger(document: str) -> Dict:
"""
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.io/diaspora_federation/discovery/webfinger.html
"""
webfinger = {
"hcard_url": None,
}
# noinspection PyBroadException
try... |
630629e152e177c0ba46a0d1 | def try_retrieve_webfinger_document(handle: str) -> Optional[str]:
"""
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:
logger.warning("retrieve_webfinger_document: invalid handle given: %s", handle... |
630629e152e177c0ba46a0d2 | def retrieve_and_parse_diaspora_webfinger(handle):
"""
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 = try_retrieve_webfinger_document(handle)
if document:
return parse_diaspora_webfinger(document)
h... |
630629e252e177c0ba46a0d6 | def retrieve_diaspora_host_meta(host):
"""
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 = fetch_document(host=host, path="/.well-known/host-meta")
if exception:
return None
xrd = XRD.pars... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.