id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| docstring_summary
stringclasses 1
value | parameters
stringclasses 1
value | return_statement
stringclasses 1
value | argument_list
stringclasses 1
value | identifier
stringclasses 1
value | nwo
stringclasses 1
value | score
float32 -1
-1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
251,800 | proycon/pynlpl | pynlpl/algorithms.py | sum_to_n | def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number
"""Produce all lists of `size` positive integers in decreasing order
that add up to `n`."""
if size == 1:
yield [n]
return
if limit is None:
limit = n
start = (n + size - 1) // size
stop = min(limit, n - size + 1) + 1
for i in range(start, stop):
for tail in sum_to_n(n - i, size - 1, i):
yield [i] + tail | python | def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number
"""Produce all lists of `size` positive integers in decreasing order
that add up to `n`."""
if size == 1:
yield [n]
return
if limit is None:
limit = n
start = (n + size - 1) // size
stop = min(limit, n - size + 1) + 1
for i in range(start, stop):
for tail in sum_to_n(n - i, size - 1, i):
yield [i] + tail | [
"def",
"sum_to_n",
"(",
"n",
",",
"size",
",",
"limit",
"=",
"None",
")",
":",
"#from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number",
"if",
"size",
"==",
"1",
":",
"yield",
"[",
"n",
"]",
"return",
"if",
"limit",
"is",
"None",
":",
"limit",
"=",
"n",
"start",
"=",
"(",
"n",
"+",
"size",
"-",
"1",
")",
"//",
"size",
"stop",
"=",
"min",
"(",
"limit",
",",
"n",
"-",
"size",
"+",
"1",
")",
"+",
"1",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"stop",
")",
":",
"for",
"tail",
"in",
"sum_to_n",
"(",
"n",
"-",
"i",
",",
"size",
"-",
"1",
",",
"i",
")",
":",
"yield",
"[",
"i",
"]",
"+",
"tail"
] | Produce all lists of `size` positive integers in decreasing order
that add up to `n`. | [
"Produce",
"all",
"lists",
"of",
"size",
"positive",
"integers",
"in",
"decreasing",
"order",
"that",
"add",
"up",
"to",
"n",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/algorithms.py#L19-L31 | -1 |
||||||
251,801 | proycon/pynlpl | pynlpl/formats/cql.py | TokenExpression.nfa | def nfa(self, nextstate):
"""Returns an initial state for an NFA"""
if self.interval:
mininterval, maxinterval = self.interval #pylint: disable=unpacking-non-sequence
nextstate2 = nextstate
for i in range(maxinterval):
state = State(transitions=[(self,self.match, nextstate2)])
if i+1> mininterval:
if nextstate is not nextstate2: state.transitions.append((self,self.match, nextstate))
if maxinterval == MAXINTERVAL:
state.epsilon.append(state)
break
nextstate2 = state
return state
else:
state = State(transitions=[(self,self.match, nextstate)])
return state | python | def nfa(self, nextstate):
"""Returns an initial state for an NFA"""
if self.interval:
mininterval, maxinterval = self.interval #pylint: disable=unpacking-non-sequence
nextstate2 = nextstate
for i in range(maxinterval):
state = State(transitions=[(self,self.match, nextstate2)])
if i+1> mininterval:
if nextstate is not nextstate2: state.transitions.append((self,self.match, nextstate))
if maxinterval == MAXINTERVAL:
state.epsilon.append(state)
break
nextstate2 = state
return state
else:
state = State(transitions=[(self,self.match, nextstate)])
return state | [
"def",
"nfa",
"(",
"self",
",",
"nextstate",
")",
":",
"if",
"self",
".",
"interval",
":",
"mininterval",
",",
"maxinterval",
"=",
"self",
".",
"interval",
"#pylint: disable=unpacking-non-sequence",
"nextstate2",
"=",
"nextstate",
"for",
"i",
"in",
"range",
"(",
"maxinterval",
")",
":",
"state",
"=",
"State",
"(",
"transitions",
"=",
"[",
"(",
"self",
",",
"self",
".",
"match",
",",
"nextstate2",
")",
"]",
")",
"if",
"i",
"+",
"1",
">",
"mininterval",
":",
"if",
"nextstate",
"is",
"not",
"nextstate2",
":",
"state",
".",
"transitions",
".",
"append",
"(",
"(",
"self",
",",
"self",
".",
"match",
",",
"nextstate",
")",
")",
"if",
"maxinterval",
"==",
"MAXINTERVAL",
":",
"state",
".",
"epsilon",
".",
"append",
"(",
"state",
")",
"break",
"nextstate2",
"=",
"state",
"return",
"state",
"else",
":",
"state",
"=",
"State",
"(",
"transitions",
"=",
"[",
"(",
"self",
",",
"self",
".",
"match",
",",
"nextstate",
")",
"]",
")",
"return",
"state"
] | Returns an initial state for an NFA | [
"Returns",
"an",
"initial",
"state",
"for",
"an",
"NFA"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/cql.py#L170-L186 | -1 |
||||||
251,802 | proycon/pynlpl | pynlpl/formats/cql.py | Query.nfa | def nfa(self):
"""convert the expression into an NFA"""
finalstate = State(final=True)
nextstate = finalstate
for tokenexpr in reversed(self):
state = tokenexpr.nfa(nextstate)
nextstate = state
return NFA(state) | python | def nfa(self):
"""convert the expression into an NFA"""
finalstate = State(final=True)
nextstate = finalstate
for tokenexpr in reversed(self):
state = tokenexpr.nfa(nextstate)
nextstate = state
return NFA(state) | [
"def",
"nfa",
"(",
"self",
")",
":",
"finalstate",
"=",
"State",
"(",
"final",
"=",
"True",
")",
"nextstate",
"=",
"finalstate",
"for",
"tokenexpr",
"in",
"reversed",
"(",
"self",
")",
":",
"state",
"=",
"tokenexpr",
".",
"nfa",
"(",
"nextstate",
")",
"nextstate",
"=",
"state",
"return",
"NFA",
"(",
"state",
")"
] | convert the expression into an NFA | [
"convert",
"the",
"expression",
"into",
"an",
"NFA"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/cql.py#L236-L243 | -1 |
||||||
251,803 | proycon/pynlpl | pynlpl/statistics.py | stddev | def stddev(values, meanval=None): #from AI: A Modern Appproach
"""The standard deviation of a set of values.
Pass in the mean if you already know it."""
if meanval == None: meanval = mean(values)
return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) ) | python | def stddev(values, meanval=None): #from AI: A Modern Appproach
"""The standard deviation of a set of values.
Pass in the mean if you already know it."""
if meanval == None: meanval = mean(values)
return math.sqrt( sum([(x - meanval)**2 for x in values]) / (len(values)-1) ) | [
"def",
"stddev",
"(",
"values",
",",
"meanval",
"=",
"None",
")",
":",
"#from AI: A Modern Appproach",
"if",
"meanval",
"==",
"None",
":",
"meanval",
"=",
"mean",
"(",
"values",
")",
"return",
"math",
".",
"sqrt",
"(",
"sum",
"(",
"[",
"(",
"x",
"-",
"meanval",
")",
"**",
"2",
"for",
"x",
"in",
"values",
"]",
")",
"/",
"(",
"len",
"(",
"values",
")",
"-",
"1",
")",
")"
] | The standard deviation of a set of values.
Pass in the mean if you already know it. | [
"The",
"standard",
"deviation",
"of",
"a",
"set",
"of",
"values",
".",
"Pass",
"in",
"the",
"mean",
"if",
"you",
"already",
"know",
"it",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L588-L592 | -1 |
||||||
251,804 | proycon/pynlpl | pynlpl/statistics.py | FrequencyList.save | def save(self, filename, addnormalised=False):
"""Save a frequency list to file, can be loaded later using the load method"""
f = io.open(filename,'w',encoding='utf-8')
for line in self.output("\t", addnormalised):
f.write(line + '\n')
f.close() | python | def save(self, filename, addnormalised=False):
"""Save a frequency list to file, can be loaded later using the load method"""
f = io.open(filename,'w',encoding='utf-8')
for line in self.output("\t", addnormalised):
f.write(line + '\n')
f.close() | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"addnormalised",
"=",
"False",
")",
":",
"f",
"=",
"io",
".",
"open",
"(",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"for",
"line",
"in",
"self",
".",
"output",
"(",
"\"\\t\"",
",",
"addnormalised",
")",
":",
"f",
".",
"write",
"(",
"line",
"+",
"'\\n'",
")",
"f",
".",
"close",
"(",
")"
] | Save a frequency list to file, can be loaded later using the load method | [
"Save",
"a",
"frequency",
"list",
"to",
"file",
"can",
"be",
"loaded",
"later",
"using",
"the",
"load",
"method"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L64-L69 | -1 |
||||||
251,805 | proycon/pynlpl | pynlpl/statistics.py | FrequencyList.output | def output(self,delimiter = '\t', addnormalised=False):
"""Print a representation of the frequency list"""
for type, count in self:
if isinstance(type,tuple) or isinstance(type,list):
if addnormalised:
yield " ".join((u(x) for x in type)) + delimiter + str(count) + delimiter + str(count/self.total)
else:
yield " ".join((u(x) for x in type)) + delimiter + str(count)
elif isstring(type):
if addnormalised:
yield type + delimiter + str(count) + delimiter + str(count/self.total)
else:
yield type + delimiter + str(count)
else:
if addnormalised:
yield str(type) + delimiter + str(count) + delimiter + str(count/self.total)
else:
yield str(type) + delimiter + str(count) | python | def output(self,delimiter = '\t', addnormalised=False):
"""Print a representation of the frequency list"""
for type, count in self:
if isinstance(type,tuple) or isinstance(type,list):
if addnormalised:
yield " ".join((u(x) for x in type)) + delimiter + str(count) + delimiter + str(count/self.total)
else:
yield " ".join((u(x) for x in type)) + delimiter + str(count)
elif isstring(type):
if addnormalised:
yield type + delimiter + str(count) + delimiter + str(count/self.total)
else:
yield type + delimiter + str(count)
else:
if addnormalised:
yield str(type) + delimiter + str(count) + delimiter + str(count/self.total)
else:
yield str(type) + delimiter + str(count) | [
"def",
"output",
"(",
"self",
",",
"delimiter",
"=",
"'\\t'",
",",
"addnormalised",
"=",
"False",
")",
":",
"for",
"type",
",",
"count",
"in",
"self",
":",
"if",
"isinstance",
"(",
"type",
",",
"tuple",
")",
"or",
"isinstance",
"(",
"type",
",",
"list",
")",
":",
"if",
"addnormalised",
":",
"yield",
"\" \"",
".",
"join",
"(",
"(",
"u",
"(",
"x",
")",
"for",
"x",
"in",
"type",
")",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
"/",
"self",
".",
"total",
")",
"else",
":",
"yield",
"\" \"",
".",
"join",
"(",
"(",
"u",
"(",
"x",
")",
"for",
"x",
"in",
"type",
")",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
")",
"elif",
"isstring",
"(",
"type",
")",
":",
"if",
"addnormalised",
":",
"yield",
"type",
"+",
"delimiter",
"+",
"str",
"(",
"count",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
"/",
"self",
".",
"total",
")",
"else",
":",
"yield",
"type",
"+",
"delimiter",
"+",
"str",
"(",
"count",
")",
"else",
":",
"if",
"addnormalised",
":",
"yield",
"str",
"(",
"type",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
"/",
"self",
".",
"total",
")",
"else",
":",
"yield",
"str",
"(",
"type",
")",
"+",
"delimiter",
"+",
"str",
"(",
"count",
")"
] | Print a representation of the frequency list | [
"Print",
"a",
"representation",
"of",
"the",
"frequency",
"list"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L182-L199 | -1 |
||||||
251,806 | proycon/pynlpl | pynlpl/statistics.py | Distribution.entropy | def entropy(self, base = 2):
"""Compute the entropy of the distribution"""
entropy = 0
if not base and self.base: base = self.base
for type in self._dist:
if not base:
entropy += self._dist[type] * -math.log(self._dist[type])
else:
entropy += self._dist[type] * -math.log(self._dist[type], base)
return entropy | python | def entropy(self, base = 2):
"""Compute the entropy of the distribution"""
entropy = 0
if not base and self.base: base = self.base
for type in self._dist:
if not base:
entropy += self._dist[type] * -math.log(self._dist[type])
else:
entropy += self._dist[type] * -math.log(self._dist[type], base)
return entropy | [
"def",
"entropy",
"(",
"self",
",",
"base",
"=",
"2",
")",
":",
"entropy",
"=",
"0",
"if",
"not",
"base",
"and",
"self",
".",
"base",
":",
"base",
"=",
"self",
".",
"base",
"for",
"type",
"in",
"self",
".",
"_dist",
":",
"if",
"not",
"base",
":",
"entropy",
"+=",
"self",
".",
"_dist",
"[",
"type",
"]",
"*",
"-",
"math",
".",
"log",
"(",
"self",
".",
"_dist",
"[",
"type",
"]",
")",
"else",
":",
"entropy",
"+=",
"self",
".",
"_dist",
"[",
"type",
"]",
"*",
"-",
"math",
".",
"log",
"(",
"self",
".",
"_dist",
"[",
"type",
"]",
",",
"base",
")",
"return",
"entropy"
] | Compute the entropy of the distribution | [
"Compute",
"the",
"entropy",
"of",
"the",
"distribution"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L270-L279 | -1 |
||||||
251,807 | proycon/pynlpl | pynlpl/statistics.py | Distribution.output | def output(self,delimiter = '\t', freqlist = None):
"""Generator yielding formatted strings expressing the time and probabily for each item in the distribution"""
for type, prob in self:
if freqlist:
if isinstance(type,list) or isinstance(type, tuple):
yield " ".join(type) + delimiter + str(freqlist[type]) + delimiter + str(prob)
else:
yield type + delimiter + str(freqlist[type]) + delimiter + str(prob)
else:
if isinstance(type,list) or isinstance(type, tuple):
yield " ".join(type) + delimiter + str(prob)
else:
yield type + delimiter + str(prob) | python | def output(self,delimiter = '\t', freqlist = None):
"""Generator yielding formatted strings expressing the time and probabily for each item in the distribution"""
for type, prob in self:
if freqlist:
if isinstance(type,list) or isinstance(type, tuple):
yield " ".join(type) + delimiter + str(freqlist[type]) + delimiter + str(prob)
else:
yield type + delimiter + str(freqlist[type]) + delimiter + str(prob)
else:
if isinstance(type,list) or isinstance(type, tuple):
yield " ".join(type) + delimiter + str(prob)
else:
yield type + delimiter + str(prob) | [
"def",
"output",
"(",
"self",
",",
"delimiter",
"=",
"'\\t'",
",",
"freqlist",
"=",
"None",
")",
":",
"for",
"type",
",",
"prob",
"in",
"self",
":",
"if",
"freqlist",
":",
"if",
"isinstance",
"(",
"type",
",",
"list",
")",
"or",
"isinstance",
"(",
"type",
",",
"tuple",
")",
":",
"yield",
"\" \"",
".",
"join",
"(",
"type",
")",
"+",
"delimiter",
"+",
"str",
"(",
"freqlist",
"[",
"type",
"]",
")",
"+",
"delimiter",
"+",
"str",
"(",
"prob",
")",
"else",
":",
"yield",
"type",
"+",
"delimiter",
"+",
"str",
"(",
"freqlist",
"[",
"type",
"]",
")",
"+",
"delimiter",
"+",
"str",
"(",
"prob",
")",
"else",
":",
"if",
"isinstance",
"(",
"type",
",",
"list",
")",
"or",
"isinstance",
"(",
"type",
",",
"tuple",
")",
":",
"yield",
"\" \"",
".",
"join",
"(",
"type",
")",
"+",
"delimiter",
"+",
"str",
"(",
"prob",
")",
"else",
":",
"yield",
"type",
"+",
"delimiter",
"+",
"str",
"(",
"prob",
")"
] | Generator yielding formatted strings expressing the time and probabily for each item in the distribution | [
"Generator",
"yielding",
"formatted",
"strings",
"expressing",
"the",
"time",
"and",
"probabily",
"for",
"each",
"item",
"in",
"the",
"distribution"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/statistics.py#L316-L328 | -1 |
||||||
251,808 | proycon/pynlpl | pynlpl/clients/freeling.py | FreeLingClient.process | def process(self, sourcewords, debug=False):
"""Process a list of words, passing it to the server and realigning the output with the original words"""
if isinstance( sourcewords, list ) or isinstance( sourcewords, tuple ):
sourcewords_s = " ".join(sourcewords)
else:
sourcewords_s = sourcewords
sourcewords = sourcewords.split(' ')
self.socket.sendall(sourcewords_s.encode(self.encoding) +'\n\0')
if debug: print("Sent:",sourcewords_s.encode(self.encoding),file=sys.stderr)
results = []
done = False
while not done:
data = b""
while not data:
buffer = self.socket.recv(self.BUFSIZE)
if debug: print("Buffer: ["+repr(buffer)+"]",file=sys.stderr)
if buffer[-1] == '\0':
data += buffer[:-1]
done = True
break
else:
data += buffer
data = u(data,self.encoding)
if debug: print("Received:",data,file=sys.stderr)
for i, line in enumerate(data.strip(' \t\0\r\n').split('\n')):
if not line.strip():
done = True
break
else:
cols = line.split(" ")
subwords = cols[0].lower().split("_")
if len(cols) > 2: #this seems a bit odd?
for word in subwords: #split multiword expressions
results.append( (word, cols[1], cols[2], i, len(subwords) > 1 ) ) #word, lemma, pos, index, multiword?
sourcewords = [ w.lower() for w in sourcewords ]
alignment = []
for i, sourceword in enumerate(sourcewords):
found = False
best = 0
distance = 999999
for j, (targetword, lemma, pos, index, multiword) in enumerate(results):
if sourceword == targetword and abs(i-j) < distance:
found = True
best = j
distance = abs(i-j)
if found:
alignment.append(results[best])
else:
alignment.append((None,None,None,None,False)) #no alignment found
return alignment | python | def process(self, sourcewords, debug=False):
"""Process a list of words, passing it to the server and realigning the output with the original words"""
if isinstance( sourcewords, list ) or isinstance( sourcewords, tuple ):
sourcewords_s = " ".join(sourcewords)
else:
sourcewords_s = sourcewords
sourcewords = sourcewords.split(' ')
self.socket.sendall(sourcewords_s.encode(self.encoding) +'\n\0')
if debug: print("Sent:",sourcewords_s.encode(self.encoding),file=sys.stderr)
results = []
done = False
while not done:
data = b""
while not data:
buffer = self.socket.recv(self.BUFSIZE)
if debug: print("Buffer: ["+repr(buffer)+"]",file=sys.stderr)
if buffer[-1] == '\0':
data += buffer[:-1]
done = True
break
else:
data += buffer
data = u(data,self.encoding)
if debug: print("Received:",data,file=sys.stderr)
for i, line in enumerate(data.strip(' \t\0\r\n').split('\n')):
if not line.strip():
done = True
break
else:
cols = line.split(" ")
subwords = cols[0].lower().split("_")
if len(cols) > 2: #this seems a bit odd?
for word in subwords: #split multiword expressions
results.append( (word, cols[1], cols[2], i, len(subwords) > 1 ) ) #word, lemma, pos, index, multiword?
sourcewords = [ w.lower() for w in sourcewords ]
alignment = []
for i, sourceword in enumerate(sourcewords):
found = False
best = 0
distance = 999999
for j, (targetword, lemma, pos, index, multiword) in enumerate(results):
if sourceword == targetword and abs(i-j) < distance:
found = True
best = j
distance = abs(i-j)
if found:
alignment.append(results[best])
else:
alignment.append((None,None,None,None,False)) #no alignment found
return alignment | [
"def",
"process",
"(",
"self",
",",
"sourcewords",
",",
"debug",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"sourcewords",
",",
"list",
")",
"or",
"isinstance",
"(",
"sourcewords",
",",
"tuple",
")",
":",
"sourcewords_s",
"=",
"\" \"",
".",
"join",
"(",
"sourcewords",
")",
"else",
":",
"sourcewords_s",
"=",
"sourcewords",
"sourcewords",
"=",
"sourcewords",
".",
"split",
"(",
"' '",
")",
"self",
".",
"socket",
".",
"sendall",
"(",
"sourcewords_s",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
"+",
"'\\n\\0'",
")",
"if",
"debug",
":",
"print",
"(",
"\"Sent:\"",
",",
"sourcewords_s",
".",
"encode",
"(",
"self",
".",
"encoding",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"results",
"=",
"[",
"]",
"done",
"=",
"False",
"while",
"not",
"done",
":",
"data",
"=",
"b\"\"",
"while",
"not",
"data",
":",
"buffer",
"=",
"self",
".",
"socket",
".",
"recv",
"(",
"self",
".",
"BUFSIZE",
")",
"if",
"debug",
":",
"print",
"(",
"\"Buffer: [\"",
"+",
"repr",
"(",
"buffer",
")",
"+",
"\"]\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"if",
"buffer",
"[",
"-",
"1",
"]",
"==",
"'\\0'",
":",
"data",
"+=",
"buffer",
"[",
":",
"-",
"1",
"]",
"done",
"=",
"True",
"break",
"else",
":",
"data",
"+=",
"buffer",
"data",
"=",
"u",
"(",
"data",
",",
"self",
".",
"encoding",
")",
"if",
"debug",
":",
"print",
"(",
"\"Received:\"",
",",
"data",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"data",
".",
"strip",
"(",
"' \\t\\0\\r\\n'",
")",
".",
"split",
"(",
"'\\n'",
")",
")",
":",
"if",
"not",
"line",
".",
"strip",
"(",
")",
":",
"done",
"=",
"True",
"break",
"else",
":",
"cols",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"subwords",
"=",
"cols",
"[",
"0",
"]",
".",
"lower",
"(",
")",
".",
"split",
"(",
"\"_\"",
")",
"if",
"len",
"(",
"cols",
")",
">",
"2",
":",
"#this seems a bit odd?",
"for",
"word",
"in",
"subwords",
":",
"#split multiword expressions",
"results",
".",
"append",
"(",
"(",
"word",
",",
"cols",
"[",
"1",
"]",
",",
"cols",
"[",
"2",
"]",
",",
"i",
",",
"len",
"(",
"subwords",
")",
">",
"1",
")",
")",
"#word, lemma, pos, index, multiword?",
"sourcewords",
"=",
"[",
"w",
".",
"lower",
"(",
")",
"for",
"w",
"in",
"sourcewords",
"]",
"alignment",
"=",
"[",
"]",
"for",
"i",
",",
"sourceword",
"in",
"enumerate",
"(",
"sourcewords",
")",
":",
"found",
"=",
"False",
"best",
"=",
"0",
"distance",
"=",
"999999",
"for",
"j",
",",
"(",
"targetword",
",",
"lemma",
",",
"pos",
",",
"index",
",",
"multiword",
")",
"in",
"enumerate",
"(",
"results",
")",
":",
"if",
"sourceword",
"==",
"targetword",
"and",
"abs",
"(",
"i",
"-",
"j",
")",
"<",
"distance",
":",
"found",
"=",
"True",
"best",
"=",
"j",
"distance",
"=",
"abs",
"(",
"i",
"-",
"j",
")",
"if",
"found",
":",
"alignment",
".",
"append",
"(",
"results",
"[",
"best",
"]",
")",
"else",
":",
"alignment",
".",
"append",
"(",
"(",
"None",
",",
"None",
",",
"None",
",",
"None",
",",
"False",
")",
")",
"#no alignment found",
"return",
"alignment"
] | Process a list of words, passing it to the server and realigning the output with the original words | [
"Process",
"a",
"list",
"of",
"words",
"passing",
"it",
"to",
"the",
"server",
"and",
"realigning",
"the",
"output",
"with",
"the",
"original",
"words"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/clients/freeling.py#L43-L101 | -1 |
||||||
251,809 | proycon/pynlpl | pynlpl/formats/folia.py | checkversion | def checkversion(version, REFVERSION=FOLIAVERSION):
"""Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal"""
try:
for refversion, docversion in zip([int(x) for x in REFVERSION.split('.')], [int(x) for x in version.split('.')]):
if docversion > refversion:
return 1 #doc is newer than library
elif docversion < refversion:
return -1 #doc is older than library
return 0 #versions are equal
except ValueError:
raise ValueError("Unable to parse document FoLiA version, invalid syntax") | python | def checkversion(version, REFVERSION=FOLIAVERSION):
"""Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal"""
try:
for refversion, docversion in zip([int(x) for x in REFVERSION.split('.')], [int(x) for x in version.split('.')]):
if docversion > refversion:
return 1 #doc is newer than library
elif docversion < refversion:
return -1 #doc is older than library
return 0 #versions are equal
except ValueError:
raise ValueError("Unable to parse document FoLiA version, invalid syntax") | [
"def",
"checkversion",
"(",
"version",
",",
"REFVERSION",
"=",
"FOLIAVERSION",
")",
":",
"try",
":",
"for",
"refversion",
",",
"docversion",
"in",
"zip",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"REFVERSION",
".",
"split",
"(",
"'.'",
")",
"]",
",",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"version",
".",
"split",
"(",
"'.'",
")",
"]",
")",
":",
"if",
"docversion",
">",
"refversion",
":",
"return",
"1",
"#doc is newer than library",
"elif",
"docversion",
"<",
"refversion",
":",
"return",
"-",
"1",
"#doc is older than library",
"return",
"0",
"#versions are equal",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Unable to parse document FoLiA version, invalid syntax\"",
")"
] | Checks FoLiA version, returns 1 if the document is newer than the library, -1 if it is older, 0 if it is equal | [
"Checks",
"FoLiA",
"version",
"returns",
"1",
"if",
"the",
"document",
"is",
"newer",
"than",
"the",
"library",
"-",
"1",
"if",
"it",
"is",
"older",
"0",
"if",
"it",
"is",
"equal"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L199-L209 | -1 |
||||||
251,810 | proycon/pynlpl | pynlpl/formats/folia.py | xmltreefromstring | def xmltreefromstring(s):
"""Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml"""
if sys.version < '3':
#Python 2
if isinstance(s,unicode): #pylint: disable=undefined-variable
s = s.encode('utf-8')
try:
return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(StringIO(s), ElementTree.XMLParser()) #older lxml, may leak!!!!
else:
#Python 3
if isinstance(s,str):
s = s.encode('utf-8')
try:
return ElementTree.parse(BytesIO(s), ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(BytesIO(s), ElementTree.XMLParser()) | python | def xmltreefromstring(s):
"""Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml"""
if sys.version < '3':
#Python 2
if isinstance(s,unicode): #pylint: disable=undefined-variable
s = s.encode('utf-8')
try:
return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(StringIO(s), ElementTree.XMLParser()) #older lxml, may leak!!!!
else:
#Python 3
if isinstance(s,str):
s = s.encode('utf-8')
try:
return ElementTree.parse(BytesIO(s), ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(BytesIO(s), ElementTree.XMLParser()) | [
"def",
"xmltreefromstring",
"(",
"s",
")",
":",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"#Python 2",
"if",
"isinstance",
"(",
"s",
",",
"unicode",
")",
":",
"#pylint: disable=undefined-variable",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"try",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"StringIO",
"(",
"s",
")",
",",
"ElementTree",
".",
"XMLParser",
"(",
"collect_ids",
"=",
"False",
")",
")",
"except",
"TypeError",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"StringIO",
"(",
"s",
")",
",",
"ElementTree",
".",
"XMLParser",
"(",
")",
")",
"#older lxml, may leak!!!!",
"else",
":",
"#Python 3",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"try",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"BytesIO",
"(",
"s",
")",
",",
"ElementTree",
".",
"XMLParser",
"(",
"collect_ids",
"=",
"False",
")",
")",
"except",
"TypeError",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"BytesIO",
"(",
"s",
")",
",",
"ElementTree",
".",
"XMLParser",
"(",
")",
")"
] | Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml | [
"Internal",
"function",
"deals",
"with",
"different",
"Python",
"versions",
"unicode",
"strings",
"versus",
"bytes",
"and",
"with",
"the",
"leak",
"bug",
"in",
"lxml"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L543-L560 | -1 |
||||||
251,811 | proycon/pynlpl | pynlpl/formats/folia.py | xmltreefromfile | def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(filename, ElementTree.XMLParser()) | python | def xmltreefromfile(filename):
"""Internal function to read an XML file"""
try:
return ElementTree.parse(filename, ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(filename, ElementTree.XMLParser()) | [
"def",
"xmltreefromfile",
"(",
"filename",
")",
":",
"try",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"filename",
",",
"ElementTree",
".",
"XMLParser",
"(",
"collect_ids",
"=",
"False",
")",
")",
"except",
"TypeError",
":",
"return",
"ElementTree",
".",
"parse",
"(",
"filename",
",",
"ElementTree",
".",
"XMLParser",
"(",
")",
")"
] | Internal function to read an XML file | [
"Internal",
"function",
"to",
"read",
"an",
"XML",
"file"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L562-L567 | -1 |
||||||
251,812 | proycon/pynlpl | pynlpl/formats/folia.py | commonancestors | def commonancestors(Class, *args):
"""Generator function to find common ancestors of a particular type for any two or more FoLiA element instances.
The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one.
Parameters:
Class: The type of ancestor to find, should be the :class:`AbstractElement` class or any subclass thereof (not an instance!)
*args: The elements to find the common ancestors of, elements are instances derived from :class:`AbstractElement`
Yields:
instance derived from :class:`AbstractElement`: A common ancestor of the arguments, an instance of the specified ``Class``.
"""
commonancestors = None #pylint: disable=redefined-outer-name
for sibling in args:
ancestors = list( sibling.ancestors(Class) )
if commonancestors is None:
commonancestors = copy(ancestors)
else:
removeancestors = []
for a in commonancestors: #pylint: disable=not-an-iterable
if not a in ancestors:
removeancestors.append(a)
for a in removeancestors:
commonancestors.remove(a)
if commonancestors:
for commonancestor in commonancestors:
yield commonancestor | python | def commonancestors(Class, *args):
"""Generator function to find common ancestors of a particular type for any two or more FoLiA element instances.
The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one.
Parameters:
Class: The type of ancestor to find, should be the :class:`AbstractElement` class or any subclass thereof (not an instance!)
*args: The elements to find the common ancestors of, elements are instances derived from :class:`AbstractElement`
Yields:
instance derived from :class:`AbstractElement`: A common ancestor of the arguments, an instance of the specified ``Class``.
"""
commonancestors = None #pylint: disable=redefined-outer-name
for sibling in args:
ancestors = list( sibling.ancestors(Class) )
if commonancestors is None:
commonancestors = copy(ancestors)
else:
removeancestors = []
for a in commonancestors: #pylint: disable=not-an-iterable
if not a in ancestors:
removeancestors.append(a)
for a in removeancestors:
commonancestors.remove(a)
if commonancestors:
for commonancestor in commonancestors:
yield commonancestor | [
"def",
"commonancestors",
"(",
"Class",
",",
"*",
"args",
")",
":",
"commonancestors",
"=",
"None",
"#pylint: disable=redefined-outer-name",
"for",
"sibling",
"in",
"args",
":",
"ancestors",
"=",
"list",
"(",
"sibling",
".",
"ancestors",
"(",
"Class",
")",
")",
"if",
"commonancestors",
"is",
"None",
":",
"commonancestors",
"=",
"copy",
"(",
"ancestors",
")",
"else",
":",
"removeancestors",
"=",
"[",
"]",
"for",
"a",
"in",
"commonancestors",
":",
"#pylint: disable=not-an-iterable",
"if",
"not",
"a",
"in",
"ancestors",
":",
"removeancestors",
".",
"append",
"(",
"a",
")",
"for",
"a",
"in",
"removeancestors",
":",
"commonancestors",
".",
"remove",
"(",
"a",
")",
"if",
"commonancestors",
":",
"for",
"commonancestor",
"in",
"commonancestors",
":",
"yield",
"commonancestor"
] | Generator function to find common ancestors of a particular type for any two or more FoLiA element instances.
The function produces all common ancestors of the type specified, starting from the closest one up to the most distant one.
Parameters:
Class: The type of ancestor to find, should be the :class:`AbstractElement` class or any subclass thereof (not an instance!)
*args: The elements to find the common ancestors of, elements are instances derived from :class:`AbstractElement`
Yields:
instance derived from :class:`AbstractElement`: A common ancestor of the arguments, an instance of the specified ``Class``. | [
"Generator",
"function",
"to",
"find",
"common",
"ancestors",
"of",
"a",
"particular",
"type",
"for",
"any",
"two",
"or",
"more",
"FoLiA",
"element",
"instances",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L594-L621 | -1 |
||||||
251,813 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.description | def description(self):
"""Obtain the description associated with the element.
Raises:
:class:`NoSuchAnnotation` if there is no associated description."""
for e in self:
if isinstance(e, Description):
return e.value
raise NoSuchAnnotation | python | def description(self):
"""Obtain the description associated with the element.
Raises:
:class:`NoSuchAnnotation` if there is no associated description."""
for e in self:
if isinstance(e, Description):
return e.value
raise NoSuchAnnotation | [
"def",
"description",
"(",
"self",
")",
":",
"for",
"e",
"in",
"self",
":",
"if",
"isinstance",
"(",
"e",
",",
"Description",
")",
":",
"return",
"e",
".",
"value",
"raise",
"NoSuchAnnotation"
] | Obtain the description associated with the element.
Raises:
:class:`NoSuchAnnotation` if there is no associated description. | [
"Obtain",
"the",
"description",
"associated",
"with",
"the",
"element",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L722-L730 | -1 |
||||||
251,814 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.findcorrectionhandling | def findcorrectionhandling(self, cls):
"""Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused"""
if cls == "current":
return CorrectionHandling.CURRENT
elif cls == "original":
return CorrectionHandling.ORIGINAL #backward compatibility
else:
correctionhandling = None
#but any other class may be anything
#Do we have corrections at all? otherwise no need to bother
for correction in self.select(Correction):
#yes, in which branch is the text class found?
found = False
hastext = False
if correction.hasnew():
found = True
doublecorrection = correction.new().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.new().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.CURRENT
break
elif correction.hascurrent():
found = True
doublecorrection = correction.current().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.current().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.CURRENT
break
if correction.hasoriginal():
found = True
doublecorrection = correction.original().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.original().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.ORIGINAL:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.ORIGINAL
break
if correctionhandling is None:
#well, we couldn't find our textclass in any correction, just fall back to current and let text validation fail if needed
return CorrectionHandling.CURRENT | python | def findcorrectionhandling(self, cls):
"""Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused"""
if cls == "current":
return CorrectionHandling.CURRENT
elif cls == "original":
return CorrectionHandling.ORIGINAL #backward compatibility
else:
correctionhandling = None
#but any other class may be anything
#Do we have corrections at all? otherwise no need to bother
for correction in self.select(Correction):
#yes, in which branch is the text class found?
found = False
hastext = False
if correction.hasnew():
found = True
doublecorrection = correction.new().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.new().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.CURRENT
break
elif correction.hascurrent():
found = True
doublecorrection = correction.current().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.current().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.CURRENT
break
if correction.hasoriginal():
found = True
doublecorrection = correction.original().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.original().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.ORIGINAL:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.ORIGINAL
break
if correctionhandling is None:
#well, we couldn't find our textclass in any correction, just fall back to current and let text validation fail if needed
return CorrectionHandling.CURRENT | [
"def",
"findcorrectionhandling",
"(",
"self",
",",
"cls",
")",
":",
"if",
"cls",
"==",
"\"current\"",
":",
"return",
"CorrectionHandling",
".",
"CURRENT",
"elif",
"cls",
"==",
"\"original\"",
":",
"return",
"CorrectionHandling",
".",
"ORIGINAL",
"#backward compatibility",
"else",
":",
"correctionhandling",
"=",
"None",
"#but any other class may be anything",
"#Do we have corrections at all? otherwise no need to bother",
"for",
"correction",
"in",
"self",
".",
"select",
"(",
"Correction",
")",
":",
"#yes, in which branch is the text class found?",
"found",
"=",
"False",
"hastext",
"=",
"False",
"if",
"correction",
".",
"hasnew",
"(",
")",
":",
"found",
"=",
"True",
"doublecorrection",
"=",
"correction",
".",
"new",
"(",
")",
".",
"count",
"(",
"Correction",
")",
">",
"0",
"if",
"doublecorrection",
":",
"return",
"None",
"#skipping text validation, correction is too complex (nested) to handle for now",
"for",
"t",
"in",
"correction",
".",
"new",
"(",
")",
".",
"select",
"(",
"TextContent",
")",
":",
"hastext",
"=",
"True",
"if",
"t",
".",
"cls",
"==",
"cls",
":",
"if",
"correctionhandling",
"is",
"not",
"None",
"and",
"correctionhandling",
"!=",
"CorrectionHandling",
".",
"CURRENT",
":",
"return",
"None",
"#inconsistent",
"else",
":",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"CURRENT",
"break",
"elif",
"correction",
".",
"hascurrent",
"(",
")",
":",
"found",
"=",
"True",
"doublecorrection",
"=",
"correction",
".",
"current",
"(",
")",
".",
"count",
"(",
"Correction",
")",
">",
"0",
"if",
"doublecorrection",
":",
"return",
"None",
"#skipping text validation, correction is too complex (nested) to handle for now",
"for",
"t",
"in",
"correction",
".",
"current",
"(",
")",
".",
"select",
"(",
"TextContent",
")",
":",
"hastext",
"=",
"True",
"if",
"t",
".",
"cls",
"==",
"cls",
":",
"if",
"correctionhandling",
"is",
"not",
"None",
"and",
"correctionhandling",
"!=",
"CorrectionHandling",
".",
"CURRENT",
":",
"return",
"None",
"#inconsistent",
"else",
":",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"CURRENT",
"break",
"if",
"correction",
".",
"hasoriginal",
"(",
")",
":",
"found",
"=",
"True",
"doublecorrection",
"=",
"correction",
".",
"original",
"(",
")",
".",
"count",
"(",
"Correction",
")",
">",
"0",
"if",
"doublecorrection",
":",
"return",
"None",
"#skipping text validation, correction is too complex (nested) to handle for now",
"for",
"t",
"in",
"correction",
".",
"original",
"(",
")",
".",
"select",
"(",
"TextContent",
")",
":",
"hastext",
"=",
"True",
"if",
"t",
".",
"cls",
"==",
"cls",
":",
"if",
"correctionhandling",
"is",
"not",
"None",
"and",
"correctionhandling",
"!=",
"CorrectionHandling",
".",
"ORIGINAL",
":",
"return",
"None",
"#inconsistent",
"else",
":",
"correctionhandling",
"=",
"CorrectionHandling",
".",
"ORIGINAL",
"break",
"if",
"correctionhandling",
"is",
"None",
":",
"#well, we couldn't find our textclass in any correction, just fall back to current and let text validation fail if needed",
"return",
"CorrectionHandling",
".",
"CURRENT"
] | Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused | [
"Find",
"the",
"proper",
"correctionhandling",
"given",
"a",
"textclass",
"by",
"looking",
"in",
"the",
"underlying",
"corrections",
"where",
"it",
"is",
"reused"
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L774-L826 | -1 |
||||||
251,815 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.textvalidation | def textvalidation(self, warnonly=None):
"""Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid.
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
"""
if warnonly is None and self.doc and self.doc.version:
warnonly = (checkversion(self.doc.version, '1.5.0') < 0) #warn only for documents older than FoLiA v1.5
valid = True
for cls in self.doc.textclasses:
if self.hastext(cls, strict=True) and not isinstance(self, (Linebreak, Whitespace)):
if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Text validation on " + repr(self),file=stderr)
correctionhandling = self.findcorrectionhandling(cls)
if correctionhandling is None:
#skipping text validation, correction is too complex (nested) to handle for now; just assume valid (benefit of the doubt)
if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] SKIPPING Text validation on " + repr(self) + ", too complex to handle (nested corrections or inconsistent use)",file=stderr)
return True #just assume it's valid then
strictnormtext = self.text(cls,retaintokenisation=False,strict=True, normalize_spaces=True)
deepnormtext = self.text(cls,retaintokenisation=False,strict=False, normalize_spaces=True)
if strictnormtext != deepnormtext:
valid = False
deviation = 0
for i, (c1,c2) in enumerate(zip(strictnormtext,deepnormtext)):
if c1 != c2:
deviation = i
break
msg = "Text for " + self.__class__.__name__ + ", ID " + str(self.id) + ", class " + cls + ", is inconsistent: EXPECTED (after normalization) *****>\n" + deepnormtext + "\n****> BUT FOUND (after normalization) ****>\n" + strictnormtext + "\n******* DEVIATION POINT: " + strictnormtext[max(0,deviation-10):deviation] + "<*HERE*>" + strictnormtext[deviation:deviation+10]
if warnonly:
print("TEXT VALIDATION ERROR: " + msg,file=sys.stderr)
else:
raise InconsistentText(msg)
#validate offsets
tc = self.textcontent(cls)
if tc.offset is not None:
#we can't validate the reference of this element yet since it may point to higher level elements still being created!! we store it in a buffer that will
#be processed by pendingvalidation() after parsing and prior to serialisation
if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Queing element for later offset validation: " + repr(self),file=stderr)
self.doc.offsetvalidationbuffer.append( (self, cls) )
return valid | python | def textvalidation(self, warnonly=None):
"""Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid.
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
"""
if warnonly is None and self.doc and self.doc.version:
warnonly = (checkversion(self.doc.version, '1.5.0') < 0) #warn only for documents older than FoLiA v1.5
valid = True
for cls in self.doc.textclasses:
if self.hastext(cls, strict=True) and not isinstance(self, (Linebreak, Whitespace)):
if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Text validation on " + repr(self),file=stderr)
correctionhandling = self.findcorrectionhandling(cls)
if correctionhandling is None:
#skipping text validation, correction is too complex (nested) to handle for now; just assume valid (benefit of the doubt)
if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] SKIPPING Text validation on " + repr(self) + ", too complex to handle (nested corrections or inconsistent use)",file=stderr)
return True #just assume it's valid then
strictnormtext = self.text(cls,retaintokenisation=False,strict=True, normalize_spaces=True)
deepnormtext = self.text(cls,retaintokenisation=False,strict=False, normalize_spaces=True)
if strictnormtext != deepnormtext:
valid = False
deviation = 0
for i, (c1,c2) in enumerate(zip(strictnormtext,deepnormtext)):
if c1 != c2:
deviation = i
break
msg = "Text for " + self.__class__.__name__ + ", ID " + str(self.id) + ", class " + cls + ", is inconsistent: EXPECTED (after normalization) *****>\n" + deepnormtext + "\n****> BUT FOUND (after normalization) ****>\n" + strictnormtext + "\n******* DEVIATION POINT: " + strictnormtext[max(0,deviation-10):deviation] + "<*HERE*>" + strictnormtext[deviation:deviation+10]
if warnonly:
print("TEXT VALIDATION ERROR: " + msg,file=sys.stderr)
else:
raise InconsistentText(msg)
#validate offsets
tc = self.textcontent(cls)
if tc.offset is not None:
#we can't validate the reference of this element yet since it may point to higher level elements still being created!! we store it in a buffer that will
#be processed by pendingvalidation() after parsing and prior to serialisation
if self.doc and self.doc.debug: print("[PyNLPl FoLiA DEBUG] Queing element for later offset validation: " + repr(self),file=stderr)
self.doc.offsetvalidationbuffer.append( (self, cls) )
return valid | [
"def",
"textvalidation",
"(",
"self",
",",
"warnonly",
"=",
"None",
")",
":",
"if",
"warnonly",
"is",
"None",
"and",
"self",
".",
"doc",
"and",
"self",
".",
"doc",
".",
"version",
":",
"warnonly",
"=",
"(",
"checkversion",
"(",
"self",
".",
"doc",
".",
"version",
",",
"'1.5.0'",
")",
"<",
"0",
")",
"#warn only for documents older than FoLiA v1.5",
"valid",
"=",
"True",
"for",
"cls",
"in",
"self",
".",
"doc",
".",
"textclasses",
":",
"if",
"self",
".",
"hastext",
"(",
"cls",
",",
"strict",
"=",
"True",
")",
"and",
"not",
"isinstance",
"(",
"self",
",",
"(",
"Linebreak",
",",
"Whitespace",
")",
")",
":",
"if",
"self",
".",
"doc",
"and",
"self",
".",
"doc",
".",
"debug",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Text validation on \"",
"+",
"repr",
"(",
"self",
")",
",",
"file",
"=",
"stderr",
")",
"correctionhandling",
"=",
"self",
".",
"findcorrectionhandling",
"(",
"cls",
")",
"if",
"correctionhandling",
"is",
"None",
":",
"#skipping text validation, correction is too complex (nested) to handle for now; just assume valid (benefit of the doubt)",
"if",
"self",
".",
"doc",
"and",
"self",
".",
"doc",
".",
"debug",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] SKIPPING Text validation on \"",
"+",
"repr",
"(",
"self",
")",
"+",
"\", too complex to handle (nested corrections or inconsistent use)\"",
",",
"file",
"=",
"stderr",
")",
"return",
"True",
"#just assume it's valid then",
"strictnormtext",
"=",
"self",
".",
"text",
"(",
"cls",
",",
"retaintokenisation",
"=",
"False",
",",
"strict",
"=",
"True",
",",
"normalize_spaces",
"=",
"True",
")",
"deepnormtext",
"=",
"self",
".",
"text",
"(",
"cls",
",",
"retaintokenisation",
"=",
"False",
",",
"strict",
"=",
"False",
",",
"normalize_spaces",
"=",
"True",
")",
"if",
"strictnormtext",
"!=",
"deepnormtext",
":",
"valid",
"=",
"False",
"deviation",
"=",
"0",
"for",
"i",
",",
"(",
"c1",
",",
"c2",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"strictnormtext",
",",
"deepnormtext",
")",
")",
":",
"if",
"c1",
"!=",
"c2",
":",
"deviation",
"=",
"i",
"break",
"msg",
"=",
"\"Text for \"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\", ID \"",
"+",
"str",
"(",
"self",
".",
"id",
")",
"+",
"\", class \"",
"+",
"cls",
"+",
"\", is inconsistent: EXPECTED (after normalization) *****>\\n\"",
"+",
"deepnormtext",
"+",
"\"\\n****> BUT FOUND (after normalization) ****>\\n\"",
"+",
"strictnormtext",
"+",
"\"\\n******* DEVIATION POINT: \"",
"+",
"strictnormtext",
"[",
"max",
"(",
"0",
",",
"deviation",
"-",
"10",
")",
":",
"deviation",
"]",
"+",
"\"<*HERE*>\"",
"+",
"strictnormtext",
"[",
"deviation",
":",
"deviation",
"+",
"10",
"]",
"if",
"warnonly",
":",
"print",
"(",
"\"TEXT VALIDATION ERROR: \"",
"+",
"msg",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"raise",
"InconsistentText",
"(",
"msg",
")",
"#validate offsets",
"tc",
"=",
"self",
".",
"textcontent",
"(",
"cls",
")",
"if",
"tc",
".",
"offset",
"is",
"not",
"None",
":",
"#we can't validate the reference of this element yet since it may point to higher level elements still being created!! we store it in a buffer that will",
"#be processed by pendingvalidation() after parsing and prior to serialisation",
"if",
"self",
".",
"doc",
"and",
"self",
".",
"doc",
".",
"debug",
":",
"print",
"(",
"\"[PyNLPl FoLiA DEBUG] Queing element for later offset validation: \"",
"+",
"repr",
"(",
"self",
")",
",",
"file",
"=",
"stderr",
")",
"self",
".",
"doc",
".",
"offsetvalidationbuffer",
".",
"append",
"(",
"(",
"self",
",",
"cls",
")",
")",
"return",
"valid"
] | Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid.
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 | [
"Run",
"text",
"validation",
"on",
"this",
"element",
".",
"Checks",
"whether",
"any",
"text",
"redundancy",
"is",
"consistent",
"and",
"whether",
"offsets",
"are",
"valid",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L829-L873 | -1 |
||||||
251,816 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.speech_speaker | def speech_speaker(self):
"""Retrieves the speaker of the audio or video file associated with the element.
The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly.
Returns:
str or None if not found
"""
if self.speaker:
return self.speaker
elif self.parent:
return self.parent.speech_speaker()
else:
return None | python | def speech_speaker(self):
"""Retrieves the speaker of the audio or video file associated with the element.
The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly.
Returns:
str or None if not found
"""
if self.speaker:
return self.speaker
elif self.parent:
return self.parent.speech_speaker()
else:
return None | [
"def",
"speech_speaker",
"(",
"self",
")",
":",
"if",
"self",
".",
"speaker",
":",
"return",
"self",
".",
"speaker",
"elif",
"self",
".",
"parent",
":",
"return",
"self",
".",
"parent",
".",
"speech_speaker",
"(",
")",
"else",
":",
"return",
"None"
] | Retrieves the speaker of the audio or video file associated with the element.
The source is inherited from ancestor elements if none is specified. For this reason, always use this method rather than access the ``src`` attribute directly.
Returns:
str or None if not found | [
"Retrieves",
"the",
"speaker",
"of",
"the",
"audio",
"or",
"video",
"file",
"associated",
"with",
"the",
"element",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1004-L1017 | -1 |
||||||
251,817 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.feat | def feat(self,subset):
"""Obtain the feature class value of the specific subset.
If a feature occurs multiple times, the values will be returned in a list.
Example::
sense = word.annotation(folia.Sense)
synset = sense.feat('synset')
Returns:
str or list
"""
r = None
for f in self:
if isinstance(f, Feature) and f.subset == subset:
if r: #support for multiclass features
if isinstance(r,list):
r.append(f.cls)
else:
r = [r, f.cls]
else:
r = f.cls
if r is None:
raise NoSuchAnnotation
else:
return r | python | def feat(self,subset):
"""Obtain the feature class value of the specific subset.
If a feature occurs multiple times, the values will be returned in a list.
Example::
sense = word.annotation(folia.Sense)
synset = sense.feat('synset')
Returns:
str or list
"""
r = None
for f in self:
if isinstance(f, Feature) and f.subset == subset:
if r: #support for multiclass features
if isinstance(r,list):
r.append(f.cls)
else:
r = [r, f.cls]
else:
r = f.cls
if r is None:
raise NoSuchAnnotation
else:
return r | [
"def",
"feat",
"(",
"self",
",",
"subset",
")",
":",
"r",
"=",
"None",
"for",
"f",
"in",
"self",
":",
"if",
"isinstance",
"(",
"f",
",",
"Feature",
")",
"and",
"f",
".",
"subset",
"==",
"subset",
":",
"if",
"r",
":",
"#support for multiclass features",
"if",
"isinstance",
"(",
"r",
",",
"list",
")",
":",
"r",
".",
"append",
"(",
"f",
".",
"cls",
")",
"else",
":",
"r",
"=",
"[",
"r",
",",
"f",
".",
"cls",
"]",
"else",
":",
"r",
"=",
"f",
".",
"cls",
"if",
"r",
"is",
"None",
":",
"raise",
"NoSuchAnnotation",
"else",
":",
"return",
"r"
] | Obtain the feature class value of the specific subset.
If a feature occurs multiple times, the values will be returned in a list.
Example::
sense = word.annotation(folia.Sense)
synset = sense.feat('synset')
Returns:
str or list | [
"Obtain",
"the",
"feature",
"class",
"value",
"of",
"the",
"specific",
"subset",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1114-L1140 | -1 |
||||||
251,818 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.copy | def copy(self, newdoc=None, idsuffix=""):
"""Make a deep copy of this element and all its children.
Parameters:
newdoc (:class:`Document`): The document the copy should be associated with.
idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same document). If set to ``True``, a random suffix will be generated.
Returns:
a copy of the element
"""
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children
c = deepcopy(self)
if idsuffix:
c.addidsuffix(idsuffix)
c.setparents()
c.setdoc(newdoc)
return c | python | def copy(self, newdoc=None, idsuffix=""):
"""Make a deep copy of this element and all its children.
Parameters:
newdoc (:class:`Document`): The document the copy should be associated with.
idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same document). If set to ``True``, a random suffix will be generated.
Returns:
a copy of the element
"""
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children
c = deepcopy(self)
if idsuffix:
c.addidsuffix(idsuffix)
c.setparents()
c.setdoc(newdoc)
return c | [
"def",
"copy",
"(",
"self",
",",
"newdoc",
"=",
"None",
",",
"idsuffix",
"=",
"\"\"",
")",
":",
"if",
"idsuffix",
"is",
"True",
":",
"idsuffix",
"=",
"\".copy.\"",
"+",
"\"%08x\"",
"%",
"random",
".",
"getrandbits",
"(",
"32",
")",
"#random 32-bit hash for each copy, same one will be reused for all children",
"c",
"=",
"deepcopy",
"(",
"self",
")",
"if",
"idsuffix",
":",
"c",
".",
"addidsuffix",
"(",
"idsuffix",
")",
"c",
".",
"setparents",
"(",
")",
"c",
".",
"setdoc",
"(",
"newdoc",
")",
"return",
"c"
] | Make a deep copy of this element and all its children.
Parameters:
newdoc (:class:`Document`): The document the copy should be associated with.
idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (prevents duplicate IDs when making copies for the same document). If set to ``True``, a random suffix will be generated.
Returns:
a copy of the element | [
"Make",
"a",
"deep",
"copy",
"of",
"this",
"element",
"and",
"all",
"its",
"children",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1234-L1250 | -1 |
||||||
251,819 | proycon/pynlpl | pynlpl/formats/folia.py | AbstractElement.copychildren | def copychildren(self, newdoc=None, idsuffix=""):
"""Generator creating a deep copy of the children of this element.
Invokes :meth:`copy` on all children, parameters are the same.
"""
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children
for c in self:
if isinstance(c, AbstractElement):
yield c.copy(newdoc,idsuffix) | python | def copychildren(self, newdoc=None, idsuffix=""):
"""Generator creating a deep copy of the children of this element.
Invokes :meth:`copy` on all children, parameters are the same.
"""
if idsuffix is True: idsuffix = ".copy." + "%08x" % random.getrandbits(32) #random 32-bit hash for each copy, same one will be reused for all children
for c in self:
if isinstance(c, AbstractElement):
yield c.copy(newdoc,idsuffix) | [
"def",
"copychildren",
"(",
"self",
",",
"newdoc",
"=",
"None",
",",
"idsuffix",
"=",
"\"\"",
")",
":",
"if",
"idsuffix",
"is",
"True",
":",
"idsuffix",
"=",
"\".copy.\"",
"+",
"\"%08x\"",
"%",
"random",
".",
"getrandbits",
"(",
"32",
")",
"#random 32-bit hash for each copy, same one will be reused for all children",
"for",
"c",
"in",
"self",
":",
"if",
"isinstance",
"(",
"c",
",",
"AbstractElement",
")",
":",
"yield",
"c",
".",
"copy",
"(",
"newdoc",
",",
"idsuffix",
")"
] | Generator creating a deep copy of the children of this element.
Invokes :meth:`copy` on all children, parameters are the same. | [
"Generator",
"creating",
"a",
"deep",
"copy",
"of",
"the",
"children",
"of",
"this",
"element",
"."
] | 7707f69a91caaa6cde037f0d0379f1d42500a68b | https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/folia.py#L1252-L1260 | -1 |