sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def serve_static(app, base_url, base_path, index=False):
"""
Serve a directory statically
Parameters:
* app: Grole application object
* base_url: Base URL to serve from, e.g. /static
* base_path: Base path to look for files in
* index: Provide simple directory indexes if Tr... | Serve a directory statically
Parameters:
* app: Grole application object
* base_url: Base URL to serve from, e.g. /static
* base_path: Base path to look for files in
* index: Provide simple directory indexes if True | entailment |
def serve_doc(app, url):
"""
Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at
"""
@app.route(url, doc=False)
def index(env, req):
ret = ''
for d in env['doc']:
ret += ... | Serve API documentation extracted from request handler docstrings
Parameters:
* app: Grole application object
* url: URL to serve at | entailment |
def parse_args(args=sys.argv[1:]):
"""
Parse command line arguments for Grole server running as static file server
"""
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--address', help='address to listen on, default localhost',
default='localhost')
pa... | Parse command line arguments for Grole server running as static file server | entailment |
def main(args=sys.argv[1:]):
"""
Run Grole static file server
"""
args = parse_args(args)
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
elif args.quiet:
logging.basicConfig(level=logging.ERROR)
else:
logging.basicConfig(level=logging.INFO)
app = Grole(... | Run Grole static file server | entailment |
async def _read(self, reader):
"""
Parses HTTP request into member variables
"""
start_line = await self._readline(reader)
self.method, self.location, self.version = start_line.decode().split()
path_query = urllib.parse.unquote(self.location).split('?', 1)
self.pa... | Parses HTTP request into member variables | entailment |
async def _readline(self, reader):
"""
Readline helper
"""
ret = await reader.readline()
if len(ret) == 0 and reader.at_eof():
raise EOFError()
return ret | Readline helper | entailment |
async def _buffer_body(self, reader):
"""
Buffers the body of the request
"""
remaining = int(self.headers.get('Content-Length', 0))
if remaining > 0:
try:
self.data = await reader.readexactly(remaining)
except asyncio.IncompleteReadError:
... | Buffers the body of the request | entailment |
def route(self, path_regex, methods=['GET'], doc=True):
"""
Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc struct... | Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc structure | entailment |
async def _handle(self, reader, writer):
"""
Handle a single TCP connection
Parses requests, finds appropriate handlers and returns responses
"""
peer = writer.get_extra_info('peername')
self._logger.debug('New connection from {}'.format(peer))
try:
#... | Handle a single TCP connection
Parses requests, finds appropriate handlers and returns responses | entailment |
def run(self, host='localhost', port=1234):
"""
Launch the server. Will run forever accepting connections until interrupted.
Parameters:
* host: The host to listen on
* port: The port to listen on
"""
# Setup loop
loop = asyncio.get_event_loop()
... | Launch the server. Will run forever accepting connections until interrupted.
Parameters:
* host: The host to listen on
* port: The port to listen on | entailment |
def hold(model: Model, reducer: Optional[Callable] = None) -> Iterator[list]:
"""Temporarilly withold change events in a modifiable list.
All changes that are captured within a "hold" context are forwarded to a list
which is yielded to the user before being sent to views of the given ``model``.
If desi... | Temporarilly withold change events in a modifiable list.
All changes that are captured within a "hold" context are forwarded to a list
which is yielded to the user before being sent to views of the given ``model``.
If desired, the user may modify the list of events before the context is left in
order t... | entailment |
def rollback(
model: Model, undo: Optional[Callable] = None, *args, **kwargs
) -> Iterator[list]:
"""Withold events if an error occurs.
Generall operate
Parameters:
model:
The model object whose change events may be witheld.
undo:
An optional function for revers... | Withold events if an error occurs.
Generall operate
Parameters:
model:
The model object whose change events may be witheld.
undo:
An optional function for reversing any changes that may have taken place.
Its signature is ``(model, events, error)`` where ``mo... | entailment |
def mute(model: Model):
"""Block a model's views from being notified.
All changes within a "mute" context will be blocked. No content is yielded to the
user as in :func:`hold`, and the views of the model are never notified that changes
took place.
Parameters:
mode: The model whose change e... | Block a model's views from being notified.
All changes within a "mute" context will be blocked. No content is yielded to the
user as in :func:`hold`, and the views of the model are never notified that changes
took place.
Parameters:
mode: The model whose change events will be blocked.
Exa... | entailment |
def expose(*methods):
"""A decorator for exposing the methods of a class.
Parameters
----------
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
decorator : function
A function accepting one argument - the class whose m... | A decorator for exposing the methods of a class.
Parameters
----------
*methods : str
A str representation of the methods that should be exposed to callbacks.
Returns
-------
decorator : function
A function accepting one argument - the class whose methods will be
expose... | entailment |
def expose_as(name, base, *methods):
"""Return a new type with certain methods that are exposed to callback registration.
Parameters
----------
name : str
The name of the new type.
base : type
A type such as list or dict.
*methods : str
A str representation of the method... | Return a new type with certain methods that are exposed to callback registration.
Parameters
----------
name : str
The name of the new type.
base : type
A type such as list or dict.
*methods : str
A str representation of the methods that should be exposed to callbacks.
... | entailment |
def watchable(value):
"""Returns True if the given value is a :class:`Watchable` subclass or instance."""
check = issubclass if inspect.isclass(value) else isinstance
return check(value, Watchable) | Returns True if the given value is a :class:`Watchable` subclass or instance. | entailment |
def watch(value, spectator_type=Spectator):
"""Register a :class:`Specatator` to a :class:`Watchable` and return it.
In order to register callbacks to an eventful object, you need to create
a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple
object that has methods for ... | Register a :class:`Specatator` to a :class:`Watchable` and return it.
In order to register callbacks to an eventful object, you need to create
a Spectator that will watch it for you. A :class:`Specatator` is a relatively simple
object that has methods for adding, deleting, and triggering callbacks. To
... | entailment |
def watched(cls, *args, **kwargs):
"""Create and return a :class:`Watchable` with its :class:`Specatator`.
See :func:`watch` for more info on :class:`Specatator` registration.
Parameters
----------
cls: type:
A subclass of :class:`Watchable`
*args:
Positional arguments used to ... | Create and return a :class:`Watchable` with its :class:`Specatator`.
See :func:`watch` for more info on :class:`Specatator` registration.
Parameters
----------
cls: type:
A subclass of :class:`Watchable`
*args:
Positional arguments used to create the instance
**kwargs:
... | entailment |
def unwatch(value):
"""Return the :class:`Specatator` of a :class:`Watchable` instance."""
if not isinstance(value, Watchable):
raise TypeError("Expected a Watchable, not %r." % value)
spectator = watcher(value)
try:
del value._instance_spectator
except Exception:
pass
re... | Return the :class:`Specatator` of a :class:`Watchable` instance. | entailment |
def callback(self, name, before=None, after=None):
"""Add a callback pair to this spectator.
You can specify, with keywords, whether each callback should be triggered
before, and/or or after a given method is called - hereafter refered to as
"beforebacks" and "afterbacks" respectively.
... | Add a callback pair to this spectator.
You can specify, with keywords, whether each callback should be triggered
before, and/or or after a given method is called - hereafter refered to as
"beforebacks" and "afterbacks" respectively.
Parameters
----------
name: str
... | entailment |
def remove_callback(self, name, before=None, after=None):
"""Remove a beforeback, and afterback pair from this Spectator
If ``before`` and ``after`` are None then all callbacks for
the given method will be removed. Otherwise, only the exact
callback pair will be removed.
Parame... | Remove a beforeback, and afterback pair from this Spectator
If ``before`` and ``after`` are None then all callbacks for
the given method will be removed. Otherwise, only the exact
callback pair will be removed.
Parameters
----------
name: str
The name of the... | entailment |
def call(self, obj, name, method, args, kwargs):
"""Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
... | Trigger a method along with its beforebacks and afterbacks.
Parameters
----------
name: str
The name of the method that will be called
args: tuple
The arguments that will be passed to the base method
kwargs: dict
The keyword args that will be ... | entailment |
def cut_to_length(text, length, delim):
"""Shorten given text on first delimiter after given number
of characters.
"""
cut = text.find(delim, length)
if cut > -1:
return text[:cut]
else:
return text | Shorten given text on first delimiter after given number
of characters. | entailment |
def get_interpreter_path(version=None):
"""Return the executable of a specified or current version."""
if version and version != str(sys.version_info[0]):
return settings.PYTHON_INTERPRETER + version
else:
return sys.executable | Return the executable of a specified or current version. | entailment |
def license_from_trove(trove):
"""Finds out license from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
Fedora name of the package license or empty string, if no licensing
information is found in trove classifiers.
"""
license = []
for classifi... | Finds out license from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
Fedora name of the package license or empty string, if no licensing
information is found in trove classifiers. | entailment |
def versions_from_trove(trove):
"""Finds out python version from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
python version string
"""
versions = set()
for classifier in trove:
if 'Programming Language :: Python ::' in classifier:
... | Finds out python version from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
python version string | entailment |
def pypi_metadata_extension(extraction_fce):
"""Extracts data from PyPI and merges them with data from extraction
method.
"""
def inner(self, client=None):
data = extraction_fce(self)
if client is None:
logger.warning("Client is None, it was probably disabled")
d... | Extracts data from PyPI and merges them with data from extraction
method. | entailment |
def venv_metadata_extension(extraction_fce):
"""Extracts specific metadata from virtualenv object, merges them with data
from given extraction method.
"""
def inner(self):
data = extraction_fce(self)
if virtualenv is None or not self.venv:
logger.debug("Skipping virtualenv m... | Extracts specific metadata from virtualenv object, merges them with data
from given extraction method. | entailment |
def process_description(description_fce):
"""Removes special character delimiters, titles
and wraps paragraphs.
"""
def inner(description):
clear_description = \
re.sub(r'\s+', ' ', # multiple whitespaces
# general URLs
re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*... | Removes special character delimiters, titles
and wraps paragraphs. | entailment |
def versions_from_archive(self):
"""Return Python versions extracted from trove classifiers. """
py_vers = versions_from_trove(self.classifiers)
return [ver for ver in py_vers if ver != self.unsupported_version] | Return Python versions extracted from trove classifiers. | entailment |
def srcname(self):
"""Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name>
"""
if self.rpm_name or self.name.startswith(('python-', 'Python-')):
return self.name... | Return srcname for the macro if the pypi name should be changed.
Those cases are:
- name was provided with -r option
- pypi name is like python-<name> | entailment |
def extract_data(self):
"""Extracts data from archive.
Returns:
PackageData object containing the extracted data.
"""
data = PackageData(
local_file=self.local_file,
name=self.name,
pkg_name=self.rpm_name or self.name_convertor.rpm_name(
... | Extracts data from archive.
Returns:
PackageData object containing the extracted data. | entailment |
def data_from_archive(self):
"""Returns all metadata extractable from the archive.
Returns:
dictionary containing metadata extracted from the archive
"""
archive_data = {}
archive_data['runtime_deps'] = self.runtime_deps
archive_data['build_deps'] = [
... | Returns all metadata extractable from the archive.
Returns:
dictionary containing metadata extracted from the archive | entailment |
def runtime_deps(self): # install_requires
"""Returns list of runtime dependencies of the package specified in
setup.py.
Dependencies are in RPM SPECFILE format - see dependency_to_rpm()
for details, but names are already transformed according to
current distro.
Return... | Returns list of runtime dependencies of the package specified in
setup.py.
Dependencies are in RPM SPECFILE format - see dependency_to_rpm()
for details, but names are already transformed according to
current distro.
Returns:
list of runtime dependencies of the pack... | entailment |
def build_deps(self): # setup_requires [tests_require, install_requires]
"""Same as runtime_deps, but build dependencies. Test and install
requires are included if package contains test suite to prevent
%check phase crashes because of missing dependencies
Returns:
list of b... | Same as runtime_deps, but build dependencies. Test and install
requires are included if package contains test suite to prevent
%check phase crashes because of missing dependencies
Returns:
list of build dependencies of the package | entailment |
def doc_files(self):
"""Returns list of doc files that should be used for %doc in specfile.
Returns:
List of doc files from the archive - only basenames, not full
paths.
"""
doc_files = []
for doc_file_re in settings.DOC_FILES_RE:
doc_files.ext... | Returns list of doc files that should be used for %doc in specfile.
Returns:
List of doc files from the archive - only basenames, not full
paths. | entailment |
def sphinx_dir(self):
"""Returns directory with sphinx documentation, if there is such.
Returns:
Full path to sphinx documentation dir inside the archive, or None
if there is no such.
"""
# search for sphinx dir doc/ or docs/ under the first directory in
#... | Returns directory with sphinx documentation, if there is such.
Returns:
Full path to sphinx documentation dir inside the archive, or None
if there is no such. | entailment |
def data_from_archive(self):
"""Appends setup.py specific metadata to archive_data."""
archive_data = super(SetupPyMetadataExtractor, self).data_from_archive
archive_data['has_packages'] = self.has_packages
archive_data['packages'] = self.packages
archive_data['has_bundled_egg_... | Appends setup.py specific metadata to archive_data. | entailment |
def get_requires(self, requires_types):
"""Extracts requires of given types from metadata file, filter windows
specific requires.
"""
if not isinstance(requires_types, list):
requires_types = list(requires_types)
extracted_requires = []
for requires_name in re... | Extracts requires of given types from metadata file, filter windows
specific requires. | entailment |
def get_url(client, name, version, wheel=False, hashed_format=False):
"""Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL
of prefered archive and md5_digest.
"""
try:
release_urls = client.release_urls(name, version)
release_data = client.release_data(name, version)
e... | Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL
of prefered archive and md5_digest. | entailment |
def get(self, wheel=False):
"""Downloads the package from PyPI.
Returns:
Full path of the downloaded file.
Raises:
PermissionError if the save_dir is not writable.
"""
try:
url = get_url(self.client, self.name, self.version,
... | Downloads the package from PyPI.
Returns:
Full path of the downloaded file.
Raises:
PermissionError if the save_dir is not writable. | entailment |
def get(self):
"""Copies file from local filesystem to self.save_dir.
Returns:
Full path of the copied file.
Raises:
EnvironmentError if the file can't be found or the save_dir
is not writable.
"""
if self.local_file.endswith('.whl'):
... | Copies file from local filesystem to self.save_dir.
Returns:
Full path of the copied file.
Raises:
EnvironmentError if the file can't be found or the save_dir
is not writable. | entailment |
def _stripped_name_version(self):
"""Returns filename stripped of the suffix.
Returns:
Filename stripped of the suffix (extension).
"""
# we don't use splitext, because on "a.tar.gz" it returns ("a.tar",
# "gz")
filename = os.path.basename(self.local_file)
... | Returns filename stripped of the suffix.
Returns:
Filename stripped of the suffix (extension). | entailment |
def fill(self, path):
'''
Scans content of directories
'''
self.bindir = set(os.listdir(path + 'bin/'))
self.lib_sitepackages = set(os.listdir(glob.glob(
path + 'lib/python?.?/site-packages/')[0])) | Scans content of directories | entailment |
def install_package_to_venv(self):
'''
Installs package given as first argument to virtualenv without
dependencies
'''
try:
self.env.install(self.name, force=True, options=["--no-deps"])
except (ve.PackageInstallationException,
ve.VirtualenvRea... | Installs package given as first argument to virtualenv without
dependencies | entailment |
def get_dirs_differance(self):
'''
Makes final versions of site_packages and scripts using DirsContent
sub method and filters
'''
try:
diff = self.dirs_after_install - self.dirs_before_install
except ValueError:
raise VirtualenvFailException(
... | Makes final versions of site_packages and scripts using DirsContent
sub method and filters | entailment |
def main(package, v, d, s, r, proxy, srpm, p, b, o, t, venv, autonc, sclize,
**scl_kwargs):
"""Convert PyPI package to RPM specfile or SRPM.
\b
\b\bArguments:
PACKAGE Provide PyPI name of the package or path to compressed
source file.
"""
register_fi... | Convert PyPI package to RPM specfile or SRPM.
\b
\b\bArguments:
PACKAGE Provide PyPI name of the package or path to compressed
source file. | entailment |
def convert_to_scl(spec, scl_options):
"""Convert spec into SCL-style spec file using `spec2scl`.
Args:
spec: (str) a spec file
scl_options: (dict) SCL options provided
Returns:
A converted spec file
"""
scl_options['skip_functions'] = scl_options['skip_functions'].split(','... | Convert spec into SCL-style spec file using `spec2scl`.
Args:
spec: (str) a spec file
scl_options: (dict) SCL options provided
Returns:
A converted spec file | entailment |
def format_options(self, ctx, formatter):
"""Writes SCL related options into the formatter as a separate
group.
"""
super(Pyp2rpmCommand, self).format_options(ctx, formatter)
scl_opts = []
for param in self.get_params(ctx):
if isinstance(param, SclizeOption):
... | Writes SCL related options into the formatter as a separate
group. | entailment |
def handle_parse_result(self, ctx, opts, args):
"""Validate SCL related options before parsing."""
if 'sclize' in opts and not SclConvertor:
raise click.UsageError("Please install spec2scl package to "
"perform SCL-style conversion")
if self.name in... | Validate SCL related options before parsing. | entailment |
def to_list(var):
"""Checks if given value is a list, tries to convert, if it is not."""
if var is None:
return []
if isinstance(var, str):
var = var.split('\n')
elif not isinstance(var, list):
try:
var = list(var)
except TypeError:
raise ValueErro... | Checks if given value is a list, tries to convert, if it is not. | entailment |
def run(self):
"""Sends extracted metadata in json format to stdout if stdout
option is specified, assigns metadata dictionary to class_metadata
variable otherwise.
"""
if self.stdout:
sys.stdout.write("extracted json data:\n" + json.dumps(
self.metada... | Sends extracted metadata in json format to stdout if stdout
option is specified, assigns metadata dictionary to class_metadata
variable otherwise. | entailment |
def dependency_to_rpm(dep, runtime):
"""Converts a dependency got by pkg_resources.Requirement.parse()
to RPM format.
Args:
dep - a dependency retrieved by pkg_resources.Requirement.parse()
runtime - whether the returned dependency should be runtime (True)
or build time (False)
R... | Converts a dependency got by pkg_resources.Requirement.parse()
to RPM format.
Args:
dep - a dependency retrieved by pkg_resources.Requirement.parse()
runtime - whether the returned dependency should be runtime (True)
or build time (False)
Returns:
List of semi-SPECFILE depend... | entailment |
def deps_from_pyp_format(requires, runtime=True):
"""Parses dependencies extracted from setup.py.
Args:
requires: list of dependencies as written in setup.py of the package.
runtime: are the dependencies runtime (True) or build time (False)?
Returns:
List of semi-SPECFILE dependencie... | Parses dependencies extracted from setup.py.
Args:
requires: list of dependencies as written in setup.py of the package.
runtime: are the dependencies runtime (True) or build time (False)?
Returns:
List of semi-SPECFILE dependencies (see dependency_to_rpm for format). | entailment |
def deps_from_pydit_json(requires, runtime=True):
"""Parses dependencies returned by pydist.json, since versions
uses brackets we can't use pkg_resources to parse and we need a separate
method
Args:
requires: list of dependencies as written in pydist.json of the package
runtime: are the ... | Parses dependencies returned by pydist.json, since versions
uses brackets we can't use pkg_resources to parse and we need a separate
method
Args:
requires: list of dependencies as written in pydist.json of the package
runtime: are the dependencies runtime (True) or build time (False)
Ret... | entailment |
def get_changelog_date_packager(self):
"""Returns part of the changelog entry, containing date and packager.
"""
try:
packager = subprocess.Popen(
'rpmdev-packager', stdout=subprocess.PIPE).communicate(
)[0].strip()
except OSError:
... | Returns part of the changelog entry, containing date and packager. | entailment |
def run(self):
"""Executes the code of the specified module."""
with utils.ChangeDir(self.dirname):
sys.path.insert(0, self.dirname)
sys.argv[1:] = self.args
runpy.run_module(self.not_suffixed(self.filename),
run_name='__main__',
... | Executes the code of the specified module. | entailment |
def run(self, interpreter):
"""Executes the code of the specified module. Deserializes captured
json data.
"""
with utils.ChangeDir(self.dirname):
command_list = ['PYTHONPATH=' + main_dir, interpreter,
self.filename] + list(self.args)
t... | Executes the code of the specified module. Deserializes captured
json data. | entailment |
def generator_to_list(fn):
"""This decorator is for flat_list function.
It converts returned generator to list.
"""
def wrapper(*args, **kw):
return list(fn(*args, **kw))
return wrapper | This decorator is for flat_list function.
It converts returned generator to list. | entailment |
def flat_list(lst):
"""This function flatten given nested list.
Argument:
nested list
Returns:
flat list
"""
if isinstance(lst, list):
for item in lst:
for i in flat_list(item):
yield i
else:
yield lst | This function flatten given nested list.
Argument:
nested list
Returns:
flat list | entailment |
def extractor_cls(self):
"""Returns the class that can read this archive based on archive suffix.
Returns:
Class that can read this archive or None if no such exists.
"""
file_cls = None
# only catches ".gz", even from ".tar.gz"
if self.is_tar:
fi... | Returns the class that can read this archive based on archive suffix.
Returns:
Class that can read this archive or None if no such exists. | entailment |
def get_content_of_file(self, name, full_path=False):
"""Returns content of file from archive.
If full_path is set to False and two files with given name exist,
content of one is returned (it is not specified which one that is).
If set to True, returns content of exactly that file.
... | Returns content of file from archive.
If full_path is set to False and two files with given name exist,
content of one is returned (it is not specified which one that is).
If set to True, returns content of exactly that file.
Args:
name: name of the file to get content of
... | entailment |
def extract_file(self, name, full_path=False, directory="."):
"""Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file.
"""
if self.handle:
for member in self.handle.getmemb... | Extract a member from the archive to the specified working directory.
Behaviour of name and pull_path is the same as in function
get_content_of_file. | entailment |
def extract_all(self, directory=".", members=None):
"""Extract all member from the archive to the specified working
directory.
"""
if self.handle:
self.handle.extractall(path=directory, members=members) | Extract all member from the archive to the specified working
directory. | entailment |
def has_file_with_suffix(self, suffixes):
"""Finds out if there is a file with one of suffixes in the archive.
Args:
suffixes: list of suffixes or single suffix to look for
Returns:
True if there is at least one file with at least one given suffix
in the archi... | Finds out if there is a file with one of suffixes in the archive.
Args:
suffixes: list of suffixes or single suffix to look for
Returns:
True if there is at least one file with at least one given suffix
in the archive, False otherwise (or archive can't be opened) | entailment |
def get_files_re(self, file_re, full_path=False, ignorecase=False):
"""Finds all files that match file_re and returns their list.
Doesn't return directories, only files.
Args:
file_re: raw string to match files against (gets compiled into re)
full_path: whether to match ... | Finds all files that match file_re and returns their list.
Doesn't return directories, only files.
Args:
file_re: raw string to match files against (gets compiled into re)
full_path: whether to match against full path inside the archive
or just the filenames
... | entailment |
def get_directories_re(
self,
directory_re,
full_path=False,
ignorecase=False):
"""Same as get_files_re, but for directories"""
if ignorecase:
compiled_re = re.compile(directory_re, re.I)
else:
compiled_re = re.compile(direc... | Same as get_files_re, but for directories | entailment |
def top_directory(self):
"""Return the name of the archive topmost directory."""
if self.handle:
return os.path.commonprefix(self.handle.getnames()).rstrip('/') | Return the name of the archive topmost directory. | entailment |
def json_wheel_metadata(self):
"""Simple getter that get content of metadata.json file in .whl archive
Returns:
metadata from metadata.json or pydist.json in json format
"""
for meta_file in ("metadata.json", "pydist.json"):
try:
return json.loads(... | Simple getter that get content of metadata.json file in .whl archive
Returns:
metadata from metadata.json or pydist.json in json format | entailment |
def record(self):
"""Getter that get content of RECORD file in .whl archive
Returns:
dict with keys `modules` and `scripts`
"""
modules = []
scripts = []
if self.get_content_of_file('RECORD'):
lines = self.get_content_of_file('RECORD').splitlines(... | Getter that get content of RECORD file in .whl archive
Returns:
dict with keys `modules` and `scripts` | entailment |
def rpm_versioned_name(cls, name, version, default_number=False):
"""Properly versions the name.
For example:
rpm_versioned_name('python-foo', '26') will return python26-foo
rpm_versioned_name('pyfoo, '3') will return python3-pyfoo
If version is same as settings.DEFAULT_PYTHON_V... | Properly versions the name.
For example:
rpm_versioned_name('python-foo', '26') will return python26-foo
rpm_versioned_name('pyfoo, '3') will return python3-pyfoo
If version is same as settings.DEFAULT_PYTHON_VERSION, no change
is done.
Args:
name: name to v... | entailment |
def rpm_name(self, name, python_version=None, pkg_name=False):
"""Returns name of the package converted to (possibly) correct package
name according to Packaging Guidelines.
Args:
name: name to convert
python_version: python version for which to retrieve the name of
... | Returns name of the package converted to (possibly) correct package
name according to Packaging Guidelines.
Args:
name: name to convert
python_version: python version for which to retrieve the name of
the package
pkg_name: flag to perfor... | entailment |
def base_name(self, name):
"""Removes any python prefixes of suffixes from name if present."""
base_name = name.replace('.', "-")
# remove python prefix if present
found_prefix = self.reg_start.search(name)
if found_prefix:
base_name = found_prefix.group(2)
#... | Removes any python prefixes of suffixes from name if present. | entailment |
def merge(self, other):
"""Merges object with other NameVariants object, not set values
of self.variants are replace by values from other object.
"""
if not isinstance(other, NameVariants):
raise TypeError("NameVariants isinstance can be merge with"
... | Merges object with other NameVariants object, not set values
of self.variants are replace by values from other object. | entailment |
def rpm_name(self, name, python_version=None, pkg_name=False):
"""Checks if name converted using superclass rpm_name_method match name
of package in the query. Searches for correct name if it doesn't.
Args:
name: name to convert
python_version: python version for which to... | Checks if name converted using superclass rpm_name_method match name
of package in the query. Searches for correct name if it doesn't.
Args:
name: name to convert
python_version: python version for which to retrieve the name of
the package
... | entailment |
def merge_versions(self, data):
"""Merges python versions specified in command lines options with
extracted versions, checks if some of the versions is not > 2 if EPEL6
template will be used. attributes base_python_version and
python_versions contain values specified by command line opti... | Merges python versions specified in command lines options with
extracted versions, checks if some of the versions is not > 2 if EPEL6
template will be used. attributes base_python_version and
python_versions contain values specified by command line options or
default values, data.python_... | entailment |
def convert(self):
"""Returns RPM SPECFILE.
Returns:
rendered RPM SPECFILE.
"""
# move file into position
try:
local_file = self.getter.get()
except (exceptions.NoSuchPackageException, OSError) as e:
logger.error(
"Faile... | Returns RPM SPECFILE.
Returns:
rendered RPM SPECFILE. | entailment |
def getter(self):
"""Returns an instance of proper PackageGetter subclass. Always
returns the same instance.
Returns:
Instance of the proper PackageGetter subclass according to
provided argument.
Raises:
NoSuchSourceException if source to get the pack... | Returns an instance of proper PackageGetter subclass. Always
returns the same instance.
Returns:
Instance of the proper PackageGetter subclass according to
provided argument.
Raises:
NoSuchSourceException if source to get the package from is unknown
... | entailment |
def metadata_extractor(self):
"""Returns an instance of proper MetadataExtractor subclass.
Always returns the same instance.
Returns:
The proper MetadataExtractor subclass according to local file
suffix.
"""
if not hasattr(self, '_local_file'):
... | Returns an instance of proper MetadataExtractor subclass.
Always returns the same instance.
Returns:
The proper MetadataExtractor subclass according to local file
suffix. | entailment |
def client(self):
"""XMLRPC client for PyPI. Always returns the same instance.
If the package is provided as a path to compressed source file,
PyPI will not be used and the client will not be instantiated.
Returns:
XMLRPC client for PyPI or None.
"""
if self... | XMLRPC client for PyPI. Always returns the same instance.
If the package is provided as a path to compressed source file,
PyPI will not be used and the client will not be instantiated.
Returns:
XMLRPC client for PyPI or None. | entailment |
def memoize_by_args(func):
"""Memoizes return value of a func based on args."""
memory = {}
@functools.wraps(func)
def memoized(*args):
if args not in memory.keys():
value = func(*args)
memory[args] = value
return memory[args]
return memoized | Memoizes return value of a func based on args. | entailment |
def build_srpm(specfile, save_dir):
"""Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree
"""
logger.info('Starting rpmbuild to build: {0} SRPM.'.fo... | Builds a srpm from given specfile using rpmbuild.
Generated srpm is stored in directory specified by save_dir.
Args:
specfile: path to a specfile
save_dir: path to source and build tree | entailment |
def remove_major_minor_suffix(scripts):
"""Checks if executables already contain a "-MAJOR.MINOR" suffix. """
minor_major_regex = re.compile("-\d.?\d?$")
return [x for x in scripts if not minor_major_regex.search(x)] | Checks if executables already contain a "-MAJOR.MINOR" suffix. | entailment |
def runtime_to_build(runtime_deps):
"""Adds all runtime deps to build deps"""
build_deps = copy.deepcopy(runtime_deps)
for dep in build_deps:
if len(dep) > 0:
dep[0] = 'BuildRequires'
return build_deps | Adds all runtime deps to build deps | entailment |
def unique_deps(deps):
"""Remove duplicities from deps list of the lists"""
deps.sort()
return list(k for k, _ in itertools.groupby(deps)) | Remove duplicities from deps list of the lists | entailment |
def c_time_locale():
"""Context manager with C LC_TIME locale"""
old_time_locale = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, 'C')
yield
locale.setlocale(locale.LC_TIME, old_time_locale) | Context manager with C LC_TIME locale | entailment |
def rpm_eval(macro):
"""Get value of given macro using rpm tool"""
try:
value = subprocess.Popen(
['rpm', '--eval', macro],
stdout=subprocess.PIPE).communicate()[0].strip()
except OSError:
logger.error('Failed to get value of {0} rpm macro'.format(
macro),... | Get value of given macro using rpm tool | entailment |
def get_default_save_path():
"""Return default save path for the packages"""
macro = '%{_topdir}'
if rpm:
save_path = rpm.expandMacro(macro)
else:
save_path = rpm_eval(macro)
if not save_path:
logger.warn("rpm tools are missing, using default save path "
... | Return default save path for the packages | entailment |
def check_and_get_data(input_list,**pars):
"""Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list:... | Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list: list
list of full filenames | entailment |
def perform_align(input_list, **kwargs):
"""Main calling function.
Parameters
----------
input_list : list
List of one or more IPPSSOOTs (rootnames) to align.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories?
clobber : Boolean
... | Main calling function.
Parameters
----------
input_list : list
List of one or more IPPSSOOTs (rootnames) to align.
archive : Boolean
Retain copies of the downloaded files in the astroquery created sub-directories?
clobber : Boolean
Download and overwrite existing local cop... | entailment |
def match_relative_fit(imglist, reference_catalog):
"""Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Tabl... | Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Table of reference sources for this field
Returns
----... | entailment |
def match_default_fit(imglist, reference_catalog):
"""Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Table... | Perform cross-matching and final fit using 2dHistogram matching
Parameters
----------
imglist : list
List of input image `~tweakwcs.tpwcs.FITSWCS` objects with metadata and source catalogs
reference_catalog : Table
Astropy Table of reference sources for this field
Returns
----... | entailment |
def determine_fit_quality(imglist,filteredTable, print_fit_parameters=True):
"""Determine the quality of the fit to the data
Parameters
----------
imglist : list
output of interpret_fits. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid
input image... | Determine the quality of the fit to the data
Parameters
----------
imglist : list
output of interpret_fits. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid
input image. This list should have been updated, in-place, with the new RMS values;
s... | entailment |
def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for ca... | Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table :... | entailment |
def generate_source_catalogs(imglist, **pars):
"""Generates a dictionary of source catalogs keyed by image name.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for source detection.
Returns
-------
sourcecatalogdict : dictionary
... | Generates a dictionary of source catalogs keyed by image name.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for source detection.
Returns
-------
sourcecatalogdict : dictionary
a dictionary (keyed by image name) of two elemen... | entailment |
def update_image_wcs_info(tweakwcs_output):
"""Write newly computed WCS information to image headers and write headerlet files
Parameters
----------
tweakwcs_output : list
output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid... | Write newly computed WCS information to image headers and write headerlet files
Parameters
----------
tweakwcs_output : list
output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid
input image.
Returns
... | entailment |
def update_headerlet_phdu(tweakwcs_item, headerlet):
"""Update the primary header data unit keywords of a headerlet object in-place
Parameters
==========
tweakwc_item :
Basically the output from tweakwcs which contains the cross match and fit
information for every chip of every valid in... | Update the primary header data unit keywords of a headerlet object in-place
Parameters
==========
tweakwc_item :
Basically the output from tweakwcs which contains the cross match and fit
information for every chip of every valid input image.
headerlet :
object containing WCS in... | entailment |
def interpret_fit_rms(tweakwcs_output, reference_catalog):
"""Interpret the FIT information to convert RMS to physical units
Parameters
----------
tweakwcs_output : list
output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid
input ima... | Interpret the FIT information to convert RMS to physical units
Parameters
----------
tweakwcs_output : list
output of tweakwcs. Contains sourcelist tables, newly computed WCS info, etc. for every chip of every valid
input image. This list gets updated, in-place, with the new RMS values;
... | entailment |
def sky(input=None,outExt=None,configObj=None, group=None, editpars=False, **inputDict):
"""
Perform sky subtraction on input list of images
Parameters
----------
input : str or list of str
a python list of image filenames, or just a single filename
configObj : configObject
an i... | Perform sky subtraction on input list of images
Parameters
----------
input : str or list of str
a python list of image filenames, or just a single filename
configObj : configObject
an instance of configObject
inputDict : dict, optional
an optional list of parameters specifi... | entailment |
def _skyUserFromFile(imageObjList, skyFile, apply_sky=None):
"""
Apply sky value as read in from a user-supplied input file.
"""
skyKW="MDRIZSKY" #header keyword that contains the sky that's been subtracted
# create dict of fname=sky pairs
skyvals = {}
if apply_sky is None:
skyappl... | Apply sky value as read in from a user-supplied input file. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.