id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
242,600
wal-e/wal-e
wal_e/worker/pg/psql_worker.py
PgBackupStatements.run_start_backup
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
def run_start_backup(cls): def handler(popen): assert popen.returncode != 0 raise UserException('Could not start hot backup') # The difficulty of getting a timezone-stamped, UTC, # ISO-formatted datetime is downright embarrassing. # # See http://bugs.pyth...
[ "def", "run_start_backup", "(", "cls", ")", ":", "def", "handler", "(", "popen", ")", ":", "assert", "popen", ".", "returncode", "!=", "0", "raise", "UserException", "(", "'Could not start hot backup'", ")", "# The difficulty of getting a timezone-stamped, UTC,", "# I...
Connects to a server and attempts to start a hot backup Yields the WAL information in a dictionary for bookkeeping and recording.
[ "Connects", "to", "a", "server", "and", "attempts", "to", "start", "a", "hot", "backup" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/psql_worker.py#L109-L133
242,601
wal-e/wal-e
wal_e/worker/pg/psql_worker.py
PgBackupStatements.run_stop_backup
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
def run_stop_backup(cls): def handler(popen): assert popen.returncode != 0 raise UserException('Could not stop hot backup') return cls._dict_transform(psql_csv_run( "SELECT file_name, " " lpad(file_offset::text, 8, '0') AS file_offset " ...
[ "def", "run_stop_backup", "(", "cls", ")", ":", "def", "handler", "(", "popen", ")", ":", "assert", "popen", ".", "returncode", "!=", "0", "raise", "UserException", "(", "'Could not stop hot backup'", ")", "return", "cls", ".", "_dict_transform", "(", "psql_cs...
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.
[ "Stop", "a", "hot", "backup", "if", "it", "was", "running", "or", "error" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/psql_worker.py#L136-L153
242,602
wal-e/wal-e
wal_e/blobstore/s3/calling_format.py
_is_ipv4_like
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
def _is_ipv4_like(s): parts = s.split('.') if len(parts) != 4: return False for part in parts: try: int(part) except ValueError: return False return True
[ "def", "_is_ipv4_like", "(", "s", ")", ":", "parts", "=", "s", ".", "split", "(", "'.'", ")", "if", "len", "(", "parts", ")", "!=", "4", ":", "return", "False", "for", "part", "in", "parts", ":", "try", ":", "int", "(", "part", ")", "except", "...
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.
[ "Find", "if", "a", "string", "superficially", "looks", "like", "an", "IPv4", "address", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L43-L62
242,603
wal-e/wal-e
wal_e/blobstore/s3/calling_format.py
_is_mostly_subdomain_compatible
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
def _is_mostly_subdomain_compatible(bucket_name): return (bucket_name.lower() == bucket_name and len(bucket_name) >= 3 and len(bucket_name) <= 63 and '_' not in bucket_name and '..' not in bucket_name and '-.' not in bucket_name and '.-' not in...
[ "def", "_is_mostly_subdomain_compatible", "(", "bucket_name", ")", ":", "return", "(", "bucket_name", ".", "lower", "(", ")", "==", "bucket_name", "and", "len", "(", "bucket_name", ")", ">=", "3", "and", "len", "(", "bucket_name", ")", "<=", "63", "and", "...
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.
[ "Returns", "True", "if", "SubdomainCallingFormat", "can", "be", "used", "...", "mostly" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L65-L83
242,604
wal-e/wal-e
wal_e/blobstore/s3/calling_format.py
_connect_secureish
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
def _connect_secureish(*args, **kwargs): if tuple(int(x) for x in boto.__version__.split('.')) >= (2, 6, 0): kwargs['validate_certs'] = True kwargs['is_secure'] = True auth_region_name = kwargs.pop('auth_region_name', None) conn = connection.S3Connection(*args, **kwargs) if auth_region_na...
[ "def", "_connect_secureish", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "tuple", "(", "int", "(", "x", ")", "for", "x", "in", "boto", ".", "__version__", ".", "split", "(", "'.'", ")", ")", ">=", "(", "2", ",", "6", ",", "0", ...
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...
[ "Connect", "using", "the", "safest", "available", "options", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L86-L109
242,605
wal-e/wal-e
wal_e/blobstore/s3/calling_format.py
from_store_name
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
def from_store_name(bucket_name, region=None): # Late-bind `region` for the sake of tests that inject the # AWS_REGION environment variable. if region is None: region = os.getenv('AWS_REGION') mostly_ok = _is_mostly_subdomain_compatible(bucket_name) if not mostly_ok: return Calling...
[ "def", "from_store_name", "(", "bucket_name", ",", "region", "=", "None", ")", ":", "# Late-bind `region` for the sake of tests that inject the", "# AWS_REGION environment variable.", "if", "region", "is", "None", ":", "region", "=", "os", ".", "getenv", "(", "'AWS_REGI...
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.
[ "Construct", "a", "CallingInfo", "value", "from", "a", "bucket", "name", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L242-L282
242,606
wal-e/wal-e
wal_e/blobstore/s3/calling_format.py
CallingInfo.connect
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
def connect(self, creds): def _conn_help(*args, **kwargs): return _connect_secureish( *args, provider=creds, calling_format=self.calling_format(), auth_region_name=self.region, **kwargs) # If WALE_S3_ENDPOINT is...
[ "def", "connect", "(", "self", ",", "creds", ")", ":", "def", "_conn_help", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_connect_secureish", "(", "*", "args", ",", "provider", "=", "creds", ",", "calling_format", "=", "self", ".", ...
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...
[ "Return", "a", "boto", "S3Connection", "set", "up", "with", "great", "care", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L191-L229
242,607
wal-e/wal-e
wal_e/blobstore/file/calling_format.py
remove_empty_dirs
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
def remove_empty_dirs(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)
[ "def", "remove_empty_dirs", "(", "path", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "d", "in", "dirs", ":", "dir_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "d", ...
removes empty dirs under a given path
[ "removes", "empty", "dirs", "under", "a", "given", "path" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/file/calling_format.py#L6-L12
242,608
wal-e/wal-e
wal_e/blobstore/file/calling_format.py
ensure_dir_exists
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
def ensure_dir_exists(path): dir_path = os.path.dirname(path) if not os.path.exists(dir_path): os.makedirs(dir_path)
[ "def", "ensure_dir_exists", "(", "path", ")", ":", "dir_path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "dir_path", ")", ":", "os", ".", "makedirs", "(", "dir_path", ")" ]
create a directory if required
[ "create", "a", "directory", "if", "required" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/file/calling_format.py#L15-L19
242,609
wal-e/wal-e
wal_e/cmd.py
external_program_check
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
def external_program_check( to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): could_not_run = [] error_msgs = [] def psql_err_handler(popen): assert popen.returncode != 0 error_msgs.append(textwrap.fill( 'Could not get a connection to the database: ' 'no...
[ "def", "external_program_check", "(", "to_check", "=", "frozenset", "(", "[", "PSQL_BIN", ",", "LZOP_BIN", ",", "PV_BIN", "]", ")", ")", ":", "could_not_run", "=", "[", "]", "error_msgs", "=", "[", "]", "def", "psql_err_handler", "(", "popen", ")", ":", ...
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 ...
[ "Validates", "the", "existence", "and", "basic", "working", "-", "ness", "of", "other", "programs" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/cmd.py#L86-L146
242,610
wal-e/wal-e
wal_e/cmd.py
parse_boolean_envvar
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
def parse_boolean_envvar(val): 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)
[ "def", "parse_boolean_envvar", "(", "val", ")", ":", "if", "not", "val", "or", "val", ".", "lower", "(", ")", "in", "{", "'false'", ",", "'0'", "}", ":", "return", "False", "elif", "val", ".", "lower", "(", ")", "in", "{", "'true'", ",", "'1'", "...
Parse a boolean environment variable.
[ "Parse", "a", "boolean", "environment", "variable", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/cmd.py#L161-L168
242,611
wal-e/wal-e
wal_e/cmd.py
_config_hint_generate
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
def _config_hint_generate(optname, both_env_and_param): env = optname.replace('-', '_').upper() if both_env_and_param: option = '--' + optname.lower() return ('Pass "{0}" or set the environment variable "{1}".' .format(option, env)) else: return 'Set the environment ...
[ "def", "_config_hint_generate", "(", "optname", ",", "both_env_and_param", ")", ":", "env", "=", "optname", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "upper", "(", ")", "if", "both_env_and_param", ":", "option", "=", "'--'", "+", "optname", ".", ...
Generate HINT language for missing configuration
[ "Generate", "HINT", "language", "for", "missing", "configuration" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/cmd.py#L386-L395
242,612
wal-e/wal-e
wal_e/cmd.py
render_subcommand
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
def render_subcommand(args): if args.subcommand == 'delete': return 'delete ' + args.delete_subcommand if args.subcommand in ('wal-prefetch', 'wal-push', 'wal-fetch'): return None return args.subcommand
[ "def", "render_subcommand", "(", "args", ")", ":", "if", "args", ".", "subcommand", "==", "'delete'", ":", "return", "'delete '", "+", "args", ".", "delete_subcommand", "if", "args", ".", "subcommand", "in", "(", "'wal-prefetch'", ",", "'wal-push'", ",", "'w...
Render a subcommand for human-centric viewing
[ "Render", "a", "subcommand", "for", "human", "-", "centric", "viewing" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/cmd.py#L570-L578
242,613
wal-e/wal-e
wal_e/worker/worker_util.py
do_lzop_put
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
def do_lzop_put(creds, url, local_path, gpg_key): assert url.endswith('.lzo') blobstore = get_blobstore(storage.StorageLayout(url)) with tempfile.NamedTemporaryFile( mode='r+b', buffering=pipebuf.PIPE_BUF_BYTES) as tf: with pipeline.get_upload_pipeline( open(local_path, ...
[ "def", "do_lzop_put", "(", "creds", ",", "url", ",", "local_path", ",", "gpg_key", ")", ":", "assert", "url", ".", "endswith", "(", "'.lzo'", ")", "blobstore", "=", "get_blobstore", "(", "storage", ".", "StorageLayout", "(", "url", ")", ")", "with", "tem...
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
[ "Compress", "and", "upload", "a", "given", "local", "path", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/worker_util.py#L16-L46
242,614
wal-e/wal-e
wal_e/worker/worker_util.py
do_lzop_get
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
def do_lzop_get(creds, url, path, decrypt, do_retry=True): blobstore = get_blobstore(storage.StorageLayout(url)) return blobstore.do_lzop_get(creds, url, path, decrypt, do_retry=do_retry)
[ "def", "do_lzop_get", "(", "creds", ",", "url", ",", "path", ",", "decrypt", ",", "do_retry", "=", "True", ")", ":", "blobstore", "=", "get_blobstore", "(", "storage", ".", "StorageLayout", "(", "url", ")", ")", "return", "blobstore", ".", "do_lzop_get", ...
Get and decompress an S3 or WABS URL This streams the content directly to lzop; the compressed version is never stored on disk.
[ "Get", "and", "decompress", "an", "S3", "or", "WABS", "URL" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/worker_util.py#L49-L58
242,615
wal-e/wal-e
wal_e/worker/base.py
_BackupList.find_all
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
def find_all(self, query): match = re.match(storage.BASE_BACKUP_REGEXP, query) if match is not None: for backup in iter(self): if backup.name == query: yield backup elif query == 'LATEST': all_backups = list(iter(self)) if...
[ "def", "find_all", "(", "self", ",", "query", ")", ":", "match", "=", "re", ".", "match", "(", "storage", ".", "BASE_BACKUP_REGEXP", ",", "query", ")", "if", "match", "is", "not", "None", ":", "for", "backup", "in", "iter", "(", "self", ")", ":", "...
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
[ "A", "procedure", "to", "assist", "in", "finding", "or", "detailing", "specific", "backups" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L106-L138
242,616
wal-e/wal-e
wal_e/worker/base.py
_DeleteFromContext._delete_wals_before
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
def _delete_wals_before(self, segment_info): wal_key_depth = self.layout.wal_directory().count('/') + 1 for key in self._backup_list(prefix=self.layout.wal_directory()): key_name = self.layout.key_name(key) bucket = self._container_name(key) url = '{scm}://{bucket}/{n...
[ "def", "_delete_wals_before", "(", "self", ",", "segment_info", ")", ":", "wal_key_depth", "=", "self", ".", "layout", ".", "wal_directory", "(", ")", ".", "count", "(", "'/'", ")", "+", "1", "for", "key", "in", "self", ".", "_backup_list", "(", "prefix"...
Delete all WAL files before segment_info. Doesn't delete any base-backup data.
[ "Delete", "all", "WAL", "files", "before", "segment_info", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L329-L393
242,617
wal-e/wal-e
wal_e/worker/base.py
_DeleteFromContext.delete_everything
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
def delete_everything(self): for k in self._backup_list(prefix=self.layout.basebackups()): self._maybe_delete_key(k, 'part of a base backup') for k in self._backup_list(prefix=self.layout.wal_directory()): self._maybe_delete_key(k, 'part of wal logs') if self.deleter: ...
[ "def", "delete_everything", "(", "self", ")", ":", "for", "k", "in", "self", ".", "_backup_list", "(", "prefix", "=", "self", ".", "layout", ".", "basebackups", "(", ")", ")", ":", "self", ".", "_maybe_delete_key", "(", "k", ",", "'part of a base backup'",...
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...
[ "Delete", "everything", "in", "a", "storage", "layout" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L395-L415
242,618
wal-e/wal-e
wal_e/worker/base.py
_DeleteFromContext.delete_before
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
def delete_before(self, segment_info): # This will delete all base backup data before segment_info. self._delete_base_backups_before(segment_info) # This will delete all WAL segments before segment_info. self._delete_wals_before(segment_info) if self.deleter: self.d...
[ "def", "delete_before", "(", "self", ",", "segment_info", ")", ":", "# This will delete all base backup data before segment_info.", "self", ".", "_delete_base_backups_before", "(", "segment_info", ")", "# This will delete all WAL segments before segment_info.", "self", ".", "_del...
Delete all base backups and WAL before a given segment This is the most commonly-used deletion operator; to delete old backups and WAL.
[ "Delete", "all", "base", "backups", "and", "WAL", "before", "a", "given", "segment" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L417-L433
242,619
wal-e/wal-e
wal_e/worker/base.py
_DeleteFromContext.delete_with_retention
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
def delete_with_retention(self, num_to_retain): base_backup_sentinel_depth = self.layout.basebackups().count('/') + 1 # Sweep over base backup files, collecting sentinel files from # completed backups. completed_basebackups = [] for key in self._backup_list(prefix=self.layout.ba...
[ "def", "delete_with_retention", "(", "self", ",", "num_to_retain", ")", ":", "base_backup_sentinel_depth", "=", "self", ".", "layout", ".", "basebackups", "(", ")", ".", "count", "(", "'/'", ")", "+", "1", "# Sweep over base backup files, collecting sentinel files fro...
Retain the num_to_retain most recent backups and delete all data before them.
[ "Retain", "the", "num_to_retain", "most", "recent", "backups", "and", "delete", "all", "data", "before", "them", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L435-L511
242,620
wal-e/wal-e
wal_e/blobstore/swift/calling_format.py
connect
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
def connect(creds): return swiftclient.Connection( authurl=creds.authurl, user=creds.user, key=creds.password, auth_version=creds.auth_version, tenant_name=creds.tenant_name, os_options={ "region_name": creds.region, "endpoint_type": creds.endp...
[ "def", "connect", "(", "creds", ")", ":", "return", "swiftclient", ".", "Connection", "(", "authurl", "=", "creds", ".", "authurl", ",", "user", "=", "creds", ".", "user", ",", "key", "=", "creds", ".", "password", ",", "auth_version", "=", "creds", "....
Construct a connection value from a container
[ "Construct", "a", "connection", "value", "from", "a", "container" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/swift/calling_format.py#L4-L28
242,621
wal-e/wal-e
wal_e/blobstore/gs/calling_format.py
connect
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
def connect(creds, max_retries=100): credentials, project = google.auth.default() return RetryClient(max_retries=max_retries, project=project, credentials=credentials)
[ "def", "connect", "(", "creds", ",", "max_retries", "=", "100", ")", ":", "credentials", ",", "project", "=", "google", ".", "auth", ".", "default", "(", ")", "return", "RetryClient", "(", "max_retries", "=", "max_retries", ",", "project", "=", "project", ...
Construct a connection value to Google Storage API The credentials are retrieved using get_credentials that checks the environment for the correct values.
[ "Construct", "a", "connection", "value", "to", "Google", "Storage", "API" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/gs/calling_format.py#L6-L15
242,622
wal-e/wal-e
wal_e/retries.py
retry
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
def retry(exception_processor=generic_exception_processor, max_retries=100): max_retries = int(os.getenv('WALE_RETRIES', max_retries)) def yield_new_function_from(f): def shim(*args, **kwargs): exc_processor_cxt = None retries = 0 while True: # Avoid...
[ "def", "retry", "(", "exception_processor", "=", "generic_exception_processor", ",", "max_retries", "=", "100", ")", ":", "max_retries", "=", "int", "(", "os", ".", "getenv", "(", "'WALE_RETRIES'", ",", "max_retries", ")", ")", "def", "yield_new_function_from", ...
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...
[ "Generic", "retry", "decorator" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/retries.py#L42-L112
242,623
wal-e/wal-e
wal_e/worker/upload_pool.py
TarUploadPool._start
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
def _start(self, tpart): 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 self.member_burden += len(tpart) g.start()
[ "def", "_start", "(", "self", ",", "tpart", ")", ":", "g", "=", "gevent", ".", "Greenlet", "(", "self", ".", "uploader", ",", "tpart", ")", "g", ".", "link", "(", "self", ".", "_finish", ")", "# Account for concurrency_burden before starting the greenlet", "...
Start upload and accout for resource consumption.
[ "Start", "upload", "and", "accout", "for", "resource", "consumption", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L29-L40
242,624
wal-e/wal-e
wal_e/worker/upload_pool.py
TarUploadPool._finish
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
def _finish(self, g): assert g.ready() if g.successful(): finished_tpart = g.get() self.wait_change.put(finished_tpart) else: self.wait_change.put(g.exception)
[ "def", "_finish", "(", "self", ",", "g", ")", ":", "assert", "g", ".", "ready", "(", ")", "if", "g", ".", "successful", "(", ")", ":", "finished_tpart", "=", "g", ".", "get", "(", ")", "self", ".", "wait_change", ".", "put", "(", "finished_tpart", ...
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.
[ "Called", "on", "completion", "of", "an", "upload", "greenlet", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L42-L54
242,625
wal-e/wal-e
wal_e/worker/upload_pool.py
TarUploadPool._wait
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
def _wait(self): val = self.wait_change.get() if isinstance(val, Exception): # Don't other uncharging, because execution is going to stop raise val else: # Uncharge for resources. self.member_burden -= len(val) self.concurrency_burden ...
[ "def", "_wait", "(", "self", ")", ":", "val", "=", "self", ".", "wait_change", ".", "get", "(", ")", "if", "isinstance", "(", "val", ",", "Exception", ")", ":", "# Don't other uncharging, because execution is going to stop", "raise", "val", "else", ":", "# Unc...
Block until an upload finishes Raise an exception if that tar volume failed with an error.
[ "Block", "until", "an", "upload", "finishes" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L56-L69
242,626
wal-e/wal-e
wal_e/worker/upload_pool.py
TarUploadPool.put
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
def put(self, tpart): if self.closed: raise UserCritical(msg='attempt to upload tar after closing', hint='report a bug') while True: too_many = ( self.concurrency_burden + 1 > self.max_concurrency or self.member_burd...
[ "def", "put", "(", "self", ",", "tpart", ")", ":", "if", "self", ".", "closed", ":", "raise", "UserCritical", "(", "msg", "=", "'attempt to upload tar after closing'", ",", "hint", "=", "'report a bug'", ")", "while", "True", ":", "too_many", "=", "(", "se...
Upload a tar volume Blocks if there is too much work outstanding already, and raise errors of previously submitted greenlets that die unexpectedly.
[ "Upload", "a", "tar", "volume" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L71-L113
242,627
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
close_filenos
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
def close_filenos(preserve): maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if maxfd == resource.RLIM_INFINITY: maxfd = 4096 for fileno in range(maxfd): if fileno not in preserve: try: os.close(fileno) except OSError as err: if n...
[ "def", "close_filenos", "(", "preserve", ")", ":", "maxfd", "=", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_NOFILE", ")", "[", "1", "]", "if", "maxfd", "==", "resource", ".", "RLIM_INFINITY", ":", "maxfd", "=", "4096", "for", "fileno", "...
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
[ "Close", "unprotected", "file", "descriptors" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L309-L333
242,628
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
default_signal_map
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
def default_signal_map(): name_map = { 'SIGTSTP': None, 'SIGTTIN': None, 'SIGTTOU': None, 'SIGTERM': 'terminate'} signal_map = {} for name, target in list(name_map.items()): if hasattr(signal, name): signal_map[getattr(signal, name)] = target return si...
[ "def", "default_signal_map", "(", ")", ":", "name_map", "=", "{", "'SIGTSTP'", ":", "None", ",", "'SIGTTIN'", ":", "None", ",", "'SIGTTOU'", ":", "None", ",", "'SIGTERM'", ":", "'terminate'", "}", "signal_map", "=", "{", "}", "for", "name", ",", "target"...
Create the default signal map for this system. :return: dict
[ "Create", "the", "default", "signal", "map", "for", "this", "system", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L336-L350
242,629
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
parent_is_inet
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
def parent_is_inet(): result = False sock = socket.fromfd( sys.__stdin__.fileno(), socket.AF_INET, socket.SOCK_RAW) try: sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) result = True except (OSError, socket.error) as err: if not err.args[0] == errno.ENO...
[ "def", "parent_is_inet", "(", ")", ":", "result", "=", "False", "sock", "=", "socket", ".", "fromfd", "(", "sys", ".", "__stdin__", ".", "fileno", "(", ")", ",", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_RAW", ")", "try", ":", "sock", ".", ...
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
[ "Check", "if", "parent", "is", "inet" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L366-L386
242,630
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
redirect_stream
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
def redirect_stream(system, target): if target is None: target_fd = os.open(os.devnull, os.O_RDWR) else: target_fd = target.fileno() try: os.dup2(target_fd, system.fileno()) except OSError as err: raise DaemonError('Could not redirect {0} to {1}: {2}' ...
[ "def", "redirect_stream", "(", "system", ",", "target", ")", ":", "if", "target", "is", "None", ":", "target_fd", "=", "os", ".", "open", "(", "os", ".", "devnull", ",", "os", ".", "O_RDWR", ")", "else", ":", "target_fd", "=", "target", ".", "fileno"...
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
[ "Redirect", "Unix", "streams" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L403-L425
242,631
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
DaemonContext._get_signal_handler
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
def _get_signal_handler(self, handler): if not handler: result = signal.SIG_IGN elif isinstance(handler, string_types): result = getattr(self, handler) else: result = handler return result
[ "def", "_get_signal_handler", "(", "self", ",", "handler", ")", ":", "if", "not", "handler", ":", "result", "=", "signal", ".", "SIG_IGN", "elif", "isinstance", "(", "handler", ",", "string_types", ")", ":", "result", "=", "getattr", "(", "self", ",", "h...
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...
[ "get", "the", "callback", "function", "for", "handler" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L141-L159
242,632
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
DaemonContext._files_preserve
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
def _files_preserve(self): result = set() files = [] if not self.files_preserve else self.files_preserve files.extend([self.stdin, self.stdout, self.stderr]) for item in files: if hasattr(item, 'fileno'): result.add(item.fileno()) if isinstance(ite...
[ "def", "_files_preserve", "(", "self", ")", ":", "result", "=", "set", "(", ")", "files", "=", "[", "]", "if", "not", "self", ".", "files_preserve", "else", "self", ".", "files_preserve", "files", ".", "extend", "(", "[", "self", ".", "stdin", ",", "...
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
[ "create", "a", "set", "of", "protected", "files" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L162-L179
242,633
wal-e/wal-e
wal_e/pep3143daemon/daemon.py
DaemonContext.working_directory
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
def working_directory(self): if self.chroot_directory and not \ self._working_directory.startswith(self.chroot_directory): return self.chroot_directory + self._working_directory else: return self._working_directory
[ "def", "working_directory", "(", "self", ")", ":", "if", "self", ".", "chroot_directory", "and", "not", "self", ".", "_working_directory", ".", "startswith", "(", "self", ".", "chroot_directory", ")", ":", "return", "self", ".", "chroot_directory", "+", "self"...
The working_directory property :return: str
[ "The", "working_directory", "property" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L196-L205
242,634
treyhunner/django-simple-history
simple_history/__init__.py
register
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
def register( model, app=None, manager_name="history", records_class=None, table_name=None, **records_config ): from . import models if records_class is None: records_class = models.HistoricalRecords records = records_class(**records_config) records.manager_name = manag...
[ "def", "register", "(", "model", ",", "app", "=", "None", ",", "manager_name", "=", "\"history\"", ",", "records_class", "=", "None", ",", "table_name", "=", "None", ",", "*", "*", "records_config", ")", ":", "from", ".", "import", "models", "if", "recor...
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 ...
[ "Create", "historical", "model", "for", "model", "and", "attach", "history", "manager", "to", "model", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/__init__.py#L6-L39
242,635
treyhunner/django-simple-history
simple_history/admin.py
SimpleHistoryAdmin.get_urls
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
def get_urls(self): 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( "^([^/]+)/history/([^/]+)/$", admin_site.admin_view(...
[ "def", "get_urls", "(", "self", ")", ":", "urls", "=", "super", "(", "SimpleHistoryAdmin", ",", "self", ")", ".", "get_urls", "(", ")", "admin_site", "=", "self", ".", "admin_site", "opts", "=", "self", ".", "model", ".", "_meta", "info", "=", "opts", ...
Returns the additional urls used by the Reversion admin.
[ "Returns", "the", "additional", "urls", "used", "by", "the", "Reversion", "admin", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/admin.py#L29-L42
242,636
treyhunner/django-simple-history
simple_history/admin.py
SimpleHistoryAdmin.save_model
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
def save_model(self, request, obj, form, change): obj._history_user = request.user super(SimpleHistoryAdmin, self).save_model(request, obj, form, change)
[ "def", "save_model", "(", "self", ",", "request", ",", "obj", ",", "form", ",", "change", ")", ":", "obj", ".", "_history_user", "=", "request", ".", "user", "super", "(", "SimpleHistoryAdmin", ",", "self", ")", ".", "save_model", "(", "request", ",", ...
Set special model attribute to user for reference after save
[ "Set", "special", "model", "attribute", "to", "user", "for", "reference", "after", "save" ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/admin.py#L203-L206
242,637
treyhunner/django-simple-history
simple_history/management/commands/populate_history.py
Command._bulk_history_create
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
def _bulk_history_create(self, model, batch_size): instances = [] history = utils.get_history_manager_for_model(model) if self.verbosity >= 1: self.stdout.write( "Starting bulk creating history models for {} instances {}-{}".format( model, 0, batch...
[ "def", "_bulk_history_create", "(", "self", ",", "model", ",", "batch_size", ")", ":", "instances", "=", "[", "]", "history", "=", "utils", ".", "get_history_manager_for_model", "(", "model", ")", "if", "self", ".", "verbosity", ">=", "1", ":", "self", "."...
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:
[ "Save", "a", "copy", "of", "all", "instances", "to", "the", "historical", "model", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/management/commands/populate_history.py#L113-L158
242,638
treyhunner/django-simple-history
simple_history/models.py
transform_field
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
def transform_field(field): 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.__class__ = models.TextField # Historical instance shouldn't change...
[ "def", "transform_field", "(", "field", ")", ":", "field", ".", "name", "=", "field", ".", "attname", "if", "isinstance", "(", "field", ",", "models", ".", "AutoField", ")", ":", "field", ".", "__class__", "=", "models", ".", "IntegerField", "elif", "isi...
Customize field appropriately for use in historical model
[ "Customize", "field", "appropriately", "for", "use", "in", "historical", "model" ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L528-L548
242,639
treyhunner/django-simple-history
simple_history/models.py
HistoricalRecords.create_history_model
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
def create_history_model(self, model, inherited): attrs = { "__module__": self.module, "_history_excluded_fields": self.excluded_fields, } app_module = "%s.models" % model._meta.app_label if inherited: # inherited use models module attrs[...
[ "def", "create_history_model", "(", "self", ",", "model", ",", "inherited", ")", ":", "attrs", "=", "{", "\"__module__\"", ":", "self", ".", "module", ",", "\"_history_excluded_fields\"", ":", "self", ".", "excluded_fields", ",", "}", "app_module", "=", "\"%s....
Creates a historical model to associate with the model provided.
[ "Creates", "a", "historical", "model", "to", "associate", "with", "the", "model", "provided", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L193-L228
242,640
treyhunner/django-simple-history
simple_history/models.py
HistoricalRecords.copy_fields
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
def copy_fields(self, model): fields = {} for field in self.fields_included(model): field = copy.copy(field) field.remote_field = copy.copy(field.remote_field) if isinstance(field, OrderWrt): # OrderWrt is a proxy field, switch to a plain IntegerField ...
[ "def", "copy_fields", "(", "self", ",", "model", ")", ":", "fields", "=", "{", "}", "for", "field", "in", "self", ".", "fields_included", "(", "model", ")", ":", "field", "=", "copy", ".", "copy", "(", "field", ")", "field", ".", "remote_field", "=",...
Creates copies of the model's original fields, returning a dictionary mapping field name to copied field object.
[ "Creates", "copies", "of", "the", "model", "s", "original", "fields", "returning", "a", "dictionary", "mapping", "field", "name", "to", "copied", "field", "object", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L237-L289
242,641
treyhunner/django-simple-history
simple_history/models.py
HistoricalRecords.get_extra_fields
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
def get_extra_fields(self, model, fields): 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 return reverse( "%s:%s_%s_simple_history" % (admin.site...
[ "def", "get_extra_fields", "(", "self", ",", "model", ",", "fields", ")", ":", "def", "revert_url", "(", "self", ")", ":", "\"\"\"URL for this change in the default admin site.\"\"\"", "opts", "=", "model", ".", "_meta", "app_label", ",", "model_name", "=", "opts"...
Return dict of extra fields added to the historical record model
[ "Return", "dict", "of", "extra", "fields", "added", "to", "the", "historical", "record", "model" ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L360-L435
242,642
treyhunner/django-simple-history
simple_history/models.py
HistoricalRecords.get_meta_options
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
def get_meta_options(self, model): meta_fields = { "ordering": ("-history_date", "-history_id"), "get_latest_by": "history_date", } if self.user_set_verbose_name: name = self.user_set_verbose_name else: name = format_lazy("historical {}", s...
[ "def", "get_meta_options", "(", "self", ",", "model", ")", ":", "meta_fields", "=", "{", "\"ordering\"", ":", "(", "\"-history_date\"", ",", "\"-history_id\"", ")", ",", "\"get_latest_by\"", ":", "\"history_date\"", ",", "}", "if", "self", ".", "user_set_verbose...
Returns a dictionary of fields that will be added to the Meta inner class of the historical record model.
[ "Returns", "a", "dictionary", "of", "fields", "that", "will", "be", "added", "to", "the", "Meta", "inner", "class", "of", "the", "historical", "record", "model", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L437-L453
242,643
treyhunner/django-simple-history
simple_history/models.py
HistoricalRecords.get_history_user
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
def get_history_user(self, instance): try: return instance._history_user except AttributeError: request = None try: if self.thread.request.user.is_authenticated: request = self.thread.request except AttributeError: ...
[ "def", "get_history_user", "(", "self", ",", "instance", ")", ":", "try", ":", "return", "instance", ".", "_history_user", "except", "AttributeError", ":", "request", "=", "None", "try", ":", "if", "self", ".", "thread", ".", "request", ".", "user", ".", ...
Get the modifying user from instance or middleware.
[ "Get", "the", "modifying", "user", "from", "instance", "or", "middleware", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L513-L525
242,644
treyhunner/django-simple-history
simple_history/manager.py
HistoryManager.most_recent
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
def most_recent(self): if not self.instance: raise TypeError( "Can't use most_recent() without a {} instance.".format( self.model._meta.object_name ) ) tmp = [] excluded_fields = getattr(self.model, "_history_excluded_fi...
[ "def", "most_recent", "(", "self", ")", ":", "if", "not", "self", ".", "instance", ":", "raise", "TypeError", "(", "\"Can't use most_recent() without a {} instance.\"", ".", "format", "(", "self", ".", "model", ".", "_meta", ".", "object_name", ")", ")", "tmp"...
Returns the most recent copy of the instance available in the history.
[ "Returns", "the", "most", "recent", "copy", "of", "the", "instance", "available", "in", "the", "history", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/manager.py#L37-L64
242,645
treyhunner/django-simple-history
simple_history/manager.py
HistoryManager.as_of
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
def as_of(self, date): if not self.instance: return self._as_of_set(date) queryset = self.get_queryset().filter(history_date__lte=date) try: history_obj = queryset[0] except IndexError: raise self.instance.DoesNotExist( "%s had not yet ...
[ "def", "as_of", "(", "self", ",", "date", ")", ":", "if", "not", "self", ".", "instance", ":", "return", "self", ".", "_as_of_set", "(", "date", ")", "queryset", "=", "self", ".", "get_queryset", "(", ")", ".", "filter", "(", "history_date__lte", "=", ...
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.
[ "Get", "a", "snapshot", "as", "of", "a", "specific", "date", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/manager.py#L66-L86
242,646
treyhunner/django-simple-history
simple_history/manager.py
HistoryManager.bulk_history_create
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
def bulk_history_create(self, objs, batch_size=None): historical_instances = [ self.model( history_date=getattr(instance, "_history_date", now()), history_user=getattr(instance, "_history_user", None), history_change_reason=getattr(instance, "changeRea...
[ "def", "bulk_history_create", "(", "self", ",", "objs", ",", "batch_size", "=", "None", ")", ":", "historical_instances", "=", "[", "self", ".", "model", "(", "history_date", "=", "getattr", "(", "instance", ",", "\"_history_date\"", ",", "now", "(", ")", ...
Bulk create the history for the objects specified by objs
[ "Bulk", "create", "the", "history", "for", "the", "objects", "specified", "by", "objs" ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/manager.py#L101-L121
242,647
treyhunner/django-simple-history
simple_history/utils.py
get_history_manager_for_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...
python
def get_history_manager_for_model(model): try: manager_name = model._meta.simple_history_manager_attribute except AttributeError: raise NotHistoricalModelError( "Cannot find a historical model for {model}.".format(model=model) ) return getattr(model, manager_name)
[ "def", "get_history_manager_for_model", "(", "model", ")", ":", "try", ":", "manager_name", "=", "model", ".", "_meta", ".", "simple_history_manager_attribute", "except", "AttributeError", ":", "raise", "NotHistoricalModelError", "(", "\"Cannot find a historical model for {...
Return the history manager for a given app model.
[ "Return", "the", "history", "manager", "for", "a", "given", "app", "model", "." ]
85758ecfe608279508a3fb5b71654d3e202eb63d
https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/utils.py#L23-L31
242,648
sony/nnabla
python/src/nnabla/parameter.py
pop_parameter
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
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...
[ "def", "pop_parameter", "(", "key", ")", ":", "names", "=", "key", ".", "split", "(", "'/'", ")", "if", "len", "(", "names", ")", ">", "1", ":", "with", "parameter_scope", "(", "names", "[", "0", "]", ")", ":", "return", "pop_parameter", "(", "'/'"...
Remove and get parameter by key. Args: key(str): Key of parameter. Returns: ~nnabla.Variable Parameter if key found, otherwise None.
[ "Remove", "and", "get", "parameter", "by", "key", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parameter.py#L149-L167
242,649
sony/nnabla
python/src/nnabla/parameter.py
get_parameter_or_create
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
def get_parameter_or_create(name, shape=None, initializer=None, need_grad=True, as_need_grad=None): names = name.split('/') if len(names) > 1: with parameter_scope(names[0]): return get_parameter_or_create('/'.join(names[1:]), shape, initializer, need_grad, as_nee...
[ "def", "get_parameter_or_create", "(", "name", ",", "shape", "=", "None", ",", "initializer", "=", "None", ",", "need_grad", "=", "True", ",", "as_need_grad", "=", "None", ")", ":", "names", "=", "name", ".", "split", "(", "'/'", ")", "if", "len", "(",...
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. ...
[ "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", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parameter.py#L179-L245
242,650
sony/nnabla
python/src/nnabla/parameter.py
get_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...
python
def get_parameters(params=None, path='', grad_only=True): global current_scope if params is None: params = OrderedDict() for k, v in iteritems(current_scope): if isinstance(v, dict): with parameter_scope(k): params = get_parameters( params, '/'...
[ "def", "get_parameters", "(", "params", "=", "None", ",", "path", "=", "''", ",", "grad_only", "=", "True", ")", ":", "global", "current_scope", "if", "params", "is", "None", ":", "params", "=", "OrderedDict", "(", ")", "for", "k", ",", "v", "in", "i...
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 ...
[ "Get", "parameter", "Variables", "under", "the", "current", "parameter", "scope", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parameter.py#L248-L275
242,651
sony/nnabla
python/src/nnabla/ext_utils.py
import_extension_module
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
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...
[ "def", "import_extension_module", "(", "ext_name", ")", ":", "import", "importlib", "try", ":", "return", "importlib", ".", "import_module", "(", "'.'", "+", "ext_name", ",", "'nnabla_ext'", ")", "except", "ImportError", "as", "e", ":", "from", "nnabla", "impo...
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 ...
[ "Import", "an", "extension", "module", "by", "name", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/ext_utils.py#L20-L50
242,652
sony/nnabla
python/src/nnabla/ext_utils.py
list_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...
python
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...
[ "def", "list_extensions", "(", ")", ":", "import", "nnabla_ext", ".", "cpu", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "realpath", "from", "os", "import", "listdir", "ext_dir", "=", "realpath", "(", "(", "join", "(", "dirname", "(...
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.
[ "List", "up", "available", "extensions", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/ext_utils.py#L53-L69
242,653
sony/nnabla
python/src/nnabla/utils/image_utils/pil_utils.py
imsave
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
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True): img = _imsave_before(img, channel_first, auto_scale) if img.dtype == np.uint16 or as_uint16: raise ValueError("Pillow only supports uint8 image to save. Cast img to uint8." "If you want to save image ...
[ "def", "imsave", "(", "path", ",", "img", ",", "channel_first", "=", "False", ",", "as_uint16", "=", "False", ",", "auto_scale", "=", "True", ")", ":", "img", "=", "_imsave_before", "(", "img", ",", "channel_first", ",", "auto_scale", ")", "if", "img", ...
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...
[ "Save", "image", "by", "pillow", "module", ".", "Currently", "pillow", "supports", "only", "uint8", "to", "save", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/image_utils/pil_utils.py#L118-L147
242,654
sony/nnabla
python/src/nnabla/utils/nnp_graph.py
NnpLoader.get_network
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
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...
[ "def", "get_network", "(", "self", ",", "name", ",", "batch_size", "=", "None", ",", "callback", "=", "None", ")", ":", "network_proto", "=", "nnabla_pb2", ".", "Network", "(", ")", "network_proto", ".", "CopyFrom", "(", "self", ".", "network_dict", "[", ...
Create a variable graph given network by name Returns: NnpNetwork
[ "Create", "a", "variable", "graph", "given", "network", "by", "name" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/nnp_graph.py#L463-L471
242,655
sony/nnabla
python/src/nnabla/utils/converter/onnx/importer.py
set_function_name
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
def set_function_name(func, node_name, base_name, func_counter): # 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, func_counter) update_function_counter...
[ "def", "set_function_name", "(", "func", ",", "node_name", ",", "base_name", ",", "func_counter", ")", ":", "# NNabla requires each function to have a unique name", "# so we generate one here.", "func", ".", "name", ",", "count", "=", "generate_function_name", "(", "func"...
Set a sufficient name for the function
[ "Set", "a", "sufficient", "name", "for", "the", "function" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L153-L159
242,656
sony/nnabla
python/src/nnabla/utils/converter/onnx/importer.py
generate_transpose
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
def generate_transpose(node_name, in_name, out_name, axes, base_name, func_counter): trans = nnabla_pb2.Function() trans.type = "Transpose" set_function_name(trans, node_name, base_name, func_counter) trans.input.extend([in_name]) trans.output.extend([out_name]) tp = trans.transpose_param tp...
[ "def", "generate_transpose", "(", "node_name", ",", "in_name", ",", "out_name", ",", "axes", ",", "base_name", ",", "func_counter", ")", ":", "trans", "=", "nnabla_pb2", ".", "Function", "(", ")", "trans", ".", "type", "=", "\"Transpose\"", "set_function_name"...
Generate a Transpose operator to transpose the specified buffer.
[ "Generate", "a", "Transpose", "operator", "to", "transpose", "the", "specified", "buffer", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L162-L172
242,657
sony/nnabla
python/src/nnabla/utils/converter/onnx/importer.py
generate_broadcast_to
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
def generate_broadcast_to(node_name, x, y, out_name, axis, base_name, func_counter): bt = nnabla_pb2.Function() bt.type = "BroadcastTo" set_function_name(bt, node_name, base_name, func_counter) bt.input.extend([x, y]) bt.output.extend([out_name]) btp = bt.broadcast_to_param btp.axis = axis ...
[ "def", "generate_broadcast_to", "(", "node_name", ",", "x", ",", "y", ",", "out_name", ",", "axis", ",", "base_name", ",", "func_counter", ")", ":", "bt", "=", "nnabla_pb2", ".", "Function", "(", ")", "bt", ".", "type", "=", "\"BroadcastTo\"", "set_functio...
Generate a BroadcastTo operator to brodcast specified buffer
[ "Generate", "a", "BroadcastTo", "operator", "to", "brodcast", "specified", "buffer" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L175-L184
242,658
sony/nnabla
python/src/nnabla/utils/converter/onnx/importer.py
convert_parameter_shape
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
def convert_parameter_shape(pb): if len(pb.network) != 1: raise ValueError( "NNP with more then a single network is currently not supported") net = pb.network[0] batch_norm_constants = [] for f in net.function: if f.type == "BatchNormalization": # BatchNormalizati...
[ "def", "convert_parameter_shape", "(", "pb", ")", ":", "if", "len", "(", "pb", ".", "network", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"NNP with more then a single network is currently not supported\"", ")", "net", "=", "pb", ".", "network", "[", "0",...
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
[ "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", "whol...
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L362-L398
242,659
sony/nnabla
python/src/nnabla/utils/converter/onnx/importer.py
add_tensor_as_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....
python
def add_tensor_as_parameter(pb, tensor): 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.data.extend(np.fromstring(tensor.raw_data,...
[ "def", "add_tensor_as_parameter", "(", "pb", ",", "tensor", ")", ":", "p", "=", "pb", ".", "parameter", ".", "add", "(", ")", "p", ".", "variable_name", "=", "tensor", ".", "name", "p", ".", "shape", ".", "dim", ".", "extend", "(", "tensor", ".", "...
Add given tensor as a parameter
[ "Add", "given", "tensor", "as", "a", "parameter" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L401-L439
242,660
sony/nnabla
python/src/nnabla/utils/converter/onnx/importer.py
OnnxImporter.BroadcastOperator
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
def BroadcastOperator(self, func_name, func_list, n): broadcasting = False broadcast_axis = -1 func = self.generate_default_function(func_name, n) for attr in n.attribute: if attr.name == "axis": if attr.type != AttributeProto.INT: raise Va...
[ "def", "BroadcastOperator", "(", "self", ",", "func_name", ",", "func_list", ",", "n", ")", ":", "broadcasting", "=", "False", "broadcast_axis", "=", "-", "1", "func", "=", "self", ".", "generate_default_function", "(", "func_name", ",", "n", ")", "for", "...
Converts a broadcasting operator to a composite with BroadcastTo
[ "Converts", "a", "broadcasting", "operator", "to", "a", "composite", "with", "BroadcastTo" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L889-L933
242,661
sony/nnabla
python/src/nnabla/utils/image_utils/pypng_utils.py
imread
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
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1): _imread_before(grayscale, num_channels) f = path if hasattr(path, "read") else open(path, "rb") r = png.Reader(file=f) width, height, pixels, metadata = r.asDirect() ...
[ "def", "imread", "(", "path", ",", "grayscale", "=", "False", ",", "size", "=", "None", ",", "interpolate", "=", "\"bilinear\"", ",", "channel_first", "=", "False", ",", "as_uint16", "=", "False", ",", "num_channels", "=", "-", "1", ")", ":", "_imread_be...
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...
[ "Read", "image", "by", "pypng", "module", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/image_utils/pypng_utils.py#L79-L122
242,662
sony/nnabla
python/src/nnabla/utils/image_utils/pypng_utils.py
imsave
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
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True): img = _imsave_before(img, channel_first, auto_scale) if auto_scale: img = upscale_pixel_intensity(img, as_uint16) img = check_type_and_cast_if_necessary(img, as_uint16) bitdepth = 8 if img.dtype == np.uint8 else 16 ...
[ "def", "imsave", "(", "path", ",", "img", ",", "channel_first", "=", "False", ",", "as_uint16", "=", "False", ",", "auto_scale", "=", "True", ")", ":", "img", "=", "_imsave_before", "(", "img", ",", "channel_first", ",", "auto_scale", ")", "if", "auto_sc...
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...
[ "Save", "image", "by", "pypng", "module", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/image_utils/pypng_utils.py#L125-L160
242,663
sony/nnabla
python/src/nnabla/context.py
context_scope
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
def context_scope(ctx): global current_ctx global context_level context_level += 1 prev_context = current_ctx current_ctx = ctx try: yield finally: context_level -= 1 current_ctx = prev_context
[ "def", "context_scope", "(", "ctx", ")", ":", "global", "current_ctx", "global", "context_level", "context_level", "+=", "1", "prev_context", "=", "current_ctx", "current_ctx", "=", "ctx", "try", ":", "yield", "finally", ":", "context_level", "-=", "1", "current...
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...
[ "Context", "as", "Python", "context", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/context.py#L29-L56
242,664
sony/nnabla
python/src/nnabla/utils/converter/onnx/exporter.py
generate_scalar_constant
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
def generate_scalar_constant(output_name, tensor_name, scalar): t = onnx.helper.make_tensor(tensor_name, data_type=TensorProto.FLOAT, dims=[1], vals=[scalar]) c = onnx.helper.make_node("Constant", [], ...
[ "def", "generate_scalar_constant", "(", "output_name", ",", "tensor_name", ",", "scalar", ")", ":", "t", "=", "onnx", ".", "helper", ".", "make_tensor", "(", "tensor_name", ",", "data_type", "=", "TensorProto", ".", "FLOAT", ",", "dims", "=", "[", "1", "]"...
Convert a scalar value to a Constant buffer. This is mainly used for xxScalar operators.
[ "Convert", "a", "scalar", "value", "to", "a", "Constant", "buffer", ".", "This", "is", "mainly", "used", "for", "xxScalar", "operators", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/exporter.py#L42-L52
242,665
sony/nnabla
python/src/nnabla/utils/converter/onnx/exporter.py
replace_negative_size_with_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...
python
def replace_negative_size_with_batch_size(shape, 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 = nnabla_pb2.Shape() out_shape.dim.extend(sl) return out_shape
[ "def", "replace_negative_size_with_batch_size", "(", "shape", ",", "batch_size", ")", ":", "sl", "=", "[", "]", "for", "d", "in", "shape", ".", "dim", ":", "if", "d", "<", "0", ":", "# Negative size means batch size", "sl", ".", "append", "(", "batch_size", ...
Replace all dimensions with negative values to batch size
[ "Replace", "all", "dimensions", "with", "negative", "values", "to", "batch", "size" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/exporter.py#L121-L132
242,666
sony/nnabla
python/src/nnabla/utils/converter/onnx/exporter.py
OnnxExporter.BinarySigmoid
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
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]
[ "def", "BinarySigmoid", "(", "self", ",", "func", ")", ":", "n", "=", "onnx", ".", "helper", ".", "make_node", "(", "'HardSigmoid'", ",", "func", ".", "input", ",", "func", ".", "output", ",", "alpha", "=", "1.0", ",", "beta", "=", "0.0", ")", "ret...
Currently, caffe2 does not support this function.
[ "Currently", "caffe2", "does", "not", "support", "this", "function", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/exporter.py#L392-L403
242,667
sony/nnabla
python/src/nnabla/experimental/graph_converters/sequential.py
SequentialConverter.convert
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
def convert(self, vroot, entry_variables): for converter in self.converters: vroot = converter.convert(vroot, entry_variables) return vroot
[ "def", "convert", "(", "self", ",", "vroot", ",", "entry_variables", ")", ":", "for", "converter", "in", "self", ".", "converters", ":", "vroot", "=", "converter", ".", "convert", "(", "vroot", ",", "entry_variables", ")", "return", "vroot" ]
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 which the conversion starts.
[ "Convert", "a", "given", "graph", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/experimental/graph_converters/sequential.py#L17-L29
242,668
sony/nnabla
python/src/nnabla/initializer.py
calc_normal_std_he_forward
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
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`....
[ "def", "calc_normal_std_he_forward", "(", "inmaps", ",", "outmaps", ",", "kernel", "=", "(", "1", ",", "1", ")", ")", ":", "return", "np", ".", "sqrt", "(", "2.", "/", "(", "np", ".", "prod", "(", "kernel", ")", "*", "inmaps", ")", ")" ]
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`. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel spa...
[ "r", "Calculates", "the", "standard", "deviation", "proposed", "by", "He", "et", "al", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/initializer.py#L216-L249
242,669
sony/nnabla
python/src/nnabla/initializer.py
calc_normal_std_glorot
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
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:...
[ "def", "calc_normal_std_glorot", "(", "inmaps", ",", "outmaps", ",", "kernel", "=", "(", "1", ",", "1", ")", ")", ":", "return", "np", ".", "sqrt", "(", "2.", "/", "(", "np", ".", "prod", "(", "kernel", ")", "*", "inmaps", "+", "outmaps", ")", ")...
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:`M`. kernel (:obj:`tuple` of :obj:`int`): Convolution ke...
[ "r", "Calculates", "the", "standard", "deviation", "proposed", "by", "Glorot", "et", "al", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/initializer.py#L288-L321
242,670
sony/nnabla
python/src/nnabla/initializer.py
calc_uniform_lim_glorot
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
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`. ...
[ "def", "calc_uniform_lim_glorot", "(", "inmaps", ",", "outmaps", ",", "kernel", "=", "(", "1", ",", "1", ")", ")", ":", "d", "=", "np", ".", "sqrt", "(", "6.", "/", "(", "np", ".", "prod", "(", "kernel", ")", "*", "inmaps", "+", "outmaps", ")", ...
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`. outmaps (int): Map size of an output Variable, :math:`M`. ...
[ "r", "Calculates", "the", "lower", "bound", "and", "the", "upper", "bound", "of", "the", "uniform", "distribution", "proposed", "by", "Glorot", "et", "al", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/initializer.py#L324-L360
242,671
sony/nnabla
python/src/nnabla/utils/save.py
_get_unique_function_name
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
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 = ...
[ "def", "_get_unique_function_name", "(", "function_type", ",", "functions", ")", ":", "function_name", "=", "function_name_base", "=", "function_type", "count", "=", "2", "while", "function_name", "in", "functions", ":", "function_name", "=", "'{}_{}'", ".", "format...
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
[ "Get", "a", "unique", "function", "name", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/save.py#L41-L56
242,672
sony/nnabla
python/src/nnabla/utils/save.py
_get_unique_variable_name
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
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...
[ "def", "_get_unique_variable_name", "(", "vname", ",", "variables", ")", ":", "count", "=", "2", "vname_base", "=", "vname", "while", "vname", "in", "variables", ":", "vname", "=", "'{}_{}'", ".", "format", "(", "vname_base", ",", "count", ")", "count", "+...
Get a unique variable name. Args: vname(str): A candidate name. variable(OrderedDict of str and Variable) Returns: str A unique variable name
[ "Get", "a", "unique", "variable", "name", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/save.py#L59-L74
242,673
sony/nnabla
python/src/nnabla/functions.py
sum
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
def sum(x, axis=None, keepdims=False): from .function_bases import sum as sum_base if axis is None: axis = range(x.ndim) elif not hasattr(axis, '__iter__'): axis = [axis] return sum_base(x, axis, keepdims)
[ "def", "sum", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "from", ".", "function_bases", "import", "sum", "as", "sum_base", "if", "axis", "is", "None", ":", "axis", "=", "range", "(", "x", ".", "ndim", ")", "elif", ...
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 (bool): Flag whether the reduced axes are kept...
[ "Reduction", "along", "axes", "with", "sum", "operation", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L21-L38
242,674
sony/nnabla
python/src/nnabla/functions.py
mean
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
def mean(x, axis=None, keepdims=False): from .function_bases import mean as mean_base if axis is None: axis = range(x.ndim) elif not hasattr(axis, '__iter__'): axis = [axis] return mean_base(x, axis, keepdims)
[ "def", "mean", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "from", ".", "function_bases", "import", "mean", "as", "mean_base", "if", "axis", "is", "None", ":", "axis", "=", "range", "(", "x", ".", "ndim", ")", "elif...
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 (bool): Flag whether the reduced axes are kept a...
[ "Reduction", "along", "axes", "with", "mean", "operation", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L41-L59
242,675
sony/nnabla
python/src/nnabla/functions.py
prod
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
def prod(x, axis=None, keepdims=False): from .function_bases import prod as prod_base if axis is None: axis = range(x.ndim) elif not hasattr(axis, '__iter__'): axis = [axis] return prod_base(x, axis, keepdims)
[ "def", "prod", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "from", ".", "function_bases", "import", "prod", "as", "prod_base", "if", "axis", "is", "None", ":", "axis", "=", "range", "(", "x", ".", "ndim", ")", "elif...
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. keepdims (bool): Flag whether the reduced axes are ...
[ "Reduction", "along", "axes", "with", "product", "operation", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L162-L183
242,676
sony/nnabla
python/src/nnabla/functions.py
reduce
def reduce(x, op='sum'): """Reduction function with given operation. Args: x (Variable): An input. op (str): 'sum' or 'mean'. Note: This is deprecated. Use ``mean`` or ``sum`` instead. """ import warnings warnings.warn( "Deprecated API. Use ``sum`` or ``mean`` ...
python
def reduce(x, op='sum'): import warnings warnings.warn( "Deprecated API. Use ``sum`` or ``mean`` instead.", DeprecationWarning) from .function_bases import reduce_sum, reduce_mean if op == 'sum': return reduce_sum(x) elif op == 'mean': return reduce_mean(x) raise ValueErr...
[ "def", "reduce", "(", "x", ",", "op", "=", "'sum'", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Deprecated API. Use ``sum`` or ``mean`` instead.\"", ",", "DeprecationWarning", ")", "from", ".", "function_bases", "import", "reduce_sum", ",", "r...
Reduction function with given operation. Args: x (Variable): An input. op (str): 'sum' or 'mean'. Note: This is deprecated. Use ``mean`` or ``sum`` instead.
[ "Reduction", "function", "with", "given", "operation", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L186-L205
242,677
sony/nnabla
python/src/nnabla/functions.py
split
def split(x, axis=0): """ Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variab...
python
def split(x, axis=0): from .function_bases import split as split_base return split_base(x, axis, x.shape[axis])
[ "def", "split", "(", "x", ",", "axis", "=", "0", ")", ":", "from", ".", "function_bases", "import", "split", "as", "split_base", "return", "split_base", "(", "x", ",", "axis", ",", "x", ".", "shape", "[", "axis", "]", ")" ]
Split arrays at the specified axis. It returns a number corresponding the size of the given axis (i.e ``x.shape[axis]``) of :obj:`~nnabla.Variable` s. Args: x(~nnabla.Variable): N-D array axis(int): Axis Returns: A :obj:`tuple` of :obj:`~nnabla.Variable` s See Also: :func...
[ "Split", "arrays", "at", "the", "specified", "axis", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L208-L226
242,678
sony/nnabla
python/src/nnabla/functions.py
batch_normalization
def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None): r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\ri...
python
def batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None): r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\ri...
[ "def", "batch_normalization", "(", "x", ",", "beta", ",", "gamma", ",", "mean", ",", "variance", ",", "axes", "=", "[", "1", "]", ",", "decay_rate", "=", "0.9", ",", "eps", "=", "1e-05", ",", "batch_stat", "=", "True", ",", "output_stat", "=", "False...
r""" Batch normalization. .. math:: \begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\right)^2 \\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\ y_i &=& \hat{x}_i \gamma + \beta. \end{eqnarray} ...
[ "r", "Batch", "normalization", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L278-L380
242,679
sony/nnabla
python/src/nnabla/functions.py
fixed_point_quantize
def fixed_point_quantize(x, sign=True, n=8, delta=2**-4, quantize=True, ste_fine_grained=True, outputs=None): r"""Fixed Point Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. n (int): Bit width used. Note th...
python
def fixed_point_quantize(x, sign=True, n=8, delta=2**-4, quantize=True, ste_fine_grained=True, outputs=None): r"""Fixed Point Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. n (int): Bit width used. Note th...
[ "def", "fixed_point_quantize", "(", "x", ",", "sign", "=", "True", ",", "n", "=", "8", ",", "delta", "=", "2", "**", "-", "4", ",", "quantize", "=", "True", ",", "ste_fine_grained", "=", "True", ",", "outputs", "=", "None", ")", ":", "from", ".", ...
r"""Fixed Point Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. n (int): Bit width used. Note that `sign` consumes one bit. :math:`n-1` is used for number representation in `signed` case. delta (floa...
[ "r", "Fixed", "Point", "Quantize" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L424-L488
242,680
sony/nnabla
python/src/nnabla/functions.py
pow2_quantize
def pow2_quantize(x, sign=True, with_zero=True, n=8, m=1, quantize=True, ste_fine_grained=True, outputs=None): r"""Pow2 Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. with_zero (bool): Indicate using zero ...
python
def pow2_quantize(x, sign=True, with_zero=True, n=8, m=1, quantize=True, ste_fine_grained=True, outputs=None): r"""Pow2 Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. with_zero (bool): Indicate using zero ...
[ "def", "pow2_quantize", "(", "x", ",", "sign", "=", "True", ",", "with_zero", "=", "True", ",", "n", "=", "8", ",", "m", "=", "1", ",", "quantize", "=", "True", ",", "ste_fine_grained", "=", "True", ",", "outputs", "=", "None", ")", ":", "from", ...
r"""Pow2 Quantize Args: x (Variable): An input variable. sign (bool): Indicate the signed number or the unsigned number. Default is true. with_zero (bool): Indicate using zero as a quantized value. Default is true. Note that `zero` consumes one bit. n (int): Bit width used. Note tha...
[ "r", "Pow2", "Quantize" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L491-L584
242,681
sony/nnabla
python/src/nnabla/functions.py
clip_by_value
def clip_by_value(x, min, max): r"""Clip inputs by values. .. math:: y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}. Args: x (Variable): An input variable. min (Variable): A min variab...
python
def clip_by_value(x, min, max): r"""Clip inputs by values. .. math:: y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}. Args: x (Variable): An input variable. min (Variable): A min variab...
[ "def", "clip_by_value", "(", "x", ",", "min", ",", "max", ")", ":", "from", ".", "function_bases", "import", "maximum2", "as", "maximum2_base", "from", ".", "function_bases", "import", "minimum2", "as", "minimum2_base", "return", "minimum2_base", "(", "maximum2_...
r"""Clip inputs by values. .. math:: y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}. Args: x (Variable): An input variable. min (Variable): A min variable by which `x` is clipped. Note tha...
[ "r", "Clip", "inputs", "by", "values", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L587-L609
242,682
sony/nnabla
python/src/nnabla/functions.py
interpolate
def interpolate(x, scale=None, output_size=None, mode='linear', align_corners=None): ''' Resize an ND array with interpolation. Scaling factors for spatial dimensions are determined by either ``scale`` or ``output_size``. ``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of ...
python
def interpolate(x, scale=None, output_size=None, mode='linear', align_corners=None): ''' Resize an ND array with interpolation. Scaling factors for spatial dimensions are determined by either ``scale`` or ``output_size``. ``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of ...
[ "def", "interpolate", "(", "x", ",", "scale", "=", "None", ",", "output_size", "=", "None", ",", "mode", "=", "'linear'", ",", "align_corners", "=", "None", ")", ":", "from", ".", "function_bases", "import", "interpolate", "as", "interpolate_base", "import",...
Resize an ND array with interpolation. Scaling factors for spatial dimensions are determined by either ``scale`` or ``output_size``. ``nd = len(scale)`` or ``nd = len(output_size)`` determines the number of spatial dimensions, and the last ``nd`` dimensions of the input ``x`` are considered as...
[ "Resize", "an", "ND", "array", "with", "interpolation", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L654-L724
242,683
sony/nnabla
python/src/nnabla/functions.py
sort
def sort(x, axis=-1, reverse=False, with_index=False, only_index=False): """Sorts the elements of `x` along a given `axis` in ascending order by value. A negative `axis` counts from the last dimension of `x`, so the default of -1 sorts along the last dimension. If `reverse` is True, then the elements ar...
python
def sort(x, axis=-1, reverse=False, with_index=False, only_index=False): from .function_bases import sort as sort_base n_outputs = 2 if with_index and not only_index else 1 return sort_base(x, axis, reverse, with_index, only_index, n_outputs)
[ "def", "sort", "(", "x", ",", "axis", "=", "-", "1", ",", "reverse", "=", "False", ",", "with_index", "=", "False", ",", "only_index", "=", "False", ")", ":", "from", ".", "function_bases", "import", "sort", "as", "sort_base", "n_outputs", "=", "2", ...
Sorts the elements of `x` along a given `axis` in ascending order by value. A negative `axis` counts from the last dimension of `x`, so the default of -1 sorts along the last dimension. If `reverse` is True, then the elements are soreted in descending order. If `with_index` is True, result is a tuple `...
[ "Sorts", "the", "elements", "of", "x", "along", "a", "given", "axis", "in", "ascending", "order", "by", "value", ".", "A", "negative", "axis", "counts", "from", "the", "last", "dimension", "of", "x", "so", "the", "default", "of", "-", "1", "sorts", "al...
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/functions.py#L727-L768
242,684
sony/nnabla
python/src/nnabla/utils/download.py
download
def download(url, output_file=None, open_file=True, allow_overwrite=False): '''Download a file from URL. Args: url (str): URL. output_file (str, optional): If given, the downloaded file is written to the given path. open_file (bool): If True, it returns an opened file stream of the down...
python
def download(url, output_file=None, open_file=True, allow_overwrite=False): '''Download a file from URL. Args: url (str): URL. output_file (str, optional): If given, the downloaded file is written to the given path. open_file (bool): If True, it returns an opened file stream of the down...
[ "def", "download", "(", "url", ",", "output_file", "=", "None", ",", "open_file", "=", "True", ",", "allow_overwrite", "=", "False", ")", ":", "filename", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "output_file", "is", "None...
Download a file from URL. Args: url (str): URL. output_file (str, optional): If given, the downloaded file is written to the given path. open_file (bool): If True, it returns an opened file stream of the downloaded file. allow_overwrite (bool): If True, it overwrites an existing fil...
[ "Download", "a", "file", "from", "URL", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/download.py#L35-L80
242,685
sony/nnabla
python/src/nnabla/utils/image_utils/cv2_utils.py
imread
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1): """ Read image by cv2 module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): (...
python
def imread(path, grayscale=False, size=None, interpolate="bilinear", channel_first=False, as_uint16=False, num_channels=-1): _imread_before(grayscale, num_channels) r_mode = cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_UNCHANGED img = _imread_helper(path, r_mode) if as_uint16 and img.d...
[ "def", "imread", "(", "path", ",", "grayscale", "=", "False", ",", "size", "=", "None", ",", "interpolate", "=", "\"bilinear\"", ",", "channel_first", "=", "False", ",", "as_uint16", "=", "False", ",", "num_channels", "=", "-", "1", ")", ":", "_imread_be...
Read image by cv2 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 specifie...
[ "Read", "image", "by", "cv2", "module", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/image_utils/cv2_utils.py#L105-L149
242,686
sony/nnabla
python/src/nnabla/utils/learning_rate_scheduler.py
PolynomialScheduler.get_learning_rate
def get_learning_rate(self, iter): ''' Get learning rate with polymomial decay based on current iteration. Args: iter (int): current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((1.0 - iter * 1.0 / self.ma...
python
def get_learning_rate(self, iter): ''' Get learning rate with polymomial decay based on current iteration. Args: iter (int): current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((1.0 - iter * 1.0 / self.ma...
[ "def", "get_learning_rate", "(", "self", ",", "iter", ")", ":", "return", "self", ".", "init_lr", "*", "(", "(", "1.0", "-", "iter", "*", "1.0", "/", "self", ".", "max_iter", ")", "**", "self", ".", "power", ")" ]
Get learning rate with polymomial decay based on current iteration. Args: iter (int): current iteration (starting with 0). Returns: float: Learning rate
[ "Get", "learning", "rate", "with", "polymomial", "decay", "based", "on", "current", "iteration", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/learning_rate_scheduler.py#L59-L69
242,687
sony/nnabla
python/src/nnabla/utils/learning_rate_scheduler.py
CosineScheduler.get_learning_rate
def get_learning_rate(self, iter): ''' Get learning rate with cosine decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((math.cos(iter * 1.0 / (self.ma...
python
def get_learning_rate(self, iter): ''' Get learning rate with cosine decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate ''' return self.init_lr * ((math.cos(iter * 1.0 / (self.ma...
[ "def", "get_learning_rate", "(", "self", ",", "iter", ")", ":", "return", "self", ".", "init_lr", "*", "(", "(", "math", ".", "cos", "(", "iter", "*", "1.0", "/", "(", "self", ".", "max_iter", ")", "*", "math", ".", "pi", ")", "+", "1.0", ")", ...
Get learning rate with cosine decay based on current iteration. Args: iter (int): Current iteration (starting with 0). Returns: float: Learning rate
[ "Get", "learning", "rate", "with", "cosine", "decay", "based", "on", "current", "iteration", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/learning_rate_scheduler.py#L87-L97
242,688
sony/nnabla
python/src/nnabla/parametric_functions.py
affine
def affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): """ The affine layer, also known as the fully connected layer. Computes .. math:: {\\mathbf y} = {\\mathbf A} {\...
python
def affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): if not hasattr(n_outmaps, '__iter__'): n_outmaps = [n_outmaps] n_outmaps = list(n_outmaps) n_outmap = int(np.prod...
[ "def", "affine", "(", "inp", ",", "n_outmaps", ",", "base_axis", "=", "1", ",", "w_init", "=", "None", ",", "b_init", "=", "None", ",", "fix_parameters", "=", "False", ",", "rng", "=", "None", ",", "with_bias", "=", "True", ",", "apply_w", "=", "None...
The affine layer, also known as the fully connected layer. Computes .. math:: {\\mathbf y} = {\\mathbf A} {\\mathbf x} + {\\mathbf b}. where :math:`{\\mathbf x}, {\\mathbf y}` are the inputs and outputs respectively, and :math:`{\\mathbf A}, {\\mathbf b}` are constants. Args: inp (~nn...
[ "The", "affine", "layer", "also", "known", "as", "the", "fully", "connected", "layer", ".", "Computes" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L132-L183
242,689
sony/nnabla
python/src/nnabla/parametric_functions.py
binary_weight_affine
def binary_weight_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Binary Weight Affine, multiplier-less inner-product with a scale factor. ...
python
def binary_weight_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): if not hasattr(n_outmaps, '__iter__'): n_outmaps = [n_outmaps] n...
[ "def", "binary_weight_affine", "(", "inp", ",", "n_outmaps", ",", "base_axis", "=", "1", ",", "quantize_zero_to", "=", "1.0", ",", "w_init", "=", "None", ",", "wb_init", "=", "None", ",", "b_init", "=", "None", ",", "fix_parameters", "=", "False", ",", "...
Binary Weight Affine, multiplier-less inner-product with a scale factor. Binary Weight Affine is the affine function, but the inner product in this function is the following, .. math:: y_j = \\frac{1}{\\|\\mathbf{w}_j\\|_{\\ell_1}} \sum_{i} sign(w_{ji}) x_i Therefore :math:`sign(w_{ji})` is ...
[ "Binary", "Weight", "Affine", "multiplier", "-", "less", "inner", "-", "product", "with", "a", "scale", "factor", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L409-L488
242,690
sony/nnabla
python/src/nnabla/parametric_functions.py
inq_affine
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Incremental Network Quantization Affine Layer During training...
python
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): if not hasattr(n_outmaps, '__iter__'): n_outmaps = [n_outmaps...
[ "def", "inq_affine", "(", "inp", ",", "n_outmaps", ",", "base_axis", "=", "1", ",", "num_bits", "=", "4", ",", "inq_iterations", "=", "(", ")", ",", "selection_algorithm", "=", "'random'", ",", "seed", "=", "-", "1", ",", "w_init", "=", "None", ",", ...
Incremental Network Quantization Affine Layer During training, the weights are sequentially quantized to power-of-two values, which allows the training of a multiplierless network. Using `inq_iterations`, one can specify after how many forward passes half of the learnable weights are fixed and quantiz...
[ "Incremental", "Network", "Quantization", "Affine", "Layer" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L496-L559
242,691
sony/nnabla
python/src/nnabla/parametric_functions.py
binary_connect_convolution
def binary_connect_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False,...
python
def binary_connect_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False,...
[ "def", "binary_connect_convolution", "(", "inp", ",", "outmaps", ",", "kernel", ",", "pad", "=", "None", ",", "stride", "=", "None", ",", "dilation", "=", "None", ",", "group", "=", "1", ",", "quantize_zero_to", "=", "1.0", ",", "w_init", "=", "None", ...
Binary Connect Convolution, multiplier-less inner-product. Binary Connect Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m,...
[ "Binary", "Connect", "Convolution", "multiplier", "-", "less", "inner", "-", "product", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L942-L1022
242,692
sony/nnabla
python/src/nnabla/parametric_functions.py
inq_convolution
def inq_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=Non...
python
def inq_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=Non...
[ "def", "inq_convolution", "(", "inp", ",", "outmaps", ",", "kernel", ",", "pad", "=", "None", ",", "stride", "=", "None", ",", "dilation", "=", "None", ",", "group", "=", "1", ",", "num_bits", "=", "4", ",", "inq_iterations", "=", "(", ")", ",", "s...
Incremental Network Quantization Convolution Layer During training, the weights are sequentially quantized to power-of-two values, which allows the training of a multiplierless network. Using `inq_iterations`, one can specify after how many forward passes half of the learnable weights are fixed and qu...
[ "Incremental", "Network", "Quantization", "Convolution", "Layer" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1122-L1180
242,693
sony/nnabla
python/src/nnabla/parametric_functions.py
depthwise_convolution
def depthwise_convolution(inp, kernel, pad=None, stride=None, dilation=None, multiplier=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True): """ N-D Depthwise Convolution with a bias term. Reference: - F. Chollet...
python
def depthwise_convolution(inp, kernel, pad=None, stride=None, dilation=None, multiplier=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True): if w_init is None: w_init = UniformInitializer( calc_uniform_lim_...
[ "def", "depthwise_convolution", "(", "inp", ",", "kernel", ",", "pad", "=", "None", ",", "stride", "=", "None", ",", "dilation", "=", "None", ",", "multiplier", "=", "1", ",", "w_init", "=", "None", ",", "b_init", "=", "None", ",", "base_axis", "=", ...
N-D Depthwise Convolution with a bias term. Reference: - F. Chollet: Chollet, Francois. "Xception: Deep Learning with Depthwise Separable Convolutions. https://arxiv.org/abs/1610.02357 Args: inp (~nnabla.Variable): N-D array. kernel (:obj:`tuple` of :obj:`int`): Convolution kernel size. F...
[ "N", "-", "D", "Depthwise", "Convolution", "with", "a", "bias", "term", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1187-L1233
242,694
sony/nnabla
python/src/nnabla/parametric_functions.py
batch_normalization
def batch_normalization(inp, axes=[1], decay_rate=0.9, eps=1e-5, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None): """ Batch normalization layer. .. math:: \\begin{array}{lcl} \\mu &=& \\frac{1}{M} \\sum x_i\\\\ ...
python
def batch_normalization(inp, axes=[1], decay_rate=0.9, eps=1e-5, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None): shape_stat = [1 for _ in inp.shape] for i in range(len(axes)): shape_stat[axes[i]] = inp.shape[axes[i]] if par...
[ "def", "batch_normalization", "(", "inp", ",", "axes", "=", "[", "1", "]", ",", "decay_rate", "=", "0.9", ",", "eps", "=", "1e-5", ",", "batch_stat", "=", "True", ",", "output_stat", "=", "False", ",", "fix_parameters", "=", "False", ",", "param_init", ...
Batch normalization layer. .. math:: \\begin{array}{lcl} \\mu &=& \\frac{1}{M} \\sum x_i\\\\ \\sigma^2 &=& \\frac{1}{M} \\sum \\left(x_i - \\mu\\right)^2\\\\ \\hat{x}_i &=& \\frac{x_i - \\mu}{\\sqrt{\\sigma^2 + \\epsilon }}\\\\ y_i &= & \\hat{x}_i \\gamma + \\beta. ...
[ "Batch", "normalization", "layer", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1611-L1682
242,695
sony/nnabla
python/src/nnabla/parametric_functions.py
mean_subtraction
def mean_subtraction(inp, base_axis=1, update_running_mean=True, fix_parameters=False): """ Mean subtraction layer. It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks...
python
def mean_subtraction(inp, base_axis=1, update_running_mean=True, fix_parameters=False): assert len(inp.shape) >= base_axis shape = inp.shape[base_axis:] mean = get_parameter_or_create( "mean", shape, ConstantInitializer(0), False) t = get_parameter_or_create( "t", (1, ), ConstantInitiali...
[ "def", "mean_subtraction", "(", "inp", ",", "base_axis", "=", "1", ",", "update_running_mean", "=", "True", ",", "fix_parameters", "=", "False", ")", ":", "assert", "len", "(", "inp", ".", "shape", ")", ">=", "base_axis", "shape", "=", "inp", ".", "shape...
Mean subtraction layer. It subtracts the mean of the elements of the input array, and normalizes it to :math:`0`. Preprocessing arrays with this function has the effect of improving accuracy in various tasks such as image classification. At training time, this function is defined as .. math:: ...
[ "Mean", "subtraction", "layer", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1689-L1726
242,696
sony/nnabla
python/src/nnabla/parametric_functions.py
prelu
def prelu(inp, base_axis=1, shared=True, fix_parameters=False): """ Parametrized Rectified Linear Unit function defined as .. math:: y_i = \max(0, x_i) + w_i \min(0, -x_i) where negative slope :math:`w` is learned and can vary across channels (an axis specified with base_axis). Weights are...
python
def prelu(inp, base_axis=1, shared=True, fix_parameters=False): shape = tuple() if shared else (inp.shape[base_axis],) w = get_parameter_or_create("slope", shape, ConstantInitializer(-1), True, not fix_parameters) return F.prelu(inp, w, base_axis)
[ "def", "prelu", "(", "inp", ",", "base_axis", "=", "1", ",", "shared", "=", "True", ",", "fix_parameters", "=", "False", ")", ":", "shape", "=", "tuple", "(", ")", "if", "shared", "else", "(", "inp", ".", "shape", "[", "base_axis", "]", ",", ")", ...
Parametrized Rectified Linear Unit function defined as .. math:: y_i = \max(0, x_i) + w_i \min(0, -x_i) where negative slope :math:`w` is learned and can vary across channels (an axis specified with base_axis). Weights are initialized with :math:`-1`. Args: x(~nnabla.Variable): N-D ar...
[ "Parametrized", "Rectified", "Linear", "Unit", "function", "defined", "as" ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1762-L1786
242,697
sony/nnabla
python/src/nnabla/parametric_functions.py
fixed_point_quantized_affine
def fixed_point_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, n_w=8, delta_w=2**-4, ...
python
def fixed_point_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, n_w=8, delta_w=2**-4, ...
[ "def", "fixed_point_quantized_affine", "(", "inp", ",", "n_outmaps", ",", "base_axis", "=", "1", ",", "w_init", "=", "None", ",", "b_init", "=", "None", ",", "fix_parameters", "=", "False", ",", "rng", "=", "None", ",", "with_bias", "=", "True", ",", "qu...
Fixed-Point Quantized Affine. Fixed-Point Quantized Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the fixed-point quantiza...
[ "Fixed", "-", "Point", "Quantized", "Affine", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1795-L1901
242,698
sony/nnabla
python/src/nnabla/parametric_functions.py
fixed_point_quantized_convolution
def fixed_point_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, ...
python
def fixed_point_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, ...
[ "def", "fixed_point_quantized_convolution", "(", "inp", ",", "outmaps", ",", "kernel", ",", "pad", "=", "None", ",", "stride", "=", "None", ",", "dilation", "=", "None", ",", "group", "=", "1", ",", "w_init", "=", "None", ",", "b_init", "=", "None", ",...
Fixed-Point Quantized Convolution. Fixed-Point Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i,...
[ "Fixed", "-", "Point", "Quantized", "Convolution", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L1910-L2017
242,699
sony/nnabla
python/src/nnabla/parametric_functions.py
pow2_quantized_affine
def pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,...
python
def pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True,...
[ "def", "pow2_quantized_affine", "(", "inp", ",", "n_outmaps", ",", "base_axis", "=", "1", ",", "w_init", "=", "None", ",", "b_init", "=", "None", ",", "fix_parameters", "=", "False", ",", "rng", "=", "None", ",", "with_bias", "=", "True", ",", "quantize_...
Pow2 Quantized Affine. Pow2 Quantized Affine is the affine function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_j = \sum_{i} Q(w_{ji}) x_i, where :math:`Q(w_{ji})` is the power-of-2 quantization function. ...
[ "Pow2", "Quantized", "Affine", "." ]
aaf3d33b7cbb38f2a03aa754178ba8f7c8481320
https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parametric_functions.py#L2026-L2132