repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
jedie/PyHardLinkBackup
PyHardLinkBackup/phlb/filesystem_walk.py
iter_filtered_dir_entry
def iter_filtered_dir_entry(dir_entries, match_patterns, on_skip): """ Filter a list of DirEntryPath instances with the given pattern :param dir_entries: list of DirEntryPath instances :param match_patterns: used with Path.match() e.g.: "__pycache__/*", "*.tmp", "*.cache" :param on_skip: function that will be called if 'match_patterns' hits. e.g.: def on_skip(entry, pattern): log.error("Skip pattern %r hit: %s" % (pattern, entry.path)) :return: yields None or DirEntryPath instances """ def match(dir_entry_path, match_patterns, on_skip): for match_pattern in match_patterns: if dir_entry_path.path_instance.match(match_pattern): on_skip(dir_entry_path, match_pattern) return True return False for entry in dir_entries: try: dir_entry_path = DirEntryPath(entry) except FileNotFoundError as err: # e.g.: A file was deleted after the first filesystem scan # Will be obsolete if we use shadow-copy / snapshot function from filesystem # see: https://github.com/jedie/PyHardLinkBackup/issues/6 log.error("Can't make DirEntryPath() instance: %s" % err) continue if match(dir_entry_path, match_patterns, on_skip): yield None else: yield dir_entry_path
python
def iter_filtered_dir_entry(dir_entries, match_patterns, on_skip): """ Filter a list of DirEntryPath instances with the given pattern :param dir_entries: list of DirEntryPath instances :param match_patterns: used with Path.match() e.g.: "__pycache__/*", "*.tmp", "*.cache" :param on_skip: function that will be called if 'match_patterns' hits. e.g.: def on_skip(entry, pattern): log.error("Skip pattern %r hit: %s" % (pattern, entry.path)) :return: yields None or DirEntryPath instances """ def match(dir_entry_path, match_patterns, on_skip): for match_pattern in match_patterns: if dir_entry_path.path_instance.match(match_pattern): on_skip(dir_entry_path, match_pattern) return True return False for entry in dir_entries: try: dir_entry_path = DirEntryPath(entry) except FileNotFoundError as err: # e.g.: A file was deleted after the first filesystem scan # Will be obsolete if we use shadow-copy / snapshot function from filesystem # see: https://github.com/jedie/PyHardLinkBackup/issues/6 log.error("Can't make DirEntryPath() instance: %s" % err) continue if match(dir_entry_path, match_patterns, on_skip): yield None else: yield dir_entry_path
[ "def", "iter_filtered_dir_entry", "(", "dir_entries", ",", "match_patterns", ",", "on_skip", ")", ":", "def", "match", "(", "dir_entry_path", ",", "match_patterns", ",", "on_skip", ")", ":", "for", "match_pattern", "in", "match_patterns", ":", "if", "dir_entry_path", ".", "path_instance", ".", "match", "(", "match_pattern", ")", ":", "on_skip", "(", "dir_entry_path", ",", "match_pattern", ")", "return", "True", "return", "False", "for", "entry", "in", "dir_entries", ":", "try", ":", "dir_entry_path", "=", "DirEntryPath", "(", "entry", ")", "except", "FileNotFoundError", "as", "err", ":", "# e.g.: A file was deleted after the first filesystem scan", "# Will be obsolete if we use shadow-copy / snapshot function from filesystem", "# see: https://github.com/jedie/PyHardLinkBackup/issues/6", "log", ".", "error", "(", "\"Can't make DirEntryPath() instance: %s\"", "%", "err", ")", "continue", "if", "match", "(", "dir_entry_path", ",", "match_patterns", ",", "on_skip", ")", ":", "yield", "None", "else", ":", "yield", "dir_entry_path" ]
Filter a list of DirEntryPath instances with the given pattern :param dir_entries: list of DirEntryPath instances :param match_patterns: used with Path.match() e.g.: "__pycache__/*", "*.tmp", "*.cache" :param on_skip: function that will be called if 'match_patterns' hits. e.g.: def on_skip(entry, pattern): log.error("Skip pattern %r hit: %s" % (pattern, entry.path)) :return: yields None or DirEntryPath instances
[ "Filter", "a", "list", "of", "DirEntryPath", "instances", "with", "the", "given", "pattern" ]
be28666834d2d9e3d8aac1b661cb2d5bd4056c29
https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/filesystem_walk.py#L85-L118
train
Capitains/MyCapytain
MyCapytain/common/utils/_http.py
parse_pagination
def parse_pagination(headers): """ Parses headers to create a pagination objects :param headers: HTTP Headers :type headers: dict :return: Navigation object for pagination :rtype: _Navigation """ links = { link.rel: parse_qs(link.href).get("page", None) for link in link_header.parse(headers.get("Link", "")).links } return _Navigation( links.get("previous", [None])[0], links.get("next", [None])[0], links.get("last", [None])[0], links.get("current", [None])[0], links.get("first", [None])[0] )
python
def parse_pagination(headers): """ Parses headers to create a pagination objects :param headers: HTTP Headers :type headers: dict :return: Navigation object for pagination :rtype: _Navigation """ links = { link.rel: parse_qs(link.href).get("page", None) for link in link_header.parse(headers.get("Link", "")).links } return _Navigation( links.get("previous", [None])[0], links.get("next", [None])[0], links.get("last", [None])[0], links.get("current", [None])[0], links.get("first", [None])[0] )
[ "def", "parse_pagination", "(", "headers", ")", ":", "links", "=", "{", "link", ".", "rel", ":", "parse_qs", "(", "link", ".", "href", ")", ".", "get", "(", "\"page\"", ",", "None", ")", "for", "link", "in", "link_header", ".", "parse", "(", "headers", ".", "get", "(", "\"Link\"", ",", "\"\"", ")", ")", ".", "links", "}", "return", "_Navigation", "(", "links", ".", "get", "(", "\"previous\"", ",", "[", "None", "]", ")", "[", "0", "]", ",", "links", ".", "get", "(", "\"next\"", ",", "[", "None", "]", ")", "[", "0", "]", ",", "links", ".", "get", "(", "\"last\"", ",", "[", "None", "]", ")", "[", "0", "]", ",", "links", ".", "get", "(", "\"current\"", ",", "[", "None", "]", ")", "[", "0", "]", ",", "links", ".", "get", "(", "\"first\"", ",", "[", "None", "]", ")", "[", "0", "]", ")" ]
Parses headers to create a pagination objects :param headers: HTTP Headers :type headers: dict :return: Navigation object for pagination :rtype: _Navigation
[ "Parses", "headers", "to", "create", "a", "pagination", "objects" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_http.py#L10-L28
train
Capitains/MyCapytain
MyCapytain/common/utils/_http.py
parse_uri
def parse_uri(uri, endpoint_uri): """ Parse a URI into a Route namedtuple :param uri: URI or relative URI :type uri: str :param endpoint_uri: URI of the endpoint :type endpoint_uri: str :return: Parsed route :rtype: _Route """ temp_parse = urlparse(uri) return _Route( urljoin(endpoint_uri, temp_parse.path), parse_qs(temp_parse.query) )
python
def parse_uri(uri, endpoint_uri): """ Parse a URI into a Route namedtuple :param uri: URI or relative URI :type uri: str :param endpoint_uri: URI of the endpoint :type endpoint_uri: str :return: Parsed route :rtype: _Route """ temp_parse = urlparse(uri) return _Route( urljoin(endpoint_uri, temp_parse.path), parse_qs(temp_parse.query) )
[ "def", "parse_uri", "(", "uri", ",", "endpoint_uri", ")", ":", "temp_parse", "=", "urlparse", "(", "uri", ")", "return", "_Route", "(", "urljoin", "(", "endpoint_uri", ",", "temp_parse", ".", "path", ")", ",", "parse_qs", "(", "temp_parse", ".", "query", ")", ")" ]
Parse a URI into a Route namedtuple :param uri: URI or relative URI :type uri: str :param endpoint_uri: URI of the endpoint :type endpoint_uri: str :return: Parsed route :rtype: _Route
[ "Parse", "a", "URI", "into", "a", "Route", "namedtuple" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/_http.py#L31-L45
train
etingof/pysnmpcrypto
pysnmpcrypto/aes.py
_cryptodome_cipher
def _cryptodome_cipher(key, iv): """Build a Pycryptodome AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance """ return AES.new(key, AES.MODE_CFB, iv, segment_size=128)
python
def _cryptodome_cipher(key, iv): """Build a Pycryptodome AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance """ return AES.new(key, AES.MODE_CFB, iv, segment_size=128)
[ "def", "_cryptodome_cipher", "(", "key", ",", "iv", ")", ":", "return", "AES", ".", "new", "(", "key", ",", "AES", ".", "MODE_CFB", ",", "iv", ",", "segment_size", "=", "128", ")" ]
Build a Pycryptodome AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance
[ "Build", "a", "Pycryptodome", "AES", "Cipher", "object", "." ]
9b92959f5e2fce833fa220343ca12add3134a77c
https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/aes.py#L17-L24
train
etingof/pysnmpcrypto
pysnmpcrypto/aes.py
_cryptography_cipher
def _cryptography_cipher(key, iv): """Build a cryptography AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance :rtype: cryptography.hazmat.primitives.ciphers.Cipher """ return Cipher( algorithm=algorithms.AES(key), mode=modes.CFB(iv), backend=default_backend() )
python
def _cryptography_cipher(key, iv): """Build a cryptography AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance :rtype: cryptography.hazmat.primitives.ciphers.Cipher """ return Cipher( algorithm=algorithms.AES(key), mode=modes.CFB(iv), backend=default_backend() )
[ "def", "_cryptography_cipher", "(", "key", ",", "iv", ")", ":", "return", "Cipher", "(", "algorithm", "=", "algorithms", ".", "AES", "(", "key", ")", ",", "mode", "=", "modes", ".", "CFB", "(", "iv", ")", ",", "backend", "=", "default_backend", "(", ")", ")" ]
Build a cryptography AES Cipher object. :param bytes key: Encryption key :param bytes iv: Initialization vector :returns: AES Cipher instance :rtype: cryptography.hazmat.primitives.ciphers.Cipher
[ "Build", "a", "cryptography", "AES", "Cipher", "object", "." ]
9b92959f5e2fce833fa220343ca12add3134a77c
https://github.com/etingof/pysnmpcrypto/blob/9b92959f5e2fce833fa220343ca12add3134a77c/pysnmpcrypto/aes.py#L27-L39
train
Capitains/MyCapytain
MyCapytain/common/utils/xml.py
make_xml_node
def make_xml_node(graph, name, close=False, attributes=None, text="", complete=False, innerXML=""): """ Create an XML Node :param graph: Graph used to geneates prefixes :param name: Name of the tag :param close: Produce closing tag (close=False -> "<tag>", close=True -> "</tag>") :param attributes: Dictionary of attributes :param text: CapitainsCtsText to put inside the node :param complete: Complete node (node with opening and closing tag) :param innerXML: XML to append to the node :return: String representation of the node :rtype: str """ name = graph.namespace_manager.qname(name) if complete: if attributes is not None: return "<{0} {1}>{2}{3}</{0}>".format( name, " ".join( [ "{}=\"{}\"".format(attr_name, attr_value) for attr_name, attr_value in attributes.items() ] ), escape(text), innerXML ) return "<{0}>{1}{2}</{0}>".format(name, escape(text), innerXML) elif close is True: return "</{}>".format(name) elif attributes is not None: return "<{} {}>".format( name, " ".join( [ "{}=\"{}\"".format(attr_name, attr_value) for attr_name, attr_value in attributes.items() ] ) ) return "<{}>".format(name)
python
def make_xml_node(graph, name, close=False, attributes=None, text="", complete=False, innerXML=""): """ Create an XML Node :param graph: Graph used to geneates prefixes :param name: Name of the tag :param close: Produce closing tag (close=False -> "<tag>", close=True -> "</tag>") :param attributes: Dictionary of attributes :param text: CapitainsCtsText to put inside the node :param complete: Complete node (node with opening and closing tag) :param innerXML: XML to append to the node :return: String representation of the node :rtype: str """ name = graph.namespace_manager.qname(name) if complete: if attributes is not None: return "<{0} {1}>{2}{3}</{0}>".format( name, " ".join( [ "{}=\"{}\"".format(attr_name, attr_value) for attr_name, attr_value in attributes.items() ] ), escape(text), innerXML ) return "<{0}>{1}{2}</{0}>".format(name, escape(text), innerXML) elif close is True: return "</{}>".format(name) elif attributes is not None: return "<{} {}>".format( name, " ".join( [ "{}=\"{}\"".format(attr_name, attr_value) for attr_name, attr_value in attributes.items() ] ) ) return "<{}>".format(name)
[ "def", "make_xml_node", "(", "graph", ",", "name", ",", "close", "=", "False", ",", "attributes", "=", "None", ",", "text", "=", "\"\"", ",", "complete", "=", "False", ",", "innerXML", "=", "\"\"", ")", ":", "name", "=", "graph", ".", "namespace_manager", ".", "qname", "(", "name", ")", "if", "complete", ":", "if", "attributes", "is", "not", "None", ":", "return", "\"<{0} {1}>{2}{3}</{0}>\"", ".", "format", "(", "name", ",", "\" \"", ".", "join", "(", "[", "\"{}=\\\"{}\\\"\"", ".", "format", "(", "attr_name", ",", "attr_value", ")", "for", "attr_name", ",", "attr_value", "in", "attributes", ".", "items", "(", ")", "]", ")", ",", "escape", "(", "text", ")", ",", "innerXML", ")", "return", "\"<{0}>{1}{2}</{0}>\"", ".", "format", "(", "name", ",", "escape", "(", "text", ")", ",", "innerXML", ")", "elif", "close", "is", "True", ":", "return", "\"</{}>\"", ".", "format", "(", "name", ")", "elif", "attributes", "is", "not", "None", ":", "return", "\"<{} {}>\"", ".", "format", "(", "name", ",", "\" \"", ".", "join", "(", "[", "\"{}=\\\"{}\\\"\"", ".", "format", "(", "attr_name", ",", "attr_value", ")", "for", "attr_name", ",", "attr_value", "in", "attributes", ".", "items", "(", ")", "]", ")", ")", "return", "\"<{}>\"", ".", "format", "(", "name", ")" ]
Create an XML Node :param graph: Graph used to geneates prefixes :param name: Name of the tag :param close: Produce closing tag (close=False -> "<tag>", close=True -> "</tag>") :param attributes: Dictionary of attributes :param text: CapitainsCtsText to put inside the node :param complete: Complete node (node with opening and closing tag) :param innerXML: XML to append to the node :return: String representation of the node :rtype: str
[ "Create", "an", "XML", "Node" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/xml.py#L27-L67
train
Capitains/MyCapytain
MyCapytain/common/utils/xml.py
performXpath
def performXpath(parent, xpath): """ Perform an XPath on an element and indicate if we need to loop over it to find something :param parent: XML Node on which to perform XPath :param xpath: XPath to run :return: (Result, Need to loop Indicator) """ loop = False if xpath.startswith(".//"): result = parent.xpath( xpath.replace(".//", "./", 1), namespaces=XPATH_NAMESPACES ) if len(result) == 0: result = parent.xpath( "*[{}]".format(xpath), namespaces=XPATH_NAMESPACES ) loop = True else: result = parent.xpath( xpath, namespaces=XPATH_NAMESPACES ) return result[0], loop
python
def performXpath(parent, xpath): """ Perform an XPath on an element and indicate if we need to loop over it to find something :param parent: XML Node on which to perform XPath :param xpath: XPath to run :return: (Result, Need to loop Indicator) """ loop = False if xpath.startswith(".//"): result = parent.xpath( xpath.replace(".//", "./", 1), namespaces=XPATH_NAMESPACES ) if len(result) == 0: result = parent.xpath( "*[{}]".format(xpath), namespaces=XPATH_NAMESPACES ) loop = True else: result = parent.xpath( xpath, namespaces=XPATH_NAMESPACES ) return result[0], loop
[ "def", "performXpath", "(", "parent", ",", "xpath", ")", ":", "loop", "=", "False", "if", "xpath", ".", "startswith", "(", "\".//\"", ")", ":", "result", "=", "parent", ".", "xpath", "(", "xpath", ".", "replace", "(", "\".//\"", ",", "\"./\"", ",", "1", ")", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "if", "len", "(", "result", ")", "==", "0", ":", "result", "=", "parent", ".", "xpath", "(", "\"*[{}]\"", ".", "format", "(", "xpath", ")", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "loop", "=", "True", "else", ":", "result", "=", "parent", ".", "xpath", "(", "xpath", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "return", "result", "[", "0", "]", ",", "loop" ]
Perform an XPath on an element and indicate if we need to loop over it to find something :param parent: XML Node on which to perform XPath :param xpath: XPath to run :return: (Result, Need to loop Indicator)
[ "Perform", "an", "XPath", "on", "an", "element", "and", "indicate", "if", "we", "need", "to", "loop", "over", "it", "to", "find", "something" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/xml.py#L129-L153
train
Capitains/MyCapytain
MyCapytain/common/utils/xml.py
copyNode
def copyNode(node, children=False, parent=False): """ Copy an XML Node :param node: Etree Node :param children: Copy children nodes is set to True :param parent: Append copied node to parent if given :return: New Element """ if parent is not False: element = SubElement( parent, node.tag, attrib=node.attrib, nsmap={None: "http://www.tei-c.org/ns/1.0"} ) else: element = Element( node.tag, attrib=node.attrib, nsmap={None: "http://www.tei-c.org/ns/1.0"} ) if children: if node.text: element._setText(node.text) for child in xmliter(node): element.append(copy(child)) return element
python
def copyNode(node, children=False, parent=False): """ Copy an XML Node :param node: Etree Node :param children: Copy children nodes is set to True :param parent: Append copied node to parent if given :return: New Element """ if parent is not False: element = SubElement( parent, node.tag, attrib=node.attrib, nsmap={None: "http://www.tei-c.org/ns/1.0"} ) else: element = Element( node.tag, attrib=node.attrib, nsmap={None: "http://www.tei-c.org/ns/1.0"} ) if children: if node.text: element._setText(node.text) for child in xmliter(node): element.append(copy(child)) return element
[ "def", "copyNode", "(", "node", ",", "children", "=", "False", ",", "parent", "=", "False", ")", ":", "if", "parent", "is", "not", "False", ":", "element", "=", "SubElement", "(", "parent", ",", "node", ".", "tag", ",", "attrib", "=", "node", ".", "attrib", ",", "nsmap", "=", "{", "None", ":", "\"http://www.tei-c.org/ns/1.0\"", "}", ")", "else", ":", "element", "=", "Element", "(", "node", ".", "tag", ",", "attrib", "=", "node", ".", "attrib", ",", "nsmap", "=", "{", "None", ":", "\"http://www.tei-c.org/ns/1.0\"", "}", ")", "if", "children", ":", "if", "node", ".", "text", ":", "element", ".", "_setText", "(", "node", ".", "text", ")", "for", "child", "in", "xmliter", "(", "node", ")", ":", "element", ".", "append", "(", "copy", "(", "child", ")", ")", "return", "element" ]
Copy an XML Node :param node: Etree Node :param children: Copy children nodes is set to True :param parent: Append copied node to parent if given :return: New Element
[ "Copy", "an", "XML", "Node" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/xml.py#L156-L182
train
Capitains/MyCapytain
MyCapytain/common/utils/xml.py
normalizeXpath
def normalizeXpath(xpath): """ Normalize XPATH split around slashes :param xpath: List of xpath elements :type xpath: [str] :return: List of refined xpath :rtype: [str] """ new_xpath = [] for x in range(0, len(xpath)): if x > 0 and len(xpath[x-1]) == 0: new_xpath.append("/"+xpath[x]) elif len(xpath[x]) > 0: new_xpath.append(xpath[x]) return new_xpath
python
def normalizeXpath(xpath): """ Normalize XPATH split around slashes :param xpath: List of xpath elements :type xpath: [str] :return: List of refined xpath :rtype: [str] """ new_xpath = [] for x in range(0, len(xpath)): if x > 0 and len(xpath[x-1]) == 0: new_xpath.append("/"+xpath[x]) elif len(xpath[x]) > 0: new_xpath.append(xpath[x]) return new_xpath
[ "def", "normalizeXpath", "(", "xpath", ")", ":", "new_xpath", "=", "[", "]", "for", "x", "in", "range", "(", "0", ",", "len", "(", "xpath", ")", ")", ":", "if", "x", ">", "0", "and", "len", "(", "xpath", "[", "x", "-", "1", "]", ")", "==", "0", ":", "new_xpath", ".", "append", "(", "\"/\"", "+", "xpath", "[", "x", "]", ")", "elif", "len", "(", "xpath", "[", "x", "]", ")", ">", "0", ":", "new_xpath", ".", "append", "(", "xpath", "[", "x", "]", ")", "return", "new_xpath" ]
Normalize XPATH split around slashes :param xpath: List of xpath elements :type xpath: [str] :return: List of refined xpath :rtype: [str]
[ "Normalize", "XPATH", "split", "around", "slashes" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/xml.py#L185-L199
train
Capitains/MyCapytain
MyCapytain/common/utils/xml.py
passageLoop
def passageLoop(parent, new_tree, xpath1, xpath2=None, preceding_siblings=False, following_siblings=False): """ Loop over passages to construct and increment new tree given a parent and XPaths :param parent: Parent on which to perform xpath :param new_tree: Parent on which to add nodes :param xpath1: List of xpath elements :type xpath1: [str] :param xpath2: List of xpath elements :type xpath2: [str] :param preceding_siblings: Append preceding siblings of XPath 1/2 match to the tree :param following_siblings: Append following siblings of XPath 1/2 match to the tree :return: Newly incremented tree """ current_1, queue_1 = __formatXpath__(xpath1) if xpath2 is None: # In case we need what is following or preceding our node result_1, loop = performXpath(parent, current_1) if loop is True: queue_1 = xpath1 central = None has_no_queue = len(queue_1) == 0 # For each sibling, when we need them in the context of a range if preceding_siblings or following_siblings: for sibling in xmliter(parent): if sibling == result_1: central = True # We copy the node we looked for (Result_1) child = copyNode(result_1, children=has_no_queue, parent=new_tree) # if we don't have children # we loop over the passage child if not has_no_queue: passageLoop( result_1, child, queue_1, None, preceding_siblings=preceding_siblings, following_siblings=following_siblings ) # If we were waiting for preceding_siblings, we break it off # As we don't need to go further if preceding_siblings: break elif not central and preceding_siblings: copyNode(sibling, parent=new_tree, children=True) elif central and following_siblings: copyNode(sibling, parent=new_tree, children=True) else: result_1, loop = performXpath(parent, current_1) if loop is True: queue_1 = xpath1 if xpath2 == xpath1: current_2, queue_2 = current_1, queue_1 else: current_2, queue_2 = __formatXpath__(xpath2) else: current_2, queue_2 = __formatXpath__(xpath2) if xpath1 != xpath2: result_2, loop = performXpath(parent, current_2) if loop is True: queue_2 = xpath2 else: result_2 = result_1 if result_1 == result_2: has_no_queue = len(queue_1) == 0 child = copyNode(result_1, children=has_no_queue, parent=new_tree) if not has_no_queue: passageLoop( result_1, child, queue_1, queue_2 ) else: start = False # For each sibling for sibling in xmliter(parent): # If we have found start # We copy the node because we are between start and end if start: # If we are at the end # We break the copy if sibling == result_2: break else: copyNode(sibling, parent=new_tree, children=True) # If this is start # Then we copy it and initiate star elif sibling == result_1: start = True has_no_queue_1 = len(queue_1) == 0 node = copyNode(sibling, children=has_no_queue_1, parent=new_tree) if not has_no_queue_1: passageLoop(sibling, node, queue_1, None, following_siblings=True) continue_loop = len(queue_2) == 0 node = copyNode(result_2, children=continue_loop, parent=new_tree) if not continue_loop: passageLoop(result_2, node, queue_2, None, preceding_siblings=True) return new_tree
python
def passageLoop(parent, new_tree, xpath1, xpath2=None, preceding_siblings=False, following_siblings=False): """ Loop over passages to construct and increment new tree given a parent and XPaths :param parent: Parent on which to perform xpath :param new_tree: Parent on which to add nodes :param xpath1: List of xpath elements :type xpath1: [str] :param xpath2: List of xpath elements :type xpath2: [str] :param preceding_siblings: Append preceding siblings of XPath 1/2 match to the tree :param following_siblings: Append following siblings of XPath 1/2 match to the tree :return: Newly incremented tree """ current_1, queue_1 = __formatXpath__(xpath1) if xpath2 is None: # In case we need what is following or preceding our node result_1, loop = performXpath(parent, current_1) if loop is True: queue_1 = xpath1 central = None has_no_queue = len(queue_1) == 0 # For each sibling, when we need them in the context of a range if preceding_siblings or following_siblings: for sibling in xmliter(parent): if sibling == result_1: central = True # We copy the node we looked for (Result_1) child = copyNode(result_1, children=has_no_queue, parent=new_tree) # if we don't have children # we loop over the passage child if not has_no_queue: passageLoop( result_1, child, queue_1, None, preceding_siblings=preceding_siblings, following_siblings=following_siblings ) # If we were waiting for preceding_siblings, we break it off # As we don't need to go further if preceding_siblings: break elif not central and preceding_siblings: copyNode(sibling, parent=new_tree, children=True) elif central and following_siblings: copyNode(sibling, parent=new_tree, children=True) else: result_1, loop = performXpath(parent, current_1) if loop is True: queue_1 = xpath1 if xpath2 == xpath1: current_2, queue_2 = current_1, queue_1 else: current_2, queue_2 = __formatXpath__(xpath2) else: current_2, queue_2 = __formatXpath__(xpath2) if xpath1 != xpath2: result_2, loop = performXpath(parent, current_2) if loop is True: queue_2 = xpath2 else: result_2 = result_1 if result_1 == result_2: has_no_queue = len(queue_1) == 0 child = copyNode(result_1, children=has_no_queue, parent=new_tree) if not has_no_queue: passageLoop( result_1, child, queue_1, queue_2 ) else: start = False # For each sibling for sibling in xmliter(parent): # If we have found start # We copy the node because we are between start and end if start: # If we are at the end # We break the copy if sibling == result_2: break else: copyNode(sibling, parent=new_tree, children=True) # If this is start # Then we copy it and initiate star elif sibling == result_1: start = True has_no_queue_1 = len(queue_1) == 0 node = copyNode(sibling, children=has_no_queue_1, parent=new_tree) if not has_no_queue_1: passageLoop(sibling, node, queue_1, None, following_siblings=True) continue_loop = len(queue_2) == 0 node = copyNode(result_2, children=continue_loop, parent=new_tree) if not continue_loop: passageLoop(result_2, node, queue_2, None, preceding_siblings=True) return new_tree
[ "def", "passageLoop", "(", "parent", ",", "new_tree", ",", "xpath1", ",", "xpath2", "=", "None", ",", "preceding_siblings", "=", "False", ",", "following_siblings", "=", "False", ")", ":", "current_1", ",", "queue_1", "=", "__formatXpath__", "(", "xpath1", ")", "if", "xpath2", "is", "None", ":", "# In case we need what is following or preceding our node", "result_1", ",", "loop", "=", "performXpath", "(", "parent", ",", "current_1", ")", "if", "loop", "is", "True", ":", "queue_1", "=", "xpath1", "central", "=", "None", "has_no_queue", "=", "len", "(", "queue_1", ")", "==", "0", "# For each sibling, when we need them in the context of a range", "if", "preceding_siblings", "or", "following_siblings", ":", "for", "sibling", "in", "xmliter", "(", "parent", ")", ":", "if", "sibling", "==", "result_1", ":", "central", "=", "True", "# We copy the node we looked for (Result_1)", "child", "=", "copyNode", "(", "result_1", ",", "children", "=", "has_no_queue", ",", "parent", "=", "new_tree", ")", "# if we don't have children", "# we loop over the passage child", "if", "not", "has_no_queue", ":", "passageLoop", "(", "result_1", ",", "child", ",", "queue_1", ",", "None", ",", "preceding_siblings", "=", "preceding_siblings", ",", "following_siblings", "=", "following_siblings", ")", "# If we were waiting for preceding_siblings, we break it off", "# As we don't need to go further", "if", "preceding_siblings", ":", "break", "elif", "not", "central", "and", "preceding_siblings", ":", "copyNode", "(", "sibling", ",", "parent", "=", "new_tree", ",", "children", "=", "True", ")", "elif", "central", "and", "following_siblings", ":", "copyNode", "(", "sibling", ",", "parent", "=", "new_tree", ",", "children", "=", "True", ")", "else", ":", "result_1", ",", "loop", "=", "performXpath", "(", "parent", ",", "current_1", ")", "if", "loop", "is", "True", ":", "queue_1", "=", "xpath1", "if", "xpath2", "==", "xpath1", ":", "current_2", ",", "queue_2", "=", "current_1", ",", "queue_1", "else", ":", "current_2", ",", "queue_2", "=", "__formatXpath__", "(", "xpath2", ")", "else", ":", "current_2", ",", "queue_2", "=", "__formatXpath__", "(", "xpath2", ")", "if", "xpath1", "!=", "xpath2", ":", "result_2", ",", "loop", "=", "performXpath", "(", "parent", ",", "current_2", ")", "if", "loop", "is", "True", ":", "queue_2", "=", "xpath2", "else", ":", "result_2", "=", "result_1", "if", "result_1", "==", "result_2", ":", "has_no_queue", "=", "len", "(", "queue_1", ")", "==", "0", "child", "=", "copyNode", "(", "result_1", ",", "children", "=", "has_no_queue", ",", "parent", "=", "new_tree", ")", "if", "not", "has_no_queue", ":", "passageLoop", "(", "result_1", ",", "child", ",", "queue_1", ",", "queue_2", ")", "else", ":", "start", "=", "False", "# For each sibling", "for", "sibling", "in", "xmliter", "(", "parent", ")", ":", "# If we have found start", "# We copy the node because we are between start and end", "if", "start", ":", "# If we are at the end", "# We break the copy", "if", "sibling", "==", "result_2", ":", "break", "else", ":", "copyNode", "(", "sibling", ",", "parent", "=", "new_tree", ",", "children", "=", "True", ")", "# If this is start", "# Then we copy it and initiate star", "elif", "sibling", "==", "result_1", ":", "start", "=", "True", "has_no_queue_1", "=", "len", "(", "queue_1", ")", "==", "0", "node", "=", "copyNode", "(", "sibling", ",", "children", "=", "has_no_queue_1", ",", "parent", "=", "new_tree", ")", "if", "not", "has_no_queue_1", ":", "passageLoop", "(", "sibling", ",", "node", ",", "queue_1", ",", "None", ",", "following_siblings", "=", "True", ")", "continue_loop", "=", "len", "(", "queue_2", ")", "==", "0", "node", "=", "copyNode", "(", "result_2", ",", "children", "=", "continue_loop", ",", "parent", "=", "new_tree", ")", "if", "not", "continue_loop", ":", "passageLoop", "(", "result_2", ",", "node", ",", "queue_2", ",", "None", ",", "preceding_siblings", "=", "True", ")", "return", "new_tree" ]
Loop over passages to construct and increment new tree given a parent and XPaths :param parent: Parent on which to perform xpath :param new_tree: Parent on which to add nodes :param xpath1: List of xpath elements :type xpath1: [str] :param xpath2: List of xpath elements :type xpath2: [str] :param preceding_siblings: Append preceding siblings of XPath 1/2 match to the tree :param following_siblings: Append following siblings of XPath 1/2 match to the tree :return: Newly incremented tree
[ "Loop", "over", "passages", "to", "construct", "and", "increment", "new", "tree", "given", "a", "parent", "and", "XPaths" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/utils/xml.py#L202-L304
train
Capitains/MyCapytain
MyCapytain/resources/prototypes/metadata.py
Collection.get_label
def get_label(self, lang=None): """ Return label for given lang or any default :param lang: Language to request :return: Label value :rtype: Literal """ x = None if lang is None: for obj in self.graph.objects(self.asNode(), RDFS.label): return obj for obj in self.graph.objects(self.asNode(), RDFS.label): x = obj if x.language == lang: return x return x
python
def get_label(self, lang=None): """ Return label for given lang or any default :param lang: Language to request :return: Label value :rtype: Literal """ x = None if lang is None: for obj in self.graph.objects(self.asNode(), RDFS.label): return obj for obj in self.graph.objects(self.asNode(), RDFS.label): x = obj if x.language == lang: return x return x
[ "def", "get_label", "(", "self", ",", "lang", "=", "None", ")", ":", "x", "=", "None", "if", "lang", "is", "None", ":", "for", "obj", "in", "self", ".", "graph", ".", "objects", "(", "self", ".", "asNode", "(", ")", ",", "RDFS", ".", "label", ")", ":", "return", "obj", "for", "obj", "in", "self", ".", "graph", ".", "objects", "(", "self", ".", "asNode", "(", ")", ",", "RDFS", ".", "label", ")", ":", "x", "=", "obj", "if", "x", ".", "language", "==", "lang", ":", "return", "x", "return", "x" ]
Return label for given lang or any default :param lang: Language to request :return: Label value :rtype: Literal
[ "Return", "label", "for", "given", "lang", "or", "any", "default" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/metadata.py#L125-L140
train
Capitains/MyCapytain
MyCapytain/resources/prototypes/metadata.py
Collection.parents
def parents(self) -> List["Collection"]: """ Iterator to find parents of current collection, from closest to furthest :rtype: Generator[:class:`Collection`] """ p = self.parent parents = [] while p is not None: parents.append(p) p = p.parent return parents
python
def parents(self) -> List["Collection"]: """ Iterator to find parents of current collection, from closest to furthest :rtype: Generator[:class:`Collection`] """ p = self.parent parents = [] while p is not None: parents.append(p) p = p.parent return parents
[ "def", "parents", "(", "self", ")", "->", "List", "[", "\"Collection\"", "]", ":", "p", "=", "self", ".", "parent", "parents", "=", "[", "]", "while", "p", "is", "not", "None", ":", "parents", ".", "append", "(", "p", ")", "p", "=", "p", ".", "parent", "return", "parents" ]
Iterator to find parents of current collection, from closest to furthest :rtype: Generator[:class:`Collection`]
[ "Iterator", "to", "find", "parents", "of", "current", "collection", "from", "closest", "to", "furthest" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/metadata.py#L162-L172
train
Capitains/MyCapytain
MyCapytain/resources/prototypes/metadata.py
Collection._add_member
def _add_member(self, member): """ Does not add member if it already knows it. .. warning:: It should not be called ! :param member: Collection to add to members """ if member.id in self.children: return None else: self.children[member.id] = member
python
def _add_member(self, member): """ Does not add member if it already knows it. .. warning:: It should not be called ! :param member: Collection to add to members """ if member.id in self.children: return None else: self.children[member.id] = member
[ "def", "_add_member", "(", "self", ",", "member", ")", ":", "if", "member", ".", "id", "in", "self", ".", "children", ":", "return", "None", "else", ":", "self", ".", "children", "[", "member", ".", "id", "]", "=", "member" ]
Does not add member if it already knows it. .. warning:: It should not be called ! :param member: Collection to add to members
[ "Does", "not", "add", "member", "if", "it", "already", "knows", "it", "." ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/metadata.py#L196-L206
train
Capitains/MyCapytain
MyCapytain/resources/prototypes/metadata.py
Collection.export_base_dts
def export_base_dts(cls, graph, obj, nsm): """ Export the base DTS information in a simple reusable way :param graph: Current graph where the information lie :param obj: Object for which we build info :param nsm: Namespace manager :return: Dict """ o = { "@id": str(obj.asNode()), "@type": nsm.qname(obj.type), nsm.qname(RDF_NAMESPACES.HYDRA.title): str(obj.get_label()), nsm.qname(RDF_NAMESPACES.HYDRA.totalItems): obj.size } for desc in graph.objects(obj.asNode(), RDF_NAMESPACES.HYDRA.description): o[nsm.qname(RDF_NAMESPACES.HYDRA.description)] = str(desc) return o
python
def export_base_dts(cls, graph, obj, nsm): """ Export the base DTS information in a simple reusable way :param graph: Current graph where the information lie :param obj: Object for which we build info :param nsm: Namespace manager :return: Dict """ o = { "@id": str(obj.asNode()), "@type": nsm.qname(obj.type), nsm.qname(RDF_NAMESPACES.HYDRA.title): str(obj.get_label()), nsm.qname(RDF_NAMESPACES.HYDRA.totalItems): obj.size } for desc in graph.objects(obj.asNode(), RDF_NAMESPACES.HYDRA.description): o[nsm.qname(RDF_NAMESPACES.HYDRA.description)] = str(desc) return o
[ "def", "export_base_dts", "(", "cls", ",", "graph", ",", "obj", ",", "nsm", ")", ":", "o", "=", "{", "\"@id\"", ":", "str", "(", "obj", ".", "asNode", "(", ")", ")", ",", "\"@type\"", ":", "nsm", ".", "qname", "(", "obj", ".", "type", ")", ",", "nsm", ".", "qname", "(", "RDF_NAMESPACES", ".", "HYDRA", ".", "title", ")", ":", "str", "(", "obj", ".", "get_label", "(", ")", ")", ",", "nsm", ".", "qname", "(", "RDF_NAMESPACES", ".", "HYDRA", ".", "totalItems", ")", ":", "obj", ".", "size", "}", "for", "desc", "in", "graph", ".", "objects", "(", "obj", ".", "asNode", "(", ")", ",", "RDF_NAMESPACES", ".", "HYDRA", ".", "description", ")", ":", "o", "[", "nsm", ".", "qname", "(", "RDF_NAMESPACES", ".", "HYDRA", ".", "description", ")", "]", "=", "str", "(", "desc", ")", "return", "o" ]
Export the base DTS information in a simple reusable way :param graph: Current graph where the information lie :param obj: Object for which we build info :param nsm: Namespace manager :return: Dict
[ "Export", "the", "base", "DTS", "information", "in", "a", "simple", "reusable", "way" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/metadata.py#L306-L325
train
Capitains/MyCapytain
MyCapytain/resources/prototypes/metadata.py
ResourceCollection.get_subject
def get_subject(self, lang=None): """ Get the subject of the object :param lang: Lang to retrieve :return: Subject string representation :rtype: Literal """ return self.metadata.get_single(key=DC.subject, lang=lang)
python
def get_subject(self, lang=None): """ Get the subject of the object :param lang: Lang to retrieve :return: Subject string representation :rtype: Literal """ return self.metadata.get_single(key=DC.subject, lang=lang)
[ "def", "get_subject", "(", "self", ",", "lang", "=", "None", ")", ":", "return", "self", ".", "metadata", ".", "get_single", "(", "key", "=", "DC", ".", "subject", ",", "lang", "=", "lang", ")" ]
Get the subject of the object :param lang: Lang to retrieve :return: Subject string representation :rtype: Literal
[ "Get", "the", "subject", "of", "the", "object" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/prototypes/metadata.py#L488-L495
train
madisona/django-contact-form
contact_form/forms.py
BaseEmailFormMixin.get_context
def get_context(self): """ Context sent to templates for rendering include the form's cleaned data and also the current Request object. """ if not self.is_valid(): raise ValueError("Cannot generate Context when form is invalid.") return dict(request=self.request, **self.cleaned_data)
python
def get_context(self): """ Context sent to templates for rendering include the form's cleaned data and also the current Request object. """ if not self.is_valid(): raise ValueError("Cannot generate Context when form is invalid.") return dict(request=self.request, **self.cleaned_data)
[ "def", "get_context", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", "(", ")", ":", "raise", "ValueError", "(", "\"Cannot generate Context when form is invalid.\"", ")", "return", "dict", "(", "request", "=", "self", ".", "request", ",", "*", "*", "self", ".", "cleaned_data", ")" ]
Context sent to templates for rendering include the form's cleaned data and also the current Request object.
[ "Context", "sent", "to", "templates", "for", "rendering", "include", "the", "form", "s", "cleaned", "data", "and", "also", "the", "current", "Request", "object", "." ]
0800034a7231f35a3d5b5cd73968e6115b9ce01c
https://github.com/madisona/django-contact-form/blob/0800034a7231f35a3d5b5cd73968e6115b9ce01c/contact_form/forms.py#L24-L31
train
SHDShim/pytheos
pytheos/eqn_anharmonic.py
zharkov_panh
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300., three_r=3. * constants.R): """ calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a0: parameter in K-1 for the Zharkov equation :param m: parameter for the Zharkov equation :param n: number of elements in a chemical formula :param z: number of formula unit in a unit cell :param three_r: 3 times gas constant :return: anharmonic contribution for pressure in GPa """ v_mol = vol_uc2mol(v, z) x = v / v0 a = a0 * np.power(x, m) def f(t): return three_r * n / 2. * a * m / v_mol * np.power(t, 2.) * 1.e-9 return f(temp) - f(t_ref)
python
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300., three_r=3. * constants.R): """ calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a0: parameter in K-1 for the Zharkov equation :param m: parameter for the Zharkov equation :param n: number of elements in a chemical formula :param z: number of formula unit in a unit cell :param three_r: 3 times gas constant :return: anharmonic contribution for pressure in GPa """ v_mol = vol_uc2mol(v, z) x = v / v0 a = a0 * np.power(x, m) def f(t): return three_r * n / 2. * a * m / v_mol * np.power(t, 2.) * 1.e-9 return f(temp) - f(t_ref)
[ "def", "zharkov_panh", "(", "v", ",", "temp", ",", "v0", ",", "a0", ",", "m", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "v_mol", "=", "vol_uc2mol", "(", "v", ",", "z", ")", "x", "=", "v", "/", "v0", "a", "=", "a0", "*", "np", ".", "power", "(", "x", ",", "m", ")", "def", "f", "(", "t", ")", ":", "return", "three_r", "*", "n", "/", "2.", "*", "a", "*", "m", "/", "v_mol", "*", "np", ".", "power", "(", "t", ",", "2.", ")", "*", "1.e-9", "return", "f", "(", "temp", ")", "-", "f", "(", "t_ref", ")" ]
calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a0: parameter in K-1 for the Zharkov equation :param m: parameter for the Zharkov equation :param n: number of elements in a chemical formula :param z: number of formula unit in a unit cell :param three_r: 3 times gas constant :return: anharmonic contribution for pressure in GPa
[ "calculate", "pressure", "from", "anharmonicity", "for", "Zharkov", "equation", "the", "equation", "is", "from", "Dorogokupets", "2015" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_anharmonic.py#L6-L29
train
lyda/misspell-check
misspellings_lib.py
split_words
def split_words(line): """Return the list of words contained in a line.""" # Normalize any camel cased words first line = _NORM_REGEX.sub(r'\1 \2', line) return [normalize(w) for w in _WORD_REGEX.split(line)]
python
def split_words(line): """Return the list of words contained in a line.""" # Normalize any camel cased words first line = _NORM_REGEX.sub(r'\1 \2', line) return [normalize(w) for w in _WORD_REGEX.split(line)]
[ "def", "split_words", "(", "line", ")", ":", "# Normalize any camel cased words first", "line", "=", "_NORM_REGEX", ".", "sub", "(", "r'\\1 \\2'", ",", "line", ")", "return", "[", "normalize", "(", "w", ")", "for", "w", "in", "_WORD_REGEX", ".", "split", "(", "line", ")", "]" ]
Return the list of words contained in a line.
[ "Return", "the", "list", "of", "words", "contained", "in", "a", "line", "." ]
f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa
https://github.com/lyda/misspell-check/blob/f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa/misspellings_lib.py#L26-L30
train
lyda/misspell-check
misspellings_lib.py
Misspellings.add
def add(self, files): """Adds files to check. Args: files: List of files to check. """ if files.__class__.__name__ == 'str': self._files.append(files) else: self._files.extend(files)
python
def add(self, files): """Adds files to check. Args: files: List of files to check. """ if files.__class__.__name__ == 'str': self._files.append(files) else: self._files.extend(files)
[ "def", "add", "(", "self", ",", "files", ")", ":", "if", "files", ".", "__class__", ".", "__name__", "==", "'str'", ":", "self", ".", "_files", ".", "append", "(", "files", ")", "else", ":", "self", ".", "_files", ".", "extend", "(", "files", ")" ]
Adds files to check. Args: files: List of files to check.
[ "Adds", "files", "to", "check", "." ]
f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa
https://github.com/lyda/misspell-check/blob/f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa/misspellings_lib.py#L67-L76
train
lyda/misspell-check
misspellings_lib.py
Misspellings.check
def check(self): """Checks the files for misspellings. Returns: (errors, results) errors: List of system errors, usually file access errors. results: List of spelling errors - each tuple is filename, line number and misspelled word. """ errors = [] results = [] for fn in self._files: if not os.path.isdir(fn): try: with open(fn, 'r') as f: line_ct = 1 for line in f: for word in split_words(line): if (word in self._misspelling_dict or word.lower() in self._misspelling_dict): results.append([fn, line_ct, word]) line_ct += 1 except UnicodeDecodeError: pass except IOError: errors.append('%s' % sys.exc_info()[1]) return errors, results
python
def check(self): """Checks the files for misspellings. Returns: (errors, results) errors: List of system errors, usually file access errors. results: List of spelling errors - each tuple is filename, line number and misspelled word. """ errors = [] results = [] for fn in self._files: if not os.path.isdir(fn): try: with open(fn, 'r') as f: line_ct = 1 for line in f: for word in split_words(line): if (word in self._misspelling_dict or word.lower() in self._misspelling_dict): results.append([fn, line_ct, word]) line_ct += 1 except UnicodeDecodeError: pass except IOError: errors.append('%s' % sys.exc_info()[1]) return errors, results
[ "def", "check", "(", "self", ")", ":", "errors", "=", "[", "]", "results", "=", "[", "]", "for", "fn", "in", "self", ".", "_files", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "fn", ")", ":", "try", ":", "with", "open", "(", "fn", ",", "'r'", ")", "as", "f", ":", "line_ct", "=", "1", "for", "line", "in", "f", ":", "for", "word", "in", "split_words", "(", "line", ")", ":", "if", "(", "word", "in", "self", ".", "_misspelling_dict", "or", "word", ".", "lower", "(", ")", "in", "self", ".", "_misspelling_dict", ")", ":", "results", ".", "append", "(", "[", "fn", ",", "line_ct", ",", "word", "]", ")", "line_ct", "+=", "1", "except", "UnicodeDecodeError", ":", "pass", "except", "IOError", ":", "errors", ".", "append", "(", "'%s'", "%", "sys", ".", "exc_info", "(", ")", "[", "1", "]", ")", "return", "errors", ",", "results" ]
Checks the files for misspellings. Returns: (errors, results) errors: List of system errors, usually file access errors. results: List of spelling errors - each tuple is filename, line number and misspelled word.
[ "Checks", "the", "files", "for", "misspellings", "." ]
f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa
https://github.com/lyda/misspell-check/blob/f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa/misspellings_lib.py#L78-L104
train
lyda/misspell-check
misspellings_lib.py
Misspellings.suggestions
def suggestions(self, word): """Returns a list of suggestions for a misspelled word. Args: word: The word to check. Returns: List of zero or more suggested replacements for word. """ suggestions = set(self._misspelling_dict.get(word, [])).union( set(self._misspelling_dict.get(word.lower(), []))) return sorted([same_case(source=word, destination=w) for w in suggestions])
python
def suggestions(self, word): """Returns a list of suggestions for a misspelled word. Args: word: The word to check. Returns: List of zero or more suggested replacements for word. """ suggestions = set(self._misspelling_dict.get(word, [])).union( set(self._misspelling_dict.get(word.lower(), []))) return sorted([same_case(source=word, destination=w) for w in suggestions])
[ "def", "suggestions", "(", "self", ",", "word", ")", ":", "suggestions", "=", "set", "(", "self", ".", "_misspelling_dict", ".", "get", "(", "word", ",", "[", "]", ")", ")", ".", "union", "(", "set", "(", "self", ".", "_misspelling_dict", ".", "get", "(", "word", ".", "lower", "(", ")", ",", "[", "]", ")", ")", ")", "return", "sorted", "(", "[", "same_case", "(", "source", "=", "word", ",", "destination", "=", "w", ")", "for", "w", "in", "suggestions", "]", ")" ]
Returns a list of suggestions for a misspelled word. Args: word: The word to check. Returns: List of zero or more suggested replacements for word.
[ "Returns", "a", "list", "of", "suggestions", "for", "a", "misspelled", "word", "." ]
f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa
https://github.com/lyda/misspell-check/blob/f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa/misspellings_lib.py#L106-L118
train
lyda/misspell-check
misspellings_lib.py
Misspellings.dump_misspelling_list
def dump_misspelling_list(self): """Returns a list of misspelled words and corrections.""" results = [] for bad_word in sorted(self._misspelling_dict.keys()): for correction in self._misspelling_dict[bad_word]: results.append([bad_word, correction]) return results
python
def dump_misspelling_list(self): """Returns a list of misspelled words and corrections.""" results = [] for bad_word in sorted(self._misspelling_dict.keys()): for correction in self._misspelling_dict[bad_word]: results.append([bad_word, correction]) return results
[ "def", "dump_misspelling_list", "(", "self", ")", ":", "results", "=", "[", "]", "for", "bad_word", "in", "sorted", "(", "self", ".", "_misspelling_dict", ".", "keys", "(", ")", ")", ":", "for", "correction", "in", "self", ".", "_misspelling_dict", "[", "bad_word", "]", ":", "results", ".", "append", "(", "[", "bad_word", ",", "correction", "]", ")", "return", "results" ]
Returns a list of misspelled words and corrections.
[ "Returns", "a", "list", "of", "misspelled", "words", "and", "corrections", "." ]
f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa
https://github.com/lyda/misspell-check/blob/f8c5d67a5ffaeb0a7101efd5a4ace81c73955efa/misspellings_lib.py#L120-L126
train
hawkular/hawkular-client-python
hawkular/alerts/common.py
HawkularAlertsClient.status
def status(self): """ Get the status of Alerting Service :return: Status object """ orig_dict = self._get(self._service_url('status')) orig_dict['implementation_version'] = orig_dict.pop('Implementation-Version') orig_dict['built_from_git_sha1'] = orig_dict.pop('Built-From-Git-SHA1') return Status(orig_dict)
python
def status(self): """ Get the status of Alerting Service :return: Status object """ orig_dict = self._get(self._service_url('status')) orig_dict['implementation_version'] = orig_dict.pop('Implementation-Version') orig_dict['built_from_git_sha1'] = orig_dict.pop('Built-From-Git-SHA1') return Status(orig_dict)
[ "def", "status", "(", "self", ")", ":", "orig_dict", "=", "self", ".", "_get", "(", "self", ".", "_service_url", "(", "'status'", ")", ")", "orig_dict", "[", "'implementation_version'", "]", "=", "orig_dict", ".", "pop", "(", "'Implementation-Version'", ")", "orig_dict", "[", "'built_from_git_sha1'", "]", "=", "orig_dict", ".", "pop", "(", "'Built-From-Git-SHA1'", ")", "return", "Status", "(", "orig_dict", ")" ]
Get the status of Alerting Service :return: Status object
[ "Get", "the", "status", "of", "Alerting", "Service" ]
52371f9ebabbe310efee2a8ff8eb735ccc0654bb
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/alerts/common.py#L81-L90
train
ChrisBeaumont/smother
smother/cli.py
cli
def cli(ctx, report, semantic, rcfile): """ Query or manipulate smother reports """ ctx.obj = { 'report': report, 'semantic': semantic, 'rcfile': rcfile, }
python
def cli(ctx, report, semantic, rcfile): """ Query or manipulate smother reports """ ctx.obj = { 'report': report, 'semantic': semantic, 'rcfile': rcfile, }
[ "def", "cli", "(", "ctx", ",", "report", ",", "semantic", ",", "rcfile", ")", ":", "ctx", ".", "obj", "=", "{", "'report'", ":", "report", ",", "'semantic'", ":", "semantic", ",", "'rcfile'", ":", "rcfile", ",", "}" ]
Query or manipulate smother reports
[ "Query", "or", "manipulate", "smother", "reports" ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L27-L35
train
ChrisBeaumont/smother
smother/cli.py
lookup
def lookup(ctx, path): """ Determine which tests intersect a source interval. """ regions = parse_intervals(path, as_context=ctx.obj['semantic']) _report_from_regions(regions, ctx.obj)
python
def lookup(ctx, path): """ Determine which tests intersect a source interval. """ regions = parse_intervals(path, as_context=ctx.obj['semantic']) _report_from_regions(regions, ctx.obj)
[ "def", "lookup", "(", "ctx", ",", "path", ")", ":", "regions", "=", "parse_intervals", "(", "path", ",", "as_context", "=", "ctx", ".", "obj", "[", "'semantic'", "]", ")", "_report_from_regions", "(", "regions", ",", "ctx", ".", "obj", ")" ]
Determine which tests intersect a source interval.
[ "Determine", "which", "tests", "intersect", "a", "source", "interval", "." ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L48-L53
train
ChrisBeaumont/smother
smother/cli.py
diff
def diff(ctx, branch): """ Determine which tests intersect a git diff. """ diff = GitDiffReporter(branch) regions = diff.changed_intervals() _report_from_regions(regions, ctx.obj, file_factory=diff.old_file)
python
def diff(ctx, branch): """ Determine which tests intersect a git diff. """ diff = GitDiffReporter(branch) regions = diff.changed_intervals() _report_from_regions(regions, ctx.obj, file_factory=diff.old_file)
[ "def", "diff", "(", "ctx", ",", "branch", ")", ":", "diff", "=", "GitDiffReporter", "(", "branch", ")", "regions", "=", "diff", ".", "changed_intervals", "(", ")", "_report_from_regions", "(", "regions", ",", "ctx", ".", "obj", ",", "file_factory", "=", "diff", ".", "old_file", ")" ]
Determine which tests intersect a git diff.
[ "Determine", "which", "tests", "intersect", "a", "git", "diff", "." ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L59-L65
train
ChrisBeaumont/smother
smother/cli.py
combine
def combine(ctx, src, dst): """ Combine several smother reports. """ c = coverage.Coverage(config_file=ctx.obj['rcfile']) result = Smother(c) for infile in src: result |= Smother.load(infile) result.write(dst)
python
def combine(ctx, src, dst): """ Combine several smother reports. """ c = coverage.Coverage(config_file=ctx.obj['rcfile']) result = Smother(c) for infile in src: result |= Smother.load(infile) result.write(dst)
[ "def", "combine", "(", "ctx", ",", "src", ",", "dst", ")", ":", "c", "=", "coverage", ".", "Coverage", "(", "config_file", "=", "ctx", ".", "obj", "[", "'rcfile'", "]", ")", "result", "=", "Smother", "(", "c", ")", "for", "infile", "in", "src", ":", "result", "|=", "Smother", ".", "load", "(", "infile", ")", "result", ".", "write", "(", "dst", ")" ]
Combine several smother reports.
[ "Combine", "several", "smother", "reports", "." ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L72-L82
train
ChrisBeaumont/smother
smother/cli.py
convert_to_relative_paths
def convert_to_relative_paths(src, dst): """ Converts all file paths in a smother report to relative paths, relative to the current directory. """ result = Smother.convert_to_relative_paths(Smother.load(src)) result.write(dst)
python
def convert_to_relative_paths(src, dst): """ Converts all file paths in a smother report to relative paths, relative to the current directory. """ result = Smother.convert_to_relative_paths(Smother.load(src)) result.write(dst)
[ "def", "convert_to_relative_paths", "(", "src", ",", "dst", ")", ":", "result", "=", "Smother", ".", "convert_to_relative_paths", "(", "Smother", ".", "load", "(", "src", ")", ")", "result", ".", "write", "(", "dst", ")" ]
Converts all file paths in a smother report to relative paths, relative to the current directory.
[ "Converts", "all", "file", "paths", "in", "a", "smother", "report", "to", "relative", "paths", "relative", "to", "the", "current", "directory", "." ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L88-L94
train
ChrisBeaumont/smother
smother/cli.py
csv
def csv(ctx, dst): """ Flatten a coverage file into a CSV of source_context, testname """ sm = Smother.load(ctx.obj['report']) semantic = ctx.obj['semantic'] writer = _csv.writer(dst, lineterminator='\n') dst.write("source_context, test_context\n") writer.writerows(sm.iter_records(semantic=semantic))
python
def csv(ctx, dst): """ Flatten a coverage file into a CSV of source_context, testname """ sm = Smother.load(ctx.obj['report']) semantic = ctx.obj['semantic'] writer = _csv.writer(dst, lineterminator='\n') dst.write("source_context, test_context\n") writer.writerows(sm.iter_records(semantic=semantic))
[ "def", "csv", "(", "ctx", ",", "dst", ")", ":", "sm", "=", "Smother", ".", "load", "(", "ctx", ".", "obj", "[", "'report'", "]", ")", "semantic", "=", "ctx", ".", "obj", "[", "'semantic'", "]", "writer", "=", "_csv", ".", "writer", "(", "dst", ",", "lineterminator", "=", "'\\n'", ")", "dst", ".", "write", "(", "\"source_context, test_context\\n\"", ")", "writer", ".", "writerows", "(", "sm", ".", "iter_records", "(", "semantic", "=", "semantic", ")", ")" ]
Flatten a coverage file into a CSV of source_context, testname
[ "Flatten", "a", "coverage", "file", "into", "a", "CSV", "of", "source_context", "testname" ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L100-L109
train
ChrisBeaumont/smother
smother/cli.py
erase
def erase(ctx): """ Erase the existing smother report. """ if os.path.exists(ctx.obj['report']): os.remove(ctx.obj['report'])
python
def erase(ctx): """ Erase the existing smother report. """ if os.path.exists(ctx.obj['report']): os.remove(ctx.obj['report'])
[ "def", "erase", "(", "ctx", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "ctx", ".", "obj", "[", "'report'", "]", ")", ":", "os", ".", "remove", "(", "ctx", ".", "obj", "[", "'report'", "]", ")" ]
Erase the existing smother report.
[ "Erase", "the", "existing", "smother", "report", "." ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L114-L119
train
ChrisBeaumont/smother
smother/cli.py
to_coverage
def to_coverage(ctx): """ Produce a .coverage file from a smother file """ sm = Smother.load(ctx.obj['report']) sm.coverage = coverage.coverage() sm.write_coverage()
python
def to_coverage(ctx): """ Produce a .coverage file from a smother file """ sm = Smother.load(ctx.obj['report']) sm.coverage = coverage.coverage() sm.write_coverage()
[ "def", "to_coverage", "(", "ctx", ")", ":", "sm", "=", "Smother", ".", "load", "(", "ctx", ".", "obj", "[", "'report'", "]", ")", "sm", ".", "coverage", "=", "coverage", ".", "coverage", "(", ")", "sm", ".", "write_coverage", "(", ")" ]
Produce a .coverage file from a smother file
[ "Produce", "a", ".", "coverage", "file", "from", "a", "smother", "file" ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/cli.py#L124-L130
train
chaoss/grimoirelab-cereslib
cereslib/dfutils/format.py
Format.fill_missing_fields
def fill_missing_fields(self, data, columns): """ This method fills with 0's missing fields :param data: original Pandas dataframe :param columns: list of columns to be filled in the DataFrame :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with missing fields filled with 0's :rtype: pandas.DataFrame """ for column in columns: if column not in data.columns: data[column] = scipy.zeros(len(data)) return data
python
def fill_missing_fields(self, data, columns): """ This method fills with 0's missing fields :param data: original Pandas dataframe :param columns: list of columns to be filled in the DataFrame :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with missing fields filled with 0's :rtype: pandas.DataFrame """ for column in columns: if column not in data.columns: data[column] = scipy.zeros(len(data)) return data
[ "def", "fill_missing_fields", "(", "self", ",", "data", ",", "columns", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "not", "in", "data", ".", "columns", ":", "data", "[", "column", "]", "=", "scipy", ".", "zeros", "(", "len", "(", "data", ")", ")", "return", "data" ]
This method fills with 0's missing fields :param data: original Pandas dataframe :param columns: list of columns to be filled in the DataFrame :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with missing fields filled with 0's :rtype: pandas.DataFrame
[ "This", "method", "fills", "with", "0", "s", "missing", "fields" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/dfutils/format.py#L43-L59
train
chaoss/grimoirelab-cereslib
cereslib/dfutils/format.py
Format.update_field_names
def update_field_names(self, data, matching): """ This method updates the names of the fields according to matching :param data: original Pandas dataframe :param matching: dictionary of matchings between old and new values :type data: pandas.DataFrame :type matching: dictionary :returns: Pandas dataframe with updated names :rtype: pandas.DataFrame """ for key in matching.keys(): if key in data.columns: data.rename(columns={key:matching[key]}) return data
python
def update_field_names(self, data, matching): """ This method updates the names of the fields according to matching :param data: original Pandas dataframe :param matching: dictionary of matchings between old and new values :type data: pandas.DataFrame :type matching: dictionary :returns: Pandas dataframe with updated names :rtype: pandas.DataFrame """ for key in matching.keys(): if key in data.columns: data.rename(columns={key:matching[key]}) return data
[ "def", "update_field_names", "(", "self", ",", "data", ",", "matching", ")", ":", "for", "key", "in", "matching", ".", "keys", "(", ")", ":", "if", "key", "in", "data", ".", "columns", ":", "data", ".", "rename", "(", "columns", "=", "{", "key", ":", "matching", "[", "key", "]", "}", ")", "return", "data" ]
This method updates the names of the fields according to matching :param data: original Pandas dataframe :param matching: dictionary of matchings between old and new values :type data: pandas.DataFrame :type matching: dictionary :returns: Pandas dataframe with updated names :rtype: pandas.DataFrame
[ "This", "method", "updates", "the", "names", "of", "the", "fields", "according", "to", "matching" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/dfutils/format.py#L61-L77
train
chaoss/grimoirelab-cereslib
cereslib/dfutils/format.py
Format.format_dates
def format_dates(self, data, columns): """ This method translates columns values into datetime objects :param data: original Pandas dataframe :param columns: list of columns to cast the date to a datetime object :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with updated 'columns' with datetime objects :rtype: pandas.DataFrame """ for column in columns: if column in data.columns: data[column] = pandas.to_datetime(data[column]) return data
python
def format_dates(self, data, columns): """ This method translates columns values into datetime objects :param data: original Pandas dataframe :param columns: list of columns to cast the date to a datetime object :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with updated 'columns' with datetime objects :rtype: pandas.DataFrame """ for column in columns: if column in data.columns: data[column] = pandas.to_datetime(data[column]) return data
[ "def", "format_dates", "(", "self", ",", "data", ",", "columns", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "in", "data", ".", "columns", ":", "data", "[", "column", "]", "=", "pandas", ".", "to_datetime", "(", "data", "[", "column", "]", ")", "return", "data" ]
This method translates columns values into datetime objects :param data: original Pandas dataframe :param columns: list of columns to cast the date to a datetime object :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with updated 'columns' with datetime objects :rtype: pandas.DataFrame
[ "This", "method", "translates", "columns", "values", "into", "datetime", "objects" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/dfutils/format.py#L80-L96
train
chaoss/grimoirelab-cereslib
cereslib/dfutils/format.py
Format.remove_columns
def remove_columns(self, data, columns): """ This method removes columns in data :param data: original Pandas dataframe :param columns: list of columns to remove :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with removed columns :rtype: pandas.DataFrame """ for column in columns: if column in data.columns: data = data.drop(column, axis=1) return data
python
def remove_columns(self, data, columns): """ This method removes columns in data :param data: original Pandas dataframe :param columns: list of columns to remove :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with removed columns :rtype: pandas.DataFrame """ for column in columns: if column in data.columns: data = data.drop(column, axis=1) return data
[ "def", "remove_columns", "(", "self", ",", "data", ",", "columns", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "in", "data", ".", "columns", ":", "data", "=", "data", ".", "drop", "(", "column", ",", "axis", "=", "1", ")", "return", "data" ]
This method removes columns in data :param data: original Pandas dataframe :param columns: list of columns to remove :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas dataframe with removed columns :rtype: pandas.DataFrame
[ "This", "method", "removes", "columns", "in", "data" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/dfutils/format.py#L98-L114
train
SHDShim/pytheos
pytheos/eqn_therm_Tange.py
tange_grun
def tange_grun(v, v0, gamma0, a, b): """ calculate Gruneisen parameter for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :return: Gruneisen parameter """ x = v / v0 return gamma0 * (1. + a * (np.power(x, b) - 1.))
python
def tange_grun(v, v0, gamma0, a, b): """ calculate Gruneisen parameter for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :return: Gruneisen parameter """ x = v / v0 return gamma0 * (1. + a * (np.power(x, b) - 1.))
[ "def", "tange_grun", "(", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ")", ":", "x", "=", "v", "/", "v0", "return", "gamma0", "*", "(", "1.", "+", "a", "*", "(", "np", ".", "power", "(", "x", ",", "b", ")", "-", "1.", ")", ")" ]
calculate Gruneisen parameter for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :return: Gruneisen parameter
[ "calculate", "Gruneisen", "parameter", "for", "the", "Tange", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Tange.py#L13-L25
train
SHDShim/pytheos
pytheos/eqn_therm_Tange.py
tange_debyetemp
def tange_debyetemp(v, v0, gamma0, a, b, theta0): """ calculate Debye temperature for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :param theta0: Debye temperature at 1 bar in K :return: Debye temperature in K """ x = v / v0 gamma = tange_grun(v, v0, gamma0, a, b) if isuncertainties([v, v0, gamma0, a, b, theta0]): theta = theta0 * np.power(x, (-1. * (1. - a) * gamma0)) * \ unp.exp((gamma0 - gamma) / b) else: theta = theta0 * np.power(x, (-1. * (1. - a) * gamma0)) * \ np.exp((gamma0 - gamma) / b) return theta
python
def tange_debyetemp(v, v0, gamma0, a, b, theta0): """ calculate Debye temperature for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :param theta0: Debye temperature at 1 bar in K :return: Debye temperature in K """ x = v / v0 gamma = tange_grun(v, v0, gamma0, a, b) if isuncertainties([v, v0, gamma0, a, b, theta0]): theta = theta0 * np.power(x, (-1. * (1. - a) * gamma0)) * \ unp.exp((gamma0 - gamma) / b) else: theta = theta0 * np.power(x, (-1. * (1. - a) * gamma0)) * \ np.exp((gamma0 - gamma) / b) return theta
[ "def", "tange_debyetemp", "(", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ",", "theta0", ")", ":", "x", "=", "v", "/", "v0", "gamma", "=", "tange_grun", "(", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ")", "if", "isuncertainties", "(", "[", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ",", "theta0", "]", ")", ":", "theta", "=", "theta0", "*", "np", ".", "power", "(", "x", ",", "(", "-", "1.", "*", "(", "1.", "-", "a", ")", "*", "gamma0", ")", ")", "*", "unp", ".", "exp", "(", "(", "gamma0", "-", "gamma", ")", "/", "b", ")", "else", ":", "theta", "=", "theta0", "*", "np", ".", "power", "(", "x", ",", "(", "-", "1.", "*", "(", "1.", "-", "a", ")", "*", "gamma0", ")", ")", "*", "np", ".", "exp", "(", "(", "gamma0", "-", "gamma", ")", "/", "b", ")", "return", "theta" ]
calculate Debye temperature for the Tange equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :param theta0: Debye temperature at 1 bar in K :return: Debye temperature in K
[ "calculate", "Debye", "temperature", "for", "the", "Tange", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Tange.py#L28-L48
train
SHDShim/pytheos
pytheos/eqn_therm_Tange.py
tange_pth
def tange_pth(v, temp, v0, gamma0, a, b, theta0, n, z, t_ref=300., three_r=3. * constants.R): """ calculate thermal pressure for the Tange equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :param theta0: Debye temperature at 1 bar in K :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature :param three_r: 3R in case adjustment is needed :return: thermal pressure in GPa """ v_mol = vol_uc2mol(v, z) gamma = tange_grun(v, v0, gamma0, a, b) theta = tange_debyetemp(v, v0, gamma0, a, b, theta0) xx = theta / temp debye = debye_E(xx) if t_ref == 0.: debye0 = 0. else: xx0 = theta / t_ref debye0 = debye_E(xx0) Eth0 = three_r * n * t_ref * debye0 Eth = three_r * n * temp * debye delEth = Eth - Eth0 p_th = (gamma / v_mol * delEth) * 1.e-9 return p_th
python
def tange_pth(v, temp, v0, gamma0, a, b, theta0, n, z, t_ref=300., three_r=3. * constants.R): """ calculate thermal pressure for the Tange equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :param theta0: Debye temperature at 1 bar in K :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature :param three_r: 3R in case adjustment is needed :return: thermal pressure in GPa """ v_mol = vol_uc2mol(v, z) gamma = tange_grun(v, v0, gamma0, a, b) theta = tange_debyetemp(v, v0, gamma0, a, b, theta0) xx = theta / temp debye = debye_E(xx) if t_ref == 0.: debye0 = 0. else: xx0 = theta / t_ref debye0 = debye_E(xx0) Eth0 = three_r * n * t_ref * debye0 Eth = three_r * n * temp * debye delEth = Eth - Eth0 p_th = (gamma / v_mol * delEth) * 1.e-9 return p_th
[ "def", "tange_pth", "(", "v", ",", "temp", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ",", "theta0", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "v_mol", "=", "vol_uc2mol", "(", "v", ",", "z", ")", "gamma", "=", "tange_grun", "(", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ")", "theta", "=", "tange_debyetemp", "(", "v", ",", "v0", ",", "gamma0", ",", "a", ",", "b", ",", "theta0", ")", "xx", "=", "theta", "/", "temp", "debye", "=", "debye_E", "(", "xx", ")", "if", "t_ref", "==", "0.", ":", "debye0", "=", "0.", "else", ":", "xx0", "=", "theta", "/", "t_ref", "debye0", "=", "debye_E", "(", "xx0", ")", "Eth0", "=", "three_r", "*", "n", "*", "t_ref", "*", "debye0", "Eth", "=", "three_r", "*", "n", "*", "temp", "*", "debye", "delEth", "=", "Eth", "-", "Eth0", "p_th", "=", "(", "gamma", "/", "v_mol", "*", "delEth", ")", "*", "1.e-9", "return", "p_th" ]
calculate thermal pressure for the Tange equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param a: volume-independent adjustable parameters :param b: volume-independent adjustable parameters :param theta0: Debye temperature at 1 bar in K :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature :param three_r: 3R in case adjustment is needed :return: thermal pressure in GPa
[ "calculate", "thermal", "pressure", "for", "the", "Tange", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Tange.py#L51-L83
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_make_passage_kwargs
def _make_passage_kwargs(urn, reference): """ Little helper used by CapitainsCtsPassage here to comply with parents args :param urn: URN String :param reference: Reference String :return: Dictionary of arguments with URN based on identifier and reference """ kwargs = {} if urn is not None: if reference is not None: kwargs["urn"] = URN("{}:{}".format(urn.upTo(URN.VERSION), reference)) else: kwargs["urn"] = urn return kwargs
python
def _make_passage_kwargs(urn, reference): """ Little helper used by CapitainsCtsPassage here to comply with parents args :param urn: URN String :param reference: Reference String :return: Dictionary of arguments with URN based on identifier and reference """ kwargs = {} if urn is not None: if reference is not None: kwargs["urn"] = URN("{}:{}".format(urn.upTo(URN.VERSION), reference)) else: kwargs["urn"] = urn return kwargs
[ "def", "_make_passage_kwargs", "(", "urn", ",", "reference", ")", ":", "kwargs", "=", "{", "}", "if", "urn", "is", "not", "None", ":", "if", "reference", "is", "not", "None", ":", "kwargs", "[", "\"urn\"", "]", "=", "URN", "(", "\"{}:{}\"", ".", "format", "(", "urn", ".", "upTo", "(", "URN", ".", "VERSION", ")", ",", "reference", ")", ")", "else", ":", "kwargs", "[", "\"urn\"", "]", "=", "urn", "return", "kwargs" ]
Little helper used by CapitainsCtsPassage here to comply with parents args :param urn: URN String :param reference: Reference String :return: Dictionary of arguments with URN based on identifier and reference
[ "Little", "helper", "used", "by", "CapitainsCtsPassage", "here", "to", "comply", "with", "parents", "args" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L33-L46
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_SharedMethods.getTextualNode
def getTextualNode(self, subreference=None, simple=False): """ Finds a passage in the current text :param subreference: Identifier of the subreference / passages :type subreference: Union[list, CtsReference] :param simple: If set to true, retrieves nodes up to the given one, cleaning non required siblings. :type simple: boolean :rtype: CapitainsCtsPassage, ContextPassage :returns: Asked passage """ if subreference is None: return self._getSimplePassage() if not isinstance(subreference, CtsReference): if isinstance(subreference, str): subreference = CtsReference(subreference) elif isinstance(subreference, list): subreference = CtsReference(".".join(subreference)) if len(subreference.start) > self.citation.root.depth: raise CitationDepthError("URN is deeper than citation scheme") if simple is True: return self._getSimplePassage(subreference) if not subreference.is_range(): start = end = subreference.start.list else: start, end = subreference.start.list, subreference.end.list citation_start = self.citation.root[len(start)-1] citation_end = self.citation.root[len(end)-1] start, end = citation_start.fill(passage=start), citation_end.fill(passage=end) start, end = normalizeXpath(start.split("/")[2:]), normalizeXpath(end.split("/")[2:]) xml = self.textObject.xml if isinstance(xml, etree._Element): root = copyNode(xml) else: root = copyNode(xml.getroot()) root = passageLoop(xml, root, start, end) if self.urn: urn = URN("{}:{}".format(self.urn, subreference)) else: urn = None return CapitainsCtsPassage( urn=urn, resource=root, text=self, citation=citation_start, reference=subreference )
python
def getTextualNode(self, subreference=None, simple=False): """ Finds a passage in the current text :param subreference: Identifier of the subreference / passages :type subreference: Union[list, CtsReference] :param simple: If set to true, retrieves nodes up to the given one, cleaning non required siblings. :type simple: boolean :rtype: CapitainsCtsPassage, ContextPassage :returns: Asked passage """ if subreference is None: return self._getSimplePassage() if not isinstance(subreference, CtsReference): if isinstance(subreference, str): subreference = CtsReference(subreference) elif isinstance(subreference, list): subreference = CtsReference(".".join(subreference)) if len(subreference.start) > self.citation.root.depth: raise CitationDepthError("URN is deeper than citation scheme") if simple is True: return self._getSimplePassage(subreference) if not subreference.is_range(): start = end = subreference.start.list else: start, end = subreference.start.list, subreference.end.list citation_start = self.citation.root[len(start)-1] citation_end = self.citation.root[len(end)-1] start, end = citation_start.fill(passage=start), citation_end.fill(passage=end) start, end = normalizeXpath(start.split("/")[2:]), normalizeXpath(end.split("/")[2:]) xml = self.textObject.xml if isinstance(xml, etree._Element): root = copyNode(xml) else: root = copyNode(xml.getroot()) root = passageLoop(xml, root, start, end) if self.urn: urn = URN("{}:{}".format(self.urn, subreference)) else: urn = None return CapitainsCtsPassage( urn=urn, resource=root, text=self, citation=citation_start, reference=subreference )
[ "def", "getTextualNode", "(", "self", ",", "subreference", "=", "None", ",", "simple", "=", "False", ")", ":", "if", "subreference", "is", "None", ":", "return", "self", ".", "_getSimplePassage", "(", ")", "if", "not", "isinstance", "(", "subreference", ",", "CtsReference", ")", ":", "if", "isinstance", "(", "subreference", ",", "str", ")", ":", "subreference", "=", "CtsReference", "(", "subreference", ")", "elif", "isinstance", "(", "subreference", ",", "list", ")", ":", "subreference", "=", "CtsReference", "(", "\".\"", ".", "join", "(", "subreference", ")", ")", "if", "len", "(", "subreference", ".", "start", ")", ">", "self", ".", "citation", ".", "root", ".", "depth", ":", "raise", "CitationDepthError", "(", "\"URN is deeper than citation scheme\"", ")", "if", "simple", "is", "True", ":", "return", "self", ".", "_getSimplePassage", "(", "subreference", ")", "if", "not", "subreference", ".", "is_range", "(", ")", ":", "start", "=", "end", "=", "subreference", ".", "start", ".", "list", "else", ":", "start", ",", "end", "=", "subreference", ".", "start", ".", "list", ",", "subreference", ".", "end", ".", "list", "citation_start", "=", "self", ".", "citation", ".", "root", "[", "len", "(", "start", ")", "-", "1", "]", "citation_end", "=", "self", ".", "citation", ".", "root", "[", "len", "(", "end", ")", "-", "1", "]", "start", ",", "end", "=", "citation_start", ".", "fill", "(", "passage", "=", "start", ")", ",", "citation_end", ".", "fill", "(", "passage", "=", "end", ")", "start", ",", "end", "=", "normalizeXpath", "(", "start", ".", "split", "(", "\"/\"", ")", "[", "2", ":", "]", ")", ",", "normalizeXpath", "(", "end", ".", "split", "(", "\"/\"", ")", "[", "2", ":", "]", ")", "xml", "=", "self", ".", "textObject", ".", "xml", "if", "isinstance", "(", "xml", ",", "etree", ".", "_Element", ")", ":", "root", "=", "copyNode", "(", "xml", ")", "else", ":", "root", "=", "copyNode", "(", "xml", ".", "getroot", "(", ")", ")", "root", "=", "passageLoop", "(", "xml", ",", "root", ",", "start", ",", "end", ")", "if", "self", ".", "urn", ":", "urn", "=", "URN", "(", "\"{}:{}\"", ".", "format", "(", "self", ".", "urn", ",", "subreference", ")", ")", "else", ":", "urn", "=", "None", "return", "CapitainsCtsPassage", "(", "urn", "=", "urn", ",", "resource", "=", "root", ",", "text", "=", "self", ",", "citation", "=", "citation_start", ",", "reference", "=", "subreference", ")" ]
Finds a passage in the current text :param subreference: Identifier of the subreference / passages :type subreference: Union[list, CtsReference] :param simple: If set to true, retrieves nodes up to the given one, cleaning non required siblings. :type simple: boolean :rtype: CapitainsCtsPassage, ContextPassage :returns: Asked passage
[ "Finds", "a", "passage", "in", "the", "current", "text" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L53-L109
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_SharedMethods._getSimplePassage
def _getSimplePassage(self, reference=None): """ Retrieve a single node representing the passage. .. warning:: Range support is awkward. :param reference: Identifier of the subreference / passages :type reference: list, reference :returns: Asked passage :rtype: CapitainsCtsPassage """ if reference is None: return _SimplePassage( resource=self.resource, reference=None, urn=self.urn, citation=self.citation.root, text=self ) subcitation = self.citation.root[reference.depth-1] resource = self.resource.xpath( subcitation.fill(reference), namespaces=XPATH_NAMESPACES ) if len(resource) != 1: raise InvalidURN return _SimplePassage( resource[0], reference=reference, urn=self.urn, citation=subcitation, text=self.textObject )
python
def _getSimplePassage(self, reference=None): """ Retrieve a single node representing the passage. .. warning:: Range support is awkward. :param reference: Identifier of the subreference / passages :type reference: list, reference :returns: Asked passage :rtype: CapitainsCtsPassage """ if reference is None: return _SimplePassage( resource=self.resource, reference=None, urn=self.urn, citation=self.citation.root, text=self ) subcitation = self.citation.root[reference.depth-1] resource = self.resource.xpath( subcitation.fill(reference), namespaces=XPATH_NAMESPACES ) if len(resource) != 1: raise InvalidURN return _SimplePassage( resource[0], reference=reference, urn=self.urn, citation=subcitation, text=self.textObject )
[ "def", "_getSimplePassage", "(", "self", ",", "reference", "=", "None", ")", ":", "if", "reference", "is", "None", ":", "return", "_SimplePassage", "(", "resource", "=", "self", ".", "resource", ",", "reference", "=", "None", ",", "urn", "=", "self", ".", "urn", ",", "citation", "=", "self", ".", "citation", ".", "root", ",", "text", "=", "self", ")", "subcitation", "=", "self", ".", "citation", ".", "root", "[", "reference", ".", "depth", "-", "1", "]", "resource", "=", "self", ".", "resource", ".", "xpath", "(", "subcitation", ".", "fill", "(", "reference", ")", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "if", "len", "(", "resource", ")", "!=", "1", ":", "raise", "InvalidURN", "return", "_SimplePassage", "(", "resource", "[", "0", "]", ",", "reference", "=", "reference", ",", "urn", "=", "self", ".", "urn", ",", "citation", "=", "subcitation", ",", "text", "=", "self", ".", "textObject", ")" ]
Retrieve a single node representing the passage. .. warning:: Range support is awkward. :param reference: Identifier of the subreference / passages :type reference: list, reference :returns: Asked passage :rtype: CapitainsCtsPassage
[ "Retrieve", "a", "single", "node", "representing", "the", "passage", "." ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L111-L145
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_SharedMethods.getReffs
def getReffs(self, level: int=1, subreference: CtsReference=None) -> CtsReferenceSet: """ CtsReference available at a given level :param level: Depth required. If not set, should retrieve first encountered level (1 based) :param subreference: Subreference (optional) :returns: List of levels """ if not subreference and hasattr(self, "reference"): subreference = self.reference elif subreference and not isinstance(subreference, CtsReference): subreference = CtsReference(subreference) return self.getValidReff(level=level, reference=subreference)
python
def getReffs(self, level: int=1, subreference: CtsReference=None) -> CtsReferenceSet: """ CtsReference available at a given level :param level: Depth required. If not set, should retrieve first encountered level (1 based) :param subreference: Subreference (optional) :returns: List of levels """ if not subreference and hasattr(self, "reference"): subreference = self.reference elif subreference and not isinstance(subreference, CtsReference): subreference = CtsReference(subreference) return self.getValidReff(level=level, reference=subreference)
[ "def", "getReffs", "(", "self", ",", "level", ":", "int", "=", "1", ",", "subreference", ":", "CtsReference", "=", "None", ")", "->", "CtsReferenceSet", ":", "if", "not", "subreference", "and", "hasattr", "(", "self", ",", "\"reference\"", ")", ":", "subreference", "=", "self", ".", "reference", "elif", "subreference", "and", "not", "isinstance", "(", "subreference", ",", "CtsReference", ")", ":", "subreference", "=", "CtsReference", "(", "subreference", ")", "return", "self", ".", "getValidReff", "(", "level", "=", "level", ",", "reference", "=", "subreference", ")" ]
CtsReference available at a given level :param level: Depth required. If not set, should retrieve first encountered level (1 based) :param subreference: Subreference (optional) :returns: List of levels
[ "CtsReference", "available", "at", "a", "given", "level" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L159-L172
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_SharedMethods.xpath
def xpath(self, *args, **kwargs): """ Perform XPath on the passage XML :param args: Ordered arguments for etree._Element().xpath() :param kwargs: Named arguments :return: Result list :rtype: list(etree._Element) """ if "smart_strings" not in kwargs: kwargs["smart_strings"] = False return self.resource.xpath(*args, **kwargs)
python
def xpath(self, *args, **kwargs): """ Perform XPath on the passage XML :param args: Ordered arguments for etree._Element().xpath() :param kwargs: Named arguments :return: Result list :rtype: list(etree._Element) """ if "smart_strings" not in kwargs: kwargs["smart_strings"] = False return self.resource.xpath(*args, **kwargs)
[ "def", "xpath", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"smart_strings\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"smart_strings\"", "]", "=", "False", "return", "self", ".", "resource", ".", "xpath", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Perform XPath on the passage XML :param args: Ordered arguments for etree._Element().xpath() :param kwargs: Named arguments :return: Result list :rtype: list(etree._Element)
[ "Perform", "XPath", "on", "the", "passage", "XML" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L285-L295
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_SharedMethods.tostring
def tostring(self, *args, **kwargs): """ Transform the CapitainsCtsPassage in XML string :param args: Ordered arguments for etree.tostring() (except the first one) :param kwargs: Named arguments :return: """ return etree.tostring(self.resource, *args, **kwargs)
python
def tostring(self, *args, **kwargs): """ Transform the CapitainsCtsPassage in XML string :param args: Ordered arguments for etree.tostring() (except the first one) :param kwargs: Named arguments :return: """ return etree.tostring(self.resource, *args, **kwargs)
[ "def", "tostring", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "etree", ".", "tostring", "(", "self", ".", "resource", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Transform the CapitainsCtsPassage in XML string :param args: Ordered arguments for etree.tostring() (except the first one) :param kwargs: Named arguments :return:
[ "Transform", "the", "CapitainsCtsPassage", "in", "XML", "string" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L297-L304
train
Capitains/MyCapytain
MyCapytain/resources/texts/local/capitains/cts.py
_SimplePassage.childIds
def childIds(self): """ Children of the passage :rtype: None, CtsReference :returns: Dictionary of chidren, where key are subreferences """ if self.depth >= len(self.citation.root): return [] elif self._children is not None: return self._children else: self._children = self.getReffs() return self._children
python
def childIds(self): """ Children of the passage :rtype: None, CtsReference :returns: Dictionary of chidren, where key are subreferences """ if self.depth >= len(self.citation.root): return [] elif self._children is not None: return self._children else: self._children = self.getReffs() return self._children
[ "def", "childIds", "(", "self", ")", ":", "if", "self", ".", "depth", ">=", "len", "(", "self", ".", "citation", ".", "root", ")", ":", "return", "[", "]", "elif", "self", ".", "_children", "is", "not", "None", ":", "return", "self", ".", "_children", "else", ":", "self", ".", "_children", "=", "self", ".", "getReffs", "(", ")", "return", "self", ".", "_children" ]
Children of the passage :rtype: None, CtsReference :returns: Dictionary of chidren, where key are subreferences
[ "Children", "of", "the", "passage" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/local/capitains/cts.py#L349-L361
train
rosshamish/hexgrid
hexgrid.py
location
def location(hexgrid_type, coord): """ Returns a formatted string representing the coordinate. The format depends on the coordinate type. Tiles look like: 1, 12 Nodes look like: (1 NW), (12 S) Edges look like: (1 NW), (12 SE) :param hexgrid_type: hexgrid.TILE, hexgrid.NODE, hexgrid.EDGE :param coord: integer coordinate in this module's hexadecimal coordinate system :return: formatted string for display """ if hexgrid_type == TILE: return str(coord) elif hexgrid_type == NODE: tile_id = nearest_tile_to_node(coord) dirn = tile_node_offset_to_direction(coord - tile_id_to_coord(tile_id)) return '({} {})'.format(tile_id, dirn) elif hexgrid_type == EDGE: tile_id = nearest_tile_to_edge(coord) dirn = tile_edge_offset_to_direction(coord - tile_id_to_coord(tile_id)) return '({} {})'.format(tile_id, dirn) else: logging.warning('unsupported hexgrid_type={}'.format(hexgrid_type)) return None
python
def location(hexgrid_type, coord): """ Returns a formatted string representing the coordinate. The format depends on the coordinate type. Tiles look like: 1, 12 Nodes look like: (1 NW), (12 S) Edges look like: (1 NW), (12 SE) :param hexgrid_type: hexgrid.TILE, hexgrid.NODE, hexgrid.EDGE :param coord: integer coordinate in this module's hexadecimal coordinate system :return: formatted string for display """ if hexgrid_type == TILE: return str(coord) elif hexgrid_type == NODE: tile_id = nearest_tile_to_node(coord) dirn = tile_node_offset_to_direction(coord - tile_id_to_coord(tile_id)) return '({} {})'.format(tile_id, dirn) elif hexgrid_type == EDGE: tile_id = nearest_tile_to_edge(coord) dirn = tile_edge_offset_to_direction(coord - tile_id_to_coord(tile_id)) return '({} {})'.format(tile_id, dirn) else: logging.warning('unsupported hexgrid_type={}'.format(hexgrid_type)) return None
[ "def", "location", "(", "hexgrid_type", ",", "coord", ")", ":", "if", "hexgrid_type", "==", "TILE", ":", "return", "str", "(", "coord", ")", "elif", "hexgrid_type", "==", "NODE", ":", "tile_id", "=", "nearest_tile_to_node", "(", "coord", ")", "dirn", "=", "tile_node_offset_to_direction", "(", "coord", "-", "tile_id_to_coord", "(", "tile_id", ")", ")", "return", "'({} {})'", ".", "format", "(", "tile_id", ",", "dirn", ")", "elif", "hexgrid_type", "==", "EDGE", ":", "tile_id", "=", "nearest_tile_to_edge", "(", "coord", ")", "dirn", "=", "tile_edge_offset_to_direction", "(", "coord", "-", "tile_id_to_coord", "(", "tile_id", ")", ")", "return", "'({} {})'", ".", "format", "(", "tile_id", ",", "dirn", ")", "else", ":", "logging", ".", "warning", "(", "'unsupported hexgrid_type={}'", ".", "format", "(", "hexgrid_type", ")", ")", "return", "None" ]
Returns a formatted string representing the coordinate. The format depends on the coordinate type. Tiles look like: 1, 12 Nodes look like: (1 NW), (12 S) Edges look like: (1 NW), (12 SE) :param hexgrid_type: hexgrid.TILE, hexgrid.NODE, hexgrid.EDGE :param coord: integer coordinate in this module's hexadecimal coordinate system :return: formatted string for display
[ "Returns", "a", "formatted", "string", "representing", "the", "coordinate", ".", "The", "format", "depends", "on", "the", "coordinate", "type", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L72-L97
train
rosshamish/hexgrid
hexgrid.py
coastal_edges
def coastal_edges(tile_id): """ Returns a list of coastal edge coordinate. An edge is coastal if it is on the grid's border. :return: list(int) """ edges = list() tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): dirn = tile_edge_offset_to_direction(edge_coord - tile_coord) if tile_id_in_direction(tile_id, dirn) is None: edges.append(edge_coord) return edges
python
def coastal_edges(tile_id): """ Returns a list of coastal edge coordinate. An edge is coastal if it is on the grid's border. :return: list(int) """ edges = list() tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): dirn = tile_edge_offset_to_direction(edge_coord - tile_coord) if tile_id_in_direction(tile_id, dirn) is None: edges.append(edge_coord) return edges
[ "def", "coastal_edges", "(", "tile_id", ")", ":", "edges", "=", "list", "(", ")", "tile_coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "for", "edge_coord", "in", "edges_touching_tile", "(", "tile_id", ")", ":", "dirn", "=", "tile_edge_offset_to_direction", "(", "edge_coord", "-", "tile_coord", ")", "if", "tile_id_in_direction", "(", "tile_id", ",", "dirn", ")", "is", "None", ":", "edges", ".", "append", "(", "edge_coord", ")", "return", "edges" ]
Returns a list of coastal edge coordinate. An edge is coastal if it is on the grid's border. :return: list(int)
[ "Returns", "a", "list", "of", "coastal", "edge", "coordinate", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L147-L160
train
rosshamish/hexgrid
hexgrid.py
tile_id_in_direction
def tile_id_in_direction(from_tile_id, direction): """ Variant on direction_to_tile. Returns None if there's no tile there. :param from_tile_id: tile identifier, int :param direction: str :return: tile identifier, int or None """ coord_from = tile_id_to_coord(from_tile_id) for offset, dirn in _tile_tile_offsets.items(): if dirn == direction: coord_to = coord_from + offset if coord_to in legal_tile_coords(): return tile_id_from_coord(coord_to) return None
python
def tile_id_in_direction(from_tile_id, direction): """ Variant on direction_to_tile. Returns None if there's no tile there. :param from_tile_id: tile identifier, int :param direction: str :return: tile identifier, int or None """ coord_from = tile_id_to_coord(from_tile_id) for offset, dirn in _tile_tile_offsets.items(): if dirn == direction: coord_to = coord_from + offset if coord_to in legal_tile_coords(): return tile_id_from_coord(coord_to) return None
[ "def", "tile_id_in_direction", "(", "from_tile_id", ",", "direction", ")", ":", "coord_from", "=", "tile_id_to_coord", "(", "from_tile_id", ")", "for", "offset", ",", "dirn", "in", "_tile_tile_offsets", ".", "items", "(", ")", ":", "if", "dirn", "==", "direction", ":", "coord_to", "=", "coord_from", "+", "offset", "if", "coord_to", "in", "legal_tile_coords", "(", ")", ":", "return", "tile_id_from_coord", "(", "coord_to", ")", "return", "None" ]
Variant on direction_to_tile. Returns None if there's no tile there. :param from_tile_id: tile identifier, int :param direction: str :return: tile identifier, int or None
[ "Variant", "on", "direction_to_tile", ".", "Returns", "None", "if", "there", "s", "no", "tile", "there", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L163-L177
train
rosshamish/hexgrid
hexgrid.py
direction_to_tile
def direction_to_tile(from_tile_id, to_tile_id): """ Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction of the offset between two tiles. The tiles must be adjacent. :param from_tile_id: tile identifier, int :param to_tile_id: tile identifier, int :return: direction from from_tile to to_tile, str """ coord_from = tile_id_to_coord(from_tile_id) coord_to = tile_id_to_coord(to_tile_id) direction = tile_tile_offset_to_direction(coord_to - coord_from) # logging.debug('Tile direction: {}->{} is {}'.format( # from_tile.tile_id, # to_tile.tile_id, # direction # )) return direction
python
def direction_to_tile(from_tile_id, to_tile_id): """ Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction of the offset between two tiles. The tiles must be adjacent. :param from_tile_id: tile identifier, int :param to_tile_id: tile identifier, int :return: direction from from_tile to to_tile, str """ coord_from = tile_id_to_coord(from_tile_id) coord_to = tile_id_to_coord(to_tile_id) direction = tile_tile_offset_to_direction(coord_to - coord_from) # logging.debug('Tile direction: {}->{} is {}'.format( # from_tile.tile_id, # to_tile.tile_id, # direction # )) return direction
[ "def", "direction_to_tile", "(", "from_tile_id", ",", "to_tile_id", ")", ":", "coord_from", "=", "tile_id_to_coord", "(", "from_tile_id", ")", "coord_to", "=", "tile_id_to_coord", "(", "to_tile_id", ")", "direction", "=", "tile_tile_offset_to_direction", "(", "coord_to", "-", "coord_from", ")", "# logging.debug('Tile direction: {}->{} is {}'.format(", "# from_tile.tile_id,", "# to_tile.tile_id,", "# direction", "# ))", "return", "direction" ]
Convenience method wrapping tile_tile_offset_to_direction. Used to get the direction of the offset between two tiles. The tiles must be adjacent. :param from_tile_id: tile identifier, int :param to_tile_id: tile identifier, int :return: direction from from_tile to to_tile, str
[ "Convenience", "method", "wrapping", "tile_tile_offset_to_direction", ".", "Used", "to", "get", "the", "direction", "of", "the", "offset", "between", "two", "tiles", ".", "The", "tiles", "must", "be", "adjacent", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L180-L197
train
rosshamish/hexgrid
hexgrid.py
edge_coord_in_direction
def edge_coord_in_direction(tile_id, direction): """ Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int """ tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): if tile_edge_offset_to_direction(edge_coord - tile_coord) == direction: return edge_coord raise ValueError('No edge found in direction={} at tile_id={}'.format( direction, tile_id ))
python
def edge_coord_in_direction(tile_id, direction): """ Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int """ tile_coord = tile_id_to_coord(tile_id) for edge_coord in edges_touching_tile(tile_id): if tile_edge_offset_to_direction(edge_coord - tile_coord) == direction: return edge_coord raise ValueError('No edge found in direction={} at tile_id={}'.format( direction, tile_id ))
[ "def", "edge_coord_in_direction", "(", "tile_id", ",", "direction", ")", ":", "tile_coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "for", "edge_coord", "in", "edges_touching_tile", "(", "tile_id", ")", ":", "if", "tile_edge_offset_to_direction", "(", "edge_coord", "-", "tile_coord", ")", "==", "direction", ":", "return", "edge_coord", "raise", "ValueError", "(", "'No edge found in direction={} at tile_id={}'", ".", "format", "(", "direction", ",", "tile_id", ")", ")" ]
Returns the edge coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: edge coord, int
[ "Returns", "the", "edge", "coordinate", "in", "the", "given", "direction", "at", "the", "given", "tile", "identifier", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L242-L257
train
rosshamish/hexgrid
hexgrid.py
node_coord_in_direction
def node_coord_in_direction(tile_id, direction): """ Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int """ tile_coord = tile_id_to_coord(tile_id) for node_coord in nodes_touching_tile(tile_id): if tile_node_offset_to_direction(node_coord - tile_coord) == direction: return node_coord raise ValueError('No node found in direction={} at tile_id={}'.format( direction, tile_id ))
python
def node_coord_in_direction(tile_id, direction): """ Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int """ tile_coord = tile_id_to_coord(tile_id) for node_coord in nodes_touching_tile(tile_id): if tile_node_offset_to_direction(node_coord - tile_coord) == direction: return node_coord raise ValueError('No node found in direction={} at tile_id={}'.format( direction, tile_id ))
[ "def", "node_coord_in_direction", "(", "tile_id", ",", "direction", ")", ":", "tile_coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "for", "node_coord", "in", "nodes_touching_tile", "(", "tile_id", ")", ":", "if", "tile_node_offset_to_direction", "(", "node_coord", "-", "tile_coord", ")", "==", "direction", ":", "return", "node_coord", "raise", "ValueError", "(", "'No node found in direction={} at tile_id={}'", ".", "format", "(", "direction", ",", "tile_id", ")", ")" ]
Returns the node coordinate in the given direction at the given tile identifier. :param tile_id: tile identifier, int :param direction: direction, str :return: node coord, int
[ "Returns", "the", "node", "coordinate", "in", "the", "given", "direction", "at", "the", "given", "tile", "identifier", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L260-L275
train
rosshamish/hexgrid
hexgrid.py
tile_id_from_coord
def tile_id_from_coord(coord): """ Convert a tile coordinate to its corresponding tile identifier. :param coord: coordinate of the tile, int :return: tile identifier, Tile.tile_id """ for i, c in _tile_id_to_coord.items(): if c == coord: return i raise Exception('Tile id lookup failed, coord={} not found in map'.format(hex(coord)))
python
def tile_id_from_coord(coord): """ Convert a tile coordinate to its corresponding tile identifier. :param coord: coordinate of the tile, int :return: tile identifier, Tile.tile_id """ for i, c in _tile_id_to_coord.items(): if c == coord: return i raise Exception('Tile id lookup failed, coord={} not found in map'.format(hex(coord)))
[ "def", "tile_id_from_coord", "(", "coord", ")", ":", "for", "i", ",", "c", "in", "_tile_id_to_coord", ".", "items", "(", ")", ":", "if", "c", "==", "coord", ":", "return", "i", "raise", "Exception", "(", "'Tile id lookup failed, coord={} not found in map'", ".", "format", "(", "hex", "(", "coord", ")", ")", ")" ]
Convert a tile coordinate to its corresponding tile identifier. :param coord: coordinate of the tile, int :return: tile identifier, Tile.tile_id
[ "Convert", "a", "tile", "coordinate", "to", "its", "corresponding", "tile", "identifier", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L293-L303
train
rosshamish/hexgrid
hexgrid.py
nearest_tile_to_edge_using_tiles
def nearest_tile_to_edge_using_tiles(tile_ids, edge_coord): """ Get the first tile found adjacent to the given edge. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param edge_coord: edge coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id """ for tile_id in tile_ids: if edge_coord - tile_id_to_coord(tile_id) in _tile_edge_offsets.keys(): return tile_id logging.critical('Did not find a tile touching edge={}'.format(edge_coord))
python
def nearest_tile_to_edge_using_tiles(tile_ids, edge_coord): """ Get the first tile found adjacent to the given edge. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param edge_coord: edge coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id """ for tile_id in tile_ids: if edge_coord - tile_id_to_coord(tile_id) in _tile_edge_offsets.keys(): return tile_id logging.critical('Did not find a tile touching edge={}'.format(edge_coord))
[ "def", "nearest_tile_to_edge_using_tiles", "(", "tile_ids", ",", "edge_coord", ")", ":", "for", "tile_id", "in", "tile_ids", ":", "if", "edge_coord", "-", "tile_id_to_coord", "(", "tile_id", ")", "in", "_tile_edge_offsets", ".", "keys", "(", ")", ":", "return", "tile_id", "logging", ".", "critical", "(", "'Did not find a tile touching edge={}'", ".", "format", "(", "edge_coord", ")", ")" ]
Get the first tile found adjacent to the given edge. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param edge_coord: edge coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id
[ "Get", "the", "first", "tile", "found", "adjacent", "to", "the", "given", "edge", ".", "Returns", "a", "tile", "identifier", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L317-L328
train
rosshamish/hexgrid
hexgrid.py
nearest_tile_to_node_using_tiles
def nearest_tile_to_node_using_tiles(tile_ids, node_coord): """ Get the first tile found adjacent to the given node. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param node_coord: node coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id """ for tile_id in tile_ids: if node_coord - tile_id_to_coord(tile_id) in _tile_node_offsets.keys(): return tile_id logging.critical('Did not find a tile touching node={}'.format(node_coord))
python
def nearest_tile_to_node_using_tiles(tile_ids, node_coord): """ Get the first tile found adjacent to the given node. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param node_coord: node coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id """ for tile_id in tile_ids: if node_coord - tile_id_to_coord(tile_id) in _tile_node_offsets.keys(): return tile_id logging.critical('Did not find a tile touching node={}'.format(node_coord))
[ "def", "nearest_tile_to_node_using_tiles", "(", "tile_ids", ",", "node_coord", ")", ":", "for", "tile_id", "in", "tile_ids", ":", "if", "node_coord", "-", "tile_id_to_coord", "(", "tile_id", ")", "in", "_tile_node_offsets", ".", "keys", "(", ")", ":", "return", "tile_id", "logging", ".", "critical", "(", "'Did not find a tile touching node={}'", ".", "format", "(", "node_coord", ")", ")" ]
Get the first tile found adjacent to the given node. Returns a tile identifier. :param tile_ids: tiles to look at for adjacency, list(Tile.tile_id) :param node_coord: node coordinate to find an adjacent tile to, int :return: tile identifier of an adjacent tile, Tile.tile_id
[ "Get", "the", "first", "tile", "found", "adjacent", "to", "the", "given", "node", ".", "Returns", "a", "tile", "identifier", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L342-L353
train
rosshamish/hexgrid
hexgrid.py
edges_touching_tile
def edges_touching_tile(tile_id): """ Get a list of edge coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of edge coordinates touching the given tile, list(int) """ coord = tile_id_to_coord(tile_id) edges = [] for offset in _tile_edge_offsets.keys(): edges.append(coord + offset) # logging.debug('tile_id={}, edges touching={}'.format(tile_id, edges)) return edges
python
def edges_touching_tile(tile_id): """ Get a list of edge coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of edge coordinates touching the given tile, list(int) """ coord = tile_id_to_coord(tile_id) edges = [] for offset in _tile_edge_offsets.keys(): edges.append(coord + offset) # logging.debug('tile_id={}, edges touching={}'.format(tile_id, edges)) return edges
[ "def", "edges_touching_tile", "(", "tile_id", ")", ":", "coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "edges", "=", "[", "]", "for", "offset", "in", "_tile_edge_offsets", ".", "keys", "(", ")", ":", "edges", ".", "append", "(", "coord", "+", "offset", ")", "# logging.debug('tile_id={}, edges touching={}'.format(tile_id, edges))", "return", "edges" ]
Get a list of edge coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of edge coordinates touching the given tile, list(int)
[ "Get", "a", "list", "of", "edge", "coordinates", "touching", "the", "given", "tile", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L356-L368
train
rosshamish/hexgrid
hexgrid.py
nodes_touching_tile
def nodes_touching_tile(tile_id): """ Get a list of node coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of node coordinates touching the given tile, list(int) """ coord = tile_id_to_coord(tile_id) nodes = [] for offset in _tile_node_offsets.keys(): nodes.append(coord + offset) # logging.debug('tile_id={}, nodes touching={}'.format(tile_id, nodes)) return nodes
python
def nodes_touching_tile(tile_id): """ Get a list of node coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of node coordinates touching the given tile, list(int) """ coord = tile_id_to_coord(tile_id) nodes = [] for offset in _tile_node_offsets.keys(): nodes.append(coord + offset) # logging.debug('tile_id={}, nodes touching={}'.format(tile_id, nodes)) return nodes
[ "def", "nodes_touching_tile", "(", "tile_id", ")", ":", "coord", "=", "tile_id_to_coord", "(", "tile_id", ")", "nodes", "=", "[", "]", "for", "offset", "in", "_tile_node_offsets", ".", "keys", "(", ")", ":", "nodes", ".", "append", "(", "coord", "+", "offset", ")", "# logging.debug('tile_id={}, nodes touching={}'.format(tile_id, nodes))", "return", "nodes" ]
Get a list of node coordinates touching the given tile. :param tile_id: tile identifier, Tile.tile_id :return: list of node coordinates touching the given tile, list(int)
[ "Get", "a", "list", "of", "node", "coordinates", "touching", "the", "given", "tile", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L371-L383
train
rosshamish/hexgrid
hexgrid.py
nodes_touching_edge
def nodes_touching_edge(edge_coord): """ Returns the two node coordinates which are on the given edge coordinate. :return: list of 2 node coordinates which are on the given edge coordinate, list(int) """ a, b = hex_digit(edge_coord, 1), hex_digit(edge_coord, 2) if a % 2 == 0 and b % 2 == 0: return [coord_from_hex_digits(a, b + 1), coord_from_hex_digits(a + 1, b)] else: return [coord_from_hex_digits(a, b), coord_from_hex_digits(a + 1, b + 1)]
python
def nodes_touching_edge(edge_coord): """ Returns the two node coordinates which are on the given edge coordinate. :return: list of 2 node coordinates which are on the given edge coordinate, list(int) """ a, b = hex_digit(edge_coord, 1), hex_digit(edge_coord, 2) if a % 2 == 0 and b % 2 == 0: return [coord_from_hex_digits(a, b + 1), coord_from_hex_digits(a + 1, b)] else: return [coord_from_hex_digits(a, b), coord_from_hex_digits(a + 1, b + 1)]
[ "def", "nodes_touching_edge", "(", "edge_coord", ")", ":", "a", ",", "b", "=", "hex_digit", "(", "edge_coord", ",", "1", ")", ",", "hex_digit", "(", "edge_coord", ",", "2", ")", "if", "a", "%", "2", "==", "0", "and", "b", "%", "2", "==", "0", ":", "return", "[", "coord_from_hex_digits", "(", "a", ",", "b", "+", "1", ")", ",", "coord_from_hex_digits", "(", "a", "+", "1", ",", "b", ")", "]", "else", ":", "return", "[", "coord_from_hex_digits", "(", "a", ",", "b", ")", ",", "coord_from_hex_digits", "(", "a", "+", "1", ",", "b", "+", "1", ")", "]" ]
Returns the two node coordinates which are on the given edge coordinate. :return: list of 2 node coordinates which are on the given edge coordinate, list(int)
[ "Returns", "the", "two", "node", "coordinates", "which", "are", "on", "the", "given", "edge", "coordinate", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L386-L398
train
rosshamish/hexgrid
hexgrid.py
legal_edge_coords
def legal_edge_coords(): """ Return all legal edge coordinates on the grid. """ edges = set() for tile_id in legal_tile_ids(): for edge in edges_touching_tile(tile_id): edges.add(edge) logging.debug('Legal edge coords({})={}'.format(len(edges), edges)) return edges
python
def legal_edge_coords(): """ Return all legal edge coordinates on the grid. """ edges = set() for tile_id in legal_tile_ids(): for edge in edges_touching_tile(tile_id): edges.add(edge) logging.debug('Legal edge coords({})={}'.format(len(edges), edges)) return edges
[ "def", "legal_edge_coords", "(", ")", ":", "edges", "=", "set", "(", ")", "for", "tile_id", "in", "legal_tile_ids", "(", ")", ":", "for", "edge", "in", "edges_touching_tile", "(", "tile_id", ")", ":", "edges", ".", "add", "(", "edge", ")", "logging", ".", "debug", "(", "'Legal edge coords({})={}'", ".", "format", "(", "len", "(", "edges", ")", ",", "edges", ")", ")", "return", "edges" ]
Return all legal edge coordinates on the grid.
[ "Return", "all", "legal", "edge", "coordinates", "on", "the", "grid", "." ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L401-L410
train
rosshamish/hexgrid
hexgrid.py
legal_node_coords
def legal_node_coords(): """ Return all legal node coordinates on the grid """ nodes = set() for tile_id in legal_tile_ids(): for node in nodes_touching_tile(tile_id): nodes.add(node) logging.debug('Legal node coords({})={}'.format(len(nodes), nodes)) return nodes
python
def legal_node_coords(): """ Return all legal node coordinates on the grid """ nodes = set() for tile_id in legal_tile_ids(): for node in nodes_touching_tile(tile_id): nodes.add(node) logging.debug('Legal node coords({})={}'.format(len(nodes), nodes)) return nodes
[ "def", "legal_node_coords", "(", ")", ":", "nodes", "=", "set", "(", ")", "for", "tile_id", "in", "legal_tile_ids", "(", ")", ":", "for", "node", "in", "nodes_touching_tile", "(", "tile_id", ")", ":", "nodes", ".", "add", "(", "node", ")", "logging", ".", "debug", "(", "'Legal node coords({})={}'", ".", "format", "(", "len", "(", "nodes", ")", ",", "nodes", ")", ")", "return", "nodes" ]
Return all legal node coordinates on the grid
[ "Return", "all", "legal", "node", "coordinates", "on", "the", "grid" ]
16abb1822dc2789cb355f54fb06c7774eea1d9f2
https://github.com/rosshamish/hexgrid/blob/16abb1822dc2789cb355f54fb06c7774eea1d9f2/hexgrid.py#L413-L422
train
jiasir/playback
playback/cli/manila.py
make
def make(parser): """provison Manila with HA""" s = parser.add_subparsers( title='commands', metavar='COMMAND', help='description', ) def create_manila_db_f(args): create_manila_db(args) create_manila_db_parser = create_manila_db_subparser(s) create_manila_db_parser.set_defaults(func=create_manila_db_f) def create_service_credentials_f(args): create_service_credentials(args) create_service_credentials_parser = create_service_credentials_subparser(s) create_service_credentials_parser.set_defaults(func=create_service_credentials_f) def install_f(args): install(args) install_parser = install_subparser(s) install_parser.set_defaults(func=install_f)
python
def make(parser): """provison Manila with HA""" s = parser.add_subparsers( title='commands', metavar='COMMAND', help='description', ) def create_manila_db_f(args): create_manila_db(args) create_manila_db_parser = create_manila_db_subparser(s) create_manila_db_parser.set_defaults(func=create_manila_db_f) def create_service_credentials_f(args): create_service_credentials(args) create_service_credentials_parser = create_service_credentials_subparser(s) create_service_credentials_parser.set_defaults(func=create_service_credentials_f) def install_f(args): install(args) install_parser = install_subparser(s) install_parser.set_defaults(func=install_f)
[ "def", "make", "(", "parser", ")", ":", "s", "=", "parser", ".", "add_subparsers", "(", "title", "=", "'commands'", ",", "metavar", "=", "'COMMAND'", ",", "help", "=", "'description'", ",", ")", "def", "create_manila_db_f", "(", "args", ")", ":", "create_manila_db", "(", "args", ")", "create_manila_db_parser", "=", "create_manila_db_subparser", "(", "s", ")", "create_manila_db_parser", ".", "set_defaults", "(", "func", "=", "create_manila_db_f", ")", "def", "create_service_credentials_f", "(", "args", ")", ":", "create_service_credentials", "(", "args", ")", "create_service_credentials_parser", "=", "create_service_credentials_subparser", "(", "s", ")", "create_service_credentials_parser", ".", "set_defaults", "(", "func", "=", "create_service_credentials_f", ")", "def", "install_f", "(", "args", ")", ":", "install", "(", "args", ")", "install_parser", "=", "install_subparser", "(", "s", ")", "install_parser", ".", "set_defaults", "(", "func", "=", "install_f", ")" ]
provison Manila with HA
[ "provison", "Manila", "with", "HA" ]
58b2a5d669dcfaa8cad50c544a4b068dcacf9b69
https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/cli/manila.py#L163-L184
train
zhemao/funktown
funktown/lookuptree.py
LookupTree.assoc
def assoc(self, index, value): '''Return a new tree with value associated at index.''' newnode = LookupTreeNode(index, value) newtree = LookupTree() newtree.root = _assoc_down(self.root, newnode, 0) return newtree
python
def assoc(self, index, value): '''Return a new tree with value associated at index.''' newnode = LookupTreeNode(index, value) newtree = LookupTree() newtree.root = _assoc_down(self.root, newnode, 0) return newtree
[ "def", "assoc", "(", "self", ",", "index", ",", "value", ")", ":", "newnode", "=", "LookupTreeNode", "(", "index", ",", "value", ")", "newtree", "=", "LookupTree", "(", ")", "newtree", ".", "root", "=", "_assoc_down", "(", "self", ".", "root", ",", "newnode", ",", "0", ")", "return", "newtree" ]
Return a new tree with value associated at index.
[ "Return", "a", "new", "tree", "with", "value", "associated", "at", "index", "." ]
8d5c5a8bdad2b85b33b4cea3febd820c2657c375
https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/lookuptree.py#L73-L78
train
zhemao/funktown
funktown/lookuptree.py
LookupTree.remove
def remove(self, index): '''Return new tree with index removed.''' newtree = LookupTree() newtree.root = _remove_down(self.root, index, 0) return newtree
python
def remove(self, index): '''Return new tree with index removed.''' newtree = LookupTree() newtree.root = _remove_down(self.root, index, 0) return newtree
[ "def", "remove", "(", "self", ",", "index", ")", ":", "newtree", "=", "LookupTree", "(", ")", "newtree", ".", "root", "=", "_remove_down", "(", "self", ".", "root", ",", "index", ",", "0", ")", "return", "newtree" ]
Return new tree with index removed.
[ "Return", "new", "tree", "with", "index", "removed", "." ]
8d5c5a8bdad2b85b33b4cea3febd820c2657c375
https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/lookuptree.py#L92-L96
train
zhemao/funktown
funktown/lookuptree.py
LookupTree.insert
def insert(self, index, value): '''Insert a node in-place. It is highly suggested that you do not use this method. Use assoc instead''' newnode = LookupTreeNode(index, value) level = 0 node = self.root while True: ind = _getbits(newnode.index, level) level += 1 child = node.children[ind] if child is None or child.index == newnode.index: if child: assert child.value == newnode.value node.children[ind] = newnode break elif child.index == _root_index: # This is a branch node = child else: branch = LookupTreeNode() nind = _getbits(newnode.index, level) cind = _getbits(child.index, level) node.children[ind] = branch # Life gets tricky when... if nind == cind: branch.children[cind] = child # recurse node = branch else: branch.children[nind] = newnode branch.children[cind] = child break
python
def insert(self, index, value): '''Insert a node in-place. It is highly suggested that you do not use this method. Use assoc instead''' newnode = LookupTreeNode(index, value) level = 0 node = self.root while True: ind = _getbits(newnode.index, level) level += 1 child = node.children[ind] if child is None or child.index == newnode.index: if child: assert child.value == newnode.value node.children[ind] = newnode break elif child.index == _root_index: # This is a branch node = child else: branch = LookupTreeNode() nind = _getbits(newnode.index, level) cind = _getbits(child.index, level) node.children[ind] = branch # Life gets tricky when... if nind == cind: branch.children[cind] = child # recurse node = branch else: branch.children[nind] = newnode branch.children[cind] = child break
[ "def", "insert", "(", "self", ",", "index", ",", "value", ")", ":", "newnode", "=", "LookupTreeNode", "(", "index", ",", "value", ")", "level", "=", "0", "node", "=", "self", ".", "root", "while", "True", ":", "ind", "=", "_getbits", "(", "newnode", ".", "index", ",", "level", ")", "level", "+=", "1", "child", "=", "node", ".", "children", "[", "ind", "]", "if", "child", "is", "None", "or", "child", ".", "index", "==", "newnode", ".", "index", ":", "if", "child", ":", "assert", "child", ".", "value", "==", "newnode", ".", "value", "node", ".", "children", "[", "ind", "]", "=", "newnode", "break", "elif", "child", ".", "index", "==", "_root_index", ":", "# This is a branch", "node", "=", "child", "else", ":", "branch", "=", "LookupTreeNode", "(", ")", "nind", "=", "_getbits", "(", "newnode", ".", "index", ",", "level", ")", "cind", "=", "_getbits", "(", "child", ".", "index", ",", "level", ")", "node", ".", "children", "[", "ind", "]", "=", "branch", "# Life gets tricky when...", "if", "nind", "==", "cind", ":", "branch", ".", "children", "[", "cind", "]", "=", "child", "# recurse", "node", "=", "branch", "else", ":", "branch", ".", "children", "[", "nind", "]", "=", "newnode", "branch", ".", "children", "[", "cind", "]", "=", "child", "break" ]
Insert a node in-place. It is highly suggested that you do not use this method. Use assoc instead
[ "Insert", "a", "node", "in", "-", "place", ".", "It", "is", "highly", "suggested", "that", "you", "do", "not", "use", "this", "method", ".", "Use", "assoc", "instead" ]
8d5c5a8bdad2b85b33b4cea3febd820c2657c375
https://github.com/zhemao/funktown/blob/8d5c5a8bdad2b85b33b4cea3febd820c2657c375/funktown/lookuptree.py#L98-L130
train
ivilata/pymultihash
multihash/codecs.py
CodecReg.reset
def reset(cls): """Reset the registry to the standard codecs.""" cls._codecs = {} c = cls._codec for (name, encode, decode) in cls._common_codec_data: cls._codecs[name] = c(encode, decode)
python
def reset(cls): """Reset the registry to the standard codecs.""" cls._codecs = {} c = cls._codec for (name, encode, decode) in cls._common_codec_data: cls._codecs[name] = c(encode, decode)
[ "def", "reset", "(", "cls", ")", ":", "cls", ".", "_codecs", "=", "{", "}", "c", "=", "cls", ".", "_codec", "for", "(", "name", ",", "encode", ",", "decode", ")", "in", "cls", ".", "_common_codec_data", ":", "cls", ".", "_codecs", "[", "name", "]", "=", "c", "(", "encode", ",", "decode", ")" ]
Reset the registry to the standard codecs.
[ "Reset", "the", "registry", "to", "the", "standard", "codecs", "." ]
093365f20f6d8627c1fae13e0f4e0b35e9b39ad2
https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/codecs.py#L57-L62
train
ivilata/pymultihash
multihash/codecs.py
CodecReg.register
def register(cls, name, encode, decode): """Add a codec to the registry. Registers a codec with the given `name` (a string) to be used with the given `encode` and `decode` functions, which take a `bytes` object and return another one. An existing codec is replaced. >>> import binascii >>> CodecReg.register('uu', binascii.b2a_uu, binascii.a2b_uu) >>> CodecReg.get_decoder('uu') is binascii.a2b_uu True >>> CodecReg.reset() >>> 'uu' in CodecReg False """ cls._codecs[name] = cls._codec(encode, decode)
python
def register(cls, name, encode, decode): """Add a codec to the registry. Registers a codec with the given `name` (a string) to be used with the given `encode` and `decode` functions, which take a `bytes` object and return another one. An existing codec is replaced. >>> import binascii >>> CodecReg.register('uu', binascii.b2a_uu, binascii.a2b_uu) >>> CodecReg.get_decoder('uu') is binascii.a2b_uu True >>> CodecReg.reset() >>> 'uu' in CodecReg False """ cls._codecs[name] = cls._codec(encode, decode)
[ "def", "register", "(", "cls", ",", "name", ",", "encode", ",", "decode", ")", ":", "cls", ".", "_codecs", "[", "name", "]", "=", "cls", ".", "_codec", "(", "encode", ",", "decode", ")" ]
Add a codec to the registry. Registers a codec with the given `name` (a string) to be used with the given `encode` and `decode` functions, which take a `bytes` object and return another one. An existing codec is replaced. >>> import binascii >>> CodecReg.register('uu', binascii.b2a_uu, binascii.a2b_uu) >>> CodecReg.get_decoder('uu') is binascii.a2b_uu True >>> CodecReg.reset() >>> 'uu' in CodecReg False
[ "Add", "a", "codec", "to", "the", "registry", "." ]
093365f20f6d8627c1fae13e0f4e0b35e9b39ad2
https://github.com/ivilata/pymultihash/blob/093365f20f6d8627c1fae13e0f4e0b35e9b39ad2/multihash/codecs.py#L65-L80
train
klen/muffin-admin
muffin_admin/formatters.py
default_formatter
def default_formatter(handler, item, value): """Default formatter. Convert value to string.""" if hasattr(value, '__unicode__'): value = value.__unicode__() return escape(str(value))
python
def default_formatter(handler, item, value): """Default formatter. Convert value to string.""" if hasattr(value, '__unicode__'): value = value.__unicode__() return escape(str(value))
[ "def", "default_formatter", "(", "handler", ",", "item", ",", "value", ")", ":", "if", "hasattr", "(", "value", ",", "'__unicode__'", ")", ":", "value", "=", "value", ".", "__unicode__", "(", ")", "return", "escape", "(", "str", "(", "value", ")", ")" ]
Default formatter. Convert value to string.
[ "Default", "formatter", ".", "Convert", "value", "to", "string", "." ]
404dc8e5107e943b7c42fa21c679c34ddb4de1d5
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/formatters.py#L7-L12
train
klen/muffin-admin
muffin_admin/formatters.py
list_formatter
def list_formatter(handler, item, value): """Format list.""" return u', '.join(str(v) for v in value)
python
def list_formatter(handler, item, value): """Format list.""" return u', '.join(str(v) for v in value)
[ "def", "list_formatter", "(", "handler", ",", "item", ",", "value", ")", ":", "return", "u', '", ".", "join", "(", "str", "(", "v", ")", "for", "v", "in", "value", ")" ]
Format list.
[ "Format", "list", "." ]
404dc8e5107e943b7c42fa21c679c34ddb4de1d5
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/formatters.py#L21-L23
train
klen/muffin-admin
muffin_admin/formatters.py
format_value
def format_value(handler, item, column): """Format value.""" value = getattr(item, column, None) formatter = FORMATTERS.get(type(value), default_formatter) return formatter(handler, item, value)
python
def format_value(handler, item, column): """Format value.""" value = getattr(item, column, None) formatter = FORMATTERS.get(type(value), default_formatter) return formatter(handler, item, value)
[ "def", "format_value", "(", "handler", ",", "item", ",", "column", ")", ":", "value", "=", "getattr", "(", "item", ",", "column", ",", "None", ")", "formatter", "=", "FORMATTERS", ".", "get", "(", "type", "(", "value", ")", ",", "default_formatter", ")", "return", "formatter", "(", "handler", ",", "item", ",", "value", ")" ]
Format value.
[ "Format", "value", "." ]
404dc8e5107e943b7c42fa21c679c34ddb4de1d5
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/formatters.py#L49-L53
train
xflr6/features
features/parsers.py
make_regex
def make_regex(string): """Regex string for optionally signed binary or privative feature. >>> [make_regex(s) for s in '+spam -spam spam'.split()] ['([+]?spam)', '(-spam)', '(spam)'] >>> make_regex('+eggs-spam') Traceback (most recent call last): ... ValueError: inappropriate feature name: '+eggs-spam' >>> make_regex('') Traceback (most recent call last): ... ValueError: inappropriate feature name: '' """ if string and string[0] in '+-': sign, name = string[0], string[1:] if not name or '+' in name or '-' in name: raise ValueError('inappropriate feature name: %r' % string) tmpl = r'([+]?%s)' if sign == '+' else r'(-%s)' return tmpl % name if not string or '+' in string or '-' in string: raise ValueError('inappropriate feature name: %r' % string) return r'(%s)' % string
python
def make_regex(string): """Regex string for optionally signed binary or privative feature. >>> [make_regex(s) for s in '+spam -spam spam'.split()] ['([+]?spam)', '(-spam)', '(spam)'] >>> make_regex('+eggs-spam') Traceback (most recent call last): ... ValueError: inappropriate feature name: '+eggs-spam' >>> make_regex('') Traceback (most recent call last): ... ValueError: inappropriate feature name: '' """ if string and string[0] in '+-': sign, name = string[0], string[1:] if not name or '+' in name or '-' in name: raise ValueError('inappropriate feature name: %r' % string) tmpl = r'([+]?%s)' if sign == '+' else r'(-%s)' return tmpl % name if not string or '+' in string or '-' in string: raise ValueError('inappropriate feature name: %r' % string) return r'(%s)' % string
[ "def", "make_regex", "(", "string", ")", ":", "if", "string", "and", "string", "[", "0", "]", "in", "'+-'", ":", "sign", ",", "name", "=", "string", "[", "0", "]", ",", "string", "[", "1", ":", "]", "if", "not", "name", "or", "'+'", "in", "name", "or", "'-'", "in", "name", ":", "raise", "ValueError", "(", "'inappropriate feature name: %r'", "%", "string", ")", "tmpl", "=", "r'([+]?%s)'", "if", "sign", "==", "'+'", "else", "r'(-%s)'", "return", "tmpl", "%", "name", "if", "not", "string", "or", "'+'", "in", "string", "or", "'-'", "in", "string", ":", "raise", "ValueError", "(", "'inappropriate feature name: %r'", "%", "string", ")", "return", "r'(%s)'", "%", "string" ]
Regex string for optionally signed binary or privative feature. >>> [make_regex(s) for s in '+spam -spam spam'.split()] ['([+]?spam)', '(-spam)', '(spam)'] >>> make_regex('+eggs-spam') Traceback (most recent call last): ... ValueError: inappropriate feature name: '+eggs-spam' >>> make_regex('') Traceback (most recent call last): ... ValueError: inappropriate feature name: ''
[ "Regex", "string", "for", "optionally", "signed", "binary", "or", "privative", "feature", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/parsers.py#L18-L45
train
xflr6/features
features/parsers.py
substring_names
def substring_names(features): """Yield all feature name pairs in substring relation. >>> list(substring_names(['+spam', '-ham', '+pam'])) [('pam', 'spam')] """ names = tools.uniqued(map(remove_sign, features)) for l, r in permutations(names, 2): if l in r: yield (l, r)
python
def substring_names(features): """Yield all feature name pairs in substring relation. >>> list(substring_names(['+spam', '-ham', '+pam'])) [('pam', 'spam')] """ names = tools.uniqued(map(remove_sign, features)) for l, r in permutations(names, 2): if l in r: yield (l, r)
[ "def", "substring_names", "(", "features", ")", ":", "names", "=", "tools", ".", "uniqued", "(", "map", "(", "remove_sign", ",", "features", ")", ")", "for", "l", ",", "r", "in", "permutations", "(", "names", ",", "2", ")", ":", "if", "l", "in", "r", ":", "yield", "(", "l", ",", "r", ")" ]
Yield all feature name pairs in substring relation. >>> list(substring_names(['+spam', '-ham', '+pam'])) [('pam', 'spam')]
[ "Yield", "all", "feature", "name", "pairs", "in", "substring", "relation", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/parsers.py#L48-L57
train
xflr6/features
features/systems.py
FeatureSystem.join
def join(self, featuresets): """Return the nearest featureset that subsumes all given ones.""" concepts = (f.concept for f in featuresets) join = self.lattice.join(concepts) return self._featuresets[join.index]
python
def join(self, featuresets): """Return the nearest featureset that subsumes all given ones.""" concepts = (f.concept for f in featuresets) join = self.lattice.join(concepts) return self._featuresets[join.index]
[ "def", "join", "(", "self", ",", "featuresets", ")", ":", "concepts", "=", "(", "f", ".", "concept", "for", "f", "in", "featuresets", ")", "join", "=", "self", ".", "lattice", ".", "join", "(", "concepts", ")", "return", "self", ".", "_featuresets", "[", "join", ".", "index", "]" ]
Return the nearest featureset that subsumes all given ones.
[ "Return", "the", "nearest", "featureset", "that", "subsumes", "all", "given", "ones", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/systems.py#L180-L184
train
xflr6/features
features/systems.py
FeatureSystem.meet
def meet(self, featuresets): """Return the nearest featureset that implies all given ones.""" concepts = (f.concept for f in featuresets) meet = self.lattice.meet(concepts) return self._featuresets[meet.index]
python
def meet(self, featuresets): """Return the nearest featureset that implies all given ones.""" concepts = (f.concept for f in featuresets) meet = self.lattice.meet(concepts) return self._featuresets[meet.index]
[ "def", "meet", "(", "self", ",", "featuresets", ")", ":", "concepts", "=", "(", "f", ".", "concept", "for", "f", "in", "featuresets", ")", "meet", "=", "self", ".", "lattice", ".", "meet", "(", "concepts", ")", "return", "self", ".", "_featuresets", "[", "meet", ".", "index", "]" ]
Return the nearest featureset that implies all given ones.
[ "Return", "the", "nearest", "featureset", "that", "implies", "all", "given", "ones", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/systems.py#L186-L190
train
xflr6/features
features/systems.py
FeatureSystem.upset_union
def upset_union(self, featuresets): """Yield all featuresets that subsume any of the given ones.""" concepts = (f.concept for f in featuresets) indexes = (c.index for c in self.lattice.upset_union(concepts)) return map(self._featuresets.__getitem__, indexes)
python
def upset_union(self, featuresets): """Yield all featuresets that subsume any of the given ones.""" concepts = (f.concept for f in featuresets) indexes = (c.index for c in self.lattice.upset_union(concepts)) return map(self._featuresets.__getitem__, indexes)
[ "def", "upset_union", "(", "self", ",", "featuresets", ")", ":", "concepts", "=", "(", "f", ".", "concept", "for", "f", "in", "featuresets", ")", "indexes", "=", "(", "c", ".", "index", "for", "c", "in", "self", ".", "lattice", ".", "upset_union", "(", "concepts", ")", ")", "return", "map", "(", "self", ".", "_featuresets", ".", "__getitem__", ",", "indexes", ")" ]
Yield all featuresets that subsume any of the given ones.
[ "Yield", "all", "featuresets", "that", "subsume", "any", "of", "the", "given", "ones", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/systems.py#L192-L196
train
xflr6/features
features/systems.py
FeatureSystem.graphviz
def graphviz(self, highlight=None, maximal_label=None, topdown=None, filename=None, directory=None, render=False, view=False): """Return the system lattice visualization as graphviz source.""" return visualize.featuresystem(self, highlight, maximal_label, topdown, filename, directory, render, view)
python
def graphviz(self, highlight=None, maximal_label=None, topdown=None, filename=None, directory=None, render=False, view=False): """Return the system lattice visualization as graphviz source.""" return visualize.featuresystem(self, highlight, maximal_label, topdown, filename, directory, render, view)
[ "def", "graphviz", "(", "self", ",", "highlight", "=", "None", ",", "maximal_label", "=", "None", ",", "topdown", "=", "None", ",", "filename", "=", "None", ",", "directory", "=", "None", ",", "render", "=", "False", ",", "view", "=", "False", ")", ":", "return", "visualize", ".", "featuresystem", "(", "self", ",", "highlight", ",", "maximal_label", ",", "topdown", ",", "filename", ",", "directory", ",", "render", ",", "view", ")" ]
Return the system lattice visualization as graphviz source.
[ "Return", "the", "system", "lattice", "visualization", "as", "graphviz", "source", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/systems.py#L204-L208
train
dingusdk/PythonIhcSdk
ihcsdk/ihcconnection.py
IHCConnection.soap_action
def soap_action(self, service, action, payloadbody): """Do a soap request.""" payload = self.soapenvelope.format(body=payloadbody).encode('utf-8') headers = {"Host": self.url, "Content-Type": "text/xml; charset=UTF-8", "Cache-Control": "no-cache", "Content-Length": str(len(payload)), "SOAPAction": action} try: self.last_exception = None response = requests.post(url=self.url + service, headers=headers, data=payload, cookies=self.cookies) except requests.exceptions.RequestException as exp: self.last_exception = exp return False if response.status_code != 200: self.last_response = response return False self.cookies = response.cookies try: xdoc = xml.etree.ElementTree.fromstring(response.text) except xml.etree.ElementTree.ParseError as exp: self.last_exception = exp self.last_response = response return False return xdoc
python
def soap_action(self, service, action, payloadbody): """Do a soap request.""" payload = self.soapenvelope.format(body=payloadbody).encode('utf-8') headers = {"Host": self.url, "Content-Type": "text/xml; charset=UTF-8", "Cache-Control": "no-cache", "Content-Length": str(len(payload)), "SOAPAction": action} try: self.last_exception = None response = requests.post(url=self.url + service, headers=headers, data=payload, cookies=self.cookies) except requests.exceptions.RequestException as exp: self.last_exception = exp return False if response.status_code != 200: self.last_response = response return False self.cookies = response.cookies try: xdoc = xml.etree.ElementTree.fromstring(response.text) except xml.etree.ElementTree.ParseError as exp: self.last_exception = exp self.last_response = response return False return xdoc
[ "def", "soap_action", "(", "self", ",", "service", ",", "action", ",", "payloadbody", ")", ":", "payload", "=", "self", ".", "soapenvelope", ".", "format", "(", "body", "=", "payloadbody", ")", ".", "encode", "(", "'utf-8'", ")", "headers", "=", "{", "\"Host\"", ":", "self", ".", "url", ",", "\"Content-Type\"", ":", "\"text/xml; charset=UTF-8\"", ",", "\"Cache-Control\"", ":", "\"no-cache\"", ",", "\"Content-Length\"", ":", "str", "(", "len", "(", "payload", ")", ")", ",", "\"SOAPAction\"", ":", "action", "}", "try", ":", "self", ".", "last_exception", "=", "None", "response", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "url", "+", "service", ",", "headers", "=", "headers", ",", "data", "=", "payload", ",", "cookies", "=", "self", ".", "cookies", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "exp", ":", "self", ".", "last_exception", "=", "exp", "return", "False", "if", "response", ".", "status_code", "!=", "200", ":", "self", ".", "last_response", "=", "response", "return", "False", "self", ".", "cookies", "=", "response", ".", "cookies", "try", ":", "xdoc", "=", "xml", ".", "etree", ".", "ElementTree", ".", "fromstring", "(", "response", ".", "text", ")", "except", "xml", ".", "etree", ".", "ElementTree", ".", "ParseError", "as", "exp", ":", "self", ".", "last_exception", "=", "exp", "self", ".", "last_response", "=", "response", "return", "False", "return", "xdoc" ]
Do a soap request.
[ "Do", "a", "soap", "request", "." ]
7e2067e009fe7600b49f30bff1cf91dc72fc891e
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcconnection.py#L24-L49
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.getValidReff
def getValidReff(self, level=1, reference=None): """ Given a resource, CtsText will compute valid reffs :param level: Depth required. If not set, should retrieve first encountered level (1 based) :type level: Int :param reference: CapitainsCtsPassage reference :type reference: CtsReference :rtype: list(str) :returns: List of levels """ if reference: urn = "{0}:{1}".format(self.urn, reference) else: urn = str(self.urn) if level == -1: level = len(self.citation) xml = self.retriever.getValidReff( level=level, urn=urn ) xml = xmlparser(xml) self._parse_request(xml.xpath("//ti:request", namespaces=XPATH_NAMESPACES)[0]) return [ref.split(":")[-1] for ref in xml.xpath("//ti:reply//ti:urn/text()", namespaces=XPATH_NAMESPACES)]
python
def getValidReff(self, level=1, reference=None): """ Given a resource, CtsText will compute valid reffs :param level: Depth required. If not set, should retrieve first encountered level (1 based) :type level: Int :param reference: CapitainsCtsPassage reference :type reference: CtsReference :rtype: list(str) :returns: List of levels """ if reference: urn = "{0}:{1}".format(self.urn, reference) else: urn = str(self.urn) if level == -1: level = len(self.citation) xml = self.retriever.getValidReff( level=level, urn=urn ) xml = xmlparser(xml) self._parse_request(xml.xpath("//ti:request", namespaces=XPATH_NAMESPACES)[0]) return [ref.split(":")[-1] for ref in xml.xpath("//ti:reply//ti:urn/text()", namespaces=XPATH_NAMESPACES)]
[ "def", "getValidReff", "(", "self", ",", "level", "=", "1", ",", "reference", "=", "None", ")", ":", "if", "reference", ":", "urn", "=", "\"{0}:{1}\"", ".", "format", "(", "self", ".", "urn", ",", "reference", ")", "else", ":", "urn", "=", "str", "(", "self", ".", "urn", ")", "if", "level", "==", "-", "1", ":", "level", "=", "len", "(", "self", ".", "citation", ")", "xml", "=", "self", ".", "retriever", ".", "getValidReff", "(", "level", "=", "level", ",", "urn", "=", "urn", ")", "xml", "=", "xmlparser", "(", "xml", ")", "self", ".", "_parse_request", "(", "xml", ".", "xpath", "(", "\"//ti:request\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "[", "0", "]", ")", "return", "[", "ref", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", "for", "ref", "in", "xml", ".", "xpath", "(", "\"//ti:reply//ti:urn/text()\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "]" ]
Given a resource, CtsText will compute valid reffs :param level: Depth required. If not set, should retrieve first encountered level (1 based) :type level: Int :param reference: CapitainsCtsPassage reference :type reference: CtsReference :rtype: list(str) :returns: List of levels
[ "Given", "a", "resource", "CtsText", "will", "compute", "valid", "reffs" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L63-L88
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.getTextualNode
def getTextualNode(self, subreference=None): """ Retrieve a passage and store it in the object :param subreference: CtsReference of the passage (Note : if given a list, this should be a list of string that \ compose the reference) :type subreference: Union[CtsReference, URN, str, list] :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list or a CtsReference """ if isinstance(subreference, URN): urn = str(subreference) elif isinstance(subreference, CtsReference): urn = "{0}:{1}".format(self.urn, str(subreference)) elif isinstance(subreference, str): if ":" in subreference: urn = subreference else: urn = "{0}:{1}".format(self.urn.upTo(URN.NO_PASSAGE), subreference) elif isinstance(subreference, list): urn = "{0}:{1}".format(self.urn, ".".join(subreference)) else: urn = str(self.urn) response = xmlparser(self.retriever.getPassage(urn=urn)) self._parse_request(response.xpath("//ti:request", namespaces=XPATH_NAMESPACES)[0]) return CtsPassage(urn=urn, resource=response, retriever=self.retriever)
python
def getTextualNode(self, subreference=None): """ Retrieve a passage and store it in the object :param subreference: CtsReference of the passage (Note : if given a list, this should be a list of string that \ compose the reference) :type subreference: Union[CtsReference, URN, str, list] :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list or a CtsReference """ if isinstance(subreference, URN): urn = str(subreference) elif isinstance(subreference, CtsReference): urn = "{0}:{1}".format(self.urn, str(subreference)) elif isinstance(subreference, str): if ":" in subreference: urn = subreference else: urn = "{0}:{1}".format(self.urn.upTo(URN.NO_PASSAGE), subreference) elif isinstance(subreference, list): urn = "{0}:{1}".format(self.urn, ".".join(subreference)) else: urn = str(self.urn) response = xmlparser(self.retriever.getPassage(urn=urn)) self._parse_request(response.xpath("//ti:request", namespaces=XPATH_NAMESPACES)[0]) return CtsPassage(urn=urn, resource=response, retriever=self.retriever)
[ "def", "getTextualNode", "(", "self", ",", "subreference", "=", "None", ")", ":", "if", "isinstance", "(", "subreference", ",", "URN", ")", ":", "urn", "=", "str", "(", "subreference", ")", "elif", "isinstance", "(", "subreference", ",", "CtsReference", ")", ":", "urn", "=", "\"{0}:{1}\"", ".", "format", "(", "self", ".", "urn", ",", "str", "(", "subreference", ")", ")", "elif", "isinstance", "(", "subreference", ",", "str", ")", ":", "if", "\":\"", "in", "subreference", ":", "urn", "=", "subreference", "else", ":", "urn", "=", "\"{0}:{1}\"", ".", "format", "(", "self", ".", "urn", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", ",", "subreference", ")", "elif", "isinstance", "(", "subreference", ",", "list", ")", ":", "urn", "=", "\"{0}:{1}\"", ".", "format", "(", "self", ".", "urn", ",", "\".\"", ".", "join", "(", "subreference", ")", ")", "else", ":", "urn", "=", "str", "(", "self", ".", "urn", ")", "response", "=", "xmlparser", "(", "self", ".", "retriever", ".", "getPassage", "(", "urn", "=", "urn", ")", ")", "self", ".", "_parse_request", "(", "response", ".", "xpath", "(", "\"//ti:request\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "[", "0", "]", ")", "return", "CtsPassage", "(", "urn", "=", "urn", ",", "resource", "=", "response", ",", "retriever", "=", "self", ".", "retriever", ")" ]
Retrieve a passage and store it in the object :param subreference: CtsReference of the passage (Note : if given a list, this should be a list of string that \ compose the reference) :type subreference: Union[CtsReference, URN, str, list] :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list or a CtsReference
[ "Retrieve", "a", "passage", "and", "store", "it", "in", "the", "object" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L90-L117
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.getPassagePlus
def getPassagePlus(self, reference=None): """ Retrieve a passage and informations around it and store it in the object :param reference: Reference of the passage :type reference: CtsReference or List of text_type :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list or a Reference """ if reference: urn = "{0}:{1}".format(self.urn, reference) else: urn = str(self.urn) response = xmlparser(self.retriever.getPassagePlus(urn=urn)) passage = CtsPassage(urn=urn, resource=response, retriever=self.retriever) passage._parse_request(response.xpath("//ti:reply/ti:label", namespaces=XPATH_NAMESPACES)[0]) self.citation = passage.citation return passage
python
def getPassagePlus(self, reference=None): """ Retrieve a passage and informations around it and store it in the object :param reference: Reference of the passage :type reference: CtsReference or List of text_type :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list or a Reference """ if reference: urn = "{0}:{1}".format(self.urn, reference) else: urn = str(self.urn) response = xmlparser(self.retriever.getPassagePlus(urn=urn)) passage = CtsPassage(urn=urn, resource=response, retriever=self.retriever) passage._parse_request(response.xpath("//ti:reply/ti:label", namespaces=XPATH_NAMESPACES)[0]) self.citation = passage.citation return passage
[ "def", "getPassagePlus", "(", "self", ",", "reference", "=", "None", ")", ":", "if", "reference", ":", "urn", "=", "\"{0}:{1}\"", ".", "format", "(", "self", ".", "urn", ",", "reference", ")", "else", ":", "urn", "=", "str", "(", "self", ".", "urn", ")", "response", "=", "xmlparser", "(", "self", ".", "retriever", ".", "getPassagePlus", "(", "urn", "=", "urn", ")", ")", "passage", "=", "CtsPassage", "(", "urn", "=", "urn", ",", "resource", "=", "response", ",", "retriever", "=", "self", ".", "retriever", ")", "passage", ".", "_parse_request", "(", "response", ".", "xpath", "(", "\"//ti:reply/ti:label\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "[", "0", "]", ")", "self", ".", "citation", "=", "passage", ".", "citation", "return", "passage" ]
Retrieve a passage and informations around it and store it in the object :param reference: Reference of the passage :type reference: CtsReference or List of text_type :rtype: CtsPassage :returns: Object representing the passage :raises: *TypeError* when reference is not a list or a Reference
[ "Retrieve", "a", "passage", "and", "informations", "around", "it", "and", "store", "it", "in", "the", "object" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L134-L153
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod._parse_request
def _parse_request(self, xml): """ Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element] """ for node in xml.xpath(".//ti:groupname", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.groupname, lang=lang, value=node.text) self.set_creator(node.text, lang) for node in xml.xpath(".//ti:title", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.title, lang=lang, value=node.text) self.set_title(node.text, lang) for node in xml.xpath(".//ti:label", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.label, lang=lang, value=node.text) self.set_subject(node.text, lang) for node in xml.xpath(".//ti:description", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.description, lang=lang, value=node.text) self.set_description(node.text, lang) # Need to code that p if not self.citation.is_set() and xml.xpath("//ti:citation", namespaces=XPATH_NAMESPACES): self.citation = CtsCollection.XmlCtsCitation.ingest( xml, xpath=".//ti:citation[not(ancestor::ti:citation)]" )
python
def _parse_request(self, xml): """ Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element] """ for node in xml.xpath(".//ti:groupname", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.groupname, lang=lang, value=node.text) self.set_creator(node.text, lang) for node in xml.xpath(".//ti:title", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.title, lang=lang, value=node.text) self.set_title(node.text, lang) for node in xml.xpath(".//ti:label", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.label, lang=lang, value=node.text) self.set_subject(node.text, lang) for node in xml.xpath(".//ti:description", namespaces=XPATH_NAMESPACES): lang = node.get("xml:lang") or CtsText.DEFAULT_LANG self.metadata.add(RDF_NAMESPACES.CTS.description, lang=lang, value=node.text) self.set_description(node.text, lang) # Need to code that p if not self.citation.is_set() and xml.xpath("//ti:citation", namespaces=XPATH_NAMESPACES): self.citation = CtsCollection.XmlCtsCitation.ingest( xml, xpath=".//ti:citation[not(ancestor::ti:citation)]" )
[ "def", "_parse_request", "(", "self", ",", "xml", ")", ":", "for", "node", "in", "xml", ".", "xpath", "(", "\".//ti:groupname\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lang", "=", "node", ".", "get", "(", "\"xml:lang\"", ")", "or", "CtsText", ".", "DEFAULT_LANG", "self", ".", "metadata", ".", "add", "(", "RDF_NAMESPACES", ".", "CTS", ".", "groupname", ",", "lang", "=", "lang", ",", "value", "=", "node", ".", "text", ")", "self", ".", "set_creator", "(", "node", ".", "text", ",", "lang", ")", "for", "node", "in", "xml", ".", "xpath", "(", "\".//ti:title\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lang", "=", "node", ".", "get", "(", "\"xml:lang\"", ")", "or", "CtsText", ".", "DEFAULT_LANG", "self", ".", "metadata", ".", "add", "(", "RDF_NAMESPACES", ".", "CTS", ".", "title", ",", "lang", "=", "lang", ",", "value", "=", "node", ".", "text", ")", "self", ".", "set_title", "(", "node", ".", "text", ",", "lang", ")", "for", "node", "in", "xml", ".", "xpath", "(", "\".//ti:label\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lang", "=", "node", ".", "get", "(", "\"xml:lang\"", ")", "or", "CtsText", ".", "DEFAULT_LANG", "self", ".", "metadata", ".", "add", "(", "RDF_NAMESPACES", ".", "CTS", ".", "label", ",", "lang", "=", "lang", ",", "value", "=", "node", ".", "text", ")", "self", ".", "set_subject", "(", "node", ".", "text", ",", "lang", ")", "for", "node", "in", "xml", ".", "xpath", "(", "\".//ti:description\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lang", "=", "node", ".", "get", "(", "\"xml:lang\"", ")", "or", "CtsText", ".", "DEFAULT_LANG", "self", ".", "metadata", ".", "add", "(", "RDF_NAMESPACES", ".", "CTS", ".", "description", ",", "lang", "=", "lang", ",", "value", "=", "node", ".", "text", ")", "self", ".", "set_description", "(", "node", ".", "text", ",", "lang", ")", "# Need to code that p", "if", "not", "self", ".", "citation", ".", "is_set", "(", ")", "and", "xml", ".", "xpath", "(", "\"//ti:citation\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "self", ".", "citation", "=", "CtsCollection", ".", "XmlCtsCitation", ".", "ingest", "(", "xml", ",", "xpath", "=", "\".//ti:citation[not(ancestor::ti:citation)]\"", ")" ]
Parse a request with metadata information :param xml: LXML Object :type xml: Union[lxml.etree._Element]
[ "Parse", "a", "request", "with", "metadata", "information" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L155-L186
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.getLabel
def getLabel(self): """ Retrieve metadata about the text :rtype: Metadata :returns: Dictionary with label informations """ response = xmlparser( self.retriever.getLabel(urn=str(self.urn)) ) self._parse_request( response.xpath("//ti:reply/ti:label", namespaces=XPATH_NAMESPACES)[0] ) return self.metadata
python
def getLabel(self): """ Retrieve metadata about the text :rtype: Metadata :returns: Dictionary with label informations """ response = xmlparser( self.retriever.getLabel(urn=str(self.urn)) ) self._parse_request( response.xpath("//ti:reply/ti:label", namespaces=XPATH_NAMESPACES)[0] ) return self.metadata
[ "def", "getLabel", "(", "self", ")", ":", "response", "=", "xmlparser", "(", "self", ".", "retriever", ".", "getLabel", "(", "urn", "=", "str", "(", "self", ".", "urn", ")", ")", ")", "self", ".", "_parse_request", "(", "response", ".", "xpath", "(", "\"//ti:reply/ti:label\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "[", "0", "]", ")", "return", "self", ".", "metadata" ]
Retrieve metadata about the text :rtype: Metadata :returns: Dictionary with label informations
[ "Retrieve", "metadata", "about", "the", "text" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L188-L202
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.getPrevNextUrn
def getPrevNextUrn(self, reference): """ Get the previous URN of a reference of the text :param reference: CtsReference from which to find siblings :type reference: Union[CtsReference, str] :return: (Previous CapitainsCtsPassage CtsReference,Next CapitainsCtsPassage CtsReference) """ _prev, _next = _SharedMethod.prevnext( self.retriever.getPrevNextUrn( urn="{}:{}".format( str( URN( str(self.urn)).upTo(URN.NO_PASSAGE) ), str(reference) ) ) ) return _prev, _next
python
def getPrevNextUrn(self, reference): """ Get the previous URN of a reference of the text :param reference: CtsReference from which to find siblings :type reference: Union[CtsReference, str] :return: (Previous CapitainsCtsPassage CtsReference,Next CapitainsCtsPassage CtsReference) """ _prev, _next = _SharedMethod.prevnext( self.retriever.getPrevNextUrn( urn="{}:{}".format( str( URN( str(self.urn)).upTo(URN.NO_PASSAGE) ), str(reference) ) ) ) return _prev, _next
[ "def", "getPrevNextUrn", "(", "self", ",", "reference", ")", ":", "_prev", ",", "_next", "=", "_SharedMethod", ".", "prevnext", "(", "self", ".", "retriever", ".", "getPrevNextUrn", "(", "urn", "=", "\"{}:{}\"", ".", "format", "(", "str", "(", "URN", "(", "str", "(", "self", ".", "urn", ")", ")", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", ")", ",", "str", "(", "reference", ")", ")", ")", ")", "return", "_prev", ",", "_next" ]
Get the previous URN of a reference of the text :param reference: CtsReference from which to find siblings :type reference: Union[CtsReference, str] :return: (Previous CapitainsCtsPassage CtsReference,Next CapitainsCtsPassage CtsReference)
[ "Get", "the", "previous", "URN", "of", "a", "reference", "of", "the", "text" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L204-L222
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.getFirstUrn
def getFirstUrn(self, reference=None): """ Get the first children URN for a given resource :param reference: CtsReference from which to find child (If None, find first reference) :type reference: CtsReference, str :return: Children URN :rtype: URN """ if reference is not None: if ":" in reference: urn = reference else: urn = "{}:{}".format( str(URN(str(self.urn)).upTo(URN.NO_PASSAGE)), str(reference) ) else: urn = str(self.urn) _first = _SharedMethod.firstUrn( self.retriever.getFirstUrn( urn ) ) return _first
python
def getFirstUrn(self, reference=None): """ Get the first children URN for a given resource :param reference: CtsReference from which to find child (If None, find first reference) :type reference: CtsReference, str :return: Children URN :rtype: URN """ if reference is not None: if ":" in reference: urn = reference else: urn = "{}:{}".format( str(URN(str(self.urn)).upTo(URN.NO_PASSAGE)), str(reference) ) else: urn = str(self.urn) _first = _SharedMethod.firstUrn( self.retriever.getFirstUrn( urn ) ) return _first
[ "def", "getFirstUrn", "(", "self", ",", "reference", "=", "None", ")", ":", "if", "reference", "is", "not", "None", ":", "if", "\":\"", "in", "reference", ":", "urn", "=", "reference", "else", ":", "urn", "=", "\"{}:{}\"", ".", "format", "(", "str", "(", "URN", "(", "str", "(", "self", ".", "urn", ")", ")", ".", "upTo", "(", "URN", ".", "NO_PASSAGE", ")", ")", ",", "str", "(", "reference", ")", ")", "else", ":", "urn", "=", "str", "(", "self", ".", "urn", ")", "_first", "=", "_SharedMethod", ".", "firstUrn", "(", "self", ".", "retriever", ".", "getFirstUrn", "(", "urn", ")", ")", "return", "_first" ]
Get the first children URN for a given resource :param reference: CtsReference from which to find child (If None, find first reference) :type reference: CtsReference, str :return: Children URN :rtype: URN
[ "Get", "the", "first", "children", "URN", "for", "a", "given", "resource" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L224-L247
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.firstUrn
def firstUrn(resource): """ Parse a resource to get the first URN :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: str """ resource = xmlparser(resource) urn = resource.xpath("//ti:reply/ti:urn/text()", namespaces=XPATH_NAMESPACES, magic_string=True) if len(urn) > 0: urn = str(urn[0]) return urn.split(":")[-1]
python
def firstUrn(resource): """ Parse a resource to get the first URN :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: str """ resource = xmlparser(resource) urn = resource.xpath("//ti:reply/ti:urn/text()", namespaces=XPATH_NAMESPACES, magic_string=True) if len(urn) > 0: urn = str(urn[0]) return urn.split(":")[-1]
[ "def", "firstUrn", "(", "resource", ")", ":", "resource", "=", "xmlparser", "(", "resource", ")", "urn", "=", "resource", ".", "xpath", "(", "\"//ti:reply/ti:urn/text()\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ",", "magic_string", "=", "True", ")", "if", "len", "(", "urn", ")", ">", "0", ":", "urn", "=", "str", "(", "urn", "[", "0", "]", ")", "return", "urn", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]" ]
Parse a resource to get the first URN :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: str
[ "Parse", "a", "resource", "to", "get", "the", "first", "URN" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L274-L287
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
_SharedMethod.prevnext
def prevnext(resource): """ Parse a resource to get the prev and next urn :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: (str, str) """ _prev, _next = False, False resource = xmlparser(resource) prevnext = resource.xpath("//ti:prevnext", namespaces=XPATH_NAMESPACES) if len(prevnext) > 0: _next, _prev = None, None prevnext = prevnext[0] _next_xpath = prevnext.xpath("ti:next/ti:urn/text()", namespaces=XPATH_NAMESPACES, smart_strings=False) _prev_xpath = prevnext.xpath("ti:prev/ti:urn/text()", namespaces=XPATH_NAMESPACES, smart_strings=False) if len(_next_xpath): _next = _next_xpath[0].split(":")[-1] if len(_prev_xpath): _prev = _prev_xpath[0].split(":")[-1] return _prev, _next
python
def prevnext(resource): """ Parse a resource to get the prev and next urn :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: (str, str) """ _prev, _next = False, False resource = xmlparser(resource) prevnext = resource.xpath("//ti:prevnext", namespaces=XPATH_NAMESPACES) if len(prevnext) > 0: _next, _prev = None, None prevnext = prevnext[0] _next_xpath = prevnext.xpath("ti:next/ti:urn/text()", namespaces=XPATH_NAMESPACES, smart_strings=False) _prev_xpath = prevnext.xpath("ti:prev/ti:urn/text()", namespaces=XPATH_NAMESPACES, smart_strings=False) if len(_next_xpath): _next = _next_xpath[0].split(":")[-1] if len(_prev_xpath): _prev = _prev_xpath[0].split(":")[-1] return _prev, _next
[ "def", "prevnext", "(", "resource", ")", ":", "_prev", ",", "_next", "=", "False", ",", "False", "resource", "=", "xmlparser", "(", "resource", ")", "prevnext", "=", "resource", ".", "xpath", "(", "\"//ti:prevnext\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "if", "len", "(", "prevnext", ")", ">", "0", ":", "_next", ",", "_prev", "=", "None", ",", "None", "prevnext", "=", "prevnext", "[", "0", "]", "_next_xpath", "=", "prevnext", ".", "xpath", "(", "\"ti:next/ti:urn/text()\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ",", "smart_strings", "=", "False", ")", "_prev_xpath", "=", "prevnext", ".", "xpath", "(", "\"ti:prev/ti:urn/text()\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ",", "smart_strings", "=", "False", ")", "if", "len", "(", "_next_xpath", ")", ":", "_next", "=", "_next_xpath", "[", "0", "]", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", "if", "len", "(", "_prev_xpath", ")", ":", "_prev", "=", "_prev_xpath", "[", "0", "]", ".", "split", "(", "\":\"", ")", "[", "-", "1", "]", "return", "_prev", ",", "_next" ]
Parse a resource to get the prev and next urn :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: (str, str)
[ "Parse", "a", "resource", "to", "get", "the", "prev", "and", "next", "urn" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L290-L314
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
CtsPassage.prevId
def prevId(self): """ Previous passage Identifier :rtype: CtsPassage :returns: Previous passage at same level """ if self._prev_id is False: # Request the next urn self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._prev_id
python
def prevId(self): """ Previous passage Identifier :rtype: CtsPassage :returns: Previous passage at same level """ if self._prev_id is False: # Request the next urn self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._prev_id
[ "def", "prevId", "(", "self", ")", ":", "if", "self", ".", "_prev_id", "is", "False", ":", "# Request the next urn", "self", ".", "_prev_id", ",", "self", ".", "_next_id", "=", "self", ".", "getPrevNextUrn", "(", "reference", "=", "self", ".", "urn", ".", "reference", ")", "return", "self", ".", "_prev_id" ]
Previous passage Identifier :rtype: CtsPassage :returns: Previous passage at same level
[ "Previous", "passage", "Identifier" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L410-L419
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
CtsPassage.nextId
def nextId(self): """ Shortcut for getting the following passage identifier :rtype: CtsReference :returns: Following passage reference """ if self._next_id is False: # Request the next urn self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._next_id
python
def nextId(self): """ Shortcut for getting the following passage identifier :rtype: CtsReference :returns: Following passage reference """ if self._next_id is False: # Request the next urn self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._next_id
[ "def", "nextId", "(", "self", ")", ":", "if", "self", ".", "_next_id", "is", "False", ":", "# Request the next urn", "self", ".", "_prev_id", ",", "self", ".", "_next_id", "=", "self", ".", "getPrevNextUrn", "(", "reference", "=", "self", ".", "urn", ".", "reference", ")", "return", "self", ".", "_next_id" ]
Shortcut for getting the following passage identifier :rtype: CtsReference :returns: Following passage reference
[ "Shortcut", "for", "getting", "the", "following", "passage", "identifier" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L431-L440
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
CtsPassage.siblingsId
def siblingsId(self): """ Shortcut for getting the previous and next passage identifier :rtype: CtsReference :returns: Following passage reference """ if self._next_id is False or self._prev_id is False: self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._prev_id, self._next_id
python
def siblingsId(self): """ Shortcut for getting the previous and next passage identifier :rtype: CtsReference :returns: Following passage reference """ if self._next_id is False or self._prev_id is False: self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference) return self._prev_id, self._next_id
[ "def", "siblingsId", "(", "self", ")", ":", "if", "self", ".", "_next_id", "is", "False", "or", "self", ".", "_prev_id", "is", "False", ":", "self", ".", "_prev_id", ",", "self", ".", "_next_id", "=", "self", ".", "getPrevNextUrn", "(", "reference", "=", "self", ".", "urn", ".", "reference", ")", "return", "self", ".", "_prev_id", ",", "self", ".", "_next_id" ]
Shortcut for getting the previous and next passage identifier :rtype: CtsReference :returns: Following passage reference
[ "Shortcut", "for", "getting", "the", "previous", "and", "next", "passage", "identifier" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L443-L451
train
Capitains/MyCapytain
MyCapytain/resources/texts/remote/cts.py
CtsPassage._parse
def _parse(self): """ Given self.resource, split information from the CTS API :return: None """ self.response = self.resource self.resource = self.resource.xpath("//ti:passage/tei:TEI", namespaces=XPATH_NAMESPACES)[0] self._prev_id, self._next_id = _SharedMethod.prevnext(self.response) if not self.citation.is_set() and len(self.resource.xpath("//ti:citation", namespaces=XPATH_NAMESPACES)): self.citation = CtsCollection.XmlCtsCitation.ingest( self.response, xpath=".//ti:citation[not(ancestor::ti:citation)]" )
python
def _parse(self): """ Given self.resource, split information from the CTS API :return: None """ self.response = self.resource self.resource = self.resource.xpath("//ti:passage/tei:TEI", namespaces=XPATH_NAMESPACES)[0] self._prev_id, self._next_id = _SharedMethod.prevnext(self.response) if not self.citation.is_set() and len(self.resource.xpath("//ti:citation", namespaces=XPATH_NAMESPACES)): self.citation = CtsCollection.XmlCtsCitation.ingest( self.response, xpath=".//ti:citation[not(ancestor::ti:citation)]" )
[ "def", "_parse", "(", "self", ")", ":", "self", ".", "response", "=", "self", ".", "resource", "self", ".", "resource", "=", "self", ".", "resource", ".", "xpath", "(", "\"//ti:passage/tei:TEI\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "[", "0", "]", "self", ".", "_prev_id", ",", "self", ".", "_next_id", "=", "_SharedMethod", ".", "prevnext", "(", "self", ".", "response", ")", "if", "not", "self", ".", "citation", ".", "is_set", "(", ")", "and", "len", "(", "self", ".", "resource", ".", "xpath", "(", "\"//ti:citation\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ")", ":", "self", ".", "citation", "=", "CtsCollection", ".", "XmlCtsCitation", ".", "ingest", "(", "self", ".", "response", ",", "xpath", "=", "\".//ti:citation[not(ancestor::ti:citation)]\"", ")" ]
Given self.resource, split information from the CTS API :return: None
[ "Given", "self", ".", "resource", "split", "information", "from", "the", "CTS", "API" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/texts/remote/cts.py#L453-L467
train
exosite-labs/pyonep
pyonep/portals/endpoints.py
Endpoints.get_user_token
def get_user_token(self): """ Gets a authorization token for session reuse. http://docs.exosite.com/portals/#get-user-token-for-openid-user """ headers = { 'User-Agent': self.user_agent(), 'Host': self.domain(), 'Accept': '*/*', } headers.update(self.headers()) r = requests.get( self.portals_url()+'/users/_this/token', headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.text else: print("get_user_token: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
python
def get_user_token(self): """ Gets a authorization token for session reuse. http://docs.exosite.com/portals/#get-user-token-for-openid-user """ headers = { 'User-Agent': self.user_agent(), 'Host': self.domain(), 'Accept': '*/*', } headers.update(self.headers()) r = requests.get( self.portals_url()+'/users/_this/token', headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.text else: print("get_user_token: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
[ "def", "get_user_token", "(", "self", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "'Host'", ":", "self", ".", "domain", "(", ")", ",", "'Accept'", ":", "'*/*'", ",", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", ".", "get", "(", "self", ".", "portals_url", "(", ")", "+", "'/users/_this/token'", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "OK", "==", "r", ".", "status_code", ":", "return", "r", ".", "text", "else", ":", "print", "(", "\"get_user_token: Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "r", ".", "raise_for_status", "(", ")" ]
Gets a authorization token for session reuse. http://docs.exosite.com/portals/#get-user-token-for-openid-user
[ "Gets", "a", "authorization", "token", "for", "session", "reuse", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/endpoints.py#L125-L144
train
exosite-labs/pyonep
pyonep/portals/endpoints.py
Endpoints.add_device
def add_device(self, model, serial): """ Returns 'device object' of newly created device. http://docs.exosite.com/portals/#create-device http://docs.exosite.com/portals/#device-object """ device = { 'model': model, 'vendor': self.vendor(), 'sn': serial, 'type': 'vendor' } headers = { 'User-Agent': self.user_agent(), } headers.update(self.headers()) r = requests.post( self.portals_url()+'/portals/'+self.portal_id()+'/devices', data=json.dumps(device), headers=headers, auth=self.auth()) if HTTP_STATUS.ADDED == r.status_code: # fix the 'meta' to be dictionary instead of string device_obj = r.json() return dictify_device_meta(device_obj) else: print("add_device: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
python
def add_device(self, model, serial): """ Returns 'device object' of newly created device. http://docs.exosite.com/portals/#create-device http://docs.exosite.com/portals/#device-object """ device = { 'model': model, 'vendor': self.vendor(), 'sn': serial, 'type': 'vendor' } headers = { 'User-Agent': self.user_agent(), } headers.update(self.headers()) r = requests.post( self.portals_url()+'/portals/'+self.portal_id()+'/devices', data=json.dumps(device), headers=headers, auth=self.auth()) if HTTP_STATUS.ADDED == r.status_code: # fix the 'meta' to be dictionary instead of string device_obj = r.json() return dictify_device_meta(device_obj) else: print("add_device: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
[ "def", "add_device", "(", "self", ",", "model", ",", "serial", ")", ":", "device", "=", "{", "'model'", ":", "model", ",", "'vendor'", ":", "self", ".", "vendor", "(", ")", ",", "'sn'", ":", "serial", ",", "'type'", ":", "'vendor'", "}", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", ".", "post", "(", "self", ".", "portals_url", "(", ")", "+", "'/portals/'", "+", "self", ".", "portal_id", "(", ")", "+", "'/devices'", ",", "data", "=", "json", ".", "dumps", "(", "device", ")", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "ADDED", "==", "r", ".", "status_code", ":", "# fix the 'meta' to be dictionary instead of string", "device_obj", "=", "r", ".", "json", "(", ")", "return", "dictify_device_meta", "(", "device_obj", ")", "else", ":", "print", "(", "\"add_device: Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "r", ".", "raise_for_status", "(", ")" ]
Returns 'device object' of newly created device. http://docs.exosite.com/portals/#create-device http://docs.exosite.com/portals/#device-object
[ "Returns", "device", "object", "of", "newly", "created", "device", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/endpoints.py#L212-L242
train
exosite-labs/pyonep
pyonep/portals/endpoints.py
Endpoints.update_portal
def update_portal(self, portal_obj): """ Implements the Update device Portals API. This function is extremely dangerous. The portal object you pass in will completely overwrite the portal. http://docs.exosite.com/portals/#update-portal """ headers = { 'User-Agent': self.user_agent(), } headers.update(self.headers()) r = requests.put( self.portals_url()+'/portals/'+self.portal_id(), data=json.dumps(portal_obj), headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.json() else: print("update_portal: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
python
def update_portal(self, portal_obj): """ Implements the Update device Portals API. This function is extremely dangerous. The portal object you pass in will completely overwrite the portal. http://docs.exosite.com/portals/#update-portal """ headers = { 'User-Agent': self.user_agent(), } headers.update(self.headers()) r = requests.put( self.portals_url()+'/portals/'+self.portal_id(), data=json.dumps(portal_obj), headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.json() else: print("update_portal: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
[ "def", "update_portal", "(", "self", ",", "portal_obj", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", ".", "put", "(", "self", ".", "portals_url", "(", ")", "+", "'/portals/'", "+", "self", ".", "portal_id", "(", ")", ",", "data", "=", "json", ".", "dumps", "(", "portal_obj", ")", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "OK", "==", "r", ".", "status_code", ":", "return", "r", ".", "json", "(", ")", "else", ":", "print", "(", "\"update_portal: Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "r", ".", "raise_for_status", "(", ")" ]
Implements the Update device Portals API. This function is extremely dangerous. The portal object you pass in will completely overwrite the portal. http://docs.exosite.com/portals/#update-portal
[ "Implements", "the", "Update", "device", "Portals", "API", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/endpoints.py#L272-L294
train
exosite-labs/pyonep
pyonep/portals/endpoints.py
Endpoints.get_device
def get_device(self, rid): """ Retrieve the device object for a given RID. http://docs.exosite.com/portals/#get-device """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) url = self.portals_url()+'/devices/'+rid # print("URL: {0}".format(url)) r = requests.get( url, headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: # fix the 'meta' to be dictionary instead of string device_obj = r.json() # device_obj['info']['description']['meta'] = \ # json.loads(device_obj['info']['description']['meta']) return device_obj else: print("get_device: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
python
def get_device(self, rid): """ Retrieve the device object for a given RID. http://docs.exosite.com/portals/#get-device """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) url = self.portals_url()+'/devices/'+rid # print("URL: {0}".format(url)) r = requests.get( url, headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: # fix the 'meta' to be dictionary instead of string device_obj = r.json() # device_obj['info']['description']['meta'] = \ # json.loads(device_obj['info']['description']['meta']) return device_obj else: print("get_device: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
[ "def", "get_device", "(", "self", ",", "rid", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "'Content-Type'", ":", "self", ".", "content_type", "(", ")", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "url", "=", "self", ".", "portals_url", "(", ")", "+", "'/devices/'", "+", "rid", "# print(\"URL: {0}\".format(url))", "r", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "OK", "==", "r", ".", "status_code", ":", "# fix the 'meta' to be dictionary instead of string", "device_obj", "=", "r", ".", "json", "(", ")", "# device_obj['info']['description']['meta'] = \\", "# json.loads(device_obj['info']['description']['meta'])", "return", "device_obj", "else", ":", "print", "(", "\"get_device: Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "r", ".", "raise_for_status", "(", ")" ]
Retrieve the device object for a given RID. http://docs.exosite.com/portals/#get-device
[ "Retrieve", "the", "device", "object", "for", "a", "given", "RID", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/endpoints.py#L296-L324
train
exosite-labs/pyonep
pyonep/portals/endpoints.py
Endpoints.get_multiple_devices
def get_multiple_devices(self, rids): """ Implements the 'Get Multiple Devices' API. Param rids: a python list object of device rids. http://docs.exosite.com/portals/#get-multiple-devices """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) url = self.portals_url()+'/users/_this/devices/' + str(rids).replace("'", "").replace(' ','') # print("URL: {0}".format(url)) r = requests.get( url, headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: # TODO: loop through all rids and fix 'meta' to be dict like add_device and get_device do return r.json() else: print("get_multiple_devices: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
python
def get_multiple_devices(self, rids): """ Implements the 'Get Multiple Devices' API. Param rids: a python list object of device rids. http://docs.exosite.com/portals/#get-multiple-devices """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) url = self.portals_url()+'/users/_this/devices/' + str(rids).replace("'", "").replace(' ','') # print("URL: {0}".format(url)) r = requests.get( url, headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: # TODO: loop through all rids and fix 'meta' to be dict like add_device and get_device do return r.json() else: print("get_multiple_devices: Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status()
[ "def", "get_multiple_devices", "(", "self", ",", "rids", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "'Content-Type'", ":", "self", ".", "content_type", "(", ")", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "url", "=", "self", ".", "portals_url", "(", ")", "+", "'/users/_this/devices/'", "+", "str", "(", "rids", ")", ".", "replace", "(", "\"'\"", ",", "\"\"", ")", ".", "replace", "(", "' '", ",", "''", ")", "# print(\"URL: {0}\".format(url))", "r", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "OK", "==", "r", ".", "status_code", ":", "# TODO: loop through all rids and fix 'meta' to be dict like add_device and get_device do", "return", "r", ".", "json", "(", ")", "else", ":", "print", "(", "\"get_multiple_devices: Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "r", ".", "raise_for_status", "(", ")" ]
Implements the 'Get Multiple Devices' API. Param rids: a python list object of device rids. http://docs.exosite.com/portals/#get-multiple-devices
[ "Implements", "the", "Get", "Multiple", "Devices", "API", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/endpoints.py#L326-L352
train
SHDShim/pytheos
pytheos/eqn_therm_Dorogokupets2015.py
dorogokupets2015_pth
def dorogokupets2015_pth(v, temp, v0, gamma0, gamma_inf, beta, theta01, m1, theta02, m2, n, z, t_ref=300., three_r=3. * constants.R): """ calculate thermal pressure for Dorogokupets 2015 EOS :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param gamma_inf: Gruneisen parameter at infinite pressure :param beta: volume dependence of Gruneisen parameter :param theta01: Debye temperature at 1 bar in K :param m1: weighting factor, see Dorogokupets 2015 for detail :param theta02: Debye temperature at 1 bar in K :param m2: weighting factor, see Dorogokupets 2015 for detail :param n: number of elements in a chemical formula :param z: number of formula unit in a unit cell :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :return: thermal pressure in GPa """ # x = v / v0 # a = a0 * np.power(x, m) v_mol = vol_uc2mol(v, z) gamma = altshuler_grun(v, v0, gamma0, gamma_inf, beta) theta1 = altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta01) theta2 = altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta02) if isuncertainties([v, temp, v0, gamma0, gamma_inf, beta, theta01, m1, theta02, m2]): term_h1 = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (unp.exp(theta1 / temp) - 1.)) term_h2 = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (unp.exp(theta2 / temp) - 1.)) term_h1_ref = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (unp.exp(theta1 / t_ref) - 1.)) term_h2_ref = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (unp.exp(theta2 / t_ref) - 1.)) else: term_h1 = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (np.exp(theta1 / temp) - 1.)) term_h2 = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (np.exp(theta2 / temp) - 1.)) term_h1_ref = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (np.exp(theta1 / t_ref) - 1.)) term_h2_ref = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (np.exp(theta2 / t_ref) - 1.)) p_th = term_h1 * 1.e-9 + term_h2 * 1.e-9 p_th_ref = term_h1_ref * 1.e-9 + term_h2_ref * 1.e-9 return (p_th - p_th_ref)
python
def dorogokupets2015_pth(v, temp, v0, gamma0, gamma_inf, beta, theta01, m1, theta02, m2, n, z, t_ref=300., three_r=3. * constants.R): """ calculate thermal pressure for Dorogokupets 2015 EOS :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param gamma_inf: Gruneisen parameter at infinite pressure :param beta: volume dependence of Gruneisen parameter :param theta01: Debye temperature at 1 bar in K :param m1: weighting factor, see Dorogokupets 2015 for detail :param theta02: Debye temperature at 1 bar in K :param m2: weighting factor, see Dorogokupets 2015 for detail :param n: number of elements in a chemical formula :param z: number of formula unit in a unit cell :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :return: thermal pressure in GPa """ # x = v / v0 # a = a0 * np.power(x, m) v_mol = vol_uc2mol(v, z) gamma = altshuler_grun(v, v0, gamma0, gamma_inf, beta) theta1 = altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta01) theta2 = altshuler_debyetemp(v, v0, gamma0, gamma_inf, beta, theta02) if isuncertainties([v, temp, v0, gamma0, gamma_inf, beta, theta01, m1, theta02, m2]): term_h1 = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (unp.exp(theta1 / temp) - 1.)) term_h2 = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (unp.exp(theta2 / temp) - 1.)) term_h1_ref = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (unp.exp(theta1 / t_ref) - 1.)) term_h2_ref = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (unp.exp(theta2 / t_ref) - 1.)) else: term_h1 = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (np.exp(theta1 / temp) - 1.)) term_h2 = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (np.exp(theta2 / temp) - 1.)) term_h1_ref = m1 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta1 / (np.exp(theta1 / t_ref) - 1.)) term_h2_ref = m2 / (m1 + m2) * three_r * n * gamma / v_mol * \ (theta2 / (np.exp(theta2 / t_ref) - 1.)) p_th = term_h1 * 1.e-9 + term_h2 * 1.e-9 p_th_ref = term_h1_ref * 1.e-9 + term_h2_ref * 1.e-9 return (p_th - p_th_ref)
[ "def", "dorogokupets2015_pth", "(", "v", ",", "temp", ",", "v0", ",", "gamma0", ",", "gamma_inf", ",", "beta", ",", "theta01", ",", "m1", ",", "theta02", ",", "m2", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "# x = v / v0", "# a = a0 * np.power(x, m)", "v_mol", "=", "vol_uc2mol", "(", "v", ",", "z", ")", "gamma", "=", "altshuler_grun", "(", "v", ",", "v0", ",", "gamma0", ",", "gamma_inf", ",", "beta", ")", "theta1", "=", "altshuler_debyetemp", "(", "v", ",", "v0", ",", "gamma0", ",", "gamma_inf", ",", "beta", ",", "theta01", ")", "theta2", "=", "altshuler_debyetemp", "(", "v", ",", "v0", ",", "gamma0", ",", "gamma_inf", ",", "beta", ",", "theta02", ")", "if", "isuncertainties", "(", "[", "v", ",", "temp", ",", "v0", ",", "gamma0", ",", "gamma_inf", ",", "beta", ",", "theta01", ",", "m1", ",", "theta02", ",", "m2", "]", ")", ":", "term_h1", "=", "m1", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta1", "/", "(", "unp", ".", "exp", "(", "theta1", "/", "temp", ")", "-", "1.", ")", ")", "term_h2", "=", "m2", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta2", "/", "(", "unp", ".", "exp", "(", "theta2", "/", "temp", ")", "-", "1.", ")", ")", "term_h1_ref", "=", "m1", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta1", "/", "(", "unp", ".", "exp", "(", "theta1", "/", "t_ref", ")", "-", "1.", ")", ")", "term_h2_ref", "=", "m2", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta2", "/", "(", "unp", ".", "exp", "(", "theta2", "/", "t_ref", ")", "-", "1.", ")", ")", "else", ":", "term_h1", "=", "m1", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta1", "/", "(", "np", ".", "exp", "(", "theta1", "/", "temp", ")", "-", "1.", ")", ")", "term_h2", "=", "m2", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta2", "/", "(", "np", ".", "exp", "(", "theta2", "/", "temp", ")", "-", "1.", ")", ")", "term_h1_ref", "=", "m1", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta1", "/", "(", "np", ".", "exp", "(", "theta1", "/", "t_ref", ")", "-", "1.", ")", ")", "term_h2_ref", "=", "m2", "/", "(", "m1", "+", "m2", ")", "*", "three_r", "*", "n", "*", "gamma", "/", "v_mol", "*", "(", "theta2", "/", "(", "np", ".", "exp", "(", "theta2", "/", "t_ref", ")", "-", "1.", ")", ")", "p_th", "=", "term_h1", "*", "1.e-9", "+", "term_h2", "*", "1.e-9", "p_th_ref", "=", "term_h1_ref", "*", "1.e-9", "+", "term_h2_ref", "*", "1.e-9", "return", "(", "p_th", "-", "p_th_ref", ")" ]
calculate thermal pressure for Dorogokupets 2015 EOS :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param gamma0: Gruneisen parameter at 1 bar :param gamma_inf: Gruneisen parameter at infinite pressure :param beta: volume dependence of Gruneisen parameter :param theta01: Debye temperature at 1 bar in K :param m1: weighting factor, see Dorogokupets 2015 for detail :param theta02: Debye temperature at 1 bar in K :param m2: weighting factor, see Dorogokupets 2015 for detail :param n: number of elements in a chemical formula :param z: number of formula unit in a unit cell :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :return: thermal pressure in GPa
[ "calculate", "thermal", "pressure", "for", "Dorogokupets", "2015", "EOS" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Dorogokupets2015.py#L9-L59
train
Capitains/MyCapytain
MyCapytain/retrievers/dts/__init__.py
HttpDtsRetriever.routes
def routes(self): """ Retrieves the main routes of the DTS Collection Response format expected : { "@context": "/dts/api/contexts/EntryPoint.jsonld", "@id": "/dts/api/", "@type": "EntryPoint", "collections": "/dts/api/collections/", "documents": "/dts/api/documents/", "navigation" : "/dts/api/navigation" } :returns: Dictionary of main routes with their path :rtype: dict """ if self._routes: return self._routes request = requests.get(self.endpoint) request.raise_for_status() data = request.json() self._routes = { "collections": parse_uri(data["collections"], self.endpoint), "documents": parse_uri(data["documents"], self.endpoint), "navigation": parse_uri(data["navigation"], self.endpoint) } return self._routes
python
def routes(self): """ Retrieves the main routes of the DTS Collection Response format expected : { "@context": "/dts/api/contexts/EntryPoint.jsonld", "@id": "/dts/api/", "@type": "EntryPoint", "collections": "/dts/api/collections/", "documents": "/dts/api/documents/", "navigation" : "/dts/api/navigation" } :returns: Dictionary of main routes with their path :rtype: dict """ if self._routes: return self._routes request = requests.get(self.endpoint) request.raise_for_status() data = request.json() self._routes = { "collections": parse_uri(data["collections"], self.endpoint), "documents": parse_uri(data["documents"], self.endpoint), "navigation": parse_uri(data["navigation"], self.endpoint) } return self._routes
[ "def", "routes", "(", "self", ")", ":", "if", "self", ".", "_routes", ":", "return", "self", ".", "_routes", "request", "=", "requests", ".", "get", "(", "self", ".", "endpoint", ")", "request", ".", "raise_for_status", "(", ")", "data", "=", "request", ".", "json", "(", ")", "self", ".", "_routes", "=", "{", "\"collections\"", ":", "parse_uri", "(", "data", "[", "\"collections\"", "]", ",", "self", ".", "endpoint", ")", ",", "\"documents\"", ":", "parse_uri", "(", "data", "[", "\"documents\"", "]", ",", "self", ".", "endpoint", ")", ",", "\"navigation\"", ":", "parse_uri", "(", "data", "[", "\"navigation\"", "]", ",", "self", ".", "endpoint", ")", "}", "return", "self", ".", "_routes" ]
Retrieves the main routes of the DTS Collection Response format expected : { "@context": "/dts/api/contexts/EntryPoint.jsonld", "@id": "/dts/api/", "@type": "EntryPoint", "collections": "/dts/api/collections/", "documents": "/dts/api/documents/", "navigation" : "/dts/api/navigation" } :returns: Dictionary of main routes with their path :rtype: dict
[ "Retrieves", "the", "main", "routes", "of", "the", "DTS", "Collection" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/retrievers/dts/__init__.py#L76-L103
train
Capitains/MyCapytain
MyCapytain/retrievers/dts/__init__.py
HttpDtsRetriever.get_collection
def get_collection(self, collection_id=None, nav="children", page=None): """ Makes a call on the Collection API :param collection_id: Id of the collection to retrieve :param nav: Direction of the navigation :param page: Page to retrieve :return: Response :rtype: requests.Response """ return self.call( "collections", { "id": collection_id, "nav": nav, "page": page }, defaults={ "id": None, "nav": "children", "page": 1 } )
python
def get_collection(self, collection_id=None, nav="children", page=None): """ Makes a call on the Collection API :param collection_id: Id of the collection to retrieve :param nav: Direction of the navigation :param page: Page to retrieve :return: Response :rtype: requests.Response """ return self.call( "collections", { "id": collection_id, "nav": nav, "page": page }, defaults={ "id": None, "nav": "children", "page": 1 } )
[ "def", "get_collection", "(", "self", ",", "collection_id", "=", "None", ",", "nav", "=", "\"children\"", ",", "page", "=", "None", ")", ":", "return", "self", ".", "call", "(", "\"collections\"", ",", "{", "\"id\"", ":", "collection_id", ",", "\"nav\"", ":", "nav", ",", "\"page\"", ":", "page", "}", ",", "defaults", "=", "{", "\"id\"", ":", "None", ",", "\"nav\"", ":", "\"children\"", ",", "\"page\"", ":", "1", "}", ")" ]
Makes a call on the Collection API :param collection_id: Id of the collection to retrieve :param nav: Direction of the navigation :param page: Page to retrieve :return: Response :rtype: requests.Response
[ "Makes", "a", "call", "on", "the", "Collection", "API" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/retrievers/dts/__init__.py#L105-L126
train
jiasir/playback
playback/glance.py
Glance._create_glance_db
def _create_glance_db(self, root_db_pass, glance_db_pass): """Create the glance database""" print red(env.host_string + ' | Create glance database') sudo( "mysql -uroot -p{0} -e \"CREATE DATABASE glance;\"".format(root_db_pass), shell=False) sudo("mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'localhost' IDENTIFIED BY '{1}';\"".format( root_db_pass, glance_db_pass), shell=False) sudo("mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'%' IDENTIFIED BY '{1}';\"".format( root_db_pass, glance_db_pass), shell=False)
python
def _create_glance_db(self, root_db_pass, glance_db_pass): """Create the glance database""" print red(env.host_string + ' | Create glance database') sudo( "mysql -uroot -p{0} -e \"CREATE DATABASE glance;\"".format(root_db_pass), shell=False) sudo("mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'localhost' IDENTIFIED BY '{1}';\"".format( root_db_pass, glance_db_pass), shell=False) sudo("mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'%' IDENTIFIED BY '{1}';\"".format( root_db_pass, glance_db_pass), shell=False)
[ "def", "_create_glance_db", "(", "self", ",", "root_db_pass", ",", "glance_db_pass", ")", ":", "print", "red", "(", "env", ".", "host_string", "+", "' | Create glance database'", ")", "sudo", "(", "\"mysql -uroot -p{0} -e \\\"CREATE DATABASE glance;\\\"\"", ".", "format", "(", "root_db_pass", ")", ",", "shell", "=", "False", ")", "sudo", "(", "\"mysql -uroot -p{0} -e \\\"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'localhost' IDENTIFIED BY '{1}';\\\"\"", ".", "format", "(", "root_db_pass", ",", "glance_db_pass", ")", ",", "shell", "=", "False", ")", "sudo", "(", "\"mysql -uroot -p{0} -e \\\"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'%' IDENTIFIED BY '{1}';\\\"\"", ".", "format", "(", "root_db_pass", ",", "glance_db_pass", ")", ",", "shell", "=", "False", ")" ]
Create the glance database
[ "Create", "the", "glance", "database" ]
58b2a5d669dcfaa8cad50c544a4b068dcacf9b69
https://github.com/jiasir/playback/blob/58b2a5d669dcfaa8cad50c544a4b068dcacf9b69/playback/glance.py#L74-L82
train
ethereum/asyncio-cancel-token
cancel_token/token.py
CancelToken.chain
def chain(self, token: 'CancelToken') -> 'CancelToken': """ Return a new CancelToken chaining this and the given token. The new CancelToken's triggered will return True if trigger() has been called on either of the chained tokens, but calling trigger() on the new token has no effect on either of the chained tokens. """ if self.loop != token._loop: raise EventLoopMismatch("Chained CancelToken objects must be on the same event loop") chain_name = ":".join([self.name, token.name]) chain = CancelToken(chain_name, loop=self.loop) chain._chain.extend([self, token]) return chain
python
def chain(self, token: 'CancelToken') -> 'CancelToken': """ Return a new CancelToken chaining this and the given token. The new CancelToken's triggered will return True if trigger() has been called on either of the chained tokens, but calling trigger() on the new token has no effect on either of the chained tokens. """ if self.loop != token._loop: raise EventLoopMismatch("Chained CancelToken objects must be on the same event loop") chain_name = ":".join([self.name, token.name]) chain = CancelToken(chain_name, loop=self.loop) chain._chain.extend([self, token]) return chain
[ "def", "chain", "(", "self", ",", "token", ":", "'CancelToken'", ")", "->", "'CancelToken'", ":", "if", "self", ".", "loop", "!=", "token", ".", "_loop", ":", "raise", "EventLoopMismatch", "(", "\"Chained CancelToken objects must be on the same event loop\"", ")", "chain_name", "=", "\":\"", ".", "join", "(", "[", "self", ".", "name", ",", "token", ".", "name", "]", ")", "chain", "=", "CancelToken", "(", "chain_name", ",", "loop", "=", "self", ".", "loop", ")", "chain", ".", "_chain", ".", "extend", "(", "[", "self", ",", "token", "]", ")", "return", "chain" ]
Return a new CancelToken chaining this and the given token. The new CancelToken's triggered will return True if trigger() has been called on either of the chained tokens, but calling trigger() on the new token has no effect on either of the chained tokens.
[ "Return", "a", "new", "CancelToken", "chaining", "this", "and", "the", "given", "token", "." ]
135395a1a396c50731c03cf570e267c47c612694
https://github.com/ethereum/asyncio-cancel-token/blob/135395a1a396c50731c03cf570e267c47c612694/cancel_token/token.py#L33-L46
train
ethereum/asyncio-cancel-token
cancel_token/token.py
CancelToken.triggered_token
def triggered_token(self) -> 'CancelToken': """ Return the token which was triggered. The returned token may be this token or one that it was chained with. """ if self._triggered.is_set(): return self for token in self._chain: if token.triggered: # Use token.triggered_token here to make the lookup recursive as self._chain may # contain other chains. return token.triggered_token return None
python
def triggered_token(self) -> 'CancelToken': """ Return the token which was triggered. The returned token may be this token or one that it was chained with. """ if self._triggered.is_set(): return self for token in self._chain: if token.triggered: # Use token.triggered_token here to make the lookup recursive as self._chain may # contain other chains. return token.triggered_token return None
[ "def", "triggered_token", "(", "self", ")", "->", "'CancelToken'", ":", "if", "self", ".", "_triggered", ".", "is_set", "(", ")", ":", "return", "self", "for", "token", "in", "self", ".", "_chain", ":", "if", "token", ".", "triggered", ":", "# Use token.triggered_token here to make the lookup recursive as self._chain may", "# contain other chains.", "return", "token", ".", "triggered_token", "return", "None" ]
Return the token which was triggered. The returned token may be this token or one that it was chained with.
[ "Return", "the", "token", "which", "was", "triggered", "." ]
135395a1a396c50731c03cf570e267c47c612694
https://github.com/ethereum/asyncio-cancel-token/blob/135395a1a396c50731c03cf570e267c47c612694/cancel_token/token.py#L55-L68
train
ethereum/asyncio-cancel-token
cancel_token/token.py
CancelToken.triggered
def triggered(self) -> bool: """ Return `True` or `False` whether this token has been triggered. """ if self._triggered.is_set(): return True return any(token.triggered for token in self._chain)
python
def triggered(self) -> bool: """ Return `True` or `False` whether this token has been triggered. """ if self._triggered.is_set(): return True return any(token.triggered for token in self._chain)
[ "def", "triggered", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_triggered", ".", "is_set", "(", ")", ":", "return", "True", "return", "any", "(", "token", ".", "triggered", "for", "token", "in", "self", ".", "_chain", ")" ]
Return `True` or `False` whether this token has been triggered.
[ "Return", "True", "or", "False", "whether", "this", "token", "has", "been", "triggered", "." ]
135395a1a396c50731c03cf570e267c47c612694
https://github.com/ethereum/asyncio-cancel-token/blob/135395a1a396c50731c03cf570e267c47c612694/cancel_token/token.py#L71-L77
train