_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q0
AbstractElement.settext
train
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...
python
{ "resource": "" }
q1
AbstractElement.setdocument
train
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 ...
python
{ "resource": "" }
q2
AbstractElement.addable
train
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...
python
{ "resource": "" }
q3
AbstractElement.postappend
train
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. "...
python
{ "resource": "" }
q4
AbstractElement.updatetext
train
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...
python
{ "resource": "" }
q5
AbstractElement.ancestors
train
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! ...
python
{ "resource": "" }
q6
AbstractElement.ancestor
train
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...
python
{ "resource": "" }
q7
AbstractElement.json
train
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...
python
{ "resource": "" }
q8
AbstractElement.xmlstring
train
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...
python
{ "resource": "" }
q9
AbstractElement.select
train
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...
python
{ "resource": "" }
q10
AbstractElement.getmetadata
train
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: ...
python
{ "resource": "" }
q11
AbstractElement.getindex
train
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...
python
{ "resource": "" }
q12
AbstractElement.precedes
train
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...
python
{ "resource": "" }
q13
AbstractElement.depthfirstsearch
train
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...
python
{ "resource": "" }
q14
AbstractElement.next
train
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...
python
{ "resource": "" }
q15
AbstractElement.previous
train
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 ...
python
{ "resource": "" }
q16
AbstractElement.remove
train
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...
python
{ "resource": "" }
q17
AllowTokenAnnotation.hasannotation
train
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))
python
{ "resource": "" }
q18
AllowTokenAnnotation.annotation
train
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...
python
{ "resource": "" }
q19
AbstractStructureElement.hasannotationlayer
train
def hasannotationlayer(self, annotationtype=None,set=None): """Does the specified annotation layer exist?""" l = self.layers(annotationtype, set) return (len(l) > 0)
python
{ "resource": "" }
q20
TextContent.getreference
train
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...
python
{ "resource": "" }
q21
PhonContent.getreference
train
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...
python
{ "resource": "" }
q22
Word.findspans
train
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:`...
python
{ "resource": "" }
q23
AbstractSpanAnnotation.setspan
train
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)
python
{ "resource": "" }
q24
AbstractSpanAnnotation._helper_wrefs
train
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...
python
{ "resource": "" }
q25
AbstractSpanAnnotation.wrefs
train
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 ...
python
{ "resource": "" }
q26
AbstractSpanAnnotation.copychildren
train
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) #...
python
{ "resource": "" }
q27
AbstractAnnotationLayer.alternatives
train
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...
python
{ "resource": "" }
q28
AbstractAnnotationLayer.findspan
train
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...
python
{ "resource": "" }
q29
Correction.hasnew
train
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
python
{ "resource": "" }
q30
Correction.hasoriginal
train
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
python
{ "resource": "" }
q31
Correction.hassuggestions
train
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
python
{ "resource": "" }
q32
Correction.new
train
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` ...
python
{ "resource": "" }
q33
Correction.original
train
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...
python
{ "resource": "" }
q34
Correction.suggestions
train
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...
python
{ "resource": "" }
q35
Morpheme.findspans
train
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...
python
{ "resource": "" }
q36
Pattern.resolve
train
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 == '*': ...
python
{ "resource": "" }
q37
Document.load
train
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...
python
{ "resource": "" }
q38
Document.items
train
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
python
{ "resource": "" }
q39
Document.save
train
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
{ "resource": "" }
q40
Document.xmldeclarations
train
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
{ "resource": "" }
q41
Document.jsondeclarations
train
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
{ "resource": "" }
q42
Document.xml
train
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
{ "resource": "" }
q43
Document.json
train
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
{ "resource": "" }
q44
Document.xmlmetadata
train
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
{ "resource": "" }
q45
Document.declare
train
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
{ "resource": "" }
q46
Document.defaultset
train
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
{ "resource": "" }
q47
Document.defaultannotator
train
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
{ "resource": "" }
q48
Document.parsemetadata
train
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
{ "resource": "" }
q49
Document.pendingvalidation
train
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
{ "resource": "" }
q50
Document.paragraphs
train
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
{ "resource": "" }
q51
Document.sentences
train
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
{ "resource": "" }
q52
NFA._states
train
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
{ "resource": "" }
q53
log
train
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
{ "resource": "" }
q54
CornettoClient.get_syn_ids_by_lemma
train
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
{ "resource": "" }
q55
CornettoClient.get_synset_xml
train
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
{ "resource": "" }
q56
WSDSystemOutput.senses
train
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
{ "resource": "" }
q57
FrogClient.align
train
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
{ "resource": "" }
q58
tokenize
train
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
{ "resource": "" }
q59
strip_accents
train
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
{ "resource": "" }
q60
swap
train
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
{ "resource": "" }
q61
find_keyword_in_context
train
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
{ "resource": "" }
q62
PriorityQueue.randomprune
train
def randomprune(self,n): """prune down to n items at random, disregarding their score""" self.data = random.sample(self.data, n)
python
{ "resource": "" }
q63
Tree.append
train
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
{ "resource": "" }
q64
Trie.size
train
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
{ "resource": "" }
q65
CorpusDocumentX.validate
train
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
{ "resource": "" }
q66
CorpusDocumentX.xpath
train
def xpath(self, expression): """Executes an xpath expression using the correct namespaces""" global namespaces return self.tree.xpath(expression, namespaces=namespaces)
python
{ "resource": "" }
q67
Taggerdata.align
train
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
{ "resource": "" }
q68
CustomLexer.build
train
def build(self, **kwargs): """Build the lexer.""" self.lexer = ply.lex.lex(object=self, **kwargs)
python
{ "resource": "" }
q69
BasicAuth.is_authorized
train
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
{ "resource": "" }
q70
BasicAuth._login
train
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
{ "resource": "" }
q71
BasicAuth._is_request_in_include_path
train
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
{ "resource": "" }
q72
BasicAuth._is_request_in_exclude_path
train
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
{ "resource": "" }
q73
bootstrap_prompt
train
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
{ "resource": "" }
q74
repl
train
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
{ "resource": "" }
q75
handle_internal_commands
train
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
{ "resource": "" }
q76
node_definitions
train
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
{ "resource": "" }
q77
from_global_id
train
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
{ "resource": "" }
q78
global_id_field
train
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
{ "resource": "" }
q79
connection_from_list
train
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
{ "resource": "" }
q80
connection_from_promised_list
train
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
{ "resource": "" }
q81
cursor_for_object_in_connection
train
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
{ "resource": "" }
q82
get_offset_with_default
train
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
{ "resource": "" }
q83
generate
train
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
{ "resource": "" }
q84
compress
train
def compress(obj): """Outputs json without whitespace.""" return json.dumps(obj, sort_keys=True, separators=(',', ':'), cls=CustomEncoder)
python
{ "resource": "" }
q85
dumps
train
def dumps(obj): """Outputs json with formatting edits + object handling.""" return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)
python
{ "resource": "" }
q86
CustomEncoder.encode
train
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
{ "resource": "" }
q87
CustomEncoder.postprocess
train
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
{ "resource": "" }
q88
run
train
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
{ "resource": "" }
q89
_coulomb
train
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
{ "resource": "" }
q90
run_step
train
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
{ "resource": "" }
q91
run_step
train
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
{ "resource": "" }
q92
run_step
train
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
{ "resource": "" }
q93
run_step
train
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...
python
{ "resource": "" }
q94
get_arguments
train
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, ...
python
{ "resource": "" }
q95
get_pipeline_path
train
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...
python
{ "resource": "" }
q96
get_pipeline_definition
train
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. ...
python
{ "resource": "" }
q97
SpecialTagDirective.to_yaml
train
def to_yaml(cls, representer, node): """How to serialize this class back to yaml.""" return representer.represent_scalar(cls.yaml_tag, node.value)
python
{ "resource": "" }
q98
PyString.get_value
train
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...
python
{ "resource": "" }
q99
Step.foreach_loop
train
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....
python
{ "resource": "" }