INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Set up os pipe buffer size, if applicable
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)
Common set-up code for initializing a (pipe) file descriptor
def _setup_fd(fd): """Common set-up code for initializing a (pipe) file descriptor""" # Make the file nonblocking (but don't lose its previous flags) flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) set_buf_size(fd)
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 of Postgres, but that mechan...
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 ...
Wait for transfer to exit, raising errors as necessary.
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 ...
Begin transfer for an indicated wal segment.
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...
Forward any raised exceptions across a channel.
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...
Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content.
def copyfileobj(src, dst, length=None, exception=OSError, bufsize=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if bufsize is None: bufsize = pipebuf.PIPE_BUF_BYTES if length == 0: return if length is None: ...
Create a process in the same way as popen_sp, but patch the file descriptors so they can be accessed from Python/gevent in a non-blocking manner.
def popen_nonblock(*args, **kwargs): """ Create a process in the same way as popen_sp, but patch the file descriptors so they can be accessed from Python/gevent in a non-blocking manner. """ proc = popen_sp(*args, **kwargs) if proc.stdin: proc.stdin = pipebuf.NonBlockBufferedWriter...
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/python-pipes/
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...
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/
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...
Return an azure BlockBlobService instance.
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')
Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk.
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: ...
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.
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;' ...
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
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( ...
Connects to a server and attempts to start a hot backup Yields the WAL information in a dictionary for bookkeeping and recording.
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...
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 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...
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.
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...
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.
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...
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). Versions below 2.6 don't support the validate_certs o...
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...
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.
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 ...
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 credentials to fluctuate rapidly. By c...
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...
removes empty dirs under a given path
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)
create a directory if required
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)
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 necessary for throughput and makes more obscure the cause of failures. This is intended to ...
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...
Parse a boolean environment variable.
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)
Generate HINT language for missing configuration
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...
Render a subcommand for human-centric viewing
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
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
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(...
Get and decompress an S3 or WABS URL This streams the content directly to lzop; the compressed version is never stored on disk.
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, ...
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
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...
Delete all WAL files before segment_info. Doesn't delete any base-backup data.
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...
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 obsolete version) * Completely oblite...
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...
Delete all base backups and WAL before a given segment This is the most commonly-used deletion operator; to delete old backups and WAL.
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...
Retain the num_to_retain most recent backups and delete all data before them.
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 ...
Construct a connection value from a container
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...
Construct a connection value to Google Storage API The credentials are retrieved using get_credentials that checks the environment for the correct values.
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...
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) tuple (with the intention that it could raise the exception without losing the trac...
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...
Start upload and accout for resource consumption.
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 ...
Block until an upload finishes Raise an exception if that tar volume failed with an error.
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 ...
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.
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...
Upload a tar volume Blocks if there is too much work outstanding already, and raise errors of previously submitted greenlets that die unexpectedly.
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', ...
Get and decompress a S3 URL This streams the content directly to lzop; the compressed version is never stored on disk.
def do_lzop_get(creds, url, path, decrypt, do_retry=True): """ Get and decompress a S3 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' def log_wal_fetch_failures_on_error(exc_t...
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 preserve: set :return: None
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...
Create the default signal map for this system. :return: dict
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...
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
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, ...
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 :return: None :raise: DaemonError
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...
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: :type handler: str, None, function :retu...
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: ...
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
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...
The working_directory property :return: str
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...
Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historical model into (defaults to model.__module__) manager_name -- class attribute name to use for historical manager records_class -- class to use for history relation (defaults to ...
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...
Returns the additional urls used by the Reversion admin.
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( ...
The 'history' admin view for this model.
def history_view(self, request, object_id, extra_context=None): """The 'history' admin view for this model.""" request.current_app = self.admin_site.name model = self.model opts = model._meta app_label = opts.app_label pk_name = opts.pk.attname history = getattr(m...
Set special model attribute to user for reference after save
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)
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:
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...
Customize field appropriately for use in historical model
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...
Creates a historical model to associate with the model provided.
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...
Creates copies of the model's original fields, returning a dictionary mapping field name to copied field object.
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...
Return dict of extra fields added to the historical record model
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 ...
Returns a dictionary of fields that will be added to the Meta inner class of the historical record model.
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", } ...
Get the modifying user from instance or middleware.
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...
Returns the most recent copy of the instance available in the history.
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 ...
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.
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: ...
Bulk create the history for the objects specified by objs
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", ...
Return the history manager for a given app model.
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...
Bulk create the objects specified by objs while also bulk creating their history (all in one transaction). :param objs: List of objs (not yet saved to the db) of type model :param model: Model class that should be created :param batch_size: Number of objects that should be created in each batch :ret...
def bulk_create_with_history(objs, model, batch_size=None): """ Bulk create the objects specified by objs while also bulk creating their history (all in one transaction). :param objs: List of objs (not yet saved to the db) of type model :param model: Model class that should be created :param bat...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
Grouping parameters registered by parametric functions listed in :mod:`nnabla.parametric_functions`. Args: name (str): Parameter scope name. scope (OrderedDict, optional): Specifiy current parameter scope as a local dictionary. The default value is ``None``. In this ca...
def parameter_scope(name, scope=None): """ Grouping parameters registered by parametric functions listed in :mod:`nnabla.parametric_functions`. Args: name (str): Parameter scope name. scope (OrderedDict, optional): Specifiy current parameter scope as a local dictionary. ...
Remove and get parameter by key. Args: key(str): Key of parameter. Returns: ~nnabla.Variable Parameter if key found, otherwise None.
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...
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. Args: name(str): The name under the current scope. If it already exists, the name is queried from the parameter manager. ...
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. ...
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 under the current scope if False, while only parameters ...
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...
Load parameters from a file with the specified format. Args: path : path or file object
def load_parameters(path, proto=None, needs_proto=False): """Load parameters from a file with the specified format. Args: path : path or file object """ _, ext = os.path.splitext(path) if ext == '.h5': # TODO temporary work around to suppress FutureWarning message. import war...
Save all parameters into a file with the specified format. Currently hdf5 and protobuf formats are supported. Args: path : path or file object params (dict, optional): Parameters to be saved. Dictionary is of a parameter name (:obj:`str`) to :obj:`~nnabla.Variable`.
def save_parameters(path, params=None): """Save all parameters into a file with the specified format. Currently hdf5 and protobuf formats are supported. Args: path : path or file object params (dict, optional): Parameters to be saved. Dictionary is of a parameter name (:obj:`str`) to :obj:`~nn...
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. Returns: module An Python module of ...
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...
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.
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...
Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: ext_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for context function in a extension module. Returns: :class:`nnabla.Conte...
def get_extension_context(ext_name, **kw): """Get the context of the specified extension. All extension's module must provide `context(**kw)` function. Args: ext_name (str) : Module path relative to `nnabla_ext`. kw (dict) : Additional keyword arguments for context function in a extension ...
Read image by PIL module. Notice that PIL only supports uint8 for RGB (not uint16). So this imread function returns only uint8 array for both RGB and gray-scale. (Currently ignore "I" mode for gray-scale (32bit integer).) Args: path (str or 'file object'): File path or object to read. g...
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1): """ Read image by PIL module. Notice that PIL only supports uint8 for RGB (not uint16). So this imread function returns only uint8 array for both RGB and gray-scale. ...
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) by default. channel_first (bool): This argument specifies the shape o...
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)...
Resize image by pil module. Args: img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default. size (tupple of int): (width, height). channel_first (bool): This argument specifies...
def imresize(img, size, interpolate="bilinear", channel_first=False): """ Resize image by pil module. Args: img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) for RGB or (height, width) for gray-scale by default. size (tupple of int): ...
Create a variable graph given network by name Returns: NnpNetwork
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...
Set kernel related parameters(strides, pads, kernel_shape) to the given parameter. This function also generates a padding function if we need a seperate pad function for asymmetry padding.
def set_kernel_parameter_and_add_padding(node, kp, pad_mode, pad_val, base_name, func_counter): """Set kernel related parameters(strides, pads, kernel_shape) to the given parameter. This function also generates a padding function ...
Set a sufficient name for the function
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, ...
Generate a Transpose operator to transpose the specified buffer.
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_...
Generate a BroadcastTo operator to brodcast specified buffer
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...
Check each padding start/end value and set the sufficient pad value. If we have asymmetry padding, we will return True to indicate the need for a separate padding function
def check_padding(pads, dim, padval): """Check each padding start/end value and set the sufficient pad value. If we have asymmetry padding, we will return True to indicate the need for a separate padding function""" asymmetry = False for i in range(dim): s = pads[i] e = pads[i+di...
Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1)
def rearrange_pads(pads): """ Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1)""" half = len(pads)//2 starts = pads[:half] ends = pads[half:] return [j for i in zip(starts, ends) for j in i]
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
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( ...
Add given tensor as a parameter
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....
Converts a broadcasting operator to a composite with BroadcastTo
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": ...
Read image by pypng module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (width, height). If None, output img shape depends on the files to read. channel_first (bool): This argument specif...
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): ...
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 argument specifies the shape of img is whether (height, width, channel) or (channel, heig...
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...
All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
def convert(self, vroot, entry_variables): """ All functions are replaced with the same `new` function. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts. """ self.graph_info ...
Resolve shape parameter and returns shape.
def resolve_reshape_params(inputs, function_proto, batch_size): '''Resolve shape parameter and returns shape. ''' f = function_proto # alias # There are 2 exceptional cases. # A. Negative dimension is batch dimension # A-1. Detect multiple negative dimensions (not allowed). negative_count ...
Resolve shape parameter and returns shape.
def resolve_broadcast_params(inputs, function_proto, batch_size): '''Resolve shape parameter and returns shape. ''' f = function_proto # alias # A. Detect multiple negative dimensions (not allowed). negative_count = 0 for d in f.broadcast_param.shape.dim: if d < 0: negative...
load Load network information from files. Args: filenames (list): List of filenames. Returns: dict: Network information.
def load(filenames, prepare_data_iterator=True, batch_size=None, exclude_parameter=False, parameter_only=False): '''load Load network information from files. Args: filenames (list): List of filenames. Returns: dict: Network information. ''' class Info: pass info = In...
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 context is used. with paramet...
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...
Convert a scalar value to a Constant buffer. This is mainly used for xxScalar operators.
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=...
Replace all dimensions with negative values to batch size
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...
Currently, caffe2 does not support this function.
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]
nnabla slice assume a batch dimension existed in the shape of input data. Onnx caffe2 implementation only support one dimension for each slice, hence, we connect multiple slice node to implement slice with multiple axis
def Slice_6(self, func): """ nnabla slice assume a batch dimension existed in the shape of input data. Onnx caffe2 implementation only support one dimension for each slice, hence, we connect multiple slice node to implement slice with multiple axis """ s0 ...