repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
DataONEorg/d1_python | lib_client/src/d1_client/session.py | Session._timeout_to_float | def _timeout_to_float(self, timeout):
"""Convert timeout to float.
Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in
Requests.
"""
if timeout is not None:
try:
timeout_float = float(timeout)
except ValueError:
... | python | def _timeout_to_float(self, timeout):
"""Convert timeout to float.
Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in
Requests.
"""
if timeout is not None:
try:
timeout_float = float(timeout)
except ValueError:
... | [
"def",
"_timeout_to_float",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"try",
":",
"timeout_float",
"=",
"float",
"(",
"timeout",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'timeout_sec must be a valid... | Convert timeout to float.
Return None if timeout is None, 0 or 0.0. timeout=None disables timeouts in
Requests. | [
"Convert",
"timeout",
"to",
"float",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_client/src/d1_client/session.py#L350-L367 |
DataONEorg/d1_python | dev_tools/src/d1_dev/src-print-redbaron-tree.py | main | def main():
"""Print the RedBaron syntax tree for a Python module."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", help="Python module path")
args = parser.parse_args()
r = d1_dev.util.redbaron_... | python | def main():
"""Print the RedBaron syntax tree for a Python module."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("path", help="Python module path")
args = parser.parse_args()
r = d1_dev.util.redbaron_... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
",",
"formatter_class",
"=",
"argparse",
".",
"RawDescriptionHelpFormatter",
")",
"parser",
".",
"add_argument",
"(",
"\"path\"",
",",
"help",
"... | Print the RedBaron syntax tree for a Python module. | [
"Print",
"the",
"RedBaron",
"syntax",
"tree",
"for",
"a",
"Python",
"module",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/dev_tools/src/d1_dev/src-print-redbaron-tree.py#L27-L36 |
DataONEorg/d1_python | lib_common/src/d1_common/utils/filesystem.py | abs_path_from_base | def abs_path_from_base(base_path, rel_path):
"""Join a base and a relative path and return an absolute path to the resulting
location.
Args:
base_path: str
Relative or absolute path to prepend to ``rel_path``.
rel_path: str
Path relative to the location of the module file from ... | python | def abs_path_from_base(base_path, rel_path):
"""Join a base and a relative path and return an absolute path to the resulting
location.
Args:
base_path: str
Relative or absolute path to prepend to ``rel_path``.
rel_path: str
Path relative to the location of the module file from ... | [
"def",
"abs_path_from_base",
"(",
"base_path",
",",
"rel_path",
")",
":",
"# noinspection PyProtectedMember",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"sys",
".",
"_getfr... | Join a base and a relative path and return an absolute path to the resulting
location.
Args:
base_path: str
Relative or absolute path to prepend to ``rel_path``.
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
... | [
"Join",
"a",
"base",
"and",
"a",
"relative",
"path",
"and",
"return",
"an",
"absolute",
"path",
"to",
"the",
"resulting",
"location",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/utils/filesystem.py#L92-L112 |
DataONEorg/d1_python | lib_common/src/d1_common/utils/filesystem.py | abs_path | def abs_path(rel_path):
"""Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location ... | python | def abs_path(rel_path):
"""Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location ... | [
"def",
"abs_path",
"(",
"rel_path",
")",
":",
"# noinspection PyProtectedMember",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"sys",
".",
"_getframe",
"(",
"1",
")",
"."... | Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location specified by ``rel_path``. | [
"Convert",
"a",
"path",
"that",
"is",
"relative",
"to",
"the",
"module",
"from",
"which",
"this",
"function",
"is",
"called",
"to",
"an",
"absolute",
"path",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/utils/filesystem.py#L115-L130 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_xml | def get_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as XML
"""
return xml.etree.ElementTree.tostring(self._root_el, encoding) | python | def get_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as XML
"""
return xml.etree.ElementTree.tostring(self._root_el, encoding) | [
"def",
"get_xml",
"(",
"self",
",",
"encoding",
"=",
"'unicode'",
")",
":",
"return",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"tostring",
"(",
"self",
".",
"_root_el",
",",
"encoding",
")"
] | Returns:
str : Current state of the wrapper as XML | [
"Returns",
":"
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L115-L121 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_pretty_xml | def get_pretty_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as a pretty printed XML string.
"""
return d1_common.xml.reformat_to_pretty_xml(
xml.etree.ElementTree.tostring(self._root_el, encoding)
) | python | def get_pretty_xml(self, encoding='unicode'):
"""Returns:
str : Current state of the wrapper as a pretty printed XML string.
"""
return d1_common.xml.reformat_to_pretty_xml(
xml.etree.ElementTree.tostring(self._root_el, encoding)
) | [
"def",
"get_pretty_xml",
"(",
"self",
",",
"encoding",
"=",
"'unicode'",
")",
":",
"return",
"d1_common",
".",
"xml",
".",
"reformat_to_pretty_xml",
"(",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"tostring",
"(",
"self",
".",
"_root_el",
",",
"encoding",... | Returns:
str : Current state of the wrapper as a pretty printed XML string. | [
"Returns",
":"
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L123-L131 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_xml_below_element | def get_xml_below_element(self, el_name, el_idx=0, encoding='unicode'):
"""
Args:
el_name : str
Name of element that is the base of the branch to retrieve.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same na... | python | def get_xml_below_element(self, el_name, el_idx=0, encoding='unicode'):
"""
Args:
el_name : str
Name of element that is the base of the branch to retrieve.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same na... | [
"def",
"get_xml_below_element",
"(",
"self",
",",
"el_name",
",",
"el_idx",
"=",
"0",
",",
"encoding",
"=",
"'unicode'",
")",
":",
"return",
"xml",
".",
"etree",
".",
"ElementTree",
".",
"tostring",
"(",
"self",
".",
"get_element_by_name",
"(",
"el_name",
... | Args:
el_name : str
Name of element that is the base of the branch to retrieve.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
str : XML fragment rooted at ``el``. | [
"Args",
":",
"el_name",
":",
"str",
"Name",
"of",
"element",
"that",
"is",
"the",
"base",
"of",
"the",
"branch",
"to",
"retrieve",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L133-L148 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_element_by_xpath | def get_element_by_xpath(self, xpath_str, namespaces=None):
"""
Args:
xpath_str : str
XPath matching the elements for which to search.
Returns:
list : List of elements matching ``xpath_str``.
If there are no matching elements, an empty list is returned.
"""
try:
... | python | def get_element_by_xpath(self, xpath_str, namespaces=None):
"""
Args:
xpath_str : str
XPath matching the elements for which to search.
Returns:
list : List of elements matching ``xpath_str``.
If there are no matching elements, an empty list is returned.
"""
try:
... | [
"def",
"get_element_by_xpath",
"(",
"self",
",",
"xpath_str",
",",
"namespaces",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"_root_el",
".",
"findall",
"(",
"'.'",
"+",
"xpath_str",
",",
"namespaces",
")",
"except",
"(",
"ValueError",
",",
... | Args:
xpath_str : str
XPath matching the elements for which to search.
Returns:
list : List of elements matching ``xpath_str``.
If there are no matching elements, an empty list is returned. | [
"Args",
":",
"xpath_str",
":",
"str",
"XPath",
"matching",
"the",
"elements",
"for",
"which",
"to",
"search",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L178-L196 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_element_by_name | def get_element_by_name(self, el_name, el_idx=0):
"""
Args:
el_name : str
Name of element to get.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
element : The selected element.
... | python | def get_element_by_name(self, el_name, el_idx=0):
"""
Args:
el_name : str
Name of element to get.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
element : The selected element.
... | [
"def",
"get_element_by_name",
"(",
"self",
",",
"el_name",
",",
"el_idx",
"=",
"0",
")",
":",
"el_list",
"=",
"self",
".",
"get_element_list_by_name",
"(",
"el_name",
")",
"try",
":",
"return",
"el_list",
"[",
"el_idx",
"]",
"except",
"IndexError",
":",
"r... | Args:
el_name : str
Name of element to get.
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
element : The selected element. | [
"Args",
":",
"el_name",
":",
"str",
"Name",
"of",
"element",
"to",
"get",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L198-L218 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_element_by_attr_key | def get_element_by_attr_key(self, attr_key, el_idx=0):
"""
Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
Element contai... | python | def get_element_by_attr_key(self, attr_key, el_idx=0):
"""
Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
Element contai... | [
"def",
"get_element_by_attr_key",
"(",
"self",
",",
"attr_key",
",",
"el_idx",
"=",
"0",
")",
":",
"el_list",
"=",
"self",
".",
"get_element_list_by_attr_key",
"(",
"attr_key",
")",
"try",
":",
"return",
"el_list",
"[",
"el_idx",
"]",
"except",
"IndexError",
... | Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use as base in the event that there are multiple sibling
elements with the same name.
Returns:
Element containing an attribute key named ``attr_key``. | [
"Args",
":",
"attr_key",
":",
"str",
"Name",
"of",
"attribute",
"for",
"which",
"to",
"search"
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L220-L240 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.set_element_text | def set_element_text(self, el_name, el_text, el_idx=0):
"""
Args:
el_name : str
Name of element to update.
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name.... | python | def set_element_text(self, el_name, el_text, el_idx=0):
"""
Args:
el_name : str
Name of element to update.
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name.... | [
"def",
"set_element_text",
"(",
"self",
",",
"el_name",
",",
"el_text",
",",
"el_idx",
"=",
"0",
")",
":",
"self",
".",
"get_element_by_name",
"(",
"el_name",
",",
"el_idx",
")",
".",
"text",
"=",
"el_text"
] | Args:
el_name : str
Name of element to update.
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name. | [
"Args",
":",
"el_name",
":",
"str",
"Name",
"of",
"element",
"to",
"update",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L259-L272 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.set_element_text_by_attr_key | def set_element_text_by_attr_key(self, attr_key, el_text, el_idx=0):
"""
Args:
attr_key : str
Name of attribute for which to search
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
ele... | python | def set_element_text_by_attr_key(self, attr_key, el_text, el_idx=0):
"""
Args:
attr_key : str
Name of attribute for which to search
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
ele... | [
"def",
"set_element_text_by_attr_key",
"(",
"self",
",",
"attr_key",
",",
"el_text",
",",
"el_idx",
"=",
"0",
")",
":",
"self",
".",
"get_element_by_attr_key",
"(",
"attr_key",
",",
"el_idx",
")",
".",
"text",
"=",
"el_text"
] | Args:
attr_key : str
Name of attribute for which to search
el_text : str
Text to set for element.
el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name. | [
"Args",
":",
"attr_key",
":",
"str",
"Name",
"of",
"attribute",
"for",
"which",
"to",
"search"
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L291-L304 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_attr_value | def get_attr_value(self, attr_key, el_idx=0):
"""Return the value of the selected attribute in the selected element.
Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use in the event that there are multiple sibling
... | python | def get_attr_value(self, attr_key, el_idx=0):
"""Return the value of the selected attribute in the selected element.
Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use in the event that there are multiple sibling
... | [
"def",
"get_attr_value",
"(",
"self",
",",
"attr_key",
",",
"el_idx",
"=",
"0",
")",
":",
"return",
"self",
".",
"get_element_by_attr_key",
"(",
"attr_key",
",",
"el_idx",
")",
".",
"attrib",
"[",
"attr_key",
"]"
] | Return the value of the selected attribute in the selected element.
Args:
attr_key : str
Name of attribute for which to search
el_idx : int
Index of element to use in the event that there are multiple sibling
elements with the same name.
Returns... | [
"Return",
"the",
"value",
"of",
"the",
"selected",
"attribute",
"in",
"the",
"selected",
"element",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L308-L323 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.set_attr_text | def set_attr_text(self, attr_key, attr_val, el_idx=0):
"""Set the value of the selected attribute of the selected element.
Args:
attr_key : str
Name of attribute for which to search
attr_val : str
Text to set for the attribute.
el_idx : int
... | python | def set_attr_text(self, attr_key, attr_val, el_idx=0):
"""Set the value of the selected attribute of the selected element.
Args:
attr_key : str
Name of attribute for which to search
attr_val : str
Text to set for the attribute.
el_idx : int
... | [
"def",
"set_attr_text",
"(",
"self",
",",
"attr_key",
",",
"attr_val",
",",
"el_idx",
"=",
"0",
")",
":",
"self",
".",
"get_element_by_attr_key",
"(",
"attr_key",
",",
"el_idx",
")",
".",
"attrib",
"[",
"attr_key",
"]",
"=",
"attr_val"
] | Set the value of the selected attribute of the selected element.
Args:
attr_key : str
Name of attribute for which to search
attr_val : str
Text to set for the attribute.
el_idx : int
Index of element to use in the event that there are multiple... | [
"Set",
"the",
"value",
"of",
"the",
"selected",
"attribute",
"of",
"the",
"selected",
"element",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L325-L340 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.get_element_dt | def get_element_dt(self, el_name, tz=None, el_idx=0):
"""Return the text of the selected element as a ``datetime.datetime`` object.
The element text must be a ISO8601 formatted datetime
Args:
el_name : str
Name of element to use.
tz : datetime.tzinfo
... | python | def get_element_dt(self, el_name, tz=None, el_idx=0):
"""Return the text of the selected element as a ``datetime.datetime`` object.
The element text must be a ISO8601 formatted datetime
Args:
el_name : str
Name of element to use.
tz : datetime.tzinfo
... | [
"def",
"get_element_dt",
"(",
"self",
",",
"el_name",
",",
"tz",
"=",
"None",
",",
"el_idx",
"=",
"0",
")",
":",
"return",
"iso8601",
".",
"parse_date",
"(",
"self",
".",
"get_element_by_name",
"(",
"el_name",
",",
"el_idx",
")",
".",
"text",
",",
"tz"... | Return the text of the selected element as a ``datetime.datetime`` object.
The element text must be a ISO8601 formatted datetime
Args:
el_name : str
Name of element to use.
tz : datetime.tzinfo
Timezone in which to return the datetime.
- Withou... | [
"Return",
"the",
"text",
"of",
"the",
"selected",
"element",
"as",
"a",
"datetime",
".",
"datetime",
"object",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L344-L373 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.set_element_dt | def set_element_dt(self, el_name, dt, tz=None, el_idx=0):
"""Set the text of the selected element to an ISO8601 formatted datetime.
Args:
el_name : str
Name of element to update.
dt : datetime.datetime
Date and time to set
tz : datetime.tzinfo
... | python | def set_element_dt(self, el_name, dt, tz=None, el_idx=0):
"""Set the text of the selected element to an ISO8601 formatted datetime.
Args:
el_name : str
Name of element to update.
dt : datetime.datetime
Date and time to set
tz : datetime.tzinfo
... | [
"def",
"set_element_dt",
"(",
"self",
",",
"el_name",
",",
"dt",
",",
"tz",
"=",
"None",
",",
"el_idx",
"=",
"0",
")",
":",
"dt",
"=",
"d1_common",
".",
"date_time",
".",
"cast_naive_datetime_to_tz",
"(",
"dt",
",",
"tz",
")",
"self",
".",
"get_element... | Set the text of the selected element to an ISO8601 formatted datetime.
Args:
el_name : str
Name of element to update.
dt : datetime.datetime
Date and time to set
tz : datetime.tzinfo
Timezone to set
- Without a timezone, other con... | [
"Set",
"the",
"text",
"of",
"the",
"selected",
"element",
"to",
"an",
"ISO8601",
"formatted",
"datetime",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L375-L403 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.replace_by_etree | def replace_by_etree(self, root_el, el_idx=0):
"""Replace element.
Select element that has the same name as ``root_el``, then replace the selected
element with ``root_el``
``root_el`` can be a single element or the root of an element tree.
Args:
root_el : element
... | python | def replace_by_etree(self, root_el, el_idx=0):
"""Replace element.
Select element that has the same name as ``root_el``, then replace the selected
element with ``root_el``
``root_el`` can be a single element or the root of an element tree.
Args:
root_el : element
... | [
"def",
"replace_by_etree",
"(",
"self",
",",
"root_el",
",",
"el_idx",
"=",
"0",
")",
":",
"el",
"=",
"self",
".",
"get_element_by_name",
"(",
"root_el",
".",
"tag",
",",
"el_idx",
")",
"el",
"[",
":",
"]",
"=",
"list",
"(",
"root_el",
")",
"el",
"... | Replace element.
Select element that has the same name as ``root_el``, then replace the selected
element with ``root_el``
``root_el`` can be a single element or the root of an element tree.
Args:
root_el : element
New element that will replace the existing elemen... | [
"Replace",
"element",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L423-L438 |
DataONEorg/d1_python | lib_common/src/d1_common/wrap/simple_xml.py | SimpleXMLWrapper.replace_by_xml | def replace_by_xml(self, xml_str, el_idx=0):
"""Replace element.
Select element that has the same name as ``xml_str``, then replace the selected
element with ``xml_str``
- ``xml_str`` must have a single element in the root.
- The root element in ``xml_str`` can have an arbitrar... | python | def replace_by_xml(self, xml_str, el_idx=0):
"""Replace element.
Select element that has the same name as ``xml_str``, then replace the selected
element with ``xml_str``
- ``xml_str`` must have a single element in the root.
- The root element in ``xml_str`` can have an arbitrar... | [
"def",
"replace_by_xml",
"(",
"self",
",",
"xml_str",
",",
"el_idx",
"=",
"0",
")",
":",
"root_el",
"=",
"self",
".",
"parse_xml",
"(",
"xml_str",
")",
"self",
".",
"replace_by_etree",
"(",
"root_el",
",",
"el_idx",
")"
] | Replace element.
Select element that has the same name as ``xml_str``, then replace the selected
element with ``xml_str``
- ``xml_str`` must have a single element in the root.
- The root element in ``xml_str`` can have an arbitrary number of children.
Args:
xml_str :... | [
"Replace",
"element",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/wrap/simple_xml.py#L440-L455 |
genialis/resolwe | resolwe/flow/models/functions.py | JsonGetPath.as_sql | def as_sql(self, compiler, connection): # pylint: disable=arguments-differ
"""Compile SQL for this function."""
sql, params = super().as_sql(compiler, connection)
params.append(self.path)
return sql, params | python | def as_sql(self, compiler, connection): # pylint: disable=arguments-differ
"""Compile SQL for this function."""
sql, params = super().as_sql(compiler, connection)
params.append(self.path)
return sql, params | [
"def",
"as_sql",
"(",
"self",
",",
"compiler",
",",
"connection",
")",
":",
"# pylint: disable=arguments-differ",
"sql",
",",
"params",
"=",
"super",
"(",
")",
".",
"as_sql",
"(",
"compiler",
",",
"connection",
")",
"params",
".",
"append",
"(",
"self",
".... | Compile SQL for this function. | [
"Compile",
"SQL",
"for",
"this",
"function",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/functions.py#L26-L30 |
genialis/resolwe | resolwe/flow/models/storage.py | StorageManager.with_json_path | def with_json_path(self, path, field=None):
"""Annotate Storage objects with a specific JSON path.
:param path: Path to get inside the stored object, which can be
either a list of path components or a comma-separated
string
:param field: Optional output field name
... | python | def with_json_path(self, path, field=None):
"""Annotate Storage objects with a specific JSON path.
:param path: Path to get inside the stored object, which can be
either a list of path components or a comma-separated
string
:param field: Optional output field name
... | [
"def",
"with_json_path",
"(",
"self",
",",
"path",
",",
"field",
"=",
"None",
")",
":",
"if",
"field",
"is",
"None",
":",
"field",
"=",
"'_'",
".",
"join",
"(",
"[",
"'json'",
"]",
"+",
"json_path_components",
"(",
"path",
")",
")",
"kwargs",
"=",
... | Annotate Storage objects with a specific JSON path.
:param path: Path to get inside the stored object, which can be
either a list of path components or a comma-separated
string
:param field: Optional output field name | [
"Annotate",
"Storage",
"objects",
"with",
"a",
"specific",
"JSON",
"path",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/storage.py#L13-L25 |
genialis/resolwe | resolwe/flow/models/storage.py | StorageManager.get_json_path | def get_json_path(self, path):
"""Return only a specific JSON path of Storage objects.
:param path: Path to get inside the stored object, which can be
either a list of path components or a comma-separated
string
"""
return self.with_json_path(path, field='result'... | python | def get_json_path(self, path):
"""Return only a specific JSON path of Storage objects.
:param path: Path to get inside the stored object, which can be
either a list of path components or a comma-separated
string
"""
return self.with_json_path(path, field='result'... | [
"def",
"get_json_path",
"(",
"self",
",",
"path",
")",
":",
"return",
"self",
".",
"with_json_path",
"(",
"path",
",",
"field",
"=",
"'result'",
")",
".",
"values_list",
"(",
"'result'",
",",
"flat",
"=",
"True",
")"
] | Return only a specific JSON path of Storage objects.
:param path: Path to get inside the stored object, which can be
either a list of path components or a comma-separated
string | [
"Return",
"only",
"a",
"specific",
"JSON",
"path",
"of",
"Storage",
"objects",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/storage.py#L27-L34 |
genialis/resolwe | resolwe/flow/models/storage.py | LazyStorageJSON._get_storage | def _get_storage(self):
"""Load `json` field from `Storage` object."""
if self._json is None:
self._json = Storage.objects.get(**self._kwargs).json | python | def _get_storage(self):
"""Load `json` field from `Storage` object."""
if self._json is None:
self._json = Storage.objects.get(**self._kwargs).json | [
"def",
"_get_storage",
"(",
"self",
")",
":",
"if",
"self",
".",
"_json",
"is",
"None",
":",
"self",
".",
"_json",
"=",
"Storage",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"self",
".",
"_kwargs",
")",
".",
"json"
] | Load `json` field from `Storage` object. | [
"Load",
"json",
"field",
"from",
"Storage",
"object",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/models/storage.py#L58-L61 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessOperation.database_forwards | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name
Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name
try:
... | python | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name
Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name
try:
... | [
"def",
"database_forwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"Process",
"=",
"from_state",
".",
"apps",
".",
"get_model",
"(",
"'flow'",
",",
"'Process'",
")",
"# pylint: disable=invalid-name",
"D... | Perform forward migration. | [
"Perform",
"forward",
"migration",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L165-L216 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessAddField.deconstruct | def deconstruct(self):
"""Deconstruct operation."""
return (
self.__class__.__name__,
[],
{
'process': self.process,
'field': self._raw_field,
'schema': self.schema,
'default': self.default,
}... | python | def deconstruct(self):
"""Deconstruct operation."""
return (
self.__class__.__name__,
[],
{
'process': self.process,
'field': self._raw_field,
'schema': self.schema,
'default': self.default,
}... | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"[",
"]",
",",
"{",
"'process'",
":",
"self",
".",
"process",
",",
"'field'",
":",
"self",
".",
"_raw_field",
",",
"'schema'",
":",
"self",
".... | Deconstruct operation. | [
"Deconstruct",
"operation",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L268-L279 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessAddField.migrate_process_schema | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | python | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | [
"def",
"migrate_process_schema",
"(",
"self",
",",
"process",
",",
"schema",
",",
"from_state",
")",
":",
"container",
"=",
"dict_dot",
"(",
"schema",
",",
"'.'",
".",
"join",
"(",
"self",
".",
"field",
"[",
":",
"-",
"1",
"]",
")",
",",
"default",
"... | Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise | [
"Migrate",
"process",
"schema",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L281-L308 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessAddField.migrate_data | def migrate_data(self, data, from_state):
"""Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state
"""
if not self.default:
return
self.default.prepare(data, from_... | python | def migrate_data(self, data, from_state):
"""Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state
"""
if not self.default:
return
self.default.prepare(data, from_... | [
"def",
"migrate_data",
"(",
"self",
",",
"data",
",",
"from_state",
")",
":",
"if",
"not",
"self",
".",
"default",
":",
"return",
"self",
".",
"default",
".",
"prepare",
"(",
"data",
",",
"from_state",
")",
"for",
"instance",
"in",
"data",
":",
"value"... | Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state | [
"Migrate",
"data",
"objects",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L310-L330 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessRenameField.deconstruct | def deconstruct(self):
"""Deconstruct operation."""
return (
self.__class__.__name__,
[],
{
'process': self.process,
'field': self._raw_field,
'new_field': self.new_field,
}
) | python | def deconstruct(self):
"""Deconstruct operation."""
return (
self.__class__.__name__,
[],
{
'process': self.process,
'field': self._raw_field,
'new_field': self.new_field,
}
) | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"[",
"]",
",",
"{",
"'process'",
":",
"self",
".",
"process",
",",
"'field'",
":",
"self",
".",
"_raw_field",
",",
"'new_field'",
":",
"self",
... | Deconstruct operation. | [
"Deconstruct",
"operation",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L396-L406 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessRenameField.migrate_process_schema | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | python | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | [
"def",
"migrate_process_schema",
"(",
"self",
",",
"process",
",",
"schema",
",",
"from_state",
")",
":",
"container",
"=",
"dict_dot",
"(",
"schema",
",",
"'.'",
".",
"join",
"(",
"self",
".",
"field",
"[",
":",
"-",
"1",
"]",
")",
",",
"default",
"... | Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise | [
"Migrate",
"process",
"schema",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L408-L438 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessRenameField.migrate_data | def migrate_data(self, data, from_state):
"""Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state
"""
for instance in data:
if instance.status == 'ER':
con... | python | def migrate_data(self, data, from_state):
"""Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state
"""
for instance in data:
if instance.status == 'ER':
con... | [
"def",
"migrate_data",
"(",
"self",
",",
"data",
",",
"from_state",
")",
":",
"for",
"instance",
"in",
"data",
":",
"if",
"instance",
".",
"status",
"==",
"'ER'",
":",
"continue",
"container",
"=",
"getattr",
"(",
"instance",
",",
"self",
".",
"schema_ty... | Migrate data objects.
:param data: Queryset containing all data objects that need
to be migrated
:param from_state: Database model state | [
"Migrate",
"data",
"objects",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L440-L456 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweDataCleanup.database_forwards | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
from resolwe.flow.models.data import DataQuerySet
# pylint: disable=protected-access
Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name
Dat... | python | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
from resolwe.flow.models.data import DataQuerySet
# pylint: disable=protected-access
Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name
Dat... | [
"def",
"database_forwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"from",
"resolwe",
".",
"flow",
".",
"models",
".",
"data",
"import",
"DataQuerySet",
"# pylint: disable=protected-access",
"Data",
"=",
... | Perform forward migration. | [
"Perform",
"forward",
"migration",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L503-L510 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessDataRemove.database_forwards | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
from resolwe.flow.models.data import DataQuerySet
# pylint: disable=protected-access
Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name
Dat... | python | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
from resolwe.flow.models.data import DataQuerySet
# pylint: disable=protected-access
Data = from_state.apps.get_model('flow', 'Data') # pylint: disable=invalid-name
Dat... | [
"def",
"database_forwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"from",
"resolwe",
".",
"flow",
".",
"models",
".",
"data",
"import",
"DataQuerySet",
"# pylint: disable=protected-access",
"Data",
"=",
... | Perform forward migration. | [
"Perform",
"forward",
"migration",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L535-L544 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweProcessChangeType.migrate_process_schema | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | python | def migrate_process_schema(self, process, schema, from_state):
"""Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise
"""
... | [
"def",
"migrate_process_schema",
"(",
"self",
",",
"process",
",",
"schema",
",",
"from_state",
")",
":",
"if",
"process",
".",
"type",
"==",
"self",
".",
"new_type",
":",
"return",
"False",
"process",
".",
"type",
"=",
"self",
".",
"new_type",
"return",
... | Migrate process schema.
:param process: Process instance
:param schema: Process schema to migrate
:param from_state: Database model state
:return: True if the process was migrated, False otherwise | [
"Migrate",
"process",
"schema",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L579-L591 |
genialis/resolwe | resolwe/flow/migration_ops.py | ResolweValidateProcessSchema.database_forwards | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name
# Validate process types to ensure consistency.
errors = validate_process_types(Process.ob... | python | def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""Perform forward migration."""
Process = from_state.apps.get_model('flow', 'Process') # pylint: disable=invalid-name
# Validate process types to ensure consistency.
errors = validate_process_types(Process.ob... | [
"def",
"database_forwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"Process",
"=",
"from_state",
".",
"apps",
".",
"get_model",
"(",
"'flow'",
",",
"'Process'",
")",
"# pylint: disable=invalid-name",
"#... | Perform forward migration. | [
"Perform",
"forward",
"migration",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/migration_ops.py#L644-L651 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/internal.py | home | def home(request):
"""Home page.
Root of web server should redirect to here.
"""
if request.path.endswith('/'):
return django.http.HttpResponseRedirect(request.path[:-1])
return django.http.HttpResponse(
generate_status_xml(), d1_common.const.CONTENT_TYPE_XML
) | python | def home(request):
"""Home page.
Root of web server should redirect to here.
"""
if request.path.endswith('/'):
return django.http.HttpResponseRedirect(request.path[:-1])
return django.http.HttpResponse(
generate_status_xml(), d1_common.const.CONTENT_TYPE_XML
) | [
"def",
"home",
"(",
"request",
")",
":",
"if",
"request",
".",
"path",
".",
"endswith",
"(",
"'/'",
")",
":",
"return",
"django",
".",
"http",
".",
"HttpResponseRedirect",
"(",
"request",
".",
"path",
"[",
":",
"-",
"1",
"]",
")",
"return",
"django",... | Home page.
Root of web server should redirect to here. | [
"Home",
"page",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/internal.py#L53-L64 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/internal.py | error_404 | def error_404(request, exception):
"""Handle 404s outside of the valid API URL endpoints Note: Cannot raise NotFound()
here, as this method is not covered by the GMN middleware handler that catches
DataONE exceptions raised by normal views."""
return django.http.HttpResponseNotFound(
d1_common.t... | python | def error_404(request, exception):
"""Handle 404s outside of the valid API URL endpoints Note: Cannot raise NotFound()
here, as this method is not covered by the GMN middleware handler that catches
DataONE exceptions raised by normal views."""
return django.http.HttpResponseNotFound(
d1_common.t... | [
"def",
"error_404",
"(",
"request",
",",
"exception",
")",
":",
"return",
"django",
".",
"http",
".",
"HttpResponseNotFound",
"(",
"d1_common",
".",
"types",
".",
"exceptions",
".",
"NotFound",
"(",
"0",
",",
"'Invalid API endpoint'",
",",
"# Include the regexes... | Handle 404s outside of the valid API URL endpoints Note: Cannot raise NotFound()
here, as this method is not covered by the GMN middleware handler that catches
DataONE exceptions raised by normal views. | [
"Handle",
"404s",
"outside",
"of",
"the",
"valid",
"API",
"URL",
"endpoints",
"Note",
":",
"Cannot",
"raise",
"NotFound",
"()",
"here",
"as",
"this",
"method",
"is",
"not",
"covered",
"by",
"the",
"GMN",
"middleware",
"handler",
"that",
"catches",
"DataONE",... | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/internal.py#L73-L86 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/views/internal.py | get_obj_store_free_space_bytes | def get_obj_store_free_space_bytes():
"""Return total free space available on the disk on which the object storage resides
(in bytes)"""
obj_store_path = django.conf.settings.OBJECT_STORE_PATH
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.Ge... | python | def get_obj_store_free_space_bytes():
"""Return total free space available on the disk on which the object storage resides
(in bytes)"""
obj_store_path = django.conf.settings.OBJECT_STORE_PATH
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.Ge... | [
"def",
"get_obj_store_free_space_bytes",
"(",
")",
":",
"obj_store_path",
"=",
"django",
".",
"conf",
".",
"settings",
".",
"OBJECT_STORE_PATH",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"free_bytes",
"=",
"ctypes",
".",
"c_ulonglong",
... | Return total free space available on the disk on which the object storage resides
(in bytes) | [
"Return",
"total",
"free",
"space",
"available",
"on",
"the",
"disk",
"on",
"which",
"the",
"object",
"storage",
"resides",
"(",
"in",
"bytes",
")"
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/views/internal.py#L230-L241 |
wilson-eft/wilson | wilson/run/smeft/smpar.py | m2Lambda_to_vMh2 | def m2Lambda_to_vMh2(m2, Lambda, C):
"""Function to numerically determine the physical Higgs VEV and mass
given the parameters of the Higgs potential."""
try:
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
except ValueError:
v = 0
... | python | def m2Lambda_to_vMh2(m2, Lambda, C):
"""Function to numerically determine the physical Higgs VEV and mass
given the parameters of the Higgs potential."""
try:
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
except ValueError:
v = 0
... | [
"def",
"m2Lambda_to_vMh2",
"(",
"m2",
",",
"Lambda",
",",
"C",
")",
":",
"try",
":",
"v",
"=",
"(",
"sqrt",
"(",
"2",
"*",
"m2",
"/",
"Lambda",
")",
"+",
"3",
"*",
"m2",
"**",
"(",
"3",
"/",
"2",
")",
"/",
"(",
"sqrt",
"(",
"2",
")",
"*",... | Function to numerically determine the physical Higgs VEV and mass
given the parameters of the Higgs potential. | [
"Function",
"to",
"numerically",
"determine",
"the",
"physical",
"Higgs",
"VEV",
"and",
"mass",
"given",
"the",
"parameters",
"of",
"the",
"Higgs",
"potential",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L38-L48 |
wilson-eft/wilson | wilson/run/smeft/smpar.py | vMh2_to_m2Lambda | def vMh2_to_m2Lambda(v, Mh2, C):
"""Function to numerically determine the parameters of the Higgs potential
given the physical Higgs VEV and mass."""
if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0:
return _vMh2_to_m2Lambda_SM(v, Mh2)
else:
def f0(x): # we want the root of this... | python | def vMh2_to_m2Lambda(v, Mh2, C):
"""Function to numerically determine the parameters of the Higgs potential
given the physical Higgs VEV and mass."""
if C['phi'] == 0 and C['phiBox'] == 0 and C['phiD'] == 0:
return _vMh2_to_m2Lambda_SM(v, Mh2)
else:
def f0(x): # we want the root of this... | [
"def",
"vMh2_to_m2Lambda",
"(",
"v",
",",
"Mh2",
",",
"C",
")",
":",
"if",
"C",
"[",
"'phi'",
"]",
"==",
"0",
"and",
"C",
"[",
"'phiBox'",
"]",
"==",
"0",
"and",
"C",
"[",
"'phiD'",
"]",
"==",
"0",
":",
"return",
"_vMh2_to_m2Lambda_SM",
"(",
"v",... | Function to numerically determine the parameters of the Higgs potential
given the physical Higgs VEV and mass. | [
"Function",
"to",
"numerically",
"determine",
"the",
"parameters",
"of",
"the",
"Higgs",
"potential",
"given",
"the",
"physical",
"Higgs",
"VEV",
"and",
"mass",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L55-L77 |
wilson-eft/wilson | wilson/run/smeft/smpar.py | get_gpbar | def get_gpbar(ebar, gbar, v, C):
r"""Function to numerically determine the hypercharge gauge coupling
in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients."""
if C['phiWB'] == 0: # this is the trivial case
gpbar = ebar * gbar / sqrt(gbar**2 - ebar**2)
else: # if epsilon != 0, need to... | python | def get_gpbar(ebar, gbar, v, C):
r"""Function to numerically determine the hypercharge gauge coupling
in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients."""
if C['phiWB'] == 0: # this is the trivial case
gpbar = ebar * gbar / sqrt(gbar**2 - ebar**2)
else: # if epsilon != 0, need to... | [
"def",
"get_gpbar",
"(",
"ebar",
",",
"gbar",
",",
"v",
",",
"C",
")",
":",
"if",
"C",
"[",
"'phiWB'",
"]",
"==",
"0",
":",
"# this is the trivial case",
"gpbar",
"=",
"ebar",
"*",
"gbar",
"/",
"sqrt",
"(",
"gbar",
"**",
"2",
"-",
"ebar",
"**",
"... | r"""Function to numerically determine the hypercharge gauge coupling
in terms of $\bar e$, $\bar g$, v, and the Wilson coefficients. | [
"r",
"Function",
"to",
"numerically",
"determine",
"the",
"hypercharge",
"gauge",
"coupling",
"in",
"terms",
"of",
"$",
"\\",
"bar",
"e$",
"$",
"\\",
"bar",
"g$",
"v",
"and",
"the",
"Wilson",
"coefficients",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L80-L97 |
wilson-eft/wilson | wilson/run/smeft/smpar.py | smeftpar | def smeftpar(scale, C, basis):
"""Get the running parameters in SMEFT."""
# start with a zero dict and update it with the input values
MW = p['m_W']
# MZ = p['m_Z']
GF = p['GF']
Mh = p['m_h']
vb = sqrt(1 / sqrt(2) / GF)
v = vb # TODO
_d = vMh2_to_m2Lambda(v=v, Mh2=Mh**2, C=C)
m2... | python | def smeftpar(scale, C, basis):
"""Get the running parameters in SMEFT."""
# start with a zero dict and update it with the input values
MW = p['m_W']
# MZ = p['m_Z']
GF = p['GF']
Mh = p['m_h']
vb = sqrt(1 / sqrt(2) / GF)
v = vb # TODO
_d = vMh2_to_m2Lambda(v=v, Mh2=Mh**2, C=C)
m2... | [
"def",
"smeftpar",
"(",
"scale",
",",
"C",
",",
"basis",
")",
":",
"# start with a zero dict and update it with the input values",
"MW",
"=",
"p",
"[",
"'m_W'",
"]",
"# MZ = p['m_Z']",
"GF",
"=",
"p",
"[",
"'GF'",
"]",
"Mh",
"=",
"p",
"[",
"'m_h'",
"]",
"v... | Get the running parameters in SMEFT. | [
"Get",
"the",
"running",
"parameters",
"in",
"SMEFT",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L100-L137 |
wilson-eft/wilson | wilson/run/smeft/smpar.py | smpar | def smpar(C):
"""Get the running effective SM parameters."""
m2 = C['m2'].real
Lambda = C['Lambda'].real
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
GF = 1 / (sqrt(2) * v**2) # TODO
Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda ... | python | def smpar(C):
"""Get the running effective SM parameters."""
m2 = C['m2'].real
Lambda = C['Lambda'].real
v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) /
(sqrt(2) * Lambda**(5 / 2)) * C['phi'])
GF = 1 / (sqrt(2) * v**2) # TODO
Mh2 = 2 * m2 * (1 - m2 / Lambda * (3 * C['phi'] - 4 * Lambda ... | [
"def",
"smpar",
"(",
"C",
")",
":",
"m2",
"=",
"C",
"[",
"'m2'",
"]",
".",
"real",
"Lambda",
"=",
"C",
"[",
"'Lambda'",
"]",
".",
"real",
"v",
"=",
"(",
"sqrt",
"(",
"2",
"*",
"m2",
"/",
"Lambda",
")",
"+",
"3",
"*",
"m2",
"**",
"(",
"3",... | Get the running effective SM parameters. | [
"Get",
"the",
"running",
"effective",
"SM",
"parameters",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/run/smeft/smpar.py#L140-L191 |
wilson-eft/wilson | wilson/util/smeftutil.py | scale_8 | def scale_8(b):
"""Translations necessary for class-8 coefficients
to go from a basis with only non-redundant WCxf
operators to a basis where the Wilson coefficients are symmetrized like
the operators."""
a = np.array(b, copy=True, dtype=complex)
for i in range(3):
a[0, 0, 1, i] = 1/2 * ... | python | def scale_8(b):
"""Translations necessary for class-8 coefficients
to go from a basis with only non-redundant WCxf
operators to a basis where the Wilson coefficients are symmetrized like
the operators."""
a = np.array(b, copy=True, dtype=complex)
for i in range(3):
a[0, 0, 1, i] = 1/2 * ... | [
"def",
"scale_8",
"(",
"b",
")",
":",
"a",
"=",
"np",
".",
"array",
"(",
"b",
",",
"copy",
"=",
"True",
",",
"dtype",
"=",
"complex",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"a",
"[",
"0",
",",
"0",
",",
"1",
",",
"i",
"]",
... | Translations necessary for class-8 coefficients
to go from a basis with only non-redundant WCxf
operators to a basis where the Wilson coefficients are symmetrized like
the operators. | [
"Translations",
"necessary",
"for",
"class",
"-",
"8",
"coefficients",
"to",
"go",
"from",
"a",
"basis",
"with",
"only",
"non",
"-",
"redundant",
"WCxf",
"operators",
"to",
"a",
"basis",
"where",
"the",
"Wilson",
"coefficients",
"are",
"symmetrized",
"like",
... | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L546-L563 |
wilson-eft/wilson | wilson/util/smeftutil.py | symmetrize | def symmetrize(C):
"""Symmetrize the Wilson coefficient arrays.
Note that this function does not take into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the opera... | python | def symmetrize(C):
"""Symmetrize the Wilson coefficient arrays.
Note that this function does not take into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the opera... | [
"def",
"symmetrize",
"(",
"C",
")",
":",
"C_symm",
"=",
"{",
"}",
"for",
"i",
",",
"v",
"in",
"C",
".",
"items",
"(",
")",
":",
"if",
"i",
"in",
"C_symm_keys",
"[",
"0",
"]",
":",
"C_symm",
"[",
"i",
"]",
"=",
"v",
".",
"real",
"elif",
"i",... | Symmetrize the Wilson coefficient arrays.
Note that this function does not take into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the operators. See `symmetrize_nonr... | [
"Symmetrize",
"the",
"Wilson",
"coefficient",
"arrays",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L593-L620 |
wilson-eft/wilson | wilson/util/smeftutil.py | arrays2wcxf | def arrays2wcxf(C):
"""Convert a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values to a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values. This is needed for the output in WCxf format."""
d = {}
... | python | def arrays2wcxf(C):
"""Convert a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values to a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values. This is needed for the output in WCxf format."""
d = {}
... | [
"def",
"arrays2wcxf",
"(",
"C",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"C",
".",
"items",
"(",
")",
":",
"if",
"np",
".",
"shape",
"(",
"v",
")",
"==",
"(",
")",
"or",
"np",
".",
"shape",
"(",
"v",
")",
"==",
"(",
"1"... | Convert a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values to a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values. This is needed for the output in WCxf format. | [
"Convert",
"a",
"dictionary",
"with",
"Wilson",
"coefficient",
"names",
"as",
"keys",
"and",
"numbers",
"or",
"numpy",
"arrays",
"as",
"values",
"to",
"a",
"dictionary",
"with",
"a",
"Wilson",
"coefficient",
"name",
"followed",
"by",
"underscore",
"and",
"nume... | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L623-L637 |
wilson-eft/wilson | wilson/util/smeftutil.py | wcxf2arrays | def wcxf2arrays(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values. This is needed for the parsing
of input in WCxf format."""
... | python | def wcxf2arrays(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values. This is needed for the parsing
of input in WCxf format."""
... | [
"def",
"wcxf2arrays",
"(",
"d",
")",
":",
"C",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"name",
"=",
"k",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"s",
"=",
"C_keys_shape",
"[",
"name",
"]",
"if",
... | Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values. This is needed for the parsing
of input in WCxf format. | [
"Convert",
"a",
"dictionary",
"with",
"a",
"Wilson",
"coefficient",
"name",
"followed",
"by",
"underscore",
"and",
"numeric",
"indices",
"as",
"keys",
"and",
"numbers",
"as",
"values",
"to",
"a",
"dictionary",
"with",
"Wilson",
"coefficient",
"names",
"as",
"k... | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L640-L657 |
wilson-eft/wilson | wilson/util/smeftutil.py | add_missing | def add_missing(C):
"""Add arrays with zeros for missing Wilson coefficient keys"""
C_out = C.copy()
for k in (set(WC_keys) - set(C.keys())):
C_out[k] = np.zeros(C_keys_shape[k])
return C_out | python | def add_missing(C):
"""Add arrays with zeros for missing Wilson coefficient keys"""
C_out = C.copy()
for k in (set(WC_keys) - set(C.keys())):
C_out[k] = np.zeros(C_keys_shape[k])
return C_out | [
"def",
"add_missing",
"(",
"C",
")",
":",
"C_out",
"=",
"C",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"(",
"set",
"(",
"WC_keys",
")",
"-",
"set",
"(",
"C",
".",
"keys",
"(",
")",
")",
")",
":",
"C_out",
"[",
"k",
"]",
"=",
"np",
".",
"ze... | Add arrays with zeros for missing Wilson coefficient keys | [
"Add",
"arrays",
"with",
"zeros",
"for",
"missing",
"Wilson",
"coefficient",
"keys"
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L660-L665 |
wilson-eft/wilson | wilson/util/smeftutil.py | C_array2dict | def C_array2dict(C):
"""Convert a 1D array containing C values to a dictionary."""
d = OrderedDict()
i=0
for k in C_keys:
s = C_keys_shape[k]
if s == 1:
j = i+1
d[k] = C[i]
else:
j = i \
+ reduce(operator.mul, s, 1)
d[k] = C[i... | python | def C_array2dict(C):
"""Convert a 1D array containing C values to a dictionary."""
d = OrderedDict()
i=0
for k in C_keys:
s = C_keys_shape[k]
if s == 1:
j = i+1
d[k] = C[i]
else:
j = i \
+ reduce(operator.mul, s, 1)
d[k] = C[i... | [
"def",
"C_array2dict",
"(",
"C",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"i",
"=",
"0",
"for",
"k",
"in",
"C_keys",
":",
"s",
"=",
"C_keys_shape",
"[",
"k",
"]",
"if",
"s",
"==",
"1",
":",
"j",
"=",
"i",
"+",
"1",
"d",
"[",
"k",
"]",
... | Convert a 1D array containing C values to a dictionary. | [
"Convert",
"a",
"1D",
"array",
"containing",
"C",
"values",
"to",
"a",
"dictionary",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L766-L780 |
wilson-eft/wilson | wilson/util/smeftutil.py | C_dict2array | def C_dict2array(C):
"""Convert an OrderedDict containing C values to a 1D array."""
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys]) | python | def C_dict2array(C):
"""Convert an OrderedDict containing C values to a 1D array."""
return np.hstack([np.asarray(C[k]).ravel() for k in C_keys]) | [
"def",
"C_dict2array",
"(",
"C",
")",
":",
"return",
"np",
".",
"hstack",
"(",
"[",
"np",
".",
"asarray",
"(",
"C",
"[",
"k",
"]",
")",
".",
"ravel",
"(",
")",
"for",
"k",
"in",
"C_keys",
"]",
")"
] | Convert an OrderedDict containing C values to a 1D array. | [
"Convert",
"an",
"OrderedDict",
"containing",
"C",
"values",
"to",
"a",
"1D",
"array",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L783-L785 |
wilson-eft/wilson | wilson/util/smeftutil.py | symmetrize_nonred | def symmetrize_nonred(C):
"""Symmetrize the Wilson coefficient arrays.
This function takes into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the operators."""
... | python | def symmetrize_nonred(C):
"""Symmetrize the Wilson coefficient arrays.
This function takes into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the operators."""
... | [
"def",
"symmetrize_nonred",
"(",
"C",
")",
":",
"C_symm",
"=",
"{",
"}",
"for",
"i",
",",
"v",
"in",
"C",
".",
"items",
"(",
")",
":",
"if",
"i",
"in",
"C_symm_keys",
"[",
"0",
"]",
":",
"C_symm",
"[",
"i",
"]",
"=",
"v",
".",
"real",
"elif",... | Symmetrize the Wilson coefficient arrays.
This function takes into account the symmetry factors
that occur when transitioning from a basis with only non-redundant operators
(like in WCxf) to a basis where the Wilson coefficients are symmetrized
like the operators. | [
"Symmetrize",
"the",
"Wilson",
"coefficient",
"arrays",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L814-L845 |
wilson-eft/wilson | wilson/util/smeftutil.py | unscale_dict | def unscale_dict(C):
"""Undo the scaling applied in `scale_dict`."""
C_out = {k: _scale_dict[k] * v for k, v in C.items()}
for k in C_symm_keys[8]:
C_out['qqql'] = unscale_8(C_out['qqql'])
return C_out | python | def unscale_dict(C):
"""Undo the scaling applied in `scale_dict`."""
C_out = {k: _scale_dict[k] * v for k, v in C.items()}
for k in C_symm_keys[8]:
C_out['qqql'] = unscale_8(C_out['qqql'])
return C_out | [
"def",
"unscale_dict",
"(",
"C",
")",
":",
"C_out",
"=",
"{",
"k",
":",
"_scale_dict",
"[",
"k",
"]",
"*",
"v",
"for",
"k",
",",
"v",
"in",
"C",
".",
"items",
"(",
")",
"}",
"for",
"k",
"in",
"C_symm_keys",
"[",
"8",
"]",
":",
"C_out",
"[",
... | Undo the scaling applied in `scale_dict`. | [
"Undo",
"the",
"scaling",
"applied",
"in",
"scale_dict",
"."
] | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L848-L853 |
wilson-eft/wilson | wilson/util/smeftutil.py | wcxf2arrays_symmetrized | def wcxf2arrays_symmetrized(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values.
In contrast to `wcxf2arrays`, here the numpy ... | python | def wcxf2arrays_symmetrized(d):
"""Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values.
In contrast to `wcxf2arrays`, here the numpy ... | [
"def",
"wcxf2arrays_symmetrized",
"(",
"d",
")",
":",
"C",
"=",
"wcxf2arrays",
"(",
"d",
")",
"C",
"=",
"symmetrize_nonred",
"(",
"C",
")",
"C",
"=",
"add_missing",
"(",
"C",
")",
"return",
"C"
] | Convert a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values to a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values.
In contrast to `wcxf2arrays`, here the numpy arrays fulfill the same
symmetry re... | [
"Convert",
"a",
"dictionary",
"with",
"a",
"Wilson",
"coefficient",
"name",
"followed",
"by",
"underscore",
"and",
"numeric",
"indices",
"as",
"keys",
"and",
"numbers",
"as",
"values",
"to",
"a",
"dictionary",
"with",
"Wilson",
"coefficient",
"names",
"as",
"k... | train | https://github.com/wilson-eft/wilson/blob/4164f55ff663d4f668c6e2b4575fd41562662cc9/wilson/util/smeftutil.py#L856-L871 |
genialis/resolwe | resolwe/flow/signals.py | commit_signal | def commit_signal(data_id):
"""Nudge manager at the end of every Data object save event."""
if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False):
immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False)
async_to_sync(manager.communicate)(data_id=data_id, save_settings=F... | python | def commit_signal(data_id):
"""Nudge manager at the end of every Data object save event."""
if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False):
immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False)
async_to_sync(manager.communicate)(data_id=data_id, save_settings=F... | [
"def",
"commit_signal",
"(",
"data_id",
")",
":",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'FLOW_MANAGER_DISABLE_AUTO_CALLS'",
",",
"False",
")",
":",
"immediate",
"=",
"getattr",
"(",
"settings",
",",
"'FLOW_MANAGER_SYNC_AUTO_CALLS'",
",",
"False",
")",
"... | Nudge manager at the end of every Data object save event. | [
"Nudge",
"manager",
"at",
"the",
"end",
"of",
"every",
"Data",
"object",
"save",
"event",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L21-L25 |
genialis/resolwe | resolwe/flow/signals.py | manager_post_save_handler | def manager_post_save_handler(sender, instance, created, **kwargs):
"""Run newly created (spawned) processes."""
if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created:
# Run manager at the end of the potential transaction. Otherwise
# tasks are send to workers... | python | def manager_post_save_handler(sender, instance, created, **kwargs):
"""Run newly created (spawned) processes."""
if instance.status == Data.STATUS_DONE or instance.status == Data.STATUS_ERROR or created:
# Run manager at the end of the potential transaction. Otherwise
# tasks are send to workers... | [
"def",
"manager_post_save_handler",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
".",
"status",
"==",
"Data",
".",
"STATUS_DONE",
"or",
"instance",
".",
"status",
"==",
"Data",
".",
"STATUS_ERROR",
"o... | Run newly created (spawned) processes. | [
"Run",
"newly",
"created",
"(",
"spawned",
")",
"processes",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L29-L35 |
genialis/resolwe | resolwe/flow/signals.py | delete_entity | def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() | python | def delete_entity(sender, instance, **kwargs):
"""Delete Entity when last Data object is deleted."""
# 1 means that the last Data object is going to be deleted.
Entity.objects.annotate(num_data=Count('data')).filter(data=instance, num_data=1).delete() | [
"def",
"delete_entity",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"# 1 means that the last Data object is going to be deleted.",
"Entity",
".",
"objects",
".",
"annotate",
"(",
"num_data",
"=",
"Count",
"(",
"'data'",
")",
")",
".",
"fil... | Delete Entity when last Data object is deleted. | [
"Delete",
"Entity",
"when",
"last",
"Data",
"object",
"is",
"deleted",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L39-L42 |
genialis/resolwe | resolwe/flow/signals.py | delete_relation | def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Rel... | python | def delete_relation(sender, instance, **kwargs):
"""Delete the Relation object when the last Entity is removed."""
def process_signal(relation_id):
"""Get the relation and delete it if it has no entities left."""
try:
relation = Relation.objects.get(pk=relation_id)
except Rel... | [
"def",
"delete_relation",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"process_signal",
"(",
"relation_id",
")",
":",
"\"\"\"Get the relation and delete it if it has no entities left.\"\"\"",
"try",
":",
"relation",
"=",
"Relation",
".",
... | Delete the Relation object when the last Entity is removed. | [
"Delete",
"the",
"Relation",
"object",
"when",
"the",
"last",
"Entity",
"is",
"removed",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/signals.py#L48-L61 |
genialis/resolwe | resolwe/flow/executors/__main__.py | run_executor | async def run_executor():
"""Start the actual execution; instantiate the executor and run."""
parser = argparse.ArgumentParser(description="Run the specified executor.")
parser.add_argument('module', help="The module from which to instantiate the concrete executor.")
args = parser.parse_args()
modu... | python | async def run_executor():
"""Start the actual execution; instantiate the executor and run."""
parser = argparse.ArgumentParser(description="Run the specified executor.")
parser.add_argument('module', help="The module from which to instantiate the concrete executor.")
args = parser.parse_args()
modu... | [
"async",
"def",
"run_executor",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Run the specified executor.\"",
")",
"parser",
".",
"add_argument",
"(",
"'module'",
",",
"help",
"=",
"\"The module from which to instantiate ... | Start the actual execution; instantiate the executor and run. | [
"Start",
"the",
"actual",
"execution",
";",
"instantiate",
"the",
"executor",
"and",
"run",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/executors/__main__.py#L39-L51 |
DataONEorg/d1_python | gmn/src/d1_gmn/app/scimeta.py | assert_valid | def assert_valid(sysmeta_pyxb, pid):
"""Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates obj... | python | def assert_valid(sysmeta_pyxb, pid):
"""Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates obj... | [
"def",
"assert_valid",
"(",
"sysmeta_pyxb",
",",
"pid",
")",
":",
"if",
"not",
"(",
"_is_validation_enabled",
"(",
")",
"and",
"_is_installed_scimeta_format_id",
"(",
"sysmeta_pyxb",
")",
")",
":",
"return",
"if",
"_is_above_size_limit",
"(",
"sysmeta_pyxb",
")",
... | Validate file at {sciobj_path} against schema selected via formatId and raise
InvalidRequest if invalid.
Validation is only performed when:
- SciMeta validation is enabled
- and Object size is below size limit for validation
- and formatId designates object as a Science Metadata object which is re... | [
"Validate",
"file",
"at",
"{",
"sciobj_path",
"}",
"against",
"schema",
"selected",
"via",
"formatId",
"and",
"raise",
"InvalidRequest",
"if",
"invalid",
"."
] | train | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/gmn/src/d1_gmn/app/scimeta.py#L30-L64 |
genialis/resolwe | resolwe/elastic/apps.py | ElasticConfig.ready | def ready(self):
"""Perform application initialization."""
# Initialize the type extension composer.
from . composer import composer
composer.discover_extensions()
is_migrating = sys.argv[1:2] == ['migrate']
if is_migrating:
# Do not register signals and ES i... | python | def ready(self):
"""Perform application initialization."""
# Initialize the type extension composer.
from . composer import composer
composer.discover_extensions()
is_migrating = sys.argv[1:2] == ['migrate']
if is_migrating:
# Do not register signals and ES i... | [
"def",
"ready",
"(",
"self",
")",
":",
"# Initialize the type extension composer.",
"from",
".",
"composer",
"import",
"composer",
"composer",
".",
"discover_extensions",
"(",
")",
"is_migrating",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"2",
"]",
"==",
"[",
... | Perform application initialization. | [
"Perform",
"application",
"initialization",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/elastic/apps.py#L12-L32 |
genialis/resolwe | resolwe/flow/serializers/fields.py | ResolweSlugRelatedField.to_internal_value | def to_internal_value(self, data):
"""Convert to internal value."""
user = getattr(self.context.get('request'), 'user')
queryset = self.get_queryset()
permission = get_full_perm('view', queryset.model)
try:
return get_objects_for_user(
user,
... | python | def to_internal_value(self, data):
"""Convert to internal value."""
user = getattr(self.context.get('request'), 'user')
queryset = self.get_queryset()
permission = get_full_perm('view', queryset.model)
try:
return get_objects_for_user(
user,
... | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"user",
"=",
"getattr",
"(",
"self",
".",
"context",
".",
"get",
"(",
"'request'",
")",
",",
"'user'",
")",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"permission",
"=",
"get_... | Convert to internal value. | [
"Convert",
"to",
"internal",
"value",
"."
] | train | https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/serializers/fields.py#L38-L57 |
Alonreznik/dynamodb-json | dynamodb_json/json_util.py | dumps | def dumps(dct, as_dict=False, **kwargs):
""" Dump the dict to json in DynamoDB Format
You can use any other simplejson or json options
:param dct - the dict to dump
:param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting
:returns: Dynam... | python | def dumps(dct, as_dict=False, **kwargs):
""" Dump the dict to json in DynamoDB Format
You can use any other simplejson or json options
:param dct - the dict to dump
:param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting
:returns: Dynam... | [
"def",
"dumps",
"(",
"dct",
",",
"as_dict",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"result_",
"=",
"TypeSerializer",
"(",
")",
".",
"serialize",
"(",
"json",
".",
"loads",
"(",
"json",
".",
"dumps",
"(",
"dct",
",",
"default",
"=",
"json_... | Dump the dict to json in DynamoDB Format
You can use any other simplejson or json options
:param dct - the dict to dump
:param as_dict - returns the result as python dict (useful for DynamoDB boto3 library) or as json sting
:returns: DynamoDB json format. | [
"Dump",
"the",
"dict",
"to",
"json",
"in",
"DynamoDB",
"Format",
"You",
"can",
"use",
"any",
"other",
"simplejson",
"or",
"json",
"options",
":",
"param",
"dct",
"-",
"the",
"dict",
"to",
"dump",
":",
"param",
"as_dict",
"-",
"returns",
"the",
"result",
... | train | https://github.com/Alonreznik/dynamodb-json/blob/f6a5c472fc349f51281fb2ecd4679479f01ee2f3/dynamodb_json/json_util.py#L32-L45 |
Alonreznik/dynamodb-json | dynamodb_json/json_util.py | object_hook | def object_hook(dct):
""" DynamoDB object hook to return python values """
try:
# First - Try to parse the dct as DynamoDB parsed
if 'BOOL' in dct:
return dct['BOOL']
if 'S' in dct:
val = dct['S']
try:
return datetime.strptime(val, '%Y-... | python | def object_hook(dct):
""" DynamoDB object hook to return python values """
try:
# First - Try to parse the dct as DynamoDB parsed
if 'BOOL' in dct:
return dct['BOOL']
if 'S' in dct:
val = dct['S']
try:
return datetime.strptime(val, '%Y-... | [
"def",
"object_hook",
"(",
"dct",
")",
":",
"try",
":",
"# First - Try to parse the dct as DynamoDB parsed",
"if",
"'BOOL'",
"in",
"dct",
":",
"return",
"dct",
"[",
"'BOOL'",
"]",
"if",
"'S'",
"in",
"dct",
":",
"val",
"=",
"dct",
"[",
"'S'",
"]",
"try",
... | DynamoDB object hook to return python values | [
"DynamoDB",
"object",
"hook",
"to",
"return",
"python",
"values"
] | train | https://github.com/Alonreznik/dynamodb-json/blob/f6a5c472fc349f51281fb2ecd4679479f01ee2f3/dynamodb_json/json_util.py#L48-L104 |
Alonreznik/dynamodb-json | dynamodb_json/json_util.py | loads | def loads(s, as_dict=False, *args, **kwargs):
""" Loads dynamodb json format to a python dict.
:param s - the json string or dict (with the as_dict variable set to True) to convert
:returns python dict object
"""
if as_dict or (not isinstance(s, six.string_types)):
s = json.dumps(s)
... | python | def loads(s, as_dict=False, *args, **kwargs):
""" Loads dynamodb json format to a python dict.
:param s - the json string or dict (with the as_dict variable set to True) to convert
:returns python dict object
"""
if as_dict or (not isinstance(s, six.string_types)):
s = json.dumps(s)
... | [
"def",
"loads",
"(",
"s",
",",
"as_dict",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"as_dict",
"or",
"(",
"not",
"isinstance",
"(",
"s",
",",
"six",
".",
"string_types",
")",
")",
":",
"s",
"=",
"json",
".",
"dump... | Loads dynamodb json format to a python dict.
:param s - the json string or dict (with the as_dict variable set to True) to convert
:returns python dict object | [
"Loads",
"dynamodb",
"json",
"format",
"to",
"a",
"python",
"dict",
".",
":",
"param",
"s",
"-",
"the",
"json",
"string",
"or",
"dict",
"(",
"with",
"the",
"as_dict",
"variable",
"set",
"to",
"True",
")",
"to",
"convert",
":",
"returns",
"python",
"dic... | train | https://github.com/Alonreznik/dynamodb-json/blob/f6a5c472fc349f51281fb2ecd4679479f01ee2f3/dynamodb_json/json_util.py#L107-L115 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.tileSize | def tileSize(self, zoom):
"Returns the size (in meters) of a tile"
assert zoom in range(0, len(self.RESOLUTIONS))
return self.tileSizePx * self.RESOLUTIONS[int(zoom)] | python | def tileSize(self, zoom):
"Returns the size (in meters) of a tile"
assert zoom in range(0, len(self.RESOLUTIONS))
return self.tileSizePx * self.RESOLUTIONS[int(zoom)] | [
"def",
"tileSize",
"(",
"self",
",",
"zoom",
")",
":",
"assert",
"zoom",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"RESOLUTIONS",
")",
")",
"return",
"self",
".",
"tileSizePx",
"*",
"self",
".",
"RESOLUTIONS",
"[",
"int",
"(",
"zoom",
... | Returns the size (in meters) of a tile | [
"Returns",
"the",
"size",
"(",
"in",
"meters",
")",
"of",
"a",
"tile"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L201-L204 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.tileBounds | def tileBounds(self, zoom, tileCol, tileRow):
"Returns the bounds of a tile in LV03 (EPSG:21781)"
assert zoom in range(0, len(self.RESOLUTIONS))
# 0,0 at top left: y axis down and x axis right
tileSize = self.tileSize(zoom)
minX = self.MINX + tileCol * tileSize
maxX = se... | python | def tileBounds(self, zoom, tileCol, tileRow):
"Returns the bounds of a tile in LV03 (EPSG:21781)"
assert zoom in range(0, len(self.RESOLUTIONS))
# 0,0 at top left: y axis down and x axis right
tileSize = self.tileSize(zoom)
minX = self.MINX + tileCol * tileSize
maxX = se... | [
"def",
"tileBounds",
"(",
"self",
",",
"zoom",
",",
"tileCol",
",",
"tileRow",
")",
":",
"assert",
"zoom",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"RESOLUTIONS",
")",
")",
"# 0,0 at top left: y axis down and x axis right",
"tileSize",
"=",
"se... | Returns the bounds of a tile in LV03 (EPSG:21781) | [
"Returns",
"the",
"bounds",
"of",
"a",
"tile",
"in",
"LV03",
"(",
"EPSG",
":",
"21781",
")"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L206-L220 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.tileAddress | def tileAddress(self, zoom, point):
"Returns a tile address based on a zoom level and \
a point in the tile"
[x, y] = point
assert x <= self.MAXX and x >= self.MINX
assert y <= self.MAXY and y >= self.MINY
assert zoom in range(0, len(self.RESOLUTIONS))
tileS = se... | python | def tileAddress(self, zoom, point):
"Returns a tile address based on a zoom level and \
a point in the tile"
[x, y] = point
assert x <= self.MAXX and x >= self.MINX
assert y <= self.MAXY and y >= self.MINY
assert zoom in range(0, len(self.RESOLUTIONS))
tileS = se... | [
"def",
"tileAddress",
"(",
"self",
",",
"zoom",
",",
"point",
")",
":",
"[",
"x",
",",
"y",
"]",
"=",
"point",
"assert",
"x",
"<=",
"self",
".",
"MAXX",
"and",
"x",
">=",
"self",
".",
"MINX",
"assert",
"y",
"<=",
"self",
".",
"MAXY",
"and",
"y"... | Returns a tile address based on a zoom level and \
a point in the tile | [
"Returns",
"a",
"tile",
"address",
"based",
"on",
"a",
"zoom",
"level",
"and",
"\\",
"a",
"point",
"in",
"the",
"tile"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L222-L246 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.intersectsExtent | def intersectsExtent(self, extent):
"Determine if an extent intersects this instance extent"
return \
self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \
self.extent[1] <= extent[3] and self.extent[3] >= extent[1] | python | def intersectsExtent(self, extent):
"Determine if an extent intersects this instance extent"
return \
self.extent[0] <= extent[2] and self.extent[2] >= extent[0] and \
self.extent[1] <= extent[3] and self.extent[3] >= extent[1] | [
"def",
"intersectsExtent",
"(",
"self",
",",
"extent",
")",
":",
"return",
"self",
".",
"extent",
"[",
"0",
"]",
"<=",
"extent",
"[",
"2",
"]",
"and",
"self",
".",
"extent",
"[",
"2",
"]",
">=",
"extent",
"[",
"0",
"]",
"and",
"self",
".",
"exten... | Determine if an extent intersects this instance extent | [
"Determine",
"if",
"an",
"extent",
"intersects",
"this",
"instance",
"extent"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L248-L252 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.iterGrid | def iterGrid(self, minZoom, maxZoom):
"Yields the tileBounds, zoom, tileCol and tileRow"
assert minZoom in range(0, len(self.RESOLUTIONS))
assert maxZoom in range(0, len(self.RESOLUTIONS))
assert minZoom <= maxZoom
for zoom in xrange(minZoom, maxZoom + 1):
[minRow, m... | python | def iterGrid(self, minZoom, maxZoom):
"Yields the tileBounds, zoom, tileCol and tileRow"
assert minZoom in range(0, len(self.RESOLUTIONS))
assert maxZoom in range(0, len(self.RESOLUTIONS))
assert minZoom <= maxZoom
for zoom in xrange(minZoom, maxZoom + 1):
[minRow, m... | [
"def",
"iterGrid",
"(",
"self",
",",
"minZoom",
",",
"maxZoom",
")",
":",
"assert",
"minZoom",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"RESOLUTIONS",
")",
")",
"assert",
"maxZoom",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".... | Yields the tileBounds, zoom, tileCol and tileRow | [
"Yields",
"the",
"tileBounds",
"zoom",
"tileCol",
"and",
"tileRow"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L254-L265 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.numberOfXTilesAtZoom | def numberOfXTilesAtZoom(self, zoom):
"Returns the number of tiles over x at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxCol - minCol + 1 | python | def numberOfXTilesAtZoom(self, zoom):
"Returns the number of tiles over x at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxCol - minCol + 1 | [
"def",
"numberOfXTilesAtZoom",
"(",
"self",
",",
"zoom",
")",
":",
"[",
"minRow",
",",
"minCol",
",",
"maxRow",
",",
"maxCol",
"]",
"=",
"self",
".",
"getExtentAddress",
"(",
"zoom",
")",
"return",
"maxCol",
"-",
"minCol",
"+",
"1"
] | Returns the number of tiles over x at a given zoom level | [
"Returns",
"the",
"number",
"of",
"tiles",
"over",
"x",
"at",
"a",
"given",
"zoom",
"level"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L267-L270 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.numberOfYTilesAtZoom | def numberOfYTilesAtZoom(self, zoom):
"Retruns the number of tiles over y at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxRow - minRow + 1 | python | def numberOfYTilesAtZoom(self, zoom):
"Retruns the number of tiles over y at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return maxRow - minRow + 1 | [
"def",
"numberOfYTilesAtZoom",
"(",
"self",
",",
"zoom",
")",
":",
"[",
"minRow",
",",
"minCol",
",",
"maxRow",
",",
"maxCol",
"]",
"=",
"self",
".",
"getExtentAddress",
"(",
"zoom",
")",
"return",
"maxRow",
"-",
"minRow",
"+",
"1"
] | Retruns the number of tiles over y at a given zoom level | [
"Retruns",
"the",
"number",
"of",
"tiles",
"over",
"y",
"at",
"a",
"given",
"zoom",
"level"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L272-L275 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.numberOfTilesAtZoom | def numberOfTilesAtZoom(self, zoom):
"Returns the total number of tile at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return (maxCol - minCol + 1) * (maxRow - minRow + 1) | python | def numberOfTilesAtZoom(self, zoom):
"Returns the total number of tile at a given zoom level"
[minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom)
return (maxCol - minCol + 1) * (maxRow - minRow + 1) | [
"def",
"numberOfTilesAtZoom",
"(",
"self",
",",
"zoom",
")",
":",
"[",
"minRow",
",",
"minCol",
",",
"maxRow",
",",
"maxCol",
"]",
"=",
"self",
".",
"getExtentAddress",
"(",
"zoom",
")",
"return",
"(",
"maxCol",
"-",
"minCol",
"+",
"1",
")",
"*",
"("... | Returns the total number of tile at a given zoom level | [
"Returns",
"the",
"total",
"number",
"of",
"tile",
"at",
"a",
"given",
"zoom",
"level"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L277-L280 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.totalNumberOfTiles | def totalNumberOfTiles(self, minZoom=None, maxZoom=None):
"Return the total number of tiles for this instance extent"
nbTiles = 0
minZoom = minZoom or 0
if maxZoom:
maxZoom = maxZoom + 1
else:
maxZoom = len(self.RESOLUTIONS)
for zoom in xrange(minZ... | python | def totalNumberOfTiles(self, minZoom=None, maxZoom=None):
"Return the total number of tiles for this instance extent"
nbTiles = 0
minZoom = minZoom or 0
if maxZoom:
maxZoom = maxZoom + 1
else:
maxZoom = len(self.RESOLUTIONS)
for zoom in xrange(minZ... | [
"def",
"totalNumberOfTiles",
"(",
"self",
",",
"minZoom",
"=",
"None",
",",
"maxZoom",
"=",
"None",
")",
":",
"nbTiles",
"=",
"0",
"minZoom",
"=",
"minZoom",
"or",
"0",
"if",
"maxZoom",
":",
"maxZoom",
"=",
"maxZoom",
"+",
"1",
"else",
":",
"maxZoom",
... | Return the total number of tiles for this instance extent | [
"Return",
"the",
"total",
"number",
"of",
"tiles",
"for",
"this",
"instance",
"extent"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L282-L292 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.getZoom | def getZoom(self, resolution):
"Return the zoom level for a given resolution"
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) | python | def getZoom(self, resolution):
"Return the zoom level for a given resolution"
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) | [
"def",
"getZoom",
"(",
"self",
",",
"resolution",
")",
":",
"assert",
"resolution",
"in",
"self",
".",
"RESOLUTIONS",
"return",
"self",
".",
"RESOLUTIONS",
".",
"index",
"(",
"resolution",
")"
] | Return the zoom level for a given resolution | [
"Return",
"the",
"zoom",
"level",
"for",
"a",
"given",
"resolution"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L298-L301 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid._getZoomLevelRange | def _getZoomLevelRange(self, resolution, unit='meters'):
"Return lower and higher zoom level given a resolution"
assert unit in ('meters', 'degrees')
if unit == 'meters' and self.unit == 'degrees':
resolution = resolution / self.metersPerUnit
elif unit == 'degrees' and self.u... | python | def _getZoomLevelRange(self, resolution, unit='meters'):
"Return lower and higher zoom level given a resolution"
assert unit in ('meters', 'degrees')
if unit == 'meters' and self.unit == 'degrees':
resolution = resolution / self.metersPerUnit
elif unit == 'degrees' and self.u... | [
"def",
"_getZoomLevelRange",
"(",
"self",
",",
"resolution",
",",
"unit",
"=",
"'meters'",
")",
":",
"assert",
"unit",
"in",
"(",
"'meters'",
",",
"'degrees'",
")",
"if",
"unit",
"==",
"'meters'",
"and",
"self",
".",
"unit",
"==",
"'degrees'",
":",
"reso... | Return lower and higher zoom level given a resolution | [
"Return",
"lower",
"and",
"higher",
"zoom",
"level",
"given",
"a",
"resolution"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L303-L318 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.getClosestZoom | def getClosestZoom(self, resolution, unit='meters'):
"""
Return the closest zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
lo, hi = self._getZoomLevelRange(resolution, unit)
... | python | def getClosestZoom(self, resolution, unit='meters'):
"""
Return the closest zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
lo, hi = self._getZoomLevelRange(resolution, unit)
... | [
"def",
"getClosestZoom",
"(",
"self",
",",
"resolution",
",",
"unit",
"=",
"'meters'",
")",
":",
"lo",
",",
"hi",
"=",
"self",
".",
"_getZoomLevelRange",
"(",
"resolution",
",",
"unit",
")",
"if",
"lo",
"==",
"0",
":",
"return",
"lo",
"if",
"hi",
"==... | Return the closest zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters') | [
"Return",
"the",
"closest",
"zoom",
"level",
"for",
"a",
"given",
"resolution",
"Parameters",
":",
"resolution",
"--",
"max",
".",
"resolution",
"unit",
"--",
"unit",
"for",
"output",
"(",
"default",
"=",
"meters",
")"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L320-L335 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.getCeilingZoom | def getCeilingZoom(self, resolution, unit='meters'):
"""
Return the maximized zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
if resolution in self.RESOLUTIONS:
return s... | python | def getCeilingZoom(self, resolution, unit='meters'):
"""
Return the maximized zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters')
"""
if resolution in self.RESOLUTIONS:
return s... | [
"def",
"getCeilingZoom",
"(",
"self",
",",
"resolution",
",",
"unit",
"=",
"'meters'",
")",
":",
"if",
"resolution",
"in",
"self",
".",
"RESOLUTIONS",
":",
"return",
"self",
".",
"getZoom",
"(",
"resolution",
")",
"lo",
",",
"hi",
"=",
"self",
".",
"_g... | Return the maximized zoom level for a given resolution
Parameters:
resolution -- max. resolution
unit -- unit for output (default='meters') | [
"Return",
"the",
"maximized",
"zoom",
"level",
"for",
"a",
"given",
"resolution",
"Parameters",
":",
"resolution",
"--",
"max",
".",
"resolution",
"unit",
"--",
"unit",
"for",
"output",
"(",
"default",
"=",
"meters",
")"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L337-L351 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.getScale | def getScale(self, zoom):
"""Returns the scale at a given zoom level"""
if self.unit == 'degrees':
resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT
else:
resolution = self.getResolution(zoom)
return resolution / STANDARD_PIXEL_SIZE | python | def getScale(self, zoom):
"""Returns the scale at a given zoom level"""
if self.unit == 'degrees':
resolution = self.getResolution(zoom) * EPSG4326_METERS_PER_UNIT
else:
resolution = self.getResolution(zoom)
return resolution / STANDARD_PIXEL_SIZE | [
"def",
"getScale",
"(",
"self",
",",
"zoom",
")",
":",
"if",
"self",
".",
"unit",
"==",
"'degrees'",
":",
"resolution",
"=",
"self",
".",
"getResolution",
"(",
"zoom",
")",
"*",
"EPSG4326_METERS_PER_UNIT",
"else",
":",
"resolution",
"=",
"self",
".",
"ge... | Returns the scale at a given zoom level | [
"Returns",
"the",
"scale",
"at",
"a",
"given",
"zoom",
"level"
] | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L353-L359 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.getExtentAddress | def getExtentAddress(self, zoom, extent=None, contained=False):
"""
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based
on the instance's extent or a user defined extent. Generic method
that works with regular and irregular pyramids.
Parameters:
zoom... | python | def getExtentAddress(self, zoom, extent=None, contained=False):
"""
Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based
on the instance's extent or a user defined extent. Generic method
that works with regular and irregular pyramids.
Parameters:
zoom... | [
"def",
"getExtentAddress",
"(",
"self",
",",
"zoom",
",",
"extent",
"=",
"None",
",",
"contained",
"=",
"False",
")",
":",
"if",
"extent",
":",
"bbox",
"=",
"extent",
"else",
":",
"bbox",
"=",
"self",
".",
"extent",
"minX",
"=",
"bbox",
"[",
"0",
"... | Return the bounding addresses ([minRow, minCol, maxRow, maxCol] based
on the instance's extent or a user defined extent. Generic method
that works with regular and irregular pyramids.
Parameters:
zoom -- the zoom for which we want the bounding addresses
extent (optional) ... | [
"Return",
"the",
"bounding",
"addresses",
"(",
"[",
"minRow",
"minCol",
"maxRow",
"maxCol",
"]",
"based",
"on",
"the",
"instance",
"s",
"extent",
"or",
"a",
"user",
"defined",
"extent",
".",
"Generic",
"method",
"that",
"works",
"with",
"regular",
"and",
"... | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L361-L403 |
geoadmin/lib-gatilegrid | gatilegrid/tilegrids.py | _TileGrid.getParentTiles | def getParentTiles(self, zoom, col, row, zoomParent):
"""
Return the parent tile(s) for an irregular (not following quadindex)
and regular tiling scheme
Parameters:
zoom -- the zoom level a the child tile
row -- the row of the child tile
col -- the col... | python | def getParentTiles(self, zoom, col, row, zoomParent):
"""
Return the parent tile(s) for an irregular (not following quadindex)
and regular tiling scheme
Parameters:
zoom -- the zoom level a the child tile
row -- the row of the child tile
col -- the col... | [
"def",
"getParentTiles",
"(",
"self",
",",
"zoom",
",",
"col",
",",
"row",
",",
"zoomParent",
")",
":",
"assert",
"zoomParent",
"<=",
"zoom",
"if",
"zoomParent",
"==",
"zoom",
":",
"return",
"[",
"[",
"zoom",
",",
"col",
",",
"row",
"]",
"]",
"extent... | Return the parent tile(s) for an irregular (not following quadindex)
and regular tiling scheme
Parameters:
zoom -- the zoom level a the child tile
row -- the row of the child tile
col -- the col of the child tile
zoomParent -- the target zoom of the parent... | [
"Return",
"the",
"parent",
"tile",
"(",
"s",
")",
"for",
"an",
"irregular",
"(",
"not",
"following",
"quadindex",
")",
"and",
"regular",
"tiling",
"scheme",
"Parameters",
":",
"zoom",
"--",
"the",
"zoom",
"level",
"a",
"the",
"child",
"tile",
"row",
"--"... | train | https://github.com/geoadmin/lib-gatilegrid/blob/28e39cba22451f6ef0ddcb93cbc0838f06815505/gatilegrid/tilegrids.py#L405-L425 |
globality-corp/microcosm-logging | microcosm_logging/factories.py | enable_loggly | def enable_loggly(graph):
"""
Enable loggly if it is configured and not debug/testing.
"""
if graph.metadata.debug or graph.metadata.testing:
return False
try:
if not graph.config.logging.loggly.token:
return False
if not graph.config.logging.loggly.environment... | python | def enable_loggly(graph):
"""
Enable loggly if it is configured and not debug/testing.
"""
if graph.metadata.debug or graph.metadata.testing:
return False
try:
if not graph.config.logging.loggly.token:
return False
if not graph.config.logging.loggly.environment... | [
"def",
"enable_loggly",
"(",
"graph",
")",
":",
"if",
"graph",
".",
"metadata",
".",
"debug",
"or",
"graph",
".",
"metadata",
".",
"testing",
":",
"return",
"False",
"try",
":",
"if",
"not",
"graph",
".",
"config",
".",
"logging",
".",
"loggly",
".",
... | Enable loggly if it is configured and not debug/testing. | [
"Enable",
"loggly",
"if",
"it",
"is",
"configured",
"and",
"not",
"debug",
"/",
"testing",
"."
] | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L89-L106 |
globality-corp/microcosm-logging | microcosm_logging/factories.py | make_dict_config | def make_dict_config(graph):
"""
Build a dictionary configuration from conventions and configuration.
"""
formatters = {}
handlers = {}
loggers = {}
# create the console handler
formatters["ExtraFormatter"] = make_extra_console_formatter(graph)
handlers["console"] = make_stream_han... | python | def make_dict_config(graph):
"""
Build a dictionary configuration from conventions and configuration.
"""
formatters = {}
handlers = {}
loggers = {}
# create the console handler
formatters["ExtraFormatter"] = make_extra_console_formatter(graph)
handlers["console"] = make_stream_han... | [
"def",
"make_dict_config",
"(",
"graph",
")",
":",
"formatters",
"=",
"{",
"}",
"handlers",
"=",
"{",
"}",
"loggers",
"=",
"{",
"}",
"# create the console handler",
"formatters",
"[",
"\"ExtraFormatter\"",
"]",
"=",
"make_extra_console_formatter",
"(",
"graph",
... | Build a dictionary configuration from conventions and configuration. | [
"Build",
"a",
"dictionary",
"configuration",
"from",
"conventions",
"and",
"configuration",
"."
] | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L109-L142 |
globality-corp/microcosm-logging | microcosm_logging/factories.py | make_json_formatter | def make_json_formatter(graph):
"""
Create the default json formatter.
"""
return {
"()": graph.config.logging.json_formatter.formatter,
"fmt": graph.config.logging.json_required_keys,
} | python | def make_json_formatter(graph):
"""
Create the default json formatter.
"""
return {
"()": graph.config.logging.json_formatter.formatter,
"fmt": graph.config.logging.json_required_keys,
} | [
"def",
"make_json_formatter",
"(",
"graph",
")",
":",
"return",
"{",
"\"()\"",
":",
"graph",
".",
"config",
".",
"logging",
".",
"json_formatter",
".",
"formatter",
",",
"\"fmt\"",
":",
"graph",
".",
"config",
".",
"logging",
".",
"json_required_keys",
",",
... | Create the default json formatter. | [
"Create",
"the",
"default",
"json",
"formatter",
"."
] | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L145-L154 |
globality-corp/microcosm-logging | microcosm_logging/factories.py | make_stream_handler | def make_stream_handler(graph, formatter):
"""
Create the stream handler. Used for console/debug output.
"""
return {
"class": graph.config.logging.stream_handler.class_,
"formatter": formatter,
"level": graph.config.logging.level,
"stream": graph.config.logging.stream_h... | python | def make_stream_handler(graph, formatter):
"""
Create the stream handler. Used for console/debug output.
"""
return {
"class": graph.config.logging.stream_handler.class_,
"formatter": formatter,
"level": graph.config.logging.level,
"stream": graph.config.logging.stream_h... | [
"def",
"make_stream_handler",
"(",
"graph",
",",
"formatter",
")",
":",
"return",
"{",
"\"class\"",
":",
"graph",
".",
"config",
".",
"logging",
".",
"stream_handler",
".",
"class_",
",",
"\"formatter\"",
":",
"formatter",
",",
"\"level\"",
":",
"graph",
"."... | Create the stream handler. Used for console/debug output. | [
"Create",
"the",
"stream",
"handler",
".",
"Used",
"for",
"console",
"/",
"debug",
"output",
"."
] | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L169-L179 |
globality-corp/microcosm-logging | microcosm_logging/factories.py | make_loggly_handler | def make_loggly_handler(graph, formatter):
"""
Create the loggly handler.
Used for searchable aggregation.
"""
base_url = graph.config.logging.loggly.base_url
loggly_url = "{}/inputs/{}/tag/{}".format(
base_url,
graph.config.logging.loggly.token,
",".join([
... | python | def make_loggly_handler(graph, formatter):
"""
Create the loggly handler.
Used for searchable aggregation.
"""
base_url = graph.config.logging.loggly.base_url
loggly_url = "{}/inputs/{}/tag/{}".format(
base_url,
graph.config.logging.loggly.token,
",".join([
... | [
"def",
"make_loggly_handler",
"(",
"graph",
",",
"formatter",
")",
":",
"base_url",
"=",
"graph",
".",
"config",
".",
"logging",
".",
"loggly",
".",
"base_url",
"loggly_url",
"=",
"\"{}/inputs/{}/tag/{}\"",
".",
"format",
"(",
"base_url",
",",
"graph",
".",
... | Create the loggly handler.
Used for searchable aggregation. | [
"Create",
"the",
"loggly",
"handler",
"."
] | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L182-L203 |
globality-corp/microcosm-logging | microcosm_logging/factories.py | make_library_levels | def make_library_levels(graph):
"""
Create third party library logging level configurations.
Tunes down overly verbose logs in commonly used libraries.
"""
# inject the default components; these can, but probably shouldn't, be overridden
levels = {}
for level in ["DEBUG", "INFO", "WARN", "... | python | def make_library_levels(graph):
"""
Create third party library logging level configurations.
Tunes down overly verbose logs in commonly used libraries.
"""
# inject the default components; these can, but probably shouldn't, be overridden
levels = {}
for level in ["DEBUG", "INFO", "WARN", "... | [
"def",
"make_library_levels",
"(",
"graph",
")",
":",
"# inject the default components; these can, but probably shouldn't, be overridden",
"levels",
"=",
"{",
"}",
"for",
"level",
"in",
"[",
"\"DEBUG\"",
",",
"\"INFO\"",
",",
"\"WARN\"",
",",
"\"ERROR\"",
"]",
":",
"l... | Create third party library logging level configurations.
Tunes down overly verbose logs in commonly used libraries. | [
"Create",
"third",
"party",
"library",
"logging",
"level",
"configurations",
"."
] | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/factories.py#L206-L228 |
edx/edx-django-sites-extensions | django_sites_extensions/middleware.py | RedirectMiddleware.process_request | def process_request(self, request):
"""
Redirects the current request if there is a matching Redirect model
with the current request URL as the old_path field.
"""
site = request.site
cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=sit... | python | def process_request(self, request):
"""
Redirects the current request if there is a matching Redirect model
with the current request URL as the old_path field.
"""
site = request.site
cache_key = '{prefix}-{site}'.format(prefix=settings.REDIRECT_CACHE_KEY_PREFIX, site=sit... | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"site",
"=",
"request",
".",
"site",
"cache_key",
"=",
"'{prefix}-{site}'",
".",
"format",
"(",
"prefix",
"=",
"settings",
".",
"REDIRECT_CACHE_KEY_PREFIX",
",",
"site",
"=",
"site",
".",
"doma... | Redirects the current request if there is a matching Redirect model
with the current request URL as the old_path field. | [
"Redirects",
"the",
"current",
"request",
"if",
"there",
"is",
"a",
"matching",
"Redirect",
"model",
"with",
"the",
"current",
"request",
"URL",
"as",
"the",
"old_path",
"field",
"."
] | train | https://github.com/edx/edx-django-sites-extensions/blob/d4fc18cb4831b7b95ccd1b2f9afc9afa1f19b096/django_sites_extensions/middleware.py#L14-L27 |
globality-corp/microcosm-logging | microcosm_logging/decorators.py | context_logger | def context_logger(context_func, func, parent=None):
"""
The results of context_func will be executed and applied to a ContextLogger
instance for the execution of func. The resulting ContextLogger instance will be
available on parent.logger for the duration of func.
:param context_func: callable wh... | python | def context_logger(context_func, func, parent=None):
"""
The results of context_func will be executed and applied to a ContextLogger
instance for the execution of func. The resulting ContextLogger instance will be
available on parent.logger for the duration of func.
:param context_func: callable wh... | [
"def",
"context_logger",
"(",
"context_func",
",",
"func",
",",
"parent",
"=",
"None",
")",
":",
"if",
"parent",
"is",
"None",
":",
"parent",
"=",
"func",
".",
"__self__",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"parent... | The results of context_func will be executed and applied to a ContextLogger
instance for the execution of func. The resulting ContextLogger instance will be
available on parent.logger for the duration of func.
:param context_func: callable which provides dictionary-like context information
:param func:... | [
"The",
"results",
"of",
"context_func",
"will",
"be",
"executed",
"and",
"applied",
"to",
"a",
"ContextLogger",
"instance",
"for",
"the",
"execution",
"of",
"func",
".",
"The",
"resulting",
"ContextLogger",
"instance",
"will",
"be",
"available",
"on",
"parent",
... | train | https://github.com/globality-corp/microcosm-logging/blob/f60ac971a343b661a47a0d0d4e0a58de76152bbc/microcosm_logging/decorators.py#L38-L61 |
edx/edx-django-sites-extensions | django_sites_extensions/models.py | patched_get_current | def patched_get_current(self, request=None):
"""
Monkey patched version of Django's SiteManager.get_current() function.
Returns the current Site based on a given request or the SITE_ID in
the project's settings. If a request is given attempts to match a site
with domain matching request.get_host().... | python | def patched_get_current(self, request=None):
"""
Monkey patched version of Django's SiteManager.get_current() function.
Returns the current Site based on a given request or the SITE_ID in
the project's settings. If a request is given attempts to match a site
with domain matching request.get_host().... | [
"def",
"patched_get_current",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"# Imported here to avoid circular import",
"from",
"django",
".",
"conf",
"import",
"settings",
"if",
"request",
":",
"try",
":",
"return",
"self",
".",
"_get_site_by_request",
"(",... | Monkey patched version of Django's SiteManager.get_current() function.
Returns the current Site based on a given request or the SITE_ID in
the project's settings. If a request is given attempts to match a site
with domain matching request.get_host(). If a request is not given or
a site cannot be found ... | [
"Monkey",
"patched",
"version",
"of",
"Django",
"s",
"SiteManager",
".",
"get_current",
"()",
"function",
"."
] | train | https://github.com/edx/edx-django-sites-extensions/blob/d4fc18cb4831b7b95ccd1b2f9afc9afa1f19b096/django_sites_extensions/models.py#L29-L55 |
edx/edx-django-sites-extensions | django_sites_extensions/models.py | patched_get_site_by_id | def patched_get_site_by_id(self, site_id):
"""
Monkey patched version of Django's SiteManager._get_site_by_id() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hits on ever... | python | def patched_get_site_by_id(self, site_id):
"""
Monkey patched version of Django's SiteManager._get_site_by_id() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hits on ever... | [
"def",
"patched_get_site_by_id",
"(",
"self",
",",
"site_id",
")",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"site",
"=",
"models",
".",
"SITE_CACHE",
".",
"get",
"(",
"site_id",
")",
"cache_timeout",
"=",
"SITE_CACHE_TIMEOUTS",
... | Monkey patched version of Django's SiteManager._get_site_by_id() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hits on every request made to the Django application, but also allo... | [
"Monkey",
"patched",
"version",
"of",
"Django",
"s",
"SiteManager",
".",
"_get_site_by_id",
"()",
"function",
"."
] | train | https://github.com/edx/edx-django-sites-extensions/blob/d4fc18cb4831b7b95ccd1b2f9afc9afa1f19b096/django_sites_extensions/models.py#L58-L76 |
edx/edx-django-sites-extensions | django_sites_extensions/models.py | patched_get_site_by_request | def patched_get_site_by_request(self, request):
"""
Monkey patched version of Django's SiteManager._get_site_by_request() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hi... | python | def patched_get_site_by_request(self, request):
"""
Monkey patched version of Django's SiteManager._get_site_by_request() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hi... | [
"def",
"patched_get_site_by_request",
"(",
"self",
",",
"request",
")",
":",
"host",
"=",
"request",
".",
"get_host",
"(",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"site",
"=",
"models",
".",
"SITE_CACHE",
".",
"get",
"(",
... | Monkey patched version of Django's SiteManager._get_site_by_request() function.
Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site.
This allows for the use of an in-memory cache for Site models, avoiding one
or more DB hits on every request made to the Django application, but also... | [
"Monkey",
"patched",
"version",
"of",
"Django",
"s",
"SiteManager",
".",
"_get_site_by_request",
"()",
"function",
"."
] | train | https://github.com/edx/edx-django-sites-extensions/blob/d4fc18cb4831b7b95ccd1b2f9afc9afa1f19b096/django_sites_extensions/models.py#L79-L98 |
IBM/pyxcli | pyxcli/helpers/xml_util.py | str_brief | def str_brief(obj, lim=20, dots='...', use_repr=True):
"""Truncates a string, starting from 'lim' chars. The given object
can be a string, or something that can be casted to a string.
>>> import string
>>> str_brief(string.uppercase)
'ABCDEFGHIJKLMNOPQRST...'
>>> str_brief(2 ** 50, lim=10, dots... | python | def str_brief(obj, lim=20, dots='...', use_repr=True):
"""Truncates a string, starting from 'lim' chars. The given object
can be a string, or something that can be casted to a string.
>>> import string
>>> str_brief(string.uppercase)
'ABCDEFGHIJKLMNOPQRST...'
>>> str_brief(2 ** 50, lim=10, dots... | [
"def",
"str_brief",
"(",
"obj",
",",
"lim",
"=",
"20",
",",
"dots",
"=",
"'...'",
",",
"use_repr",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
"or",
"not",
"use_repr",
":",
"full",
"=",
"str",
"(",
"obj",
")",
"... | Truncates a string, starting from 'lim' chars. The given object
can be a string, or something that can be casted to a string.
>>> import string
>>> str_brief(string.uppercase)
'ABCDEFGHIJKLMNOPQRST...'
>>> str_brief(2 ** 50, lim=10, dots='0')
'11258999060' | [
"Truncates",
"a",
"string",
"starting",
"from",
"lim",
"chars",
".",
"The",
"given",
"object",
"can",
"be",
"a",
"string",
"or",
"something",
"that",
"can",
"be",
"casted",
"to",
"a",
"string",
"."
] | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/helpers/xml_util.py#L42-L67 |
IBM/pyxcli | pyxcli/mirroring/mirrored_entities.py | MirroredEntities.get_mirror_resources_by_name_map | def get_mirror_resources_by_name_map(self, scope=None):
""" returns a map volume_name -> volume, cg_name->cg
scope is either None or CG or Volume
"""
volumes_mirrors_by_name = dict()
cgs_mirrors_by_name = dict()
if ((scope is None) or (scope.lower() == 'volume')... | python | def get_mirror_resources_by_name_map(self, scope=None):
""" returns a map volume_name -> volume, cg_name->cg
scope is either None or CG or Volume
"""
volumes_mirrors_by_name = dict()
cgs_mirrors_by_name = dict()
if ((scope is None) or (scope.lower() == 'volume')... | [
"def",
"get_mirror_resources_by_name_map",
"(",
"self",
",",
"scope",
"=",
"None",
")",
":",
"volumes_mirrors_by_name",
"=",
"dict",
"(",
")",
"cgs_mirrors_by_name",
"=",
"dict",
"(",
")",
"if",
"(",
"(",
"scope",
"is",
"None",
")",
"or",
"(",
"scope",
"."... | returns a map volume_name -> volume, cg_name->cg
scope is either None or CG or Volume | [
"returns",
"a",
"map",
"volume_name",
"-",
">",
"volume",
"cg_name",
"-",
">",
"cg",
"scope",
"is",
"either",
"None",
"or",
"CG",
"or",
"Volume"
] | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/mirrored_entities.py#L48-L64 |
IBM/pyxcli | pyxcli/mirroring/mirrored_entities.py | MirroredEntities.get_host_port_names | def get_host_port_names(self, host_name):
""" return a list of the port names of XIV host """
port_names = list()
host = self.get_hosts_by_name(host_name)
fc_ports = host.fc_ports
iscsi_ports = host.iscsi_ports
port_names.extend(fc_ports.split(',') if fc_ports != ''... | python | def get_host_port_names(self, host_name):
""" return a list of the port names of XIV host """
port_names = list()
host = self.get_hosts_by_name(host_name)
fc_ports = host.fc_ports
iscsi_ports = host.iscsi_ports
port_names.extend(fc_ports.split(',') if fc_ports != ''... | [
"def",
"get_host_port_names",
"(",
"self",
",",
"host_name",
")",
":",
"port_names",
"=",
"list",
"(",
")",
"host",
"=",
"self",
".",
"get_hosts_by_name",
"(",
"host_name",
")",
"fc_ports",
"=",
"host",
".",
"fc_ports",
"iscsi_ports",
"=",
"host",
".",
"is... | return a list of the port names of XIV host | [
"return",
"a",
"list",
"of",
"the",
"port",
"names",
"of",
"XIV",
"host"
] | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/mirrored_entities.py#L115-L123 |
IBM/pyxcli | pyxcli/mirroring/mirrored_entities.py | MirroredEntities.get_cluster_port_names | def get_cluster_port_names(self, cluster_name):
""" return a list of the port names under XIV CLuster """
port_names = list()
for host_name in self.get_hosts_by_clusters()[cluster_name]:
port_names.extend(self.get_hosts_by_name(host_name))
return port_names | python | def get_cluster_port_names(self, cluster_name):
""" return a list of the port names under XIV CLuster """
port_names = list()
for host_name in self.get_hosts_by_clusters()[cluster_name]:
port_names.extend(self.get_hosts_by_name(host_name))
return port_names | [
"def",
"get_cluster_port_names",
"(",
"self",
",",
"cluster_name",
")",
":",
"port_names",
"=",
"list",
"(",
")",
"for",
"host_name",
"in",
"self",
".",
"get_hosts_by_clusters",
"(",
")",
"[",
"cluster_name",
"]",
":",
"port_names",
".",
"extend",
"(",
"self... | return a list of the port names under XIV CLuster | [
"return",
"a",
"list",
"of",
"the",
"port",
"names",
"under",
"XIV",
"CLuster"
] | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/mirrored_entities.py#L125-L130 |
IBM/pyxcli | pyxcli/pool.py | XCLIClientPool.flush | def flush(self):
"""remove all stale clients from pool"""
now = time.time()
to_remove = []
for k, entry in self.pool.items():
if entry.timestamp < now:
entry.client.close()
to_remove.append(k)
for k in to_remove:
del self.po... | python | def flush(self):
"""remove all stale clients from pool"""
now = time.time()
to_remove = []
for k, entry in self.pool.items():
if entry.timestamp < now:
entry.client.close()
to_remove.append(k)
for k in to_remove:
del self.po... | [
"def",
"flush",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"to_remove",
"=",
"[",
"]",
"for",
"k",
",",
"entry",
"in",
"self",
".",
"pool",
".",
"items",
"(",
")",
":",
"if",
"entry",
".",
"timestamp",
"<",
"now",
":",
... | remove all stale clients from pool | [
"remove",
"all",
"stale",
"clients",
"from",
"pool"
] | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/pool.py#L70-L79 |
IBM/pyxcli | pyxcli/pool.py | XCLIClientPool.get | def get(self, user, password, endpoints):
"""Gets an existing connection or opens a new one
"""
now = time.time()
# endpoints can either be str or list
if isinstance(endpoints, str):
endpoints = [endpoints]
for ep in endpoints:
if ep not in self.po... | python | def get(self, user, password, endpoints):
"""Gets an existing connection or opens a new one
"""
now = time.time()
# endpoints can either be str or list
if isinstance(endpoints, str):
endpoints = [endpoints]
for ep in endpoints:
if ep not in self.po... | [
"def",
"get",
"(",
"self",
",",
"user",
",",
"password",
",",
"endpoints",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# endpoints can either be str or list",
"if",
"isinstance",
"(",
"endpoints",
",",
"str",
")",
":",
"endpoints",
"=",
"[",
"e... | Gets an existing connection or opens a new one | [
"Gets",
"an",
"existing",
"connection",
"or",
"opens",
"a",
"new",
"one"
] | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/pool.py#L81-L110 |
aioworkers/aioworkers | aioworkers/humanize.py | size | def size(value: int, suffixes: list = None) -> str:
"""
>>> size(1024)
'1 KB'
"""
suffixes = suffixes or [
'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
order = int(log2(value) / 10) if value else 0
return '{:.4g} {}'.format(value / (1 << (order * 10)), suffixes[order]) | python | def size(value: int, suffixes: list = None) -> str:
"""
>>> size(1024)
'1 KB'
"""
suffixes = suffixes or [
'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
order = int(log2(value) / 10) if value else 0
return '{:.4g} {}'.format(value / (1 << (order * 10)), suffixes[order]) | [
"def",
"size",
"(",
"value",
":",
"int",
",",
"suffixes",
":",
"list",
"=",
"None",
")",
"->",
"str",
":",
"suffixes",
"=",
"suffixes",
"or",
"[",
"'bytes'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
",",
"'PB'",
",",
"'EB'",
",",
"'ZB'... | >>> size(1024)
'1 KB' | [
">>>",
"size",
"(",
"1024",
")",
"1",
"KB"
] | train | https://github.com/aioworkers/aioworkers/blob/94caa5584a75bae1cee6c8c7a24667bff9cefa90/aioworkers/humanize.py#L5-L13 |
aioworkers/aioworkers | aioworkers/humanize.py | parse_size | def parse_size(value):
"""
>>> parse_size('1M')
1048576
>>> parse_size('512K512K')
1048576
>>> parse_size('512K 512K')
1048576
>>> parse_size('512K 512K 4')
1048580
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
... | python | def parse_size(value):
"""
>>> parse_size('1M')
1048576
>>> parse_size('512K512K')
1048576
>>> parse_size('512K 512K')
1048576
>>> parse_size('512K 512K 4')
1048580
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
... | [
"def",
"parse_size",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"value",
"elif",
"not",
"pattern_valid",
".",
"fullmatch",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"value... | >>> parse_size('1M')
1048576
>>> parse_size('512K512K')
1048576
>>> parse_size('512K 512K')
1048576
>>> parse_size('512K 512K 4')
1048580 | [
">>>",
"parse_size",
"(",
"1M",
")",
"1048576",
">>>",
"parse_size",
"(",
"512K512K",
")",
"1048576",
">>>",
"parse_size",
"(",
"512K",
"512K",
")",
"1048576",
">>>",
"parse_size",
"(",
"512K",
"512K",
"4",
")",
"1048580"
] | train | https://github.com/aioworkers/aioworkers/blob/94caa5584a75bae1cee6c8c7a24667bff9cefa90/aioworkers/humanize.py#L29-L56 |
aioworkers/aioworkers | aioworkers/humanize.py | parse_duration | def parse_duration(value):
"""
>>> parse_duration('1h')
3600
>>> parse_duration('1m')
60
>>> parse_duration('1m 2s')
62
>>> parse_duration('1')
1
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
raise ValueErro... | python | def parse_duration(value):
"""
>>> parse_duration('1h')
3600
>>> parse_duration('1m')
60
>>> parse_duration('1m 2s')
62
>>> parse_duration('1')
1
"""
if isinstance(value, (int, float)):
return value
elif not pattern_valid.fullmatch(value):
raise ValueErro... | [
"def",
"parse_duration",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"value",
"elif",
"not",
"pattern_valid",
".",
"fullmatch",
"(",
"value",
")",
":",
"raise",
"ValueError",
"(",
"v... | >>> parse_duration('1h')
3600
>>> parse_duration('1m')
60
>>> parse_duration('1m 2s')
62
>>> parse_duration('1')
1 | [
">>>",
"parse_duration",
"(",
"1h",
")",
"3600",
">>>",
"parse_duration",
"(",
"1m",
")",
"60",
">>>",
"parse_duration",
"(",
"1m",
"2s",
")",
"62",
">>>",
"parse_duration",
"(",
"1",
")",
"1"
] | train | https://github.com/aioworkers/aioworkers/blob/94caa5584a75bae1cee6c8c7a24667bff9cefa90/aioworkers/humanize.py#L68-L96 |
IBM/pyxcli | pyxcli/events/events.py | EventsManager.send_event | def send_event(self, action, properties, event_severity=EVENT_SEVERITY):
"""
send css_event and if fails send custom_event instead
Args:
action (ACTIONS): the action causing the event
properties (dict): the action additional properties
event_severity (string):... | python | def send_event(self, action, properties, event_severity=EVENT_SEVERITY):
"""
send css_event and if fails send custom_event instead
Args:
action (ACTIONS): the action causing the event
properties (dict): the action additional properties
event_severity (string):... | [
"def",
"send_event",
"(",
"self",
",",
"action",
",",
"properties",
",",
"event_severity",
"=",
"EVENT_SEVERITY",
")",
":",
"# verify properties",
"event_properties",
"=",
"dict",
"(",
")",
"if",
"(",
"properties",
"is",
"None",
")",
"else",
"properties",
"if"... | send css_event and if fails send custom_event instead
Args:
action (ACTIONS): the action causing the event
properties (dict): the action additional properties
event_severity (string): the event severity
Raises:
XCLIError: if the xcli.cmd.custom_event faile... | [
"send",
"css_event",
"and",
"if",
"fails",
"send",
"custom_event",
"instead",
"Args",
":",
"action",
"(",
"ACTIONS",
")",
":",
"the",
"action",
"causing",
"the",
"event",
"properties",
"(",
"dict",
")",
":",
"the",
"action",
"additional",
"properties",
"even... | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/events/events.py#L71-L124 |
IBM/pyxcli | pyxcli/mirroring/recovery_manager.py | RecoveryManager._create_mirror | def _create_mirror(self, resource_type, resource_name, target_name,
mirror_type, slave_resource_name, create_slave='no',
remote_pool=None, rpo=None, remote_rpo=None,
schedule=None, remote_schedule=None,
activate_mirror='no')... | python | def _create_mirror(self, resource_type, resource_name, target_name,
mirror_type, slave_resource_name, create_slave='no',
remote_pool=None, rpo=None, remote_rpo=None,
schedule=None, remote_schedule=None,
activate_mirror='no')... | [
"def",
"_create_mirror",
"(",
"self",
",",
"resource_type",
",",
"resource_name",
",",
"target_name",
",",
"mirror_type",
",",
"slave_resource_name",
",",
"create_slave",
"=",
"'no'",
",",
"remote_pool",
"=",
"None",
",",
"rpo",
"=",
"None",
",",
"remote_rpo",
... | creates a mirror and returns a mirror object.
resource_type must be 'vol' or 'cg',
target name must be a valid target from target_list,
mirror type must be 'sync' or 'async',
slave_resource_name would be the slave_vol or slave_cg name | [
"creates",
"a",
"mirror",
"and",
"returns",
"a",
"mirror",
"object",
".",
"resource_type",
"must",
"be",
"vol",
"or",
"cg",
"target",
"name",
"must",
"be",
"a",
"valid",
"target",
"from",
"target_list",
"mirror",
"type",
"must",
"be",
"sync",
"or",
"async"... | train | https://github.com/IBM/pyxcli/blob/7d8ece1dcc16f50246740a447aa81b94a0dbced4/pyxcli/mirroring/recovery_manager.py#L273-L319 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.