repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
proycon/pynlpl | pynlpl/formats/folia.py | Document.alias | def alias(self, annotationtype, set, fallback=False):
"""Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled)"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
if annotationtype in self.set_alias and set in se... | python | def alias(self, annotationtype, set, fallback=False):
"""Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled)"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
if annotationtype in self.set_alias and set in se... | [
"def",
"alias",
"(",
"self",
",",
"annotationtype",
",",
"set",
",",
"fallback",
"=",
"False",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATIONTYPE",
"if",
"annotationtype",
... | Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled) | [
"Return",
"the",
"alias",
"for",
"a",
"set",
"(",
"if",
"applicable",
"returns",
"the",
"unaltered",
"set",
"otherwise",
"iff",
"fallback",
"is",
"enabled",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6527-L6535 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.unalias | def unalias(self, annotationtype, alias):
"""Return the set for an alias (if applicable, raises an exception otherwise)"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return self.alias_set[annotationtype][alias] | python | def unalias(self, annotationtype, alias):
"""Return the set for an alias (if applicable, raises an exception otherwise)"""
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return self.alias_set[annotationtype][alias] | [
"def",
"unalias",
"(",
"self",
",",
"annotationtype",
",",
"alias",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATIONTYPE",
"return",
"self",
".",
"alias_set",
"[",
"annotation... | Return the set for an alias (if applicable, raises an exception otherwise) | [
"Return",
"the",
"set",
"for",
"an",
"alias",
"(",
"if",
"applicable",
"raises",
"an",
"exception",
"otherwise",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6538-L6541 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.save | def save(self, filename=None):
"""Save the document to file.
Arguments:
* filename (str): The filename to save to. If not set (``None``, default), saves to the same file as loaded from.
"""
if not filename:
filename = self.filename
if not filename:
... | python | def save(self, filename=None):
"""Save the document to file.
Arguments:
* filename (str): The filename to save to. If not set (``None``, default), saves to the same file as loaded from.
"""
if not filename:
filename = self.filename
if not filename:
... | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
")",
":",
"if",
"not",
"filename",
":",
"filename",
"=",
"self",
".",
"filename",
"if",
"not",
"filename",
":",
"raise",
"Exception",
"(",
"\"No filename specified\"",
")",
"if",
"filename",
"[",
... | Save the document to file.
Arguments:
* filename (str): The filename to save to. If not set (``None``, default), saves to the same file as loaded from. | [
"Save",
"the",
"document",
"to",
"file",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6547-L6568 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.append | def append(self,text):
"""Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech)
"""
if text is Text:
... | python | def append(self,text):
"""Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech)
"""
if text is Text:
... | [
"def",
"append",
"(",
"self",
",",
"text",
")",
":",
"if",
"text",
"is",
"Text",
":",
"text",
"=",
"Text",
"(",
"self",
",",
"id",
"=",
"self",
".",
"id",
"+",
"'.text.'",
"+",
"str",
"(",
"len",
"(",
"self",
".",
"data",
")",
"+",
"1",
")",
... | Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech) | [
"Add",
"a",
"text",
"(",
"or",
"speech",
")",
"to",
"the",
"document",
":"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6621-L6643 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.xmldeclarations | def xmldeclarations(self):
"""Internal method to generate XML nodes for all declarations"""
l = []
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={None: "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace"})
for annotationtype, set in self.annotations:
... | python | def xmldeclarations(self):
"""Internal method to generate XML nodes for all declarations"""
l = []
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={None: "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace"})
for annotationtype, set in self.annotations:
... | [
"def",
"xmldeclarations",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"E",
"=",
"ElementMaker",
"(",
"namespace",
"=",
"\"http://ilk.uvt.nl/folia\"",
",",
"nsmap",
"=",
"{",
"None",
":",
"\"http://ilk.uvt.nl/folia\"",
",",
"'xml'",
":",
"\"http://www.w3.org/XML/1... | Internal method to generate XML nodes for all declarations | [
"Internal",
"method",
"to",
"generate",
"XML",
"nodes",
"for",
"all",
"declarations"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6653-L6690 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.jsondeclarations | def jsondeclarations(self):
"""Return all declarations in a form ready to be serialised to JSON.
Returns:
list of dict
"""
l = []
for annotationtype, set in self.annotations:
label = None
#Find the 'label' for the declarations dynamically (aka... | python | def jsondeclarations(self):
"""Return all declarations in a form ready to be serialised to JSON.
Returns:
list of dict
"""
l = []
for annotationtype, set in self.annotations:
label = None
#Find the 'label' for the declarations dynamically (aka... | [
"def",
"jsondeclarations",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"annotationtype",
",",
"set",
"in",
"self",
".",
"annotations",
":",
"label",
"=",
"None",
"#Find the 'label' for the declarations dynamically (aka: AnnotationType --> String)",
"for",
"key",... | Return all declarations in a form ready to be serialised to JSON.
Returns:
list of dict | [
"Return",
"all",
"declarations",
"in",
"a",
"form",
"ready",
"to",
"be",
"serialised",
"to",
"JSON",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6692-L6731 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.xml | def xml(self):
"""Serialise the document to XML.
Returns:
lxml.etree.Element
See also:
:meth:`Document.xmlstring`
"""
self.pendingvalidation()
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={'xml' : "http://www.w3.org/XML/1998/names... | python | def xml(self):
"""Serialise the document to XML.
Returns:
lxml.etree.Element
See also:
:meth:`Document.xmlstring`
"""
self.pendingvalidation()
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={'xml' : "http://www.w3.org/XML/1998/names... | [
"def",
"xml",
"(",
"self",
")",
":",
"self",
".",
"pendingvalidation",
"(",
")",
"E",
"=",
"ElementMaker",
"(",
"namespace",
"=",
"\"http://ilk.uvt.nl/folia\"",
",",
"nsmap",
"=",
"{",
"'xml'",
":",
"\"http://www.w3.org/XML/1998/namespace\"",
",",
"'xlink'",
":"... | Serialise the document to XML.
Returns:
lxml.etree.Element
See also:
:meth:`Document.xmlstring` | [
"Serialise",
"the",
"document",
"to",
"XML",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6733-L6773 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.json | def json(self):
"""Serialise the document to a ``dict`` ready for serialisation to JSON.
Example::
import json
jsondoc = json.dumps(doc.json())
"""
self.pendingvalidation()
jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations(... | python | def json(self):
"""Serialise the document to a ``dict`` ready for serialisation to JSON.
Example::
import json
jsondoc = json.dumps(doc.json())
"""
self.pendingvalidation()
jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations(... | [
"def",
"json",
"(",
"self",
")",
":",
"self",
".",
"pendingvalidation",
"(",
")",
"jsondoc",
"=",
"{",
"'id'",
":",
"self",
".",
"id",
",",
"'children'",
":",
"[",
"]",
",",
"'declarations'",
":",
"self",
".",
"jsondeclarations",
"(",
")",
"}",
"if",... | Serialise the document to a ``dict`` ready for serialisation to JSON.
Example::
import json
jsondoc = json.dumps(doc.json()) | [
"Serialise",
"the",
"document",
"to",
"a",
"dict",
"ready",
"for",
"serialisation",
"to",
"JSON",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6775-L6794 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.xmlmetadata | def xmlmetadata(self):
"""Internal method to serialize metadata to XML"""
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={None: "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace"})
elements = []
if self.metadatatype == "native":
if isinstanc... | python | def xmlmetadata(self):
"""Internal method to serialize metadata to XML"""
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={None: "http://ilk.uvt.nl/folia", 'xml' : "http://www.w3.org/XML/1998/namespace"})
elements = []
if self.metadatatype == "native":
if isinstanc... | [
"def",
"xmlmetadata",
"(",
"self",
")",
":",
"E",
"=",
"ElementMaker",
"(",
"namespace",
"=",
"\"http://ilk.uvt.nl/folia\"",
",",
"nsmap",
"=",
"{",
"None",
":",
"\"http://ilk.uvt.nl/folia\"",
",",
"'xml'",
":",
"\"http://www.w3.org/XML/1998/namespace\"",
"}",
")",
... | Internal method to serialize metadata to XML | [
"Internal",
"method",
"to",
"serialize",
"metadata",
"to",
"XML"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6796-L6828 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.parsexmldeclarations | def parsexmldeclarations(self, node):
"""Internal method to parse XML declarations"""
if self.debug >= 1:
print("[PyNLPl FoLiA DEBUG] Processing Annotation Declarations",file=stderr)
self.declareprocessed = True
for subnode in node: #pylint: disable=too-many-nested-blocks
... | python | def parsexmldeclarations(self, node):
"""Internal method to parse XML declarations"""
if self.debug >= 1:
print("[PyNLPl FoLiA DEBUG] Processing Annotation Declarations",file=stderr)
self.declareprocessed = True
for subnode in node: #pylint: disable=too-many-nested-blocks
... | [
"def",
"parsexmldeclarations",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"debug",
">=",
"1",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Processing Annotation Declarations\"",
",",
"file",
"=",
"stderr",
")",
"self",
".",
"declareprocessed",
"=",
"Tr... | Internal method to parse XML declarations | [
"Internal",
"method",
"to",
"parse",
"XML",
"declarations"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6833-L6948 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.setimdi | def setimdi(self, node): #OBSOLETE
"""OBSOLETE"""
ns = {'imdi': 'http://www.mpi.nl/IMDI/Schema/IMDI'}
self.metadatatype = MetaDataType.IMDI
if LXE:
self.metadata = ElementTree.tostring(node, xml_declaration=False, pretty_print=True, encoding='utf-8')
else:
... | python | def setimdi(self, node): #OBSOLETE
"""OBSOLETE"""
ns = {'imdi': 'http://www.mpi.nl/IMDI/Schema/IMDI'}
self.metadatatype = MetaDataType.IMDI
if LXE:
self.metadata = ElementTree.tostring(node, xml_declaration=False, pretty_print=True, encoding='utf-8')
else:
... | [
"def",
"setimdi",
"(",
"self",
",",
"node",
")",
":",
"#OBSOLETE",
"ns",
"=",
"{",
"'imdi'",
":",
"'http://www.mpi.nl/IMDI/Schema/IMDI'",
"}",
"self",
".",
"metadatatype",
"=",
"MetaDataType",
".",
"IMDI",
"if",
"LXE",
":",
"self",
".",
"metadata",
"=",
"E... | OBSOLETE | [
"OBSOLETE"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6953-L6970 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.declare | def declare(self, annotationtype, set, **kwargs):
"""Declare a new annotation type to be used in the document.
Keyword arguments can be used to set defaults for any annotation of this type and set.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the c... | python | def declare(self, annotationtype, set, **kwargs):
"""Declare a new annotation type to be used in the document.
Keyword arguments can be used to set defaults for any annotation of this type and set.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the c... | [
"def",
"declare",
"(",
"self",
",",
"annotationtype",
",",
"set",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"sys",
".",
"version",
">",
"'3'",
"and",
"not",
"isinstance",
"(",
"set",
",",
"str",
")",
")",
"or",
"(",
"sys",
".",
"version",
"<"... | Declare a new annotation type to be used in the document.
Keyword arguments can be used to set defaults for any annotation of this type and set.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation`... | [
"Declare",
"a",
"new",
"annotation",
"type",
"to",
"be",
"used",
"in",
"the",
"document",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L6972-L7018 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.declared | def declared(self, annotationtype, set):
"""Checks if the annotation type is present (i.e. declared) in the document.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member o... | python | def declared(self, annotationtype, set):
"""Checks if the annotation type is present (i.e. declared) in the document.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member o... | [
"def",
"declared",
"(",
"self",
",",
"annotationtype",
",",
"set",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATIONTYPE",
"return",
"(",
"(",
"annotationtype",
",",
"set",
"... | Checks if the annotation type is present (i.e. declared) in the document.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`AnnotationType`, such as ``AnnotationType.... | [
"Checks",
"if",
"the",
"annotation",
"type",
"is",
"present",
"(",
"i",
".",
"e",
".",
"declared",
")",
"in",
"the",
"document",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7020-L7036 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.defaultset | def defaultset(self, annotationtype):
"""Obtain the default set for the specified annotation type.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`Annotatio... | python | def defaultset(self, annotationtype):
"""Obtain the default set for the specified annotation type.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`Annotatio... | [
"def",
"defaultset",
"(",
"self",
",",
"annotationtype",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
"or",
"isinstance",
"(",
"annotationtype",
",",
"AbstractElement",
")",
":",
"annotationtype",
"=",
"annotationtype",
".",
"ANNOTATION... | Obtain the default set for the specified annotation type.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`AnnotationType`, such as ``AnnotationType.POS``.
... | [
"Obtain",
"the",
"default",
"set",
"for",
"the",
"specified",
"annotation",
"type",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7039-L7058 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.defaultannotator | def defaultannotator(self, annotationtype, set=None):
"""Obtain the default annotator for the specified annotation type and set.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or... | python | def defaultannotator(self, annotationtype, set=None):
"""Obtain the default annotator for the specified annotation type and set.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or... | [
"def",
"defaultannotator",
"(",
"self",
",",
"annotationtype",
",",
"set",
"=",
"None",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"annotationtype",
")",
"or",
"isinstance",
"(",
"annotationtype",
",",
"AbstractElement",
")",
":",
"annotationtype",
"=",
... | Obtain the default annotator for the specified annotation type and set.
Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`AnnotationType`, such as ``AnnotationType.PO... | [
"Obtain",
"the",
"default",
"annotator",
"for",
"the",
"specified",
"annotation",
"type",
"and",
"set",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7061-L7080 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.title | def title(self, value=None):
"""Get or set the document's title from/in the metadata
No arguments: Get the document's title from metadata
Argument: Set the document's title in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
... | python | def title(self, value=None):
"""Get or set the document's title from/in the metadata
No arguments: Get the document's title from metadata
Argument: Set the document's title in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
... | [
"def",
"title",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"not",
"(",
"value",
"is",
"None",
")",
":",
"if",
"(",
"self",
".",
"metadatatype",
"==",
"\"native\"",
")",
":",
"self",
".",
"metadata",
"[",
"'title'",
"]",
"=",
"value",
... | Get or set the document's title from/in the metadata
No arguments: Get the document's title from metadata
Argument: Set the document's title in metadata | [
"Get",
"or",
"set",
"the",
"document",
"s",
"title",
"from",
"/",
"in",
"the",
"metadata"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7127-L7144 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.date | def date(self, value=None):
"""Get or set the document's date from/in the metadata.
No arguments: Get the document's date from metadata
Argument: Set the document's date in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
... | python | def date(self, value=None):
"""Get or set the document's date from/in the metadata.
No arguments: Get the document's date from metadata
Argument: Set the document's date in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
... | [
"def",
"date",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"not",
"(",
"value",
"is",
"None",
")",
":",
"if",
"(",
"self",
".",
"metadatatype",
"==",
"\"native\"",
")",
":",
"self",
".",
"metadata",
"[",
"'date'",
"]",
"=",
"value",
"... | Get or set the document's date from/in the metadata.
No arguments: Get the document's date from metadata
Argument: Set the document's date in metadata | [
"Get",
"or",
"set",
"the",
"document",
"s",
"date",
"from",
"/",
"in",
"the",
"metadata",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7146-L7163 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.publisher | def publisher(self, value=None):
"""No arguments: Get the document's publisher from metadata
Argument: Set the document's publisher in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['publisher'] = value
el... | python | def publisher(self, value=None):
"""No arguments: Get the document's publisher from metadata
Argument: Set the document's publisher in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['publisher'] = value
el... | [
"def",
"publisher",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"not",
"(",
"value",
"is",
"None",
")",
":",
"if",
"(",
"self",
".",
"metadatatype",
"==",
"\"native\"",
")",
":",
"self",
".",
"metadata",
"[",
"'publisher'",
"]",
"=",
"v... | No arguments: Get the document's publisher from metadata
Argument: Set the document's publisher in metadata | [
"No",
"arguments",
":",
"Get",
"the",
"document",
"s",
"publisher",
"from",
"metadata",
"Argument",
":",
"Set",
"the",
"document",
"s",
"publisher",
"in",
"metadata"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7165-L7180 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.license | def license(self, value=None):
"""No arguments: Get the document's license from metadata
Argument: Set the document's license in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['license'] = value
else:
... | python | def license(self, value=None):
"""No arguments: Get the document's license from metadata
Argument: Set the document's license in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['license'] = value
else:
... | [
"def",
"license",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"not",
"(",
"value",
"is",
"None",
")",
":",
"if",
"(",
"self",
".",
"metadatatype",
"==",
"\"native\"",
")",
":",
"self",
".",
"metadata",
"[",
"'license'",
"]",
"=",
"value... | No arguments: Get the document's license from metadata
Argument: Set the document's license in metadata | [
"No",
"arguments",
":",
"Get",
"the",
"document",
"s",
"license",
"from",
"metadata",
"Argument",
":",
"Set",
"the",
"document",
"s",
"license",
"in",
"metadata"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7182-L7197 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.language | def language(self, value=None):
"""No arguments: Get the document's language (ISO-639-3) from metadata
Argument: Set the document's language (ISO-639-3) in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['language'] = ... | python | def language(self, value=None):
"""No arguments: Get the document's language (ISO-639-3) from metadata
Argument: Set the document's language (ISO-639-3) in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['language'] = ... | [
"def",
"language",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"not",
"(",
"value",
"is",
"None",
")",
":",
"if",
"(",
"self",
".",
"metadatatype",
"==",
"\"native\"",
")",
":",
"self",
".",
"metadata",
"[",
"'language'",
"]",
"=",
"val... | No arguments: Get the document's language (ISO-639-3) from metadata
Argument: Set the document's language (ISO-639-3) in metadata | [
"No",
"arguments",
":",
"Get",
"the",
"document",
"s",
"language",
"(",
"ISO",
"-",
"639",
"-",
"3",
")",
"from",
"metadata",
"Argument",
":",
"Set",
"the",
"document",
"s",
"language",
"(",
"ISO",
"-",
"639",
"-",
"3",
")",
"in",
"metadata"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7199-L7214 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.parsemetadata | def parsemetadata(self, node):
"""Internal method to parse metadata"""
if 'type' in node.attrib:
self.metadatatype = node.attrib['type']
else:
#no type specified, default to native
self.metadatatype = "native"
if 'src' in node.attrib:
sel... | python | def parsemetadata(self, node):
"""Internal method to parse metadata"""
if 'type' in node.attrib:
self.metadatatype = node.attrib['type']
else:
#no type specified, default to native
self.metadatatype = "native"
if 'src' in node.attrib:
sel... | [
"def",
"parsemetadata",
"(",
"self",
",",
"node",
")",
":",
"if",
"'type'",
"in",
"node",
".",
"attrib",
":",
"self",
".",
"metadatatype",
"=",
"node",
".",
"attrib",
"[",
"'type'",
"]",
"else",
":",
"#no type specified, default to native",
"self",
".",
"m... | Internal method to parse metadata | [
"Internal",
"method",
"to",
"parse",
"metadata"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7216-L7261 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.parsexml | def parsexml(self, node, ParentClass = None):
"""Internal method.
This is the main XML parser, will invoke class-specific XML parsers."""
if (LXE and isinstance(node,ElementTree._ElementTree)) or (not LXE and isinstance(node, ElementTree.ElementTree)): #pylint: disable=protected-access
... | python | def parsexml(self, node, ParentClass = None):
"""Internal method.
This is the main XML parser, will invoke class-specific XML parsers."""
if (LXE and isinstance(node,ElementTree._ElementTree)) or (not LXE and isinstance(node, ElementTree.ElementTree)): #pylint: disable=protected-access
... | [
"def",
"parsexml",
"(",
"self",
",",
"node",
",",
"ParentClass",
"=",
"None",
")",
":",
"if",
"(",
"LXE",
"and",
"isinstance",
"(",
"node",
",",
"ElementTree",
".",
"_ElementTree",
")",
")",
"or",
"(",
"not",
"LXE",
"and",
"isinstance",
"(",
"node",
... | Internal method.
This is the main XML parser, will invoke class-specific XML parsers. | [
"Internal",
"method",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7301-L7393 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.pendingvalidation | def pendingvalidation(self, warnonly=None):
"""Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
Returns:
... | python | def pendingvalidation(self, warnonly=None):
"""Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
Returns:
... | [
"def",
"pendingvalidation",
"(",
"self",
",",
"warnonly",
"=",
"None",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Processing pending validations (if any)\"",
",",
"file",
"=",
"stderr",
")",
"if",
"warnonly",
"is",
"None",
"... | Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
Returns:
bool | [
"Perform",
"any",
"pending",
"validations"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7396-L7424 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.select | def select(self, Class, set=None, recursive=True, ignore=True):
"""See :meth:`AbstractElement.select`"""
if self.mode == Mode.MEMORY:
for t in self.data:
if Class.__name__ == 'Text':
yield t
else:
for e in t.select(Clas... | python | def select(self, Class, set=None, recursive=True, ignore=True):
"""See :meth:`AbstractElement.select`"""
if self.mode == Mode.MEMORY:
for t in self.data:
if Class.__name__ == 'Text':
yield t
else:
for e in t.select(Clas... | [
"def",
"select",
"(",
"self",
",",
"Class",
",",
"set",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"ignore",
"=",
"True",
")",
":",
"if",
"self",
".",
"mode",
"==",
"Mode",
".",
"MEMORY",
":",
"for",
"t",
"in",
"self",
".",
"data",
":",
"... | See :meth:`AbstractElement.select` | [
"See",
":",
"meth",
":",
"AbstractElement",
".",
"select"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7427-L7435 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.count | def count(self, Class, set=None, recursive=True,ignore=True):
"""See :meth:`AbstractElement.count`"""
if self.mode == Mode.MEMORY:
s = 0
for t in self.data:
s += sum( 1 for e in t.select(Class,recursive,True ) )
return s | python | def count(self, Class, set=None, recursive=True,ignore=True):
"""See :meth:`AbstractElement.count`"""
if self.mode == Mode.MEMORY:
s = 0
for t in self.data:
s += sum( 1 for e in t.select(Class,recursive,True ) )
return s | [
"def",
"count",
"(",
"self",
",",
"Class",
",",
"set",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"ignore",
"=",
"True",
")",
":",
"if",
"self",
".",
"mode",
"==",
"Mode",
".",
"MEMORY",
":",
"s",
"=",
"0",
"for",
"t",
"in",
"self",
".",
... | See :meth:`AbstractElement.count` | [
"See",
":",
"meth",
":",
"AbstractElement",
".",
"count"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7437-L7443 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.paragraphs | def paragraphs(self, index = None):
"""Return a generator of all paragraphs found in the document.
If an index is specified, return the n'th paragraph only (starting at 0)"""
if index is None:
return self.select(Paragraph)
else:
if index < 0:
inde... | python | def paragraphs(self, index = None):
"""Return a generator of all paragraphs found in the document.
If an index is specified, return the n'th paragraph only (starting at 0)"""
if index is None:
return self.select(Paragraph)
else:
if index < 0:
inde... | [
"def",
"paragraphs",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"self",
".",
"select",
"(",
"Paragraph",
")",
"else",
":",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"sum",
"(",
"t",
".",
"count... | Return a generator of all paragraphs found in the document.
If an index is specified, return the n'th paragraph only (starting at 0) | [
"Return",
"a",
"generator",
"of",
"all",
"paragraphs",
"found",
"in",
"the",
"document",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7445-L7458 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.sentences | def sentences(self, index = None):
"""Return a generator of all sentence found in the document. Except for sentences in quotes.
If an index is specified, return the n'th sentence only (starting at 0)"""
if index is None:
return self.select(Sentence,None,True,[Quote])
else:
... | python | def sentences(self, index = None):
"""Return a generator of all sentence found in the document. Except for sentences in quotes.
If an index is specified, return the n'th sentence only (starting at 0)"""
if index is None:
return self.select(Sentence,None,True,[Quote])
else:
... | [
"def",
"sentences",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"self",
".",
"select",
"(",
"Sentence",
",",
"None",
",",
"True",
",",
"[",
"Quote",
"]",
")",
"else",
":",
"if",
"index",
"<",
"0",... | Return a generator of all sentence found in the document. Except for sentences in quotes.
If an index is specified, return the n'th sentence only (starting at 0) | [
"Return",
"a",
"generator",
"of",
"all",
"sentence",
"found",
"in",
"the",
"document",
".",
"Except",
"for",
"sentences",
"in",
"quotes",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7460-L7473 |
proycon/pynlpl | pynlpl/formats/folia.py | Document.text | def text(self, cls='current', retaintokenisation=False):
"""Returns the text of the entire document (returns a unicode instance)
See also:
:meth:`AbstractElement.text`
"""
#backward compatibility, old versions didn't have cls as first argument, so if a boolean is passed fir... | python | def text(self, cls='current', retaintokenisation=False):
"""Returns the text of the entire document (returns a unicode instance)
See also:
:meth:`AbstractElement.text`
"""
#backward compatibility, old versions didn't have cls as first argument, so if a boolean is passed fir... | [
"def",
"text",
"(",
"self",
",",
"cls",
"=",
"'current'",
",",
"retaintokenisation",
"=",
"False",
")",
":",
"#backward compatibility, old versions didn't have cls as first argument, so if a boolean is passed first we interpret it as the 2nd:",
"if",
"cls",
"is",
"True",
"or",
... | Returns the text of the entire document (returns a unicode instance)
See also:
:meth:`AbstractElement.text` | [
"Returns",
"the",
"text",
"of",
"the",
"entire",
"document",
"(",
"returns",
"a",
"unicode",
"instance",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L7493-L7512 |
proycon/pynlpl | pynlpl/fsa.py | NFA._states | def _states(self, state, processedstates=[]): #pylint: disable=dangerous-default-value
"""Iterate over all states in no particular order"""
processedstates.append(state)
for nextstate in state.epsilon:
if not nextstate in processedstates:
self._states(nextstate, proc... | python | def _states(self, state, processedstates=[]): #pylint: disable=dangerous-default-value
"""Iterate over all states in no particular order"""
processedstates.append(state)
for nextstate in state.epsilon:
if not nextstate in processedstates:
self._states(nextstate, proc... | [
"def",
"_states",
"(",
"self",
",",
"state",
",",
"processedstates",
"=",
"[",
"]",
")",
":",
"#pylint: disable=dangerous-default-value",
"processedstates",
".",
"append",
"(",
"state",
")",
"for",
"nextstate",
"in",
"state",
".",
"epsilon",
":",
"if",
"not",
... | Iterate over all states in no particular order | [
"Iterate",
"over",
"all",
"states",
"in",
"no",
"particular",
"order"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/fsa.py#L97-L109 |
proycon/pynlpl | pynlpl/common.py | log | def log(msg, **kwargs):
"""Generic log method. Will prepend timestamp.
Keyword arguments:
system - Name of the system/module
indent - Integer denoting the desired level of indentation
streams - List of streams to output to
stream - Stream to output to (singleton version of stream... | python | def log(msg, **kwargs):
"""Generic log method. Will prepend timestamp.
Keyword arguments:
system - Name of the system/module
indent - Integer denoting the desired level of indentation
streams - List of streams to output to
stream - Stream to output to (singleton version of stream... | [
"def",
"log",
"(",
"msg",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'debug'",
"in",
"kwargs",
":",
"if",
"'currentdebug'",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"'currentdebug'",
"]",
"<",
"kwargs",
"[",
"'debug'",
"]",
":",
"return",
"False",
"e... | Generic log method. Will prepend timestamp.
Keyword arguments:
system - Name of the system/module
indent - Integer denoting the desired level of indentation
streams - List of streams to output to
stream - Stream to output to (singleton version of streams) | [
"Generic",
"log",
"method",
".",
"Will",
"prepend",
"timestamp",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/common.py#L98-L136 |
proycon/pynlpl | pynlpl/search.py | AbstractSearch.searchbest | def searchbest(self):
"""Returns the single best result (if multiple have the same score, the first match is returned)"""
finalsolution = None
bestscore = None
for solution in self:
if bestscore == None:
bestscore = solution.score()
finalsoluti... | python | def searchbest(self):
"""Returns the single best result (if multiple have the same score, the first match is returned)"""
finalsolution = None
bestscore = None
for solution in self:
if bestscore == None:
bestscore = solution.score()
finalsoluti... | [
"def",
"searchbest",
"(",
"self",
")",
":",
"finalsolution",
"=",
"None",
"bestscore",
"=",
"None",
"for",
"solution",
"in",
"self",
":",
"if",
"bestscore",
"==",
"None",
":",
"bestscore",
"=",
"solution",
".",
"score",
"(",
")",
"finalsolution",
"=",
"s... | Returns the single best result (if multiple have the same score, the first match is returned) | [
"Returns",
"the",
"single",
"best",
"result",
"(",
"if",
"multiple",
"have",
"the",
"same",
"score",
"the",
"first",
"match",
"is",
"returned",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/search.py#L243-L261 |
proycon/pynlpl | pynlpl/search.py | AbstractSearch.searchtop | def searchtop(self,n=10):
"""Return the top n best resulta (or possibly less if not enough is found)"""
solutions = PriorityQueue([], lambda x: x.score, self.minimize, length=n, blockworse=False, blockequal=False,duplicates=False)
for solution in self:
solutions.append(so... | python | def searchtop(self,n=10):
"""Return the top n best resulta (or possibly less if not enough is found)"""
solutions = PriorityQueue([], lambda x: x.score, self.minimize, length=n, blockworse=False, blockequal=False,duplicates=False)
for solution in self:
solutions.append(so... | [
"def",
"searchtop",
"(",
"self",
",",
"n",
"=",
"10",
")",
":",
"solutions",
"=",
"PriorityQueue",
"(",
"[",
"]",
",",
"lambda",
"x",
":",
"x",
".",
"score",
",",
"self",
".",
"minimize",
",",
"length",
"=",
"n",
",",
"blockworse",
"=",
"False",
... | Return the top n best resulta (or possibly less if not enough is found) | [
"Return",
"the",
"top",
"n",
"best",
"resulta",
"(",
"or",
"possibly",
"less",
"if",
"not",
"enough",
"is",
"found",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/search.py#L263-L268 |
proycon/pynlpl | pynlpl/search.py | AbstractSearch.searchlast | def searchlast(self,n=10):
"""Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type."""
solutions = deque([], n)
for solution in self:
solutions.append(solution)
return... | python | def searchlast(self,n=10):
"""Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type."""
solutions = deque([], n)
for solution in self:
solutions.append(solution)
return... | [
"def",
"searchlast",
"(",
"self",
",",
"n",
"=",
"10",
")",
":",
"solutions",
"=",
"deque",
"(",
"[",
"]",
",",
"n",
")",
"for",
"solution",
"in",
"self",
":",
"solutions",
".",
"append",
"(",
"solution",
")",
"return",
"solutions"
] | Return the last n results (or possibly less if not found). Note that the last results are not necessarily the best ones! Depending on the search type. | [
"Return",
"the",
"last",
"n",
"results",
"(",
"or",
"possibly",
"less",
"if",
"not",
"found",
")",
".",
"Note",
"that",
"the",
"last",
"results",
"are",
"not",
"necessarily",
"the",
"best",
"ones!",
"Depending",
"on",
"the",
"search",
"type",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/search.py#L270-L275 |
proycon/pynlpl | pynlpl/clients/cornetto.py | CornettoClient.get_syn_ids_by_lemma | def get_syn_ids_by_lemma(self, lemma):
"""Returns a list of synset IDs based on a lemma"""
if not isinstance(lemma,unicode):
lemma = unicode(lemma,'utf-8')
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.de... | python | def get_syn_ids_by_lemma(self, lemma):
"""Returns a list of synset IDs based on a lemma"""
if not isinstance(lemma,unicode):
lemma = unicode(lemma,'utf-8')
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.de... | [
"def",
"get_syn_ids_by_lemma",
"(",
"self",
",",
"lemma",
")",
":",
"if",
"not",
"isinstance",
"(",
"lemma",
",",
"unicode",
")",
":",
"lemma",
"=",
"unicode",
"(",
"lemma",
",",
"'utf-8'",
")",
"http",
",",
"resp",
",",
"content",
"=",
"self",
".",
... | Returns a list of synset IDs based on a lemma | [
"Returns",
"a",
"list",
"of",
"synset",
"IDs",
"based",
"on",
"a",
"lemma"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/cornetto.py#L96-L160 |
proycon/pynlpl | pynlpl/clients/cornetto.py | CornettoClient.get_synset_xml | def get_synset_xml(self,syn_id):
"""
call cdb_syn with synset identifier -> returns the synset xml;
"""
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.debug:
printf( "cornettodb/views/query_remote_s... | python | def get_synset_xml(self,syn_id):
"""
call cdb_syn with synset identifier -> returns the synset xml;
"""
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.debug:
printf( "cornettodb/views/query_remote_s... | [
"def",
"get_synset_xml",
"(",
"self",
",",
"syn_id",
")",
":",
"http",
",",
"resp",
",",
"content",
"=",
"self",
".",
"connect",
"(",
")",
"params",
"=",
"\"\"",
"fragment",
"=",
"\"\"",
"path",
"=",
"\"cdb_syn\"",
"if",
"self",
".",
"debug",
":",
"p... | call cdb_syn with synset identifier -> returns the synset xml; | [
"call",
"cdb_syn",
"with",
"synset",
"identifier",
"-",
">",
"returns",
"the",
"synset",
"xml",
";"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/cornetto.py#L227-L272 |
proycon/pynlpl | pynlpl/clients/cornetto.py | CornettoClient.get_lus_from_synset | def get_lus_from_synset(self, syn_id):
"""Returns a list of (word, lu_id) tuples given a synset ID"""
root = self.get_synset_xml(syn_id)
elem_synonyms = root.find( ".//synonyms" )
lus = []
for elem_synonym in elem_synonyms:
synonym_str = elem_synonym.get( "c_lu_id-... | python | def get_lus_from_synset(self, syn_id):
"""Returns a list of (word, lu_id) tuples given a synset ID"""
root = self.get_synset_xml(syn_id)
elem_synonyms = root.find( ".//synonyms" )
lus = []
for elem_synonym in elem_synonyms:
synonym_str = elem_synonym.get( "c_lu_id-... | [
"def",
"get_lus_from_synset",
"(",
"self",
",",
"syn_id",
")",
":",
"root",
"=",
"self",
".",
"get_synset_xml",
"(",
"syn_id",
")",
"elem_synonyms",
"=",
"root",
".",
"find",
"(",
"\".//synonyms\"",
")",
"lus",
"=",
"[",
"]",
"for",
"elem_synonym",
"in",
... | Returns a list of (word, lu_id) tuples given a synset ID | [
"Returns",
"a",
"list",
"of",
"(",
"word",
"lu_id",
")",
"tuples",
"given",
"a",
"synset",
"ID"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/cornetto.py#L275-L288 |
proycon/pynlpl | pynlpl/clients/cornetto.py | CornettoClient.get_lu_from_synset | def get_lu_from_synset(self, syn_id, lemma = None):
"""Returns (lu_id, synonyms=[(word, lu_id)] ) tuple given a synset ID and a lemma"""
if not lemma:
return self.get_lus_from_synset(syn_id) #alias
if not isinstance(lemma,unicode):
lemma = unicode(lemma,'utf-8')
... | python | def get_lu_from_synset(self, syn_id, lemma = None):
"""Returns (lu_id, synonyms=[(word, lu_id)] ) tuple given a synset ID and a lemma"""
if not lemma:
return self.get_lus_from_synset(syn_id) #alias
if not isinstance(lemma,unicode):
lemma = unicode(lemma,'utf-8')
... | [
"def",
"get_lu_from_synset",
"(",
"self",
",",
"syn_id",
",",
"lemma",
"=",
"None",
")",
":",
"if",
"not",
"lemma",
":",
"return",
"self",
".",
"get_lus_from_synset",
"(",
"syn_id",
")",
"#alias",
"if",
"not",
"isinstance",
"(",
"lemma",
",",
"unicode",
... | Returns (lu_id, synonyms=[(word, lu_id)] ) tuple given a synset ID and a lemma | [
"Returns",
"(",
"lu_id",
"synonyms",
"=",
"[",
"(",
"word",
"lu_id",
")",
"]",
")",
"tuple",
"given",
"a",
"synset",
"ID",
"and",
"a",
"lemma"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/cornetto.py#L291-L317 |
proycon/pynlpl | pynlpl/formats/dutchsemcor.py | WSDSystemOutput.senses | def senses(self, bestonly=False):
"""Returns a list of all predicted senses"""
l = []
for word_id, senses,distance in self:
for sense, confidence in senses:
if not sense in l: l.append(sense)
if bestonly:
break
return l | python | def senses(self, bestonly=False):
"""Returns a list of all predicted senses"""
l = []
for word_id, senses,distance in self:
for sense, confidence in senses:
if not sense in l: l.append(sense)
if bestonly:
break
return l | [
"def",
"senses",
"(",
"self",
",",
"bestonly",
"=",
"False",
")",
":",
"l",
"=",
"[",
"]",
"for",
"word_id",
",",
"senses",
",",
"distance",
"in",
"self",
":",
"for",
"sense",
",",
"confidence",
"in",
"senses",
":",
"if",
"not",
"sense",
"in",
"l",... | Returns a list of all predicted senses | [
"Returns",
"a",
"list",
"of",
"all",
"predicted",
"senses"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/dutchsemcor.py#L139-L147 |
proycon/pynlpl | pynlpl/clients/frogclient.py | FrogClient.process | def process(self,input_data, source_encoding="utf-8", return_unicode = True, oldfrog=False):
"""Receives input_data in the form of a str or unicode object, passes this to the server, with proper consideration for the encodings, and returns the Frog output as a list of tuples: (word,pos,lemma,morphology), each o... | python | def process(self,input_data, source_encoding="utf-8", return_unicode = True, oldfrog=False):
"""Receives input_data in the form of a str or unicode object, passes this to the server, with proper consideration for the encodings, and returns the Frog output as a list of tuples: (word,pos,lemma,morphology), each o... | [
"def",
"process",
"(",
"self",
",",
"input_data",
",",
"source_encoding",
"=",
"\"utf-8\"",
",",
"return_unicode",
"=",
"True",
",",
"oldfrog",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"input_data",
",",
"list",
")",
"or",
"isinstance",
"(",
"input... | Receives input_data in the form of a str or unicode object, passes this to the server, with proper consideration for the encodings, and returns the Frog output as a list of tuples: (word,pos,lemma,morphology), each of these is a proper unicode object unless return_unicode is set to False, in which case raw strings will... | [
"Receives",
"input_data",
"in",
"the",
"form",
"of",
"a",
"str",
"or",
"unicode",
"object",
"passes",
"this",
"to",
"the",
"server",
"with",
"proper",
"consideration",
"for",
"the",
"encodings",
"and",
"returns",
"the",
"Frog",
"output",
"as",
"a",
"list",
... | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/frogclient.py#L40-L98 |
proycon/pynlpl | pynlpl/clients/frogclient.py | FrogClient.align | def align(self,inputwords, outputwords):
"""For each inputword, provides the index of the outputword"""
alignment = []
cursor = 0
for inputword in inputwords:
if len(outputwords) > cursor and outputwords[cursor] == inputword:
alignment.append(cursor)
... | python | def align(self,inputwords, outputwords):
"""For each inputword, provides the index of the outputword"""
alignment = []
cursor = 0
for inputword in inputwords:
if len(outputwords) > cursor and outputwords[cursor] == inputword:
alignment.append(cursor)
... | [
"def",
"align",
"(",
"self",
",",
"inputwords",
",",
"outputwords",
")",
":",
"alignment",
"=",
"[",
"]",
"cursor",
"=",
"0",
"for",
"inputword",
"in",
"inputwords",
":",
"if",
"len",
"(",
"outputwords",
")",
">",
"cursor",
"and",
"outputwords",
"[",
"... | For each inputword, provides the index of the outputword | [
"For",
"each",
"inputword",
"provides",
"the",
"index",
"of",
"the",
"outputword"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/frogclient.py#L115-L129 |
proycon/pynlpl | pynlpl/textprocessors.py | calculate_overlap | def calculate_overlap(haystack, needle, allowpartial=True):
"""Calculate the overlap between two sequences. Yields (overlap, placement) tuples (multiple because there may be multiple overlaps!). The former is the part of the sequence that overlaps, and the latter is -1 if the overlap is on the left side, 0 if it is... | python | def calculate_overlap(haystack, needle, allowpartial=True):
"""Calculate the overlap between two sequences. Yields (overlap, placement) tuples (multiple because there may be multiple overlaps!). The former is the part of the sequence that overlaps, and the latter is -1 if the overlap is on the left side, 0 if it is... | [
"def",
"calculate_overlap",
"(",
"haystack",
",",
"needle",
",",
"allowpartial",
"=",
"True",
")",
":",
"needle",
"=",
"tuple",
"(",
"needle",
")",
"haystack",
"=",
"tuple",
"(",
"haystack",
")",
"solutions",
"=",
"[",
"]",
"#equality check",
"if",
"needle... | Calculate the overlap between two sequences. Yields (overlap, placement) tuples (multiple because there may be multiple overlaps!). The former is the part of the sequence that overlaps, and the latter is -1 if the overlap is on the left side, 0 if it is a subset, 1 if it overlaps on the right side, 2 if its an identica... | [
"Calculate",
"the",
"overlap",
"between",
"two",
"sequences",
".",
"Yields",
"(",
"overlap",
"placement",
")",
"tuples",
"(",
"multiple",
"because",
"there",
"may",
"be",
"multiple",
"overlaps!",
")",
".",
"The",
"former",
"is",
"the",
"part",
"of",
"the",
... | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L228-L262 |
proycon/pynlpl | pynlpl/textprocessors.py | tokenize | def tokenize(text, regexps=TOKENIZERRULES):
"""Tokenizes a string and returns a list of tokens
:param text: The text to tokenise
:type text: string
:param regexps: Regular expressions to use as tokeniser rules in tokenisation (default=_pynlpl.textprocessors.TOKENIZERRULES_)
:type regexps: Tuple/li... | python | def tokenize(text, regexps=TOKENIZERRULES):
"""Tokenizes a string and returns a list of tokens
:param text: The text to tokenise
:type text: string
:param regexps: Regular expressions to use as tokeniser rules in tokenisation (default=_pynlpl.textprocessors.TOKENIZERRULES_)
:type regexps: Tuple/li... | [
"def",
"tokenize",
"(",
"text",
",",
"regexps",
"=",
"TOKENIZERRULES",
")",
":",
"for",
"i",
",",
"regexp",
"in",
"list",
"(",
"enumerate",
"(",
"regexps",
")",
")",
":",
"if",
"isstring",
"(",
"regexp",
")",
":",
"regexps",
"[",
"i",
"]",
"=",
"re... | Tokenizes a string and returns a list of tokens
:param text: The text to tokenise
:type text: string
:param regexps: Regular expressions to use as tokeniser rules in tokenisation (default=_pynlpl.textprocessors.TOKENIZERRULES_)
:type regexps: Tuple/list of regular expressions to use in tokenisation
... | [
"Tokenizes",
"a",
"string",
"and",
"returns",
"a",
"list",
"of",
"tokens"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L317-L386 |
proycon/pynlpl | pynlpl/textprocessors.py | split_sentences | def split_sentences(tokens):
"""Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens"""
begin = 0
for i, token in enumerate(tokens):
if is_end_of_sentence(tokens, i):
yield tokens[begin:i+1]
begin = i+1
... | python | def split_sentences(tokens):
"""Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens"""
begin = 0
for i, token in enumerate(tokens):
if is_end_of_sentence(tokens, i):
yield tokens[begin:i+1]
begin = i+1
... | [
"def",
"split_sentences",
"(",
"tokens",
")",
":",
"begin",
"=",
"0",
"for",
"i",
",",
"token",
"in",
"enumerate",
"(",
"tokens",
")",
":",
"if",
"is_end_of_sentence",
"(",
"tokens",
",",
"i",
")",
":",
"yield",
"tokens",
"[",
"begin",
":",
"i",
"+",... | Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens | [
"Split",
"sentences",
"(",
"based",
"on",
"tokenised",
"data",
")",
"returns",
"sentences",
"as",
"a",
"list",
"of",
"lists",
"of",
"tokens",
"each",
"sentence",
"is",
"a",
"list",
"of",
"tokens"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L403-L411 |
proycon/pynlpl | pynlpl/textprocessors.py | strip_accents | def strip_accents(s, encoding= 'utf-8'):
"""Strip characters with diacritics and return a flat ascii representation"""
if sys.version < '3':
if isinstance(s,unicode):
return unicodedata.normalize('NFKD', s).encode('ASCII', 'ignore')
else:
return unicodedata.normalize('NFKD'... | python | def strip_accents(s, encoding= 'utf-8'):
"""Strip characters with diacritics and return a flat ascii representation"""
if sys.version < '3':
if isinstance(s,unicode):
return unicodedata.normalize('NFKD', s).encode('ASCII', 'ignore')
else:
return unicodedata.normalize('NFKD'... | [
"def",
"strip_accents",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"return",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"s",
")"... | Strip characters with diacritics and return a flat ascii representation | [
"Strip",
"characters",
"with",
"diacritics",
"and",
"return",
"a",
"flat",
"ascii",
"representation"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L415-L424 |
proycon/pynlpl | pynlpl/textprocessors.py | swap | def swap(tokens, maxdist=2):
"""Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations."""
assert maxdist >= 2
tokens = list(tokens)
if maxdist > len(tokens):
maxdist = len(tokens)
l = len(... | python | def swap(tokens, maxdist=2):
"""Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations."""
assert maxdist >= 2
tokens = list(tokens)
if maxdist > len(tokens):
maxdist = len(tokens)
l = len(... | [
"def",
"swap",
"(",
"tokens",
",",
"maxdist",
"=",
"2",
")",
":",
"assert",
"maxdist",
">=",
"2",
"tokens",
"=",
"list",
"(",
"tokens",
")",
"if",
"maxdist",
">",
"len",
"(",
"tokens",
")",
":",
"maxdist",
"=",
"len",
"(",
"tokens",
")",
"l",
"="... | Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations. | [
"Perform",
"a",
"swap",
"operation",
"on",
"a",
"sequence",
"of",
"tokens",
"exhaustively",
"swapping",
"all",
"tokens",
"up",
"to",
"the",
"maximum",
"specified",
"distance",
".",
"This",
"is",
"a",
"subset",
"of",
"all",
"permutations",
"."
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L426-L441 |
proycon/pynlpl | pynlpl/textprocessors.py | find_keyword_in_context | def find_keyword_in_context(tokens, keyword, contextsize=1):
"""Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list"""
if isinstance(key... | python | def find_keyword_in_context(tokens, keyword, contextsize=1):
"""Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list"""
if isinstance(key... | [
"def",
"find_keyword_in_context",
"(",
"tokens",
",",
"keyword",
",",
"contextsize",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"keyword",
",",
"tuple",
")",
"and",
"isinstance",
"(",
"keyword",
",",
"list",
")",
":",
"l",
"=",
"len",
"(",
"keyword",
... | Find a keyword in a particular sequence of tokens, and return the local context. Contextsize is the number of words to the left and right. The keyword may have multiple word, in which case it should to passed as a tuple or list | [
"Find",
"a",
"keyword",
"in",
"a",
"particular",
"sequence",
"of",
"tokens",
"and",
"return",
"the",
"local",
"context",
".",
"Contextsize",
"is",
"the",
"number",
"of",
"words",
"to",
"the",
"left",
"and",
"right",
".",
"The",
"keyword",
"may",
"have",
... | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/textprocessors.py#L444-L455 |
proycon/pynlpl | pynlpl/datatypes.py | FIFOQueue.pop | def pop(self):
"""Retrieve the next element in line, this will remove it from the queue"""
e = self.data[self.start]
self.start += 1
if self.start > 5 and self.start > len(self.data)//2:
self.data = self.data[self.start:]
self.start = 0
return e | python | def pop(self):
"""Retrieve the next element in line, this will remove it from the queue"""
e = self.data[self.start]
self.start += 1
if self.start > 5 and self.start > len(self.data)//2:
self.data = self.data[self.start:]
self.start = 0
return e | [
"def",
"pop",
"(",
"self",
")",
":",
"e",
"=",
"self",
".",
"data",
"[",
"self",
".",
"start",
"]",
"self",
".",
"start",
"+=",
"1",
"if",
"self",
".",
"start",
">",
"5",
"and",
"self",
".",
"start",
">",
"len",
"(",
"self",
".",
"data",
")",... | Retrieve the next element in line, this will remove it from the queue | [
"Retrieve",
"the",
"next",
"element",
"in",
"line",
"this",
"will",
"remove",
"it",
"from",
"the",
"queue"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L65-L72 |
proycon/pynlpl | pynlpl/datatypes.py | PriorityQueue.append | def append(self, item):
"""Adds an item to the priority queue (in the right place), returns True if successfull, False if the item was blocked (because of a bad score)"""
f = self.f(item)
if callable(f):
score = f()
else:
score = f
if not self.duplicates:... | python | def append(self, item):
"""Adds an item to the priority queue (in the right place), returns True if successfull, False if the item was blocked (because of a bad score)"""
f = self.f(item)
if callable(f):
score = f()
else:
score = f
if not self.duplicates:... | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"f",
"=",
"self",
".",
"f",
"(",
"item",
")",
"if",
"callable",
"(",
"f",
")",
":",
"score",
"=",
"f",
"(",
")",
"else",
":",
"score",
"=",
"f",
"if",
"not",
"self",
".",
"duplicates",
":",... | Adds an item to the priority queue (in the right place), returns True if successfull, False if the item was blocked (because of a bad score) | [
"Adds",
"an",
"item",
"to",
"the",
"priority",
"queue",
"(",
"in",
"the",
"right",
"place",
")",
"returns",
"True",
"if",
"successfull",
"False",
"if",
"the",
"item",
"was",
"blocked",
"(",
"because",
"of",
"a",
"bad",
"score",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L97-L142 |
proycon/pynlpl | pynlpl/datatypes.py | PriorityQueue.pop | def pop(self):
"""Retrieve the next element in line, this will remove it from the queue"""
if self.minimize:
return self.data.pop(0)[1]
else:
return self.data.pop()[1] | python | def pop(self):
"""Retrieve the next element in line, this will remove it from the queue"""
if self.minimize:
return self.data.pop(0)[1]
else:
return self.data.pop()[1] | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"self",
".",
"minimize",
":",
"return",
"self",
".",
"data",
".",
"pop",
"(",
"0",
")",
"[",
"1",
"]",
"else",
":",
"return",
"self",
".",
"data",
".",
"pop",
"(",
")",
"[",
"1",
"]"
] | Retrieve the next element in line, this will remove it from the queue | [
"Retrieve",
"the",
"next",
"element",
"in",
"line",
"this",
"will",
"remove",
"it",
"from",
"the",
"queue"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L173-L178 |
proycon/pynlpl | pynlpl/datatypes.py | PriorityQueue.score | def score(self, i):
"""Return the score for item x (cheap lookup), Item 0 is always the best item"""
if self.minimize:
return self.data[i][0]
else:
return self.data[(-1 * i) - 1][0] | python | def score(self, i):
"""Return the score for item x (cheap lookup), Item 0 is always the best item"""
if self.minimize:
return self.data[i][0]
else:
return self.data[(-1 * i) - 1][0] | [
"def",
"score",
"(",
"self",
",",
"i",
")",
":",
"if",
"self",
".",
"minimize",
":",
"return",
"self",
".",
"data",
"[",
"i",
"]",
"[",
"0",
"]",
"else",
":",
"return",
"self",
".",
"data",
"[",
"(",
"-",
"1",
"*",
"i",
")",
"-",
"1",
"]",
... | Return the score for item x (cheap lookup), Item 0 is always the best item | [
"Return",
"the",
"score",
"for",
"item",
"x",
"(",
"cheap",
"lookup",
")",
"Item",
"0",
"is",
"always",
"the",
"best",
"item"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L181-L186 |
proycon/pynlpl | pynlpl/datatypes.py | PriorityQueue.prune | def prune(self, n):
"""prune all but the first (=best) n items"""
if self.minimize:
self.data = self.data[:n]
else:
self.data = self.data[-1 * n:] | python | def prune(self, n):
"""prune all but the first (=best) n items"""
if self.minimize:
self.data = self.data[:n]
else:
self.data = self.data[-1 * n:] | [
"def",
"prune",
"(",
"self",
",",
"n",
")",
":",
"if",
"self",
".",
"minimize",
":",
"self",
".",
"data",
"=",
"self",
".",
"data",
"[",
":",
"n",
"]",
"else",
":",
"self",
".",
"data",
"=",
"self",
".",
"data",
"[",
"-",
"1",
"*",
"n",
":"... | prune all but the first (=best) n items | [
"prune",
"all",
"but",
"the",
"first",
"(",
"=",
"best",
")",
"n",
"items"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L188-L193 |
proycon/pynlpl | pynlpl/datatypes.py | PriorityQueue.randomprune | def randomprune(self,n):
"""prune down to n items at random, disregarding their score"""
self.data = random.sample(self.data, n) | python | def randomprune(self,n):
"""prune down to n items at random, disregarding their score"""
self.data = random.sample(self.data, n) | [
"def",
"randomprune",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"data",
"=",
"random",
".",
"sample",
"(",
"self",
".",
"data",
",",
"n",
")"
] | prune down to n items at random, disregarding their score | [
"prune",
"down",
"to",
"n",
"items",
"at",
"random",
"disregarding",
"their",
"score"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L196-L198 |
proycon/pynlpl | pynlpl/datatypes.py | PriorityQueue.prunebyscore | def prunebyscore(self, score, retainequalscore=False):
"""Deletes all items below/above a certain score from the queue, depending on whether minimize is True or False. Note: It is recommended (more efficient) to use blockworse=True / blockequal=True instead! Preventing the addition of 'worse' items."""
... | python | def prunebyscore(self, score, retainequalscore=False):
"""Deletes all items below/above a certain score from the queue, depending on whether minimize is True or False. Note: It is recommended (more efficient) to use blockworse=True / blockequal=True instead! Preventing the addition of 'worse' items."""
... | [
"def",
"prunebyscore",
"(",
"self",
",",
"score",
",",
"retainequalscore",
"=",
"False",
")",
":",
"if",
"retainequalscore",
":",
"if",
"self",
".",
"minimize",
":",
"f",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
"<=",
"score",
"else",
":",
"f",
... | Deletes all items below/above a certain score from the queue, depending on whether minimize is True or False. Note: It is recommended (more efficient) to use blockworse=True / blockequal=True instead! Preventing the addition of 'worse' items. | [
"Deletes",
"all",
"items",
"below",
"/",
"above",
"a",
"certain",
"score",
"from",
"the",
"queue",
"depending",
"on",
"whether",
"minimize",
"is",
"True",
"or",
"False",
".",
"Note",
":",
"It",
"is",
"recommended",
"(",
"more",
"efficient",
")",
"to",
"u... | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L205-L217 |
proycon/pynlpl | pynlpl/datatypes.py | Tree.append | def append(self, item):
"""Add an item to the Tree"""
if not isinstance(item, Tree):
return ValueError("Can only append items of type Tree")
if not self.children: self.children = []
item.parent = self
self.children.append(item) | python | def append(self, item):
"""Add an item to the Tree"""
if not isinstance(item, Tree):
return ValueError("Can only append items of type Tree")
if not self.children: self.children = []
item.parent = self
self.children.append(item) | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"Tree",
")",
":",
"return",
"ValueError",
"(",
"\"Can only append items of type Tree\"",
")",
"if",
"not",
"self",
".",
"children",
":",
"self",
".",
"childre... | Add an item to the Tree | [
"Add",
"an",
"item",
"to",
"the",
"Tree"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L261-L267 |
proycon/pynlpl | pynlpl/datatypes.py | Trie.size | def size(self):
"""Size is number of nodes under the trie, including the current node"""
if self.children:
return sum( ( c.size() for c in self.children.values() ) ) + 1
else:
return 1 | python | def size(self):
"""Size is number of nodes under the trie, including the current node"""
if self.children:
return sum( ( c.size() for c in self.children.values() ) ) + 1
else:
return 1 | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"self",
".",
"children",
":",
"return",
"sum",
"(",
"(",
"c",
".",
"size",
"(",
")",
"for",
"c",
"in",
"self",
".",
"children",
".",
"values",
"(",
")",
")",
")",
"+",
"1",
"else",
":",
"return",
"1... | Size is number of nodes under the trie, including the current node | [
"Size",
"is",
"number",
"of",
"nodes",
"under",
"the",
"trie",
"including",
"the",
"current",
"node"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L361-L366 |
proycon/pynlpl | pynlpl/datatypes.py | Trie.walk | def walk(self, leavesonly=True, maxdepth=None, _depth = 0):
"""Depth-first search, walking through trie, returning all encounterd nodes (by default only leaves)"""
if self.children:
if not maxdepth or (maxdepth and _depth < maxdepth):
for key, child in self.children.items():
... | python | def walk(self, leavesonly=True, maxdepth=None, _depth = 0):
"""Depth-first search, walking through trie, returning all encounterd nodes (by default only leaves)"""
if self.children:
if not maxdepth or (maxdepth and _depth < maxdepth):
for key, child in self.children.items():
... | [
"def",
"walk",
"(",
"self",
",",
"leavesonly",
"=",
"True",
",",
"maxdepth",
"=",
"None",
",",
"_depth",
"=",
"0",
")",
":",
"if",
"self",
".",
"children",
":",
"if",
"not",
"maxdepth",
"or",
"(",
"maxdepth",
"and",
"_depth",
"<",
"maxdepth",
")",
... | Depth-first search, walking through trie, returning all encounterd nodes (by default only leaves) | [
"Depth",
"-",
"first",
"search",
"walking",
"through",
"trie",
"returning",
"all",
"encounterd",
"nodes",
"(",
"by",
"default",
"only",
"leaves",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/datatypes.py#L392-L401 |
proycon/pynlpl | pynlpl/formats/sonar.py | CorpusDocument.sentences | def sentences(self):
"""Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma)"""
prevp = 0
prevs = 0
sentence = [];
sentence_id = ""
for word, id, pos, lemma in iter(self):
try:
d... | python | def sentences(self):
"""Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma)"""
prevp = 0
prevs = 0
sentence = [];
sentence_id = ""
for word, id, pos, lemma in iter(self):
try:
d... | [
"def",
"sentences",
"(",
"self",
")",
":",
"prevp",
"=",
"0",
"prevs",
"=",
"0",
"sentence",
"=",
"[",
"]",
"sentence_id",
"=",
"\"\"",
"for",
"word",
",",
"id",
",",
"pos",
",",
"lemma",
"in",
"iter",
"(",
"self",
")",
":",
"try",
":",
"doc_id",... | Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma) | [
"Iterate",
"over",
"all",
"sentences",
"(",
"sentence_id",
"sentence",
")",
"in",
"the",
"document",
"sentence",
"is",
"a",
"list",
"of",
"4",
"-",
"tuples",
"(",
"word",
"id",
"pos",
"lemma",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/sonar.py#L85-L108 |
proycon/pynlpl | pynlpl/formats/sonar.py | CorpusDocument.paragraphs | def paragraphs(self, with_id = False):
"""Extracts paragraphs, returns list of plain-text(!) paragraphs"""
prevp = 0
partext = []
for word, id, pos, lemma in iter(self):
doc_id, ptype, p, s, w = re.findall('([\w\d-]+)\.(p|head)\.(\d+)\.s\.(\d+)\.w\.(\d+)',id)[0]
i... | python | def paragraphs(self, with_id = False):
"""Extracts paragraphs, returns list of plain-text(!) paragraphs"""
prevp = 0
partext = []
for word, id, pos, lemma in iter(self):
doc_id, ptype, p, s, w = re.findall('([\w\d-]+)\.(p|head)\.(\d+)\.s\.(\d+)\.w\.(\d+)',id)[0]
i... | [
"def",
"paragraphs",
"(",
"self",
",",
"with_id",
"=",
"False",
")",
":",
"prevp",
"=",
"0",
"partext",
"=",
"[",
"]",
"for",
"word",
",",
"id",
",",
"pos",
",",
"lemma",
"in",
"iter",
"(",
"self",
")",
":",
"doc_id",
",",
"ptype",
",",
"p",
",... | Extracts paragraphs, returns list of plain-text(!) paragraphs | [
"Extracts",
"paragraphs",
"returns",
"list",
"of",
"plain",
"-",
"text",
"(",
"!",
")",
"paragraphs"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/sonar.py#L110-L122 |
proycon/pynlpl | pynlpl/formats/sonar.py | CorpusDocumentX.validate | def validate(self, formats_dir="../formats/"):
"""checks if the document is valid"""
#TODO: download XSD from web
if self.inline:
xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines()))))
xmlschema.assertValid(... | python | def validate(self, formats_dir="../formats/"):
"""checks if the document is valid"""
#TODO: download XSD from web
if self.inline:
xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines()))))
xmlschema.assertValid(... | [
"def",
"validate",
"(",
"self",
",",
"formats_dir",
"=",
"\"../formats/\"",
")",
":",
"#TODO: download XSD from web",
"if",
"self",
".",
"inline",
":",
"xmlschema",
"=",
"ElementTree",
".",
"XMLSchema",
"(",
"ElementTree",
".",
"parse",
"(",
"StringIO",
"(",
"... | checks if the document is valid | [
"checks",
"if",
"the",
"document",
"is",
"valid"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/sonar.py#L235-L244 |
proycon/pynlpl | pynlpl/formats/sonar.py | CorpusDocumentX.xpath | def xpath(self, expression):
"""Executes an xpath expression using the correct namespaces"""
global namespaces
return self.tree.xpath(expression, namespaces=namespaces) | python | def xpath(self, expression):
"""Executes an xpath expression using the correct namespaces"""
global namespaces
return self.tree.xpath(expression, namespaces=namespaces) | [
"def",
"xpath",
"(",
"self",
",",
"expression",
")",
":",
"global",
"namespaces",
"return",
"self",
".",
"tree",
".",
"xpath",
"(",
"expression",
",",
"namespaces",
"=",
"namespaces",
")"
] | Executes an xpath expression using the correct namespaces | [
"Executes",
"an",
"xpath",
"expression",
"using",
"the",
"correct",
"namespaces"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/sonar.py#L247-L250 |
proycon/pynlpl | pynlpl/formats/taggerdata.py | Taggerdata.align | def align(self, referencewords, datatuple):
"""align the reference sentence with the tagged data"""
targetwords = []
for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])):
if word:
subwords = word.split("_")
for w in subw... | python | def align(self, referencewords, datatuple):
"""align the reference sentence with the tagged data"""
targetwords = []
for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])):
if word:
subwords = word.split("_")
for w in subw... | [
"def",
"align",
"(",
"self",
",",
"referencewords",
",",
"datatuple",
")",
":",
"targetwords",
"=",
"[",
"]",
"for",
"i",
",",
"(",
"word",
",",
"lemma",
",",
"postag",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"datatuple",
"[",
"0",
"]",
",",
"data... | align the reference sentence with the tagged data | [
"align",
"the",
"reference",
"sentence",
"with",
"the",
"tagged",
"data"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/taggerdata.py#L99-L125 |
proycon/pynlpl | pynlpl/formats/foliaset.py | SetDefinition.mainset | def mainset(self):
"""Returns information regarding the set"""
if self.mainsetcache:
return self.mainsetcache
set_uri = self.get_set_uri()
for row in self.graph.query("SELECT ?seturi ?setid ?setlabel ?setopen ?setempty WHERE { ?seturi rdf:type skos:Collection . OPTIONAL { ?se... | python | def mainset(self):
"""Returns information regarding the set"""
if self.mainsetcache:
return self.mainsetcache
set_uri = self.get_set_uri()
for row in self.graph.query("SELECT ?seturi ?setid ?setlabel ?setopen ?setempty WHERE { ?seturi rdf:type skos:Collection . OPTIONAL { ?se... | [
"def",
"mainset",
"(",
"self",
")",
":",
"if",
"self",
".",
"mainsetcache",
":",
"return",
"self",
".",
"mainsetcache",
"set_uri",
"=",
"self",
".",
"get_set_uri",
"(",
")",
"for",
"row",
"in",
"self",
".",
"graph",
".",
"query",
"(",
"\"SELECT ?seturi ?... | Returns information regarding the set | [
"Returns",
"information",
"regarding",
"the",
"set"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/foliaset.py#L351-L359 |
proycon/pynlpl | pynlpl/formats/foliaset.py | SetDefinition.subset | def subset(self, subset_id):
"""Returns information regarding the set"""
if subset_id in self.subsetcache:
return self.subsetcache[subset_id]
set_uri = self.get_set_uri(subset_id)
for row in self.graph.query("SELECT ?seturi ?setid ?setlabel ?setopen WHERE { ?seturi rdf:type s... | python | def subset(self, subset_id):
"""Returns information regarding the set"""
if subset_id in self.subsetcache:
return self.subsetcache[subset_id]
set_uri = self.get_set_uri(subset_id)
for row in self.graph.query("SELECT ?seturi ?setid ?setlabel ?setopen WHERE { ?seturi rdf:type s... | [
"def",
"subset",
"(",
"self",
",",
"subset_id",
")",
":",
"if",
"subset_id",
"in",
"self",
".",
"subsetcache",
":",
"return",
"self",
".",
"subsetcache",
"[",
"subset_id",
"]",
"set_uri",
"=",
"self",
".",
"get_set_uri",
"(",
"subset_id",
")",
"for",
"ro... | Returns information regarding the set | [
"Returns",
"information",
"regarding",
"the",
"set"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/foliaset.py#L361-L369 |
proycon/pynlpl | pynlpl/formats/foliaset.py | SetDefinition.orderedclasses | def orderedclasses(self, set_uri_or_id=None, nestedhierarchy=False):
"""Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder`"""
classes = self.classes(set_uri_or_id, nestedhierarchy)
... | python | def orderedclasses(self, set_uri_or_id=None, nestedhierarchy=False):
"""Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder`"""
classes = self.classes(set_uri_or_id, nestedhierarchy)
... | [
"def",
"orderedclasses",
"(",
"self",
",",
"set_uri_or_id",
"=",
"None",
",",
"nestedhierarchy",
"=",
"False",
")",
":",
"classes",
"=",
"self",
".",
"classes",
"(",
"set_uri_or_id",
",",
"nestedhierarchy",
")",
"for",
"classid",
"in",
"self",
".",
"classord... | Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder` | [
"Higher",
"-",
"order",
"generator",
"function",
"that",
"yields",
"class",
"information",
"in",
"the",
"right",
"order",
"combines",
"calls",
"to",
":",
"meth",
":",
"SetDefinition",
".",
"classes",
"and",
":",
"meth",
":",
"SetDefinition",
".",
"classorder"
... | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/foliaset.py#L371-L375 |
proycon/pynlpl | pynlpl/formats/foliaset.py | SetDefinition.classes | def classes(self, set_uri_or_id=None, nestedhierarchy=False):
"""Returns a dictionary of classes for the specified (sub)set (if None, default, the main set is selected)"""
if set_uri_or_id and set_uri_or_id.startswith(('http://','https://')):
set_uri = set_uri_or_id
else:
... | python | def classes(self, set_uri_or_id=None, nestedhierarchy=False):
"""Returns a dictionary of classes for the specified (sub)set (if None, default, the main set is selected)"""
if set_uri_or_id and set_uri_or_id.startswith(('http://','https://')):
set_uri = set_uri_or_id
else:
... | [
"def",
"classes",
"(",
"self",
",",
"set_uri_or_id",
"=",
"None",
",",
"nestedhierarchy",
"=",
"False",
")",
":",
"if",
"set_uri_or_id",
"and",
"set_uri_or_id",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"set_uri",
"=",
"se... | Returns a dictionary of classes for the specified (sub)set (if None, default, the main set is selected) | [
"Returns",
"a",
"dictionary",
"of",
"classes",
"for",
"the",
"specified",
"(",
"sub",
")",
"set",
"(",
"if",
"None",
"default",
"the",
"main",
"set",
"is",
"selected",
")"
] | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/foliaset.py#L381-L414 |
proycon/pynlpl | pynlpl/formats/foliaset.py | SetDefinition.classorder | def classorder(self,classes):
"""Return a list of class IDs in order for presentational purposes: order is determined first and foremost by explicit ordering, else alphabetically by label or as a last resort by class ID"""
return [ classid for classid, classitem in sorted( ((classid, classitem) for clas... | python | def classorder(self,classes):
"""Return a list of class IDs in order for presentational purposes: order is determined first and foremost by explicit ordering, else alphabetically by label or as a last resort by class ID"""
return [ classid for classid, classitem in sorted( ((classid, classitem) for clas... | [
"def",
"classorder",
"(",
"self",
",",
"classes",
")",
":",
"return",
"[",
"classid",
"for",
"classid",
",",
"classitem",
"in",
"sorted",
"(",
"(",
"(",
"classid",
",",
"classitem",
")",
"for",
"classid",
",",
"classitem",
"in",
"classes",
".",
"items",
... | Return a list of class IDs in order for presentational purposes: order is determined first and foremost by explicit ordering, else alphabetically by label or as a last resort by class ID | [
"Return",
"a",
"list",
"of",
"class",
"IDs",
"in",
"order",
"for",
"presentational",
"purposes",
":",
"order",
"is",
"determined",
"first",
"and",
"foremost",
"by",
"explicit",
"ordering",
"else",
"alphabetically",
"by",
"label",
"or",
"as",
"a",
"last",
"re... | train | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/foliaset.py#L416-L419 |
scrapinghub/js2xml | js2xml/lexer.py | CustomLexer.build | def build(self, **kwargs):
"""Build the lexer."""
self.lexer = ply.lex.lex(object=self, **kwargs) | python | def build(self, **kwargs):
"""Build the lexer."""
self.lexer = ply.lex.lex(object=self, **kwargs) | [
"def",
"build",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"lexer",
"=",
"ply",
".",
"lex",
".",
"lex",
"(",
"object",
"=",
"self",
",",
"*",
"*",
"kwargs",
")"
] | Build the lexer. | [
"Build",
"the",
"lexer",
"."
] | train | https://github.com/scrapinghub/js2xml/blob/d01b79e1a82de157deffcc1a22f4e0b6bfa07715/js2xml/lexer.py#L74-L76 |
scrapinghub/js2xml | js2xml/utils/vars.py | make_varname | def make_varname(tree):
"""
<left> tree </left>
"""
if tree.tag == 'identifier':
return tree.attrib['name']
if tree.tag in ('string', 'boolean'):
return tree.text
if tree.tag == 'number':
return tree.attrib['value']
if tree.tag in ('property', 'object'):
re... | python | def make_varname(tree):
"""
<left> tree </left>
"""
if tree.tag == 'identifier':
return tree.attrib['name']
if tree.tag in ('string', 'boolean'):
return tree.text
if tree.tag == 'number':
return tree.attrib['value']
if tree.tag in ('property', 'object'):
re... | [
"def",
"make_varname",
"(",
"tree",
")",
":",
"if",
"tree",
".",
"tag",
"==",
"'identifier'",
":",
"return",
"tree",
".",
"attrib",
"[",
"'name'",
"]",
"if",
"tree",
".",
"tag",
"in",
"(",
"'string'",
",",
"'boolean'",
")",
":",
"return",
"tree",
"."... | <left> tree </left> | [
"<left",
">",
"tree",
"<",
"/",
"left",
">"
] | train | https://github.com/scrapinghub/js2xml/blob/d01b79e1a82de157deffcc1a22f4e0b6bfa07715/js2xml/utils/vars.py#L55-L83 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | _users_from_environ | def _users_from_environ(env_prefix=''):
"""Environment value via `user:password|user2:password2`"""
auth_string = os.environ.get(env_prefix + 'WSGI_AUTH_CREDENTIALS')
if not auth_string:
return {}
result = {}
for credentials in auth_string.split('|'):
username, password = credential... | python | def _users_from_environ(env_prefix=''):
"""Environment value via `user:password|user2:password2`"""
auth_string = os.environ.get(env_prefix + 'WSGI_AUTH_CREDENTIALS')
if not auth_string:
return {}
result = {}
for credentials in auth_string.split('|'):
username, password = credential... | [
"def",
"_users_from_environ",
"(",
"env_prefix",
"=",
"''",
")",
":",
"auth_string",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_prefix",
"+",
"'WSGI_AUTH_CREDENTIALS'",
")",
"if",
"not",
"auth_string",
":",
"return",
"{",
"}",
"result",
"=",
"{",
"}"... | Environment value via `user:password|user2:password2` | [
"Environment",
"value",
"via",
"user",
":",
"password|user2",
":",
"password2"
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L102-L112 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | _exclude_paths_from_environ | def _exclude_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_EXCLUDE_PATHS')
if not paths:
return []
return paths.split(';') | python | def _exclude_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_EXCLUDE_PATHS')
if not paths:
return []
return paths.split(';') | [
"def",
"_exclude_paths_from_environ",
"(",
"env_prefix",
"=",
"''",
")",
":",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_prefix",
"+",
"'WSGI_AUTH_EXCLUDE_PATHS'",
")",
"if",
"not",
"paths",
":",
"return",
"[",
"]",
"return",
"paths",
".",
"... | Environment value via `/login;/register` | [
"Environment",
"value",
"via",
"/",
"login",
";",
"/",
"register"
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L115-L120 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | _include_paths_from_environ | def _include_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_PATHS')
if not paths:
return []
return paths.split(';') | python | def _include_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_PATHS')
if not paths:
return []
return paths.split(';') | [
"def",
"_include_paths_from_environ",
"(",
"env_prefix",
"=",
"''",
")",
":",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"env_prefix",
"+",
"'WSGI_AUTH_PATHS'",
")",
"if",
"not",
"paths",
":",
"return",
"[",
"]",
"return",
"paths",
".",
"split",
... | Environment value via `/login;/register` | [
"Environment",
"value",
"via",
"/",
"login",
";",
"/",
"register"
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L123-L128 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | BasicAuth.is_authorized | def is_authorized(self, request):
"""Check if the user is authenticated for the given request.
The include_paths and exclude_paths are first checked. If
authentication is required then the Authorization HTTP header is
checked against the credentials.
"""
if self._is_req... | python | def is_authorized(self, request):
"""Check if the user is authenticated for the given request.
The include_paths and exclude_paths are first checked. If
authentication is required then the Authorization HTTP header is
checked against the credentials.
"""
if self._is_req... | [
"def",
"is_authorized",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"_is_request_in_include_path",
"(",
"request",
")",
":",
"if",
"self",
".",
"_is_request_in_exclude_path",
"(",
"request",
")",
":",
"return",
"True",
"else",
":",
"auth",
"=",... | Check if the user is authenticated for the given request.
The include_paths and exclude_paths are first checked. If
authentication is required then the Authorization HTTP header is
checked against the credentials. | [
"Check",
"if",
"the",
"user",
"is",
"authenticated",
"for",
"the",
"given",
"request",
"."
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L48-L68 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | BasicAuth._login | def _login(self, environ, start_response):
"""Send a login response back to the client."""
response = HTTPUnauthorized()
response.www_authenticate = ('Basic', {'realm': self._realm})
return response(environ, start_response) | python | def _login(self, environ, start_response):
"""Send a login response back to the client."""
response = HTTPUnauthorized()
response.www_authenticate = ('Basic', {'realm': self._realm})
return response(environ, start_response) | [
"def",
"_login",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"response",
"=",
"HTTPUnauthorized",
"(",
")",
"response",
".",
"www_authenticate",
"=",
"(",
"'Basic'",
",",
"{",
"'realm'",
":",
"self",
".",
"_realm",
"}",
")",
"return",
"... | Send a login response back to the client. | [
"Send",
"a",
"login",
"response",
"back",
"to",
"the",
"client",
"."
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L70-L74 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | BasicAuth._is_request_in_include_path | def _is_request_in_include_path(self, request):
"""Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths.
"""
if self._include_paths:
for path in self._include_p... | python | def _is_request_in_include_path(self, request):
"""Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths.
"""
if self._include_paths:
for path in self._include_p... | [
"def",
"_is_request_in_include_path",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"_include_paths",
":",
"for",
"path",
"in",
"self",
".",
"_include_paths",
":",
"if",
"request",
".",
"path",
".",
"startswith",
"(",
"path",
")",
":",
"return"... | Check if the request path is in the `_include_paths` list.
If no specific include paths are given then we assume that
authentication is required for all paths. | [
"Check",
"if",
"the",
"request",
"path",
"is",
"in",
"the",
"_include_paths",
"list",
"."
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L76-L89 |
mvantellingen/wsgi-basic-auth | src/wsgi_basic_auth.py | BasicAuth._is_request_in_exclude_path | def _is_request_in_exclude_path(self, request):
"""Check if the request path is in the `_exclude_paths` list"""
if self._exclude_paths:
for path in self._exclude_paths:
if request.path.startswith(path):
return True
return False
else:
... | python | def _is_request_in_exclude_path(self, request):
"""Check if the request path is in the `_exclude_paths` list"""
if self._exclude_paths:
for path in self._exclude_paths:
if request.path.startswith(path):
return True
return False
else:
... | [
"def",
"_is_request_in_exclude_path",
"(",
"self",
",",
"request",
")",
":",
"if",
"self",
".",
"_exclude_paths",
":",
"for",
"path",
"in",
"self",
".",
"_exclude_paths",
":",
"if",
"request",
".",
"path",
".",
"startswith",
"(",
"path",
")",
":",
"return"... | Check if the request path is in the `_exclude_paths` list | [
"Check",
"if",
"the",
"request",
"path",
"is",
"in",
"the",
"_exclude_paths",
"list"
] | train | https://github.com/mvantellingen/wsgi-basic-auth/blob/4e829bff21526f587f8d1a8592b63e1abd862a74/src/wsgi_basic_auth.py#L91-L99 |
click-contrib/click-repl | click_repl/__init__.py | bootstrap_prompt | def bootstrap_prompt(prompt_kwargs, group):
"""
Bootstrap prompt_toolkit kwargs or use user defined values.
:param prompt_kwargs: The user specified prompt kwargs.
"""
prompt_kwargs = prompt_kwargs or {}
defaults = {
"history": InMemoryHistory(),
"completer": ClickCompleter(gro... | python | def bootstrap_prompt(prompt_kwargs, group):
"""
Bootstrap prompt_toolkit kwargs or use user defined values.
:param prompt_kwargs: The user specified prompt kwargs.
"""
prompt_kwargs = prompt_kwargs or {}
defaults = {
"history": InMemoryHistory(),
"completer": ClickCompleter(gro... | [
"def",
"bootstrap_prompt",
"(",
"prompt_kwargs",
",",
"group",
")",
":",
"prompt_kwargs",
"=",
"prompt_kwargs",
"or",
"{",
"}",
"defaults",
"=",
"{",
"\"history\"",
":",
"InMemoryHistory",
"(",
")",
",",
"\"completer\"",
":",
"ClickCompleter",
"(",
"group",
")... | Bootstrap prompt_toolkit kwargs or use user defined values.
:param prompt_kwargs: The user specified prompt kwargs. | [
"Bootstrap",
"prompt_toolkit",
"kwargs",
"or",
"use",
"user",
"defined",
"values",
"."
] | train | https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L146-L165 |
click-contrib/click-repl | click_repl/__init__.py | repl | def repl( # noqa: C901
old_ctx,
prompt_kwargs=None,
allow_system_commands=True,
allow_internal_commands=True,
):
"""
Start an interactive shell. All subcommands are available in it.
:param old_ctx: The current Click context.
:param prompt_kwargs: Parameters passed to
:py:func:`... | python | def repl( # noqa: C901
old_ctx,
prompt_kwargs=None,
allow_system_commands=True,
allow_internal_commands=True,
):
"""
Start an interactive shell. All subcommands are available in it.
:param old_ctx: The current Click context.
:param prompt_kwargs: Parameters passed to
:py:func:`... | [
"def",
"repl",
"(",
"# noqa: C901",
"old_ctx",
",",
"prompt_kwargs",
"=",
"None",
",",
"allow_system_commands",
"=",
"True",
",",
"allow_internal_commands",
"=",
"True",
",",
")",
":",
"# parent should be available, but we're not going to bother if not",
"group_ctx",
"=",... | Start an interactive shell. All subcommands are available in it.
:param old_ctx: The current Click context.
:param prompt_kwargs: Parameters passed to
:py:func:`prompt_toolkit.shortcuts.prompt`.
If stdin is not a TTY, no prompt will be printed, but only commands read
from stdin. | [
"Start",
"an",
"interactive",
"shell",
".",
"All",
"subcommands",
"are",
"available",
"in",
"it",
"."
] | train | https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L168-L257 |
click-contrib/click-repl | click_repl/__init__.py | register_repl | def register_repl(group, name="repl"):
"""Register :func:`repl()` as sub-command *name* of *group*."""
group.command(name=name)(click.pass_context(repl)) | python | def register_repl(group, name="repl"):
"""Register :func:`repl()` as sub-command *name* of *group*."""
group.command(name=name)(click.pass_context(repl)) | [
"def",
"register_repl",
"(",
"group",
",",
"name",
"=",
"\"repl\"",
")",
":",
"group",
".",
"command",
"(",
"name",
"=",
"name",
")",
"(",
"click",
".",
"pass_context",
"(",
"repl",
")",
")"
] | Register :func:`repl()` as sub-command *name* of *group*. | [
"Register",
":",
"func",
":",
"repl",
"()",
"as",
"sub",
"-",
"command",
"*",
"name",
"*",
"of",
"*",
"group",
"*",
"."
] | train | https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L260-L262 |
click-contrib/click-repl | click_repl/__init__.py | handle_internal_commands | def handle_internal_commands(command):
"""Run repl-internal commands.
Repl-internal commands are all commands starting with ":".
"""
if command.startswith(":"):
target = _get_registered_target(command[1:], default=None)
if target:
return target() | python | def handle_internal_commands(command):
"""Run repl-internal commands.
Repl-internal commands are all commands starting with ":".
"""
if command.startswith(":"):
target = _get_registered_target(command[1:], default=None)
if target:
return target() | [
"def",
"handle_internal_commands",
"(",
"command",
")",
":",
"if",
"command",
".",
"startswith",
"(",
"\":\"",
")",
":",
"target",
"=",
"_get_registered_target",
"(",
"command",
"[",
"1",
":",
"]",
",",
"default",
"=",
"None",
")",
"if",
"target",
":",
"... | Run repl-internal commands.
Repl-internal commands are all commands starting with ":". | [
"Run",
"repl",
"-",
"internal",
"commands",
"."
] | train | https://github.com/click-contrib/click-repl/blob/2d78dc520eb0bb5b813bad3b72344edbd22a7f4e/click_repl/__init__.py#L283-L292 |
nel215/ksvd | ksvd/__init__.py | ApproximateKSVD.fit | def fit(self, X):
"""
Parameters
----------
X: shape = [n_samples, n_features]
"""
D = self._initialize(X)
for i in range(self.max_iter):
gamma = self._transform(D, X)
e = np.linalg.norm(X - gamma.dot(D))
if e < self.tol:
... | python | def fit(self, X):
"""
Parameters
----------
X: shape = [n_samples, n_features]
"""
D = self._initialize(X)
for i in range(self.max_iter):
gamma = self._transform(D, X)
e = np.linalg.norm(X - gamma.dot(D))
if e < self.tol:
... | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"D",
"=",
"self",
".",
"_initialize",
"(",
"X",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"max_iter",
")",
":",
"gamma",
"=",
"self",
".",
"_transform",
"(",
"D",
",",
"X",
")",
"e",
"=",... | Parameters
----------
X: shape = [n_samples, n_features] | [
"Parameters",
"----------",
"X",
":",
"shape",
"=",
"[",
"n_samples",
"n_features",
"]"
] | train | https://github.com/nel215/ksvd/blob/917f65a9f15ee7689253b27f0107a9773cf837f6/ksvd/__init__.py#L67-L82 |
graphql-python/graphql-relay-py | graphql_relay/node/node.py | node_definitions | def node_definitions(id_fetcher, type_resolver=None, id_resolver=None):
'''
Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a... | python | def node_definitions(id_fetcher, type_resolver=None, id_resolver=None):
'''
Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a... | [
"def",
"node_definitions",
"(",
"id_fetcher",
",",
"type_resolver",
"=",
"None",
",",
"id_resolver",
"=",
"None",
")",
":",
"node_interface",
"=",
"GraphQLInterfaceType",
"(",
"'Node'",
",",
"description",
"=",
"'An object with an ID'",
",",
"fields",
"=",
"lambda... | Given a function to map from an ID to an underlying object, and a function
to map from an underlying object to the concrete GraphQLObjectType it
corresponds to, constructs a `Node` interface that objects can implement,
and a field config for a `node` root field.
If the type_resolver is omitted, object ... | [
"Given",
"a",
"function",
"to",
"map",
"from",
"an",
"ID",
"to",
"an",
"underlying",
"object",
"and",
"a",
"function",
"to",
"map",
"from",
"an",
"underlying",
"object",
"to",
"the",
"concrete",
"GraphQLObjectType",
"it",
"corresponds",
"to",
"constructs",
"... | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/node/node.py#L15-L49 |
graphql-python/graphql-relay-py | graphql_relay/node/node.py | from_global_id | def from_global_id(global_id):
'''
Takes the "global ID" created by toGlobalID, and retuns the type name and ID
used to create it.
'''
unbased_global_id = unbase64(global_id)
_type, _id = unbased_global_id.split(':', 1)
return _type, _id | python | def from_global_id(global_id):
'''
Takes the "global ID" created by toGlobalID, and retuns the type name and ID
used to create it.
'''
unbased_global_id = unbase64(global_id)
_type, _id = unbased_global_id.split(':', 1)
return _type, _id | [
"def",
"from_global_id",
"(",
"global_id",
")",
":",
"unbased_global_id",
"=",
"unbase64",
"(",
"global_id",
")",
"_type",
",",
"_id",
"=",
"unbased_global_id",
".",
"split",
"(",
"':'",
",",
"1",
")",
"return",
"_type",
",",
"_id"
] | Takes the "global ID" created by toGlobalID, and retuns the type name and ID
used to create it. | [
"Takes",
"the",
"global",
"ID",
"created",
"by",
"toGlobalID",
"and",
"retuns",
"the",
"type",
"name",
"and",
"ID",
"used",
"to",
"create",
"it",
"."
] | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/node/node.py#L60-L67 |
graphql-python/graphql-relay-py | graphql_relay/node/node.py | global_id_field | def global_id_field(type_name, id_fetcher=None):
'''
Creates the configuration for an id field on a node, using `to_global_id` to
construct the ID from the provided typename. The type-specific ID is fetcher
by calling id_fetcher on the object, or if not provided, by accessing the `id`
property on th... | python | def global_id_field(type_name, id_fetcher=None):
'''
Creates the configuration for an id field on a node, using `to_global_id` to
construct the ID from the provided typename. The type-specific ID is fetcher
by calling id_fetcher on the object, or if not provided, by accessing the `id`
property on th... | [
"def",
"global_id_field",
"(",
"type_name",
",",
"id_fetcher",
"=",
"None",
")",
":",
"return",
"GraphQLField",
"(",
"GraphQLNonNull",
"(",
"GraphQLID",
")",
",",
"description",
"=",
"'The ID of an object'",
",",
"resolver",
"=",
"lambda",
"obj",
",",
"args",
... | Creates the configuration for an id field on a node, using `to_global_id` to
construct the ID from the provided typename. The type-specific ID is fetcher
by calling id_fetcher on the object, or if not provided, by accessing the `id`
property on the object. | [
"Creates",
"the",
"configuration",
"for",
"an",
"id",
"field",
"on",
"a",
"node",
"using",
"to_global_id",
"to",
"construct",
"the",
"ID",
"from",
"the",
"provided",
"typename",
".",
"The",
"type",
"-",
"specific",
"ID",
"is",
"fetcher",
"by",
"calling",
"... | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/node/node.py#L70-L84 |
graphql-python/graphql-relay-py | graphql_relay/connection/arrayconnection.py | connection_from_list | def connection_from_list(data, args=None, **kwargs):
'''
A simple function that accepts an array and connection arguments, and returns
a connection object for use in GraphQL. It uses array offsets as pagination,
so pagination will only work if the array is static.
'''
_len = len(data)
return... | python | def connection_from_list(data, args=None, **kwargs):
'''
A simple function that accepts an array and connection arguments, and returns
a connection object for use in GraphQL. It uses array offsets as pagination,
so pagination will only work if the array is static.
'''
_len = len(data)
return... | [
"def",
"connection_from_list",
"(",
"data",
",",
"args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_len",
"=",
"len",
"(",
"data",
")",
"return",
"connection_from_list_slice",
"(",
"data",
",",
"args",
",",
"slice_start",
"=",
"0",
",",
"list_leng... | A simple function that accepts an array and connection arguments, and returns
a connection object for use in GraphQL. It uses array offsets as pagination,
so pagination will only work if the array is static. | [
"A",
"simple",
"function",
"that",
"accepts",
"an",
"array",
"and",
"connection",
"arguments",
"and",
"returns",
"a",
"connection",
"object",
"for",
"use",
"in",
"GraphQL",
".",
"It",
"uses",
"array",
"offsets",
"as",
"pagination",
"so",
"pagination",
"will",
... | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/connection/arrayconnection.py#L7-L21 |
graphql-python/graphql-relay-py | graphql_relay/connection/arrayconnection.py | connection_from_promised_list | def connection_from_promised_list(data_promise, args=None, **kwargs):
'''
A version of `connectionFromArray` that takes a promised array, and returns a
promised connection.
'''
return data_promise.then(lambda data: connection_from_list(data, args, **kwargs)) | python | def connection_from_promised_list(data_promise, args=None, **kwargs):
'''
A version of `connectionFromArray` that takes a promised array, and returns a
promised connection.
'''
return data_promise.then(lambda data: connection_from_list(data, args, **kwargs)) | [
"def",
"connection_from_promised_list",
"(",
"data_promise",
",",
"args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"data_promise",
".",
"then",
"(",
"lambda",
"data",
":",
"connection_from_list",
"(",
"data",
",",
"args",
",",
"*",
"*",
"k... | A version of `connectionFromArray` that takes a promised array, and returns a
promised connection. | [
"A",
"version",
"of",
"connectionFromArray",
"that",
"takes",
"a",
"promised",
"array",
"and",
"returns",
"a",
"promised",
"connection",
"."
] | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/connection/arrayconnection.py#L24-L29 |
graphql-python/graphql-relay-py | graphql_relay/connection/arrayconnection.py | connection_from_list_slice | def connection_from_list_slice(list_slice, args=None, connection_type=None,
edge_type=None, pageinfo_type=None,
slice_start=0, list_length=0, list_slice_length=None):
'''
Given a slice (subset) of an array, returns a connection object for use in
... | python | def connection_from_list_slice(list_slice, args=None, connection_type=None,
edge_type=None, pageinfo_type=None,
slice_start=0, list_length=0, list_slice_length=None):
'''
Given a slice (subset) of an array, returns a connection object for use in
... | [
"def",
"connection_from_list_slice",
"(",
"list_slice",
",",
"args",
"=",
"None",
",",
"connection_type",
"=",
"None",
",",
"edge_type",
"=",
"None",
",",
"pageinfo_type",
"=",
"None",
",",
"slice_start",
"=",
"0",
",",
"list_length",
"=",
"0",
",",
"list_sl... | Given a slice (subset) of an array, returns a connection object for use in
GraphQL.
This function is similar to `connectionFromArray`, but is intended for use
cases where you know the cardinality of the connection, consider it too large
to materialize the entire array, and instead wish pass in a slice o... | [
"Given",
"a",
"slice",
"(",
"subset",
")",
"of",
"an",
"array",
"returns",
"a",
"connection",
"object",
"for",
"use",
"in",
"GraphQL",
".",
"This",
"function",
"is",
"similar",
"to",
"connectionFromArray",
"but",
"is",
"intended",
"for",
"use",
"cases",
"w... | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/connection/arrayconnection.py#L32-L107 |
graphql-python/graphql-relay-py | graphql_relay/connection/arrayconnection.py | cursor_for_object_in_connection | def cursor_for_object_in_connection(data, _object):
'''
Return the cursor associated with an object in an array.
'''
if _object not in data:
return None
offset = data.index(_object)
return offset_to_cursor(offset) | python | def cursor_for_object_in_connection(data, _object):
'''
Return the cursor associated with an object in an array.
'''
if _object not in data:
return None
offset = data.index(_object)
return offset_to_cursor(offset) | [
"def",
"cursor_for_object_in_connection",
"(",
"data",
",",
"_object",
")",
":",
"if",
"_object",
"not",
"in",
"data",
":",
"return",
"None",
"offset",
"=",
"data",
".",
"index",
"(",
"_object",
")",
"return",
"offset_to_cursor",
"(",
"offset",
")"
] | Return the cursor associated with an object in an array. | [
"Return",
"the",
"cursor",
"associated",
"with",
"an",
"object",
"in",
"an",
"array",
"."
] | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/connection/arrayconnection.py#L134-L142 |
graphql-python/graphql-relay-py | graphql_relay/connection/arrayconnection.py | get_offset_with_default | def get_offset_with_default(cursor=None, default_offset=0):
'''
Given an optional cursor and a default offset, returns the offset
to use; if the cursor contains a valid offset, that will be used,
otherwise it will be the default.
'''
if not is_str(cursor):
return default_offset
offs... | python | def get_offset_with_default(cursor=None, default_offset=0):
'''
Given an optional cursor and a default offset, returns the offset
to use; if the cursor contains a valid offset, that will be used,
otherwise it will be the default.
'''
if not is_str(cursor):
return default_offset
offs... | [
"def",
"get_offset_with_default",
"(",
"cursor",
"=",
"None",
",",
"default_offset",
"=",
"0",
")",
":",
"if",
"not",
"is_str",
"(",
"cursor",
")",
":",
"return",
"default_offset",
"offset",
"=",
"cursor_to_offset",
"(",
"cursor",
")",
"try",
":",
"return",
... | Given an optional cursor and a default offset, returns the offset
to use; if the cursor contains a valid offset, that will be used,
otherwise it will be the default. | [
"Given",
"an",
"optional",
"cursor",
"and",
"a",
"default",
"offset",
"returns",
"the",
"offset",
"to",
"use",
";",
"if",
"the",
"cursor",
"contains",
"a",
"valid",
"offset",
"that",
"will",
"be",
"used",
"otherwise",
"it",
"will",
"be",
"the",
"default",
... | train | https://github.com/graphql-python/graphql-relay-py/blob/17ce2efa3c396df42791ae00667120b5fae64610/graphql_relay/connection/arrayconnection.py#L145-L158 |
patrickfuller/jgraph | python/notebook.py | draw | def draw(data, size=(600, 400), node_size=2.0, edge_size=0.25,
default_node_color=0x5bc0de, default_edge_color=0xaaaaaa, z=100,
shader='basic', optimize=True, directed=True, display_html=True,
show_save=False):
"""Draws an interactive 3D visualization of the inputted graph.
Args:
... | python | def draw(data, size=(600, 400), node_size=2.0, edge_size=0.25,
default_node_color=0x5bc0de, default_edge_color=0xaaaaaa, z=100,
shader='basic', optimize=True, directed=True, display_html=True,
show_save=False):
"""Draws an interactive 3D visualization of the inputted graph.
Args:
... | [
"def",
"draw",
"(",
"data",
",",
"size",
"=",
"(",
"600",
",",
"400",
")",
",",
"node_size",
"=",
"2.0",
",",
"edge_size",
"=",
"0.25",
",",
"default_node_color",
"=",
"0x5bc0de",
",",
"default_edge_color",
"=",
"0xaaaaaa",
",",
"z",
"=",
"100",
",",
... | Draws an interactive 3D visualization of the inputted graph.
Args:
data: Either an adjacency list of tuples (ie. [(1,2),...]) or object
size: (Optional) Dimensions of visualization, in pixels
node_size: (Optional) Defaults to 2.0
edge_size: (Optional) Defaults to 0.25
defaul... | [
"Draws",
"an",
"interactive",
"3D",
"visualization",
"of",
"the",
"inputted",
"graph",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/notebook.py#L29-L133 |
patrickfuller/jgraph | python/notebook.py | generate | def generate(data, iterations=1000, force_strength=5.0, dampening=0.01,
max_velocity=2.0, max_distance=50, is_3d=True):
"""Runs a force-directed algorithm on a graph, returning a data structure.
Args:
data: An adjacency list of tuples (ie. [(1,2),...])
iterations: (Optional) Number... | python | def generate(data, iterations=1000, force_strength=5.0, dampening=0.01,
max_velocity=2.0, max_distance=50, is_3d=True):
"""Runs a force-directed algorithm on a graph, returning a data structure.
Args:
data: An adjacency list of tuples (ie. [(1,2),...])
iterations: (Optional) Number... | [
"def",
"generate",
"(",
"data",
",",
"iterations",
"=",
"1000",
",",
"force_strength",
"=",
"5.0",
",",
"dampening",
"=",
"0.01",
",",
"max_velocity",
"=",
"2.0",
",",
"max_distance",
"=",
"50",
",",
"is_3d",
"=",
"True",
")",
":",
"edges",
"=",
"[",
... | Runs a force-directed algorithm on a graph, returning a data structure.
Args:
data: An adjacency list of tuples (ie. [(1,2),...])
iterations: (Optional) Number of FDL iterations to run in coordinate
generation
force_strength: (Optional) Strength of Coulomb and Hooke forces
... | [
"Runs",
"a",
"force",
"-",
"directed",
"algorithm",
"on",
"a",
"graph",
"returning",
"a",
"data",
"structure",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/notebook.py#L136-L159 |
patrickfuller/jgraph | python/json_formatter.py | compress | def compress(obj):
"""Outputs json without whitespace."""
return json.dumps(obj, sort_keys=True, separators=(',', ':'),
cls=CustomEncoder) | python | def compress(obj):
"""Outputs json without whitespace."""
return json.dumps(obj, sort_keys=True, separators=(',', ':'),
cls=CustomEncoder) | [
"def",
"compress",
"(",
"obj",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
",",
"cls",
"=",
"CustomEncoder",
")"
] | Outputs json without whitespace. | [
"Outputs",
"json",
"without",
"whitespace",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/json_formatter.py#L18-L21 |
patrickfuller/jgraph | python/json_formatter.py | dumps | def dumps(obj):
"""Outputs json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder) | python | def dumps(obj):
"""Outputs json with formatting edits + object handling."""
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder) | [
"def",
"dumps",
"(",
"obj",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"obj",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"cls",
"=",
"CustomEncoder",
")"
] | Outputs json with formatting edits + object handling. | [
"Outputs",
"json",
"with",
"formatting",
"edits",
"+",
"object",
"handling",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/json_formatter.py#L24-L26 |
patrickfuller/jgraph | python/json_formatter.py | CustomEncoder.encode | def encode(self, obj):
"""Fired for every object."""
s = super(CustomEncoder, self).encode(obj)
# If uncompressed, postprocess for formatting
if len(s.splitlines()) > 1:
s = self.postprocess(s)
return s | python | def encode(self, obj):
"""Fired for every object."""
s = super(CustomEncoder, self).encode(obj)
# If uncompressed, postprocess for formatting
if len(s.splitlines()) > 1:
s = self.postprocess(s)
return s | [
"def",
"encode",
"(",
"self",
",",
"obj",
")",
":",
"s",
"=",
"super",
"(",
"CustomEncoder",
",",
"self",
")",
".",
"encode",
"(",
"obj",
")",
"# If uncompressed, postprocess for formatting",
"if",
"len",
"(",
"s",
".",
"splitlines",
"(",
")",
")",
">",
... | Fired for every object. | [
"Fired",
"for",
"every",
"object",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/json_formatter.py#L31-L37 |
patrickfuller/jgraph | python/json_formatter.py | CustomEncoder.postprocess | def postprocess(self, json_string):
"""Displays each entry on its own line."""
is_compressing, is_hash, compressed, spaces = False, False, [], 0
for row in json_string.split('\n'):
if is_compressing:
if (row[:spaces + 5] == ' ' * (spaces + 4) +
... | python | def postprocess(self, json_string):
"""Displays each entry on its own line."""
is_compressing, is_hash, compressed, spaces = False, False, [], 0
for row in json_string.split('\n'):
if is_compressing:
if (row[:spaces + 5] == ' ' * (spaces + 4) +
... | [
"def",
"postprocess",
"(",
"self",
",",
"json_string",
")",
":",
"is_compressing",
",",
"is_hash",
",",
"compressed",
",",
"spaces",
"=",
"False",
",",
"False",
",",
"[",
"]",
",",
"0",
"for",
"row",
"in",
"json_string",
".",
"split",
"(",
"'\\n'",
")"... | Displays each entry on its own line. | [
"Displays",
"each",
"entry",
"on",
"its",
"own",
"line",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/json_formatter.py#L39-L61 |
patrickfuller/jgraph | python/force_directed_layout.py | run | def run(edges, iterations=1000, force_strength=5.0, dampening=0.01,
max_velocity=2.0, max_distance=50, is_3d=True):
"""Runs a force-directed-layout algorithm on the input graph.
iterations - Number of FDL iterations to run in coordinate generation
force_strength - Strength of Coulomb and Hooke forc... | python | def run(edges, iterations=1000, force_strength=5.0, dampening=0.01,
max_velocity=2.0, max_distance=50, is_3d=True):
"""Runs a force-directed-layout algorithm on the input graph.
iterations - Number of FDL iterations to run in coordinate generation
force_strength - Strength of Coulomb and Hooke forc... | [
"def",
"run",
"(",
"edges",
",",
"iterations",
"=",
"1000",
",",
"force_strength",
"=",
"5.0",
",",
"dampening",
"=",
"0.01",
",",
"max_velocity",
"=",
"2.0",
",",
"max_distance",
"=",
"50",
",",
"is_3d",
"=",
"True",
")",
":",
"# Get a list of node ids fr... | Runs a force-directed-layout algorithm on the input graph.
iterations - Number of FDL iterations to run in coordinate generation
force_strength - Strength of Coulomb and Hooke forces
(edit this to scale the distance between nodes)
dampening - Multiplier to reduce force applied to nodes... | [
"Runs",
"a",
"force",
"-",
"directed",
"-",
"layout",
"algorithm",
"on",
"the",
"input",
"graph",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/force_directed_layout.py#L10-L59 |
patrickfuller/jgraph | python/force_directed_layout.py | _coulomb | def _coulomb(n1, n2, k, r):
"""Calculates Coulomb forces and updates node data."""
# Get relevant positional data
delta = [x2 - x1 for x1, x2 in zip(n1['velocity'], n2['velocity'])]
distance = sqrt(sum(d ** 2 for d in delta))
# If the deltas are too small, use random values to keep things moving
... | python | def _coulomb(n1, n2, k, r):
"""Calculates Coulomb forces and updates node data."""
# Get relevant positional data
delta = [x2 - x1 for x1, x2 in zip(n1['velocity'], n2['velocity'])]
distance = sqrt(sum(d ** 2 for d in delta))
# If the deltas are too small, use random values to keep things moving
... | [
"def",
"_coulomb",
"(",
"n1",
",",
"n2",
",",
"k",
",",
"r",
")",
":",
"# Get relevant positional data",
"delta",
"=",
"[",
"x2",
"-",
"x1",
"for",
"x1",
",",
"x2",
"in",
"zip",
"(",
"n1",
"[",
"'velocity'",
"]",
",",
"n2",
"[",
"'velocity'",
"]",
... | Calculates Coulomb forces and updates node data. | [
"Calculates",
"Coulomb",
"forces",
"and",
"updates",
"node",
"data",
"."
] | train | https://github.com/patrickfuller/jgraph/blob/7297450f26ae8cba21914668a5aaa755de8aa14d/python/force_directed_layout.py#L62-L77 |
pypyr/pypyr-cli | pypyr/steps/contextclearall.py | run_step | def run_step(context):
"""Wipe the entire context.
Args:
Context is a dictionary or dictionary-like.
Does not require any specific keys in context.
"""
logger.debug("started")
context.clear()
logger.info(f"Context wiped. New context size: {len(context)}")
logger.debug("don... | python | def run_step(context):
"""Wipe the entire context.
Args:
Context is a dictionary or dictionary-like.
Does not require any specific keys in context.
"""
logger.debug("started")
context.clear()
logger.info(f"Context wiped. New context size: {len(context)}")
logger.debug("don... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"context",
".",
"clear",
"(",
")",
"logger",
".",
"info",
"(",
"f\"Context wiped. New context size: {len(context)}\"",
")",
"logger",
".",
"debug",
"(",
"\"done\"",
"... | Wipe the entire context.
Args:
Context is a dictionary or dictionary-like.
Does not require any specific keys in context. | [
"Wipe",
"the",
"entire",
"context",
"."
] | train | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/contextclearall.py#L8-L20 |
pypyr/pypyr-cli | pypyr/parser/jsonfile.py | get_parsed_context | def get_parsed_context(context_arg):
"""Parse input context string and returns context as dictionary."""
assert context_arg, ("pipeline must be invoked with context arg set. For "
"this json parser you're looking for something "
"like: "
... | python | def get_parsed_context(context_arg):
"""Parse input context string and returns context as dictionary."""
assert context_arg, ("pipeline must be invoked with context arg set. For "
"this json parser you're looking for something "
"like: "
... | [
"def",
"get_parsed_context",
"(",
"context_arg",
")",
":",
"assert",
"context_arg",
",",
"(",
"\"pipeline must be invoked with context arg set. For \"",
"\"this json parser you're looking for something \"",
"\"like: \"",
"\"pypyr pipelinename './myjsonfile.json'\"",
")",
"logger",
".... | Parse input context string and returns context as dictionary. | [
"Parse",
"input",
"context",
"string",
"and",
"returns",
"context",
"as",
"dictionary",
"."
] | train | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/parser/jsonfile.py#L10-L24 |
pypyr/pypyr-cli | pypyr/steps/pathcheck.py | run_step | def run_step(context):
"""pypyr step that checks if a file or directory path exists.
Args:
context: pypyr.context.Context. Mandatory.
The following context key must exist
- pathsToCheck. str/path-like or list of str/paths.
Path to file on... | python | def run_step(context):
"""pypyr step that checks if a file or directory path exists.
Args:
context: pypyr.context.Context. Mandatory.
The following context key must exist
- pathsToCheck. str/path-like or list of str/paths.
Path to file on... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"context",
".",
"assert_key_has_value",
"(",
"key",
"=",
"'pathCheck'",
",",
"caller",
"=",
"__name__",
")",
"paths_to_check",
"=",
"context",
"[",
"'pathCheck'",
"... | pypyr step that checks if a file or directory path exists.
Args:
context: pypyr.context.Context. Mandatory.
The following context key must exist
- pathsToCheck. str/path-like or list of str/paths.
Path to file on disk to check.
All input... | [
"pypyr",
"step",
"that",
"checks",
"if",
"a",
"file",
"or",
"directory",
"path",
"exists",
"."
] | train | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/pathcheck.py#L10-L83 |
pypyr/pypyr-cli | pypyr/steps/filewritejson.py | run_step | def run_step(context):
"""Write payload out to json file.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileWriteJson
- path. mandatory. path-like. Write output file to
here. Will create... | python | def run_step(context):
"""Write payload out to json file.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileWriteJson
- path. mandatory. path-like. Write output file to
here. Will create... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"context",
".",
"assert_child_key_has_value",
"(",
"'fileWriteJson'",
",",
"'path'",
",",
"__name__",
")",
"out_path",
"=",
"context",
".",
"get_formatted_string",
"(",... | Write payload out to json file.
Args:
context: pypyr.context.Context. Mandatory.
The following context keys expected:
- fileWriteJson
- path. mandatory. path-like. Write output file to
here. Will create directories in path for you.
... | [
"Write",
"payload",
"out",
"to",
"json",
"file",
"."
] | train | https://github.com/pypyr/pypyr-cli/blob/4003f999cd5eb030b4c7407317de728f5115a80f/pypyr/steps/filewritejson.py#L10-L53 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.