Dataset Viewer
Auto-converted to Parquet Duplicate
code
large_stringlengths
52
373k
docstring
large_stringlengths
3
47.2k
language
large_stringclasses
6 values
def settext(self, text, cls='current'): """Set the text for this element. Arguments: text (str): The text cls (str): The class of the text, defaults to ``current`` (leave this unless you know what you are doing). There may be only one text content element of each class associate...
Set the text for this element. Arguments: text (str): The text cls (str): The class of the text, defaults to ``current`` (leave this unless you know what you are doing). There may be only one text content element of each class associated with the element.
python
def setdocument(self, doc): """Associate a document with this element. Arguments: doc (:class:`Document`): A document Each element must be associated with a FoLiA document. """ assert isinstance(doc, Document) if not self.doc: self.doc = doc ...
Associate a document with this element. Arguments: doc (:class:`Document`): A document Each element must be associated with a FoLiA document.
python
def addable(Class, parent, set=None, raiseexceptions=True): """Tests whether a new element of this class can be added to the parent. This method is mostly for internal use. This will use the ``OCCURRENCES`` property, but may be overidden by subclasses for more customised behaviour. Par...
Tests whether a new element of this class can be added to the parent. This method is mostly for internal use. This will use the ``OCCURRENCES`` property, but may be overidden by subclasses for more customised behaviour. Parameters: parent (:class:`AbstractElement`): The element tha...
python
def postappend(self): """This method will be called after an element is added to another and does some checks. It can do extra checks and if necessary raise exceptions to prevent addition. By default makes sure the right document is associated. This method is mostly for internal use. "...
This method will be called after an element is added to another and does some checks. It can do extra checks and if necessary raise exceptions to prevent addition. By default makes sure the right document is associated. This method is mostly for internal use.
python
def updatetext(self): """Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER``""" if self.TEXTCONTAINER: s = "" for child in self: if isinstance(child, AbstractElement): child...
Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER``
python
def ancestors(self, Class=None): """Generator yielding all ancestors of this element, effectively back-tracing its path to the root element. A tuple of multiple classes may be specified. Arguments: *Class: The class or classes (:class:`AbstractElement` or subclasses). Not instances! ...
Generator yielding all ancestors of this element, effectively back-tracing its path to the root element. A tuple of multiple classes may be specified. Arguments: *Class: The class or classes (:class:`AbstractElement` or subclasses). Not instances! Yields: elements (instances de...
python
def ancestor(self, *Classes): """Find the most immediate ancestor of the specified type, multiple classes may be specified. Arguments: *Classes: The possible classes (:class:`AbstractElement` or subclasses) to select from. Not instances! Example:: paragraph = word.ance...
Find the most immediate ancestor of the specified type, multiple classes may be specified. Arguments: *Classes: The possible classes (:class:`AbstractElement` or subclasses) to select from. Not instances! Example:: paragraph = word.ancestor(folia.Paragraph)
python
def json(self, attribs=None, recurse=True, ignorelist=False): """Serialises the FoLiA element and all its contents to a Python dictionary suitable for serialisation to JSON. Example:: import json json.dumps(word.json()) Returns: dict """ jso...
Serialises the FoLiA element and all its contents to a Python dictionary suitable for serialisation to JSON. Example:: import json json.dumps(word.json()) Returns: dict
python
def xmlstring(self, pretty_print=False): """Serialises this FoLiA element and all its contents to XML. Returns: str: a string with XML representation for this element and all its children""" s = ElementTree.tostring(self.xml(), xml_declaration=False, pretty_print=pretty_print, encod...
Serialises this FoLiA element and all its contents to XML. Returns: str: a string with XML representation for this element and all its children
python
def select(self, Class, set=None, recursive=True, ignore=True, node=None): #pylint: disable=bad-classmethod-argument,redefined-builtin """Select child elements of the specified class. A further restriction can be made based on set. Arguments: Class (class): The class to select; an...
Select child elements of the specified class. A further restriction can be made based on set. Arguments: Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement` Set (str): The set to match against, only elements pertaining to ...
python
def getmetadata(self, key=None): """Get the metadata that applies to this element, automatically inherited from parent elements""" if self.metadata: d = self.doc.submetadata[self.metadata] elif self.parent: d = self.parent.getmetadata() elif self.doc: ...
Get the metadata that applies to this element, automatically inherited from parent elements
python
def getindex(self, child, recursive=True, ignore=True): """Get the index at which an element occurs, recursive by default! Returns: int """ #breadth first search for i, c in enumerate(self.data): if c is child: return i if recursi...
Get the index at which an element occurs, recursive by default! Returns: int
python
def precedes(self, other): """Returns a boolean indicating whether this element precedes the other element""" try: ancestor = next(commonancestors(AbstractElement, self, other)) except StopIteration: raise Exception("Elements share no common ancestor") #now we jus...
Returns a boolean indicating whether this element precedes the other element
python
def depthfirstsearch(self, function): """Generic depth first search algorithm using a callback function, continues as long as the callback function returns None""" result = function(self) if result is not None: return result for e in self: result = e.depthfirstsea...
Generic depth first search algorithm using a callback function, continues as long as the callback function returns None
python
def next(self, Class=True, scope=True, reverse=False): """Returns the next element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned. Arguments: * ``Class``: The...
Returns the next element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned. Arguments: * ``Class``: The class to select; any python class subclassed off `'AbstractElemen...
python
def previous(self, Class=True, scope=True): """Returns the previous element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned. Arguments: * ``Class``: The class ...
Returns the previous element, if it is of the specified type and if it does not cross the boundary of the defined scope. Returns None if no next element is found. Non-authoritative elements are never returned. Arguments: * ``Class``: The class to select; any python class subclassed off `'AbstractEl...
python
def remove(self, child): """Removes the child element""" if not isinstance(child, AbstractElement): raise ValueError("Expected AbstractElement, got " + str(type(child))) if child.parent == self: child.parent = None self.data.remove(child) #delete from inde...
Removes the child element
python
def hasannotation(self,Class,set=None): """Returns an integer indicating whether such as annotation exists, and if so, how many. See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters.""" return sum( 1 for _ in self.select(Class,set,True,default_ignore_annotations))
Returns an integer indicating whether such as annotation exists, and if so, how many. See :meth:`AllowTokenAnnotation.annotations`` for a description of the parameters.
python
def annotation(self, type, set=None): """Obtain a single annotation element. A further restriction can be made based on set. Arguments: Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement` Set (str): The set to matc...
Obtain a single annotation element. A further restriction can be made based on set. Arguments: Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement` Set (str): The set to match against, only elements pertaining to this set w...
python
def hasannotationlayer(self, annotationtype=None,set=None): """Does the specified annotation layer exist?""" l = self.layers(annotationtype, set) return (len(l) > 0)
Does the specified annotation layer exist?
python
def getreference(self, validate=True): """Returns and validates the Text Content's reference. Raises UnresolvableTextContent when invalid""" if self.offset is None: return None #nothing to test if self.ref: ref = self.doc[self.ref] else: ref = self.finddefaultref...
Returns and validates the Text Content's reference. Raises UnresolvableTextContent when invalid
python
def getreference(self, validate=True): """Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid""" if self.offset is None: return None #nothing to test if self.ref: ref = self.doc[self.ref] else: ref = self.finddefaultr...
Return and validate the Phonetic Content's reference. Raises UnresolvableTextContent when invalid
python
def findspans(self, type,set=None): """Yields span annotation elements of the specified type that include this word. Arguments: type: The annotation type, can be passed as using any of the :class:`AnnotationType` member, or by passing the relevant :class:`AbstractSpanAnnotation` or :class:`...
Yields span annotation elements of the specified type that include this word. Arguments: type: The annotation type, can be passed as using any of the :class:`AnnotationType` member, or by passing the relevant :class:`AbstractSpanAnnotation` or :class:`AbstractAnnotationLayer` class. set...
python
def setspan(self, *args): """Sets the span of the span element anew, erases all data inside. Arguments: *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme` """ self.data = [] for child in args: self.append(child)
Sets the span of the span element anew, erases all data inside. Arguments: *args: Instances of :class:`Word`, :class:`Morpheme` or :class:`Phoneme`
python
def _helper_wrefs(self, targets, recurse=True): """Internal helper function""" for c in self: if isinstance(c,Word) or isinstance(c,Morpheme) or isinstance(c, Phoneme): targets.append(c) elif isinstance(c,WordReference): try: ta...
Internal helper function
python
def wrefs(self, index = None, recurse=True): """Returns a list of word references, these can be Words but also Morphemes or Phonemes. Arguments: index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the list of all ...
Returns a list of word references, these can be Words but also Morphemes or Phonemes. Arguments: index (int or None): If set to an integer, will retrieve and return the n'th element (starting at 0) instead of returning the list of all
python
def copychildren(self, newdoc=None, idsuffix=""): """Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash""" if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #...
Generator creating a deep copy of the children of this element. If idsuffix is a string, if set to True, a random idsuffix will be generated including a random 32-bit hash
python
def alternatives(self, Class=None, set=None): """Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set. Arguments: * ``Class`` - The Class you want to retrieve (e.g. PosAnnotation). Or set to None to select all alternatives regard...
Generator over alternatives, either all or only of a specific annotation type, and possibly restrained also by set. Arguments: * ``Class`` - The Class you want to retrieve (e.g. PosAnnotation). Or set to None to select all alternatives regardless of what type they are. * ``set`` - The...
python
def findspan(self, *words): """Returns the span element which spans over the specified words or morphemes. See also: :meth:`Word.findspans` """ for span in self.select(AbstractSpanAnnotation,None,True): if tuple(span.wrefs()) == words: return spa...
Returns the span element which spans over the specified words or morphemes. See also: :meth:`Word.findspans`
python
def hasnew(self,allowempty=False): """Does the correction define new corrected annotations?""" for e in self.select(New,None,False, False): if not allowempty and len(e) == 0: continue return True return False
Does the correction define new corrected annotations?
python
def hasoriginal(self,allowempty=False): """Does the correction record the old annotations prior to correction?""" for e in self.select(Original,None,False, False): if not allowempty and len(e) == 0: continue return True return False
Does the correction record the old annotations prior to correction?
python
def hassuggestions(self,allowempty=False): """Does the correction propose suggestions for correction?""" for e in self.select(Suggestion,None,False, False): if not allowempty and len(e) == 0: continue return True return False
Does the correction propose suggestions for correction?
python
def new(self,index = None): """Get the new corrected annotation. This returns only one annotation if multiple exist, use `index` to select another in the sequence. Returns: an annotation element (:class:`AbstractElement`) Raises: :class:`NoSuchAnnotation` ...
Get the new corrected annotation. This returns only one annotation if multiple exist, use `index` to select another in the sequence. Returns: an annotation element (:class:`AbstractElement`) Raises: :class:`NoSuchAnnotation`
python
def original(self,index=None): """Get the old annotation prior to correction. This returns only one annotation if multiple exist, use `index` to select another in the sequence. Returns: an annotation element (:class:`AbstractElement`) Raises: :class:`NoSuchAnno...
Get the old annotation prior to correction. This returns only one annotation if multiple exist, use `index` to select another in the sequence. Returns: an annotation element (:class:`AbstractElement`) Raises: :class:`NoSuchAnnotation`
python
def suggestions(self,index=None): """Get suggestions for correction. Yields: :class:`Suggestion` element that encapsulate the suggested annotations (if index is ``None``, default) Returns: a :class:`Suggestion` element that encapsulate the suggested annotations (if inde...
Get suggestions for correction. Yields: :class:`Suggestion` element that encapsulate the suggested annotations (if index is ``None``, default) Returns: a :class:`Suggestion` element that encapsulate the suggested annotations (if index is set) Raises: :class...
python
def findspans(self, type,set=None): """Find span annotation of the specified type that include this word""" if issubclass(type, AbstractAnnotationLayer): layerclass = type else: layerclass = ANNOTATIONTYPE2LAYERCLASS[type.ANNOTATIONTYPE] e = self while Tru...
Find span annotation of the specified type that include this word
python
def resolve(self,size, distribution): """Resolve a variable sized pattern to all patterns of a certain fixed size""" if not self.variablesize(): raise Exception("Can only resize patterns with * wildcards") nrofwildcards = 0 for x in self.sequence: if x == '*': ...
Resolve a variable sized pattern to all patterns of a certain fixed size
python
def load(self, filename): """Load a FoLiA XML file. Argument: filename (str): The file to load """ #if LXE and self.mode != Mode.XPATH: # #workaround for xml:id problem (disabled) # #f = open(filename) # #s = f.read().replace(' xml:id=', ' id...
Load a FoLiA XML file. Argument: filename (str): The file to load
python
def items(self): """Returns a depth-first flat list of all items in the document""" l = [] for e in self.data: l += e.items() return l
Returns a depth-first flat list of all items in the document
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: ...
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.
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: ...
Internal method to generate XML nodes for all declarations
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...
Return all declarations in a form ready to be serialised to JSON. Returns: list of dict
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...
Serialise the document to XML. Returns: lxml.etree.Element See also: :meth:`Document.xmlstring`
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(...
Serialise the document to a ``dict`` ready for serialisation to JSON. Example:: import json jsondoc = json.dumps(doc.json())
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...
Internal method to serialize metadata to XML
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...
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`...
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...
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``. ...
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...
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...
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...
Internal method to parse metadata
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: ...
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
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...
Return a generator of all paragraphs found in the document. If an index is specified, return the n'th paragraph only (starting at 0)
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: ...
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)
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...
Iterate over all states in no particular order
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...
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)
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...
Returns a list of synset IDs based on a lemma
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...
call cdb_syn with synset identifier -> returns the synset xml;
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
Returns a list of all predicted senses
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) ...
For each inputword, provides the index of the outputword
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...
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 ...
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'...
Strip characters with diacritics and return a flat ascii representation
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(...
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.
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...
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
python
def randomprune(self,n): """prune down to n items at random, disregarding their score""" self.data = random.sample(self.data, n)
prune down to n items at random, disregarding their score
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)
Add an item to the Tree
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
Size is number of nodes under the trie, including the current node
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(...
checks if the document is valid
python
def xpath(self, expression): """Executes an xpath expression using the correct namespaces""" global namespaces return self.tree.xpath(expression, namespaces=namespaces)
Executes an xpath expression using the correct namespaces
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...
align the reference sentence with the tagged data
python
def build(self, **kwargs): """Build the lexer.""" self.lexer = ply.lex.lex(object=self, **kwargs)
Build the lexer.
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...
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.
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)
Send a login response back to the client.
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...
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.
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: ...
Check if the request path is in the `_exclude_paths` list
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...
Bootstrap prompt_toolkit kwargs or use user defined values. :param prompt_kwargs: The user specified prompt kwargs.
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:`...
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.
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()
Run repl-internal commands. Repl-internal commands are all commands starting with ":".
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...
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 ...
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
Takes the "global ID" created by toGlobalID, and retuns the type name and ID used to create it.
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...
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.
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...
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.
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))
A version of `connectionFromArray` that takes a promised array, and returns a promised connection.
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)
Return the cursor associated with an object in an array.
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...
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.
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...
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 ...
python
def compress(obj): """Outputs json without whitespace.""" return json.dumps(obj, sort_keys=True, separators=(',', ':'), cls=CustomEncoder)
Outputs json without whitespace.
python
def dumps(obj): """Outputs json with formatting edits + object handling.""" return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)
Outputs json with formatting edits + object handling.
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
Fired for every object.
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) + ...
Displays each entry on its own line.
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...
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...
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 ...
Calculates Coulomb forces and updates node data.
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...
Wipe the entire context. Args: Context is a dictionary or dictionary-like. Does not require any specific keys in context.
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...
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...
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...
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. ...
python
def run_step(context): """Run another pipeline from this step. The parent pipeline is the current, executing pipeline. The invoked, or child pipeline is the pipeline you are calling from this step. Args: context: dictionary-like pypyr.context.Context. context is mandatory. Use...
Run another pipeline from this step. The parent pipeline is the current, executing pipeline. The invoked, or child pipeline is the pipeline you are calling from this step. Args: context: dictionary-like pypyr.context.Context. context is mandatory. Uses the following context keys i...
python
def get_arguments(context): """Parse arguments for pype from context and assign default values. Args: context: pypyr.context.Context. context is mandatory. Returns: tuple (pipeline_name, #str use_parent_context, #bool pipe_arg, #str skip_parse, ...
Parse arguments for pype from context and assign default values. Args: context: pypyr.context.Context. context is mandatory. Returns: tuple (pipeline_name, #str use_parent_context, #bool pipe_arg, #str skip_parse, #bool raise_error #b...
python
def get_pipeline_path(pipeline_name, working_directory): """Look for the pipeline in the various places it could be. First checks the cwd. Then checks pypyr/pipelines dir. Args: pipeline_name: string. Name of pipeline to find working_directory: string. Path in which to look for pipeline_na...
Look for the pipeline in the various places it could be. First checks the cwd. Then checks pypyr/pipelines dir. Args: pipeline_name: string. Name of pipeline to find working_directory: string. Path in which to look for pipeline_name.yaml Returns: Absolute path to the pipeline_name...
python
def get_pipeline_definition(pipeline_name, working_dir): """Open and parse the pipeline definition yaml. Parses pipeline yaml and returns dictionary representing the pipeline. pipeline_name.yaml should be in the working_dir/pipelines/ directory. Args: pipeline_name: string. Name of pipeline. ...
Open and parse the pipeline definition yaml. Parses pipeline yaml and returns dictionary representing the pipeline. pipeline_name.yaml should be in the working_dir/pipelines/ directory. Args: pipeline_name: string. Name of pipeline. This will be the file-name of the pipelin...
python
def to_yaml(cls, representer, node): """How to serialize this class back to yaml.""" return representer.represent_scalar(cls.yaml_tag, node.value)
How to serialize this class back to yaml.
python
def get_value(self, context): """Run python eval on the input string.""" if self.value: return expressions.eval_string(self.value, context) else: # Empty input raises cryptic EOF syntax err, this more human # friendly raise ValueError('!py string e...
Run python eval on the input string.
python
def foreach_loop(self, context): """Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate....
Run step once for each item in foreach_items. On each iteration, the invoked step can use context['i'] to get the current iterator value. Args: context: (pypyr.context.Context) The pypyr context. This arg will mutate.
python
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
78