func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def alias(self, annotationtype, set, fallback=False):
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
if annotationtype in self.set_alias and set in self.set_alias[annotationtype]:
return self.set_alias[annotationtype][set]
elif fallback:
... | Return the alias for a set (if applicable, returns the unaltered set otherwise iff fallback is enabled) |
def unalias(self, annotationtype, alias):
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return self.alias_set[annotationtype][alias] | Return the set for an alias (if applicable, raises an exception otherwise) |
def save(self, filename=None):
if not filename:
filename = self.filename
if not filename:
raise Exception("No filename specified")
if filename[-4:].lower() == '.bz2':
f = bz2.BZ2File(filename,'wb')
f.write(self.xmlstring().encode('utf-8'))... | 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. |
def append(self,text):
if text is Text:
text = Text(self, id=self.id + '.text.' + str(len(self.data)+1) )
elif text is Speech:
text = Speech(self, id=self.id + '.speech.' + str(len(self.data)+1) ) #pylint: disable=redefined-variable-type
else:
assert ... | 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) |
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/1998/namespace"})
for annotationtype, set in self.annotations:
label = None
#Find the 'label' for the dec... | Internal method to generate XML nodes for all declarations |
def jsondeclarations(self):
l = []
for annotationtype, set in self.annotations:
label = None
#Find the 'label' for the declarations dynamically (aka: AnnotationType --> String)
for key, value in vars(AnnotationType).items():
if value == annota... | Return all declarations in a form ready to be serialised to JSON.
Returns:
list of dict |
def xml(self):
self.pendingvalidation()
E = ElementMaker(namespace="http://ilk.uvt.nl/folia",nsmap={'xml' : "http://www.w3.org/XML/1998/namespace", 'xlink':"http://www.w3.org/1999/xlink"})
attribs = {}
attribs['{http://www.w3.org/XML/1998/namespace}id'] = self.id
#if sel... | Serialise the document to XML.
Returns:
lxml.etree.Element
See also:
:meth:`Document.xmlstring` |
def json(self):
self.pendingvalidation()
jsondoc = {'id': self.id, 'children': [], 'declarations': self.jsondeclarations() }
if self.version:
jsondoc['version'] = self.version
else:
jsondoc['version'] = FOLIAVERSION
jsondoc['generator'] = 'pynlpl.... | Serialise the document to a ``dict`` ready for serialisation to JSON.
Example::
import json
jsondoc = json.dumps(doc.json()) |
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"})
elements = []
if self.metadatatype == "native":
if isinstance(self.metadata, NativeMetaData):
... | Internal method to serialize metadata to XML |
def parsexmldeclarations(self, node):
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
if not isinstance(subnode.tag, str): c... | Internal method to parse XML declarations |
def setimdi(self, node): #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:
self.metadata... | OBSOLETE |
def declare(self, annotationtype, set, **kwargs):
if (sys.version > '3' and not isinstance(set,str)) or (sys.version < '3' and not isinstance(set,(str,unicode))):
raise ValueError("Set parameter for declare() must be a string")
if inspect.isclass(annotationtype):
annotat... | 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`... |
def declared(self, annotationtype, set):
if inspect.isclass(annotationtype): annotationtype = annotationtype.ANNOTATIONTYPE
return ( (annotationtype,set) in self.annotations) or (set in self.alias_set and self.alias_set[set] and (annotationtype, self.alias_set[set]) in self.annotations ) | 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.... |
def defaultset(self, annotationtype):
if inspect.isclass(annotationtype) or isinstance(annotationtype,AbstractElement): annotationtype = annotationtype.ANNOTATIONTYPE
try:
return list(self.annotationdefaults[annotationtype].keys())[0]
except KeyError:
raise NoDef... | 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``.
... |
def defaultannotator(self, annotationtype, set=None):
if inspect.isclass(annotationtype) or isinstance(annotationtype,AbstractElement): annotationtype = annotationtype.ANNOTATIONTYPE
if not set: set = self.defaultset(annotationtype)
try:
return self.annotationdefaults[annota... | 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... |
def title(self, value=None):
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['title'] = value
else:
self._title = value
if (self.metadatatype == "native"):
if 'title' in self.metadata:
... | 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 |
def date(self, value=None):
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['date'] = value
else:
self._date = value
if (self.metadatatype == "native"):
if 'date' in self.metadata:
retu... | 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 |
def publisher(self, value=None):
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['publisher'] = value
else:
self._publisher = value
if (self.metadatatype == "native"):
if 'publisher' in self.metadata:
... | No arguments: Get the document's publisher from metadata
Argument: Set the document's publisher in metadata |
def license(self, value=None):
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['license'] = value
else:
self._license = value
if (self.metadatatype == "native"):
if 'license' in self.metadata:
... | No arguments: Get the document's license from metadata
Argument: Set the document's license in metadata |
def language(self, value=None):
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['language'] = value
else:
self._language = value
if self.metadatatype == "native":
if 'language' in self.metadata:
... | No arguments: Get the document's language (ISO-639-3) from metadata
Argument: Set the document's language (ISO-639-3) in metadata |
def parsemetadata(self, node):
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:
self.metadata = ExternalMetaData(node.attrib... | Internal method to parse metadata |
def parsexml(self, node, ParentClass = None):
if (LXE and isinstance(node,ElementTree._ElementTree)) or (not LXE and isinstance(node, ElementTree.ElementTree)): #pylint: disable=protected-access
node = node.getroot()
elif isstring(node):
node = xmltreefromstring(node).ge... | Internal method.
This is the main XML parser, will invoke class-specific XML parsers. |
def pendingvalidation(self, warnonly=None):
if self.debug: print("[PyNLPl FoLiA DEBUG] Processing pending validations (if any)",file=stderr)
if warnonly is None and self and self.version:
warnonly = (checkversion(self.version, '1.5.0') < 0) #warn only for documents older than FoLiA ... | 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 |
def select(self, Class, set=None, recursive=True, ignore=True):
if self.mode == Mode.MEMORY:
for t in self.data:
if Class.__name__ == 'Text':
yield t
else:
for e in t.select(Class,set,recursive,ignore):
... | See :meth:`AbstractElement.select` |
def count(self, Class, set=None, recursive=True,ignore=True):
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 | See :meth:`AbstractElement.count` |
def paragraphs(self, index = None):
if index is None:
return self.select(Paragraph)
else:
if index < 0:
index = sum(t.count(Paragraph) for t in self.data) + index
for t in self.data:
for i,e in enumerate(t.select(Paragraph)) :
... | Return a generator of all paragraphs found in the document.
If an index is specified, return the n'th paragraph only (starting at 0) |
def sentences(self, index = None):
if index is None:
return self.select(Sentence,None,True,[Quote])
else:
if index < 0:
index = sum(t.count(Sentence,None,True,[Quote]) for t in self.data) + index
for t in self.data:
for i,e in ... | 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) |
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 cls is False:
retaintokenisation = cls
cls = 'current'
... | Returns the text of the entire document (returns a unicode instance)
See also:
:meth:`AbstractElement.text` |
def _states(self, state, processedstates=[]): #pylint: disable=dangerous-default-value
processedstates.append(state)
for nextstate in state.epsilon:
if not nextstate in processedstates:
self._states(nextstate, processedstates)
for _, nextstate in state.transi... | Iterate over all states in no particular order |
def log(msg, **kwargs):
if 'debug' in kwargs:
if 'currentdebug' in kwargs:
if kwargs['currentdebug'] < kwargs['debug']:
return False
else:
return False #no currentdebug passed, assuming no debug mode and thus skipping message
s = "[" + datetime.dateti... | 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) |
def searchbest(self):
finalsolution = None
bestscore = None
for solution in self:
if bestscore == None:
bestscore = solution.score()
finalsolution = solution
elif self.minimize:
score = solution.score()
... | Returns the single best result (if multiple have the same score, the first match is returned) |
def searchtop(self,n=10):
solutions = PriorityQueue([], lambda x: x.score, self.minimize, length=n, blockworse=False, blockequal=False,duplicates=False)
for solution in self:
solutions.append(solution)
return solutions | Return the top n best resulta (or possibly less if not enough is found) |
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. |
def get_syn_ids_by_lemma(self, lemma):
if not isinstance(lemma,unicode):
lemma = unicode(lemma,'utf-8')
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.debug:
printf( "cornettodb/views/query_remot... | Returns a list of synset IDs based on a lemma |
def get_synset_xml(self,syn_id):
http, resp, content = self.connect()
params = ""
fragment = ""
path = "cdb_syn"
if self.debug:
printf( "cornettodb/views/query_remote_syn_id: db_opt: %s" % path )
# output_opt: plain, html, xml
# 'xml' is act... | call cdb_syn with synset identifier -> returns the synset xml; |
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 elem_synonyms:
synonym_str = elem_synonym.get( "c_lu_id-previewtext" ) # get "c_lu_id-previewtext" attribute
... | Returns a list of (word, lu_id) tuples given a synset ID |
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):
lemma = unicode(lemma,'utf-8')
root = self.get_synset_xml(syn_id)
elem_synonyms = root.find( ".//synonyms" )... | Returns (lu_id, synonyms=[(word, lu_id)] ) tuple given a synset ID and a lemma |
def senses(self, bestonly=False):
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 |
def process(self,input_data, source_encoding="utf-8", return_unicode = True, oldfrog=False):
if isinstance(input_data, list) or isinstance(input_data, tuple):
input_data = " ".join(input_data)
input_data = u(input_data, source_encoding) #decode (or preferably do this in an earlier ... | 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... |
def align(self,inputwords, outputwords):
alignment = []
cursor = 0
for inputword in inputwords:
if len(outputwords) > cursor and outputwords[cursor] == inputword:
alignment.append(cursor)
cursor += 1
elif len(outputwords) > cursor+... | For each inputword, provides the index of the outputword |
def calculate_overlap(haystack, needle, allowpartial=True):
needle = tuple(needle)
haystack = tuple(haystack)
solutions = []
#equality check
if needle == haystack:
return [(needle, 2)]
if allowpartial:
minl =1
else:
minl = len(needle)
for l in range(minl,min(... | 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... |
def tokenize(text, regexps=TOKENIZERRULES):
for i,regexp in list(enumerate(regexps)):
if isstring(regexp):
regexps[i] = re.compile(regexp)
tokens = []
begin = 0
for i, c in enumerate(text):
if begin > i:
continue
elif i == begin:
m = False... | 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
... |
def split_sentences(tokens):
begin = 0
for i, token in enumerate(tokens):
if is_end_of_sentence(tokens, i):
yield tokens[begin:i+1]
begin = i+1
if begin <= len(tokens)-1:
yield tokens[begin:] | Split sentences (based on tokenised data), returns sentences as a list of lists of tokens, each sentence is a list of tokens |
def strip_accents(s, encoding= 'utf-8'):
if sys.version < '3':
if isinstance(s,unicode):
return unicodedata.normalize('NFKD', s).encode('ASCII', 'ignore')
else:
return unicodedata.normalize('NFKD', unicode(s,encoding)).encode('ASCII', 'ignore')
else:
if isinsta... | Strip characters with diacritics and return a flat ascii representation |
def swap(tokens, maxdist=2):
assert maxdist >= 2
tokens = list(tokens)
if maxdist > len(tokens):
maxdist = len(tokens)
l = len(tokens)
for i in range(0,l - 1):
for permutation in permutations(tokens[i:i+maxdist]):
if permutation != tuple(tokens[i:i+maxdist]):
... | 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. |
def find_keyword_in_context(tokens, keyword, contextsize=1):
if isinstance(keyword,tuple) and isinstance(keyword,list):
l = len(keyword)
else:
keyword = (keyword,)
l = 1
n = l + contextsize*2
focuspos = contextsize + 1
for ngram in Windower(tokens,n,None,None):
i... | 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 |
def pop(self):
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 | Retrieve the next element in line, this will remove it from the queue |
def append(self, item):
f = self.f(item)
if callable(f):
score = f()
else:
score = f
if not self.duplicates:
for s, i in self.data:
if s == score and item == i:
#item is a duplicate, don't add it
... | 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) |
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 |
def score(self, i):
if self.minimize:
return self.data[i][0]
else:
return self.data[(-1 * i) - 1][0] | Return the score for item x (cheap lookup), Item 0 is always the best item |
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 |
def randomprune(self,n):
self.data = random.sample(self.data, n) | prune down to n items at random, disregarding their score |
def prunebyscore(self, score, retainequalscore=False):
if retainequalscore:
if self.minimize:
f = lambda x: x[0] <= score
else:
f = lambda x: x[0] >= score
else:
if self.minimize:
f = lambda x: x[0] < score
... | 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 append(self, item):
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 |
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 |
def walk(self, leavesonly=True, maxdepth=None, _depth = 0):
if self.children:
if not maxdepth or (maxdepth and _depth < maxdepth):
for key, child in self.children.items():
if child.leaf():
yield child
else:
... | Depth-first search, walking through trie, returning all encounterd nodes (by default only leaves) |
def sentences(self):
prevp = 0
prevs = 0
sentence = [];
sentence_id = ""
for word, id, pos, lemma in iter(self):
try:
doc_id, ptype, p, s, w = re.findall('([\w\d-]+)\.(p|head)\.(\d+)\.s\.(\d+)\.w\.(\d+)',id)[0]
if ((p != prevp)... | Iterate over all sentences (sentence_id, sentence) in the document, sentence is a list of 4-tuples (word,id,pos,lemma) |
def paragraphs(self, with_id = False):
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]
if prevp != p and partext:
yield ( doc_id + "." ... | Extracts paragraphs, returns list of plain-text(!) paragraphs |
def validate(self, formats_dir="../formats/"):
#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(self.tree)
#return xmlsch... | checks if the document is valid |
def xpath(self, expression):
global namespaces
return self.tree.xpath(expression, namespaces=namespaces) | Executes an xpath expression using the correct namespaces |
def align(self, referencewords, datatuple):
targetwords = []
for i, (word,lemma,postag) in enumerate(zip(datatuple[0],datatuple[1],datatuple[2])):
if word:
subwords = word.split("_")
for w in subwords: #split multiword expressions
... | align the reference sentence with the tagged data |
def mainset(self):
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 { ?seturi skos:notation ?setid } OPTIONAL { ?set... | Returns information regarding the set |
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 row in self.graph.query("SELECT ?seturi ?setid ?setlabel ?setopen WHERE { ?seturi rdf:type skos:Collection . OPTIONAL { ?seturi skos:no... | Returns information regarding the set |
def orderedclasses(self, set_uri_or_id=None, nestedhierarchy=False):
classes = self.classes(set_uri_or_id, nestedhierarchy)
for classid in self.classorder(classes):
yield classes[classid] | Higher-order generator function that yields class information in the right order, combines calls to :meth:`SetDefinition.classes` and :meth:`SetDefinition.classorder` |
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 = set_uri_or_id
else:
set_uri = self.get_set_uri(set_uri_or_id)
assert set_uri is not None
classes= {}
uri... | Returns a dictionary of classes for the specified (sub)set (if None, default, the main set is selected) |
def classorder(self,classes):
return [ classid for classid, classitem in sorted( ((classid, classitem) for classid, classitem in classes.items() if 'seqnr' in classitem) , key=lambda pair: pair[1]['seqnr'] )] + \
[ classid for classid, classitem in sorted( ((classid, classitem) for class... | 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 |
def build(self, **kwargs):
self.lexer = ply.lex.lex(object=self, **kwargs) | Build the lexer. |
def make_varname(tree):
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'):
return make_varname(_xpath_one(tree, '*'... | <left> tree </left> |
def _users_from_environ(env_prefix=''):
auth_string = os.environ.get(env_prefix + 'WSGI_AUTH_CREDENTIALS')
if not auth_string:
return {}
result = {}
for credentials in auth_string.split('|'):
username, password = credentials.split(':', 1)
result[username] = password
retu... | Environment value via `user:password|user2:password2` |
def _exclude_paths_from_environ(env_prefix=''):
paths = os.environ.get(env_prefix + 'WSGI_AUTH_EXCLUDE_PATHS')
if not paths:
return []
return paths.split(';') | Environment value via `/login;/register` |
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` |
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 = request.authorization
if auth and auth[0] == 'Basic':
creden... | 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. |
def _login(self, environ, start_response):
response = HTTPUnauthorized()
response.www_authenticate = ('Basic', {'realm': self._realm})
return response(environ, start_response) | Send a login response back to the client. |
def _is_request_in_include_path(self, request):
if self._include_paths:
for path in self._include_paths:
if request.path.startswith(path):
return True
return False
else:
return True | 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. |
def _is_request_in_exclude_path(self, request):
if self._exclude_paths:
for path in self._exclude_paths:
if request.path.startswith(path):
return True
return False
else:
return False | Check if the request path is in the `_exclude_paths` list |
def bootstrap_prompt(prompt_kwargs, group):
prompt_kwargs = prompt_kwargs or {}
defaults = {
"history": InMemoryHistory(),
"completer": ClickCompleter(group),
"message": u"> ",
}
for key in defaults:
default_value = defaults[key]
if key not in prompt_kwargs:
... | Bootstrap prompt_toolkit kwargs or use user defined values.
:param prompt_kwargs: The user specified prompt kwargs. |
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 = old_ctx.parent or old_ctx
group = group_ctx.command
isatty = sys.stdin.isatty()
# Dele... | 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. |
def register_repl(group, name="repl"):
group.command(name=name)(click.pass_context(repl)) | Register :func:`repl()` as sub-command *name* of *group*. |
def handle_internal_commands(command):
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 ":". |
def fit(self, X):
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:
break
D, gamma = self._update_dict(X, D, gamma)
self.components_ =... | Parameters
----------
X: shape = [n_samples, n_features] |
def node_definitions(id_fetcher, type_resolver=None, id_resolver=None):
node_interface = GraphQLInterfaceType(
'Node',
description='An object with an ID',
fields=lambda: OrderedDict((
('id', GraphQLField(
GraphQLNonNull(GraphQLID),
description... | 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 ... |
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. |
def global_id_field(type_name, id_fetcher=None):
return GraphQLField(
GraphQLNonNull(GraphQLID),
description='The ID of an object',
resolver=lambda obj, args, context, info: to_global_id(
type_name or info.parent_type.name,
id_fetcher(obj, context, info) if id_fe... | 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. |
def connection_from_list(data, args=None, **kwargs):
_len = len(data)
return connection_from_list_slice(
data,
args,
slice_start=0,
list_length=_len,
list_slice_length=_len,
**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. |
def connection_from_promised_list(data_promise, args=None, **kwargs):
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. |
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):
connection_type = connection_type or Connection
edge_type = edge_type or Edge
... | 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... |
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. |
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 int(offset)
except:
return default_offset | 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. |
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):
# Catch errors on string-based input before getting js involved
shade... | 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... |
def generate(data, iterations=1000, force_strength=5.0, dampening=0.01,
max_velocity=2.0, max_distance=50, is_3d=True):
edges = [{'source': s, 'target': t} for s, t in data]
nodes = force_directed_layout.run(edges, iterations, force_strength,
dampening, ma... | 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
... |
def compress(obj):
return json.dumps(obj, sort_keys=True, separators=(',', ':'),
cls=CustomEncoder) | Outputs json without whitespace. |
def dumps(obj):
return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder) | Outputs json with formatting edits + object handling. |
def encode(self, obj):
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. |
def postprocess(self, json_string):
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) +
('"' if is_hash else '{')):
... | Displays each entry on its own line. |
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 from the edge data
nodes = set(e['source'] for e in edges) | set(e['target'] for e in edges)
# Convert to a data-storing object and initialize some values... | 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... |
def _coulomb(n1, n2, k, r):
# 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
if distance < 0.1:
delta = [uniform(0.1, 0.2)... | Calculates Coulomb forces and updates node data. |
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. |
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.debug("starti... | Parse input context string and returns context as dictionary. |
def run_step(context):
logger.debug("started")
context.assert_key_has_value(key='pathCheck', caller=__name__)
paths_to_check = context['pathCheck']
if not paths_to_check:
raise KeyInContextHasNoValueError("context['pathCheck'] must have a "
f"value ... | 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... |
def run_step(context):
logger.debug("started")
context.assert_child_key_has_value('fileWriteJson', 'path', __name__)
out_path = context.get_formatted_string(context['fileWriteJson']['path'])
# doing it like this to safeguard against accidentally dumping all context
# with potentially sensitive ... | 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.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.