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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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
for rec in results:
prt.write("{R}\n".format(R=rec.__str__(indent=indent))) | 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
for rec in results:
prt.write("{R}\n".format(R=rec.__str__(indent=indent))) | [
"def",
"print_results_adj",
"(",
"results",
",",
"indent",
"=",
"False",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"# Print column headers if there are results to be printed",
"if",
"results",
":",
"prt",
".",
"write",
"(",
"\"{R}\\n\"",
".",
"format",
"(... | Print GOEA results. | [
"Print",
"GOEA",
"results",
"."
] | 407682e573a108864a79031f8ca19ee3bf377626 | https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/go_enrichment.py#L554-L561 | train | 223,600 |
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:
from goatools.nt_utils import wr_py_nts
nts_goea = goea_results
# If list has GOEnrichmentRecords or verbose namedtuples, exclude some fields.
if hasattr(goea_results[0], "_fldsdefprt") or hasattr(goea_results[0], 'goterm'):
# Exclude some attributes from the namedtuple when saving results
# to a Python file because the information is redundant or verbose.
nts_goea = MgrNtGOEAs(goea_results).get_goea_nts_prt(**kws)
docstring = "\n".join([docstring, "# {VER}\n\n".format(VER=self.obo_dag.version)])
assert hasattr(nts_goea[0], '_fields')
if sortby is None:
sortby = MgrNtGOEAs.dflt_sortby_objgoea
nts_goea = sorted(nts_goea, key=sortby)
wr_py_nts(fout_py, nts_goea, docstring, var_name) | 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:
from goatools.nt_utils import wr_py_nts
nts_goea = goea_results
# If list has GOEnrichmentRecords or verbose namedtuples, exclude some fields.
if hasattr(goea_results[0], "_fldsdefprt") or hasattr(goea_results[0], 'goterm'):
# Exclude some attributes from the namedtuple when saving results
# to a Python file because the information is redundant or verbose.
nts_goea = MgrNtGOEAs(goea_results).get_goea_nts_prt(**kws)
docstring = "\n".join([docstring, "# {VER}\n\n".format(VER=self.obo_dag.version)])
assert hasattr(nts_goea[0], '_fields')
if sortby is None:
sortby = MgrNtGOEAs.dflt_sortby_objgoea
nts_goea = sorted(nts_goea, key=sortby)
wr_py_nts(fout_py, nts_goea, docstring, var_name) | [
"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 | 223,601 |
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 method out of frustration with chromedriver and its problems with clicking
items that need to be scrolled to in order to be clickable. In '__ensure_element_by_xpath' we
scroll to the item before returning it, but chrome has some problems if it doesn't get some
time to scroll to the item. This method ensures chromes gets enough time to scroll to the item
before clicking it. I tried SEVERAL more 'correct' methods to get around this, but none of them
worked 100% of the time (waiting for the element to be 'clickable' does not work).
"""
# We ensure the element is scrolled into the middle of the viewport to ensure that
# it is clickable. There are two main ways an element may not be clickable:
# - It is outside of the viewport
# - It is under a banner or toolbar
# This script solves both cases
script = ("var viewPortHeight = Math.max("
"document.documentElement.clientHeight, window.innerHeight || 0);"
"var elementTop = arguments[0].getBoundingClientRect().top;"
"window.scrollBy(0, elementTop-(viewPortHeight/2));")
self.parent.execute_script(script, self) # parent = the webdriver
for _ in range(10):
try:
self.click()
return
except WebDriverException as e:
exception_message = str(e)
time.sleep(0.2)
raise WebDriverException(
"Couldn't click item after trying 10 times, got error message: \n{}".format(
exception_message
)
) | 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 method out of frustration with chromedriver and its problems with clicking
items that need to be scrolled to in order to be clickable. In '__ensure_element_by_xpath' we
scroll to the item before returning it, but chrome has some problems if it doesn't get some
time to scroll to the item. This method ensures chromes gets enough time to scroll to the item
before clicking it. I tried SEVERAL more 'correct' methods to get around this, but none of them
worked 100% of the time (waiting for the element to be 'clickable' does not work).
"""
# We ensure the element is scrolled into the middle of the viewport to ensure that
# it is clickable. There are two main ways an element may not be clickable:
# - It is outside of the viewport
# - It is under a banner or toolbar
# This script solves both cases
script = ("var viewPortHeight = Math.max("
"document.documentElement.clientHeight, window.innerHeight || 0);"
"var elementTop = arguments[0].getBoundingClientRect().top;"
"window.scrollBy(0, elementTop-(viewPortHeight/2));")
self.parent.execute_script(script, self) # parent = the webdriver
for _ in range(10):
try:
self.click()
return
except WebDriverException as e:
exception_message = str(e)
time.sleep(0.2)
raise WebDriverException(
"Couldn't click item after trying 10 times, got error message: \n{}".format(
exception_message
)
) | [
"def",
"_ensure_click",
"(",
"self",
")",
":",
"# We ensure the element is scrolled into the middle of the viewport to ensure that",
"# it is clickable. There are two main ways an element may not be clickable:",
"# - It is outside of the viewport",
"# - It is under a banner or toolbar",
"# T... | 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 chromedriver and its problems with clicking
items that need to be scrolled to in order to be clickable. In '__ensure_element_by_xpath' we
scroll to the item before returning it, but chrome has some problems if it doesn't get some
time to scroll to the item. This method ensures chromes gets enough time to scroll to the item
before clicking it. I tried SEVERAL more 'correct' methods to get around this, but none of them
worked 100% of the time (waiting for the element to be 'clickable' does not work). | [
"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 | 223,602 |
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 not provided.
"""
if not domain and self._last_requests_url:
domain = tldextract.extract(self._last_requests_url).registered_domain
elif not domain and not self._last_requests_url:
raise Exception('Trying to transfer cookies to selenium without specifying a domain '
'and without having visited any page in the current session')
# Transfer cookies
for c in [c for c in self.cookies if domain in c.domain]:
self.driver.ensure_add_cookie({'name': c.name, 'value': c.value, 'path': c.path,
'expiry': c.expires, 'domain': c.domain}) | 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 not provided.
"""
if not domain and self._last_requests_url:
domain = tldextract.extract(self._last_requests_url).registered_domain
elif not domain and not self._last_requests_url:
raise Exception('Trying to transfer cookies to selenium without specifying a domain '
'and without having visited any page in the current session')
# Transfer cookies
for c in [c for c in self.cookies if domain in c.domain]:
self.driver.ensure_add_cookie({'name': c.name, 'value': c.value, 'path': c.path,
'expiry': c.expires, 'domain': c.domain}) | [
"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 | 223,603 |
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.update({"user-agent": selenium_user_agent}) | 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.update({"user-agent": selenium_user_agent}) | [
"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 | 223,604 |
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 must contain the keys (name, value, domain) and
may contain the keys (path, expiry).
We first check that we aren't currently in the cookie's domain, if we aren't, we GET
the cookie's domain and then add the cookies to the driver.
We can override the cookie's domain using 'override_domain'. The use for this
parameter is that sometimes GETting the cookie's domain redirects you to a different
sub domain, and therefore adding the cookie fails. So sometimes the user may
need to override the cookie's domain to a less strict one, Eg.: 'site.com' instead of
'home.site.com', in this way even if the site redirects us to a subdomain, the cookie will
stick. If you set the domain to '', the cookie gets added with whatever domain the browser
is currently at (at least in chrome it does), so this ensures the cookie gets added.
It also retries adding the cookie with a more permissive domain if it fails in the first
try, and raises an exception if that fails. The standard selenium behaviour in this case
was to not do anything, which was very hard to debug.
"""
if override_domain:
cookie['domain'] = override_domain
cookie_domain = cookie['domain'] if cookie['domain'][0] != '.' else cookie['domain'][1:]
try:
browser_domain = tldextract.extract(self.current_url).fqdn
except AttributeError:
browser_domain = ''
if cookie_domain not in browser_domain:
# TODO Check if hardcoding 'http' causes trouble
# TODO Consider using a new proxy for this next request to not cause an anomalous
# request. This way their server sees our ip address as continuously having the
# same cookies and not have a request mid-session with no cookies
self.get('http://' + cookie_domain)
# Fixes phantomjs bug, all domains must start with a period
if self.name == "phantomjs": cookie['domain'] = '.' + cookie['domain']
self.add_cookie(cookie)
# If we fail adding the cookie, retry with a more permissive domain
if not self.is_cookie_in_driver(cookie):
cookie['domain'] = tldextract.extract(cookie['domain']).registered_domain
self.add_cookie(cookie)
if not self.is_cookie_in_driver(cookie):
raise WebDriverException(
"Couldn't add the following cookie to the webdriver\n{}\n".format(cookie)
) | 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 must contain the keys (name, value, domain) and
may contain the keys (path, expiry).
We first check that we aren't currently in the cookie's domain, if we aren't, we GET
the cookie's domain and then add the cookies to the driver.
We can override the cookie's domain using 'override_domain'. The use for this
parameter is that sometimes GETting the cookie's domain redirects you to a different
sub domain, and therefore adding the cookie fails. So sometimes the user may
need to override the cookie's domain to a less strict one, Eg.: 'site.com' instead of
'home.site.com', in this way even if the site redirects us to a subdomain, the cookie will
stick. If you set the domain to '', the cookie gets added with whatever domain the browser
is currently at (at least in chrome it does), so this ensures the cookie gets added.
It also retries adding the cookie with a more permissive domain if it fails in the first
try, and raises an exception if that fails. The standard selenium behaviour in this case
was to not do anything, which was very hard to debug.
"""
if override_domain:
cookie['domain'] = override_domain
cookie_domain = cookie['domain'] if cookie['domain'][0] != '.' else cookie['domain'][1:]
try:
browser_domain = tldextract.extract(self.current_url).fqdn
except AttributeError:
browser_domain = ''
if cookie_domain not in browser_domain:
# TODO Check if hardcoding 'http' causes trouble
# TODO Consider using a new proxy for this next request to not cause an anomalous
# request. This way their server sees our ip address as continuously having the
# same cookies and not have a request mid-session with no cookies
self.get('http://' + cookie_domain)
# Fixes phantomjs bug, all domains must start with a period
if self.name == "phantomjs": cookie['domain'] = '.' + cookie['domain']
self.add_cookie(cookie)
# If we fail adding the cookie, retry with a more permissive domain
if not self.is_cookie_in_driver(cookie):
cookie['domain'] = tldextract.extract(cookie['domain']).registered_domain
self.add_cookie(cookie)
if not self.is_cookie_in_driver(cookie):
raise WebDriverException(
"Couldn't add the following cookie to the webdriver\n{}\n".format(cookie)
) | [
"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 keys (path, expiry).
We first check that we aren't currently in the cookie's domain, if we aren't, we GET
the cookie's domain and then add the cookies to the driver.
We can override the cookie's domain using 'override_domain'. The use for this
parameter is that sometimes GETting the cookie's domain redirects you to a different
sub domain, and therefore adding the cookie fails. So sometimes the user may
need to override the cookie's domain to a less strict one, Eg.: 'site.com' instead of
'home.site.com', in this way even if the site redirects us to a subdomain, the cookie will
stick. If you set the domain to '', the cookie gets added with whatever domain the browser
is currently at (at least in chrome it does), so this ensures the cookie gets added.
It also retries adding the cookie with a more permissive domain if it fails in the first
try, and raises an exception if that fails. The standard selenium behaviour in this case
was to not do anything, which was very hard to debug. | [
"Ensures",
"a",
"cookie",
"gets",
"added",
"to",
"the",
"driver"
] | 9533932ae688da26f3fb78b97b3c0b05c6f24934 | https://github.com/tryolabs/requestium/blob/9533932ae688da26f3fb78b97b3c0b05c6f24934/requestium/requestium.py#L194-L244 | train | 223,605 |
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():
if (cookie['name'] == driver_cookie['name'] and
cookie['value'] == driver_cookie['value'] and
(cookie['domain'] == driver_cookie['domain'] or
'.' + cookie['domain'] == driver_cookie['domain'])):
return True
return False | 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():
if (cookie['name'] == driver_cookie['name'] and
cookie['value'] == driver_cookie['value'] and
(cookie['domain'] == driver_cookie['domain'] or
'.' + cookie['domain'] == driver_cookie['domain'])):
return True
return False | [
"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 | 223,606 |
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 till a page loads when GETing it,
but it doesn't do this when it runs javascript and makes AJAX requests.
So we must explicitly wait in that case.
The 'locator' argument defines what strategy we use to search for the element.
The 'state' argument allows us to chose between waiting for the element to be visible,
clickable, present, or invisible. Presence is more inclusive, but sometimes we want to
know if the element is visible. Careful, its not always intuitive what Selenium considers
to be a visible element. We can also wait for it to be clickable, although this method
is a bit buggy in selenium, an element can be 'clickable' according to selenium and
still fail when we try to click it.
More info at: http://selenium-python.readthedocs.io/waits.html
"""
locators = {'id': By.ID,
'name': By.NAME,
'xpath': By.XPATH,
'link_text': By.LINK_TEXT,
'partial_link_text': By.PARTIAL_LINK_TEXT,
'tag_name': By.TAG_NAME,
'class_name': By.CLASS_NAME,
'css_selector': By.CSS_SELECTOR}
locator = locators[locator]
if not timeout: timeout = self.default_timeout
if state == 'visible':
element = WebDriverWait(self, timeout).until(
EC.visibility_of_element_located((locator, selector))
)
elif state == 'clickable':
element = WebDriverWait(self, timeout).until(
EC.element_to_be_clickable((locator, selector))
)
elif state == 'present':
element = WebDriverWait(self, timeout).until(
EC.presence_of_element_located((locator, selector))
)
elif state == 'invisible':
WebDriverWait(self, timeout).until(
EC.invisibility_of_element_located((locator, selector))
)
element = None
else:
raise ValueError(
"The 'state' argument must be 'visible', 'clickable', 'present' "
"or 'invisible', not '{}'".format(state)
)
# We add this method to our element to provide a more robust click. Chromedriver
# sometimes needs some time before it can click an item, specially if it needs to
# scroll into it first. This method ensures clicks don't fail because of this.
if element:
element.ensure_click = partial(_ensure_click, element)
return element | 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 till a page loads when GETing it,
but it doesn't do this when it runs javascript and makes AJAX requests.
So we must explicitly wait in that case.
The 'locator' argument defines what strategy we use to search for the element.
The 'state' argument allows us to chose between waiting for the element to be visible,
clickable, present, or invisible. Presence is more inclusive, but sometimes we want to
know if the element is visible. Careful, its not always intuitive what Selenium considers
to be a visible element. We can also wait for it to be clickable, although this method
is a bit buggy in selenium, an element can be 'clickable' according to selenium and
still fail when we try to click it.
More info at: http://selenium-python.readthedocs.io/waits.html
"""
locators = {'id': By.ID,
'name': By.NAME,
'xpath': By.XPATH,
'link_text': By.LINK_TEXT,
'partial_link_text': By.PARTIAL_LINK_TEXT,
'tag_name': By.TAG_NAME,
'class_name': By.CLASS_NAME,
'css_selector': By.CSS_SELECTOR}
locator = locators[locator]
if not timeout: timeout = self.default_timeout
if state == 'visible':
element = WebDriverWait(self, timeout).until(
EC.visibility_of_element_located((locator, selector))
)
elif state == 'clickable':
element = WebDriverWait(self, timeout).until(
EC.element_to_be_clickable((locator, selector))
)
elif state == 'present':
element = WebDriverWait(self, timeout).until(
EC.presence_of_element_located((locator, selector))
)
elif state == 'invisible':
WebDriverWait(self, timeout).until(
EC.invisibility_of_element_located((locator, selector))
)
element = None
else:
raise ValueError(
"The 'state' argument must be 'visible', 'clickable', 'present' "
"or 'invisible', not '{}'".format(state)
)
# We add this method to our element to provide a more robust click. Chromedriver
# sometimes needs some time before it can click an item, specially if it needs to
# scroll into it first. This method ensures clicks don't fail because of this.
if element:
element.ensure_click = partial(_ensure_click, element)
return element | [
"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 and makes AJAX requests.
So we must explicitly wait in that case.
The 'locator' argument defines what strategy we use to search for the element.
The 'state' argument allows us to chose between waiting for the element to be visible,
clickable, present, or invisible. Presence is more inclusive, but sometimes we want to
know if the element is visible. Careful, its not always intuitive what Selenium considers
to be a visible element. We can also wait for it to be clickable, although this method
is a bit buggy in selenium, an element can be 'clickable' according to selenium and
still fail when we try to click it.
More info at: http://selenium-python.readthedocs.io/waits.html | [
"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 | 223,607 |
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) + len(rgb) + 3 + int(size_x) * int(size_y) * 3
images.append(Image.open(BytesIO(data[index:index + file_size])))
index += file_size
return images | 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) + len(rgb) + 3 + int(size_x) * int(size_y) * 3
images.append(Image.open(BytesIO(data[index:index + file_size])))
index += file_size
return images | [
"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 | 223,608 |
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 | 223,609 |
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:c2+12] == b'PNG'):
images.append(Image.open(BytesIO(data[c1:c2 + 8])))
c1 = c2 + 8
c2 = c1
c2 += 1
return images | 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:c2+12] == b'PNG'):
images.append(Image.open(BytesIO(data[c1:c2 + 8])))
c1 = c2 + 8
c2 = c1
c2 += 1
return images | [
"def",
"parse_buffer_to_png",
"(",
"data",
")",
":",
"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",
"dat... | 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 | 223,610 |
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 printed to the other log handlers.
"""
# Configuration must only happen once: no mechanism for avoiding
# duplication of handlers exists.
assert len(HANDLERS) == 0
log_destinations = get_log_destinations()
if 'stderr' in log_destinations:
# Add stderr output.
HANDLERS.append(logging.StreamHandler())
def terrible_log_output(s):
import sys
print(s, file=sys.stderr)
places = [
# Linux
'/dev/log',
# FreeBSD
'/var/run/log',
# Macintosh
'/var/run/syslog',
]
default_syslog_address = places[0]
for p in places:
if path.exists(p):
default_syslog_address = p
break
syslog_address = kwargs.setdefault('syslog_address',
default_syslog_address)
valid_facility = False
if 'syslog' in log_destinations:
facility, valid_facility = get_syslog_facility()
if not valid_facility:
terrible_log_output('invalid syslog facility level specified')
try:
# Add syslog output.
HANDLERS.append(handlers.SysLogHandler(syslog_address,
facility=facility))
except EnvironmentError as e:
if e.errno in [errno.EACCES, errno.ECONNREFUSED]:
message = ('wal-e: Could not set up syslog, '
'continuing anyway. '
'Reason: {0}').format(errno.errorcode[e.errno])
terrible_log_output(message)
fs = kwargs.get("format", logging.BASIC_FORMAT)
dfs = kwargs.get("datefmt", None)
fmt = IndentFormatter(fs, dfs)
for handler in HANDLERS:
handler.setFormatter(fmt)
logging.root.addHandler(handler)
# Default to INFO level logging.
set_level(kwargs.get('level', logging.INFO)) | 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 printed to the other log handlers.
"""
# Configuration must only happen once: no mechanism for avoiding
# duplication of handlers exists.
assert len(HANDLERS) == 0
log_destinations = get_log_destinations()
if 'stderr' in log_destinations:
# Add stderr output.
HANDLERS.append(logging.StreamHandler())
def terrible_log_output(s):
import sys
print(s, file=sys.stderr)
places = [
# Linux
'/dev/log',
# FreeBSD
'/var/run/log',
# Macintosh
'/var/run/syslog',
]
default_syslog_address = places[0]
for p in places:
if path.exists(p):
default_syslog_address = p
break
syslog_address = kwargs.setdefault('syslog_address',
default_syslog_address)
valid_facility = False
if 'syslog' in log_destinations:
facility, valid_facility = get_syslog_facility()
if not valid_facility:
terrible_log_output('invalid syslog facility level specified')
try:
# Add syslog output.
HANDLERS.append(handlers.SysLogHandler(syslog_address,
facility=facility))
except EnvironmentError as e:
if e.errno in [errno.EACCES, errno.ECONNREFUSED]:
message = ('wal-e: Could not set up syslog, '
'continuing anyway. '
'Reason: {0}').format(errno.errorcode[e.errno])
terrible_log_output(message)
fs = kwargs.get("format", logging.BASIC_FORMAT)
dfs = kwargs.get("datefmt", None)
fmt = IndentFormatter(fs, dfs)
for handler in HANDLERS:
handler.setFormatter(fmt)
logging.root.addHandler(handler)
# Default to INFO level logging.
set_level(kwargs.get('level', logging.INFO)) | [
"def",
"configure",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Configuration must only happen once: no mechanism for avoiding",
"# duplication of handlers exists.",
"assert",
"len",
"(",
"HANDLERS",
")",
"==",
"0",
"log_destinations",
"=",
"get_log_destinatio... | 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 | 223,611 |
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.SysLogHandler.LOG_USER
return facility, valid_facility | 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.SysLogHandler.LOG_USER
return facility, valid_facility | [
"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 | 223,612 |
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 | 223,613 |
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",
"(... | 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 | 223,614 |
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 anyway.
if not root.endswith(os.path.sep):
root += os.path.sep
# Ensure that the root path is a directory before continuing.
if not os.path.isdir(root):
raise TarBadRootError(root=root)
bogus_tar = None
try:
# Create a bogus TarFile as a contrivance to be able to run
# gettarinfo and produce such instances. Some of the settings
# on the TarFile are important, like whether to de-reference
# symlinks.
bogus_tar = tarfile.TarFile(os.devnull, 'w', dereference=False)
# Bookkeeping for segmentation of tar members into partitions.
partition_number = 0
partition_bytes = 0
partition_members = 0
partition = TarPartition(partition_number)
for file_path in file_paths:
# Ensure tar members exist within a shared root before
# continuing.
if not file_path.startswith(root):
raise TarBadPathError(root=root, offensive_path=file_path)
# Create an ExtendedTarInfo to represent the tarfile.
try:
et_info = ExtendedTarInfo(
tarinfo=bogus_tar.gettarinfo(
file_path, arcname=file_path[len(root):]),
submitted_path=file_path)
except EnvironmentError as e:
if (e.errno == errno.ENOENT and
e.filename == file_path):
# log a NOTICE/INFO that the file was unlinked.
# Ostensibly harmless (such unlinks should be replayed
# in the WAL) but good to know.
logger.debug(
msg='tar member additions skipping an unlinked file',
detail='Skipping {0}.'.format(et_info.submitted_path))
continue
else:
raise
# Ensure tar members are within an expected size before
# continuing.
if et_info.tarinfo.size > max_partition_size:
raise TarMemberTooBigError(
et_info.tarinfo.name, max_partition_size,
et_info.tarinfo.size)
if (partition_bytes + et_info.tarinfo.size >= max_partition_size
or partition_members >= PARTITION_MAX_MEMBERS):
# Partition is full and cannot accept another member,
# so yield the complete one to the caller.
yield partition
# Prepare a fresh partition to accrue additional file
# paths into.
partition_number += 1
partition_bytes = et_info.tarinfo.size
partition_members = 1
partition = TarPartition(
partition_number, [et_info])
else:
# Partition is able to accept this member, so just add
# it and increment the size counters.
partition_bytes += et_info.tarinfo.size
partition_members += 1
partition.append(et_info)
# Partition size overflow must not to be possible
# here.
assert partition_bytes < max_partition_size
finally:
if bogus_tar is not None:
bogus_tar.close()
# Flush out the final partition should it be non-empty.
if partition:
yield partition | 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 anyway.
if not root.endswith(os.path.sep):
root += os.path.sep
# Ensure that the root path is a directory before continuing.
if not os.path.isdir(root):
raise TarBadRootError(root=root)
bogus_tar = None
try:
# Create a bogus TarFile as a contrivance to be able to run
# gettarinfo and produce such instances. Some of the settings
# on the TarFile are important, like whether to de-reference
# symlinks.
bogus_tar = tarfile.TarFile(os.devnull, 'w', dereference=False)
# Bookkeeping for segmentation of tar members into partitions.
partition_number = 0
partition_bytes = 0
partition_members = 0
partition = TarPartition(partition_number)
for file_path in file_paths:
# Ensure tar members exist within a shared root before
# continuing.
if not file_path.startswith(root):
raise TarBadPathError(root=root, offensive_path=file_path)
# Create an ExtendedTarInfo to represent the tarfile.
try:
et_info = ExtendedTarInfo(
tarinfo=bogus_tar.gettarinfo(
file_path, arcname=file_path[len(root):]),
submitted_path=file_path)
except EnvironmentError as e:
if (e.errno == errno.ENOENT and
e.filename == file_path):
# log a NOTICE/INFO that the file was unlinked.
# Ostensibly harmless (such unlinks should be replayed
# in the WAL) but good to know.
logger.debug(
msg='tar member additions skipping an unlinked file',
detail='Skipping {0}.'.format(et_info.submitted_path))
continue
else:
raise
# Ensure tar members are within an expected size before
# continuing.
if et_info.tarinfo.size > max_partition_size:
raise TarMemberTooBigError(
et_info.tarinfo.name, max_partition_size,
et_info.tarinfo.size)
if (partition_bytes + et_info.tarinfo.size >= max_partition_size
or partition_members >= PARTITION_MAX_MEMBERS):
# Partition is full and cannot accept another member,
# so yield the complete one to the caller.
yield partition
# Prepare a fresh partition to accrue additional file
# paths into.
partition_number += 1
partition_bytes = et_info.tarinfo.size
partition_members = 1
partition = TarPartition(
partition_number, [et_info])
else:
# Partition is able to accept this member, so just add
# it and increment the size counters.
partition_bytes += et_info.tarinfo.size
partition_members += 1
partition.append(et_info)
# Partition size overflow must not to be possible
# here.
assert partition_bytes < max_partition_size
finally:
if bogus_tar is not None:
bogus_tar.close()
# Flush out the final partition should it be non-empty.
if partition:
yield partition | [
"def",
"_segmentation_guts",
"(",
"root",
",",
"file_paths",
",",
"max_partition_size",
")",
":",
"# Canonicalize root to include the trailing slash, since root is",
"# intended to be a directory anyway.",
"if",
"not",
"root",
".",
"endswith",
"(",
"os",
".",
"path",
".",
... | 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 | 223,615 |
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 doesn't fit cleanly into the TarPartition object,
# tarballs are only ever extracted for partitions so the logic jives
# for the most part.
tar = tarfile.open(mode='r|', fileobj=fileobj,
bufsize=pipebuf.PIPE_BUF_BYTES)
# canonicalize dest_path so the prefix check below works
dest_path = os.path.realpath(dest_path)
# list of files that need fsyncing
extracted_files = []
# Iterate through each member of the tarfile individually. We must
# approach it this way because we are dealing with a pipe and the
# getmembers() method will consume it before we extract any data.
for member in tar:
assert not member.name.startswith('/')
relpath = os.path.join(dest_path, member.name)
# Workaround issue with tar handling of symlink, see:
# https://bugs.python.org/issue12800
if member.issym():
target_path = os.path.join(dest_path, member.name)
try:
os.symlink(member.linkname, target_path)
except OSError as e:
if e.errno == errno.EEXIST:
os.remove(target_path)
os.symlink(member.linkname, target_path)
else:
raise
continue
if member.isreg() and member.size >= pipebuf.PIPE_BUF_BYTES:
cat_extract(tar, member, relpath)
else:
tar.extract(member, path=dest_path)
filename = os.path.realpath(relpath)
extracted_files.append(filename)
# avoid accumulating an unbounded list of strings which
# could be quite large for a large database
if len(extracted_files) > 1000:
_fsync_files(extracted_files)
del extracted_files[:]
tar.close()
_fsync_files(extracted_files) | 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 doesn't fit cleanly into the TarPartition object,
# tarballs are only ever extracted for partitions so the logic jives
# for the most part.
tar = tarfile.open(mode='r|', fileobj=fileobj,
bufsize=pipebuf.PIPE_BUF_BYTES)
# canonicalize dest_path so the prefix check below works
dest_path = os.path.realpath(dest_path)
# list of files that need fsyncing
extracted_files = []
# Iterate through each member of the tarfile individually. We must
# approach it this way because we are dealing with a pipe and the
# getmembers() method will consume it before we extract any data.
for member in tar:
assert not member.name.startswith('/')
relpath = os.path.join(dest_path, member.name)
# Workaround issue with tar handling of symlink, see:
# https://bugs.python.org/issue12800
if member.issym():
target_path = os.path.join(dest_path, member.name)
try:
os.symlink(member.linkname, target_path)
except OSError as e:
if e.errno == errno.EEXIST:
os.remove(target_path)
os.symlink(member.linkname, target_path)
else:
raise
continue
if member.isreg() and member.size >= pipebuf.PIPE_BUF_BYTES:
cat_extract(tar, member, relpath)
else:
tar.extract(member, path=dest_path)
filename = os.path.realpath(relpath)
extracted_files.append(filename)
# avoid accumulating an unbounded list of strings which
# could be quite large for a large database
if len(extracted_files) > 1000:
_fsync_files(extracted_files)
del extracted_files[:]
tar.close()
_fsync_files(extracted_files) | [
"def",
"tarfile_extract",
"(",
"fileobj",
",",
"dest_path",
")",
":",
"# Though this method doesn't fit cleanly into the TarPartition object,",
"# tarballs are only ever extracted for partitions so the logic jives",
"# for the most part.",
"tar",
"=",
"tarfile",
".",
"open",
"(",
"... | 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 | 223,616 |
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 backup instead.
if query is None:
bl_iter = bl
else:
bl_iter = bl.find_all(query)
# TODO: support switchable formats for difference needs.
w_csv = csv.writer(sys.stdout, dialect='excel-tab')
w_csv.writerow(BackupInfo._fields)
for bi in bl_iter:
w_csv.writerow([getattr(bi, k) for k in BackupInfo._fields])
sys.stdout.flush() | 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 backup instead.
if query is None:
bl_iter = bl
else:
bl_iter = bl.find_all(query)
# TODO: support switchable formats for difference needs.
w_csv = csv.writer(sys.stdout, dialect='excel-tab')
w_csv.writerow(BackupInfo._fields)
for bi in bl_iter:
w_csv.writerow([getattr(bi, k) for k in BackupInfo._fields])
sys.stdout.flush() | [
"def",
"backup_list",
"(",
"self",
",",
"query",
",",
"detail",
")",
":",
"import",
"csv",
"from",
"wal_e",
".",
"storage",
".",
"base",
"import",
"BackupInfo",
"bl",
"=",
"self",
".",
"_backup_list",
"(",
"detail",
")",
"# If there is no query, return an exha... | 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 | 223,617 |
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 stop the backup in
most situations.
"""
upload_good = False
backup_stop_good = False
while_offline = False
start_backup_info = None
if 'while_offline' in kwargs:
while_offline = kwargs.pop('while_offline')
try:
if not while_offline:
start_backup_info = PgBackupStatements.run_start_backup()
version = PgBackupStatements.pg_version()['version']
else:
if os.path.exists(os.path.join(data_directory,
'postmaster.pid')):
hint = ('Shut down postgres. '
'If there is a stale lockfile, '
'then remove it after being very sure postgres '
'is not running.')
raise UserException(
msg='while_offline set, but pg looks to be running',
detail='Found a postmaster.pid lockfile, and aborting',
hint=hint)
ctrl_data = PgControlDataParser(data_directory)
start_backup_info = ctrl_data.last_xlog_file_name_and_offset()
version = ctrl_data.pg_version()
ret_tuple = self._upload_pg_cluster_dir(
start_backup_info, data_directory, version=version, *args,
**kwargs)
spec, uploaded_to, expanded_size_bytes = ret_tuple
upload_good = True
finally:
if not upload_good:
logger.warning(
'blocking on sending WAL segments',
detail=('The backup was not completed successfully, '
'but we have to wait anyway. '
'See README: TODO about pg_cancel_backup'))
if not while_offline:
stop_backup_info = PgBackupStatements.run_stop_backup()
else:
stop_backup_info = start_backup_info
backup_stop_good = True
# XXX: Ugly, this is more of a 'worker' task because it might
# involve retries and error messages, something that is not
# treated by the "operator" category of modules. So
# basically, if this small upload fails, the whole upload
# fails!
if upload_good and backup_stop_good:
# Try to write a sentinel file to the cluster backup
# directory that indicates that the base backup upload has
# definitely run its course and also communicates what WAL
# segments are needed to get to consistency.
sentinel_content = json.dumps(
{'wal_segment_backup_stop':
stop_backup_info['file_name'],
'wal_segment_offset_backup_stop':
stop_backup_info['file_offset'],
'expanded_size_bytes': expanded_size_bytes,
'spec': spec})
# XXX: should use the storage operators.
#
# XXX: distinguish sentinels by *PREFIX* not suffix,
# which makes searching harder. (For the next version
# bump).
uri_put_file(self.creds,
uploaded_to + '_backup_stop_sentinel.json',
BytesIO(sentinel_content.encode("utf8")),
content_type='application/json')
else:
# NB: Other exceptions should be raised before this that
# have more informative results, it is intended that this
# exception never will get raised.
raise UserCritical('could not complete backup process') | 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 stop the backup in
most situations.
"""
upload_good = False
backup_stop_good = False
while_offline = False
start_backup_info = None
if 'while_offline' in kwargs:
while_offline = kwargs.pop('while_offline')
try:
if not while_offline:
start_backup_info = PgBackupStatements.run_start_backup()
version = PgBackupStatements.pg_version()['version']
else:
if os.path.exists(os.path.join(data_directory,
'postmaster.pid')):
hint = ('Shut down postgres. '
'If there is a stale lockfile, '
'then remove it after being very sure postgres '
'is not running.')
raise UserException(
msg='while_offline set, but pg looks to be running',
detail='Found a postmaster.pid lockfile, and aborting',
hint=hint)
ctrl_data = PgControlDataParser(data_directory)
start_backup_info = ctrl_data.last_xlog_file_name_and_offset()
version = ctrl_data.pg_version()
ret_tuple = self._upload_pg_cluster_dir(
start_backup_info, data_directory, version=version, *args,
**kwargs)
spec, uploaded_to, expanded_size_bytes = ret_tuple
upload_good = True
finally:
if not upload_good:
logger.warning(
'blocking on sending WAL segments',
detail=('The backup was not completed successfully, '
'but we have to wait anyway. '
'See README: TODO about pg_cancel_backup'))
if not while_offline:
stop_backup_info = PgBackupStatements.run_stop_backup()
else:
stop_backup_info = start_backup_info
backup_stop_good = True
# XXX: Ugly, this is more of a 'worker' task because it might
# involve retries and error messages, something that is not
# treated by the "operator" category of modules. So
# basically, if this small upload fails, the whole upload
# fails!
if upload_good and backup_stop_good:
# Try to write a sentinel file to the cluster backup
# directory that indicates that the base backup upload has
# definitely run its course and also communicates what WAL
# segments are needed to get to consistency.
sentinel_content = json.dumps(
{'wal_segment_backup_stop':
stop_backup_info['file_name'],
'wal_segment_offset_backup_stop':
stop_backup_info['file_offset'],
'expanded_size_bytes': expanded_size_bytes,
'spec': spec})
# XXX: should use the storage operators.
#
# XXX: distinguish sentinels by *PREFIX* not suffix,
# which makes searching harder. (For the next version
# bump).
uri_put_file(self.creds,
uploaded_to + '_backup_stop_sentinel.json',
BytesIO(sentinel_content.encode("utf8")),
content_type='application/json')
else:
# NB: Other exceptions should be raised before this that
# have more informative results, it is intended that this
# exception never will get raised.
raise UserCritical('could not complete backup process') | [
"def",
"database_backup",
"(",
"self",
",",
"data_directory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"upload_good",
"=",
"False",
"backup_stop_good",
"=",
"False",
"while_offline",
"=",
"False",
"start_backup_info",
"=",
"None",
"if",
"'while_off... | 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 | 223,618 |
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
# relative to other uploads when parallel wal-push is enabled,
# in that it's not desirable to tweak its .ready/.done files
# in archive_status.
xlog_dir = os.path.dirname(wal_path)
segment = WalSegment(wal_path, explicit=True)
uploader = WalUploader(self.layout, self.creds, self.gpg_key_id)
group = WalTransferGroup(uploader)
group.start(segment)
# Upload any additional wal segments up to the specified
# concurrency by scanning the Postgres archive_status
# directory.
started = 1
seg_stream = WalSegment.from_ready_archive_status(xlog_dir)
while started < concurrency:
try:
other_segment = next(seg_stream)
except StopIteration:
break
if other_segment.path != wal_path:
group.start(other_segment)
started += 1
try:
# Wait for uploads to finish.
group.join()
except EnvironmentError as e:
if e.errno == errno.ENOENT:
print(e)
raise UserException(
msg='could not find file for wal-push',
detail=('The operating system reported: {0} {1}'
.format(e.strerror, repr(e.filename))))
raise | 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
# relative to other uploads when parallel wal-push is enabled,
# in that it's not desirable to tweak its .ready/.done files
# in archive_status.
xlog_dir = os.path.dirname(wal_path)
segment = WalSegment(wal_path, explicit=True)
uploader = WalUploader(self.layout, self.creds, self.gpg_key_id)
group = WalTransferGroup(uploader)
group.start(segment)
# Upload any additional wal segments up to the specified
# concurrency by scanning the Postgres archive_status
# directory.
started = 1
seg_stream = WalSegment.from_ready_archive_status(xlog_dir)
while started < concurrency:
try:
other_segment = next(seg_stream)
except StopIteration:
break
if other_segment.path != wal_path:
group.start(other_segment)
started += 1
try:
# Wait for uploads to finish.
group.join()
except EnvironmentError as e:
if e.errno == errno.ENOENT:
print(e)
raise UserException(
msg='could not find file for wal-push',
detail=('The operating system reported: {0} {1}'
.format(e.strerror, repr(e.filename))))
raise | [
"def",
"wal_archive",
"(",
"self",
",",
"wal_path",
",",
"concurrency",
"=",
"1",
")",
":",
"# Upload the segment expressly indicated. It's special",
"# relative to other uploads when parallel wal-push is enabled,",
"# in that it's not desirable to tweak its .ready/.done files",
"# in... | 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 | 223,619 |
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(wal_path), so both are required.
"""
url = '{0}://{1}/{2}'.format(
self.layout.scheme, self.layout.store_name(),
self.layout.wal_path(wal_name))
if prefetch_max > 0:
# Check for prefetch-hit.
base = os.path.dirname(os.path.realpath(wal_destination))
pd = prefetch.Dirs(base)
seg = WalSegment(wal_name)
started = start_prefetches(seg, pd, prefetch_max)
last_size = 0
while True:
if pd.contains(seg):
pd.promote(seg, wal_destination)
logger.info(
msg='promoted prefetched wal segment',
structured={'action': 'wal-fetch',
'key': url,
'seg': wal_name,
'prefix': self.layout.path_prefix})
pd.clear_except(started)
return True
# If there is a 'running' download, wait a bit for it
# to make progress or finish. However, if it doesn't
# make progress in some amount of time, assume that
# the prefetch process has died and go on with the
# in-band downloading code.
sz = pd.running_size(seg)
if sz <= last_size:
break
last_size = sz
gevent.sleep(0.5)
pd.clear_except(started)
logger.info(
msg='begin wal restore',
structured={'action': 'wal-fetch',
'key': url,
'seg': wal_name,
'prefix': self.layout.path_prefix,
'state': 'begin'})
ret = do_lzop_get(self.creds, url, wal_destination,
self.gpg_key_id is not None)
logger.info(
msg='complete wal restore',
structured={'action': 'wal-fetch',
'key': url,
'seg': wal_name,
'prefix': self.layout.path_prefix,
'state': 'complete'})
return ret | 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(wal_path), so both are required.
"""
url = '{0}://{1}/{2}'.format(
self.layout.scheme, self.layout.store_name(),
self.layout.wal_path(wal_name))
if prefetch_max > 0:
# Check for prefetch-hit.
base = os.path.dirname(os.path.realpath(wal_destination))
pd = prefetch.Dirs(base)
seg = WalSegment(wal_name)
started = start_prefetches(seg, pd, prefetch_max)
last_size = 0
while True:
if pd.contains(seg):
pd.promote(seg, wal_destination)
logger.info(
msg='promoted prefetched wal segment',
structured={'action': 'wal-fetch',
'key': url,
'seg': wal_name,
'prefix': self.layout.path_prefix})
pd.clear_except(started)
return True
# If there is a 'running' download, wait a bit for it
# to make progress or finish. However, if it doesn't
# make progress in some amount of time, assume that
# the prefetch process has died and go on with the
# in-band downloading code.
sz = pd.running_size(seg)
if sz <= last_size:
break
last_size = sz
gevent.sleep(0.5)
pd.clear_except(started)
logger.info(
msg='begin wal restore',
structured={'action': 'wal-fetch',
'key': url,
'seg': wal_name,
'prefix': self.layout.path_prefix,
'state': 'begin'})
ret = do_lzop_get(self.creds, url, wal_destination,
self.gpg_key_id is not None)
logger.info(
msg='complete wal restore',
structured={'action': 'wal-fetch',
'key': url,
'seg': wal_name,
'prefix': self.layout.path_prefix,
'state': 'complete'})
return ret | [
"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 | 223,620 |
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 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
uncompressed Postgres heap file that is pipelined into lzo. Once
lzo is completely finished (necessary to have access to the file
size) the file is sent to S3 or WABS.
TODO: Investigate an optimization to decouple the compression and
upload steps to make sure that the most efficient possible use of
pipelining of network and disk resources occurs. Right now it
possible to bounce back and forth between bottlenecking on reading
from the database block device and subsequently the S3/WABS sending
steps should the processes be at the same stage of the upload
pipeline: this can have a very negative impact on being able to
make full use of system resources.
Furthermore, it desirable to overflowing the page cache: having
separate tunables for number of simultanious compression jobs
(which occupy /tmp space and page cache) and number of uploads
(which affect upload throughput) would help.
"""
spec, parts = tar_partition.partition(pg_cluster_dir)
# TODO :: Move arbitray path construction to StorageLayout Object
backup_prefix = '{0}/basebackups_{1}/base_{file_name}_{file_offset}'\
.format(self.layout.prefix.rstrip('/'), FILE_STRUCTURE_VERSION,
**start_backup_info)
if rate_limit is None:
per_process_limit = None
else:
per_process_limit = int(rate_limit / pool_size)
# Reject tiny per-process rate limits. They should be
# rejected more nicely elsewhere.
assert per_process_limit is None or per_process_limit > 0
total_size = 0
# Make an attempt to upload extended version metadata
extended_version_url = backup_prefix + '/extended_version.txt'
logger.info(
msg='start upload postgres version metadata',
detail=('Uploading to {extended_version_url}.'
.format(extended_version_url=extended_version_url)))
uri_put_file(self.creds,
extended_version_url, BytesIO(version.encode("utf8")),
content_type='text/plain')
logger.info(msg='postgres version metadata upload complete')
uploader = PartitionUploader(self.creds, backup_prefix,
per_process_limit, self.gpg_key_id)
pool = TarUploadPool(uploader, pool_size)
# Enqueue uploads for parallel execution
for tpart in parts:
total_size += tpart.total_member_size
# 'put' can raise an exception for a just-failed upload,
# aborting the process.
pool.put(tpart)
# Wait for remaining parts to upload. An exception can be
# raised to signal failure of the upload.
pool.join()
return spec, backup_prefix, total_size | 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 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
uncompressed Postgres heap file that is pipelined into lzo. Once
lzo is completely finished (necessary to have access to the file
size) the file is sent to S3 or WABS.
TODO: Investigate an optimization to decouple the compression and
upload steps to make sure that the most efficient possible use of
pipelining of network and disk resources occurs. Right now it
possible to bounce back and forth between bottlenecking on reading
from the database block device and subsequently the S3/WABS sending
steps should the processes be at the same stage of the upload
pipeline: this can have a very negative impact on being able to
make full use of system resources.
Furthermore, it desirable to overflowing the page cache: having
separate tunables for number of simultanious compression jobs
(which occupy /tmp space and page cache) and number of uploads
(which affect upload throughput) would help.
"""
spec, parts = tar_partition.partition(pg_cluster_dir)
# TODO :: Move arbitray path construction to StorageLayout Object
backup_prefix = '{0}/basebackups_{1}/base_{file_name}_{file_offset}'\
.format(self.layout.prefix.rstrip('/'), FILE_STRUCTURE_VERSION,
**start_backup_info)
if rate_limit is None:
per_process_limit = None
else:
per_process_limit = int(rate_limit / pool_size)
# Reject tiny per-process rate limits. They should be
# rejected more nicely elsewhere.
assert per_process_limit is None or per_process_limit > 0
total_size = 0
# Make an attempt to upload extended version metadata
extended_version_url = backup_prefix + '/extended_version.txt'
logger.info(
msg='start upload postgres version metadata',
detail=('Uploading to {extended_version_url}.'
.format(extended_version_url=extended_version_url)))
uri_put_file(self.creds,
extended_version_url, BytesIO(version.encode("utf8")),
content_type='text/plain')
logger.info(msg='postgres version metadata upload complete')
uploader = PartitionUploader(self.creds, backup_prefix,
per_process_limit, self.gpg_key_id)
pool = TarUploadPool(uploader, pool_size)
# Enqueue uploads for parallel execution
for tpart in parts:
total_size += tpart.total_member_size
# 'put' can raise an exception for a just-failed upload,
# aborting the process.
pool.put(tpart)
# Wait for remaining parts to upload. An exception can be
# raised to signal failure of the upload.
pool.join()
return spec, backup_prefix, total_size | [
"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
uncompressed Postgres heap file that is pipelined into lzo. Once
lzo is completely finished (necessary to have access to the file
size) the file is sent to S3 or WABS.
TODO: Investigate an optimization to decouple the compression and
upload steps to make sure that the most efficient possible use of
pipelining of network and disk resources occurs. Right now it
possible to bounce back and forth between bottlenecking on reading
from the database block device and subsequently the S3/WABS sending
steps should the processes be at the same stage of the upload
pipeline: this can have a very negative impact on being able to
make full use of system resources.
Furthermore, it desirable to overflowing the page cache: having
separate tunables for number of simultanious compression jobs
(which occupy /tmp space and page cache) and number of uploads
(which affect upload throughput) would help. | [
"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 | 223,621 |
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().
"""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except UserException as e:
self.exceptions.append(e)
return wrapper | 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().
"""
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except UserException as e:
self.exceptions.append(e)
return wrapper | [
"def",
"_exception_gather_guard",
"(",
"self",
",",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*"... | 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 | 223,622 |
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 spurious
warnings.
"""
def lackadaisical_mkdir(place):
ok = False
place = path.realpath(place)
try:
os.makedirs(place, 0o700)
ok = True
except EnvironmentError as e:
if e.errno == errno.EEXIST:
# Has already been created: this is the most
# common situation, and is fine.
ok = True
else:
logger.warning(
msg='could not create prefetch directory',
detail=('Prefetch directory creation target: {0}, {1}'
.format(place, e.strerror)))
return ok
ok = True
for d in [self.prefetched_dir, self.running]:
ok &= lackadaisical_mkdir(d)
lackadaisical_mkdir(self.seg_dir(segment)) | 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 spurious
warnings.
"""
def lackadaisical_mkdir(place):
ok = False
place = path.realpath(place)
try:
os.makedirs(place, 0o700)
ok = True
except EnvironmentError as e:
if e.errno == errno.EEXIST:
# Has already been created: this is the most
# common situation, and is fine.
ok = True
else:
logger.warning(
msg='could not create prefetch directory',
detail=('Prefetch directory creation target: {0}, {1}'
.format(place, e.strerror)))
return ok
ok = True
for d in [self.prefetched_dir, self.running]:
ok &= lackadaisical_mkdir(d)
lackadaisical_mkdir(self.seg_dir(segment)) | [
"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 | 223,623 |
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:
raise SystemExit(err)
try:
fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
raise SystemExit('Already running according to ' + self._pidfile)
pidfile.seek(0)
pidfile.truncate()
pidfile.write(str(os.getpid()) + '\n')
pidfile.flush()
self.pidfile = pidfile
atexit.register(self.release) | 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:
raise SystemExit(err)
try:
fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
raise SystemExit('Already running according to ' + self._pidfile)
pidfile.seek(0)
pidfile.truncate()
pidfile.write(str(os.getpid()) + '\n')
pidfile.flush()
self.pidfile = pidfile
atexit.register(self.release) | [
"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 | 223,624 |
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 | 223,625 |
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 number of syscalls
# when dealing with high-throughput pipes.
if not hasattr(fcntl, 'F_SETPIPE_SZ'):
import platform
if platform.system() == 'Linux':
fcntl.F_SETPIPE_SZ = 1031
# If Linux procfs (or something that looks like it) exposes its
# maximum F_SETPIPE_SZ, adjust the default buffer sizes.
try:
with open('/proc/sys/fs/pipe-max-size', 'r') as f:
# Figure out OS pipe size, but in case it is unusually large
# or small restrain it to sensible values.
OS_PIPE_SZ = min(int(f.read()), 1024 * 1024)
PIPE_BUF_BYTES = max(OS_PIPE_SZ, PIPE_BUF_BYTES)
except Exception:
pass | 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 number of syscalls
# when dealing with high-throughput pipes.
if not hasattr(fcntl, 'F_SETPIPE_SZ'):
import platform
if platform.system() == 'Linux':
fcntl.F_SETPIPE_SZ = 1031
# If Linux procfs (or something that looks like it) exposes its
# maximum F_SETPIPE_SZ, adjust the default buffer sizes.
try:
with open('/proc/sys/fs/pipe-max-size', 'r') as f:
# Figure out OS pipe size, but in case it is unusually large
# or small restrain it to sensible values.
OS_PIPE_SZ = min(int(f.read()), 1024 * 1024)
PIPE_BUF_BYTES = max(OS_PIPE_SZ, PIPE_BUF_BYTES)
except Exception:
pass | [
"def",
"_configure_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 ... | 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 | 223,626 |
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 | 223,627 |
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
of Postgres, but that mechanism is not changing too fast over
the last five years and seems simple enough.
"""
# Recheck that this is not an segment explicitly passed from Postgres
if self.explicit:
raise UserCritical(
msg='unexpected attempt to modify wal metadata detected',
detail=('Segments explicitly passed from postgres should not '
'engage in archiver metadata manipulation: {0}'
.format(self.path)),
hint='report a bug')
# Attempt a rename of archiver metadata, wrapping unexpected
# raised exceptions into a UserCritical.
try:
status_dir = path.join(path.dirname(self.path),
'archive_status')
ready_metadata = path.join(status_dir, self.name + '.ready')
done_metadata = path.join(status_dir, self.name + '.done')
os.rename(ready_metadata, done_metadata)
except Exception:
raise UserCritical(
msg='problem moving .ready archive status to .done',
detail='Traceback is: {0}'.format(traceback.format_exc()),
hint='report a bug') | 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
of Postgres, but that mechanism is not changing too fast over
the last five years and seems simple enough.
"""
# Recheck that this is not an segment explicitly passed from Postgres
if self.explicit:
raise UserCritical(
msg='unexpected attempt to modify wal metadata detected',
detail=('Segments explicitly passed from postgres should not '
'engage in archiver metadata manipulation: {0}'
.format(self.path)),
hint='report a bug')
# Attempt a rename of archiver metadata, wrapping unexpected
# raised exceptions into a UserCritical.
try:
status_dir = path.join(path.dirname(self.path),
'archive_status')
ready_metadata = path.join(status_dir, self.name + '.ready')
done_metadata = path.join(status_dir, self.name + '.done')
os.rename(ready_metadata, done_metadata)
except Exception:
raise UserCritical(
msg='problem moving .ready archive status to .done',
detail='Traceback is: {0}'.format(traceback.format_exc()),
hint='report a bug') | [
"def",
"mark_done",
"(",
"self",
")",
":",
"# Recheck that this is not an segment explicitly passed from Postgres",
"if",
"self",
".",
"explicit",
":",
"raise",
"UserCritical",
"(",
"msg",
"=",
"'unexpected attempt to modify wal metadata detected'",
",",
"detail",
"=",
"(",... | 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 mechanism is not changing too fast over
the last five years and seems simple enough. | [
"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 | 223,628 |
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
# then attempt to force them to exit so join()
# terminates in a reasonable amount of time.
gevent.joinall(list(self.greenlets), timeout=30)
gevent.killall(list(self.greenlets), block=True, timeout=30)
raise val | 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
# then attempt to force them to exit so join()
# terminates in a reasonable amount of time.
gevent.joinall(list(self.greenlets), timeout=30)
gevent.killall(list(self.greenlets), block=True, timeout=30)
raise val | [
"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 | 223,629 |
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._complete_execution)
self.greenlets.add(g)
# Increment .expect before starting the greenlet, or else a
# very unlucky .join could be fooled as to when pool is
# complete.
self.expect += 1
g.start() | 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._complete_execution)
self.greenlets.add(g)
# Increment .expect before starting the greenlet, or else a
# very unlucky .join could be fooled as to when pool is
# complete.
self.expect += 1
g.start() | [
"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 | 223,630 |
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.ready()
self.greenlets.remove(g)
placed = UserCritical(msg='placeholder bogus exception',
hint='report a bug')
if g.successful():
try:
segment = g.get()
if not segment.explicit:
segment.mark_done()
except BaseException as e:
# Absorb and forward exceptions across the channel.
placed = e
else:
placed = None
else:
placed = g.exception
self.wait_change.put(placed) | 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.ready()
self.greenlets.remove(g)
placed = UserCritical(msg='placeholder bogus exception',
hint='report a bug')
if g.successful():
try:
segment = g.get()
if not segment.explicit:
segment.mark_done()
except BaseException as e:
# Absorb and forward exceptions across the channel.
placed = e
else:
placed = None
else:
placed = g.exception
self.wait_change.put(placed) | [
"def",
"_complete_execution",
"(",
"self",
",",
"g",
")",
":",
"# 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",
".",
"ready",
"(",
"... | 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 | 223,631 |
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/python-pipes/
"""
if len(args) < 2:
raise ValueError("pipe needs at least 2 processes")
# Set stdout=PIPE in every subprocess except the last
for i in args[:-1]:
i["stdout"] = subprocess.PIPE
# Runs all subprocesses connecting stdins and stdouts to create the
# pipeline. Closes stdouts to avoid deadlocks.
popens = [popen_sp(**args[0])]
for i in range(1, len(args)):
args[i]["stdin"] = popens[i - 1].stdout
popens.append(popen_sp(**args[i]))
popens[i - 1].stdout.close()
# Returns the array of subprocesses just created
return popens | 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/python-pipes/
"""
if len(args) < 2:
raise ValueError("pipe needs at least 2 processes")
# Set stdout=PIPE in every subprocess except the last
for i in args[:-1]:
i["stdout"] = subprocess.PIPE
# Runs all subprocesses connecting stdins and stdouts to create the
# pipeline. Closes stdouts to avoid deadlocks.
popens = [popen_sp(**args[0])]
for i in range(1, len(args)):
args[i]["stdin"] = popens[i - 1].stdout
popens.append(popen_sp(**args[i]))
popens[i - 1].stdout.close()
# Returns the array of subprocesses just created
return popens | [
"def",
"pipe",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"2",
":",
"raise",
"ValueError",
"(",
"\"pipe needs at least 2 processes\"",
")",
"# Set stdout=PIPE in every subprocess except the last",
"for",
"i",
"in",
"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/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 | 223,632 |
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.copy(popens)
results = [0] * len(popens)
while popens:
last = popens.pop(-1)
results[len(popens)] = last.wait()
return results | 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.copy(popens)
results = [0] * len(popens)
while popens:
last = popens.pop(-1)
results[len(popens)] = last.wait()
return results | [
"def",
"pipe_wait",
"(",
"popens",
")",
":",
"# Avoid mutating the passed copy",
"popens",
"=",
"copy",
".",
"copy",
"(",
"popens",
")",
"results",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"popens",
")",
"while",
"popens",
":",
"last",
"=",
"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/ | [
"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 | 223,633 |
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 | 223,634 |
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:
key = _uri_to_key(creds, url)
with get_download_pipeline(PIPE, decomp_out.f, decrypt) as pl:
g = gevent.spawn(write_and_return_error, key, pl.stdin)
exc = g.get()
if exc is not None:
raise exc
logger.info(
msg='completed download and decompression',
detail='Downloaded and decompressed "{url}" to "{path}"'
.format(url=url, path=path))
return True | 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:
key = _uri_to_key(creds, url)
with get_download_pipeline(PIPE, decomp_out.f, decrypt) as pl:
g = gevent.spawn(write_and_return_error, key, pl.stdin)
exc = g.get()
if exc is not None:
raise exc
logger.info(
msg='completed download and decompression',
detail='Downloaded and decompressed "{url}" to "{path}"'
.format(url=url, path=path))
return True | [
"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 | 223,635 |
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;'
.format(query=sql_command))
new_env = os.environ.copy()
new_env.setdefault('PGOPTIONS', '')
new_env["PGOPTIONS"] += ' --statement-timeout=0'
psql_proc = popen_nonblock([PSQL_BIN, '-d', 'postgres', '--no-password',
'--no-psqlrc', '-c', csv_query],
stdout=PIPE,
env=new_env)
stdout = psql_proc.communicate()[0].decode('utf-8')
if psql_proc.returncode != 0:
if error_handler is not None:
error_handler(psql_proc)
else:
assert error_handler is None
raise UserException(
'could not csv-execute a query successfully via psql',
'Query was "{query}".'.format(sql_command),
'You may have to set some libpq environment '
'variables if you are sure the server is running.')
# Previous code must raise any desired exceptions for non-zero
# exit codes
assert psql_proc.returncode == 0
# Fake enough iterator interface to get a CSV Reader object
# that works.
return csv.reader(iter(stdout.strip().split('\n'))) | 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;'
.format(query=sql_command))
new_env = os.environ.copy()
new_env.setdefault('PGOPTIONS', '')
new_env["PGOPTIONS"] += ' --statement-timeout=0'
psql_proc = popen_nonblock([PSQL_BIN, '-d', 'postgres', '--no-password',
'--no-psqlrc', '-c', csv_query],
stdout=PIPE,
env=new_env)
stdout = psql_proc.communicate()[0].decode('utf-8')
if psql_proc.returncode != 0:
if error_handler is not None:
error_handler(psql_proc)
else:
assert error_handler is None
raise UserException(
'could not csv-execute a query successfully via psql',
'Query was "{query}".'.format(sql_command),
'You may have to set some libpq environment '
'variables if you are sure the server is running.')
# Previous code must raise any desired exceptions for non-zero
# exit codes
assert psql_proc.returncode == 0
# Fake enough iterator interface to get a CSV Reader object
# that works.
return csv.reader(iter(stdout.strip().split('\n'))) | [
"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 | 223,636 |
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(
"SELECT current_setting('server_version_num')"))
if int(version['current_setting']) >= 100000:
cls._WAL_NAME = 'wal'
else:
cls._WAL_NAME = 'xlog'
return cls._WAL_NAME | 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(
"SELECT current_setting('server_version_num')"))
if int(version['current_setting']) >= 100000:
cls._WAL_NAME = 'wal'
else:
cls._WAL_NAME = 'xlog'
return cls._WAL_NAME | [
"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 | 223,637 |
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 start hot backup')
# The difficulty of getting a timezone-stamped, UTC,
# ISO-formatted datetime is downright embarrassing.
#
# See http://bugs.python.org/issue5094
label = 'freeze_start_' + (datetime.datetime.utcnow()
.replace(tzinfo=UTC()).isoformat())
return cls._dict_transform(psql_csv_run(
"SELECT file_name, "
" lpad(file_offset::text, 8, '0') AS file_offset "
"FROM pg_{0}file_name_offset("
" pg_start_backup('{1}'))".format(cls._wal_name(), label),
error_handler=handler)) | 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 start hot backup')
# The difficulty of getting a timezone-stamped, UTC,
# ISO-formatted datetime is downright embarrassing.
#
# See http://bugs.python.org/issue5094
label = 'freeze_start_' + (datetime.datetime.utcnow()
.replace(tzinfo=UTC()).isoformat())
return cls._dict_transform(psql_csv_run(
"SELECT file_name, "
" lpad(file_offset::text, 8, '0') AS file_offset "
"FROM pg_{0}file_name_offset("
" pg_start_backup('{1}'))".format(cls._wal_name(), label),
error_handler=handler)) | [
"def",
"run_start_backup",
"(",
"cls",
")",
":",
"def",
"handler",
"(",
"popen",
")",
":",
"assert",
"popen",
".",
"returncode",
"!=",
"0",
"raise",
"UserException",
"(",
"'Could not start hot backup'",
")",
"# The difficulty of getting a timezone-stamped, UTC,",
"# I... | Connects to a server and attempts to start a hot backup
Yields the WAL information in a dictionary for bookkeeping and
recording. | [
"Connects",
"to",
"a",
"server",
"and",
"attempts",
"to",
"start",
"a",
"hot",
"backup"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/pg/psql_worker.py#L109-L133 | train | 223,638 |
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 UserException('Could not stop hot backup')
return cls._dict_transform(psql_csv_run(
"SELECT file_name, "
" lpad(file_offset::text, 8, '0') AS file_offset "
"FROM pg_{0}file_name_offset("
" pg_stop_backup())".format(cls._wal_name()),
error_handler=handler)) | 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 UserException('Could not stop hot backup')
return cls._dict_transform(psql_csv_run(
"SELECT file_name, "
" lpad(file_offset::text, 8, '0') AS file_offset "
"FROM pg_{0}file_name_offset("
" pg_stop_backup())".format(cls._wal_name()),
error_handler=handler)) | [
"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 | 223,639 |
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.
"""
parts = s.split('.')
if len(parts) != 4:
return False
for part in parts:
try:
int(part)
except ValueError:
return False
return True | 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.
"""
parts = s.split('.')
if len(parts) != 4:
return False
for part in parts:
try:
int(part)
except ValueError:
return False
return True | [
"def",
"_is_ipv4_like",
"(",
"s",
")",
":",
"parts",
"=",
"s",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"!=",
"4",
":",
"return",
"False",
"for",
"part",
"in",
"parts",
":",
"try",
":",
"int",
"(",
"part",
")",
"except",
"... | Find if a string superficially looks like an IPv4 address.
AWS documentation plays it fast and loose with this; in other
regions, it seems like even non-valid IPv4 addresses (in
particular, ones that possess decimal numbers out of range for
IPv4) are rejected. | [
"Find",
"if",
"a",
"string",
"superficially",
"looks",
"like",
"an",
"IPv4",
"address",
"."
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L43-L62 | train | 223,640 |
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 and
len(bucket_name) >= 3 and
len(bucket_name) <= 63 and
'_' not in bucket_name and
'..' not in bucket_name and
'-.' not in bucket_name and
'.-' not in bucket_name and
not bucket_name.startswith('-') and
not bucket_name.endswith('-') and
not bucket_name.startswith('.') and
not bucket_name.endswith('.') and
not _is_ipv4_like(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 and
len(bucket_name) >= 3 and
len(bucket_name) <= 63 and
'_' not in bucket_name and
'..' not in bucket_name and
'-.' not in bucket_name and
'.-' not in bucket_name and
not bucket_name.startswith('-') and
not bucket_name.endswith('-') and
not bucket_name.startswith('.') and
not bucket_name.endswith('.') and
not _is_ipv4_like(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 | 223,641 |
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).
Versions below 2.6 don't support the validate_certs option to
S3Connection, and enable it via configuration option just seems to
cause an error.
"""
if tuple(int(x) for x in boto.__version__.split('.')) >= (2, 6, 0):
kwargs['validate_certs'] = True
kwargs['is_secure'] = True
auth_region_name = kwargs.pop('auth_region_name', None)
conn = connection.S3Connection(*args, **kwargs)
if auth_region_name:
conn.auth_region_name = auth_region_name
return conn | 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).
Versions below 2.6 don't support the validate_certs option to
S3Connection, and enable it via configuration option just seems to
cause an error.
"""
if tuple(int(x) for x in boto.__version__.split('.')) >= (2, 6, 0):
kwargs['validate_certs'] = True
kwargs['is_secure'] = True
auth_region_name = kwargs.pop('auth_region_name', None)
conn = connection.S3Connection(*args, **kwargs)
if auth_region_name:
conn.auth_region_name = auth_region_name
return conn | [
"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 option to
S3Connection, and enable it via configuration option just seems to
cause an error. | [
"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 | 223,642 |
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
# AWS_REGION environment variable.
if region is None:
region = os.getenv('AWS_REGION')
mostly_ok = _is_mostly_subdomain_compatible(bucket_name)
if not mostly_ok:
return CallingInfo(
bucket_name=bucket_name,
region=region,
calling_format=connection.OrdinaryCallingFormat,
ordinary_endpoint=must_resolve(region))
else:
if '.' in bucket_name:
# The bucket_name might have been DNS compatible, but once
# dots are involved TLS certificate validations will
# certainly fail even if that's the case.
return CallingInfo(
bucket_name=bucket_name,
calling_format=connection.OrdinaryCallingFormat,
region=region,
ordinary_endpoint=must_resolve(region))
else:
# If the bucket follows naming rules and has no dots in
# the name, SubdomainCallingFormat can be used, with TLS,
# world-wide.
return CallingInfo(
bucket_name=bucket_name,
calling_format=connection.SubdomainCallingFormat,
region=region,
ordinary_endpoint=None)
assert False | 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
# AWS_REGION environment variable.
if region is None:
region = os.getenv('AWS_REGION')
mostly_ok = _is_mostly_subdomain_compatible(bucket_name)
if not mostly_ok:
return CallingInfo(
bucket_name=bucket_name,
region=region,
calling_format=connection.OrdinaryCallingFormat,
ordinary_endpoint=must_resolve(region))
else:
if '.' in bucket_name:
# The bucket_name might have been DNS compatible, but once
# dots are involved TLS certificate validations will
# certainly fail even if that's the case.
return CallingInfo(
bucket_name=bucket_name,
calling_format=connection.OrdinaryCallingFormat,
region=region,
ordinary_endpoint=must_resolve(region))
else:
# If the bucket follows naming rules and has no dots in
# the name, SubdomainCallingFormat can be used, with TLS,
# world-wide.
return CallingInfo(
bucket_name=bucket_name,
calling_format=connection.SubdomainCallingFormat,
region=region,
ordinary_endpoint=None)
assert False | [
"def",
"from_store_name",
"(",
"bucket_name",
",",
"region",
"=",
"None",
")",
":",
"# Late-bind `region` for the sake of tests that inject the",
"# AWS_REGION environment variable.",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"os",
".",
"getenv",
"(",
"'AWS_REGI... | Construct a CallingInfo value from a bucket name.
This is useful to encapsulate the ugliness of setting up S3
connections, especially with regions and TLS certificates are
involved. | [
"Construct",
"a",
"CallingInfo",
"value",
"from",
"a",
"bucket",
"name",
"."
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/s3/calling_format.py#L242-L282 | train | 223,643 |
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
credentials to fluctuate rapidly. By comparison, region
fluctuations of a bucket name are not nearly so likely versus
the gains of not looking up a bucket's region over and over.
"""
def _conn_help(*args, **kwargs):
return _connect_secureish(
*args,
provider=creds,
calling_format=self.calling_format(),
auth_region_name=self.region,
**kwargs)
# If WALE_S3_ENDPOINT is set, do not attempt to guess
# the right calling conventions and instead honor the explicit
# settings within WALE_S3_ENDPOINT.
impl = os.getenv('WALE_S3_ENDPOINT')
if impl:
return connection.S3Connection(**_s3connection_opts_from_uri(impl))
# Check if subdomain format compatible: if so, use the
# BUCKETNAME.s3.amazonaws.com hostname to communicate with the
# bucket.
if self.calling_format is connection.SubdomainCallingFormat:
return _conn_help(host='s3.amazonaws.com')
# Check if OrdinaryCallingFormat compatible, but also see if
# the endpoint has already been set, in which case only
# setting the host= flag is necessary.
assert self.calling_format is connection.OrdinaryCallingFormat
assert self.ordinary_endpoint is not None
return _conn_help(host=self.ordinary_endpoint) | 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
credentials to fluctuate rapidly. By comparison, region
fluctuations of a bucket name are not nearly so likely versus
the gains of not looking up a bucket's region over and over.
"""
def _conn_help(*args, **kwargs):
return _connect_secureish(
*args,
provider=creds,
calling_format=self.calling_format(),
auth_region_name=self.region,
**kwargs)
# If WALE_S3_ENDPOINT is set, do not attempt to guess
# the right calling conventions and instead honor the explicit
# settings within WALE_S3_ENDPOINT.
impl = os.getenv('WALE_S3_ENDPOINT')
if impl:
return connection.S3Connection(**_s3connection_opts_from_uri(impl))
# Check if subdomain format compatible: if so, use the
# BUCKETNAME.s3.amazonaws.com hostname to communicate with the
# bucket.
if self.calling_format is connection.SubdomainCallingFormat:
return _conn_help(host='s3.amazonaws.com')
# Check if OrdinaryCallingFormat compatible, but also see if
# the endpoint has already been set, in which case only
# setting the host= flag is necessary.
assert self.calling_format is connection.OrdinaryCallingFormat
assert self.ordinary_endpoint is not None
return _conn_help(host=self.ordinary_endpoint) | [
"def",
"connect",
"(",
"self",
",",
"creds",
")",
":",
"def",
"_conn_help",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_connect_secureish",
"(",
"*",
"args",
",",
"provider",
"=",
"creds",
",",
"calling_format",
"=",
"self",
".",
... | Return a boto S3Connection set up with great care.
This includes TLS settings, calling format selection, and
region detection.
The credentials are applied by the caller because in many
cases (instance-profile IAM) it is possible for those
credentials to fluctuate rapidly. By comparison, region
fluctuations of a bucket name are not nearly so likely versus
the gains of not looking up a bucket's region over and over. | [
"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 | 223,644 |
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 | 223,645 |
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 | 223,646 |
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 necessary for throughput and makes more obscure the
cause of failures. This is intended to be a time and frustration
saving measure. This problem has confused The Author in practice
when switching rapidly between machines.
"""
could_not_run = []
error_msgs = []
def psql_err_handler(popen):
assert popen.returncode != 0
error_msgs.append(textwrap.fill(
'Could not get a connection to the database: '
'note that superuser access is required'))
# Bogus error message that is re-caught and re-raised
raise EnvironmentError('INTERNAL: Had problems running psql '
'from external_program_check')
with open(os.devnull, 'wb') as nullf:
for program in to_check:
try:
if program is PSQL_BIN:
psql_csv_run('SELECT 1', error_handler=psql_err_handler)
else:
if program is PV_BIN:
extra_args = ['--quiet']
else:
extra_args = []
proc = popen_sp([program] + extra_args,
stdout=nullf, stderr=nullf,
stdin=subprocess.PIPE)
# Close stdin for processes that default to
# reading from the pipe; the programs WAL-E uses
# of this kind will terminate in this case.
proc.stdin.close()
proc.wait()
except EnvironmentError:
could_not_run.append(program)
if could_not_run:
error_msgs.append(
'Could not run the following programs, are they installed? ' +
', '.join(could_not_run))
if error_msgs:
raise UserException(
'could not run one or more external programs WAL-E depends upon',
'\n'.join(error_msgs))
return None | 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 necessary for throughput and makes more obscure the
cause of failures. This is intended to be a time and frustration
saving measure. This problem has confused The Author in practice
when switching rapidly between machines.
"""
could_not_run = []
error_msgs = []
def psql_err_handler(popen):
assert popen.returncode != 0
error_msgs.append(textwrap.fill(
'Could not get a connection to the database: '
'note that superuser access is required'))
# Bogus error message that is re-caught and re-raised
raise EnvironmentError('INTERNAL: Had problems running psql '
'from external_program_check')
with open(os.devnull, 'wb') as nullf:
for program in to_check:
try:
if program is PSQL_BIN:
psql_csv_run('SELECT 1', error_handler=psql_err_handler)
else:
if program is PV_BIN:
extra_args = ['--quiet']
else:
extra_args = []
proc = popen_sp([program] + extra_args,
stdout=nullf, stderr=nullf,
stdin=subprocess.PIPE)
# Close stdin for processes that default to
# reading from the pipe; the programs WAL-E uses
# of this kind will terminate in this case.
proc.stdin.close()
proc.wait()
except EnvironmentError:
could_not_run.append(program)
if could_not_run:
error_msgs.append(
'Could not run the following programs, are they installed? ' +
', '.join(could_not_run))
if error_msgs:
raise UserException(
'could not run one or more external programs WAL-E depends upon',
'\n'.join(error_msgs))
return None | [
"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 be a time and frustration
saving measure. This problem has confused The Author in practice
when switching rapidly between machines. | [
"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 | 223,647 |
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 | 223,648 |
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(option, env))
else:
return 'Set the environment variable {0}.'.format(env) | 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(option, env))
else:
return 'Set the environment variable {0}.'.format(env) | [
"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 | 223,649 |
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 | 223,650 |
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('.lzo')
blobstore = get_blobstore(storage.StorageLayout(url))
with tempfile.NamedTemporaryFile(
mode='r+b', buffering=pipebuf.PIPE_BUF_BYTES) as tf:
with pipeline.get_upload_pipeline(
open(local_path, 'rb'), tf, gpg_key=gpg_key):
pass
tf.flush()
clock_start = time.time()
tf.seek(0)
k = blobstore.uri_put_file(creds, url, tf)
clock_finish = time.time()
kib_per_second = format_kib_per_second(
clock_start, clock_finish, k.size)
return kib_per_second | 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('.lzo')
blobstore = get_blobstore(storage.StorageLayout(url))
with tempfile.NamedTemporaryFile(
mode='r+b', buffering=pipebuf.PIPE_BUF_BYTES) as tf:
with pipeline.get_upload_pipeline(
open(local_path, 'rb'), tf, gpg_key=gpg_key):
pass
tf.flush()
clock_start = time.time()
tf.seek(0)
k = blobstore.uri_put_file(creds, url, tf)
clock_finish = time.time()
kib_per_second = format_kib_per_second(
clock_start, clock_finish, k.size)
return kib_per_second | [
"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 | 223,651 |
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, path, decrypt, do_retry=do_retry) | 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, path, decrypt, do_retry=do_retry) | [
"def",
"do_lzop_get",
"(",
"creds",
",",
"url",
",",
"path",
",",
"decrypt",
",",
"do_retry",
"=",
"True",
")",
":",
"blobstore",
"=",
"get_blobstore",
"(",
"storage",
".",
"StorageLayout",
"(",
"url",
")",
")",
"return",
"blobstore",
".",
"do_lzop_get",
... | Get and decompress an S3 or WABS URL
This streams the content directly to lzop; the compressed version
is never stored on disk. | [
"Get",
"and",
"decompress",
"an",
"S3",
"or",
"WABS",
"URL"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/worker_util.py#L49-L58 | train | 223,652 |
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.match(storage.BASE_BACKUP_REGEXP, query)
if match is not None:
for backup in iter(self):
if backup.name == query:
yield backup
elif query == 'LATEST':
all_backups = list(iter(self))
if not all_backups:
return
assert len(all_backups) > 0
all_backups.sort(key=lambda bi: bi.last_modified)
yield all_backups[-1]
else:
raise exception.UserException(
msg='invalid backup query submitted',
detail='The submitted query operator was "{0}."'
.format(query)) | 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.match(storage.BASE_BACKUP_REGEXP, query)
if match is not None:
for backup in iter(self):
if backup.name == query:
yield backup
elif query == 'LATEST':
all_backups = list(iter(self))
if not all_backups:
return
assert len(all_backups) > 0
all_backups.sort(key=lambda bi: bi.last_modified)
yield all_backups[-1]
else:
raise exception.UserException(
msg='invalid backup query submitted',
detail='The submitted query operator was "{0}."'
.format(query)) | [
"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 | 223,653 |
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()):
key_name = self.layout.key_name(key)
bucket = self._container_name(key)
url = '{scm}://{bucket}/{name}'.format(scm=self.layout.scheme,
bucket=bucket,
name=key_name)
key_parts = key_name.split('/')
key_depth = len(key_parts)
if key_depth != wal_key_depth:
logger.warning(
msg="skipping non-qualifying key in 'delete before'",
detail=(
'The unexpected key is "{0}", and it appears to be '
'at an unexpected depth.'.format(url)),
hint=generic_weird_key_hint_message)
elif key_depth == wal_key_depth:
segment_match = (re.match(storage.SEGMENT_REGEXP + r'\.lzo',
key_parts[-1]))
label_match = (re.match(storage.SEGMENT_REGEXP +
r'\.[A-F0-9]{8,8}.backup.lzo',
key_parts[-1]))
history_match = re.match(r'[A-F0-9]{8,8}\.history',
key_parts[-1])
all_matches = [segment_match, label_match, history_match]
non_matches = len(list(m for m in all_matches if m is None))
# These patterns are intended to be mutually
# exclusive, so either one should match or none should
# match.
assert non_matches in (len(all_matches) - 1, len(all_matches))
if non_matches == len(all_matches):
logger.warning(
msg="skipping non-qualifying key in 'delete before'",
detail=('The unexpected key is "{0}", and it appears '
'not to match the WAL file naming pattern.'
.format(url)),
hint=generic_weird_key_hint_message)
elif segment_match is not None:
scanned_sn = self._groupdict_to_segment_number(
segment_match.groupdict())
self._delete_if_before(segment_info, scanned_sn, key,
'a wal file')
elif label_match is not None:
scanned_sn = self._groupdict_to_segment_number(
label_match.groupdict())
self._delete_if_before(segment_info, scanned_sn, key,
'a backup history file')
elif history_match is not None:
# History (timeline) files do not have any actual
# WAL position information, so they are never
# deleted.
pass
else:
assert False
else:
assert False | 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()):
key_name = self.layout.key_name(key)
bucket = self._container_name(key)
url = '{scm}://{bucket}/{name}'.format(scm=self.layout.scheme,
bucket=bucket,
name=key_name)
key_parts = key_name.split('/')
key_depth = len(key_parts)
if key_depth != wal_key_depth:
logger.warning(
msg="skipping non-qualifying key in 'delete before'",
detail=(
'The unexpected key is "{0}", and it appears to be '
'at an unexpected depth.'.format(url)),
hint=generic_weird_key_hint_message)
elif key_depth == wal_key_depth:
segment_match = (re.match(storage.SEGMENT_REGEXP + r'\.lzo',
key_parts[-1]))
label_match = (re.match(storage.SEGMENT_REGEXP +
r'\.[A-F0-9]{8,8}.backup.lzo',
key_parts[-1]))
history_match = re.match(r'[A-F0-9]{8,8}\.history',
key_parts[-1])
all_matches = [segment_match, label_match, history_match]
non_matches = len(list(m for m in all_matches if m is None))
# These patterns are intended to be mutually
# exclusive, so either one should match or none should
# match.
assert non_matches in (len(all_matches) - 1, len(all_matches))
if non_matches == len(all_matches):
logger.warning(
msg="skipping non-qualifying key in 'delete before'",
detail=('The unexpected key is "{0}", and it appears '
'not to match the WAL file naming pattern.'
.format(url)),
hint=generic_weird_key_hint_message)
elif segment_match is not None:
scanned_sn = self._groupdict_to_segment_number(
segment_match.groupdict())
self._delete_if_before(segment_info, scanned_sn, key,
'a wal file')
elif label_match is not None:
scanned_sn = self._groupdict_to_segment_number(
label_match.groupdict())
self._delete_if_before(segment_info, scanned_sn, key,
'a backup history file')
elif history_match is not None:
# History (timeline) files do not have any actual
# WAL position information, so they are never
# deleted.
pass
else:
assert False
else:
assert False | [
"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 | 223,654 |
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 obsolete version)
* Completely obliterate all backups (from a decommissioned
database, for example)
"""
for k in self._backup_list(prefix=self.layout.basebackups()):
self._maybe_delete_key(k, 'part of a base backup')
for k in self._backup_list(prefix=self.layout.wal_directory()):
self._maybe_delete_key(k, 'part of wal logs')
if self.deleter:
self.deleter.close() | 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 obsolete version)
* Completely obliterate all backups (from a decommissioned
database, for example)
"""
for k in self._backup_list(prefix=self.layout.basebackups()):
self._maybe_delete_key(k, 'part of a base backup')
for k in self._backup_list(prefix=self.layout.wal_directory()):
self._maybe_delete_key(k, 'part of wal logs')
if self.deleter:
self.deleter.close() | [
"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 obliterate all backups (from a decommissioned
database, for example) | [
"Delete",
"everything",
"in",
"a",
"storage",
"layout"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L395-L415 | train | 223,655 |
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_backups_before(segment_info)
# This will delete all WAL segments before segment_info.
self._delete_wals_before(segment_info)
if self.deleter:
self.deleter.close() | 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_backups_before(segment_info)
# This will delete all WAL segments before segment_info.
self._delete_wals_before(segment_info)
if self.deleter:
self.deleter.close() | [
"def",
"delete_before",
"(",
"self",
",",
"segment_info",
")",
":",
"# This will delete all base backup data before segment_info.",
"self",
".",
"_delete_base_backups_before",
"(",
"segment_info",
")",
"# This will delete all WAL segments before segment_info.",
"self",
".",
"_del... | Delete all base backups and WAL before a given segment
This is the most commonly-used deletion operator; to delete
old backups and WAL. | [
"Delete",
"all",
"base",
"backups",
"and",
"WAL",
"before",
"a",
"given",
"segment"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L417-L433 | train | 223,656 |
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
# completed backups.
completed_basebackups = []
for key in self._backup_list(prefix=self.layout.basebackups()):
key_name = self.layout.key_name(key)
key_parts = key_name.split('/')
key_depth = len(key_parts)
url = '{scheme}://{bucket}/{name}'.format(
scheme=self.layout.scheme,
bucket=self._container_name(key),
name=key_name)
if key_depth == base_backup_sentinel_depth:
# This is a key at the depth of a base-backup-sentinel file.
# Check to see if it matches the known form.
match = re.match(storage.COMPLETE_BASE_BACKUP_REGEXP,
key_parts[-1])
# If this isn't a base-backup-sentinel file, just ignore it.
if match is None:
continue
# This key corresponds to a base-backup-sentinel file and
# represents a completed backup. Grab its segment number.
scanned_sn = \
self._groupdict_to_segment_number(match.groupdict())
completed_basebackups.append(dict(
scanned_sn=scanned_sn,
url=url))
# Sort the base backups from newest to oldest.
basebackups = sorted(
completed_basebackups,
key=lambda backup: backup['scanned_sn'].as_an_integer,
reverse=True)
last_retained = None
if len(basebackups) <= num_to_retain:
detail = None
if len(basebackups) == 0:
msg = 'Not deleting any data.'
detail = 'No existing base backups.'
elif len(basebackups) == 1:
last_retained = basebackups[-1]
msg = 'Retaining existing base backup.'
else:
last_retained = basebackups[-1]
msg = "Retaining all %d base backups." % len(basebackups)
else:
last_retained = basebackups[num_to_retain - 1]
num_deleting = len(basebackups) - num_to_retain
msg = "Deleting %d oldest base backups." % num_deleting
detail = "Found %d total base backups." % len(basebackups)
log_message = dict(msg=msg)
if detail is not None:
log_message['detail'] = detail
if last_retained is not None:
log_message['hint'] = \
"Deleting keys older than %s." % last_retained['url']
logger.info(**log_message)
# This will delete all base backup and WAL data before
# last_retained['scanned_sn'].
if last_retained is not None:
self._delete_base_backups_before(last_retained['scanned_sn'])
self._delete_wals_before(last_retained['scanned_sn'])
if self.deleter:
self.deleter.close() | 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
# completed backups.
completed_basebackups = []
for key in self._backup_list(prefix=self.layout.basebackups()):
key_name = self.layout.key_name(key)
key_parts = key_name.split('/')
key_depth = len(key_parts)
url = '{scheme}://{bucket}/{name}'.format(
scheme=self.layout.scheme,
bucket=self._container_name(key),
name=key_name)
if key_depth == base_backup_sentinel_depth:
# This is a key at the depth of a base-backup-sentinel file.
# Check to see if it matches the known form.
match = re.match(storage.COMPLETE_BASE_BACKUP_REGEXP,
key_parts[-1])
# If this isn't a base-backup-sentinel file, just ignore it.
if match is None:
continue
# This key corresponds to a base-backup-sentinel file and
# represents a completed backup. Grab its segment number.
scanned_sn = \
self._groupdict_to_segment_number(match.groupdict())
completed_basebackups.append(dict(
scanned_sn=scanned_sn,
url=url))
# Sort the base backups from newest to oldest.
basebackups = sorted(
completed_basebackups,
key=lambda backup: backup['scanned_sn'].as_an_integer,
reverse=True)
last_retained = None
if len(basebackups) <= num_to_retain:
detail = None
if len(basebackups) == 0:
msg = 'Not deleting any data.'
detail = 'No existing base backups.'
elif len(basebackups) == 1:
last_retained = basebackups[-1]
msg = 'Retaining existing base backup.'
else:
last_retained = basebackups[-1]
msg = "Retaining all %d base backups." % len(basebackups)
else:
last_retained = basebackups[num_to_retain - 1]
num_deleting = len(basebackups) - num_to_retain
msg = "Deleting %d oldest base backups." % num_deleting
detail = "Found %d total base backups." % len(basebackups)
log_message = dict(msg=msg)
if detail is not None:
log_message['detail'] = detail
if last_retained is not None:
log_message['hint'] = \
"Deleting keys older than %s." % last_retained['url']
logger.info(**log_message)
# This will delete all base backup and WAL data before
# last_retained['scanned_sn'].
if last_retained is not None:
self._delete_base_backups_before(last_retained['scanned_sn'])
self._delete_wals_before(last_retained['scanned_sn'])
if self.deleter:
self.deleter.close() | [
"def",
"delete_with_retention",
"(",
"self",
",",
"num_to_retain",
")",
":",
"base_backup_sentinel_depth",
"=",
"self",
".",
"layout",
".",
"basebackups",
"(",
")",
".",
"count",
"(",
"'/'",
")",
"+",
"1",
"# Sweep over base backup files, collecting sentinel files fro... | Retain the num_to_retain most recent backups and delete all data
before them. | [
"Retain",
"the",
"num_to_retain",
"most",
"recent",
"backups",
"and",
"delete",
"all",
"data",
"before",
"them",
"."
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/base.py#L435-L511 | train | 223,657 |
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={
"region_name": creds.region,
"endpoint_type": creds.endpoint_type,
"domain_id": creds.domain_id,
"domain_name": creds.domain_name,
"tenant_id": creds.tenant_id,
"user_id": creds.user_id,
"user_domain_id": creds.user_domain_id,
"user_domain_name": creds.user_domain_name,
"project_id": creds.project_id,
"project_name": creds.project_name,
"project_domain_id": creds.project_domain_id,
"project_domain_name": creds.project_domain_name,
}
) | 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={
"region_name": creds.region,
"endpoint_type": creds.endpoint_type,
"domain_id": creds.domain_id,
"domain_name": creds.domain_name,
"tenant_id": creds.tenant_id,
"user_id": creds.user_id,
"user_domain_id": creds.user_domain_id,
"user_domain_name": creds.user_domain_name,
"project_id": creds.project_id,
"project_name": creds.project_name,
"project_domain_id": creds.project_domain_id,
"project_domain_name": creds.project_domain_name,
}
) | [
"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 | 223,658 |
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, project=project,
credentials=credentials) | 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, project=project,
credentials=credentials) | [
"def",
"connect",
"(",
"creds",
",",
"max_retries",
"=",
"100",
")",
":",
"credentials",
",",
"project",
"=",
"google",
".",
"auth",
".",
"default",
"(",
")",
"return",
"RetryClient",
"(",
"max_retries",
"=",
"max_retries",
",",
"project",
"=",
"project",
... | Construct a connection value to Google Storage API
The credentials are retrieved using get_credentials that checks
the environment for the correct values. | [
"Construct",
"a",
"connection",
"value",
"to",
"Google",
"Storage",
"API"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/blobstore/gs/calling_format.py#L6-L15 | train | 223,659 |
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) tuple (with the intention that it could raise the
exception without losing the traceback) and the exception
processor's optionally usable context value (exc_processor_cxt).
It's recommended to delete all references to the traceback passed
to the exception_processor to speed up garbage collector via the
'del' operator.
This context value is passed to and returned from every invocation
of the exception processor. This can be used to more conveniently
(vs. an object with __call__ defined) implement exception
processors that have some state, such as the 'number of attempts'.
The first invocation will pass None.
:param f: A function to be retried.
:type f: function
:param exception_processor: A function to process raised
exceptions.
:type exception_processor: function
:param max_retries: An integer representing the maximum
number of retry attempts.
:type max_retries: integer
"""
max_retries = int(os.getenv('WALE_RETRIES', max_retries))
def yield_new_function_from(f):
def shim(*args, **kwargs):
exc_processor_cxt = None
retries = 0
while True:
# Avoid livelocks while spinning on retry by yielding.
gevent.sleep(0.1)
try:
return f(*args, **kwargs)
except KeyboardInterrupt:
raise
except Exception:
exception_info_tuple = None
retries += 1
if max_retries >= 1 and retries >= max_retries:
raise
try:
exception_info_tuple = sys.exc_info()
exc_processor_cxt = exception_processor(
exception_info_tuple,
exc_processor_cxt=exc_processor_cxt)
finally:
# Although cycles are harmless long-term, help the
# garbage collector.
del exception_info_tuple
# Exponential backoff with jitter capped at 2 minutes.
duration = min(120, (2 ** retries)) / 2
gevent.sleep(duration + random.randint(0, duration))
return functools.wraps(f)(shim)
return yield_new_function_from | 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) tuple (with the intention that it could raise the
exception without losing the traceback) and the exception
processor's optionally usable context value (exc_processor_cxt).
It's recommended to delete all references to the traceback passed
to the exception_processor to speed up garbage collector via the
'del' operator.
This context value is passed to and returned from every invocation
of the exception processor. This can be used to more conveniently
(vs. an object with __call__ defined) implement exception
processors that have some state, such as the 'number of attempts'.
The first invocation will pass None.
:param f: A function to be retried.
:type f: function
:param exception_processor: A function to process raised
exceptions.
:type exception_processor: function
:param max_retries: An integer representing the maximum
number of retry attempts.
:type max_retries: integer
"""
max_retries = int(os.getenv('WALE_RETRIES', max_retries))
def yield_new_function_from(f):
def shim(*args, **kwargs):
exc_processor_cxt = None
retries = 0
while True:
# Avoid livelocks while spinning on retry by yielding.
gevent.sleep(0.1)
try:
return f(*args, **kwargs)
except KeyboardInterrupt:
raise
except Exception:
exception_info_tuple = None
retries += 1
if max_retries >= 1 and retries >= max_retries:
raise
try:
exception_info_tuple = sys.exc_info()
exc_processor_cxt = exception_processor(
exception_info_tuple,
exc_processor_cxt=exc_processor_cxt)
finally:
# Although cycles are harmless long-term, help the
# garbage collector.
del exception_info_tuple
# Exponential backoff with jitter capped at 2 minutes.
duration = min(120, (2 ** retries)) / 2
gevent.sleep(duration + random.randint(0, duration))
return functools.wraps(f)(shim)
return yield_new_function_from | [
"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 traceback) and the exception
processor's optionally usable context value (exc_processor_cxt).
It's recommended to delete all references to the traceback passed
to the exception_processor to speed up garbage collector via the
'del' operator.
This context value is passed to and returned from every invocation
of the exception processor. This can be used to more conveniently
(vs. an object with __call__ defined) implement exception
processors that have some state, such as the 'number of attempts'.
The first invocation will pass None.
:param f: A function to be retried.
:type f: function
:param exception_processor: A function to process raised
exceptions.
:type exception_processor: function
:param max_retries: An integer representing the maximum
number of retry attempts.
:type max_retries: integer | [
"Generic",
"retry",
"decorator"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/retries.py#L42-L112 | train | 223,660 |
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
self.member_burden += len(tpart)
g.start() | 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
self.member_burden += len(tpart)
g.start() | [
"def",
"_start",
"(",
"self",
",",
"tpart",
")",
":",
"g",
"=",
"gevent",
".",
"Greenlet",
"(",
"self",
".",
"uploader",
",",
"tpart",
")",
"g",
".",
"link",
"(",
"self",
".",
"_finish",
")",
"# Account for concurrency_burden before starting the greenlet",
"... | Start upload and accout for resource consumption. | [
"Start",
"upload",
"and",
"accout",
"for",
"resource",
"consumption",
"."
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L29-L40 | train | 223,661 |
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()
self.wait_change.put(finished_tpart)
else:
self.wait_change.put(g.exception) | 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()
self.wait_change.put(finished_tpart)
else:
self.wait_change.put(g.exception) | [
"def",
"_finish",
"(",
"self",
",",
"g",
")",
":",
"assert",
"g",
".",
"ready",
"(",
")",
"if",
"g",
".",
"successful",
"(",
")",
":",
"finished_tpart",
"=",
"g",
".",
"get",
"(",
")",
"self",
".",
"wait_change",
".",
"put",
"(",
"finished_tpart",
... | Called on completion of an upload greenlet.
Takes care to forward Exceptions or, if there is no error, the
finished TarPartition value across a channel. | [
"Called",
"on",
"completion",
"of",
"an",
"upload",
"greenlet",
"."
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L42-L54 | train | 223,662 |
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
else:
# Uncharge for resources.
self.member_burden -= len(val)
self.concurrency_burden -= 1 | 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
else:
# Uncharge for resources.
self.member_burden -= len(val)
self.concurrency_burden -= 1 | [
"def",
"_wait",
"(",
"self",
")",
":",
"val",
"=",
"self",
".",
"wait_change",
".",
"get",
"(",
")",
"if",
"isinstance",
"(",
"val",
",",
"Exception",
")",
":",
"# Don't other uncharging, because execution is going to stop",
"raise",
"val",
"else",
":",
"# Unc... | Block until an upload finishes
Raise an exception if that tar volume failed with an error. | [
"Block",
"until",
"an",
"upload",
"finishes"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/worker/upload_pool.py#L56-L69 | train | 223,663 |
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',
hint='report a bug')
while True:
too_many = (
self.concurrency_burden + 1 > self.max_concurrency
or self.member_burden + len(tpart) > self.max_members
)
if too_many:
# If there are not enough resources to start an upload
# even with zero uploads in progress, then something
# has gone wrong: the user should not be given enough
# rope to hang themselves in this way.
if self.concurrency_burden == 0:
raise UserCritical(
msg=('not enough resources in pool to '
'support an upload'),
hint='report a bug')
# _wait blocks until an upload finishes and clears its
# used resources, after which another attempt to
# evaluate scheduling resources for another upload
# might be worth evaluating.
#
# Alternatively, an error was encountered in a
# previous upload in which case it'll be raised here
# and cause the process to regard the upload as a
# failure.
self._wait()
gc.collect()
else:
# Enough resources available: commence upload
self._start(tpart)
return | 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',
hint='report a bug')
while True:
too_many = (
self.concurrency_burden + 1 > self.max_concurrency
or self.member_burden + len(tpart) > self.max_members
)
if too_many:
# If there are not enough resources to start an upload
# even with zero uploads in progress, then something
# has gone wrong: the user should not be given enough
# rope to hang themselves in this way.
if self.concurrency_burden == 0:
raise UserCritical(
msg=('not enough resources in pool to '
'support an upload'),
hint='report a bug')
# _wait blocks until an upload finishes and clears its
# used resources, after which another attempt to
# evaluate scheduling resources for another upload
# might be worth evaluating.
#
# Alternatively, an error was encountered in a
# previous upload in which case it'll be raised here
# and cause the process to regard the upload as a
# failure.
self._wait()
gc.collect()
else:
# Enough resources available: commence upload
self._start(tpart)
return | [
"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 | 223,664 |
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 preserve: set
:return: None
"""
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY:
maxfd = 4096
for fileno in range(maxfd):
if fileno not in preserve:
try:
os.close(fileno)
except OSError as err:
if not err.errno == errno.EBADF:
raise DaemonError(
'Failed to close file descriptor {0}: {1}'
.format(fileno, err)) | 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 preserve: set
:return: None
"""
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if maxfd == resource.RLIM_INFINITY:
maxfd = 4096
for fileno in range(maxfd):
if fileno not in preserve:
try:
os.close(fileno)
except OSError as err:
if not err.errno == errno.EBADF:
raise DaemonError(
'Failed to close file descriptor {0}: {1}'
.format(fileno, err)) | [
"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 | 223,665 |
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(signal, name):
signal_map[getattr(signal, name)] = target
return signal_map | 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(signal, name):
signal_map[getattr(signal, name)] = target
return signal_map | [
"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 | 223,666 |
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,
socket.SOCK_RAW)
try:
sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
result = True
except (OSError, socket.error) as err:
if not err.args[0] == errno.ENOTSOCK:
result = True
return result | 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,
socket.SOCK_RAW)
try:
sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
result = True
except (OSError, socket.error) as err:
if not err.args[0] == errno.ENOTSOCK:
result = True
return result | [
"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 | 223,667 |
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
:return: None
:raise: DaemonError
"""
if target is None:
target_fd = os.open(os.devnull, os.O_RDWR)
else:
target_fd = target.fileno()
try:
os.dup2(target_fd, system.fileno())
except OSError as err:
raise DaemonError('Could not redirect {0} to {1}: {2}'
.format(system, target, err)) | 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
:return: None
:raise: DaemonError
"""
if target is None:
target_fd = os.open(os.devnull, os.O_RDWR)
else:
target_fd = target.fileno()
try:
os.dup2(target_fd, system.fileno())
except OSError as err:
raise DaemonError('Could not redirect {0} to {1}: {2}'
.format(system, target, err)) | [
"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 | 223,668 |
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:
:type handler: str, None, function
:return: function
"""
if not handler:
result = signal.SIG_IGN
elif isinstance(handler, string_types):
result = getattr(self, handler)
else:
result = handler
return result | 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:
:type handler: str, None, function
:return: function
"""
if not handler:
result = signal.SIG_IGN
elif isinstance(handler, string_types):
result = getattr(self, handler)
else:
result = handler
return result | [
"def",
"_get_signal_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"not",
"handler",
":",
"result",
"=",
"signal",
".",
"SIG_IGN",
"elif",
"isinstance",
"(",
"handler",
",",
"string_types",
")",
":",
"result",
"=",
"getattr",
"(",
"self",
",",
"h... | get the callback function for handler
If the handler is None, returns signal.SIG_IGN.
If the handler is a string, return the matching attribute of this
instance if possible.
Else return the handler itself.
:param handler:
:type handler: str, None, function
:return: function | [
"get",
"the",
"callback",
"function",
"for",
"handler"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L141-L159 | train | 223,669 |
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 not self.files_preserve else self.files_preserve
files.extend([self.stdin, self.stdout, self.stderr])
for item in files:
if hasattr(item, 'fileno'):
result.add(item.fileno())
if isinstance(item, int):
result.add(item)
return result | 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 not self.files_preserve else self.files_preserve
files.extend([self.stdin, self.stdout, self.stderr])
for item in files:
if hasattr(item, 'fileno'):
result.add(item.fileno())
if isinstance(item, int):
result.add(item)
return result | [
"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 | 223,670 |
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:
return self._working_directory | 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:
return self._working_directory | [
"def",
"working_directory",
"(",
"self",
")",
":",
"if",
"self",
".",
"chroot_directory",
"and",
"not",
"self",
".",
"_working_directory",
".",
"startswith",
"(",
"self",
".",
"chroot_directory",
")",
":",
"return",
"self",
".",
"chroot_directory",
"+",
"self"... | The working_directory property
:return: str | [
"The",
"working_directory",
"property"
] | 027263860e72a403bc0e1497bb3e67523138e7a2 | https://github.com/wal-e/wal-e/blob/027263860e72a403bc0e1497bb3e67523138e7a2/wal_e/pep3143daemon/daemon.py#L196-L205 | train | 223,671 |
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.__module__)
manager_name -- class attribute name to use for historical manager
records_class -- class to use for history relation (defaults to
HistoricalRecords)
table_name -- Custom name for history table (defaults to
'APPNAME_historicalMODELNAME')
This method should be used as an alternative to attaching an
`HistoricalManager` instance directly to `model`.
"""
from . import models
if records_class is None:
records_class = models.HistoricalRecords
records = records_class(**records_config)
records.manager_name = manager_name
records.table_name = table_name
records.module = app and ("%s.models" % app) or model.__module__
records.cls = model
records.add_extra_methods(model)
records.finalize(model) | 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.__module__)
manager_name -- class attribute name to use for historical manager
records_class -- class to use for history relation (defaults to
HistoricalRecords)
table_name -- Custom name for history table (defaults to
'APPNAME_historicalMODELNAME')
This method should be used as an alternative to attaching an
`HistoricalManager` instance directly to `model`.
"""
from . import models
if records_class is None:
records_class = models.HistoricalRecords
records = records_class(**records_config)
records.manager_name = manager_name
records.table_name = table_name
records.module = app and ("%s.models" % app) or model.__module__
records.cls = model
records.add_extra_methods(model)
records.finalize(model) | [
"def",
"register",
"(",
"model",
",",
"app",
"=",
"None",
",",
"manager_name",
"=",
"\"history\"",
",",
"records_class",
"=",
"None",
",",
"table_name",
"=",
"None",
",",
"*",
"*",
"records_config",
")",
":",
"from",
".",
"import",
"models",
"if",
"recor... | Create historical model for `model` and attach history manager to `model`.
Keyword arguments:
app -- App to install historical model into (defaults to model.__module__)
manager_name -- class attribute name to use for historical manager
records_class -- class to use for history relation (defaults to
HistoricalRecords)
table_name -- Custom name for history table (defaults to
'APPNAME_historicalMODELNAME')
This method should be used as an alternative to attaching an
`HistoricalManager` instance directly to `model`. | [
"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 | 223,672 |
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(
"^([^/]+)/history/([^/]+)/$",
admin_site.admin_view(self.history_form_view),
name="%s_%s_simple_history" % info,
)
]
return history_urls + urls | 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(
"^([^/]+)/history/([^/]+)/$",
admin_site.admin_view(self.history_form_view),
name="%s_%s_simple_history" % info,
)
]
return history_urls + urls | [
"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 | 223,673 |
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 | 223,674 |
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_manager_for_model(model)
if self.verbosity >= 1:
self.stdout.write(
"Starting bulk creating history models for {} instances {}-{}".format(
model, 0, batch_size
)
)
iterator_kwargs = (
{"chunk_size": batch_size} if django.VERSION >= (2, 0, 0) else {}
)
for index, instance in enumerate(
model._default_manager.iterator(**iterator_kwargs)
):
# Can't Just pass batch_size to bulk_create as this can lead to
# Out of Memory Errors as we load too many models into memory after
# creating them. So we only keep batch_size worth of models in
# historical_instances and clear them after we hit batch_size
if index % batch_size == 0:
history.bulk_history_create(instances, batch_size=batch_size)
instances = []
if self.verbosity >= 1:
self.stdout.write(
"Finished bulk creating history models for {} "
"instances {}-{}, starting next {}".format(
model, index - batch_size, index, batch_size
)
)
instances.append(instance)
# create any we didn't get in the last loop
if instances:
history.bulk_history_create(instances, batch_size=batch_size) | 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_manager_for_model(model)
if self.verbosity >= 1:
self.stdout.write(
"Starting bulk creating history models for {} instances {}-{}".format(
model, 0, batch_size
)
)
iterator_kwargs = (
{"chunk_size": batch_size} if django.VERSION >= (2, 0, 0) else {}
)
for index, instance in enumerate(
model._default_manager.iterator(**iterator_kwargs)
):
# Can't Just pass batch_size to bulk_create as this can lead to
# Out of Memory Errors as we load too many models into memory after
# creating them. So we only keep batch_size worth of models in
# historical_instances and clear them after we hit batch_size
if index % batch_size == 0:
history.bulk_history_create(instances, batch_size=batch_size)
instances = []
if self.verbosity >= 1:
self.stdout.write(
"Finished bulk creating history models for {} "
"instances {}-{}, starting next {}".format(
model, index - batch_size, index, batch_size
)
)
instances.append(instance)
# create any we didn't get in the last loop
if instances:
history.bulk_history_create(instances, batch_size=batch_size) | [
"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 | 223,675 |
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.__class__ = models.TextField
# Historical instance shouldn't change create/update timestamps
field.auto_now = False
field.auto_now_add = False
if field.primary_key or field.unique:
# Unique fields can no longer be guaranteed unique,
# but they should still be indexed for faster lookups.
field.primary_key = False
field._unique = False
field.db_index = True
field.serialize = True | 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.__class__ = models.TextField
# Historical instance shouldn't change create/update timestamps
field.auto_now = False
field.auto_now_add = False
if field.primary_key or field.unique:
# Unique fields can no longer be guaranteed unique,
# but they should still be indexed for faster lookups.
field.primary_key = False
field._unique = False
field.db_index = True
field.serialize = True | [
"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 | 223,676 |
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._meta.app_label
if inherited:
# inherited use models module
attrs["__module__"] = model.__module__
elif model.__module__ != self.module:
# registered under different app
attrs["__module__"] = self.module
elif app_module != self.module:
# Abuse an internal API because the app registry is loading.
app = apps.app_configs[model._meta.app_label]
models_module = app.name
attrs["__module__"] = models_module
fields = self.copy_fields(model)
attrs.update(fields)
attrs.update(self.get_extra_fields(model, fields))
# type in python2 wants str as a first argument
attrs.update(Meta=type(str("Meta"), (), self.get_meta_options(model)))
if self.table_name is not None:
attrs["Meta"].db_table = self.table_name
# Set as the default then check for overrides
name = self.get_history_model_name(model)
registered_models[model._meta.db_table] = model
return python_2_unicode_compatible(type(str(name), self.bases, attrs)) | 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._meta.app_label
if inherited:
# inherited use models module
attrs["__module__"] = model.__module__
elif model.__module__ != self.module:
# registered under different app
attrs["__module__"] = self.module
elif app_module != self.module:
# Abuse an internal API because the app registry is loading.
app = apps.app_configs[model._meta.app_label]
models_module = app.name
attrs["__module__"] = models_module
fields = self.copy_fields(model)
attrs.update(fields)
attrs.update(self.get_extra_fields(model, fields))
# type in python2 wants str as a first argument
attrs.update(Meta=type(str("Meta"), (), self.get_meta_options(model)))
if self.table_name is not None:
attrs["Meta"].db_table = self.table_name
# Set as the default then check for overrides
name = self.get_history_model_name(model)
registered_models[model._meta.db_table] = model
return python_2_unicode_compatible(type(str(name), self.bases, attrs)) | [
"def",
"create_history_model",
"(",
"self",
",",
"model",
",",
"inherited",
")",
":",
"attrs",
"=",
"{",
"\"__module__\"",
":",
"self",
".",
"module",
",",
"\"_history_excluded_fields\"",
":",
"self",
".",
"excluded_fields",
",",
"}",
"app_module",
"=",
"\"%s.... | Creates a historical model to associate with the model provided. | [
"Creates",
"a",
"historical",
"model",
"to",
"associate",
"with",
"the",
"model",
"provided",
"."
] | 85758ecfe608279508a3fb5b71654d3e202eb63d | https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L193-L228 | train | 223,677 |
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 = copy.copy(field.remote_field)
if isinstance(field, OrderWrt):
# OrderWrt is a proxy field, switch to a plain IntegerField
field.__class__ = models.IntegerField
if isinstance(field, models.ForeignKey):
old_field = field
old_swappable = old_field.swappable
old_field.swappable = False
try:
_name, _path, args, field_args = old_field.deconstruct()
finally:
old_field.swappable = old_swappable
if getattr(old_field, "one_to_one", False) or isinstance(
old_field, models.OneToOneField
):
FieldType = models.ForeignKey
else:
FieldType = type(old_field)
# If field_args['to'] is 'self' then we have a case where the object
# has a foreign key to itself. If we pass the historical record's
# field to = 'self', the foreign key will point to an historical
# record rather than the base record. We can use old_field.model here.
if field_args.get("to", None) == "self":
field_args["to"] = old_field.model
# Override certain arguments passed when creating the field
# so that they work for the historical field.
field_args.update(
db_constraint=False,
related_name="+",
null=True,
blank=True,
primary_key=False,
db_index=True,
serialize=True,
unique=False,
on_delete=models.DO_NOTHING,
)
field = FieldType(*args, **field_args)
field.name = old_field.name
else:
transform_field(field)
fields[field.name] = field
return fields | 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 = copy.copy(field.remote_field)
if isinstance(field, OrderWrt):
# OrderWrt is a proxy field, switch to a plain IntegerField
field.__class__ = models.IntegerField
if isinstance(field, models.ForeignKey):
old_field = field
old_swappable = old_field.swappable
old_field.swappable = False
try:
_name, _path, args, field_args = old_field.deconstruct()
finally:
old_field.swappable = old_swappable
if getattr(old_field, "one_to_one", False) or isinstance(
old_field, models.OneToOneField
):
FieldType = models.ForeignKey
else:
FieldType = type(old_field)
# If field_args['to'] is 'self' then we have a case where the object
# has a foreign key to itself. If we pass the historical record's
# field to = 'self', the foreign key will point to an historical
# record rather than the base record. We can use old_field.model here.
if field_args.get("to", None) == "self":
field_args["to"] = old_field.model
# Override certain arguments passed when creating the field
# so that they work for the historical field.
field_args.update(
db_constraint=False,
related_name="+",
null=True,
blank=True,
primary_key=False,
db_index=True,
serialize=True,
unique=False,
on_delete=models.DO_NOTHING,
)
field = FieldType(*args, **field_args)
field.name = old_field.name
else:
transform_field(field)
fields[field.name] = field
return fields | [
"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 | 223,678 |
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
return reverse(
"%s:%s_%s_simple_history" % (admin.site.name, app_label, model_name),
args=[getattr(self, opts.pk.attname), self.history_id],
)
def get_instance(self):
attrs = {
field.attname: getattr(self, field.attname) for field in fields.values()
}
if self._history_excluded_fields:
excluded_attnames = [
model._meta.get_field(field).attname
for field in self._history_excluded_fields
]
values = (
model.objects.filter(pk=getattr(self, model._meta.pk.attname))
.values(*excluded_attnames)
.get()
)
attrs.update(values)
return model(**attrs)
def get_next_record(self):
"""
Get the next history record for the instance. `None` if last.
"""
history = utils.get_history_manager_for_model(self.instance)
return (
history.filter(Q(history_date__gt=self.history_date))
.order_by("history_date")
.first()
)
def get_prev_record(self):
"""
Get the previous history record for the instance. `None` if first.
"""
history = utils.get_history_manager_for_model(self.instance)
return (
history.filter(Q(history_date__lt=self.history_date))
.order_by("history_date")
.last()
)
extra_fields = {
"history_id": self._get_history_id_field(),
"history_date": models.DateTimeField(),
"history_change_reason": self._get_history_change_reason_field(),
"history_type": models.CharField(
max_length=1,
choices=(("+", _("Created")), ("~", _("Changed")), ("-", _("Deleted"))),
),
"history_object": HistoricalObjectDescriptor(
model, self.fields_included(model)
),
"instance": property(get_instance),
"instance_type": model,
"next_record": property(get_next_record),
"prev_record": property(get_prev_record),
"revert_url": revert_url,
"__str__": lambda self: "{} as of {}".format(
self.history_object, self.history_date
),
}
extra_fields.update(self._get_history_related_field(model))
extra_fields.update(self._get_history_user_fields())
return extra_fields | 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
return reverse(
"%s:%s_%s_simple_history" % (admin.site.name, app_label, model_name),
args=[getattr(self, opts.pk.attname), self.history_id],
)
def get_instance(self):
attrs = {
field.attname: getattr(self, field.attname) for field in fields.values()
}
if self._history_excluded_fields:
excluded_attnames = [
model._meta.get_field(field).attname
for field in self._history_excluded_fields
]
values = (
model.objects.filter(pk=getattr(self, model._meta.pk.attname))
.values(*excluded_attnames)
.get()
)
attrs.update(values)
return model(**attrs)
def get_next_record(self):
"""
Get the next history record for the instance. `None` if last.
"""
history = utils.get_history_manager_for_model(self.instance)
return (
history.filter(Q(history_date__gt=self.history_date))
.order_by("history_date")
.first()
)
def get_prev_record(self):
"""
Get the previous history record for the instance. `None` if first.
"""
history = utils.get_history_manager_for_model(self.instance)
return (
history.filter(Q(history_date__lt=self.history_date))
.order_by("history_date")
.last()
)
extra_fields = {
"history_id": self._get_history_id_field(),
"history_date": models.DateTimeField(),
"history_change_reason": self._get_history_change_reason_field(),
"history_type": models.CharField(
max_length=1,
choices=(("+", _("Created")), ("~", _("Changed")), ("-", _("Deleted"))),
),
"history_object": HistoricalObjectDescriptor(
model, self.fields_included(model)
),
"instance": property(get_instance),
"instance_type": model,
"next_record": property(get_next_record),
"prev_record": property(get_prev_record),
"revert_url": revert_url,
"__str__": lambda self: "{} as of {}".format(
self.history_object, self.history_date
),
}
extra_fields.update(self._get_history_related_field(model))
extra_fields.update(self._get_history_user_fields())
return extra_fields | [
"def",
"get_extra_fields",
"(",
"self",
",",
"model",
",",
"fields",
")",
":",
"def",
"revert_url",
"(",
"self",
")",
":",
"\"\"\"URL for this change in the default admin site.\"\"\"",
"opts",
"=",
"model",
".",
"_meta",
"app_label",
",",
"model_name",
"=",
"opts"... | Return dict of extra fields added to the historical record model | [
"Return",
"dict",
"of",
"extra",
"fields",
"added",
"to",
"the",
"historical",
"record",
"model"
] | 85758ecfe608279508a3fb5b71654d3e202eb63d | https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/models.py#L360-L435 | train | 223,679 |
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",
}
if self.user_set_verbose_name:
name = self.user_set_verbose_name
else:
name = format_lazy("historical {}", smart_text(model._meta.verbose_name))
meta_fields["verbose_name"] = name
if self.app:
meta_fields["app_label"] = self.app
return meta_fields | 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",
}
if self.user_set_verbose_name:
name = self.user_set_verbose_name
else:
name = format_lazy("historical {}", smart_text(model._meta.verbose_name))
meta_fields["verbose_name"] = name
if self.app:
meta_fields["app_label"] = self.app
return meta_fields | [
"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 | 223,680 |
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:
request = self.thread.request
except AttributeError:
pass
return self.get_user(instance=instance, request=request) | 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:
request = self.thread.request
except AttributeError:
pass
return self.get_user(instance=instance, request=request) | [
"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 | 223,681 |
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
)
)
tmp = []
excluded_fields = getattr(self.model, "_history_excluded_fields", [])
for field in self.instance._meta.fields:
if field.name in excluded_fields:
continue
if isinstance(field, models.ForeignKey):
tmp.append(field.name + "_id")
else:
tmp.append(field.name)
fields = tuple(tmp)
try:
values = self.get_queryset().values_list(*fields)[0]
except IndexError:
raise self.instance.DoesNotExist(
"%s has no historical record." % self.instance._meta.object_name
)
return self.instance.__class__(*values) | 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
)
)
tmp = []
excluded_fields = getattr(self.model, "_history_excluded_fields", [])
for field in self.instance._meta.fields:
if field.name in excluded_fields:
continue
if isinstance(field, models.ForeignKey):
tmp.append(field.name + "_id")
else:
tmp.append(field.name)
fields = tuple(tmp)
try:
values = self.get_queryset().values_list(*fields)[0]
except IndexError:
raise self.instance.DoesNotExist(
"%s has no historical record." % self.instance._meta.object_name
)
return self.instance.__class__(*values) | [
"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 | 223,682 |
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:
return self._as_of_set(date)
queryset = self.get_queryset().filter(history_date__lte=date)
try:
history_obj = queryset[0]
except IndexError:
raise self.instance.DoesNotExist(
"%s had not yet been created." % self.instance._meta.object_name
)
if history_obj.history_type == "-":
raise self.instance.DoesNotExist(
"%s had already been deleted." % self.instance._meta.object_name
)
return history_obj.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:
return self._as_of_set(date)
queryset = self.get_queryset().filter(history_date__lte=date)
try:
history_obj = queryset[0]
except IndexError:
raise self.instance.DoesNotExist(
"%s had not yet been created." % self.instance._meta.object_name
)
if history_obj.history_type == "-":
raise self.instance.DoesNotExist(
"%s had already been deleted." % self.instance._meta.object_name
)
return history_obj.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 | 223,683 |
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", None),
history_change_reason=getattr(instance, "changeReason", ""),
history_type="+",
**{
field.attname: getattr(instance, field.attname)
for field in instance._meta.fields
if field.name not in self.model._history_excluded_fields
}
)
for instance in objs
]
return self.model.objects.bulk_create(
historical_instances, batch_size=batch_size
) | 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", None),
history_change_reason=getattr(instance, "changeReason", ""),
history_type="+",
**{
field.attname: getattr(instance, field.attname)
for field in instance._meta.fields
if field.name not in self.model._history_excluded_fields
}
)
for instance in objs
]
return self.model.objects.bulk_create(
historical_instances, batch_size=batch_size
) | [
"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 | 223,684 |
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=model)
)
return getattr(model, manager_name) | 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=model)
)
return getattr(model, manager_name) | [
"def",
"get_history_manager_for_model",
"(",
"model",
")",
":",
"try",
":",
"manager_name",
"=",
"model",
".",
"_meta",
".",
"simple_history_manager_attribute",
"except",
"AttributeError",
":",
"raise",
"NotHistoricalModelError",
"(",
"\"Cannot find a historical model for {... | Return the history manager for a given app model. | [
"Return",
"the",
"history",
"manager",
"for",
"a",
"given",
"app",
"model",
"."
] | 85758ecfe608279508a3fb5b71654d3e202eb63d | https://github.com/treyhunner/django-simple-history/blob/85758ecfe608279508a3fb5b71654d3e202eb63d/simple_history/utils.py#L23-L31 | train | 223,685 |
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_parameter('/'.join(names[1:]))
global current_scope
param = current_scope.get(key, None)
if param is not None:
del current_scope[key]
return param | 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_parameter('/'.join(names[1:]))
global current_scope
param = current_scope.get(key, None)
if param is not None:
del current_scope[key]
return param | [
"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 | 223,686 |
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.
Args:
name(str): The name under the current scope. If it already exists, the name is queried from the
parameter manager.
shape (:obj:`tuple` of :obj:`int`): Shape of created parameter. The shape of the specified
parameter must match with this shape. The default is None which is only valid if initializer is given as an :obj:`numpy.ndarray`.
initializer (:obj:`nnabla.initializer.BaseInitializer` or :obj:`numpy.ndarray`): An initialization function to be applied to the parameter. :obj:`numpy.ndarray` can also be given to initialize parameters from numpy array data.
need_grad (bool):
Register the parameter with the specified ``need_grad`` flag.
The default is True. If the flag is different from the previously
specified one, the flag will be overwritten, but the values will be
kept.
as_need_grad (bool):
Get a parameter variable with the specified ``need_grad`` flag.
Note that this doesn't overwrite the flag of the registered parameter
variable with the provided name. Instead, if the given flag
mismatches with the previously registered ``need_grad`` flag, it
returns a new variable referring to the same array contents but with
``need_grad=as_need_grad``.
"""
names = name.split('/')
if len(names) > 1:
with parameter_scope(names[0]):
return get_parameter_or_create('/'.join(names[1:]), shape, initializer, need_grad, as_need_grad)
param = get_parameter(names[0])
if param is None:
class VariableInfo:
pass
info = VariableInfo()
info.initializer = initializer
if initializer is not None:
if isinstance(initializer, numpy.ndarray): # numpy init
param = nn.Variable(initializer.shape, need_grad=need_grad)
param.d = initializer
# initializer init
elif isinstance(initializer, nn.initializer.BaseInitializer) or initializer.__name__ == "<lambda>":
assert shape is not None
param = nn.Variable(shape, need_grad=need_grad)
param.d = initializer(shape=param.shape)
else:
raise ValueError(
"`initializer` must be either the :obj:`numpy.ndarray` or an instance inherited from `nnabla.initializer.BaseInitializer`.")
else: # default init
assert shape is not None
param = nn.Variable(shape, need_grad=need_grad)
set_parameter(name, param)
else:
if param.shape != tuple(shape):
raise ValueError(
'The size of existing parameter "{}" {} is different from the size of new parameter {}.\n'
'To clear all parameters, call nn.clear_parameters().'.format(name, param.shape, tuple(shape)))
if need_grad != param.need_grad:
param.need_grad = need_grad
if as_need_grad is None:
return param
if param.need_grad != as_need_grad:
param = param.get_unlinked_variable(need_grad=as_need_grad)
return param | 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.
Args:
name(str): The name under the current scope. If it already exists, the name is queried from the
parameter manager.
shape (:obj:`tuple` of :obj:`int`): Shape of created parameter. The shape of the specified
parameter must match with this shape. The default is None which is only valid if initializer is given as an :obj:`numpy.ndarray`.
initializer (:obj:`nnabla.initializer.BaseInitializer` or :obj:`numpy.ndarray`): An initialization function to be applied to the parameter. :obj:`numpy.ndarray` can also be given to initialize parameters from numpy array data.
need_grad (bool):
Register the parameter with the specified ``need_grad`` flag.
The default is True. If the flag is different from the previously
specified one, the flag will be overwritten, but the values will be
kept.
as_need_grad (bool):
Get a parameter variable with the specified ``need_grad`` flag.
Note that this doesn't overwrite the flag of the registered parameter
variable with the provided name. Instead, if the given flag
mismatches with the previously registered ``need_grad`` flag, it
returns a new variable referring to the same array contents but with
``need_grad=as_need_grad``.
"""
names = name.split('/')
if len(names) > 1:
with parameter_scope(names[0]):
return get_parameter_or_create('/'.join(names[1:]), shape, initializer, need_grad, as_need_grad)
param = get_parameter(names[0])
if param is None:
class VariableInfo:
pass
info = VariableInfo()
info.initializer = initializer
if initializer is not None:
if isinstance(initializer, numpy.ndarray): # numpy init
param = nn.Variable(initializer.shape, need_grad=need_grad)
param.d = initializer
# initializer init
elif isinstance(initializer, nn.initializer.BaseInitializer) or initializer.__name__ == "<lambda>":
assert shape is not None
param = nn.Variable(shape, need_grad=need_grad)
param.d = initializer(shape=param.shape)
else:
raise ValueError(
"`initializer` must be either the :obj:`numpy.ndarray` or an instance inherited from `nnabla.initializer.BaseInitializer`.")
else: # default init
assert shape is not None
param = nn.Variable(shape, need_grad=need_grad)
set_parameter(name, param)
else:
if param.shape != tuple(shape):
raise ValueError(
'The size of existing parameter "{}" {} is different from the size of new parameter {}.\n'
'To clear all parameters, call nn.clear_parameters().'.format(name, param.shape, tuple(shape)))
if need_grad != param.need_grad:
param.need_grad = need_grad
if as_need_grad is None:
return param
if param.need_grad != as_need_grad:
param = param.get_unlinked_variable(need_grad=as_need_grad)
return param | [
"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.
shape (:obj:`tuple` of :obj:`int`): Shape of created parameter. The shape of the specified
parameter must match with this shape. The default is None which is only valid if initializer is given as an :obj:`numpy.ndarray`.
initializer (:obj:`nnabla.initializer.BaseInitializer` or :obj:`numpy.ndarray`): An initialization function to be applied to the parameter. :obj:`numpy.ndarray` can also be given to initialize parameters from numpy array data.
need_grad (bool):
Register the parameter with the specified ``need_grad`` flag.
The default is True. If the flag is different from the previously
specified one, the flag will be overwritten, but the values will be
kept.
as_need_grad (bool):
Get a parameter variable with the specified ``need_grad`` flag.
Note that this doesn't overwrite the flag of the registered parameter
variable with the provided name. Instead, if the given flag
mismatches with the previously registered ``need_grad`` flag, it
returns a new variable referring to the same array contents but with
``need_grad=as_need_grad``. | [
"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 | 223,687 |
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 under the current scope if
False, while only parameters with need_grad=True are retrieved
if True.
Returns:
dict: {:obj:`str` : :obj:`~nnabla.Variable`}
"""
global current_scope
if params is None:
params = OrderedDict()
for k, v in iteritems(current_scope):
if isinstance(v, dict):
with parameter_scope(k):
params = get_parameters(
params, '/'.join([path, k]) if path else k, grad_only=grad_only)
else:
assert isinstance(v, nn.Variable)
if not grad_only or v.need_grad:
params['/'.join([path, k]) if path else k] = v
return params | 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 under the current scope if
False, while only parameters with need_grad=True are retrieved
if True.
Returns:
dict: {:obj:`str` : :obj:`~nnabla.Variable`}
"""
global current_scope
if params is None:
params = OrderedDict()
for k, v in iteritems(current_scope):
if isinstance(v, dict):
with parameter_scope(k):
params = get_parameters(
params, '/'.join([path, k]) if path else k, grad_only=grad_only)
else:
assert isinstance(v, nn.Variable)
if not grad_only or v.need_grad:
params['/'.join([path, k]) if path else k] = v
return params | [
"def",
"get_parameters",
"(",
"params",
"=",
"None",
",",
"path",
"=",
"''",
",",
"grad_only",
"=",
"True",
")",
":",
"global",
"current_scope",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"OrderedDict",
"(",
")",
"for",
"k",
",",
"v",
"in",
"i... | Get parameter Variables under the current parameter scope.
Args:
params (dict): Internal use. User doesn't set it manually.
path (str): Internal use. User doesn't set it manually.
grad_only (bool): Retrieve all parameters under the current scope if
False, while only parameters with need_grad=True are retrieved
if True.
Returns:
dict: {:obj:`str` : :obj:`~nnabla.Variable`} | [
"Get",
"parameter",
"Variables",
"under",
"the",
"current",
"parameter",
"scope",
"."
] | aaf3d33b7cbb38f2a03aa754178ba8f7c8481320 | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/parameter.py#L248-L275 | train | 223,688 |
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.
Returns: module
An Python module of a particular NNabla extension.
Example:
.. code-block:: python
ext = import_extension_module('cudnn')
available_devices = ext.get_devices()
print(available_devices)
ext.device_synchronize(available_devices[0])
ext.clear_memory_cache()
'''
import importlib
try:
return importlib.import_module('.' + ext_name, 'nnabla_ext')
except ImportError as e:
from nnabla import logger
logger.error('Extension `{}` does not exist.'.format(ext_name))
raise e | 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.
Returns: module
An Python module of a particular NNabla extension.
Example:
.. code-block:: python
ext = import_extension_module('cudnn')
available_devices = ext.get_devices()
print(available_devices)
ext.device_synchronize(available_devices[0])
ext.clear_memory_cache()
'''
import importlib
try:
return importlib.import_module('.' + ext_name, 'nnabla_ext')
except ImportError as e:
from nnabla import logger
logger.error('Extension `{}` does not exist.'.format(ext_name))
raise e | [
"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 a particular NNabla extension.
Example:
.. code-block:: python
ext = import_extension_module('cudnn')
available_devices = ext.get_devices()
print(available_devices)
ext.device_synchronize(available_devices[0])
ext.clear_memory_cache() | [
"Import",
"an",
"extension",
"module",
"by",
"name",
"."
] | aaf3d33b7cbb38f2a03aa754178ba8f7c8481320 | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/ext_utils.py#L20-L50 | train | 223,689 |
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 os.path import dirname, join, realpath
from os import listdir
ext_dir = realpath((join(dirname(nnabla_ext.cpu.__file__), '..')))
return listdir(ext_dir) | 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 os.path import dirname, join, realpath
from os import listdir
ext_dir = realpath((join(dirname(nnabla_ext.cpu.__file__), '..')))
return listdir(ext_dir) | [
"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 | 223,690 |
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) by default.
channel_first (bool):
This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width).
Default value is False, which means the img shape is considered as (height, width, channel)
as_uint16 (bool):
In this backend, this argument is always False because pillow dose not support uint16.
If True, exception will be raised.
auto_scale (bool) :
Whether upscale pixel values or not.
If you want to save float image, this argument must be True.
In pillow backend, only float ([0, 1]) to uint8 ([0, 255]) is supported.
"""
img = _imsave_before(img, channel_first, auto_scale)
if img.dtype == np.uint16 or as_uint16:
raise ValueError("Pillow only supports uint8 image to save. Cast img to uint8."
"If you want to save image as uint16, install pypng or cv2 "
"and nnabla.utils.image_utils automatically change backend to use these module.")
if auto_scale and img.dtype != np.uint8:
img = (img * 255).astype(np.uint8)
Image.fromarray(img).save(path) | 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) by default.
channel_first (bool):
This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width).
Default value is False, which means the img shape is considered as (height, width, channel)
as_uint16 (bool):
In this backend, this argument is always False because pillow dose not support uint16.
If True, exception will be raised.
auto_scale (bool) :
Whether upscale pixel values or not.
If you want to save float image, this argument must be True.
In pillow backend, only float ([0, 1]) to uint8 ([0, 255]) is supported.
"""
img = _imsave_before(img, channel_first, auto_scale)
if img.dtype == np.uint16 or as_uint16:
raise ValueError("Pillow only supports uint8 image to save. Cast img to uint8."
"If you want to save image as uint16, install pypng or cv2 "
"and nnabla.utils.image_utils automatically change backend to use these module.")
if auto_scale and img.dtype != np.uint8:
img = (img * 255).astype(np.uint8)
Image.fromarray(img).save(path) | [
"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 of img is whether (height, width, channel) or (channel, height, width).
Default value is False, which means the img shape is considered as (height, width, channel)
as_uint16 (bool):
In this backend, this argument is always False because pillow dose not support uint16.
If True, exception will be raised.
auto_scale (bool) :
Whether upscale pixel values or not.
If you want to save float image, this argument must be True.
In pillow backend, only float ([0, 1]) to uint8 ([0, 255]) is supported. | [
"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 | 223,691 |
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, batch_size, callback=callback) | 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, batch_size, callback=callback) | [
"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 | 223,692 |
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,
func_counter)
update_function_counter(func.type, func_counter, count) | 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,
func_counter)
update_function_counter(func.type, func_counter, count) | [
"def",
"set_function_name",
"(",
"func",
",",
"node_name",
",",
"base_name",
",",
"func_counter",
")",
":",
"# NNabla requires each function to have a unique name",
"# so we generate one here.",
"func",
".",
"name",
",",
"count",
"=",
"generate_function_name",
"(",
"func"... | Set a sufficient name for the function | [
"Set",
"a",
"sufficient",
"name",
"for",
"the",
"function"
] | aaf3d33b7cbb38f2a03aa754178ba8f7c8481320 | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L153-L159 | train | 223,693 |
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_name])
trans.output.extend([out_name])
tp = trans.transpose_param
tp.axes.extend(axes)
return trans | 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_name])
trans.output.extend([out_name])
tp = trans.transpose_param
tp.axes.extend(axes)
return trans | [
"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 | 223,694 |
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.extend([out_name])
btp = bt.broadcast_to_param
btp.axis = axis
return bt | 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.extend([out_name])
btp = bt.broadcast_to_param
btp.axis = axis
return bt | [
"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 | 223,695 |
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(
"NNP with more then a single network is currently not supported")
net = pb.network[0]
batch_norm_constants = []
for f in net.function:
if f.type == "BatchNormalization":
# BatchNormalization in ONNX requires the scale, bias, mean, and variance input to be
# one dimensional (https://github.com/onnx/onnx/blob/master/docs/Operators.md#batchnormalization).
# However in NNabla these input must have a specific shape that matches the input shape.
# For example if the input shape is (1,3,3,3), the above variables must have the shape (1,3,1,1) and not (3).
# (1,3,1,1) is actually the same as a one-dimensional tensor of size 3,
# but NNabla's check currently does not allow this.
# Thus, we convert the shape of the above input so we can pass NNabla's check.
# If NNabla lightens the shape check, we should be able to remove this conversion.
# copy all input names for scale, bias, mean, variance
batch_norm_constants.extend(f.input[1:5])
# This loop should be fairly slow since we loop through all variables and parameters per constant
for c in batch_norm_constants:
# Reshape all BatchNormalization constant inputs assuming the size is (1,size,1,1)
for v in net.variable:
if v.name == c:
size = v.shape.dim[0]
del v.shape.dim[:]
v.shape.dim.extend([1, size, 1, 1])
break
for p in pb.parameter:
if p.variable_name == c:
size = p.shape.dim[0]
del p.shape.dim[:]
p.shape.dim.extend([1, size, 1, 1])
break | 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(
"NNP with more then a single network is currently not supported")
net = pb.network[0]
batch_norm_constants = []
for f in net.function:
if f.type == "BatchNormalization":
# BatchNormalization in ONNX requires the scale, bias, mean, and variance input to be
# one dimensional (https://github.com/onnx/onnx/blob/master/docs/Operators.md#batchnormalization).
# However in NNabla these input must have a specific shape that matches the input shape.
# For example if the input shape is (1,3,3,3), the above variables must have the shape (1,3,1,1) and not (3).
# (1,3,1,1) is actually the same as a one-dimensional tensor of size 3,
# but NNabla's check currently does not allow this.
# Thus, we convert the shape of the above input so we can pass NNabla's check.
# If NNabla lightens the shape check, we should be able to remove this conversion.
# copy all input names for scale, bias, mean, variance
batch_norm_constants.extend(f.input[1:5])
# This loop should be fairly slow since we loop through all variables and parameters per constant
for c in batch_norm_constants:
# Reshape all BatchNormalization constant inputs assuming the size is (1,size,1,1)
for v in net.variable:
if v.name == c:
size = v.shape.dim[0]
del v.shape.dim[:]
v.shape.dim.extend([1, size, 1, 1])
break
for p in pb.parameter:
if p.variable_name == c:
size = p.shape.dim[0]
del p.shape.dim[:]
p.shape.dim.extend([1, size, 1, 1])
break | [
"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 | 223,696 |
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.data.extend(np.fromstring(tensor.raw_data, dtype=np.float32))
elif len(tensor.float_data) > 0:
p.data.extend(tensor.float_data)
else:
raise ValueError("float data not found for {}".format(tensor.name))
elif tensor.data_type == TensorProto.INT32:
# convert raw bytestream to integer
if tensor.raw_data:
p.data.extend(np.fromstring(tensor.raw_data, dtype=np.int32))
elif len(tensor.int32_data) > 0:
p.data.extend(tensor.int32_data)
else:
raise ValueError("int32 data not found for {}".format(tensor.name))
elif tensor.data_type == TensorProto.INT64:
# convert raw bytestream to integer
if tensor.raw_data:
p.data.extend(np.fromstring(tensor.raw_data, dtype=np.int64))
elif len(tensor.int64_data) > 0:
p.data.extend(tensor.int64_data)
else:
raise ValueError("int64 data not found for {}".format(tensor.name))
elif tensor.data_type == TensorProto.BOOL:
if tensor.raw_data:
p.data.extend(np.fromstring(tensor.raw_data, dtype=np.bool))
else:
raise ValueError("bool data not found for {}".format(tensor.name))
else:
raise ValueError("Unsupported tensor data type for {}: {}"
.format(tensor.name, tensor.data_type))
p.need_grad = False | 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.data.extend(np.fromstring(tensor.raw_data, dtype=np.float32))
elif len(tensor.float_data) > 0:
p.data.extend(tensor.float_data)
else:
raise ValueError("float data not found for {}".format(tensor.name))
elif tensor.data_type == TensorProto.INT32:
# convert raw bytestream to integer
if tensor.raw_data:
p.data.extend(np.fromstring(tensor.raw_data, dtype=np.int32))
elif len(tensor.int32_data) > 0:
p.data.extend(tensor.int32_data)
else:
raise ValueError("int32 data not found for {}".format(tensor.name))
elif tensor.data_type == TensorProto.INT64:
# convert raw bytestream to integer
if tensor.raw_data:
p.data.extend(np.fromstring(tensor.raw_data, dtype=np.int64))
elif len(tensor.int64_data) > 0:
p.data.extend(tensor.int64_data)
else:
raise ValueError("int64 data not found for {}".format(tensor.name))
elif tensor.data_type == TensorProto.BOOL:
if tensor.raw_data:
p.data.extend(np.fromstring(tensor.raw_data, dtype=np.bool))
else:
raise ValueError("bool data not found for {}".format(tensor.name))
else:
raise ValueError("Unsupported tensor data type for {}: {}"
.format(tensor.name, tensor.data_type))
p.need_grad = False | [
"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 | 223,697 |
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":
if attr.type != AttributeProto.INT:
raise ValueError(
"Only INT is supported for axis in {} op_type".format(n.op_type))
broadcast_axis = attr.i
elif attr.name == "broadcast":
if attr.type != AttributeProto.INT:
raise ValueError(
"Only INT is supported for broadcast in {} op_type".format(n.op_type))
if attr.i == 1:
broadcasting = True
else:
raise ValueError("Unsupported attribute {} was specified at {}"
.format(attr.name, n.op_type))
if not broadcasting:
input0_shape = self.get_func_input_shape(func.input[0])
input1_shape = self.get_func_input_shape(func.input[1])
output_shape = []
for i in range(len(input0_shape)):
output_shape.append(max(input0_shape[i], input1_shape[i]))
self._shape_output[func.output[0]] = output_shape
func_list.append(func)
return
# Create a BroadcastTo operator to broadcast input B
b_idx = 1 # B is the second input
broadcasted_postfix = "_broadcasted"
input = n.input[:]
bin = n.input[b_idx]
bout = bin+broadcasted_postfix
bt = generate_broadcast_to(n.name, n.input[0], bin, bout, broadcast_axis,
self._graph.name, self._func_counter)
self._shape_output[bout] = self.get_func_input_shape(n.input[0])
func_list.append(bt)
input[b_idx] = bout # rewire input to broadcasted input
# update input with the converted inputs
del func.input[:]
func.input.extend(input)
self._shape_output[func.output[0]] = self._shape_output[bout]
func_list.append(func) | 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":
if attr.type != AttributeProto.INT:
raise ValueError(
"Only INT is supported for axis in {} op_type".format(n.op_type))
broadcast_axis = attr.i
elif attr.name == "broadcast":
if attr.type != AttributeProto.INT:
raise ValueError(
"Only INT is supported for broadcast in {} op_type".format(n.op_type))
if attr.i == 1:
broadcasting = True
else:
raise ValueError("Unsupported attribute {} was specified at {}"
.format(attr.name, n.op_type))
if not broadcasting:
input0_shape = self.get_func_input_shape(func.input[0])
input1_shape = self.get_func_input_shape(func.input[1])
output_shape = []
for i in range(len(input0_shape)):
output_shape.append(max(input0_shape[i], input1_shape[i]))
self._shape_output[func.output[0]] = output_shape
func_list.append(func)
return
# Create a BroadcastTo operator to broadcast input B
b_idx = 1 # B is the second input
broadcasted_postfix = "_broadcasted"
input = n.input[:]
bin = n.input[b_idx]
bout = bin+broadcasted_postfix
bt = generate_broadcast_to(n.name, n.input[0], bin, bout, broadcast_axis,
self._graph.name, self._func_counter)
self._shape_output[bout] = self.get_func_input_shape(n.input[0])
func_list.append(bt)
input[b_idx] = bout # rewire input to broadcasted input
# update input with the converted inputs
del func.input[:]
func.input.extend(input)
self._shape_output[func.output[0]] = self._shape_output[bout]
func_list.append(func) | [
"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 | 223,698 |
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):
(width, height).
If None, output img shape depends on the files to read.
channel_first (bool):
This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width).
Default value is False, which means the img shape is (height, width, channel).
interpolate (str):
must be one of ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"].
as_uint16 (bool):
If True, this function reads image as uint16.
num_channels (int):
channel size of output array.
Default is -1 which preserves raw image shape.
Returns:
numpy.ndarray
"""
_imread_before(grayscale, num_channels)
f = path if hasattr(path, "read") else open(path, "rb")
r = png.Reader(file=f)
width, height, pixels, metadata = r.asDirect()
bit_depth = metadata.get("bitdepth")
if bit_depth not in [8, 16]:
raise ValueError("The bit-depth of the image you want to read is unsupported ({}bit)."
"Currently, pypng backend`s imread supports only [8, 16] bit-depth."
"the path for this image is {}".format(bit_depth, path))
img = read_result_to_ndarray(
pixels, width, height, metadata, grayscale, as_uint16, num_channels)
return _imread_after(img, size, interpolate, channel_first, imresize) | 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):
(width, height).
If None, output img shape depends on the files to read.
channel_first (bool):
This argument specifies the shape of img is whether (height, width, channel) or (channel, height, width).
Default value is False, which means the img shape is (height, width, channel).
interpolate (str):
must be one of ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"].
as_uint16 (bool):
If True, this function reads image as uint16.
num_channels (int):
channel size of output array.
Default is -1 which preserves raw image shape.
Returns:
numpy.ndarray
"""
_imread_before(grayscale, num_channels)
f = path if hasattr(path, "read") else open(path, "rb")
r = png.Reader(file=f)
width, height, pixels, metadata = r.asDirect()
bit_depth = metadata.get("bitdepth")
if bit_depth not in [8, 16]:
raise ValueError("The bit-depth of the image you want to read is unsupported ({}bit)."
"Currently, pypng backend`s imread supports only [8, 16] bit-depth."
"the path for this image is {}".format(bit_depth, path))
img = read_result_to_ndarray(
pixels, width, height, metadata, grayscale, as_uint16, num_channels)
return _imread_after(img, size, interpolate, channel_first, imresize) | [
"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 specifies the shape of img is whether (height, width, channel) or (channel, height, width).
Default value is False, which means the img shape is (height, width, channel).
interpolate (str):
must be one of ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"].
as_uint16 (bool):
If True, this function reads image as uint16.
num_channels (int):
channel size of output array.
Default is -1 which preserves raw image shape.
Returns:
numpy.ndarray | [
"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 | 223,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.