text stringlengths 81 112k |
|---|
Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world.
def _page(q, chunk=1000):
""" Quick utility to page a query, 1000 items at a time.
We need this so we don't OOM (out of memory) ourselves loading the world.
"""
offset = 0... |
This takes a *really* long time. Like, hours.
def upgrade():
""" This takes a *really* long time. Like, hours. """
config_paths = context.config.get_main_option('fedmsg_config_dir')
filenames = fedmsg.config._gather_configs_in(config_paths)
config = fedmsg.config.load_config(filenames=filenames)
... |
Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use.
def run(cmd):
""" Execute a shell command.
Both envoy and python-sh failed me...
commands, although deprecated, feels like the easiest tool to use.
"""
status... |
Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json
def read_datanommer_entries_from_filedump():
""" Read in all datanommer entries from a file created with:
$ datanommer-dump > myfile.json
"""
# TODO -- un-hardcode this filename when I need to run this n... |
Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
converted values to set on the model instance
:return: A two-tuple of m... |
Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instan... |
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio.storage.azure._AzureBaseSystem subclass):
The source storage system.
def copy(self, src, dst, other_system=None):
"""
Copy object of ... |
Get base keyword arguments for client for a
specific path.
Args:
path (str): Absolute path or URL.
Returns:
dict: client args
def get_client_kwargs(self, path):
"""
Get base keyword arguments for client for a
specific path.
Args:
... |
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
def _head(self, client_kwargs):
"""
Returns object or bucket HTTP header.
Args:
client_kwargs (dict): Client arguments.
... |
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
f... |
Lists objects.
args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object header dict,
directory bool
def _list_objects... |
Make a directory.
args:
client_kwargs (dict): Client arguments.
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# Directory
if 'd... |
Remove an object.
args:
client_kwargs (dict): Client arguments.
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_azure_exception():
# File
if 'file_nam... |
Update range with data
Args:
data (bytes): data.
def _update_range(self, data, **kwargs):
"""
Update range with data
Args:
data (bytes): data.
"""
self._client.update_range(data=data, **kwargs) |
Given a bodhi message, return the FAS username.
def handle_bodhi(msg):
""" Given a bodhi message, return the FAS username. """
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submi... |
Given a wiki message, return the FAS username.
def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise Valu... |
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is lo... |
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage).
def format_and_is_storage(path):
... |
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
def equivalent_to(std_function):
"""
Decorates... |
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
def _handle_oss_error():
"""
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _OssError as exception:
... |
Copy object of the same storage.
Args:
src (str): Path or URL.
dst (str): Path or URL.
other_system (pycosio._core.io_system.SystemBase subclass): Unused.
def copy(self, src, dst, other_system=None):
"""
Copy object of the same storage.
Args:
... |
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
def _get_client(self):
"""
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
"""
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss... |
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
def _get_roots(self):
"""
Return URL roots for this storage.
Returns:
tuple of str or re.Pattern: URL roots
"""
return (
# OSS Scheme
# - ... |
Get bucket object.
Returns:
oss2.Bucket
def _get_bucket(self, client_kwargs):
"""
Get bucket object.
Returns:
oss2.Bucket
"""
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_n... |
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
... |
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
dict: HTTP header.
def _head(self, client_kwargs):
"""
Returns object HTTP header.
Args:
client_kwargs (dict): Client arguments.
Returns:
... |
Make a directory.
args:
client_kwargs (dict): Client arguments.
def _make_dir(self, client_kwargs):
"""
Make a directory.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kw... |
Remove an object.
args:
client_kwargs (dict): Client arguments.
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_oss_error():
bucket = self._get_bucket(client_kwar... |
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
... |
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_oss_error():
respons... |
Lists objects.
args:
client_kwargs (dict): Client arguments.
path (str): Path relative to current locator.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
generator of tuple: object name str, object ... |
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
def _read_range(self, start, end=0):
"""
Read a range of bytes in s... |
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
def _readall(self):
"""
Read and return all the bytes from the stream until EOF.
Returns:
bytes: Object content
"""
with _handle_oss_error():
ret... |
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
def _flush(self, buffer):
"""
Flush the write buffers of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
"""
with _handle_oss_er... |
Flush the write buffers of the stream.
def _flush(self):
"""
Flush the write buffers of the stream.
"""
# Initialize multipart upload
if self._upload_id is None:
with _handle_oss_error():
self._upload_id = self._bucket.init_multipart_upload(
... |
Close the object in write mode.
def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
parts = [_PartInfo(part_number=future['part_number'],
etag=future['response'].result().etag)
for future i... |
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file... |
Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines
def _text_io_wrapper(stream, mode, encoding, errors, newline... |
Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
category: {{ random_model('Category') }}
... |
Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
tags: {{ random_models('Tag') }}
Will render... |
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries return... |
"Hash" all keys in a timerange to the same value.
def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key |
Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
parameters:
- an :class:`Identifier`
- the model inst... |
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifi... |
Load all fixtures from :attr:`fixtures_dir`
def _load_data(self):
"""
Load all fixtures from :attr:`fixtures_dir`
"""
filenames = []
model_identifiers = defaultdict(list)
# attempt to load fixture files from given directories (first pass)
# for each valid model ... |
Load fixtures from the given filename
def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
"""
Load fixtures from the given filename
"""
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
... |
Convert and normalize identifier strings to Identifiers, as well as determine
class relationships.
def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tupl... |
Make sure the jinja environment is minimally configured.
def _ensure_env(self, env: Union[jinja2.Environment, None]):
"""
Make sure the jinja environment is minimally configured.
"""
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = j... |
A "stripped" jinja environment.
def _preloading_env(self):
"""
A "stripped" jinja environment.
"""
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
fina... |
Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client ... |
Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
... |
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
... |
sadness because argparse doesn't quite do what we want.
def manual_argument_parsing(argv):
"""sadness because argparse doesn't quite do what we want."""
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dash... |
Use this to make a console_script entry point for your application
which applies patches.
:param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,)
:param original_entry_point: Such as 'pip'
def make_entry_point(patches, original_entry_point):
"""Use this to make a console_script entry p... |
Storage client
Returns:
client
def client(self):
"""
Storage client
Returns:
client
"""
if self._client is None:
self._client = self._get_client()
return self._client |
Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
... |
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
def getctime(self, p... |
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
def getmtime(s... |
Get time from header
Args:
header (dict): Object header.
keys (tuple of str): Header keys.
name (str): Method name.
Returns:
float: The number of seconds since the epoch
def _get_time(header, keys, name):
"""
Get time from header
... |
Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes.
def getsize(self, path=None, client_kwargs=None, header=None):
"""
... |
Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes.
def _getsize_from_header(self, header):
"""
Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size... |
Return True if path is an existing directory.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
virtual_dir (bool): If True, checks if directory exists virtually
if an object path if not exists as a specific object.
assume_exi... |
Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
... |
Returns object HTTP header.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
dict: HTTP header.
def head(self, path=None, client_kwargs=None, header=None):
"""
Returns object H... |
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path.
def relpath(self, path):
"""
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relativ... |
Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator.
def is_loca... |
Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.
Returns:
tuple of str: locator, path.
def split_locator(self, path):
"""
Split the path into a pair (locator, path).
args:
path (str): Absolute path or URL.... |
Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
def make_dir(self, path, relative=False):
"""
Make a directory.
Args:
path (str): Path or URL.
relative (bool): Path is relative to curre... |
Remove an object.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
def remove(self, path, relative=False):
"""
Remove an object.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current... |
Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path
def ensure_dir_path(self, path, relative=False):
"""
... |
List objects.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
first_level (bool): It True, returns only first level objects.
Else, returns full tree.
max_request_entries (int): If specified, maximum entries return... |
Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object
def stat(self, path=None, client_kwargs=None, header=None):
"""
... |
Initialize a connection. Create tables if requested.
def init(uri=None, alembic_ini=None, engine=None, create=False):
""" Initialize a connection. Create tables if requested."""
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
... |
Take a dict-like fedmsg envelope and store the headers and message
in the table.
def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestam... |
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
def get_or_create(cls, name):
"""
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
"""
obj = cls.query.filter_by(name=name).... |
Flexible query interface for messages.
Arguments are filters. start and end should be :mod:`datetime` objs.
Other filters should be lists of strings. They are applied in a
conjunctive-normal-form (CNF) kind of way
for example, the following::
users = ['ralph', 'lmacken']
... |
Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
path (path-like object): Path or URL.
Returns:
bool: True if directory exists.
def isdir(path):
"""
Return True if path is an existing directory.
Equivalent to "os.path.isdir".
Args:
... |
Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a di... |
Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory.
def samefile(path1, path2):
"""
... |
Split the path into a pair (drive, tail) where drive is either a
mount point or the empty string. On systems which do not use drive
specifications, drive will always be the empty string.
In all cases, drive + tail will be the same as path.
Equivalent to "os.path.splitdrive".
Args:
path (p... |
Handles pycosio exceptions and raise standard OS exceptions.
def handle_os_exceptions():
"""
Handles pycosio exceptions and raise standard OS exceptions.
"""
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()... |
Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names.
def listdir(path='.'):
"""
Return a list containing the names of the entries in the d... |
Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment
(not just the rightmost) will be created if it does not exist.
Equivalent to "os.makedirs".
Args:
name (path-like object): Path or URL.
mode (int): The mode param... |
Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage o... |
Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
def remove(path, dir_fd=None):
""... |
Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects.
def rmdir(path, dir_fd=None):
"""
Remove a... |
Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path... |
scandir generator
Args:
is_bytes (bool): True if DirEntry must handle path as bytes.
scandir_path (str): Path.
system (pycosio._core.io_system.SystemBase subclass):
Storage system.
Yields:
DirEntry: Directory entries
def _scandir_generator(is_bytes, scandir_path, s... |
The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name.
def name(self):
"""
The entry’s base filename, relative to the scandir() path argument.
Returns:
str: name.
"""
name = self._name.rstrip('/')
if self... |
The entry’s full path name:
equivalent to os.path.join(scandir_path, entry.name)
where scandir_path is the scandir() path argument.
The path is only absolute if the scandir() path argument was absolute.
Returns:
str: name.
def path(self):
"""
The entry’s fu... |
Return True if this entry is a directory or a symbolic link pointing to
a directory; return False if the entry is or points to any other kind
of file, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlin... |
Return True if this entry is a file or a symbolic link pointing to a
file; return False if the entry is or points to a directory or other
non-file entry, or if it doesn’t exist anymore.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow sym... |
Return a stat_result object for this entry.
The result is cached on the os.DirEntry object.
Args:
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Returns:
os.stat_result: Stat result object
def stat(self, follow_symlink... |
Flush the write buffers of the stream if applicable and
close the object.
def close(self):
"""
Flush the write buffers of the stream if applicable and
close the object.
"""
if self._writable and not self._closed:
self._closed = True
with self._see... |
Flush the write buffers of the stream if applicable.
def flush(self):
"""
Flush the write buffers of the stream if applicable.
"""
if self._writable:
with self._seek_lock:
self._flush_raw_or_buffered()
# Clear the buffer
self.... |
Flush using raw of buffered methods.
def _flush_raw_or_buffered(self):
"""
Flush using raw of buffered methods.
"""
# Flush only if bytes written
# This avoid no required process/thread
# creation and network call.
# This step is performed by raw stream.
... |
Return bytes from the stream without advancing the position.
Args:
size (int): Number of bytes to read. -1 to read the full
stream.
Returns:
bytes: bytes read
def peek(self, size=-1):
"""
Return bytes from the stream without advancing the positi... |
Preload data for reading
def _preload_range(self):
"""Preload data for reading"""
queue = self._read_queue
size = self._buffer_size
start = self._seek
end = int(start + size * self._max_buffers)
workers_submit = self._workers.submit
indexes = tuple(range(start, e... |
Read and return up to size bytes,
with at most one call to the underlying raw stream’s.
Use at most one call to the underlying raw stream’s read method.
Args:
size (int): Number of bytes to read. -1 to read the
stream until end.
Returns:
bytes: ... |
Read bytes into a pre-allocated, writable bytes-like object b,
and return the number of bytes read.
Args:
b (bytes-like object): buffer.
Returns:
int: number of bytes read
def readinto(self, b):
"""
Read bytes into a pre-allocated, writable bytes-like o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.