_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q224100 | IndentFormatter.format | train | def format(self, record, *args, **kwargs):
"""
Format a message in the log
Act like the normal format, but indent anything that is a
newline within the message.
"""
return logging.Formatter.format(
self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8) | python | {
"resource": ""
} |
q224101 | _segmentation_guts | train | def _segmentation_guts(root, file_paths, max_partition_size):
"""Segment a series of file paths into TarPartition values
These TarPartitions are disjoint and roughly below the prescribed
size.
"""
# Canonicalize root to include the trailing slash, since root is
# intended to be a directory anyw... | python | {
"resource": ""
} |
q224102 | TarPartition.tarfile_extract | train | def tarfile_extract(fileobj, dest_path):
"""Extract a tarfile described by a file object to a specified path.
Args:
fileobj (file): File object wrapping the target tarfile.
dest_path (str): Path to extract the contents of the tarfile to.
"""
# Though this method ... | python | {
"resource": ""
} |
q224103 | Backup.backup_list | train | def backup_list(self, query, detail):
"""
Lists base backups and basic information about them
"""
import csv
from wal_e.storage.base import BackupInfo
bl = self._backup_list(detail)
# If there is no query, return an exhaustive list, otherwise
# find a ba... | python | {
"resource": ""
} |
q224104 | Backup.database_backup | train | def database_backup(self, data_directory, *args, **kwargs):
"""Uploads a PostgreSQL file cluster to S3 or Windows Azure Blob
Service
Mechanism: just wraps _upload_pg_cluster_dir with
start/stop backup actions with exception handling.
In particular there is a 'finally' block to ... | python | {
"resource": ""
} |
q224105 | Backup.wal_archive | train | def wal_archive(self, wal_path, concurrency=1):
"""
Uploads a WAL file to S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
archive_command feature.
"""
# Upload the segment expressly indicated. It's special
# relativ... | python | {
"resource": ""
} |
q224106 | Backup.wal_restore | train | def wal_restore(self, wal_name, wal_destination, prefetch_max):
"""
Downloads a WAL file from S3 or Windows Azure Blob Service
This code is intended to typically be called from Postgres's
restore_command feature.
NB: Postgres doesn't guarantee that wal_name ==
basename(... | python | {
"resource": ""
} |
q224107 | Backup._upload_pg_cluster_dir | train | def _upload_pg_cluster_dir(self, start_backup_info, pg_cluster_dir,
version, pool_size, rate_limit=None):
"""
Upload to url_prefix from pg_cluster_dir
This function ignores the directory pg_xlog, which contains WAL
files and are not generally part of a bas... | python | {
"resource": ""
} |
q224108 | Backup._exception_gather_guard | train | def _exception_gather_guard(self, fn):
"""
A higher order function to trap UserExceptions and then log them.
This is to present nicer output to the user when failures are
occuring in another thread of execution that may not end up at
the catch-all try/except in main().
"... | python | {
"resource": ""
} |
q224109 | Dirs.create | train | def create(self, segment):
"""A best-effort attempt to create directories.
Warnings are issued to the user if those directories could not
created or if they don't exist.
The caller should only call this function if the user
requested prefetching (i.e. concurrency) to avoid spur... | python | {
"resource": ""
} |
q224110 | PidFile.acquire | train | def acquire(self):
"""Acquire the pidfile.
Create the pidfile, lock it, write the pid into it
and register the release with atexit.
:return: None
:raise: SystemExit
"""
try:
pidfile = open(self._pidfile, "a")
except IOError as err:
... | python | {
"resource": ""
} |
q224111 | PidFile.release | train | def release(self):
"""Release the pidfile.
Close and delete the Pidfile.
:return: None
"""
try:
self.pidfile.close()
os.remove(self._pidfile)
except OSError as err:
if err.errno != 2:
raise | python | {
"resource": ""
} |
q224112 | _configure_buffer_sizes | train | def _configure_buffer_sizes():
"""Set up module globals controlling buffer sizes"""
global PIPE_BUF_BYTES
global OS_PIPE_SZ
PIPE_BUF_BYTES = 65536
OS_PIPE_SZ = None
# Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism,
# but a good one that can drastically reduce the numbe... | python | {
"resource": ""
} |
q224113 | set_buf_size | train | def set_buf_size(fd):
"""Set up os pipe buffer size, if applicable"""
if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'):
fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ) | python | {
"resource": ""
} |
q224114 | WalSegment.mark_done | train | def mark_done(self):
"""Mark the archive status of this segment as 'done'.
This is most useful when performing out-of-band parallel
uploads of segments, so that Postgres doesn't try to go and
upload them again.
This amounts to messing with an internal bookkeeping mechanism
... | python | {
"resource": ""
} |
q224115 | WalTransferGroup.join | train | def join(self):
"""Wait for transfer to exit, raising errors as necessary."""
self.closed = True
while self.expect > 0:
val = self.wait_change.get()
self.expect -= 1
if val is not None:
# Wait a while for all running greenlets to exit, and
... | python | {
"resource": ""
} |
q224116 | WalTransferGroup.start | train | def start(self, segment):
"""Begin transfer for an indicated wal segment."""
if self.closed:
raise UserCritical(msg='attempt to transfer wal after closing',
hint='report a bug')
g = gevent.Greenlet(self.transferer, segment)
g.link(self._comple... | python | {
"resource": ""
} |
q224117 | WalTransferGroup._complete_execution | train | def _complete_execution(self, g):
"""Forward any raised exceptions across a channel."""
# Triggered via completion callback.
#
# Runs in its own greenlet, so take care to forward the
# exception, if any, to fail the entire transfer in event of
# trouble.
assert g... | python | {
"resource": ""
} |
q224118 | pipe | train | def pipe(*args):
"""
Takes as parameters several dicts, each with the same
parameters passed to popen.
Runs the various processes in a pipeline, connecting
the stdout of every process except the last with the
stdin of the next process.
Adapted from http://www.enricozini.org/2009/debian/pyt... | python | {
"resource": ""
} |
q224119 | pipe_wait | train | def pipe_wait(popens):
"""
Given an array of Popen objects returned by the
pipe method, wait for all processes to terminate
and return the array with their return values.
Taken from http://www.enricozini.org/2009/debian/python-pipes/
"""
# Avoid mutating the passed copy
popens = copy.c... | python | {
"resource": ""
} |
q224120 | CallingInfo.connect | train | def connect(self, creds):
"""Return an azure BlockBlobService instance.
"""
return BlockBlobService(account_name=creds.account_name,
account_key=creds.account_key,
sas_token=creds.access_token,
protocol='https') | python | {
"resource": ""
} |
q224121 | do_lzop_get | train | def do_lzop_get(creds, url, path, decrypt, do_retry):
"""
Get and decompress a URL
This streams the content directly to lzop; the compressed version
is never stored on disk.
"""
assert url.endswith('.lzo'), 'Expect an lzop-compressed file'
with files.DeleteOnError(path) as decomp_out:
... | python | {
"resource": ""
} |
q224122 | psql_csv_run | train | def psql_csv_run(sql_command, error_handler=None):
"""
Runs psql and returns a CSVReader object from the query
This CSVReader includes header names as the first record in all
situations. The output is fully buffered into Python.
"""
csv_query = ('COPY ({query}) TO STDOUT WITH CSV HEADER;'
... | python | {
"resource": ""
} |
q224123 | PgBackupStatements._wal_name | train | def _wal_name(cls):
"""
Sets and returns _WAL_NAME to 'wal' or 'xlog' depending on
version of postgres we are working with.
It is used for handling xlog -> wal rename in postgres v10
"""
if cls._WAL_NAME is None:
version = cls._dict_transform(psql_csv_run(
... | python | {
"resource": ""
} |
q224124 | PgBackupStatements.run_start_backup | train | def run_start_backup(cls):
"""
Connects to a server and attempts to start a hot backup
Yields the WAL information in a dictionary for bookkeeping and
recording.
"""
def handler(popen):
assert popen.returncode != 0
raise UserException('Could not s... | python | {
"resource": ""
} |
q224125 | PgBackupStatements.run_stop_backup | train | def run_stop_backup(cls):
"""
Stop a hot backup, if it was running, or error
Return the last WAL file name and position that is required to
gain consistency on the captured heap.
"""
def handler(popen):
assert popen.returncode != 0
raise UserExce... | python | {
"resource": ""
} |
q224126 | _is_ipv4_like | train | def _is_ipv4_like(s):
"""Find if a string superficially looks like an IPv4 address.
AWS documentation plays it fast and loose with this; in other
regions, it seems like even non-valid IPv4 addresses (in
particular, ones that possess decimal numbers out of range for
IPv4) are rejected.
"""
p... | python | {
"resource": ""
} |
q224127 | _is_mostly_subdomain_compatible | train | def _is_mostly_subdomain_compatible(bucket_name):
"""Returns True if SubdomainCallingFormat can be used...mostly
This checks to make sure that putting aside certificate validation
issues that a bucket_name is able to use the
SubdomainCallingFormat.
"""
return (bucket_name.lower() == bucket_name... | python | {
"resource": ""
} |
q224128 | _connect_secureish | train | def _connect_secureish(*args, **kwargs):
"""Connect using the safest available options.
This turns on encryption (works in all supported boto versions)
and certificate validation (in the subset of supported boto
versions that can handle certificate validation, namely, those
after 2.6.0).
Versi... | python | {
"resource": ""
} |
q224129 | from_store_name | train | def from_store_name(bucket_name, region=None):
"""Construct a CallingInfo value from a bucket name.
This is useful to encapsulate the ugliness of setting up S3
connections, especially with regions and TLS certificates are
involved.
"""
# Late-bind `region` for the sake of tests that inject the
... | python | {
"resource": ""
} |
q224130 | CallingInfo.connect | train | def connect(self, creds):
"""Return a boto S3Connection set up with great care.
This includes TLS settings, calling format selection, and
region detection.
The credentials are applied by the caller because in many
cases (instance-profile IAM) it is possible for those
cr... | python | {
"resource": ""
} |
q224131 | remove_empty_dirs | train | def remove_empty_dirs(path):
""" removes empty dirs under a given path """
for root, dirs, files in os.walk(path):
for d in dirs:
dir_path = os.path.join(root, d)
if not os.listdir(dir_path):
os.rmdir(dir_path) | python | {
"resource": ""
} |
q224132 | ensure_dir_exists | train | def ensure_dir_exists(path):
""" create a directory if required """
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path) | python | {
"resource": ""
} |
q224133 | external_program_check | train | def external_program_check(
to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])):
"""
Validates the existence and basic working-ness of other programs
Implemented because it is easy to get confusing error output when
one does not install a dependency because of the fork-worker model
that is both n... | python | {
"resource": ""
} |
q224134 | parse_boolean_envvar | train | def parse_boolean_envvar(val):
"""Parse a boolean environment variable."""
if not val or val.lower() in {'false', '0'}:
return False
elif val.lower() in {'true', '1'}:
return True
else:
raise ValueError('Invalid boolean environment variable: %s' % val) | python | {
"resource": ""
} |
q224135 | _config_hint_generate | train | def _config_hint_generate(optname, both_env_and_param):
"""Generate HINT language for missing configuration"""
env = optname.replace('-', '_').upper()
if both_env_and_param:
option = '--' + optname.lower()
return ('Pass "{0}" or set the environment variable "{1}".'
.format(o... | python | {
"resource": ""
} |
q224136 | render_subcommand | train | def render_subcommand(args):
"""Render a subcommand for human-centric viewing"""
if args.subcommand == 'delete':
return 'delete ' + args.delete_subcommand
if args.subcommand in ('wal-prefetch', 'wal-push', 'wal-fetch'):
return None
return args.subcommand | python | {
"resource": ""
} |
q224137 | do_lzop_put | train | def do_lzop_put(creds, url, local_path, gpg_key):
"""
Compress and upload a given local path.
:type url: string
:param url: A (s3|wabs)://bucket/key style URL that is the destination
:type local_path: string
:param local_path: a path to a file to be compressed
"""
assert url.endswith(... | python | {
"resource": ""
} |
q224138 | do_lzop_get | train | def do_lzop_get(creds, url, path, decrypt, do_retry=True):
"""
Get and decompress an S3 or WABS URL
This streams the content directly to lzop; the compressed version
is never stored on disk.
"""
blobstore = get_blobstore(storage.StorageLayout(url))
return blobstore.do_lzop_get(creds, url, ... | python | {
"resource": ""
} |
q224139 | _BackupList.find_all | train | def find_all(self, query):
"""A procedure to assist in finding or detailing specific backups
Currently supports:
* a backup name (base_number_number)
* the psuedo-name LATEST, which finds the backup with the most
recent modification date
"""
match = re.matc... | python | {
"resource": ""
} |
q224140 | _DeleteFromContext._delete_wals_before | train | def _delete_wals_before(self, segment_info):
"""
Delete all WAL files before segment_info.
Doesn't delete any base-backup data.
"""
wal_key_depth = self.layout.wal_directory().count('/') + 1
for key in self._backup_list(prefix=self.layout.wal_directory()):
ke... | python | {
"resource": ""
} |
q224141 | _DeleteFromContext.delete_everything | train | def delete_everything(self):
"""Delete everything in a storage layout
Named provocatively for a reason: can (and in fact intended
to) cause irrecoverable loss of data. This can be used to:
* Completely obliterate data from old WAL-E versions
(i.e. layout.VERSION is an obsole... | python | {
"resource": ""
} |
q224142 | _DeleteFromContext.delete_before | train | def delete_before(self, segment_info):
"""
Delete all base backups and WAL before a given segment
This is the most commonly-used deletion operator; to delete
old backups and WAL.
"""
# This will delete all base backup data before segment_info.
self._delete_base... | python | {
"resource": ""
} |
q224143 | _DeleteFromContext.delete_with_retention | train | def delete_with_retention(self, num_to_retain):
"""
Retain the num_to_retain most recent backups and delete all data
before them.
"""
base_backup_sentinel_depth = self.layout.basebackups().count('/') + 1
# Sweep over base backup files, collecting sentinel files from
... | python | {
"resource": ""
} |
q224144 | connect | train | def connect(creds):
"""
Construct a connection value from a container
"""
return swiftclient.Connection(
authurl=creds.authurl,
user=creds.user,
key=creds.password,
auth_version=creds.auth_version,
tenant_name=creds.tenant_name,
os_options={
"r... | python | {
"resource": ""
} |
q224145 | connect | train | def connect(creds, max_retries=100):
"""Construct a connection value to Google Storage API
The credentials are retrieved using get_credentials that checks
the environment for the correct values.
"""
credentials, project = google.auth.default()
return RetryClient(max_retries=max_retries, projec... | python | {
"resource": ""
} |
q224146 | retry | train | def retry(exception_processor=generic_exception_processor, max_retries=100):
"""
Generic retry decorator
Tries to call the decorated function. Should no exception be
raised, the value is simply returned, otherwise, call an
exception_processor function with the exception (type, value,
traceback... | python | {
"resource": ""
} |
q224147 | TarUploadPool._start | train | def _start(self, tpart):
"""Start upload and accout for resource consumption."""
g = gevent.Greenlet(self.uploader, tpart)
g.link(self._finish)
# Account for concurrency_burden before starting the greenlet
# to avoid racing against .join.
self.concurrency_burden += 1
... | python | {
"resource": ""
} |
q224148 | TarUploadPool._finish | train | def _finish(self, g):
"""Called on completion of an upload greenlet.
Takes care to forward Exceptions or, if there is no error, the
finished TarPartition value across a channel.
"""
assert g.ready()
if g.successful():
finished_tpart = g.get()
sel... | python | {
"resource": ""
} |
q224149 | TarUploadPool._wait | train | def _wait(self):
"""Block until an upload finishes
Raise an exception if that tar volume failed with an error.
"""
val = self.wait_change.get()
if isinstance(val, Exception):
# Don't other uncharging, because execution is going to stop
raise val
... | python | {
"resource": ""
} |
q224150 | TarUploadPool.put | train | def put(self, tpart):
"""Upload a tar volume
Blocks if there is too much work outstanding already, and
raise errors of previously submitted greenlets that die
unexpectedly.
"""
if self.closed:
raise UserCritical(msg='attempt to upload tar after closing',
... | python | {
"resource": ""
} |
q224151 | close_filenos | train | def close_filenos(preserve):
""" Close unprotected file descriptors
Close all open file descriptors that are not in preserve.
If ulimit -nofile is "unlimited", all is defined filenos <= 4096,
else all is <= the output of resource.getrlimit().
:param preserve: set with protected files
:type pr... | python | {
"resource": ""
} |
q224152 | default_signal_map | train | def default_signal_map():
""" Create the default signal map for this system.
:return: dict
"""
name_map = {
'SIGTSTP': None,
'SIGTTIN': None,
'SIGTTOU': None,
'SIGTERM': 'terminate'}
signal_map = {}
for name, target in list(name_map.items()):
if hasattr(s... | python | {
"resource": ""
} |
q224153 | parent_is_inet | train | def parent_is_inet():
""" Check if parent is inet
Check if our parent seems ot be a superserver, aka inetd/xinetd.
This is done by checking if sys.__stdin__ is a network socket.
:return: bool
"""
result = False
sock = socket.fromfd(
sys.__stdin__.fileno(),
socket.AF_INET,
... | python | {
"resource": ""
} |
q224154 | redirect_stream | train | def redirect_stream(system, target):
""" Redirect Unix streams
If None, redirect Stream to /dev/null, else redirect to target.
:param system: ether sys.stdin, sys.stdout, or sys.stderr
:type system: file object
:param target: File like object, or None
:type target: None, File Object
:ret... | python | {
"resource": ""
} |
q224155 | DaemonContext._get_signal_handler | train | def _get_signal_handler(self, handler):
""" get the callback function for handler
If the handler is None, returns signal.SIG_IGN.
If the handler is a string, return the matching attribute of this
instance if possible.
Else return the handler itself.
:param handler:
... | python | {
"resource": ""
} |
q224156 | DaemonContext._files_preserve | train | def _files_preserve(self):
""" create a set of protected files
create a set of files, based on self.files_preserve and
self.stdin, self,stdout and self.stderr, that should not get
closed while daemonizing.
:return: set
"""
result = set()
files = [] if no... | python | {
"resource": ""
} |
q224157 | DaemonContext.working_directory | train | def working_directory(self):
""" The working_directory property
:return: str
"""
if self.chroot_directory and not \
self._working_directory.startswith(self.chroot_directory):
return self.chroot_directory + self._working_directory
else:
ret... | python | {
"resource": ""
} |
q224158 | register | train | def register(
model,
app=None,
manager_name="history",
records_class=None,
table_name=None,
**records_config
):
"""
Create historical model for `model` and attach history manager to `model`.
Keyword arguments:
app -- App to install historical model into (defaults to model.__modu... | python | {
"resource": ""
} |
q224159 | SimpleHistoryAdmin.get_urls | train | def get_urls(self):
"""Returns the additional urls used by the Reversion admin."""
urls = super(SimpleHistoryAdmin, self).get_urls()
admin_site = self.admin_site
opts = self.model._meta
info = opts.app_label, opts.model_name
history_urls = [
url(
... | python | {
"resource": ""
} |
q224160 | SimpleHistoryAdmin.save_model | train | def save_model(self, request, obj, form, change):
"""Set special model attribute to user for reference after save"""
obj._history_user = request.user
super(SimpleHistoryAdmin, self).save_model(request, obj, form, change) | python | {
"resource": ""
} |
q224161 | Command._bulk_history_create | train | def _bulk_history_create(self, model, batch_size):
"""Save a copy of all instances to the historical model.
:param model: Model you want to bulk create
:param batch_size: number of models to create at once.
:return:
"""
instances = []
history = utils.get_history... | python | {
"resource": ""
} |
q224162 | transform_field | train | def transform_field(field):
"""Customize field appropriately for use in historical model"""
field.name = field.attname
if isinstance(field, models.AutoField):
field.__class__ = models.IntegerField
elif isinstance(field, models.FileField):
# Don't copy file, just path.
field.__cl... | python | {
"resource": ""
} |
q224163 | HistoricalRecords.create_history_model | train | def create_history_model(self, model, inherited):
"""
Creates a historical model to associate with the model provided.
"""
attrs = {
"__module__": self.module,
"_history_excluded_fields": self.excluded_fields,
}
app_module = "%s.models" % model._m... | python | {
"resource": ""
} |
q224164 | HistoricalRecords.copy_fields | train | def copy_fields(self, model):
"""
Creates copies of the model's original fields, returning
a dictionary mapping field name to copied field object.
"""
fields = {}
for field in self.fields_included(model):
field = copy.copy(field)
field.remote_field... | python | {
"resource": ""
} |
q224165 | HistoricalRecords.get_extra_fields | train | def get_extra_fields(self, model, fields):
"""Return dict of extra fields added to the historical record model"""
def revert_url(self):
"""URL for this change in the default admin site."""
opts = model._meta
app_label, model_name = opts.app_label, opts.model_name
... | python | {
"resource": ""
} |
q224166 | HistoricalRecords.get_meta_options | train | def get_meta_options(self, model):
"""
Returns a dictionary of fields that will be added to
the Meta inner class of the historical record model.
"""
meta_fields = {
"ordering": ("-history_date", "-history_id"),
"get_latest_by": "history_date",
}
... | python | {
"resource": ""
} |
q224167 | HistoricalRecords.get_history_user | train | def get_history_user(self, instance):
"""Get the modifying user from instance or middleware."""
try:
return instance._history_user
except AttributeError:
request = None
try:
if self.thread.request.user.is_authenticated:
requ... | python | {
"resource": ""
} |
q224168 | HistoryManager.most_recent | train | def most_recent(self):
"""
Returns the most recent copy of the instance available in the history.
"""
if not self.instance:
raise TypeError(
"Can't use most_recent() without a {} instance.".format(
self.model._meta.object_name
... | python | {
"resource": ""
} |
q224169 | HistoryManager.as_of | train | def as_of(self, date):
"""Get a snapshot as of a specific date.
Returns an instance, or an iterable of the instances, of the
original model with all the attributes set according to what
was present on the object on the date provided.
"""
if not self.instance:
... | python | {
"resource": ""
} |
q224170 | HistoryManager.bulk_history_create | train | def bulk_history_create(self, objs, batch_size=None):
"""Bulk create the history for the objects specified by objs"""
historical_instances = [
self.model(
history_date=getattr(instance, "_history_date", now()),
history_user=getattr(instance, "_history_user", ... | python | {
"resource": ""
} |
q224171 | get_history_manager_for_model | train | def get_history_manager_for_model(model):
"""Return the history manager for a given app model."""
try:
manager_name = model._meta.simple_history_manager_attribute
except AttributeError:
raise NotHistoricalModelError(
"Cannot find a historical model for {model}.".format(model=mode... | python | {
"resource": ""
} |
q224172 | pop_parameter | train | def pop_parameter(key):
'''Remove and get parameter by key.
Args:
key(str): Key of parameter.
Returns: ~nnabla.Variable
Parameter if key found, otherwise None.
'''
names = key.split('/')
if len(names) > 1:
with parameter_scope(names[0]):
return pop_paramete... | python | {
"resource": ""
} |
q224173 | get_parameter_or_create | train | def get_parameter_or_create(name, shape=None, initializer=None, need_grad=True,
as_need_grad=None):
"""
Returns an existing parameter variable with the provided name.
If a variable with the provided name does not exist,
a new variable with the provided name is returned.
... | python | {
"resource": ""
} |
q224174 | get_parameters | train | def get_parameters(params=None, path='', grad_only=True):
"""Get parameter Variables under the current parameter scope.
Args:
params (dict): Internal use. User doesn't set it manually.
path (str): Internal use. User doesn't set it manually.
grad_only (bool): Retrieve all parameters und... | python | {
"resource": ""
} |
q224175 | import_extension_module | train | def import_extension_module(ext_name):
'''
Import an extension module by name.
The extension modules are installed under the `nnabla_ext` package as
namespace packages. All extension modules provide a unified set of APIs.
Args:
ext_name(str): Extension name. e.g. 'cpu', 'cuda', 'cudnn' etc... | python | {
"resource": ""
} |
q224176 | list_extensions | train | def list_extensions():
'''
List up available extensions.
Note:
It may not work on some platforms/environments since it depends
on the directory structure of the namespace packages.
Returns: list of str
Names of available extensions.
'''
import nnabla_ext.cpu
from o... | python | {
"resource": ""
} |
q224177 | imsave | train | def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True):
"""
Save image by pillow module.
Currently, pillow supports only uint8 to save.
Args:
path (str): output filename
img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel)... | python | {
"resource": ""
} |
q224178 | NnpLoader.get_network | train | def get_network(self, name, batch_size=None, callback=None):
'''Create a variable graph given network by name
Returns: NnpNetwork
'''
network_proto = nnabla_pb2.Network()
network_proto.CopyFrom(self.network_dict[name])
return NnpNetwork(network_proto, self._params, bat... | python | {
"resource": ""
} |
q224179 | set_function_name | train | def set_function_name(func, node_name, base_name, func_counter):
"""Set a sufficient name for the function"""
# NNabla requires each function to have a unique name
# so we generate one here.
func.name, count = generate_function_name(func.type, base_name, node_name,
... | python | {
"resource": ""
} |
q224180 | generate_transpose | train | def generate_transpose(node_name, in_name, out_name, axes, base_name, func_counter):
"""Generate a Transpose operator to transpose the specified buffer.
"""
trans = nnabla_pb2.Function()
trans.type = "Transpose"
set_function_name(trans, node_name, base_name, func_counter)
trans.input.extend([in_... | python | {
"resource": ""
} |
q224181 | generate_broadcast_to | train | def generate_broadcast_to(node_name, x, y, out_name, axis, base_name, func_counter):
"""Generate a BroadcastTo operator to brodcast specified buffer"""
bt = nnabla_pb2.Function()
bt.type = "BroadcastTo"
set_function_name(bt, node_name, base_name, func_counter)
bt.input.extend([x, y])
bt.output.e... | python | {
"resource": ""
} |
q224182 | convert_parameter_shape | train | def convert_parameter_shape(pb):
"""Convert the shape of some parameters so they fit NNabla's requirements.
We do this as a post conversion because in the future we may be able to
delete the whole conversion if NNabla's code gets changed"""
if len(pb.network) != 1:
raise ValueError(
... | python | {
"resource": ""
} |
q224183 | add_tensor_as_parameter | train | def add_tensor_as_parameter(pb, tensor):
"""Add given tensor as a parameter"""
p = pb.parameter.add()
p.variable_name = tensor.name
p.shape.dim.extend(tensor.dims)
if tensor.data_type == TensorProto.FLOAT:
# convert raw bytestream to floating points
if tensor.raw_data:
p.... | python | {
"resource": ""
} |
q224184 | OnnxImporter.BroadcastOperator | train | def BroadcastOperator(self, func_name, func_list, n):
"""Converts a broadcasting operator to a composite with BroadcastTo"""
broadcasting = False
broadcast_axis = -1
func = self.generate_default_function(func_name, n)
for attr in n.attribute:
if attr.name == "axis":
... | python | {
"resource": ""
} |
q224185 | imread | train | def imread(path, grayscale=False, size=None, interpolate="bilinear",
channel_first=False, as_uint16=False, num_channels=-1):
"""
Read image by pypng module.
Args:
path (str or 'file object'): File path or object to read.
grayscale (bool):
size (tupple of int):
... | python | {
"resource": ""
} |
q224186 | imsave | train | def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True):
"""
Save image by pypng module.
Args:
path (str): output filename
img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default.
channel_first:
This... | python | {
"resource": ""
} |
q224187 | context_scope | train | def context_scope(ctx):
"""
Context as Python context.
.. code-block:: python
import nnabla as nn
import nnabla.functions as F
x = nn.Variable([2, 3 ,4])
ctx = nnabla_ext.cuda.context('0')
with context_scope(ctx):
# Inside with scope, the specified conte... | python | {
"resource": ""
} |
q224188 | generate_scalar_constant | train | def generate_scalar_constant(output_name, tensor_name, scalar):
"""Convert a scalar value to a Constant buffer.
This is mainly used for xxScalar operators."""
t = onnx.helper.make_tensor(tensor_name,
data_type=TensorProto.FLOAT,
dims=[1], vals=... | python | {
"resource": ""
} |
q224189 | replace_negative_size_with_batch_size | train | def replace_negative_size_with_batch_size(shape, batch_size):
"""Replace all dimensions with negative values to batch size"""
sl = []
for d in shape.dim:
if d < 0:
# Negative size means batch size
sl.append(batch_size)
else:
sl.append(d)
out_shape = nn... | python | {
"resource": ""
} |
q224190 | OnnxExporter.BinarySigmoid | train | def BinarySigmoid(self, func):
'''
Currently, caffe2 does not support this function.
'''
n = onnx.helper.make_node(
'HardSigmoid',
func.input,
func.output,
alpha=1.0,
beta=0.0
)
return [n] | python | {
"resource": ""
} |
q224191 | SequentialConverter.convert | train | def convert(self, vroot, entry_variables):
"""Convert a given graph.
Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially.
Args:
vroot (:obj:`Variable`): NNabla Variable
entry_variables (:obj:`Variable`): Entry variable from... | python | {
"resource": ""
} |
q224192 | calc_normal_std_he_forward | train | def calc_normal_std_he_forward(inmaps, outmaps, kernel=(1, 1)):
r"""Calculates the standard deviation proposed by He et al.
.. math::
\sigma = \sqrt{\frac{2}{NK}}
Args:
inmaps (int): Map size of an input Variable, :math:`N`.
outmaps (int): Map size of an output Variable, :math:`M`.... | python | {
"resource": ""
} |
q224193 | calc_normal_std_glorot | train | def calc_normal_std_glorot(inmaps, outmaps, kernel=(1, 1)):
r"""Calculates the standard deviation proposed by Glorot et al.
.. math::
\sigma = \sqrt{\frac{2}{NK + M}}
Args:
inmaps (int): Map size of an input Variable, :math:`N`.
outmaps (int): Map size of an output Variable, :math:... | python | {
"resource": ""
} |
q224194 | calc_uniform_lim_glorot | train | def calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1)):
r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al.
.. math::
b &= \sqrt{\frac{6}{NK + M}}\\
a &= -b
Args:
inmaps (int): Map size of an input Variable, :math:`N`.
... | python | {
"resource": ""
} |
q224195 | _get_unique_function_name | train | def _get_unique_function_name(function_type, functions):
'''Get a unique function name.
Args:
function_type(str): Name of Function. Ex) Convolution, Affine
functions(OrderedDict of (str, Function)
Returns: str
A unique function name
'''
function_name = function_name_base = ... | python | {
"resource": ""
} |
q224196 | _get_unique_variable_name | train | def _get_unique_variable_name(vname, variables):
'''Get a unique variable name.
Args:
vname(str): A candidate name.
variable(OrderedDict of str and Variable)
Returns: str
A unique variable name
'''
count = 2
vname_base = vname
while vname in variables:
vname... | python | {
"resource": ""
} |
q224197 | sum | train | def sum(x, axis=None, keepdims=False):
"""Reduction along axes with sum operation.
Args:
x (Variable): An input variable.
axis (None, int or tuple of ints): Axis or axes along which the sum is
calculated. Passing the default value `None` will reduce all dimensions.
keepdims ... | python | {
"resource": ""
} |
q224198 | mean | train | def mean(x, axis=None, keepdims=False):
"""Reduction along axes with mean operation.
Args:
x (Variable): An input variable.
axis (None, int or tuple of ints): Axis or axes along which mean is
calculated. Passing the default value `None` will reduce all dimensions.
keepdims (... | python | {
"resource": ""
} |
q224199 | prod | train | def prod(x, axis=None, keepdims=False):
"""Reduction along axes with product operation.
Args:
x (Variable): An input variable.
axis (None, int or tuple of ints): Axis or axes along which product is
calculated. Passing the default value `None` will reduce all dimensions.
keep... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.