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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
tanghaibao/goatools
goatools/go_enrichment.py
GOEnrichmentStudy.print_results_adj
def print_results_adj(results, indent=False, prt=sys.stdout): """Print GOEA results.""" # Print column headers if there are results to be printed if results: prt.write("{R}\n".format(R="\t".join(GOEnrichmentStudy.get_prtflds_default(results)))) # Print the GOEA results ...
python
def print_results_adj(results, indent=False, prt=sys.stdout): """Print GOEA results.""" # Print column headers if there are results to be printed if results: prt.write("{R}\n".format(R="\t".join(GOEnrichmentStudy.get_prtflds_default(results)))) # Print the GOEA results ...
[ "def", "print_results_adj", "(", "results", ",", "indent", "=", "False", ",", "prt", "=", "sys", ".", "stdout", ")", ":", "if", "results", ":", "prt", ".", "write", "(", "\"{R}\\n\"", ".", "format", "(", "R", "=", "\"\\t\"", ".", "join", "(", "GOEnri...
Print GOEA results.
[ "Print", "GOEA", "results", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L554-L561
train
tanghaibao/goatools
goatools/go_enrichment.py
GOEnrichmentStudy.wr_py_goea_results
def wr_py_goea_results(self, fout_py, goea_results, **kws): """Save GOEA results into Python package containing list of namedtuples.""" var_name = kws.get("var_name", "goea_results") docstring = kws.get("docstring", "") sortby = kws.get("sortby", None) if goea_results: ...
python
def wr_py_goea_results(self, fout_py, goea_results, **kws): """Save GOEA results into Python package containing list of namedtuples.""" var_name = kws.get("var_name", "goea_results") docstring = kws.get("docstring", "") sortby = kws.get("sortby", None) if goea_results: ...
[ "def", "wr_py_goea_results", "(", "self", ",", "fout_py", ",", "goea_results", ",", "**", "kws", ")", ":", "var_name", "=", "kws", ".", "get", "(", "\"var_name\"", ",", "\"goea_results\"", ")", "docstring", "=", "kws", ".", "get", "(", "\"docstring\"", ","...
Save GOEA results into Python package containing list of namedtuples.
[ "Save", "GOEA", "results", "into", "Python", "package", "containing", "list", "of", "namedtuples", "." ]
407682e573a108864a79031f8ca19ee3bf377626
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L563-L581
train
tryolabs/requestium
requestium/requestium.py
_ensure_click
def _ensure_click(self): """Ensures a click gets made, because Selenium can be a bit buggy about clicks This method gets added to the selenium element returned in '__ensure_element_by_xpath'. We should probably add it to more selenium methods, such as all the 'find**' methods though. I wrote this meth...
python
def _ensure_click(self): """Ensures a click gets made, because Selenium can be a bit buggy about clicks This method gets added to the selenium element returned in '__ensure_element_by_xpath'. We should probably add it to more selenium methods, such as all the 'find**' methods though. I wrote this meth...
[ "def", "_ensure_click", "(", "self", ")", ":", "script", "=", "(", "\"var viewPortHeight = Math.max(\"", "\"document.documentElement.clientHeight, window.innerHeight || 0);\"", "\"var elementTop = arguments[0].getBoundingClientRect().top;\"", "\"window.scrollBy(0, elementTop-(viewPortHeight/...
Ensures a click gets made, because Selenium can be a bit buggy about clicks This method gets added to the selenium element returned in '__ensure_element_by_xpath'. We should probably add it to more selenium methods, such as all the 'find**' methods though. I wrote this method out of frustration with chrom...
[ "Ensures", "a", "click", "gets", "made", "because", "Selenium", "can", "be", "a", "bit", "buggy", "about", "clicks" ]
9533932ae688da26f3fb78b97b3c0b05c6f24934
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L365-L401
train
tryolabs/requestium
requestium/requestium.py
Session.transfer_session_cookies_to_driver
def transfer_session_cookies_to_driver(self, domain=None): """Copies the Session's cookies into the webdriver Using the 'domain' parameter we choose the cookies we wish to transfer, we only transfer the cookies which belong to that domain. The domain defaults to our last visited site if...
python
def transfer_session_cookies_to_driver(self, domain=None): """Copies the Session's cookies into the webdriver Using the 'domain' parameter we choose the cookies we wish to transfer, we only transfer the cookies which belong to that domain. The domain defaults to our last visited site if...
[ "def", "transfer_session_cookies_to_driver", "(", "self", ",", "domain", "=", "None", ")", ":", "if", "not", "domain", "and", "self", ".", "_last_requests_url", ":", "domain", "=", "tldextract", ".", "extract", "(", "self", ".", "_last_requests_url", ")", ".",...
Copies the Session's cookies into the webdriver Using the 'domain' parameter we choose the cookies we wish to transfer, we only transfer the cookies which belong to that domain. The domain defaults to our last visited site if not provided.
[ "Copies", "the", "Session", "s", "cookies", "into", "the", "webdriver" ]
9533932ae688da26f3fb78b97b3c0b05c6f24934
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L98-L114
train
tryolabs/requestium
requestium/requestium.py
Session.copy_user_agent_from_driver
def copy_user_agent_from_driver(self): """ Updates requests' session user-agent with the driver's user agent This method will start the browser process if its not already running. """ selenium_user_agent = self.driver.execute_script("return navigator.userAgent;") self.headers.up...
python
def copy_user_agent_from_driver(self): """ Updates requests' session user-agent with the driver's user agent This method will start the browser process if its not already running. """ selenium_user_agent = self.driver.execute_script("return navigator.userAgent;") self.headers.up...
[ "def", "copy_user_agent_from_driver", "(", "self", ")", ":", "selenium_user_agent", "=", "self", ".", "driver", ".", "execute_script", "(", "\"return navigator.userAgent;\"", ")", "self", ".", "headers", ".", "update", "(", "{", "\"user-agent\"", ":", "selenium_user...
Updates requests' session user-agent with the driver's user agent This method will start the browser process if its not already running.
[ "Updates", "requests", "session", "user", "-", "agent", "with", "the", "driver", "s", "user", "agent" ]
9533932ae688da26f3fb78b97b3c0b05c6f24934
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L138-L144
train
tryolabs/requestium
requestium/requestium.py
DriverMixin.ensure_add_cookie
def ensure_add_cookie(self, cookie, override_domain=None): """Ensures a cookie gets added to the driver Selenium needs the driver to be currently at the domain of the cookie before allowing you to add it, so we need to get through this limitation. The cookie parameter is a dict which m...
python
def ensure_add_cookie(self, cookie, override_domain=None): """Ensures a cookie gets added to the driver Selenium needs the driver to be currently at the domain of the cookie before allowing you to add it, so we need to get through this limitation. The cookie parameter is a dict which m...
[ "def", "ensure_add_cookie", "(", "self", ",", "cookie", ",", "override_domain", "=", "None", ")", ":", "if", "override_domain", ":", "cookie", "[", "'domain'", "]", "=", "override_domain", "cookie_domain", "=", "cookie", "[", "'domain'", "]", "if", "cookie", ...
Ensures a cookie gets added to the driver Selenium needs the driver to be currently at the domain of the cookie before allowing you to add it, so we need to get through this limitation. The cookie parameter is a dict which must contain the keys (name, value, domain) and may contain the...
[ "Ensures", "a", "cookie", "gets", "added", "to", "the", "driver" ]
9533932ae688da26f3fb78b97b3c0b05c6f24934
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L194-L244
train
tryolabs/requestium
requestium/requestium.py
DriverMixin.is_cookie_in_driver
def is_cookie_in_driver(self, cookie): """We check that the cookie is correctly added to the driver We only compare name, value and domain, as the rest can produce false negatives. We are a bit lenient when comparing domains. """ for driver_cookie in self.get_cookies(): ...
python
def is_cookie_in_driver(self, cookie): """We check that the cookie is correctly added to the driver We only compare name, value and domain, as the rest can produce false negatives. We are a bit lenient when comparing domains. """ for driver_cookie in self.get_cookies(): ...
[ "def", "is_cookie_in_driver", "(", "self", ",", "cookie", ")", ":", "for", "driver_cookie", "in", "self", ".", "get_cookies", "(", ")", ":", "if", "(", "cookie", "[", "'name'", "]", "==", "driver_cookie", "[", "'name'", "]", "and", "cookie", "[", "'value...
We check that the cookie is correctly added to the driver We only compare name, value and domain, as the rest can produce false negatives. We are a bit lenient when comparing domains.
[ "We", "check", "that", "the", "cookie", "is", "correctly", "added", "to", "the", "driver" ]
9533932ae688da26f3fb78b97b3c0b05c6f24934
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L246-L258
train
tryolabs/requestium
requestium/requestium.py
DriverMixin.ensure_element
def ensure_element(self, locator, selector, state="present", timeout=None): """This method allows us to wait till an element appears or disappears in the browser The webdriver runs in parallel with our scripts, so we must wait for it everytime it runs javascript. Selenium automatically waits ti...
python
def ensure_element(self, locator, selector, state="present", timeout=None): """This method allows us to wait till an element appears or disappears in the browser The webdriver runs in parallel with our scripts, so we must wait for it everytime it runs javascript. Selenium automatically waits ti...
[ "def", "ensure_element", "(", "self", ",", "locator", ",", "selector", ",", "state", "=", "\"present\"", ",", "timeout", "=", "None", ")", ":", "locators", "=", "{", "'id'", ":", "By", ".", "ID", ",", "'name'", ":", "By", ".", "NAME", ",", "'xpath'",...
This method allows us to wait till an element appears or disappears in the browser The webdriver runs in parallel with our scripts, so we must wait for it everytime it runs javascript. Selenium automatically waits till a page loads when GETing it, but it doesn't do this when it runs javascript ...
[ "This", "method", "allows", "us", "to", "wait", "till", "an", "element", "appears", "or", "disappears", "in", "the", "browser" ]
9533932ae688da26f3fb78b97b3c0b05c6f24934
https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L284-L342
train
Belval/pdf2image
pdf2image/parsers.py
parse_buffer_to_ppm
def parse_buffer_to_ppm(data): """ Parse PPM file bytes to Pillow Image """ images = [] index = 0 while index < len(data): code, size, rgb = tuple(data[index:index + 40].split(b'\n')[0:3]) size_x, size_y = tuple(size.split(b' ')) file_size = len(code) + len(size) +...
python
def parse_buffer_to_ppm(data): """ Parse PPM file bytes to Pillow Image """ images = [] index = 0 while index < len(data): code, size, rgb = tuple(data[index:index + 40].split(b'\n')[0:3]) size_x, size_y = tuple(size.split(b' ')) file_size = len(code) + len(size) +...
[ "def", "parse_buffer_to_ppm", "(", "data", ")", ":", "images", "=", "[", "]", "index", "=", "0", "while", "index", "<", "len", "(", "data", ")", ":", "code", ",", "size", ",", "rgb", "=", "tuple", "(", "data", "[", "index", ":", "index", "+", "40...
Parse PPM file bytes to Pillow Image
[ "Parse", "PPM", "file", "bytes", "to", "Pillow", "Image" ]
48ea7ac36ad67e1f9b06593b67d7cdf2c337505c
https://github.com/Belval/pdf2image/blob/48ea7ac36ad67e1f9b06593b67d7cdf2c337505c/pdf2image/parsers.py#L9-L25
train
Belval/pdf2image
pdf2image/parsers.py
parse_buffer_to_jpeg
def parse_buffer_to_jpeg(data): """ Parse JPEG file bytes to Pillow Image """ return [ Image.open(BytesIO(image_data + b'\xff\xd9')) for image_data in data.split(b'\xff\xd9')[:-1] # Last element is obviously empty ]
python
def parse_buffer_to_jpeg(data): """ Parse JPEG file bytes to Pillow Image """ return [ Image.open(BytesIO(image_data + b'\xff\xd9')) for image_data in data.split(b'\xff\xd9')[:-1] # Last element is obviously empty ]
[ "def", "parse_buffer_to_jpeg", "(", "data", ")", ":", "return", "[", "Image", ".", "open", "(", "BytesIO", "(", "image_data", "+", "b'\\xff\\xd9'", ")", ")", "for", "image_data", "in", "data", ".", "split", "(", "b'\\xff\\xd9'", ")", "[", ":", "-", "1", ...
Parse JPEG file bytes to Pillow Image
[ "Parse", "JPEG", "file", "bytes", "to", "Pillow", "Image" ]
48ea7ac36ad67e1f9b06593b67d7cdf2c337505c
https://github.com/Belval/pdf2image/blob/48ea7ac36ad67e1f9b06593b67d7cdf2c337505c/pdf2image/parsers.py#L27-L35
train
Belval/pdf2image
pdf2image/parsers.py
parse_buffer_to_png
def parse_buffer_to_png(data): """ Parse PNG file bytes to Pillow Image """ images = [] c1 = 0 c2 = 0 data_len = len(data) while c1 < data_len: # IEND can appear in a PNG without being the actual end if data[c2:c2 + 4] == b'IEND' and (c2 + 8 == data_len or data[c2+9...
python
def parse_buffer_to_png(data): """ Parse PNG file bytes to Pillow Image """ images = [] c1 = 0 c2 = 0 data_len = len(data) while c1 < data_len: # IEND can appear in a PNG without being the actual end if data[c2:c2 + 4] == b'IEND' and (c2 + 8 == data_len or data[c2+9...
[ "def", "parse_buffer_to_png", "(", "data", ")", ":", "images", "=", "[", "]", "c1", "=", "0", "c2", "=", "0", "data_len", "=", "len", "(", "data", ")", "while", "c1", "<", "data_len", ":", "if", "data", "[", "c2", ":", "c2", "+", "4", "]", "=="...
Parse PNG file bytes to Pillow Image
[ "Parse", "PNG", "file", "bytes", "to", "Pillow", "Image" ]
48ea7ac36ad67e1f9b06593b67d7cdf2c337505c
https://github.com/Belval/pdf2image/blob/48ea7ac36ad67e1f9b06593b67d7cdf2c337505c/pdf2image/parsers.py#L37-L55
train
wal-e/wal-e
wal_e/log_help.py
configure
def configure(*args, **kwargs): """ Configure logging. Borrowed from logging.basicConfig Uses the IndentFormatter instead of the regular Formatter Also, opts the caller into Syslog output, unless syslog could not be opened for some reason or another, in which case a warning will be printe...
python
def configure(*args, **kwargs): """ Configure logging. Borrowed from logging.basicConfig Uses the IndentFormatter instead of the regular Formatter Also, opts the caller into Syslog output, unless syslog could not be opened for some reason or another, in which case a warning will be printe...
[ "def", "configure", "(", "*", "args", ",", "**", "kwargs", ")", ":", "assert", "len", "(", "HANDLERS", ")", "==", "0", "log_destinations", "=", "get_log_destinations", "(", ")", "if", "'stderr'", "in", "log_destinations", ":", "HANDLERS", ".", "append", "(...
Configure logging. Borrowed from logging.basicConfig Uses the IndentFormatter instead of the regular Formatter Also, opts the caller into Syslog output, unless syslog could not be opened for some reason or another, in which case a warning will be printed to the other log handlers.
[ "Configure", "logging", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/log_help.py#L32-L108
train
wal-e/wal-e
wal_e/log_help.py
get_syslog_facility
def get_syslog_facility(): """Get syslog facility from ENV var""" facil = os.getenv('WALE_SYSLOG_FACILITY', 'user') valid_facility = True try: facility = handlers.SysLogHandler.facility_names[facil.lower()] except KeyError: valid_facility = False facility = handlers.SysLogHa...
python
def get_syslog_facility(): """Get syslog facility from ENV var""" facil = os.getenv('WALE_SYSLOG_FACILITY', 'user') valid_facility = True try: facility = handlers.SysLogHandler.facility_names[facil.lower()] except KeyError: valid_facility = False facility = handlers.SysLogHa...
[ "def", "get_syslog_facility", "(", ")", ":", "facil", "=", "os", ".", "getenv", "(", "'WALE_SYSLOG_FACILITY'", ",", "'user'", ")", "valid_facility", "=", "True", "try", ":", "facility", "=", "handlers", ".", "SysLogHandler", ".", "facility_names", "[", "facil"...
Get syslog facility from ENV var
[ "Get", "syslog", "facility", "from", "ENV", "var" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/log_help.py#L118-L129
train
wal-e/wal-e
wal_e/log_help.py
set_level
def set_level(level): """Adjust the logging level of WAL-E""" for handler in HANDLERS: handler.setLevel(level) logging.root.setLevel(level)
python
def set_level(level): """Adjust the logging level of WAL-E""" for handler in HANDLERS: handler.setLevel(level) logging.root.setLevel(level)
[ "def", "set_level", "(", "level", ")", ":", "for", "handler", "in", "HANDLERS", ":", "handler", ".", "setLevel", "(", "level", ")", "logging", ".", "root", ".", "setLevel", "(", "level", ")" ]
Adjust the logging level of WAL-E
[ "Adjust", "the", "logging", "level", "of", "WAL", "-", "E" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/log_help.py#L132-L137
train
wal-e/wal-e
wal_e/log_help.py
IndentFormatter.format
def format(self, record, *args, **kwargs): """ Format a message in the log Act like the normal format, but indent anything that is a newline within the message. """ return logging.Formatter.format( self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8)
python
def format(self, record, *args, **kwargs): """ Format a message in the log Act like the normal format, but indent anything that is a newline within the message. """ return logging.Formatter.format( self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8)
[ "def", "format", "(", "self", ",", "record", ",", "*", "args", ",", "**", "kwargs", ")", ":", "return", "logging", ".", "Formatter", ".", "format", "(", "self", ",", "record", ",", "*", "args", ",", "**", "kwargs", ")", ".", "replace", "(", "'\\n'"...
Format a message in the log Act like the normal format, but indent anything that is a newline within the message.
[ "Format", "a", "message", "in", "the", "log" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/log_help.py#L20-L29
train
wal-e/wal-e
wal_e/tar_partition.py
_segmentation_guts
def _segmentation_guts(root, file_paths, max_partition_size): """Segment a series of file paths into TarPartition values These TarPartitions are disjoint and roughly below the prescribed size. """ # Canonicalize root to include the trailing slash, since root is # intended to be a directory anyw...
python
def _segmentation_guts(root, file_paths, max_partition_size): """Segment a series of file paths into TarPartition values These TarPartitions are disjoint and roughly below the prescribed size. """ # Canonicalize root to include the trailing slash, since root is # intended to be a directory anyw...
[ "def", "_segmentation_guts", "(", "root", ",", "file_paths", ",", "max_partition_size", ")", ":", "if", "not", "root", ".", "endswith", "(", "os", ".", "path", ".", "sep", ")", ":", "root", "+=", "os", ".", "path", ".", "sep", "if", "not", "os", ".",...
Segment a series of file paths into TarPartition values These TarPartitions are disjoint and roughly below the prescribed size.
[ "Segment", "a", "series", "of", "file", "paths", "into", "TarPartition", "values" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/tar_partition.py#L351-L444
train
wal-e/wal-e
wal_e/tar_partition.py
TarPartition.tarfile_extract
def tarfile_extract(fileobj, dest_path): """Extract a tarfile described by a file object to a specified path. Args: fileobj (file): File object wrapping the target tarfile. dest_path (str): Path to extract the contents of the tarfile to. """ # Though this method ...
python
def tarfile_extract(fileobj, dest_path): """Extract a tarfile described by a file object to a specified path. Args: fileobj (file): File object wrapping the target tarfile. dest_path (str): Path to extract the contents of the tarfile to. """ # Though this method ...
[ "def", "tarfile_extract", "(", "fileobj", ",", "dest_path", ")", ":", "tar", "=", "tarfile", ".", "open", "(", "mode", "=", "'r|'", ",", "fileobj", "=", "fileobj", ",", "bufsize", "=", "pipebuf", ".", "PIPE_BUF_BYTES", ")", "dest_path", "=", "os", ".", ...
Extract a tarfile described by a file object to a specified path. Args: fileobj (file): File object wrapping the target tarfile. dest_path (str): Path to extract the contents of the tarfile to.
[ "Extract", "a", "tarfile", "described", "by", "a", "file", "object", "to", "a", "specified", "path", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/tar_partition.py#L258-L312
train
wal-e/wal-e
wal_e/operator/backup.py
Backup.backup_list
def backup_list(self, query, detail): """ Lists base backups and basic information about them """ import csv from wal_e.storage.base import BackupInfo bl = self._backup_list(detail) # If there is no query, return an exhaustive list, otherwise # find a ba...
python
def backup_list(self, query, detail): """ Lists base backups and basic information about them """ import csv from wal_e.storage.base import BackupInfo bl = self._backup_list(detail) # If there is no query, return an exhaustive list, otherwise # find a ba...
[ "def", "backup_list", "(", "self", ",", "query", ",", "detail", ")", ":", "import", "csv", "from", "wal_e", ".", "storage", ".", "base", "import", "BackupInfo", "bl", "=", "self", ".", "_backup_list", "(", "detail", ")", "if", "query", "is", "None", ":...
Lists base backups and basic information about them
[ "Lists", "base", "backups", "and", "basic", "information", "about", "them" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L46-L69
train
wal-e/wal-e
wal_e/operator/backup.py
Backup.database_backup
def database_backup(self, data_directory, *args, **kwargs): """Uploads a PostgreSQL file cluster to S3 or Windows Azure Blob Service Mechanism: just wraps _upload_pg_cluster_dir with start/stop backup actions with exception handling. In particular there is a 'finally' block to ...
python
def database_backup(self, data_directory, *args, **kwargs): """Uploads a PostgreSQL file cluster to S3 or Windows Azure Blob Service Mechanism: just wraps _upload_pg_cluster_dir with start/stop backup actions with exception handling. In particular there is a 'finally' block to ...
[ "def", "database_backup", "(", "self", ",", "data_directory", ",", "*", "args", ",", "**", "kwargs", ")", ":", "upload_good", "=", "False", "backup_stop_good", "=", "False", "while_offline", "=", "False", "start_backup_info", "=", "None", "if", "'while_offline'"...
Uploads a PostgreSQL file cluster to S3 or Windows Azure Blob Service Mechanism: just wraps _upload_pg_cluster_dir with start/stop backup actions with exception handling. In particular there is a 'finally' block to stop the backup in most situations.
[ "Uploads", "a", "PostgreSQL", "file", "cluster", "to", "S3", "or", "Windows", "Azure", "Blob", "Service" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L158-L246
train
wal-e/wal-e
wal_e/operator/backup.py
Backup.wal_archive
def wal_archive(self, wal_path, concurrency=1): """ Uploads a WAL file to S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's archive_command feature. """ # Upload the segment expressly indicated. It's special # relativ...
python
def wal_archive(self, wal_path, concurrency=1): """ Uploads a WAL file to S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's archive_command feature. """ # Upload the segment expressly indicated. It's special # relativ...
[ "def", "wal_archive", "(", "self", ",", "wal_path", ",", "concurrency", "=", "1", ")", ":", "xlog_dir", "=", "os", ".", "path", ".", "dirname", "(", "wal_path", ")", "segment", "=", "WalSegment", "(", "wal_path", ",", "explicit", "=", "True", ")", "upl...
Uploads a WAL file to S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's archive_command feature.
[ "Uploads", "a", "WAL", "file", "to", "S3", "or", "Windows", "Azure", "Blob", "Service" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L248-L291
train
wal-e/wal-e
wal_e/operator/backup.py
Backup.wal_restore
def wal_restore(self, wal_name, wal_destination, prefetch_max): """ Downloads a WAL file from S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's restore_command feature. NB: Postgres doesn't guarantee that wal_name == basename(...
python
def wal_restore(self, wal_name, wal_destination, prefetch_max): """ Downloads a WAL file from S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's restore_command feature. NB: Postgres doesn't guarantee that wal_name == basename(...
[ "def", "wal_restore", "(", "self", ",", "wal_name", ",", "wal_destination", ",", "prefetch_max", ")", ":", "url", "=", "'{0}://{1}/{2}'", ".", "format", "(", "self", ".", "layout", ".", "scheme", ",", "self", ".", "layout", ".", "store_name", "(", ")", "...
Downloads a WAL file from S3 or Windows Azure Blob Service This code is intended to typically be called from Postgres's restore_command feature. NB: Postgres doesn't guarantee that wal_name == basename(wal_path), so both are required.
[ "Downloads", "a", "WAL", "file", "from", "S3", "or", "Windows", "Azure", "Blob", "Service" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L293-L363
train
wal-e/wal-e
wal_e/operator/backup.py
Backup._upload_pg_cluster_dir
def _upload_pg_cluster_dir(self, start_backup_info, pg_cluster_dir, version, pool_size, rate_limit=None): """ Upload to url_prefix from pg_cluster_dir This function ignores the directory pg_xlog, which contains WAL files and are not generally part of a bas...
python
def _upload_pg_cluster_dir(self, start_backup_info, pg_cluster_dir, version, pool_size, rate_limit=None): """ Upload to url_prefix from pg_cluster_dir This function ignores the directory pg_xlog, which contains WAL files and are not generally part of a bas...
[ "def", "_upload_pg_cluster_dir", "(", "self", ",", "start_backup_info", ",", "pg_cluster_dir", ",", "version", ",", "pool_size", ",", "rate_limit", "=", "None", ")", ":", "spec", ",", "parts", "=", "tar_partition", ".", "partition", "(", "pg_cluster_dir", ")", ...
Upload to url_prefix from pg_cluster_dir This function ignores the directory pg_xlog, which contains WAL files and are not generally part of a base backup. Note that this is also lzo compresses the files: thus, the number of pooled processes involves doing a full sequential scan of the...
[ "Upload", "to", "url_prefix", "from", "pg_cluster_dir" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L430-L506
train
wal-e/wal-e
wal_e/operator/backup.py
Backup._exception_gather_guard
def _exception_gather_guard(self, fn): """ A higher order function to trap UserExceptions and then log them. This is to present nicer output to the user when failures are occuring in another thread of execution that may not end up at the catch-all try/except in main(). "...
python
def _exception_gather_guard(self, fn): """ A higher order function to trap UserExceptions and then log them. This is to present nicer output to the user when failures are occuring in another thread of execution that may not end up at the catch-all try/except in main(). "...
[ "def", "_exception_gather_guard", "(", "self", ",", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "**", "kwargs"...
A higher order function to trap UserExceptions and then log them. This is to present nicer output to the user when failures are occuring in another thread of execution that may not end up at the catch-all try/except in main().
[ "A", "higher", "order", "function", "to", "trap", "UserExceptions", "and", "then", "log", "them", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/operator/backup.py#L508-L524
train
wal-e/wal-e
wal_e/worker/prefetch.py
Dirs.create
def create(self, segment): """A best-effort attempt to create directories. Warnings are issued to the user if those directories could not created or if they don't exist. The caller should only call this function if the user requested prefetching (i.e. concurrency) to avoid spur...
python
def create(self, segment): """A best-effort attempt to create directories. Warnings are issued to the user if those directories could not created or if they don't exist. The caller should only call this function if the user requested prefetching (i.e. concurrency) to avoid spur...
[ "def", "create", "(", "self", ",", "segment", ")", ":", "def", "lackadaisical_mkdir", "(", "place", ")", ":", "ok", "=", "False", "place", "=", "path", ".", "realpath", "(", "place", ")", "try", ":", "os", ".", "makedirs", "(", "place", ",", "0o700",...
A best-effort attempt to create directories. Warnings are issued to the user if those directories could not created or if they don't exist. The caller should only call this function if the user requested prefetching (i.e. concurrency) to avoid spurious warnings.
[ "A", "best", "-", "effort", "attempt", "to", "create", "directories", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/prefetch.py#L91-L128
train
wal-e/wal-e
wal_e/pep3143daemon/pidfile.py
PidFile.acquire
def acquire(self): """Acquire the pidfile. Create the pidfile, lock it, write the pid into it and register the release with atexit. :return: None :raise: SystemExit """ try: pidfile = open(self._pidfile, "a") except IOError as err: ...
python
def acquire(self): """Acquire the pidfile. Create the pidfile, lock it, write the pid into it and register the release with atexit. :return: None :raise: SystemExit """ try: pidfile = open(self._pidfile, "a") except IOError as err: ...
[ "def", "acquire", "(", "self", ")", ":", "try", ":", "pidfile", "=", "open", "(", "self", ".", "_pidfile", ",", "\"a\"", ")", "except", "IOError", "as", "err", ":", "raise", "SystemExit", "(", "err", ")", "try", ":", "fcntl", ".", "flock", "(", "pi...
Acquire the pidfile. Create the pidfile, lock it, write the pid into it and register the release with atexit. :return: None :raise: SystemExit
[ "Acquire", "the", "pidfile", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/pidfile.py#L44-L67
train
wal-e/wal-e
wal_e/pep3143daemon/pidfile.py
PidFile.release
def release(self): """Release the pidfile. Close and delete the Pidfile. :return: None """ try: self.pidfile.close() os.remove(self._pidfile) except OSError as err: if err.errno != 2: raise
python
def release(self): """Release the pidfile. Close and delete the Pidfile. :return: None """ try: self.pidfile.close() os.remove(self._pidfile) except OSError as err: if err.errno != 2: raise
[ "def", "release", "(", "self", ")", ":", "try", ":", "self", ".", "pidfile", ".", "close", "(", ")", "os", ".", "remove", "(", "self", ".", "_pidfile", ")", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "!=", "2", ":", "raise"...
Release the pidfile. Close and delete the Pidfile. :return: None
[ "Release", "the", "pidfile", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/pidfile.py#L69-L82
train
wal-e/wal-e
wal_e/pipebuf.py
_configure_buffer_sizes
def _configure_buffer_sizes(): """Set up module globals controlling buffer sizes""" global PIPE_BUF_BYTES global OS_PIPE_SZ PIPE_BUF_BYTES = 65536 OS_PIPE_SZ = None # Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism, # but a good one that can drastically reduce the numbe...
python
def _configure_buffer_sizes(): """Set up module globals controlling buffer sizes""" global PIPE_BUF_BYTES global OS_PIPE_SZ PIPE_BUF_BYTES = 65536 OS_PIPE_SZ = None # Teach the 'fcntl' module about 'F_SETPIPE_SZ', which is a Linux-ism, # but a good one that can drastically reduce the numbe...
[ "def", "_configure_buffer_sizes", "(", ")", ":", "global", "PIPE_BUF_BYTES", "global", "OS_PIPE_SZ", "PIPE_BUF_BYTES", "=", "65536", "OS_PIPE_SZ", "=", "None", "if", "not", "hasattr", "(", "fcntl", ",", "'F_SETPIPE_SZ'", ")", ":", "import", "platform", "if", "pl...
Set up module globals controlling buffer sizes
[ "Set", "up", "module", "globals", "controlling", "buffer", "sizes" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pipebuf.py#L18-L44
train
wal-e/wal-e
wal_e/pipebuf.py
set_buf_size
def set_buf_size(fd): """Set up os pipe buffer size, if applicable""" if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'): fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ)
python
def set_buf_size(fd): """Set up os pipe buffer size, if applicable""" if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'): fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ)
[ "def", "set_buf_size", "(", "fd", ")", ":", "if", "OS_PIPE_SZ", "and", "hasattr", "(", "fcntl", ",", "'F_SETPIPE_SZ'", ")", ":", "fcntl", ".", "fcntl", "(", "fd", ",", "fcntl", ".", "F_SETPIPE_SZ", ",", "OS_PIPE_SZ", ")" ]
Set up os pipe buffer size, if applicable
[ "Set", "up", "os", "pipe", "buffer", "size", "if", "applicable" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pipebuf.py#L50-L53
train
wal-e/wal-e
wal_e/worker/pg/wal_transfer.py
WalSegment.mark_done
def mark_done(self): """Mark the archive status of this segment as 'done'. This is most useful when performing out-of-band parallel uploads of segments, so that Postgres doesn't try to go and upload them again. This amounts to messing with an internal bookkeeping mechanism ...
python
def mark_done(self): """Mark the archive status of this segment as 'done'. This is most useful when performing out-of-band parallel uploads of segments, so that Postgres doesn't try to go and upload them again. This amounts to messing with an internal bookkeeping mechanism ...
[ "def", "mark_done", "(", "self", ")", ":", "if", "self", ".", "explicit", ":", "raise", "UserCritical", "(", "msg", "=", "'unexpected attempt to modify wal metadata detected'", ",", "detail", "=", "(", "'Segments explicitly passed from postgres should not '", "'engage in ...
Mark the archive status of this segment as 'done'. This is most useful when performing out-of-band parallel uploads of segments, so that Postgres doesn't try to go and upload them again. This amounts to messing with an internal bookkeeping mechanism of Postgres, but that mechan...
[ "Mark", "the", "archive", "status", "of", "this", "segment", "as", "done", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/wal_transfer.py#L30-L65
train
wal-e/wal-e
wal_e/worker/pg/wal_transfer.py
WalTransferGroup.join
def join(self): """Wait for transfer to exit, raising errors as necessary.""" self.closed = True while self.expect > 0: val = self.wait_change.get() self.expect -= 1 if val is not None: # Wait a while for all running greenlets to exit, and ...
python
def join(self): """Wait for transfer to exit, raising errors as necessary.""" self.closed = True while self.expect > 0: val = self.wait_change.get() self.expect -= 1 if val is not None: # Wait a while for all running greenlets to exit, and ...
[ "def", "join", "(", "self", ")", ":", "self", ".", "closed", "=", "True", "while", "self", ".", "expect", ">", "0", ":", "val", "=", "self", ".", "wait_change", ".", "get", "(", ")", "self", ".", "expect", "-=", "1", "if", "val", "is", "not", "...
Wait for transfer to exit, raising errors as necessary.
[ "Wait", "for", "transfer", "to", "exit", "raising", "errors", "as", "necessary", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/wal_transfer.py#L130-L144
train
wal-e/wal-e
wal_e/worker/pg/wal_transfer.py
WalTransferGroup.start
def start(self, segment): """Begin transfer for an indicated wal segment.""" if self.closed: raise UserCritical(msg='attempt to transfer wal after closing', hint='report a bug') g = gevent.Greenlet(self.transferer, segment) g.link(self._comple...
python
def start(self, segment): """Begin transfer for an indicated wal segment.""" if self.closed: raise UserCritical(msg='attempt to transfer wal after closing', hint='report a bug') g = gevent.Greenlet(self.transferer, segment) g.link(self._comple...
[ "def", "start", "(", "self", ",", "segment", ")", ":", "if", "self", ".", "closed", ":", "raise", "UserCritical", "(", "msg", "=", "'attempt to transfer wal after closing'", ",", "hint", "=", "'report a bug'", ")", "g", "=", "gevent", ".", "Greenlet", "(", ...
Begin transfer for an indicated wal segment.
[ "Begin", "transfer", "for", "an", "indicated", "wal", "segment", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/wal_transfer.py#L146-L162
train
wal-e/wal-e
wal_e/worker/pg/wal_transfer.py
WalTransferGroup._complete_execution
def _complete_execution(self, g): """Forward any raised exceptions across a channel.""" # Triggered via completion callback. # # Runs in its own greenlet, so take care to forward the # exception, if any, to fail the entire transfer in event of # trouble. assert g...
python
def _complete_execution(self, g): """Forward any raised exceptions across a channel.""" # Triggered via completion callback. # # Runs in its own greenlet, so take care to forward the # exception, if any, to fail the entire transfer in event of # trouble. assert g...
[ "def", "_complete_execution", "(", "self", ",", "g", ")", ":", "assert", "g", ".", "ready", "(", ")", "self", ".", "greenlets", ".", "remove", "(", "g", ")", "placed", "=", "UserCritical", "(", "msg", "=", "'placeholder bogus exception'", ",", "hint", "=...
Forward any raised exceptions across a channel.
[ "Forward", "any", "raised", "exceptions", "across", "a", "channel", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/wal_transfer.py#L164-L192
train
wal-e/wal-e
wal_e/piper.py
pipe
def pipe(*args): """ Takes as parameters several dicts, each with the same parameters passed to popen. Runs the various processes in a pipeline, connecting the stdout of every process except the last with the stdin of the next process. Adapted from http://www.enricozini.org/2009/debian/pyt...
python
def pipe(*args): """ Takes as parameters several dicts, each with the same parameters passed to popen. Runs the various processes in a pipeline, connecting the stdout of every process except the last with the stdin of the next process. Adapted from http://www.enricozini.org/2009/debian/pyt...
[ "def", "pipe", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "<", "2", ":", "raise", "ValueError", "(", "\"pipe needs at least 2 processes\"", ")", "for", "i", "in", "args", "[", ":", "-", "1", "]", ":", "i", "[", "\"stdout\"", "]", "=...
Takes as parameters several dicts, each with the same parameters passed to popen. Runs the various processes in a pipeline, connecting the stdout of every process except the last with the stdin of the next process. Adapted from http://www.enricozini.org/2009/debian/python-pipes/
[ "Takes", "as", "parameters", "several", "dicts", "each", "with", "the", "same", "parameters", "passed", "to", "popen", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/piper.py#L94-L122
train
wal-e/wal-e
wal_e/piper.py
pipe_wait
def pipe_wait(popens): """ Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/ """ # Avoid mutating the passed copy popens = copy.c...
python
def pipe_wait(popens): """ Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/ """ # Avoid mutating the passed copy popens = copy.c...
[ "def", "pipe_wait", "(", "popens", ")", ":", "popens", "=", "copy", ".", "copy", "(", "popens", ")", "results", "=", "[", "0", "]", "*", "len", "(", "popens", ")", "while", "popens", ":", "last", "=", "popens", ".", "pop", "(", "-", "1", ")", "...
Given an array of Popen objects returned by the pipe method, wait for all processes to terminate and return the array with their return values. Taken from http://www.enricozini.org/2009/debian/python-pipes/
[ "Given", "an", "array", "of", "Popen", "objects", "returned", "by", "the", "pipe", "method", "wait", "for", "all", "processes", "to", "terminate", "and", "return", "the", "array", "with", "their", "return", "values", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/piper.py#L125-L140
train
wal-e/wal-e
wal_e/blobstore/wabs/calling_format.py
CallingInfo.connect
def connect(self, creds): """Return an azure BlockBlobService instance. """ return BlockBlobService(account_name=creds.account_name, account_key=creds.account_key, sas_token=creds.access_token, protocol='https')
python
def connect(self, creds): """Return an azure BlockBlobService instance. """ return BlockBlobService(account_name=creds.account_name, account_key=creds.account_key, sas_token=creds.access_token, protocol='https')
[ "def", "connect", "(", "self", ",", "creds", ")", ":", "return", "BlockBlobService", "(", "account_name", "=", "creds", ".", "account_name", ",", "account_key", "=", "creds", ".", "account_key", ",", "sas_token", "=", "creds", ".", "access_token", ",", "prot...
Return an azure BlockBlobService instance.
[ "Return", "an", "azure", "BlockBlobService", "instance", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/wabs/calling_format.py#L23-L29
train
wal-e/wal-e
wal_e/blobstore/file/file_util.py
do_lzop_get
def do_lzop_get(creds, url, path, decrypt, do_retry): """ Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk. """ assert url.endswith('.lzo'), 'Expect an lzop-compressed file' with files.DeleteOnError(path) as decomp_out: ...
python
def do_lzop_get(creds, url, path, decrypt, do_retry): """ Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk. """ assert url.endswith('.lzo'), 'Expect an lzop-compressed file' with files.DeleteOnError(path) as decomp_out: ...
[ "def", "do_lzop_get", "(", "creds", ",", "url", ",", "path", ",", "decrypt", ",", "do_retry", ")", ":", "assert", "url", ".", "endswith", "(", "'.lzo'", ")", ",", "'Expect an lzop-compressed file'", "with", "files", ".", "DeleteOnError", "(", "path", ")", ...
Get and decompress a URL This streams the content directly to lzop; the compressed version is never stored on disk.
[ "Get", "and", "decompress", "a", "URL" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/file/file_util.py#L36-L59
train
wal-e/wal-e
wal_e/worker/pg/psql_worker.py
psql_csv_run
def psql_csv_run(sql_command, error_handler=None): """ Runs psql and returns a CSVReader object from the query This CSVReader includes header names as the first record in all situations. The output is fully buffered into Python. """ csv_query = ('COPY ({query}) TO STDOUT WITH CSV HEADER;' ...
python
def psql_csv_run(sql_command, error_handler=None): """ Runs psql and returns a CSVReader object from the query This CSVReader includes header names as the first record in all situations. The output is fully buffered into Python. """ csv_query = ('COPY ({query}) TO STDOUT WITH CSV HEADER;' ...
[ "def", "psql_csv_run", "(", "sql_command", ",", "error_handler", "=", "None", ")", ":", "csv_query", "=", "(", "'COPY ({query}) TO STDOUT WITH CSV HEADER;'", ".", "format", "(", "query", "=", "sql_command", ")", ")", "new_env", "=", "os", ".", "environ", ".", ...
Runs psql and returns a CSVReader object from the query This CSVReader includes header names as the first record in all situations. The output is fully buffered into Python.
[ "Runs", "psql", "and", "returns", "a", "CSVReader", "object", "from", "the", "query" ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/psql_worker.py#L34-L71
train
wal-e/wal-e
wal_e/worker/pg/psql_worker.py
PgBackupStatements._wal_name
def _wal_name(cls): """ Sets and returns _WAL_NAME to 'wal' or 'xlog' depending on version of postgres we are working with. It is used for handling xlog -> wal rename in postgres v10 """ if cls._WAL_NAME is None: version = cls._dict_transform(psql_csv_run( ...
python
def _wal_name(cls): """ Sets and returns _WAL_NAME to 'wal' or 'xlog' depending on version of postgres we are working with. It is used for handling xlog -> wal rename in postgres v10 """ if cls._WAL_NAME is None: version = cls._dict_transform(psql_csv_run( ...
[ "def", "_wal_name", "(", "cls", ")", ":", "if", "cls", ".", "_WAL_NAME", "is", "None", ":", "version", "=", "cls", ".", "_dict_transform", "(", "psql_csv_run", "(", "\"SELECT current_setting('server_version_num')\"", ")", ")", "if", "int", "(", "version", "[",...
Sets and returns _WAL_NAME to 'wal' or 'xlog' depending on version of postgres we are working with. It is used for handling xlog -> wal rename in postgres v10
[ "Sets", "and", "returns", "_WAL_NAME", "to", "wal", "or", "xlog", "depending", "on", "version", "of", "postgres", "we", "are", "working", "with", "." ]
027263860e72a403bc0e1497bb3e67523138e7a2
https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/psql_worker.py#L91-L106
train
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): """ 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...
[ "def", "run_start_backup", "(", "cls", ")", ":", "def", "handler", "(", "popen", ")", ":", "assert", "popen", ".", "returncode", "!=", "0", "raise", "UserException", "(", "'Could not start hot backup'", ")", "label", "=", "'freeze_start_'", "+", "(", "datetime...
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
train
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): """ 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...
[ "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
train
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): """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...
[ "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
train
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): """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...
[ "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
train
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): """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...
[ "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
train
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): """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 ...
[ "def", "from_store_name", "(", "bucket_name", ",", "region", "=", "None", ")", ":", "if", "region", "is", "None", ":", "region", "=", "os", ".", "getenv", "(", "'AWS_REGION'", ")", "mostly_ok", "=", "_is_mostly_subdomain_compatible", "(", "bucket_name", ")", ...
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
train
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): """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...
[ "def", "connect", "(", "self", ",", "creds", ")", ":", "def", "_conn_help", "(", "*", "args", ",", "**", "kwargs", ")", ":", "return", "_connect_secureish", "(", "*", "args", ",", "provider", "=", "creds", ",", "calling_format", "=", "self", ".", "call...
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
train
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): """ 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)
[ "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
train
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): """ create a directory if required """ 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
train
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])): """ 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...
[ "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
train
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): """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)
[ "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
train
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): """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...
[ "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
train
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): """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
[ "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
train
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): """ 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(...
[ "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
train
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): """ 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, ...
[ "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
train
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): """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...
[ "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
train
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): """ 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...
[ "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
train
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): """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...
[ "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
train
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): """ 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...
[ "def", "delete_before", "(", "self", ",", "segment_info", ")", ":", "self", ".", "_delete_base_backups_before", "(", "segment_info", ")", "self", ".", "_delete_wals_before", "(", "segment_info", ")", "if", "self", ".", "deleter", ":", "self", ".", "deleter", "...
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
train
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): """ 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 ...
[ "def", "delete_with_retention", "(", "self", ",", "num_to_retain", ")", ":", "base_backup_sentinel_depth", "=", "self", ".", "layout", ".", "basebackups", "(", ")", ".", "count", "(", "'/'", ")", "+", "1", "completed_basebackups", "=", "[", "]", "for", "key"...
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
train
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): """ 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...
[ "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
train
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): """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...
[ "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
train
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): """ 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...
[ "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
train
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): """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 ...
[ "def", "_start", "(", "self", ",", "tpart", ")", ":", "g", "=", "gevent", ".", "Greenlet", "(", "self", ".", "uploader", ",", "tpart", ")", "g", ".", "link", "(", "self", ".", "_finish", ")", "self", ".", "concurrency_burden", "+=", "1", "self", "....
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
train
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): """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...
[ "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
train
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): """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 ...
[ "def", "_wait", "(", "self", ")", ":", "val", "=", "self", ".", "wait_change", ".", "get", "(", ")", "if", "isinstance", "(", "val", ",", "Exception", ")", ":", "raise", "val", "else", ":", "self", ".", "member_burden", "-=", "len", "(", "val", ")"...
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
train
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): """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', ...
[ "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
train
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): """ 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...
[ "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
train
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(): """ 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...
[ "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
train
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(): """ 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, ...
[ "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
train
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): """ 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...
[ "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
train
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): """ 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: ...
[ "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
train
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): """ 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...
[ "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
train
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): """ 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...
[ "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
train
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 ): """ Create historical model for `model` and attach history manager to `model`. Keyword arguments: app -- App to install historical model into (defaults to model.__modu...
[ "def", "register", "(", "model", ",", "app", "=", "None", ",", "manager_name", "=", "\"history\"", ",", "records_class", "=", "None", ",", "table_name", "=", "None", ",", "**", "records_config", ")", ":", "from", ".", "import", "models", "if", "records_cla...
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
train
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): """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( ...
[ "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
train
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): """Set special model attribute to user for reference after save""" 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
train
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): """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...
[ "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
train
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): """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...
[ "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
train
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): """ 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...
[ "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
train
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): """ 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...
[ "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
train
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): """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 ...
[ "def", "get_extra_fields", "(", "self", ",", "model", ",", "fields", ")", ":", "def", "revert_url", "(", "self", ")", ":", "opts", "=", "model", ".", "_meta", "app_label", ",", "model_name", "=", "opts", ".", "app_label", ",", "opts", ".", "model_name", ...
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
train
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): """ 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", } ...
[ "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
train
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): """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...
[ "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
train
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): """ 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 ...
[ "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
train
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): """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: ...
[ "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
train
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): """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", ...
[ "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
train
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): """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...
[ "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
train
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
train
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): """ 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. ...
[ "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
train
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): """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...
[ "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
train
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
train
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
train
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): """ 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)...
[ "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
train
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
train
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): """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, ...
[ "def", "set_function_name", "(", "func", ",", "node_name", ",", "base_name", ",", "func_counter", ")", ":", "func", ".", "name", ",", "count", "=", "generate_function_name", "(", "func", ".", "type", ",", "base_name", ",", "node_name", ",", "func_counter", "...
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
train
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): """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_...
[ "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
train
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): """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...
[ "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
train
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): """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( ...
[ "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
train
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): """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....
[ "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
train
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): """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": ...
[ "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
train
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): """ Read image by pypng module. Args: path (str or 'file object'): File path or object to read. grayscale (bool): size (tupple of int): ...
[ "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
train